diff --git a/CHANGELOG.md b/CHANGELOG.md index 7d4915b..f2e4aec 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,20 @@ # Changelog +## v1.1.1-rc.1 (2025-06-16) + +### Bug fixes + +- Fix type stub ([`0ffdb73`](https://github.com/34j/types-array-api/commit/0ffdb735bc41f949d682f88c793e6250e17e5ba3)) +- Fix type stub ([`a66fdce`](https://github.com/34j/types-array-api/commit/a66fdceb4ec850af908c421044fc1a4508a115ba)) +- Fix multiple issues ([`2146100`](https://github.com/34j/types-array-api/commit/21461009724e8d1100724196f8ec4eb814d19f34)) + +### Documentation + +- Show private ([`af7c493`](https://github.com/34j/types-array-api/commit/af7c493067ca9fa4456392b2638988334b50e559)) +- Show private ([`43668e4`](https://github.com/34j/types-array-api/commit/43668e4b8ad2dfe9b2c6aa685608d9c3fb813667)) +- Show private ([`322a6a7`](https://github.com/34j/types-array-api/commit/322a6a70598f4802c59923308f843029026f231a)) +- Show private ([`b5c3dcf`](https://github.com/34j/types-array-api/commit/b5c3dcfdf011834ca8889f9f05e106014b50dda6)) + ## v1.1.0 (2025-06-16) ### Features diff --git a/docs/conf.py b/docs/conf.py index e28ac74..7ca67f6 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -15,7 +15,7 @@ project = "Python array API standard typing" copyright = "2025, 34j" author = "34j" -release = "1.1.0" +release = "1.1.1-rc.1" # -- General configuration --------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration @@ -77,6 +77,7 @@ def run_apidoc(_: Any) -> None: [ "--force", "--module-first", + "--private", "-o", docs_path.as_posix(), module_path.as_posix(), diff --git a/pyproject.toml b/pyproject.toml index 808f189..6455b8a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ requires = [ "setuptools" ] [project] name = "types-array-api" -version = "1.1.0" +version = "1.1.1-rc.1" description = "Typing for array API and array-api-compat" readme = "README.md" license = "MIT AND Apache-2.0" @@ -29,6 +29,7 @@ dependencies = [ "attrs>=25.3.0", "rich>=10", "typer>=0.15,<1", + "typing-extensions>=4.14.0", ] urls."Bug Tracker" = "https://github.com/34j/types-array-api/issues" urls.Changelog = "https://github.com/34j/types-array-api/blob/main/CHANGELOG.md" diff --git a/src/array_api/_2022_12.py b/src/array_api/_2022_12.py index eb84c3e..b360f85 100644 --- a/src/array_api/_2022_12.py +++ b/src/array_api/_2022_12.py @@ -1,8 +1,10 @@ from __future__ import annotations from abc import abstractmethod +from collections.abc import Buffer as SupportsBufferProtocol from collections.abc import Sequence from enum import Enum +from types import EllipsisType as ellipsis from typing import ( Any, Literal, @@ -10,6 +12,8 @@ runtime_checkable, ) +from typing_extensions import CapsuleType as PyCapsule + inf = float("inf") @@ -43,13 +47,13 @@ class finfo_object[TDtype](Protocol): @runtime_checkable -class Array[TPycapsule, TArray: Array, TDevice, TDtype, TEllipsis](Protocol): - def __init__(self: TArray) -> None: +class Array[TArray: Array, TDevice, TDtype](Protocol): + def __init__(self) -> None: """Initialize the attributes for the array object class.""" ... @property - def dtype(self: TArray) -> TDtype: + def dtype(self) -> TDtype: """ Data type of the array elements. @@ -62,7 +66,7 @@ def dtype(self: TArray) -> TDtype: ... @property - def device(self: TArray) -> TDevice: + def device(self) -> TDevice: """ Hardware device the array data resides on. @@ -75,7 +79,7 @@ def device(self: TArray) -> TDevice: ... @property - def mT(self: TArray) -> TArray: + def mT(self) -> TArray: """ Transpose of a matrix (or a stack of matrices). @@ -90,7 +94,7 @@ def mT(self: TArray) -> TArray: ... @property - def ndim(self: TArray) -> int: + def ndim(self) -> int: """ Number of array dimensions (axes). @@ -103,7 +107,7 @@ def ndim(self: TArray) -> int: ... @property - def shape(self: TArray) -> tuple[int | None, ...]: + def shape(self) -> tuple[int | None, ...]: """ Array dimensions. @@ -123,7 +127,7 @@ def shape(self: TArray) -> tuple[int | None, ...]: ... @property - def size(self: TArray) -> int | None: + def size(self) -> int | None: """ Number of elements in an array. @@ -143,7 +147,7 @@ def size(self: TArray) -> int | None: ... @property - def T(self: TArray) -> TArray: + def T(self) -> TArray: """ Transpose of the array. @@ -161,13 +165,95 @@ def T(self: TArray) -> TArray: """ ... - def __array_namespace__(self: TArray, /, *, api_version: str | None = None) -> Any: + def __abs__(self, /) -> TArray: + """ + Calculates the absolute value for each element of an array instance. + + For real-valued input arrays, the element-wise result has the same magnitude as the respective element in ``x`` but has positive sign. + + .. note:: + For signed integer data types, the absolute value of the minimum representable integer is implementation-dependent. + + Parameters + ---------- + self + array instance. Should have a numeric data type. + + Returns + ------- + out: array + an array containing the element-wise absolute value. If ``self`` has a real-valued data type, the returned array must have the same data type as ``self``. If ``self`` has a complex floating-point data type, the returned arrayed must have a real-valued floating-point data type whose precision matches the precision of ``self`` (e.g., if ``self`` is ``complex128``, then the returned array must have a ``float64`` data type). + + Notes + ----- + + .. note:: + Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.abs`. + + .. versionchanged:: 2022.12 + Added complex data type support. + + """ + ... + + def __add__(self, other: int | float | complex | TArray, /) -> TArray: + """ + Calculates the sum for each element of an array instance with the respective element of the array ``other``. + + Parameters + ---------- + self + array instance (augend array). Should have a numeric data type. + other: Union[int, float, complex, array] + addend array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a numeric data type. + + Returns + ------- + out: array + an array containing the element-wise sums. The returned array must have a data type determined by :ref:`type-promotion`. + + Notes + ----- + + .. note:: + Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.add`. + + .. versionchanged:: 2022.12 + Added complex data type support. + + """ + ... + + def __and__(self, other: int | bool | TArray, /) -> TArray: + """ + Evaluates ``self_i & other_i`` for each element of an array instance with the respective element of the array ``other``. + + Parameters + ---------- + self + array instance. Should have an integer or boolean data type. + other: Union[int, bool, array] + other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have an integer or boolean data type. + + Returns + ------- + out: array + an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. + + + .. note:: + Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.bitwise_and`. + + """ + ... + + def __array_namespace__(self, /, *, api_version: str | None = None) -> Any: """ Returns an object that has all the array API functions on it. Parameters ---------- - self: array + self array instance. api_version: Optional[str] string representing the version of the array API specification to be returned, in ``'YYYY.MM'`` form, for example, ``'2020.10'``. If it is ``None``, it should return the namespace corresponding to latest version of the array API specification. If the given version is invalid or not implemented for the given module, an error should be raised. Default: ``None``. @@ -180,13 +266,80 @@ def __array_namespace__(self: TArray, /, *, api_version: str | None = None) -> A """ ... - def __dlpack__(self: TArray, /, *, stream: int | Any | None = None) -> TPycapsule: + def __bool__(self, /) -> bool: + """ + Converts a zero-dimensional array to a Python ``bool`` object. + + Parameters + ---------- + self + zero-dimensional array instance. + + Returns + ------- + out: bool + a Python ``bool`` object representing the single element of the array. + + Notes + ----- + **Special cases** + + For real-valued floating-point operands, + + - If ``self`` is ``NaN``, the result is ``True``. + - If ``self`` is either ``+infinity`` or ``-infinity``, the result is ``True``. + - If ``self`` is either ``+0`` or ``-0``, the result is ``False``. + + For complex floating-point operands, special cases must be handled as if the operation is implemented as the logical OR of ``bool(real(self))`` and ``bool(imag(self))``. + + .. versionchanged:: 2022.12 + Added boolean and complex data type support. + + """ + ... + + def __complex__(self, /) -> complex: + """ + Converts a zero-dimensional array to a Python ``complex`` object. + + Parameters + ---------- + self + zero-dimensional array instance. + + Returns + ------- + out: complex + a Python ``complex`` object representing the single element of the array instance. + + Notes + ----- + **Special cases** + + For boolean operands, + + - If ``self`` is ``True``, the result is ``1+0j``. + - If ``self`` is ``False``, the result is ``0+0j``. + + For real-valued floating-point operands, + + - If ``self`` is ``NaN``, the result is ``NaN + NaN j``. + - If ``self`` is ``+infinity``, the result is ``+infinity + 0j``. + - If ``self`` is ``-infinity``, the result is ``-infinity + 0j``. + - If ``self`` is a finite number, the result is ``self + 0j``. + + .. versionadded:: 2022.12 + + """ + ... + + def __dlpack__(self, /, *, stream: int | Any | None = None) -> PyCapsule: """ Exports the array for consumption by :func:`~array_api.from_dlpack` as a DLPack capsule. Parameters ---------- - self: array + self array instance. stream: Optional[Union[int, Any]] for CUDA and ROCm, a Python integer representing a pointer to a stream, on devices that support streams. ``stream`` is provided by the consumer to the producer to instruct the producer to ensure that operations can safely be performed on the array (e.g., by inserting a dependency between streams via "wait for event"). The pointer must be a positive integer or ``-1``. If ``stream`` is ``-1``, the value may be used by the consumer to signal "producer must not perform any synchronization". The ownership of the stream stays with the consumer. On CPU and other device types without streams, only ``None`` is accepted. @@ -251,13 +404,13 @@ def __dlpack__(self: TArray, /, *, stream: int | Any | None = None) -> TPycapsul """ ... - def __dlpack_device__(self: TArray, /) -> tuple[Enum, int]: + def __dlpack_device__(self, /) -> tuple[Enum, int]: """ Returns device type and device ID in DLPack format. Meant for use within :func:`~array_api.from_dlpack`. Parameters ---------- - self: array + self array instance. Returns @@ -279,366 +432,278 @@ def __dlpack_device__(self: TArray, /) -> tuple[Enum, int]: """ ... - def to_device(self: TArray, device: TDevice, /, *, stream: int | Any | None = None) -> TArray: + def __eq__(self, other: int | float | complex | bool | TArray, /) -> TArray: # type: ignore[override] """ - Copy the array from the device on which it currently resides to the specified ``device``. + Computes the truth value of ``self_i == other_i`` for each element of an array instance with the respective element of the array ``other``. Parameters ---------- - self: array - array instance. - device: device - a ``device`` object (see :ref:`device-support`). - stream: Optional[Union[int, Any]] - stream object to use during copy. In addition to the types supported in :meth:`array.__dlpack__`, implementations may choose to support any library-specific stream object with the caveat that any code using such an object would not be portable. + self + array instance. May have any data type. + other: Union[int, float, complex, bool, array] + other array. Must be compatible with ``self`` (see :ref:`broadcasting`). May have any data type. Returns ------- out: array - an array with the same data and data type as ``self`` and located on the specified ``device``. + an array containing the element-wise results. The returned array must have a data type of ``bool``. .. note:: - If ``stream`` is given, the copy operation should be enqueued on the provided ``stream``; otherwise, the copy operation should be enqueued on the default stream/queue. Whether the copy is performed synchronously or asynchronously is implementation-dependent. Accordingly, if synchronization is required to guarantee data safety, this must be clearly explained in a conforming library's documentation. + Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.equal`. + + .. versionchanged:: 2022.12 + Added complex data type support. """ ... - def __getitem__(self: TArray, key: int | slice | TEllipsis | None | tuple[int | slice | TEllipsis | None, ...] | TArray, /) -> TArray: + def __float__(self, /) -> float: """ - Returns ``self[key]``. + Converts a zero-dimensional array to a Python ``float`` object. - See :ref:`indexing` for details on supported indexing semantics. + .. note:: + Casting integer values outside the representable bounds of Python's float type is not specified and is implementation-dependent. Parameters ---------- - self: array - array instance. - key: Union[int, slice, ellipsis, None, Tuple[Union[int, slice, ellipsis, None], ...], array] - index key. + self + zero-dimensional array instance. Should have a real-valued or boolean data type. If ``self`` has a complex floating-point data type, the function must raise a ``TypeError``. Returns ------- - out: array - an array containing the accessed value(s). The returned array must have the same data type as ``self``. - - """ - ... - - def __setitem__(self: TArray, key: int | slice | TEllipsis | tuple[int | slice | TEllipsis, ...] | TArray, value: int | float | complex | bool | TArray, /) -> None: - """ - Sets ``self[key]`` to ``value``. - - See :ref:`indexing` for details on supported indexing semantics. - - Parameters - ---------- - self: array - array instance. - key: Union[int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], array] - index key. - value: Union[int, float, complex, bool, array] - value(s) to set. Must be compatible with ``self[key]`` (see :ref:`broadcasting`). - + out: float + a Python ``float`` object representing the single element of the array instance. - .. note:: + Notes + ----- + **Special cases** - Setting array values must not affect the data type of ``self``. + For boolean operands, - When ``value`` is a Python scalar (i.e., ``int``, ``float``, ``bool``), behavior must follow specification guidance on mixing arrays with Python scalars (see :ref:`type-promotion`). + - If ``self`` is ``True``, the result is ``1``. + - If ``self`` is ``False``, the result is ``0``. - When ``value`` is an ``array`` of a different data type than ``self``, how values are cast to the data type of ``self`` is implementation defined. + .. versionchanged:: 2022.12 + Added boolean and complex data type support. """ ... - def __add__(self: TArray, other: int | float | complex | TArray, /) -> TArray: + def __floordiv__(self, other: int | float | TArray, /) -> TArray: """ - Calculates the sum for each element of an array instance with the respective element of the array ``other``. + Evaluates ``self_i // other_i`` for each element of an array instance with the respective element of the array ``other``. + + .. note:: + For input arrays which promote to an integer data type, the result of division by zero is unspecified and thus implementation-defined. Parameters ---------- - self: array - array instance (augend array). Should have a numeric data type. - other: Union[int, float, complex, array] - addend array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a numeric data type. + self + array instance. Should have a real-valued data type. + other: Union[int, float, array] + other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a real-valued data type. Returns ------- out: array - an array containing the element-wise sums. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. - Notes - ----- .. note:: - Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.add`. - - .. versionchanged:: 2022.12 - Added complex data type support. + Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.floor_divide`. """ ... - def __sub__(self: TArray, other: int | float | complex | TArray, /) -> TArray: + def __ge__(self, other: int | float | TArray, /) -> TArray: """ - Calculates the difference for each element of an array instance with the respective element of the array ``other``. + Computes the truth value of ``self_i >= other_i`` for each element of an array instance with the respective element of the array ``other``. - The result of ``self_i - other_i`` must be the same as ``self_i + (-other_i)`` and must be governed by the same floating-point rules as addition (see :meth:`array.__add__`). + .. note:: + For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). Parameters ---------- - self: array - array instance (minuend array). Should have a numeric data type. - other: Union[int, float, complex, array] - subtrahend array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a numeric data type. + self + array instance. Should have a real-valued data type. + other: Union[int, float, array] + other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a real-valued data type. Returns ------- out: array - an array containing the element-wise differences. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise results. The returned array must have a data type of ``bool``. - Notes - ----- .. note:: - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.subtract`. - - .. versionchanged:: 2022.12 - Added complex data type support. + Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.greater_equal`. """ ... - def __mul__(self: TArray, other: int | float | complex | TArray, /) -> TArray: + def __getitem__(self, key: int | slice | ellipsis | None | tuple[int | slice | ellipsis | None, ...] | TArray, /) -> TArray: """ - Calculates the product for each element of an array instance with the respective element of the array ``other``. + Returns ``self[key]``. - .. note:: - Floating-point multiplication is not always associative due to finite precision. + See :ref:`indexing` for details on supported indexing semantics. Parameters ---------- - self: array - array instance. Should have a numeric data type. - other: Union[int, float, complex, array] - other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a numeric data type. + self + array instance. + key: Union[int, slice, ellipsis, None, Tuple[Union[int, slice, ellipsis, None], ...], array] + index key. Returns ------- out: array - an array containing the element-wise products. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the accessed value(s). The returned array must have the same data type as ``self``. - Notes - ----- - - .. note:: - Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.multiply`. - - .. versionchanged:: 2022.12 - Added complex data type support. + """ + ... + def __gt__(self, other: int | float | TArray, /) -> TArray: """ - ... - - def __matmul__(self: TArray, other: TArray, /) -> TArray: - """ - Computes the matrix product. + Computes the truth value of ``self_i > other_i`` for each element of an array instance with the respective element of the array ``other``. .. note:: - The ``matmul`` function must implement the same semantics as the built-in ``@`` operator (see `PEP 465 `_). + For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). Parameters ---------- - self: array - array instance. Should have a numeric data type. Must have at least one dimension. If ``self`` is one-dimensional having shape ``(M,)`` and ``other`` has more than one dimension, ``self`` must be promoted to a two-dimensional array by prepending ``1`` to its dimensions (i.e., must have shape ``(1, M)``). After matrix multiplication, the prepended dimensions in the returned array must be removed. If ``self`` has more than one dimension (including after vector-to-matrix promotion), ``shape(self)[:-2]`` must be compatible with ``shape(other)[:-2]`` (after vector-to-matrix promotion) (see :ref:`broadcasting`). If ``self`` has shape ``(..., M, K)``, the innermost two dimensions form matrices on which to perform matrix multiplication. - other: array - other array. Should have a numeric data type. Must have at least one dimension. If ``other`` is one-dimensional having shape ``(N,)`` and ``self`` has more than one dimension, ``other`` must be promoted to a two-dimensional array by appending ``1`` to its dimensions (i.e., must have shape ``(N, 1)``). After matrix multiplication, the appended dimensions in the returned array must be removed. If ``other`` has more than one dimension (including after vector-to-matrix promotion), ``shape(other)[:-2]`` must be compatible with ``shape(self)[:-2]`` (after vector-to-matrix promotion) (see :ref:`broadcasting`). If ``other`` has shape ``(..., K, N)``, the innermost two dimensions form matrices on which to perform matrix multiplication. - - - .. note:: - If either ``x1`` or ``x2`` has a complex floating-point data type, neither argument must be complex-conjugated or transposed. If conjugation and/or transposition is desired, these operations should be explicitly performed prior to computing the matrix product. + self + array instance. Should have a real-valued data type. + other: Union[int, float, array] + other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a real-valued data type. Returns ------- out: array - - if both ``self`` and ``other`` are one-dimensional arrays having shape ``(N,)``, a zero-dimensional array containing the inner product as its only element. - - if ``self`` is a two-dimensional array having shape ``(M, K)`` and ``other`` is a two-dimensional array having shape ``(K, N)``, a two-dimensional array containing the `conventional matrix product `_ and having shape ``(M, N)``. - - if ``self`` is a one-dimensional array having shape ``(K,)`` and ``other`` is an array having shape ``(..., K, N)``, an array having shape ``(..., N)`` (i.e., prepended dimensions during vector-to-matrix promotion must be removed) and containing the `conventional matrix product `_. - - if ``self`` is an array having shape ``(..., M, K)`` and ``other`` is a one-dimensional array having shape ``(K,)``, an array having shape ``(..., M)`` (i.e., appended dimensions during vector-to-matrix promotion must be removed) and containing the `conventional matrix product `_. - - if ``self`` is a two-dimensional array having shape ``(M, K)`` and ``other`` is an array having shape ``(..., K, N)``, an array having shape ``(..., M, N)`` and containing the `conventional matrix product `_ for each stacked matrix. - - if ``self`` is an array having shape ``(..., M, K)`` and ``other`` is a two-dimensional array having shape ``(K, N)``, an array having shape ``(..., M, N)`` and containing the `conventional matrix product `_ for each stacked matrix. - - if either ``self`` or ``other`` has more than two dimensions, an array having a shape determined by :ref:`broadcasting` ``shape(self)[:-2]`` against ``shape(other)[:-2]`` and containing the `conventional matrix product `_ for each stacked matrix. - - The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise results. The returned array must have a data type of ``bool``. - Notes - ----- .. note:: - Results must equal the results returned by the equivalent function :func:`~array_api.matmul`. - - **Raises** - - - if either ``self`` or ``other`` is a zero-dimensional array. - - if ``self`` is a one-dimensional array having shape ``(K,)``, ``other`` is a one-dimensional array having shape ``(L,)``, and ``K != L``. - - if ``self`` is a one-dimensional array having shape ``(K,)``, ``other`` is an array having shape ``(..., L, N)``, and ``K != L``. - - if ``self`` is an array having shape ``(..., M, K)``, ``other`` is a one-dimensional array having shape ``(L,)``, and ``K != L``. - - if ``self`` is an array having shape ``(..., M, K)``, ``other`` is an array having shape ``(..., L, N)``, and ``K != L``. - - .. versionchanged:: 2022.12 - Added complex data type support. + Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.greater`. """ ... - def __truediv__(self: TArray, other: int | float | complex | TArray, /) -> TArray: + def __index__(self, /) -> int: """ - Evaluates ``self_i / other_i`` for each element of an array instance with the respective element of the array ``other``. + Converts a zero-dimensional integer array to a Python ``int`` object. .. note:: - If one or both of ``self`` and ``other`` have integer data types, the result is implementation-dependent, as type promotion between data type "kinds" (e.g., integer versus floating-point) is unspecified. - - Specification-compliant libraries may choose to raise an error or return an array containing the element-wise results. If an array is returned, the array must have a real-valued floating-point data type. + This method is called to implement `operator.index() `_. See also `PEP 357 `_. Parameters ---------- - self: array - array instance. Should have a numeric data type. - other: Union[int, float, complex, array] - other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a numeric data type. + self + zero-dimensional array instance. Should have an integer data type. If ``self`` has a floating-point data type, the function must raise a ``TypeError``. Returns ------- - out: array - an array containing the element-wise results. The returned array should have a floating-point data type determined by :ref:`type-promotion`. - - Notes - ----- - - .. note:: - Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.divide`. - - .. versionchanged:: 2022.12 - Added complex data type support. + out: int + a Python ``int`` object representing the single element of the array instance. """ ... - def __floordiv__(self: TArray, other: int | float | TArray, /) -> TArray: + def __int__(self, /) -> int: """ - Evaluates ``self_i // other_i`` for each element of an array instance with the respective element of the array ``other``. - - .. note:: - For input arrays which promote to an integer data type, the result of division by zero is unspecified and thus implementation-defined. + Converts a zero-dimensional array to a Python ``int`` object. Parameters ---------- - self: array - array instance. Should have a real-valued data type. - other: Union[int, float, array] - other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a real-valued data type. + self + zero-dimensional array instance. Should have a real-valued or boolean data type. If ``self`` has a complex floating-point data type, the function must raise a ``TypeError``. Returns ------- - out: array - an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. + out: int + a Python ``int`` object representing the single element of the array instance. + Notes + ----- + **Special cases** - .. note:: - Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.floor_divide`. + For boolean operands, - """ - ... + - If ``self`` is ``True``, the result is ``1``. + - If ``self`` is ``False``, the result is ``0``. - def __mod__(self: TArray, other: int | float | TArray, /) -> TArray: - """ - Evaluates ``self_i % other_i`` for each element of an array instance with the respective element of the array ``other``. + For floating-point operands, - .. note:: - For input arrays which promote to an integer data type, the result of division by zero is unspecified and thus implementation-defined. + - If ``self`` is a finite number, the result is the integer part of ``self``. + - If ``self`` is ``-0``, the result is ``0``. - Parameters - ---------- - self: array - array instance. Should have a real-valued data type. - other: Union[int, float, array] - other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a real-valued data type. + **Raises** - Returns - ------- - out: array - an array containing the element-wise results. Each element-wise result must have the same sign as the respective element ``other_i``. The returned array must have a real-valued floating-point data type determined by :ref:`type-promotion`. + For floating-point operands, + - If ``self`` is either ``+infinity`` or ``-infinity``, raise ``OverflowError``. + - If ``self`` is ``NaN``, raise ``ValueError``. - .. note:: - Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.remainder`. + .. versionchanged:: 2022.12 + Added boolean and complex data type support. """ ... - def __pow__(self: TArray, other: int | float | complex | TArray, /) -> TArray: + def __invert__(self, /) -> TArray: """ - Calculates an implementation-dependent approximation of exponentiation by raising each element (the base) of an array instance to the power of ``other_i`` (the exponent), where ``other_i`` is the corresponding element of the array ``other``. - - .. note:: - If both ``self`` and ``other`` have integer data types, the result of ``__pow__`` when `other_i` is negative (i.e., less than zero) is unspecified and thus implementation-dependent. - - If ``self`` has an integer data type and ``other`` has a floating-point data type, behavior is implementation-dependent, as type promotion between data type "kinds" (e.g., integer versus floating-point) is unspecified. + Evaluates ``~self_i`` for each element of an array instance. Parameters ---------- - self: array - array instance whose elements correspond to the exponentiation base. Should have a numeric data type. - other: Union[int, float, complex, array] - other array whose elements correspond to the exponentiation exponent. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a numeric data type. + self + array instance. Should have an integer or boolean data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise results. The returned array must have the same data type as `self`. - Notes - ----- .. note:: - Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.pow`. - - .. versionchanged:: 2022.12 - Added complex data type support. + Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.bitwise_invert`. """ ... - def __lshift__(self: TArray, other: int | TArray, /) -> TArray: + def __le__(self, other: int | float | TArray, /) -> TArray: """ - Evaluates ``self_i << other_i`` for each element of an array instance with the respective element of the array ``other``. + Computes the truth value of ``self_i <= other_i`` for each element of an array instance with the respective element of the array ``other``. + + .. note:: + For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). Parameters ---------- - self: array - array instance. Should have an integer data type. - other: Union[int, array] - other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have an integer data type. Each element must be greater than or equal to ``0``. + self + array instance. Should have a real-valued data type. + other: Union[int, float, array] + other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a real-valued data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have the same data type as ``self``. + an array containing the element-wise results. The returned array must have a data type of ``bool``. .. note:: - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.bitwise_left_shift`. + Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.less_equal`. """ ... - def __rshift__(self: TArray, other: int | TArray, /) -> TArray: + def __lshift__(self, other: int | TArray, /) -> TArray: """ - Evaluates ``self_i >> other_i`` for each element of an array instance with the respective element of the array ``other``. + Evaluates ``self_i << other_i`` for each element of an array instance with the respective element of the array ``other``. Parameters ---------- - self: array + self array instance. Should have an integer data type. other: Union[int, array] other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have an integer data type. Each element must be greater than or equal to ``0``. @@ -650,107 +715,80 @@ def __rshift__(self: TArray, other: int | TArray, /) -> TArray: .. note:: - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.bitwise_right_shift`. + Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.bitwise_left_shift`. """ ... - def __and__(self: TArray, other: int | bool | TArray, /) -> TArray: + def __lt__(self, other: int | float | TArray, /) -> TArray: """ - Evaluates ``self_i & other_i`` for each element of an array instance with the respective element of the array ``other``. - - Parameters - ---------- - self: array - array instance. Should have an integer or boolean data type. - other: Union[int, bool, array] - other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have an integer or boolean data type. - - Returns - ------- - out: array - an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. - + Computes the truth value of ``self_i < other_i`` for each element of an array instance with the respective element of the array ``other``. .. note:: - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.bitwise_and`. - - """ - ... - - def __xor__(self: TArray, other: int | bool | TArray, /) -> TArray: - """ - Evaluates ``self_i ^ other_i`` for each element of an array instance with the respective element of the array ``other``. + For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). Parameters ---------- - self: array - array instance. Should have an integer or boolean data type. - other: Union[int, bool, array] - other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have an integer or boolean data type. + self + array instance. Should have a real-valued data type. + other: Union[int, float, array] + other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a real-valued data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise results. The returned array must have a data type of ``bool``. .. note:: - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.bitwise_xor`. + Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.less`. """ ... - def __or__(self: TArray, other: int | bool | TArray, /) -> TArray: + def __matmul__(self, other: TArray, /) -> TArray: """ - Evaluates ``self_i | other_i`` for each element of an array instance with the respective element of the array ``other``. - - Parameters - ---------- - self: array - array instance. Should have an integer or boolean data type. - other: Union[int, bool, array] - other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have an integer or boolean data type. - - Returns - ------- - out: array - an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. - - Notes - ----- + Computes the matrix product. .. note:: - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.bitwise_or`. - - """ - ... + The ``matmul`` function must implement the same semantics as the built-in ``@`` operator (see `PEP 465 `_). - def __neg__(self: TArray, /) -> TArray: - """ - Evaluates ``-self_i`` for each element of an array instance. + Parameters + ---------- + self + array instance. Should have a numeric data type. Must have at least one dimension. If ``self`` is one-dimensional having shape ``(M,)`` and ``other`` has more than one dimension, ``self`` must be promoted to a two-dimensional array by prepending ``1`` to its dimensions (i.e., must have shape ``(1, M)``). After matrix multiplication, the prepended dimensions in the returned array must be removed. If ``self`` has more than one dimension (including after vector-to-matrix promotion), ``shape(self)[:-2]`` must be compatible with ``shape(other)[:-2]`` (after vector-to-matrix promotion) (see :ref:`broadcasting`). If ``self`` has shape ``(..., M, K)``, the innermost two dimensions form matrices on which to perform matrix multiplication. + other: array + other array. Should have a numeric data type. Must have at least one dimension. If ``other`` is one-dimensional having shape ``(N,)`` and ``self`` has more than one dimension, ``other`` must be promoted to a two-dimensional array by appending ``1`` to its dimensions (i.e., must have shape ``(N, 1)``). After matrix multiplication, the appended dimensions in the returned array must be removed. If ``other`` has more than one dimension (including after vector-to-matrix promotion), ``shape(other)[:-2]`` must be compatible with ``shape(self)[:-2]`` (after vector-to-matrix promotion) (see :ref:`broadcasting`). If ``other`` has shape ``(..., K, N)``, the innermost two dimensions form matrices on which to perform matrix multiplication. - .. note:: - For signed integer data types, the numerical negative of the minimum representable integer is implementation-dependent. .. note:: - If ``self`` has a complex floating-point data type, both the real and imaginary components for each ``self_i`` must be negated (a result which follows from the rules of complex number multiplication). - - Parameters - ---------- - self: array - array instance. Should have a numeric data type. + If either ``x1`` or ``x2`` has a complex floating-point data type, neither argument must be complex-conjugated or transposed. If conjugation and/or transposition is desired, these operations should be explicitly performed prior to computing the matrix product. Returns ------- out: array - an array containing the evaluated result for each element in ``self``. The returned array must have a data type determined by :ref:`type-promotion`. + - if both ``self`` and ``other`` are one-dimensional arrays having shape ``(N,)``, a zero-dimensional array containing the inner product as its only element. + - if ``self`` is a two-dimensional array having shape ``(M, K)`` and ``other`` is a two-dimensional array having shape ``(K, N)``, a two-dimensional array containing the `conventional matrix product `_ and having shape ``(M, N)``. + - if ``self`` is a one-dimensional array having shape ``(K,)`` and ``other`` is an array having shape ``(..., K, N)``, an array having shape ``(..., N)`` (i.e., prepended dimensions during vector-to-matrix promotion must be removed) and containing the `conventional matrix product `_. + - if ``self`` is an array having shape ``(..., M, K)`` and ``other`` is a one-dimensional array having shape ``(K,)``, an array having shape ``(..., M)`` (i.e., appended dimensions during vector-to-matrix promotion must be removed) and containing the `conventional matrix product `_. + - if ``self`` is a two-dimensional array having shape ``(M, K)`` and ``other`` is an array having shape ``(..., K, N)``, an array having shape ``(..., M, N)`` and containing the `conventional matrix product `_ for each stacked matrix. + - if ``self`` is an array having shape ``(..., M, K)`` and ``other`` is a two-dimensional array having shape ``(K, N)``, an array having shape ``(..., M, N)`` and containing the `conventional matrix product `_ for each stacked matrix. + - if either ``self`` or ``other`` has more than two dimensions, an array having a shape determined by :ref:`broadcasting` ``shape(self)[:-2]`` against ``shape(other)[:-2]`` and containing the `conventional matrix product `_ for each stacked matrix. + - The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- .. note:: - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.negative`. + Results must equal the results returned by the equivalent function :func:`~array_api.matmul`. + + **Raises** + + - if either ``self`` or ``other`` is a zero-dimensional array. + - if ``self`` is a one-dimensional array having shape ``(K,)``, ``other`` is a one-dimensional array having shape ``(L,)``, and ``K != L``. + - if ``self`` is a one-dimensional array having shape ``(K,)``, ``other`` is an array having shape ``(..., L, N)``, and ``K != L``. + - if ``self`` is an array having shape ``(..., M, K)``, ``other`` is a one-dimensional array having shape ``(L,)``, and ``K != L``. + - if ``self`` is an array having shape ``(..., M, K)``, ``other`` is an array having shape ``(..., L, N)``, and ``K != L``. .. versionchanged:: 2022.12 Added complex data type support. @@ -758,51 +796,56 @@ def __neg__(self: TArray, /) -> TArray: """ ... - def __pos__(self: TArray, /) -> TArray: + def __mod__(self, other: int | float | TArray, /) -> TArray: """ - Evaluates ``+self_i`` for each element of an array instance. + Evaluates ``self_i % other_i`` for each element of an array instance with the respective element of the array ``other``. + + .. note:: + For input arrays which promote to an integer data type, the result of division by zero is unspecified and thus implementation-defined. Parameters ---------- - self: array - array instance. Should have a numeric data type. + self + array instance. Should have a real-valued data type. + other: Union[int, float, array] + other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a real-valued data type. Returns ------- out: array - an array containing the evaluated result for each element. The returned array must have the same data type as ``self``. + an array containing the element-wise results. Each element-wise result must have the same sign as the respective element ``other_i``. The returned array must have a real-valued floating-point data type determined by :ref:`type-promotion`. .. note:: - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.positive`. + Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.remainder`. """ ... - def __abs__(self: TArray, /) -> TArray: + def __mul__(self, other: int | float | complex | TArray, /) -> TArray: """ - Calculates the absolute value for each element of an array instance. - - For real-valued input arrays, the element-wise result has the same magnitude as the respective element in ``x`` but has positive sign. + Calculates the product for each element of an array instance with the respective element of the array ``other``. .. note:: - For signed integer data types, the absolute value of the minimum representable integer is implementation-dependent. + Floating-point multiplication is not always associative due to finite precision. Parameters ---------- - self: array + self array instance. Should have a numeric data type. + other: Union[int, float, complex, array] + other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a numeric data type. Returns ------- out: array - an array containing the element-wise absolute value. If ``self`` has a real-valued data type, the returned array must have the same data type as ``self``. If ``self`` has a complex floating-point data type, the returned arrayed must have a real-valued floating-point data type whose precision matches the precision of ``self`` (e.g., if ``self`` is ``complex128``, then the returned array must have a ``float64`` data type). + an array containing the element-wise products. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- .. note:: - Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.abs`. + Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.multiply`. .. versionchanged:: 2022.12 Added complex data type support. @@ -810,341 +853,302 @@ def __abs__(self: TArray, /) -> TArray: """ ... - def __invert__(self: TArray, /) -> TArray: + def __ne__(self, other: int | float | complex | bool | TArray, /) -> TArray: # type: ignore[override] """ - Evaluates ``~self_i`` for each element of an array instance. + Computes the truth value of ``self_i != other_i`` for each element of an array instance with the respective element of the array ``other``. Parameters ---------- - self: array - array instance. Should have an integer or boolean data type. + self + array instance. May have any data type. + other: Union[int, float, complex, bool, array] + other array. Must be compatible with ``self`` (see :ref:`broadcasting`). May have any data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have the same data type as `self`. + an array containing the element-wise results. The returned array must have a data type of ``bool`` (i.e., must be a boolean array). + Notes + ----- .. note:: - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.bitwise_invert`. + Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.not_equal`. + + .. versionchanged:: 2022.12 + Added complex data type support. """ ... - def __lt__(self: TArray, other: int | float | TArray, /) -> TArray: + def __neg__(self, /) -> TArray: """ - Computes the truth value of ``self_i < other_i`` for each element of an array instance with the respective element of the array ``other``. - - .. note:: - For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). - - Parameters - ---------- - self: array - array instance. Should have a real-valued data type. - other: Union[int, float, array] - other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a real-valued data type. - - Returns - ------- - out: array - an array containing the element-wise results. The returned array must have a data type of ``bool``. - + Evaluates ``-self_i`` for each element of an array instance. .. note:: - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.less`. - - """ - ... - - def __le__(self: TArray, other: int | float | TArray, /) -> TArray: - """ - Computes the truth value of ``self_i <= other_i`` for each element of an array instance with the respective element of the array ``other``. + For signed integer data types, the numerical negative of the minimum representable integer is implementation-dependent. .. note:: - For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). + If ``self`` has a complex floating-point data type, both the real and imaginary components for each ``self_i`` must be negated (a result which follows from the rules of complex number multiplication). Parameters ---------- - self: array - array instance. Should have a real-valued data type. - other: Union[int, float, array] - other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a real-valued data type. + self + array instance. Should have a numeric data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type of ``bool``. + an array containing the evaluated result for each element in ``self``. The returned array must have a data type determined by :ref:`type-promotion`. + Notes + ----- .. note:: - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.less_equal`. + Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.negative`. + + .. versionchanged:: 2022.12 + Added complex data type support. """ ... - def __eq__(self: TArray, other: int | float | complex | bool | TArray, /) -> TArray: # type: ignore[override] + def __or__(self, other: int | bool | TArray, /) -> TArray: """ - Computes the truth value of ``self_i == other_i`` for each element of an array instance with the respective element of the array ``other``. + Evaluates ``self_i | other_i`` for each element of an array instance with the respective element of the array ``other``. Parameters ---------- - self: array - array instance. May have any data type. - other: Union[int, float, complex, bool, array] - other array. Must be compatible with ``self`` (see :ref:`broadcasting`). May have any data type. + self + array instance. Should have an integer or boolean data type. + other: Union[int, bool, array] + other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have an integer or boolean data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type of ``bool``. + an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. + Notes + ----- .. note:: - Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.equal`. - - .. versionchanged:: 2022.12 - Added complex data type support. + Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.bitwise_or`. """ ... - def __ne__(self: TArray, other: int | float | complex | bool | TArray, /) -> TArray: # type: ignore[override] + def __pos__(self, /) -> TArray: """ - Computes the truth value of ``self_i != other_i`` for each element of an array instance with the respective element of the array ``other``. + Evaluates ``+self_i`` for each element of an array instance. Parameters ---------- - self: array - array instance. May have any data type. - other: Union[int, float, complex, bool, array] - other array. Must be compatible with ``self`` (see :ref:`broadcasting`). May have any data type. + self + array instance. Should have a numeric data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type of ``bool`` (i.e., must be a boolean array). + an array containing the evaluated result for each element. The returned array must have the same data type as ``self``. - Notes - ----- .. note:: - Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.not_equal`. - - .. versionchanged:: 2022.12 - Added complex data type support. + Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.positive`. """ ... - def __gt__(self: TArray, other: int | float | TArray, /) -> TArray: + def __pow__(self, other: int | float | complex | TArray, /) -> TArray: """ - Computes the truth value of ``self_i > other_i`` for each element of an array instance with the respective element of the array ``other``. + Calculates an implementation-dependent approximation of exponentiation by raising each element (the base) of an array instance to the power of ``other_i`` (the exponent), where ``other_i`` is the corresponding element of the array ``other``. .. note:: - For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). + If both ``self`` and ``other`` have integer data types, the result of ``__pow__`` when `other_i` is negative (i.e., less than zero) is unspecified and thus implementation-dependent. + + If ``self`` has an integer data type and ``other`` has a floating-point data type, behavior is implementation-dependent, as type promotion between data type "kinds" (e.g., integer versus floating-point) is unspecified. Parameters ---------- - self: array - array instance. Should have a real-valued data type. - other: Union[int, float, array] - other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a real-valued data type. + self + array instance whose elements correspond to the exponentiation base. Should have a numeric data type. + other: Union[int, float, complex, array] + other array whose elements correspond to the exponentiation exponent. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a numeric data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type of ``bool``. + an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. + Notes + ----- .. note:: - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.greater`. + Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.pow`. + + .. versionchanged:: 2022.12 + Added complex data type support. """ ... - def __ge__(self: TArray, other: int | float | TArray, /) -> TArray: + def __rshift__(self, other: int | TArray, /) -> TArray: """ - Computes the truth value of ``self_i >= other_i`` for each element of an array instance with the respective element of the array ``other``. - - .. note:: - For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). + Evaluates ``self_i >> other_i`` for each element of an array instance with the respective element of the array ``other``. Parameters ---------- - self: array - array instance. Should have a real-valued data type. - other: Union[int, float, array] - other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a real-valued data type. + self + array instance. Should have an integer data type. + other: Union[int, array] + other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have an integer data type. Each element must be greater than or equal to ``0``. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type of ``bool``. + an array containing the element-wise results. The returned array must have the same data type as ``self``. .. note:: - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.greater_equal`. + Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.bitwise_right_shift`. """ ... - def __bool__(self: TArray, /) -> bool: + def __setitem__(self, key: int | slice | ellipsis | tuple[int | slice | ellipsis, ...] | TArray, value: int | float | complex | bool | TArray, /) -> None: """ - Converts a zero-dimensional array to a Python ``bool`` object. + Sets ``self[key]`` to ``value``. + + See :ref:`indexing` for details on supported indexing semantics. Parameters ---------- - self: array - zero-dimensional array instance. - - Returns - ------- - out: bool - a Python ``bool`` object representing the single element of the array. + self + array instance. + key: Union[int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], array] + index key. + value: Union[int, float, complex, bool, array] + value(s) to set. Must be compatible with ``self[key]`` (see :ref:`broadcasting`). - Notes - ----- - **Special cases** - For real-valued floating-point operands, + .. note:: - - If ``self`` is ``NaN``, the result is ``True``. - - If ``self`` is either ``+infinity`` or ``-infinity``, the result is ``True``. - - If ``self`` is either ``+0`` or ``-0``, the result is ``False``. + Setting array values must not affect the data type of ``self``. - For complex floating-point operands, special cases must be handled as if the operation is implemented as the logical OR of ``bool(real(self))`` and ``bool(imag(self))``. + When ``value`` is a Python scalar (i.e., ``int``, ``float``, ``bool``), behavior must follow specification guidance on mixing arrays with Python scalars (see :ref:`type-promotion`). - .. versionchanged:: 2022.12 - Added boolean and complex data type support. + When ``value`` is an ``array`` of a different data type than ``self``, how values are cast to the data type of ``self`` is implementation defined. """ ... - def __complex__(self: TArray, /) -> complex: + def __sub__(self, other: int | float | complex | TArray, /) -> TArray: """ - Converts a zero-dimensional array to a Python ``complex`` object. + Calculates the difference for each element of an array instance with the respective element of the array ``other``. + + The result of ``self_i - other_i`` must be the same as ``self_i + (-other_i)`` and must be governed by the same floating-point rules as addition (see :meth:`array.__add__`). Parameters ---------- - self: array - zero-dimensional array instance. + self + array instance (minuend array). Should have a numeric data type. + other: Union[int, float, complex, array] + subtrahend array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a numeric data type. Returns ------- - out: complex - a Python ``complex`` object representing the single element of the array instance. + out: array + an array containing the element-wise differences. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- - **Special cases** - - For boolean operands, - - If ``self`` is ``True``, the result is ``1+0j``. - - If ``self`` is ``False``, the result is ``0+0j``. - - For real-valued floating-point operands, - - - If ``self`` is ``NaN``, the result is ``NaN + NaN j``. - - If ``self`` is ``+infinity``, the result is ``+infinity + 0j``. - - If ``self`` is ``-infinity``, the result is ``-infinity + 0j``. - - If ``self`` is a finite number, the result is ``self + 0j``. + .. note:: + Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.subtract`. - .. versionadded:: 2022.12 + .. versionchanged:: 2022.12 + Added complex data type support. """ ... - def __int__(self: TArray, /) -> int: + def __truediv__(self, other: int | float | complex | TArray, /) -> TArray: """ - Converts a zero-dimensional array to a Python ``int`` object. + Evaluates ``self_i / other_i`` for each element of an array instance with the respective element of the array ``other``. + + .. note:: + If one or both of ``self`` and ``other`` have integer data types, the result is implementation-dependent, as type promotion between data type "kinds" (e.g., integer versus floating-point) is unspecified. + + Specification-compliant libraries may choose to raise an error or return an array containing the element-wise results. If an array is returned, the array must have a real-valued floating-point data type. Parameters ---------- - self: array - zero-dimensional array instance. Should have a real-valued or boolean data type. If ``self`` has a complex floating-point data type, the function must raise a ``TypeError``. + self + array instance. Should have a numeric data type. + other: Union[int, float, complex, array] + other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a numeric data type. Returns ------- - out: int - a Python ``int`` object representing the single element of the array instance. + out: array + an array containing the element-wise results. The returned array should have a floating-point data type determined by :ref:`type-promotion`. Notes ----- - **Special cases** - - For boolean operands, - - If ``self`` is ``True``, the result is ``1``. - - If ``self`` is ``False``, the result is ``0``. - - For floating-point operands, - - - If ``self`` is a finite number, the result is the integer part of ``self``. - - If ``self`` is ``-0``, the result is ``0``. - - **Raises** - - For floating-point operands, - - - If ``self`` is either ``+infinity`` or ``-infinity``, raise ``OverflowError``. - - If ``self`` is ``NaN``, raise ``ValueError``. + .. note:: + Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.divide`. .. versionchanged:: 2022.12 - Added boolean and complex data type support. + Added complex data type support. """ ... - def __float__(self: TArray, /) -> float: + def __xor__(self, other: int | bool | TArray, /) -> TArray: """ - Converts a zero-dimensional array to a Python ``float`` object. - - .. note:: - Casting integer values outside the representable bounds of Python's float type is not specified and is implementation-dependent. + Evaluates ``self_i ^ other_i`` for each element of an array instance with the respective element of the array ``other``. Parameters ---------- - self: array - zero-dimensional array instance. Should have a real-valued or boolean data type. If ``self`` has a complex floating-point data type, the function must raise a ``TypeError``. + self + array instance. Should have an integer or boolean data type. + other: Union[int, bool, array] + other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have an integer or boolean data type. Returns ------- - out: float - a Python ``float`` object representing the single element of the array instance. - - Notes - ----- - **Special cases** - - For boolean operands, + out: array + an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. - - If ``self`` is ``True``, the result is ``1``. - - If ``self`` is ``False``, the result is ``0``. - .. versionchanged:: 2022.12 - Added boolean and complex data type support. + .. note:: + Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.bitwise_xor`. """ ... - def __index__(self: TArray, /) -> int: + def to_device(self, device: TDevice, /, *, stream: int | Any | None = None) -> TArray: """ - Converts a zero-dimensional integer array to a Python ``int`` object. - - .. note:: - This method is called to implement `operator.index() `_. See also `PEP 357 `_. + Copy the array from the device on which it currently resides to the specified ``device``. Parameters ---------- - self: array - zero-dimensional array instance. Should have an integer data type. If ``self`` has a floating-point data type, the function must raise a ``TypeError``. + self + array instance. + device: device + a ``device`` object (see :ref:`device-support`). + stream: Optional[Union[int, Any]] + stream object to use during copy. In addition to the types supported in :meth:`array.__dlpack__`, implementations may choose to support any library-specific stream object with the caveat that any code using such an object would not be portable. Returns ------- - out: int - a Python ``int`` object representing the single element of the array instance. + out: array + an array with the same data and data type as ``self`` and located on the specified ``device``. + + + .. note:: + If ``stream`` is given, the copy operation should be enqueued on the provided ``stream``; otherwise, the copy operation should be enqueued on the default stream/queue. Whether the copy is performed synchronously or asynchronously is implementation-dependent. Accordingly, if synchronization is required to guarantee data safety, this must be clearly explained in a conforming library's documentation. """ ... @@ -1156,42 +1160,42 @@ class astype[TArray: Array, TDtype](Protocol): Copies an array to a specified data type irrespective of :ref:`type-promotion` rules. .. note:: - Casting floating-point ``NaN`` and ``infinity`` values to integral data types is not specified and is implementation-dependent. + Casting floating-point ``NaN`` and ``infinity`` values to integral data types is not specified and is implementation-dependent. .. note:: - Casting a complex floating-point array to a real-valued data type should not be permitted. + Casting a complex floating-point array to a real-valued data type should not be permitted. - Historically, when casting a complex floating-point array to a real-valued data type, libraries such as NumPy have discarded imaginary components such that, for a complex floating-point array ``x``, ``astype(x)`` equals ``astype(real(x))``). This behavior is considered problematic as the choice to discard the imaginary component is arbitrary and introduces more than one way to achieve the same outcome (i.e., for a complex floating-point array ``x``, ``astype(x)`` and ``astype(real(x))`` versus only ``astype(imag(x))``). Instead, in order to avoid ambiguity and to promote clarity, this specification requires that array API consumers explicitly express which component should be cast to a specified real-valued data type. + Historically, when casting a complex floating-point array to a real-valued data type, libraries such as NumPy have discarded imaginary components such that, for a complex floating-point array ``x``, ``astype(x)`` equals ``astype(real(x))``). This behavior is considered problematic as the choice to discard the imaginary component is arbitrary and introduces more than one way to achieve the same outcome (i.e., for a complex floating-point array ``x``, ``astype(x)`` and ``astype(real(x))`` versus only ``astype(imag(x))``). Instead, in order to avoid ambiguity and to promote clarity, this specification requires that array API consumers explicitly express which component should be cast to a specified real-valued data type. .. note:: - When casting a boolean input array to a real-valued data type, a value of ``True`` must cast to a real-valued number equal to ``1``, and a value of ``False`` must cast to a real-valued number equal to ``0``. + When casting a boolean input array to a real-valued data type, a value of ``True`` must cast to a real-valued number equal to ``1``, and a value of ``False`` must cast to a real-valued number equal to ``0``. - When casting a boolean input array to a complex floating-point data type, a value of ``True`` must cast to a complex number equal to ``1 + 0j``, and a value of ``False`` must cast to a complex number equal to ``0 + 0j``. + When casting a boolean input array to a complex floating-point data type, a value of ``True`` must cast to a complex number equal to ``1 + 0j``, and a value of ``False`` must cast to a complex number equal to ``0 + 0j``. .. note:: - When casting a real-valued input array to ``bool``, a value of ``0`` must cast to ``False``, and a non-zero value must cast to ``True``. + When casting a real-valued input array to ``bool``, a value of ``0`` must cast to ``False``, and a non-zero value must cast to ``True``. - When casting a complex floating-point array to ``bool``, a value of ``0 + 0j`` must cast to ``False``, and all other values must cast to ``True``. + When casting a complex floating-point array to ``bool``, a value of ``0 + 0j`` must cast to ``False``, and all other values must cast to ``True``. Parameters ---------- x: array - array to cast. + array to cast. dtype: dtype - desired data type. + desired data type. copy: bool - specifies whether to copy an array when the specified ``dtype`` matches the data type of the input array ``x``. If ``True``, a newly allocated array must always be returned. If ``False`` and the specified ``dtype`` matches the data type of the input array, the input array must be returned; otherwise, a newly allocated array must be returned. Default: ``True``. + specifies whether to copy an array when the specified ``dtype`` matches the data type of the input array ``x``. If ``True``, a newly allocated array must always be returned. If ``False`` and the specified ``dtype`` matches the data type of the input array, the input array must be returned; otherwise, a newly allocated array must be returned. Default: ``True``. Returns ------- out: array - an array having the specified data type. The returned array must have the same shape as ``x``. + an array having the specified data type. The returned array must have the same shape as ``x``. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -1207,14 +1211,14 @@ class can_cast[TArray: Array, TDtype](Protocol): Parameters ---------- from_: Union[dtype, array] - input data type or array from which to cast. + input data type or array from which to cast. to: dtype - desired data type. + desired data type. Returns ------- out: bool - ``True`` if the cast can occur according to :ref:`type-promotion` rules; otherwise, ``False``. + ``True`` if the cast can occur according to :ref:`type-promotion` rules; otherwise, ``False``. """ @@ -1230,47 +1234,47 @@ class finfo[TArray: Array, TDtype](Protocol): Parameters ---------- type: Union[dtype, array] - the kind of floating-point data-type about which to get information. If complex, the information is about its component data type. + the kind of floating-point data-type about which to get information. If complex, the information is about its component data type. - .. note:: - Complex floating-point data types are specified to always use the same precision for both its real and imaginary components, so the information should be true for either component. + .. note:: + Complex floating-point data types are specified to always use the same precision for both its real and imaginary components, so the information should be true for either component. Returns ------- out: finfo object - an object having the following attributes: + an object having the following attributes: - - **bits**: *int* + - **bits**: *int* - number of bits occupied by the real-valued floating-point data type. + number of bits occupied by the real-valued floating-point data type. - - **eps**: *float* + - **eps**: *float* - difference between 1.0 and the next smallest representable real-valued floating-point number larger than 1.0 according to the IEEE-754 standard. + difference between 1.0 and the next smallest representable real-valued floating-point number larger than 1.0 according to the IEEE-754 standard. - - **max**: *float* + - **max**: *float* - largest representable real-valued number. + largest representable real-valued number. - - **min**: *float* + - **min**: *float* - smallest representable real-valued number. + smallest representable real-valued number. - - **smallest_normal**: *float* + - **smallest_normal**: *float* - smallest positive real-valued floating-point number with full precision. + smallest positive real-valued floating-point number with full precision. - - **dtype**: dtype + - **dtype**: dtype - real-valued floating-point data type. + real-valued floating-point data type. - .. versionadded:: 2022.12 + .. versionadded:: 2022.12 Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -1286,30 +1290,30 @@ class iinfo[TArray: Array, TDtype](Protocol): Parameters ---------- type: Union[dtype, array] - the kind of integer data-type about which to get information. + the kind of integer data-type about which to get information. Returns ------- out: iinfo object - an object having the following attributes: + an object having the following attributes: - - **bits**: *int* + - **bits**: *int* - number of bits occupied by the type. + number of bits occupied by the type. - - **max**: *int* + - **max**: *int* - largest representable number. + largest representable number. - - **min**: *int* + - **min**: *int* - smallest representable number. + smallest representable number. - - **dtype**: dtype + - **dtype**: dtype - integer data type. + integer data type. - .. versionadded:: 2022.12 + .. versionadded:: 2022.12 """ @@ -1325,32 +1329,32 @@ class isdtype[TDtype](Protocol): Parameters ---------- dtype: dtype - the input dtype. + the input dtype. kind: Union[str, dtype, Tuple[Union[str, dtype], ...]] - data type kind. + data type kind. - - If ``kind`` is a dtype, the function must return a boolean indicating whether the input ``dtype`` is equal to the dtype specified by ``kind``. - - If ``kind`` is a string, the function must return a boolean indicating whether the input ``dtype`` is of a specified data type kind. The following dtype kinds must be supported: + - If ``kind`` is a dtype, the function must return a boolean indicating whether the input ``dtype`` is equal to the dtype specified by ``kind``. + - If ``kind`` is a string, the function must return a boolean indicating whether the input ``dtype`` is of a specified data type kind. The following dtype kinds must be supported: - - ``'bool'``: boolean data types (e.g., ``bool``). - - ``'signed integer'``: signed integer data types (e.g., ``int8``, ``int16``, ``int32``, ``int64``). - - ``'unsigned integer'``: unsigned integer data types (e.g., ``uint8``, ``uint16``, ``uint32``, ``uint64``). - - ``'integral'``: integer data types. Shorthand for ``('signed integer', 'unsigned integer')``. - - ``'real floating'``: real-valued floating-point data types (e.g., ``float32``, ``float64``). - - ``'complex floating'``: complex floating-point data types (e.g., ``complex64``, ``complex128``). - - ``'numeric'``: numeric data types. Shorthand for ``('integral', 'real floating', 'complex floating')``. + - ``'bool'``: boolean data types (e.g., ``bool``). + - ``'signed integer'``: signed integer data types (e.g., ``int8``, ``int16``, ``int32``, ``int64``). + - ``'unsigned integer'``: unsigned integer data types (e.g., ``uint8``, ``uint16``, ``uint32``, ``uint64``). + - ``'integral'``: integer data types. Shorthand for ``('signed integer', 'unsigned integer')``. + - ``'real floating'``: real-valued floating-point data types (e.g., ``float32``, ``float64``). + - ``'complex floating'``: complex floating-point data types (e.g., ``complex64``, ``complex128``). + - ``'numeric'``: numeric data types. Shorthand for ``('integral', 'real floating', 'complex floating')``. - - If ``kind`` is a tuple, the tuple specifies a union of dtypes and/or kinds, and the function must return a boolean indicating whether the input ``dtype`` is either equal to a specified dtype or belongs to at least one specified data type kind. + - If ``kind`` is a tuple, the tuple specifies a union of dtypes and/or kinds, and the function must return a boolean indicating whether the input ``dtype`` is either equal to a specified dtype or belongs to at least one specified data type kind. - .. note:: - A conforming implementation of the array API standard is **not** limited to only including the dtypes described in this specification in the required data type kinds. For example, implementations supporting ``float16`` and ``bfloat16`` can include ``float16`` and ``bfloat16`` in the ``real floating`` data type kind. Similarly, implementations supporting ``int128`` can include ``int128`` in the ``signed integer`` data type kind. + .. note:: + A conforming implementation of the array API standard is **not** limited to only including the dtypes described in this specification in the required data type kinds. For example, implementations supporting ``float16`` and ``bfloat16`` can include ``float16`` and ``bfloat16`` in the ``real floating`` data type kind. Similarly, implementations supporting ``int128`` can include ``int128`` in the ``signed integer`` data type kind. - In short, conforming implementations may extend data type kinds; however, data type kinds must remain consistent (e.g., only integer dtypes may belong to integer data type kinds and only floating-point dtypes may belong to floating-point data type kinds), and extensions must be clearly documented as such in library documentation. + In short, conforming implementations may extend data type kinds; however, data type kinds must remain consistent (e.g., only integer dtypes may belong to integer data type kinds and only floating-point dtypes may belong to floating-point data type kinds), and extensions must be clearly documented as such in library documentation. Returns ------- out: bool - boolean indicating whether a provided dtype is of a specified data type kind. + boolean indicating whether a provided dtype is of a specified data type kind. Notes ----- @@ -1369,17 +1373,17 @@ class result_type[TArray: Array, TDtype](Protocol): Returns the dtype that results from applying the type promotion rules (see :ref:`type-promotion`) to the arguments. .. note:: - If provided mixed dtypes (e.g., integer and floating-point), the returned dtype will be implementation-specific. + If provided mixed dtypes (e.g., integer and floating-point), the returned dtype will be implementation-specific. Parameters ---------- arrays_and_dtypes: Union[array, dtype] - an arbitrary number of input arrays and/or dtypes. + an arbitrary number of input arrays and/or dtypes. Returns ------- out: dtype - the dtype resulting from an operation involving the input arrays and dtypes. + the dtype resulting from an operation involving the input arrays and dtypes. """ @@ -1393,24 +1397,24 @@ class max[TArray: Array](Protocol): Calculates the maximum value of the input array ``x``. .. note:: - When the number of elements over which to compute the maximum value is zero, the maximum value is implementation-defined. Specification-compliant libraries may choose to raise an error, return a sentinel value (e.g., if ``x`` is a floating-point input array, return ``NaN``), or return the minimum possible value for the input array ``x`` data type (e.g., if ``x`` is a floating-point array, return ``-infinity``). + When the number of elements over which to compute the maximum value is zero, the maximum value is implementation-defined. Specification-compliant libraries may choose to raise an error, return a sentinel value (e.g., if ``x`` is a floating-point input array, return ``NaN``), or return the minimum possible value for the input array ``x`` data type (e.g., if ``x`` is a floating-point array, return ``-infinity``). .. note:: - For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). + For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). Parameters ---------- x: array - input array. Should have a real-valued data type. + input array. Should have a real-valued data type. axis: Optional[Union[int, Tuple[int, ...]]] - axis or axes along which maximum values must be computed. By default, the maximum value must be computed over the entire array. If a tuple of integers, maximum values must be computed over multiple axes. Default: ``None``. + axis or axes along which maximum values must be computed. By default, the maximum value must be computed over the entire array. If a tuple of integers, maximum values must be computed over multiple axes. Default: ``None``. keepdims: bool - if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. + if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. Returns ------- out: array - if the maximum value was computed over the entire array, a zero-dimensional array containing the maximum value; otherwise, a non-zero-dimensional array containing the maximum values. The returned array must have the same data type as ``x``. + if the maximum value was computed over the entire array, a zero-dimensional array containing the maximum value; otherwise, a non-zero-dimensional array containing the maximum values. The returned array must have the same data type as ``x``. Notes ----- @@ -1434,19 +1438,19 @@ class mean[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a real-valued floating-point data type. + input array. Should have a real-valued floating-point data type. axis: Optional[Union[int, Tuple[int, ...]]] - axis or axes along which arithmetic means must be computed. By default, the mean must be computed over the entire array. If a tuple of integers, arithmetic means must be computed over multiple axes. Default: ``None``. + axis or axes along which arithmetic means must be computed. By default, the mean must be computed over the entire array. If a tuple of integers, arithmetic means must be computed over multiple axes. Default: ``None``. keepdims: bool - if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. + if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. Returns ------- out: array - if the arithmetic mean was computed over the entire array, a zero-dimensional array containing the arithmetic mean; otherwise, a non-zero-dimensional array containing the arithmetic means. The returned array must have the same data type as ``x``. + if the arithmetic mean was computed over the entire array, a zero-dimensional array containing the arithmetic mean; otherwise, a non-zero-dimensional array containing the arithmetic means. The returned array must have the same data type as ``x``. - .. note:: - While this specification recommends that this function only accept input arrays having a real-valued floating-point data type, specification-compliant array libraries may choose to accept input arrays having an integer data type. While mixed data type promotion is implementation-defined, if the input array ``x`` has an integer data type, the returned array must have the default real-valued floating-point data type. + .. note:: + While this specification recommends that this function only accept input arrays having a real-valued floating-point data type, specification-compliant array libraries may choose to accept input arrays having an integer data type. While mixed data type promotion is implementation-defined, if the input array ``x`` has an integer data type, the returned array must have the default real-valued floating-point data type. Notes ----- @@ -1469,24 +1473,24 @@ class min[TArray: Array](Protocol): Calculates the minimum value of the input array ``x``. .. note:: - When the number of elements over which to compute the minimum value is zero, the minimum value is implementation-defined. Specification-compliant libraries may choose to raise an error, return a sentinel value (e.g., if ``x`` is a floating-point input array, return ``NaN``), or return the maximum possible value for the input array ``x`` data type (e.g., if ``x`` is a floating-point array, return ``+infinity``). + When the number of elements over which to compute the minimum value is zero, the minimum value is implementation-defined. Specification-compliant libraries may choose to raise an error, return a sentinel value (e.g., if ``x`` is a floating-point input array, return ``NaN``), or return the maximum possible value for the input array ``x`` data type (e.g., if ``x`` is a floating-point array, return ``+infinity``). .. note:: - For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). + For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). Parameters ---------- x: array - input array. Should have a real-valued data type. + input array. Should have a real-valued data type. axis: Optional[Union[int, Tuple[int, ...]]] - axis or axes along which minimum values must be computed. By default, the minimum value must be computed over the entire array. If a tuple of integers, minimum values must be computed over multiple axes. Default: ``None``. + axis or axes along which minimum values must be computed. By default, the minimum value must be computed over the entire array. If a tuple of integers, minimum values must be computed over multiple axes. Default: ``None``. keepdims: bool - if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. + if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. Returns ------- out: array - if the minimum value was computed over the entire array, a zero-dimensional array containing the minimum value; otherwise, a non-zero-dimensional array containing the minimum values. The returned array must have the same data type as ``x``. + if the minimum value was computed over the entire array, a zero-dimensional array containing the minimum value; otherwise, a non-zero-dimensional array containing the minimum values. The returned array must have the same data type as ``x``. Notes ----- @@ -1510,30 +1514,30 @@ class prod[TArray: Array, TDtype](Protocol): Parameters ---------- x: array - input array. Should have a numeric data type. + input array. Should have a numeric data type. axis: Optional[Union[int, Tuple[int, ...]]] - axis or axes along which products must be computed. By default, the product must be computed over the entire array. If a tuple of integers, products must be computed over multiple axes. Default: ``None``. + axis or axes along which products must be computed. By default, the product must be computed over the entire array. If a tuple of integers, products must be computed over multiple axes. Default: ``None``. dtype: Optional[dtype] - data type of the returned array. If ``None``, + data type of the returned array. If ``None``, - - if the default data type corresponding to the data type "kind" (integer, real-valued floating-point, or complex floating-point) of ``x`` has a smaller range of values than the data type of ``x`` (e.g., ``x`` has data type ``int64`` and the default data type is ``int32``, or ``x`` has data type ``uint64`` and the default data type is ``int64``), the returned array must have the same data type as ``x``. - - if ``x`` has a real-valued floating-point data type, the returned array must have the default real-valued floating-point data type. - - if ``x`` has a complex floating-point data type, the returned array must have the default complex floating-point data type. - - if ``x`` has a signed integer data type (e.g., ``int16``), the returned array must have the default integer data type. - - if ``x`` has an unsigned integer data type (e.g., ``uint16``), the returned array must have an unsigned integer data type having the same number of bits as the default integer data type (e.g., if the default integer data type is ``int32``, the returned array must have a ``uint32`` data type). + - if the default data type corresponding to the data type "kind" (integer, real-valued floating-point, or complex floating-point) of ``x`` has a smaller range of values than the data type of ``x`` (e.g., ``x`` has data type ``int64`` and the default data type is ``int32``, or ``x`` has data type ``uint64`` and the default data type is ``int64``), the returned array must have the same data type as ``x``. + - if ``x`` has a real-valued floating-point data type, the returned array must have the default real-valued floating-point data type. + - if ``x`` has a complex floating-point data type, the returned array must have the default complex floating-point data type. + - if ``x`` has a signed integer data type (e.g., ``int16``), the returned array must have the default integer data type. + - if ``x`` has an unsigned integer data type (e.g., ``uint16``), the returned array must have an unsigned integer data type having the same number of bits as the default integer data type (e.g., if the default integer data type is ``int32``, the returned array must have a ``uint32`` data type). - If the data type (either specified or resolved) differs from the data type of ``x``, the input array should be cast to the specified data type before computing the product. Default: ``None``. + If the data type (either specified or resolved) differs from the data type of ``x``, the input array should be cast to the specified data type before computing the product. Default: ``None``. - .. note:: - This keyword argument is intended to help prevent data type overflows. + .. note:: + This keyword argument is intended to help prevent data type overflows. keepdims: bool - if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. + if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. Returns ------- out: array - if the product was computed over the entire array, a zero-dimensional array containing the product; otherwise, a non-zero-dimensional array containing the products. The returned array must have a data type as described by the ``dtype`` parameter above. + if the product was computed over the entire array, a zero-dimensional array containing the product; otherwise, a non-zero-dimensional array containing the products. The returned array must have a data type as described by the ``dtype`` parameter above. Notes ----- @@ -1546,7 +1550,7 @@ class prod[TArray: Array, TDtype](Protocol): For both real-valued and complex floating-point operands, special cases must be handled as if the operation is implemented by successive application of :func:`~array_api.multiply`. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -1562,21 +1566,21 @@ class std[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a real-valued floating-point data type. + input array. Should have a real-valued floating-point data type. axis: Optional[Union[int, Tuple[int, ...]]] - axis or axes along which standard deviations must be computed. By default, the standard deviation must be computed over the entire array. If a tuple of integers, standard deviations must be computed over multiple axes. Default: ``None``. + axis or axes along which standard deviations must be computed. By default, the standard deviation must be computed over the entire array. If a tuple of integers, standard deviations must be computed over multiple axes. Default: ``None``. correction: Union[int, float] - degrees of freedom adjustment. Setting this parameter to a value other than ``0`` has the effect of adjusting the divisor during the calculation of the standard deviation according to ``N-c`` where ``N`` corresponds to the total number of elements over which the standard deviation is computed and ``c`` corresponds to the provided degrees of freedom adjustment. When computing the standard deviation of a population, setting this parameter to ``0`` is the standard choice (i.e., the provided array contains data constituting an entire population). When computing the corrected sample standard deviation, setting this parameter to ``1`` is the standard choice (i.e., the provided array contains data sampled from a larger population; this is commonly referred to as Bessel's correction). Default: ``0``. + degrees of freedom adjustment. Setting this parameter to a value other than ``0`` has the effect of adjusting the divisor during the calculation of the standard deviation according to ``N-c`` where ``N`` corresponds to the total number of elements over which the standard deviation is computed and ``c`` corresponds to the provided degrees of freedom adjustment. When computing the standard deviation of a population, setting this parameter to ``0`` is the standard choice (i.e., the provided array contains data constituting an entire population). When computing the corrected sample standard deviation, setting this parameter to ``1`` is the standard choice (i.e., the provided array contains data sampled from a larger population; this is commonly referred to as Bessel's correction). Default: ``0``. keepdims: bool - if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. + if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. Returns ------- out: array - if the standard deviation was computed over the entire array, a zero-dimensional array containing the standard deviation; otherwise, a non-zero-dimensional array containing the standard deviations. The returned array must have the same data type as ``x``. + if the standard deviation was computed over the entire array, a zero-dimensional array containing the standard deviation; otherwise, a non-zero-dimensional array containing the standard deviations. The returned array must have the same data type as ``x``. - .. note:: - While this specification recommends that this function only accept input arrays having a real-valued floating-point data type, specification-compliant array libraries may choose to accept input arrays having an integer data type. While mixed data type promotion is implementation-defined, if the input array ``x`` has an integer data type, the returned array must have the default real-valued floating-point data type. + .. note:: + While this specification recommends that this function only accept input arrays having a real-valued floating-point data type, specification-compliant array libraries may choose to accept input arrays having an integer data type. While mixed data type promotion is implementation-defined, if the input array ``x`` has an integer data type, the returned array must have the default real-valued floating-point data type. Notes ----- @@ -1601,30 +1605,30 @@ class sum[TArray: Array, TDtype](Protocol): Parameters ---------- x: array - input array. Should have a numeric data type. + input array. Should have a numeric data type. axis: Optional[Union[int, Tuple[int, ...]]] - axis or axes along which sums must be computed. By default, the sum must be computed over the entire array. If a tuple of integers, sums must be computed over multiple axes. Default: ``None``. + axis or axes along which sums must be computed. By default, the sum must be computed over the entire array. If a tuple of integers, sums must be computed over multiple axes. Default: ``None``. dtype: Optional[dtype] - data type of the returned array. If ``None``, + data type of the returned array. If ``None``, - - if the default data type corresponding to the data type "kind" (integer, real-valued floating-point, or complex floating-point) of ``x`` has a smaller range of values than the data type of ``x`` (e.g., ``x`` has data type ``int64`` and the default data type is ``int32``, or ``x`` has data type ``uint64`` and the default data type is ``int64``), the returned array must have the same data type as ``x``. - - if ``x`` has a real-valued floating-point data type, the returned array must have the default real-valued floating-point data type. - - if ``x`` has a complex floating-point data type, the returned array must have the default complex floating-point data type. - - if ``x`` has a signed integer data type (e.g., ``int16``), the returned array must have the default integer data type. - - if ``x`` has an unsigned integer data type (e.g., ``uint16``), the returned array must have an unsigned integer data type having the same number of bits as the default integer data type (e.g., if the default integer data type is ``int32``, the returned array must have a ``uint32`` data type). + - if the default data type corresponding to the data type "kind" (integer, real-valued floating-point, or complex floating-point) of ``x`` has a smaller range of values than the data type of ``x`` (e.g., ``x`` has data type ``int64`` and the default data type is ``int32``, or ``x`` has data type ``uint64`` and the default data type is ``int64``), the returned array must have the same data type as ``x``. + - if ``x`` has a real-valued floating-point data type, the returned array must have the default real-valued floating-point data type. + - if ``x`` has a complex floating-point data type, the returned array must have the default complex floating-point data type. + - if ``x`` has a signed integer data type (e.g., ``int16``), the returned array must have the default integer data type. + - if ``x`` has an unsigned integer data type (e.g., ``uint16``), the returned array must have an unsigned integer data type having the same number of bits as the default integer data type (e.g., if the default integer data type is ``int32``, the returned array must have a ``uint32`` data type). - If the data type (either specified or resolved) differs from the data type of ``x``, the input array should be cast to the specified data type before computing the sum. Default: ``None``. + If the data type (either specified or resolved) differs from the data type of ``x``, the input array should be cast to the specified data type before computing the sum. Default: ``None``. - .. note:: - keyword argument is intended to help prevent data type overflows. + .. note:: + keyword argument is intended to help prevent data type overflows. keepdims: bool - if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. + if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. Returns ------- out: array - if the sum was computed over the entire array, a zero-dimensional array containing the sum; otherwise, an array containing the sums. The returned array must have a data type as described by the ``dtype`` parameter above. + if the sum was computed over the entire array, a zero-dimensional array containing the sum; otherwise, an array containing the sums. The returned array must have a data type as described by the ``dtype`` parameter above. Notes ----- @@ -1637,7 +1641,7 @@ class sum[TArray: Array, TDtype](Protocol): For both real-valued and complex floating-point operands, special cases must be handled as if the operation is implemented by successive application of :func:`~array_api.add`. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -1653,22 +1657,22 @@ class var[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a real-valued floating-point data type. + input array. Should have a real-valued floating-point data type. axis: Optional[Union[int, Tuple[int, ...]]] - axis or axes along which variances must be computed. By default, the variance must be computed over the entire array. If a tuple of integers, variances must be computed over multiple axes. Default: ``None``. + axis or axes along which variances must be computed. By default, the variance must be computed over the entire array. If a tuple of integers, variances must be computed over multiple axes. Default: ``None``. correction: Union[int, float] - degrees of freedom adjustment. Setting this parameter to a value other than ``0`` has the effect of adjusting the divisor during the calculation of the variance according to ``N-c`` where ``N`` corresponds to the total number of elements over which the variance is computed and ``c`` corresponds to the provided degrees of freedom adjustment. When computing the variance of a population, setting this parameter to ``0`` is the standard choice (i.e., the provided array contains data constituting an entire population). When computing the unbiased sample variance, setting this parameter to ``1`` is the standard choice (i.e., the provided array contains data sampled from a larger population; this is commonly referred to as Bessel's correction). Default: ``0``. + degrees of freedom adjustment. Setting this parameter to a value other than ``0`` has the effect of adjusting the divisor during the calculation of the variance according to ``N-c`` where ``N`` corresponds to the total number of elements over which the variance is computed and ``c`` corresponds to the provided degrees of freedom adjustment. When computing the variance of a population, setting this parameter to ``0`` is the standard choice (i.e., the provided array contains data constituting an entire population). When computing the unbiased sample variance, setting this parameter to ``1`` is the standard choice (i.e., the provided array contains data sampled from a larger population; this is commonly referred to as Bessel's correction). Default: ``0``. keepdims: bool - if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. + if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. Returns ------- out: array - if the variance was computed over the entire array, a zero-dimensional array containing the variance; otherwise, a non-zero-dimensional array containing the variances. The returned array must have the same data type as ``x``. + if the variance was computed over the entire array, a zero-dimensional array containing the variance; otherwise, a non-zero-dimensional array containing the variances. The returned array must have the same data type as ``x``. .. note:: - While this specification recommends that this function only accept input arrays having a real-valued floating-point data type, specification-compliant array libraries may choose to accept input arrays having an integer data type. While mixed data type promotion is implementation-defined, if the input array ``x`` has an integer data type, the returned array must have the default real-valued floating-point data type. + While this specification recommends that this function only accept input arrays having a real-valued floating-point data type, specification-compliant array libraries may choose to accept input arrays having an integer data type. While mixed data type promotion is implementation-defined, if the input array ``x`` has an integer data type, the returned array must have the default real-valued floating-point data type. Notes ----- @@ -1693,24 +1697,24 @@ class arange[TArray: Array, TDevice, TDtype](Protocol): Parameters ---------- start: Union[int, float] - if ``stop`` is specified, the start of interval (inclusive); otherwise, the end of the interval (exclusive). If ``stop`` is not specified, the default starting value is ``0``. + if ``stop`` is specified, the start of interval (inclusive); otherwise, the end of the interval (exclusive). If ``stop`` is not specified, the default starting value is ``0``. stop: Optional[Union[int, float]] - the end of the interval. Default: ``None``. + the end of the interval. Default: ``None``. step: Union[int, float] - the distance between two adjacent elements (``out[i+1] - out[i]``). Must not be ``0``; may be negative, this results in an empty array if ``stop >= start``. Default: ``1``. + the distance between two adjacent elements (``out[i+1] - out[i]``). Must not be ``0``; may be negative, this results in an empty array if ``stop >= start``. Default: ``1``. dtype: Optional[dtype] - output array data type. If ``dtype`` is ``None``, the output array data type must be inferred from ``start``, ``stop`` and ``step``. If those are all integers, the output array dtype must be the default integer dtype; if one or more have type ``float``, then the output array dtype must be the default real-valued floating-point data type. Default: ``None``. + output array data type. If ``dtype`` is ``None``, the output array data type must be inferred from ``start``, ``stop`` and ``step``. If those are all integers, the output array dtype must be the default integer dtype; if one or more have type ``float``, then the output array dtype must be the default real-valued floating-point data type. Default: ``None``. device: Optional[device] - device on which to place the created array. Default: ``None``. + device on which to place the created array. Default: ``None``. .. note:: - This function cannot guarantee that the interval does not include the ``stop`` value in those cases where ``step`` is not an integer and floating-point rounding errors affect the length of the output array. + This function cannot guarantee that the interval does not include the ``stop`` value in those cases where ``step`` is not an integer and floating-point rounding errors affect the length of the output array. Returns ------- out: array - a one-dimensional array containing evenly spaced values. The length of the output array must be ``ceil((stop-start)/step)`` if ``stop - start`` and ``step`` have the same sign, and length ``0`` otherwise. + a one-dimensional array containing evenly spaced values. The length of the output array must be ``ceil((stop-start)/step)`` if ``stop - start`` and ``step`` have the same sign, and length ``0`` otherwise. """ @@ -1719,58 +1723,58 @@ def __call__(self, start: int | float, /, stop: int | float | None = None, step: @runtime_checkable -class asarray[TSupportsbufferprotocol, TArray: Array, TDevice, TDtype](Protocol): +class asarray[TArray: Array, TDevice, TDtype](Protocol): r""" Convert the input to an array. Parameters ---------- obj: Union[array, bool, int, float, complex, NestedSequence[bool | int | float | complex], SupportsBufferProtocol] - object to be converted to an array. May be a Python scalar, a (possibly nested) sequence of Python scalars, or an object supporting the Python buffer protocol. + object to be converted to an array. May be a Python scalar, a (possibly nested) sequence of Python scalars, or an object supporting the Python buffer protocol. - .. admonition:: Tip - :class: important + .. admonition:: Tip + :class: important - An object supporting the buffer protocol can be turned into a memoryview through ``memoryview(obj)``. + An object supporting the buffer protocol can be turned into a memoryview through ``memoryview(obj)``. dtype: Optional[dtype] - output array data type. If ``dtype`` is ``None``, the output array data type must be inferred from the data type(s) in ``obj``. If all input values are Python scalars, then, in order of precedence, + output array data type. If ``dtype`` is ``None``, the output array data type must be inferred from the data type(s) in ``obj``. If all input values are Python scalars, then, in order of precedence, - - if all values are of type ``bool``, the output data type must be ``bool``. - - if all values are of type ``int`` or are a mixture of ``bool`` and ``int``, the output data type must be the default integer data type. - - if one or more values are ``complex`` numbers, the output data type must be the default complex floating-point data type. - - if one or more values are ``float``\\s, the output data type must be the default real-valued floating-point data type. + - if all values are of type ``bool``, the output data type must be ``bool``. + - if all values are of type ``int`` or are a mixture of ``bool`` and ``int``, the output data type must be the default integer data type. + - if one or more values are ``complex`` numbers, the output data type must be the default complex floating-point data type. + - if one or more values are ``float``\\s, the output data type must be the default real-valued floating-point data type. - Default: ``None``. + Default: ``None``. - .. admonition:: Note - :class: note + .. admonition:: Note + :class: note - If ``dtype`` is not ``None``, then array conversions should obey :ref:`type-promotion` rules. Conversions not specified according to :ref:`type-promotion` rules may or may not be permitted by a conforming array library. To perform an explicit cast, use :func:`array_api.astype`. + If ``dtype`` is not ``None``, then array conversions should obey :ref:`type-promotion` rules. Conversions not specified according to :ref:`type-promotion` rules may or may not be permitted by a conforming array library. To perform an explicit cast, use :func:`array_api.astype`. - .. note:: - If an input value exceeds the precision of the resolved output array data type, behavior is left unspecified and, thus, implementation-defined. + .. note:: + If an input value exceeds the precision of the resolved output array data type, behavior is left unspecified and, thus, implementation-defined. device: Optional[device] - device on which to place the created array. If ``device`` is ``None`` and ``obj`` is an array, the output array device must be inferred from ``obj``. Default: ``None``. + device on which to place the created array. If ``device`` is ``None`` and ``obj`` is an array, the output array device must be inferred from ``obj``. Default: ``None``. copy: Optional[bool] - boolean indicating whether or not to copy the input. If ``True``, the function must always copy. If ``False``, the function must never copy for input which supports the buffer protocol and must raise a ``ValueError`` in case a copy would be necessary. If ``None``, the function must reuse existing memory buffer if possible and copy otherwise. Default: ``None``. + boolean indicating whether or not to copy the input. If ``True``, the function must always copy. If ``False``, the function must never copy for input which supports the buffer protocol and must raise a ``ValueError`` in case a copy would be necessary. If ``None``, the function must reuse existing memory buffer if possible and copy otherwise. Default: ``None``. Returns ------- out: array - an array containing the data from ``obj``. + an array containing the data from ``obj``. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @abstractmethod - def __call__(self, obj: TArray | bool | int | float | complex | NestedSequence | TSupportsbufferprotocol, /, *, dtype: TDtype | None = None, device: TDevice | None = None, copy: bool | None = None) -> TArray: ... + def __call__(self, obj: TArray | bool | int | float | complex | NestedSequence | SupportsBufferProtocol, /, *, dtype: TDtype | None = None, device: TDevice | None = None, copy: bool | None = None) -> TArray: ... @runtime_checkable @@ -1781,16 +1785,16 @@ class empty[TArray: Array, TDevice, TDtype](Protocol): Parameters ---------- shape: Union[int, Tuple[int, ...]] - output array shape. + output array shape. dtype: Optional[dtype] - output array data type. If ``dtype`` is ``None``, the output array data type must be the default real-valued floating-point data type. Default: ``None``. + output array data type. If ``dtype`` is ``None``, the output array data type must be the default real-valued floating-point data type. Default: ``None``. device: Optional[device] - device on which to place the created array. Default: ``None``. + device on which to place the created array. Default: ``None``. Returns ------- out: array - an array containing uninitialized data. + an array containing uninitialized data. """ @@ -1806,16 +1810,16 @@ class empty_like[TArray: Array, TDevice, TDtype](Protocol): Parameters ---------- x: array - input array from which to derive the output array shape. + input array from which to derive the output array shape. dtype: Optional[dtype] - output array data type. If ``dtype`` is ``None``, the output array data type must be inferred from ``x``. Default: ``None``. + output array data type. If ``dtype`` is ``None``, the output array data type must be inferred from ``x``. Default: ``None``. device: Optional[device] - device on which to place the created array. If ``device`` is ``None``, the output array device must be inferred from ``x``. Default: ``None``. + device on which to place the created array. If ``device`` is ``None``, the output array device must be inferred from ``x``. Default: ``None``. Returns ------- out: array - an array having the same shape as ``x`` and containing uninitialized data. + an array having the same shape as ``x`` and containing uninitialized data. """ @@ -1829,31 +1833,31 @@ class eye[TArray: Array, TDevice, TDtype](Protocol): Returns a two-dimensional array with ones on the ``k``\\th diagonal and zeros elsewhere. .. note:: - An output array having a complex floating-point data type must have the value ``1 + 0j`` along the ``k``\\th diagonal and ``0 + 0j`` elsewhere. + An output array having a complex floating-point data type must have the value ``1 + 0j`` along the ``k``\\th diagonal and ``0 + 0j`` elsewhere. Parameters ---------- n_rows: int - number of rows in the output array. + number of rows in the output array. n_cols: Optional[int] - number of columns in the output array. If ``None``, the default number of columns in the output array is equal to ``n_rows``. Default: ``None``. + number of columns in the output array. If ``None``, the default number of columns in the output array is equal to ``n_rows``. Default: ``None``. k: int - index of the diagonal. A positive value refers to an upper diagonal, a negative value to a lower diagonal, and ``0`` to the main diagonal. Default: ``0``. + index of the diagonal. A positive value refers to an upper diagonal, a negative value to a lower diagonal, and ``0`` to the main diagonal. Default: ``0``. dtype: Optional[dtype] - output array data type. If ``dtype`` is ``None``, the output array data type must be the default real-valued floating-point data type. Default: ``None``. + output array data type. If ``dtype`` is ``None``, the output array data type must be the default real-valued floating-point data type. Default: ``None``. device: Optional[device] - device on which to place the created array. Default: ``None``. + device on which to place the created array. Default: ``None``. Returns ------- out: array - an array where all elements are equal to zero, except for the ``k``\\th diagonal, whose values are equal to one. + an array where all elements are equal to zero, except for the ``k``\\th diagonal, whose values are equal to one. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -1869,17 +1873,17 @@ class from_dlpack[TArray: Array](Protocol): Parameters ---------- x: object - input (array) object. + input (array) object. Returns ------- out: array - an array containing the data in `x`. + an array containing the data in `x`. - .. admonition:: Note - :class: note + .. admonition:: Note + :class: note - The returned array may be either a copy or a view. See :ref:`data-interchange` for details. + The returned array may be either a copy or a view. See :ref:`data-interchange` for details. """ @@ -1895,33 +1899,33 @@ class full[TArray: Array, TDevice, TDtype](Protocol): Parameters ---------- shape: Union[int, Tuple[int, ...]] - output array shape. + output array shape. fill_value: Union[bool, int, float, complex] - fill value. + fill value. dtype: Optional[dtype] - output array data type. If ``dtype`` is ``None``, the output array data type must be inferred from ``fill_value`` according to the following rules: + output array data type. If ``dtype`` is ``None``, the output array data type must be inferred from ``fill_value`` according to the following rules: - - If the fill value is an ``int``, the output array data type must be the default integer data type. - - If the fill value is a ``float``, the output array data type must be the default real-valued floating-point data type. - - If the fill value is a ``complex`` number, the output array data type must be the default complex floating-point data type. - - If the fill value is a ``bool``, the output array must have a boolean data type. Default: ``None``. + - If the fill value is an ``int``, the output array data type must be the default integer data type. + - If the fill value is a ``float``, the output array data type must be the default real-valued floating-point data type. + - If the fill value is a ``complex`` number, the output array data type must be the default complex floating-point data type. + - If the fill value is a ``bool``, the output array must have a boolean data type. Default: ``None``. - .. note:: - If the ``fill_value`` exceeds the precision of the resolved default output array data type, behavior is left unspecified and, thus, implementation-defined. + .. note:: + If the ``fill_value`` exceeds the precision of the resolved default output array data type, behavior is left unspecified and, thus, implementation-defined. device: Optional[device] - device on which to place the created array. Default: ``None``. + device on which to place the created array. Default: ``None``. Returns ------- out: array - an array where every element is equal to ``fill_value``. + an array where every element is equal to ``fill_value``. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -1937,31 +1941,31 @@ class full_like[TArray: Array, TDevice, TDtype](Protocol): Parameters ---------- x: array - input array from which to derive the output array shape. + input array from which to derive the output array shape. fill_value: Union[bool, int, float, complex] - fill value. + fill value. dtype: Optional[dtype] - output array data type. If ``dtype`` is ``None``, the output array data type must be inferred from ``x``. Default: ``None``. + output array data type. If ``dtype`` is ``None``, the output array data type must be inferred from ``x``. Default: ``None``. - .. note:: - If the ``fill_value`` exceeds the precision of the resolved output array data type, behavior is unspecified and, thus, implementation-defined. + .. note:: + If the ``fill_value`` exceeds the precision of the resolved output array data type, behavior is unspecified and, thus, implementation-defined. - .. note:: - If the ``fill_value`` has a data type which is not of the same data type kind (boolean, integer, or floating-point) as the resolved output array data type (see :ref:`type-promotion`), behavior is unspecified and, thus, implementation-defined. + .. note:: + If the ``fill_value`` has a data type which is not of the same data type kind (boolean, integer, or floating-point) as the resolved output array data type (see :ref:`type-promotion`), behavior is unspecified and, thus, implementation-defined. device: Optional[device] - device on which to place the created array. If ``device`` is ``None``, the output array device must be inferred from ``x``. Default: ``None``. + device on which to place the created array. If ``device`` is ``None``, the output array device must be inferred from ``x``. Default: ``None``. Returns ------- out: array - an array having the same shape as ``x`` and where every element is equal to ``fill_value``. + an array having the same shape as ``x`` and where every element is equal to ``fill_value``. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -1977,59 +1981,59 @@ class linspace[TArray: Array, TDevice, TDtype](Protocol): Let :math:`N` be the number of generated values (which is either ``num`` or ``num+1`` depending on whether ``endpoint`` is ``True`` or ``False``, respectively). For real-valued output arrays, the spacing between values is given by .. math:: - \\Delta_{\\textrm{real}} = \\frac{\\textrm{stop} - \\textrm{start}}{N - 1} + \\Delta_{\\textrm{real}} = \\frac{\\textrm{stop} - \\textrm{start}}{N - 1} For complex output arrays, let ``a = real(start)``, ``b = imag(start)``, ``c = real(stop)``, and ``d = imag(stop)``. The spacing between complex values is given by .. math:: - \\Delta_{\\textrm{complex}} = \\frac{c-a}{N-1} + \\frac{d-b}{N-1} j + \\Delta_{\\textrm{complex}} = \\frac{c-a}{N-1} + \\frac{d-b}{N-1} j Parameters ---------- start: Union[int, float, complex] - the start of the interval. + the start of the interval. stop: Union[int, float, complex] - the end of the interval. If ``endpoint`` is ``False``, the function must generate a sequence of ``num+1`` evenly spaced numbers starting with ``start`` and ending with ``stop`` and exclude the ``stop`` from the returned array such that the returned array consists of evenly spaced numbers over the half-open interval ``[start, stop)``. If ``endpoint`` is ``True``, the output array must consist of evenly spaced numbers over the closed interval ``[start, stop]``. Default: ``True``. + the end of the interval. If ``endpoint`` is ``False``, the function must generate a sequence of ``num+1`` evenly spaced numbers starting with ``start`` and ending with ``stop`` and exclude the ``stop`` from the returned array such that the returned array consists of evenly spaced numbers over the half-open interval ``[start, stop)``. If ``endpoint`` is ``True``, the output array must consist of evenly spaced numbers over the closed interval ``[start, stop]``. Default: ``True``. - .. note:: - The step size changes when `endpoint` is `False`. + .. note:: + The step size changes when `endpoint` is `False`. num: int - number of samples. Must be a nonnegative integer value. + number of samples. Must be a nonnegative integer value. dtype: Optional[dtype] - output array data type. Should be a floating-point data type. If ``dtype`` is ``None``, + output array data type. Should be a floating-point data type. If ``dtype`` is ``None``, - - if either ``start`` or ``stop`` is a ``complex`` number, the output data type must be the default complex floating-point data type. - - if both ``start`` and ``stop`` are real-valued, the output data type must be the default real-valued floating-point data type. + - if either ``start`` or ``stop`` is a ``complex`` number, the output data type must be the default complex floating-point data type. + - if both ``start`` and ``stop`` are real-valued, the output data type must be the default real-valued floating-point data type. - Default: ``None``. + Default: ``None``. - .. admonition:: Note - :class: note + .. admonition:: Note + :class: note - If ``dtype`` is not ``None``, conversion of ``start`` and ``stop`` should obey :ref:`type-promotion` rules. Conversions not specified according to :ref:`type-promotion` rules may or may not be permitted by a conforming array library. + If ``dtype`` is not ``None``, conversion of ``start`` and ``stop`` should obey :ref:`type-promotion` rules. Conversions not specified according to :ref:`type-promotion` rules may or may not be permitted by a conforming array library. device: Optional[device] - device on which to place the created array. Default: ``None``. + device on which to place the created array. Default: ``None``. endpoint: bool - boolean indicating whether to include ``stop`` in the interval. Default: ``True``. + boolean indicating whether to include ``stop`` in the interval. Default: ``True``. Returns ------- out: array - a one-dimensional array containing evenly spaced values. + a one-dimensional array containing evenly spaced values. Notes ----- .. note:: - While this specification recommends that this function only return arrays having a floating-point data type, specification-compliant array libraries may choose to support output arrays having an integer data type (e.g., due to backward compatibility concerns). However, function behavior when generating integer output arrays is unspecified and, thus, is implementation-defined. Accordingly, using this function to generate integer output arrays is not portable. + While this specification recommends that this function only return arrays having a floating-point data type, specification-compliant array libraries may choose to support output arrays having an integer data type (e.g., due to backward compatibility concerns). However, function behavior when generating integer output arrays is unspecified and, thus, is implementation-defined. Accordingly, using this function to generate integer output arrays is not portable. .. note:: - As mixed data type promotion is implementation-defined, behavior when ``start`` or ``stop`` exceeds the maximum safe integer of an output floating-point data type is implementation-defined. An implementation may choose to overflow or raise an exception. + As mixed data type promotion is implementation-defined, behavior when ``start`` or ``stop`` exceeds the maximum safe integer of an output floating-point data type is implementation-defined. An implementation may choose to overflow or raise an exception. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -2045,29 +2049,29 @@ class meshgrid[TArray: Array](Protocol): Parameters ---------- arrays: array - an arbitrary number of one-dimensional arrays representing grid coordinates. Each array should have the same numeric data type. + an arbitrary number of one-dimensional arrays representing grid coordinates. Each array should have the same numeric data type. indexing: Literal["xy", "ij"] - Cartesian ``'xy'`` or matrix ``'ij'`` indexing of output. If provided zero or one one-dimensional vector(s) (i.e., the zero- and one-dimensional cases, respectively), the ``indexing`` keyword has no effect and should be ignored. Default: ``'xy'``. + Cartesian ``'xy'`` or matrix ``'ij'`` indexing of output. If provided zero or one one-dimensional vector(s) (i.e., the zero- and one-dimensional cases, respectively), the ``indexing`` keyword has no effect and should be ignored. Default: ``'xy'``. Returns ------- out: List[array] - list of N arrays, where ``N`` is the number of provided one-dimensional input arrays. Each returned array must have rank ``N``. For ``N`` one-dimensional arrays having lengths ``Ni = len(xi)``, + list of N arrays, where ``N`` is the number of provided one-dimensional input arrays. Each returned array must have rank ``N``. For ``N`` one-dimensional arrays having lengths ``Ni = len(xi)``, - - if matrix indexing ``ij``, then each returned array must have the shape ``(N1, N2, N3, ..., Nn)``. - - if Cartesian indexing ``xy``, then each returned array must have shape ``(N2, N1, N3, ..., Nn)``. + - if matrix indexing ``ij``, then each returned array must have the shape ``(N1, N2, N3, ..., Nn)``. + - if Cartesian indexing ``xy``, then each returned array must have shape ``(N2, N1, N3, ..., Nn)``. - Accordingly, for the two-dimensional case with input one-dimensional arrays of length ``M`` and ``N``, if matrix indexing ``ij``, then each returned array must have shape ``(M, N)``, and, if Cartesian indexing ``xy``, then each returned array must have shape ``(N, M)``. + Accordingly, for the two-dimensional case with input one-dimensional arrays of length ``M`` and ``N``, if matrix indexing ``ij``, then each returned array must have shape ``(M, N)``, and, if Cartesian indexing ``xy``, then each returned array must have shape ``(N, M)``. - Similarly, for the three-dimensional case with input one-dimensional arrays of length ``M``, ``N``, and ``P``, if matrix indexing ``ij``, then each returned array must have shape ``(M, N, P)``, and, if Cartesian indexing ``xy``, then each returned array must have shape ``(N, M, P)``. + Similarly, for the three-dimensional case with input one-dimensional arrays of length ``M``, ``N``, and ``P``, if matrix indexing ``ij``, then each returned array must have shape ``(M, N, P)``, and, if Cartesian indexing ``xy``, then each returned array must have shape ``(N, M, P)``. - Each returned array should have the same data type as the input arrays. + Each returned array should have the same data type as the input arrays. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -2081,27 +2085,27 @@ class ones[TArray: Array, TDevice, TDtype](Protocol): Returns a new array having a specified ``shape`` and filled with ones. .. note:: - An output array having a complex floating-point data type must contain complex numbers having a real component equal to one and an imaginary component equal to zero (i.e., ``1 + 0j``). + An output array having a complex floating-point data type must contain complex numbers having a real component equal to one and an imaginary component equal to zero (i.e., ``1 + 0j``). Parameters ---------- shape: Union[int, Tuple[int, ...]] - output array shape. + output array shape. dtype: Optional[dtype] - output array data type. If ``dtype`` is ``None``, the output array data type must be the default real-valued floating-point data type. Default: ``None``. + output array data type. If ``dtype`` is ``None``, the output array data type must be the default real-valued floating-point data type. Default: ``None``. device: Optional[device] - device on which to place the created array. Default: ``None``. + device on which to place the created array. Default: ``None``. Returns ------- out: array - an array containing ones. + an array containing ones. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -2115,27 +2119,27 @@ class ones_like[TArray: Array, TDevice, TDtype](Protocol): Returns a new array filled with ones and having the same ``shape`` as an input array ``x``. .. note:: - An output array having a complex floating-point data type must contain complex numbers having a real component equal to one and an imaginary component equal to zero (i.e., ``1 + 0j``). + An output array having a complex floating-point data type must contain complex numbers having a real component equal to one and an imaginary component equal to zero (i.e., ``1 + 0j``). Parameters ---------- x: array - input array from which to derive the output array shape. + input array from which to derive the output array shape. dtype: Optional[dtype] - output array data type. If ``dtype`` is ``None``, the output array data type must be inferred from ``x``. Default: ``None``. + output array data type. If ``dtype`` is ``None``, the output array data type must be inferred from ``x``. Default: ``None``. device: Optional[device] - device on which to place the created array. If ``device`` is ``None``, the output array device must be inferred from ``x``. Default: ``None``. + device on which to place the created array. If ``device`` is ``None``, the output array device must be inferred from ``x``. Default: ``None``. Returns ------- out: array - an array having the same shape as ``x`` and filled with ones. + an array having the same shape as ``x`` and filled with ones. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -2149,22 +2153,22 @@ class tril[TArray: Array](Protocol): Returns the lower triangular part of a matrix (or a stack of matrices) ``x``. .. note:: - The lower triangular part of the matrix is defined as the elements on and below the specified diagonal ``k``. + The lower triangular part of the matrix is defined as the elements on and below the specified diagonal ``k``. Parameters ---------- x: array - input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. + input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. k: int - diagonal above which to zero elements. If ``k = 0``, the diagonal is the main diagonal. If ``k < 0``, the diagonal is below the main diagonal. If ``k > 0``, the diagonal is above the main diagonal. Default: ``0``. + diagonal above which to zero elements. If ``k = 0``, the diagonal is the main diagonal. If ``k < 0``, the diagonal is below the main diagonal. If ``k > 0``, the diagonal is above the main diagonal. Default: ``0``. - .. note:: - The main diagonal is defined as the set of indices ``{(i, i)}`` for ``i`` on the interval ``[0, min(M, N) - 1]``. + .. note:: + The main diagonal is defined as the set of indices ``{(i, i)}`` for ``i`` on the interval ``[0, min(M, N) - 1]``. Returns ------- out: array - an array containing the lower triangular part(s). The returned array must have the same shape and data type as ``x``. All elements above the specified diagonal ``k`` must be zeroed. The returned array should be allocated on the same device as ``x``. + an array containing the lower triangular part(s). The returned array must have the same shape and data type as ``x``. All elements above the specified diagonal ``k`` must be zeroed. The returned array should be allocated on the same device as ``x``. """ @@ -2178,22 +2182,22 @@ class triu[TArray: Array](Protocol): Returns the upper triangular part of a matrix (or a stack of matrices) ``x``. .. note:: - The upper triangular part of the matrix is defined as the elements on and above the specified diagonal ``k``. + The upper triangular part of the matrix is defined as the elements on and above the specified diagonal ``k``. Parameters ---------- x: array - input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. + input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. k: int - diagonal below which to zero elements. If ``k = 0``, the diagonal is the main diagonal. If ``k < 0``, the diagonal is below the main diagonal. If ``k > 0``, the diagonal is above the main diagonal. Default: ``0``. + diagonal below which to zero elements. If ``k = 0``, the diagonal is the main diagonal. If ``k < 0``, the diagonal is below the main diagonal. If ``k > 0``, the diagonal is above the main diagonal. Default: ``0``. - .. note:: - The main diagonal is defined as the set of indices ``{(i, i)}`` for ``i`` on the interval ``[0, min(M, N) - 1]``. + .. note:: + The main diagonal is defined as the set of indices ``{(i, i)}`` for ``i`` on the interval ``[0, min(M, N) - 1]``. Returns ------- out: array - an array containing the upper triangular part(s). The returned array must have the same shape and data type as ``x``. All elements below the specified diagonal ``k`` must be zeroed. The returned array should be allocated on the same device as ``x``. + an array containing the upper triangular part(s). The returned array must have the same shape and data type as ``x``. All elements below the specified diagonal ``k`` must be zeroed. The returned array should be allocated on the same device as ``x``. """ @@ -2209,16 +2213,16 @@ class zeros[TArray: Array, TDevice, TDtype](Protocol): Parameters ---------- shape: Union[int, Tuple[int, ...]] - output array shape. + output array shape. dtype: Optional[dtype] - output array data type. If ``dtype`` is ``None``, the output array data type must be the default real-valued floating-point data type. Default: ``None``. + output array data type. If ``dtype`` is ``None``, the output array data type must be the default real-valued floating-point data type. Default: ``None``. device: Optional[device] - device on which to place the created array. Default: ``None``. + device on which to place the created array. Default: ``None``. Returns ------- out: array - an array containing zeros. + an array containing zeros. """ @@ -2234,16 +2238,16 @@ class zeros_like[TArray: Array, TDevice, TDtype](Protocol): Parameters ---------- x: array - input array from which to derive the output array shape. + input array from which to derive the output array shape. dtype: Optional[dtype] - output array data type. If ``dtype`` is ``None``, the output array data type must be inferred from ``x``. Default: ``None``. + output array data type. If ``dtype`` is ``None``, the output array data type must be inferred from ``x``. Default: ``None``. device: Optional[device] - device on which to place the created array. If ``device`` is ``None``, the output array device must be inferred from ``x``. Default: ``None``. + device on which to place the created array. If ``device`` is ``None``, the output array device must be inferred from ``x``. Default: ``None``. Returns ------- out: array - an array having the same shape as ``x`` and filled with zeros. + an array having the same shape as ``x`` and filled with zeros. """ @@ -2261,39 +2265,39 @@ class cholesky[TArray: Array](Protocol): The lower **Cholesky decomposition** of a complex Hermitian or real symmetric positive-definite matrix :math:`x \\in\\ \\mathbb{K}^{n \\times n}` is defined as .. math:: - x = LL^{H} \\qquad \\text{L $\\in\\ \\mathbb{K}^{n \\times n}$} + x = LL^{H} \\qquad \\text{L $\\in\\ \\mathbb{K}^{n \\times n}$} where :math:`L` is a lower triangular matrix and :math:`L^{H}` is the conjugate transpose when :math:`L` is complex-valued and the transpose when :math:`L` is real-valued. The upper Cholesky decomposition is defined similarly .. math:: - x = U^{H}U \\qquad \\text{U $\\in\\ \\mathbb{K}^{n \\times n}$} + x = U^{H}U \\qquad \\text{U $\\in\\ \\mathbb{K}^{n \\times n}$} where :math:`U` is an upper triangular matrix. When ``x`` is a stack of matrices, the function must compute the Cholesky decomposition for each matrix in the stack. .. note:: - Whether an array library explicitly checks whether an input array is Hermitian or a symmetric positive-definite matrix (or a stack of matrices) is implementation-defined. + Whether an array library explicitly checks whether an input array is Hermitian or a symmetric positive-definite matrix (or a stack of matrices) is implementation-defined. Parameters ---------- x: array - input array having shape ``(..., M, M)`` and whose innermost two dimensions form square complex Hermitian or real symmetric positive-definite matrices. Should have a floating-point data type. + input array having shape ``(..., M, M)`` and whose innermost two dimensions form square complex Hermitian or real symmetric positive-definite matrices. Should have a floating-point data type. upper: bool - If ``True``, the result must be the upper-triangular Cholesky factor :math:`U`. If ``False``, the result must be the lower-triangular Cholesky factor :math:`L`. Default: ``False``. + If ``True``, the result must be the upper-triangular Cholesky factor :math:`U`. If ``False``, the result must be the lower-triangular Cholesky factor :math:`L`. Default: ``False``. Returns ------- out: array - an array containing the Cholesky factors for each square matrix. If ``upper`` is ``False``, the returned array must contain lower-triangular matrices; otherwise, the returned array must contain upper-triangular matrices. The returned array must have a floating-point data type determined by :ref:`type-promotion` and must have the same shape as ``x``. + an array containing the Cholesky factors for each square matrix. If ``upper`` is ``False``, the returned array must contain lower-triangular matrices; otherwise, the returned array must contain upper-triangular matrices. The returned array must have a floating-point data type determined by :ref:`type-promotion` and must have the same shape as ``x``. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -2311,29 +2315,29 @@ class cross[TArray: Array](Protocol): Parameters ---------- x1: array - first input array. Must have a numeric data type. + first input array. Must have a numeric data type. x2: array - second input array. Must be compatible with ``x1`` for all non-compute axes (see :ref:`broadcasting`). The size of the axis over which to compute the cross product must be the same size as the respective axis in ``x1``. Must have a numeric data type. + second input array. Must be compatible with ``x1`` for all non-compute axes (see :ref:`broadcasting`). The size of the axis over which to compute the cross product must be the same size as the respective axis in ``x1``. Must have a numeric data type. - .. note:: - The compute axis (dimension) must not be broadcasted. + .. note:: + The compute axis (dimension) must not be broadcasted. axis: int - the axis (dimension) of ``x1`` and ``x2`` containing the vectors for which to compute the cross product. Must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of the shape determined according to :ref:`broadcasting`. If specified as a negative integer, the function must determine the axis along which to compute the cross product by counting backward from the last dimension (where ``-1`` refers to the last dimension). By default, the function must compute the cross product over the last axis. Default: ``-1``. + the axis (dimension) of ``x1`` and ``x2`` containing the vectors for which to compute the cross product. Must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of the shape determined according to :ref:`broadcasting`. If specified as a negative integer, the function must determine the axis along which to compute the cross product by counting backward from the last dimension (where ``-1`` refers to the last dimension). By default, the function must compute the cross product over the last axis. Default: ``-1``. Returns ------- out: array - an array containing the cross products. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the cross products. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- .. versionchanged:: 2022.12 - Added support for broadcasting. + Added support for broadcasting. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. **Raises** @@ -2355,18 +2359,18 @@ class det[TArray: Array](Protocol): Parameters ---------- x: array - input array having shape ``(..., M, M)`` and whose innermost two dimensions form square matrices. Should have a floating-point data type. + input array having shape ``(..., M, M)`` and whose innermost two dimensions form square matrices. Should have a floating-point data type. Returns ------- out: array - if ``x`` is a two-dimensional array, a zero-dimensional array containing the determinant; otherwise, a non-zero dimensional array containing the determinant for each square matrix. The returned array must have the same data type as ``x``. + if ``x`` is a two-dimensional array, a zero-dimensional array containing the determinant; otherwise, a non-zero dimensional array containing the determinant for each square matrix. The returned array must have the same data type as ``x``. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -2382,20 +2386,20 @@ class diagonal[TArray: Array](Protocol): Parameters ---------- x: array - input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. + input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. offset: int - offset specifying the off-diagonal relative to the main diagonal. + offset specifying the off-diagonal relative to the main diagonal. - - ``offset = 0``: the main diagonal. - - ``offset > 0``: off-diagonal above the main diagonal. - - ``offset < 0``: off-diagonal below the main diagonal. + - ``offset = 0``: the main diagonal. + - ``offset > 0``: off-diagonal above the main diagonal. + - ``offset < 0``: off-diagonal below the main diagonal. - Default: `0`. + Default: `0`. Returns ------- out: array - an array containing the diagonals and whose shape is determined by removing the last two dimensions and appending a dimension equal to the size of the resulting diagonals. The returned array must have the same data type as ``x``. + an array containing the diagonals and whose shape is determined by removing the last two dimensions and appending a dimension equal to the size of the resulting diagonals. The returned array must have the same data type as ``x``. """ @@ -2413,45 +2417,45 @@ class eigh[TArray: Array](Protocol): The **eigenvalue decomposition** of a complex Hermitian or real symmetric matrix :math:`x \\in\\ \\mathbb{K}^{n \\times n}` is defined as .. math:: - x = Q \\Lambda Q^H + x = Q \\Lambda Q^H with :math:`Q \\in \\mathbb{K}^{n \\times n}` and :math:`\\Lambda \\in \\mathbb{R}^n` and where :math:`Q^H` is the conjugate transpose when :math:`Q` is complex and the transpose when :math:`Q` is real-valued and :math:`\\Lambda` is a diagonal matrix whose diagonal elements are the corresponding eigenvalues. When ``x`` is real-valued, :math:`Q` is orthogonal, and, when ``x`` is complex, :math:`Q` is unitary. .. note:: - The eigenvalues of a complex Hermitian or real symmetric matrix are always real. + The eigenvalues of a complex Hermitian or real symmetric matrix are always real. .. warning:: - The eigenvectors of a symmetric matrix are not unique and are not continuous with respect to ``x``. Because eigenvectors are not unique, different hardware and software may compute different eigenvectors. + The eigenvectors of a symmetric matrix are not unique and are not continuous with respect to ``x``. Because eigenvectors are not unique, different hardware and software may compute different eigenvectors. - Non-uniqueness stems from the fact that multiplying an eigenvector by :math:`-1` when ``x`` is real-valued and by :math:`e^{\\phi j}` (:math:`\\phi \\in \\mathbb{R}`) when ``x`` is complex produces another set of valid eigenvectors. + Non-uniqueness stems from the fact that multiplying an eigenvector by :math:`-1` when ``x`` is real-valued and by :math:`e^{\\phi j}` (:math:`\\phi \\in \\mathbb{R}`) when ``x`` is complex produces another set of valid eigenvectors. .. note:: - Whether an array library explicitly checks whether an input array is Hermitian or a symmetric matrix (or a stack of matrices) is implementation-defined. + Whether an array library explicitly checks whether an input array is Hermitian or a symmetric matrix (or a stack of matrices) is implementation-defined. .. note:: - The function ``eig`` will be added in a future version of the specification. + The function ``eig`` will be added in a future version of the specification. Parameters ---------- x: array - input array having shape ``(..., M, M)`` and whose innermost two dimensions form square matrices. Should have a floating-point data type. + input array having shape ``(..., M, M)`` and whose innermost two dimensions form square matrices. Should have a floating-point data type. Returns ------- out: Tuple[array, array] - a namedtuple (``eigenvalues``, ``eigenvectors``) whose + a namedtuple (``eigenvalues``, ``eigenvectors``) whose - - first element must have the field name ``eigenvalues`` (corresponding to :math:`\\operatorname{diag}\\Lambda` above) and must be an array consisting of computed eigenvalues. The array containing the eigenvalues must have shape ``(..., M)`` and must have a real-valued floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``complex128``, then ``eigenvalues`` must be ``float64``). - - second element have have the field name ``eigenvectors`` (corresponding to :math:`Q` above) and must be an array where the columns of the inner most matrices contain the computed eigenvectors. These matrices must be orthogonal. The array containing the eigenvectors must have shape ``(..., M, M)`` and must have the same data type as ``x``. + - first element must have the field name ``eigenvalues`` (corresponding to :math:`\\operatorname{diag}\\Lambda` above) and must be an array consisting of computed eigenvalues. The array containing the eigenvalues must have shape ``(..., M)`` and must have a real-valued floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``complex128``, then ``eigenvalues`` must be ``float64``). + - second element have have the field name ``eigenvectors`` (corresponding to :math:`Q` above) and must be an array where the columns of the inner most matrices contain the computed eigenvectors. These matrices must be orthogonal. The array containing the eigenvectors must have shape ``(..., M, M)`` and must have the same data type as ``x``. Notes ----- .. note:: - Eigenvalue sort order is left unspecified and is thus implementation-dependent. + Eigenvalue sort order is left unspecified and is thus implementation-dependent. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -2469,37 +2473,37 @@ class eigvalsh[TArray: Array](Protocol): The **eigenvalues** of a complex Hermitian or real symmetric matrix :math:`x \\in\\ \\mathbb{K}^{n \\times n}` are defined as the roots (counted with multiplicity) of the polynomial :math:`p` of degree :math:`n` given by .. math:: - p(\\lambda) = \\operatorname{det}(x - \\lambda I_n) + p(\\lambda) = \\operatorname{det}(x - \\lambda I_n) where :math:`\\lambda \\in \\mathbb{R}` and where :math:`I_n` is the *n*-dimensional identity matrix. .. note:; - The eigenvalues of a complex Hermitian or real symmetric matrix are always real. + The eigenvalues of a complex Hermitian or real symmetric matrix are always real. .. note:: - Whether an array library explicitly checks whether an input array is Hermitian or a symmetric matrix (or a stack of matrices) is implementation-defined. + Whether an array library explicitly checks whether an input array is Hermitian or a symmetric matrix (or a stack of matrices) is implementation-defined. .. note:: - The function ``eigvals`` will be added in a future version of the specification. + The function ``eigvals`` will be added in a future version of the specification. Parameters ---------- x: array - input array having shape ``(..., M, M)`` and whose innermost two dimensions form square matrices. Should have a floating-point data type. + input array having shape ``(..., M, M)`` and whose innermost two dimensions form square matrices. Should have a floating-point data type. Returns ------- out: array - an array containing the computed eigenvalues. The returned array must have shape ``(..., M)`` and have a real-valued floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``complex128``, then must have a ``float64`` data type). + an array containing the computed eigenvalues. The returned array must have shape ``(..., M)`` and have a real-valued floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``complex128``, then must have a ``float64`` data type). Notes ----- .. note:: - Eigenvalue sort order is left unspecified and is thus implementation-dependent. + Eigenvalue sort order is left unspecified and is thus implementation-dependent. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -2517,7 +2521,7 @@ class inv[TArray: Array](Protocol): The **inverse matrix** :math:`x^{-1} \\in\\ \\mathbb{K}^{n \\times n}` of a square matrix :math:`x \\in\\ \\mathbb{K}^{n \\times n}` is defined as .. math:: - x^{-1}x = xx^{-1} = I_n + x^{-1}x = xx^{-1} = I_n where :math:`I_n` is the *n*-dimensional identity matrix. @@ -2528,18 +2532,18 @@ class inv[TArray: Array](Protocol): Parameters ---------- x: array - input array having shape ``(..., M, M)`` and whose innermost two dimensions form square matrices. Should have a floating-point data type. + input array having shape ``(..., M, M)`` and whose innermost two dimensions form square matrices. Should have a floating-point data type. Returns ------- out: array - an array containing the multiplicative inverses. The returned array must have a floating-point data type determined by :ref:`type-promotion` and must have the same shape as ``x``. + an array containing the multiplicative inverses. The returned array must have a floating-point data type determined by :ref:`type-promotion` and must have the same shape as ``x``. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -2555,56 +2559,56 @@ class matrix_norm[TArray: Array](Protocol): Parameters ---------- x: array - input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. Should have a floating-point data type. + input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. Should have a floating-point data type. keepdims: bool - If ``True``, the last two axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the last two axes (dimensions) must not be included in the result. Default: ``False``. + If ``True``, the last two axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the last two axes (dimensions) must not be included in the result. Default: ``False``. ord: Optional[Union[int, float, Literal[inf, -inf, 'fro', 'nuc']]] - order of the norm. The following mathematical norms must be supported: + order of the norm. The following mathematical norms must be supported: - +------------------+---------------------------------+ - | ord | description | - +==================+=================================+ - | 'fro' | Frobenius norm | - +------------------+---------------------------------+ - | 'nuc' | nuclear norm | - +------------------+---------------------------------+ - | 1 | max(sum(abs(x), axis=0)) | - +------------------+---------------------------------+ - | 2 | largest singular value | - +------------------+---------------------------------+ - | inf | max(sum(abs(x), axis=1)) | - +------------------+---------------------------------+ + +------------------+---------------------------------+ + | ord | description | + +==================+=================================+ + | 'fro' | Frobenius norm | + +------------------+---------------------------------+ + | 'nuc' | nuclear norm | + +------------------+---------------------------------+ + | 1 | max(sum(abs(x), axis=0)) | + +------------------+---------------------------------+ + | 2 | largest singular value | + +------------------+---------------------------------+ + | inf | max(sum(abs(x), axis=1)) | + +------------------+---------------------------------+ - The following non-mathematical "norms" must be supported: + The following non-mathematical "norms" must be supported: - +------------------+---------------------------------+ - | ord | description | - +==================+=================================+ - | -1 | min(sum(abs(x), axis=0)) | - +------------------+---------------------------------+ - | -2 | smallest singular value | - +------------------+---------------------------------+ - | -inf | min(sum(abs(x), axis=1)) | - +------------------+---------------------------------+ + +------------------+---------------------------------+ + | ord | description | + +==================+=================================+ + | -1 | min(sum(abs(x), axis=0)) | + +------------------+---------------------------------+ + | -2 | smallest singular value | + +------------------+---------------------------------+ + | -inf | min(sum(abs(x), axis=1)) | + +------------------+---------------------------------+ - If ``ord=1``, the norm corresponds to the induced matrix norm where ``p=1`` (i.e., the maximum absolute value column sum). + If ``ord=1``, the norm corresponds to the induced matrix norm where ``p=1`` (i.e., the maximum absolute value column sum). - If ``ord=2``, the norm corresponds to the induced matrix norm where ``p=inf`` (i.e., the maximum absolute value row sum). + If ``ord=2``, the norm corresponds to the induced matrix norm where ``p=inf`` (i.e., the maximum absolute value row sum). - If ``ord=inf``, the norm corresponds to the induced matrix norm where ``p=2`` (i.e., the largest singular value). + If ``ord=inf``, the norm corresponds to the induced matrix norm where ``p=2`` (i.e., the largest singular value). - Default: ``'fro'``. + Default: ``'fro'``. Returns ------- out: array - an array containing the norms for each ``MxN`` matrix. If ``keepdims`` is ``False``, the returned array must have a rank which is two less than the rank of ``x``. If ``x`` has a real-valued data type, the returned array must have a real-valued floating-point data type determined by :ref:`type-promotion`. If ``x`` has a complex-valued data type, the returned array must have a real-valued floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``complex128``, then the returned array must have a ``float64`` data type). + an array containing the norms for each ``MxN`` matrix. If ``keepdims`` is ``False``, the returned array must have a rank which is two less than the rank of ``x``. If ``x`` has a real-valued data type, the returned array must have a real-valued floating-point data type determined by :ref:`type-promotion`. If ``x`` has a complex-valued data type, the returned array must have a real-valued floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``complex128``, then the returned array must have a ``float64`` data type). Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -2621,20 +2625,20 @@ class matrix_power[TArray: Array](Protocol): Parameters ---------- x: array - input array having shape ``(..., M, M)`` and whose innermost two dimensions form square matrices. Should have a floating-point data type. + input array having shape ``(..., M, M)`` and whose innermost two dimensions form square matrices. Should have a floating-point data type. n: int - integer exponent. + integer exponent. Returns ------- out: array - if ``n`` is equal to zero, an array containing the identity matrix for each square matrix. If ``n`` is less than zero, an array containing the inverse of each square matrix raised to the absolute value of ``n``, provided that each square matrix is invertible. If ``n`` is greater than zero, an array containing the result of raising each square matrix to the power ``n``. The returned array must have the same shape as ``x`` and a floating-point data type determined by :ref:`type-promotion`. + if ``n`` is equal to zero, an array containing the identity matrix for each square matrix. If ``n`` is less than zero, an array containing the inverse of each square matrix raised to the absolute value of ``n``, provided that each square matrix is invertible. If ``n`` is greater than zero, an array containing the result of raising each square matrix to the power ``n``. The returned array must have the same shape as ``x`` and a floating-point data type determined by :ref:`type-promotion`. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -2652,20 +2656,20 @@ class matrix_rank[TArray: Array](Protocol): Parameters ---------- x: array - input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. Should have a floating-point data type. + input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. Should have a floating-point data type. rtol: Optional[Union[float, array]] - relative tolerance for small singular values. Singular values approximately less than or equal to ``rtol * largest_singular_value`` are set to zero. If a ``float``, the value is equivalent to a zero-dimensional array having a real-valued floating-point data type determined by :ref:`type-promotion` (as applied to ``x``) and must be broadcast against each matrix. If an ``array``, must have a real-valued floating-point data type and must be compatible with ``shape(x)[:-2]`` (see :ref:`broadcasting`). If ``None``, the default value is ``max(M, N) * eps``, where ``eps`` must be the machine epsilon associated with the real-valued floating-point data type determined by :ref:`type-promotion` (as applied to ``x``). Default: ``None``. + relative tolerance for small singular values. Singular values approximately less than or equal to ``rtol * largest_singular_value`` are set to zero. If a ``float``, the value is equivalent to a zero-dimensional array having a real-valued floating-point data type determined by :ref:`type-promotion` (as applied to ``x``) and must be broadcast against each matrix. If an ``array``, must have a real-valued floating-point data type and must be compatible with ``shape(x)[:-2]`` (see :ref:`broadcasting`). If ``None``, the default value is ``max(M, N) * eps``, where ``eps`` must be the machine epsilon associated with the real-valued floating-point data type determined by :ref:`type-promotion` (as applied to ``x``). Default: ``None``. Returns ------- out: array - an array containing the ranks. The returned array must have the default integer data type and must have shape ``(...)`` (i.e., must have a shape equal to ``shape(x)[:-2]``). + an array containing the ranks. The returned array must have the default integer data type and must have shape ``(...)`` (i.e., must have a shape equal to ``shape(x)[:-2]``). Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -2681,20 +2685,20 @@ class outer[TArray: Array](Protocol): Parameters ---------- x1: array - first one-dimensional input array of size ``N``. Must have a numeric data type. + first one-dimensional input array of size ``N``. Must have a numeric data type. x2: array - second one-dimensional input array of size ``M``. Must have a numeric data type. + second one-dimensional input array of size ``M``. Must have a numeric data type. Returns ------- out: array - a two-dimensional array containing the outer product and whose shape is ``(N, M)``. The returned array must have a data type determined by :ref:`type-promotion`. + a two-dimensional array containing the outer product and whose shape is ``(N, M)``. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -2712,12 +2716,12 @@ class pinv[TArray: Array](Protocol): While the pseudo-inverse can be defined algebraically, one can understand the pseudo-inverse via singular value decomposition (SVD). Namely, if .. math:: - A = U \\Sigma V^H + A = U \\Sigma V^H is a singular decomposition of :math:`A`, then .. math:: - A^{+} = U \\Sigma^{+} V^H + A^{+} = U \\Sigma^{+} V^H where :math:`U` and :math:`V^H` are orthogonal matrices, :math:`\\Sigma` is a diagonal matrix consisting of :math:`A`'s singular values, and :math:`\\Sigma^{+}` is then a diagonal matrix consisting of the reciprocals of :math:`A`'s singular values, leaving zeros in place. During numerical computation, only elements larger than a small tolerance are considered nonzero, and all others replaced by zeros. @@ -2726,20 +2730,20 @@ class pinv[TArray: Array](Protocol): Parameters ---------- x: array - input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. Should have a floating-point data type. + input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. Should have a floating-point data type. rtol: Optional[Union[float, array]] - relative tolerance for small singular values. Singular values approximately less than or equal to ``rtol * largest_singular_value`` are set to zero. If a ``float``, the value is equivalent to a zero-dimensional array having a real-valued floating-point data type determined by :ref:`type-promotion` (as applied to ``x``) and must be broadcast against each matrix. If an ``array``, must have a real-valued floating-point data type and must be compatible with ``shape(x)[:-2]`` (see :ref:`broadcasting`). If ``None``, the default value is ``max(M, N) * eps``, where ``eps`` must be the machine epsilon associated with the real-valued floating-point data type determined by :ref:`type-promotion` (as applied to ``x``). Default: ``None``. + relative tolerance for small singular values. Singular values approximately less than or equal to ``rtol * largest_singular_value`` are set to zero. If a ``float``, the value is equivalent to a zero-dimensional array having a real-valued floating-point data type determined by :ref:`type-promotion` (as applied to ``x``) and must be broadcast against each matrix. If an ``array``, must have a real-valued floating-point data type and must be compatible with ``shape(x)[:-2]`` (see :ref:`broadcasting`). If ``None``, the default value is ``max(M, N) * eps``, where ``eps`` must be the machine epsilon associated with the real-valued floating-point data type determined by :ref:`type-promotion` (as applied to ``x``). Default: ``None``. Returns ------- out: array - an array containing the pseudo-inverse(s). The returned array must have a floating-point data type determined by :ref:`type-promotion` and must have shape ``(..., N, M)`` (i.e., must have the same shape as ``x``, except the innermost two dimensions must be transposed). + an array containing the pseudo-inverse(s). The returned array must have a floating-point data type determined by :ref:`type-promotion` and must have shape ``(..., N, M)`` (i.e., must have the same shape as ``x``, except the innermost two dimensions must be transposed). Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -2757,14 +2761,14 @@ class qr[TArray: Array](Protocol): The **complete QR decomposition** of a matrix :math:`x \\in\\ \\mathbb{K}^{n \\times n}` is defined as .. math:: - x = QR + x = QR where :math:`Q \\in\\ \\mathbb{K}^{m \\times m}` is orthogonal when ``x`` is real-valued and unitary when ``x`` is complex-valued and where :math:`R \\in\\ \\mathbb{K}^{m \\times n}` is an upper triangular matrix with real diagonal (even when ``x`` is complex-valued). When :math:`m \\gt n` (tall matrix), as :math:`R` is upper triangular, the last :math:`m - n` rows are zero. In this case, the last :math:`m - n` columns of :math:`Q` can be dropped to form the **reduced QR decomposition**. .. math:: - x = QR + x = QR where :math:`Q \\in\\ \\mathbb{K}^{m \\times n}` and :math:`R \\in\\ \\mathbb{K}^{n \\times n}`. @@ -2773,41 +2777,41 @@ class qr[TArray: Array](Protocol): When ``x`` is a stack of matrices, the function must compute the QR decomposition for each matrix in the stack. .. note:: - Whether an array library explicitly checks whether an input array is a full column rank matrix (or a stack of full column rank matrices) is implementation-defined. + Whether an array library explicitly checks whether an input array is a full column rank matrix (or a stack of full column rank matrices) is implementation-defined. .. warning:: - The elements in the diagonal of :math:`R` are not necessarily positive. Accordingly, the returned QR decomposition is only unique up to the sign of the diagonal of :math:`R`, and different libraries or inputs on different devices may produce different valid decompositions. + The elements in the diagonal of :math:`R` are not necessarily positive. Accordingly, the returned QR decomposition is only unique up to the sign of the diagonal of :math:`R`, and different libraries or inputs on different devices may produce different valid decompositions. .. warning:: - The QR decomposition is only well-defined if the first ``k = min(m,n)`` columns of every matrix in ``x`` are linearly independent. + The QR decomposition is only well-defined if the first ``k = min(m,n)`` columns of every matrix in ``x`` are linearly independent. Parameters ---------- x: array - input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices of rank ``N``. Should have a floating-point data type. + input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices of rank ``N``. Should have a floating-point data type. mode: Literal['reduced', 'complete'] - decomposition mode. Should be one of the following modes: + decomposition mode. Should be one of the following modes: - - ``'reduced'``: compute only the leading ``K`` columns of ``q``, such that ``q`` and ``r`` have dimensions ``(..., M, K)`` and ``(..., K, N)``, respectively, and where ``K = min(M, N)``. - - ``'complete'``: compute ``q`` and ``r`` with dimensions ``(..., M, M)`` and ``(..., M, N)``, respectively. + - ``'reduced'``: compute only the leading ``K`` columns of ``q``, such that ``q`` and ``r`` have dimensions ``(..., M, K)`` and ``(..., K, N)``, respectively, and where ``K = min(M, N)``. + - ``'complete'``: compute ``q`` and ``r`` with dimensions ``(..., M, M)`` and ``(..., M, N)``, respectively. - Default: ``'reduced'``. + Default: ``'reduced'``. Returns ------- out: Tuple[array, array] - a namedtuple ``(Q, R)`` whose + a namedtuple ``(Q, R)`` whose - - first element must have the field name ``Q`` and must be an array whose shape depends on the value of ``mode`` and contain matrices with orthonormal columns. If ``mode`` is ``'complete'``, the array must have shape ``(..., M, M)``. If ``mode`` is ``'reduced'``, the array must have shape ``(..., M, K)``, where ``K = min(M, N)``. The first ``x.ndim-2`` dimensions must have the same size as those of the input array ``x``. - - second element must have the field name ``R`` and must be an array whose shape depends on the value of ``mode`` and contain upper-triangular matrices. If ``mode`` is ``'complete'``, the array must have shape ``(..., M, N)``. If ``mode`` is ``'reduced'``, the array must have shape ``(..., K, N)``, where ``K = min(M, N)``. The first ``x.ndim-2`` dimensions must have the same size as those of the input ``x``. + - first element must have the field name ``Q`` and must be an array whose shape depends on the value of ``mode`` and contain matrices with orthonormal columns. If ``mode`` is ``'complete'``, the array must have shape ``(..., M, M)``. If ``mode`` is ``'reduced'``, the array must have shape ``(..., M, K)``, where ``K = min(M, N)``. The first ``x.ndim-2`` dimensions must have the same size as those of the input array ``x``. + - second element must have the field name ``R`` and must be an array whose shape depends on the value of ``mode`` and contain upper-triangular matrices. If ``mode`` is ``'complete'``, the array must have shape ``(..., M, N)``. If ``mode`` is ``'reduced'``, the array must have shape ``(..., K, N)``, where ``K = min(M, N)``. The first ``x.ndim-2`` dimensions must have the same size as those of the input ``x``. - Each returned array must have a floating-point data type determined by :ref:`type-promotion`. + Each returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -2821,15 +2825,15 @@ class slogdet[TArray: Array](Protocol): Returns the sign and the natural logarithm of the absolute value of the determinant of a square matrix (or a stack of square matrices) ``x``. .. note:: - The purpose of this function is to calculate the determinant more accurately when the determinant is either very small or very large, as calling ``det`` may overflow or underflow. + The purpose of this function is to calculate the determinant more accurately when the determinant is either very small or very large, as calling ``det`` may overflow or underflow. The sign of the determinant is given by .. math:: - \\operatorname{sign}(\\det x) = \\begin{cases} - 0 & \\textrm{if } \\det x = 0 \\\\ - \\frac{\\det x}{|\\det x|} & \\textrm{otherwise} - \\end{cases} + \\operatorname{sign}(\\det x) = \\begin{cases} + 0 & \\textrm{if } \\det x = 0 \\\\ + \\frac{\\det x}{|\\det x|} & \\textrm{otherwise} + \\end{cases} where :math:`|\\det x|` is the absolute value of the determinant of ``x``. @@ -2846,28 +2850,28 @@ class slogdet[TArray: Array](Protocol): - If the determinant is ``0 + 0j``, the ``sign`` should be ``0 + 0j`` and ``logabsdet`` should be ``-infinity + 0j``. .. note:: - Depending on the underlying algorithm, when the determinant is zero, the returned result may differ from ``-infinity`` (or ``-infinity + 0j``). In all cases, the determinant should be equal to ``sign * exp(logabsdet)`` (although, again, the result may be subject to numerical precision errors). + Depending on the underlying algorithm, when the determinant is zero, the returned result may differ from ``-infinity`` (or ``-infinity + 0j``). In all cases, the determinant should be equal to ``sign * exp(logabsdet)`` (although, again, the result may be subject to numerical precision errors). Parameters ---------- x: array - input array having shape ``(..., M, M)`` and whose innermost two dimensions form square matrices. Should have a floating-point data type. + input array having shape ``(..., M, M)`` and whose innermost two dimensions form square matrices. Should have a floating-point data type. Returns ------- out: Tuple[array, array] - a namedtuple (``sign``, ``logabsdet``) whose + a namedtuple (``sign``, ``logabsdet``) whose - - first element must have the field name ``sign`` and must be an array containing a number representing the sign of the determinant for each square matrix. Must have the same data type as ``x``. - - second element must have the field name ``logabsdet`` and must be an array containing the natural logarithm of the absolute value of the determinant for each square matrix. If ``x`` is real-valued, the returned array must have a real-valued floating-point data type determined by :ref:`type-promotion`. If ``x`` is complex, the returned array must have a real-valued floating-point data type having the same precision as ``x`` (e.g., if ``x`` is ``complex64``, ``logabsdet`` must have a ``float32`` data type). + - first element must have the field name ``sign`` and must be an array containing a number representing the sign of the determinant for each square matrix. Must have the same data type as ``x``. + - second element must have the field name ``logabsdet`` and must be an array containing the natural logarithm of the absolute value of the determinant for each square matrix. If ``x`` is real-valued, the returned array must have a real-valued floating-point data type determined by :ref:`type-promotion`. If ``x`` is complex, the returned array must have a real-valued floating-point data type having the same precision as ``x`` (e.g., if ``x`` is ``complex64``, ``logabsdet`` must have a ``float32`` data type). - Each returned array must have shape ``shape(x)[:-2]``. + Each returned array must have shape ``shape(x)[:-2]``. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -2885,32 +2889,32 @@ class solve[TArray: Array](Protocol): This function computes the solution :math:`X \\in\\ \\mathbb{K}^{m \\times k}` of the **linear system** associated to :math:`A \\in\\ \\mathbb{K}^{m \\times m}` and :math:`B \\in\\ \\mathbb{K}^{m \\times k}` and is defined as .. math:: - AX = B + AX = B This system of linear equations has a unique solution if and only if :math:`A` is invertible. .. note:: - Whether an array library explicitly checks whether ``x1`` is invertible is implementation-defined. + Whether an array library explicitly checks whether ``x1`` is invertible is implementation-defined. When ``x1`` and/or ``x2`` is a stack of matrices, the function must compute a solution for each matrix in the stack. Parameters ---------- x1: array - coefficient array ``A`` having shape ``(..., M, M)`` and whose innermost two dimensions form square matrices. Must be of full rank (i.e., all rows or, equivalently, columns must be linearly independent). Should have a floating-point data type. + coefficient array ``A`` having shape ``(..., M, M)`` and whose innermost two dimensions form square matrices. Must be of full rank (i.e., all rows or, equivalently, columns must be linearly independent). Should have a floating-point data type. x2: array - ordinate (or "dependent variable") array ``B``. If ``x2`` has shape ``(M,)``, ``x2`` is equivalent to an array having shape ``(..., M, 1)``. If ``x2`` has shape ``(..., M, K)``, each column ``k`` defines a set of ordinate values for which to compute a solution, and ``shape(x2)[:-2]`` must be compatible with ``shape(x1)[:-2]`` (see :ref:`broadcasting`). Should have a floating-point data type. + ordinate (or "dependent variable") array ``B``. If ``x2`` has shape ``(M,)``, ``x2`` is equivalent to an array having shape ``(..., M, 1)``. If ``x2`` has shape ``(..., M, K)``, each column ``k`` defines a set of ordinate values for which to compute a solution, and ``shape(x2)[:-2]`` must be compatible with ``shape(x1)[:-2]`` (see :ref:`broadcasting`). Should have a floating-point data type. Returns ------- out: array - an array containing the solution to the system ``AX = B`` for each square matrix. If ``x2`` has shape ``(M,)``, the returned array must have shape equal to ``shape(x1)[:-2] + shape(x2)[-1:]``. Otherwise, if ``x2`` has shape ``(..., M, K)```, the returned array must have shape equal to ``(..., M, K)``, where ``...`` refers to the result of broadcasting ``shape(x1)[:-2]`` and ``shape(x2)[:-2]``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the solution to the system ``AX = B`` for each square matrix. If ``x2`` has shape ``(M,)``, the returned array must have shape equal to ``shape(x1)[:-2] + shape(x2)[-1:]``. Otherwise, if ``x2`` has shape ``(..., M, K)```, the returned array must have shape equal to ``(..., M, K)``, where ``...`` refers to the result of broadcasting ``shape(x1)[:-2]`` and ``shape(x2)[:-2]``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -2928,14 +2932,14 @@ class svd[TArray: Array](Protocol): The full **singular value decomposition** of an :math:`m \\times n` matrix :math:`x \\in\\ \\mathbb{K}^{m \\times n}` is a factorization of the form .. math:: - x = U \\Sigma V^H + x = U \\Sigma V^H where :math:`U \\in\\ \\mathbb{K}^{m \\times m}`, :math:`\\Sigma \\in\\ \\mathbb{K}^{m \\times\\ n}`, :math:`\\operatorname{diag}(\\Sigma) \\in\\ \\mathbb{R}^{k}` with :math:`k = \\operatorname{min}(m, n)`, :math:`V^H \\in\\ \\mathbb{K}^{n \\times n}`, and where :math:`V^H` is the conjugate transpose when :math:`V` is complex and the transpose when :math:`V` is real-valued. When ``x`` is real-valued, :math:`U`, :math:`V` (and thus :math:`V^H`) are orthogonal, and, when ``x`` is complex, :math:`U`, :math:`V` (and thus :math:`V^H`) are unitary. When :math:`m \\gt n` (tall matrix), we can drop the last :math:`m - n` columns of :math:`U` to form the reduced SVD .. math:: - x = U \\Sigma V^H + x = U \\Sigma V^H where :math:`U \\in\\ \\mathbb{K}^{m \\times k}`, :math:`\\Sigma \\in\\ \\mathbb{K}^{k \\times\\ k}`, :math:`\\operatorname{diag}(\\Sigma) \\in\\ \\mathbb{R}^{k}`, and :math:`V^H \\in\\ \\mathbb{K}^{k \\times n}`. In this case, :math:`U` and :math:`V` have orthonormal columns. @@ -2946,31 +2950,31 @@ class svd[TArray: Array](Protocol): When ``x`` is a stack of matrices, the function must compute the singular value decomposition for each matrix in the stack. .. warning:: - The returned arrays :math:`U` and :math:`V` are neither unique nor continuous with respect to ``x``. Because :math:`U` and :math:`V` are not unique, different hardware and software may compute different singular vectors. + The returned arrays :math:`U` and :math:`V` are neither unique nor continuous with respect to ``x``. Because :math:`U` and :math:`V` are not unique, different hardware and software may compute different singular vectors. - Non-uniqueness stems from the fact that multiplying any pair of singular vectors :math:`u_k`, :math:`v_k` by :math:`-1` when ``x`` is real-valued and by :math:`e^{\\phi j}` (:math:`\\phi \\in \\mathbb{R}`) when ``x`` is complex produces another two valid singular vectors of the matrix. + Non-uniqueness stems from the fact that multiplying any pair of singular vectors :math:`u_k`, :math:`v_k` by :math:`-1` when ``x`` is real-valued and by :math:`e^{\\phi j}` (:math:`\\phi \\in \\mathbb{R}`) when ``x`` is complex produces another two valid singular vectors of the matrix. Parameters ---------- x: array - input array having shape ``(..., M, N)`` and whose innermost two dimensions form matrices on which to perform singular value decomposition. Should have a floating-point data type. + input array having shape ``(..., M, N)`` and whose innermost two dimensions form matrices on which to perform singular value decomposition. Should have a floating-point data type. full_matrices: bool - If ``True``, compute full-sized ``U`` and ``Vh``, such that ``U`` has shape ``(..., M, M)`` and ``Vh`` has shape ``(..., N, N)``. If ``False``, compute on the leading ``K`` singular vectors, such that ``U`` has shape ``(..., M, K)`` and ``Vh`` has shape ``(..., K, N)`` and where ``K = min(M, N)``. Default: ``True``. + If ``True``, compute full-sized ``U`` and ``Vh``, such that ``U`` has shape ``(..., M, M)`` and ``Vh`` has shape ``(..., N, N)``. If ``False``, compute on the leading ``K`` singular vectors, such that ``U`` has shape ``(..., M, K)`` and ``Vh`` has shape ``(..., K, N)`` and where ``K = min(M, N)``. Default: ``True``. Returns ------- out: Tuple[array, array, array] - a namedtuple ``(U, S, Vh)`` whose + a namedtuple ``(U, S, Vh)`` whose - - first element must have the field name ``U`` and must be an array whose shape depends on the value of ``full_matrices`` and contain matrices with orthonormal columns (i.e., the columns are left singular vectors). If ``full_matrices`` is ``True``, the array must have shape ``(..., M, M)``. If ``full_matrices`` is ``False``, the array must have shape ``(..., M, K)``, where ``K = min(M, N)``. The first ``x.ndim-2`` dimensions must have the same shape as those of the input ``x``. Must have the same data type as ``x``. - - second element must have the field name ``S`` and must be an array with shape ``(..., K)`` that contains the vector(s) of singular values of length ``K``, where ``K = min(M, N)``. For each vector, the singular values must be sorted in descending order by magnitude, such that ``s[..., 0]`` is the largest value, ``s[..., 1]`` is the second largest value, et cetera. The first ``x.ndim-2`` dimensions must have the same shape as those of the input ``x``. Must have a real-valued floating-point data type having the same precision as ``x`` (e.g., if ``x`` is ``complex64``, ``S`` must have a ``float32`` data type). - - third element must have the field name ``Vh`` and must be an array whose shape depends on the value of ``full_matrices`` and contain orthonormal rows (i.e., the rows are the right singular vectors and the array is the adjoint). If ``full_matrices`` is ``True``, the array must have shape ``(..., N, N)``. If ``full_matrices`` is ``False``, the array must have shape ``(..., K, N)`` where ``K = min(M, N)``. The first ``x.ndim-2`` dimensions must have the same shape as those of the input ``x``. Must have the same data type as ``x``. + - first element must have the field name ``U`` and must be an array whose shape depends on the value of ``full_matrices`` and contain matrices with orthonormal columns (i.e., the columns are left singular vectors). If ``full_matrices`` is ``True``, the array must have shape ``(..., M, M)``. If ``full_matrices`` is ``False``, the array must have shape ``(..., M, K)``, where ``K = min(M, N)``. The first ``x.ndim-2`` dimensions must have the same shape as those of the input ``x``. Must have the same data type as ``x``. + - second element must have the field name ``S`` and must be an array with shape ``(..., K)`` that contains the vector(s) of singular values of length ``K``, where ``K = min(M, N)``. For each vector, the singular values must be sorted in descending order by magnitude, such that ``s[..., 0]`` is the largest value, ``s[..., 1]`` is the second largest value, et cetera. The first ``x.ndim-2`` dimensions must have the same shape as those of the input ``x``. Must have a real-valued floating-point data type having the same precision as ``x`` (e.g., if ``x`` is ``complex64``, ``S`` must have a ``float32`` data type). + - third element must have the field name ``Vh`` and must be an array whose shape depends on the value of ``full_matrices`` and contain orthonormal rows (i.e., the rows are the right singular vectors and the array is the adjoint). If ``full_matrices`` is ``True``, the array must have shape ``(..., N, N)``. If ``full_matrices`` is ``False``, the array must have shape ``(..., K, N)`` where ``K = min(M, N)``. The first ``x.ndim-2`` dimensions must have the same shape as those of the input ``x``. Must have the same data type as ``x``. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -2988,18 +2992,18 @@ class svdvals[TArray: Array](Protocol): Parameters ---------- x: array - input array having shape ``(..., M, N)`` and whose innermost two dimensions form matrices on which to perform singular value decomposition. Should have a floating-point data type. + input array having shape ``(..., M, N)`` and whose innermost two dimensions form matrices on which to perform singular value decomposition. Should have a floating-point data type. Returns ------- out: array - an array with shape ``(..., K)`` that contains the vector(s) of singular values of length ``K``, where ``K = min(M, N)``. For each vector, the singular values must be sorted in descending order by magnitude, such that ``s[..., 0]`` is the largest value, ``s[..., 1]`` is the second largest value, et cetera. The first ``x.ndim-2`` dimensions must have the same shape as those of the input ``x``. The returned array must have a real-valued floating-point data type having the same precision as ``x`` (e.g., if ``x`` is ``complex64``, the returned array must have a ``float32`` data type). + an array with shape ``(..., K)`` that contains the vector(s) of singular values of length ``K``, where ``K = min(M, N)``. For each vector, the singular values must be sorted in descending order by magnitude, such that ``s[..., 0]`` is the largest value, ``s[..., 1]`` is the second largest value, et cetera. The first ``x.ndim-2`` dimensions must have the same shape as those of the input ``x``. The returned array must have a real-valued floating-point data type having the same precision as ``x`` (e.g., if ``x`` is ``complex64``, the returned array must have a ``float32`` data type). Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -3015,39 +3019,39 @@ class trace[TArray: Array, TDtype](Protocol): Parameters ---------- x: array - input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. Should have a numeric data type. + input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. Should have a numeric data type. offset: int - offset specifying the off-diagonal relative to the main diagonal. + offset specifying the off-diagonal relative to the main diagonal. - - ``offset = 0``: the main diagonal. - - ``offset > 0``: off-diagonal above the main diagonal. - - ``offset < 0``: off-diagonal below the main diagonal. + - ``offset = 0``: the main diagonal. + - ``offset > 0``: off-diagonal above the main diagonal. + - ``offset < 0``: off-diagonal below the main diagonal. - Default: ``0``. + Default: ``0``. dtype: Optional[dtype] - data type of the returned array. If ``None``, + data type of the returned array. If ``None``, - - if the default data type corresponding to the data type "kind" (integer, real-valued floating-point, or complex floating-point) of ``x`` has a smaller range of values than the data type of ``x`` (e.g., ``x`` has data type ``int64`` and the default data type is ``int32``, or ``x`` has data type ``uint64`` and the default data type is ``int64``), the returned array must have the same data type as ``x``. - - if ``x`` has a real-valued floating-point data type, the returned array must have the default real-valued floating-point data type. - - if ``x`` has a complex floating-point data type, the returned array must have the default complex floating-point data type. - - if ``x`` has a signed integer data type (e.g., ``int16``), the returned array must have the default integer data type. - - if ``x`` has an unsigned integer data type (e.g., ``uint16``), the returned array must have an unsigned integer data type having the same number of bits as the default integer data type (e.g., if the default integer data type is ``int32``, the returned array must have a ``uint32`` data type). + - if the default data type corresponding to the data type "kind" (integer, real-valued floating-point, or complex floating-point) of ``x`` has a smaller range of values than the data type of ``x`` (e.g., ``x`` has data type ``int64`` and the default data type is ``int32``, or ``x`` has data type ``uint64`` and the default data type is ``int64``), the returned array must have the same data type as ``x``. + - if ``x`` has a real-valued floating-point data type, the returned array must have the default real-valued floating-point data type. + - if ``x`` has a complex floating-point data type, the returned array must have the default complex floating-point data type. + - if ``x`` has a signed integer data type (e.g., ``int16``), the returned array must have the default integer data type. + - if ``x`` has an unsigned integer data type (e.g., ``uint16``), the returned array must have an unsigned integer data type having the same number of bits as the default integer data type (e.g., if the default integer data type is ``int32``, the returned array must have a ``uint32`` data type). - If the data type (either specified or resolved) differs from the data type of ``x``, the input array should be cast to the specified data type before computing the sum. Default: ``None``. + If the data type (either specified or resolved) differs from the data type of ``x``, the input array should be cast to the specified data type before computing the sum. Default: ``None``. - .. note:: - keyword argument is intended to help prevent data type overflows. + .. note:: + keyword argument is intended to help prevent data type overflows. Returns ------- out: array - an array containing the traces and whose shape is determined by removing the last two dimensions and storing the traces in the last array dimension. For example, if ``x`` has rank ``k`` and shape ``(I, J, K, ..., L, M, N)``, then an output array has rank ``k-2`` and shape ``(I, J, K, ..., L)`` where + an array containing the traces and whose shape is determined by removing the last two dimensions and storing the traces in the last array dimension. For example, if ``x`` has rank ``k`` and shape ``(I, J, K, ..., L, M, N)``, then an output array has rank ``k-2`` and shape ``(I, J, K, ..., L)`` where - :: + :: - out[i, j, k, ..., l] = trace(a[i, j, k, ..., l, :, :]) + out[i, j, k, ..., l] = trace(a[i, j, k, ..., l, :, :]) - The returned array must have a data type as described by the ``dtype`` parameter above. + The returned array must have a data type as described by the ``dtype`` parameter above. Notes ----- @@ -3060,7 +3064,7 @@ class trace[TArray: Array, TDtype](Protocol): For both real-valued and complex floating-point operands, special cases must be handled as if the operation is implemented by successive application of :func:`~array_api.add`. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -3076,54 +3080,54 @@ class vector_norm[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a floating-point data type. + input array. Should have a floating-point data type. axis: Optional[Union[int, Tuple[int, ...]]] - If an integer, ``axis`` specifies the axis (dimension) along which to compute vector norms. If an n-tuple, ``axis`` specifies the axes (dimensions) along which to compute batched vector norms. If ``None``, the vector norm must be computed over all array values (i.e., equivalent to computing the vector norm of a flattened array). Negative indices must be supported. Default: ``None``. + If an integer, ``axis`` specifies the axis (dimension) along which to compute vector norms. If an n-tuple, ``axis`` specifies the axes (dimensions) along which to compute batched vector norms. If ``None``, the vector norm must be computed over all array values (i.e., equivalent to computing the vector norm of a flattened array). Negative indices must be supported. Default: ``None``. keepdims: bool - If ``True``, the axes (dimensions) specified by ``axis`` must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the axes (dimensions) specified by ``axis`` must not be included in the result. Default: ``False``. + If ``True``, the axes (dimensions) specified by ``axis`` must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the axes (dimensions) specified by ``axis`` must not be included in the result. Default: ``False``. ord: Union[int, float, Literal[inf, -inf]] - order of the norm. The following mathematical norms must be supported: + order of the norm. The following mathematical norms must be supported: - +------------------+----------------------------+ - | ord | description | - +==================+============================+ - | 1 | L1-norm (Manhattan) | - +------------------+----------------------------+ - | 2 | L2-norm (Euclidean) | - +------------------+----------------------------+ - | inf | infinity norm | - +------------------+----------------------------+ - | (int,float >= 1) | p-norm | - +------------------+----------------------------+ + +------------------+----------------------------+ + | ord | description | + +==================+============================+ + | 1 | L1-norm (Manhattan) | + +------------------+----------------------------+ + | 2 | L2-norm (Euclidean) | + +------------------+----------------------------+ + | inf | infinity norm | + +------------------+----------------------------+ + | (int,float >= 1) | p-norm | + +------------------+----------------------------+ - The following non-mathematical "norms" must be supported: + The following non-mathematical "norms" must be supported: - +------------------+--------------------------------+ - | ord | description | - +==================+================================+ - | 0 | sum(a != 0) | - +------------------+--------------------------------+ - | -1 | 1./sum(1./abs(a)) | - +------------------+--------------------------------+ - | -2 | 1./sqrt(sum(1./abs(a)\\*\\*2)) | - +------------------+--------------------------------+ - | -inf | min(abs(a)) | - +------------------+--------------------------------+ - | (int,float < 1) | sum(abs(a)\\*\\*ord)\\*\\*(1./ord) | - +------------------+--------------------------------+ + +------------------+--------------------------------+ + | ord | description | + +==================+================================+ + | 0 | sum(a != 0) | + +------------------+--------------------------------+ + | -1 | 1./sum(1./abs(a)) | + +------------------+--------------------------------+ + | -2 | 1./sqrt(sum(1./abs(a)\\*\\*2)) | + +------------------+--------------------------------+ + | -inf | min(abs(a)) | + +------------------+--------------------------------+ + | (int,float < 1) | sum(abs(a)\\*\\*ord)\\*\\*(1./ord) | + +------------------+--------------------------------+ - Default: ``2``. + Default: ``2``. Returns ------- out: array - an array containing the vector norms. If ``axis`` is ``None``, the returned array must be a zero-dimensional array containing a vector norm. If ``axis`` is a scalar value (``int`` or ``float``), the returned array must have a rank which is one less than the rank of ``x``. If ``axis`` is a ``n``-tuple, the returned array must have a rank which is ``n`` less than the rank of ``x``. If ``x`` has a real-valued data type, the returned array must have a real-valued floating-point data type determined by :ref:`type-promotion`. If ``x`` has a complex-valued data type, the returned array must have a real-valued floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``complex128``, then the returned array must have a ``float64`` data type). + an array containing the vector norms. If ``axis`` is ``None``, the returned array must be a zero-dimensional array containing a vector norm. If ``axis`` is a scalar value (``int`` or ``float``), the returned array must have a rank which is one less than the rank of ``x``. If ``axis`` is a ``n``-tuple, the returned array must have a rank which is ``n`` less than the rank of ``x``. If ``x`` has a real-valued data type, the returned array must have a real-valued floating-point data type determined by :ref:`type-promotion`. If ``x`` has a complex-valued data type, the returned array must have a real-valued floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``complex128``, then the returned array must have a ``float64`` data type). Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -3138,23 +3142,23 @@ class argsort[TArray: Array](Protocol): Returns the indices that sort an array ``x`` along a specified axis. .. note:: - For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). + For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). Parameters ---------- x : array - input array. Should have a real-valued data type. + input array. Should have a real-valued data type. axis: int - axis along which to sort. If set to ``-1``, the function must sort along the last axis. Default: ``-1``. + axis along which to sort. If set to ``-1``, the function must sort along the last axis. Default: ``-1``. descending: bool - sort order. If ``True``, the returned indices sort ``x`` in descending order (by value). If ``False``, the returned indices sort ``x`` in ascending order (by value). Default: ``False``. + sort order. If ``True``, the returned indices sort ``x`` in descending order (by value). If ``False``, the returned indices sort ``x`` in ascending order (by value). Default: ``False``. stable: bool - sort stability. If ``True``, the returned indices must maintain the relative order of ``x`` values which compare as equal. If ``False``, the returned indices may or may not maintain the relative order of ``x`` values which compare as equal (i.e., the relative order of ``x`` values which compare as equal is implementation-dependent). Default: ``True``. + sort stability. If ``True``, the returned indices must maintain the relative order of ``x`` values which compare as equal. If ``False``, the returned indices may or may not maintain the relative order of ``x`` values which compare as equal (i.e., the relative order of ``x`` values which compare as equal is implementation-dependent). Default: ``True``. Returns ------- out : array - an array of indices. The returned array must have the same shape as ``x``. The returned array must have the default array index data type. + an array of indices. The returned array must have the same shape as ``x``. The returned array must have the default array index data type. """ @@ -3168,23 +3172,23 @@ class sort[TArray: Array](Protocol): Returns a sorted copy of an input array ``x``. .. note:: - For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). + For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). Parameters ---------- x: array - input array. Should have a real-valued data type. + input array. Should have a real-valued data type. axis: int - axis along which to sort. If set to ``-1``, the function must sort along the last axis. Default: ``-1``. + axis along which to sort. If set to ``-1``, the function must sort along the last axis. Default: ``-1``. descending: bool - sort order. If ``True``, the array must be sorted in descending order (by value). If ``False``, the array must be sorted in ascending order (by value). Default: ``False``. + sort order. If ``True``, the array must be sorted in descending order (by value). If ``False``, the array must be sorted in ascending order (by value). Default: ``False``. stable: bool - sort stability. If ``True``, the returned array must maintain the relative order of ``x`` values which compare as equal. If ``False``, the returned array may or may not maintain the relative order of ``x`` values which compare as equal (i.e., the relative order of ``x`` values which compare as equal is implementation-dependent). Default: ``True``. + sort stability. If ``True``, the returned array must maintain the relative order of ``x`` values which compare as equal. If ``False``, the returned array may or may not maintain the relative order of ``x`` values which compare as equal (i.e., the relative order of ``x`` values which compare as equal is implementation-dependent). Default: ``True``. Returns ------- out : array - a sorted array. The returned array must have the same data type and shape as ``x``. + a sorted array. The returned array must have the same data type and shape as ``x``. """ @@ -3200,29 +3204,29 @@ class abs[TArray: Array](Protocol): For real-valued input arrays, the element-wise result has the same magnitude as the respective element in ``x`` but has positive sign. .. note:: - For signed integer data types, the absolute value of the minimum representable integer is implementation-dependent. + For signed integer data types, the absolute value of the minimum representable integer is implementation-dependent. .. note:: - For complex floating-point operands, the complex absolute value is known as the norm, modulus, or magnitude and, for a complex number :math:`z = a + bj` is computed as + For complex floating-point operands, the complex absolute value is known as the norm, modulus, or magnitude and, for a complex number :math:`z = a + bj` is computed as - .. math:: - \\operatorname{abs}(z) = \\sqrt{a^2 + b^2} + .. math:: + \\operatorname{abs}(z) = \\sqrt{a^2 + b^2} .. note:: - For complex floating-point operands, conforming implementations should take care to avoid undue overflow or underflow during intermediate stages of computation. + For complex floating-point operands, conforming implementations should take care to avoid undue overflow or underflow during intermediate stages of computation. .. - TODO: once ``hypot`` is added to the specification, remove the special cases for complex floating-point operands and the note concerning guarding against undue overflow/underflow, and state that special cases must be handled as if implemented as ``hypot(real(x), imag(x))``. + TODO: once ``hypot`` is added to the specification, remove the special cases for complex floating-point operands and the note concerning guarding against undue overflow/underflow, and state that special cases must be handled as if implemented as ``hypot(real(x), imag(x))``. Parameters ---------- x: array - input array. Should have a numeric data type. + input array. Should have a numeric data type. Returns ------- out: array - an array containing the absolute value of each element in ``x``. If ``x`` has a real-valued data type, the returned array must have the same data type as ``x``. If ``x`` has a complex floating-point data type, the returned array must have a real-valued floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``complex128``, then the returned array must have a ``float64`` data type). + an array containing the absolute value of each element in ``x``. If ``x`` has a real-valued data type, the returned array must have the same data type as ``x``. If ``x`` has a complex floating-point data type, the returned array must have a real-valued floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``complex128``, then the returned array must have a ``float64`` data type). Notes ----- @@ -3245,7 +3249,7 @@ class abs[TArray: Array](Protocol): - If ``a`` is ``NaN`` and ``b`` is ``NaN``, the result is ``NaN``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -3261,35 +3265,35 @@ class acos[TArray: Array](Protocol): Each element-wise result is expressed in radians. .. note:: - The principal value of the arc cosine of a complex number :math:`z` is + The principal value of the arc cosine of a complex number :math:`z` is - .. math:: - \\operatorname{acos}(z) = \\frac{1}{2}\\pi + j\\ \\ln(zj + \\sqrt{1-z^2}) + .. math:: + \\operatorname{acos}(z) = \\frac{1}{2}\\pi + j\\ \\ln(zj + \\sqrt{1-z^2}) - For any :math:`z`, + For any :math:`z`, - .. math:: - \\operatorname{acos}(z) = \\pi - \\operatorname{acos}(-z) + .. math:: + \\operatorname{acos}(z) = \\pi - \\operatorname{acos}(-z) .. note:: - For complex floating-point operands, ``acos(conj(x))`` must equal ``conj(acos(x))``. + For complex floating-point operands, ``acos(conj(x))`` must equal ``conj(acos(x))``. .. note:: - The inverse cosine (or arc cosine) is a multi-valued function and requires a branch cut on the complex plane. By convention, a branch cut is placed at the line segments :math:`(-\\infty, -1)` and :math:`(1, \\infty)` of the real axis. + The inverse cosine (or arc cosine) is a multi-valued function and requires a branch cut on the complex plane. By convention, a branch cut is placed at the line segments :math:`(-\\infty, -1)` and :math:`(1, \\infty)` of the real axis. - Accordingly, for complex arguments, the function returns the inverse cosine in the range of a strip unbounded along the imaginary axis and in the interval :math:`[0, \\pi]` along the real axis. + Accordingly, for complex arguments, the function returns the inverse cosine in the range of a strip unbounded along the imaginary axis and in the interval :math:`[0, \\pi]` along the real axis. - *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). + *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). Parameters ---------- x: array - input array. Should have a floating-point data type. + input array. Should have a floating-point data type. Returns ------- out: array - an array containing the inverse cosine of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the inverse cosine of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -3318,7 +3322,7 @@ class acos[TArray: Array](Protocol): - If ``a`` is ``NaN`` and ``b`` is ``NaN``, the result is ``NaN + NaN j``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -3332,42 +3336,42 @@ class acosh[TArray: Array](Protocol): Calculates an implementation-dependent approximation to the inverse hyperbolic cosine for each element ``x_i`` of the input array ``x``. .. note:: - The principal value of the inverse hyperbolic cosine of a complex number :math:`z` is + The principal value of the inverse hyperbolic cosine of a complex number :math:`z` is - .. math:: - \\operatorname{acosh}(z) = \\ln(z + \\sqrt{z+1}\\sqrt{z-1}) + .. math:: + \\operatorname{acosh}(z) = \\ln(z + \\sqrt{z+1}\\sqrt{z-1}) - For any :math:`z`, + For any :math:`z`, - .. math:: - \\operatorname{acosh}(z) = \\frac{\\sqrt{z-1}}{\\sqrt{1-z}}\\operatorname{acos}(z) + .. math:: + \\operatorname{acosh}(z) = \\frac{\\sqrt{z-1}}{\\sqrt{1-z}}\\operatorname{acos}(z) - or simply + or simply - .. math:: - \\operatorname{acosh}(z) = j\\ \\operatorname{acos}(z) + .. math:: + \\operatorname{acosh}(z) = j\\ \\operatorname{acos}(z) - in the upper half of the complex plane. + in the upper half of the complex plane. .. note:: - For complex floating-point operands, ``acosh(conj(x))`` must equal ``conj(acosh(x))``. + For complex floating-point operands, ``acosh(conj(x))`` must equal ``conj(acosh(x))``. .. note:: - The inverse hyperbolic cosine is a multi-valued function and requires a branch cut on the complex plane. By convention, a branch cut is placed at the line segment :math:`(-\\infty, 1)` of the real axis. + The inverse hyperbolic cosine is a multi-valued function and requires a branch cut on the complex plane. By convention, a branch cut is placed at the line segment :math:`(-\\infty, 1)` of the real axis. - Accordingly, for complex arguments, the function returns the inverse hyperbolic cosine in the interval :math:`[0, \\infty)` along the real axis and in the interval :math:`[-\\pi j, +\\pi j]` along the imaginary axis. + Accordingly, for complex arguments, the function returns the inverse hyperbolic cosine in the interval :math:`[0, \\infty)` along the real axis and in the interval :math:`[-\\pi j, +\\pi j]` along the imaginary axis. - *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). + *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). Parameters ---------- x: array - input array whose elements each represent the area of a hyperbolic sector. Should have a floating-point data type. + input array whose elements each represent the area of a hyperbolic sector. Should have a floating-point data type. Returns ------- out: array - an array containing the inverse hyperbolic cosine of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the inverse hyperbolic cosine of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -3396,7 +3400,7 @@ class acosh[TArray: Array](Protocol): - If ``a`` is ``NaN`` and ``b`` is ``NaN``, the result is ``NaN + NaN j``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -3412,14 +3416,14 @@ class add[TArray: Array](Protocol): Parameters ---------- x1: array - first input array. Should have a numeric data type. + first input array. Should have a numeric data type. x2: array - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a numeric data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a numeric data type. Returns ------- out: array - an array containing the element-wise sums. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise sums. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- @@ -3446,7 +3450,7 @@ class add[TArray: Array](Protocol): - In the remaining cases, when neither ``infinity``, ``+0``, ``-0``, nor a ``NaN`` is involved, and the operands have the same mathematical sign or have different magnitudes, the sum must be computed and rounded to the nearest representable value according to IEEE 754-2019 and a supported round mode. If the magnitude is too large to represent, the operation overflows and the result is an `infinity` of appropriate mathematical sign. .. note:: - Floating-point addition is a commutative operation, but not always associative. + Floating-point addition is a commutative operation, but not always associative. For complex floating-point operands, addition is defined according to the following table. For real components ``a`` and ``c`` and imaginary components ``b`` and ``d``, @@ -3468,7 +3472,7 @@ class add[TArray: Array](Protocol): Hence, if ``z1 = a + bj = -0 + 0j`` and ``z2 = c + dj = -0 - 0j``, the result of ``z1 + z2`` is ``-0 + 0j``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -3484,35 +3488,35 @@ class asin[TArray: Array](Protocol): Each element-wise result is expressed in radians. .. note:: - The principal value of the arc sine of a complex number :math:`z` is + The principal value of the arc sine of a complex number :math:`z` is - .. math:: - \\operatorname{asin}(z) = -j\\ \\ln(zj + \\sqrt{1-z^2}) + .. math:: + \\operatorname{asin}(z) = -j\\ \\ln(zj + \\sqrt{1-z^2}) - For any :math:`z`, + For any :math:`z`, - .. math:: - \\operatorname{asin}(z) = \\operatorname{acos}(-z) - \\frac{\\pi}{2} + .. math:: + \\operatorname{asin}(z) = \\operatorname{acos}(-z) - \\frac{\\pi}{2} .. note:: - For complex floating-point operands, ``asin(conj(x))`` must equal ``conj(asin(x))``. + For complex floating-point operands, ``asin(conj(x))`` must equal ``conj(asin(x))``. .. note:: - The inverse sine (or arc sine) is a multi-valued function and requires a branch cut on the complex plane. By convention, a branch cut is placed at the line segments :math:`(-\\infty, -1)` and :math:`(1, \\infty)` of the real axis. + The inverse sine (or arc sine) is a multi-valued function and requires a branch cut on the complex plane. By convention, a branch cut is placed at the line segments :math:`(-\\infty, -1)` and :math:`(1, \\infty)` of the real axis. - Accordingly, for complex arguments, the function returns the inverse sine in the range of a strip unbounded along the imaginary axis and in the interval :math:`[-\\pi/2, +\\pi/2]` along the real axis. + Accordingly, for complex arguments, the function returns the inverse sine in the range of a strip unbounded along the imaginary axis and in the interval :math:`[-\\pi/2, +\\pi/2]` along the real axis. - *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). + *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). Parameters ---------- x: array - input array. Should have a floating-point data type. + input array. Should have a floating-point data type. Returns ------- out: array - an array containing the inverse sine of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the inverse sine of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -3529,7 +3533,7 @@ class asin[TArray: Array](Protocol): For complex floating-point operands, special cases must be handled as if the operation is implemented as ``-1j * asinh(x*1j)``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -3543,35 +3547,35 @@ class asinh[TArray: Array](Protocol): Calculates an implementation-dependent approximation to the inverse hyperbolic sine for each element ``x_i`` in the input array ``x``. .. note:: - The principal value of the inverse hyperbolic sine of a complex number :math:`z` is + The principal value of the inverse hyperbolic sine of a complex number :math:`z` is - .. math:: - \\operatorname{asinh}(z) = \\ln(z + \\sqrt{1+z^2}) + .. math:: + \\operatorname{asinh}(z) = \\ln(z + \\sqrt{1+z^2}) - For any :math:`z`, + For any :math:`z`, - .. math:: - \\operatorname{asinh}(z) = \\frac{\\operatorname{asin}(zj)}{j} + .. math:: + \\operatorname{asinh}(z) = \\frac{\\operatorname{asin}(zj)}{j} .. note:: - For complex floating-point operands, ``asinh(conj(x))`` must equal ``conj(asinh(x))`` and ``asinh(-z)`` must equal ``-asinh(z)``. + For complex floating-point operands, ``asinh(conj(x))`` must equal ``conj(asinh(x))`` and ``asinh(-z)`` must equal ``-asinh(z)``. .. note:: - The inverse hyperbolic sine is a multi-valued function and requires a branch cut on the complex plane. By convention, a branch cut is placed at the line segments :math:`(-\\infty j, -j)` and :math:`(j, \\infty j)` of the imaginary axis. + The inverse hyperbolic sine is a multi-valued function and requires a branch cut on the complex plane. By convention, a branch cut is placed at the line segments :math:`(-\\infty j, -j)` and :math:`(j, \\infty j)` of the imaginary axis. - Accordingly, for complex arguments, the function returns the inverse hyperbolic sine in the range of a strip unbounded along the real axis and in the interval :math:`[-\\pi j/2, +\\pi j/2]` along the imaginary axis. + Accordingly, for complex arguments, the function returns the inverse hyperbolic sine in the range of a strip unbounded along the real axis and in the interval :math:`[-\\pi j/2, +\\pi j/2]` along the imaginary axis. - *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). + *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). Parameters ---------- x: array - input array whose elements each represent the area of a hyperbolic sector. Should have a floating-point data type. + input array whose elements each represent the area of a hyperbolic sector. Should have a floating-point data type. Returns ------- out: array - an array containing the inverse hyperbolic sine of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the inverse hyperbolic sine of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -3598,7 +3602,7 @@ class asinh[TArray: Array](Protocol): - If ``a`` is ``NaN`` and ``b`` is ``NaN``, the result is ``NaN + NaN j``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -3614,30 +3618,30 @@ class atan[TArray: Array](Protocol): Each element-wise result is expressed in radians. .. note:: - The principal value of the inverse tangent of a complex number :math:`z` is + The principal value of the inverse tangent of a complex number :math:`z` is - .. math:: - \\operatorname{atan}(z) = -\\frac{\\ln(1 - zj) - \\ln(1 + zj)}{2}j + .. math:: + \\operatorname{atan}(z) = -\\frac{\\ln(1 - zj) - \\ln(1 + zj)}{2}j .. note:: - For complex floating-point operands, ``atan(conj(x))`` must equal ``conj(atan(x))``. + For complex floating-point operands, ``atan(conj(x))`` must equal ``conj(atan(x))``. .. note:: - The inverse tangent (or arc tangent) is a multi-valued function and requires a branch on the complex plane. By convention, a branch cut is placed at the line segments :math:`(-\\infty j, -j)` and :math:`(+j, \\infty j)` of the imaginary axis. + The inverse tangent (or arc tangent) is a multi-valued function and requires a branch on the complex plane. By convention, a branch cut is placed at the line segments :math:`(-\\infty j, -j)` and :math:`(+j, \\infty j)` of the imaginary axis. - Accordingly, for complex arguments, the function returns the inverse tangent in the range of a strip unbounded along the imaginary axis and in the interval :math:`[-\\pi/2, +\\pi/2]` along the real axis. + Accordingly, for complex arguments, the function returns the inverse tangent in the range of a strip unbounded along the imaginary axis and in the interval :math:`[-\\pi/2, +\\pi/2]` along the real axis. - *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). + *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). Parameters ---------- x: array - input array. Should have a floating-point data type. + input array. Should have a floating-point data type. Returns ------- out: array - an array containing the inverse tangent of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the inverse tangent of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -3654,7 +3658,7 @@ class atan[TArray: Array](Protocol): For complex floating-point operands, special cases must be handled as if the operation is implemented as ``-1j * atanh(x*1j)``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -3670,21 +3674,21 @@ class atan2[TArray: Array](Protocol): The mathematical signs of ``x1_i`` and ``x2_i`` determine the quadrant of each element-wise result. The quadrant (i.e., branch) is chosen such that each element-wise result is the signed angle in radians between the ray ending at the origin and passing through the point ``(1,0)`` and the ray ending at the origin and passing through the point ``(x2_i, x1_i)``. .. note:: - Note the role reversal: the "y-coordinate" is the first function parameter; the "x-coordinate" is the second function parameter. The parameter order is intentional and traditional for the two-argument inverse tangent function where the y-coordinate argument is first and the x-coordinate argument is second. + Note the role reversal: the "y-coordinate" is the first function parameter; the "x-coordinate" is the second function parameter. The parameter order is intentional and traditional for the two-argument inverse tangent function where the y-coordinate argument is first and the x-coordinate argument is second. By IEEE 754 convention, the inverse tangent of the quotient ``x1/x2`` is defined for ``x2_i`` equal to positive or negative zero and for either or both of ``x1_i`` and ``x2_i`` equal to positive or negative ``infinity``. Parameters ---------- x1: array - input array corresponding to the y-coordinates. Should have a real-valued floating-point data type. + input array corresponding to the y-coordinates. Should have a real-valued floating-point data type. x2: array - input array corresponding to the x-coordinates. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued floating-point data type. + input array corresponding to the x-coordinates. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued floating-point data type. Returns ------- out: array - an array containing the inverse tangent of the quotient ``x1/x2``. The returned array must have a real-valued floating-point data type determined by :ref:`type-promotion`. + an array containing the inverse tangent of the quotient ``x1/x2``. The returned array must have a real-valued floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -3728,35 +3732,35 @@ class atanh[TArray: Array](Protocol): Calculates an implementation-dependent approximation to the inverse hyperbolic tangent for each element ``x_i`` of the input array ``x``. .. note:: - The principal value of the inverse hyperbolic tangent of a complex number :math:`z` is + The principal value of the inverse hyperbolic tangent of a complex number :math:`z` is - .. math:: - \\operatorname{atanh}(z) = \\frac{\\ln(1+z)-\\ln(z-1)}{2} + .. math:: + \\operatorname{atanh}(z) = \\frac{\\ln(1+z)-\\ln(z-1)}{2} - For any :math:`z`, + For any :math:`z`, - .. math:: - \\operatorname{atanh}(z) = \\frac{\\operatorname{atan}(zj)}{j} + .. math:: + \\operatorname{atanh}(z) = \\frac{\\operatorname{atan}(zj)}{j} .. note:: - For complex floating-point operands, ``atanh(conj(x))`` must equal ``conj(atanh(x))`` and ``atanh(-x)`` must equal ``-atanh(x)``. + For complex floating-point operands, ``atanh(conj(x))`` must equal ``conj(atanh(x))`` and ``atanh(-x)`` must equal ``-atanh(x)``. .. note:: - The inverse hyperbolic tangent is a multi-valued function and requires a branch cut on the complex plane. By convention, a branch cut is placed at the line segments :math:`(-\\infty, 1]` and :math:`[1, \\infty)` of the real axis. + The inverse hyperbolic tangent is a multi-valued function and requires a branch cut on the complex plane. By convention, a branch cut is placed at the line segments :math:`(-\\infty, 1]` and :math:`[1, \\infty)` of the real axis. - Accordingly, for complex arguments, the function returns the inverse hyperbolic tangent in the range of a half-strip unbounded along the real axis and in the interval :math:`[-\\pi j/2, +\\pi j/2]` along the imaginary axis. + Accordingly, for complex arguments, the function returns the inverse hyperbolic tangent in the range of a half-strip unbounded along the real axis and in the interval :math:`[-\\pi j/2, +\\pi j/2]` along the imaginary axis. - *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). + *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). Parameters ---------- x: array - input array whose elements each represent the area of a hyperbolic sector. Should have a floating-point data type. + input array whose elements each represent the area of a hyperbolic sector. Should have a floating-point data type. Returns ------- out: array - an array containing the inverse hyperbolic tangent of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the inverse hyperbolic tangent of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -3787,7 +3791,7 @@ class atanh[TArray: Array](Protocol): - If ``a`` is ``NaN`` and ``b`` is ``NaN``, the result is ``NaN + NaN j``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -3803,14 +3807,14 @@ class bitwise_and[TArray: Array](Protocol): Parameters ---------- x1: array - first input array. Should have an integer or boolean data type. + first input array. Should have an integer or boolean data type. x2: array - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have an integer or boolean data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have an integer or boolean data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. """ @@ -3826,14 +3830,14 @@ class bitwise_left_shift[TArray: Array](Protocol): Parameters ---------- x1: array - first input array. Should have an integer data type. + first input array. Should have an integer data type. x2: array - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have an integer data type. Each element must be greater than or equal to ``0``. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have an integer data type. Each element must be greater than or equal to ``0``. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. """ @@ -3849,12 +3853,12 @@ class bitwise_invert[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have an integer or boolean data type. + input array. Should have an integer or boolean data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have the same data type as ``x``. + an array containing the element-wise results. The returned array must have the same data type as ``x``. """ @@ -3870,14 +3874,14 @@ class bitwise_or[TArray: Array](Protocol): Parameters ---------- x1: array - first input array. Should have an integer or boolean data type. + first input array. Should have an integer or boolean data type. x2: array - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have an integer or boolean data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have an integer or boolean data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. """ @@ -3891,19 +3895,19 @@ class bitwise_right_shift[TArray: Array](Protocol): Shifts the bits of each element ``x1_i`` of the input array ``x1`` to the right according to the respective element ``x2_i`` of the input array ``x2``. .. note:: - This operation must be an arithmetic shift (i.e., sign-propagating) and thus equivalent to floor division by a power of two. + This operation must be an arithmetic shift (i.e., sign-propagating) and thus equivalent to floor division by a power of two. Parameters ---------- x1: array - first input array. Should have an integer data type. + first input array. Should have an integer data type. x2: array - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have an integer data type. Each element must be greater than or equal to ``0``. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have an integer data type. Each element must be greater than or equal to ``0``. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. """ @@ -3919,14 +3923,14 @@ class bitwise_xor[TArray: Array](Protocol): Parameters ---------- x1: array - first input array. Should have an integer or boolean data type. + first input array. Should have an integer or boolean data type. x2: array - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have an integer or boolean data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have an integer or boolean data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. """ @@ -3942,12 +3946,12 @@ class ceil[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a real-valued data type. + input array. Should have a real-valued data type. Returns ------- out: array - an array containing the rounded result for each element in ``x``. The returned array must have the same data type as ``x``. + an array containing the rounded result for each element in ``x``. The returned array must have the same data type as ``x``. Notes ----- @@ -3977,24 +3981,24 @@ class conj[TArray: Array](Protocol): For complex numbers of the form .. math:: - a + bj + a + bj the complex conjugate is defined as .. math:: - a - bj + a - bj Hence, the returned complex conjugates must be computed by negating the imaginary component of each element ``x_i``. Parameters ---------- x: array - input array. Should have a complex floating-point data type. + input array. Should have a complex floating-point data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have the same data type as ``x``. + an array containing the element-wise results. The returned array must have the same data type as ``x``. .. versionadded:: 2022.12 @@ -4012,25 +4016,25 @@ class cos[TArray: Array](Protocol): Each element ``x_i`` is assumed to be expressed in radians. .. note:: - The cosine is an entire function on the complex plane and has no branch cuts. + The cosine is an entire function on the complex plane and has no branch cuts. .. note:: - For complex arguments, the mathematical definition of cosine is + For complex arguments, the mathematical definition of cosine is - .. math:: - \\begin{align} \\operatorname{cos}(x) &= \\sum_{n=0}^\\infty \\frac{(-1)^n}{(2n)!} x^{2n} \\\\ &= \\frac{e^{jx} + e^{-jx}}{2} \\\\ &= \\operatorname{cosh}(jx) \\end{align} + .. math:: + \\begin{align} \\operatorname{cos}(x) &= \\sum_{n=0}^\\infty \\frac{(-1)^n}{(2n)!} x^{2n} \\\\ &= \\frac{e^{jx} + e^{-jx}}{2} \\\\ &= \\operatorname{cosh}(jx) \\end{align} - where :math:`\\operatorname{cosh}` is the hyperbolic cosine. + where :math:`\\operatorname{cosh}` is the hyperbolic cosine. Parameters ---------- x: array - input array whose elements are each expressed in radians. Should have a floating-point data type. + input array whose elements are each expressed in radians. Should have a floating-point data type. Returns ------- out: array - an array containing the cosine of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the cosine of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -4047,7 +4051,7 @@ class cos[TArray: Array](Protocol): For complex floating-point operands, special cases must be handled as if the operation is implemented as ``cosh(x*1j)``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -4063,27 +4067,27 @@ class cosh[TArray: Array](Protocol): The mathematical definition of the hyperbolic cosine is .. math:: - \\operatorname{cosh}(x) = \\frac{e^x + e^{-x}}{2} + \\operatorname{cosh}(x) = \\frac{e^x + e^{-x}}{2} .. note:: - The hyperbolic cosine is an entire function in the complex plane and has no branch cuts. The function is periodic, with period :math:`2\\pi j`, with respect to the imaginary component. + The hyperbolic cosine is an entire function in the complex plane and has no branch cuts. The function is periodic, with period :math:`2\\pi j`, with respect to the imaginary component. Parameters ---------- x: array - input array whose elements each represent a hyperbolic angle. Should have a floating-point data type. + input array whose elements each represent a hyperbolic angle. Should have a floating-point data type. Returns ------- out: array - an array containing the hyperbolic cosine of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the hyperbolic cosine of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- **Special cases** .. note:: - For all operands, ``cosh(x)`` must equal ``cosh(-x)``. + For all operands, ``cosh(x)`` must equal ``cosh(-x)``. For real-valued floating-point operands, @@ -4096,7 +4100,7 @@ class cosh[TArray: Array](Protocol): For complex floating-point operands, let ``a = real(x_i)``, ``b = imag(x_i)``, and .. note:: - For complex floating-point operands, ``cosh(conj(x))`` must equal ``conj(cosh(x))``. + For complex floating-point operands, ``cosh(conj(x))`` must equal ``conj(cosh(x))``. - If ``a`` is ``+0`` and ``b`` is ``+0``, the result is ``1 + 0j``. - If ``a`` is ``+0`` and ``b`` is ``+infinity``, the result is ``NaN + 0j`` (sign of the imaginary component is unspecified). @@ -4114,7 +4118,7 @@ class cosh[TArray: Array](Protocol): where ``cis(v)`` is ``cos(v) + sin(v)*1j``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -4128,21 +4132,21 @@ class divide[TArray: Array](Protocol): Calculates the division of each element ``x1_i`` of the input array ``x1`` with the respective element ``x2_i`` of the input array ``x2``. .. note:: - If one or both of the input arrays have integer data types, the result is implementation-dependent, as type promotion between data type "kinds" (e.g., integer versus floating-point) is unspecified. + If one or both of the input arrays have integer data types, the result is implementation-dependent, as type promotion between data type "kinds" (e.g., integer versus floating-point) is unspecified. - Specification-compliant libraries may choose to raise an error or return an array containing the element-wise results. If an array is returned, the array must have a real-valued floating-point data type. + Specification-compliant libraries may choose to raise an error or return an array containing the element-wise results. If an array is returned, the array must have a real-valued floating-point data type. Parameters ---------- x1: array - dividend input array. Should have a numeric data type. + dividend input array. Should have a numeric data type. x2: array - divisor input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a numeric data type. + divisor input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a numeric data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the element-wise results. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -4190,7 +4194,7 @@ class divide[TArray: Array](Protocol): When ``a``, ``b``, ``c``, or ``d`` are all finite numbers (i.e., a value other than ``NaN``, ``+infinity``, or ``-infinity``), division of complex floating-point operands should be computed as if calculated according to the textbook formula for complex number division .. math:: - \\frac{a + bj}{c + dj} = \\frac{(ac + bd) + (bc - ad)j}{c^2 + d^2} + \\frac{a + bj}{c + dj} = \\frac{(ac + bd) + (bc - ad)j}{c^2 + d^2} When at least one of ``a``, ``b``, ``c``, or ``d`` is ``NaN``, ``+infinity``, or ``-infinity``, @@ -4198,10 +4202,10 @@ class divide[TArray: Array](Protocol): - In the remaining cases, the result is implementation dependent. .. note:: - For complex floating-point operands, the results of special cases may be implementation dependent depending on how an implementation chooses to model complex numbers and complex infinity (e.g., complex plane versus Riemann sphere). For those implementations following C99 and its one-infinity model, when at least one component is infinite, even if the other component is ``NaN``, the complex value is infinite, and the usual arithmetic rules do not apply to complex-complex division. In the interest of performance, other implementations may want to avoid the complex branching logic necessary to implement the one-infinity model and choose to implement all complex-complex division according to the textbook formula. Accordingly, special case behavior is unlikely to be consistent across implementations. + For complex floating-point operands, the results of special cases may be implementation dependent depending on how an implementation chooses to model complex numbers and complex infinity (e.g., complex plane versus Riemann sphere). For those implementations following C99 and its one-infinity model, when at least one component is infinite, even if the other component is ``NaN``, the complex value is infinite, and the usual arithmetic rules do not apply to complex-complex division. In the interest of performance, other implementations may want to avoid the complex branching logic necessary to implement the one-infinity model and choose to implement all complex-complex division according to the textbook formula. Accordingly, special case behavior is unlikely to be consistent across implementations. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -4217,14 +4221,14 @@ class equal[TArray: Array](Protocol): Parameters ---------- x1: array - first input array. May have any data type. + first input array. May have any data type. x2: array - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). May have any data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). May have any data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type of ``bool``. + an array containing the element-wise results. The returned array must have a data type of ``bool``. Notes ----- @@ -4246,10 +4250,10 @@ class equal[TArray: Array](Protocol): - In the remaining cases, the result is the logical AND of the equality comparison between the real values ``a`` and ``c`` (real components) and between the real values ``b`` and ``d`` (imaginary components), as described above for real-valued floating-point operands (i.e., ``a == c AND b == d``). .. note:: - For discussion of complex number equality, see :ref:`complex-numbers`. + For discussion of complex number equality, see :ref:`complex-numbers`. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -4263,20 +4267,20 @@ class exp[TArray: Array](Protocol): Calculates an implementation-dependent approximation to the exponential function for each element ``x_i`` of the input array ``x`` (``e`` raised to the power of ``x_i``, where ``e`` is the base of the natural logarithm). .. note:: - For complex floating-point operands, ``exp(conj(x))`` must equal ``conj(exp(x))``. + For complex floating-point operands, ``exp(conj(x))`` must equal ``conj(exp(x))``. .. note:: - The exponential function is an entire function in the complex plane and has no branch cuts. + The exponential function is an entire function in the complex plane and has no branch cuts. Parameters ---------- x: array - input array. Should have a floating-point data type. + input array. Should have a floating-point data type. Returns ------- out: array - an array containing the evaluated exponential function result for each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the evaluated exponential function result for each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -4309,7 +4313,7 @@ class exp[TArray: Array](Protocol): where ``cis(v)`` is ``cos(v) + sin(v)*1j``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -4323,23 +4327,23 @@ class expm1[TArray: Array](Protocol): Calculates an implementation-dependent approximation to ``exp(x)-1`` for each element ``x_i`` of the input array ``x``. .. note:: - The purpose of this function is to calculate ``exp(x)-1.0`` more accurately when `x` is close to zero. Accordingly, conforming implementations should avoid implementing this function as simply ``exp(x)-1.0``. See FDLIBM, or some other IEEE 754-2019 compliant mathematical library, for a potential reference implementation. + The purpose of this function is to calculate ``exp(x)-1.0`` more accurately when `x` is close to zero. Accordingly, conforming implementations should avoid implementing this function as simply ``exp(x)-1.0``. See FDLIBM, or some other IEEE 754-2019 compliant mathematical library, for a potential reference implementation. .. note:: - For complex floating-point operands, ``expm1(conj(x))`` must equal ``conj(expm1(x))``. + For complex floating-point operands, ``expm1(conj(x))`` must equal ``conj(expm1(x))``. .. note:: - The exponential function is an entire function in the complex plane and has no branch cuts. + The exponential function is an entire function in the complex plane and has no branch cuts. Parameters ---------- x: array - input array. Should have a floating-point data type. + input array. Should have a floating-point data type. Returns ------- out: array - an array containing the evaluated result for each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the evaluated result for each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -4372,7 +4376,7 @@ class expm1[TArray: Array](Protocol): where ``cis(v)`` is ``cos(v) + sin(v)*1j``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -4388,12 +4392,12 @@ class floor[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a real-valued data type. + input array. Should have a real-valued data type. Returns ------- out: array - an array containing the rounded result for each element in ``x``. The returned array must have the same data type as ``x``. + an array containing the rounded result for each element in ``x``. The returned array must have the same data type as ``x``. Notes ----- @@ -4421,32 +4425,32 @@ class floor_divide[TArray: Array](Protocol): Rounds the result of dividing each element ``x1_i`` of the input array ``x1`` by the respective element ``x2_i`` of the input array ``x2`` to the greatest (i.e., closest to `+infinity`) integer-value number that is not greater than the division result. .. note:: - For input arrays which promote to an integer data type, the result of division by zero is unspecified and thus implementation-defined. + For input arrays which promote to an integer data type, the result of division by zero is unspecified and thus implementation-defined. Parameters ---------- x1: array - dividend input array. Should have a real-valued data type. + dividend input array. Should have a real-valued data type. x2: array - divisor input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued data type. + divisor input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- **Special cases** .. note:: - Floor division was introduced in Python via `PEP 238 `_ with the goal to disambiguate "true division" (i.e., computing an approximation to the mathematical operation of division) from "floor division" (i.e., rounding the result of division toward negative infinity). The former was computed when one of the operands was a ``float``, while the latter was computed when both operands were ``int``\\s. Overloading the ``/`` operator to support both behaviors led to subtle numerical bugs when integers are possible, but not expected. + Floor division was introduced in Python via `PEP 238 `_ with the goal to disambiguate "true division" (i.e., computing an approximation to the mathematical operation of division) from "floor division" (i.e., rounding the result of division toward negative infinity). The former was computed when one of the operands was a ``float``, while the latter was computed when both operands were ``int``\\s. Overloading the ``/`` operator to support both behaviors led to subtle numerical bugs when integers are possible, but not expected. - To resolve this ambiguity, ``/`` was designated for true division, and ``//`` was designated for floor division. Semantically, floor division was `defined `_ as equivalent to ``a // b == floor(a/b)``; however, special floating-point cases were left ill-defined. + To resolve this ambiguity, ``/`` was designated for true division, and ``//`` was designated for floor division. Semantically, floor division was `defined `_ as equivalent to ``a // b == floor(a/b)``; however, special floating-point cases were left ill-defined. - Accordingly, floor division is not implemented consistently across array libraries for some of the special cases documented below. Namely, when one of the operands is ``infinity``, libraries may diverge with some choosing to strictly follow ``floor(a/b)`` and others choosing to pair ``//`` with ``%`` according to the relation ``b = a % b + b * (a // b)``. The special cases leading to divergent behavior are documented below. + Accordingly, floor division is not implemented consistently across array libraries for some of the special cases documented below. Namely, when one of the operands is ``infinity``, libraries may diverge with some choosing to strictly follow ``floor(a/b)`` and others choosing to pair ``//`` with ``%`` according to the relation ``b = a % b + b * (a // b)``. The special cases leading to divergent behavior are documented below. - This specification prefers floor division to match ``floor(divide(x1, x2))`` in order to avoid surprising and unexpected results; however, array libraries may choose to more strictly follow Python behavior. + This specification prefers floor division to match ``floor(divide(x1, x2))`` in order to avoid surprising and unexpected results; however, array libraries may choose to more strictly follow Python behavior. For floating-point operands, @@ -4485,19 +4489,19 @@ class greater[TArray: Array](Protocol): Computes the truth value of ``x1_i > x2_i`` for each element ``x1_i`` of the input array ``x1`` with the respective element ``x2_i`` of the input array ``x2``. .. note:: - For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). + For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). Parameters ---------- x1: array - first input array. Should have a real-valued data type. + first input array. Should have a real-valued data type. x2: array - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type of ``bool``. + an array containing the element-wise results. The returned array must have a data type of ``bool``. """ @@ -4511,19 +4515,19 @@ class greater_equal[TArray: Array](Protocol): Computes the truth value of ``x1_i >= x2_i`` for each element ``x1_i`` of the input array ``x1`` with the respective element ``x2_i`` of the input array ``x2``. .. note:: - For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). + For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). Parameters ---------- x1: array - first input array. Should have a real-valued data type. + first input array. Should have a real-valued data type. x2: array - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type of ``bool``. + an array containing the element-wise results. The returned array must have a data type of ``bool``. """ @@ -4539,12 +4543,12 @@ class imag[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a complex floating-point data type. + input array. Should have a complex floating-point data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a floating-point data type with the same floating-point precision as ``x`` (e.g., if ``x`` is ``complex64``, the returned array must have the floating-point data type ``float32``). + an array containing the element-wise results. The returned array must have a floating-point data type with the same floating-point precision as ``x`` (e.g., if ``x`` is ``complex64``, the returned array must have the floating-point data type ``float32``). .. versionadded:: 2022.12 @@ -4562,12 +4566,12 @@ class isfinite[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a numeric data type. + input array. Should have a numeric data type. Returns ------- out: array - an array containing test results. The returned array must have a data type of ``bool``. + an array containing test results. The returned array must have a data type of ``bool``. Notes ----- @@ -4587,7 +4591,7 @@ class isfinite[TArray: Array](Protocol): - If ``a`` is a finite number and ``b`` is a finite number, the result is ``True``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -4603,12 +4607,12 @@ class isinf[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a numeric data type. + input array. Should have a numeric data type. Returns ------- out: array - an array containing test results. The returned array must have a data type of ``bool``. + an array containing test results. The returned array must have a data type of ``bool``. Notes ----- @@ -4626,7 +4630,7 @@ class isinf[TArray: Array](Protocol): - In the remaining cases, the result is ``False``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -4642,12 +4646,12 @@ class isnan[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a numeric data type. + input array. Should have a numeric data type. Returns ------- out: array - an array containing test results. The returned array should have a data type of ``bool``. + an array containing test results. The returned array should have a data type of ``bool``. Notes ----- @@ -4664,7 +4668,7 @@ class isnan[TArray: Array](Protocol): - In the remaining cases, the result is ``False``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -4678,19 +4682,19 @@ class less[TArray: Array](Protocol): Computes the truth value of ``x1_i < x2_i`` for each element ``x1_i`` of the input array ``x1`` with the respective element ``x2_i`` of the input array ``x2``. .. note:: - For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). + For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). Parameters ---------- x1: array - first input array. Should have a real-valued data type. + first input array. Should have a real-valued data type. x2: array - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type of ``bool``. + an array containing the element-wise results. The returned array must have a data type of ``bool``. """ @@ -4704,19 +4708,19 @@ class less_equal[TArray: Array](Protocol): Computes the truth value of ``x1_i <= x2_i`` for each element ``x1_i`` of the input array ``x1`` with the respective element ``x2_i`` of the input array ``x2``. .. note:: - For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). + For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). Parameters ---------- x1: array - first input array. Should have a real-valued data type. + first input array. Should have a real-valued data type. x2: array - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type of ``bool``. + an array containing the element-wise results. The returned array must have a data type of ``bool``. """ @@ -4730,29 +4734,29 @@ class log[TArray: Array](Protocol): Calculates an implementation-dependent approximation to the natural (base ``e``) logarithm for each element ``x_i`` of the input array ``x``. .. note:: - The natural logarithm of a complex number :math:`z` with polar coordinates :math:`(r,\\theta)` equals :math:`\\ln r + (\\theta + 2n\\pi)j` with principal value :math:`\\ln r + \\theta j`. + The natural logarithm of a complex number :math:`z` with polar coordinates :math:`(r,\\theta)` equals :math:`\\ln r + (\\theta + 2n\\pi)j` with principal value :math:`\\ln r + \\theta j`. .. note:: - For complex floating-point operands, ``log(conj(x))`` must equal ``conj(log(x))``. + For complex floating-point operands, ``log(conj(x))`` must equal ``conj(log(x))``. .. note:: - By convention, the branch cut of the natural logarithm is the negative real axis :math:`(-\\infty, 0)`. + By convention, the branch cut of the natural logarithm is the negative real axis :math:`(-\\infty, 0)`. - The natural logarithm is a continuous function from above the branch cut, taking into account the sign of the imaginary component. + The natural logarithm is a continuous function from above the branch cut, taking into account the sign of the imaginary component. - Accordingly, for complex arguments, the function returns the natural logarithm in the range of a strip in the interval :math:`[-\\pi j, +\\pi j]` along the imaginary axis and mathematically unbounded along the real axis. + Accordingly, for complex arguments, the function returns the natural logarithm in the range of a strip in the interval :math:`[-\\pi j, +\\pi j]` along the imaginary axis and mathematically unbounded along the real axis. - *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). + *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). Parameters ---------- x: array - input array. Should have a floating-point data type. + input array. Should have a floating-point data type. Returns ------- out: array - an array containing the evaluated natural logarithm for each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the evaluated natural logarithm for each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -4782,7 +4786,7 @@ class log[TArray: Array](Protocol): - If ``a`` is ``NaN`` and ``b`` is ``NaN``, the result is ``NaN + NaN j``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -4796,29 +4800,29 @@ class log1p[TArray: Array](Protocol): Calculates an implementation-dependent approximation to ``log(1+x)``, where ``log`` refers to the natural (base ``e``) logarithm, for each element ``x_i`` of the input array ``x``. .. note:: - The purpose of this function is to calculate ``log(1+x)`` more accurately when `x` is close to zero. Accordingly, conforming implementations should avoid implementing this function as simply ``log(1+x)``. See FDLIBM, or some other IEEE 754-2019 compliant mathematical library, for a potential reference implementation. + The purpose of this function is to calculate ``log(1+x)`` more accurately when `x` is close to zero. Accordingly, conforming implementations should avoid implementing this function as simply ``log(1+x)``. See FDLIBM, or some other IEEE 754-2019 compliant mathematical library, for a potential reference implementation. .. note:: - For complex floating-point operands, ``log1p(conj(x))`` must equal ``conj(log1p(x))``. + For complex floating-point operands, ``log1p(conj(x))`` must equal ``conj(log1p(x))``. .. note:: - By convention, the branch cut of the natural logarithm is the negative real axis :math:`(-\\infty, 0)`. + By convention, the branch cut of the natural logarithm is the negative real axis :math:`(-\\infty, 0)`. - The natural logarithm is a continuous function from above the branch cut, taking into account the sign of the imaginary component. + The natural logarithm is a continuous function from above the branch cut, taking into account the sign of the imaginary component. - Accordingly, for complex arguments, the function returns the natural logarithm in the range of a strip in the interval :math:`[-\\pi j, +\\pi j]` along the imaginary axis and mathematically unbounded along the real axis. + Accordingly, for complex arguments, the function returns the natural logarithm in the range of a strip in the interval :math:`[-\\pi j, +\\pi j]` along the imaginary axis and mathematically unbounded along the real axis. - *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). + *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). Parameters ---------- x: array - input array. Should have a floating-point data type. + input array. Should have a floating-point data type. Returns ------- out: array - an array containing the evaluated result for each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the evaluated result for each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -4848,7 +4852,7 @@ class log1p[TArray: Array](Protocol): - If ``a`` is ``NaN`` and ``b`` is ``NaN``, the result is ``NaN + NaN j``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -4862,17 +4866,17 @@ class log2[TArray: Array](Protocol): Calculates an implementation-dependent approximation to the base ``2`` logarithm for each element ``x_i`` of the input array ``x``. .. note:: - For complex floating-point operands, ``log2(conj(x))`` must equal ``conj(log2(x))``. + For complex floating-point operands, ``log2(conj(x))`` must equal ``conj(log2(x))``. Parameters ---------- x: array - input array. Should have a floating-point data type. + input array. Should have a floating-point data type. Returns ------- out: array - an array containing the evaluated base ``2`` logarithm for each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the evaluated base ``2`` logarithm for each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -4889,12 +4893,12 @@ class log2[TArray: Array](Protocol): For complex floating-point operands, special cases must be handled as if the operation is implemented using the standard change of base formula .. math:: - \\log_{2} x = \\frac{\\log_{e} x}{\\log_{e} 2} + \\log_{2} x = \\frac{\\log_{e} x}{\\log_{e} 2} where :math:`\\log_{e}` is the natural logarithm, as implemented by :func:`~array_api.log`. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -4908,17 +4912,17 @@ class log10[TArray: Array](Protocol): Calculates an implementation-dependent approximation to the base ``10`` logarithm for each element ``x_i`` of the input array ``x``. .. note:: - For complex floating-point operands, ``log10(conj(x))`` must equal ``conj(log10(x))``. + For complex floating-point operands, ``log10(conj(x))`` must equal ``conj(log10(x))``. Parameters ---------- x: array - input array. Should have a floating-point data type. + input array. Should have a floating-point data type. Returns ------- out: array - an array containing the evaluated base ``10`` logarithm for each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the evaluated base ``10`` logarithm for each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -4935,12 +4939,12 @@ class log10[TArray: Array](Protocol): For complex floating-point operands, special cases must be handled as if the operation is implemented using the standard change of base formula .. math:: - \\log_{10} x = \\frac{\\log_{e} x}{\\log_{e} 10} + \\log_{10} x = \\frac{\\log_{e} x}{\\log_{e} 10} where :math:`\\log_{e}` is the natural logarithm, as implemented by :func:`~array_api.log`. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -4956,14 +4960,14 @@ class logaddexp[TArray: Array](Protocol): Parameters ---------- x1: array - first input array. Should have a real-valued floating-point data type. + first input array. Should have a real-valued floating-point data type. x2: array - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued floating-point data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued floating-point data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a real-valued floating-point data type determined by :ref:`type-promotion`. + an array containing the element-wise results. The returned array must have a real-valued floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -4987,19 +4991,19 @@ class logical_and[TArray: Array](Protocol): Computes the logical AND for each element ``x1_i`` of the input array ``x1`` with the respective element ``x2_i`` of the input array ``x2``. .. note:: - While this specification recommends that this function only accept input arrays having a boolean data type, specification-compliant array libraries may choose to accept input arrays having real-valued data types. If non-boolean data types are supported, zeros must be considered the equivalent of ``False``, while non-zeros must be considered the equivalent of ``True``. + While this specification recommends that this function only accept input arrays having a boolean data type, specification-compliant array libraries may choose to accept input arrays having real-valued data types. If non-boolean data types are supported, zeros must be considered the equivalent of ``False``, while non-zeros must be considered the equivalent of ``True``. Parameters ---------- x1: array - first input array. Should have a boolean data type. + first input array. Should have a boolean data type. x2: array - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a boolean data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a boolean data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type of `bool`. + an array containing the element-wise results. The returned array must have a data type of `bool`. """ @@ -5013,17 +5017,17 @@ class logical_not[TArray: Array](Protocol): Computes the logical NOT for each element ``x_i`` of the input array ``x``. .. note:: - While this specification recommends that this function only accept input arrays having a boolean data type, specification-compliant array libraries may choose to accept input arrays having real-valued data types. If non-boolean data types are supported, zeros must be considered the equivalent of ``False``, while non-zeros must be considered the equivalent of ``True``. + While this specification recommends that this function only accept input arrays having a boolean data type, specification-compliant array libraries may choose to accept input arrays having real-valued data types. If non-boolean data types are supported, zeros must be considered the equivalent of ``False``, while non-zeros must be considered the equivalent of ``True``. Parameters ---------- x: array - input array. Should have a boolean data type. + input array. Should have a boolean data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type of ``bool``. + an array containing the element-wise results. The returned array must have a data type of ``bool``. """ @@ -5037,19 +5041,19 @@ class logical_or[TArray: Array](Protocol): Computes the logical OR for each element ``x1_i`` of the input array ``x1`` with the respective element ``x2_i`` of the input array ``x2``. .. note:: - While this specification recommends that this function only accept input arrays having a boolean data type, specification-compliant array libraries may choose to accept input arrays having real-valued data types. If non-boolean data types are supported, zeros must be considered the equivalent of ``False``, while non-zeros must be considered the equivalent of ``True``. + While this specification recommends that this function only accept input arrays having a boolean data type, specification-compliant array libraries may choose to accept input arrays having real-valued data types. If non-boolean data types are supported, zeros must be considered the equivalent of ``False``, while non-zeros must be considered the equivalent of ``True``. Parameters ---------- x1: array - first input array. Should have a boolean data type. + first input array. Should have a boolean data type. x2: array - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a boolean data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a boolean data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type of ``bool``. + an array containing the element-wise results. The returned array must have a data type of ``bool``. """ @@ -5063,19 +5067,19 @@ class logical_xor[TArray: Array](Protocol): Computes the logical XOR for each element ``x1_i`` of the input array ``x1`` with the respective element ``x2_i`` of the input array ``x2``. .. note:: - While this specification recommends that this function only accept input arrays having a boolean data type, specification-compliant array libraries may choose to accept input arrays having real-valued data types. If non-boolean data types are supported, zeros must be considered the equivalent of ``False``, while non-zeros must be considered the equivalent of ``True``. + While this specification recommends that this function only accept input arrays having a boolean data type, specification-compliant array libraries may choose to accept input arrays having real-valued data types. If non-boolean data types are supported, zeros must be considered the equivalent of ``False``, while non-zeros must be considered the equivalent of ``True``. Parameters ---------- x1: array - first input array. Should have a boolean data type. + first input array. Should have a boolean data type. x2: array - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a boolean data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a boolean data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type of ``bool``. + an array containing the element-wise results. The returned array must have a data type of ``bool``. """ @@ -5089,19 +5093,19 @@ class multiply[TArray: Array](Protocol): Calculates the product for each element ``x1_i`` of the input array ``x1`` with the respective element ``x2_i`` of the input array ``x2``. .. note:: - Floating-point multiplication is not always associative due to finite precision. + Floating-point multiplication is not always associative due to finite precision. Parameters ---------- x1: array - first input array. Should have a numeric data type. + first input array. Should have a numeric data type. x2: array - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a numeric data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a numeric data type. Returns ------- out: array - an array containing the element-wise products. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise products. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- @@ -5136,7 +5140,7 @@ class multiply[TArray: Array](Protocol): When ``a``, ``b``, ``c``, or ``d`` are all finite numbers (i.e., a value other than ``NaN``, ``+infinity``, or ``-infinity``), multiplication of complex floating-point operands should be computed as if calculated according to the textbook formula for complex number multiplication .. math:: - (a + bj) \\cdot (c + dj) = (ac - bd) + (bc + ad)j + (a + bj) \\cdot (c + dj) = (ac - bd) + (bc + ad)j When at least one of ``a``, ``b``, ``c``, or ``d`` is ``NaN``, ``+infinity``, or ``-infinity``, @@ -5144,10 +5148,10 @@ class multiply[TArray: Array](Protocol): - In the remaining cases, the result is implementation dependent. .. note:: - For complex floating-point operands, the results of special cases may be implementation dependent depending on how an implementation chooses to model complex numbers and complex infinity (e.g., complex plane versus Riemann sphere). For those implementations following C99 and its one-infinity model, when at least one component is infinite, even if the other component is ``NaN``, the complex value is infinite, and the usual arithmetic rules do not apply to complex-complex multiplication. In the interest of performance, other implementations may want to avoid the complex branching logic necessary to implement the one-infinity model and choose to implement all complex-complex multiplication according to the textbook formula. Accordingly, special case behavior is unlikely to be consistent across implementations. + For complex floating-point operands, the results of special cases may be implementation dependent depending on how an implementation chooses to model complex numbers and complex infinity (e.g., complex plane versus Riemann sphere). For those implementations following C99 and its one-infinity model, when at least one component is infinite, even if the other component is ``NaN``, the complex value is infinite, and the usual arithmetic rules do not apply to complex-complex multiplication. In the interest of performance, other implementations may want to avoid the complex branching logic necessary to implement the one-infinity model and choose to implement all complex-complex multiplication according to the textbook formula. Accordingly, special case behavior is unlikely to be consistent across implementations. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -5161,26 +5165,26 @@ class negative[TArray: Array](Protocol): Computes the numerical negative of each element ``x_i`` (i.e., ``y_i = -x_i``) of the input array ``x``. .. note:: - For signed integer data types, the numerical negative of the minimum representable integer is implementation-dependent. + For signed integer data types, the numerical negative of the minimum representable integer is implementation-dependent. .. note:: - If ``x`` has a complex floating-point data type, both the real and imaginary components for each ``x_i`` must be negated (a result which follows from the rules of complex number multiplication). + If ``x`` has a complex floating-point data type, both the real and imaginary components for each ``x_i`` must be negated (a result which follows from the rules of complex number multiplication). Parameters ---------- x: array - input array. Should have a numeric data type. + input array. Should have a numeric data type. Returns ------- out: array - an array containing the evaluated result for each element in ``x``. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the evaluated result for each element in ``x``. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -5196,14 +5200,14 @@ class not_equal[TArray: Array](Protocol): Parameters ---------- x1: array - first input array. May have any data type. + first input array. May have any data type. x2: array - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type of ``bool``. + an array containing the element-wise results. The returned array must have a data type of ``bool``. Notes ----- @@ -5223,10 +5227,10 @@ class not_equal[TArray: Array](Protocol): - In the remaining cases, the result is the logical OR of the equality comparison between the real values ``a`` and ``c`` (real components) and between the real values ``b`` and ``d`` (imaginary components), as described above for real-valued floating-point operands (i.e., ``a != c OR b != d``). .. note:: - For discussion of complex number equality, see :ref:`complex-numbers`. + For discussion of complex number equality, see :ref:`complex-numbers`. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -5242,18 +5246,18 @@ class positive[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a numeric data type. + input array. Should have a numeric data type. Returns ------- out: array - an array containing the evaluated result for each element in ``x``. The returned array must have the same data type as ``x``. + an array containing the evaluated result for each element in ``x``. The returned array must have the same data type as ``x``. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -5267,28 +5271,28 @@ class pow[TArray: Array](Protocol): Calculates an implementation-dependent approximation of exponentiation by raising each element ``x1_i`` (the base) of the input array ``x1`` to the power of ``x2_i`` (the exponent), where ``x2_i`` is the corresponding element of the input array ``x2``. .. note:: - If both ``x1`` and ``x2`` have integer data types, the result of ``pow`` when ``x2_i`` is negative (i.e., less than zero) is unspecified and thus implementation-dependent. + If both ``x1`` and ``x2`` have integer data types, the result of ``pow`` when ``x2_i`` is negative (i.e., less than zero) is unspecified and thus implementation-dependent. - If ``x1`` has an integer data type and ``x2`` has a floating-point data type, behavior is implementation-dependent (type promotion between data type "kinds" (integer versus floating-point) is unspecified). + If ``x1`` has an integer data type and ``x2`` has a floating-point data type, behavior is implementation-dependent (type promotion between data type "kinds" (integer versus floating-point) is unspecified). .. note:: - By convention, the branch cut of the natural logarithm is the negative real axis :math:`(-\\infty, 0)`. + By convention, the branch cut of the natural logarithm is the negative real axis :math:`(-\\infty, 0)`. - The natural logarithm is a continuous function from above the branch cut, taking into account the sign of the imaginary component. As special cases involving complex floating-point operands should be handled according to ``exp(x2*log(x1))``, exponentiation has the same branch cut for ``x1`` as the natural logarithm (see :func:`~array_api.log`). + The natural logarithm is a continuous function from above the branch cut, taking into account the sign of the imaginary component. As special cases involving complex floating-point operands should be handled according to ``exp(x2*log(x1))``, exponentiation has the same branch cut for ``x1`` as the natural logarithm (see :func:`~array_api.log`). - *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). + *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). Parameters ---------- x1: array - first input array whose elements correspond to the exponentiation base. Should have a numeric data type. + first input array whose elements correspond to the exponentiation base. Should have a numeric data type. x2: array - second input array whose elements correspond to the exponentiation exponent. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a numeric data type. + second input array whose elements correspond to the exponentiation exponent. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a numeric data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- @@ -5324,10 +5328,10 @@ class pow[TArray: Array](Protocol): For complex floating-point operands, special cases should be handled as if the operation is implemented as ``exp(x2*log(x1))``. .. note:: - Conforming implementations are allowed to treat special cases involving complex floating-point operands more carefully than as described in this specification. + Conforming implementations are allowed to treat special cases involving complex floating-point operands more carefully than as described in this specification. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -5343,12 +5347,12 @@ class real[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a complex floating-point data type. + input array. Should have a complex floating-point data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a floating-point data type with the same floating-point precision as ``x`` (e.g., if ``x`` is ``complex64``, the returned array must have the floating-point data type ``float32``). + an array containing the element-wise results. The returned array must have a floating-point data type with the same floating-point precision as ``x`` (e.g., if ``x`` is ``complex64``, the returned array must have the floating-point data type ``float32``). Notes ----- @@ -5366,29 +5370,29 @@ class remainder[TArray: Array](Protocol): Returns the remainder of division for each element ``x1_i`` of the input array ``x1`` and the respective element ``x2_i`` of the input array ``x2``. .. note:: - This function is equivalent to the Python modulus operator ``x1_i % x2_i``. + This function is equivalent to the Python modulus operator ``x1_i % x2_i``. .. note:: - For input arrays which promote to an integer data type, the result of division by zero is unspecified and thus implementation-defined. + For input arrays which promote to an integer data type, the result of division by zero is unspecified and thus implementation-defined. Parameters ---------- x1: array - dividend input array. Should have a real-valued data type. + dividend input array. Should have a real-valued data type. x2: array - divisor input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued data type. + divisor input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued data type. Returns ------- out: array - an array containing the element-wise results. Each element-wise result must have the same sign as the respective element ``x2_i``. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise results. Each element-wise result must have the same sign as the respective element ``x2_i``. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- **Special cases** .. note:: - In general, similar to Python's ``%`` operator, this function is **not** recommended for floating-point operands as semantics do not follow IEEE 754. That this function is specified to accept floating-point operands is primarily for reasons of backward compatibility. + In general, similar to Python's ``%`` operator, this function is **not** recommended for floating-point operands as semantics do not follow IEEE 754. That this function is specified to accept floating-point operands is primarily for reasons of backward compatibility. For floating-point operands, @@ -5425,26 +5429,26 @@ class round[TArray: Array](Protocol): Rounds each element ``x_i`` of the input array ``x`` to the nearest integer-valued number. .. note:: - For complex floating-point operands, real and imaginary components must be independently rounded to the nearest integer-valued number. + For complex floating-point operands, real and imaginary components must be independently rounded to the nearest integer-valued number. - Rounded real and imaginary components must be equal to their equivalent rounded real-valued floating-point counterparts (i.e., for complex-valued ``x``, ``real(round(x))`` must equal ``round(real(x)))`` and ``imag(round(x))`` must equal ``round(imag(x))``). + Rounded real and imaginary components must be equal to their equivalent rounded real-valued floating-point counterparts (i.e., for complex-valued ``x``, ``real(round(x))`` must equal ``round(real(x)))`` and ``imag(round(x))`` must equal ``round(imag(x))``). Parameters ---------- x: array - input array. Should have a numeric data type. + input array. Should have a numeric data type. Returns ------- out: array - an array containing the rounded result for each element in ``x``. The returned array must have the same data type as ``x``. + an array containing the rounded result for each element in ``x``. The returned array must have the same data type as ``x``. Notes ----- **Special cases** .. note:: - For complex floating-point operands, the following special cases apply to real and imaginary components independently (e.g., if ``real(x_i)`` is ``NaN``, the rounded real component is ``NaN``). + For complex floating-point operands, the following special cases apply to real and imaginary components independently (e.g., if ``real(x_i)`` is ``NaN``, the rounded real component is ``NaN``). - If ``x_i`` is already integer-valued, the result is ``x_i``. @@ -5458,7 +5462,7 @@ class round[TArray: Array](Protocol): - If two integers are equally close to ``x_i``, the result is the even integer closest to ``x_i``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -5474,22 +5478,22 @@ class sign[TArray: Array](Protocol): The sign function (also known as the **signum function**) of a number :math:`x_i` is defined as .. math:: - \\operatorname{sign}(x_i) = \\begin{cases} - 0 & \\textrm{if } x_i = 0 \\\\ - \\frac{x_i}{|x_i|} & \\textrm{otherwise} - \\end{cases} + \\operatorname{sign}(x_i) = \\begin{cases} + 0 & \\textrm{if } x_i = 0 \\\\ + \\frac{x_i}{|x_i|} & \\textrm{otherwise} + \\end{cases} where :math:`|x_i|` is the absolute value of :math:`x_i`. Parameters ---------- x: array - input array. Should have a numeric data type. + input array. Should have a numeric data type. Returns ------- out: array - an array containing the evaluated result for each element in ``x``. The returned array must have the same data type as ``x``. + an array containing the evaluated result for each element in ``x``. The returned array must have the same data type as ``x``. Notes ----- @@ -5509,7 +5513,7 @@ class sign[TArray: Array](Protocol): - In the remaining cases, special cases must be handled according to the rules of complex number division (see :func:`~array_api.divide`). .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -5525,25 +5529,25 @@ class sin[TArray: Array](Protocol): Each element ``x_i`` is assumed to be expressed in radians. .. note:: - The sine is an entire function on the complex plane and has no branch cuts. + The sine is an entire function on the complex plane and has no branch cuts. .. note:: - For complex arguments, the mathematical definition of sine is + For complex arguments, the mathematical definition of sine is - .. math:: - \\begin{align} \\operatorname{sin}(x) &= \\frac{e^{jx} - e^{-jx}}{2j} \\\\ &= \\frac{\\operatorname{sinh}(jx)}{j} \\\\ &= \\frac{\\operatorname{sinh}(jx)}{j} \\cdot \\frac{j}{j} \\\\ &= -j \\cdot \\operatorname{sinh}(jx) \\end{align} + .. math:: + \\begin{align} \\operatorname{sin}(x) &= \\frac{e^{jx} - e^{-jx}}{2j} \\\\ &= \\frac{\\operatorname{sinh}(jx)}{j} \\\\ &= \\frac{\\operatorname{sinh}(jx)}{j} \\cdot \\frac{j}{j} \\\\ &= -j \\cdot \\operatorname{sinh}(jx) \\end{align} - where :math:`\\operatorname{sinh}` is the hyperbolic sine. + where :math:`\\operatorname{sinh}` is the hyperbolic sine. Parameters ---------- x: array - input array whose elements are each expressed in radians. Should have a floating-point data type. + input array whose elements are each expressed in radians. Should have a floating-point data type. Returns ------- out: array - an array containing the sine of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the sine of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -5559,7 +5563,7 @@ class sin[TArray: Array](Protocol): For complex floating-point operands, special cases must be handled as if the operation is implemented as ``-1j * sinh(x*1j)``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -5575,27 +5579,27 @@ class sinh[TArray: Array](Protocol): The mathematical definition of the hyperbolic sine is .. math:: - \\operatorname{sinh}(x) = \\frac{e^x - e^{-x}}{2} + \\operatorname{sinh}(x) = \\frac{e^x - e^{-x}}{2} .. note:: - The hyperbolic sine is an entire function in the complex plane and has no branch cuts. The function is periodic, with period :math:`2\\pi j`, with respect to the imaginary component. + The hyperbolic sine is an entire function in the complex plane and has no branch cuts. The function is periodic, with period :math:`2\\pi j`, with respect to the imaginary component. Parameters ---------- x: array - input array whose elements each represent a hyperbolic angle. Should have a floating-point data type. + input array whose elements each represent a hyperbolic angle. Should have a floating-point data type. Returns ------- out: array - an array containing the hyperbolic sine of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the hyperbolic sine of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- **Special cases** .. note:: - For all operands, ``sinh(x)`` must equal ``-sinh(-x)``. + For all operands, ``sinh(x)`` must equal ``-sinh(-x)``. For real-valued floating-point operands, @@ -5608,7 +5612,7 @@ class sinh[TArray: Array](Protocol): For complex floating-point operands, let ``a = real(x_i)``, ``b = imag(x_i)``, and .. note:: - For complex floating-point operands, ``sinh(conj(x))`` must equal ``conj(sinh(x))``. + For complex floating-point operands, ``sinh(conj(x))`` must equal ``conj(sinh(x))``. - If ``a`` is ``+0`` and ``b`` is ``+0``, the result is ``+0 + 0j``. - If ``a`` is ``+0`` and ``b`` is ``+infinity``, the result is ``0 + NaN j`` (sign of the real component is unspecified). @@ -5626,7 +5630,7 @@ class sinh[TArray: Array](Protocol): where ``cis(v)`` is ``cos(v) + sin(v)*1j``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -5642,17 +5646,17 @@ class square[TArray: Array](Protocol): The square of a number ``x_i`` is defined as .. math:: - x_i^2 = x_i \\cdot x_i + x_i^2 = x_i \\cdot x_i Parameters ---------- x: array - input array. Should have a numeric data type. + input array. Should have a numeric data type. Returns ------- out: array - an array containing the evaluated result for each element in ``x``. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the evaluated result for each element in ``x``. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- @@ -5661,7 +5665,7 @@ class square[TArray: Array](Protocol): For floating-point operands, special cases must be handled as if the operation is implemented as ``x * x`` (see :func:`~array_api.multiply`). .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -5675,29 +5679,29 @@ class sqrt[TArray: Array](Protocol): Calculates the principal square root for each element ``x_i`` of the input array ``x``. .. note:: - After rounding, each result must be indistinguishable from the infinitely precise result (as required by IEEE 754). + After rounding, each result must be indistinguishable from the infinitely precise result (as required by IEEE 754). .. note:: - For complex floating-point operands, ``sqrt(conj(x))`` must equal ``conj(sqrt(x))``. + For complex floating-point operands, ``sqrt(conj(x))`` must equal ``conj(sqrt(x))``. .. note:: - By convention, the branch cut of the square root is the negative real axis :math:`(-\\infty, 0)`. + By convention, the branch cut of the square root is the negative real axis :math:`(-\\infty, 0)`. - The square root is a continuous function from above the branch cut, taking into account the sign of the imaginary component. + The square root is a continuous function from above the branch cut, taking into account the sign of the imaginary component. - Accordingly, for complex arguments, the function returns the square root in the range of the right half-plane, including the imaginary axis (i.e., the plane defined by :math:`[0, +\\infty)` along the real axis and :math:`(-\\infty, +\\infty)` along the imaginary axis). + Accordingly, for complex arguments, the function returns the square root in the range of the right half-plane, including the imaginary axis (i.e., the plane defined by :math:`[0, +\\infty)` along the real axis and :math:`(-\\infty, +\\infty)` along the imaginary axis). - *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). + *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). Parameters ---------- x: array - input array. Should have a floating-point data type. + input array. Should have a floating-point data type. Returns ------- out: array - an array containing the square root of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the square root of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -5724,7 +5728,7 @@ class sqrt[TArray: Array](Protocol): - If ``a`` is ``NaN`` and ``b`` is ``NaN``, the result is ``NaN + NaN j``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -5742,20 +5746,20 @@ class subtract[TArray: Array](Protocol): Parameters ---------- x1: array - first input array. Should have a numeric data type. + first input array. Should have a numeric data type. x2: array - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a numeric data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a numeric data type. Returns ------- out: array - an array containing the element-wise differences. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise differences. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -5771,25 +5775,25 @@ class tan[TArray: Array](Protocol): Each element ``x_i`` is assumed to be expressed in radians. .. note:: - Tangent is an analytical function on the complex plane and has no branch cuts. The function is periodic, with period :math:`\\pi j`, with respect to the real component and has first order poles along the real line at coordinates :math:`(\\pi (\\frac{1}{2} + n), 0)`. However, IEEE 754 binary floating-point representation cannot represent the value :math:`\\pi / 2` exactly, and, thus, no argument value is possible for which a pole error occurs. + Tangent is an analytical function on the complex plane and has no branch cuts. The function is periodic, with period :math:`\\pi j`, with respect to the real component and has first order poles along the real line at coordinates :math:`(\\pi (\\frac{1}{2} + n), 0)`. However, IEEE 754 binary floating-point representation cannot represent the value :math:`\\pi / 2` exactly, and, thus, no argument value is possible for which a pole error occurs. .. note:: - For complex arguments, the mathematical definition of tangent is + For complex arguments, the mathematical definition of tangent is - .. math:: - \\begin{align} \\operatorname{tan}(x) &= \\frac{j(e^{-jx} - e^{jx})}{e^{-jx} + e^{jx}} \\\\ &= (-1) \\frac{j(e^{jx} - e^{-jx})}{e^{jx} + e^{-jx}} \\\\ &= -j \\cdot \\operatorname{tanh}(jx) \\end{align} + .. math:: + \\begin{align} \\operatorname{tan}(x) &= \\frac{j(e^{-jx} - e^{jx})}{e^{-jx} + e^{jx}} \\\\ &= (-1) \\frac{j(e^{jx} - e^{-jx})}{e^{jx} + e^{-jx}} \\\\ &= -j \\cdot \\operatorname{tanh}(jx) \\end{align} - where :math:`\\operatorname{tanh}` is the hyperbolic tangent. + where :math:`\\operatorname{tanh}` is the hyperbolic tangent. Parameters ---------- x: array - input array whose elements are expressed in radians. Should have a floating-point data type. + input array whose elements are expressed in radians. Should have a floating-point data type. Returns ------- out: array - an array containing the tangent of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the tangent of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -5805,7 +5809,7 @@ class tan[TArray: Array](Protocol): For complex floating-point operands, special cases must be handled as if the operation is implemented as ``-1j * tanh(x*1j)``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -5821,29 +5825,29 @@ class tanh[TArray: Array](Protocol): The mathematical definition of the hyperbolic tangent is .. math:: - \\begin{align} \\operatorname{tanh}(x) &= \\frac{\\operatorname{sinh}(x)}{\\operatorname{cosh}(x)} \\\\ &= \\frac{e^x - e^{-x}}{e^x + e^{-x}} \\end{align} + \\begin{align} \\operatorname{tanh}(x) &= \\frac{\\operatorname{sinh}(x)}{\\operatorname{cosh}(x)} \\\\ &= \\frac{e^x - e^{-x}}{e^x + e^{-x}} \\end{align} where :math:`\\operatorname{sinh}(x)` is the hyperbolic sine and :math:`\\operatorname{cosh}(x)` is the hyperbolic cosine. .. note:: - The hyperbolic tangent is an analytical function on the complex plane and has no branch cuts. The function is periodic, with period :math:`\\pi j`, with respect to the imaginary component and has first order poles along the imaginary line at coordinates :math:`(0, \\pi (\\frac{1}{2} + n))`. However, IEEE 754 binary floating-point representation cannot represent :math:`\\pi / 2` exactly, and, thus, no argument value is possible such that a pole error occurs. + The hyperbolic tangent is an analytical function on the complex plane and has no branch cuts. The function is periodic, with period :math:`\\pi j`, with respect to the imaginary component and has first order poles along the imaginary line at coordinates :math:`(0, \\pi (\\frac{1}{2} + n))`. However, IEEE 754 binary floating-point representation cannot represent :math:`\\pi / 2` exactly, and, thus, no argument value is possible such that a pole error occurs. Parameters ---------- x: array - input array whose elements each represent a hyperbolic angle. Should have a floating-point data type. + input array whose elements each represent a hyperbolic angle. Should have a floating-point data type. Returns ------- out: array - an array containing the hyperbolic tangent of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the hyperbolic tangent of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- **Special cases** .. note:: - For all operands, ``tanh(-x)`` must equal ``-tanh(x)``. + For all operands, ``tanh(-x)`` must equal ``-tanh(x)``. For real-valued floating-point operands, @@ -5856,7 +5860,7 @@ class tanh[TArray: Array](Protocol): For complex floating-point operands, let ``a = real(x_i)``, ``b = imag(x_i)``, and .. note:: - For complex floating-point operands, ``tanh(conj(x))`` must equal ``conj(tanh(x))``. + For complex floating-point operands, ``tanh(conj(x))`` must equal ``conj(tanh(x))``. - If ``a`` is ``+0`` and ``b`` is ``+0``, the result is ``+0 + 0j``. - If ``a`` is a nonzero finite number and ``b`` is ``+infinity``, the result is ``NaN + NaN j``. @@ -5871,12 +5875,12 @@ class tanh[TArray: Array](Protocol): - If ``a`` is ``NaN`` and ``b`` is ``NaN``, the result is ``NaN + NaN j``. .. warning:: - For historical reasons stemming from the C standard, array libraries may not return the expected result when ``a`` is ``+0`` and ``b`` is either ``+infinity`` or ``NaN``. The result should be ``+0 + NaN j`` in both cases; however, for libraries compiled against older C versions, the result may be ``NaN + NaN j``. + For historical reasons stemming from the C standard, array libraries may not return the expected result when ``a`` is ``+0`` and ``b`` is either ``+infinity`` or ``NaN``. The result should be ``+0 + NaN j`` in both cases; however, for libraries compiled against older C versions, the result may be ``NaN + NaN j``. - Array libraries are not required to patch these older C versions, and, thus, users are advised that results may vary across array library implementations for these special cases. + Array libraries are not required to patch these older C versions, and, thus, users are advised that results may vary across array library implementations for these special cases. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -5892,12 +5896,12 @@ class trunc[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a real-valued data type. + input array. Should have a real-valued data type. Returns ------- out: array - an array containing the rounded result for each element in ``x``. The returned array must have the same data type as ``x``. + an array containing the rounded result for each element in ``x``. The returned array must have the same data type as ``x``. Notes ----- @@ -5927,21 +5931,21 @@ class argmax[TArray: Array](Protocol): When the maximum value occurs multiple times, only the indices corresponding to the first occurrence are returned. .. note:: - For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). + For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). Parameters ---------- x: array - input array. Should have a real-valued data type. + input array. Should have a real-valued data type. axis: Optional[int] - axis along which to search. If ``None``, the function must return the index of the maximum value of the flattened array. Default: ``None``. + axis along which to search. If ``None``, the function must return the index of the maximum value of the flattened array. Default: ``None``. keepdims: bool - if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. + if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. Returns ------- out: array - if ``axis`` is ``None``, a zero-dimensional array containing the index of the first occurrence of the maximum value; otherwise, a non-zero-dimensional array containing the indices of the maximum values. The returned array must have be the default array index data type. + if ``axis`` is ``None``, a zero-dimensional array containing the index of the first occurrence of the maximum value; otherwise, a non-zero-dimensional array containing the indices of the maximum values. The returned array must have be the default array index data type. """ @@ -5957,21 +5961,21 @@ class argmin[TArray: Array](Protocol): When the minimum value occurs multiple times, only the indices corresponding to the first occurrence are returned. .. note:: - For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). + For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). Parameters ---------- x: array - input array. Should have a real-valued data type. + input array. Should have a real-valued data type. axis: Optional[int] - axis along which to search. If ``None``, the function must return the index of the minimum value of the flattened array. Default: ``None``. + axis along which to search. If ``None``, the function must return the index of the minimum value of the flattened array. Default: ``None``. keepdims: bool - if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. + if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. Returns ------- out: array - if ``axis`` is ``None``, a zero-dimensional array containing the index of the first occurrence of the minimum value; otherwise, a non-zero-dimensional array containing the indices of the minimum values. The returned array must have the default array index data type. + if ``axis`` is ``None``, a zero-dimensional array containing the index of the first occurrence of the minimum value; otherwise, a non-zero-dimensional array containing the indices of the minimum values. The returned array must have the default array index data type. """ @@ -5985,31 +5989,31 @@ class nonzero[TArray: Array](Protocol): Returns the indices of the array elements which are non-zero. .. note:: - If ``x`` has a complex floating-point data type, non-zero elements are those elements having at least one component (real or imaginary) which is non-zero. + If ``x`` has a complex floating-point data type, non-zero elements are those elements having at least one component (real or imaginary) which is non-zero. .. note:: - If ``x`` has a boolean data type, non-zero elements are those elements which are equal to ``True``. + If ``x`` has a boolean data type, non-zero elements are those elements which are equal to ``True``. .. admonition:: Data-dependent output shape - :class: admonition important + :class: admonition important - The shape of the output array for this function depends on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) may find this function difficult to implement without knowing array values. Accordingly, such libraries may choose to omit this function. See :ref:`data-dependent-output-shapes` section for more details. + The shape of the output array for this function depends on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) may find this function difficult to implement without knowing array values. Accordingly, such libraries may choose to omit this function. See :ref:`data-dependent-output-shapes` section for more details. Parameters ---------- x: array - input array. Must have a positive rank. If ``x`` is zero-dimensional, the function must raise an exception. + input array. Must have a positive rank. If ``x`` is zero-dimensional, the function must raise an exception. Returns ------- out: Tuple[array, ...] - a tuple of ``k`` arrays, one for each dimension of ``x`` and each of size ``n`` (where ``n`` is the total number of non-zero elements), containing the indices of the non-zero elements in that dimension. The indices must be returned in row-major, C-style order. The returned array must have the default array index data type. + a tuple of ``k`` arrays, one for each dimension of ``x`` and each of size ``n`` (where ``n`` is the total number of non-zero elements), containing the indices of the non-zero elements in that dimension. The indices must be returned in row-major, C-style order. The returned array must have the default array index data type. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -6025,16 +6029,16 @@ class where[TArray: Array](Protocol): Parameters ---------- condition: array - when ``True``, yield ``x1_i``; otherwise, yield ``x2_i``. Should have a boolean data type. Must be compatible with ``x1`` and ``x2`` (see :ref:`broadcasting`). + when ``True``, yield ``x1_i``; otherwise, yield ``x2_i``. Should have a boolean data type. Must be compatible with ``x1`` and ``x2`` (see :ref:`broadcasting`). x1: array - first input array. Must be compatible with ``condition`` and ``x2`` (see :ref:`broadcasting`). + first input array. Must be compatible with ``condition`` and ``x2`` (see :ref:`broadcasting`). x2: array - second input array. Must be compatible with ``condition`` and ``x1`` (see :ref:`broadcasting`). + second input array. Must be compatible with ``condition`` and ``x1`` (see :ref:`broadcasting`). Returns ------- out: array - an array with elements from ``x1`` where ``condition`` is ``True``, and elements from ``x2`` elsewhere. The returned array must have a data type determined by :ref:`type-promotion` rules with the arrays ``x1`` and ``x2``. + an array with elements from ``x1`` where ``condition`` is ``True``, and elements from ``x2`` elsewhere. The returned array must have a data type determined by :ref:`type-promotion` rules with the arrays ``x1`` and ``x2``. """ @@ -6048,33 +6052,33 @@ class all[TArray: Array](Protocol): Tests whether all input array elements evaluate to ``True`` along a specified axis. .. note:: - Positive infinity, negative infinity, and NaN must evaluate to ``True``. + Positive infinity, negative infinity, and NaN must evaluate to ``True``. .. note:: - If ``x`` has a complex floating-point data type, elements having a non-zero component (real or imaginary) must evaluate to ``True``. + If ``x`` has a complex floating-point data type, elements having a non-zero component (real or imaginary) must evaluate to ``True``. .. note:: - If ``x`` is an empty array or the size of the axis (dimension) along which to evaluate elements is zero, the test result must be ``True``. + If ``x`` is an empty array or the size of the axis (dimension) along which to evaluate elements is zero, the test result must be ``True``. Parameters ---------- x: array - input array. + input array. axis: Optional[Union[int, Tuple[int, ...]]] - axis or axes along which to perform a logical AND reduction. By default, a logical AND reduction must be performed over the entire array. If a tuple of integers, logical AND reductions must be performed over multiple axes. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to perform a reduction by counting backward from the last dimension (where ``-1`` refers to the last dimension). If provided an invalid ``axis``, the function must raise an exception. Default: ``None``. + axis or axes along which to perform a logical AND reduction. By default, a logical AND reduction must be performed over the entire array. If a tuple of integers, logical AND reductions must be performed over multiple axes. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to perform a reduction by counting backward from the last dimension (where ``-1`` refers to the last dimension). If provided an invalid ``axis``, the function must raise an exception. Default: ``None``. keepdims: bool - If ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. + If ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. Returns ------- out: array - if a logical AND reduction was performed over the entire array, the returned array must be a zero-dimensional array containing the test result; otherwise, the returned array must be a non-zero-dimensional array containing the test results. The returned array must have a data type of ``bool``. + if a logical AND reduction was performed over the entire array, the returned array must be a zero-dimensional array containing the test result; otherwise, the returned array must be a non-zero-dimensional array containing the test results. The returned array must have a data type of ``bool``. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -6088,33 +6092,33 @@ class any[TArray: Array](Protocol): Tests whether any input array element evaluates to ``True`` along a specified axis. .. note:: - Positive infinity, negative infinity, and NaN must evaluate to ``True``. + Positive infinity, negative infinity, and NaN must evaluate to ``True``. .. note:: - If ``x`` has a complex floating-point data type, elements having a non-zero component (real or imaginary) must evaluate to ``True``. + If ``x`` has a complex floating-point data type, elements having a non-zero component (real or imaginary) must evaluate to ``True``. .. note:: - If ``x`` is an empty array or the size of the axis (dimension) along which to evaluate elements is zero, the test result must be ``False``. + If ``x`` is an empty array or the size of the axis (dimension) along which to evaluate elements is zero, the test result must be ``False``. Parameters ---------- x: array - input array. + input array. axis: Optional[Union[int, Tuple[int, ...]]] - axis or axes along which to perform a logical OR reduction. By default, a logical OR reduction must be performed over the entire array. If a tuple of integers, logical OR reductions must be performed over multiple axes. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to perform a reduction by counting backward from the last dimension (where ``-1`` refers to the last dimension). If provided an invalid ``axis``, the function must raise an exception. Default: ``None``. + axis or axes along which to perform a logical OR reduction. By default, a logical OR reduction must be performed over the entire array. If a tuple of integers, logical OR reductions must be performed over multiple axes. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to perform a reduction by counting backward from the last dimension (where ``-1`` refers to the last dimension). If provided an invalid ``axis``, the function must raise an exception. Default: ``None``. keepdims: bool - If ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. + If ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. Returns ------- out: array - if a logical OR reduction was performed over the entire array, the returned array must be a zero-dimensional array containing the test result; otherwise, the returned array must be a non-zero-dimensional array containing the test results. The returned array must have a data type of ``bool``. + if a logical OR reduction was performed over the entire array, the returned array must be a zero-dimensional array containing the test result; otherwise, the returned array must be a non-zero-dimensional array containing the test results. The returned array must have a data type of ``bool``. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -6128,23 +6132,23 @@ class take[TArray: Array](Protocol): Returns elements of an array along an axis. .. note:: - Conceptually, ``take(x, indices, axis=3)`` is equivalent to ``x[:,:,:,indices,...]``; however, explicit indexing via arrays of indices is not currently supported in this specification due to concerns regarding ``__setitem__`` and array mutation semantics. + Conceptually, ``take(x, indices, axis=3)`` is equivalent to ``x[:,:,:,indices,...]``; however, explicit indexing via arrays of indices is not currently supported in this specification due to concerns regarding ``__setitem__`` and array mutation semantics. Parameters ---------- x: array - input array. + input array. indices: array - array indices. The array must be one-dimensional and have an integer data type. + array indices. The array must be one-dimensional and have an integer data type. axis: Optional[int] - axis over which to select values. If ``axis`` is negative, the function must determine the axis along which to select values by counting from the last dimension. + axis over which to select values. If ``axis`` is negative, the function must determine the axis along which to select values by counting from the last dimension. - If ``x`` is a one-dimensional array, providing an ``axis`` is optional; however, if ``x`` has more than one dimension, providing an ``axis`` is required. + If ``x`` is a one-dimensional array, providing an ``axis`` is optional; however, if ``x`` has more than one dimension, providing an ``axis`` is required. Returns ------- out: array - an array having the same data type as ``x``. The output array must have the same rank (i.e., number of dimensions) as ``x`` and must have the same shape as ``x``, except for the axis specified by ``axis`` whose size must equal the number of elements in ``indices``. + an array having the same data type as ``x``. The output array must have the same rank (i.e., number of dimensions) as ``x`` and must have the same shape as ``x``, except for the axis specified by ``axis`` whose size must equal the number of elements in ``indices``. """ @@ -6158,35 +6162,35 @@ class fft[TArray: Array](Protocol): Computes the one-dimensional discrete Fourier transform. .. note:: - Applying the one-dimensional inverse discrete Fourier transform to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e., ``ifft(fft(x)) == x``), provided that the transform and inverse transform are performed with the same arguments (number of elements, axis, and normalization mode). + Applying the one-dimensional inverse discrete Fourier transform to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e., ``ifft(fft(x)) == x``), provided that the transform and inverse transform are performed with the same arguments (number of elements, axis, and normalization mode). Parameters ---------- x: array - input array. Should have a complex floating-point data type. + input array. Should have a complex floating-point data type. n: Optional[int] - number of elements over which to compute the transform along the axis (dimension) specified by ``axis``. Let ``M`` be the size of the input array along the axis specified by ``axis``. When ``n`` is ``None``, the function must set ``n`` equal to ``M``. + number of elements over which to compute the transform along the axis (dimension) specified by ``axis``. Let ``M`` be the size of the input array along the axis specified by ``axis``. When ``n`` is ``None``, the function must set ``n`` equal to ``M``. - - If ``n`` is greater than ``M``, the axis specified by ``axis`` must be zero-padded to size ``n``. - - If ``n`` is less than ``M``, the axis specified by ``axis`` must be trimmed to size ``n``. - - If ``n`` equals ``M``, all elements along the axis specified by ``axis`` must be used when computing the transform. + - If ``n`` is greater than ``M``, the axis specified by ``axis`` must be zero-padded to size ``n``. + - If ``n`` is less than ``M``, the axis specified by ``axis`` must be trimmed to size ``n``. + - If ``n`` equals ``M``, all elements along the axis specified by ``axis`` must be used when computing the transform. - Default: ``None``. + Default: ``None``. axis: int - axis (dimension) of the input array over which to compute the transform. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). Default: ``-1``. + axis (dimension) of the input array over which to compute the transform. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). Default: ``-1``. norm: Literal['backward', 'ortho', 'forward'] - normalization mode. Should be one of the following modes: + normalization mode. Should be one of the following modes: - - ``'backward'``: no normalization. - - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). - - ``'forward'``: normalize by ``1/n``. + - ``'backward'``: no normalization. + - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). + - ``'forward'``: normalize by ``1/n``. - Default: ``'backward'``. + Default: ``'backward'``. Returns ------- out: array - an array transformed along the axis (dimension) specified by ``axis``. The returned array must have the same data type as ``x`` and must have the same shape as ``x``, except for the axis specified by ``axis`` which must have size ``n``. + an array transformed along the axis (dimension) specified by ``axis``. The returned array must have the same data type as ``x`` and must have the same shape as ``x``, except for the axis specified by ``axis`` which must have size ``n``. Notes ----- @@ -6205,35 +6209,35 @@ class ifft[TArray: Array](Protocol): Computes the one-dimensional inverse discrete Fourier transform. .. note:: - Applying the one-dimensional inverse discrete Fourier transform to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e., ``ifft(fft(x)) == x``), provided that the transform and inverse transform are performed with the same arguments (number of elements, axis, and normalization mode). + Applying the one-dimensional inverse discrete Fourier transform to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e., ``ifft(fft(x)) == x``), provided that the transform and inverse transform are performed with the same arguments (number of elements, axis, and normalization mode). Parameters ---------- x: array - input array. Should have a complex floating-point data type. + input array. Should have a complex floating-point data type. n: Optional[int] - number of elements over which to compute the transform along the axis (dimension) specified by ``axis``. Let ``M`` be the size of the input array along the axis specified by ``axis``. When ``n`` is ``None``, the function must set ``n`` equal to ``M``. + number of elements over which to compute the transform along the axis (dimension) specified by ``axis``. Let ``M`` be the size of the input array along the axis specified by ``axis``. When ``n`` is ``None``, the function must set ``n`` equal to ``M``. - - If ``n`` is greater than ``M``, the axis specified by ``axis`` must be zero-padded to size ``n``. - - If ``n`` is less than ``M``, the axis specified by ``axis`` must be trimmed to size ``n``. - - If ``n`` equals ``M``, all elements along the axis specified by ``axis`` must be used when computing the transform. + - If ``n`` is greater than ``M``, the axis specified by ``axis`` must be zero-padded to size ``n``. + - If ``n`` is less than ``M``, the axis specified by ``axis`` must be trimmed to size ``n``. + - If ``n`` equals ``M``, all elements along the axis specified by ``axis`` must be used when computing the transform. - Default: ``None``. + Default: ``None``. axis: int - axis (dimension) of the input array over which to compute the transform. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). Default: ``-1``. + axis (dimension) of the input array over which to compute the transform. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). Default: ``-1``. norm: Literal['backward', 'ortho', 'forward'] - normalization mode. Should be one of the following modes: + normalization mode. Should be one of the following modes: - - ``'backward'``: normalize by ``1/n``. - - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). - - ``'forward'``: no normalization. + - ``'backward'``: normalize by ``1/n``. + - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). + - ``'forward'``: no normalization. - Default: ``'backward'``. + Default: ``'backward'``. Returns ------- out: array - an array transformed along the axis (dimension) specified by ``axis``. The returned array must have the same data type as ``x`` and must have the same shape as ``x``, except for the axis specified by ``axis`` which must have size ``n``. + an array transformed along the axis (dimension) specified by ``axis``. The returned array must have the same data type as ``x`` and must have the same shape as ``x``, except for the axis specified by ``axis`` which must have size ``n``. Notes ----- @@ -6252,41 +6256,41 @@ class fftn[TArray: Array](Protocol): Computes the n-dimensional discrete Fourier transform. .. note:: - Applying the n-dimensional inverse discrete Fourier transform to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e., ``ifftn(fftn(x)) == x``), provided that the transform and inverse transform are performed with the same arguments (sizes, axes, and normalization mode). + Applying the n-dimensional inverse discrete Fourier transform to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e., ``ifftn(fftn(x)) == x``), provided that the transform and inverse transform are performed with the same arguments (sizes, axes, and normalization mode). Parameters ---------- x: array - input array. Should have a complex floating-point data type. + input array. Should have a complex floating-point data type. s: Optional[Sequence[int]] - number of elements over which to compute the transform along the axes (dimensions) specified by ``axes``. Let ``i`` be the index of the ``n``-th axis specified by ``axes`` (i.e., ``i = axes[n]``) and ``M[i]`` be the size of the input array along axis ``i``. When ``s`` is ``None``, the function must set ``s`` equal to a sequence of integers such that ``s[i]`` equals ``M[i]`` for all ``i``. + number of elements over which to compute the transform along the axes (dimensions) specified by ``axes``. Let ``i`` be the index of the ``n``-th axis specified by ``axes`` (i.e., ``i = axes[n]``) and ``M[i]`` be the size of the input array along axis ``i``. When ``s`` is ``None``, the function must set ``s`` equal to a sequence of integers such that ``s[i]`` equals ``M[i]`` for all ``i``. - - If ``s[i]`` is greater than ``M[i]``, axis ``i`` must be zero-padded to size ``s[i]``. - - If ``s[i]`` is less than ``M[i]``, axis ``i`` must be trimmed to size ``s[i]``. - - If ``s[i]`` equals ``M[i]`` or ``-1``, all elements along axis ``i`` must be used when computing the transform. + - If ``s[i]`` is greater than ``M[i]``, axis ``i`` must be zero-padded to size ``s[i]``. + - If ``s[i]`` is less than ``M[i]``, axis ``i`` must be trimmed to size ``s[i]``. + - If ``s[i]`` equals ``M[i]`` or ``-1``, all elements along axis ``i`` must be used when computing the transform. - If ``s`` is not ``None``, ``axes`` must not be ``None``. Default: ``None``. + If ``s`` is not ``None``, ``axes`` must not be ``None``. Default: ``None``. axes: Optional[Sequence[int]] - axes (dimensions) over which to compute the transform. A valid axis in ``axes`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an axis is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). + axes (dimensions) over which to compute the transform. A valid axis in ``axes`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an axis is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). - If ``s`` is provided, the corresponding ``axes`` to be transformed must also be provided. If ``axes`` is ``None``, the function must compute the transform over all axes. Default: ``None``. + If ``s`` is provided, the corresponding ``axes`` to be transformed must also be provided. If ``axes`` is ``None``, the function must compute the transform over all axes. Default: ``None``. - If ``axes`` contains two or more entries which resolve to the same axis (i.e., resolved axes are not unique), the behavior is unspecified and thus implementation-defined. + If ``axes`` contains two or more entries which resolve to the same axis (i.e., resolved axes are not unique), the behavior is unspecified and thus implementation-defined. norm: Literal['backward', 'ortho', 'forward'] - normalization mode. Should be one of the following modes: + normalization mode. Should be one of the following modes: - - ``'backward'``: no normalization. - - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). - - ``'forward'``: normalize by ``1/n``. + - ``'backward'``: no normalization. + - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). + - ``'forward'``: normalize by ``1/n``. - where ``n = prod(s)`` is the logical FFT size. + where ``n = prod(s)`` is the logical FFT size. - Default: ``'backward'``. + Default: ``'backward'``. Returns ------- out: array - an array transformed along the axes (dimensions) specified by ``axes``. The returned array must have the same data type as ``x`` and must have the same shape as ``x``, except for the axes specified by ``axes`` which must have size ``s[i]``. + an array transformed along the axes (dimensions) specified by ``axes``. The returned array must have the same data type as ``x`` and must have the same shape as ``x``, except for the axes specified by ``axes`` which must have size ``s[i]``. Notes ----- @@ -6305,41 +6309,41 @@ class ifftn[TArray: Array](Protocol): Computes the n-dimensional inverse discrete Fourier transform. .. note:: - Applying the n-dimensional inverse discrete Fourier transform to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e., ``ifftn(fftn(x)) == x``), provided that the transform and inverse transform are performed with the same arguments (sizes, axes, and normalization mode). + Applying the n-dimensional inverse discrete Fourier transform to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e., ``ifftn(fftn(x)) == x``), provided that the transform and inverse transform are performed with the same arguments (sizes, axes, and normalization mode). Parameters ---------- x: array - input array. Should have a complex floating-point data type. + input array. Should have a complex floating-point data type. s: Optional[Sequence[int]] - number of elements over which to compute the transform along the axes (dimensions) specified by ``axes``. Let ``i`` be the index of the ``n``-th axis specified by ``axes`` (i.e., ``i = axes[n]``) and ``M[i]`` be the size of the input array along axis ``i``. When ``s`` is ``None``, the function must set ``s`` equal to a sequence of integers such that ``s[i]`` equals ``M[i]`` for all ``i``. + number of elements over which to compute the transform along the axes (dimensions) specified by ``axes``. Let ``i`` be the index of the ``n``-th axis specified by ``axes`` (i.e., ``i = axes[n]``) and ``M[i]`` be the size of the input array along axis ``i``. When ``s`` is ``None``, the function must set ``s`` equal to a sequence of integers such that ``s[i]`` equals ``M[i]`` for all ``i``. - - If ``s[i]`` is greater than ``M[i]``, axis ``i`` must be zero-padded to size ``s[i]``. - - If ``s[i]`` is less than ``M[i]``, axis ``i`` must be trimmed to size ``s[i]``. - - If ``s[i]`` equals ``M[i]`` or ``-1``, all elements along axis ``i`` must be used when computing the transform. + - If ``s[i]`` is greater than ``M[i]``, axis ``i`` must be zero-padded to size ``s[i]``. + - If ``s[i]`` is less than ``M[i]``, axis ``i`` must be trimmed to size ``s[i]``. + - If ``s[i]`` equals ``M[i]`` or ``-1``, all elements along axis ``i`` must be used when computing the transform. - If ``s`` is not ``None``, ``axes`` must not be ``None``. Default: ``None``. + If ``s`` is not ``None``, ``axes`` must not be ``None``. Default: ``None``. axes: Optional[Sequence[int]] - axes (dimensions) over which to compute the transform. A valid axis in ``axes`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an axis is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). + axes (dimensions) over which to compute the transform. A valid axis in ``axes`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an axis is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). - If ``s`` is provided, the corresponding ``axes`` to be transformed must also be provided. If ``axes`` is ``None``, the function must compute the transform over all axes. Default: ``None``. + If ``s`` is provided, the corresponding ``axes`` to be transformed must also be provided. If ``axes`` is ``None``, the function must compute the transform over all axes. Default: ``None``. - If ``axes`` contains two or more entries which resolve to the same axis (i.e., resolved axes are not unique), the behavior is unspecified and thus implementation-defined. + If ``axes`` contains two or more entries which resolve to the same axis (i.e., resolved axes are not unique), the behavior is unspecified and thus implementation-defined. norm: Literal['backward', 'ortho', 'forward'] - specify the normalization mode. Should be one of the following modes: + specify the normalization mode. Should be one of the following modes: - - ``'backward'``: normalize by ``1/n``. - - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). - - ``'forward'``: no normalization. + - ``'backward'``: normalize by ``1/n``. + - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). + - ``'forward'``: no normalization. - where ``n = prod(s)`` is the logical FFT size. + where ``n = prod(s)`` is the logical FFT size. - Default: ``'backward'``. + Default: ``'backward'``. Returns ------- out: array - an array transformed along the axes (dimensions) specified by ``axes``. The returned array must have the same data type as ``x`` and must have the same shape as ``x``, except for the axes specified by ``axes`` which must have size ``s[i]``. + an array transformed along the axes (dimensions) specified by ``axes``. The returned array must have the same data type as ``x`` and must have the same shape as ``x``, except for the axes specified by ``axes`` which must have size ``s[i]``. Notes ----- @@ -6358,35 +6362,35 @@ class rfft[TArray: Array](Protocol): Computes the one-dimensional discrete Fourier transform for real-valued input. .. note:: - Applying the one-dimensional inverse discrete Fourier transform for real-valued input to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e., ``irfft(rfft(x)) == x``), provided that the transform and inverse transform are performed with the same arguments (axis and normalization mode) and consistent values for the number of elements over which to compute the transforms. + Applying the one-dimensional inverse discrete Fourier transform for real-valued input to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e., ``irfft(rfft(x)) == x``), provided that the transform and inverse transform are performed with the same arguments (axis and normalization mode) and consistent values for the number of elements over which to compute the transforms. Parameters ---------- x: array - input array. Must have a real-valued floating-point data type. + input array. Must have a real-valued floating-point data type. n: Optional[int] - number of elements over which to compute the transform along the axis (dimension) specified by ``axis``. Let ``M`` be the size of the input array along the axis specified by ``axis``. When ``n`` is ``None``, the function must set ``n`` equal to ``M``. + number of elements over which to compute the transform along the axis (dimension) specified by ``axis``. Let ``M`` be the size of the input array along the axis specified by ``axis``. When ``n`` is ``None``, the function must set ``n`` equal to ``M``. - - If ``n`` is greater than ``M``, the axis specified by ``axis`` must be zero-padded to size ``n``. - - If ``n`` is less than ``M``, the axis specified by ``axis`` must be trimmed to size ``n``. - - If ``n`` equals ``M``, all elements along the axis specified by ``axis`` must be used when computing the transform. + - If ``n`` is greater than ``M``, the axis specified by ``axis`` must be zero-padded to size ``n``. + - If ``n`` is less than ``M``, the axis specified by ``axis`` must be trimmed to size ``n``. + - If ``n`` equals ``M``, all elements along the axis specified by ``axis`` must be used when computing the transform. - Default: ``None``. + Default: ``None``. axis: int - axis (dimension) of the input array over which to compute the transform. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). Default: ``-1``. + axis (dimension) of the input array over which to compute the transform. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). Default: ``-1``. norm: Literal['backward', 'ortho', 'forward'] - normalization mode. Should be one of the following modes: + normalization mode. Should be one of the following modes: - - ``'backward'``: no normalization. - - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). - - ``'forward'``: normalize by ``1/n``. + - ``'backward'``: no normalization. + - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). + - ``'forward'``: normalize by ``1/n``. - Default: ``'backward'``. + Default: ``'backward'``. Returns ------- out: array - an array transformed along the axis (dimension) specified by ``axis``. The returned array must have a complex floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``float64``, then the returned array must have a ``complex128`` data type). The returned array must have the same shape as ``x``, except for the axis specified by ``axis`` which must have size ``n//2 + 1``. + an array transformed along the axis (dimension) specified by ``axis``. The returned array must have a complex floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``float64``, then the returned array must have a ``complex128`` data type). The returned array must have the same shape as ``x``, except for the axis specified by ``axis`` which must have size ``n//2 + 1``. Notes ----- @@ -6405,35 +6409,35 @@ class irfft[TArray: Array](Protocol): Computes the one-dimensional inverse of ``rfft`` for complex-valued input. .. note:: - Applying the one-dimensional inverse discrete Fourier transform for real-valued input to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e., ``irfft(rfft(x)) == x``), provided that the transform and inverse transform are performed with the same arguments (axis and normalization mode) and consistent values for the number of elements over which to compute the transforms. + Applying the one-dimensional inverse discrete Fourier transform for real-valued input to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e., ``irfft(rfft(x)) == x``), provided that the transform and inverse transform are performed with the same arguments (axis and normalization mode) and consistent values for the number of elements over which to compute the transforms. Parameters ---------- x: array - input array. Should have a complex floating-point data type. + input array. Should have a complex floating-point data type. n: Optional[int] - number of elements along the transformed axis (dimension) specified by ``axis`` in the **output array**. Let ``M`` be the size of the input array along the axis specified by ``axis``. When ``n`` is ``None``, the function must set ``n`` equal to ``2*(M-1)``. + number of elements along the transformed axis (dimension) specified by ``axis`` in the **output array**. Let ``M`` be the size of the input array along the axis specified by ``axis``. When ``n`` is ``None``, the function must set ``n`` equal to ``2*(M-1)``. - - If ``n//2+1`` is greater than ``M``, the axis of the input array specified by ``axis`` must be zero-padded to size ``n//2+1``. - - If ``n//2+1`` is less than ``M``, the axis of the input array specified by ``axis`` must be trimmed to size ``n//2+1``. - - If ``n//2+1`` equals ``M``, all elements along the axis of the input array specified by ``axis`` must be used when computing the transform. + - If ``n//2+1`` is greater than ``M``, the axis of the input array specified by ``axis`` must be zero-padded to size ``n//2+1``. + - If ``n//2+1`` is less than ``M``, the axis of the input array specified by ``axis`` must be trimmed to size ``n//2+1``. + - If ``n//2+1`` equals ``M``, all elements along the axis of the input array specified by ``axis`` must be used when computing the transform. - Default: ``None``. + Default: ``None``. axis: int - axis (dimension) of the input array over which to compute the transform. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). Default: ``-1``. + axis (dimension) of the input array over which to compute the transform. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). Default: ``-1``. norm: Literal['backward', 'ortho', 'forward'] - normalization mode. Should be one of the following modes: + normalization mode. Should be one of the following modes: - - ``'backward'``: normalize by ``1/n``. - - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). - - ``'forward'``: no normalization. + - ``'backward'``: normalize by ``1/n``. + - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). + - ``'forward'``: no normalization. - Default: ``'backward'``. + Default: ``'backward'``. Returns ------- out: array - an array transformed along the axis (dimension) specified by ``axis``. The returned array must have a real-valued floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``complex128``, then the returned array must have a ``float64`` data type). The returned array must have the same shape as ``x``, except for the axis specified by ``axis`` which must have size ``n``. + an array transformed along the axis (dimension) specified by ``axis``. The returned array must have a real-valued floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``complex128``, then the returned array must have a ``float64`` data type). The returned array must have the same shape as ``x``, except for the axis specified by ``axis`` which must have size ``n``. Notes ----- @@ -6453,41 +6457,41 @@ class rfftn[TArray: Array](Protocol): Computes the n-dimensional discrete Fourier transform for real-valued input. .. note:: - Applying the n-dimensional inverse discrete Fourier transform for real-valued input to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e., ``irfftn(rfftn(x)) == x``), provided that the transform and inverse transform are performed with the same arguments (axes and normalization mode) and consistent sizes. + Applying the n-dimensional inverse discrete Fourier transform for real-valued input to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e., ``irfftn(rfftn(x)) == x``), provided that the transform and inverse transform are performed with the same arguments (axes and normalization mode) and consistent sizes. Parameters ---------- x: array - input array. Must have a real-valued floating-point data type. + input array. Must have a real-valued floating-point data type. s: Optional[Sequence[int]] - number of elements over which to compute the transform along axes (dimensions) specified by ``axes``. Let ``i`` be the index of the ``n``-th axis specified by ``axes`` (i.e., ``i = axes[n]``) and ``M[i]`` be the size of the input array along axis ``i``. When ``s`` is ``None``, the function must set ``s`` equal to a sequence of integers such that ``s[i]`` equals ``M[i]`` for all ``i``. + number of elements over which to compute the transform along axes (dimensions) specified by ``axes``. Let ``i`` be the index of the ``n``-th axis specified by ``axes`` (i.e., ``i = axes[n]``) and ``M[i]`` be the size of the input array along axis ``i``. When ``s`` is ``None``, the function must set ``s`` equal to a sequence of integers such that ``s[i]`` equals ``M[i]`` for all ``i``. - - If ``s[i]`` is greater than ``M[i]``, axis ``i`` must be zero-padded to size ``s[i]``. - - If ``s[i]`` is less than ``M[i]``, axis ``i`` must be trimmed to size ``s[i]``. - - If ``s[i]`` equals ``M[i]`` or ``-1``, all elements along axis ``i`` must be used when computing the transform. + - If ``s[i]`` is greater than ``M[i]``, axis ``i`` must be zero-padded to size ``s[i]``. + - If ``s[i]`` is less than ``M[i]``, axis ``i`` must be trimmed to size ``s[i]``. + - If ``s[i]`` equals ``M[i]`` or ``-1``, all elements along axis ``i`` must be used when computing the transform. - If ``s`` is not ``None``, ``axes`` must not be ``None``. Default: ``None``. + If ``s`` is not ``None``, ``axes`` must not be ``None``. Default: ``None``. axes: Optional[Sequence[int]] - axes (dimensions) over which to compute the transform. A valid axis in ``axes`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an axis is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). + axes (dimensions) over which to compute the transform. A valid axis in ``axes`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an axis is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). - If ``s`` is provided, the corresponding ``axes`` to be transformed must also be provided. If ``axes`` is ``None``, the function must compute the transform over all axes. Default: ``None``. + If ``s`` is provided, the corresponding ``axes`` to be transformed must also be provided. If ``axes`` is ``None``, the function must compute the transform over all axes. Default: ``None``. - If ``axes`` contains two or more entries which resolve to the same axis (i.e., resolved axes are not unique), the behavior is unspecified and thus implementation-defined. + If ``axes`` contains two or more entries which resolve to the same axis (i.e., resolved axes are not unique), the behavior is unspecified and thus implementation-defined. norm: Literal['backward', 'ortho', 'forward'] - normalization mode. Should be one of the following modes: + normalization mode. Should be one of the following modes: - - ``'backward'``: no normalization. - - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). - - ``'forward'``: normalize by ``1/n``. + - ``'backward'``: no normalization. + - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). + - ``'forward'``: normalize by ``1/n``. - where ``n = prod(s)``, the logical FFT size. + where ``n = prod(s)``, the logical FFT size. - Default: ``'backward'``. + Default: ``'backward'``. Returns ------- out: array - an array transformed along the axes (dimension) specified by ``axes``. The returned array must have a complex floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``float64``, then the returned array must have a ``complex128`` data type). The returned array must have the same shape as ``x``, except for the last transformed axis which must have size ``s[-1]//2 + 1`` and the remaining transformed axes which must have size ``s[i]``. + an array transformed along the axes (dimension) specified by ``axes``. The returned array must have a complex floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``float64``, then the returned array must have a ``complex128`` data type). The returned array must have the same shape as ``x``, except for the last transformed axis which must have size ``s[-1]//2 + 1`` and the remaining transformed axes which must have size ``s[i]``. Notes ----- @@ -6506,41 +6510,41 @@ class irfftn[TArray: Array](Protocol): Computes the n-dimensional inverse of ``rfftn`` for complex-valued input. .. note:: - Applying the n-dimensional inverse discrete Fourier transform for real-valued input to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e., ``irfftn(rfftn(x)) == x``), provided that the transform and inverse transform are performed with the same arguments (axes and normalization mode) and consistent sizes. + Applying the n-dimensional inverse discrete Fourier transform for real-valued input to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e., ``irfftn(rfftn(x)) == x``), provided that the transform and inverse transform are performed with the same arguments (axes and normalization mode) and consistent sizes. Parameters ---------- x: array - input array. Should have a complex floating-point data type. + input array. Should have a complex floating-point data type. s: Optional[Sequence[int]] - number of elements along the transformed axes (dimensions) specified by ``axes`` in the **output array**. Let ``i`` be the index of the ``n``-th axis specified by ``axes`` (i.e., ``i = axes[n]``) and ``M[i]`` be the size of the input array along axis ``i``. When ``s`` is ``None``, the function must set ``s`` equal to a sequence of integers such that ``s[i]`` equals ``M[i]`` for all ``i``, except for the last transformed axis in which ``s[i]`` equals ``2*(M[i]-1)``. For each ``i``, let ``n`` equal ``s[i]``, except for the last transformed axis in which ``n`` equals ``s[i]//2+1``. + number of elements along the transformed axes (dimensions) specified by ``axes`` in the **output array**. Let ``i`` be the index of the ``n``-th axis specified by ``axes`` (i.e., ``i = axes[n]``) and ``M[i]`` be the size of the input array along axis ``i``. When ``s`` is ``None``, the function must set ``s`` equal to a sequence of integers such that ``s[i]`` equals ``M[i]`` for all ``i``, except for the last transformed axis in which ``s[i]`` equals ``2*(M[i]-1)``. For each ``i``, let ``n`` equal ``s[i]``, except for the last transformed axis in which ``n`` equals ``s[i]//2+1``. - - If ``n`` is greater than ``M[i]``, axis ``i`` of the input array must be zero-padded to size ``n``. - - If ``n`` is less than ``M[i]``, axis ``i`` of the input array must be trimmed to size ``n``. - - If ``n`` equals ``M[i]`` or ``-1``, all elements along axis ``i`` of the input array must be used when computing the transform. + - If ``n`` is greater than ``M[i]``, axis ``i`` of the input array must be zero-padded to size ``n``. + - If ``n`` is less than ``M[i]``, axis ``i`` of the input array must be trimmed to size ``n``. + - If ``n`` equals ``M[i]`` or ``-1``, all elements along axis ``i`` of the input array must be used when computing the transform. - If ``s`` is not ``None``, ``axes`` must not be ``None``. Default: ``None``. + If ``s`` is not ``None``, ``axes`` must not be ``None``. Default: ``None``. axes: Optional[Sequence[int]] - axes (dimensions) over which to compute the transform. A valid axis in ``axes`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an axis is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). + axes (dimensions) over which to compute the transform. A valid axis in ``axes`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an axis is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). - If ``s`` is provided, the corresponding ``axes`` to be transformed must also be provided. If ``axes`` is ``None``, the function must compute the transform over all axes. Default: ``None``. + If ``s`` is provided, the corresponding ``axes`` to be transformed must also be provided. If ``axes`` is ``None``, the function must compute the transform over all axes. Default: ``None``. - If ``axes`` contains two or more entries which resolve to the same axis (i.e., resolved axes are not unique), the behavior is unspecified and thus implementation-defined. + If ``axes`` contains two or more entries which resolve to the same axis (i.e., resolved axes are not unique), the behavior is unspecified and thus implementation-defined. norm: Literal['backward', 'ortho', 'forward'] - normalization mode. Should be one of the following modes: + normalization mode. Should be one of the following modes: - - ``'backward'``: normalize by ``1/n``. - - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). - - ``'forward'``: no normalization. + - ``'backward'``: normalize by ``1/n``. + - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). + - ``'forward'``: no normalization. - where ``n = prod(s)`` is the logical FFT size. + where ``n = prod(s)`` is the logical FFT size. - Default: ``'backward'``. + Default: ``'backward'``. Returns ------- out: array - an array transformed along the axes (dimension) specified by ``axes``. The returned array must have a real-valued floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``complex128``, then the returned array must have a ``float64`` data type). The returned array must have the same shape as ``x``, except for the transformed axes which must have size ``s[i]``. + an array transformed along the axes (dimension) specified by ``axes``. The returned array must have a real-valued floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``complex128``, then the returned array must have a ``float64`` data type). The returned array must have the same shape as ``x``, except for the transformed axes which must have size ``s[i]``. Notes ----- @@ -6562,30 +6566,30 @@ class hfft[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a complex floating-point data type. + input array. Should have a complex floating-point data type. n: Optional[int] - number of elements along the transformed axis (dimension) specified by ``axis`` in the **output array**. Let ``M`` be the size of the input array along the axis specified by ``axis``. When ``n`` is ``None``, the function must set ``n`` equal to ``2*(M-1)``. + number of elements along the transformed axis (dimension) specified by ``axis`` in the **output array**. Let ``M`` be the size of the input array along the axis specified by ``axis``. When ``n`` is ``None``, the function must set ``n`` equal to ``2*(M-1)``. - - If ``n//2+1`` is greater than ``M``, the axis of the input array specified by ``axis`` must be zero-padded to length ``n//2+1``. - - If ``n//2+1`` is less than ``M``, the axis of the input array specified by ``axis`` must be trimmed to size ``n//2+1``. - - If ``n//2+1`` equals ``M``, all elements along the axis of the input array specified by ``axis`` must be used when computing the transform. + - If ``n//2+1`` is greater than ``M``, the axis of the input array specified by ``axis`` must be zero-padded to length ``n//2+1``. + - If ``n//2+1`` is less than ``M``, the axis of the input array specified by ``axis`` must be trimmed to size ``n//2+1``. + - If ``n//2+1`` equals ``M``, all elements along the axis of the input array specified by ``axis`` must be used when computing the transform. - Default: ``None``. + Default: ``None``. axis: int - axis (dimension) of the input array over which to compute the transform. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). Default: ``-1``. + axis (dimension) of the input array over which to compute the transform. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). Default: ``-1``. norm: Literal['backward', 'ortho', 'forward'] - normalization mode. Should be one of the following modes: + normalization mode. Should be one of the following modes: - - ``'backward'``: no normalization. - - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). - - ``'forward'``: normalize by ``1/n``. + - ``'backward'``: no normalization. + - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). + - ``'forward'``: normalize by ``1/n``. - Default: ``'backward'``. + Default: ``'backward'``. Returns ------- out: array - an array transformed along the axis (dimension) specified by ``axis``. The returned array must have a real-valued floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``complex128``, then the returned array must have a ``float64`` data type). The returned array must have the same shape as ``x``, except for the axis specified by ``axis`` which must have size ``n``. + an array transformed along the axis (dimension) specified by ``axis``. The returned array must have a real-valued floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``complex128``, then the returned array must have a ``float64`` data type). The returned array must have the same shape as ``x``, except for the axis specified by ``axis`` which must have size ``n``. Notes ----- @@ -6606,30 +6610,30 @@ class ihfft[TArray: Array](Protocol): Parameters ---------- x: array - input array. Must have a real-valued floating-point data type. + input array. Must have a real-valued floating-point data type. n: Optional[int] - number of elements over which to compute the transform along the axis (dimension) specified by ``axis``. Let ``M`` be the size of the input array along the axis specified by ``axis``. When ``n`` is ``None``, the function must set ``n`` equal to ``M``. + number of elements over which to compute the transform along the axis (dimension) specified by ``axis``. Let ``M`` be the size of the input array along the axis specified by ``axis``. When ``n`` is ``None``, the function must set ``n`` equal to ``M``. - - If ``n`` is greater than ``M``, the axis specified by ``axis`` must be zero-padded to size ``n``. - - If ``n`` is less than ``M``, the axis specified by ``axis`` must be trimmed to size ``n``. - - If ``n`` equals ``M``, all elements along the axis specified by ``axis`` must be used when computing the transform. + - If ``n`` is greater than ``M``, the axis specified by ``axis`` must be zero-padded to size ``n``. + - If ``n`` is less than ``M``, the axis specified by ``axis`` must be trimmed to size ``n``. + - If ``n`` equals ``M``, all elements along the axis specified by ``axis`` must be used when computing the transform. - Default: ``None``. + Default: ``None``. axis: int - axis (dimension) of the input array over which to compute the transform. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). Default: ``-1``. + axis (dimension) of the input array over which to compute the transform. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). Default: ``-1``. norm: Literal['backward', 'ortho', 'forward'] - normalization mode. Should be one of the following modes: + normalization mode. Should be one of the following modes: - - ``'backward'``: normalize by ``1/n``. - - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). - - ``'forward'``: no normalization. + - ``'backward'``: normalize by ``1/n``. + - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). + - ``'forward'``: no normalization. - Default: ``'backward'``. + Default: ``'backward'``. Returns ------- out: array - an array transformed along the axis (dimension) specified by ``axis``. The returned array must have a complex floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``float64``, then the returned array must have a ``complex128`` data type). The returned array must have the same shape as ``x``, except for the axis specified by ``axis`` which must have size ``n//2 + 1``. + an array transformed along the axis (dimension) specified by ``axis``. The returned array must have a complex floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``float64``, then the returned array must have a ``complex128`` data type). The returned array must have the same shape as ``x``, except for the axis specified by ``axis`` which must have size ``n//2 + 1``. Notes ----- @@ -6651,22 +6655,22 @@ class fftfreq[TArray: Array, TDevice](Protocol): .. code-block:: - f = [0, 1, ..., n/2-1, -n/2, ..., -1] / (d*n) # if n is even - f = [0, 1, ..., (n-1)/2, -(n-1)/2, ..., -1] / (d*n) # if n is odd + f = [0, 1, ..., n/2-1, -n/2, ..., -1] / (d*n) # if n is even + f = [0, 1, ..., (n-1)/2, -(n-1)/2, ..., -1] / (d*n) # if n is odd Parameters ---------- n: int - window length. + window length. d: float - sample spacing between individual samples of the Fourier transform input. Default: ``1.0``. + sample spacing between individual samples of the Fourier transform input. Default: ``1.0``. device: Optional[device] - device on which to place the created array. Default: ``None``. + device on which to place the created array. Default: ``None``. Returns ------- out: array - an array of shape ``(n,)`` containing the sample frequencies. The returned array must have the default real-valued floating-point data type. + an array of shape ``(n,)`` containing the sample frequencies. The returned array must have the default real-valued floating-point data type. Notes ----- @@ -6688,24 +6692,24 @@ class rfftfreq[TArray: Array, TDevice](Protocol): .. code-block:: - f = [0, 1, ..., n/2-1, n/2] / (d*n) # if n is even - f = [0, 1, ..., (n-1)/2-1, (n-1)/2] / (d*n) # if n is odd + f = [0, 1, ..., n/2-1, n/2] / (d*n) # if n is even + f = [0, 1, ..., (n-1)/2-1, (n-1)/2] / (d*n) # if n is odd The Nyquist frequency component is considered to be positive. Parameters ---------- n: int - window length. + window length. d: float - sample spacing between individual samples of the Fourier transform input. Default: ``1.0``. + sample spacing between individual samples of the Fourier transform input. Default: ``1.0``. device: Optional[device] - device on which to place the created array. Default: ``None``. + device on which to place the created array. Default: ``None``. Returns ------- out: array - an array of shape ``(n//2+1,)`` containing the sample frequencies. The returned array must have the default real-valued floating-point data type. + an array of shape ``(n//2+1,)`` containing the sample frequencies. The returned array must have the default real-valued floating-point data type. Notes ----- @@ -6726,21 +6730,21 @@ class fftshift[TArray: Array](Protocol): This function swaps half-spaces for all axes (dimensions) specified by ``axes``. .. note:: - ``out[0]`` is the Nyquist component only if the length of the input is even. + ``out[0]`` is the Nyquist component only if the length of the input is even. Parameters ---------- x: array - input array. Should have a floating-point data type. + input array. Should have a floating-point data type. axes: Optional[Union[int, Sequence[int]]] - axes over which to shift. If ``None``, the function must shift all axes. Default: ``None``. + axes over which to shift. If ``None``, the function must shift all axes. Default: ``None``. - If ``axes`` contains two or more entries which resolve to the same axis (i.e., resolved axes are not unique), the behavior is unspecified and thus implementation-defined. + If ``axes`` contains two or more entries which resolve to the same axis (i.e., resolved axes are not unique), the behavior is unspecified and thus implementation-defined. Returns ------- out: array - the shifted array. The returned array must have the same data type and shape as ``x``. + the shifted array. The returned array must have the same data type and shape as ``x``. Notes ----- @@ -6759,21 +6763,21 @@ class ifftshift[TArray: Array](Protocol): Inverse of ``fftshift``. .. note:: - Although identical for even-length ``x``, ``fftshift`` and ``ifftshift`` differ by one sample for odd-length ``x``. + Although identical for even-length ``x``, ``fftshift`` and ``ifftshift`` differ by one sample for odd-length ``x``. Parameters ---------- x: array - input array. Should have a floating-point data type. + input array. Should have a floating-point data type. axes: Optional[Union[int, Sequence[int]]] - axes over which to perform the inverse shift. If ``None``, the function must shift all axes. Default: ``None``. + axes over which to perform the inverse shift. If ``None``, the function must shift all axes. Default: ``None``. - If ``axes`` contains two or more entries which resolve to the same axis (i.e., resolved axes are not unique), the behavior is unspecified and thus implementation-defined. + If ``axes`` contains two or more entries which resolve to the same axis (i.e., resolved axes are not unique), the behavior is unspecified and thus implementation-defined. Returns ------- out: array - the shifted array. The returned array must have the same data type and shape as ``x``. + the shifted array. The returned array must have the same data type and shape as ``x``. Notes ----- @@ -6792,37 +6796,37 @@ class matmul[TArray: Array](Protocol): Computes the matrix product. .. note:: - The ``matmul`` function must implement the same semantics as the built-in ``@`` operator (see `PEP 465 `_). + The ``matmul`` function must implement the same semantics as the built-in ``@`` operator (see `PEP 465 `_). Parameters ---------- x1: array - first input array. Should have a numeric data type. Must have at least one dimension. If ``x1`` is one-dimensional having shape ``(M,)`` and ``x2`` has more than one dimension, ``x1`` must be promoted to a two-dimensional array by prepending ``1`` to its dimensions (i.e., must have shape ``(1, M)``). After matrix multiplication, the prepended dimensions in the returned array must be removed. If ``x1`` has more than one dimension (including after vector-to-matrix promotion), ``shape(x1)[:-2]`` must be compatible with ``shape(x2)[:-2]`` (after vector-to-matrix promotion) (see :ref:`broadcasting`). If ``x1`` has shape ``(..., M, K)``, the innermost two dimensions form matrices on which to perform matrix multiplication. + first input array. Should have a numeric data type. Must have at least one dimension. If ``x1`` is one-dimensional having shape ``(M,)`` and ``x2`` has more than one dimension, ``x1`` must be promoted to a two-dimensional array by prepending ``1`` to its dimensions (i.e., must have shape ``(1, M)``). After matrix multiplication, the prepended dimensions in the returned array must be removed. If ``x1`` has more than one dimension (including after vector-to-matrix promotion), ``shape(x1)[:-2]`` must be compatible with ``shape(x2)[:-2]`` (after vector-to-matrix promotion) (see :ref:`broadcasting`). If ``x1`` has shape ``(..., M, K)``, the innermost two dimensions form matrices on which to perform matrix multiplication. x2: array - second input array. Should have a numeric data type. Must have at least one dimension. If ``x2`` is one-dimensional having shape ``(N,)`` and ``x1`` has more than one dimension, ``x2`` must be promoted to a two-dimensional array by appending ``1`` to its dimensions (i.e., must have shape ``(N, 1)``). After matrix multiplication, the appended dimensions in the returned array must be removed. If ``x2`` has more than one dimension (including after vector-to-matrix promotion), ``shape(x2)[:-2]`` must be compatible with ``shape(x1)[:-2]`` (after vector-to-matrix promotion) (see :ref:`broadcasting`). If ``x2`` has shape ``(..., K, N)``, the innermost two dimensions form matrices on which to perform matrix multiplication. + second input array. Should have a numeric data type. Must have at least one dimension. If ``x2`` is one-dimensional having shape ``(N,)`` and ``x1`` has more than one dimension, ``x2`` must be promoted to a two-dimensional array by appending ``1`` to its dimensions (i.e., must have shape ``(N, 1)``). After matrix multiplication, the appended dimensions in the returned array must be removed. If ``x2`` has more than one dimension (including after vector-to-matrix promotion), ``shape(x2)[:-2]`` must be compatible with ``shape(x1)[:-2]`` (after vector-to-matrix promotion) (see :ref:`broadcasting`). If ``x2`` has shape ``(..., K, N)``, the innermost two dimensions form matrices on which to perform matrix multiplication. .. note:: - If either ``x1`` or ``x2`` has a complex floating-point data type, neither argument must be complex-conjugated or transposed. If conjugation and/or transposition is desired, these operations should be explicitly performed prior to computing the matrix product. + If either ``x1`` or ``x2`` has a complex floating-point data type, neither argument must be complex-conjugated or transposed. If conjugation and/or transposition is desired, these operations should be explicitly performed prior to computing the matrix product. Returns ------- out: array - - if both ``x1`` and ``x2`` are one-dimensional arrays having shape ``(N,)``, a zero-dimensional array containing the inner product as its only element. - - if ``x1`` is a two-dimensional array having shape ``(M, K)`` and ``x2`` is a two-dimensional array having shape ``(K, N)``, a two-dimensional array containing the `conventional matrix product `_ and having shape ``(M, N)``. - - if ``x1`` is a one-dimensional array having shape ``(K,)`` and ``x2`` is an array having shape ``(..., K, N)``, an array having shape ``(..., N)`` (i.e., prepended dimensions during vector-to-matrix promotion must be removed) and containing the `conventional matrix product `_. - - if ``x1`` is an array having shape ``(..., M, K)`` and ``x2`` is a one-dimensional array having shape ``(K,)``, an array having shape ``(..., M)`` (i.e., appended dimensions during vector-to-matrix promotion must be removed) and containing the `conventional matrix product `_. - - if ``x1`` is a two-dimensional array having shape ``(M, K)`` and ``x2`` is an array having shape ``(..., K, N)``, an array having shape ``(..., M, N)`` and containing the `conventional matrix product `_ for each stacked matrix. - - if ``x1`` is an array having shape ``(..., M, K)`` and ``x2`` is a two-dimensional array having shape ``(K, N)``, an array having shape ``(..., M, N)`` and containing the `conventional matrix product `_ for each stacked matrix. - - if either ``x1`` or ``x2`` has more than two dimensions, an array having a shape determined by :ref:`broadcasting` ``shape(x1)[:-2]`` against ``shape(x2)[:-2]`` and containing the `conventional matrix product `_ for each stacked matrix. + - if both ``x1`` and ``x2`` are one-dimensional arrays having shape ``(N,)``, a zero-dimensional array containing the inner product as its only element. + - if ``x1`` is a two-dimensional array having shape ``(M, K)`` and ``x2`` is a two-dimensional array having shape ``(K, N)``, a two-dimensional array containing the `conventional matrix product `_ and having shape ``(M, N)``. + - if ``x1`` is a one-dimensional array having shape ``(K,)`` and ``x2`` is an array having shape ``(..., K, N)``, an array having shape ``(..., N)`` (i.e., prepended dimensions during vector-to-matrix promotion must be removed) and containing the `conventional matrix product `_. + - if ``x1`` is an array having shape ``(..., M, K)`` and ``x2`` is a one-dimensional array having shape ``(K,)``, an array having shape ``(..., M)`` (i.e., appended dimensions during vector-to-matrix promotion must be removed) and containing the `conventional matrix product `_. + - if ``x1`` is a two-dimensional array having shape ``(M, K)`` and ``x2`` is an array having shape ``(..., K, N)``, an array having shape ``(..., M, N)`` and containing the `conventional matrix product `_ for each stacked matrix. + - if ``x1`` is an array having shape ``(..., M, K)`` and ``x2`` is a two-dimensional array having shape ``(K, N)``, an array having shape ``(..., M, N)`` and containing the `conventional matrix product `_ for each stacked matrix. + - if either ``x1`` or ``x2`` has more than two dimensions, an array having a shape determined by :ref:`broadcasting` ``shape(x1)[:-2]`` against ``shape(x2)[:-2]`` and containing the `conventional matrix product `_ for each stacked matrix. - The returned array must have a data type determined by :ref:`type-promotion`. + The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. **Raises** @@ -6846,12 +6850,12 @@ class matrix_transpose[TArray: Array](Protocol): Parameters ---------- x: array - input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. + input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. Returns ------- out: array - an array containing the transpose for each matrix and having shape ``(..., N, M)``. The returned array must have the same data type as ``x``. + an array containing the transpose for each matrix and having shape ``(..., N, M)``. The returned array must have the same data type as ``x``. """ @@ -6865,43 +6869,43 @@ class tensordot[TArray: Array](Protocol): Returns a tensor contraction of ``x1`` and ``x2`` over specific axes. .. note:: - The ``tensordot`` function corresponds to the generalized matrix product. + The ``tensordot`` function corresponds to the generalized matrix product. Parameters ---------- x1: array - first input array. Should have a numeric data type. + first input array. Should have a numeric data type. x2: array - second input array. Should have a numeric data type. Corresponding contracted axes of ``x1`` and ``x2`` must be equal. + second input array. Should have a numeric data type. Corresponding contracted axes of ``x1`` and ``x2`` must be equal. - .. note:: - Contracted axes (dimensions) must not be broadcasted. + .. note:: + Contracted axes (dimensions) must not be broadcasted. axes: Union[int, Tuple[Sequence[int], Sequence[int]]] - number of axes (dimensions) to contract or explicit sequences of axes (dimensions) for ``x1`` and ``x2``, respectively. + number of axes (dimensions) to contract or explicit sequences of axes (dimensions) for ``x1`` and ``x2``, respectively. - If ``axes`` is an ``int`` equal to ``N``, then contraction must be performed over the last ``N`` axes of ``x1`` and the first ``N`` axes of ``x2`` in order. The size of each corresponding axis (dimension) must match. Must be nonnegative. + If ``axes`` is an ``int`` equal to ``N``, then contraction must be performed over the last ``N`` axes of ``x1`` and the first ``N`` axes of ``x2`` in order. The size of each corresponding axis (dimension) must match. Must be nonnegative. - - If ``N`` equals ``0``, the result is the tensor (outer) product. - - If ``N`` equals ``1``, the result is the tensor dot product. - - If ``N`` equals ``2``, the result is the tensor double contraction (default). + - If ``N`` equals ``0``, the result is the tensor (outer) product. + - If ``N`` equals ``1``, the result is the tensor dot product. + - If ``N`` equals ``2``, the result is the tensor double contraction (default). - If ``axes`` is a tuple of two sequences ``(x1_axes, x2_axes)``, the first sequence must apply to ``x1`` and the second sequence to ``x2``. Both sequences must have the same length. Each axis (dimension) ``x1_axes[i]`` for ``x1`` must have the same size as the respective axis (dimension) ``x2_axes[i]`` for ``x2``. Each sequence must consist of unique (nonnegative) integers that specify valid axes for each respective array. + If ``axes`` is a tuple of two sequences ``(x1_axes, x2_axes)``, the first sequence must apply to ``x1`` and the second sequence to ``x2``. Both sequences must have the same length. Each axis (dimension) ``x1_axes[i]`` for ``x1`` must have the same size as the respective axis (dimension) ``x2_axes[i]`` for ``x2``. Each sequence must consist of unique (nonnegative) integers that specify valid axes for each respective array. .. note:: - If either ``x1`` or ``x2`` has a complex floating-point data type, neither argument must be complex-conjugated or transposed. If conjugation and/or transposition is desired, these operations should be explicitly performed prior to computing the generalized matrix product. + If either ``x1`` or ``x2`` has a complex floating-point data type, neither argument must be complex-conjugated or transposed. If conjugation and/or transposition is desired, these operations should be explicitly performed prior to computing the generalized matrix product. Returns ------- out: array - an array containing the tensor contraction whose shape consists of the non-contracted axes (dimensions) of the first array ``x1``, followed by the non-contracted axes (dimensions) of the second array ``x2``. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the tensor contraction whose shape consists of the non-contracted axes (dimensions) of the first array ``x1``, followed by the non-contracted axes (dimensions) of the second array ``x2``. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -6917,33 +6921,33 @@ class vecdot[TArray: Array](Protocol): Let :math:`\\mathbf{a}` be a vector in ``x1`` and :math:`\\mathbf{b}` be a corresponding vector in ``x2``. The dot product is defined as .. math:: - \\mathbf{a} \\cdot \\mathbf{b} = \\sum_{i=0}^{n-1} \\overline{a_i}b_i + \\mathbf{a} \\cdot \\mathbf{b} = \\sum_{i=0}^{n-1} \\overline{a_i}b_i over the dimension specified by ``axis`` and where :math:`n` is the dimension size and :math:`\\overline{a_i}` denotes the complex conjugate if :math:`a_i` is complex and the identity if :math:`a_i` is real-valued. Parameters ---------- x1: array - first input array. Should have a floating-point data type. + first input array. Should have a floating-point data type. x2: array - second input array. Must be compatible with ``x1`` for all non-contracted axes (see :ref:`broadcasting`). The size of the axis over which to compute the dot product must be the same size as the respective axis in ``x1``. Should have a floating-point data type. + second input array. Must be compatible with ``x1`` for all non-contracted axes (see :ref:`broadcasting`). The size of the axis over which to compute the dot product must be the same size as the respective axis in ``x1``. Should have a floating-point data type. - .. note:: - The contracted axis (dimension) must not be broadcasted. + .. note:: + The contracted axis (dimension) must not be broadcasted. axis: int - axis over which to compute the dot product. Must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of the shape determined according to :ref:`broadcasting`. If specified as a negative integer, the function must determine the axis along which to compute the dot product by counting backward from the last dimension (where ``-1`` refers to the last dimension). By default, the function must compute the dot product over the last axis. Default: ``-1``. + axis over which to compute the dot product. Must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of the shape determined according to :ref:`broadcasting`. If specified as a negative integer, the function must determine the axis along which to compute the dot product by counting backward from the last dimension (where ``-1`` refers to the last dimension). By default, the function must compute the dot product over the last axis. Default: ``-1``. Returns ------- out: array - if ``x1`` and ``x2`` are both one-dimensional arrays, a zero-dimensional containing the dot product; otherwise, a non-zero-dimensional array containing the dot products and having rank ``N-1``, where ``N`` is the rank (number of dimensions) of the shape determined according to :ref:`broadcasting` along the non-contracted axes. The returned array must have a data type determined by :ref:`type-promotion`. + if ``x1`` and ``x2`` are both one-dimensional arrays, a zero-dimensional containing the dot product; otherwise, a non-zero-dimensional array containing the dot products and having rank ``N-1``, where ``N`` is the rank (number of dimensions) of the shape determined according to :ref:`broadcasting` along the non-contracted axes. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. **Raises** @@ -6964,12 +6968,12 @@ class broadcast_arrays[TArray: Array](Protocol): Parameters ---------- arrays: array - an arbitrary number of to-be broadcasted arrays. + an arbitrary number of to-be broadcasted arrays. Returns ------- out: List[array] - a list of broadcasted arrays. Each array must have the same shape. Each array must have the same dtype as its corresponding input array. + a list of broadcasted arrays. Each array must have the same shape. Each array must have the same dtype as its corresponding input array. """ @@ -6985,14 +6989,14 @@ class broadcast_to[TArray: Array](Protocol): Parameters ---------- x: array - array to broadcast. + array to broadcast. shape: Tuple[int, ...] - array shape. Must be compatible with ``x`` (see :ref:`broadcasting`). If the array is incompatible with the specified shape, the function should raise an exception. + array shape. Must be compatible with ``x`` (see :ref:`broadcasting`). If the array is incompatible with the specified shape, the function should raise an exception. Returns ------- out: array - an array having a specified shape. Must have the same data type as ``x``. + an array having a specified shape. Must have the same data type as ``x``. """ @@ -7008,17 +7012,17 @@ class concat[TArray: Array](Protocol): Parameters ---------- arrays: Union[Tuple[array, ...], List[array]] - input arrays to join. The arrays must have the same shape, except in the dimension specified by ``axis``. + input arrays to join. The arrays must have the same shape, except in the dimension specified by ``axis``. axis: Optional[int] - axis along which the arrays will be joined. If ``axis`` is ``None``, arrays must be flattened before concatenation. If ``axis`` is negative, the function must determine the axis along which to join by counting from the last dimension. Default: ``0``. + axis along which the arrays will be joined. If ``axis`` is ``None``, arrays must be flattened before concatenation. If ``axis`` is negative, the function must determine the axis along which to join by counting from the last dimension. Default: ``0``. Returns ------- out: array - an output array containing the concatenated values. If the input arrays have different data types, normal :ref:`type-promotion` must apply. If the input arrays have the same data type, the output array must have the same data type as the input arrays. + an output array containing the concatenated values. If the input arrays have different data types, normal :ref:`type-promotion` must apply. If the input arrays have the same data type, the output array must have the same data type as the input arrays. - .. note:: - This specification leaves type promotion between data type families (i.e., ``intxx`` and ``floatxx``) unspecified. + .. note:: + This specification leaves type promotion between data type families (i.e., ``intxx`` and ``floatxx``) unspecified. """ @@ -7034,14 +7038,14 @@ class expand_dims[TArray: Array](Protocol): Parameters ---------- x: array - input array. + input array. axis: int - axis position (zero-based). If ``x`` has rank (i.e, number of dimensions) ``N``, a valid ``axis`` must reside on the closed-interval ``[-N-1, N]``. If provided a negative ``axis``, the axis position at which to insert a singleton dimension must be computed as ``N + axis + 1``. Hence, if provided ``-1``, the resolved axis position must be ``N`` (i.e., a singleton dimension must be appended to the input array ``x``). If provided ``-N-1``, the resolved axis position must be ``0`` (i.e., a singleton dimension must be prepended to the input array ``x``). An ``IndexError`` exception must be raised if provided an invalid ``axis`` position. + axis position (zero-based). If ``x`` has rank (i.e, number of dimensions) ``N``, a valid ``axis`` must reside on the closed-interval ``[-N-1, N]``. If provided a negative ``axis``, the axis position at which to insert a singleton dimension must be computed as ``N + axis + 1``. Hence, if provided ``-1``, the resolved axis position must be ``N`` (i.e., a singleton dimension must be appended to the input array ``x``). If provided ``-N-1``, the resolved axis position must be ``0`` (i.e., a singleton dimension must be prepended to the input array ``x``). An ``IndexError`` exception must be raised if provided an invalid ``axis`` position. Returns ------- out: array - an expanded output array having the same data type as ``x``. + an expanded output array having the same data type as ``x``. """ @@ -7057,14 +7061,14 @@ class flip[TArray: Array](Protocol): Parameters ---------- x: array - input array. + input array. axis: Optional[Union[int, Tuple[int, ...]]] - axis (or axes) along which to flip. If ``axis`` is ``None``, the function must flip all input array axes. If ``axis`` is negative, the function must count from the last dimension. If provided more than one axis, the function must flip only the specified axes. Default: ``None``. + axis (or axes) along which to flip. If ``axis`` is ``None``, the function must flip all input array axes. If ``axis`` is negative, the function must count from the last dimension. If provided more than one axis, the function must flip only the specified axes. Default: ``None``. Returns ------- out: array - an output array having the same data type and shape as ``x`` and whose elements, relative to ``x``, are reordered. + an output array having the same data type and shape as ``x`` and whose elements, relative to ``x``, are reordered. """ @@ -7080,14 +7084,14 @@ class permute_dims[TArray: Array](Protocol): Parameters ---------- x: array - input array. + input array. axes: Tuple[int, ...] - tuple containing a permutation of ``(0, 1, ..., N-1)`` where ``N`` is the number of axes (dimensions) of ``x``. + tuple containing a permutation of ``(0, 1, ..., N-1)`` where ``N`` is the number of axes (dimensions) of ``x``. Returns ------- out: array - an array containing the axes permutation. The returned array must have the same data type as ``x``. + an array containing the axes permutation. The returned array must have the same data type as ``x``. """ @@ -7103,16 +7107,16 @@ class reshape[TArray: Array](Protocol): Parameters ---------- x: array - input array to reshape. + input array to reshape. shape: Tuple[int, ...] - a new shape compatible with the original shape. One shape dimension is allowed to be ``-1``. When a shape dimension is ``-1``, the corresponding output array shape dimension must be inferred from the length of the array and the remaining dimensions. + a new shape compatible with the original shape. One shape dimension is allowed to be ``-1``. When a shape dimension is ``-1``, the corresponding output array shape dimension must be inferred from the length of the array and the remaining dimensions. copy: Optional[bool] - boolean indicating whether or not to copy the input array. If ``True``, the function must always copy. If ``False``, the function must never copy and must raise a ``ValueError`` in case a copy would be necessary. If ``None``, the function must reuse existing memory buffer if possible and copy otherwise. Default: ``None``. + boolean indicating whether or not to copy the input array. If ``True``, the function must always copy. If ``False``, the function must never copy and must raise a ``ValueError`` in case a copy would be necessary. If ``None``, the function must reuse existing memory buffer if possible and copy otherwise. Default: ``None``. Returns ------- out: array - an output array having the same data type and elements as ``x``. + an output array having the same data type and elements as ``x``. """ @@ -7128,16 +7132,16 @@ class roll[TArray: Array](Protocol): Parameters ---------- x: array - input array. + input array. shift: Union[int, Tuple[int, ...]] - number of places by which the elements are shifted. If ``shift`` is a tuple, then ``axis`` must be a tuple of the same size, and each of the given axes must be shifted by the corresponding element in ``shift``. If ``shift`` is an ``int`` and ``axis`` a tuple, then the same ``shift`` must be used for all specified axes. If a shift is positive, then array elements must be shifted positively (toward larger indices) along the dimension of ``axis``. If a shift is negative, then array elements must be shifted negatively (toward smaller indices) along the dimension of ``axis``. + number of places by which the elements are shifted. If ``shift`` is a tuple, then ``axis`` must be a tuple of the same size, and each of the given axes must be shifted by the corresponding element in ``shift``. If ``shift`` is an ``int`` and ``axis`` a tuple, then the same ``shift`` must be used for all specified axes. If a shift is positive, then array elements must be shifted positively (toward larger indices) along the dimension of ``axis``. If a shift is negative, then array elements must be shifted negatively (toward smaller indices) along the dimension of ``axis``. axis: Optional[Union[int, Tuple[int, ...]]] - axis (or axes) along which elements to shift. If ``axis`` is ``None``, the array must be flattened, shifted, and then restored to its original shape. Default: ``None``. + axis (or axes) along which elements to shift. If ``axis`` is ``None``, the array must be flattened, shifted, and then restored to its original shape. Default: ``None``. Returns ------- out: array - an output array having the same data type as ``x`` and whose elements, relative to ``x``, are shifted. + an output array having the same data type as ``x`` and whose elements, relative to ``x``, are shifted. """ @@ -7153,14 +7157,14 @@ class squeeze[TArray: Array](Protocol): Parameters ---------- x: array - input array. + input array. axis: Union[int, Tuple[int, ...]] - axis (or axes) to squeeze. If a specified axis has a size greater than one, a ``ValueError`` must be raised. + axis (or axes) to squeeze. If a specified axis has a size greater than one, a ``ValueError`` must be raised. Returns ------- out: array - an output array having the same data type and elements as ``x``. + an output array having the same data type and elements as ``x``. """ @@ -7176,17 +7180,17 @@ class stack[TArray: Array](Protocol): Parameters ---------- arrays: Union[Tuple[array, ...], List[array]] - input arrays to join. Each array must have the same shape. + input arrays to join. Each array must have the same shape. axis: int - axis along which the arrays will be joined. Providing an ``axis`` specifies the index of the new axis in the dimensions of the result. For example, if ``axis`` is ``0``, the new axis will be the first dimension and the output array will have shape ``(N, A, B, C)``; if ``axis`` is ``1``, the new axis will be the second dimension and the output array will have shape ``(A, N, B, C)``; and, if ``axis`` is ``-1``, the new axis will be the last dimension and the output array will have shape ``(A, B, C, N)``. A valid ``axis`` must be on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If provided an ``axis`` outside of the required interval, the function must raise an exception. Default: ``0``. + axis along which the arrays will be joined. Providing an ``axis`` specifies the index of the new axis in the dimensions of the result. For example, if ``axis`` is ``0``, the new axis will be the first dimension and the output array will have shape ``(N, A, B, C)``; if ``axis`` is ``1``, the new axis will be the second dimension and the output array will have shape ``(A, N, B, C)``; and, if ``axis`` is ``-1``, the new axis will be the last dimension and the output array will have shape ``(A, B, C, N)``. A valid ``axis`` must be on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If provided an ``axis`` outside of the required interval, the function must raise an exception. Default: ``0``. Returns ------- out: array - an output array having rank ``N+1``, where ``N`` is the rank (number of dimensions) of ``x``. If the input arrays have different data types, normal :ref:`type-promotion` must apply. If the input arrays have the same data type, the output array must have the same data type as the input arrays. + an output array having rank ``N+1``, where ``N`` is the rank (number of dimensions) of ``x``. If the input arrays have different data types, normal :ref:`type-promotion` must apply. If the input arrays have the same data type, the output array must have the same data type as the input arrays. - .. note:: - This specification leaves type promotion between data type families (i.e., ``intxx`` and ``floatxx``) unspecified. + .. note:: + This specification leaves type promotion between data type families (i.e., ``intxx`` and ``floatxx``) unspecified. """ @@ -7200,44 +7204,44 @@ class unique_all[TArray: Array](Protocol): Returns the unique elements of an input array ``x``, the first occurring indices for each unique element in ``x``, the indices from the set of unique elements that reconstruct ``x``, and the corresponding counts for each unique element in ``x``. .. admonition:: Data-dependent output shape - :class: important + :class: important - The shapes of two of the output arrays for this function depend on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) may find this function difficult to implement without knowing array values. Accordingly, such libraries may choose to omit this function. See :ref:`data-dependent-output-shapes` section for more details. + The shapes of two of the output arrays for this function depend on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) may find this function difficult to implement without knowing array values. Accordingly, such libraries may choose to omit this function. See :ref:`data-dependent-output-shapes` section for more details. .. note:: - Uniqueness should be determined based on value equality (see :func:`~array_api.equal`). For input arrays having floating-point data types, value-based equality implies the following behavior. + Uniqueness should be determined based on value equality (see :func:`~array_api.equal`). For input arrays having floating-point data types, value-based equality implies the following behavior. - - As ``nan`` values compare as ``False``, ``nan`` values should be considered distinct. - - As complex floating-point values having at least one ``nan`` component compare as ``False``, complex floating-point values having ``nan`` components should be considered distinct. - - As ``-0`` and ``+0`` compare as ``True``, signed zeros should not be considered distinct, and the corresponding unique element will be implementation-dependent (e.g., an implementation could choose to return ``-0`` if ``-0`` occurs before ``+0``). + - As ``nan`` values compare as ``False``, ``nan`` values should be considered distinct. + - As complex floating-point values having at least one ``nan`` component compare as ``False``, complex floating-point values having ``nan`` components should be considered distinct. + - As ``-0`` and ``+0`` compare as ``True``, signed zeros should not be considered distinct, and the corresponding unique element will be implementation-dependent (e.g., an implementation could choose to return ``-0`` if ``-0`` occurs before ``+0``). - As signed zeros are not distinct, using ``inverse_indices`` to reconstruct the input array is not guaranteed to return an array having the exact same values. + As signed zeros are not distinct, using ``inverse_indices`` to reconstruct the input array is not guaranteed to return an array having the exact same values. - Each ``nan`` value and each complex floating-point value having a ``nan`` component should have a count of one, while the counts for signed zeros should be aggregated as a single count. + Each ``nan`` value and each complex floating-point value having a ``nan`` component should have a count of one, while the counts for signed zeros should be aggregated as a single count. Parameters ---------- x: array - input array. If ``x`` has more than one dimension, the function must flatten ``x`` and return the unique elements of the flattened array. + input array. If ``x`` has more than one dimension, the function must flatten ``x`` and return the unique elements of the flattened array. Returns ------- out: Tuple[array, array, array, array] - a namedtuple ``(values, indices, inverse_indices, counts)`` whose + a namedtuple ``(values, indices, inverse_indices, counts)`` whose - - first element must have the field name ``values`` and must be an array containing the unique elements of ``x``. The array must have the same data type as ``x``. - - second element must have the field name ``indices`` and must be an array containing the indices (first occurrences) of ``x`` that result in ``values``. The array must have the same shape as ``values`` and must have the default array index data type. - - third element must have the field name ``inverse_indices`` and must be an array containing the indices of ``values`` that reconstruct ``x``. The array must have the same shape as ``x`` and must have the default array index data type. - - fourth element must have the field name ``counts`` and must be an array containing the number of times each unique element occurs in ``x``. The returned array must have same shape as ``values`` and must have the default array index data type. + - first element must have the field name ``values`` and must be an array containing the unique elements of ``x``. The array must have the same data type as ``x``. + - second element must have the field name ``indices`` and must be an array containing the indices (first occurrences) of ``x`` that result in ``values``. The array must have the same shape as ``values`` and must have the default array index data type. + - third element must have the field name ``inverse_indices`` and must be an array containing the indices of ``values`` that reconstruct ``x``. The array must have the same shape as ``x`` and must have the default array index data type. + - fourth element must have the field name ``counts`` and must be an array containing the number of times each unique element occurs in ``x``. The returned array must have same shape as ``values`` and must have the default array index data type. - .. note:: - The order of unique elements is not specified and may vary between implementations. + .. note:: + The order of unique elements is not specified and may vary between implementations. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -7251,40 +7255,40 @@ class unique_counts[TArray: Array](Protocol): Returns the unique elements of an input array ``x`` and the corresponding counts for each unique element in ``x``. .. admonition:: Data-dependent output shape - :class: important + :class: important - The shapes of two of the output arrays for this function depend on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) may find this function difficult to implement without knowing array values. Accordingly, such libraries may choose to omit this function. See :ref:`data-dependent-output-shapes` section for more details. + The shapes of two of the output arrays for this function depend on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) may find this function difficult to implement without knowing array values. Accordingly, such libraries may choose to omit this function. See :ref:`data-dependent-output-shapes` section for more details. .. note:: - Uniqueness should be determined based on value equality (see :func:`~array_api.equal`). For input arrays having floating-point data types, value-based equality implies the following behavior. + Uniqueness should be determined based on value equality (see :func:`~array_api.equal`). For input arrays having floating-point data types, value-based equality implies the following behavior. - - As ``nan`` values compare as ``False``, ``nan`` values should be considered distinct. - - As complex floating-point values having at least one ``nan`` component compare as ``False``, complex floating-point values having ``nan`` components should be considered distinct. - - As ``-0`` and ``+0`` compare as ``True``, signed zeros should not be considered distinct, and the corresponding unique element will be implementation-dependent (e.g., an implementation could choose to return ``-0`` if ``-0`` occurs before ``+0``). + - As ``nan`` values compare as ``False``, ``nan`` values should be considered distinct. + - As complex floating-point values having at least one ``nan`` component compare as ``False``, complex floating-point values having ``nan`` components should be considered distinct. + - As ``-0`` and ``+0`` compare as ``True``, signed zeros should not be considered distinct, and the corresponding unique element will be implementation-dependent (e.g., an implementation could choose to return ``-0`` if ``-0`` occurs before ``+0``). - Each ``nan`` value and each complex floating-point value having a ``nan`` component should have a count of one, while the counts for signed zeros should be aggregated as a single count. + Each ``nan`` value and each complex floating-point value having a ``nan`` component should have a count of one, while the counts for signed zeros should be aggregated as a single count. Parameters ---------- x: array - input array. If ``x`` has more than one dimension, the function must flatten ``x`` and return the unique elements of the flattened array. + input array. If ``x`` has more than one dimension, the function must flatten ``x`` and return the unique elements of the flattened array. Returns ------- out: Tuple[array, array] - a namedtuple `(values, counts)` whose + a namedtuple `(values, counts)` whose - - first element must have the field name ``values`` and must be an array containing the unique elements of ``x``. The array must have the same data type as ``x``. - - second element must have the field name `counts` and must be an array containing the number of times each unique element occurs in ``x``. The returned array must have same shape as ``values`` and must have the default array index data type. + - first element must have the field name ``values`` and must be an array containing the unique elements of ``x``. The array must have the same data type as ``x``. + - second element must have the field name `counts` and must be an array containing the number of times each unique element occurs in ``x``. The returned array must have same shape as ``values`` and must have the default array index data type. - .. note:: - The order of unique elements is not specified and may vary between implementations. + .. note:: + The order of unique elements is not specified and may vary between implementations. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -7298,40 +7302,40 @@ class unique_inverse[TArray: Array](Protocol): Returns the unique elements of an input array ``x`` and the indices from the set of unique elements that reconstruct ``x``. .. admonition:: Data-dependent output shape - :class: important + :class: important - The shapes of two of the output arrays for this function depend on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) may find this function difficult to implement without knowing array values. Accordingly, such libraries may choose to omit this function. See :ref:`data-dependent-output-shapes` section for more details. + The shapes of two of the output arrays for this function depend on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) may find this function difficult to implement without knowing array values. Accordingly, such libraries may choose to omit this function. See :ref:`data-dependent-output-shapes` section for more details. .. note:: - Uniqueness should be determined based on value equality (see :func:`~array_api.equal`). For input arrays having floating-point data types, value-based equality implies the following behavior. + Uniqueness should be determined based on value equality (see :func:`~array_api.equal`). For input arrays having floating-point data types, value-based equality implies the following behavior. - - As ``nan`` values compare as ``False``, ``nan`` values should be considered distinct. - - As complex floating-point values having at least one ``nan`` component compare as ``False``, complex floating-point values having ``nan`` components should be considered distinct. - - As ``-0`` and ``+0`` compare as ``True``, signed zeros should not be considered distinct, and the corresponding unique element will be implementation-dependent (e.g., an implementation could choose to return ``-0`` if ``-0`` occurs before ``+0``). + - As ``nan`` values compare as ``False``, ``nan`` values should be considered distinct. + - As complex floating-point values having at least one ``nan`` component compare as ``False``, complex floating-point values having ``nan`` components should be considered distinct. + - As ``-0`` and ``+0`` compare as ``True``, signed zeros should not be considered distinct, and the corresponding unique element will be implementation-dependent (e.g., an implementation could choose to return ``-0`` if ``-0`` occurs before ``+0``). - As signed zeros are not distinct, using ``inverse_indices`` to reconstruct the input array is not guaranteed to return an array having the exact same values. + As signed zeros are not distinct, using ``inverse_indices`` to reconstruct the input array is not guaranteed to return an array having the exact same values. Parameters ---------- x: array - input array. If ``x`` has more than one dimension, the function must flatten ``x`` and return the unique elements of the flattened array. + input array. If ``x`` has more than one dimension, the function must flatten ``x`` and return the unique elements of the flattened array. Returns ------- out: Tuple[array, array] - a namedtuple ``(values, inverse_indices)`` whose + a namedtuple ``(values, inverse_indices)`` whose - - first element must have the field name ``values`` and must be an array containing the unique elements of ``x``. The array must have the same data type as ``x``. - - second element must have the field name ``inverse_indices`` and must be an array containing the indices of ``values`` that reconstruct ``x``. The array must have the same shape as ``x`` and have the default array index data type. + - first element must have the field name ``values`` and must be an array containing the unique elements of ``x``. The array must have the same data type as ``x``. + - second element must have the field name ``inverse_indices`` and must be an array containing the indices of ``values`` that reconstruct ``x``. The array must have the same shape as ``x`` and have the default array index data type. - .. note:: - The order of unique elements is not specified and may vary between implementations. + .. note:: + The order of unique elements is not specified and may vary between implementations. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -7345,35 +7349,35 @@ class unique_values[TArray: Array](Protocol): Returns the unique elements of an input array ``x``. .. admonition:: Data-dependent output shape - :class: important + :class: important - The shapes of two of the output arrays for this function depend on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) may find this function difficult to implement without knowing array values. Accordingly, such libraries may choose to omit this function. See :ref:`data-dependent-output-shapes` section for more details. + The shapes of two of the output arrays for this function depend on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) may find this function difficult to implement without knowing array values. Accordingly, such libraries may choose to omit this function. See :ref:`data-dependent-output-shapes` section for more details. .. note:: - Uniqueness should be determined based on value equality (see :func:`~array_api.equal`). For input arrays having floating-point data types, value-based equality implies the following behavior. + Uniqueness should be determined based on value equality (see :func:`~array_api.equal`). For input arrays having floating-point data types, value-based equality implies the following behavior. - - As ``nan`` values compare as ``False``, ``nan`` values should be considered distinct. - - As complex floating-point values having at least one ``nan`` component compare as ``False``, complex floating-point values having ``nan`` components should be considered distinct. - - As ``-0`` and ``+0`` compare as ``True``, signed zeros should not be considered distinct, and the corresponding unique element will be implementation-dependent (e.g., an implementation could choose to return ``-0`` if ``-0`` occurs before ``+0``). + - As ``nan`` values compare as ``False``, ``nan`` values should be considered distinct. + - As complex floating-point values having at least one ``nan`` component compare as ``False``, complex floating-point values having ``nan`` components should be considered distinct. + - As ``-0`` and ``+0`` compare as ``True``, signed zeros should not be considered distinct, and the corresponding unique element will be implementation-dependent (e.g., an implementation could choose to return ``-0`` if ``-0`` occurs before ``+0``). Parameters ---------- x: array - input array. If ``x`` has more than one dimension, the function must flatten ``x`` and return the unique elements of the flattened array. + input array. If ``x`` has more than one dimension, the function must flatten ``x`` and return the unique elements of the flattened array. Returns ------- out: array - an array containing the set of unique elements in ``x``. The returned array must have the same data type as ``x``. + an array containing the set of unique elements in ``x``. The returned array must have the same data type as ``x``. - .. note:: - The order of unique elements is not specified and may vary between implementations. + .. note:: + The order of unique elements is not specified and may vary between implementations. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -7382,7 +7386,7 @@ def __call__(self, x: TArray, /) -> TArray: ... @runtime_checkable -class ArrayNamespace[TSupportsbufferprotocol, TArray: Array, TDevice, TDtype](Protocol): +class ArrayNamespace[TArray: Array, TDevice, TDtype](Protocol): astype: astype[TArray, TDtype] "Copies an array to a specified data type irrespective of :ref:`type-promotion` rules.\n\n.. note::\n Casting floating-point ``NaN`` and ``infinity`` values to integral data types is not specified and is implementation-dependent.\n\n.. note::\n Casting a complex floating-point array to a real-valued data type should not be permitted.\n\n Historically, when casting a complex floating-point array to a real-valued data type, libraries such as NumPy have discarded imaginary components such that, for a complex floating-point array ``x``, ``astype(x)`` equals ``astype(real(x))``). This behavior is considered problematic as the choice to discard the imaginary component is arbitrary and introduces more than one way to achieve the same outcome (i.e., for a complex floating-point array ``x``, ``astype(x)`` and ``astype(real(x))`` versus only ``astype(imag(x))``). Instead, in order to avoid ambiguity and to promote clarity, this specification requires that array API consumers explicitly express which component should be cast to a specified real-valued data type.\n\n.. note::\n When casting a boolean input array to a real-valued data type, a value of ``True`` must cast to a real-valued number equal to ``1``, and a value of ``False`` must cast to a real-valued number equal to ``0``.\n\n When casting a boolean input array to a complex floating-point data type, a value of ``True`` must cast to a complex number equal to ``1 + 0j``, and a value of ``False`` must cast to a complex number equal to ``0 + 0j``.\n\n.. note::\n When casting a real-valued input array to ``bool``, a value of ``0`` must cast to ``False``, and a non-zero value must cast to ``True``.\n\n When casting a complex floating-point array to ``bool``, a value of ``0 + 0j`` must cast to ``False``, and all other values must cast to ``True``.\n\nParameters\n----------\nx: array\n array to cast.\ndtype: dtype\n desired data type.\ncopy: bool\n specifies whether to copy an array when the specified ``dtype`` matches the data type of the input array ``x``. If ``True``, a newly allocated array must always be returned. If ``False`` and the specified ``dtype`` matches the data type of the input array, the input array must be returned; otherwise, a newly allocated array must be returned. Default: ``True``.\n\nReturns\n-------\nout: array\n an array having the specified data type. The returned array must have the same shape as ``x``.\n\nNotes\n-----\n\n.. versionchanged:: 2022.12\n Added complex data type support." can_cast: can_cast[TArray, TDtype] @@ -7411,7 +7415,7 @@ class ArrayNamespace[TSupportsbufferprotocol, TArray: Array, TDevice, TDtype](Pr "Calculates the variance of the input array ``x``.\n\nParameters\n----------\nx: array\n input array. Should have a real-valued floating-point data type.\naxis: Optional[Union[int, Tuple[int, ...]]]\n axis or axes along which variances must be computed. By default, the variance must be computed over the entire array. If a tuple of integers, variances must be computed over multiple axes. Default: ``None``.\ncorrection: Union[int, float]\n degrees of freedom adjustment. Setting this parameter to a value other than ``0`` has the effect of adjusting the divisor during the calculation of the variance according to ``N-c`` where ``N`` corresponds to the total number of elements over which the variance is computed and ``c`` corresponds to the provided degrees of freedom adjustment. When computing the variance of a population, setting this parameter to ``0`` is the standard choice (i.e., the provided array contains data constituting an entire population). When computing the unbiased sample variance, setting this parameter to ``1`` is the standard choice (i.e., the provided array contains data sampled from a larger population; this is commonly referred to as Bessel's correction). Default: ``0``.\nkeepdims: bool\n if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``.\n\nReturns\n-------\nout: array\n if the variance was computed over the entire array, a zero-dimensional array containing the variance; otherwise, a non-zero-dimensional array containing the variances. The returned array must have the same data type as ``x``.\n\n\n.. note::\n While this specification recommends that this function only accept input arrays having a real-valued floating-point data type, specification-compliant array libraries may choose to accept input arrays having an integer data type. While mixed data type promotion is implementation-defined, if the input array ``x`` has an integer data type, the returned array must have the default real-valued floating-point data type.\n\nNotes\n-----\n\n**Special Cases**\n\nLet ``N`` equal the number of elements over which to compute the variance.\n\n- If ``N - correction`` is less than or equal to ``0``, the variance is ``NaN``.\n- If ``x_i`` is ``NaN``, the variance is ``NaN`` (i.e., ``NaN`` values propagate)." arange: arange[TArray, TDevice, TDtype] "Returns evenly spaced values within the half-open interval ``[start, stop)`` as a one-dimensional array.\n\nParameters\n----------\nstart: Union[int, float]\n if ``stop`` is specified, the start of interval (inclusive); otherwise, the end of the interval (exclusive). If ``stop`` is not specified, the default starting value is ``0``.\nstop: Optional[Union[int, float]]\n the end of the interval. Default: ``None``.\nstep: Union[int, float]\n the distance between two adjacent elements (``out[i+1] - out[i]``). Must not be ``0``; may be negative, this results in an empty array if ``stop >= start``. Default: ``1``.\ndtype: Optional[dtype]\n output array data type. If ``dtype`` is ``None``, the output array data type must be inferred from ``start``, ``stop`` and ``step``. If those are all integers, the output array dtype must be the default integer dtype; if one or more have type ``float``, then the output array dtype must be the default real-valued floating-point data type. Default: ``None``.\ndevice: Optional[device]\n device on which to place the created array. Default: ``None``.\n\n\n.. note::\n This function cannot guarantee that the interval does not include the ``stop`` value in those cases where ``step`` is not an integer and floating-point rounding errors affect the length of the output array.\n\nReturns\n-------\nout: array\n a one-dimensional array containing evenly spaced values. The length of the output array must be ``ceil((stop-start)/step)`` if ``stop - start`` and ``step`` have the same sign, and length ``0`` otherwise." - asarray: asarray[TSupportsbufferprotocol, TArray, TDevice, TDtype] + asarray: asarray[TArray, TDevice, TDtype] "Convert the input to an array.\n\nParameters\n----------\nobj: Union[array, bool, int, float, complex, NestedSequence[bool | int | float | complex], SupportsBufferProtocol]\n object to be converted to an array. May be a Python scalar, a (possibly nested) sequence of Python scalars, or an object supporting the Python buffer protocol.\n\n .. admonition:: Tip\n :class: important\n\n An object supporting the buffer protocol can be turned into a memoryview through ``memoryview(obj)``.\n\ndtype: Optional[dtype]\n output array data type. If ``dtype`` is ``None``, the output array data type must be inferred from the data type(s) in ``obj``. If all input values are Python scalars, then, in order of precedence,\n\n - if all values are of type ``bool``, the output data type must be ``bool``.\n - if all values are of type ``int`` or are a mixture of ``bool`` and ``int``, the output data type must be the default integer data type.\n - if one or more values are ``complex`` numbers, the output data type must be the default complex floating-point data type.\n - if one or more values are ``float``\\s, the output data type must be the default real-valued floating-point data type.\n\n Default: ``None``.\n\n .. admonition:: Note\n :class: note\n\n If ``dtype`` is not ``None``, then array conversions should obey :ref:`type-promotion` rules. Conversions not specified according to :ref:`type-promotion` rules may or may not be permitted by a conforming array library. To perform an explicit cast, use :func:`array_api.astype`.\n\n .. note::\n If an input value exceeds the precision of the resolved output array data type, behavior is left unspecified and, thus, implementation-defined.\n\ndevice: Optional[device]\n device on which to place the created array. If ``device`` is ``None`` and ``obj`` is an array, the output array device must be inferred from ``obj``. Default: ``None``.\ncopy: Optional[bool]\n boolean indicating whether or not to copy the input. If ``True``, the function must always copy. If ``False``, the function must never copy for input which supports the buffer protocol and must raise a ``ValueError`` in case a copy would be necessary. If ``None``, the function must reuse existing memory buffer if possible and copy otherwise. Default: ``None``.\n\nReturns\n-------\nout: array\n an array containing the data from ``obj``.\n\nNotes\n-----\n\n.. versionchanged:: 2022.12\n Added complex data type support." empty: empty[TArray, TDevice, TDtype] "Returns an uninitialized array having a specified `shape`.\n\nParameters\n----------\nshape: Union[int, Tuple[int, ...]]\n output array shape.\ndtype: Optional[dtype]\n output array data type. If ``dtype`` is ``None``, the output array data type must be the default real-valued floating-point data type. Default: ``None``.\ndevice: Optional[device]\n device on which to place the created array. Default: ``None``.\n\nReturns\n-------\nout: array\n an array containing uninitialized data." @@ -7605,15 +7609,15 @@ class ArrayNamespace[TSupportsbufferprotocol, TArray: Array, TDevice, TDtype](Pr "Removes singleton dimensions (axes) from ``x``.\n\nParameters\n----------\nx: array\n input array.\naxis: Union[int, Tuple[int, ...]]\n axis (or axes) to squeeze. If a specified axis has a size greater than one, a ``ValueError`` must be raised.\n\nReturns\n-------\nout: array\n an output array having the same data type and elements as ``x``." stack: stack[TArray,] "Joins a sequence of arrays along a new axis.\n\nParameters\n----------\narrays: Union[Tuple[array, ...], List[array]]\n input arrays to join. Each array must have the same shape.\naxis: int\n axis along which the arrays will be joined. Providing an ``axis`` specifies the index of the new axis in the dimensions of the result. For example, if ``axis`` is ``0``, the new axis will be the first dimension and the output array will have shape ``(N, A, B, C)``; if ``axis`` is ``1``, the new axis will be the second dimension and the output array will have shape ``(A, N, B, C)``; and, if ``axis`` is ``-1``, the new axis will be the last dimension and the output array will have shape ``(A, B, C, N)``. A valid ``axis`` must be on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If provided an ``axis`` outside of the required interval, the function must raise an exception. Default: ``0``.\n\nReturns\n-------\nout: array\n an output array having rank ``N+1``, where ``N`` is the rank (number of dimensions) of ``x``. If the input arrays have different data types, normal :ref:`type-promotion` must apply. If the input arrays have the same data type, the output array must have the same data type as the input arrays.\n\n .. note::\n This specification leaves type promotion between data type families (i.e., ``intxx`` and ``floatxx``) unspecified." - e: float + e: TArray "\nIEEE 754 floating-point representation of Euler's constant.\n\n``e = 2.71828182845904523536028747135266249775724709369995...``\n" - inf: float + inf: TArray "\nIEEE 754 floating-point representation of (positive) infinity.\n" - nan: float + nan: TArray "\nIEEE 754 floating-point representation of Not a Number (``NaN``).\n" - newaxis: float + newaxis: TArray "\nAn alias for ``None`` which is useful for indexing arrays.\n" - pi: float + pi: TArray "\nIEEE 754 floating-point representation of the mathematical constant ``π``.\n\n``pi = 3.1415926535897932384626433...``\n" unique_all: unique_all[TArray,] "Returns the unique elements of an input array ``x``, the first occurring indices for each unique element in ``x``, the indices from the set of unique elements that reconstruct ``x``, and the corresponding counts for each unique element in ``x``.\n\n.. admonition:: Data-dependent output shape\n :class: important\n\n The shapes of two of the output arrays for this function depend on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) may find this function difficult to implement without knowing array values. Accordingly, such libraries may choose to omit this function. See :ref:`data-dependent-output-shapes` section for more details.\n\n.. note::\n Uniqueness should be determined based on value equality (see :func:`~array_api.equal`). For input arrays having floating-point data types, value-based equality implies the following behavior.\n\n - As ``nan`` values compare as ``False``, ``nan`` values should be considered distinct.\n - As complex floating-point values having at least one ``nan`` component compare as ``False``, complex floating-point values having ``nan`` components should be considered distinct.\n - As ``-0`` and ``+0`` compare as ``True``, signed zeros should not be considered distinct, and the corresponding unique element will be implementation-dependent (e.g., an implementation could choose to return ``-0`` if ``-0`` occurs before ``+0``).\n\n As signed zeros are not distinct, using ``inverse_indices`` to reconstruct the input array is not guaranteed to return an array having the exact same values.\n\n Each ``nan`` value and each complex floating-point value having a ``nan`` component should have a count of one, while the counts for signed zeros should be aggregated as a single count.\n\nParameters\n----------\nx: array\n input array. If ``x`` has more than one dimension, the function must flatten ``x`` and return the unique elements of the flattened array.\n\nReturns\n-------\nout: Tuple[array, array, array, array]\n a namedtuple ``(values, indices, inverse_indices, counts)`` whose\n\n - first element must have the field name ``values`` and must be an array containing the unique elements of ``x``. The array must have the same data type as ``x``.\n - second element must have the field name ``indices`` and must be an array containing the indices (first occurrences) of ``x`` that result in ``values``. The array must have the same shape as ``values`` and must have the default array index data type.\n - third element must have the field name ``inverse_indices`` and must be an array containing the indices of ``values`` that reconstruct ``x``. The array must have the same shape as ``x`` and must have the default array index data type.\n - fourth element must have the field name ``counts`` and must be an array containing the number of times each unique element occurs in ``x``. The returned array must have same shape as ``values`` and must have the default array index data type.\n\n .. note::\n The order of unique elements is not specified and may vary between implementations.\n\nNotes\n-----\n\n.. versionchanged:: 2022.12\n Added complex data type support." @@ -7623,19 +7627,19 @@ class ArrayNamespace[TSupportsbufferprotocol, TArray: Array, TDevice, TDtype](Pr "Returns the unique elements of an input array ``x`` and the indices from the set of unique elements that reconstruct ``x``.\n\n.. admonition:: Data-dependent output shape\n :class: important\n\n The shapes of two of the output arrays for this function depend on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) may find this function difficult to implement without knowing array values. Accordingly, such libraries may choose to omit this function. See :ref:`data-dependent-output-shapes` section for more details.\n\n.. note::\n Uniqueness should be determined based on value equality (see :func:`~array_api.equal`). For input arrays having floating-point data types, value-based equality implies the following behavior.\n\n - As ``nan`` values compare as ``False``, ``nan`` values should be considered distinct.\n - As complex floating-point values having at least one ``nan`` component compare as ``False``, complex floating-point values having ``nan`` components should be considered distinct.\n - As ``-0`` and ``+0`` compare as ``True``, signed zeros should not be considered distinct, and the corresponding unique element will be implementation-dependent (e.g., an implementation could choose to return ``-0`` if ``-0`` occurs before ``+0``).\n\n As signed zeros are not distinct, using ``inverse_indices`` to reconstruct the input array is not guaranteed to return an array having the exact same values.\n\nParameters\n----------\nx: array\n input array. If ``x`` has more than one dimension, the function must flatten ``x`` and return the unique elements of the flattened array.\n\nReturns\n-------\nout: Tuple[array, array]\n a namedtuple ``(values, inverse_indices)`` whose\n\n - first element must have the field name ``values`` and must be an array containing the unique elements of ``x``. The array must have the same data type as ``x``.\n - second element must have the field name ``inverse_indices`` and must be an array containing the indices of ``values`` that reconstruct ``x``. The array must have the same shape as ``x`` and have the default array index data type.\n\n .. note::\n The order of unique elements is not specified and may vary between implementations.\n\nNotes\n-----\n\n.. versionchanged:: 2022.12\n Added complex data type support." unique_values: unique_values[TArray,] "Returns the unique elements of an input array ``x``.\n\n.. admonition:: Data-dependent output shape\n :class: important\n\n The shapes of two of the output arrays for this function depend on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) may find this function difficult to implement without knowing array values. Accordingly, such libraries may choose to omit this function. See :ref:`data-dependent-output-shapes` section for more details.\n\n.. note::\n Uniqueness should be determined based on value equality (see :func:`~array_api.equal`). For input arrays having floating-point data types, value-based equality implies the following behavior.\n\n - As ``nan`` values compare as ``False``, ``nan`` values should be considered distinct.\n - As complex floating-point values having at least one ``nan`` component compare as ``False``, complex floating-point values having ``nan`` components should be considered distinct.\n - As ``-0`` and ``+0`` compare as ``True``, signed zeros should not be considered distinct, and the corresponding unique element will be implementation-dependent (e.g., an implementation could choose to return ``-0`` if ``-0`` occurs before ``+0``).\n\nParameters\n----------\nx: array\n input array. If ``x`` has more than one dimension, the function must flatten ``x`` and return the unique elements of the flattened array.\n\nReturns\n-------\nout: array\n an array containing the set of unique elements in ``x``. The returned array must have the same data type as ``x``.\n\n .. note::\n The order of unique elements is not specified and may vary between implementations.\n\nNotes\n-----\n\n.. versionchanged:: 2022.12\n Added complex data type support." - bool: float - complex128: float - complex64: float - float32: float - float64: float - int16: float - int32: float - int64: float - int8: float - uint16: float - uint32: float - uint64: float - uint8: float + bool: TDtype + complex128: TDtype + complex64: TDtype + float32: TDtype + float64: TDtype + int16: TDtype + int32: TDtype + int64: TDtype + int8: TDtype + uint16: TDtype + uint32: TDtype + uint64: TDtype + uint8: TDtype Device: TDevice @@ -7722,6 +7726,6 @@ class FftNamespace[TArray: Array, TDevice](Protocol): @runtime_checkable -class ArrayNamespaceFull[TSupportsbufferprotocol, TArray: Array, TDevice, TDtype](ArrayNamespace[TSupportsbufferprotocol, TArray, TDevice, TDtype], Protocol): +class ArrayNamespaceFull[TArray: Array, TDevice, TDtype](ArrayNamespace[TArray, TDevice, TDtype], Protocol): linalg: LinalgNamespace[TArray, TDtype] fft: FftNamespace[TArray, TDevice] diff --git a/src/array_api/_2023_12.py b/src/array_api/_2023_12.py index 797f9f4..c51269b 100644 --- a/src/array_api/_2023_12.py +++ b/src/array_api/_2023_12.py @@ -1,8 +1,10 @@ from __future__ import annotations from abc import abstractmethod +from collections.abc import Buffer as SupportsBufferProtocol from collections.abc import Sequence from enum import Enum +from types import EllipsisType as ellipsis from typing import ( Any, Literal, @@ -10,11 +12,13 @@ runtime_checkable, ) +from typing_extensions import CapsuleType as PyCapsule + inf = float("inf") @runtime_checkable -class Info[TCapabilities, TDatatypes, TDefaultdatatypes, TArray: Array, TDevice, TDtype](Protocol): +class Info[TArray: Array, TCapabilities, TDatatypes, TDefaultdatatypes, TDevice, TDtype](Protocol): """Namespace returned by `__array_namespace_info__`.""" def capabilities(self) -> TCapabilities: ... @@ -58,13 +62,13 @@ class finfo_object[TDtype](Protocol): @runtime_checkable -class Array[TPycapsule, TArray: Array, TDevice, TDtype, TEllipsis](Protocol): - def __init__(self: TArray) -> None: +class Array[TArray: Array, TDevice, TDtype](Protocol): + def __init__(self) -> None: """Initialize the attributes for the array object class.""" ... @property - def dtype(self: TArray) -> TDtype: + def dtype(self) -> TDtype: """ Data type of the array elements. @@ -77,7 +81,7 @@ def dtype(self: TArray) -> TDtype: ... @property - def device(self: TArray) -> TDevice: + def device(self) -> TDevice: """ Hardware device the array data resides on. @@ -90,7 +94,7 @@ def device(self: TArray) -> TDevice: ... @property - def mT(self: TArray) -> TArray: + def mT(self) -> TArray: """ Transpose of a matrix (or a stack of matrices). @@ -105,7 +109,7 @@ def mT(self: TArray) -> TArray: ... @property - def ndim(self: TArray) -> int: + def ndim(self) -> int: """ Number of array dimensions (axes). @@ -118,7 +122,7 @@ def ndim(self: TArray) -> int: ... @property - def shape(self: TArray) -> tuple[int | None, ...]: + def shape(self) -> tuple[int | None, ...]: """ Array dimensions. @@ -138,7 +142,7 @@ def shape(self: TArray) -> tuple[int | None, ...]: ... @property - def size(self: TArray) -> int | None: + def size(self) -> int | None: """ Number of elements in an array. @@ -158,7 +162,7 @@ def size(self: TArray) -> int | None: ... @property - def T(self: TArray) -> TArray: + def T(self) -> TArray: """ Transpose of the array. @@ -176,13 +180,95 @@ def T(self: TArray) -> TArray: """ ... - def __array_namespace__(self: TArray, /, *, api_version: str | None = None) -> Any: + def __abs__(self, /) -> TArray: + """ + Calculates the absolute value for each element of an array instance. + + For real-valued input arrays, the element-wise result has the same magnitude as the respective element in ``x`` but has positive sign. + + .. note:: + For signed integer data types, the absolute value of the minimum representable integer is implementation-dependent. + + Parameters + ---------- + self + array instance. Should have a numeric data type. + + Returns + ------- + out: array + an array containing the element-wise absolute value. If ``self`` has a real-valued data type, the returned array must have the same data type as ``self``. If ``self`` has a complex floating-point data type, the returned arrayed must have a real-valued floating-point data type whose precision matches the precision of ``self`` (e.g., if ``self`` is ``complex128``, then the returned array must have a ``float64`` data type). + + Notes + ----- + + .. note:: + Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.abs`. + + .. versionchanged:: 2022.12 + Added complex data type support. + + """ + ... + + def __add__(self, other: int | float | complex | TArray, /) -> TArray: + """ + Calculates the sum for each element of an array instance with the respective element of the array ``other``. + + Parameters + ---------- + self + array instance (augend array). Should have a numeric data type. + other: Union[int, float, complex, array] + addend array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a numeric data type. + + Returns + ------- + out: array + an array containing the element-wise sums. The returned array must have a data type determined by :ref:`type-promotion`. + + Notes + ----- + + .. note:: + Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.add`. + + .. versionchanged:: 2022.12 + Added complex data type support. + + """ + ... + + def __and__(self, other: int | bool | TArray, /) -> TArray: + """ + Evaluates ``self_i & other_i`` for each element of an array instance with the respective element of the array ``other``. + + Parameters + ---------- + self + array instance. Should have an integer or boolean data type. + other: Union[int, bool, array] + other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have an integer or boolean data type. + + Returns + ------- + out: array + an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. + + + .. note:: + Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.bitwise_and`. + + """ + ... + + def __array_namespace__(self, /, *, api_version: str | None = None) -> Any: """ Returns an object that has all the array API functions on it. Parameters ---------- - self: array + self array instance. api_version: Optional[str] string representing the version of the array API specification to be returned, in ``'YYYY.MM'`` form, for example, ``'2020.10'``. If it is ``None``, it should return the namespace corresponding to latest version of the array API specification. If the given version is invalid or not implemented for the given module, an error should be raised. Default: ``None``. @@ -195,13 +281,94 @@ def __array_namespace__(self: TArray, /, *, api_version: str | None = None) -> A """ ... - def __dlpack__(self: TArray, /, *, stream: int | Any | None = None, max_version: tuple[int, int] | None = None, dl_device: tuple[Enum, int] | None = None, copy: bool | None = None) -> TPycapsule: + def __bool__(self, /) -> bool: + """ + Converts a zero-dimensional array to a Python ``bool`` object. + + Parameters + ---------- + self + zero-dimensional array instance. + + Returns + ------- + out: bool + a Python ``bool`` object representing the single element of the array. + + Notes + ----- + **Special cases** + + For real-valued floating-point operands, + + - If ``self`` is ``NaN``, the result is ``True``. + - If ``self`` is either ``+infinity`` or ``-infinity``, the result is ``True``. + - If ``self`` is either ``+0`` or ``-0``, the result is ``False``. + + For complex floating-point operands, special cases must be handled as if the operation is implemented as the logical OR of ``bool(real(self))`` and ``bool(imag(self))``. + + **Lazy implementations** + + The Python language requires the return value to be of type ``bool``. Lazy implementations are therefore not able to return any kind of lazy/delayed object here and should raise a ``ValueError`` instead. + + .. versionchanged:: 2022.12 + Added boolean and complex data type support. + + .. versionchanged:: 2023.12 + Allowed lazy implementations to error. + + """ + ... + + def __complex__(self, /) -> complex: + """ + Converts a zero-dimensional array to a Python ``complex`` object. + + Parameters + ---------- + self + zero-dimensional array instance. + + Returns + ------- + out: complex + a Python ``complex`` object representing the single element of the array instance. + + Notes + ----- + **Special cases** + + For boolean operands, + + - If ``self`` is ``True``, the result is ``1+0j``. + - If ``self`` is ``False``, the result is ``0+0j``. + + For real-valued floating-point operands, + + - If ``self`` is ``NaN``, the result is ``NaN + NaN j``. + - If ``self`` is ``+infinity``, the result is ``+infinity + 0j``. + - If ``self`` is ``-infinity``, the result is ``-infinity + 0j``. + - If ``self`` is a finite number, the result is ``self + 0j``. + + **Lazy implementations** + + The Python language requires the return value to be of type ``complex``. Lazy implementations are therefore not able to return any kind of lazy/delayed object here and should raise a ``ValueError`` instead. + + .. versionadded:: 2022.12 + + .. versionchanged:: 2023.12 + Allowed lazy implementations to error. + + """ + ... + + def __dlpack__(self, /, *, stream: int | Any | None = None, max_version: tuple[int, int] | None = None, dl_device: tuple[Enum, int] | None = None, copy: bool | None = None) -> PyCapsule: """ Exports the array for consumption by :func:`~array_api.from_dlpack` as a DLPack capsule. Parameters ---------- - self: array + self array instance. stream: Optional[Union[int, Any]] for CUDA and ROCm, a Python integer representing a pointer to a stream, on devices that support streams. ``stream`` is provided by the consumer to the producer to instruct the producer to ensure that operations can safely be performed on the array (e.g., by inserting a dependency between streams via "wait for event"). The pointer must be an integer larger than or equal to ``-1`` (see below for allowed values on each platform). If ``stream`` is ``-1``, the value may be used by the consumer to signal "producer must not perform any synchronization". The ownership of the stream stays with the consumer. On CPU and other device types without streams, only ``None`` is accepted. @@ -362,13 +529,13 @@ def __dlpack__(self: TArray, /, *, stream: int | Any | None = None, max_version: """ ... - def __dlpack_device__(self: TArray, /) -> tuple[Enum, int]: + def __dlpack_device__(self, /) -> tuple[Enum, int]: """ Returns device type and device ID in DLPack format. Meant for use within :func:`~array_api.from_dlpack`. Parameters ---------- - self: array + self array instance. Returns @@ -392,538 +559,388 @@ def __dlpack_device__(self: TArray, /) -> tuple[Enum, int]: """ ... - def to_device(self: TArray, device: TDevice, /, *, stream: int | Any | None = None) -> TArray: + def __eq__(self, other: int | float | complex | bool | TArray, /) -> TArray: # type: ignore[override] """ - Copy the array from the device on which it currently resides to the specified ``device``. + Computes the truth value of ``self_i == other_i`` for each element of an array instance with the respective element of the array ``other``. Parameters ---------- - self: array - array instance. - device: device - a ``device`` object (see :ref:`device-support`). - stream: Optional[Union[int, Any]] - stream object to use during copy. In addition to the types supported in :meth:`array.__dlpack__`, implementations may choose to support any library-specific stream object with the caveat that any code using such an object would not be portable. + self + array instance. May have any data type. + other: Union[int, float, complex, bool, array] + other array. Must be compatible with ``self`` (see :ref:`broadcasting`). May have any data type. Returns ------- out: array - an array with the same data and data type as ``self`` and located on the specified ``device``. + an array containing the element-wise results. The returned array must have a data type of ``bool``. - Notes - ----- - - When a provided ``device`` object corresponds to the same device on which an array instance resides, implementations may choose to perform an explicit copy or return ``self``. - - If ``stream`` is provided, the copy operation should be enqueued on the provided ``stream``; otherwise, the copy operation should be enqueued on the default stream/queue. Whether the copy is performed synchronously or asynchronously is implementation-dependent. Accordingly, if synchronization is required to guarantee data safety, this must be clearly explained in a conforming array library's documentation. + .. note:: + Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.equal`. - .. versionchanged:: 2023.12 - Clarified behavior when a provided ``device`` object corresponds to the device on which an array instance resides. + .. versionchanged:: 2022.12 + Added complex data type support. """ ... - def __getitem__(self: TArray, key: int | slice | TEllipsis | None | tuple[int | slice | TEllipsis | None, ...] | TArray, /) -> TArray: + def __float__(self, /) -> float: """ - Returns ``self[key]``. + Converts a zero-dimensional array to a Python ``float`` object. - See :ref:`indexing` for details on supported indexing semantics. + .. note:: + Casting integer values outside the representable bounds of Python's float type is not specified and is implementation-dependent. Parameters ---------- - self: array - array instance. - key: Union[int, slice, ellipsis, None, Tuple[Union[int, slice, ellipsis, None], ...], array] - index key. + self + zero-dimensional array instance. Should have a real-valued or boolean data type. If ``self`` has a complex floating-point data type, the function must raise a ``TypeError``. Returns ------- - out: array - an array containing the accessed value(s). The returned array must have the same data type as ``self``. - - """ - ... - - def __setitem__(self: TArray, key: int | slice | TEllipsis | tuple[int | slice | TEllipsis, ...] | TArray, value: int | float | complex | bool | TArray, /) -> None: - """ - Sets ``self[key]`` to ``value``. + out: float + a Python ``float`` object representing the single element of the array instance. - See :ref:`indexing` for details on supported indexing semantics. + Notes + ----- + **Special cases** - Parameters - ---------- - self: array - array instance. - key: Union[int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], array] - index key. - value: Union[int, float, complex, bool, array] - value(s) to set. Must be compatible with ``self[key]`` (see :ref:`broadcasting`). + For boolean operands, + - If ``self`` is ``True``, the result is ``1``. + - If ``self`` is ``False``, the result is ``0``. - .. note:: + **Lazy implementations** - Setting array values must not affect the data type of ``self``. + The Python language requires the return value to be of type ``float``. Lazy implementations are therefore not able to return any kind of lazy/delayed object here and should raise a ``ValueError`` instead. - When ``value`` is a Python scalar (i.e., ``int``, ``float``, ``bool``), behavior must follow specification guidance on mixing arrays with Python scalars (see :ref:`type-promotion`). + .. versionchanged:: 2022.12 + Added boolean and complex data type support. - When ``value`` is an ``array`` of a different data type than ``self``, how values are cast to the data type of ``self`` is implementation defined. + .. versionchanged:: 2023.12 + Allowed lazy implementations to error. """ ... - def __add__(self: TArray, other: int | float | complex | TArray, /) -> TArray: + def __floordiv__(self, other: int | float | TArray, /) -> TArray: """ - Calculates the sum for each element of an array instance with the respective element of the array ``other``. + Evaluates ``self_i // other_i`` for each element of an array instance with the respective element of the array ``other``. + + .. note:: + For input arrays which promote to an integer data type, the result of division by zero is unspecified and thus implementation-defined. Parameters ---------- - self: array - array instance (augend array). Should have a numeric data type. - other: Union[int, float, complex, array] - addend array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a numeric data type. + self + array instance. Should have a real-valued data type. + other: Union[int, float, array] + other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a real-valued data type. Returns ------- out: array - an array containing the element-wise sums. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. - Notes - ----- .. note:: - Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.add`. - - .. versionchanged:: 2022.12 - Added complex data type support. + Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.floor_divide`. """ ... - def __sub__(self: TArray, other: int | float | complex | TArray, /) -> TArray: + def __ge__(self, other: int | float | TArray, /) -> TArray: """ - Calculates the difference for each element of an array instance with the respective element of the array ``other``. + Computes the truth value of ``self_i >= other_i`` for each element of an array instance with the respective element of the array ``other``. - The result of ``self_i - other_i`` must be the same as ``self_i + (-other_i)`` and must be governed by the same floating-point rules as addition (see :meth:`array.__add__`). + .. note:: + For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). Parameters ---------- - self: array - array instance (minuend array). Should have a numeric data type. - other: Union[int, float, complex, array] - subtrahend array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a numeric data type. + self + array instance. Should have a real-valued data type. + other: Union[int, float, array] + other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a real-valued data type. Returns ------- out: array - an array containing the element-wise differences. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise results. The returned array must have a data type of ``bool``. - Notes - ----- .. note:: - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.subtract`. - - .. versionchanged:: 2022.12 - Added complex data type support. + Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.greater_equal`. """ ... - def __mul__(self: TArray, other: int | float | complex | TArray, /) -> TArray: + def __getitem__(self, key: int | slice | ellipsis | None | tuple[int | slice | ellipsis | None, ...] | TArray, /) -> TArray: """ - Calculates the product for each element of an array instance with the respective element of the array ``other``. + Returns ``self[key]``. - .. note:: - Floating-point multiplication is not always associative due to finite precision. + See :ref:`indexing` for details on supported indexing semantics. Parameters ---------- - self: array - array instance. Should have a numeric data type. - other: Union[int, float, complex, array] - other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a numeric data type. + self + array instance. + key: Union[int, slice, ellipsis, None, Tuple[Union[int, slice, ellipsis, None], ...], array] + index key. Returns ------- out: array - an array containing the element-wise products. The returned array must have a data type determined by :ref:`type-promotion`. - - Notes - ----- - - .. note:: - Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.multiply`. - - .. versionchanged:: 2022.12 - Added complex data type support. + an array containing the accessed value(s). The returned array must have the same data type as ``self``. """ ... - def __matmul__(self: TArray, other: TArray, /) -> TArray: + def __gt__(self, other: int | float | TArray, /) -> TArray: """ - Computes the matrix product. + Computes the truth value of ``self_i > other_i`` for each element of an array instance with the respective element of the array ``other``. .. note:: - The ``matmul`` function must implement the same semantics as the built-in ``@`` operator (see `PEP 465 `_). + For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). Parameters ---------- - self: array - array instance. Should have a numeric data type. Must have at least one dimension. If ``self`` is one-dimensional having shape ``(M,)`` and ``other`` has more than one dimension, ``self`` must be promoted to a two-dimensional array by prepending ``1`` to its dimensions (i.e., must have shape ``(1, M)``). After matrix multiplication, the prepended dimensions in the returned array must be removed. If ``self`` has more than one dimension (including after vector-to-matrix promotion), ``shape(self)[:-2]`` must be compatible with ``shape(other)[:-2]`` (after vector-to-matrix promotion) (see :ref:`broadcasting`). If ``self`` has shape ``(..., M, K)``, the innermost two dimensions form matrices on which to perform matrix multiplication. - other: array - other array. Should have a numeric data type. Must have at least one dimension. If ``other`` is one-dimensional having shape ``(N,)`` and ``self`` has more than one dimension, ``other`` must be promoted to a two-dimensional array by appending ``1`` to its dimensions (i.e., must have shape ``(N, 1)``). After matrix multiplication, the appended dimensions in the returned array must be removed. If ``other`` has more than one dimension (including after vector-to-matrix promotion), ``shape(other)[:-2]`` must be compatible with ``shape(self)[:-2]`` (after vector-to-matrix promotion) (see :ref:`broadcasting`). If ``other`` has shape ``(..., K, N)``, the innermost two dimensions form matrices on which to perform matrix multiplication. - - - .. note:: - If either ``x1`` or ``x2`` has a complex floating-point data type, neither argument must be complex-conjugated or transposed. If conjugation and/or transposition is desired, these operations should be explicitly performed prior to computing the matrix product. + self + array instance. Should have a real-valued data type. + other: Union[int, float, array] + other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a real-valued data type. Returns ------- out: array - - if both ``self`` and ``other`` are one-dimensional arrays having shape ``(N,)``, a zero-dimensional array containing the inner product as its only element. - - if ``self`` is a two-dimensional array having shape ``(M, K)`` and ``other`` is a two-dimensional array having shape ``(K, N)``, a two-dimensional array containing the `conventional matrix product `_ and having shape ``(M, N)``. - - if ``self`` is a one-dimensional array having shape ``(K,)`` and ``other`` is an array having shape ``(..., K, N)``, an array having shape ``(..., N)`` (i.e., prepended dimensions during vector-to-matrix promotion must be removed) and containing the `conventional matrix product `_. - - if ``self`` is an array having shape ``(..., M, K)`` and ``other`` is a one-dimensional array having shape ``(K,)``, an array having shape ``(..., M)`` (i.e., appended dimensions during vector-to-matrix promotion must be removed) and containing the `conventional matrix product `_. - - if ``self`` is a two-dimensional array having shape ``(M, K)`` and ``other`` is an array having shape ``(..., K, N)``, an array having shape ``(..., M, N)`` and containing the `conventional matrix product `_ for each stacked matrix. - - if ``self`` is an array having shape ``(..., M, K)`` and ``other`` is a two-dimensional array having shape ``(K, N)``, an array having shape ``(..., M, N)`` and containing the `conventional matrix product `_ for each stacked matrix. - - if either ``self`` or ``other`` has more than two dimensions, an array having a shape determined by :ref:`broadcasting` ``shape(self)[:-2]`` against ``shape(other)[:-2]`` and containing the `conventional matrix product `_ for each stacked matrix. - - The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise results. The returned array must have a data type of ``bool``. - Notes - ----- .. note:: - Results must equal the results returned by the equivalent function :func:`~array_api.matmul`. - - **Raises** - - - if either ``self`` or ``other`` is a zero-dimensional array. - - if ``self`` is a one-dimensional array having shape ``(K,)``, ``other`` is a one-dimensional array having shape ``(L,)``, and ``K != L``. - - if ``self`` is a one-dimensional array having shape ``(K,)``, ``other`` is an array having shape ``(..., L, N)``, and ``K != L``. - - if ``self`` is an array having shape ``(..., M, K)``, ``other`` is a one-dimensional array having shape ``(L,)``, and ``K != L``. - - if ``self`` is an array having shape ``(..., M, K)``, ``other`` is an array having shape ``(..., L, N)``, and ``K != L``. - - .. versionchanged:: 2022.12 - Added complex data type support. + Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.greater`. """ ... - def __truediv__(self: TArray, other: int | float | complex | TArray, /) -> TArray: + def __index__(self, /) -> int: """ - Evaluates ``self_i / other_i`` for each element of an array instance with the respective element of the array ``other``. + Converts a zero-dimensional integer array to a Python ``int`` object. .. note:: - If one or both of ``self`` and ``other`` have integer data types, the result is implementation-dependent, as type promotion between data type "kinds" (e.g., integer versus floating-point) is unspecified. - - Specification-compliant libraries may choose to raise an error or return an array containing the element-wise results. If an array is returned, the array must have a real-valued floating-point data type. + This method is called to implement `operator.index() `_. See also `PEP 357 `_. Parameters ---------- - self: array - array instance. Should have a numeric data type. - other: Union[int, float, complex, array] - other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a numeric data type. + self + zero-dimensional array instance. Should have an integer data type. If ``self`` has a floating-point data type, the function must raise a ``TypeError``. Returns ------- - out: array - an array containing the element-wise results. The returned array should have a floating-point data type determined by :ref:`type-promotion`. + out: int + a Python ``int`` object representing the single element of the array instance. Notes ----- + **Lazy implementations** - .. note:: - Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.divide`. - - .. versionchanged:: 2022.12 - Added complex data type support. - - """ - ... - - def __floordiv__(self: TArray, other: int | float | TArray, /) -> TArray: - """ - Evaluates ``self_i // other_i`` for each element of an array instance with the respective element of the array ``other``. - - .. note:: - For input arrays which promote to an integer data type, the result of division by zero is unspecified and thus implementation-defined. - - Parameters - ---------- - self: array - array instance. Should have a real-valued data type. - other: Union[int, float, array] - other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a real-valued data type. - - Returns - ------- - out: array - an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. - + The Python language requires the return value to be of type ``int``. Lazy implementations are therefore not able to return any kind of lazy/delayed object here and should raise a ``ValueError`` instead. - .. note:: - Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.floor_divide`. + .. versionchanged:: 2023.12 + Allowed lazy implementations to error. """ ... - def __mod__(self: TArray, other: int | float | TArray, /) -> TArray: + def __int__(self, /) -> int: """ - Evaluates ``self_i % other_i`` for each element of an array instance with the respective element of the array ``other``. - - .. note:: - For input arrays which promote to an integer data type, the result of division by zero is unspecified and thus implementation-defined. + Converts a zero-dimensional array to a Python ``int`` object. Parameters ---------- - self: array - array instance. Should have a real-valued data type. - other: Union[int, float, array] - other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a real-valued data type. + self + zero-dimensional array instance. Should have a real-valued or boolean data type. If ``self`` has a complex floating-point data type, the function must raise a ``TypeError``. Returns ------- - out: array - an array containing the element-wise results. Each element-wise result must have the same sign as the respective element ``other_i``. The returned array must have a real-valued floating-point data type determined by :ref:`type-promotion`. + out: int + a Python ``int`` object representing the single element of the array instance. + Notes + ----- + **Special cases** - .. note:: - Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.remainder`. + For boolean operands, - """ - ... + - If ``self`` is ``True``, the result is ``1``. + - If ``self`` is ``False``, the result is ``0``. - def __pow__(self: TArray, other: int | float | complex | TArray, /) -> TArray: - """ - Calculates an implementation-dependent approximation of exponentiation by raising each element (the base) of an array instance to the power of ``other_i`` (the exponent), where ``other_i`` is the corresponding element of the array ``other``. + For floating-point operands, - .. note:: - If both ``self`` and ``other`` have integer data types, the result of ``__pow__`` when `other_i` is negative (i.e., less than zero) is unspecified and thus implementation-dependent. + - If ``self`` is a finite number, the result is the integer part of ``self``. + - If ``self`` is ``-0``, the result is ``0``. - If ``self`` has an integer data type and ``other`` has a floating-point data type, behavior is implementation-dependent, as type promotion between data type "kinds" (e.g., integer versus floating-point) is unspecified. + **Raises** - Parameters - ---------- - self: array - array instance whose elements correspond to the exponentiation base. Should have a numeric data type. - other: Union[int, float, complex, array] - other array whose elements correspond to the exponentiation exponent. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a numeric data type. + For floating-point operands, - Returns - ------- - out: array - an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. + - If ``self`` is either ``+infinity`` or ``-infinity``, raise ``OverflowError``. + - If ``self`` is ``NaN``, raise ``ValueError``. Notes ----- + **Lazy implementations** - .. note:: - Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.pow`. + The Python language requires the return value to be of type ``int``. Lazy implementations are therefore not able to return any kind of lazy/delayed object here and should raise a ``ValueError`` instead. .. versionchanged:: 2022.12 - Added complex data type support. + Added boolean and complex data type support. + + .. versionchanged:: 2023.12 + Allowed lazy implementations to error. """ ... - def __lshift__(self: TArray, other: int | TArray, /) -> TArray: + def __invert__(self, /) -> TArray: """ - Evaluates ``self_i << other_i`` for each element of an array instance with the respective element of the array ``other``. + Evaluates ``~self_i`` for each element of an array instance. Parameters ---------- - self: array - array instance. Should have an integer data type. - other: Union[int, array] - other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have an integer data type. Each element must be greater than or equal to ``0``. + self + array instance. Should have an integer or boolean data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have the same data type as ``self``. + an array containing the element-wise results. The returned array must have the same data type as `self`. .. note:: - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.bitwise_left_shift`. + Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.bitwise_invert`. """ ... - def __rshift__(self: TArray, other: int | TArray, /) -> TArray: + def __le__(self, other: int | float | TArray, /) -> TArray: """ - Evaluates ``self_i >> other_i`` for each element of an array instance with the respective element of the array ``other``. - - Parameters - ---------- - self: array - array instance. Should have an integer data type. - other: Union[int, array] - other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have an integer data type. Each element must be greater than or equal to ``0``. - - Returns - ------- - out: array - an array containing the element-wise results. The returned array must have the same data type as ``self``. - + Computes the truth value of ``self_i <= other_i`` for each element of an array instance with the respective element of the array ``other``. .. note:: - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.bitwise_right_shift`. - - """ - ... - - def __and__(self: TArray, other: int | bool | TArray, /) -> TArray: - """ - Evaluates ``self_i & other_i`` for each element of an array instance with the respective element of the array ``other``. + For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). Parameters ---------- - self: array - array instance. Should have an integer or boolean data type. - other: Union[int, bool, array] - other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have an integer or boolean data type. + self + array instance. Should have a real-valued data type. + other: Union[int, float, array] + other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a real-valued data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise results. The returned array must have a data type of ``bool``. .. note:: - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.bitwise_and`. + Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.less_equal`. """ ... - def __xor__(self: TArray, other: int | bool | TArray, /) -> TArray: + def __lshift__(self, other: int | TArray, /) -> TArray: """ - Evaluates ``self_i ^ other_i`` for each element of an array instance with the respective element of the array ``other``. + Evaluates ``self_i << other_i`` for each element of an array instance with the respective element of the array ``other``. Parameters ---------- - self: array - array instance. Should have an integer or boolean data type. - other: Union[int, bool, array] - other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have an integer or boolean data type. + self + array instance. Should have an integer data type. + other: Union[int, array] + other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have an integer data type. Each element must be greater than or equal to ``0``. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise results. The returned array must have the same data type as ``self``. .. note:: - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.bitwise_xor`. + Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.bitwise_left_shift`. """ ... - def __or__(self: TArray, other: int | bool | TArray, /) -> TArray: + def __lt__(self, other: int | float | TArray, /) -> TArray: """ - Evaluates ``self_i | other_i`` for each element of an array instance with the respective element of the array ``other``. + Computes the truth value of ``self_i < other_i`` for each element of an array instance with the respective element of the array ``other``. + + .. note:: + For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). Parameters ---------- - self: array - array instance. Should have an integer or boolean data type. - other: Union[int, bool, array] - other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have an integer or boolean data type. + self + array instance. Should have a real-valued data type. + other: Union[int, float, array] + other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a real-valued data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise results. The returned array must have a data type of ``bool``. .. note:: - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.bitwise_or`. + Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.less`. """ ... - def __neg__(self: TArray, /) -> TArray: + def __matmul__(self, other: TArray, /) -> TArray: """ - Evaluates ``-self_i`` for each element of an array instance. - - .. note:: - For signed integer data types, the numerical negative of the minimum representable integer is implementation-dependent. + Computes the matrix product. .. note:: - If ``self`` has a complex floating-point data type, both the real and imaginary components for each ``self_i`` must be negated (a result which follows from the rules of complex number multiplication). + The ``matmul`` function must implement the same semantics as the built-in ``@`` operator (see `PEP 465 `_). Parameters ---------- - self: array - array instance. Should have a numeric data type. - - Returns - ------- - out: array - an array containing the evaluated result for each element in ``self``. The returned array must have a data type determined by :ref:`type-promotion`. + self + array instance. Should have a numeric data type. Must have at least one dimension. If ``self`` is one-dimensional having shape ``(M,)`` and ``other`` has more than one dimension, ``self`` must be promoted to a two-dimensional array by prepending ``1`` to its dimensions (i.e., must have shape ``(1, M)``). After matrix multiplication, the prepended dimensions in the returned array must be removed. If ``self`` has more than one dimension (including after vector-to-matrix promotion), ``shape(self)[:-2]`` must be compatible with ``shape(other)[:-2]`` (after vector-to-matrix promotion) (see :ref:`broadcasting`). If ``self`` has shape ``(..., M, K)``, the innermost two dimensions form matrices on which to perform matrix multiplication. + other: array + other array. Should have a numeric data type. Must have at least one dimension. If ``other`` is one-dimensional having shape ``(N,)`` and ``self`` has more than one dimension, ``other`` must be promoted to a two-dimensional array by appending ``1`` to its dimensions (i.e., must have shape ``(N, 1)``). After matrix multiplication, the appended dimensions in the returned array must be removed. If ``other`` has more than one dimension (including after vector-to-matrix promotion), ``shape(other)[:-2]`` must be compatible with ``shape(self)[:-2]`` (after vector-to-matrix promotion) (see :ref:`broadcasting`). If ``other`` has shape ``(..., K, N)``, the innermost two dimensions form matrices on which to perform matrix multiplication. - Notes - ----- .. note:: - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.negative`. - - .. versionchanged:: 2022.12 - Added complex data type support. - - """ - ... - - def __pos__(self: TArray, /) -> TArray: - """ - Evaluates ``+self_i`` for each element of an array instance. - - Parameters - ---------- - self: array - array instance. Should have a numeric data type. + If either ``x1`` or ``x2`` has a complex floating-point data type, neither argument must be complex-conjugated or transposed. If conjugation and/or transposition is desired, these operations should be explicitly performed prior to computing the matrix product. Returns ------- out: array - an array containing the evaluated result for each element. The returned array must have the same data type as ``self``. + - if both ``self`` and ``other`` are one-dimensional arrays having shape ``(N,)``, a zero-dimensional array containing the inner product as its only element. + - if ``self`` is a two-dimensional array having shape ``(M, K)`` and ``other`` is a two-dimensional array having shape ``(K, N)``, a two-dimensional array containing the `conventional matrix product `_ and having shape ``(M, N)``. + - if ``self`` is a one-dimensional array having shape ``(K,)`` and ``other`` is an array having shape ``(..., K, N)``, an array having shape ``(..., N)`` (i.e., prepended dimensions during vector-to-matrix promotion must be removed) and containing the `conventional matrix product `_. + - if ``self`` is an array having shape ``(..., M, K)`` and ``other`` is a one-dimensional array having shape ``(K,)``, an array having shape ``(..., M)`` (i.e., appended dimensions during vector-to-matrix promotion must be removed) and containing the `conventional matrix product `_. + - if ``self`` is a two-dimensional array having shape ``(M, K)`` and ``other`` is an array having shape ``(..., K, N)``, an array having shape ``(..., M, N)`` and containing the `conventional matrix product `_ for each stacked matrix. + - if ``self`` is an array having shape ``(..., M, K)`` and ``other`` is a two-dimensional array having shape ``(K, N)``, an array having shape ``(..., M, N)`` and containing the `conventional matrix product `_ for each stacked matrix. + - if either ``self`` or ``other`` has more than two dimensions, an array having a shape determined by :ref:`broadcasting` ``shape(self)[:-2]`` against ``shape(other)[:-2]`` and containing the `conventional matrix product `_ for each stacked matrix. + - The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- .. note:: - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.positive`. - - .. versionchanged:: 2022.12 - Added complex data type support. - - """ - ... - - def __abs__(self: TArray, /) -> TArray: - """ - Calculates the absolute value for each element of an array instance. - - For real-valued input arrays, the element-wise result has the same magnitude as the respective element in ``x`` but has positive sign. - - .. note:: - For signed integer data types, the absolute value of the minimum representable integer is implementation-dependent. - - Parameters - ---------- - self: array - array instance. Should have a numeric data type. - - Returns - ------- - out: array - an array containing the element-wise absolute value. If ``self`` has a real-valued data type, the returned array must have the same data type as ``self``. If ``self`` has a complex floating-point data type, the returned arrayed must have a real-valued floating-point data type whose precision matches the precision of ``self`` (e.g., if ``self`` is ``complex128``, then the returned array must have a ``float64`` data type). + Results must equal the results returned by the equivalent function :func:`~array_api.matmul`. - Notes - ----- + **Raises** - .. note:: - Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.abs`. + - if either ``self`` or ``other`` is a zero-dimensional array. + - if ``self`` is a one-dimensional array having shape ``(K,)``, ``other`` is a one-dimensional array having shape ``(L,)``, and ``K != L``. + - if ``self`` is a one-dimensional array having shape ``(K,)``, ``other`` is an array having shape ``(..., L, N)``, and ``K != L``. + - if ``self`` is an array having shape ``(..., M, K)``, ``other`` is a one-dimensional array having shape ``(L,)``, and ``K != L``. + - if ``self`` is an array having shape ``(..., M, K)``, ``other`` is an array having shape ``(..., L, N)``, and ``K != L``. .. versionchanged:: 2022.12 Added complex data type support. @@ -931,37 +948,16 @@ def __abs__(self: TArray, /) -> TArray: """ ... - def __invert__(self: TArray, /) -> TArray: + def __mod__(self, other: int | float | TArray, /) -> TArray: """ - Evaluates ``~self_i`` for each element of an array instance. - - Parameters - ---------- - self: array - array instance. Should have an integer or boolean data type. - - Returns - ------- - out: array - an array containing the element-wise results. The returned array must have the same data type as `self`. - - - .. note:: - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.bitwise_invert`. - - """ - ... - - def __lt__(self: TArray, other: int | float | TArray, /) -> TArray: - """ - Computes the truth value of ``self_i < other_i`` for each element of an array instance with the respective element of the array ``other``. + Evaluates ``self_i % other_i`` for each element of an array instance with the respective element of the array ``other``. .. note:: - For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). + For input arrays which promote to an integer data type, the result of division by zero is unspecified and thus implementation-defined. Parameters ---------- - self: array + self array instance. Should have a real-valued data type. other: Union[int, float, array] other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a real-valued data type. @@ -969,48 +965,53 @@ def __lt__(self: TArray, other: int | float | TArray, /) -> TArray: Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type of ``bool``. + an array containing the element-wise results. Each element-wise result must have the same sign as the respective element ``other_i``. The returned array must have a real-valued floating-point data type determined by :ref:`type-promotion`. .. note:: - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.less`. + Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.remainder`. """ ... - def __le__(self: TArray, other: int | float | TArray, /) -> TArray: + def __mul__(self, other: int | float | complex | TArray, /) -> TArray: """ - Computes the truth value of ``self_i <= other_i`` for each element of an array instance with the respective element of the array ``other``. + Calculates the product for each element of an array instance with the respective element of the array ``other``. .. note:: - For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). + Floating-point multiplication is not always associative due to finite precision. Parameters ---------- - self: array - array instance. Should have a real-valued data type. - other: Union[int, float, array] - other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a real-valued data type. + self + array instance. Should have a numeric data type. + other: Union[int, float, complex, array] + other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a numeric data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type of ``bool``. + an array containing the element-wise products. The returned array must have a data type determined by :ref:`type-promotion`. + Notes + ----- .. note:: - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.less_equal`. + Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.multiply`. + + .. versionchanged:: 2022.12 + Added complex data type support. """ ... - def __eq__(self: TArray, other: int | float | complex | bool | TArray, /) -> TArray: # type: ignore[override] + def __ne__(self, other: int | float | complex | bool | TArray, /) -> TArray: # type: ignore[override] """ - Computes the truth value of ``self_i == other_i`` for each element of an array instance with the respective element of the array ``other``. + Computes the truth value of ``self_i != other_i`` for each element of an array instance with the respective element of the array ``other``. Parameters ---------- - self: array + self array instance. May have any data type. other: Union[int, float, complex, bool, array] other array. Must be compatible with ``self`` (see :ref:`broadcasting`). May have any data type. @@ -1018,11 +1019,14 @@ def __eq__(self: TArray, other: int | float | complex | bool | TArray, /) -> TAr Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type of ``bool``. + an array containing the element-wise results. The returned array must have a data type of ``bool`` (i.e., must be a boolean array). + + Notes + ----- .. note:: - Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.equal`. + Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.not_equal`. .. versionchanged:: 2022.12 Added complex data type support. @@ -1030,28 +1034,31 @@ def __eq__(self: TArray, other: int | float | complex | bool | TArray, /) -> TAr """ ... - def __ne__(self: TArray, other: int | float | complex | bool | TArray, /) -> TArray: # type: ignore[override] + def __neg__(self, /) -> TArray: """ - Computes the truth value of ``self_i != other_i`` for each element of an array instance with the respective element of the array ``other``. + Evaluates ``-self_i`` for each element of an array instance. + + .. note:: + For signed integer data types, the numerical negative of the minimum representable integer is implementation-dependent. + + .. note:: + If ``self`` has a complex floating-point data type, both the real and imaginary components for each ``self_i`` must be negated (a result which follows from the rules of complex number multiplication). Parameters ---------- - self: array - array instance. May have any data type. - other: Union[int, float, complex, bool, array] - other array. Must be compatible with ``self`` (see :ref:`broadcasting`). May have any data type. + self + array instance. Should have a numeric data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type of ``bool`` (i.e., must be a boolean array). - + an array containing the evaluated result for each element in ``self``. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- .. note:: - Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.not_equal`. + Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.negative`. .. versionchanged:: 2022.12 Added complex data type support. @@ -1059,253 +1066,250 @@ def __ne__(self: TArray, other: int | float | complex | bool | TArray, /) -> TAr """ ... - def __gt__(self: TArray, other: int | float | TArray, /) -> TArray: + def __or__(self, other: int | bool | TArray, /) -> TArray: """ - Computes the truth value of ``self_i > other_i`` for each element of an array instance with the respective element of the array ``other``. - - .. note:: - For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). + Evaluates ``self_i | other_i`` for each element of an array instance with the respective element of the array ``other``. Parameters ---------- - self: array - array instance. Should have a real-valued data type. - other: Union[int, float, array] - other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a real-valued data type. + self + array instance. Should have an integer or boolean data type. + other: Union[int, bool, array] + other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have an integer or boolean data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type of ``bool``. + an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. .. note:: - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.greater`. + Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.bitwise_or`. """ ... - def __ge__(self: TArray, other: int | float | TArray, /) -> TArray: + def __pos__(self, /) -> TArray: """ - Computes the truth value of ``self_i >= other_i`` for each element of an array instance with the respective element of the array ``other``. - - .. note:: - For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). + Evaluates ``+self_i`` for each element of an array instance. Parameters ---------- - self: array - array instance. Should have a real-valued data type. - other: Union[int, float, array] - other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a real-valued data type. + self + array instance. Should have a numeric data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type of ``bool``. + an array containing the evaluated result for each element. The returned array must have the same data type as ``self``. + Notes + ----- .. note:: - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.greater_equal`. + Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.positive`. + + .. versionchanged:: 2022.12 + Added complex data type support. """ ... - def __bool__(self: TArray, /) -> bool: + def __pow__(self, other: int | float | complex | TArray, /) -> TArray: """ - Converts a zero-dimensional array to a Python ``bool`` object. + Calculates an implementation-dependent approximation of exponentiation by raising each element (the base) of an array instance to the power of ``other_i`` (the exponent), where ``other_i`` is the corresponding element of the array ``other``. + + .. note:: + If both ``self`` and ``other`` have integer data types, the result of ``__pow__`` when `other_i` is negative (i.e., less than zero) is unspecified and thus implementation-dependent. + + If ``self`` has an integer data type and ``other`` has a floating-point data type, behavior is implementation-dependent, as type promotion between data type "kinds" (e.g., integer versus floating-point) is unspecified. Parameters ---------- - self: array - zero-dimensional array instance. + self + array instance whose elements correspond to the exponentiation base. Should have a numeric data type. + other: Union[int, float, complex, array] + other array whose elements correspond to the exponentiation exponent. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a numeric data type. Returns ------- - out: bool - a Python ``bool`` object representing the single element of the array. + out: array + an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- - **Special cases** - - For real-valued floating-point operands, - - - If ``self`` is ``NaN``, the result is ``True``. - - If ``self`` is either ``+infinity`` or ``-infinity``, the result is ``True``. - - If ``self`` is either ``+0`` or ``-0``, the result is ``False``. - - For complex floating-point operands, special cases must be handled as if the operation is implemented as the logical OR of ``bool(real(self))`` and ``bool(imag(self))``. - - **Lazy implementations** - The Python language requires the return value to be of type ``bool``. Lazy implementations are therefore not able to return any kind of lazy/delayed object here and should raise a ``ValueError`` instead. + .. note:: + Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.pow`. .. versionchanged:: 2022.12 - Added boolean and complex data type support. - - .. versionchanged:: 2023.12 - Allowed lazy implementations to error. + Added complex data type support. """ ... - def __complex__(self: TArray, /) -> complex: + def __rshift__(self, other: int | TArray, /) -> TArray: """ - Converts a zero-dimensional array to a Python ``complex`` object. + Evaluates ``self_i >> other_i`` for each element of an array instance with the respective element of the array ``other``. Parameters ---------- - self: array - zero-dimensional array instance. + self + array instance. Should have an integer data type. + other: Union[int, array] + other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have an integer data type. Each element must be greater than or equal to ``0``. Returns ------- - out: complex - a Python ``complex`` object representing the single element of the array instance. + out: array + an array containing the element-wise results. The returned array must have the same data type as ``self``. - Notes - ----- - **Special cases** - For boolean operands, + .. note:: + Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.bitwise_right_shift`. - - If ``self`` is ``True``, the result is ``1+0j``. - - If ``self`` is ``False``, the result is ``0+0j``. + """ + ... - For real-valued floating-point operands, + def __setitem__(self, key: int | slice | ellipsis | tuple[int | slice | ellipsis, ...] | TArray, value: int | float | complex | bool | TArray, /) -> None: + """ + Sets ``self[key]`` to ``value``. - - If ``self`` is ``NaN``, the result is ``NaN + NaN j``. - - If ``self`` is ``+infinity``, the result is ``+infinity + 0j``. - - If ``self`` is ``-infinity``, the result is ``-infinity + 0j``. - - If ``self`` is a finite number, the result is ``self + 0j``. + See :ref:`indexing` for details on supported indexing semantics. - **Lazy implementations** + Parameters + ---------- + self + array instance. + key: Union[int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], array] + index key. + value: Union[int, float, complex, bool, array] + value(s) to set. Must be compatible with ``self[key]`` (see :ref:`broadcasting`). - The Python language requires the return value to be of type ``complex``. Lazy implementations are therefore not able to return any kind of lazy/delayed object here and should raise a ``ValueError`` instead. - .. versionadded:: 2022.12 + .. note:: - .. versionchanged:: 2023.12 - Allowed lazy implementations to error. + Setting array values must not affect the data type of ``self``. + + When ``value`` is a Python scalar (i.e., ``int``, ``float``, ``bool``), behavior must follow specification guidance on mixing arrays with Python scalars (see :ref:`type-promotion`). + + When ``value`` is an ``array`` of a different data type than ``self``, how values are cast to the data type of ``self`` is implementation defined. """ ... - def __int__(self: TArray, /) -> int: + def __sub__(self, other: int | float | complex | TArray, /) -> TArray: """ - Converts a zero-dimensional array to a Python ``int`` object. + Calculates the difference for each element of an array instance with the respective element of the array ``other``. + + The result of ``self_i - other_i`` must be the same as ``self_i + (-other_i)`` and must be governed by the same floating-point rules as addition (see :meth:`array.__add__`). Parameters ---------- - self: array - zero-dimensional array instance. Should have a real-valued or boolean data type. If ``self`` has a complex floating-point data type, the function must raise a ``TypeError``. + self + array instance (minuend array). Should have a numeric data type. + other: Union[int, float, complex, array] + subtrahend array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a numeric data type. Returns ------- - out: int - a Python ``int`` object representing the single element of the array instance. + out: array + an array containing the element-wise differences. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- - **Special cases** - For boolean operands, + .. note:: + Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.subtract`. - - If ``self`` is ``True``, the result is ``1``. - - If ``self`` is ``False``, the result is ``0``. + .. versionchanged:: 2022.12 + Added complex data type support. - For floating-point operands, + """ + ... - - If ``self`` is a finite number, the result is the integer part of ``self``. - - If ``self`` is ``-0``, the result is ``0``. + def __truediv__(self, other: int | float | complex | TArray, /) -> TArray: + """ + Evaluates ``self_i / other_i`` for each element of an array instance with the respective element of the array ``other``. - **Raises** + .. note:: + If one or both of ``self`` and ``other`` have integer data types, the result is implementation-dependent, as type promotion between data type "kinds" (e.g., integer versus floating-point) is unspecified. - For floating-point operands, + Specification-compliant libraries may choose to raise an error or return an array containing the element-wise results. If an array is returned, the array must have a real-valued floating-point data type. - - If ``self`` is either ``+infinity`` or ``-infinity``, raise ``OverflowError``. - - If ``self`` is ``NaN``, raise ``ValueError``. + Parameters + ---------- + self + array instance. Should have a numeric data type. + other: Union[int, float, complex, array] + other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a numeric data type. + + Returns + ------- + out: array + an array containing the element-wise results. The returned array should have a floating-point data type determined by :ref:`type-promotion`. Notes ----- - **Lazy implementations** - The Python language requires the return value to be of type ``int``. Lazy implementations are therefore not able to return any kind of lazy/delayed object here and should raise a ``ValueError`` instead. + .. note:: + Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.divide`. .. versionchanged:: 2022.12 - Added boolean and complex data type support. - - .. versionchanged:: 2023.12 - Allowed lazy implementations to error. + Added complex data type support. """ ... - def __float__(self: TArray, /) -> float: + def __xor__(self, other: int | bool | TArray, /) -> TArray: """ - Converts a zero-dimensional array to a Python ``float`` object. - - .. note:: - Casting integer values outside the representable bounds of Python's float type is not specified and is implementation-dependent. + Evaluates ``self_i ^ other_i`` for each element of an array instance with the respective element of the array ``other``. Parameters ---------- - self: array - zero-dimensional array instance. Should have a real-valued or boolean data type. If ``self`` has a complex floating-point data type, the function must raise a ``TypeError``. + self + array instance. Should have an integer or boolean data type. + other: Union[int, bool, array] + other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have an integer or boolean data type. Returns ------- - out: float - a Python ``float`` object representing the single element of the array instance. - - Notes - ----- - **Special cases** - - For boolean operands, - - - If ``self`` is ``True``, the result is ``1``. - - If ``self`` is ``False``, the result is ``0``. - - **Lazy implementations** - - The Python language requires the return value to be of type ``float``. Lazy implementations are therefore not able to return any kind of lazy/delayed object here and should raise a ``ValueError`` instead. + out: array + an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. - .. versionchanged:: 2022.12 - Added boolean and complex data type support. - .. versionchanged:: 2023.12 - Allowed lazy implementations to error. + .. note:: + Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.bitwise_xor`. """ ... - def __index__(self: TArray, /) -> int: + def to_device(self, device: TDevice, /, *, stream: int | Any | None = None) -> TArray: """ - Converts a zero-dimensional integer array to a Python ``int`` object. - - .. note:: - This method is called to implement `operator.index() `_. See also `PEP 357 `_. + Copy the array from the device on which it currently resides to the specified ``device``. Parameters ---------- - self: array - zero-dimensional array instance. Should have an integer data type. If ``self`` has a floating-point data type, the function must raise a ``TypeError``. + self + array instance. + device: device + a ``device`` object (see :ref:`device-support`). + stream: Optional[Union[int, Any]] + stream object to use during copy. In addition to the types supported in :meth:`array.__dlpack__`, implementations may choose to support any library-specific stream object with the caveat that any code using such an object would not be portable. Returns ------- - out: int - a Python ``int`` object representing the single element of the array instance. + out: array + an array with the same data and data type as ``self`` and located on the specified ``device``. + Notes ----- - **Lazy implementations** - - The Python language requires the return value to be of type ``int``. Lazy implementations are therefore not able to return any kind of lazy/delayed object here and should raise a ``ValueError`` instead. + - When a provided ``device`` object corresponds to the same device on which an array instance resides, implementations may choose to perform an explicit copy or return ``self``. + - If ``stream`` is provided, the copy operation should be enqueued on the provided ``stream``; otherwise, the copy operation should be enqueued on the default stream/queue. Whether the copy is performed synchronously or asynchronously is implementation-dependent. Accordingly, if synchronization is required to guarantee data safety, this must be clearly explained in a conforming array library's documentation. .. versionchanged:: 2023.12 - Allowed lazy implementations to error. + Clarified behavior when a provided ``device`` object corresponds to the device on which an array instance resides. """ ... @@ -1317,47 +1321,47 @@ class astype[TArray: Array, TDevice, TDtype](Protocol): Copies an array to a specified data type irrespective of :ref:`type-promotion` rules. .. note:: - Casting floating-point ``NaN`` and ``infinity`` values to integral data types is not specified and is implementation-dependent. + Casting floating-point ``NaN`` and ``infinity`` values to integral data types is not specified and is implementation-dependent. .. note:: - Casting a complex floating-point array to a real-valued data type should not be permitted. + Casting a complex floating-point array to a real-valued data type should not be permitted. - Historically, when casting a complex floating-point array to a real-valued data type, libraries such as NumPy have discarded imaginary components such that, for a complex floating-point array ``x``, ``astype(x)`` equals ``astype(real(x))``). This behavior is considered problematic as the choice to discard the imaginary component is arbitrary and introduces more than one way to achieve the same outcome (i.e., for a complex floating-point array ``x``, ``astype(x)`` and ``astype(real(x))`` versus only ``astype(imag(x))``). Instead, in order to avoid ambiguity and to promote clarity, this specification requires that array API consumers explicitly express which component should be cast to a specified real-valued data type. + Historically, when casting a complex floating-point array to a real-valued data type, libraries such as NumPy have discarded imaginary components such that, for a complex floating-point array ``x``, ``astype(x)`` equals ``astype(real(x))``). This behavior is considered problematic as the choice to discard the imaginary component is arbitrary and introduces more than one way to achieve the same outcome (i.e., for a complex floating-point array ``x``, ``astype(x)`` and ``astype(real(x))`` versus only ``astype(imag(x))``). Instead, in order to avoid ambiguity and to promote clarity, this specification requires that array API consumers explicitly express which component should be cast to a specified real-valued data type. .. note:: - When casting a boolean input array to a real-valued data type, a value of ``True`` must cast to a real-valued number equal to ``1``, and a value of ``False`` must cast to a real-valued number equal to ``0``. + When casting a boolean input array to a real-valued data type, a value of ``True`` must cast to a real-valued number equal to ``1``, and a value of ``False`` must cast to a real-valued number equal to ``0``. - When casting a boolean input array to a complex floating-point data type, a value of ``True`` must cast to a complex number equal to ``1 + 0j``, and a value of ``False`` must cast to a complex number equal to ``0 + 0j``. + When casting a boolean input array to a complex floating-point data type, a value of ``True`` must cast to a complex number equal to ``1 + 0j``, and a value of ``False`` must cast to a complex number equal to ``0 + 0j``. .. note:: - When casting a real-valued input array to ``bool``, a value of ``0`` must cast to ``False``, and a non-zero value must cast to ``True``. + When casting a real-valued input array to ``bool``, a value of ``0`` must cast to ``False``, and a non-zero value must cast to ``True``. - When casting a complex floating-point array to ``bool``, a value of ``0 + 0j`` must cast to ``False``, and all other values must cast to ``True``. + When casting a complex floating-point array to ``bool``, a value of ``0 + 0j`` must cast to ``False``, and all other values must cast to ``True``. Parameters ---------- x: array - array to cast. + array to cast. dtype: dtype - desired data type. + desired data type. copy: bool - specifies whether to copy an array when the specified ``dtype`` matches the data type of the input array ``x``. If ``True``, a newly allocated array must always be returned. If ``False`` and the specified ``dtype`` matches the data type of the input array, the input array must be returned; otherwise, a newly allocated array must be returned. Default: ``True``. + specifies whether to copy an array when the specified ``dtype`` matches the data type of the input array ``x``. If ``True``, a newly allocated array must always be returned. If ``False`` and the specified ``dtype`` matches the data type of the input array, the input array must be returned; otherwise, a newly allocated array must be returned. Default: ``True``. device: Optional[device] - device on which to place the returned array. If ``device`` is ``None``, the output array device must be inferred from ``x``. Default: ``None``. + device on which to place the returned array. If ``device`` is ``None``, the output array device must be inferred from ``x``. Default: ``None``. Returns ------- out: array - an array having the specified data type. The returned array must have the same shape as ``x``. + an array having the specified data type. The returned array must have the same shape as ``x``. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. .. versionchanged:: 2023.12 - Added device keyword argument support. + Added device keyword argument support. """ @@ -1373,14 +1377,14 @@ class can_cast[TArray: Array, TDtype](Protocol): Parameters ---------- from_: Union[dtype, array] - input data type or array from which to cast. + input data type or array from which to cast. to: dtype - desired data type. + desired data type. Returns ------- out: bool - ``True`` if the cast can occur according to :ref:`type-promotion` rules; otherwise, ``False``. + ``True`` if the cast can occur according to :ref:`type-promotion` rules; otherwise, ``False``. """ @@ -1396,47 +1400,47 @@ class finfo[TArray: Array, TDtype](Protocol): Parameters ---------- type: Union[dtype, array] - the kind of floating-point data-type about which to get information. If complex, the information is about its component data type. + the kind of floating-point data-type about which to get information. If complex, the information is about its component data type. - .. note:: - Complex floating-point data types are specified to always use the same precision for both its real and imaginary components, so the information should be true for either component. + .. note:: + Complex floating-point data types are specified to always use the same precision for both its real and imaginary components, so the information should be true for either component. Returns ------- out: finfo object - an object having the following attributes: + an object having the following attributes: - - **bits**: *int* + - **bits**: *int* - number of bits occupied by the real-valued floating-point data type. + number of bits occupied by the real-valued floating-point data type. - - **eps**: *float* + - **eps**: *float* - difference between 1.0 and the next smallest representable real-valued floating-point number larger than 1.0 according to the IEEE-754 standard. + difference between 1.0 and the next smallest representable real-valued floating-point number larger than 1.0 according to the IEEE-754 standard. - - **max**: *float* + - **max**: *float* - largest representable real-valued number. + largest representable real-valued number. - - **min**: *float* + - **min**: *float* - smallest representable real-valued number. + smallest representable real-valued number. - - **smallest_normal**: *float* + - **smallest_normal**: *float* - smallest positive real-valued floating-point number with full precision. + smallest positive real-valued floating-point number with full precision. - - **dtype**: dtype + - **dtype**: dtype - real-valued floating-point data type. + real-valued floating-point data type. - .. versionadded:: 2022.12 + .. versionadded:: 2022.12 Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -1452,30 +1456,30 @@ class iinfo[TArray: Array, TDtype](Protocol): Parameters ---------- type: Union[dtype, array] - the kind of integer data-type about which to get information. + the kind of integer data-type about which to get information. Returns ------- out: iinfo object - an object having the following attributes: + an object having the following attributes: - - **bits**: *int* + - **bits**: *int* - number of bits occupied by the type. + number of bits occupied by the type. - - **max**: *int* + - **max**: *int* - largest representable number. + largest representable number. - - **min**: *int* + - **min**: *int* - smallest representable number. + smallest representable number. - - **dtype**: dtype + - **dtype**: dtype - integer data type. + integer data type. - .. versionadded:: 2022.12 + .. versionadded:: 2022.12 """ @@ -1491,32 +1495,32 @@ class isdtype[TDtype](Protocol): Parameters ---------- dtype: dtype - the input dtype. + the input dtype. kind: Union[str, dtype, Tuple[Union[str, dtype], ...]] - data type kind. + data type kind. - - If ``kind`` is a dtype, the function must return a boolean indicating whether the input ``dtype`` is equal to the dtype specified by ``kind``. - - If ``kind`` is a string, the function must return a boolean indicating whether the input ``dtype`` is of a specified data type kind. The following dtype kinds must be supported: + - If ``kind`` is a dtype, the function must return a boolean indicating whether the input ``dtype`` is equal to the dtype specified by ``kind``. + - If ``kind`` is a string, the function must return a boolean indicating whether the input ``dtype`` is of a specified data type kind. The following dtype kinds must be supported: - - ``'bool'``: boolean data types (e.g., ``bool``). - - ``'signed integer'``: signed integer data types (e.g., ``int8``, ``int16``, ``int32``, ``int64``). - - ``'unsigned integer'``: unsigned integer data types (e.g., ``uint8``, ``uint16``, ``uint32``, ``uint64``). - - ``'integral'``: integer data types. Shorthand for ``('signed integer', 'unsigned integer')``. - - ``'real floating'``: real-valued floating-point data types (e.g., ``float32``, ``float64``). - - ``'complex floating'``: complex floating-point data types (e.g., ``complex64``, ``complex128``). - - ``'numeric'``: numeric data types. Shorthand for ``('integral', 'real floating', 'complex floating')``. + - ``'bool'``: boolean data types (e.g., ``bool``). + - ``'signed integer'``: signed integer data types (e.g., ``int8``, ``int16``, ``int32``, ``int64``). + - ``'unsigned integer'``: unsigned integer data types (e.g., ``uint8``, ``uint16``, ``uint32``, ``uint64``). + - ``'integral'``: integer data types. Shorthand for ``('signed integer', 'unsigned integer')``. + - ``'real floating'``: real-valued floating-point data types (e.g., ``float32``, ``float64``). + - ``'complex floating'``: complex floating-point data types (e.g., ``complex64``, ``complex128``). + - ``'numeric'``: numeric data types. Shorthand for ``('integral', 'real floating', 'complex floating')``. - - If ``kind`` is a tuple, the tuple specifies a union of dtypes and/or kinds, and the function must return a boolean indicating whether the input ``dtype`` is either equal to a specified dtype or belongs to at least one specified data type kind. + - If ``kind`` is a tuple, the tuple specifies a union of dtypes and/or kinds, and the function must return a boolean indicating whether the input ``dtype`` is either equal to a specified dtype or belongs to at least one specified data type kind. - .. note:: - A conforming implementation of the array API standard is **not** limited to only including the dtypes described in this specification in the required data type kinds. For example, implementations supporting ``float16`` and ``bfloat16`` can include ``float16`` and ``bfloat16`` in the ``real floating`` data type kind. Similarly, implementations supporting ``int128`` can include ``int128`` in the ``signed integer`` data type kind. + .. note:: + A conforming implementation of the array API standard is **not** limited to only including the dtypes described in this specification in the required data type kinds. For example, implementations supporting ``float16`` and ``bfloat16`` can include ``float16`` and ``bfloat16`` in the ``real floating`` data type kind. Similarly, implementations supporting ``int128`` can include ``int128`` in the ``signed integer`` data type kind. - In short, conforming implementations may extend data type kinds; however, data type kinds must remain consistent (e.g., only integer dtypes may belong to integer data type kinds and only floating-point dtypes may belong to floating-point data type kinds), and extensions must be clearly documented as such in library documentation. + In short, conforming implementations may extend data type kinds; however, data type kinds must remain consistent (e.g., only integer dtypes may belong to integer data type kinds and only floating-point dtypes may belong to floating-point data type kinds), and extensions must be clearly documented as such in library documentation. Returns ------- out: bool - boolean indicating whether a provided dtype is of a specified data type kind. + boolean indicating whether a provided dtype is of a specified data type kind. Notes ----- @@ -1535,17 +1539,17 @@ class result_type[TArray: Array, TDtype](Protocol): Returns the dtype that results from applying the type promotion rules (see :ref:`type-promotion`) to the arguments. .. note:: - If provided mixed dtypes (e.g., integer and floating-point), the returned dtype will be implementation-specific. + If provided mixed dtypes (e.g., integer and floating-point), the returned dtype will be implementation-specific. Parameters ---------- arrays_and_dtypes: Union[array, dtype] - an arbitrary number of input arrays and/or dtypes. + an arbitrary number of input arrays and/or dtypes. Returns ------- out: dtype - the dtype resulting from an operation involving the input arrays and dtypes. + the dtype resulting from an operation involving the input arrays and dtypes. """ @@ -1561,32 +1565,32 @@ class cumulative_sum[TArray: Array, TDtype](Protocol): Parameters ---------- x: array - input array. Should have a numeric data type. + input array. Should have a numeric data type. axis: Optional[int] - axis along which a cumulative sum must be computed. If ``axis`` is negative, the function must determine the axis along which to compute a cumulative sum by counting from the last dimension. + axis along which a cumulative sum must be computed. If ``axis`` is negative, the function must determine the axis along which to compute a cumulative sum by counting from the last dimension. - If ``x`` is a one-dimensional array, providing an ``axis`` is optional; however, if ``x`` has more than one dimension, providing an ``axis`` is required. + If ``x`` is a one-dimensional array, providing an ``axis`` is optional; however, if ``x`` has more than one dimension, providing an ``axis`` is required. dtype: Optional[dtype] - data type of the returned array. If ``None``, the returned array must have the same data type as ``x``, unless ``x`` has an integer data type supporting a smaller range of values than the default integer data type (e.g., ``x`` has an ``int16`` or ``uint32`` data type and the default integer data type is ``int64``). In those latter cases: + data type of the returned array. If ``None``, the returned array must have the same data type as ``x``, unless ``x`` has an integer data type supporting a smaller range of values than the default integer data type (e.g., ``x`` has an ``int16`` or ``uint32`` data type and the default integer data type is ``int64``). In those latter cases: - - if ``x`` has a signed integer data type (e.g., ``int16``), the returned array must have the default integer data type. - - if ``x`` has an unsigned integer data type (e.g., ``uint16``), the returned array must have an unsigned integer data type having the same number of bits as the default integer data type (e.g., if the default integer data type is ``int32``, the returned array must have a ``uint32`` data type). + - if ``x`` has a signed integer data type (e.g., ``int16``), the returned array must have the default integer data type. + - if ``x`` has an unsigned integer data type (e.g., ``uint16``), the returned array must have an unsigned integer data type having the same number of bits as the default integer data type (e.g., if the default integer data type is ``int32``, the returned array must have a ``uint32`` data type). - If the data type (either specified or resolved) differs from the data type of ``x``, the input array should be cast to the specified data type before computing the sum (rationale: the ``dtype`` keyword argument is intended to help prevent overflows). Default: ``None``. + If the data type (either specified or resolved) differs from the data type of ``x``, the input array should be cast to the specified data type before computing the sum (rationale: the ``dtype`` keyword argument is intended to help prevent overflows). Default: ``None``. include_initial: bool - boolean indicating whether to include the initial value as the first value in the output. By convention, the initial value must be the additive identity (i.e., zero). Default: ``False``. + boolean indicating whether to include the initial value as the first value in the output. By convention, the initial value must be the additive identity (i.e., zero). Default: ``False``. Returns ------- out: array - an array containing the cumulative sums. The returned array must have a data type as described by the ``dtype`` parameter above. + an array containing the cumulative sums. The returned array must have a data type as described by the ``dtype`` parameter above. - Let ``N`` be the size of the axis along which to compute the cumulative sum. The returned array must have a shape determined according to the following rules: + Let ``N`` be the size of the axis along which to compute the cumulative sum. The returned array must have a shape determined according to the following rules: - - if ``include_initial`` is ``True``, the returned array must have the same shape as ``x``, except the size of the axis along which to compute the cumulative sum must be ``N+1``. - - if ``include_initial`` is ``False``, the returned array must have the same shape as ``x``. + - if ``include_initial`` is ``True``, the returned array must have the same shape as ``x``, except the size of the axis along which to compute the cumulative sum must be ``N+1``. + - if ``include_initial`` is ``False``, the returned array must have the same shape as ``x``. Notes ----- @@ -1610,16 +1614,16 @@ class max[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a real-valued data type. + input array. Should have a real-valued data type. axis: Optional[Union[int, Tuple[int, ...]]] - axis or axes along which maximum values must be computed. By default, the maximum value must be computed over the entire array. If a tuple of integers, maximum values must be computed over multiple axes. Default: ``None``. + axis or axes along which maximum values must be computed. By default, the maximum value must be computed over the entire array. If a tuple of integers, maximum values must be computed over multiple axes. Default: ``None``. keepdims: bool - if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. + if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. Returns ------- out: array - if the maximum value was computed over the entire array, a zero-dimensional array containing the maximum value; otherwise, a non-zero-dimensional array containing the maximum values. The returned array must have the same data type as ``x``. + if the maximum value was computed over the entire array, a zero-dimensional array containing the maximum value; otherwise, a non-zero-dimensional array containing the maximum values. The returned array must have the same data type as ``x``. Notes ----- @@ -1636,7 +1640,7 @@ class max[TArray: Array](Protocol): - If ``x_i`` is ``NaN``, the maximum value is ``NaN`` (i.e., ``NaN`` values propagate). .. versionchanged:: 2023.12 - Clarified that the order of signed zeros is implementation-defined. + Clarified that the order of signed zeros is implementation-defined. """ @@ -1652,19 +1656,19 @@ class mean[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a real-valued floating-point data type. + input array. Should have a real-valued floating-point data type. axis: Optional[Union[int, Tuple[int, ...]]] - axis or axes along which arithmetic means must be computed. By default, the mean must be computed over the entire array. If a tuple of integers, arithmetic means must be computed over multiple axes. Default: ``None``. + axis or axes along which arithmetic means must be computed. By default, the mean must be computed over the entire array. If a tuple of integers, arithmetic means must be computed over multiple axes. Default: ``None``. keepdims: bool - if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. + if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. Returns ------- out: array - if the arithmetic mean was computed over the entire array, a zero-dimensional array containing the arithmetic mean; otherwise, a non-zero-dimensional array containing the arithmetic means. The returned array must have the same data type as ``x``. + if the arithmetic mean was computed over the entire array, a zero-dimensional array containing the arithmetic mean; otherwise, a non-zero-dimensional array containing the arithmetic means. The returned array must have the same data type as ``x``. - .. note:: - While this specification recommends that this function only accept input arrays having a real-valued floating-point data type, specification-compliant array libraries may choose to accept input arrays having an integer data type. While mixed data type promotion is implementation-defined, if the input array ``x`` has an integer data type, the returned array must have the default real-valued floating-point data type. + .. note:: + While this specification recommends that this function only accept input arrays having a real-valued floating-point data type, specification-compliant array libraries may choose to accept input arrays having an integer data type. While mixed data type promotion is implementation-defined, if the input array ``x`` has an integer data type, the returned array must have the default real-valued floating-point data type. Notes ----- @@ -1689,16 +1693,16 @@ class min[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a real-valued data type. + input array. Should have a real-valued data type. axis: Optional[Union[int, Tuple[int, ...]]] - axis or axes along which minimum values must be computed. By default, the minimum value must be computed over the entire array. If a tuple of integers, minimum values must be computed over multiple axes. Default: ``None``. + axis or axes along which minimum values must be computed. By default, the minimum value must be computed over the entire array. If a tuple of integers, minimum values must be computed over multiple axes. Default: ``None``. keepdims: bool - if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. + if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. Returns ------- out: array - if the minimum value was computed over the entire array, a zero-dimensional array containing the minimum value; otherwise, a non-zero-dimensional array containing the minimum values. The returned array must have the same data type as ``x``. + if the minimum value was computed over the entire array, a zero-dimensional array containing the minimum value; otherwise, a non-zero-dimensional array containing the minimum values. The returned array must have the same data type as ``x``. Notes ----- @@ -1715,7 +1719,7 @@ class min[TArray: Array](Protocol): - If ``x_i`` is ``NaN``, the minimum value is ``NaN`` (i.e., ``NaN`` values propagate). .. versionchanged:: 2023.12 - Clarified that the order of signed zeros is implementation-defined. + Clarified that the order of signed zeros is implementation-defined. """ @@ -1731,25 +1735,25 @@ class prod[TArray: Array, TDtype](Protocol): Parameters ---------- x: array - input array. Should have a numeric data type. + input array. Should have a numeric data type. axis: Optional[Union[int, Tuple[int, ...]]] - axis or axes along which products must be computed. By default, the product must be computed over the entire array. If a tuple of integers, products must be computed over multiple axes. Default: ``None``. + axis or axes along which products must be computed. By default, the product must be computed over the entire array. If a tuple of integers, products must be computed over multiple axes. Default: ``None``. dtype: Optional[dtype] - data type of the returned array. If ``None``, the returned array must have the same data type as ``x``, unless ``x`` has an integer data type supporting a smaller range of values than the default integer data type (e.g., ``x`` has an ``int16`` or ``uint32`` data type and the default integer data type is ``int64``). In those latter cases: + data type of the returned array. If ``None``, the returned array must have the same data type as ``x``, unless ``x`` has an integer data type supporting a smaller range of values than the default integer data type (e.g., ``x`` has an ``int16`` or ``uint32`` data type and the default integer data type is ``int64``). In those latter cases: - - if ``x`` has a signed integer data type (e.g., ``int16``), the returned array must have the default integer data type. - - if ``x`` has an unsigned integer data type (e.g., ``uint16``), the returned array must have an unsigned integer data type having the same number of bits as the default integer data type (e.g., if the default integer data type is ``int32``, the returned array must have a ``uint32`` data type). + - if ``x`` has a signed integer data type (e.g., ``int16``), the returned array must have the default integer data type. + - if ``x`` has an unsigned integer data type (e.g., ``uint16``), the returned array must have an unsigned integer data type having the same number of bits as the default integer data type (e.g., if the default integer data type is ``int32``, the returned array must have a ``uint32`` data type). - If the data type (either specified or resolved) differs from the data type of ``x``, the input array should be cast to the specified data type before computing the sum (rationale: the ``dtype`` keyword argument is intended to help prevent overflows). Default: ``None``. + If the data type (either specified or resolved) differs from the data type of ``x``, the input array should be cast to the specified data type before computing the sum (rationale: the ``dtype`` keyword argument is intended to help prevent overflows). Default: ``None``. keepdims: bool - if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. + if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. Returns ------- out: array - if the product was computed over the entire array, a zero-dimensional array containing the product; otherwise, a non-zero-dimensional array containing the products. The returned array must have a data type as described by the ``dtype`` parameter above. + if the product was computed over the entire array, a zero-dimensional array containing the product; otherwise, a non-zero-dimensional array containing the products. The returned array must have a data type as described by the ``dtype`` parameter above. Notes ----- @@ -1762,10 +1766,10 @@ class prod[TArray: Array, TDtype](Protocol): For both real-valued and complex floating-point operands, special cases must be handled as if the operation is implemented by successive application of :func:`~array_api.multiply`. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. .. versionchanged:: 2023.12 - Required the function to return a floating-point array having the same data type as the input array when provided a floating-point array. + Required the function to return a floating-point array having the same data type as the input array when provided a floating-point array. """ @@ -1781,21 +1785,21 @@ class std[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a real-valued floating-point data type. + input array. Should have a real-valued floating-point data type. axis: Optional[Union[int, Tuple[int, ...]]] - axis or axes along which standard deviations must be computed. By default, the standard deviation must be computed over the entire array. If a tuple of integers, standard deviations must be computed over multiple axes. Default: ``None``. + axis or axes along which standard deviations must be computed. By default, the standard deviation must be computed over the entire array. If a tuple of integers, standard deviations must be computed over multiple axes. Default: ``None``. correction: Union[int, float] - degrees of freedom adjustment. Setting this parameter to a value other than ``0`` has the effect of adjusting the divisor during the calculation of the standard deviation according to ``N-c`` where ``N`` corresponds to the total number of elements over which the standard deviation is computed and ``c`` corresponds to the provided degrees of freedom adjustment. When computing the standard deviation of a population, setting this parameter to ``0`` is the standard choice (i.e., the provided array contains data constituting an entire population). When computing the corrected sample standard deviation, setting this parameter to ``1`` is the standard choice (i.e., the provided array contains data sampled from a larger population; this is commonly referred to as Bessel's correction). Default: ``0``. + degrees of freedom adjustment. Setting this parameter to a value other than ``0`` has the effect of adjusting the divisor during the calculation of the standard deviation according to ``N-c`` where ``N`` corresponds to the total number of elements over which the standard deviation is computed and ``c`` corresponds to the provided degrees of freedom adjustment. When computing the standard deviation of a population, setting this parameter to ``0`` is the standard choice (i.e., the provided array contains data constituting an entire population). When computing the corrected sample standard deviation, setting this parameter to ``1`` is the standard choice (i.e., the provided array contains data sampled from a larger population; this is commonly referred to as Bessel's correction). Default: ``0``. keepdims: bool - if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. + if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. Returns ------- out: array - if the standard deviation was computed over the entire array, a zero-dimensional array containing the standard deviation; otherwise, a non-zero-dimensional array containing the standard deviations. The returned array must have the same data type as ``x``. + if the standard deviation was computed over the entire array, a zero-dimensional array containing the standard deviation; otherwise, a non-zero-dimensional array containing the standard deviations. The returned array must have the same data type as ``x``. - .. note:: - While this specification recommends that this function only accept input arrays having a real-valued floating-point data type, specification-compliant array libraries may choose to accept input arrays having an integer data type. While mixed data type promotion is implementation-defined, if the input array ``x`` has an integer data type, the returned array must have the default real-valued floating-point data type. + .. note:: + While this specification recommends that this function only accept input arrays having a real-valued floating-point data type, specification-compliant array libraries may choose to accept input arrays having an integer data type. While mixed data type promotion is implementation-defined, if the input array ``x`` has an integer data type, the returned array must have the default real-valued floating-point data type. Notes ----- @@ -1820,25 +1824,25 @@ class sum[TArray: Array, TDtype](Protocol): Parameters ---------- x: array - input array. Should have a numeric data type. + input array. Should have a numeric data type. axis: Optional[Union[int, Tuple[int, ...]]] - axis or axes along which sums must be computed. By default, the sum must be computed over the entire array. If a tuple of integers, sums must be computed over multiple axes. Default: ``None``. + axis or axes along which sums must be computed. By default, the sum must be computed over the entire array. If a tuple of integers, sums must be computed over multiple axes. Default: ``None``. dtype: Optional[dtype] - data type of the returned array. If ``None``, the returned array must have the same data type as ``x``, unless ``x`` has an integer data type supporting a smaller range of values than the default integer data type (e.g., ``x`` has an ``int16`` or ``uint32`` data type and the default integer data type is ``int64``). In those latter cases: + data type of the returned array. If ``None``, the returned array must have the same data type as ``x``, unless ``x`` has an integer data type supporting a smaller range of values than the default integer data type (e.g., ``x`` has an ``int16`` or ``uint32`` data type and the default integer data type is ``int64``). In those latter cases: - - if ``x`` has a signed integer data type (e.g., ``int16``), the returned array must have the default integer data type. - - if ``x`` has an unsigned integer data type (e.g., ``uint16``), the returned array must have an unsigned integer data type having the same number of bits as the default integer data type (e.g., if the default integer data type is ``int32``, the returned array must have a ``uint32`` data type). + - if ``x`` has a signed integer data type (e.g., ``int16``), the returned array must have the default integer data type. + - if ``x`` has an unsigned integer data type (e.g., ``uint16``), the returned array must have an unsigned integer data type having the same number of bits as the default integer data type (e.g., if the default integer data type is ``int32``, the returned array must have a ``uint32`` data type). - If the data type (either specified or resolved) differs from the data type of ``x``, the input array should be cast to the specified data type before computing the sum (rationale: the ``dtype`` keyword argument is intended to help prevent overflows). Default: ``None``. + If the data type (either specified or resolved) differs from the data type of ``x``, the input array should be cast to the specified data type before computing the sum (rationale: the ``dtype`` keyword argument is intended to help prevent overflows). Default: ``None``. keepdims: bool - if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. + if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. Returns ------- out: array - if the sum was computed over the entire array, a zero-dimensional array containing the sum; otherwise, an array containing the sums. The returned array must have a data type as described by the ``dtype`` parameter above. + if the sum was computed over the entire array, a zero-dimensional array containing the sum; otherwise, an array containing the sums. The returned array must have a data type as described by the ``dtype`` parameter above. Notes ----- @@ -1851,10 +1855,10 @@ class sum[TArray: Array, TDtype](Protocol): For both real-valued and complex floating-point operands, special cases must be handled as if the operation is implemented by successive application of :func:`~array_api.add`. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. .. versionchanged:: 2023.12 - Required the function to return a floating-point array having the same data type as the input array when provided a floating-point array. + Required the function to return a floating-point array having the same data type as the input array when provided a floating-point array. """ @@ -1870,22 +1874,22 @@ class var[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a real-valued floating-point data type. + input array. Should have a real-valued floating-point data type. axis: Optional[Union[int, Tuple[int, ...]]] - axis or axes along which variances must be computed. By default, the variance must be computed over the entire array. If a tuple of integers, variances must be computed over multiple axes. Default: ``None``. + axis or axes along which variances must be computed. By default, the variance must be computed over the entire array. If a tuple of integers, variances must be computed over multiple axes. Default: ``None``. correction: Union[int, float] - degrees of freedom adjustment. Setting this parameter to a value other than ``0`` has the effect of adjusting the divisor during the calculation of the variance according to ``N-c`` where ``N`` corresponds to the total number of elements over which the variance is computed and ``c`` corresponds to the provided degrees of freedom adjustment. When computing the variance of a population, setting this parameter to ``0`` is the standard choice (i.e., the provided array contains data constituting an entire population). When computing the unbiased sample variance, setting this parameter to ``1`` is the standard choice (i.e., the provided array contains data sampled from a larger population; this is commonly referred to as Bessel's correction). Default: ``0``. + degrees of freedom adjustment. Setting this parameter to a value other than ``0`` has the effect of adjusting the divisor during the calculation of the variance according to ``N-c`` where ``N`` corresponds to the total number of elements over which the variance is computed and ``c`` corresponds to the provided degrees of freedom adjustment. When computing the variance of a population, setting this parameter to ``0`` is the standard choice (i.e., the provided array contains data constituting an entire population). When computing the unbiased sample variance, setting this parameter to ``1`` is the standard choice (i.e., the provided array contains data sampled from a larger population; this is commonly referred to as Bessel's correction). Default: ``0``. keepdims: bool - if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. + if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. Returns ------- out: array - if the variance was computed over the entire array, a zero-dimensional array containing the variance; otherwise, a non-zero-dimensional array containing the variances. The returned array must have the same data type as ``x``. + if the variance was computed over the entire array, a zero-dimensional array containing the variance; otherwise, a non-zero-dimensional array containing the variances. The returned array must have the same data type as ``x``. .. note:: - While this specification recommends that this function only accept input arrays having a real-valued floating-point data type, specification-compliant array libraries may choose to accept input arrays having an integer data type. While mixed data type promotion is implementation-defined, if the input array ``x`` has an integer data type, the returned array must have the default real-valued floating-point data type. + While this specification recommends that this function only accept input arrays having a real-valued floating-point data type, specification-compliant array libraries may choose to accept input arrays having an integer data type. While mixed data type promotion is implementation-defined, if the input array ``x`` has an integer data type, the returned array must have the default real-valued floating-point data type. Notes ----- @@ -1910,24 +1914,24 @@ class arange[TArray: Array, TDevice, TDtype](Protocol): Parameters ---------- start: Union[int, float] - if ``stop`` is specified, the start of interval (inclusive); otherwise, the end of the interval (exclusive). If ``stop`` is not specified, the default starting value is ``0``. + if ``stop`` is specified, the start of interval (inclusive); otherwise, the end of the interval (exclusive). If ``stop`` is not specified, the default starting value is ``0``. stop: Optional[Union[int, float]] - the end of the interval. Default: ``None``. + the end of the interval. Default: ``None``. step: Union[int, float] - the distance between two adjacent elements (``out[i+1] - out[i]``). Must not be ``0``; may be negative, this results in an empty array if ``stop >= start``. Default: ``1``. + the distance between two adjacent elements (``out[i+1] - out[i]``). Must not be ``0``; may be negative, this results in an empty array if ``stop >= start``. Default: ``1``. dtype: Optional[dtype] - output array data type. If ``dtype`` is ``None``, the output array data type must be inferred from ``start``, ``stop`` and ``step``. If those are all integers, the output array dtype must be the default integer dtype; if one or more have type ``float``, then the output array dtype must be the default real-valued floating-point data type. Default: ``None``. + output array data type. If ``dtype`` is ``None``, the output array data type must be inferred from ``start``, ``stop`` and ``step``. If those are all integers, the output array dtype must be the default integer dtype; if one or more have type ``float``, then the output array dtype must be the default real-valued floating-point data type. Default: ``None``. device: Optional[device] - device on which to place the created array. Default: ``None``. + device on which to place the created array. Default: ``None``. .. note:: - This function cannot guarantee that the interval does not include the ``stop`` value in those cases where ``step`` is not an integer and floating-point rounding errors affect the length of the output array. + This function cannot guarantee that the interval does not include the ``stop`` value in those cases where ``step`` is not an integer and floating-point rounding errors affect the length of the output array. Returns ------- out: array - a one-dimensional array containing evenly spaced values. The length of the output array must be ``ceil((stop-start)/step)`` if ``stop - start`` and ``step`` have the same sign, and length ``0`` otherwise. + a one-dimensional array containing evenly spaced values. The length of the output array must be ``ceil((stop-start)/step)`` if ``stop - start`` and ``step`` have the same sign, and length ``0`` otherwise. """ @@ -1936,58 +1940,58 @@ def __call__(self, start: int | float, /, stop: int | float | None = None, step: @runtime_checkable -class asarray[TSupportsbufferprotocol, TArray: Array, TDevice, TDtype](Protocol): +class asarray[TArray: Array, TDevice, TDtype](Protocol): r""" Convert the input to an array. Parameters ---------- obj: Union[array, bool, int, float, complex, NestedSequence[bool | int | float | complex], SupportsBufferProtocol] - object to be converted to an array. May be a Python scalar, a (possibly nested) sequence of Python scalars, or an object supporting the Python buffer protocol. + object to be converted to an array. May be a Python scalar, a (possibly nested) sequence of Python scalars, or an object supporting the Python buffer protocol. - .. admonition:: Tip - :class: important + .. admonition:: Tip + :class: important - An object supporting the buffer protocol can be turned into a memoryview through ``memoryview(obj)``. + An object supporting the buffer protocol can be turned into a memoryview through ``memoryview(obj)``. dtype: Optional[dtype] - output array data type. If ``dtype`` is ``None``, the output array data type must be inferred from the data type(s) in ``obj``. If all input values are Python scalars, then, in order of precedence, + output array data type. If ``dtype`` is ``None``, the output array data type must be inferred from the data type(s) in ``obj``. If all input values are Python scalars, then, in order of precedence, - - if all values are of type ``bool``, the output data type must be ``bool``. - - if all values are of type ``int`` or are a mixture of ``bool`` and ``int``, the output data type must be the default integer data type. - - if one or more values are ``complex`` numbers, the output data type must be the default complex floating-point data type. - - if one or more values are ``float``\\s, the output data type must be the default real-valued floating-point data type. + - if all values are of type ``bool``, the output data type must be ``bool``. + - if all values are of type ``int`` or are a mixture of ``bool`` and ``int``, the output data type must be the default integer data type. + - if one or more values are ``complex`` numbers, the output data type must be the default complex floating-point data type. + - if one or more values are ``float``\\s, the output data type must be the default real-valued floating-point data type. - Default: ``None``. + Default: ``None``. - .. admonition:: Note - :class: note + .. admonition:: Note + :class: note - If ``dtype`` is not ``None``, then array conversions should obey :ref:`type-promotion` rules. Conversions not specified according to :ref:`type-promotion` rules may or may not be permitted by a conforming array library. To perform an explicit cast, use :func:`array_api.astype`. + If ``dtype`` is not ``None``, then array conversions should obey :ref:`type-promotion` rules. Conversions not specified according to :ref:`type-promotion` rules may or may not be permitted by a conforming array library. To perform an explicit cast, use :func:`array_api.astype`. - .. note:: - If an input value exceeds the precision of the resolved output array data type, behavior is left unspecified and, thus, implementation-defined. + .. note:: + If an input value exceeds the precision of the resolved output array data type, behavior is left unspecified and, thus, implementation-defined. device: Optional[device] - device on which to place the created array. If ``device`` is ``None`` and ``obj`` is an array, the output array device must be inferred from ``obj``. Default: ``None``. + device on which to place the created array. If ``device`` is ``None`` and ``obj`` is an array, the output array device must be inferred from ``obj``. Default: ``None``. copy: Optional[bool] - boolean indicating whether or not to copy the input. If ``True``, the function must always copy. If ``False``, the function must never copy for input which supports the buffer protocol and must raise a ``ValueError`` in case a copy would be necessary. If ``None``, the function must reuse existing memory buffer if possible and copy otherwise. Default: ``None``. + boolean indicating whether or not to copy the input. If ``True``, the function must always copy. If ``False``, the function must never copy for input which supports the buffer protocol and must raise a ``ValueError`` in case a copy would be necessary. If ``None``, the function must reuse existing memory buffer if possible and copy otherwise. Default: ``None``. Returns ------- out: array - an array containing the data from ``obj``. + an array containing the data from ``obj``. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @abstractmethod - def __call__(self, obj: TArray | bool | int | float | complex | NestedSequence | TSupportsbufferprotocol, /, *, dtype: TDtype | None = None, device: TDevice | None = None, copy: bool | None = None) -> TArray: ... + def __call__(self, obj: TArray | bool | int | float | complex | NestedSequence | SupportsBufferProtocol, /, *, dtype: TDtype | None = None, device: TDevice | None = None, copy: bool | None = None) -> TArray: ... @runtime_checkable @@ -1998,16 +2002,16 @@ class empty[TArray: Array, TDevice, TDtype](Protocol): Parameters ---------- shape: Union[int, Tuple[int, ...]] - output array shape. + output array shape. dtype: Optional[dtype] - output array data type. If ``dtype`` is ``None``, the output array data type must be the default real-valued floating-point data type. Default: ``None``. + output array data type. If ``dtype`` is ``None``, the output array data type must be the default real-valued floating-point data type. Default: ``None``. device: Optional[device] - device on which to place the created array. Default: ``None``. + device on which to place the created array. Default: ``None``. Returns ------- out: array - an array containing uninitialized data. + an array containing uninitialized data. """ @@ -2023,16 +2027,16 @@ class empty_like[TArray: Array, TDevice, TDtype](Protocol): Parameters ---------- x: array - input array from which to derive the output array shape. + input array from which to derive the output array shape. dtype: Optional[dtype] - output array data type. If ``dtype`` is ``None``, the output array data type must be inferred from ``x``. Default: ``None``. + output array data type. If ``dtype`` is ``None``, the output array data type must be inferred from ``x``. Default: ``None``. device: Optional[device] - device on which to place the created array. If ``device`` is ``None``, the output array device must be inferred from ``x``. Default: ``None``. + device on which to place the created array. If ``device`` is ``None``, the output array device must be inferred from ``x``. Default: ``None``. Returns ------- out: array - an array having the same shape as ``x`` and containing uninitialized data. + an array having the same shape as ``x`` and containing uninitialized data. """ @@ -2046,31 +2050,31 @@ class eye[TArray: Array, TDevice, TDtype](Protocol): Returns a two-dimensional array with ones on the ``k``\\th diagonal and zeros elsewhere. .. note:: - An output array having a complex floating-point data type must have the value ``1 + 0j`` along the ``k``\\th diagonal and ``0 + 0j`` elsewhere. + An output array having a complex floating-point data type must have the value ``1 + 0j`` along the ``k``\\th diagonal and ``0 + 0j`` elsewhere. Parameters ---------- n_rows: int - number of rows in the output array. + number of rows in the output array. n_cols: Optional[int] - number of columns in the output array. If ``None``, the default number of columns in the output array is equal to ``n_rows``. Default: ``None``. + number of columns in the output array. If ``None``, the default number of columns in the output array is equal to ``n_rows``. Default: ``None``. k: int - index of the diagonal. A positive value refers to an upper diagonal, a negative value to a lower diagonal, and ``0`` to the main diagonal. Default: ``0``. + index of the diagonal. A positive value refers to an upper diagonal, a negative value to a lower diagonal, and ``0`` to the main diagonal. Default: ``0``. dtype: Optional[dtype] - output array data type. If ``dtype`` is ``None``, the output array data type must be the default real-valued floating-point data type. Default: ``None``. + output array data type. If ``dtype`` is ``None``, the output array data type must be the default real-valued floating-point data type. Default: ``None``. device: Optional[device] - device on which to place the created array. Default: ``None``. + device on which to place the created array. Default: ``None``. Returns ------- out: array - an array where all elements are equal to zero, except for the ``k``\\th diagonal, whose values are equal to one. + an array where all elements are equal to zero, except for the ``k``\\th diagonal, whose values are equal to one. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -2086,44 +2090,44 @@ class from_dlpack[TArray: Array, TDevice](Protocol): Parameters ---------- x: object - input (array) object. + input (array) object. device: Optional[device] - device on which to place the created array. If ``device`` is ``None`` and ``x`` supports DLPack, the output array must be on the same device as ``x``. Default: ``None``. + device on which to place the created array. If ``device`` is ``None`` and ``x`` supports DLPack, the output array must be on the same device as ``x``. Default: ``None``. - The v2023.12 standard only mandates that a compliant library should offer a way for ``from_dlpack`` to return an array - whose underlying memory is accessible to the Python interpreter, when the corresponding ``device`` is provided. If the - array library does not support such cases at all, the function must raise ``BufferError``. If a copy must be made to - enable this support but ``copy`` is set to ``False``, the function must raise ``ValueError``. + The v2023.12 standard only mandates that a compliant library should offer a way for ``from_dlpack`` to return an array + whose underlying memory is accessible to the Python interpreter, when the corresponding ``device`` is provided. If the + array library does not support such cases at all, the function must raise ``BufferError``. If a copy must be made to + enable this support but ``copy`` is set to ``False``, the function must raise ``ValueError``. - Other device kinds will be considered for standardization in a future version of this API standard. + Other device kinds will be considered for standardization in a future version of this API standard. copy: Optional[bool] - boolean indicating whether or not to copy the input. If ``True``, the function must always copy. If ``False``, the function must never copy, and raise ``BufferError`` in case a copy is deemed necessary (e.g. if a cross-device data movement is requested, and it is not possible without a copy). If ``None``, the function must reuse the existing memory buffer if possible and copy otherwise. Default: ``None``. + boolean indicating whether or not to copy the input. If ``True``, the function must always copy. If ``False``, the function must never copy, and raise ``BufferError`` in case a copy is deemed necessary (e.g. if a cross-device data movement is requested, and it is not possible without a copy). If ``None``, the function must reuse the existing memory buffer if possible and copy otherwise. Default: ``None``. Returns ------- out: array - an array containing the data in ``x``. + an array containing the data in ``x``. - .. admonition:: Note - :class: note + .. admonition:: Note + :class: note - The returned array may be either a copy or a view. See :ref:`data-interchange` for details. + The returned array may be either a copy or a view. See :ref:`data-interchange` for details. Raises ------ BufferError - The ``__dlpack__`` and ``__dlpack_device__`` methods on the input array - may raise ``BufferError`` when the data cannot be exported as DLPack - (e.g., incompatible dtype, strides, or device). It may also raise other errors - when export fails for other reasons (e.g., not enough memory available - to materialize the data). ``from_dlpack`` must propagate such - exceptions. + The ``__dlpack__`` and ``__dlpack_device__`` methods on the input array + may raise ``BufferError`` when the data cannot be exported as DLPack + (e.g., incompatible dtype, strides, or device). It may also raise other errors + when export fails for other reasons (e.g., not enough memory available + to materialize the data). ``from_dlpack`` must propagate such + exceptions. AttributeError - If the ``__dlpack__`` and ``__dlpack_device__`` methods are not present - on the input array. This may happen for libraries that are never able - to export their data with DLPack. + If the ``__dlpack__`` and ``__dlpack_device__`` methods are not present + on the input array. This may happen for libraries that are never able + to export their data with DLPack. ValueError - If data exchange is possible via an explicit copy but ``copy`` is set to ``False``. + If data exchange is possible via an explicit copy but ``copy`` is set to ``False``. Notes ----- @@ -2135,24 +2139,24 @@ class from_dlpack[TArray: Array, TDevice](Protocol): .. code:: python - def func(x, y): - xp_x = x.__array_namespace__() - xp_y = y.__array_namespace__() + def func(x, y): + xp_x = x.__array_namespace__() + xp_y = y.__array_namespace__() - # Other functions than `from_dlpack` only work if both arrays are from the same library. So if - # `y` is from a different one than `x`, let's convert `y` into an array of the same type as `x`: - if not xp_x == xp_y: - y = xp_x.from_dlpack(y, copy=True, device=x.device) + # Other functions than `from_dlpack` only work if both arrays are from the same library. So if + # `y` is from a different one than `x`, let's convert `y` into an array of the same type as `x`: + if not xp_x == xp_y: + y = xp_x.from_dlpack(y, copy=True, device=x.device) - # From now on use `xp_x.xxxxx` functions, as both arrays are from the library `xp_x` - ... + # From now on use `xp_x.xxxxx` functions, as both arrays are from the library `xp_x` + ... .. versionchanged:: 2023.12 - Required exceptions to address unsupported use cases. + Required exceptions to address unsupported use cases. .. versionchanged:: 2023.12 - Added device and copy support. + Added device and copy support. """ @@ -2168,33 +2172,33 @@ class full[TArray: Array, TDevice, TDtype](Protocol): Parameters ---------- shape: Union[int, Tuple[int, ...]] - output array shape. + output array shape. fill_value: Union[bool, int, float, complex] - fill value. + fill value. dtype: Optional[dtype] - output array data type. If ``dtype`` is ``None``, the output array data type must be inferred from ``fill_value`` according to the following rules: + output array data type. If ``dtype`` is ``None``, the output array data type must be inferred from ``fill_value`` according to the following rules: - - If the fill value is an ``int``, the output array data type must be the default integer data type. - - If the fill value is a ``float``, the output array data type must be the default real-valued floating-point data type. - - If the fill value is a ``complex`` number, the output array data type must be the default complex floating-point data type. - - If the fill value is a ``bool``, the output array must have a boolean data type. Default: ``None``. + - If the fill value is an ``int``, the output array data type must be the default integer data type. + - If the fill value is a ``float``, the output array data type must be the default real-valued floating-point data type. + - If the fill value is a ``complex`` number, the output array data type must be the default complex floating-point data type. + - If the fill value is a ``bool``, the output array must have a boolean data type. Default: ``None``. - .. note:: - If the ``fill_value`` exceeds the precision of the resolved default output array data type, behavior is left unspecified and, thus, implementation-defined. + .. note:: + If the ``fill_value`` exceeds the precision of the resolved default output array data type, behavior is left unspecified and, thus, implementation-defined. device: Optional[device] - device on which to place the created array. Default: ``None``. + device on which to place the created array. Default: ``None``. Returns ------- out: array - an array where every element is equal to ``fill_value``. + an array where every element is equal to ``fill_value``. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -2210,31 +2214,31 @@ class full_like[TArray: Array, TDevice, TDtype](Protocol): Parameters ---------- x: array - input array from which to derive the output array shape. + input array from which to derive the output array shape. fill_value: Union[bool, int, float, complex] - fill value. + fill value. dtype: Optional[dtype] - output array data type. If ``dtype`` is ``None``, the output array data type must be inferred from ``x``. Default: ``None``. + output array data type. If ``dtype`` is ``None``, the output array data type must be inferred from ``x``. Default: ``None``. - .. note:: - If the ``fill_value`` exceeds the precision of the resolved output array data type, behavior is unspecified and, thus, implementation-defined. + .. note:: + If the ``fill_value`` exceeds the precision of the resolved output array data type, behavior is unspecified and, thus, implementation-defined. - .. note:: - If the ``fill_value`` has a data type which is not of the same data type kind (boolean, integer, or floating-point) as the resolved output array data type (see :ref:`type-promotion`), behavior is unspecified and, thus, implementation-defined. + .. note:: + If the ``fill_value`` has a data type which is not of the same data type kind (boolean, integer, or floating-point) as the resolved output array data type (see :ref:`type-promotion`), behavior is unspecified and, thus, implementation-defined. device: Optional[device] - device on which to place the created array. If ``device`` is ``None``, the output array device must be inferred from ``x``. Default: ``None``. + device on which to place the created array. If ``device`` is ``None``, the output array device must be inferred from ``x``. Default: ``None``. Returns ------- out: array - an array having the same shape as ``x`` and where every element is equal to ``fill_value``. + an array having the same shape as ``x`` and where every element is equal to ``fill_value``. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -2250,59 +2254,59 @@ class linspace[TArray: Array, TDevice, TDtype](Protocol): Let :math:`N` be the number of generated values (which is either ``num`` or ``num+1`` depending on whether ``endpoint`` is ``True`` or ``False``, respectively). For real-valued output arrays, the spacing between values is given by .. math:: - \\Delta_{\\textrm{real}} = \\frac{\\textrm{stop} - \\textrm{start}}{N - 1} + \\Delta_{\\textrm{real}} = \\frac{\\textrm{stop} - \\textrm{start}}{N - 1} For complex output arrays, let ``a = real(start)``, ``b = imag(start)``, ``c = real(stop)``, and ``d = imag(stop)``. The spacing between complex values is given by .. math:: - \\Delta_{\\textrm{complex}} = \\frac{c-a}{N-1} + \\frac{d-b}{N-1} j + \\Delta_{\\textrm{complex}} = \\frac{c-a}{N-1} + \\frac{d-b}{N-1} j Parameters ---------- start: Union[int, float, complex] - the start of the interval. + the start of the interval. stop: Union[int, float, complex] - the end of the interval. If ``endpoint`` is ``False``, the function must generate a sequence of ``num+1`` evenly spaced numbers starting with ``start`` and ending with ``stop`` and exclude the ``stop`` from the returned array such that the returned array consists of evenly spaced numbers over the half-open interval ``[start, stop)``. If ``endpoint`` is ``True``, the output array must consist of evenly spaced numbers over the closed interval ``[start, stop]``. Default: ``True``. + the end of the interval. If ``endpoint`` is ``False``, the function must generate a sequence of ``num+1`` evenly spaced numbers starting with ``start`` and ending with ``stop`` and exclude the ``stop`` from the returned array such that the returned array consists of evenly spaced numbers over the half-open interval ``[start, stop)``. If ``endpoint`` is ``True``, the output array must consist of evenly spaced numbers over the closed interval ``[start, stop]``. Default: ``True``. - .. note:: - The step size changes when `endpoint` is `False`. + .. note:: + The step size changes when `endpoint` is `False`. num: int - number of samples. Must be a nonnegative integer value. + number of samples. Must be a nonnegative integer value. dtype: Optional[dtype] - output array data type. Should be a floating-point data type. If ``dtype`` is ``None``, + output array data type. Should be a floating-point data type. If ``dtype`` is ``None``, - - if either ``start`` or ``stop`` is a ``complex`` number, the output data type must be the default complex floating-point data type. - - if both ``start`` and ``stop`` are real-valued, the output data type must be the default real-valued floating-point data type. + - if either ``start`` or ``stop`` is a ``complex`` number, the output data type must be the default complex floating-point data type. + - if both ``start`` and ``stop`` are real-valued, the output data type must be the default real-valued floating-point data type. - Default: ``None``. + Default: ``None``. - .. admonition:: Note - :class: note + .. admonition:: Note + :class: note - If ``dtype`` is not ``None``, conversion of ``start`` and ``stop`` should obey :ref:`type-promotion` rules. Conversions not specified according to :ref:`type-promotion` rules may or may not be permitted by a conforming array library. + If ``dtype`` is not ``None``, conversion of ``start`` and ``stop`` should obey :ref:`type-promotion` rules. Conversions not specified according to :ref:`type-promotion` rules may or may not be permitted by a conforming array library. device: Optional[device] - device on which to place the created array. Default: ``None``. + device on which to place the created array. Default: ``None``. endpoint: bool - boolean indicating whether to include ``stop`` in the interval. Default: ``True``. + boolean indicating whether to include ``stop`` in the interval. Default: ``True``. Returns ------- out: array - a one-dimensional array containing evenly spaced values. + a one-dimensional array containing evenly spaced values. Notes ----- .. note:: - While this specification recommends that this function only return arrays having a floating-point data type, specification-compliant array libraries may choose to support output arrays having an integer data type (e.g., due to backward compatibility concerns). However, function behavior when generating integer output arrays is unspecified and, thus, is implementation-defined. Accordingly, using this function to generate integer output arrays is not portable. + While this specification recommends that this function only return arrays having a floating-point data type, specification-compliant array libraries may choose to support output arrays having an integer data type (e.g., due to backward compatibility concerns). However, function behavior when generating integer output arrays is unspecified and, thus, is implementation-defined. Accordingly, using this function to generate integer output arrays is not portable. .. note:: - As mixed data type promotion is implementation-defined, behavior when ``start`` or ``stop`` exceeds the maximum safe integer of an output floating-point data type is implementation-defined. An implementation may choose to overflow or raise an exception. + As mixed data type promotion is implementation-defined, behavior when ``start`` or ``stop`` exceeds the maximum safe integer of an output floating-point data type is implementation-defined. An implementation may choose to overflow or raise an exception. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -2318,29 +2322,29 @@ class meshgrid[TArray: Array](Protocol): Parameters ---------- arrays: array - an arbitrary number of one-dimensional arrays representing grid coordinates. Each array should have the same numeric data type. + an arbitrary number of one-dimensional arrays representing grid coordinates. Each array should have the same numeric data type. indexing: Literal["xy", "ij"] - Cartesian ``'xy'`` or matrix ``'ij'`` indexing of output. If provided zero or one one-dimensional vector(s) (i.e., the zero- and one-dimensional cases, respectively), the ``indexing`` keyword has no effect and should be ignored. Default: ``'xy'``. + Cartesian ``'xy'`` or matrix ``'ij'`` indexing of output. If provided zero or one one-dimensional vector(s) (i.e., the zero- and one-dimensional cases, respectively), the ``indexing`` keyword has no effect and should be ignored. Default: ``'xy'``. Returns ------- out: List[array] - list of N arrays, where ``N`` is the number of provided one-dimensional input arrays. Each returned array must have rank ``N``. For ``N`` one-dimensional arrays having lengths ``Ni = len(xi)``, + list of N arrays, where ``N`` is the number of provided one-dimensional input arrays. Each returned array must have rank ``N``. For ``N`` one-dimensional arrays having lengths ``Ni = len(xi)``, - - if matrix indexing ``ij``, then each returned array must have the shape ``(N1, N2, N3, ..., Nn)``. - - if Cartesian indexing ``xy``, then each returned array must have shape ``(N2, N1, N3, ..., Nn)``. + - if matrix indexing ``ij``, then each returned array must have the shape ``(N1, N2, N3, ..., Nn)``. + - if Cartesian indexing ``xy``, then each returned array must have shape ``(N2, N1, N3, ..., Nn)``. - Accordingly, for the two-dimensional case with input one-dimensional arrays of length ``M`` and ``N``, if matrix indexing ``ij``, then each returned array must have shape ``(M, N)``, and, if Cartesian indexing ``xy``, then each returned array must have shape ``(N, M)``. + Accordingly, for the two-dimensional case with input one-dimensional arrays of length ``M`` and ``N``, if matrix indexing ``ij``, then each returned array must have shape ``(M, N)``, and, if Cartesian indexing ``xy``, then each returned array must have shape ``(N, M)``. - Similarly, for the three-dimensional case with input one-dimensional arrays of length ``M``, ``N``, and ``P``, if matrix indexing ``ij``, then each returned array must have shape ``(M, N, P)``, and, if Cartesian indexing ``xy``, then each returned array must have shape ``(N, M, P)``. + Similarly, for the three-dimensional case with input one-dimensional arrays of length ``M``, ``N``, and ``P``, if matrix indexing ``ij``, then each returned array must have shape ``(M, N, P)``, and, if Cartesian indexing ``xy``, then each returned array must have shape ``(N, M, P)``. - Each returned array should have the same data type as the input arrays. + Each returned array should have the same data type as the input arrays. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -2354,27 +2358,27 @@ class ones[TArray: Array, TDevice, TDtype](Protocol): Returns a new array having a specified ``shape`` and filled with ones. .. note:: - An output array having a complex floating-point data type must contain complex numbers having a real component equal to one and an imaginary component equal to zero (i.e., ``1 + 0j``). + An output array having a complex floating-point data type must contain complex numbers having a real component equal to one and an imaginary component equal to zero (i.e., ``1 + 0j``). Parameters ---------- shape: Union[int, Tuple[int, ...]] - output array shape. + output array shape. dtype: Optional[dtype] - output array data type. If ``dtype`` is ``None``, the output array data type must be the default real-valued floating-point data type. Default: ``None``. + output array data type. If ``dtype`` is ``None``, the output array data type must be the default real-valued floating-point data type. Default: ``None``. device: Optional[device] - device on which to place the created array. Default: ``None``. + device on which to place the created array. Default: ``None``. Returns ------- out: array - an array containing ones. + an array containing ones. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -2388,27 +2392,27 @@ class ones_like[TArray: Array, TDevice, TDtype](Protocol): Returns a new array filled with ones and having the same ``shape`` as an input array ``x``. .. note:: - An output array having a complex floating-point data type must contain complex numbers having a real component equal to one and an imaginary component equal to zero (i.e., ``1 + 0j``). + An output array having a complex floating-point data type must contain complex numbers having a real component equal to one and an imaginary component equal to zero (i.e., ``1 + 0j``). Parameters ---------- x: array - input array from which to derive the output array shape. + input array from which to derive the output array shape. dtype: Optional[dtype] - output array data type. If ``dtype`` is ``None``, the output array data type must be inferred from ``x``. Default: ``None``. + output array data type. If ``dtype`` is ``None``, the output array data type must be inferred from ``x``. Default: ``None``. device: Optional[device] - device on which to place the created array. If ``device`` is ``None``, the output array device must be inferred from ``x``. Default: ``None``. + device on which to place the created array. If ``device`` is ``None``, the output array device must be inferred from ``x``. Default: ``None``. Returns ------- out: array - an array having the same shape as ``x`` and filled with ones. + an array having the same shape as ``x`` and filled with ones. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -2422,22 +2426,22 @@ class tril[TArray: Array](Protocol): Returns the lower triangular part of a matrix (or a stack of matrices) ``x``. .. note:: - The lower triangular part of the matrix is defined as the elements on and below the specified diagonal ``k``. + The lower triangular part of the matrix is defined as the elements on and below the specified diagonal ``k``. Parameters ---------- x: array - input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. + input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. k: int - diagonal above which to zero elements. If ``k = 0``, the diagonal is the main diagonal. If ``k < 0``, the diagonal is below the main diagonal. If ``k > 0``, the diagonal is above the main diagonal. Default: ``0``. + diagonal above which to zero elements. If ``k = 0``, the diagonal is the main diagonal. If ``k < 0``, the diagonal is below the main diagonal. If ``k > 0``, the diagonal is above the main diagonal. Default: ``0``. - .. note:: - The main diagonal is defined as the set of indices ``{(i, i)}`` for ``i`` on the interval ``[0, min(M, N) - 1]``. + .. note:: + The main diagonal is defined as the set of indices ``{(i, i)}`` for ``i`` on the interval ``[0, min(M, N) - 1]``. Returns ------- out: array - an array containing the lower triangular part(s). The returned array must have the same shape and data type as ``x``. All elements above the specified diagonal ``k`` must be zeroed. The returned array should be allocated on the same device as ``x``. + an array containing the lower triangular part(s). The returned array must have the same shape and data type as ``x``. All elements above the specified diagonal ``k`` must be zeroed. The returned array should be allocated on the same device as ``x``. """ @@ -2451,22 +2455,22 @@ class triu[TArray: Array](Protocol): Returns the upper triangular part of a matrix (or a stack of matrices) ``x``. .. note:: - The upper triangular part of the matrix is defined as the elements on and above the specified diagonal ``k``. + The upper triangular part of the matrix is defined as the elements on and above the specified diagonal ``k``. Parameters ---------- x: array - input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. + input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. k: int - diagonal below which to zero elements. If ``k = 0``, the diagonal is the main diagonal. If ``k < 0``, the diagonal is below the main diagonal. If ``k > 0``, the diagonal is above the main diagonal. Default: ``0``. + diagonal below which to zero elements. If ``k = 0``, the diagonal is the main diagonal. If ``k < 0``, the diagonal is below the main diagonal. If ``k > 0``, the diagonal is above the main diagonal. Default: ``0``. - .. note:: - The main diagonal is defined as the set of indices ``{(i, i)}`` for ``i`` on the interval ``[0, min(M, N) - 1]``. + .. note:: + The main diagonal is defined as the set of indices ``{(i, i)}`` for ``i`` on the interval ``[0, min(M, N) - 1]``. Returns ------- out: array - an array containing the upper triangular part(s). The returned array must have the same shape and data type as ``x``. All elements below the specified diagonal ``k`` must be zeroed. The returned array should be allocated on the same device as ``x``. + an array containing the upper triangular part(s). The returned array must have the same shape and data type as ``x``. All elements below the specified diagonal ``k`` must be zeroed. The returned array should be allocated on the same device as ``x``. """ @@ -2482,16 +2486,16 @@ class zeros[TArray: Array, TDevice, TDtype](Protocol): Parameters ---------- shape: Union[int, Tuple[int, ...]] - output array shape. + output array shape. dtype: Optional[dtype] - output array data type. If ``dtype`` is ``None``, the output array data type must be the default real-valued floating-point data type. Default: ``None``. + output array data type. If ``dtype`` is ``None``, the output array data type must be the default real-valued floating-point data type. Default: ``None``. device: Optional[device] - device on which to place the created array. Default: ``None``. + device on which to place the created array. Default: ``None``. Returns ------- out: array - an array containing zeros. + an array containing zeros. """ @@ -2507,16 +2511,16 @@ class zeros_like[TArray: Array, TDevice, TDtype](Protocol): Parameters ---------- x: array - input array from which to derive the output array shape. + input array from which to derive the output array shape. dtype: Optional[dtype] - output array data type. If ``dtype`` is ``None``, the output array data type must be inferred from ``x``. Default: ``None``. + output array data type. If ``dtype`` is ``None``, the output array data type must be inferred from ``x``. Default: ``None``. device: Optional[device] - device on which to place the created array. If ``device`` is ``None``, the output array device must be inferred from ``x``. Default: ``None``. + device on which to place the created array. If ``device`` is ``None``, the output array device must be inferred from ``x``. Default: ``None``. Returns ------- out: array - an array having the same shape as ``x`` and filled with zeros. + an array having the same shape as ``x`` and filled with zeros. """ @@ -2534,39 +2538,39 @@ class cholesky[TArray: Array](Protocol): The lower **Cholesky decomposition** of a complex Hermitian or real symmetric positive-definite matrix :math:`x \\in\\ \\mathbb{K}^{n \\times n}` is defined as .. math:: - x = LL^{H} \\qquad \\text{L $\\in\\ \\mathbb{K}^{n \\times n}$} + x = LL^{H} \\qquad \\text{L $\\in\\ \\mathbb{K}^{n \\times n}$} where :math:`L` is a lower triangular matrix and :math:`L^{H}` is the conjugate transpose when :math:`L` is complex-valued and the transpose when :math:`L` is real-valued. The upper Cholesky decomposition is defined similarly .. math:: - x = U^{H}U \\qquad \\text{U $\\in\\ \\mathbb{K}^{n \\times n}$} + x = U^{H}U \\qquad \\text{U $\\in\\ \\mathbb{K}^{n \\times n}$} where :math:`U` is an upper triangular matrix. When ``x`` is a stack of matrices, the function must compute the Cholesky decomposition for each matrix in the stack. .. note:: - Whether an array library explicitly checks whether an input array is Hermitian or a symmetric positive-definite matrix (or a stack of matrices) is implementation-defined. + Whether an array library explicitly checks whether an input array is Hermitian or a symmetric positive-definite matrix (or a stack of matrices) is implementation-defined. Parameters ---------- x: array - input array having shape ``(..., M, M)`` and whose innermost two dimensions form square complex Hermitian or real symmetric positive-definite matrices. Should have a floating-point data type. + input array having shape ``(..., M, M)`` and whose innermost two dimensions form square complex Hermitian or real symmetric positive-definite matrices. Should have a floating-point data type. upper: bool - If ``True``, the result must be the upper-triangular Cholesky factor :math:`U`. If ``False``, the result must be the lower-triangular Cholesky factor :math:`L`. Default: ``False``. + If ``True``, the result must be the upper-triangular Cholesky factor :math:`U`. If ``False``, the result must be the lower-triangular Cholesky factor :math:`L`. Default: ``False``. Returns ------- out: array - an array containing the Cholesky factors for each square matrix. If ``upper`` is ``False``, the returned array must contain lower-triangular matrices; otherwise, the returned array must contain upper-triangular matrices. The returned array must have a floating-point data type determined by :ref:`type-promotion` and must have the same shape as ``x``. + an array containing the Cholesky factors for each square matrix. If ``upper`` is ``False``, the returned array must contain lower-triangular matrices; otherwise, the returned array must contain upper-triangular matrices. The returned array must have a floating-point data type determined by :ref:`type-promotion` and must have the same shape as ``x``. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -2584,20 +2588,20 @@ class cross[TArray: Array](Protocol): Parameters ---------- x1: array - first input array. Must have a numeric data type. The size of the axis over which the cross product is to be computed must be equal to 3. + first input array. Must have a numeric data type. The size of the axis over which the cross product is to be computed must be equal to 3. x2: array - second input array. Must be broadcast compatible with ``x1`` along all axes other than the axis along which the cross-product is computed (see :ref:`broadcasting`). The size of the axis over which the cross product is to be computed must be equal to 3. Must have a numeric data type. + second input array. Must be broadcast compatible with ``x1`` along all axes other than the axis along which the cross-product is computed (see :ref:`broadcasting`). The size of the axis over which the cross product is to be computed must be equal to 3. Must have a numeric data type. - .. note:: - The compute axis (dimension) must not be broadcasted. + .. note:: + The compute axis (dimension) must not be broadcasted. axis: int - the axis (dimension) of ``x1`` and ``x2`` containing the vectors for which to compute the cross product. Should be an integer on the interval ``[-N, -1]``, where ``N`` is ``min(x1.ndim, x2.ndim)``. The function must determine the axis along which to compute the cross product by counting backward from the last dimension (where ``-1`` refers to the last dimension). By default, the function must compute the cross product over the last axis. Default: ``-1``. + the axis (dimension) of ``x1`` and ``x2`` containing the vectors for which to compute the cross product. Should be an integer on the interval ``[-N, -1]``, where ``N`` is ``min(x1.ndim, x2.ndim)``. The function must determine the axis along which to compute the cross product by counting backward from the last dimension (where ``-1`` refers to the last dimension). By default, the function must compute the cross product over the last axis. Default: ``-1``. Returns ------- out: array - an array containing the cross products. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the cross products. The returned array must have a data type determined by :ref:`type-promotion`. Notes @@ -2607,13 +2611,13 @@ class cross[TArray: Array](Protocol): - if the size of the axis over which to compute the cross product is not equal to ``3`` (before broadcasting) for both ``x1`` and ``x2``. .. versionchanged:: 2022.12 - Added support for broadcasting. + Added support for broadcasting. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. .. versionchanged:: 2023.12 - Restricted broadcasting to only non-compute axes and required that ``axis`` be a negative integer. + Restricted broadcasting to only non-compute axes and required that ``axis`` be a negative integer. """ @@ -2629,18 +2633,18 @@ class det[TArray: Array](Protocol): Parameters ---------- x: array - input array having shape ``(..., M, M)`` and whose innermost two dimensions form square matrices. Should have a floating-point data type. + input array having shape ``(..., M, M)`` and whose innermost two dimensions form square matrices. Should have a floating-point data type. Returns ------- out: array - if ``x`` is a two-dimensional array, a zero-dimensional array containing the determinant; otherwise, a non-zero dimensional array containing the determinant for each square matrix. The returned array must have the same data type as ``x``. + if ``x`` is a two-dimensional array, a zero-dimensional array containing the determinant; otherwise, a non-zero dimensional array containing the determinant for each square matrix. The returned array must have the same data type as ``x``. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -2656,20 +2660,20 @@ class diagonal[TArray: Array](Protocol): Parameters ---------- x: array - input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. + input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. offset: int - offset specifying the off-diagonal relative to the main diagonal. + offset specifying the off-diagonal relative to the main diagonal. - - ``offset = 0``: the main diagonal. - - ``offset > 0``: off-diagonal above the main diagonal. - - ``offset < 0``: off-diagonal below the main diagonal. + - ``offset = 0``: the main diagonal. + - ``offset > 0``: off-diagonal above the main diagonal. + - ``offset < 0``: off-diagonal below the main diagonal. - Default: `0`. + Default: `0`. Returns ------- out: array - an array containing the diagonals and whose shape is determined by removing the last two dimensions and appending a dimension equal to the size of the resulting diagonals. The returned array must have the same data type as ``x``. + an array containing the diagonals and whose shape is determined by removing the last two dimensions and appending a dimension equal to the size of the resulting diagonals. The returned array must have the same data type as ``x``. """ @@ -2687,45 +2691,45 @@ class eigh[TArray: Array](Protocol): The **eigenvalue decomposition** of a complex Hermitian or real symmetric matrix :math:`x \\in\\ \\mathbb{K}^{n \\times n}` is defined as .. math:: - x = Q \\Lambda Q^H + x = Q \\Lambda Q^H with :math:`Q \\in \\mathbb{K}^{n \\times n}` and :math:`\\Lambda \\in \\mathbb{R}^n` and where :math:`Q^H` is the conjugate transpose when :math:`Q` is complex and the transpose when :math:`Q` is real-valued and :math:`\\Lambda` is a diagonal matrix whose diagonal elements are the corresponding eigenvalues. When ``x`` is real-valued, :math:`Q` is orthogonal, and, when ``x`` is complex, :math:`Q` is unitary. .. note:: - The eigenvalues of a complex Hermitian or real symmetric matrix are always real. + The eigenvalues of a complex Hermitian or real symmetric matrix are always real. .. warning:: - The eigenvectors of a symmetric matrix are not unique and are not continuous with respect to ``x``. Because eigenvectors are not unique, different hardware and software may compute different eigenvectors. + The eigenvectors of a symmetric matrix are not unique and are not continuous with respect to ``x``. Because eigenvectors are not unique, different hardware and software may compute different eigenvectors. - Non-uniqueness stems from the fact that multiplying an eigenvector by :math:`-1` when ``x`` is real-valued and by :math:`e^{\\phi j}` (:math:`\\phi \\in \\mathbb{R}`) when ``x`` is complex produces another set of valid eigenvectors. + Non-uniqueness stems from the fact that multiplying an eigenvector by :math:`-1` when ``x`` is real-valued and by :math:`e^{\\phi j}` (:math:`\\phi \\in \\mathbb{R}`) when ``x`` is complex produces another set of valid eigenvectors. .. note:: - Whether an array library explicitly checks whether an input array is Hermitian or a symmetric matrix (or a stack of matrices) is implementation-defined. + Whether an array library explicitly checks whether an input array is Hermitian or a symmetric matrix (or a stack of matrices) is implementation-defined. .. note:: - The function ``eig`` will be added in a future version of the specification. + The function ``eig`` will be added in a future version of the specification. Parameters ---------- x: array - input array having shape ``(..., M, M)`` and whose innermost two dimensions form square matrices. Should have a floating-point data type. + input array having shape ``(..., M, M)`` and whose innermost two dimensions form square matrices. Should have a floating-point data type. Returns ------- out: Tuple[array, array] - a namedtuple (``eigenvalues``, ``eigenvectors``) whose + a namedtuple (``eigenvalues``, ``eigenvectors``) whose - - first element must have the field name ``eigenvalues`` (corresponding to :math:`\\operatorname{diag}\\Lambda` above) and must be an array consisting of computed eigenvalues. The array containing the eigenvalues must have shape ``(..., M)`` and must have a real-valued floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``complex128``, then ``eigenvalues`` must be ``float64``). - - second element have have the field name ``eigenvectors`` (corresponding to :math:`Q` above) and must be an array where the columns of the inner most matrices contain the computed eigenvectors. These matrices must be orthogonal. The array containing the eigenvectors must have shape ``(..., M, M)`` and must have the same data type as ``x``. + - first element must have the field name ``eigenvalues`` (corresponding to :math:`\\operatorname{diag}\\Lambda` above) and must be an array consisting of computed eigenvalues. The array containing the eigenvalues must have shape ``(..., M)`` and must have a real-valued floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``complex128``, then ``eigenvalues`` must be ``float64``). + - second element have have the field name ``eigenvectors`` (corresponding to :math:`Q` above) and must be an array where the columns of the inner most matrices contain the computed eigenvectors. These matrices must be orthogonal. The array containing the eigenvectors must have shape ``(..., M, M)`` and must have the same data type as ``x``. Notes ----- .. note:: - Eigenvalue sort order is left unspecified and is thus implementation-dependent. + Eigenvalue sort order is left unspecified and is thus implementation-dependent. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -2743,37 +2747,37 @@ class eigvalsh[TArray: Array](Protocol): The **eigenvalues** of a complex Hermitian or real symmetric matrix :math:`x \\in\\ \\mathbb{K}^{n \\times n}` are defined as the roots (counted with multiplicity) of the polynomial :math:`p` of degree :math:`n` given by .. math:: - p(\\lambda) = \\operatorname{det}(x - \\lambda I_n) + p(\\lambda) = \\operatorname{det}(x - \\lambda I_n) where :math:`\\lambda \\in \\mathbb{R}` and where :math:`I_n` is the *n*-dimensional identity matrix. .. note:; - The eigenvalues of a complex Hermitian or real symmetric matrix are always real. + The eigenvalues of a complex Hermitian or real symmetric matrix are always real. .. note:: - Whether an array library explicitly checks whether an input array is Hermitian or a symmetric matrix (or a stack of matrices) is implementation-defined. + Whether an array library explicitly checks whether an input array is Hermitian or a symmetric matrix (or a stack of matrices) is implementation-defined. .. note:: - The function ``eigvals`` will be added in a future version of the specification. + The function ``eigvals`` will be added in a future version of the specification. Parameters ---------- x: array - input array having shape ``(..., M, M)`` and whose innermost two dimensions form square matrices. Should have a floating-point data type. + input array having shape ``(..., M, M)`` and whose innermost two dimensions form square matrices. Should have a floating-point data type. Returns ------- out: array - an array containing the computed eigenvalues. The returned array must have shape ``(..., M)`` and have a real-valued floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``complex128``, then must have a ``float64`` data type). + an array containing the computed eigenvalues. The returned array must have shape ``(..., M)`` and have a real-valued floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``complex128``, then must have a ``float64`` data type). Notes ----- .. note:: - Eigenvalue sort order is left unspecified and is thus implementation-dependent. + Eigenvalue sort order is left unspecified and is thus implementation-dependent. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -2791,7 +2795,7 @@ class inv[TArray: Array](Protocol): The **inverse matrix** :math:`x^{-1} \\in\\ \\mathbb{K}^{n \\times n}` of a square matrix :math:`x \\in\\ \\mathbb{K}^{n \\times n}` is defined as .. math:: - x^{-1}x = xx^{-1} = I_n + x^{-1}x = xx^{-1} = I_n where :math:`I_n` is the *n*-dimensional identity matrix. @@ -2802,18 +2806,18 @@ class inv[TArray: Array](Protocol): Parameters ---------- x: array - input array having shape ``(..., M, M)`` and whose innermost two dimensions form square matrices. Should have a floating-point data type. + input array having shape ``(..., M, M)`` and whose innermost two dimensions form square matrices. Should have a floating-point data type. Returns ------- out: array - an array containing the multiplicative inverses. The returned array must have a floating-point data type determined by :ref:`type-promotion` and must have the same shape as ``x``. + an array containing the multiplicative inverses. The returned array must have a floating-point data type determined by :ref:`type-promotion` and must have the same shape as ``x``. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -2829,56 +2833,56 @@ class matrix_norm[TArray: Array](Protocol): Parameters ---------- x: array - input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. Should have a floating-point data type. + input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. Should have a floating-point data type. keepdims: bool - If ``True``, the last two axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the last two axes (dimensions) must not be included in the result. Default: ``False``. + If ``True``, the last two axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the last two axes (dimensions) must not be included in the result. Default: ``False``. ord: Optional[Union[int, float, Literal[inf, -inf, 'fro', 'nuc']]] - order of the norm. The following mathematical norms must be supported: + order of the norm. The following mathematical norms must be supported: - +------------------+---------------------------------+ - | ord | description | - +==================+=================================+ - | 'fro' | Frobenius norm | - +------------------+---------------------------------+ - | 'nuc' | nuclear norm | - +------------------+---------------------------------+ - | 1 | max(sum(abs(x), axis=0)) | - +------------------+---------------------------------+ - | 2 | largest singular value | - +------------------+---------------------------------+ - | inf | max(sum(abs(x), axis=1)) | - +------------------+---------------------------------+ + +------------------+---------------------------------+ + | ord | description | + +==================+=================================+ + | 'fro' | Frobenius norm | + +------------------+---------------------------------+ + | 'nuc' | nuclear norm | + +------------------+---------------------------------+ + | 1 | max(sum(abs(x), axis=0)) | + +------------------+---------------------------------+ + | 2 | largest singular value | + +------------------+---------------------------------+ + | inf | max(sum(abs(x), axis=1)) | + +------------------+---------------------------------+ - The following non-mathematical "norms" must be supported: + The following non-mathematical "norms" must be supported: - +------------------+---------------------------------+ - | ord | description | - +==================+=================================+ - | -1 | min(sum(abs(x), axis=0)) | - +------------------+---------------------------------+ - | -2 | smallest singular value | - +------------------+---------------------------------+ - | -inf | min(sum(abs(x), axis=1)) | - +------------------+---------------------------------+ + +------------------+---------------------------------+ + | ord | description | + +==================+=================================+ + | -1 | min(sum(abs(x), axis=0)) | + +------------------+---------------------------------+ + | -2 | smallest singular value | + +------------------+---------------------------------+ + | -inf | min(sum(abs(x), axis=1)) | + +------------------+---------------------------------+ - If ``ord=1``, the norm corresponds to the induced matrix norm where ``p=1`` (i.e., the maximum absolute value column sum). + If ``ord=1``, the norm corresponds to the induced matrix norm where ``p=1`` (i.e., the maximum absolute value column sum). - If ``ord=2``, the norm corresponds to the induced matrix norm where ``p=inf`` (i.e., the maximum absolute value row sum). + If ``ord=2``, the norm corresponds to the induced matrix norm where ``p=inf`` (i.e., the maximum absolute value row sum). - If ``ord=inf``, the norm corresponds to the induced matrix norm where ``p=2`` (i.e., the largest singular value). + If ``ord=inf``, the norm corresponds to the induced matrix norm where ``p=2`` (i.e., the largest singular value). - Default: ``'fro'``. + Default: ``'fro'``. Returns ------- out: array - an array containing the norms for each ``MxN`` matrix. If ``keepdims`` is ``False``, the returned array must have a rank which is two less than the rank of ``x``. If ``x`` has a real-valued data type, the returned array must have a real-valued floating-point data type determined by :ref:`type-promotion`. If ``x`` has a complex-valued data type, the returned array must have a real-valued floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``complex128``, then the returned array must have a ``float64`` data type). + an array containing the norms for each ``MxN`` matrix. If ``keepdims`` is ``False``, the returned array must have a rank which is two less than the rank of ``x``. If ``x`` has a real-valued data type, the returned array must have a real-valued floating-point data type determined by :ref:`type-promotion`. If ``x`` has a complex-valued data type, the returned array must have a real-valued floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``complex128``, then the returned array must have a ``float64`` data type). Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -2895,20 +2899,20 @@ class matrix_power[TArray: Array](Protocol): Parameters ---------- x: array - input array having shape ``(..., M, M)`` and whose innermost two dimensions form square matrices. Should have a floating-point data type. + input array having shape ``(..., M, M)`` and whose innermost two dimensions form square matrices. Should have a floating-point data type. n: int - integer exponent. + integer exponent. Returns ------- out: array - if ``n`` is equal to zero, an array containing the identity matrix for each square matrix. If ``n`` is less than zero, an array containing the inverse of each square matrix raised to the absolute value of ``n``, provided that each square matrix is invertible. If ``n`` is greater than zero, an array containing the result of raising each square matrix to the power ``n``. The returned array must have the same shape as ``x`` and a floating-point data type determined by :ref:`type-promotion`. + if ``n`` is equal to zero, an array containing the identity matrix for each square matrix. If ``n`` is less than zero, an array containing the inverse of each square matrix raised to the absolute value of ``n``, provided that each square matrix is invertible. If ``n`` is greater than zero, an array containing the result of raising each square matrix to the power ``n``. The returned array must have the same shape as ``x`` and a floating-point data type determined by :ref:`type-promotion`. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -2926,20 +2930,20 @@ class matrix_rank[TArray: Array](Protocol): Parameters ---------- x: array - input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. Should have a floating-point data type. + input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. Should have a floating-point data type. rtol: Optional[Union[float, array]] - relative tolerance for small singular values. Singular values approximately less than or equal to ``rtol * largest_singular_value`` are set to zero. If a ``float``, the value is equivalent to a zero-dimensional array having a real-valued floating-point data type determined by :ref:`type-promotion` (as applied to ``x``) and must be broadcast against each matrix. If an ``array``, must have a real-valued floating-point data type and must be compatible with ``shape(x)[:-2]`` (see :ref:`broadcasting`). If ``None``, the default value is ``max(M, N) * eps``, where ``eps`` must be the machine epsilon associated with the real-valued floating-point data type determined by :ref:`type-promotion` (as applied to ``x``). Default: ``None``. + relative tolerance for small singular values. Singular values approximately less than or equal to ``rtol * largest_singular_value`` are set to zero. If a ``float``, the value is equivalent to a zero-dimensional array having a real-valued floating-point data type determined by :ref:`type-promotion` (as applied to ``x``) and must be broadcast against each matrix. If an ``array``, must have a real-valued floating-point data type and must be compatible with ``shape(x)[:-2]`` (see :ref:`broadcasting`). If ``None``, the default value is ``max(M, N) * eps``, where ``eps`` must be the machine epsilon associated with the real-valued floating-point data type determined by :ref:`type-promotion` (as applied to ``x``). Default: ``None``. Returns ------- out: array - an array containing the ranks. The returned array must have the default integer data type and must have shape ``(...)`` (i.e., must have a shape equal to ``shape(x)[:-2]``). + an array containing the ranks. The returned array must have the default integer data type and must have shape ``(...)`` (i.e., must have a shape equal to ``shape(x)[:-2]``). Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -2955,20 +2959,20 @@ class outer[TArray: Array](Protocol): Parameters ---------- x1: array - first one-dimensional input array of size ``N``. Must have a numeric data type. + first one-dimensional input array of size ``N``. Must have a numeric data type. x2: array - second one-dimensional input array of size ``M``. Must have a numeric data type. + second one-dimensional input array of size ``M``. Must have a numeric data type. Returns ------- out: array - a two-dimensional array containing the outer product and whose shape is ``(N, M)``. The returned array must have a data type determined by :ref:`type-promotion`. + a two-dimensional array containing the outer product and whose shape is ``(N, M)``. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -2986,12 +2990,12 @@ class pinv[TArray: Array](Protocol): While the pseudo-inverse can be defined algebraically, one can understand the pseudo-inverse via singular value decomposition (SVD). Namely, if .. math:: - A = U \\Sigma V^H + A = U \\Sigma V^H is a singular decomposition of :math:`A`, then .. math:: - A^{+} = U \\Sigma^{+} V^H + A^{+} = U \\Sigma^{+} V^H where :math:`U` and :math:`V^H` are orthogonal matrices, :math:`\\Sigma` is a diagonal matrix consisting of :math:`A`'s singular values, and :math:`\\Sigma^{+}` is then a diagonal matrix consisting of the reciprocals of :math:`A`'s singular values, leaving zeros in place. During numerical computation, only elements larger than a small tolerance are considered nonzero, and all others replaced by zeros. @@ -3000,20 +3004,20 @@ class pinv[TArray: Array](Protocol): Parameters ---------- x: array - input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. Should have a floating-point data type. + input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. Should have a floating-point data type. rtol: Optional[Union[float, array]] - relative tolerance for small singular values. Singular values approximately less than or equal to ``rtol * largest_singular_value`` are set to zero. If a ``float``, the value is equivalent to a zero-dimensional array having a real-valued floating-point data type determined by :ref:`type-promotion` (as applied to ``x``) and must be broadcast against each matrix. If an ``array``, must have a real-valued floating-point data type and must be compatible with ``shape(x)[:-2]`` (see :ref:`broadcasting`). If ``None``, the default value is ``max(M, N) * eps``, where ``eps`` must be the machine epsilon associated with the real-valued floating-point data type determined by :ref:`type-promotion` (as applied to ``x``). Default: ``None``. + relative tolerance for small singular values. Singular values approximately less than or equal to ``rtol * largest_singular_value`` are set to zero. If a ``float``, the value is equivalent to a zero-dimensional array having a real-valued floating-point data type determined by :ref:`type-promotion` (as applied to ``x``) and must be broadcast against each matrix. If an ``array``, must have a real-valued floating-point data type and must be compatible with ``shape(x)[:-2]`` (see :ref:`broadcasting`). If ``None``, the default value is ``max(M, N) * eps``, where ``eps`` must be the machine epsilon associated with the real-valued floating-point data type determined by :ref:`type-promotion` (as applied to ``x``). Default: ``None``. Returns ------- out: array - an array containing the pseudo-inverse(s). The returned array must have a floating-point data type determined by :ref:`type-promotion` and must have shape ``(..., N, M)`` (i.e., must have the same shape as ``x``, except the innermost two dimensions must be transposed). + an array containing the pseudo-inverse(s). The returned array must have a floating-point data type determined by :ref:`type-promotion` and must have shape ``(..., N, M)`` (i.e., must have the same shape as ``x``, except the innermost two dimensions must be transposed). Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -3031,14 +3035,14 @@ class qr[TArray: Array](Protocol): The **complete QR decomposition** of a matrix :math:`x \\in\\ \\mathbb{K}^{n \\times n}` is defined as .. math:: - x = QR + x = QR where :math:`Q \\in\\ \\mathbb{K}^{m \\times m}` is orthogonal when ``x`` is real-valued and unitary when ``x`` is complex-valued and where :math:`R \\in\\ \\mathbb{K}^{m \\times n}` is an upper triangular matrix with real diagonal (even when ``x`` is complex-valued). When :math:`m \\gt n` (tall matrix), as :math:`R` is upper triangular, the last :math:`m - n` rows are zero. In this case, the last :math:`m - n` columns of :math:`Q` can be dropped to form the **reduced QR decomposition**. .. math:: - x = QR + x = QR where :math:`Q \\in\\ \\mathbb{K}^{m \\times n}` and :math:`R \\in\\ \\mathbb{K}^{n \\times n}`. @@ -3047,41 +3051,41 @@ class qr[TArray: Array](Protocol): When ``x`` is a stack of matrices, the function must compute the QR decomposition for each matrix in the stack. .. note:: - Whether an array library explicitly checks whether an input array is a full column rank matrix (or a stack of full column rank matrices) is implementation-defined. + Whether an array library explicitly checks whether an input array is a full column rank matrix (or a stack of full column rank matrices) is implementation-defined. .. warning:: - The elements in the diagonal of :math:`R` are not necessarily positive. Accordingly, the returned QR decomposition is only unique up to the sign of the diagonal of :math:`R`, and different libraries or inputs on different devices may produce different valid decompositions. + The elements in the diagonal of :math:`R` are not necessarily positive. Accordingly, the returned QR decomposition is only unique up to the sign of the diagonal of :math:`R`, and different libraries or inputs on different devices may produce different valid decompositions. .. warning:: - The QR decomposition is only well-defined if the first ``k = min(m,n)`` columns of every matrix in ``x`` are linearly independent. + The QR decomposition is only well-defined if the first ``k = min(m,n)`` columns of every matrix in ``x`` are linearly independent. Parameters ---------- x: array - input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices of rank ``N``. Should have a floating-point data type. + input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices of rank ``N``. Should have a floating-point data type. mode: Literal['reduced', 'complete'] - decomposition mode. Should be one of the following modes: + decomposition mode. Should be one of the following modes: - - ``'reduced'``: compute only the leading ``K`` columns of ``q``, such that ``q`` and ``r`` have dimensions ``(..., M, K)`` and ``(..., K, N)``, respectively, and where ``K = min(M, N)``. - - ``'complete'``: compute ``q`` and ``r`` with dimensions ``(..., M, M)`` and ``(..., M, N)``, respectively. + - ``'reduced'``: compute only the leading ``K`` columns of ``q``, such that ``q`` and ``r`` have dimensions ``(..., M, K)`` and ``(..., K, N)``, respectively, and where ``K = min(M, N)``. + - ``'complete'``: compute ``q`` and ``r`` with dimensions ``(..., M, M)`` and ``(..., M, N)``, respectively. - Default: ``'reduced'``. + Default: ``'reduced'``. Returns ------- out: Tuple[array, array] - a namedtuple ``(Q, R)`` whose + a namedtuple ``(Q, R)`` whose - - first element must have the field name ``Q`` and must be an array whose shape depends on the value of ``mode`` and contain matrices with orthonormal columns. If ``mode`` is ``'complete'``, the array must have shape ``(..., M, M)``. If ``mode`` is ``'reduced'``, the array must have shape ``(..., M, K)``, where ``K = min(M, N)``. The first ``x.ndim-2`` dimensions must have the same size as those of the input array ``x``. - - second element must have the field name ``R`` and must be an array whose shape depends on the value of ``mode`` and contain upper-triangular matrices. If ``mode`` is ``'complete'``, the array must have shape ``(..., M, N)``. If ``mode`` is ``'reduced'``, the array must have shape ``(..., K, N)``, where ``K = min(M, N)``. The first ``x.ndim-2`` dimensions must have the same size as those of the input ``x``. + - first element must have the field name ``Q`` and must be an array whose shape depends on the value of ``mode`` and contain matrices with orthonormal columns. If ``mode`` is ``'complete'``, the array must have shape ``(..., M, M)``. If ``mode`` is ``'reduced'``, the array must have shape ``(..., M, K)``, where ``K = min(M, N)``. The first ``x.ndim-2`` dimensions must have the same size as those of the input array ``x``. + - second element must have the field name ``R`` and must be an array whose shape depends on the value of ``mode`` and contain upper-triangular matrices. If ``mode`` is ``'complete'``, the array must have shape ``(..., M, N)``. If ``mode`` is ``'reduced'``, the array must have shape ``(..., K, N)``, where ``K = min(M, N)``. The first ``x.ndim-2`` dimensions must have the same size as those of the input ``x``. - Each returned array must have a floating-point data type determined by :ref:`type-promotion`. + Each returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -3095,15 +3099,15 @@ class slogdet[TArray: Array](Protocol): Returns the sign and the natural logarithm of the absolute value of the determinant of a square matrix (or a stack of square matrices) ``x``. .. note:: - The purpose of this function is to calculate the determinant more accurately when the determinant is either very small or very large, as calling ``det`` may overflow or underflow. + The purpose of this function is to calculate the determinant more accurately when the determinant is either very small or very large, as calling ``det`` may overflow or underflow. The sign of the determinant is given by .. math:: - \\operatorname{sign}(\\det x) = \\begin{cases} - 0 & \\textrm{if } \\det x = 0 \\\\ - \\frac{\\det x}{|\\det x|} & \\textrm{otherwise} - \\end{cases} + \\operatorname{sign}(\\det x) = \\begin{cases} + 0 & \\textrm{if } \\det x = 0 \\\\ + \\frac{\\det x}{|\\det x|} & \\textrm{otherwise} + \\end{cases} where :math:`|\\det x|` is the absolute value of the determinant of ``x``. @@ -3120,28 +3124,28 @@ class slogdet[TArray: Array](Protocol): - If the determinant is ``0 + 0j``, the ``sign`` should be ``0 + 0j`` and ``logabsdet`` should be ``-infinity + 0j``. .. note:: - Depending on the underlying algorithm, when the determinant is zero, the returned result may differ from ``-infinity`` (or ``-infinity + 0j``). In all cases, the determinant should be equal to ``sign * exp(logabsdet)`` (although, again, the result may be subject to numerical precision errors). + Depending on the underlying algorithm, when the determinant is zero, the returned result may differ from ``-infinity`` (or ``-infinity + 0j``). In all cases, the determinant should be equal to ``sign * exp(logabsdet)`` (although, again, the result may be subject to numerical precision errors). Parameters ---------- x: array - input array having shape ``(..., M, M)`` and whose innermost two dimensions form square matrices. Should have a floating-point data type. + input array having shape ``(..., M, M)`` and whose innermost two dimensions form square matrices. Should have a floating-point data type. Returns ------- out: Tuple[array, array] - a namedtuple (``sign``, ``logabsdet``) whose + a namedtuple (``sign``, ``logabsdet``) whose - - first element must have the field name ``sign`` and must be an array containing a number representing the sign of the determinant for each square matrix. Must have the same data type as ``x``. - - second element must have the field name ``logabsdet`` and must be an array containing the natural logarithm of the absolute value of the determinant for each square matrix. If ``x`` is real-valued, the returned array must have a real-valued floating-point data type determined by :ref:`type-promotion`. If ``x`` is complex, the returned array must have a real-valued floating-point data type having the same precision as ``x`` (e.g., if ``x`` is ``complex64``, ``logabsdet`` must have a ``float32`` data type). + - first element must have the field name ``sign`` and must be an array containing a number representing the sign of the determinant for each square matrix. Must have the same data type as ``x``. + - second element must have the field name ``logabsdet`` and must be an array containing the natural logarithm of the absolute value of the determinant for each square matrix. If ``x`` is real-valued, the returned array must have a real-valued floating-point data type determined by :ref:`type-promotion`. If ``x`` is complex, the returned array must have a real-valued floating-point data type having the same precision as ``x`` (e.g., if ``x`` is ``complex64``, ``logabsdet`` must have a ``float32`` data type). - Each returned array must have shape ``shape(x)[:-2]``. + Each returned array must have shape ``shape(x)[:-2]``. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -3159,32 +3163,32 @@ class solve[TArray: Array](Protocol): This function computes the solution :math:`X \\in\\ \\mathbb{K}^{m \\times k}` of the **linear system** associated to :math:`A \\in\\ \\mathbb{K}^{m \\times m}` and :math:`B \\in\\ \\mathbb{K}^{m \\times k}` and is defined as .. math:: - AX = B + AX = B This system of linear equations has a unique solution if and only if :math:`A` is invertible. .. note:: - Whether an array library explicitly checks whether ``x1`` is invertible is implementation-defined. + Whether an array library explicitly checks whether ``x1`` is invertible is implementation-defined. When ``x1`` and/or ``x2`` is a stack of matrices, the function must compute a solution for each matrix in the stack. Parameters ---------- x1: array - coefficient array ``A`` having shape ``(..., M, M)`` and whose innermost two dimensions form square matrices. Must be of full rank (i.e., all rows or, equivalently, columns must be linearly independent). Should have a floating-point data type. + coefficient array ``A`` having shape ``(..., M, M)`` and whose innermost two dimensions form square matrices. Must be of full rank (i.e., all rows or, equivalently, columns must be linearly independent). Should have a floating-point data type. x2: array - ordinate (or "dependent variable") array ``B``. If ``x2`` has shape ``(M,)``, ``x2`` is equivalent to an array having shape ``(..., M, 1)``. If ``x2`` has shape ``(..., M, K)``, each column ``k`` defines a set of ordinate values for which to compute a solution, and ``shape(x2)[:-2]`` must be compatible with ``shape(x1)[:-2]`` (see :ref:`broadcasting`). Should have a floating-point data type. + ordinate (or "dependent variable") array ``B``. If ``x2`` has shape ``(M,)``, ``x2`` is equivalent to an array having shape ``(..., M, 1)``. If ``x2`` has shape ``(..., M, K)``, each column ``k`` defines a set of ordinate values for which to compute a solution, and ``shape(x2)[:-2]`` must be compatible with ``shape(x1)[:-2]`` (see :ref:`broadcasting`). Should have a floating-point data type. Returns ------- out: array - an array containing the solution to the system ``AX = B`` for each square matrix. If ``x2`` has shape ``(M,)``, the returned array must have shape equal to ``shape(x1)[:-2] + shape(x2)[-1:]``. Otherwise, if ``x2`` has shape ``(..., M, K)```, the returned array must have shape equal to ``(..., M, K)``, where ``...`` refers to the result of broadcasting ``shape(x1)[:-2]`` and ``shape(x2)[:-2]``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the solution to the system ``AX = B`` for each square matrix. If ``x2`` has shape ``(M,)``, the returned array must have shape equal to ``shape(x1)[:-2] + shape(x2)[-1:]``. Otherwise, if ``x2`` has shape ``(..., M, K)```, the returned array must have shape equal to ``(..., M, K)``, where ``...`` refers to the result of broadcasting ``shape(x1)[:-2]`` and ``shape(x2)[:-2]``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -3202,14 +3206,14 @@ class svd[TArray: Array](Protocol): The full **singular value decomposition** of an :math:`m \\times n` matrix :math:`x \\in\\ \\mathbb{K}^{m \\times n}` is a factorization of the form .. math:: - x = U \\Sigma V^H + x = U \\Sigma V^H where :math:`U \\in\\ \\mathbb{K}^{m \\times m}`, :math:`\\Sigma \\in\\ \\mathbb{K}^{m \\times\\ n}`, :math:`\\operatorname{diag}(\\Sigma) \\in\\ \\mathbb{R}^{k}` with :math:`k = \\operatorname{min}(m, n)`, :math:`V^H \\in\\ \\mathbb{K}^{n \\times n}`, and where :math:`V^H` is the conjugate transpose when :math:`V` is complex and the transpose when :math:`V` is real-valued. When ``x`` is real-valued, :math:`U`, :math:`V` (and thus :math:`V^H`) are orthogonal, and, when ``x`` is complex, :math:`U`, :math:`V` (and thus :math:`V^H`) are unitary. When :math:`m \\gt n` (tall matrix), we can drop the last :math:`m - n` columns of :math:`U` to form the reduced SVD .. math:: - x = U \\Sigma V^H + x = U \\Sigma V^H where :math:`U \\in\\ \\mathbb{K}^{m \\times k}`, :math:`\\Sigma \\in\\ \\mathbb{K}^{k \\times\\ k}`, :math:`\\operatorname{diag}(\\Sigma) \\in\\ \\mathbb{R}^{k}`, and :math:`V^H \\in\\ \\mathbb{K}^{k \\times n}`. In this case, :math:`U` and :math:`V` have orthonormal columns. @@ -3220,31 +3224,31 @@ class svd[TArray: Array](Protocol): When ``x`` is a stack of matrices, the function must compute the singular value decomposition for each matrix in the stack. .. warning:: - The returned arrays :math:`U` and :math:`V` are neither unique nor continuous with respect to ``x``. Because :math:`U` and :math:`V` are not unique, different hardware and software may compute different singular vectors. + The returned arrays :math:`U` and :math:`V` are neither unique nor continuous with respect to ``x``. Because :math:`U` and :math:`V` are not unique, different hardware and software may compute different singular vectors. - Non-uniqueness stems from the fact that multiplying any pair of singular vectors :math:`u_k`, :math:`v_k` by :math:`-1` when ``x`` is real-valued and by :math:`e^{\\phi j}` (:math:`\\phi \\in \\mathbb{R}`) when ``x`` is complex produces another two valid singular vectors of the matrix. + Non-uniqueness stems from the fact that multiplying any pair of singular vectors :math:`u_k`, :math:`v_k` by :math:`-1` when ``x`` is real-valued and by :math:`e^{\\phi j}` (:math:`\\phi \\in \\mathbb{R}`) when ``x`` is complex produces another two valid singular vectors of the matrix. Parameters ---------- x: array - input array having shape ``(..., M, N)`` and whose innermost two dimensions form matrices on which to perform singular value decomposition. Should have a floating-point data type. + input array having shape ``(..., M, N)`` and whose innermost two dimensions form matrices on which to perform singular value decomposition. Should have a floating-point data type. full_matrices: bool - If ``True``, compute full-sized ``U`` and ``Vh``, such that ``U`` has shape ``(..., M, M)`` and ``Vh`` has shape ``(..., N, N)``. If ``False``, compute on the leading ``K`` singular vectors, such that ``U`` has shape ``(..., M, K)`` and ``Vh`` has shape ``(..., K, N)`` and where ``K = min(M, N)``. Default: ``True``. + If ``True``, compute full-sized ``U`` and ``Vh``, such that ``U`` has shape ``(..., M, M)`` and ``Vh`` has shape ``(..., N, N)``. If ``False``, compute on the leading ``K`` singular vectors, such that ``U`` has shape ``(..., M, K)`` and ``Vh`` has shape ``(..., K, N)`` and where ``K = min(M, N)``. Default: ``True``. Returns ------- out: Tuple[array, array, array] - a namedtuple ``(U, S, Vh)`` whose + a namedtuple ``(U, S, Vh)`` whose - - first element must have the field name ``U`` and must be an array whose shape depends on the value of ``full_matrices`` and contain matrices with orthonormal columns (i.e., the columns are left singular vectors). If ``full_matrices`` is ``True``, the array must have shape ``(..., M, M)``. If ``full_matrices`` is ``False``, the array must have shape ``(..., M, K)``, where ``K = min(M, N)``. The first ``x.ndim-2`` dimensions must have the same shape as those of the input ``x``. Must have the same data type as ``x``. - - second element must have the field name ``S`` and must be an array with shape ``(..., K)`` that contains the vector(s) of singular values of length ``K``, where ``K = min(M, N)``. For each vector, the singular values must be sorted in descending order by magnitude, such that ``s[..., 0]`` is the largest value, ``s[..., 1]`` is the second largest value, et cetera. The first ``x.ndim-2`` dimensions must have the same shape as those of the input ``x``. Must have a real-valued floating-point data type having the same precision as ``x`` (e.g., if ``x`` is ``complex64``, ``S`` must have a ``float32`` data type). - - third element must have the field name ``Vh`` and must be an array whose shape depends on the value of ``full_matrices`` and contain orthonormal rows (i.e., the rows are the right singular vectors and the array is the adjoint). If ``full_matrices`` is ``True``, the array must have shape ``(..., N, N)``. If ``full_matrices`` is ``False``, the array must have shape ``(..., K, N)`` where ``K = min(M, N)``. The first ``x.ndim-2`` dimensions must have the same shape as those of the input ``x``. Must have the same data type as ``x``. + - first element must have the field name ``U`` and must be an array whose shape depends on the value of ``full_matrices`` and contain matrices with orthonormal columns (i.e., the columns are left singular vectors). If ``full_matrices`` is ``True``, the array must have shape ``(..., M, M)``. If ``full_matrices`` is ``False``, the array must have shape ``(..., M, K)``, where ``K = min(M, N)``. The first ``x.ndim-2`` dimensions must have the same shape as those of the input ``x``. Must have the same data type as ``x``. + - second element must have the field name ``S`` and must be an array with shape ``(..., K)`` that contains the vector(s) of singular values of length ``K``, where ``K = min(M, N)``. For each vector, the singular values must be sorted in descending order by magnitude, such that ``s[..., 0]`` is the largest value, ``s[..., 1]`` is the second largest value, et cetera. The first ``x.ndim-2`` dimensions must have the same shape as those of the input ``x``. Must have a real-valued floating-point data type having the same precision as ``x`` (e.g., if ``x`` is ``complex64``, ``S`` must have a ``float32`` data type). + - third element must have the field name ``Vh`` and must be an array whose shape depends on the value of ``full_matrices`` and contain orthonormal rows (i.e., the rows are the right singular vectors and the array is the adjoint). If ``full_matrices`` is ``True``, the array must have shape ``(..., N, N)``. If ``full_matrices`` is ``False``, the array must have shape ``(..., K, N)`` where ``K = min(M, N)``. The first ``x.ndim-2`` dimensions must have the same shape as those of the input ``x``. Must have the same data type as ``x``. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -3262,18 +3266,18 @@ class svdvals[TArray: Array](Protocol): Parameters ---------- x: array - input array having shape ``(..., M, N)`` and whose innermost two dimensions form matrices on which to perform singular value decomposition. Should have a floating-point data type. + input array having shape ``(..., M, N)`` and whose innermost two dimensions form matrices on which to perform singular value decomposition. Should have a floating-point data type. Returns ------- out: array - an array with shape ``(..., K)`` that contains the vector(s) of singular values of length ``K``, where ``K = min(M, N)``. For each vector, the singular values must be sorted in descending order by magnitude, such that ``s[..., 0]`` is the largest value, ``s[..., 1]`` is the second largest value, et cetera. The first ``x.ndim-2`` dimensions must have the same shape as those of the input ``x``. The returned array must have a real-valued floating-point data type having the same precision as ``x`` (e.g., if ``x`` is ``complex64``, the returned array must have a ``float32`` data type). + an array with shape ``(..., K)`` that contains the vector(s) of singular values of length ``K``, where ``K = min(M, N)``. For each vector, the singular values must be sorted in descending order by magnitude, such that ``s[..., 0]`` is the largest value, ``s[..., 1]`` is the second largest value, et cetera. The first ``x.ndim-2`` dimensions must have the same shape as those of the input ``x``. The returned array must have a real-valued floating-point data type having the same precision as ``x`` (e.g., if ``x`` is ``complex64``, the returned array must have a ``float32`` data type). Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -3289,33 +3293,33 @@ class trace[TArray: Array, TDtype](Protocol): Parameters ---------- x: array - input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. Should have a numeric data type. + input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. Should have a numeric data type. offset: int - offset specifying the off-diagonal relative to the main diagonal. + offset specifying the off-diagonal relative to the main diagonal. - - ``offset = 0``: the main diagonal. - - ``offset > 0``: off-diagonal above the main diagonal. - - ``offset < 0``: off-diagonal below the main diagonal. + - ``offset = 0``: the main diagonal. + - ``offset > 0``: off-diagonal above the main diagonal. + - ``offset < 0``: off-diagonal below the main diagonal. - Default: ``0``. + Default: ``0``. dtype: Optional[dtype] - data type of the returned array. If ``None``, the returned array must have the same data type as ``x``, unless ``x`` has an integer data type supporting a smaller range of values than the default integer data type (e.g., ``x`` has an ``int16`` or ``uint32`` data type and the default integer data type is ``int64``). In those latter cases: + data type of the returned array. If ``None``, the returned array must have the same data type as ``x``, unless ``x`` has an integer data type supporting a smaller range of values than the default integer data type (e.g., ``x`` has an ``int16`` or ``uint32`` data type and the default integer data type is ``int64``). In those latter cases: - - if ``x`` has a signed integer data type (e.g., ``int16``), the returned array must have the default integer data type. - - if ``x`` has an unsigned integer data type (e.g., ``uint16``), the returned array must have an unsigned integer data type having the same number of bits as the default integer data type (e.g., if the default integer data type is ``int32``, the returned array must have a ``uint32`` data type). + - if ``x`` has a signed integer data type (e.g., ``int16``), the returned array must have the default integer data type. + - if ``x`` has an unsigned integer data type (e.g., ``uint16``), the returned array must have an unsigned integer data type having the same number of bits as the default integer data type (e.g., if the default integer data type is ``int32``, the returned array must have a ``uint32`` data type). - If the data type (either specified or resolved) differs from the data type of ``x``, the input array should be cast to the specified data type before computing the sum (rationale: the ``dtype`` keyword argument is intended to help prevent overflows). Default: ``None``. + If the data type (either specified or resolved) differs from the data type of ``x``, the input array should be cast to the specified data type before computing the sum (rationale: the ``dtype`` keyword argument is intended to help prevent overflows). Default: ``None``. Returns ------- out: array - an array containing the traces and whose shape is determined by removing the last two dimensions and storing the traces in the last array dimension. For example, if ``x`` has rank ``k`` and shape ``(I, J, K, ..., L, M, N)``, then an output array has rank ``k-2`` and shape ``(I, J, K, ..., L)`` where + an array containing the traces and whose shape is determined by removing the last two dimensions and storing the traces in the last array dimension. For example, if ``x`` has rank ``k`` and shape ``(I, J, K, ..., L, M, N)``, then an output array has rank ``k-2`` and shape ``(I, J, K, ..., L)`` where - :: + :: - out[i, j, k, ..., l] = trace(a[i, j, k, ..., l, :, :]) + out[i, j, k, ..., l] = trace(a[i, j, k, ..., l, :, :]) - The returned array must have a data type as described by the ``dtype`` parameter above. + The returned array must have a data type as described by the ``dtype`` parameter above. Notes ----- @@ -3328,10 +3332,10 @@ class trace[TArray: Array, TDtype](Protocol): For both real-valued and complex floating-point operands, special cases must be handled as if the operation is implemented by successive application of :func:`~array_api.add`. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. .. versionchanged:: 2023.12 - Required the function to return a floating-point array having the same data type as the input array when provided a floating-point array. + Required the function to return a floating-point array having the same data type as the input array when provided a floating-point array. """ @@ -3347,54 +3351,54 @@ class vector_norm[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a floating-point data type. + input array. Should have a floating-point data type. axis: Optional[Union[int, Tuple[int, ...]]] - If an integer, ``axis`` specifies the axis (dimension) along which to compute vector norms. If an n-tuple, ``axis`` specifies the axes (dimensions) along which to compute batched vector norms. If ``None``, the vector norm must be computed over all array values (i.e., equivalent to computing the vector norm of a flattened array). Negative indices must be supported. Default: ``None``. + If an integer, ``axis`` specifies the axis (dimension) along which to compute vector norms. If an n-tuple, ``axis`` specifies the axes (dimensions) along which to compute batched vector norms. If ``None``, the vector norm must be computed over all array values (i.e., equivalent to computing the vector norm of a flattened array). Negative indices must be supported. Default: ``None``. keepdims: bool - If ``True``, the axes (dimensions) specified by ``axis`` must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the axes (dimensions) specified by ``axis`` must not be included in the result. Default: ``False``. + If ``True``, the axes (dimensions) specified by ``axis`` must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the axes (dimensions) specified by ``axis`` must not be included in the result. Default: ``False``. ord: Union[int, float, Literal[inf, -inf]] - order of the norm. The following mathematical norms must be supported: + order of the norm. The following mathematical norms must be supported: - +------------------+----------------------------+ - | ord | description | - +==================+============================+ - | 1 | L1-norm (Manhattan) | - +------------------+----------------------------+ - | 2 | L2-norm (Euclidean) | - +------------------+----------------------------+ - | inf | infinity norm | - +------------------+----------------------------+ - | (int,float >= 1) | p-norm | - +------------------+----------------------------+ + +------------------+----------------------------+ + | ord | description | + +==================+============================+ + | 1 | L1-norm (Manhattan) | + +------------------+----------------------------+ + | 2 | L2-norm (Euclidean) | + +------------------+----------------------------+ + | inf | infinity norm | + +------------------+----------------------------+ + | (int,float >= 1) | p-norm | + +------------------+----------------------------+ - The following non-mathematical "norms" must be supported: + The following non-mathematical "norms" must be supported: - +------------------+--------------------------------+ - | ord | description | - +==================+================================+ - | 0 | sum(a != 0) | - +------------------+--------------------------------+ - | -1 | 1./sum(1./abs(a)) | - +------------------+--------------------------------+ - | -2 | 1./sqrt(sum(1./abs(a)\\*\\*2)) | - +------------------+--------------------------------+ - | -inf | min(abs(a)) | - +------------------+--------------------------------+ - | (int,float < 1) | sum(abs(a)\\*\\*ord)\\*\\*(1./ord) | - +------------------+--------------------------------+ + +------------------+--------------------------------+ + | ord | description | + +==================+================================+ + | 0 | sum(a != 0) | + +------------------+--------------------------------+ + | -1 | 1./sum(1./abs(a)) | + +------------------+--------------------------------+ + | -2 | 1./sqrt(sum(1./abs(a)\\*\\*2)) | + +------------------+--------------------------------+ + | -inf | min(abs(a)) | + +------------------+--------------------------------+ + | (int,float < 1) | sum(abs(a)\\*\\*ord)\\*\\*(1./ord) | + +------------------+--------------------------------+ - Default: ``2``. + Default: ``2``. Returns ------- out: array - an array containing the vector norms. If ``axis`` is ``None``, the returned array must be a zero-dimensional array containing a vector norm. If ``axis`` is a scalar value (``int`` or ``float``), the returned array must have a rank which is one less than the rank of ``x``. If ``axis`` is a ``n``-tuple, the returned array must have a rank which is ``n`` less than the rank of ``x``. If ``x`` has a real-valued data type, the returned array must have a real-valued floating-point data type determined by :ref:`type-promotion`. If ``x`` has a complex-valued data type, the returned array must have a real-valued floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``complex128``, then the returned array must have a ``float64`` data type). + an array containing the vector norms. If ``axis`` is ``None``, the returned array must be a zero-dimensional array containing a vector norm. If ``axis`` is a scalar value (``int`` or ``float``), the returned array must have a rank which is one less than the rank of ``x``. If ``axis`` is a ``n``-tuple, the returned array must have a rank which is ``n`` less than the rank of ``x``. If ``x`` has a real-valued data type, the returned array must have a real-valued floating-point data type determined by :ref:`type-promotion`. If ``x`` has a complex-valued data type, the returned array must have a real-valued floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``complex128``, then the returned array must have a ``float64`` data type). Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -3409,23 +3413,23 @@ class argsort[TArray: Array](Protocol): Returns the indices that sort an array ``x`` along a specified axis. .. note:: - For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). + For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). Parameters ---------- x : array - input array. Should have a real-valued data type. + input array. Should have a real-valued data type. axis: int - axis along which to sort. If set to ``-1``, the function must sort along the last axis. Default: ``-1``. + axis along which to sort. If set to ``-1``, the function must sort along the last axis. Default: ``-1``. descending: bool - sort order. If ``True``, the returned indices sort ``x`` in descending order (by value). If ``False``, the returned indices sort ``x`` in ascending order (by value). Default: ``False``. + sort order. If ``True``, the returned indices sort ``x`` in descending order (by value). If ``False``, the returned indices sort ``x`` in ascending order (by value). Default: ``False``. stable: bool - sort stability. If ``True``, the returned indices must maintain the relative order of ``x`` values which compare as equal. If ``False``, the returned indices may or may not maintain the relative order of ``x`` values which compare as equal (i.e., the relative order of ``x`` values which compare as equal is implementation-dependent). Default: ``True``. + sort stability. If ``True``, the returned indices must maintain the relative order of ``x`` values which compare as equal. If ``False``, the returned indices may or may not maintain the relative order of ``x`` values which compare as equal (i.e., the relative order of ``x`` values which compare as equal is implementation-dependent). Default: ``True``. Returns ------- out : array - an array of indices. The returned array must have the same shape as ``x``. The returned array must have the default array index data type. + an array of indices. The returned array must have the same shape as ``x``. The returned array must have the default array index data type. """ @@ -3439,23 +3443,23 @@ class sort[TArray: Array](Protocol): Returns a sorted copy of an input array ``x``. .. note:: - For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). + For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). Parameters ---------- x: array - input array. Should have a real-valued data type. + input array. Should have a real-valued data type. axis: int - axis along which to sort. If set to ``-1``, the function must sort along the last axis. Default: ``-1``. + axis along which to sort. If set to ``-1``, the function must sort along the last axis. Default: ``-1``. descending: bool - sort order. If ``True``, the array must be sorted in descending order (by value). If ``False``, the array must be sorted in ascending order (by value). Default: ``False``. + sort order. If ``True``, the array must be sorted in descending order (by value). If ``False``, the array must be sorted in ascending order (by value). Default: ``False``. stable: bool - sort stability. If ``True``, the returned array must maintain the relative order of ``x`` values which compare as equal. If ``False``, the returned array may or may not maintain the relative order of ``x`` values which compare as equal (i.e., the relative order of ``x`` values which compare as equal is implementation-dependent). Default: ``True``. + sort stability. If ``True``, the returned array must maintain the relative order of ``x`` values which compare as equal. If ``False``, the returned array may or may not maintain the relative order of ``x`` values which compare as equal (i.e., the relative order of ``x`` values which compare as equal is implementation-dependent). Default: ``True``. Returns ------- out : array - a sorted array. The returned array must have the same data type and shape as ``x``. + a sorted array. The returned array must have the same data type and shape as ``x``. """ @@ -3471,29 +3475,29 @@ class abs[TArray: Array](Protocol): For real-valued input arrays, the element-wise result has the same magnitude as the respective element in ``x`` but has positive sign. .. note:: - For signed integer data types, the absolute value of the minimum representable integer is implementation-dependent. + For signed integer data types, the absolute value of the minimum representable integer is implementation-dependent. .. note:: - For complex floating-point operands, the complex absolute value is known as the norm, modulus, or magnitude and, for a complex number :math:`z = a + bj` is computed as + For complex floating-point operands, the complex absolute value is known as the norm, modulus, or magnitude and, for a complex number :math:`z = a + bj` is computed as - .. math:: - \\operatorname{abs}(z) = \\sqrt{a^2 + b^2} + .. math:: + \\operatorname{abs}(z) = \\sqrt{a^2 + b^2} .. note:: - For complex floating-point operands, conforming implementations should take care to avoid undue overflow or underflow during intermediate stages of computation. + For complex floating-point operands, conforming implementations should take care to avoid undue overflow or underflow during intermediate stages of computation. .. - TODO: once ``hypot`` is added to the specification, remove the special cases for complex floating-point operands and the note concerning guarding against undue overflow/underflow, and state that special cases must be handled as if implemented as ``hypot(real(x), imag(x))``. + TODO: once ``hypot`` is added to the specification, remove the special cases for complex floating-point operands and the note concerning guarding against undue overflow/underflow, and state that special cases must be handled as if implemented as ``hypot(real(x), imag(x))``. Parameters ---------- x: array - input array. Should have a numeric data type. + input array. Should have a numeric data type. Returns ------- out: array - an array containing the absolute value of each element in ``x``. If ``x`` has a real-valued data type, the returned array must have the same data type as ``x``. If ``x`` has a complex floating-point data type, the returned array must have a real-valued floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``complex128``, then the returned array must have a ``float64`` data type). + an array containing the absolute value of each element in ``x``. If ``x`` has a real-valued data type, the returned array must have the same data type as ``x``. If ``x`` has a complex floating-point data type, the returned array must have a real-valued floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``complex128``, then the returned array must have a ``float64`` data type). Notes ----- @@ -3516,7 +3520,7 @@ class abs[TArray: Array](Protocol): - If ``a`` is ``NaN`` and ``b`` is ``NaN``, the result is ``NaN``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -3532,35 +3536,35 @@ class acos[TArray: Array](Protocol): Each element-wise result is expressed in radians. .. note:: - The principal value of the arc cosine of a complex number :math:`z` is + The principal value of the arc cosine of a complex number :math:`z` is - .. math:: - \\operatorname{acos}(z) = \\frac{1}{2}\\pi + j\\ \\ln(zj + \\sqrt{1-z^2}) + .. math:: + \\operatorname{acos}(z) = \\frac{1}{2}\\pi + j\\ \\ln(zj + \\sqrt{1-z^2}) - For any :math:`z`, + For any :math:`z`, - .. math:: - \\operatorname{acos}(z) = \\pi - \\operatorname{acos}(-z) + .. math:: + \\operatorname{acos}(z) = \\pi - \\operatorname{acos}(-z) .. note:: - For complex floating-point operands, ``acos(conj(x))`` must equal ``conj(acos(x))``. + For complex floating-point operands, ``acos(conj(x))`` must equal ``conj(acos(x))``. .. note:: - The inverse cosine (or arc cosine) is a multi-valued function and requires a branch cut on the complex plane. By convention, a branch cut is placed at the line segments :math:`(-\\infty, -1)` and :math:`(1, \\infty)` of the real axis. + The inverse cosine (or arc cosine) is a multi-valued function and requires a branch cut on the complex plane. By convention, a branch cut is placed at the line segments :math:`(-\\infty, -1)` and :math:`(1, \\infty)` of the real axis. - Accordingly, for complex arguments, the function returns the inverse cosine in the range of a strip unbounded along the imaginary axis and in the interval :math:`[0, \\pi]` along the real axis. + Accordingly, for complex arguments, the function returns the inverse cosine in the range of a strip unbounded along the imaginary axis and in the interval :math:`[0, \\pi]` along the real axis. - *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). + *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). Parameters ---------- x: array - input array. Should have a floating-point data type. + input array. Should have a floating-point data type. Returns ------- out: array - an array containing the inverse cosine of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the inverse cosine of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -3589,7 +3593,7 @@ class acos[TArray: Array](Protocol): - If ``a`` is ``NaN`` and ``b`` is ``NaN``, the result is ``NaN + NaN j``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -3603,42 +3607,42 @@ class acosh[TArray: Array](Protocol): Calculates an implementation-dependent approximation to the inverse hyperbolic cosine for each element ``x_i`` of the input array ``x``. .. note:: - The principal value of the inverse hyperbolic cosine of a complex number :math:`z` is + The principal value of the inverse hyperbolic cosine of a complex number :math:`z` is - .. math:: - \\operatorname{acosh}(z) = \\ln(z + \\sqrt{z+1}\\sqrt{z-1}) + .. math:: + \\operatorname{acosh}(z) = \\ln(z + \\sqrt{z+1}\\sqrt{z-1}) - For any :math:`z`, + For any :math:`z`, - .. math:: - \\operatorname{acosh}(z) = \\frac{\\sqrt{z-1}}{\\sqrt{1-z}}\\operatorname{acos}(z) + .. math:: + \\operatorname{acosh}(z) = \\frac{\\sqrt{z-1}}{\\sqrt{1-z}}\\operatorname{acos}(z) - or simply + or simply - .. math:: - \\operatorname{acosh}(z) = j\\ \\operatorname{acos}(z) + .. math:: + \\operatorname{acosh}(z) = j\\ \\operatorname{acos}(z) - in the upper half of the complex plane. + in the upper half of the complex plane. .. note:: - For complex floating-point operands, ``acosh(conj(x))`` must equal ``conj(acosh(x))``. + For complex floating-point operands, ``acosh(conj(x))`` must equal ``conj(acosh(x))``. .. note:: - The inverse hyperbolic cosine is a multi-valued function and requires a branch cut on the complex plane. By convention, a branch cut is placed at the line segment :math:`(-\\infty, 1)` of the real axis. + The inverse hyperbolic cosine is a multi-valued function and requires a branch cut on the complex plane. By convention, a branch cut is placed at the line segment :math:`(-\\infty, 1)` of the real axis. - Accordingly, for complex arguments, the function returns the inverse hyperbolic cosine in the interval :math:`[0, \\infty)` along the real axis and in the interval :math:`[-\\pi j, +\\pi j]` along the imaginary axis. + Accordingly, for complex arguments, the function returns the inverse hyperbolic cosine in the interval :math:`[0, \\infty)` along the real axis and in the interval :math:`[-\\pi j, +\\pi j]` along the imaginary axis. - *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). + *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). Parameters ---------- x: array - input array whose elements each represent the area of a hyperbolic sector. Should have a floating-point data type. + input array whose elements each represent the area of a hyperbolic sector. Should have a floating-point data type. Returns ------- out: array - an array containing the inverse hyperbolic cosine of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the inverse hyperbolic cosine of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -3667,7 +3671,7 @@ class acosh[TArray: Array](Protocol): - If ``a`` is ``NaN`` and ``b`` is ``NaN``, the result is ``NaN + NaN j``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -3683,14 +3687,14 @@ class add[TArray: Array](Protocol): Parameters ---------- x1: array - first input array. Should have a numeric data type. + first input array. Should have a numeric data type. x2: array - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a numeric data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a numeric data type. Returns ------- out: array - an array containing the element-wise sums. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise sums. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- @@ -3717,7 +3721,7 @@ class add[TArray: Array](Protocol): - In the remaining cases, when neither ``infinity``, ``+0``, ``-0``, nor a ``NaN`` is involved, and the operands have the same mathematical sign or have different magnitudes, the sum must be computed and rounded to the nearest representable value according to IEEE 754-2019 and a supported round mode. If the magnitude is too large to represent, the operation overflows and the result is an `infinity` of appropriate mathematical sign. .. note:: - Floating-point addition is a commutative operation, but not always associative. + Floating-point addition is a commutative operation, but not always associative. For complex floating-point operands, addition is defined according to the following table. For real components ``a`` and ``c`` and imaginary components ``b`` and ``d``, @@ -3739,7 +3743,7 @@ class add[TArray: Array](Protocol): Hence, if ``z1 = a + bj = -0 + 0j`` and ``z2 = c + dj = -0 - 0j``, the result of ``z1 + z2`` is ``-0 + 0j``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -3755,35 +3759,35 @@ class asin[TArray: Array](Protocol): Each element-wise result is expressed in radians. .. note:: - The principal value of the arc sine of a complex number :math:`z` is + The principal value of the arc sine of a complex number :math:`z` is - .. math:: - \\operatorname{asin}(z) = -j\\ \\ln(zj + \\sqrt{1-z^2}) + .. math:: + \\operatorname{asin}(z) = -j\\ \\ln(zj + \\sqrt{1-z^2}) - For any :math:`z`, + For any :math:`z`, - .. math:: - \\operatorname{asin}(z) = \\operatorname{acos}(-z) - \\frac{\\pi}{2} + .. math:: + \\operatorname{asin}(z) = \\operatorname{acos}(-z) - \\frac{\\pi}{2} .. note:: - For complex floating-point operands, ``asin(conj(x))`` must equal ``conj(asin(x))``. + For complex floating-point operands, ``asin(conj(x))`` must equal ``conj(asin(x))``. .. note:: - The inverse sine (or arc sine) is a multi-valued function and requires a branch cut on the complex plane. By convention, a branch cut is placed at the line segments :math:`(-\\infty, -1)` and :math:`(1, \\infty)` of the real axis. + The inverse sine (or arc sine) is a multi-valued function and requires a branch cut on the complex plane. By convention, a branch cut is placed at the line segments :math:`(-\\infty, -1)` and :math:`(1, \\infty)` of the real axis. - Accordingly, for complex arguments, the function returns the inverse sine in the range of a strip unbounded along the imaginary axis and in the interval :math:`[-\\pi/2, +\\pi/2]` along the real axis. + Accordingly, for complex arguments, the function returns the inverse sine in the range of a strip unbounded along the imaginary axis and in the interval :math:`[-\\pi/2, +\\pi/2]` along the real axis. - *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). + *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). Parameters ---------- x: array - input array. Should have a floating-point data type. + input array. Should have a floating-point data type. Returns ------- out: array - an array containing the inverse sine of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the inverse sine of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -3800,7 +3804,7 @@ class asin[TArray: Array](Protocol): For complex floating-point operands, special cases must be handled as if the operation is implemented as ``-1j * asinh(x*1j)``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -3814,35 +3818,35 @@ class asinh[TArray: Array](Protocol): Calculates an implementation-dependent approximation to the inverse hyperbolic sine for each element ``x_i`` in the input array ``x``. .. note:: - The principal value of the inverse hyperbolic sine of a complex number :math:`z` is + The principal value of the inverse hyperbolic sine of a complex number :math:`z` is - .. math:: - \\operatorname{asinh}(z) = \\ln(z + \\sqrt{1+z^2}) + .. math:: + \\operatorname{asinh}(z) = \\ln(z + \\sqrt{1+z^2}) - For any :math:`z`, + For any :math:`z`, - .. math:: - \\operatorname{asinh}(z) = \\frac{\\operatorname{asin}(zj)}{j} + .. math:: + \\operatorname{asinh}(z) = \\frac{\\operatorname{asin}(zj)}{j} .. note:: - For complex floating-point operands, ``asinh(conj(x))`` must equal ``conj(asinh(x))`` and ``asinh(-z)`` must equal ``-asinh(z)``. + For complex floating-point operands, ``asinh(conj(x))`` must equal ``conj(asinh(x))`` and ``asinh(-z)`` must equal ``-asinh(z)``. .. note:: - The inverse hyperbolic sine is a multi-valued function and requires a branch cut on the complex plane. By convention, a branch cut is placed at the line segments :math:`(-\\infty j, -j)` and :math:`(j, \\infty j)` of the imaginary axis. + The inverse hyperbolic sine is a multi-valued function and requires a branch cut on the complex plane. By convention, a branch cut is placed at the line segments :math:`(-\\infty j, -j)` and :math:`(j, \\infty j)` of the imaginary axis. - Accordingly, for complex arguments, the function returns the inverse hyperbolic sine in the range of a strip unbounded along the real axis and in the interval :math:`[-\\pi j/2, +\\pi j/2]` along the imaginary axis. + Accordingly, for complex arguments, the function returns the inverse hyperbolic sine in the range of a strip unbounded along the real axis and in the interval :math:`[-\\pi j/2, +\\pi j/2]` along the imaginary axis. - *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). + *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). Parameters ---------- x: array - input array whose elements each represent the area of a hyperbolic sector. Should have a floating-point data type. + input array whose elements each represent the area of a hyperbolic sector. Should have a floating-point data type. Returns ------- out: array - an array containing the inverse hyperbolic sine of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the inverse hyperbolic sine of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -3869,7 +3873,7 @@ class asinh[TArray: Array](Protocol): - If ``a`` is ``NaN`` and ``b`` is ``NaN``, the result is ``NaN + NaN j``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -3885,30 +3889,30 @@ class atan[TArray: Array](Protocol): Each element-wise result is expressed in radians. .. note:: - The principal value of the inverse tangent of a complex number :math:`z` is + The principal value of the inverse tangent of a complex number :math:`z` is - .. math:: - \\operatorname{atan}(z) = -\\frac{\\ln(1 - zj) - \\ln(1 + zj)}{2}j + .. math:: + \\operatorname{atan}(z) = -\\frac{\\ln(1 - zj) - \\ln(1 + zj)}{2}j .. note:: - For complex floating-point operands, ``atan(conj(x))`` must equal ``conj(atan(x))``. + For complex floating-point operands, ``atan(conj(x))`` must equal ``conj(atan(x))``. .. note:: - The inverse tangent (or arc tangent) is a multi-valued function and requires a branch on the complex plane. By convention, a branch cut is placed at the line segments :math:`(-\\infty j, -j)` and :math:`(+j, \\infty j)` of the imaginary axis. + The inverse tangent (or arc tangent) is a multi-valued function and requires a branch on the complex plane. By convention, a branch cut is placed at the line segments :math:`(-\\infty j, -j)` and :math:`(+j, \\infty j)` of the imaginary axis. - Accordingly, for complex arguments, the function returns the inverse tangent in the range of a strip unbounded along the imaginary axis and in the interval :math:`[-\\pi/2, +\\pi/2]` along the real axis. + Accordingly, for complex arguments, the function returns the inverse tangent in the range of a strip unbounded along the imaginary axis and in the interval :math:`[-\\pi/2, +\\pi/2]` along the real axis. - *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). + *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). Parameters ---------- x: array - input array. Should have a floating-point data type. + input array. Should have a floating-point data type. Returns ------- out: array - an array containing the inverse tangent of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the inverse tangent of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -3925,7 +3929,7 @@ class atan[TArray: Array](Protocol): For complex floating-point operands, special cases must be handled as if the operation is implemented as ``-1j * atanh(x*1j)``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -3941,21 +3945,21 @@ class atan2[TArray: Array](Protocol): The mathematical signs of ``x1_i`` and ``x2_i`` determine the quadrant of each element-wise result. The quadrant (i.e., branch) is chosen such that each element-wise result is the signed angle in radians between the ray ending at the origin and passing through the point ``(1,0)`` and the ray ending at the origin and passing through the point ``(x2_i, x1_i)``. .. note:: - Note the role reversal: the "y-coordinate" is the first function parameter; the "x-coordinate" is the second function parameter. The parameter order is intentional and traditional for the two-argument inverse tangent function where the y-coordinate argument is first and the x-coordinate argument is second. + Note the role reversal: the "y-coordinate" is the first function parameter; the "x-coordinate" is the second function parameter. The parameter order is intentional and traditional for the two-argument inverse tangent function where the y-coordinate argument is first and the x-coordinate argument is second. By IEEE 754 convention, the inverse tangent of the quotient ``x1/x2`` is defined for ``x2_i`` equal to positive or negative zero and for either or both of ``x1_i`` and ``x2_i`` equal to positive or negative ``infinity``. Parameters ---------- x1: array - input array corresponding to the y-coordinates. Should have a real-valued floating-point data type. + input array corresponding to the y-coordinates. Should have a real-valued floating-point data type. x2: array - input array corresponding to the x-coordinates. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued floating-point data type. + input array corresponding to the x-coordinates. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued floating-point data type. Returns ------- out: array - an array containing the inverse tangent of the quotient ``x1/x2``. The returned array must have a real-valued floating-point data type determined by :ref:`type-promotion`. + an array containing the inverse tangent of the quotient ``x1/x2``. The returned array must have a real-valued floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -3999,35 +4003,35 @@ class atanh[TArray: Array](Protocol): Calculates an implementation-dependent approximation to the inverse hyperbolic tangent for each element ``x_i`` of the input array ``x``. .. note:: - The principal value of the inverse hyperbolic tangent of a complex number :math:`z` is + The principal value of the inverse hyperbolic tangent of a complex number :math:`z` is - .. math:: - \\operatorname{atanh}(z) = \\frac{\\ln(1+z)-\\ln(z-1)}{2} + .. math:: + \\operatorname{atanh}(z) = \\frac{\\ln(1+z)-\\ln(z-1)}{2} - For any :math:`z`, + For any :math:`z`, - .. math:: - \\operatorname{atanh}(z) = \\frac{\\operatorname{atan}(zj)}{j} + .. math:: + \\operatorname{atanh}(z) = \\frac{\\operatorname{atan}(zj)}{j} .. note:: - For complex floating-point operands, ``atanh(conj(x))`` must equal ``conj(atanh(x))`` and ``atanh(-x)`` must equal ``-atanh(x)``. + For complex floating-point operands, ``atanh(conj(x))`` must equal ``conj(atanh(x))`` and ``atanh(-x)`` must equal ``-atanh(x)``. .. note:: - The inverse hyperbolic tangent is a multi-valued function and requires a branch cut on the complex plane. By convention, a branch cut is placed at the line segments :math:`(-\\infty, 1]` and :math:`[1, \\infty)` of the real axis. + The inverse hyperbolic tangent is a multi-valued function and requires a branch cut on the complex plane. By convention, a branch cut is placed at the line segments :math:`(-\\infty, 1]` and :math:`[1, \\infty)` of the real axis. - Accordingly, for complex arguments, the function returns the inverse hyperbolic tangent in the range of a half-strip unbounded along the real axis and in the interval :math:`[-\\pi j/2, +\\pi j/2]` along the imaginary axis. + Accordingly, for complex arguments, the function returns the inverse hyperbolic tangent in the range of a half-strip unbounded along the real axis and in the interval :math:`[-\\pi j/2, +\\pi j/2]` along the imaginary axis. - *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). + *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). Parameters ---------- x: array - input array whose elements each represent the area of a hyperbolic sector. Should have a floating-point data type. + input array whose elements each represent the area of a hyperbolic sector. Should have a floating-point data type. Returns ------- out: array - an array containing the inverse hyperbolic tangent of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the inverse hyperbolic tangent of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -4058,7 +4062,7 @@ class atanh[TArray: Array](Protocol): - If ``a`` is ``NaN`` and ``b`` is ``NaN``, the result is ``NaN + NaN j``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -4074,14 +4078,14 @@ class bitwise_and[TArray: Array](Protocol): Parameters ---------- x1: array - first input array. Should have an integer or boolean data type. + first input array. Should have an integer or boolean data type. x2: array - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have an integer or boolean data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have an integer or boolean data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. """ @@ -4097,14 +4101,14 @@ class bitwise_left_shift[TArray: Array](Protocol): Parameters ---------- x1: array - first input array. Should have an integer data type. + first input array. Should have an integer data type. x2: array - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have an integer data type. Each element must be greater than or equal to ``0``. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have an integer data type. Each element must be greater than or equal to ``0``. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. """ @@ -4120,12 +4124,12 @@ class bitwise_invert[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have an integer or boolean data type. + input array. Should have an integer or boolean data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have the same data type as ``x``. + an array containing the element-wise results. The returned array must have the same data type as ``x``. """ @@ -4141,14 +4145,14 @@ class bitwise_or[TArray: Array](Protocol): Parameters ---------- x1: array - first input array. Should have an integer or boolean data type. + first input array. Should have an integer or boolean data type. x2: array - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have an integer or boolean data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have an integer or boolean data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. """ @@ -4162,19 +4166,19 @@ class bitwise_right_shift[TArray: Array](Protocol): Shifts the bits of each element ``x1_i`` of the input array ``x1`` to the right according to the respective element ``x2_i`` of the input array ``x2``. .. note:: - This operation must be an arithmetic shift (i.e., sign-propagating) and thus equivalent to floor division by a power of two. + This operation must be an arithmetic shift (i.e., sign-propagating) and thus equivalent to floor division by a power of two. Parameters ---------- x1: array - first input array. Should have an integer data type. + first input array. Should have an integer data type. x2: array - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have an integer data type. Each element must be greater than or equal to ``0``. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have an integer data type. Each element must be greater than or equal to ``0``. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. """ @@ -4190,14 +4194,14 @@ class bitwise_xor[TArray: Array](Protocol): Parameters ---------- x1: array - first input array. Should have an integer or boolean data type. + first input array. Should have an integer or boolean data type. x2: array - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have an integer or boolean data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have an integer or boolean data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. """ @@ -4213,12 +4217,12 @@ class ceil[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a real-valued data type. + input array. Should have a real-valued data type. Returns ------- out: array - an array containing the rounded result for each element in ``x``. The returned array must have the same data type as ``x``. + an array containing the rounded result for each element in ``x``. The returned array must have the same data type as ``x``. Notes ----- @@ -4248,16 +4252,16 @@ class clip[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a real-valued data type. + input array. Should have a real-valued data type. min: Optional[Union[int, float, array]] - lower-bound of the range to which to clamp. If ``None``, no lower bound must be applied. Must be compatible with ``x`` and ``max`` (see :ref:`broadcasting`). Should have a real-valued data type. Default: ``None``. + lower-bound of the range to which to clamp. If ``None``, no lower bound must be applied. Must be compatible with ``x`` and ``max`` (see :ref:`broadcasting`). Should have a real-valued data type. Default: ``None``. max: Optional[Union[int, float, array]] - upper-bound of the range to which to clamp. If ``None``, no upper bound must be applied. Must be compatible with ``x`` and ``min`` (see :ref:`broadcasting`). Should have a real-valued data type. Default: ``None``. + upper-bound of the range to which to clamp. If ``None``, no upper bound must be applied. Must be compatible with ``x`` and ``min`` (see :ref:`broadcasting`). Should have a real-valued data type. Default: ``None``. Returns ------- out: array - an array containing element-wise results. The returned array must have the same data type as ``x``. + an array containing element-wise results. The returned array must have the same data type as ``x``. Notes ----- @@ -4288,24 +4292,24 @@ class conj[TArray: Array](Protocol): For complex numbers of the form .. math:: - a + bj + a + bj the complex conjugate is defined as .. math:: - a - bj + a - bj Hence, the returned complex conjugates must be computed by negating the imaginary component of each element ``x_i``. Parameters ---------- x: array - input array. Should have a complex floating-point data type. + input array. Should have a complex floating-point data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have the same data type as ``x``. + an array containing the element-wise results. The returned array must have the same data type as ``x``. Notes ----- @@ -4326,14 +4330,14 @@ class copysign[TArray: Array](Protocol): Parameters ---------- x1: array - input array containing magnitudes. Should have a real-valued floating-point data type. + input array containing magnitudes. Should have a real-valued floating-point data type. x2: array - input array whose sign bits are applied to the magnitudes of ``x1``. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued floating-point data type. + input array whose sign bits are applied to the magnitudes of ``x1``. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued floating-point data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the element-wise results. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -4371,25 +4375,25 @@ class cos[TArray: Array](Protocol): Each element ``x_i`` is assumed to be expressed in radians. .. note:: - The cosine is an entire function on the complex plane and has no branch cuts. + The cosine is an entire function on the complex plane and has no branch cuts. .. note:: - For complex arguments, the mathematical definition of cosine is + For complex arguments, the mathematical definition of cosine is - .. math:: - \\begin{align} \\operatorname{cos}(x) &= \\sum_{n=0}^\\infty \\frac{(-1)^n}{(2n)!} x^{2n} \\\\ &= \\frac{e^{jx} + e^{-jx}}{2} \\\\ &= \\operatorname{cosh}(jx) \\end{align} + .. math:: + \\begin{align} \\operatorname{cos}(x) &= \\sum_{n=0}^\\infty \\frac{(-1)^n}{(2n)!} x^{2n} \\\\ &= \\frac{e^{jx} + e^{-jx}}{2} \\\\ &= \\operatorname{cosh}(jx) \\end{align} - where :math:`\\operatorname{cosh}` is the hyperbolic cosine. + where :math:`\\operatorname{cosh}` is the hyperbolic cosine. Parameters ---------- x: array - input array whose elements are each expressed in radians. Should have a floating-point data type. + input array whose elements are each expressed in radians. Should have a floating-point data type. Returns ------- out: array - an array containing the cosine of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the cosine of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -4406,7 +4410,7 @@ class cos[TArray: Array](Protocol): For complex floating-point operands, special cases must be handled as if the operation is implemented as ``cosh(x*1j)``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -4422,27 +4426,27 @@ class cosh[TArray: Array](Protocol): The mathematical definition of the hyperbolic cosine is .. math:: - \\operatorname{cosh}(x) = \\frac{e^x + e^{-x}}{2} + \\operatorname{cosh}(x) = \\frac{e^x + e^{-x}}{2} .. note:: - The hyperbolic cosine is an entire function in the complex plane and has no branch cuts. The function is periodic, with period :math:`2\\pi j`, with respect to the imaginary component. + The hyperbolic cosine is an entire function in the complex plane and has no branch cuts. The function is periodic, with period :math:`2\\pi j`, with respect to the imaginary component. Parameters ---------- x: array - input array whose elements each represent a hyperbolic angle. Should have a floating-point data type. + input array whose elements each represent a hyperbolic angle. Should have a floating-point data type. Returns ------- out: array - an array containing the hyperbolic cosine of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the hyperbolic cosine of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- **Special cases** .. note:: - For all operands, ``cosh(x)`` must equal ``cosh(-x)``. + For all operands, ``cosh(x)`` must equal ``cosh(-x)``. For real-valued floating-point operands, @@ -4455,7 +4459,7 @@ class cosh[TArray: Array](Protocol): For complex floating-point operands, let ``a = real(x_i)``, ``b = imag(x_i)``, and .. note:: - For complex floating-point operands, ``cosh(conj(x))`` must equal ``conj(cosh(x))``. + For complex floating-point operands, ``cosh(conj(x))`` must equal ``conj(cosh(x))``. - If ``a`` is ``+0`` and ``b`` is ``+0``, the result is ``1 + 0j``. - If ``a`` is ``+0`` and ``b`` is ``+infinity``, the result is ``NaN + 0j`` (sign of the imaginary component is unspecified). @@ -4473,7 +4477,7 @@ class cosh[TArray: Array](Protocol): where ``cis(v)`` is ``cos(v) + sin(v)*1j``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -4487,21 +4491,21 @@ class divide[TArray: Array](Protocol): Calculates the division of each element ``x1_i`` of the input array ``x1`` with the respective element ``x2_i`` of the input array ``x2``. .. note:: - If one or both of the input arrays have integer data types, the result is implementation-dependent, as type promotion between data type "kinds" (e.g., integer versus floating-point) is unspecified. + If one or both of the input arrays have integer data types, the result is implementation-dependent, as type promotion between data type "kinds" (e.g., integer versus floating-point) is unspecified. - Specification-compliant libraries may choose to raise an error or return an array containing the element-wise results. If an array is returned, the array must have a real-valued floating-point data type. + Specification-compliant libraries may choose to raise an error or return an array containing the element-wise results. If an array is returned, the array must have a real-valued floating-point data type. Parameters ---------- x1: array - dividend input array. Should have a numeric data type. + dividend input array. Should have a numeric data type. x2: array - divisor input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a numeric data type. + divisor input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a numeric data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the element-wise results. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -4549,7 +4553,7 @@ class divide[TArray: Array](Protocol): When ``a``, ``b``, ``c``, or ``d`` are all finite numbers (i.e., a value other than ``NaN``, ``+infinity``, or ``-infinity``), division of complex floating-point operands should be computed as if calculated according to the textbook formula for complex number division .. math:: - \\frac{a + bj}{c + dj} = \\frac{(ac + bd) + (bc - ad)j}{c^2 + d^2} + \\frac{a + bj}{c + dj} = \\frac{(ac + bd) + (bc - ad)j}{c^2 + d^2} When at least one of ``a``, ``b``, ``c``, or ``d`` is ``NaN``, ``+infinity``, or ``-infinity``, @@ -4557,10 +4561,10 @@ class divide[TArray: Array](Protocol): - In the remaining cases, the result is implementation dependent. .. note:: - For complex floating-point operands, the results of special cases may be implementation dependent depending on how an implementation chooses to model complex numbers and complex infinity (e.g., complex plane versus Riemann sphere). For those implementations following C99 and its one-infinity model, when at least one component is infinite, even if the other component is ``NaN``, the complex value is infinite, and the usual arithmetic rules do not apply to complex-complex division. In the interest of performance, other implementations may want to avoid the complex branching logic necessary to implement the one-infinity model and choose to implement all complex-complex division according to the textbook formula. Accordingly, special case behavior is unlikely to be consistent across implementations. + For complex floating-point operands, the results of special cases may be implementation dependent depending on how an implementation chooses to model complex numbers and complex infinity (e.g., complex plane versus Riemann sphere). For those implementations following C99 and its one-infinity model, when at least one component is infinite, even if the other component is ``NaN``, the complex value is infinite, and the usual arithmetic rules do not apply to complex-complex division. In the interest of performance, other implementations may want to avoid the complex branching logic necessary to implement the one-infinity model and choose to implement all complex-complex division according to the textbook formula. Accordingly, special case behavior is unlikely to be consistent across implementations. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -4576,14 +4580,14 @@ class equal[TArray: Array](Protocol): Parameters ---------- x1: array - first input array. May have any data type. + first input array. May have any data type. x2: array - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). May have any data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). May have any data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type of ``bool``. + an array containing the element-wise results. The returned array must have a data type of ``bool``. Notes ----- @@ -4605,10 +4609,10 @@ class equal[TArray: Array](Protocol): - In the remaining cases, the result is the logical AND of the equality comparison between the real values ``a`` and ``c`` (real components) and between the real values ``b`` and ``d`` (imaginary components), as described above for real-valued floating-point operands (i.e., ``a == c AND b == d``). .. note:: - For discussion of complex number equality, see :ref:`complex-numbers`. + For discussion of complex number equality, see :ref:`complex-numbers`. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -4622,20 +4626,20 @@ class exp[TArray: Array](Protocol): Calculates an implementation-dependent approximation to the exponential function for each element ``x_i`` of the input array ``x`` (``e`` raised to the power of ``x_i``, where ``e`` is the base of the natural logarithm). .. note:: - For complex floating-point operands, ``exp(conj(x))`` must equal ``conj(exp(x))``. + For complex floating-point operands, ``exp(conj(x))`` must equal ``conj(exp(x))``. .. note:: - The exponential function is an entire function in the complex plane and has no branch cuts. + The exponential function is an entire function in the complex plane and has no branch cuts. Parameters ---------- x: array - input array. Should have a floating-point data type. + input array. Should have a floating-point data type. Returns ------- out: array - an array containing the evaluated exponential function result for each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the evaluated exponential function result for each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -4668,7 +4672,7 @@ class exp[TArray: Array](Protocol): where ``cis(v)`` is ``cos(v) + sin(v)*1j``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -4682,23 +4686,23 @@ class expm1[TArray: Array](Protocol): Calculates an implementation-dependent approximation to ``exp(x)-1`` for each element ``x_i`` of the input array ``x``. .. note:: - The purpose of this function is to calculate ``exp(x)-1.0`` more accurately when `x` is close to zero. Accordingly, conforming implementations should avoid implementing this function as simply ``exp(x)-1.0``. See FDLIBM, or some other IEEE 754-2019 compliant mathematical library, for a potential reference implementation. + The purpose of this function is to calculate ``exp(x)-1.0`` more accurately when `x` is close to zero. Accordingly, conforming implementations should avoid implementing this function as simply ``exp(x)-1.0``. See FDLIBM, or some other IEEE 754-2019 compliant mathematical library, for a potential reference implementation. .. note:: - For complex floating-point operands, ``expm1(conj(x))`` must equal ``conj(expm1(x))``. + For complex floating-point operands, ``expm1(conj(x))`` must equal ``conj(expm1(x))``. .. note:: - The exponential function is an entire function in the complex plane and has no branch cuts. + The exponential function is an entire function in the complex plane and has no branch cuts. Parameters ---------- x: array - input array. Should have a floating-point data type. + input array. Should have a floating-point data type. Returns ------- out: array - an array containing the evaluated result for each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the evaluated result for each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -4731,7 +4735,7 @@ class expm1[TArray: Array](Protocol): where ``cis(v)`` is ``cos(v) + sin(v)*1j``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -4747,12 +4751,12 @@ class floor[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a real-valued data type. + input array. Should have a real-valued data type. Returns ------- out: array - an array containing the rounded result for each element in ``x``. The returned array must have the same data type as ``x``. + an array containing the rounded result for each element in ``x``. The returned array must have the same data type as ``x``. Notes ----- @@ -4780,32 +4784,32 @@ class floor_divide[TArray: Array](Protocol): Rounds the result of dividing each element ``x1_i`` of the input array ``x1`` by the respective element ``x2_i`` of the input array ``x2`` to the greatest (i.e., closest to `+infinity`) integer-value number that is not greater than the division result. .. note:: - For input arrays which promote to an integer data type, the result of division by zero is unspecified and thus implementation-defined. + For input arrays which promote to an integer data type, the result of division by zero is unspecified and thus implementation-defined. Parameters ---------- x1: array - dividend input array. Should have a real-valued data type. + dividend input array. Should have a real-valued data type. x2: array - divisor input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued data type. + divisor input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- **Special cases** .. note:: - Floor division was introduced in Python via `PEP 238 `_ with the goal to disambiguate "true division" (i.e., computing an approximation to the mathematical operation of division) from "floor division" (i.e., rounding the result of division toward negative infinity). The former was computed when one of the operands was a ``float``, while the latter was computed when both operands were ``int``\\s. Overloading the ``/`` operator to support both behaviors led to subtle numerical bugs when integers are possible, but not expected. + Floor division was introduced in Python via `PEP 238 `_ with the goal to disambiguate "true division" (i.e., computing an approximation to the mathematical operation of division) from "floor division" (i.e., rounding the result of division toward negative infinity). The former was computed when one of the operands was a ``float``, while the latter was computed when both operands were ``int``\\s. Overloading the ``/`` operator to support both behaviors led to subtle numerical bugs when integers are possible, but not expected. - To resolve this ambiguity, ``/`` was designated for true division, and ``//`` was designated for floor division. Semantically, floor division was `defined `_ as equivalent to ``a // b == floor(a/b)``; however, special floating-point cases were left ill-defined. + To resolve this ambiguity, ``/`` was designated for true division, and ``//`` was designated for floor division. Semantically, floor division was `defined `_ as equivalent to ``a // b == floor(a/b)``; however, special floating-point cases were left ill-defined. - Accordingly, floor division is not implemented consistently across array libraries for some of the special cases documented below. Namely, when one of the operands is ``infinity``, libraries may diverge with some choosing to strictly follow ``floor(a/b)`` and others choosing to pair ``//`` with ``%`` according to the relation ``b = a % b + b * (a // b)``. The special cases leading to divergent behavior are documented below. + Accordingly, floor division is not implemented consistently across array libraries for some of the special cases documented below. Namely, when one of the operands is ``infinity``, libraries may diverge with some choosing to strictly follow ``floor(a/b)`` and others choosing to pair ``//`` with ``%`` according to the relation ``b = a % b + b * (a // b)``. The special cases leading to divergent behavior are documented below. - This specification prefers floor division to match ``floor(divide(x1, x2))`` in order to avoid surprising and unexpected results; however, array libraries may choose to more strictly follow Python behavior. + This specification prefers floor division to match ``floor(divide(x1, x2))`` in order to avoid surprising and unexpected results; however, array libraries may choose to more strictly follow Python behavior. For floating-point operands, @@ -4844,19 +4848,19 @@ class greater[TArray: Array](Protocol): Computes the truth value of ``x1_i > x2_i`` for each element ``x1_i`` of the input array ``x1`` with the respective element ``x2_i`` of the input array ``x2``. .. note:: - For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). + For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). Parameters ---------- x1: array - first input array. Should have a real-valued data type. + first input array. Should have a real-valued data type. x2: array - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type of ``bool``. + an array containing the element-wise results. The returned array must have a data type of ``bool``. """ @@ -4870,19 +4874,19 @@ class greater_equal[TArray: Array](Protocol): Computes the truth value of ``x1_i >= x2_i`` for each element ``x1_i`` of the input array ``x1`` with the respective element ``x2_i`` of the input array ``x2``. .. note:: - For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). + For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). Parameters ---------- x1: array - first input array. Should have a real-valued data type. + first input array. Should have a real-valued data type. x2: array - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type of ``bool``. + an array containing the element-wise results. The returned array must have a data type of ``bool``. """ @@ -4896,19 +4900,19 @@ class hypot[TArray: Array](Protocol): Computes the square root of the sum of squares for each element ``x1_i`` of the input array ``x1`` with the respective element ``x2_i`` of the input array ``x2``. .. note:: - The value computed by this function may be interpreted as the length of the hypotenuse of a right-angled triangle with sides of length ``x1_i`` and ``x2_i``, the distance of a point ``(x1_i, x2_i)`` from the origin ``(0, 0)``, or the magnitude of a complex number ``x1_i + x2_i * 1j``. + The value computed by this function may be interpreted as the length of the hypotenuse of a right-angled triangle with sides of length ``x1_i`` and ``x2_i``, the distance of a point ``(x1_i, x2_i)`` from the origin ``(0, 0)``, or the magnitude of a complex number ``x1_i + x2_i * 1j``. Parameters ---------- x1: array - first input array. Should have a real-valued floating-point data type. + first input array. Should have a real-valued floating-point data type. x2: array - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued floating-point data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued floating-point data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a real-valued floating-point data type determined by :ref:`type-promotion`. + an array containing the element-wise results. The returned array must have a real-valued floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -4929,9 +4933,9 @@ class hypot[TArray: Array](Protocol): For real-valued floating-point operands, ``hypot(x1, x2)`` must equal ``hypot(x2, x1)``, ``hypot(x1, -x2)``, ``hypot(-x1, x2)``, and ``hypot(-x1, -x2)``. .. note:: - IEEE 754-2019 requires support for subnormal (a.k.a., denormal) numbers, which are useful for supporting gradual underflow. However, hardware support for subnormal numbers is not universal, and many platforms (e.g., accelerators) and compilers support toggling denormals-are-zero (DAZ) and/or flush-to-zero (FTZ) behavior to increase performance and to guard against timing attacks. + IEEE 754-2019 requires support for subnormal (a.k.a., denormal) numbers, which are useful for supporting gradual underflow. However, hardware support for subnormal numbers is not universal, and many platforms (e.g., accelerators) and compilers support toggling denormals-are-zero (DAZ) and/or flush-to-zero (FTZ) behavior to increase performance and to guard against timing attacks. - Accordingly, conforming implementations may vary in their support for subnormal numbers. + Accordingly, conforming implementations may vary in their support for subnormal numbers. .. versionadded:: 2023.12 @@ -4949,12 +4953,12 @@ class imag[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a complex floating-point data type. + input array. Should have a complex floating-point data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a floating-point data type with the same floating-point precision as ``x`` (e.g., if ``x`` is ``complex64``, the returned array must have the floating-point data type ``float32``). + an array containing the element-wise results. The returned array must have a floating-point data type with the same floating-point precision as ``x`` (e.g., if ``x`` is ``complex64``, the returned array must have the floating-point data type ``float32``). Notes ----- @@ -4975,12 +4979,12 @@ class isfinite[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a numeric data type. + input array. Should have a numeric data type. Returns ------- out: array - an array containing test results. The returned array must have a data type of ``bool``. + an array containing test results. The returned array must have a data type of ``bool``. Notes ----- @@ -5000,7 +5004,7 @@ class isfinite[TArray: Array](Protocol): - If ``a`` is a finite number and ``b`` is a finite number, the result is ``True``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -5016,12 +5020,12 @@ class isinf[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a numeric data type. + input array. Should have a numeric data type. Returns ------- out: array - an array containing test results. The returned array must have a data type of ``bool``. + an array containing test results. The returned array must have a data type of ``bool``. Notes ----- @@ -5039,7 +5043,7 @@ class isinf[TArray: Array](Protocol): - In the remaining cases, the result is ``False``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -5055,12 +5059,12 @@ class isnan[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a numeric data type. + input array. Should have a numeric data type. Returns ------- out: array - an array containing test results. The returned array should have a data type of ``bool``. + an array containing test results. The returned array should have a data type of ``bool``. Notes ----- @@ -5077,7 +5081,7 @@ class isnan[TArray: Array](Protocol): - In the remaining cases, the result is ``False``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -5091,19 +5095,19 @@ class less[TArray: Array](Protocol): Computes the truth value of ``x1_i < x2_i`` for each element ``x1_i`` of the input array ``x1`` with the respective element ``x2_i`` of the input array ``x2``. .. note:: - For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). + For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). Parameters ---------- x1: array - first input array. Should have a real-valued data type. + first input array. Should have a real-valued data type. x2: array - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type of ``bool``. + an array containing the element-wise results. The returned array must have a data type of ``bool``. """ @@ -5117,19 +5121,19 @@ class less_equal[TArray: Array](Protocol): Computes the truth value of ``x1_i <= x2_i`` for each element ``x1_i`` of the input array ``x1`` with the respective element ``x2_i`` of the input array ``x2``. .. note:: - For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). + For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). Parameters ---------- x1: array - first input array. Should have a real-valued data type. + first input array. Should have a real-valued data type. x2: array - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type of ``bool``. + an array containing the element-wise results. The returned array must have a data type of ``bool``. """ @@ -5143,29 +5147,29 @@ class log[TArray: Array](Protocol): Calculates an implementation-dependent approximation to the natural (base ``e``) logarithm for each element ``x_i`` of the input array ``x``. .. note:: - The natural logarithm of a complex number :math:`z` with polar coordinates :math:`(r,\\theta)` equals :math:`\\ln r + (\\theta + 2n\\pi)j` with principal value :math:`\\ln r + \\theta j`. + The natural logarithm of a complex number :math:`z` with polar coordinates :math:`(r,\\theta)` equals :math:`\\ln r + (\\theta + 2n\\pi)j` with principal value :math:`\\ln r + \\theta j`. .. note:: - For complex floating-point operands, ``log(conj(x))`` must equal ``conj(log(x))``. + For complex floating-point operands, ``log(conj(x))`` must equal ``conj(log(x))``. .. note:: - By convention, the branch cut of the natural logarithm is the negative real axis :math:`(-\\infty, 0)`. + By convention, the branch cut of the natural logarithm is the negative real axis :math:`(-\\infty, 0)`. - The natural logarithm is a continuous function from above the branch cut, taking into account the sign of the imaginary component. + The natural logarithm is a continuous function from above the branch cut, taking into account the sign of the imaginary component. - Accordingly, for complex arguments, the function returns the natural logarithm in the range of a strip in the interval :math:`[-\\pi j, +\\pi j]` along the imaginary axis and mathematically unbounded along the real axis. + Accordingly, for complex arguments, the function returns the natural logarithm in the range of a strip in the interval :math:`[-\\pi j, +\\pi j]` along the imaginary axis and mathematically unbounded along the real axis. - *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). + *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). Parameters ---------- x: array - input array. Should have a floating-point data type. + input array. Should have a floating-point data type. Returns ------- out: array - an array containing the evaluated natural logarithm for each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the evaluated natural logarithm for each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -5195,7 +5199,7 @@ class log[TArray: Array](Protocol): - If ``a`` is ``NaN`` and ``b`` is ``NaN``, the result is ``NaN + NaN j``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -5209,29 +5213,29 @@ class log1p[TArray: Array](Protocol): Calculates an implementation-dependent approximation to ``log(1+x)``, where ``log`` refers to the natural (base ``e``) logarithm, for each element ``x_i`` of the input array ``x``. .. note:: - The purpose of this function is to calculate ``log(1+x)`` more accurately when `x` is close to zero. Accordingly, conforming implementations should avoid implementing this function as simply ``log(1+x)``. See FDLIBM, or some other IEEE 754-2019 compliant mathematical library, for a potential reference implementation. + The purpose of this function is to calculate ``log(1+x)`` more accurately when `x` is close to zero. Accordingly, conforming implementations should avoid implementing this function as simply ``log(1+x)``. See FDLIBM, or some other IEEE 754-2019 compliant mathematical library, for a potential reference implementation. .. note:: - For complex floating-point operands, ``log1p(conj(x))`` must equal ``conj(log1p(x))``. + For complex floating-point operands, ``log1p(conj(x))`` must equal ``conj(log1p(x))``. .. note:: - By convention, the branch cut of the natural logarithm is the negative real axis :math:`(-\\infty, 0)`. + By convention, the branch cut of the natural logarithm is the negative real axis :math:`(-\\infty, 0)`. - The natural logarithm is a continuous function from above the branch cut, taking into account the sign of the imaginary component. + The natural logarithm is a continuous function from above the branch cut, taking into account the sign of the imaginary component. - Accordingly, for complex arguments, the function returns the natural logarithm in the range of a strip in the interval :math:`[-\\pi j, +\\pi j]` along the imaginary axis and mathematically unbounded along the real axis. + Accordingly, for complex arguments, the function returns the natural logarithm in the range of a strip in the interval :math:`[-\\pi j, +\\pi j]` along the imaginary axis and mathematically unbounded along the real axis. - *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). + *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). Parameters ---------- x: array - input array. Should have a floating-point data type. + input array. Should have a floating-point data type. Returns ------- out: array - an array containing the evaluated result for each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the evaluated result for each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -5261,7 +5265,7 @@ class log1p[TArray: Array](Protocol): - If ``a`` is ``NaN`` and ``b`` is ``NaN``, the result is ``NaN + NaN j``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -5275,17 +5279,17 @@ class log2[TArray: Array](Protocol): Calculates an implementation-dependent approximation to the base ``2`` logarithm for each element ``x_i`` of the input array ``x``. .. note:: - For complex floating-point operands, ``log2(conj(x))`` must equal ``conj(log2(x))``. + For complex floating-point operands, ``log2(conj(x))`` must equal ``conj(log2(x))``. Parameters ---------- x: array - input array. Should have a floating-point data type. + input array. Should have a floating-point data type. Returns ------- out: array - an array containing the evaluated base ``2`` logarithm for each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the evaluated base ``2`` logarithm for each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -5302,12 +5306,12 @@ class log2[TArray: Array](Protocol): For complex floating-point operands, special cases must be handled as if the operation is implemented using the standard change of base formula .. math:: - \\log_{2} x = \\frac{\\log_{e} x}{\\log_{e} 2} + \\log_{2} x = \\frac{\\log_{e} x}{\\log_{e} 2} where :math:`\\log_{e}` is the natural logarithm, as implemented by :func:`~array_api.log`. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -5321,17 +5325,17 @@ class log10[TArray: Array](Protocol): Calculates an implementation-dependent approximation to the base ``10`` logarithm for each element ``x_i`` of the input array ``x``. .. note:: - For complex floating-point operands, ``log10(conj(x))`` must equal ``conj(log10(x))``. + For complex floating-point operands, ``log10(conj(x))`` must equal ``conj(log10(x))``. Parameters ---------- x: array - input array. Should have a floating-point data type. + input array. Should have a floating-point data type. Returns ------- out: array - an array containing the evaluated base ``10`` logarithm for each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the evaluated base ``10`` logarithm for each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -5348,12 +5352,12 @@ class log10[TArray: Array](Protocol): For complex floating-point operands, special cases must be handled as if the operation is implemented using the standard change of base formula .. math:: - \\log_{10} x = \\frac{\\log_{e} x}{\\log_{e} 10} + \\log_{10} x = \\frac{\\log_{e} x}{\\log_{e} 10} where :math:`\\log_{e}` is the natural logarithm, as implemented by :func:`~array_api.log`. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -5369,14 +5373,14 @@ class logaddexp[TArray: Array](Protocol): Parameters ---------- x1: array - first input array. Should have a real-valued floating-point data type. + first input array. Should have a real-valued floating-point data type. x2: array - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued floating-point data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued floating-point data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a real-valued floating-point data type determined by :ref:`type-promotion`. + an array containing the element-wise results. The returned array must have a real-valued floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -5400,19 +5404,19 @@ class logical_and[TArray: Array](Protocol): Computes the logical AND for each element ``x1_i`` of the input array ``x1`` with the respective element ``x2_i`` of the input array ``x2``. .. note:: - While this specification recommends that this function only accept input arrays having a boolean data type, specification-compliant array libraries may choose to accept input arrays having real-valued data types. If non-boolean data types are supported, zeros must be considered the equivalent of ``False``, while non-zeros must be considered the equivalent of ``True``. + While this specification recommends that this function only accept input arrays having a boolean data type, specification-compliant array libraries may choose to accept input arrays having real-valued data types. If non-boolean data types are supported, zeros must be considered the equivalent of ``False``, while non-zeros must be considered the equivalent of ``True``. Parameters ---------- x1: array - first input array. Should have a boolean data type. + first input array. Should have a boolean data type. x2: array - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a boolean data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a boolean data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type of `bool`. + an array containing the element-wise results. The returned array must have a data type of `bool`. """ @@ -5426,17 +5430,17 @@ class logical_not[TArray: Array](Protocol): Computes the logical NOT for each element ``x_i`` of the input array ``x``. .. note:: - While this specification recommends that this function only accept input arrays having a boolean data type, specification-compliant array libraries may choose to accept input arrays having real-valued data types. If non-boolean data types are supported, zeros must be considered the equivalent of ``False``, while non-zeros must be considered the equivalent of ``True``. + While this specification recommends that this function only accept input arrays having a boolean data type, specification-compliant array libraries may choose to accept input arrays having real-valued data types. If non-boolean data types are supported, zeros must be considered the equivalent of ``False``, while non-zeros must be considered the equivalent of ``True``. Parameters ---------- x: array - input array. Should have a boolean data type. + input array. Should have a boolean data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type of ``bool``. + an array containing the element-wise results. The returned array must have a data type of ``bool``. """ @@ -5450,19 +5454,19 @@ class logical_or[TArray: Array](Protocol): Computes the logical OR for each element ``x1_i`` of the input array ``x1`` with the respective element ``x2_i`` of the input array ``x2``. .. note:: - While this specification recommends that this function only accept input arrays having a boolean data type, specification-compliant array libraries may choose to accept input arrays having real-valued data types. If non-boolean data types are supported, zeros must be considered the equivalent of ``False``, while non-zeros must be considered the equivalent of ``True``. + While this specification recommends that this function only accept input arrays having a boolean data type, specification-compliant array libraries may choose to accept input arrays having real-valued data types. If non-boolean data types are supported, zeros must be considered the equivalent of ``False``, while non-zeros must be considered the equivalent of ``True``. Parameters ---------- x1: array - first input array. Should have a boolean data type. + first input array. Should have a boolean data type. x2: array - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a boolean data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a boolean data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type of ``bool``. + an array containing the element-wise results. The returned array must have a data type of ``bool``. """ @@ -5476,19 +5480,19 @@ class logical_xor[TArray: Array](Protocol): Computes the logical XOR for each element ``x1_i`` of the input array ``x1`` with the respective element ``x2_i`` of the input array ``x2``. .. note:: - While this specification recommends that this function only accept input arrays having a boolean data type, specification-compliant array libraries may choose to accept input arrays having real-valued data types. If non-boolean data types are supported, zeros must be considered the equivalent of ``False``, while non-zeros must be considered the equivalent of ``True``. + While this specification recommends that this function only accept input arrays having a boolean data type, specification-compliant array libraries may choose to accept input arrays having real-valued data types. If non-boolean data types are supported, zeros must be considered the equivalent of ``False``, while non-zeros must be considered the equivalent of ``True``. Parameters ---------- x1: array - first input array. Should have a boolean data type. + first input array. Should have a boolean data type. x2: array - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a boolean data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a boolean data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type of ``bool``. + an array containing the element-wise results. The returned array must have a data type of ``bool``. """ @@ -5504,14 +5508,14 @@ class maximum[TArray: Array](Protocol): Parameters ---------- x1: array - first input array. Should have a real-valued data type. + first input array. Should have a real-valued data type. x2: array - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued data type. Returns ------- out: array - an array containing the element-wise maximum values. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise maximum values. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- @@ -5541,14 +5545,14 @@ class minimum[TArray: Array](Protocol): Parameters ---------- x1: array - first input array. Should have a real-valued data type. + first input array. Should have a real-valued data type. x2: array - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued data type. Returns ------- out: array - an array containing the element-wise minimum values. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise minimum values. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- @@ -5576,19 +5580,19 @@ class multiply[TArray: Array](Protocol): Calculates the product for each element ``x1_i`` of the input array ``x1`` with the respective element ``x2_i`` of the input array ``x2``. .. note:: - Floating-point multiplication is not always associative due to finite precision. + Floating-point multiplication is not always associative due to finite precision. Parameters ---------- x1: array - first input array. Should have a numeric data type. + first input array. Should have a numeric data type. x2: array - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a numeric data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a numeric data type. Returns ------- out: array - an array containing the element-wise products. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise products. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- @@ -5623,7 +5627,7 @@ class multiply[TArray: Array](Protocol): When ``a``, ``b``, ``c``, or ``d`` are all finite numbers (i.e., a value other than ``NaN``, ``+infinity``, or ``-infinity``), multiplication of complex floating-point operands should be computed as if calculated according to the textbook formula for complex number multiplication .. math:: - (a + bj) \\cdot (c + dj) = (ac - bd) + (bc + ad)j + (a + bj) \\cdot (c + dj) = (ac - bd) + (bc + ad)j When at least one of ``a``, ``b``, ``c``, or ``d`` is ``NaN``, ``+infinity``, or ``-infinity``, @@ -5631,10 +5635,10 @@ class multiply[TArray: Array](Protocol): - In the remaining cases, the result is implementation dependent. .. note:: - For complex floating-point operands, the results of special cases may be implementation dependent depending on how an implementation chooses to model complex numbers and complex infinity (e.g., complex plane versus Riemann sphere). For those implementations following C99 and its one-infinity model, when at least one component is infinite, even if the other component is ``NaN``, the complex value is infinite, and the usual arithmetic rules do not apply to complex-complex multiplication. In the interest of performance, other implementations may want to avoid the complex branching logic necessary to implement the one-infinity model and choose to implement all complex-complex multiplication according to the textbook formula. Accordingly, special case behavior is unlikely to be consistent across implementations. + For complex floating-point operands, the results of special cases may be implementation dependent depending on how an implementation chooses to model complex numbers and complex infinity (e.g., complex plane versus Riemann sphere). For those implementations following C99 and its one-infinity model, when at least one component is infinite, even if the other component is ``NaN``, the complex value is infinite, and the usual arithmetic rules do not apply to complex-complex multiplication. In the interest of performance, other implementations may want to avoid the complex branching logic necessary to implement the one-infinity model and choose to implement all complex-complex multiplication according to the textbook formula. Accordingly, special case behavior is unlikely to be consistent across implementations. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -5648,26 +5652,26 @@ class negative[TArray: Array](Protocol): Computes the numerical negative of each element ``x_i`` (i.e., ``y_i = -x_i``) of the input array ``x``. .. note:: - For signed integer data types, the numerical negative of the minimum representable integer is implementation-dependent. + For signed integer data types, the numerical negative of the minimum representable integer is implementation-dependent. .. note:: - If ``x`` has a complex floating-point data type, both the real and imaginary components for each ``x_i`` must be negated (a result which follows from the rules of complex number multiplication). + If ``x`` has a complex floating-point data type, both the real and imaginary components for each ``x_i`` must be negated (a result which follows from the rules of complex number multiplication). Parameters ---------- x: array - input array. Should have a numeric data type. + input array. Should have a numeric data type. Returns ------- out: array - an array containing the evaluated result for each element in ``x``. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the evaluated result for each element in ``x``. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -5683,14 +5687,14 @@ class not_equal[TArray: Array](Protocol): Parameters ---------- x1: array - first input array. May have any data type. + first input array. May have any data type. x2: array - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type of ``bool``. + an array containing the element-wise results. The returned array must have a data type of ``bool``. Notes ----- @@ -5710,10 +5714,10 @@ class not_equal[TArray: Array](Protocol): - In the remaining cases, the result is the logical OR of the equality comparison between the real values ``a`` and ``c`` (real components) and between the real values ``b`` and ``d`` (imaginary components), as described above for real-valued floating-point operands (i.e., ``a != c OR b != d``). .. note:: - For discussion of complex number equality, see :ref:`complex-numbers`. + For discussion of complex number equality, see :ref:`complex-numbers`. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -5729,18 +5733,18 @@ class positive[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a numeric data type. + input array. Should have a numeric data type. Returns ------- out: array - an array containing the evaluated result for each element in ``x``. The returned array must have the same data type as ``x``. + an array containing the evaluated result for each element in ``x``. The returned array must have the same data type as ``x``. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -5754,28 +5758,28 @@ class pow[TArray: Array](Protocol): Calculates an implementation-dependent approximation of exponentiation by raising each element ``x1_i`` (the base) of the input array ``x1`` to the power of ``x2_i`` (the exponent), where ``x2_i`` is the corresponding element of the input array ``x2``. .. note:: - If both ``x1`` and ``x2`` have integer data types, the result of ``pow`` when ``x2_i`` is negative (i.e., less than zero) is unspecified and thus implementation-dependent. + If both ``x1`` and ``x2`` have integer data types, the result of ``pow`` when ``x2_i`` is negative (i.e., less than zero) is unspecified and thus implementation-dependent. - If ``x1`` has an integer data type and ``x2`` has a floating-point data type, behavior is implementation-dependent (type promotion between data type "kinds" (integer versus floating-point) is unspecified). + If ``x1`` has an integer data type and ``x2`` has a floating-point data type, behavior is implementation-dependent (type promotion between data type "kinds" (integer versus floating-point) is unspecified). .. note:: - By convention, the branch cut of the natural logarithm is the negative real axis :math:`(-\\infty, 0)`. + By convention, the branch cut of the natural logarithm is the negative real axis :math:`(-\\infty, 0)`. - The natural logarithm is a continuous function from above the branch cut, taking into account the sign of the imaginary component. As special cases involving complex floating-point operands should be handled according to ``exp(x2*log(x1))``, exponentiation has the same branch cut for ``x1`` as the natural logarithm (see :func:`~array_api.log`). + The natural logarithm is a continuous function from above the branch cut, taking into account the sign of the imaginary component. As special cases involving complex floating-point operands should be handled according to ``exp(x2*log(x1))``, exponentiation has the same branch cut for ``x1`` as the natural logarithm (see :func:`~array_api.log`). - *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). + *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). Parameters ---------- x1: array - first input array whose elements correspond to the exponentiation base. Should have a numeric data type. + first input array whose elements correspond to the exponentiation base. Should have a numeric data type. x2: array - second input array whose elements correspond to the exponentiation exponent. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a numeric data type. + second input array whose elements correspond to the exponentiation exponent. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a numeric data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- @@ -5811,10 +5815,10 @@ class pow[TArray: Array](Protocol): For complex floating-point operands, special cases should be handled as if the operation is implemented as ``exp(x2*log(x1))``. .. note:: - Conforming implementations are allowed to treat special cases involving complex floating-point operands more carefully than as described in this specification. + Conforming implementations are allowed to treat special cases involving complex floating-point operands more carefully than as described in this specification. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -5830,12 +5834,12 @@ class real[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a complex floating-point data type. + input array. Should have a complex floating-point data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a floating-point data type with the same floating-point precision as ``x`` (e.g., if ``x`` is ``complex64``, the returned array must have the floating-point data type ``float32``). + an array containing the element-wise results. The returned array must have a floating-point data type with the same floating-point precision as ``x`` (e.g., if ``x`` is ``complex64``, the returned array must have the floating-point data type ``float32``). Notes ----- @@ -5854,29 +5858,29 @@ class remainder[TArray: Array](Protocol): Returns the remainder of division for each element ``x1_i`` of the input array ``x1`` and the respective element ``x2_i`` of the input array ``x2``. .. note:: - This function is equivalent to the Python modulus operator ``x1_i % x2_i``. + This function is equivalent to the Python modulus operator ``x1_i % x2_i``. .. note:: - For input arrays which promote to an integer data type, the result of division by zero is unspecified and thus implementation-defined. + For input arrays which promote to an integer data type, the result of division by zero is unspecified and thus implementation-defined. Parameters ---------- x1: array - dividend input array. Should have a real-valued data type. + dividend input array. Should have a real-valued data type. x2: array - divisor input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued data type. + divisor input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued data type. Returns ------- out: array - an array containing the element-wise results. Each element-wise result must have the same sign as the respective element ``x2_i``. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise results. Each element-wise result must have the same sign as the respective element ``x2_i``. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- **Special cases** .. note:: - In general, similar to Python's ``%`` operator, this function is **not** recommended for floating-point operands as semantics do not follow IEEE 754. That this function is specified to accept floating-point operands is primarily for reasons of backward compatibility. + In general, similar to Python's ``%`` operator, this function is **not** recommended for floating-point operands as semantics do not follow IEEE 754. That this function is specified to accept floating-point operands is primarily for reasons of backward compatibility. For floating-point operands, @@ -5913,26 +5917,26 @@ class round[TArray: Array](Protocol): Rounds each element ``x_i`` of the input array ``x`` to the nearest integer-valued number. .. note:: - For complex floating-point operands, real and imaginary components must be independently rounded to the nearest integer-valued number. + For complex floating-point operands, real and imaginary components must be independently rounded to the nearest integer-valued number. - Rounded real and imaginary components must be equal to their equivalent rounded real-valued floating-point counterparts (i.e., for complex-valued ``x``, ``real(round(x))`` must equal ``round(real(x)))`` and ``imag(round(x))`` must equal ``round(imag(x))``). + Rounded real and imaginary components must be equal to their equivalent rounded real-valued floating-point counterparts (i.e., for complex-valued ``x``, ``real(round(x))`` must equal ``round(real(x)))`` and ``imag(round(x))`` must equal ``round(imag(x))``). Parameters ---------- x: array - input array. Should have a numeric data type. + input array. Should have a numeric data type. Returns ------- out: array - an array containing the rounded result for each element in ``x``. The returned array must have the same data type as ``x``. + an array containing the rounded result for each element in ``x``. The returned array must have the same data type as ``x``. Notes ----- **Special cases** .. note:: - For complex floating-point operands, the following special cases apply to real and imaginary components independently (e.g., if ``real(x_i)`` is ``NaN``, the rounded real component is ``NaN``). + For complex floating-point operands, the following special cases apply to real and imaginary components independently (e.g., if ``real(x_i)`` is ``NaN``, the rounded real component is ``NaN``). - If ``x_i`` is already integer-valued, the result is ``x_i``. @@ -5946,7 +5950,7 @@ class round[TArray: Array](Protocol): - If two integers are equally close to ``x_i``, the result is the even integer closest to ``x_i``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -5962,22 +5966,22 @@ class sign[TArray: Array](Protocol): The sign function (also known as the **signum function**) of a number :math:`x_i` is defined as .. math:: - \\operatorname{sign}(x_i) = \\begin{cases} - 0 & \\textrm{if } x_i = 0 \\\\ - \\frac{x_i}{|x_i|} & \\textrm{otherwise} - \\end{cases} + \\operatorname{sign}(x_i) = \\begin{cases} + 0 & \\textrm{if } x_i = 0 \\\\ + \\frac{x_i}{|x_i|} & \\textrm{otherwise} + \\end{cases} where :math:`|x_i|` is the absolute value of :math:`x_i`. Parameters ---------- x: array - input array. Should have a numeric data type. + input array. Should have a numeric data type. Returns ------- out: array - an array containing the evaluated result for each element in ``x``. The returned array must have the same data type as ``x``. + an array containing the evaluated result for each element in ``x``. The returned array must have the same data type as ``x``. Notes ----- @@ -5997,7 +6001,7 @@ class sign[TArray: Array](Protocol): - In the remaining cases, special cases must be handled according to the rules of complex number division (see :func:`~array_api.divide`). .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -6015,12 +6019,12 @@ class signbit[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a real-valued floating-point data type. + input array. Should have a real-valued floating-point data type. Returns ------- out: array - an array containing the evaluated result for each element in ``x``. The returned array must have a data type of ``bool``. + an array containing the evaluated result for each element in ``x``. The returned array must have a data type of ``bool``. Notes ----- @@ -6053,25 +6057,25 @@ class sin[TArray: Array](Protocol): Each element ``x_i`` is assumed to be expressed in radians. .. note:: - The sine is an entire function on the complex plane and has no branch cuts. + The sine is an entire function on the complex plane and has no branch cuts. .. note:: - For complex arguments, the mathematical definition of sine is + For complex arguments, the mathematical definition of sine is - .. math:: - \\begin{align} \\operatorname{sin}(x) &= \\frac{e^{jx} - e^{-jx}}{2j} \\\\ &= \\frac{\\operatorname{sinh}(jx)}{j} \\\\ &= \\frac{\\operatorname{sinh}(jx)}{j} \\cdot \\frac{j}{j} \\\\ &= -j \\cdot \\operatorname{sinh}(jx) \\end{align} + .. math:: + \\begin{align} \\operatorname{sin}(x) &= \\frac{e^{jx} - e^{-jx}}{2j} \\\\ &= \\frac{\\operatorname{sinh}(jx)}{j} \\\\ &= \\frac{\\operatorname{sinh}(jx)}{j} \\cdot \\frac{j}{j} \\\\ &= -j \\cdot \\operatorname{sinh}(jx) \\end{align} - where :math:`\\operatorname{sinh}` is the hyperbolic sine. + where :math:`\\operatorname{sinh}` is the hyperbolic sine. Parameters ---------- x: array - input array whose elements are each expressed in radians. Should have a floating-point data type. + input array whose elements are each expressed in radians. Should have a floating-point data type. Returns ------- out: array - an array containing the sine of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the sine of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -6087,7 +6091,7 @@ class sin[TArray: Array](Protocol): For complex floating-point operands, special cases must be handled as if the operation is implemented as ``-1j * sinh(x*1j)``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -6103,27 +6107,27 @@ class sinh[TArray: Array](Protocol): The mathematical definition of the hyperbolic sine is .. math:: - \\operatorname{sinh}(x) = \\frac{e^x - e^{-x}}{2} + \\operatorname{sinh}(x) = \\frac{e^x - e^{-x}}{2} .. note:: - The hyperbolic sine is an entire function in the complex plane and has no branch cuts. The function is periodic, with period :math:`2\\pi j`, with respect to the imaginary component. + The hyperbolic sine is an entire function in the complex plane and has no branch cuts. The function is periodic, with period :math:`2\\pi j`, with respect to the imaginary component. Parameters ---------- x: array - input array whose elements each represent a hyperbolic angle. Should have a floating-point data type. + input array whose elements each represent a hyperbolic angle. Should have a floating-point data type. Returns ------- out: array - an array containing the hyperbolic sine of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the hyperbolic sine of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- **Special cases** .. note:: - For all operands, ``sinh(x)`` must equal ``-sinh(-x)``. + For all operands, ``sinh(x)`` must equal ``-sinh(-x)``. For real-valued floating-point operands, @@ -6136,7 +6140,7 @@ class sinh[TArray: Array](Protocol): For complex floating-point operands, let ``a = real(x_i)``, ``b = imag(x_i)``, and .. note:: - For complex floating-point operands, ``sinh(conj(x))`` must equal ``conj(sinh(x))``. + For complex floating-point operands, ``sinh(conj(x))`` must equal ``conj(sinh(x))``. - If ``a`` is ``+0`` and ``b`` is ``+0``, the result is ``+0 + 0j``. - If ``a`` is ``+0`` and ``b`` is ``+infinity``, the result is ``0 + NaN j`` (sign of the real component is unspecified). @@ -6154,7 +6158,7 @@ class sinh[TArray: Array](Protocol): where ``cis(v)`` is ``cos(v) + sin(v)*1j``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -6170,17 +6174,17 @@ class square[TArray: Array](Protocol): The square of a number ``x_i`` is defined as .. math:: - x_i^2 = x_i \\cdot x_i + x_i^2 = x_i \\cdot x_i Parameters ---------- x: array - input array. Should have a numeric data type. + input array. Should have a numeric data type. Returns ------- out: array - an array containing the evaluated result for each element in ``x``. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the evaluated result for each element in ``x``. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- @@ -6189,7 +6193,7 @@ class square[TArray: Array](Protocol): For floating-point operands, special cases must be handled as if the operation is implemented as ``x * x`` (see :func:`~array_api.multiply`). .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -6203,29 +6207,29 @@ class sqrt[TArray: Array](Protocol): Calculates the principal square root for each element ``x_i`` of the input array ``x``. .. note:: - After rounding, each result must be indistinguishable from the infinitely precise result (as required by IEEE 754). + After rounding, each result must be indistinguishable from the infinitely precise result (as required by IEEE 754). .. note:: - For complex floating-point operands, ``sqrt(conj(x))`` must equal ``conj(sqrt(x))``. + For complex floating-point operands, ``sqrt(conj(x))`` must equal ``conj(sqrt(x))``. .. note:: - By convention, the branch cut of the square root is the negative real axis :math:`(-\\infty, 0)`. + By convention, the branch cut of the square root is the negative real axis :math:`(-\\infty, 0)`. - The square root is a continuous function from above the branch cut, taking into account the sign of the imaginary component. + The square root is a continuous function from above the branch cut, taking into account the sign of the imaginary component. - Accordingly, for complex arguments, the function returns the square root in the range of the right half-plane, including the imaginary axis (i.e., the plane defined by :math:`[0, +\\infty)` along the real axis and :math:`(-\\infty, +\\infty)` along the imaginary axis). + Accordingly, for complex arguments, the function returns the square root in the range of the right half-plane, including the imaginary axis (i.e., the plane defined by :math:`[0, +\\infty)` along the real axis and :math:`(-\\infty, +\\infty)` along the imaginary axis). - *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). + *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). Parameters ---------- x: array - input array. Should have a floating-point data type. + input array. Should have a floating-point data type. Returns ------- out: array - an array containing the square root of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the square root of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -6252,7 +6256,7 @@ class sqrt[TArray: Array](Protocol): - If ``a`` is ``NaN`` and ``b`` is ``NaN``, the result is ``NaN + NaN j``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -6270,20 +6274,20 @@ class subtract[TArray: Array](Protocol): Parameters ---------- x1: array - first input array. Should have a numeric data type. + first input array. Should have a numeric data type. x2: array - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a numeric data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a numeric data type. Returns ------- out: array - an array containing the element-wise differences. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise differences. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -6299,25 +6303,25 @@ class tan[TArray: Array](Protocol): Each element ``x_i`` is assumed to be expressed in radians. .. note:: - Tangent is an analytical function on the complex plane and has no branch cuts. The function is periodic, with period :math:`\\pi j`, with respect to the real component and has first order poles along the real line at coordinates :math:`(\\pi (\\frac{1}{2} + n), 0)`. However, IEEE 754 binary floating-point representation cannot represent the value :math:`\\pi / 2` exactly, and, thus, no argument value is possible for which a pole error occurs. + Tangent is an analytical function on the complex plane and has no branch cuts. The function is periodic, with period :math:`\\pi j`, with respect to the real component and has first order poles along the real line at coordinates :math:`(\\pi (\\frac{1}{2} + n), 0)`. However, IEEE 754 binary floating-point representation cannot represent the value :math:`\\pi / 2` exactly, and, thus, no argument value is possible for which a pole error occurs. .. note:: - For complex arguments, the mathematical definition of tangent is + For complex arguments, the mathematical definition of tangent is - .. math:: - \\begin{align} \\operatorname{tan}(x) &= \\frac{j(e^{-jx} - e^{jx})}{e^{-jx} + e^{jx}} \\\\ &= (-1) \\frac{j(e^{jx} - e^{-jx})}{e^{jx} + e^{-jx}} \\\\ &= -j \\cdot \\operatorname{tanh}(jx) \\end{align} + .. math:: + \\begin{align} \\operatorname{tan}(x) &= \\frac{j(e^{-jx} - e^{jx})}{e^{-jx} + e^{jx}} \\\\ &= (-1) \\frac{j(e^{jx} - e^{-jx})}{e^{jx} + e^{-jx}} \\\\ &= -j \\cdot \\operatorname{tanh}(jx) \\end{align} - where :math:`\\operatorname{tanh}` is the hyperbolic tangent. + where :math:`\\operatorname{tanh}` is the hyperbolic tangent. Parameters ---------- x: array - input array whose elements are expressed in radians. Should have a floating-point data type. + input array whose elements are expressed in radians. Should have a floating-point data type. Returns ------- out: array - an array containing the tangent of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the tangent of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -6333,7 +6337,7 @@ class tan[TArray: Array](Protocol): For complex floating-point operands, special cases must be handled as if the operation is implemented as ``-1j * tanh(x*1j)``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -6349,29 +6353,29 @@ class tanh[TArray: Array](Protocol): The mathematical definition of the hyperbolic tangent is .. math:: - \\begin{align} \\operatorname{tanh}(x) &= \\frac{\\operatorname{sinh}(x)}{\\operatorname{cosh}(x)} \\\\ &= \\frac{e^x - e^{-x}}{e^x + e^{-x}} \\end{align} + \\begin{align} \\operatorname{tanh}(x) &= \\frac{\\operatorname{sinh}(x)}{\\operatorname{cosh}(x)} \\\\ &= \\frac{e^x - e^{-x}}{e^x + e^{-x}} \\end{align} where :math:`\\operatorname{sinh}(x)` is the hyperbolic sine and :math:`\\operatorname{cosh}(x)` is the hyperbolic cosine. .. note:: - The hyperbolic tangent is an analytical function on the complex plane and has no branch cuts. The function is periodic, with period :math:`\\pi j`, with respect to the imaginary component and has first order poles along the imaginary line at coordinates :math:`(0, \\pi (\\frac{1}{2} + n))`. However, IEEE 754 binary floating-point representation cannot represent :math:`\\pi / 2` exactly, and, thus, no argument value is possible such that a pole error occurs. + The hyperbolic tangent is an analytical function on the complex plane and has no branch cuts. The function is periodic, with period :math:`\\pi j`, with respect to the imaginary component and has first order poles along the imaginary line at coordinates :math:`(0, \\pi (\\frac{1}{2} + n))`. However, IEEE 754 binary floating-point representation cannot represent :math:`\\pi / 2` exactly, and, thus, no argument value is possible such that a pole error occurs. Parameters ---------- x: array - input array whose elements each represent a hyperbolic angle. Should have a floating-point data type. + input array whose elements each represent a hyperbolic angle. Should have a floating-point data type. Returns ------- out: array - an array containing the hyperbolic tangent of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the hyperbolic tangent of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- **Special cases** .. note:: - For all operands, ``tanh(-x)`` must equal ``-tanh(x)``. + For all operands, ``tanh(-x)`` must equal ``-tanh(x)``. For real-valued floating-point operands, @@ -6384,7 +6388,7 @@ class tanh[TArray: Array](Protocol): For complex floating-point operands, let ``a = real(x_i)``, ``b = imag(x_i)``, and .. note:: - For complex floating-point operands, ``tanh(conj(x))`` must equal ``conj(tanh(x))``. + For complex floating-point operands, ``tanh(conj(x))`` must equal ``conj(tanh(x))``. - If ``a`` is ``+0`` and ``b`` is ``+0``, the result is ``+0 + 0j``. - If ``a`` is a nonzero finite number and ``b`` is ``+infinity``, the result is ``NaN + NaN j``. @@ -6399,12 +6403,12 @@ class tanh[TArray: Array](Protocol): - If ``a`` is ``NaN`` and ``b`` is ``NaN``, the result is ``NaN + NaN j``. .. warning:: - For historical reasons stemming from the C standard, array libraries may not return the expected result when ``a`` is ``+0`` and ``b`` is either ``+infinity`` or ``NaN``. The result should be ``+0 + NaN j`` in both cases; however, for libraries compiled against older C versions, the result may be ``NaN + NaN j``. + For historical reasons stemming from the C standard, array libraries may not return the expected result when ``a`` is ``+0`` and ``b`` is either ``+infinity`` or ``NaN``. The result should be ``+0 + NaN j`` in both cases; however, for libraries compiled against older C versions, the result may be ``NaN + NaN j``. - Array libraries are not required to patch these older C versions, and, thus, users are advised that results may vary across array library implementations for these special cases. + Array libraries are not required to patch these older C versions, and, thus, users are advised that results may vary across array library implementations for these special cases. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -6420,12 +6424,12 @@ class trunc[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a real-valued data type. + input array. Should have a real-valued data type. Returns ------- out: array - an array containing the rounded result for each element in ``x``. The returned array must have the same data type as ``x``. + an array containing the rounded result for each element in ``x``. The returned array must have the same data type as ``x``. Notes ----- @@ -6455,21 +6459,21 @@ class argmax[TArray: Array](Protocol): When the maximum value occurs multiple times, only the indices corresponding to the first occurrence are returned. .. note:: - For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). + For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). Parameters ---------- x: array - input array. Should have a real-valued data type. + input array. Should have a real-valued data type. axis: Optional[int] - axis along which to search. If ``None``, the function must return the index of the maximum value of the flattened array. Default: ``None``. + axis along which to search. If ``None``, the function must return the index of the maximum value of the flattened array. Default: ``None``. keepdims: bool - if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. + if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. Returns ------- out: array - if ``axis`` is ``None``, a zero-dimensional array containing the index of the first occurrence of the maximum value; otherwise, a non-zero-dimensional array containing the indices of the maximum values. The returned array must have be the default array index data type. + if ``axis`` is ``None``, a zero-dimensional array containing the index of the first occurrence of the maximum value; otherwise, a non-zero-dimensional array containing the indices of the maximum values. The returned array must have be the default array index data type. """ @@ -6485,21 +6489,21 @@ class argmin[TArray: Array](Protocol): When the minimum value occurs multiple times, only the indices corresponding to the first occurrence are returned. .. note:: - For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). + For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). Parameters ---------- x: array - input array. Should have a real-valued data type. + input array. Should have a real-valued data type. axis: Optional[int] - axis along which to search. If ``None``, the function must return the index of the minimum value of the flattened array. Default: ``None``. + axis along which to search. If ``None``, the function must return the index of the minimum value of the flattened array. Default: ``None``. keepdims: bool - if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. + if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. Returns ------- out: array - if ``axis`` is ``None``, a zero-dimensional array containing the index of the first occurrence of the minimum value; otherwise, a non-zero-dimensional array containing the indices of the minimum values. The returned array must have the default array index data type. + if ``axis`` is ``None``, a zero-dimensional array containing the index of the first occurrence of the minimum value; otherwise, a non-zero-dimensional array containing the indices of the minimum values. The returned array must have the default array index data type. """ @@ -6513,31 +6517,31 @@ class nonzero[TArray: Array](Protocol): Returns the indices of the array elements which are non-zero. .. note:: - If ``x`` has a complex floating-point data type, non-zero elements are those elements having at least one component (real or imaginary) which is non-zero. + If ``x`` has a complex floating-point data type, non-zero elements are those elements having at least one component (real or imaginary) which is non-zero. .. note:: - If ``x`` has a boolean data type, non-zero elements are those elements which are equal to ``True``. + If ``x`` has a boolean data type, non-zero elements are those elements which are equal to ``True``. .. admonition:: Data-dependent output shape - :class: admonition important + :class: admonition important - The shape of the output array for this function depends on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) may find this function difficult to implement without knowing array values. Accordingly, such libraries may choose to omit this function. See :ref:`data-dependent-output-shapes` section for more details. + The shape of the output array for this function depends on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) may find this function difficult to implement without knowing array values. Accordingly, such libraries may choose to omit this function. See :ref:`data-dependent-output-shapes` section for more details. Parameters ---------- x: array - input array. Must have a positive rank. If ``x`` is zero-dimensional, the function must raise an exception. + input array. Must have a positive rank. If ``x`` is zero-dimensional, the function must raise an exception. Returns ------- out: Tuple[array, ...] - a tuple of ``k`` arrays, one for each dimension of ``x`` and each of size ``n`` (where ``n`` is the total number of non-zero elements), containing the indices of the non-zero elements in that dimension. The indices must be returned in row-major, C-style order. The returned array must have the default array index data type. + a tuple of ``k`` arrays, one for each dimension of ``x`` and each of size ``n`` (where ``n`` is the total number of non-zero elements), containing the indices of the non-zero elements in that dimension. The indices must be returned in row-major, C-style order. The returned array must have the default array index data type. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -6553,29 +6557,29 @@ class searchsorted[TArray: Array](Protocol): Parameters ---------- x1: array - input array. Must be a one-dimensional array. Should have a real-valued data type. If ``sorter`` is ``None``, must be sorted in ascending order; otherwise, ``sorter`` must be an array of indices that sort ``x1`` in ascending order. + input array. Must be a one-dimensional array. Should have a real-valued data type. If ``sorter`` is ``None``, must be sorted in ascending order; otherwise, ``sorter`` must be an array of indices that sort ``x1`` in ascending order. x2: array - array containing search values. Should have a real-valued data type. + array containing search values. Should have a real-valued data type. side: Literal['left', 'right'] - argument controlling which index is returned if a value lands exactly on an edge. + argument controlling which index is returned if a value lands exactly on an edge. - Let ``v`` be an element of ``x2`` given by ``v = x2[j]``, where ``j`` refers to a valid index (see :ref:`indexing`). + Let ``v`` be an element of ``x2`` given by ``v = x2[j]``, where ``j`` refers to a valid index (see :ref:`indexing`). - - If ``v`` is less than all elements in ``x1``, then ``out[j]`` must be ``0``. - - If ``v`` is greater than all elements in ``x1``, then ``out[j]`` must be ``M``, where ``M`` is the number of elements in ``x1``. - - Otherwise, each returned index ``i = out[j]`` must satisfy an index condition: + - If ``v`` is less than all elements in ``x1``, then ``out[j]`` must be ``0``. + - If ``v`` is greater than all elements in ``x1``, then ``out[j]`` must be ``M``, where ``M`` is the number of elements in ``x1``. + - Otherwise, each returned index ``i = out[j]`` must satisfy an index condition: - - If ``side == 'left'``, then ``x1[i-1] < v <= x1[i]``. - - If ``side == 'right'``, then ``x1[i-1] <= v < x1[i]``. + - If ``side == 'left'``, then ``x1[i-1] < v <= x1[i]``. + - If ``side == 'right'``, then ``x1[i-1] <= v < x1[i]``. - Default: ``'left'``. + Default: ``'left'``. sorter: Optional[array] - array of indices that sort ``x1`` in ascending order. The array must have the same shape as ``x1`` and have an integer data type. Default: ``None``. + array of indices that sort ``x1`` in ascending order. The array must have the same shape as ``x1`` and have an integer data type. Default: ``None``. Returns ------- out: array - an array of indices with the same shape as ``x2``. The returned array must have the default array index data type. + an array of indices with the same shape as ``x2``. The returned array must have the default array index data type. Notes ----- @@ -6599,16 +6603,16 @@ class where[TArray: Array](Protocol): Parameters ---------- condition: array - when ``True``, yield ``x1_i``; otherwise, yield ``x2_i``. Should have a boolean data type. Must be compatible with ``x1`` and ``x2`` (see :ref:`broadcasting`). + when ``True``, yield ``x1_i``; otherwise, yield ``x2_i``. Should have a boolean data type. Must be compatible with ``x1`` and ``x2`` (see :ref:`broadcasting`). x1: array - first input array. Must be compatible with ``condition`` and ``x2`` (see :ref:`broadcasting`). + first input array. Must be compatible with ``condition`` and ``x2`` (see :ref:`broadcasting`). x2: array - second input array. Must be compatible with ``condition`` and ``x1`` (see :ref:`broadcasting`). + second input array. Must be compatible with ``condition`` and ``x1`` (see :ref:`broadcasting`). Returns ------- out: array - an array with elements from ``x1`` where ``condition`` is ``True``, and elements from ``x2`` elsewhere. The returned array must have a data type determined by :ref:`type-promotion` rules with the arrays ``x1`` and ``x2``. + an array with elements from ``x1`` where ``condition`` is ``True``, and elements from ``x2`` elsewhere. The returned array must have a data type determined by :ref:`type-promotion` rules with the arrays ``x1`` and ``x2``. """ @@ -6622,33 +6626,33 @@ class all[TArray: Array](Protocol): Tests whether all input array elements evaluate to ``True`` along a specified axis. .. note:: - Positive infinity, negative infinity, and NaN must evaluate to ``True``. + Positive infinity, negative infinity, and NaN must evaluate to ``True``. .. note:: - If ``x`` has a complex floating-point data type, elements having a non-zero component (real or imaginary) must evaluate to ``True``. + If ``x`` has a complex floating-point data type, elements having a non-zero component (real or imaginary) must evaluate to ``True``. .. note:: - If ``x`` is an empty array or the size of the axis (dimension) along which to evaluate elements is zero, the test result must be ``True``. + If ``x`` is an empty array or the size of the axis (dimension) along which to evaluate elements is zero, the test result must be ``True``. Parameters ---------- x: array - input array. + input array. axis: Optional[Union[int, Tuple[int, ...]]] - axis or axes along which to perform a logical AND reduction. By default, a logical AND reduction must be performed over the entire array. If a tuple of integers, logical AND reductions must be performed over multiple axes. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to perform a reduction by counting backward from the last dimension (where ``-1`` refers to the last dimension). If provided an invalid ``axis``, the function must raise an exception. Default: ``None``. + axis or axes along which to perform a logical AND reduction. By default, a logical AND reduction must be performed over the entire array. If a tuple of integers, logical AND reductions must be performed over multiple axes. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to perform a reduction by counting backward from the last dimension (where ``-1`` refers to the last dimension). If provided an invalid ``axis``, the function must raise an exception. Default: ``None``. keepdims: bool - If ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. + If ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. Returns ------- out: array - if a logical AND reduction was performed over the entire array, the returned array must be a zero-dimensional array containing the test result; otherwise, the returned array must be a non-zero-dimensional array containing the test results. The returned array must have a data type of ``bool``. + if a logical AND reduction was performed over the entire array, the returned array must be a zero-dimensional array containing the test result; otherwise, the returned array must be a non-zero-dimensional array containing the test results. The returned array must have a data type of ``bool``. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -6662,33 +6666,33 @@ class any[TArray: Array](Protocol): Tests whether any input array element evaluates to ``True`` along a specified axis. .. note:: - Positive infinity, negative infinity, and NaN must evaluate to ``True``. + Positive infinity, negative infinity, and NaN must evaluate to ``True``. .. note:: - If ``x`` has a complex floating-point data type, elements having a non-zero component (real or imaginary) must evaluate to ``True``. + If ``x`` has a complex floating-point data type, elements having a non-zero component (real or imaginary) must evaluate to ``True``. .. note:: - If ``x`` is an empty array or the size of the axis (dimension) along which to evaluate elements is zero, the test result must be ``False``. + If ``x`` is an empty array or the size of the axis (dimension) along which to evaluate elements is zero, the test result must be ``False``. Parameters ---------- x: array - input array. + input array. axis: Optional[Union[int, Tuple[int, ...]]] - axis or axes along which to perform a logical OR reduction. By default, a logical OR reduction must be performed over the entire array. If a tuple of integers, logical OR reductions must be performed over multiple axes. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to perform a reduction by counting backward from the last dimension (where ``-1`` refers to the last dimension). If provided an invalid ``axis``, the function must raise an exception. Default: ``None``. + axis or axes along which to perform a logical OR reduction. By default, a logical OR reduction must be performed over the entire array. If a tuple of integers, logical OR reductions must be performed over multiple axes. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to perform a reduction by counting backward from the last dimension (where ``-1`` refers to the last dimension). If provided an invalid ``axis``, the function must raise an exception. Default: ``None``. keepdims: bool - If ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. + If ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. Returns ------- out: array - if a logical OR reduction was performed over the entire array, the returned array must be a zero-dimensional array containing the test result; otherwise, the returned array must be a non-zero-dimensional array containing the test results. The returned array must have a data type of ``bool``. + if a logical OR reduction was performed over the entire array, the returned array must be a zero-dimensional array containing the test result; otherwise, the returned array must be a non-zero-dimensional array containing the test results. The returned array must have a data type of ``bool``. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -6697,7 +6701,7 @@ def __call__(self, x: TArray, /, *, axis: int | tuple[int, ...] | None = None, k @runtime_checkable -class __array_namespace_info__[TCapabilities, TDatatypes, TDefaultdatatypes, TArray: Array, TDevice, TDtype](Protocol): +class __array_namespace_info__[TArray: Array, TCapabilities, TDatatypes, TDefaultdatatypes, TDevice, TDtype](Protocol): """ Returns a namespace with Array API namespace inspection utilities. @@ -6706,7 +6710,7 @@ class __array_namespace_info__[TCapabilities, TDatatypes, TDefaultdatatypes, TAr Returns ------- out: Info - An object containing Array API namespace inspection utilities. + An object containing Array API namespace inspection utilities. Notes ----- @@ -6714,19 +6718,19 @@ class __array_namespace_info__[TCapabilities, TDatatypes, TDefaultdatatypes, TAr :: - info = xp.__array_namespace_info__() - info.capabilities() - info.devices() - info.dtypes() - info.default_dtypes() - # ... + info = xp.__array_namespace_info__() + info.capabilities() + info.devices() + info.dtypes() + info.default_dtypes() + # ... .. versionadded: 2023.12 """ @abstractmethod - def __call__(self, /) -> Info[TCapabilities, TDatatypes, TDefaultdatatypes, TArray, TDevice, TDtype]: ... + def __call__(self, /) -> Info[TArray, TCapabilities, TDatatypes, TDefaultdatatypes, TDevice, TDtype]: ... @runtime_checkable @@ -6735,27 +6739,27 @@ class take[TArray: Array](Protocol): Returns elements of an array along an axis. .. note:: - Conceptually, ``take(x, indices, axis=3)`` is equivalent to ``x[:,:,:,indices,...]``; however, explicit indexing via arrays of indices is not currently supported in this specification due to concerns regarding ``__setitem__`` and array mutation semantics. + Conceptually, ``take(x, indices, axis=3)`` is equivalent to ``x[:,:,:,indices,...]``; however, explicit indexing via arrays of indices is not currently supported in this specification due to concerns regarding ``__setitem__`` and array mutation semantics. Parameters ---------- x: array - input array. + input array. indices: array - array indices. The array must be one-dimensional and have an integer data type. + array indices. The array must be one-dimensional and have an integer data type. - .. note:: - This specification does not require bounds checking. The behavior for out-of-bounds indices is left unspecified. + .. note:: + This specification does not require bounds checking. The behavior for out-of-bounds indices is left unspecified. axis: Optional[int] - axis over which to select values. If ``axis`` is negative, the function must determine the axis along which to select values by counting from the last dimension. + axis over which to select values. If ``axis`` is negative, the function must determine the axis along which to select values by counting from the last dimension. - If ``x`` is a one-dimensional array, providing an ``axis`` is optional; however, if ``x`` has more than one dimension, providing an ``axis`` is required. + If ``x`` is a one-dimensional array, providing an ``axis`` is optional; however, if ``x`` has more than one dimension, providing an ``axis`` is required. Returns ------- out: array - an array having the same data type as ``x``. The output array must have the same rank (i.e., number of dimensions) as ``x`` and must have the same shape as ``x``, except for the axis specified by ``axis`` whose size must equal the number of elements in ``indices``. + an array having the same data type as ``x``. The output array must have the same rank (i.e., number of dimensions) as ``x`` and must have the same shape as ``x``, except for the axis specified by ``axis`` whose size must equal the number of elements in ``indices``. Notes ----- @@ -6763,7 +6767,7 @@ class take[TArray: Array](Protocol): .. versionadded:: 2022.12 .. versionchanged:: 2023.12 - Out-of-bounds behavior is explicitly left unspecified. + Out-of-bounds behavior is explicitly left unspecified. """ @@ -6777,35 +6781,35 @@ class fft[TArray: Array](Protocol): Computes the one-dimensional discrete Fourier transform. .. note:: - Applying the one-dimensional inverse discrete Fourier transform to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e., ``ifft(fft(x)) == x``), provided that the transform and inverse transform are performed with the same arguments (number of elements, axis, and normalization mode). + Applying the one-dimensional inverse discrete Fourier transform to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e., ``ifft(fft(x)) == x``), provided that the transform and inverse transform are performed with the same arguments (number of elements, axis, and normalization mode). Parameters ---------- x: array - input array. Should have a complex floating-point data type. + input array. Should have a complex floating-point data type. n: Optional[int] - number of elements over which to compute the transform along the axis (dimension) specified by ``axis``. Let ``M`` be the size of the input array along the axis specified by ``axis``. When ``n`` is ``None``, the function must set ``n`` equal to ``M``. + number of elements over which to compute the transform along the axis (dimension) specified by ``axis``. Let ``M`` be the size of the input array along the axis specified by ``axis``. When ``n`` is ``None``, the function must set ``n`` equal to ``M``. - - If ``n`` is greater than ``M``, the axis specified by ``axis`` must be zero-padded to size ``n``. - - If ``n`` is less than ``M``, the axis specified by ``axis`` must be trimmed to size ``n``. - - If ``n`` equals ``M``, all elements along the axis specified by ``axis`` must be used when computing the transform. + - If ``n`` is greater than ``M``, the axis specified by ``axis`` must be zero-padded to size ``n``. + - If ``n`` is less than ``M``, the axis specified by ``axis`` must be trimmed to size ``n``. + - If ``n`` equals ``M``, all elements along the axis specified by ``axis`` must be used when computing the transform. - Default: ``None``. + Default: ``None``. axis: int - axis (dimension) of the input array over which to compute the transform. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). Default: ``-1``. + axis (dimension) of the input array over which to compute the transform. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). Default: ``-1``. norm: Literal['backward', 'ortho', 'forward'] - normalization mode. Should be one of the following modes: + normalization mode. Should be one of the following modes: - - ``'backward'``: no normalization. - - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). - - ``'forward'``: normalize by ``1/n``. + - ``'backward'``: no normalization. + - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). + - ``'forward'``: normalize by ``1/n``. - Default: ``'backward'``. + Default: ``'backward'``. Returns ------- out: array - an array transformed along the axis (dimension) specified by ``axis``. The returned array must have the same data type as ``x`` and must have the same shape as ``x``, except for the axis specified by ``axis`` which must have size ``n``. + an array transformed along the axis (dimension) specified by ``axis``. The returned array must have the same data type as ``x`` and must have the same shape as ``x``, except for the axis specified by ``axis`` which must have size ``n``. Notes ----- @@ -6813,7 +6817,7 @@ class fft[TArray: Array](Protocol): .. versionadded:: 2022.12 .. versionchanged:: 2023.12 - Required the input array have a complex floating-point data type and required that the output array have the same data type as the input array. + Required the input array have a complex floating-point data type and required that the output array have the same data type as the input array. """ @@ -6827,35 +6831,35 @@ class ifft[TArray: Array](Protocol): Computes the one-dimensional inverse discrete Fourier transform. .. note:: - Applying the one-dimensional inverse discrete Fourier transform to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e., ``ifft(fft(x)) == x``), provided that the transform and inverse transform are performed with the same arguments (number of elements, axis, and normalization mode). + Applying the one-dimensional inverse discrete Fourier transform to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e., ``ifft(fft(x)) == x``), provided that the transform and inverse transform are performed with the same arguments (number of elements, axis, and normalization mode). Parameters ---------- x: array - input array. Should have a complex floating-point data type. + input array. Should have a complex floating-point data type. n: Optional[int] - number of elements over which to compute the transform along the axis (dimension) specified by ``axis``. Let ``M`` be the size of the input array along the axis specified by ``axis``. When ``n`` is ``None``, the function must set ``n`` equal to ``M``. + number of elements over which to compute the transform along the axis (dimension) specified by ``axis``. Let ``M`` be the size of the input array along the axis specified by ``axis``. When ``n`` is ``None``, the function must set ``n`` equal to ``M``. - - If ``n`` is greater than ``M``, the axis specified by ``axis`` must be zero-padded to size ``n``. - - If ``n`` is less than ``M``, the axis specified by ``axis`` must be trimmed to size ``n``. - - If ``n`` equals ``M``, all elements along the axis specified by ``axis`` must be used when computing the transform. + - If ``n`` is greater than ``M``, the axis specified by ``axis`` must be zero-padded to size ``n``. + - If ``n`` is less than ``M``, the axis specified by ``axis`` must be trimmed to size ``n``. + - If ``n`` equals ``M``, all elements along the axis specified by ``axis`` must be used when computing the transform. - Default: ``None``. + Default: ``None``. axis: int - axis (dimension) of the input array over which to compute the transform. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). Default: ``-1``. + axis (dimension) of the input array over which to compute the transform. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). Default: ``-1``. norm: Literal['backward', 'ortho', 'forward'] - normalization mode. Should be one of the following modes: + normalization mode. Should be one of the following modes: - - ``'backward'``: normalize by ``1/n``. - - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). - - ``'forward'``: no normalization. + - ``'backward'``: normalize by ``1/n``. + - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). + - ``'forward'``: no normalization. - Default: ``'backward'``. + Default: ``'backward'``. Returns ------- out: array - an array transformed along the axis (dimension) specified by ``axis``. The returned array must have the same data type as ``x`` and must have the same shape as ``x``, except for the axis specified by ``axis`` which must have size ``n``. + an array transformed along the axis (dimension) specified by ``axis``. The returned array must have the same data type as ``x`` and must have the same shape as ``x``, except for the axis specified by ``axis`` which must have size ``n``. Notes ----- @@ -6863,7 +6867,7 @@ class ifft[TArray: Array](Protocol): .. versionadded:: 2022.12 .. versionchanged:: 2023.12 - Required the input array have a complex floating-point data type and required that the output array have the same data type as the input array. + Required the input array have a complex floating-point data type and required that the output array have the same data type as the input array. """ @@ -6877,41 +6881,41 @@ class fftn[TArray: Array](Protocol): Computes the n-dimensional discrete Fourier transform. .. note:: - Applying the n-dimensional inverse discrete Fourier transform to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e., ``ifftn(fftn(x)) == x``), provided that the transform and inverse transform are performed with the same arguments (sizes, axes, and normalization mode). + Applying the n-dimensional inverse discrete Fourier transform to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e., ``ifftn(fftn(x)) == x``), provided that the transform and inverse transform are performed with the same arguments (sizes, axes, and normalization mode). Parameters ---------- x: array - input array. Should have a complex floating-point data type. + input array. Should have a complex floating-point data type. s: Optional[Sequence[int]] - number of elements over which to compute the transform along the axes (dimensions) specified by ``axes``. Let ``i`` be the index of the ``n``-th axis specified by ``axes`` (i.e., ``i = axes[n]``) and ``M[i]`` be the size of the input array along axis ``i``. When ``s`` is ``None``, the function must set ``s`` equal to a sequence of integers such that ``s[i]`` equals ``M[i]`` for all ``i``. + number of elements over which to compute the transform along the axes (dimensions) specified by ``axes``. Let ``i`` be the index of the ``n``-th axis specified by ``axes`` (i.e., ``i = axes[n]``) and ``M[i]`` be the size of the input array along axis ``i``. When ``s`` is ``None``, the function must set ``s`` equal to a sequence of integers such that ``s[i]`` equals ``M[i]`` for all ``i``. - - If ``s[i]`` is greater than ``M[i]``, axis ``i`` must be zero-padded to size ``s[i]``. - - If ``s[i]`` is less than ``M[i]``, axis ``i`` must be trimmed to size ``s[i]``. - - If ``s[i]`` equals ``M[i]`` or ``-1``, all elements along axis ``i`` must be used when computing the transform. + - If ``s[i]`` is greater than ``M[i]``, axis ``i`` must be zero-padded to size ``s[i]``. + - If ``s[i]`` is less than ``M[i]``, axis ``i`` must be trimmed to size ``s[i]``. + - If ``s[i]`` equals ``M[i]`` or ``-1``, all elements along axis ``i`` must be used when computing the transform. - If ``s`` is not ``None``, ``axes`` must not be ``None``. Default: ``None``. + If ``s`` is not ``None``, ``axes`` must not be ``None``. Default: ``None``. axes: Optional[Sequence[int]] - axes (dimensions) over which to compute the transform. A valid axis in ``axes`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an axis is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). + axes (dimensions) over which to compute the transform. A valid axis in ``axes`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an axis is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). - If ``s`` is provided, the corresponding ``axes`` to be transformed must also be provided. If ``axes`` is ``None``, the function must compute the transform over all axes. Default: ``None``. + If ``s`` is provided, the corresponding ``axes`` to be transformed must also be provided. If ``axes`` is ``None``, the function must compute the transform over all axes. Default: ``None``. - If ``axes`` contains two or more entries which resolve to the same axis (i.e., resolved axes are not unique), the behavior is unspecified and thus implementation-defined. + If ``axes`` contains two or more entries which resolve to the same axis (i.e., resolved axes are not unique), the behavior is unspecified and thus implementation-defined. norm: Literal['backward', 'ortho', 'forward'] - normalization mode. Should be one of the following modes: + normalization mode. Should be one of the following modes: - - ``'backward'``: no normalization. - - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). - - ``'forward'``: normalize by ``1/n``. + - ``'backward'``: no normalization. + - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). + - ``'forward'``: normalize by ``1/n``. - where ``n = prod(s)`` is the logical FFT size. + where ``n = prod(s)`` is the logical FFT size. - Default: ``'backward'``. + Default: ``'backward'``. Returns ------- out: array - an array transformed along the axes (dimensions) specified by ``axes``. The returned array must have the same data type as ``x`` and must have the same shape as ``x``, except for the axes specified by ``axes`` which must have size ``s[i]``. + an array transformed along the axes (dimensions) specified by ``axes``. The returned array must have the same data type as ``x`` and must have the same shape as ``x``, except for the axes specified by ``axes`` which must have size ``s[i]``. Notes ----- @@ -6919,7 +6923,7 @@ class fftn[TArray: Array](Protocol): .. versionadded:: 2022.12 .. versionchanged:: 2023.12 - Required the input array have a complex floating-point data type and required that the output array have the same data type as the input array. + Required the input array have a complex floating-point data type and required that the output array have the same data type as the input array. """ @@ -6933,41 +6937,41 @@ class ifftn[TArray: Array](Protocol): Computes the n-dimensional inverse discrete Fourier transform. .. note:: - Applying the n-dimensional inverse discrete Fourier transform to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e., ``ifftn(fftn(x)) == x``), provided that the transform and inverse transform are performed with the same arguments (sizes, axes, and normalization mode). + Applying the n-dimensional inverse discrete Fourier transform to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e., ``ifftn(fftn(x)) == x``), provided that the transform and inverse transform are performed with the same arguments (sizes, axes, and normalization mode). Parameters ---------- x: array - input array. Should have a complex floating-point data type. + input array. Should have a complex floating-point data type. s: Optional[Sequence[int]] - number of elements over which to compute the transform along the axes (dimensions) specified by ``axes``. Let ``i`` be the index of the ``n``-th axis specified by ``axes`` (i.e., ``i = axes[n]``) and ``M[i]`` be the size of the input array along axis ``i``. When ``s`` is ``None``, the function must set ``s`` equal to a sequence of integers such that ``s[i]`` equals ``M[i]`` for all ``i``. + number of elements over which to compute the transform along the axes (dimensions) specified by ``axes``. Let ``i`` be the index of the ``n``-th axis specified by ``axes`` (i.e., ``i = axes[n]``) and ``M[i]`` be the size of the input array along axis ``i``. When ``s`` is ``None``, the function must set ``s`` equal to a sequence of integers such that ``s[i]`` equals ``M[i]`` for all ``i``. - - If ``s[i]`` is greater than ``M[i]``, axis ``i`` must be zero-padded to size ``s[i]``. - - If ``s[i]`` is less than ``M[i]``, axis ``i`` must be trimmed to size ``s[i]``. - - If ``s[i]`` equals ``M[i]`` or ``-1``, all elements along axis ``i`` must be used when computing the transform. + - If ``s[i]`` is greater than ``M[i]``, axis ``i`` must be zero-padded to size ``s[i]``. + - If ``s[i]`` is less than ``M[i]``, axis ``i`` must be trimmed to size ``s[i]``. + - If ``s[i]`` equals ``M[i]`` or ``-1``, all elements along axis ``i`` must be used when computing the transform. - If ``s`` is not ``None``, ``axes`` must not be ``None``. Default: ``None``. + If ``s`` is not ``None``, ``axes`` must not be ``None``. Default: ``None``. axes: Optional[Sequence[int]] - axes (dimensions) over which to compute the transform. A valid axis in ``axes`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an axis is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). + axes (dimensions) over which to compute the transform. A valid axis in ``axes`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an axis is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). - If ``s`` is provided, the corresponding ``axes`` to be transformed must also be provided. If ``axes`` is ``None``, the function must compute the transform over all axes. Default: ``None``. + If ``s`` is provided, the corresponding ``axes`` to be transformed must also be provided. If ``axes`` is ``None``, the function must compute the transform over all axes. Default: ``None``. - If ``axes`` contains two or more entries which resolve to the same axis (i.e., resolved axes are not unique), the behavior is unspecified and thus implementation-defined. + If ``axes`` contains two or more entries which resolve to the same axis (i.e., resolved axes are not unique), the behavior is unspecified and thus implementation-defined. norm: Literal['backward', 'ortho', 'forward'] - specify the normalization mode. Should be one of the following modes: + specify the normalization mode. Should be one of the following modes: - - ``'backward'``: normalize by ``1/n``. - - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). - - ``'forward'``: no normalization. + - ``'backward'``: normalize by ``1/n``. + - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). + - ``'forward'``: no normalization. - where ``n = prod(s)`` is the logical FFT size. + where ``n = prod(s)`` is the logical FFT size. - Default: ``'backward'``. + Default: ``'backward'``. Returns ------- out: array - an array transformed along the axes (dimensions) specified by ``axes``. The returned array must have the same data type as ``x`` and must have the same shape as ``x``, except for the axes specified by ``axes`` which must have size ``s[i]``. + an array transformed along the axes (dimensions) specified by ``axes``. The returned array must have the same data type as ``x`` and must have the same shape as ``x``, except for the axes specified by ``axes`` which must have size ``s[i]``. Notes ----- @@ -6975,7 +6979,7 @@ class ifftn[TArray: Array](Protocol): .. versionadded:: 2022.12 .. versionchanged:: 2023.12 - Required the input array have a complex floating-point data type and required that the output array have the same data type as the input array. + Required the input array have a complex floating-point data type and required that the output array have the same data type as the input array. """ @@ -6989,35 +6993,35 @@ class rfft[TArray: Array](Protocol): Computes the one-dimensional discrete Fourier transform for real-valued input. .. note:: - Applying the one-dimensional inverse discrete Fourier transform for real-valued input to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e., ``irfft(rfft(x)) == x``), provided that the transform and inverse transform are performed with the same arguments (axis and normalization mode) and consistent values for the number of elements over which to compute the transforms. + Applying the one-dimensional inverse discrete Fourier transform for real-valued input to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e., ``irfft(rfft(x)) == x``), provided that the transform and inverse transform are performed with the same arguments (axis and normalization mode) and consistent values for the number of elements over which to compute the transforms. Parameters ---------- x: array - input array. Must have a real-valued floating-point data type. + input array. Must have a real-valued floating-point data type. n: Optional[int] - number of elements over which to compute the transform along the axis (dimension) specified by ``axis``. Let ``M`` be the size of the input array along the axis specified by ``axis``. When ``n`` is ``None``, the function must set ``n`` equal to ``M``. + number of elements over which to compute the transform along the axis (dimension) specified by ``axis``. Let ``M`` be the size of the input array along the axis specified by ``axis``. When ``n`` is ``None``, the function must set ``n`` equal to ``M``. - - If ``n`` is greater than ``M``, the axis specified by ``axis`` must be zero-padded to size ``n``. - - If ``n`` is less than ``M``, the axis specified by ``axis`` must be trimmed to size ``n``. - - If ``n`` equals ``M``, all elements along the axis specified by ``axis`` must be used when computing the transform. + - If ``n`` is greater than ``M``, the axis specified by ``axis`` must be zero-padded to size ``n``. + - If ``n`` is less than ``M``, the axis specified by ``axis`` must be trimmed to size ``n``. + - If ``n`` equals ``M``, all elements along the axis specified by ``axis`` must be used when computing the transform. - Default: ``None``. + Default: ``None``. axis: int - axis (dimension) of the input array over which to compute the transform. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). Default: ``-1``. + axis (dimension) of the input array over which to compute the transform. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). Default: ``-1``. norm: Literal['backward', 'ortho', 'forward'] - normalization mode. Should be one of the following modes: + normalization mode. Should be one of the following modes: - - ``'backward'``: no normalization. - - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). - - ``'forward'``: normalize by ``1/n``. + - ``'backward'``: no normalization. + - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). + - ``'forward'``: normalize by ``1/n``. - Default: ``'backward'``. + Default: ``'backward'``. Returns ------- out: array - an array transformed along the axis (dimension) specified by ``axis``. The returned array must have a complex floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``float64``, then the returned array must have a ``complex128`` data type). The returned array must have the same shape as ``x``, except for the axis specified by ``axis`` which must have size ``n//2 + 1``. + an array transformed along the axis (dimension) specified by ``axis``. The returned array must have a complex floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``float64``, then the returned array must have a ``complex128`` data type). The returned array must have the same shape as ``x``, except for the axis specified by ``axis`` which must have size ``n//2 + 1``. Notes ----- @@ -7036,35 +7040,35 @@ class irfft[TArray: Array](Protocol): Computes the one-dimensional inverse of ``rfft`` for complex-valued input. .. note:: - Applying the one-dimensional inverse discrete Fourier transform for real-valued input to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e., ``irfft(rfft(x)) == x``), provided that the transform and inverse transform are performed with the same arguments (axis and normalization mode) and consistent values for the number of elements over which to compute the transforms. + Applying the one-dimensional inverse discrete Fourier transform for real-valued input to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e., ``irfft(rfft(x)) == x``), provided that the transform and inverse transform are performed with the same arguments (axis and normalization mode) and consistent values for the number of elements over which to compute the transforms. Parameters ---------- x: array - input array. Should have a complex floating-point data type. + input array. Should have a complex floating-point data type. n: Optional[int] - number of elements along the transformed axis (dimension) specified by ``axis`` in the **output array**. Let ``M`` be the size of the input array along the axis specified by ``axis``. When ``n`` is ``None``, the function must set ``n`` equal to ``2*(M-1)``. + number of elements along the transformed axis (dimension) specified by ``axis`` in the **output array**. Let ``M`` be the size of the input array along the axis specified by ``axis``. When ``n`` is ``None``, the function must set ``n`` equal to ``2*(M-1)``. - - If ``n//2+1`` is greater than ``M``, the axis of the input array specified by ``axis`` must be zero-padded to size ``n//2+1``. - - If ``n//2+1`` is less than ``M``, the axis of the input array specified by ``axis`` must be trimmed to size ``n//2+1``. - - If ``n//2+1`` equals ``M``, all elements along the axis of the input array specified by ``axis`` must be used when computing the transform. + - If ``n//2+1`` is greater than ``M``, the axis of the input array specified by ``axis`` must be zero-padded to size ``n//2+1``. + - If ``n//2+1`` is less than ``M``, the axis of the input array specified by ``axis`` must be trimmed to size ``n//2+1``. + - If ``n//2+1`` equals ``M``, all elements along the axis of the input array specified by ``axis`` must be used when computing the transform. - Default: ``None``. + Default: ``None``. axis: int - axis (dimension) of the input array over which to compute the transform. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). Default: ``-1``. + axis (dimension) of the input array over which to compute the transform. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). Default: ``-1``. norm: Literal['backward', 'ortho', 'forward'] - normalization mode. Should be one of the following modes: + normalization mode. Should be one of the following modes: - - ``'backward'``: normalize by ``1/n``. - - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). - - ``'forward'``: no normalization. + - ``'backward'``: normalize by ``1/n``. + - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). + - ``'forward'``: no normalization. - Default: ``'backward'``. + Default: ``'backward'``. Returns ------- out: array - an array transformed along the axis (dimension) specified by ``axis``. The returned array must have a real-valued floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``complex128``, then the returned array must have a ``float64`` data type). The returned array must have the same shape as ``x``, except for the axis specified by ``axis`` which must have size ``n``. + an array transformed along the axis (dimension) specified by ``axis``. The returned array must have a real-valued floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``complex128``, then the returned array must have a ``float64`` data type). The returned array must have the same shape as ``x``, except for the axis specified by ``axis`` which must have size ``n``. Notes ----- @@ -7073,7 +7077,7 @@ class irfft[TArray: Array](Protocol): .. versionadded:: 2022.12 .. versionchanged:: 2023.12 - Required the output array have a real-valued floating-point data type having the same precision as the input array. + Required the output array have a real-valued floating-point data type having the same precision as the input array. """ @@ -7087,41 +7091,41 @@ class rfftn[TArray: Array](Protocol): Computes the n-dimensional discrete Fourier transform for real-valued input. .. note:: - Applying the n-dimensional inverse discrete Fourier transform for real-valued input to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e., ``irfftn(rfftn(x)) == x``), provided that the transform and inverse transform are performed with the same arguments (axes and normalization mode) and consistent sizes. + Applying the n-dimensional inverse discrete Fourier transform for real-valued input to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e., ``irfftn(rfftn(x)) == x``), provided that the transform and inverse transform are performed with the same arguments (axes and normalization mode) and consistent sizes. Parameters ---------- x: array - input array. Must have a real-valued floating-point data type. + input array. Must have a real-valued floating-point data type. s: Optional[Sequence[int]] - number of elements over which to compute the transform along axes (dimensions) specified by ``axes``. Let ``i`` be the index of the ``n``-th axis specified by ``axes`` (i.e., ``i = axes[n]``) and ``M[i]`` be the size of the input array along axis ``i``. When ``s`` is ``None``, the function must set ``s`` equal to a sequence of integers such that ``s[i]`` equals ``M[i]`` for all ``i``. + number of elements over which to compute the transform along axes (dimensions) specified by ``axes``. Let ``i`` be the index of the ``n``-th axis specified by ``axes`` (i.e., ``i = axes[n]``) and ``M[i]`` be the size of the input array along axis ``i``. When ``s`` is ``None``, the function must set ``s`` equal to a sequence of integers such that ``s[i]`` equals ``M[i]`` for all ``i``. - - If ``s[i]`` is greater than ``M[i]``, axis ``i`` must be zero-padded to size ``s[i]``. - - If ``s[i]`` is less than ``M[i]``, axis ``i`` must be trimmed to size ``s[i]``. - - If ``s[i]`` equals ``M[i]`` or ``-1``, all elements along axis ``i`` must be used when computing the transform. + - If ``s[i]`` is greater than ``M[i]``, axis ``i`` must be zero-padded to size ``s[i]``. + - If ``s[i]`` is less than ``M[i]``, axis ``i`` must be trimmed to size ``s[i]``. + - If ``s[i]`` equals ``M[i]`` or ``-1``, all elements along axis ``i`` must be used when computing the transform. - If ``s`` is not ``None``, ``axes`` must not be ``None``. Default: ``None``. + If ``s`` is not ``None``, ``axes`` must not be ``None``. Default: ``None``. axes: Optional[Sequence[int]] - axes (dimensions) over which to compute the transform. A valid axis in ``axes`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an axis is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). + axes (dimensions) over which to compute the transform. A valid axis in ``axes`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an axis is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). - If ``s`` is provided, the corresponding ``axes`` to be transformed must also be provided. If ``axes`` is ``None``, the function must compute the transform over all axes. Default: ``None``. + If ``s`` is provided, the corresponding ``axes`` to be transformed must also be provided. If ``axes`` is ``None``, the function must compute the transform over all axes. Default: ``None``. - If ``axes`` contains two or more entries which resolve to the same axis (i.e., resolved axes are not unique), the behavior is unspecified and thus implementation-defined. + If ``axes`` contains two or more entries which resolve to the same axis (i.e., resolved axes are not unique), the behavior is unspecified and thus implementation-defined. norm: Literal['backward', 'ortho', 'forward'] - normalization mode. Should be one of the following modes: + normalization mode. Should be one of the following modes: - - ``'backward'``: no normalization. - - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). - - ``'forward'``: normalize by ``1/n``. + - ``'backward'``: no normalization. + - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). + - ``'forward'``: normalize by ``1/n``. - where ``n = prod(s)``, the logical FFT size. + where ``n = prod(s)``, the logical FFT size. - Default: ``'backward'``. + Default: ``'backward'``. Returns ------- out: array - an array transformed along the axes (dimension) specified by ``axes``. The returned array must have a complex floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``float64``, then the returned array must have a ``complex128`` data type). The returned array must have the same shape as ``x``, except for the last transformed axis which must have size ``s[-1]//2 + 1`` and the remaining transformed axes which must have size ``s[i]``. + an array transformed along the axes (dimension) specified by ``axes``. The returned array must have a complex floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``float64``, then the returned array must have a ``complex128`` data type). The returned array must have the same shape as ``x``, except for the last transformed axis which must have size ``s[-1]//2 + 1`` and the remaining transformed axes which must have size ``s[i]``. Notes ----- @@ -7140,41 +7144,41 @@ class irfftn[TArray: Array](Protocol): Computes the n-dimensional inverse of ``rfftn`` for complex-valued input. .. note:: - Applying the n-dimensional inverse discrete Fourier transform for real-valued input to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e., ``irfftn(rfftn(x)) == x``), provided that the transform and inverse transform are performed with the same arguments (axes and normalization mode) and consistent sizes. + Applying the n-dimensional inverse discrete Fourier transform for real-valued input to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e., ``irfftn(rfftn(x)) == x``), provided that the transform and inverse transform are performed with the same arguments (axes and normalization mode) and consistent sizes. Parameters ---------- x: array - input array. Should have a complex floating-point data type. + input array. Should have a complex floating-point data type. s: Optional[Sequence[int]] - number of elements along the transformed axes (dimensions) specified by ``axes`` in the **output array**. Let ``i`` be the index of the ``n``-th axis specified by ``axes`` (i.e., ``i = axes[n]``) and ``M[i]`` be the size of the input array along axis ``i``. When ``s`` is ``None``, the function must set ``s`` equal to a sequence of integers such that ``s[i]`` equals ``M[i]`` for all ``i``, except for the last transformed axis in which ``s[i]`` equals ``2*(M[i]-1)``. For each ``i``, let ``n`` equal ``s[i]``, except for the last transformed axis in which ``n`` equals ``s[i]//2+1``. + number of elements along the transformed axes (dimensions) specified by ``axes`` in the **output array**. Let ``i`` be the index of the ``n``-th axis specified by ``axes`` (i.e., ``i = axes[n]``) and ``M[i]`` be the size of the input array along axis ``i``. When ``s`` is ``None``, the function must set ``s`` equal to a sequence of integers such that ``s[i]`` equals ``M[i]`` for all ``i``, except for the last transformed axis in which ``s[i]`` equals ``2*(M[i]-1)``. For each ``i``, let ``n`` equal ``s[i]``, except for the last transformed axis in which ``n`` equals ``s[i]//2+1``. - - If ``n`` is greater than ``M[i]``, axis ``i`` of the input array must be zero-padded to size ``n``. - - If ``n`` is less than ``M[i]``, axis ``i`` of the input array must be trimmed to size ``n``. - - If ``n`` equals ``M[i]`` or ``-1``, all elements along axis ``i`` of the input array must be used when computing the transform. + - If ``n`` is greater than ``M[i]``, axis ``i`` of the input array must be zero-padded to size ``n``. + - If ``n`` is less than ``M[i]``, axis ``i`` of the input array must be trimmed to size ``n``. + - If ``n`` equals ``M[i]`` or ``-1``, all elements along axis ``i`` of the input array must be used when computing the transform. - If ``s`` is not ``None``, ``axes`` must not be ``None``. Default: ``None``. + If ``s`` is not ``None``, ``axes`` must not be ``None``. Default: ``None``. axes: Optional[Sequence[int]] - axes (dimensions) over which to compute the transform. A valid axis in ``axes`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an axis is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). + axes (dimensions) over which to compute the transform. A valid axis in ``axes`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an axis is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). - If ``s`` is provided, the corresponding ``axes`` to be transformed must also be provided. If ``axes`` is ``None``, the function must compute the transform over all axes. Default: ``None``. + If ``s`` is provided, the corresponding ``axes`` to be transformed must also be provided. If ``axes`` is ``None``, the function must compute the transform over all axes. Default: ``None``. - If ``axes`` contains two or more entries which resolve to the same axis (i.e., resolved axes are not unique), the behavior is unspecified and thus implementation-defined. + If ``axes`` contains two or more entries which resolve to the same axis (i.e., resolved axes are not unique), the behavior is unspecified and thus implementation-defined. norm: Literal['backward', 'ortho', 'forward'] - normalization mode. Should be one of the following modes: + normalization mode. Should be one of the following modes: - - ``'backward'``: normalize by ``1/n``. - - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). - - ``'forward'``: no normalization. + - ``'backward'``: normalize by ``1/n``. + - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). + - ``'forward'``: no normalization. - where ``n = prod(s)`` is the logical FFT size. + where ``n = prod(s)`` is the logical FFT size. - Default: ``'backward'``. + Default: ``'backward'``. Returns ------- out: array - an array transformed along the axes (dimension) specified by ``axes``. The returned array must have a real-valued floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``complex128``, then the returned array must have a ``float64`` data type). The returned array must have the same shape as ``x``, except for the transformed axes which must have size ``s[i]``. + an array transformed along the axes (dimension) specified by ``axes``. The returned array must have a real-valued floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``complex128``, then the returned array must have a ``float64`` data type). The returned array must have the same shape as ``x``, except for the transformed axes which must have size ``s[i]``. Notes ----- @@ -7183,7 +7187,7 @@ class irfftn[TArray: Array](Protocol): .. versionadded:: 2022.12 .. versionchanged:: 2023.12 - Required the output array have a real-valued floating-point data type having the same precision as the input array. + Required the output array have a real-valued floating-point data type having the same precision as the input array. """ @@ -7199,30 +7203,30 @@ class hfft[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a complex floating-point data type. + input array. Should have a complex floating-point data type. n: Optional[int] - number of elements along the transformed axis (dimension) specified by ``axis`` in the **output array**. Let ``M`` be the size of the input array along the axis specified by ``axis``. When ``n`` is ``None``, the function must set ``n`` equal to ``2*(M-1)``. + number of elements along the transformed axis (dimension) specified by ``axis`` in the **output array**. Let ``M`` be the size of the input array along the axis specified by ``axis``. When ``n`` is ``None``, the function must set ``n`` equal to ``2*(M-1)``. - - If ``n//2+1`` is greater than ``M``, the axis of the input array specified by ``axis`` must be zero-padded to length ``n//2+1``. - - If ``n//2+1`` is less than ``M``, the axis of the input array specified by ``axis`` must be trimmed to size ``n//2+1``. - - If ``n//2+1`` equals ``M``, all elements along the axis of the input array specified by ``axis`` must be used when computing the transform. + - If ``n//2+1`` is greater than ``M``, the axis of the input array specified by ``axis`` must be zero-padded to length ``n//2+1``. + - If ``n//2+1`` is less than ``M``, the axis of the input array specified by ``axis`` must be trimmed to size ``n//2+1``. + - If ``n//2+1`` equals ``M``, all elements along the axis of the input array specified by ``axis`` must be used when computing the transform. - Default: ``None``. + Default: ``None``. axis: int - axis (dimension) of the input array over which to compute the transform. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). Default: ``-1``. + axis (dimension) of the input array over which to compute the transform. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). Default: ``-1``. norm: Literal['backward', 'ortho', 'forward'] - normalization mode. Should be one of the following modes: + normalization mode. Should be one of the following modes: - - ``'backward'``: no normalization. - - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). - - ``'forward'``: normalize by ``1/n``. + - ``'backward'``: no normalization. + - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). + - ``'forward'``: normalize by ``1/n``. - Default: ``'backward'``. + Default: ``'backward'``. Returns ------- out: array - an array transformed along the axis (dimension) specified by ``axis``. The returned array must have a real-valued floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``complex128``, then the returned array must have a ``float64`` data type). The returned array must have the same shape as ``x``, except for the axis specified by ``axis`` which must have size ``n``. + an array transformed along the axis (dimension) specified by ``axis``. The returned array must have a real-valued floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``complex128``, then the returned array must have a ``float64`` data type). The returned array must have the same shape as ``x``, except for the axis specified by ``axis`` which must have size ``n``. Notes ----- @@ -7230,7 +7234,7 @@ class hfft[TArray: Array](Protocol): .. versionadded:: 2022.12 .. versionchanged:: 2023.12 - Required the input array to have a complex floating-point data type and required that the output array have a real-valued data type having the same precision as the input array. + Required the input array to have a complex floating-point data type and required that the output array have a real-valued data type having the same precision as the input array. """ @@ -7246,30 +7250,30 @@ class ihfft[TArray: Array](Protocol): Parameters ---------- x: array - input array. Must have a real-valued floating-point data type. + input array. Must have a real-valued floating-point data type. n: Optional[int] - number of elements over which to compute the transform along the axis (dimension) specified by ``axis``. Let ``M`` be the size of the input array along the axis specified by ``axis``. When ``n`` is ``None``, the function must set ``n`` equal to ``M``. + number of elements over which to compute the transform along the axis (dimension) specified by ``axis``. Let ``M`` be the size of the input array along the axis specified by ``axis``. When ``n`` is ``None``, the function must set ``n`` equal to ``M``. - - If ``n`` is greater than ``M``, the axis specified by ``axis`` must be zero-padded to size ``n``. - - If ``n`` is less than ``M``, the axis specified by ``axis`` must be trimmed to size ``n``. - - If ``n`` equals ``M``, all elements along the axis specified by ``axis`` must be used when computing the transform. + - If ``n`` is greater than ``M``, the axis specified by ``axis`` must be zero-padded to size ``n``. + - If ``n`` is less than ``M``, the axis specified by ``axis`` must be trimmed to size ``n``. + - If ``n`` equals ``M``, all elements along the axis specified by ``axis`` must be used when computing the transform. - Default: ``None``. + Default: ``None``. axis: int - axis (dimension) of the input array over which to compute the transform. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). Default: ``-1``. + axis (dimension) of the input array over which to compute the transform. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). Default: ``-1``. norm: Literal['backward', 'ortho', 'forward'] - normalization mode. Should be one of the following modes: + normalization mode. Should be one of the following modes: - - ``'backward'``: normalize by ``1/n``. - - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). - - ``'forward'``: no normalization. + - ``'backward'``: normalize by ``1/n``. + - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). + - ``'forward'``: no normalization. - Default: ``'backward'``. + Default: ``'backward'``. Returns ------- out: array - an array transformed along the axis (dimension) specified by ``axis``. The returned array must have a complex floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``float64``, then the returned array must have a ``complex128`` data type). The returned array must have the same shape as ``x``, except for the axis specified by ``axis`` which must have size ``n//2 + 1``. + an array transformed along the axis (dimension) specified by ``axis``. The returned array must have a complex floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``float64``, then the returned array must have a ``complex128`` data type). The returned array must have the same shape as ``x``, except for the axis specified by ``axis`` which must have size ``n//2 + 1``. Notes ----- @@ -7291,22 +7295,22 @@ class fftfreq[TArray: Array, TDevice](Protocol): .. code-block:: - f = [0, 1, ..., n/2-1, -n/2, ..., -1] / (d*n) # if n is even - f = [0, 1, ..., (n-1)/2, -(n-1)/2, ..., -1] / (d*n) # if n is odd + f = [0, 1, ..., n/2-1, -n/2, ..., -1] / (d*n) # if n is even + f = [0, 1, ..., (n-1)/2, -(n-1)/2, ..., -1] / (d*n) # if n is odd Parameters ---------- n: int - window length. + window length. d: float - sample spacing between individual samples of the Fourier transform input. Default: ``1.0``. + sample spacing between individual samples of the Fourier transform input. Default: ``1.0``. device: Optional[device] - device on which to place the created array. Default: ``None``. + device on which to place the created array. Default: ``None``. Returns ------- out: array - an array of shape ``(n,)`` containing the sample frequencies. The returned array must have the default real-valued floating-point data type. + an array of shape ``(n,)`` containing the sample frequencies. The returned array must have the default real-valued floating-point data type. Notes ----- @@ -7314,7 +7318,7 @@ class fftfreq[TArray: Array, TDevice](Protocol): .. versionadded:: 2022.12 .. versionchanged:: 2023.12 - Required the output array have the default real-valued floating-point data type. + Required the output array have the default real-valued floating-point data type. """ @@ -7331,24 +7335,24 @@ class rfftfreq[TArray: Array, TDevice](Protocol): .. code-block:: - f = [0, 1, ..., n/2-1, n/2] / (d*n) # if n is even - f = [0, 1, ..., (n-1)/2-1, (n-1)/2] / (d*n) # if n is odd + f = [0, 1, ..., n/2-1, n/2] / (d*n) # if n is even + f = [0, 1, ..., (n-1)/2-1, (n-1)/2] / (d*n) # if n is odd The Nyquist frequency component is considered to be positive. Parameters ---------- n: int - window length. + window length. d: float - sample spacing between individual samples of the Fourier transform input. Default: ``1.0``. + sample spacing between individual samples of the Fourier transform input. Default: ``1.0``. device: Optional[device] - device on which to place the created array. Default: ``None``. + device on which to place the created array. Default: ``None``. Returns ------- out: array - an array of shape ``(n//2+1,)`` containing the sample frequencies. The returned array must have the default real-valued floating-point data type. + an array of shape ``(n//2+1,)`` containing the sample frequencies. The returned array must have the default real-valued floating-point data type. Notes ----- @@ -7356,7 +7360,7 @@ class rfftfreq[TArray: Array, TDevice](Protocol): .. versionadded:: 2022.12 .. versionchanged:: 2023.12 - Required the output array have the default real-valued floating-point data type. + Required the output array have the default real-valued floating-point data type. """ @@ -7372,21 +7376,21 @@ class fftshift[TArray: Array](Protocol): This function swaps half-spaces for all axes (dimensions) specified by ``axes``. .. note:: - ``out[0]`` is the Nyquist component only if the length of the input is even. + ``out[0]`` is the Nyquist component only if the length of the input is even. Parameters ---------- x: array - input array. Should have a floating-point data type. + input array. Should have a floating-point data type. axes: Optional[Union[int, Sequence[int]]] - axes over which to shift. If ``None``, the function must shift all axes. Default: ``None``. + axes over which to shift. If ``None``, the function must shift all axes. Default: ``None``. - If ``axes`` contains two or more entries which resolve to the same axis (i.e., resolved axes are not unique), the behavior is unspecified and thus implementation-defined. + If ``axes`` contains two or more entries which resolve to the same axis (i.e., resolved axes are not unique), the behavior is unspecified and thus implementation-defined. Returns ------- out: array - the shifted array. The returned array must have the same data type and shape as ``x``. + the shifted array. The returned array must have the same data type and shape as ``x``. Notes ----- @@ -7405,21 +7409,21 @@ class ifftshift[TArray: Array](Protocol): Inverse of ``fftshift``. .. note:: - Although identical for even-length ``x``, ``fftshift`` and ``ifftshift`` differ by one sample for odd-length ``x``. + Although identical for even-length ``x``, ``fftshift`` and ``ifftshift`` differ by one sample for odd-length ``x``. Parameters ---------- x: array - input array. Should have a floating-point data type. + input array. Should have a floating-point data type. axes: Optional[Union[int, Sequence[int]]] - axes over which to perform the inverse shift. If ``None``, the function must shift all axes. Default: ``None``. + axes over which to perform the inverse shift. If ``None``, the function must shift all axes. Default: ``None``. - If ``axes`` contains two or more entries which resolve to the same axis (i.e., resolved axes are not unique), the behavior is unspecified and thus implementation-defined. + If ``axes`` contains two or more entries which resolve to the same axis (i.e., resolved axes are not unique), the behavior is unspecified and thus implementation-defined. Returns ------- out: array - the shifted array. The returned array must have the same data type and shape as ``x``. + the shifted array. The returned array must have the same data type and shape as ``x``. Notes ----- @@ -7438,37 +7442,37 @@ class matmul[TArray: Array](Protocol): Computes the matrix product. .. note:: - The ``matmul`` function must implement the same semantics as the built-in ``@`` operator (see `PEP 465 `_). + The ``matmul`` function must implement the same semantics as the built-in ``@`` operator (see `PEP 465 `_). Parameters ---------- x1: array - first input array. Should have a numeric data type. Must have at least one dimension. If ``x1`` is one-dimensional having shape ``(M,)`` and ``x2`` has more than one dimension, ``x1`` must be promoted to a two-dimensional array by prepending ``1`` to its dimensions (i.e., must have shape ``(1, M)``). After matrix multiplication, the prepended dimensions in the returned array must be removed. If ``x1`` has more than one dimension (including after vector-to-matrix promotion), ``shape(x1)[:-2]`` must be compatible with ``shape(x2)[:-2]`` (after vector-to-matrix promotion) (see :ref:`broadcasting`). If ``x1`` has shape ``(..., M, K)``, the innermost two dimensions form matrices on which to perform matrix multiplication. + first input array. Should have a numeric data type. Must have at least one dimension. If ``x1`` is one-dimensional having shape ``(M,)`` and ``x2`` has more than one dimension, ``x1`` must be promoted to a two-dimensional array by prepending ``1`` to its dimensions (i.e., must have shape ``(1, M)``). After matrix multiplication, the prepended dimensions in the returned array must be removed. If ``x1`` has more than one dimension (including after vector-to-matrix promotion), ``shape(x1)[:-2]`` must be compatible with ``shape(x2)[:-2]`` (after vector-to-matrix promotion) (see :ref:`broadcasting`). If ``x1`` has shape ``(..., M, K)``, the innermost two dimensions form matrices on which to perform matrix multiplication. x2: array - second input array. Should have a numeric data type. Must have at least one dimension. If ``x2`` is one-dimensional having shape ``(N,)`` and ``x1`` has more than one dimension, ``x2`` must be promoted to a two-dimensional array by appending ``1`` to its dimensions (i.e., must have shape ``(N, 1)``). After matrix multiplication, the appended dimensions in the returned array must be removed. If ``x2`` has more than one dimension (including after vector-to-matrix promotion), ``shape(x2)[:-2]`` must be compatible with ``shape(x1)[:-2]`` (after vector-to-matrix promotion) (see :ref:`broadcasting`). If ``x2`` has shape ``(..., K, N)``, the innermost two dimensions form matrices on which to perform matrix multiplication. + second input array. Should have a numeric data type. Must have at least one dimension. If ``x2`` is one-dimensional having shape ``(N,)`` and ``x1`` has more than one dimension, ``x2`` must be promoted to a two-dimensional array by appending ``1`` to its dimensions (i.e., must have shape ``(N, 1)``). After matrix multiplication, the appended dimensions in the returned array must be removed. If ``x2`` has more than one dimension (including after vector-to-matrix promotion), ``shape(x2)[:-2]`` must be compatible with ``shape(x1)[:-2]`` (after vector-to-matrix promotion) (see :ref:`broadcasting`). If ``x2`` has shape ``(..., K, N)``, the innermost two dimensions form matrices on which to perform matrix multiplication. .. note:: - If either ``x1`` or ``x2`` has a complex floating-point data type, neither argument must be complex-conjugated or transposed. If conjugation and/or transposition is desired, these operations should be explicitly performed prior to computing the matrix product. + If either ``x1`` or ``x2`` has a complex floating-point data type, neither argument must be complex-conjugated or transposed. If conjugation and/or transposition is desired, these operations should be explicitly performed prior to computing the matrix product. Returns ------- out: array - - if both ``x1`` and ``x2`` are one-dimensional arrays having shape ``(N,)``, a zero-dimensional array containing the inner product as its only element. - - if ``x1`` is a two-dimensional array having shape ``(M, K)`` and ``x2`` is a two-dimensional array having shape ``(K, N)``, a two-dimensional array containing the `conventional matrix product `_ and having shape ``(M, N)``. - - if ``x1`` is a one-dimensional array having shape ``(K,)`` and ``x2`` is an array having shape ``(..., K, N)``, an array having shape ``(..., N)`` (i.e., prepended dimensions during vector-to-matrix promotion must be removed) and containing the `conventional matrix product `_. - - if ``x1`` is an array having shape ``(..., M, K)`` and ``x2`` is a one-dimensional array having shape ``(K,)``, an array having shape ``(..., M)`` (i.e., appended dimensions during vector-to-matrix promotion must be removed) and containing the `conventional matrix product `_. - - if ``x1`` is a two-dimensional array having shape ``(M, K)`` and ``x2`` is an array having shape ``(..., K, N)``, an array having shape ``(..., M, N)`` and containing the `conventional matrix product `_ for each stacked matrix. - - if ``x1`` is an array having shape ``(..., M, K)`` and ``x2`` is a two-dimensional array having shape ``(K, N)``, an array having shape ``(..., M, N)`` and containing the `conventional matrix product `_ for each stacked matrix. - - if either ``x1`` or ``x2`` has more than two dimensions, an array having a shape determined by :ref:`broadcasting` ``shape(x1)[:-2]`` against ``shape(x2)[:-2]`` and containing the `conventional matrix product `_ for each stacked matrix. + - if both ``x1`` and ``x2`` are one-dimensional arrays having shape ``(N,)``, a zero-dimensional array containing the inner product as its only element. + - if ``x1`` is a two-dimensional array having shape ``(M, K)`` and ``x2`` is a two-dimensional array having shape ``(K, N)``, a two-dimensional array containing the `conventional matrix product `_ and having shape ``(M, N)``. + - if ``x1`` is a one-dimensional array having shape ``(K,)`` and ``x2`` is an array having shape ``(..., K, N)``, an array having shape ``(..., N)`` (i.e., prepended dimensions during vector-to-matrix promotion must be removed) and containing the `conventional matrix product `_. + - if ``x1`` is an array having shape ``(..., M, K)`` and ``x2`` is a one-dimensional array having shape ``(K,)``, an array having shape ``(..., M)`` (i.e., appended dimensions during vector-to-matrix promotion must be removed) and containing the `conventional matrix product `_. + - if ``x1`` is a two-dimensional array having shape ``(M, K)`` and ``x2`` is an array having shape ``(..., K, N)``, an array having shape ``(..., M, N)`` and containing the `conventional matrix product `_ for each stacked matrix. + - if ``x1`` is an array having shape ``(..., M, K)`` and ``x2`` is a two-dimensional array having shape ``(K, N)``, an array having shape ``(..., M, N)`` and containing the `conventional matrix product `_ for each stacked matrix. + - if either ``x1`` or ``x2`` has more than two dimensions, an array having a shape determined by :ref:`broadcasting` ``shape(x1)[:-2]`` against ``shape(x2)[:-2]`` and containing the `conventional matrix product `_ for each stacked matrix. - The returned array must have a data type determined by :ref:`type-promotion`. + The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. **Raises** @@ -7492,12 +7496,12 @@ class matrix_transpose[TArray: Array](Protocol): Parameters ---------- x: array - input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. + input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. Returns ------- out: array - an array containing the transpose for each matrix and having shape ``(..., N, M)``. The returned array must have the same data type as ``x``. + an array containing the transpose for each matrix and having shape ``(..., N, M)``. The returned array must have the same data type as ``x``. """ @@ -7511,46 +7515,46 @@ class tensordot[TArray: Array](Protocol): Returns a tensor contraction of ``x1`` and ``x2`` over specific axes. .. note:: - The ``tensordot`` function corresponds to the generalized matrix product. + The ``tensordot`` function corresponds to the generalized matrix product. Parameters ---------- x1: array - first input array. Should have a numeric data type. + first input array. Should have a numeric data type. x2: array - second input array. Should have a numeric data type. Corresponding contracted axes of ``x1`` and ``x2`` must be equal. + second input array. Should have a numeric data type. Corresponding contracted axes of ``x1`` and ``x2`` must be equal. - .. note:: - Contracted axes (dimensions) must not be broadcasted. + .. note:: + Contracted axes (dimensions) must not be broadcasted. axes: Union[int, Tuple[Sequence[int], Sequence[int]]] - number of axes (dimensions) to contract or explicit sequences of axis (dimension) indices for ``x1`` and ``x2``, respectively. + number of axes (dimensions) to contract or explicit sequences of axis (dimension) indices for ``x1`` and ``x2``, respectively. - If ``axes`` is an ``int`` equal to ``N``, then contraction must be performed over the last ``N`` axes of ``x1`` and the first ``N`` axes of ``x2`` in order. The size of each corresponding axis (dimension) must match. Must be nonnegative. + If ``axes`` is an ``int`` equal to ``N``, then contraction must be performed over the last ``N`` axes of ``x1`` and the first ``N`` axes of ``x2`` in order. The size of each corresponding axis (dimension) must match. Must be nonnegative. - - If ``N`` equals ``0``, the result is the tensor (outer) product. - - If ``N`` equals ``1``, the result is the tensor dot product. - - If ``N`` equals ``2``, the result is the tensor double contraction (default). + - If ``N`` equals ``0``, the result is the tensor (outer) product. + - If ``N`` equals ``1``, the result is the tensor dot product. + - If ``N`` equals ``2``, the result is the tensor double contraction (default). - If ``axes`` is a tuple of two sequences ``(x1_axes, x2_axes)``, the first sequence must apply to ``x1`` and the second sequence to ``x2``. Both sequences must have the same length. Each axis (dimension) ``x1_axes[i]`` for ``x1`` must have the same size as the respective axis (dimension) ``x2_axes[i]`` for ``x2``. Each index referred to in a sequence must be unique. If ``x1`` has rank (i.e, number of dimensions) ``N``, a valid ``x1`` axis must reside on the half-open interval ``[-N, N)``. If ``x2`` has rank ``M``, a valid ``x2`` axis must reside on the half-open interval ``[-M, M)``. + If ``axes`` is a tuple of two sequences ``(x1_axes, x2_axes)``, the first sequence must apply to ``x1`` and the second sequence to ``x2``. Both sequences must have the same length. Each axis (dimension) ``x1_axes[i]`` for ``x1`` must have the same size as the respective axis (dimension) ``x2_axes[i]`` for ``x2``. Each index referred to in a sequence must be unique. If ``x1`` has rank (i.e, number of dimensions) ``N``, a valid ``x1`` axis must reside on the half-open interval ``[-N, N)``. If ``x2`` has rank ``M``, a valid ``x2`` axis must reside on the half-open interval ``[-M, M)``. .. note:: - If either ``x1`` or ``x2`` has a complex floating-point data type, neither argument must be complex-conjugated or transposed. If conjugation and/or transposition is desired, these operations should be explicitly performed prior to computing the generalized matrix product. + If either ``x1`` or ``x2`` has a complex floating-point data type, neither argument must be complex-conjugated or transposed. If conjugation and/or transposition is desired, these operations should be explicitly performed prior to computing the generalized matrix product. Returns ------- out: array - an array containing the tensor contraction whose shape consists of the non-contracted axes (dimensions) of the first array ``x1``, followed by the non-contracted axes (dimensions) of the second array ``x2``. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the tensor contraction whose shape consists of the non-contracted axes (dimensions) of the first array ``x1``, followed by the non-contracted axes (dimensions) of the second array ``x2``. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. .. versionchanged:: 2023.12 - Allow negative axes. + Allow negative axes. """ @@ -7566,27 +7570,27 @@ class vecdot[TArray: Array](Protocol): Let :math:`\\mathbf{a}` be a vector in ``x1`` and :math:`\\mathbf{b}` be a corresponding vector in ``x2``. The dot product is defined as .. math:: - \\mathbf{a} \\cdot \\mathbf{b} = \\sum_{i=0}^{n-1} \\overline{a_i}b_i + \\mathbf{a} \\cdot \\mathbf{b} = \\sum_{i=0}^{n-1} \\overline{a_i}b_i over the dimension specified by ``axis`` and where :math:`n` is the dimension size and :math:`\\overline{a_i}` denotes the complex conjugate if :math:`a_i` is complex and the identity if :math:`a_i` is real-valued. Parameters ---------- x1: array - first input array. Should have a floating-point data type. + first input array. Should have a floating-point data type. x2: array - second input array. Must be compatible with ``x1`` for all non-contracted axes (see :ref:`broadcasting`). The size of the axis over which to compute the dot product must be the same size as the respective axis in ``x1``. Should have a floating-point data type. + second input array. Must be compatible with ``x1`` for all non-contracted axes (see :ref:`broadcasting`). The size of the axis over which to compute the dot product must be the same size as the respective axis in ``x1``. Should have a floating-point data type. - .. note:: - The contracted axis (dimension) must not be broadcasted. + .. note:: + The contracted axis (dimension) must not be broadcasted. axis: int - the axis (dimension) of ``x1`` and ``x2`` containing the vectors for which to compute the dot product. Should be an integer on the interval ``[-N, -1]``, where ``N`` is ``min(x1.ndim, x2.ndim)``. The function must determine the axis along which to compute the dot product by counting backward from the last dimension (where ``-1`` refers to the last dimension). By default, the function must compute the dot product over the last axis. Default: ``-1``. + the axis (dimension) of ``x1`` and ``x2`` containing the vectors for which to compute the dot product. Should be an integer on the interval ``[-N, -1]``, where ``N`` is ``min(x1.ndim, x2.ndim)``. The function must determine the axis along which to compute the dot product by counting backward from the last dimension (where ``-1`` refers to the last dimension). By default, the function must compute the dot product over the last axis. Default: ``-1``. Returns ------- out: array - if ``x1`` and ``x2`` are both one-dimensional arrays, a zero-dimensional containing the dot product; otherwise, a non-zero-dimensional array containing the dot products and having rank ``N-1``, where ``N`` is the rank (number of dimensions) of the shape determined according to :ref:`broadcasting` along the non-contracted axes. The returned array must have a data type determined by :ref:`type-promotion`. + if ``x1`` and ``x2`` are both one-dimensional arrays, a zero-dimensional containing the dot product; otherwise, a non-zero-dimensional array containing the dot products and having rank ``N-1``, where ``N`` is the rank (number of dimensions) of the shape determined according to :ref:`broadcasting` along the non-contracted axes. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- @@ -7595,10 +7599,10 @@ class vecdot[TArray: Array](Protocol): - if the size of the axis over which to compute the dot product is not the same (before broadcasting) for both ``x1`` and ``x2``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. .. versionchanged:: 2023.12 - Restricted ``axis`` to only negative integers. + Restricted ``axis`` to only negative integers. """ @@ -7614,12 +7618,12 @@ class broadcast_arrays[TArray: Array](Protocol): Parameters ---------- arrays: array - an arbitrary number of to-be broadcasted arrays. + an arbitrary number of to-be broadcasted arrays. Returns ------- out: List[array] - a list of broadcasted arrays. Each array must have the same shape. Each array must have the same dtype as its corresponding input array. + a list of broadcasted arrays. Each array must have the same shape. Each array must have the same dtype as its corresponding input array. """ @@ -7635,14 +7639,14 @@ class broadcast_to[TArray: Array](Protocol): Parameters ---------- x: array - array to broadcast. + array to broadcast. shape: Tuple[int, ...] - array shape. Must be compatible with ``x`` (see :ref:`broadcasting`). If the array is incompatible with the specified shape, the function should raise an exception. + array shape. Must be compatible with ``x`` (see :ref:`broadcasting`). If the array is incompatible with the specified shape, the function should raise an exception. Returns ------- out: array - an array having a specified shape. Must have the same data type as ``x``. + an array having a specified shape. Must have the same data type as ``x``. """ @@ -7658,17 +7662,17 @@ class concat[TArray: Array](Protocol): Parameters ---------- arrays: Union[Tuple[array, ...], List[array]] - input arrays to join. The arrays must have the same shape, except in the dimension specified by ``axis``. + input arrays to join. The arrays must have the same shape, except in the dimension specified by ``axis``. axis: Optional[int] - axis along which the arrays will be joined. If ``axis`` is ``None``, arrays must be flattened before concatenation. If ``axis`` is negative, the function must determine the axis along which to join by counting from the last dimension. Default: ``0``. + axis along which the arrays will be joined. If ``axis`` is ``None``, arrays must be flattened before concatenation. If ``axis`` is negative, the function must determine the axis along which to join by counting from the last dimension. Default: ``0``. Returns ------- out: array - an output array containing the concatenated values. If the input arrays have different data types, normal :ref:`type-promotion` must apply. If the input arrays have the same data type, the output array must have the same data type as the input arrays. + an output array containing the concatenated values. If the input arrays have different data types, normal :ref:`type-promotion` must apply. If the input arrays have the same data type, the output array must have the same data type as the input arrays. - .. note:: - This specification leaves type promotion between data type families (i.e., ``intxx`` and ``floatxx``) unspecified. + .. note:: + This specification leaves type promotion between data type families (i.e., ``intxx`` and ``floatxx``) unspecified. """ @@ -7684,19 +7688,19 @@ class expand_dims[TArray: Array](Protocol): Parameters ---------- x: array - input array. + input array. axis: int - axis position (zero-based). If ``x`` has rank (i.e, number of dimensions) ``N``, a valid ``axis`` must reside on the closed-interval ``[-N-1, N]``. If provided a negative ``axis``, the axis position at which to insert a singleton dimension must be computed as ``N + axis + 1``. Hence, if provided ``-1``, the resolved axis position must be ``N`` (i.e., a singleton dimension must be appended to the input array ``x``). If provided ``-N-1``, the resolved axis position must be ``0`` (i.e., a singleton dimension must be prepended to the input array ``x``). + axis position (zero-based). If ``x`` has rank (i.e, number of dimensions) ``N``, a valid ``axis`` must reside on the closed-interval ``[-N-1, N]``. If provided a negative ``axis``, the axis position at which to insert a singleton dimension must be computed as ``N + axis + 1``. Hence, if provided ``-1``, the resolved axis position must be ``N`` (i.e., a singleton dimension must be appended to the input array ``x``). If provided ``-N-1``, the resolved axis position must be ``0`` (i.e., a singleton dimension must be prepended to the input array ``x``). Returns ------- out: array - an expanded output array having the same data type as ``x``. + an expanded output array having the same data type as ``x``. Raises ------ IndexError - If provided an invalid ``axis`` position, an ``IndexError`` should be raised. + If provided an invalid ``axis`` position, an ``IndexError`` should be raised. """ @@ -7712,14 +7716,14 @@ class flip[TArray: Array](Protocol): Parameters ---------- x: array - input array. + input array. axis: Optional[Union[int, Tuple[int, ...]]] - axis (or axes) along which to flip. If ``axis`` is ``None``, the function must flip all input array axes. If ``axis`` is negative, the function must count from the last dimension. If provided more than one axis, the function must flip only the specified axes. Default: ``None``. + axis (or axes) along which to flip. If ``axis`` is ``None``, the function must flip all input array axes. If ``axis`` is negative, the function must count from the last dimension. If provided more than one axis, the function must flip only the specified axes. Default: ``None``. Returns ------- out: array - an output array having the same data type and shape as ``x`` and whose elements, relative to ``x``, are reordered. + an output array having the same data type and shape as ``x`` and whose elements, relative to ``x``, are reordered. """ @@ -7735,16 +7739,16 @@ class moveaxis[TArray: Array](Protocol): Parameters ---------- x: array - input array. + input array. source: Union[int, Tuple[int, ...]] - Axes to move. Provided axes must be unique. If ``x`` has rank (i.e, number of dimensions) ``N``, a valid axis must reside on the half-open interval ``[-N, N)``. + Axes to move. Provided axes must be unique. If ``x`` has rank (i.e, number of dimensions) ``N``, a valid axis must reside on the half-open interval ``[-N, N)``. destination: Union[int, Tuple[int, ...]] - indices defining the desired positions for each respective ``source`` axis index. Provided indices must be unique. If ``x`` has rank (i.e, number of dimensions) ``N``, a valid axis must reside on the half-open interval ``[-N, N)``. + indices defining the desired positions for each respective ``source`` axis index. Provided indices must be unique. If ``x`` has rank (i.e, number of dimensions) ``N``, a valid axis must reside on the half-open interval ``[-N, N)``. Returns ------- out: array - an array containing reordered axes. The returned array must have the same data type as ``x``. + an array containing reordered axes. The returned array must have the same data type as ``x``. Notes ----- @@ -7765,14 +7769,14 @@ class permute_dims[TArray: Array](Protocol): Parameters ---------- x: array - input array. + input array. axes: Tuple[int, ...] - tuple containing a permutation of ``(0, 1, ..., N-1)`` where ``N`` is the number of axes (dimensions) of ``x``. + tuple containing a permutation of ``(0, 1, ..., N-1)`` where ``N`` is the number of axes (dimensions) of ``x``. Returns ------- out: array - an array containing the axes permutation. The returned array must have the same data type as ``x``. + an array containing the axes permutation. The returned array must have the same data type as ``x``. """ @@ -7786,39 +7790,39 @@ class repeat[TArray: Array](Protocol): Repeats each element of an array a specified number of times on a per-element basis. .. admonition:: Data-dependent output shape - :class: important + :class: important - When ``repeats`` is an array, the shape of the output array for this function depends on the data values in the ``repeats`` array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) may find this function difficult to implement without knowing the values in ``repeats``. Accordingly, such libraries may choose to omit support for ``repeats`` arrays; however, conforming implementations must support providing a literal ``int``. See :ref:`data-dependent-output-shapes` section for more details. + When ``repeats`` is an array, the shape of the output array for this function depends on the data values in the ``repeats`` array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) may find this function difficult to implement without knowing the values in ``repeats``. Accordingly, such libraries may choose to omit support for ``repeats`` arrays; however, conforming implementations must support providing a literal ``int``. See :ref:`data-dependent-output-shapes` section for more details. Parameters ---------- x: array - input array containing elements to repeat. + input array containing elements to repeat. repeats: Union[int, array] - the number of repetitions for each element. + the number of repetitions for each element. - If ``axis`` is ``None``, let ``N = prod(x.shape)`` and + If ``axis`` is ``None``, let ``N = prod(x.shape)`` and - - if ``repeats`` is an array, ``repeats`` must be broadcast compatible with the shape ``(N,)`` (i.e., be a one-dimensional array having shape ``(1,)`` or ``(N,)``). - - if ``repeats`` is an integer, ``repeats`` must be broadcasted to the shape `(N,)`. + - if ``repeats`` is an array, ``repeats`` must be broadcast compatible with the shape ``(N,)`` (i.e., be a one-dimensional array having shape ``(1,)`` or ``(N,)``). + - if ``repeats`` is an integer, ``repeats`` must be broadcasted to the shape `(N,)`. - If ``axis`` is not ``None``, let ``M = x.shape[axis]`` and + If ``axis`` is not ``None``, let ``M = x.shape[axis]`` and - - if ``repeats`` is an array, ``repeats`` must be broadcast compatible with the shape ``(M,)`` (i.e., be a one-dimensional array having shape ``(1,)`` or ``(M,)``). - - if ``repeats`` is an integer, ``repeats`` must be broadcasted to the shape ``(M,)``. + - if ``repeats`` is an array, ``repeats`` must be broadcast compatible with the shape ``(M,)`` (i.e., be a one-dimensional array having shape ``(1,)`` or ``(M,)``). + - if ``repeats`` is an integer, ``repeats`` must be broadcasted to the shape ``(M,)``. - If ``repeats`` is an array, the array must have an integer data type. + If ``repeats`` is an array, the array must have an integer data type. - .. note:: - For specification-conforming array libraries supporting hardware acceleration, providing an array for ``repeats`` may cause device synchronization due to an unknown output shape. For those array libraries where synchronization concerns are applicable, conforming array libraries are advised to include a warning in their documentation regarding potential performance degradation when ``repeats`` is an array. + .. note:: + For specification-conforming array libraries supporting hardware acceleration, providing an array for ``repeats`` may cause device synchronization due to an unknown output shape. For those array libraries where synchronization concerns are applicable, conforming array libraries are advised to include a warning in their documentation regarding potential performance degradation when ``repeats`` is an array. axis: Optional[int] - the axis (dimension) along which to repeat elements. If ``axis`` is `None`, the function must flatten the input array ``x`` and then repeat elements of the flattened input array and return the result as a one-dimensional output array. A flattened input array must be flattened in row-major, C-style order. Default: ``None``. + the axis (dimension) along which to repeat elements. If ``axis`` is `None`, the function must flatten the input array ``x`` and then repeat elements of the flattened input array and return the result as a one-dimensional output array. A flattened input array must be flattened in row-major, C-style order. Default: ``None``. Returns ------- out: array - an output array containing repeated elements. The returned array must have the same data type as ``x``. If ``axis`` is ``None``, the returned array must be a one-dimensional array; otherwise, the returned array must have the same shape as ``x``, except for the axis (dimension) along which elements were repeated. + an output array containing repeated elements. The returned array must have the same data type as ``x``. If ``axis`` is ``None``, the returned array must be a one-dimensional array; otherwise, the returned array must have the same shape as ``x``, except for the axis (dimension) along which elements were repeated. Notes ----- @@ -7839,22 +7843,22 @@ class reshape[TArray: Array](Protocol): Parameters ---------- x: array - input array to reshape. + input array to reshape. shape: Tuple[int, ...] - a new shape compatible with the original shape. One shape dimension is allowed to be ``-1``. When a shape dimension is ``-1``, the corresponding output array shape dimension must be inferred from the length of the array and the remaining dimensions. + a new shape compatible with the original shape. One shape dimension is allowed to be ``-1``. When a shape dimension is ``-1``, the corresponding output array shape dimension must be inferred from the length of the array and the remaining dimensions. copy: Optional[bool] - whether or not to copy the input array. If ``True``, the function must always copy. If ``False``, the function must never copy. If ``None``, the function must avoid copying, if possible, and may copy otherwise. Default: ``None``. + whether or not to copy the input array. If ``True``, the function must always copy. If ``False``, the function must never copy. If ``None``, the function must avoid copying, if possible, and may copy otherwise. Default: ``None``. Returns ------- out: array - an output array having the same data type and elements as ``x``. + an output array having the same data type and elements as ``x``. Raises ------ ValueError - If ``copy=False`` and a copy would be necessary, a ``ValueError`` - should be raised. + If ``copy=False`` and a copy would be necessary, a ``ValueError`` + should be raised. """ @@ -7870,16 +7874,16 @@ class roll[TArray: Array](Protocol): Parameters ---------- x: array - input array. + input array. shift: Union[int, Tuple[int, ...]] - number of places by which the elements are shifted. If ``shift`` is a tuple, then ``axis`` must be a tuple of the same size, and each of the given axes must be shifted by the corresponding element in ``shift``. If ``shift`` is an ``int`` and ``axis`` a tuple, then the same ``shift`` must be used for all specified axes. If a shift is positive, then array elements must be shifted positively (toward larger indices) along the dimension of ``axis``. If a shift is negative, then array elements must be shifted negatively (toward smaller indices) along the dimension of ``axis``. + number of places by which the elements are shifted. If ``shift`` is a tuple, then ``axis`` must be a tuple of the same size, and each of the given axes must be shifted by the corresponding element in ``shift``. If ``shift`` is an ``int`` and ``axis`` a tuple, then the same ``shift`` must be used for all specified axes. If a shift is positive, then array elements must be shifted positively (toward larger indices) along the dimension of ``axis``. If a shift is negative, then array elements must be shifted negatively (toward smaller indices) along the dimension of ``axis``. axis: Optional[Union[int, Tuple[int, ...]]] - axis (or axes) along which elements to shift. If ``axis`` is ``None``, the array must be flattened, shifted, and then restored to its original shape. Default: ``None``. + axis (or axes) along which elements to shift. If ``axis`` is ``None``, the array must be flattened, shifted, and then restored to its original shape. Default: ``None``. Returns ------- out: array - an output array having the same data type as ``x`` and whose elements, relative to ``x``, are shifted. + an output array having the same data type as ``x`` and whose elements, relative to ``x``, are shifted. """ @@ -7895,20 +7899,20 @@ class squeeze[TArray: Array](Protocol): Parameters ---------- x: array - input array. + input array. axis: Union[int, Tuple[int, ...]] - axis (or axes) to squeeze. + axis (or axes) to squeeze. Returns ------- out: array - an output array having the same data type and elements as ``x``. + an output array having the same data type and elements as ``x``. Raises ------ ValueError - If a specified axis has a size greater than one (i.e., it is not a - singleton dimension), a ``ValueError`` should be raised. + If a specified axis has a size greater than one (i.e., it is not a + singleton dimension), a ``ValueError`` should be raised. """ @@ -7924,17 +7928,17 @@ class stack[TArray: Array](Protocol): Parameters ---------- arrays: Union[Tuple[array, ...], List[array]] - input arrays to join. Each array must have the same shape. + input arrays to join. Each array must have the same shape. axis: int - axis along which the arrays will be joined. Providing an ``axis`` specifies the index of the new axis in the dimensions of the result. For example, if ``axis`` is ``0``, the new axis will be the first dimension and the output array will have shape ``(N, A, B, C)``; if ``axis`` is ``1``, the new axis will be the second dimension and the output array will have shape ``(A, N, B, C)``; and, if ``axis`` is ``-1``, the new axis will be the last dimension and the output array will have shape ``(A, B, C, N)``. A valid ``axis`` must be on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If provided an ``axis`` outside of the required interval, the function must raise an exception. Default: ``0``. + axis along which the arrays will be joined. Providing an ``axis`` specifies the index of the new axis in the dimensions of the result. For example, if ``axis`` is ``0``, the new axis will be the first dimension and the output array will have shape ``(N, A, B, C)``; if ``axis`` is ``1``, the new axis will be the second dimension and the output array will have shape ``(A, N, B, C)``; and, if ``axis`` is ``-1``, the new axis will be the last dimension and the output array will have shape ``(A, B, C, N)``. A valid ``axis`` must be on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If provided an ``axis`` outside of the required interval, the function must raise an exception. Default: ``0``. Returns ------- out: array - an output array having rank ``N+1``, where ``N`` is the rank (number of dimensions) of ``x``. If the input arrays have different data types, normal :ref:`type-promotion` must apply. If the input arrays have the same data type, the output array must have the same data type as the input arrays. + an output array having rank ``N+1``, where ``N`` is the rank (number of dimensions) of ``x``. If the input arrays have different data types, normal :ref:`type-promotion` must apply. If the input arrays have the same data type, the output array must have the same data type as the input arrays. - .. note:: - This specification leaves type promotion between data type families (i.e., ``intxx`` and ``floatxx``) unspecified. + .. note:: + This specification leaves type promotion between data type families (i.e., ``intxx`` and ``floatxx``) unspecified. """ @@ -7950,20 +7954,20 @@ class tile[TArray: Array](Protocol): Parameters ---------- x: array - input array. + input array. repetitions: Tuple[int, ...] - number of repetitions along each axis (dimension). + number of repetitions along each axis (dimension). - Let ``N = len(x.shape)`` and ``M = len(repetitions)``. + Let ``N = len(x.shape)`` and ``M = len(repetitions)``. - If ``N > M``, the function must prepend ones until all axes (dimensions) are specified (e.g., if ``x`` has shape ``(8,6,4,2)`` and ``repetitions`` is the tuple ``(3,3)``, then ``repetitions`` must be treated as ``(1,1,3,3)``). + If ``N > M``, the function must prepend ones until all axes (dimensions) are specified (e.g., if ``x`` has shape ``(8,6,4,2)`` and ``repetitions`` is the tuple ``(3,3)``, then ``repetitions`` must be treated as ``(1,1,3,3)``). - If ``N < M``, the function must prepend singleton axes (dimensions) to ``x`` until ``x`` has as many axes (dimensions) as ``repetitions`` specifies (e.g., if ``x`` has shape ``(4,2)`` and ``repetitions`` is the tuple ``(3,3,3,3)``, then ``x`` must be treated as if it has shape ``(1,1,4,2)``). + If ``N < M``, the function must prepend singleton axes (dimensions) to ``x`` until ``x`` has as many axes (dimensions) as ``repetitions`` specifies (e.g., if ``x`` has shape ``(4,2)`` and ``repetitions`` is the tuple ``(3,3,3,3)``, then ``x`` must be treated as if it has shape ``(1,1,4,2)``). Returns ------- out: array - a tiled output array. The returned array must have the same data type as ``x`` and must have a rank (i.e., number of dimensions) equal to ``max(N, M)``. If ``S`` is the shape of the tiled array after prepending singleton dimensions (if necessary) and ``r`` is the tuple of repetitions after prepending ones (if necessary), then the number of elements along each axis (dimension) must satisfy ``S[i]*r[i]``, where ``i`` refers to the ``i`` th axis (dimension). + a tiled output array. The returned array must have the same data type as ``x`` and must have a rank (i.e., number of dimensions) equal to ``max(N, M)``. If ``S`` is the shape of the tiled array after prepending singleton dimensions (if necessary) and ``r`` is the tuple of repetitions after prepending ones (if necessary), then the number of elements along each axis (dimension) must satisfy ``S[i]*r[i]``, where ``i`` refers to the ``i`` th axis (dimension). Notes ----- @@ -7984,14 +7988,14 @@ class unstack[TArray: Array](Protocol): Parameters ---------- x: array - input array. + input array. axis: int - axis along which the array will be split. A valid ``axis`` must be on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If provided an ``axis`` outside of the required interval, the function must raise an exception. Default: ``0``. + axis along which the array will be split. A valid ``axis`` must be on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If provided an ``axis`` outside of the required interval, the function must raise an exception. Default: ``0``. Returns ------- out: Tuple[array, ...] - tuple of slices along the given dimension. All the arrays have the same shape. + tuple of slices along the given dimension. All the arrays have the same shape. Notes ----- @@ -8010,47 +8014,47 @@ class unique_all[TArray: Array](Protocol): Returns the unique elements of an input array ``x``, the first occurring indices for each unique element in ``x``, the indices from the set of unique elements that reconstruct ``x``, and the corresponding counts for each unique element in ``x``. .. admonition:: Data-dependent output shape - :class: important + :class: important - The shapes of two of the output arrays for this function depend on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) may find this function difficult to implement without knowing array values. Accordingly, such libraries may choose to omit this function. See :ref:`data-dependent-output-shapes` section for more details. + The shapes of two of the output arrays for this function depend on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) may find this function difficult to implement without knowing array values. Accordingly, such libraries may choose to omit this function. See :ref:`data-dependent-output-shapes` section for more details. .. note:: - Uniqueness should be determined based on value equality (see :func:`~array_api.equal`). For input arrays having floating-point data types, value-based equality implies the following behavior. + Uniqueness should be determined based on value equality (see :func:`~array_api.equal`). For input arrays having floating-point data types, value-based equality implies the following behavior. - - As ``nan`` values compare as ``False``, ``nan`` values should be considered distinct. - - As complex floating-point values having at least one ``nan`` component compare as ``False``, complex floating-point values having ``nan`` components should be considered distinct. - - As ``-0`` and ``+0`` compare as ``True``, signed zeros should not be considered distinct, and the corresponding unique element will be implementation-dependent (e.g., an implementation could choose to return ``-0`` if ``-0`` occurs before ``+0``). + - As ``nan`` values compare as ``False``, ``nan`` values should be considered distinct. + - As complex floating-point values having at least one ``nan`` component compare as ``False``, complex floating-point values having ``nan`` components should be considered distinct. + - As ``-0`` and ``+0`` compare as ``True``, signed zeros should not be considered distinct, and the corresponding unique element will be implementation-dependent (e.g., an implementation could choose to return ``-0`` if ``-0`` occurs before ``+0``). - As signed zeros are not distinct, using ``inverse_indices`` to reconstruct the input array is not guaranteed to return an array having the exact same values. + As signed zeros are not distinct, using ``inverse_indices`` to reconstruct the input array is not guaranteed to return an array having the exact same values. - Each ``nan`` value and each complex floating-point value having a ``nan`` component should have a count of one, while the counts for signed zeros should be aggregated as a single count. + Each ``nan`` value and each complex floating-point value having a ``nan`` component should have a count of one, while the counts for signed zeros should be aggregated as a single count. Parameters ---------- x: array - input array. If ``x`` has more than one dimension, the function must flatten ``x`` and return the unique elements of the flattened array. + input array. If ``x`` has more than one dimension, the function must flatten ``x`` and return the unique elements of the flattened array. Returns ------- out: Tuple[array, array, array, array] - a namedtuple ``(values, indices, inverse_indices, counts)`` whose + a namedtuple ``(values, indices, inverse_indices, counts)`` whose - - first element must have the field name ``values`` and must be a one-dimensional array containing the unique elements of ``x``. The array must have the same data type as ``x``. - - second element must have the field name ``indices`` and must be an array containing the indices (first occurrences) of a flattened ``x`` that result in ``values``. The array must have the same shape as ``values`` and must have the default array index data type. - - third element must have the field name ``inverse_indices`` and must be an array containing the indices of ``values`` that reconstruct ``x``. The array must have the same shape as ``x`` and must have the default array index data type. - - fourth element must have the field name ``counts`` and must be an array containing the number of times each unique element occurs in ``x``. The order of the returned counts must match the order of ``values``, such that a specific element in ``counts`` corresponds to the respective unique element in ``values``. The returned array must have same shape as ``values`` and must have the default array index data type. + - first element must have the field name ``values`` and must be a one-dimensional array containing the unique elements of ``x``. The array must have the same data type as ``x``. + - second element must have the field name ``indices`` and must be an array containing the indices (first occurrences) of a flattened ``x`` that result in ``values``. The array must have the same shape as ``values`` and must have the default array index data type. + - third element must have the field name ``inverse_indices`` and must be an array containing the indices of ``values`` that reconstruct ``x``. The array must have the same shape as ``x`` and must have the default array index data type. + - fourth element must have the field name ``counts`` and must be an array containing the number of times each unique element occurs in ``x``. The order of the returned counts must match the order of ``values``, such that a specific element in ``counts`` corresponds to the respective unique element in ``values``. The returned array must have same shape as ``values`` and must have the default array index data type. - .. note:: - The order of unique elements is not specified and may vary between implementations. + .. note:: + The order of unique elements is not specified and may vary between implementations. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. .. versionchanged:: 2023.12 - Clarified flattening behavior and required the order of ``counts`` match the order of ``values``. + Clarified flattening behavior and required the order of ``counts`` match the order of ``values``. """ @@ -8064,43 +8068,43 @@ class unique_counts[TArray: Array](Protocol): Returns the unique elements of an input array ``x`` and the corresponding counts for each unique element in ``x``. .. admonition:: Data-dependent output shape - :class: important + :class: important - The shapes of two of the output arrays for this function depend on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) may find this function difficult to implement without knowing array values. Accordingly, such libraries may choose to omit this function. See :ref:`data-dependent-output-shapes` section for more details. + The shapes of two of the output arrays for this function depend on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) may find this function difficult to implement without knowing array values. Accordingly, such libraries may choose to omit this function. See :ref:`data-dependent-output-shapes` section for more details. .. note:: - Uniqueness should be determined based on value equality (see :func:`~array_api.equal`). For input arrays having floating-point data types, value-based equality implies the following behavior. + Uniqueness should be determined based on value equality (see :func:`~array_api.equal`). For input arrays having floating-point data types, value-based equality implies the following behavior. - - As ``nan`` values compare as ``False``, ``nan`` values should be considered distinct. - - As complex floating-point values having at least one ``nan`` component compare as ``False``, complex floating-point values having ``nan`` components should be considered distinct. - - As ``-0`` and ``+0`` compare as ``True``, signed zeros should not be considered distinct, and the corresponding unique element will be implementation-dependent (e.g., an implementation could choose to return ``-0`` if ``-0`` occurs before ``+0``). + - As ``nan`` values compare as ``False``, ``nan`` values should be considered distinct. + - As complex floating-point values having at least one ``nan`` component compare as ``False``, complex floating-point values having ``nan`` components should be considered distinct. + - As ``-0`` and ``+0`` compare as ``True``, signed zeros should not be considered distinct, and the corresponding unique element will be implementation-dependent (e.g., an implementation could choose to return ``-0`` if ``-0`` occurs before ``+0``). - Each ``nan`` value and each complex floating-point value having a ``nan`` component should have a count of one, while the counts for signed zeros should be aggregated as a single count. + Each ``nan`` value and each complex floating-point value having a ``nan`` component should have a count of one, while the counts for signed zeros should be aggregated as a single count. Parameters ---------- x: array - input array. If ``x`` has more than one dimension, the function must flatten ``x`` and return the unique elements of the flattened array. + input array. If ``x`` has more than one dimension, the function must flatten ``x`` and return the unique elements of the flattened array. Returns ------- out: Tuple[array, array] - a namedtuple `(values, counts)` whose + a namedtuple `(values, counts)` whose - - first element must have the field name ``values`` and must be a one-dimensional array containing the unique elements of ``x``. The array must have the same data type as ``x``. - - second element must have the field name `counts` and must be an array containing the number of times each unique element occurs in ``x``. The order of the returned counts must match the order of ``values``, such that a specific element in ``counts`` corresponds to the respective unique element in ``values``. The returned array must have same shape as ``values`` and must have the default array index data type. + - first element must have the field name ``values`` and must be a one-dimensional array containing the unique elements of ``x``. The array must have the same data type as ``x``. + - second element must have the field name `counts` and must be an array containing the number of times each unique element occurs in ``x``. The order of the returned counts must match the order of ``values``, such that a specific element in ``counts`` corresponds to the respective unique element in ``values``. The returned array must have same shape as ``values`` and must have the default array index data type. - .. note:: - The order of unique elements is not specified and may vary between implementations. + .. note:: + The order of unique elements is not specified and may vary between implementations. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. .. versionchanged:: 2023.12 - Clarified flattening behavior and required the order of ``counts`` match the order of ``values``. + Clarified flattening behavior and required the order of ``counts`` match the order of ``values``. """ @@ -8114,43 +8118,43 @@ class unique_inverse[TArray: Array](Protocol): Returns the unique elements of an input array ``x`` and the indices from the set of unique elements that reconstruct ``x``. .. admonition:: Data-dependent output shape - :class: important + :class: important - The shapes of two of the output arrays for this function depend on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) may find this function difficult to implement without knowing array values. Accordingly, such libraries may choose to omit this function. See :ref:`data-dependent-output-shapes` section for more details. + The shapes of two of the output arrays for this function depend on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) may find this function difficult to implement without knowing array values. Accordingly, such libraries may choose to omit this function. See :ref:`data-dependent-output-shapes` section for more details. .. note:: - Uniqueness should be determined based on value equality (see :func:`~array_api.equal`). For input arrays having floating-point data types, value-based equality implies the following behavior. + Uniqueness should be determined based on value equality (see :func:`~array_api.equal`). For input arrays having floating-point data types, value-based equality implies the following behavior. - - As ``nan`` values compare as ``False``, ``nan`` values should be considered distinct. - - As complex floating-point values having at least one ``nan`` component compare as ``False``, complex floating-point values having ``nan`` components should be considered distinct. - - As ``-0`` and ``+0`` compare as ``True``, signed zeros should not be considered distinct, and the corresponding unique element will be implementation-dependent (e.g., an implementation could choose to return ``-0`` if ``-0`` occurs before ``+0``). + - As ``nan`` values compare as ``False``, ``nan`` values should be considered distinct. + - As complex floating-point values having at least one ``nan`` component compare as ``False``, complex floating-point values having ``nan`` components should be considered distinct. + - As ``-0`` and ``+0`` compare as ``True``, signed zeros should not be considered distinct, and the corresponding unique element will be implementation-dependent (e.g., an implementation could choose to return ``-0`` if ``-0`` occurs before ``+0``). - As signed zeros are not distinct, using ``inverse_indices`` to reconstruct the input array is not guaranteed to return an array having the exact same values. + As signed zeros are not distinct, using ``inverse_indices`` to reconstruct the input array is not guaranteed to return an array having the exact same values. Parameters ---------- x: array - input array. If ``x`` has more than one dimension, the function must flatten ``x`` and return the unique elements of the flattened array. + input array. If ``x`` has more than one dimension, the function must flatten ``x`` and return the unique elements of the flattened array. Returns ------- out: Tuple[array, array] - a namedtuple ``(values, inverse_indices)`` whose + a namedtuple ``(values, inverse_indices)`` whose - - first element must have the field name ``values`` and must be a one-dimensional array containing the unique elements of ``x``. The array must have the same data type as ``x``. - - second element must have the field name ``inverse_indices`` and must be an array containing the indices of ``values`` that reconstruct ``x``. The array must have the same shape as ``x`` and have the default array index data type. + - first element must have the field name ``values`` and must be a one-dimensional array containing the unique elements of ``x``. The array must have the same data type as ``x``. + - second element must have the field name ``inverse_indices`` and must be an array containing the indices of ``values`` that reconstruct ``x``. The array must have the same shape as ``x`` and have the default array index data type. - .. note:: - The order of unique elements is not specified and may vary between implementations. + .. note:: + The order of unique elements is not specified and may vary between implementations. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. .. versionchanged:: 2023.12 - Clarified flattening behavior. + Clarified flattening behavior. """ @@ -8164,38 +8168,38 @@ class unique_values[TArray: Array](Protocol): Returns the unique elements of an input array ``x``. .. admonition:: Data-dependent output shape - :class: important + :class: important - The shapes of two of the output arrays for this function depend on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) may find this function difficult to implement without knowing array values. Accordingly, such libraries may choose to omit this function. See :ref:`data-dependent-output-shapes` section for more details. + The shapes of two of the output arrays for this function depend on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) may find this function difficult to implement without knowing array values. Accordingly, such libraries may choose to omit this function. See :ref:`data-dependent-output-shapes` section for more details. .. note:: - Uniqueness should be determined based on value equality (see :func:`~array_api.equal`). For input arrays having floating-point data types, value-based equality implies the following behavior. + Uniqueness should be determined based on value equality (see :func:`~array_api.equal`). For input arrays having floating-point data types, value-based equality implies the following behavior. - - As ``nan`` values compare as ``False``, ``nan`` values should be considered distinct. - - As complex floating-point values having at least one ``nan`` component compare as ``False``, complex floating-point values having ``nan`` components should be considered distinct. - - As ``-0`` and ``+0`` compare as ``True``, signed zeros should not be considered distinct, and the corresponding unique element will be implementation-dependent (e.g., an implementation could choose to return ``-0`` if ``-0`` occurs before ``+0``). + - As ``nan`` values compare as ``False``, ``nan`` values should be considered distinct. + - As complex floating-point values having at least one ``nan`` component compare as ``False``, complex floating-point values having ``nan`` components should be considered distinct. + - As ``-0`` and ``+0`` compare as ``True``, signed zeros should not be considered distinct, and the corresponding unique element will be implementation-dependent (e.g., an implementation could choose to return ``-0`` if ``-0`` occurs before ``+0``). Parameters ---------- x: array - input array. If ``x`` has more than one dimension, the function must flatten ``x`` and return the unique elements of the flattened array. + input array. If ``x`` has more than one dimension, the function must flatten ``x`` and return the unique elements of the flattened array. Returns ------- out: array - a one-dimensional array containing the set of unique elements in ``x``. The returned array must have the same data type as ``x``. + a one-dimensional array containing the set of unique elements in ``x``. The returned array must have the same data type as ``x``. - .. note:: - The order of unique elements is not specified and may vary between implementations. + .. note:: + The order of unique elements is not specified and may vary between implementations. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. .. versionchanged:: 2023.12 - Required that the output array must be one-dimensional. + Required that the output array must be one-dimensional. """ @@ -8204,7 +8208,7 @@ def __call__(self, x: TArray, /) -> TArray: ... @runtime_checkable -class ArrayNamespace[TCapabilities, TDatatypes, TDefaultdatatypes, TSupportsbufferprotocol, TArray: Array, TDevice, TDtype](Protocol): +class ArrayNamespace[TArray: Array, TCapabilities, TDatatypes, TDefaultdatatypes, TDevice, TDtype](Protocol): astype: astype[TArray, TDevice, TDtype] "Copies an array to a specified data type irrespective of :ref:`type-promotion` rules.\n\n.. note::\n Casting floating-point ``NaN`` and ``infinity`` values to integral data types is not specified and is implementation-dependent.\n\n.. note::\n Casting a complex floating-point array to a real-valued data type should not be permitted.\n\n Historically, when casting a complex floating-point array to a real-valued data type, libraries such as NumPy have discarded imaginary components such that, for a complex floating-point array ``x``, ``astype(x)`` equals ``astype(real(x))``). This behavior is considered problematic as the choice to discard the imaginary component is arbitrary and introduces more than one way to achieve the same outcome (i.e., for a complex floating-point array ``x``, ``astype(x)`` and ``astype(real(x))`` versus only ``astype(imag(x))``). Instead, in order to avoid ambiguity and to promote clarity, this specification requires that array API consumers explicitly express which component should be cast to a specified real-valued data type.\n\n.. note::\n When casting a boolean input array to a real-valued data type, a value of ``True`` must cast to a real-valued number equal to ``1``, and a value of ``False`` must cast to a real-valued number equal to ``0``.\n\n When casting a boolean input array to a complex floating-point data type, a value of ``True`` must cast to a complex number equal to ``1 + 0j``, and a value of ``False`` must cast to a complex number equal to ``0 + 0j``.\n\n.. note::\n When casting a real-valued input array to ``bool``, a value of ``0`` must cast to ``False``, and a non-zero value must cast to ``True``.\n\n When casting a complex floating-point array to ``bool``, a value of ``0 + 0j`` must cast to ``False``, and all other values must cast to ``True``.\n\nParameters\n----------\nx: array\n array to cast.\ndtype: dtype\n desired data type.\ncopy: bool\n specifies whether to copy an array when the specified ``dtype`` matches the data type of the input array ``x``. If ``True``, a newly allocated array must always be returned. If ``False`` and the specified ``dtype`` matches the data type of the input array, the input array must be returned; otherwise, a newly allocated array must be returned. Default: ``True``.\ndevice: Optional[device]\n device on which to place the returned array. If ``device`` is ``None``, the output array device must be inferred from ``x``. Default: ``None``.\n\nReturns\n-------\nout: array\n an array having the specified data type. The returned array must have the same shape as ``x``.\n\nNotes\n-----\n\n.. versionchanged:: 2022.12\n Added complex data type support.\n\n.. versionchanged:: 2023.12\n Added device keyword argument support." can_cast: can_cast[TArray, TDtype] @@ -8235,7 +8239,7 @@ class ArrayNamespace[TCapabilities, TDatatypes, TDefaultdatatypes, TSupportsbuff "Calculates the variance of the input array ``x``.\n\nParameters\n----------\nx: array\n input array. Should have a real-valued floating-point data type.\naxis: Optional[Union[int, Tuple[int, ...]]]\n axis or axes along which variances must be computed. By default, the variance must be computed over the entire array. If a tuple of integers, variances must be computed over multiple axes. Default: ``None``.\ncorrection: Union[int, float]\n degrees of freedom adjustment. Setting this parameter to a value other than ``0`` has the effect of adjusting the divisor during the calculation of the variance according to ``N-c`` where ``N`` corresponds to the total number of elements over which the variance is computed and ``c`` corresponds to the provided degrees of freedom adjustment. When computing the variance of a population, setting this parameter to ``0`` is the standard choice (i.e., the provided array contains data constituting an entire population). When computing the unbiased sample variance, setting this parameter to ``1`` is the standard choice (i.e., the provided array contains data sampled from a larger population; this is commonly referred to as Bessel's correction). Default: ``0``.\nkeepdims: bool\n if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``.\n\nReturns\n-------\nout: array\n if the variance was computed over the entire array, a zero-dimensional array containing the variance; otherwise, a non-zero-dimensional array containing the variances. The returned array must have the same data type as ``x``.\n\n\n.. note::\n While this specification recommends that this function only accept input arrays having a real-valued floating-point data type, specification-compliant array libraries may choose to accept input arrays having an integer data type. While mixed data type promotion is implementation-defined, if the input array ``x`` has an integer data type, the returned array must have the default real-valued floating-point data type.\n\nNotes\n-----\n\n**Special Cases**\n\nLet ``N`` equal the number of elements over which to compute the variance.\n\n- If ``N - correction`` is less than or equal to ``0``, the variance is ``NaN``.\n- If ``x_i`` is ``NaN``, the variance is ``NaN`` (i.e., ``NaN`` values propagate)." arange: arange[TArray, TDevice, TDtype] "Returns evenly spaced values within the half-open interval ``[start, stop)`` as a one-dimensional array.\n\nParameters\n----------\nstart: Union[int, float]\n if ``stop`` is specified, the start of interval (inclusive); otherwise, the end of the interval (exclusive). If ``stop`` is not specified, the default starting value is ``0``.\nstop: Optional[Union[int, float]]\n the end of the interval. Default: ``None``.\nstep: Union[int, float]\n the distance between two adjacent elements (``out[i+1] - out[i]``). Must not be ``0``; may be negative, this results in an empty array if ``stop >= start``. Default: ``1``.\ndtype: Optional[dtype]\n output array data type. If ``dtype`` is ``None``, the output array data type must be inferred from ``start``, ``stop`` and ``step``. If those are all integers, the output array dtype must be the default integer dtype; if one or more have type ``float``, then the output array dtype must be the default real-valued floating-point data type. Default: ``None``.\ndevice: Optional[device]\n device on which to place the created array. Default: ``None``.\n\n\n.. note::\n This function cannot guarantee that the interval does not include the ``stop`` value in those cases where ``step`` is not an integer and floating-point rounding errors affect the length of the output array.\n\nReturns\n-------\nout: array\n a one-dimensional array containing evenly spaced values. The length of the output array must be ``ceil((stop-start)/step)`` if ``stop - start`` and ``step`` have the same sign, and length ``0`` otherwise." - asarray: asarray[TSupportsbufferprotocol, TArray, TDevice, TDtype] + asarray: asarray[TArray, TDevice, TDtype] "Convert the input to an array.\n\nParameters\n----------\nobj: Union[array, bool, int, float, complex, NestedSequence[bool | int | float | complex], SupportsBufferProtocol]\n object to be converted to an array. May be a Python scalar, a (possibly nested) sequence of Python scalars, or an object supporting the Python buffer protocol.\n\n .. admonition:: Tip\n :class: important\n\n An object supporting the buffer protocol can be turned into a memoryview through ``memoryview(obj)``.\n\ndtype: Optional[dtype]\n output array data type. If ``dtype`` is ``None``, the output array data type must be inferred from the data type(s) in ``obj``. If all input values are Python scalars, then, in order of precedence,\n\n - if all values are of type ``bool``, the output data type must be ``bool``.\n - if all values are of type ``int`` or are a mixture of ``bool`` and ``int``, the output data type must be the default integer data type.\n - if one or more values are ``complex`` numbers, the output data type must be the default complex floating-point data type.\n - if one or more values are ``float``\\s, the output data type must be the default real-valued floating-point data type.\n\n Default: ``None``.\n\n .. admonition:: Note\n :class: note\n\n If ``dtype`` is not ``None``, then array conversions should obey :ref:`type-promotion` rules. Conversions not specified according to :ref:`type-promotion` rules may or may not be permitted by a conforming array library. To perform an explicit cast, use :func:`array_api.astype`.\n\n .. note::\n If an input value exceeds the precision of the resolved output array data type, behavior is left unspecified and, thus, implementation-defined.\n\ndevice: Optional[device]\n device on which to place the created array. If ``device`` is ``None`` and ``obj`` is an array, the output array device must be inferred from ``obj``. Default: ``None``.\ncopy: Optional[bool]\n boolean indicating whether or not to copy the input. If ``True``, the function must always copy. If ``False``, the function must never copy for input which supports the buffer protocol and must raise a ``ValueError`` in case a copy would be necessary. If ``None``, the function must reuse existing memory buffer if possible and copy otherwise. Default: ``None``.\n\nReturns\n-------\nout: array\n an array containing the data from ``obj``.\n\nNotes\n-----\n\n.. versionchanged:: 2022.12\n Added complex data type support." empty: empty[TArray, TDevice, TDtype] "Returns an uninitialized array having a specified `shape`.\n\nParameters\n----------\nshape: Union[int, Tuple[int, ...]]\n output array shape.\ndtype: Optional[dtype]\n output array data type. If ``dtype`` is ``None``, the output array data type must be the default real-valued floating-point data type. Default: ``None``.\ndevice: Optional[device]\n device on which to place the created array. Default: ``None``.\n\nReturns\n-------\nout: array\n an array containing uninitialized data." @@ -8413,7 +8417,7 @@ class ArrayNamespace[TCapabilities, TDatatypes, TDefaultdatatypes, TSupportsbuff "Tests whether all input array elements evaluate to ``True`` along a specified axis.\n\n.. note::\n Positive infinity, negative infinity, and NaN must evaluate to ``True``.\n\n.. note::\n If ``x`` has a complex floating-point data type, elements having a non-zero component (real or imaginary) must evaluate to ``True``.\n\n.. note::\n If ``x`` is an empty array or the size of the axis (dimension) along which to evaluate elements is zero, the test result must be ``True``.\n\nParameters\n----------\nx: array\n input array.\naxis: Optional[Union[int, Tuple[int, ...]]]\n axis or axes along which to perform a logical AND reduction. By default, a logical AND reduction must be performed over the entire array. If a tuple of integers, logical AND reductions must be performed over multiple axes. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to perform a reduction by counting backward from the last dimension (where ``-1`` refers to the last dimension). If provided an invalid ``axis``, the function must raise an exception. Default: ``None``.\nkeepdims: bool\n If ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``.\n\nReturns\n-------\nout: array\n if a logical AND reduction was performed over the entire array, the returned array must be a zero-dimensional array containing the test result; otherwise, the returned array must be a non-zero-dimensional array containing the test results. The returned array must have a data type of ``bool``.\n\nNotes\n-----\n\n.. versionchanged:: 2022.12\n Added complex data type support." any: any[TArray,] "Tests whether any input array element evaluates to ``True`` along a specified axis.\n\n.. note::\n Positive infinity, negative infinity, and NaN must evaluate to ``True``.\n\n.. note::\n If ``x`` has a complex floating-point data type, elements having a non-zero component (real or imaginary) must evaluate to ``True``.\n\n.. note::\n If ``x`` is an empty array or the size of the axis (dimension) along which to evaluate elements is zero, the test result must be ``False``.\n\nParameters\n----------\nx: array\n input array.\naxis: Optional[Union[int, Tuple[int, ...]]]\n axis or axes along which to perform a logical OR reduction. By default, a logical OR reduction must be performed over the entire array. If a tuple of integers, logical OR reductions must be performed over multiple axes. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to perform a reduction by counting backward from the last dimension (where ``-1`` refers to the last dimension). If provided an invalid ``axis``, the function must raise an exception. Default: ``None``.\nkeepdims: bool\n If ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``.\n\nReturns\n-------\nout: array\n if a logical OR reduction was performed over the entire array, the returned array must be a zero-dimensional array containing the test result; otherwise, the returned array must be a non-zero-dimensional array containing the test results. The returned array must have a data type of ``bool``.\n\nNotes\n-----\n\n.. versionchanged:: 2022.12\n Added complex data type support." - __array_namespace_info__: __array_namespace_info__[TCapabilities, TDatatypes, TDefaultdatatypes, TArray, TDevice, TDtype] + __array_namespace_info__: __array_namespace_info__[TArray, TCapabilities, TDatatypes, TDefaultdatatypes, TDevice, TDtype] "Returns a namespace with Array API namespace inspection utilities.\n\nSee :ref:`inspection` for a list of inspection APIs.\n\nReturns\n-------\nout: Info\n An object containing Array API namespace inspection utilities.\n\nNotes\n-----\n\nThe returned object may be either a namespace or a class, so long as an Array API user can access inspection utilities as follows:\n\n::\n\n info = xp.__array_namespace_info__()\n info.capabilities()\n info.devices()\n info.dtypes()\n info.default_dtypes()\n # ...\n\n.. versionadded: 2023.12" take: take[TArray,] "Returns elements of an array along an axis.\n\n.. note::\n Conceptually, ``take(x, indices, axis=3)`` is equivalent to ``x[:,:,:,indices,...]``; however, explicit indexing via arrays of indices is not currently supported in this specification due to concerns regarding ``__setitem__`` and array mutation semantics.\n\nParameters\n----------\nx: array\n input array.\nindices: array\n array indices. The array must be one-dimensional and have an integer data type.\n\n .. note::\n This specification does not require bounds checking. The behavior for out-of-bounds indices is left unspecified.\n\naxis: Optional[int]\n axis over which to select values. If ``axis`` is negative, the function must determine the axis along which to select values by counting from the last dimension.\n\n If ``x`` is a one-dimensional array, providing an ``axis`` is optional; however, if ``x`` has more than one dimension, providing an ``axis`` is required.\n\nReturns\n-------\nout: array\n an array having the same data type as ``x``. The output array must have the same rank (i.e., number of dimensions) as ``x`` and must have the same shape as ``x``, except for the axis specified by ``axis`` whose size must equal the number of elements in ``indices``.\n\nNotes\n-----\n\n.. versionadded:: 2022.12\n\n.. versionchanged:: 2023.12\n Out-of-bounds behavior is explicitly left unspecified." @@ -8453,15 +8457,15 @@ class ArrayNamespace[TCapabilities, TDatatypes, TDefaultdatatypes, TSupportsbuff "Constructs an array by tiling an input array.\n\nParameters\n----------\nx: array\n input array.\nrepetitions: Tuple[int, ...]\n number of repetitions along each axis (dimension).\n\n Let ``N = len(x.shape)`` and ``M = len(repetitions)``.\n\n If ``N > M``, the function must prepend ones until all axes (dimensions) are specified (e.g., if ``x`` has shape ``(8,6,4,2)`` and ``repetitions`` is the tuple ``(3,3)``, then ``repetitions`` must be treated as ``(1,1,3,3)``).\n\n If ``N < M``, the function must prepend singleton axes (dimensions) to ``x`` until ``x`` has as many axes (dimensions) as ``repetitions`` specifies (e.g., if ``x`` has shape ``(4,2)`` and ``repetitions`` is the tuple ``(3,3,3,3)``, then ``x`` must be treated as if it has shape ``(1,1,4,2)``).\n\nReturns\n-------\nout: array\n a tiled output array. The returned array must have the same data type as ``x`` and must have a rank (i.e., number of dimensions) equal to ``max(N, M)``. If ``S`` is the shape of the tiled array after prepending singleton dimensions (if necessary) and ``r`` is the tuple of repetitions after prepending ones (if necessary), then the number of elements along each axis (dimension) must satisfy ``S[i]*r[i]``, where ``i`` refers to the ``i`` th axis (dimension).\n\nNotes\n-----\n\n.. versionadded:: 2023.12" unstack: unstack[TArray,] "Splits an array into a sequence of arrays along the given axis.\n\nParameters\n----------\nx: array\n input array.\naxis: int\n axis along which the array will be split. A valid ``axis`` must be on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If provided an ``axis`` outside of the required interval, the function must raise an exception. Default: ``0``.\n\nReturns\n-------\nout: Tuple[array, ...]\n tuple of slices along the given dimension. All the arrays have the same shape.\n\nNotes\n-----\n\n.. versionadded:: 2023.12" - e: float + e: TArray "\nIEEE 754 floating-point representation of Euler's constant.\n\n``e = 2.71828182845904523536028747135266249775724709369995...``\n" - inf: float + inf: TArray "\nIEEE 754 floating-point representation of (positive) infinity.\n" - nan: float + nan: TArray "\nIEEE 754 floating-point representation of Not a Number (``NaN``).\n" - newaxis: float + newaxis: TArray "\nAn alias for ``None`` which is useful for indexing arrays.\n" - pi: float + pi: TArray "\nIEEE 754 floating-point representation of the mathematical constant ``π``.\n\n``pi = 3.1415926535897932384626433...``\n" unique_all: unique_all[TArray,] "Returns the unique elements of an input array ``x``, the first occurring indices for each unique element in ``x``, the indices from the set of unique elements that reconstruct ``x``, and the corresponding counts for each unique element in ``x``.\n\n.. admonition:: Data-dependent output shape\n :class: important\n\n The shapes of two of the output arrays for this function depend on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) may find this function difficult to implement without knowing array values. Accordingly, such libraries may choose to omit this function. See :ref:`data-dependent-output-shapes` section for more details.\n\n.. note::\n Uniqueness should be determined based on value equality (see :func:`~array_api.equal`). For input arrays having floating-point data types, value-based equality implies the following behavior.\n\n - As ``nan`` values compare as ``False``, ``nan`` values should be considered distinct.\n - As complex floating-point values having at least one ``nan`` component compare as ``False``, complex floating-point values having ``nan`` components should be considered distinct.\n - As ``-0`` and ``+0`` compare as ``True``, signed zeros should not be considered distinct, and the corresponding unique element will be implementation-dependent (e.g., an implementation could choose to return ``-0`` if ``-0`` occurs before ``+0``).\n\n As signed zeros are not distinct, using ``inverse_indices`` to reconstruct the input array is not guaranteed to return an array having the exact same values.\n\n Each ``nan`` value and each complex floating-point value having a ``nan`` component should have a count of one, while the counts for signed zeros should be aggregated as a single count.\n\nParameters\n----------\nx: array\n input array. If ``x`` has more than one dimension, the function must flatten ``x`` and return the unique elements of the flattened array.\n\nReturns\n-------\nout: Tuple[array, array, array, array]\n a namedtuple ``(values, indices, inverse_indices, counts)`` whose\n\n - first element must have the field name ``values`` and must be a one-dimensional array containing the unique elements of ``x``. The array must have the same data type as ``x``.\n - second element must have the field name ``indices`` and must be an array containing the indices (first occurrences) of a flattened ``x`` that result in ``values``. The array must have the same shape as ``values`` and must have the default array index data type.\n - third element must have the field name ``inverse_indices`` and must be an array containing the indices of ``values`` that reconstruct ``x``. The array must have the same shape as ``x`` and must have the default array index data type.\n - fourth element must have the field name ``counts`` and must be an array containing the number of times each unique element occurs in ``x``. The order of the returned counts must match the order of ``values``, such that a specific element in ``counts`` corresponds to the respective unique element in ``values``. The returned array must have same shape as ``values`` and must have the default array index data type.\n\n .. note::\n The order of unique elements is not specified and may vary between implementations.\n\nNotes\n-----\n\n.. versionchanged:: 2022.12\n Added complex data type support.\n\n.. versionchanged:: 2023.12\n Clarified flattening behavior and required the order of ``counts`` match the order of ``values``." @@ -8471,19 +8475,19 @@ class ArrayNamespace[TCapabilities, TDatatypes, TDefaultdatatypes, TSupportsbuff "Returns the unique elements of an input array ``x`` and the indices from the set of unique elements that reconstruct ``x``.\n\n.. admonition:: Data-dependent output shape\n :class: important\n\n The shapes of two of the output arrays for this function depend on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) may find this function difficult to implement without knowing array values. Accordingly, such libraries may choose to omit this function. See :ref:`data-dependent-output-shapes` section for more details.\n\n.. note::\n Uniqueness should be determined based on value equality (see :func:`~array_api.equal`). For input arrays having floating-point data types, value-based equality implies the following behavior.\n\n - As ``nan`` values compare as ``False``, ``nan`` values should be considered distinct.\n - As complex floating-point values having at least one ``nan`` component compare as ``False``, complex floating-point values having ``nan`` components should be considered distinct.\n - As ``-0`` and ``+0`` compare as ``True``, signed zeros should not be considered distinct, and the corresponding unique element will be implementation-dependent (e.g., an implementation could choose to return ``-0`` if ``-0`` occurs before ``+0``).\n\n As signed zeros are not distinct, using ``inverse_indices`` to reconstruct the input array is not guaranteed to return an array having the exact same values.\n\nParameters\n----------\nx: array\n input array. If ``x`` has more than one dimension, the function must flatten ``x`` and return the unique elements of the flattened array.\n\nReturns\n-------\nout: Tuple[array, array]\n a namedtuple ``(values, inverse_indices)`` whose\n\n - first element must have the field name ``values`` and must be a one-dimensional array containing the unique elements of ``x``. The array must have the same data type as ``x``.\n - second element must have the field name ``inverse_indices`` and must be an array containing the indices of ``values`` that reconstruct ``x``. The array must have the same shape as ``x`` and have the default array index data type.\n\n .. note::\n The order of unique elements is not specified and may vary between implementations.\n\nNotes\n-----\n\n.. versionchanged:: 2022.12\n Added complex data type support.\n\n.. versionchanged:: 2023.12\n Clarified flattening behavior." unique_values: unique_values[TArray,] "Returns the unique elements of an input array ``x``.\n\n.. admonition:: Data-dependent output shape\n :class: important\n\n The shapes of two of the output arrays for this function depend on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) may find this function difficult to implement without knowing array values. Accordingly, such libraries may choose to omit this function. See :ref:`data-dependent-output-shapes` section for more details.\n\n.. note::\n Uniqueness should be determined based on value equality (see :func:`~array_api.equal`). For input arrays having floating-point data types, value-based equality implies the following behavior.\n\n - As ``nan`` values compare as ``False``, ``nan`` values should be considered distinct.\n - As complex floating-point values having at least one ``nan`` component compare as ``False``, complex floating-point values having ``nan`` components should be considered distinct.\n - As ``-0`` and ``+0`` compare as ``True``, signed zeros should not be considered distinct, and the corresponding unique element will be implementation-dependent (e.g., an implementation could choose to return ``-0`` if ``-0`` occurs before ``+0``).\n\nParameters\n----------\nx: array\n input array. If ``x`` has more than one dimension, the function must flatten ``x`` and return the unique elements of the flattened array.\n\nReturns\n-------\nout: array\n a one-dimensional array containing the set of unique elements in ``x``. The returned array must have the same data type as ``x``.\n\n .. note::\n The order of unique elements is not specified and may vary between implementations.\n\nNotes\n-----\n\n.. versionchanged:: 2022.12\n Added complex data type support.\n\n.. versionchanged:: 2023.12\n Required that the output array must be one-dimensional." - bool: float - complex128: float - complex64: float - float32: float - float64: float - int16: float - int32: float - int64: float - int8: float - uint16: float - uint32: float - uint64: float - uint8: float + bool: TDtype + complex128: TDtype + complex64: TDtype + float32: TDtype + float64: TDtype + int16: TDtype + int32: TDtype + int64: TDtype + int8: TDtype + uint16: TDtype + uint32: TDtype + uint64: TDtype + uint8: TDtype Device: TDevice @@ -8570,6 +8574,6 @@ class FftNamespace[TArray: Array, TDevice](Protocol): @runtime_checkable -class ArrayNamespaceFull[TCapabilities, TDatatypes, TDefaultdatatypes, TSupportsbufferprotocol, TArray: Array, TDevice, TDtype](ArrayNamespace[TCapabilities, TDatatypes, TDefaultdatatypes, TSupportsbufferprotocol, TArray, TDevice, TDtype], Protocol): +class ArrayNamespaceFull[TArray: Array, TCapabilities, TDatatypes, TDefaultdatatypes, TDevice, TDtype](ArrayNamespace[TArray, TCapabilities, TDatatypes, TDefaultdatatypes, TDevice, TDtype], Protocol): linalg: LinalgNamespace[TArray, TDtype] fft: FftNamespace[TArray, TDevice] diff --git a/src/array_api/_2024_12.py b/src/array_api/_2024_12.py index 456f59c..f850190 100644 --- a/src/array_api/_2024_12.py +++ b/src/array_api/_2024_12.py @@ -1,8 +1,10 @@ from __future__ import annotations from abc import abstractmethod +from collections.abc import Buffer as SupportsBufferProtocol from collections.abc import Sequence from enum import Enum +from types import EllipsisType as ellipsis from typing import ( Any, Literal, @@ -10,11 +12,13 @@ runtime_checkable, ) +from typing_extensions import CapsuleType as PyCapsule + inf = float("inf") @runtime_checkable -class Info[TCapabilities, TDatatypes, TDefaultdatatypes, TArray: Array, TDevice, TDtype](Protocol): +class Info[TArray: Array, TCapabilities, TDatatypes, TDefaultdatatypes, TDevice, TDtype](Protocol): """Namespace returned by `__array_namespace_info__`.""" def capabilities(self) -> TCapabilities: ... @@ -58,13 +62,13 @@ class finfo_object[TDtype](Protocol): @runtime_checkable -class Array[TPycapsule, TArray: Array, TDevice, TDtype, TEllipsis](Protocol): - def __init__(self: TArray) -> None: +class Array[TArray: Array, TDevice, TDtype](Protocol): + def __init__(self) -> None: """Initialize the attributes for the array object class.""" ... @property - def dtype(self: TArray) -> TDtype: + def dtype(self) -> TDtype: """ Data type of the array elements. @@ -77,7 +81,7 @@ def dtype(self: TArray) -> TDtype: ... @property - def device(self: TArray) -> TDevice: + def device(self) -> TDevice: """ Hardware device the array data resides on. @@ -90,7 +94,7 @@ def device(self: TArray) -> TDevice: ... @property - def mT(self: TArray) -> TArray: + def mT(self) -> TArray: """ Transpose of a matrix (or a stack of matrices). @@ -105,7 +109,7 @@ def mT(self: TArray) -> TArray: ... @property - def ndim(self: TArray) -> int: + def ndim(self) -> int: """ Number of array dimensions (axes). @@ -118,7 +122,7 @@ def ndim(self: TArray) -> int: ... @property - def shape(self: TArray) -> tuple[int | None, ...]: + def shape(self) -> tuple[int | None, ...]: """ Array dimensions. @@ -138,7 +142,7 @@ def shape(self: TArray) -> tuple[int | None, ...]: ... @property - def size(self: TArray) -> int | None: + def size(self) -> int | None: """ Number of elements in an array. @@ -158,7 +162,7 @@ def size(self: TArray) -> int | None: ... @property - def T(self: TArray) -> TArray: + def T(self) -> TArray: """ Transpose of the array. @@ -176,13 +180,93 @@ def T(self: TArray) -> TArray: """ ... - def __array_namespace__(self: TArray, /, *, api_version: str | None = None) -> Any: + def __abs__(self, /) -> TArray: + """ + Calculates the absolute value for each element of an array instance. + + For real-valued input arrays, the element-wise result has the same magnitude as the respective element in ``x`` but has positive sign. + + .. note:: + For signed integer data types, the absolute value of the minimum representable integer is implementation-dependent. + + Parameters + ---------- + self + array instance. Should have a numeric data type. + + Returns + ------- + out: array + an array containing the element-wise absolute value. If ``self`` has a real-valued data type, the returned array must have the same data type as ``self``. If ``self`` has a complex floating-point data type, the returned arrayed must have a real-valued floating-point data type whose precision matches the precision of ``self`` (e.g., if ``self`` is ``complex128``, then the returned array must have a ``float64`` data type). + + Notes + ----- + + .. note:: + Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.abs`. + + .. versionchanged:: 2022.12 + Added complex data type support. + + """ + ... + + def __add__(self, other: int | float | complex | TArray, /) -> TArray: + """ + Calculates the sum for each element of an array instance with the respective element of the array ``other``. + + Parameters + ---------- + self + array instance (augend array). Should have a numeric data type. + other: Union[int, float, array] + addend array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a numeric data type. + + Returns + ------- + out: array + an array containing the element-wise sums. The returned array must have a data type determined by :ref:`type-promotion`. + + Notes + ----- + - Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.add`. + + .. versionchanged:: 2022.12 + Added complex data type support. + + """ + ... + + def __and__(self, other: int | bool | TArray, /) -> TArray: + """ + Evaluates ``self_i & other_i`` for each element of an array instance with the respective element of the array ``other``. + + Parameters + ---------- + self + array instance. Should have an integer or boolean data type. + other: Union[int, bool, array] + other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have an integer or boolean data type. + + Returns + ------- + out: array + an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. + + Notes + ----- + - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.bitwise_and`. + + """ + ... + + def __array_namespace__(self, /, *, api_version: str | None = None) -> Any: """ Returns an object that has all the array API functions on it. Parameters ---------- - self: array + self array instance. api_version: Optional[str] string representing the version of the array API specification to be returned, in ``'YYYY.MM'`` form, for example, ``'2020.10'``. If it is ``None``, it should return the namespace corresponding to latest version of the array API specification. If the given version is invalid or not implemented for the given module, an error should be raised. Default: ``None``. @@ -195,13 +279,94 @@ def __array_namespace__(self: TArray, /, *, api_version: str | None = None) -> A """ ... - def __dlpack__(self: TArray, /, *, stream: int | Any | None = None, max_version: tuple[int, int] | None = None, dl_device: tuple[Enum, int] | None = None, copy: bool | None = None) -> TPycapsule: + def __bool__(self, /) -> bool: + """ + Converts a zero-dimensional array to a Python ``bool`` object. + + Parameters + ---------- + self + zero-dimensional array instance. + + Returns + ------- + out: bool + a Python ``bool`` object representing the single element of the array. + + Notes + ----- + **Special cases** + + For real-valued floating-point operands, + + - If ``self`` is ``NaN``, the result is ``True``. + - If ``self`` is either ``+infinity`` or ``-infinity``, the result is ``True``. + - If ``self`` is either ``+0`` or ``-0``, the result is ``False``. + + For complex floating-point operands, special cases must be handled as if the operation is implemented as the logical OR of ``bool(real(self))`` and ``bool(imag(self))``. + + **Lazy implementations** + + The Python language requires the return value to be of type ``bool``. Lazy implementations are therefore not able to return any kind of lazy/delayed object here and should raise a ``ValueError`` instead. + + .. versionchanged:: 2022.12 + Added boolean and complex data type support. + + .. versionchanged:: 2023.12 + Allowed lazy implementations to error. + + """ + ... + + def __complex__(self, /) -> complex: + """ + Converts a zero-dimensional array to a Python ``complex`` object. + + Parameters + ---------- + self + zero-dimensional array instance. + + Returns + ------- + out: complex + a Python ``complex`` object representing the single element of the array instance. + + Notes + ----- + **Special cases** + + For boolean operands, + + - If ``self`` is ``True``, the result is ``1+0j``. + - If ``self`` is ``False``, the result is ``0+0j``. + + For real-valued floating-point operands, + + - If ``self`` is ``NaN``, the result is ``NaN + NaN j``. + - If ``self`` is ``+infinity``, the result is ``+infinity + 0j``. + - If ``self`` is ``-infinity``, the result is ``-infinity + 0j``. + - If ``self`` is a finite number, the result is ``self + 0j``. + + **Lazy implementations** + + The Python language requires the return value to be of type ``complex``. Lazy implementations are therefore not able to return any kind of lazy/delayed object here and should raise a ``ValueError`` instead. + + .. versionadded:: 2022.12 + + .. versionchanged:: 2023.12 + Allowed lazy implementations to error. + + """ + ... + + def __dlpack__(self, /, *, stream: int | Any | None = None, max_version: tuple[int, int] | None = None, dl_device: tuple[Enum, int] | None = None, copy: bool | None = None) -> PyCapsule: """ Exports the array for consumption by :func:`~array_api.from_dlpack` as a DLPack capsule. Parameters ---------- - self: array + self array instance. stream: Optional[Union[int, Any]] for CUDA and ROCm, a Python integer representing a pointer to a stream, on devices that support streams. ``stream`` is provided by the consumer to the producer to instruct the producer to ensure that operations can safely be performed on the array (e.g., by inserting a dependency between streams via "wait for event"). The pointer must be an integer larger than or equal to ``-1`` (see below for allowed values on each platform). If ``stream`` is ``-1``, the value may be used by the consumer to signal "producer must not perform any synchronization". The ownership of the stream stays with the consumer. On CPU and other device types without streams, only ``None`` is accepted. @@ -365,13 +530,13 @@ def __dlpack__(self: TArray, /, *, stream: int | Any | None = None, max_version: """ ... - def __dlpack_device__(self: TArray, /) -> tuple[Enum, int]: + def __dlpack_device__(self, /) -> tuple[Enum, int]: """ Returns device type and device ID in DLPack format. Meant for use within :func:`~array_api.from_dlpack`. Parameters ---------- - self: array + self array instance. Returns @@ -395,360 +560,319 @@ def __dlpack_device__(self: TArray, /) -> tuple[Enum, int]: """ ... - def to_device(self: TArray, device: TDevice, /, *, stream: int | Any | None = None) -> TArray: + def __eq__(self, other: int | float | complex | bool | TArray, /) -> TArray: # type: ignore[override] """ - Copy the array from the device on which it currently resides to the specified ``device``. + Computes the truth value of ``self_i == other_i`` for each element of an array instance with the respective element of the array ``other``. Parameters ---------- - self: array - array instance. - device: device - a ``device`` object (see :ref:`device-support`). - stream: Optional[Union[int, Any]] - stream object to use during copy. In addition to the types supported in :meth:`array.__dlpack__`, implementations may choose to support any library-specific stream object with the caveat that any code using such an object would not be portable. + self + array instance. May have any data type. + other: Union[int, float, complex, bool, array] + other array. Must be compatible with ``self`` (see :ref:`broadcasting`). May have any data type. Returns ------- out: array - an array with the same data and data type as ``self`` and located on the specified ``device``. - + an array containing the element-wise results. The returned array must have a data type of ``bool``. Notes ----- - - When a provided ``device`` object corresponds to the same device on which an array instance resides, implementations may choose to perform an explicit copy or return ``self``. - - If ``stream`` is provided, the copy operation should be enqueued on the provided ``stream``; otherwise, the copy operation should be enqueued on the default stream/queue. Whether the copy is performed synchronously or asynchronously is implementation-dependent. Accordingly, if synchronization is required to guarantee data safety, this must be clearly explained in a conforming array library's documentation. + - Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.equal`. + - Comparison of arrays without a corresponding promotable data type (see :ref:`type-promotion`) is undefined and thus implementation-dependent. - .. versionchanged:: 2023.12 - Clarified behavior when a provided ``device`` object corresponds to the device on which an array instance resides. + .. versionchanged:: 2022.12 + Added complex data type support. + + .. versionchanged:: 2024.12 + Cross-kind comparisons are explicitly left unspecified. """ ... - def __getitem__(self: TArray, key: int | slice | TEllipsis | None | tuple[int | slice | TEllipsis | TArray | None, ...] | TArray, /) -> TArray: + def __float__(self, /) -> float: """ - Returns ``self[key]``. + Converts a zero-dimensional array to a Python ``float`` object. + + .. note:: + Casting integer values outside the representable bounds of Python's float type is not specified and is implementation-dependent. Parameters ---------- - self: array - array instance. - key: Union[int, slice, ellipsis, None, Tuple[Union[int, slice, ellipsis, array, None], ...], array] - index key. + self + zero-dimensional array instance. Should have a real-valued or boolean data type. If ``self`` has a complex floating-point data type, the function must raise a ``TypeError``. Returns ------- - out: array - an array containing the accessed value(s). The returned array must have the same data type as ``self``. + out: float + a Python ``float`` object representing the single element of the array instance. Notes ----- - - See :ref:`indexing` for details on supported indexing semantics. - - When ``__getitem__`` is defined on an object, Python will automatically define iteration (i.e., the behavior from ``iter(x)``) as ``x[0]``, ``x[1]``, ..., ``x[N-1]``. This can also be implemented directly by defining ``__iter__``. Therefore, for a one-dimensional array ``x``, iteration should produce a sequence of zero-dimensional arrays ``x[0]``, ``x[1]``, ..., ``x[N-1]``, where ``N`` is the number of elements in the array. Iteration behavior for arrays having zero dimensions or more than one dimension is unspecified and thus implementation-defined. - - .. versionchanged:: 2024.12 - Clarified that iteration is defined for one-dimensional arrays. + **Special cases** - """ - ... + For boolean operands, - def __setitem__(self: TArray, key: int | slice | TEllipsis | tuple[int | slice | TEllipsis | TArray, ...] | TArray, value: int | float | complex | bool | TArray, /) -> None: - """ - Sets ``self[key]`` to ``value``. + - If ``self`` is ``True``, the result is ``1``. + - If ``self`` is ``False``, the result is ``0``. - Parameters - ---------- - self: array - array instance. - key: Union[int, slice, ellipsis, Tuple[Union[int, slice, ellipsis, array], ...], array] - index key. - value: Union[int, float, complex, bool, array] - value(s) to set. Must be compatible with ``self[key]`` (see :ref:`broadcasting`). + **Lazy implementations** - Notes - ----- - - See :ref:`indexing` for details on supported indexing semantics. + The Python language requires the return value to be of type ``float``. Lazy implementations are therefore not able to return any kind of lazy/delayed object here and should raise a ``ValueError`` instead. - .. note:: - Indexing semantics when ``key`` is an integer array or a tuple of integers and integer arrays is currently unspecified and thus implementation-defined. This will be revisited in a future revision of this standard. + .. versionchanged:: 2022.12 + Added boolean and complex data type support. - - Setting array values must not affect the data type of ``self``. - - When ``value`` is a Python scalar (i.e., ``int``, ``float``, ``complex``, ``bool``), behavior must follow specification guidance on mixing arrays with Python scalars (see :ref:`type-promotion`). - - When ``value`` is an ``array`` of a different data type than ``self``, how values are cast to the data type of ``self`` is implementation defined. + .. versionchanged:: 2023.12 + Allowed lazy implementations to error. """ ... - def __add__(self: TArray, other: int | float | complex | TArray, /) -> TArray: + def __floordiv__(self, other: int | float | TArray, /) -> TArray: """ - Calculates the sum for each element of an array instance with the respective element of the array ``other``. + Evaluates ``self_i // other_i`` for each element of an array instance with the respective element of the array ``other``. + + .. note:: + For input arrays which promote to an integer data type, the result of division by zero is unspecified and thus implementation-defined. Parameters ---------- - self: array - array instance (augend array). Should have a numeric data type. + self + array instance. Should have a real-valued data type. other: Union[int, float, array] - addend array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a numeric data type. + other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a real-valued data type. Returns ------- out: array - an array containing the element-wise sums. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. - Notes - ----- - - Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.add`. - .. versionchanged:: 2022.12 - Added complex data type support. + .. note:: + Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.floor_divide`. """ ... - def __sub__(self: TArray, other: int | float | complex | TArray, /) -> TArray: + def __ge__(self, other: int | float | TArray, /) -> TArray: """ - Calculates the difference for each element of an array instance with the respective element of the array ``other``. + Computes the truth value of ``self_i >= other_i`` for each element of an array instance with the respective element of the array ``other``. Parameters ---------- - self: array - array instance (minuend array). Should have a numeric data type. - other: Union[int, float, complex, array] - subtrahend array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a numeric data type. + self + array instance. Should have a real-valued data type. + other: Union[int, float, array] + other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a real-valued data type. Returns ------- out: array - an array containing the element-wise differences. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise results. The returned array must have a data type of ``bool``. Notes ----- - - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.subtract`. - - The result of ``self_i - other_i`` must be the same as ``self_i + (-other_i)`` and must be governed by the same floating-point rules as addition (see :meth:`array.__add__`). + - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.greater_equal`. + - Comparison of arrays without a corresponding promotable data type (see :ref:`type-promotion`) is undefined and thus implementation-dependent. + - For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). - .. versionchanged:: 2022.12 - Added complex data type support. + .. versionchanged:: 2024.12 + Cross-kind comparisons are explicitly left unspecified. """ ... - def __mul__(self: TArray, other: int | float | complex | TArray, /) -> TArray: + def __getitem__(self, key: int | slice | ellipsis | None | tuple[int | slice | ellipsis | TArray | None, ...] | TArray, /) -> TArray: """ - Calculates the product for each element of an array instance with the respective element of the array ``other``. - - .. note:: - Floating-point multiplication is not always associative due to finite precision. + Returns ``self[key]``. Parameters ---------- - self: array - array instance. Should have a numeric data type. - other: Union[int, float, complex, array] - other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a numeric data type. + self + array instance. + key: Union[int, slice, ellipsis, None, Tuple[Union[int, slice, ellipsis, array, None], ...], array] + index key. Returns ------- out: array - an array containing the element-wise products. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the accessed value(s). The returned array must have the same data type as ``self``. Notes ----- - - Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.multiply`. + - See :ref:`indexing` for details on supported indexing semantics. + - When ``__getitem__`` is defined on an object, Python will automatically define iteration (i.e., the behavior from ``iter(x)``) as ``x[0]``, ``x[1]``, ..., ``x[N-1]``. This can also be implemented directly by defining ``__iter__``. Therefore, for a one-dimensional array ``x``, iteration should produce a sequence of zero-dimensional arrays ``x[0]``, ``x[1]``, ..., ``x[N-1]``, where ``N`` is the number of elements in the array. Iteration behavior for arrays having zero dimensions or more than one dimension is unspecified and thus implementation-defined. - .. versionchanged:: 2022.12 - Added complex data type support. + .. versionchanged:: 2024.12 + Clarified that iteration is defined for one-dimensional arrays. """ ... - def __matmul__(self: TArray, other: TArray, /) -> TArray: + def __gt__(self, other: int | float | TArray, /) -> TArray: """ - Computes the matrix product. - - .. note:: - The ``matmul`` function must implement the same semantics as the built-in ``@`` operator (see `PEP 465 `_). + Computes the truth value of ``self_i > other_i`` for each element of an array instance with the respective element of the array ``other``. Parameters ---------- - self: array - array instance. Should have a numeric data type. Must have at least one dimension. If ``self`` is one-dimensional having shape ``(M,)`` and ``other`` has more than one dimension, ``self`` must be promoted to a two-dimensional array by prepending ``1`` to its dimensions (i.e., must have shape ``(1, M)``). After matrix multiplication, the prepended dimensions in the returned array must be removed. If ``self`` has more than one dimension (including after vector-to-matrix promotion), ``shape(self)[:-2]`` must be compatible with ``shape(other)[:-2]`` (after vector-to-matrix promotion) (see :ref:`broadcasting`). If ``self`` has shape ``(..., M, K)``, the innermost two dimensions form matrices on which to perform matrix multiplication. - other: array - other array. Should have a numeric data type. Must have at least one dimension. If ``other`` is one-dimensional having shape ``(N,)`` and ``self`` has more than one dimension, ``other`` must be promoted to a two-dimensional array by appending ``1`` to its dimensions (i.e., must have shape ``(N, 1)``). After matrix multiplication, the appended dimensions in the returned array must be removed. If ``other`` has more than one dimension (including after vector-to-matrix promotion), ``shape(other)[:-2]`` must be compatible with ``shape(self)[:-2]`` (after vector-to-matrix promotion) (see :ref:`broadcasting`). If ``other`` has shape ``(..., K, N)``, the innermost two dimensions form matrices on which to perform matrix multiplication. - - - .. note:: - If either ``x1`` or ``x2`` has a complex floating-point data type, neither argument must be complex-conjugated or transposed. If conjugation and/or transposition is desired, these operations should be explicitly performed prior to computing the matrix product. + self + array instance. Should have a real-valued data type. + other: Union[int, float, array] + other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a real-valued data type. Returns ------- out: array - - if both ``self`` and ``other`` are one-dimensional arrays having shape ``(N,)``, a zero-dimensional array containing the inner product as its only element. - - if ``self`` is a two-dimensional array having shape ``(M, K)`` and ``other`` is a two-dimensional array having shape ``(K, N)``, a two-dimensional array containing the `conventional matrix product `_ and having shape ``(M, N)``. - - if ``self`` is a one-dimensional array having shape ``(K,)`` and ``other`` is an array having shape ``(..., K, N)``, an array having shape ``(..., N)`` (i.e., prepended dimensions during vector-to-matrix promotion must be removed) and containing the `conventional matrix product `_. - - if ``self`` is an array having shape ``(..., M, K)`` and ``other`` is a one-dimensional array having shape ``(K,)``, an array having shape ``(..., M)`` (i.e., appended dimensions during vector-to-matrix promotion must be removed) and containing the `conventional matrix product `_. - - if ``self`` is a two-dimensional array having shape ``(M, K)`` and ``other`` is an array having shape ``(..., K, N)``, an array having shape ``(..., M, N)`` and containing the `conventional matrix product `_ for each stacked matrix. - - if ``self`` is an array having shape ``(..., M, K)`` and ``other`` is a two-dimensional array having shape ``(K, N)``, an array having shape ``(..., M, N)`` and containing the `conventional matrix product `_ for each stacked matrix. - - if either ``self`` or ``other`` has more than two dimensions, an array having a shape determined by :ref:`broadcasting` ``shape(self)[:-2]`` against ``shape(other)[:-2]`` and containing the `conventional matrix product `_ for each stacked matrix. - - The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise results. The returned array must have a data type of ``bool``. Notes ----- + - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.greater`. + - Comparison of arrays without a corresponding promotable data type (see :ref:`type-promotion`) is undefined and thus implementation-dependent. + - For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). - .. note:: - Results must equal the results returned by the equivalent function :func:`~array_api.matmul`. - - **Raises** - - - if either ``self`` or ``other`` is a zero-dimensional array. - - if ``self`` is a one-dimensional array having shape ``(K,)``, ``other`` is a one-dimensional array having shape ``(L,)``, and ``K != L``. - - if ``self`` is a one-dimensional array having shape ``(K,)``, ``other`` is an array having shape ``(..., L, N)``, and ``K != L``. - - if ``self`` is an array having shape ``(..., M, K)``, ``other`` is a one-dimensional array having shape ``(L,)``, and ``K != L``. - - if ``self`` is an array having shape ``(..., M, K)``, ``other`` is an array having shape ``(..., L, N)``, and ``K != L``. - - .. versionchanged:: 2022.12 - Added complex data type support. + .. versionchanged:: 2024.12 + Cross-kind comparisons are explicitly left unspecified. """ ... - def __truediv__(self: TArray, other: int | float | complex | TArray, /) -> TArray: + def __index__(self, /) -> int: """ - Evaluates ``self_i / other_i`` for each element of an array instance with the respective element of the array ``other``. + Converts a zero-dimensional integer array to a Python ``int`` object. + + .. note:: + This method is called to implement `operator.index() `_. See also `PEP 357 `_. Parameters ---------- - self: array - array instance. Should have a numeric data type. - other: Union[int, float, complex, array] - other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a numeric data type. + self + zero-dimensional array instance. Should have an integer data type. If ``self`` has a floating-point data type, the function must raise a ``TypeError``. Returns ------- - out: array - an array containing the element-wise results. The returned array should have a floating-point data type determined by :ref:`type-promotion`. + out: int + a Python ``int`` object representing the single element of the array instance. Notes ----- - - Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.divide`. - - - If one or both of ``self`` and ``other`` have integer data types, the result is implementation-dependent, as type promotion between data type "kinds" (e.g., integer versus floating-point) is unspecified. + **Lazy implementations** - Specification-compliant libraries may choose to raise an error or return an array containing the element-wise results. If an array is returned, the array must have a real-valued floating-point data type. + The Python language requires the return value to be of type ``int``. Lazy implementations are therefore not able to return any kind of lazy/delayed object here and should raise a ``ValueError`` instead. - .. versionchanged:: 2022.12 - Added complex data type support. + .. versionchanged:: 2023.12 + Allowed lazy implementations to error. """ ... - def __floordiv__(self: TArray, other: int | float | TArray, /) -> TArray: + def __int__(self, /) -> int: """ - Evaluates ``self_i // other_i`` for each element of an array instance with the respective element of the array ``other``. - - .. note:: - For input arrays which promote to an integer data type, the result of division by zero is unspecified and thus implementation-defined. + Converts a zero-dimensional array to a Python ``int`` object. Parameters ---------- - self: array - array instance. Should have a real-valued data type. - other: Union[int, float, array] - other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a real-valued data type. + self + zero-dimensional array instance. Should have a real-valued or boolean data type. If ``self`` has a complex floating-point data type, the function must raise a ``TypeError``. Returns ------- - out: array - an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. + out: int + a Python ``int`` object representing the single element of the array instance. + Notes + ----- + **Special cases** - .. note:: - Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.floor_divide`. + For boolean operands, - """ - ... + - If ``self`` is ``True``, the result is ``1``. + - If ``self`` is ``False``, the result is ``0``. - def __mod__(self: TArray, other: int | float | TArray, /) -> TArray: - """ - Evaluates ``self_i % other_i`` for each element of an array instance with the respective element of the array ``other``. + For floating-point operands, - Parameters - ---------- - self: array - array instance. Should have a real-valued data type. - other: Union[int, float, array] - other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a real-valued data type. + - If ``self`` is a finite number, the result is the integer part of ``self``. + - If ``self`` is ``-0``, the result is ``0``. - Returns - ------- - out: array - an array containing the element-wise results. Each element-wise result must have the same sign as the respective element ``other_i``. The returned array must have a real-valued floating-point data type determined by :ref:`type-promotion`. + **Raises** + + For floating-point operands, + + - If ``self`` is either ``+infinity`` or ``-infinity``, raise ``OverflowError``. + - If ``self`` is ``NaN``, raise ``ValueError``. Notes ----- - - Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.remainder`. - - For input arrays which promote to an integer data type, the result of division by zero is unspecified and thus implementation-defined. + **Lazy implementations** + + The Python language requires the return value to be of type ``int``. Lazy implementations are therefore not able to return any kind of lazy/delayed object here and should raise a ``ValueError`` instead. + + .. versionchanged:: 2022.12 + Added boolean and complex data type support. + + .. versionchanged:: 2023.12 + Allowed lazy implementations to error. """ ... - def __pow__(self: TArray, other: int | float | complex | TArray, /) -> TArray: + def __invert__(self, /) -> TArray: """ - Calculates an implementation-dependent approximation of exponentiation by raising each element (the base) of an array instance to the power of ``other_i`` (the exponent), where ``other_i`` is the corresponding element of the array ``other``. + Evaluates ``~self_i`` for each element of an array instance. Parameters ---------- - self: array - array instance whose elements correspond to the exponentiation base. Should have a numeric data type. - other: Union[int, float, complex, array] - other array whose elements correspond to the exponentiation exponent. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a numeric data type. + self + array instance. Should have an integer or boolean data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise results. The returned array must have the same data type as `self`. - Notes - ----- - - Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.pow`. - - If both ``self`` and ``other`` have integer data types, the result of ``__pow__`` when `other_i` is negative (i.e., less than zero) is unspecified and thus implementation-dependent. - - If ``self`` has an integer data type and ``other`` has a floating-point data type, behavior is implementation-dependent, as type promotion between data type "kinds" (e.g., integer versus floating-point) is unspecified. - .. versionchanged:: 2022.12 - Added complex data type support. + .. note:: + Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.bitwise_invert`. """ ... - def __lshift__(self: TArray, other: int | TArray, /) -> TArray: + def __le__(self, other: int | float | TArray, /) -> TArray: """ - Evaluates ``self_i << other_i`` for each element of an array instance with the respective element of the array ``other``. + Computes the truth value of ``self_i <= other_i`` for each element of an array instance with the respective element of the array ``other``. Parameters ---------- - self: array - array instance. Should have an integer data type. - other: Union[int, array] - other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have an integer data type. Each element must be greater than or equal to ``0``. + self + array instance. Should have a real-valued data type. + other: Union[int, float, array] + other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a real-valued data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have the same data type as ``self``. + an array containing the element-wise results. The returned array must have a data type of ``bool``. Notes ----- - - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.bitwise_left_shift`. + - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.less_equal`. + - Comparison of arrays without a corresponding promotable data type (see :ref:`type-promotion`) is undefined and thus implementation-dependent. + - For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). + + .. versionchanged:: 2024.12 + Cross-kind comparisons are explicitly left unspecified. """ ... - def __rshift__(self: TArray, other: int | TArray, /) -> TArray: + def __lshift__(self, other: int | TArray, /) -> TArray: """ - Evaluates ``self_i >> other_i`` for each element of an array instance with the respective element of the array ``other``. + Evaluates ``self_i << other_i`` for each element of an array instance with the respective element of the array ``other``. Parameters ---------- - self: array + self array instance. Should have an integer data type. other: Union[int, array] other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have an integer data type. Each element must be greater than or equal to ``0``. @@ -760,162 +884,82 @@ def __rshift__(self: TArray, other: int | TArray, /) -> TArray: Notes ----- - - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.bitwise_right_shift`. - - """ - ... - - def __and__(self: TArray, other: int | bool | TArray, /) -> TArray: - """ - Evaluates ``self_i & other_i`` for each element of an array instance with the respective element of the array ``other``. - - Parameters - ---------- - self: array - array instance. Should have an integer or boolean data type. - other: Union[int, bool, array] - other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have an integer or boolean data type. - - Returns - ------- - out: array - an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. - - Notes - ----- - - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.bitwise_and`. + - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.bitwise_left_shift`. """ ... - def __xor__(self: TArray, other: int | bool | TArray, /) -> TArray: + def __lt__(self, other: int | float | TArray, /) -> TArray: """ - Evaluates ``self_i ^ other_i`` for each element of an array instance with the respective element of the array ``other``. + Computes the truth value of ``self_i < other_i`` for each element of an array instance with the respective element of the array ``other``. Parameters ---------- - self: array - array instance. Should have an integer or boolean data type. - other: Union[int, bool, array] - other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have an integer or boolean data type. + self + array instance. Should have a real-valued data type. + other: Union[int, float, array] + other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a real-valued data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise results. The returned array must have a data type of ``bool``. Notes ----- - - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.bitwise_xor`. - - """ - ... - - def __or__(self: TArray, other: int | bool | TArray, /) -> TArray: - """ - Evaluates ``self_i | other_i`` for each element of an array instance with the respective element of the array ``other``. - - Parameters - ---------- - self: array - array instance. Should have an integer or boolean data type. - other: Union[int, bool, array] - other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have an integer or boolean data type. - - Returns - ------- - out: array - an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. + - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.less`. + - Comparison of arrays without a corresponding promotable data type (see :ref:`type-promotion`) is undefined and thus implementation-dependent. + - For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). - Notes - ----- - - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.bitwise_or`. + .. versionchanged:: 2024.12 + Cross-kind comparisons are explicitly left unspecified. """ ... - def __neg__(self: TArray, /) -> TArray: + def __matmul__(self, other: TArray, /) -> TArray: """ - Evaluates ``-self_i`` for each element of an array instance. - - .. note:: - For signed integer data types, the numerical negative of the minimum representable integer is implementation-dependent. + Computes the matrix product. .. note:: - If ``self`` has a complex floating-point data type, both the real and imaginary components for each ``self_i`` must be negated (a result which follows from the rules of complex number multiplication). + The ``matmul`` function must implement the same semantics as the built-in ``@`` operator (see `PEP 465 `_). Parameters ---------- - self: array - array instance. Should have a numeric data type. - - Returns - ------- - out: array - an array containing the evaluated result for each element in ``self``. The returned array must have a data type determined by :ref:`type-promotion`. + self + array instance. Should have a numeric data type. Must have at least one dimension. If ``self`` is one-dimensional having shape ``(M,)`` and ``other`` has more than one dimension, ``self`` must be promoted to a two-dimensional array by prepending ``1`` to its dimensions (i.e., must have shape ``(1, M)``). After matrix multiplication, the prepended dimensions in the returned array must be removed. If ``self`` has more than one dimension (including after vector-to-matrix promotion), ``shape(self)[:-2]`` must be compatible with ``shape(other)[:-2]`` (after vector-to-matrix promotion) (see :ref:`broadcasting`). If ``self`` has shape ``(..., M, K)``, the innermost two dimensions form matrices on which to perform matrix multiplication. + other: array + other array. Should have a numeric data type. Must have at least one dimension. If ``other`` is one-dimensional having shape ``(N,)`` and ``self`` has more than one dimension, ``other`` must be promoted to a two-dimensional array by appending ``1`` to its dimensions (i.e., must have shape ``(N, 1)``). After matrix multiplication, the appended dimensions in the returned array must be removed. If ``other`` has more than one dimension (including after vector-to-matrix promotion), ``shape(other)[:-2]`` must be compatible with ``shape(self)[:-2]`` (after vector-to-matrix promotion) (see :ref:`broadcasting`). If ``other`` has shape ``(..., K, N)``, the innermost two dimensions form matrices on which to perform matrix multiplication. - Notes - ----- .. note:: - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.negative`. - - .. versionchanged:: 2022.12 - Added complex data type support. - - """ - ... - - def __pos__(self: TArray, /) -> TArray: - """ - Evaluates ``+self_i`` for each element of an array instance. - - Parameters - ---------- - self: array - array instance. Should have a numeric data type. + If either ``x1`` or ``x2`` has a complex floating-point data type, neither argument must be complex-conjugated or transposed. If conjugation and/or transposition is desired, these operations should be explicitly performed prior to computing the matrix product. Returns ------- out: array - an array containing the evaluated result for each element. The returned array must have the same data type as ``self``. + - if both ``self`` and ``other`` are one-dimensional arrays having shape ``(N,)``, a zero-dimensional array containing the inner product as its only element. + - if ``self`` is a two-dimensional array having shape ``(M, K)`` and ``other`` is a two-dimensional array having shape ``(K, N)``, a two-dimensional array containing the `conventional matrix product `_ and having shape ``(M, N)``. + - if ``self`` is a one-dimensional array having shape ``(K,)`` and ``other`` is an array having shape ``(..., K, N)``, an array having shape ``(..., N)`` (i.e., prepended dimensions during vector-to-matrix promotion must be removed) and containing the `conventional matrix product `_. + - if ``self`` is an array having shape ``(..., M, K)`` and ``other`` is a one-dimensional array having shape ``(K,)``, an array having shape ``(..., M)`` (i.e., appended dimensions during vector-to-matrix promotion must be removed) and containing the `conventional matrix product `_. + - if ``self`` is a two-dimensional array having shape ``(M, K)`` and ``other`` is an array having shape ``(..., K, N)``, an array having shape ``(..., M, N)`` and containing the `conventional matrix product `_ for each stacked matrix. + - if ``self`` is an array having shape ``(..., M, K)`` and ``other`` is a two-dimensional array having shape ``(K, N)``, an array having shape ``(..., M, N)`` and containing the `conventional matrix product `_ for each stacked matrix. + - if either ``self`` or ``other`` has more than two dimensions, an array having a shape determined by :ref:`broadcasting` ``shape(self)[:-2]`` against ``shape(other)[:-2]`` and containing the `conventional matrix product `_ for each stacked matrix. + - The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- .. note:: - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.positive`. - - .. versionchanged:: 2022.12 - Added complex data type support. - - """ - ... - - def __abs__(self: TArray, /) -> TArray: - """ - Calculates the absolute value for each element of an array instance. - - For real-valued input arrays, the element-wise result has the same magnitude as the respective element in ``x`` but has positive sign. - - .. note:: - For signed integer data types, the absolute value of the minimum representable integer is implementation-dependent. - - Parameters - ---------- - self: array - array instance. Should have a numeric data type. - - Returns - ------- - out: array - an array containing the element-wise absolute value. If ``self`` has a real-valued data type, the returned array must have the same data type as ``self``. If ``self`` has a complex floating-point data type, the returned arrayed must have a real-valued floating-point data type whose precision matches the precision of ``self`` (e.g., if ``self`` is ``complex128``, then the returned array must have a ``float64`` data type). + Results must equal the results returned by the equivalent function :func:`~array_api.matmul`. - Notes - ----- + **Raises** - .. note:: - Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.abs`. + - if either ``self`` or ``other`` is a zero-dimensional array. + - if ``self`` is a one-dimensional array having shape ``(K,)``, ``other`` is a one-dimensional array having shape ``(L,)``, and ``K != L``. + - if ``self`` is a one-dimensional array having shape ``(K,)``, ``other`` is an array having shape ``(..., L, N)``, and ``K != L``. + - if ``self`` is an array having shape ``(..., M, K)``, ``other`` is a one-dimensional array having shape ``(L,)``, and ``K != L``. + - if ``self`` is an array having shape ``(..., M, K)``, ``other`` is an array having shape ``(..., L, N)``, and ``K != L``. .. versionchanged:: 2022.12 Added complex data type support. @@ -923,34 +967,13 @@ def __abs__(self: TArray, /) -> TArray: """ ... - def __invert__(self: TArray, /) -> TArray: - """ - Evaluates ``~self_i`` for each element of an array instance. - - Parameters - ---------- - self: array - array instance. Should have an integer or boolean data type. - - Returns - ------- - out: array - an array containing the element-wise results. The returned array must have the same data type as `self`. - - - .. note:: - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.bitwise_invert`. - - """ - ... - - def __lt__(self: TArray, other: int | float | TArray, /) -> TArray: + def __mod__(self, other: int | float | TArray, /) -> TArray: """ - Computes the truth value of ``self_i < other_i`` for each element of an array instance with the respective element of the array ``other``. + Evaluates ``self_i % other_i`` for each element of an array instance with the respective element of the array ``other``. Parameters ---------- - self: array + self array instance. Should have a real-valued data type. other: Union[int, float, array] other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a real-valued data type. @@ -958,55 +981,52 @@ def __lt__(self: TArray, other: int | float | TArray, /) -> TArray: Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type of ``bool``. + an array containing the element-wise results. Each element-wise result must have the same sign as the respective element ``other_i``. The returned array must have a real-valued floating-point data type determined by :ref:`type-promotion`. Notes ----- - - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.less`. - - Comparison of arrays without a corresponding promotable data type (see :ref:`type-promotion`) is undefined and thus implementation-dependent. - - For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). - - .. versionchanged:: 2024.12 - Cross-kind comparisons are explicitly left unspecified. + - Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.remainder`. + - For input arrays which promote to an integer data type, the result of division by zero is unspecified and thus implementation-defined. """ ... - def __le__(self: TArray, other: int | float | TArray, /) -> TArray: + def __mul__(self, other: int | float | complex | TArray, /) -> TArray: """ - Computes the truth value of ``self_i <= other_i`` for each element of an array instance with the respective element of the array ``other``. + Calculates the product for each element of an array instance with the respective element of the array ``other``. + + .. note:: + Floating-point multiplication is not always associative due to finite precision. Parameters ---------- - self: array - array instance. Should have a real-valued data type. - other: Union[int, float, array] - other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a real-valued data type. + self + array instance. Should have a numeric data type. + other: Union[int, float, complex, array] + other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a numeric data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type of ``bool``. + an array containing the element-wise products. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- - - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.less_equal`. - - Comparison of arrays without a corresponding promotable data type (see :ref:`type-promotion`) is undefined and thus implementation-dependent. - - For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). + - Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.multiply`. - .. versionchanged:: 2024.12 - Cross-kind comparisons are explicitly left unspecified. + .. versionchanged:: 2022.12 + Added complex data type support. """ ... - def __eq__(self: TArray, other: int | float | complex | bool | TArray, /) -> TArray: # type: ignore[override] + def __ne__(self, other: int | float | complex | bool | TArray, /) -> TArray: # type: ignore[override] """ - Computes the truth value of ``self_i == other_i`` for each element of an array instance with the respective element of the array ``other``. + Computes the truth value of ``self_i != other_i`` for each element of an array instance with the respective element of the array ``other``. Parameters ---------- - self: array + self array instance. May have any data type. other: Union[int, float, complex, bool, array] other array. Must be compatible with ``self`` (see :ref:`broadcasting`). May have any data type. @@ -1014,11 +1034,11 @@ def __eq__(self: TArray, other: int | float | complex | bool | TArray, /) -> TAr Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type of ``bool``. + an array containing the element-wise results. The returned array must have a data type of ``bool`` (i.e., must be a boolean array). Notes ----- - - Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.equal`. + - Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.not_equal`. - Comparison of arrays without a corresponding promotable data type (see :ref:`type-promotion`) is undefined and thus implementation-dependent. .. versionchanged:: 2022.12 @@ -1030,287 +1050,271 @@ def __eq__(self: TArray, other: int | float | complex | bool | TArray, /) -> TAr """ ... - def __ne__(self: TArray, other: int | float | complex | bool | TArray, /) -> TArray: # type: ignore[override] + def __neg__(self, /) -> TArray: """ - Computes the truth value of ``self_i != other_i`` for each element of an array instance with the respective element of the array ``other``. + Evaluates ``-self_i`` for each element of an array instance. + + .. note:: + For signed integer data types, the numerical negative of the minimum representable integer is implementation-dependent. + + .. note:: + If ``self`` has a complex floating-point data type, both the real and imaginary components for each ``self_i`` must be negated (a result which follows from the rules of complex number multiplication). Parameters ---------- - self: array - array instance. May have any data type. - other: Union[int, float, complex, bool, array] - other array. Must be compatible with ``self`` (see :ref:`broadcasting`). May have any data type. + self + array instance. Should have a numeric data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type of ``bool`` (i.e., must be a boolean array). + an array containing the evaluated result for each element in ``self``. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- - - Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.not_equal`. - - Comparison of arrays without a corresponding promotable data type (see :ref:`type-promotion`) is undefined and thus implementation-dependent. + + .. note:: + Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.negative`. .. versionchanged:: 2022.12 Added complex data type support. - .. versionchanged:: 2024.12 - Cross-kind comparisons are explicitly left unspecified. - """ ... - def __gt__(self: TArray, other: int | float | TArray, /) -> TArray: + def __or__(self, other: int | bool | TArray, /) -> TArray: """ - Computes the truth value of ``self_i > other_i`` for each element of an array instance with the respective element of the array ``other``. + Evaluates ``self_i | other_i`` for each element of an array instance with the respective element of the array ``other``. Parameters ---------- - self: array - array instance. Should have a real-valued data type. - other: Union[int, float, array] - other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a real-valued data type. + self + array instance. Should have an integer or boolean data type. + other: Union[int, bool, array] + other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have an integer or boolean data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type of ``bool``. + an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- - - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.greater`. - - Comparison of arrays without a corresponding promotable data type (see :ref:`type-promotion`) is undefined and thus implementation-dependent. - - For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). - - .. versionchanged:: 2024.12 - Cross-kind comparisons are explicitly left unspecified. + - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.bitwise_or`. """ ... - def __ge__(self: TArray, other: int | float | TArray, /) -> TArray: + def __pos__(self, /) -> TArray: """ - Computes the truth value of ``self_i >= other_i`` for each element of an array instance with the respective element of the array ``other``. + Evaluates ``+self_i`` for each element of an array instance. Parameters ---------- - self: array - array instance. Should have a real-valued data type. - other: Union[int, float, array] - other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a real-valued data type. + self + array instance. Should have a numeric data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type of ``bool``. + an array containing the evaluated result for each element. The returned array must have the same data type as ``self``. Notes ----- - - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.greater_equal`. - - Comparison of arrays without a corresponding promotable data type (see :ref:`type-promotion`) is undefined and thus implementation-dependent. - - For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). - .. versionchanged:: 2024.12 - Cross-kind comparisons are explicitly left unspecified. + .. note:: + Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.positive`. + + .. versionchanged:: 2022.12 + Added complex data type support. """ ... - def __bool__(self: TArray, /) -> bool: + def __pow__(self, other: int | float | complex | TArray, /) -> TArray: """ - Converts a zero-dimensional array to a Python ``bool`` object. + Calculates an implementation-dependent approximation of exponentiation by raising each element (the base) of an array instance to the power of ``other_i`` (the exponent), where ``other_i`` is the corresponding element of the array ``other``. Parameters ---------- - self: array - zero-dimensional array instance. + self + array instance whose elements correspond to the exponentiation base. Should have a numeric data type. + other: Union[int, float, complex, array] + other array whose elements correspond to the exponentiation exponent. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a numeric data type. Returns ------- - out: bool - a Python ``bool`` object representing the single element of the array. + out: array + an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- - **Special cases** - - For real-valued floating-point operands, - - - If ``self`` is ``NaN``, the result is ``True``. - - If ``self`` is either ``+infinity`` or ``-infinity``, the result is ``True``. - - If ``self`` is either ``+0`` or ``-0``, the result is ``False``. - - For complex floating-point operands, special cases must be handled as if the operation is implemented as the logical OR of ``bool(real(self))`` and ``bool(imag(self))``. - - **Lazy implementations** - - The Python language requires the return value to be of type ``bool``. Lazy implementations are therefore not able to return any kind of lazy/delayed object here and should raise a ``ValueError`` instead. + - Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.pow`. + - If both ``self`` and ``other`` have integer data types, the result of ``__pow__`` when `other_i` is negative (i.e., less than zero) is unspecified and thus implementation-dependent. + - If ``self`` has an integer data type and ``other`` has a floating-point data type, behavior is implementation-dependent, as type promotion between data type "kinds" (e.g., integer versus floating-point) is unspecified. .. versionchanged:: 2022.12 - Added boolean and complex data type support. - - .. versionchanged:: 2023.12 - Allowed lazy implementations to error. + Added complex data type support. """ ... - def __complex__(self: TArray, /) -> complex: + def __rshift__(self, other: int | TArray, /) -> TArray: """ - Converts a zero-dimensional array to a Python ``complex`` object. + Evaluates ``self_i >> other_i`` for each element of an array instance with the respective element of the array ``other``. Parameters ---------- - self: array - zero-dimensional array instance. + self + array instance. Should have an integer data type. + other: Union[int, array] + other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have an integer data type. Each element must be greater than or equal to ``0``. Returns ------- - out: complex - a Python ``complex`` object representing the single element of the array instance. + out: array + an array containing the element-wise results. The returned array must have the same data type as ``self``. Notes ----- - **Special cases** - - For boolean operands, - - - If ``self`` is ``True``, the result is ``1+0j``. - - If ``self`` is ``False``, the result is ``0+0j``. + - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.bitwise_right_shift`. - For real-valued floating-point operands, + """ + ... - - If ``self`` is ``NaN``, the result is ``NaN + NaN j``. - - If ``self`` is ``+infinity``, the result is ``+infinity + 0j``. - - If ``self`` is ``-infinity``, the result is ``-infinity + 0j``. - - If ``self`` is a finite number, the result is ``self + 0j``. + def __setitem__(self, key: int | slice | ellipsis | tuple[int | slice | ellipsis | TArray, ...] | TArray, value: int | float | complex | bool | TArray, /) -> None: + """ + Sets ``self[key]`` to ``value``. - **Lazy implementations** + Parameters + ---------- + self + array instance. + key: Union[int, slice, ellipsis, Tuple[Union[int, slice, ellipsis, array], ...], array] + index key. + value: Union[int, float, complex, bool, array] + value(s) to set. Must be compatible with ``self[key]`` (see :ref:`broadcasting`). - The Python language requires the return value to be of type ``complex``. Lazy implementations are therefore not able to return any kind of lazy/delayed object here and should raise a ``ValueError`` instead. + Notes + ----- + - See :ref:`indexing` for details on supported indexing semantics. - .. versionadded:: 2022.12 + .. note:: + Indexing semantics when ``key`` is an integer array or a tuple of integers and integer arrays is currently unspecified and thus implementation-defined. This will be revisited in a future revision of this standard. - .. versionchanged:: 2023.12 - Allowed lazy implementations to error. + - Setting array values must not affect the data type of ``self``. + - When ``value`` is a Python scalar (i.e., ``int``, ``float``, ``complex``, ``bool``), behavior must follow specification guidance on mixing arrays with Python scalars (see :ref:`type-promotion`). + - When ``value`` is an ``array`` of a different data type than ``self``, how values are cast to the data type of ``self`` is implementation defined. """ ... - def __int__(self: TArray, /) -> int: + def __sub__(self, other: int | float | complex | TArray, /) -> TArray: """ - Converts a zero-dimensional array to a Python ``int`` object. + Calculates the difference for each element of an array instance with the respective element of the array ``other``. Parameters ---------- - self: array - zero-dimensional array instance. Should have a real-valued or boolean data type. If ``self`` has a complex floating-point data type, the function must raise a ``TypeError``. + self + array instance (minuend array). Should have a numeric data type. + other: Union[int, float, complex, array] + subtrahend array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a numeric data type. Returns ------- - out: int - a Python ``int`` object representing the single element of the array instance. + out: array + an array containing the element-wise differences. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- - **Special cases** - - For boolean operands, - - - If ``self`` is ``True``, the result is ``1``. - - If ``self`` is ``False``, the result is ``0``. + - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.subtract`. + - The result of ``self_i - other_i`` must be the same as ``self_i + (-other_i)`` and must be governed by the same floating-point rules as addition (see :meth:`array.__add__`). - For floating-point operands, + .. versionchanged:: 2022.12 + Added complex data type support. - - If ``self`` is a finite number, the result is the integer part of ``self``. - - If ``self`` is ``-0``, the result is ``0``. + """ + ... - **Raises** + def __truediv__(self, other: int | float | complex | TArray, /) -> TArray: + """ + Evaluates ``self_i / other_i`` for each element of an array instance with the respective element of the array ``other``. - For floating-point operands, + Parameters + ---------- + self + array instance. Should have a numeric data type. + other: Union[int, float, complex, array] + other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a numeric data type. - - If ``self`` is either ``+infinity`` or ``-infinity``, raise ``OverflowError``. - - If ``self`` is ``NaN``, raise ``ValueError``. + Returns + ------- + out: array + an array containing the element-wise results. The returned array should have a floating-point data type determined by :ref:`type-promotion`. Notes ----- - **Lazy implementations** + - Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.divide`. - The Python language requires the return value to be of type ``int``. Lazy implementations are therefore not able to return any kind of lazy/delayed object here and should raise a ``ValueError`` instead. + - If one or both of ``self`` and ``other`` have integer data types, the result is implementation-dependent, as type promotion between data type "kinds" (e.g., integer versus floating-point) is unspecified. - .. versionchanged:: 2022.12 - Added boolean and complex data type support. + Specification-compliant libraries may choose to raise an error or return an array containing the element-wise results. If an array is returned, the array must have a real-valued floating-point data type. - .. versionchanged:: 2023.12 - Allowed lazy implementations to error. + .. versionchanged:: 2022.12 + Added complex data type support. """ ... - def __float__(self: TArray, /) -> float: + def __xor__(self, other: int | bool | TArray, /) -> TArray: """ - Converts a zero-dimensional array to a Python ``float`` object. - - .. note:: - Casting integer values outside the representable bounds of Python's float type is not specified and is implementation-dependent. + Evaluates ``self_i ^ other_i`` for each element of an array instance with the respective element of the array ``other``. Parameters ---------- - self: array - zero-dimensional array instance. Should have a real-valued or boolean data type. If ``self`` has a complex floating-point data type, the function must raise a ``TypeError``. + self + array instance. Should have an integer or boolean data type. + other: Union[int, bool, array] + other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have an integer or boolean data type. Returns ------- - out: float - a Python ``float`` object representing the single element of the array instance. + out: array + an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- - **Special cases** - - For boolean operands, - - - If ``self`` is ``True``, the result is ``1``. - - If ``self`` is ``False``, the result is ``0``. - - **Lazy implementations** - - The Python language requires the return value to be of type ``float``. Lazy implementations are therefore not able to return any kind of lazy/delayed object here and should raise a ``ValueError`` instead. - - .. versionchanged:: 2022.12 - Added boolean and complex data type support. - - .. versionchanged:: 2023.12 - Allowed lazy implementations to error. + - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.bitwise_xor`. """ ... - def __index__(self: TArray, /) -> int: + def to_device(self, device: TDevice, /, *, stream: int | Any | None = None) -> TArray: """ - Converts a zero-dimensional integer array to a Python ``int`` object. - - .. note:: - This method is called to implement `operator.index() `_. See also `PEP 357 `_. + Copy the array from the device on which it currently resides to the specified ``device``. Parameters ---------- - self: array - zero-dimensional array instance. Should have an integer data type. If ``self`` has a floating-point data type, the function must raise a ``TypeError``. + self + array instance. + device: device + a ``device`` object (see :ref:`device-support`). + stream: Optional[Union[int, Any]] + stream object to use during copy. In addition to the types supported in :meth:`array.__dlpack__`, implementations may choose to support any library-specific stream object with the caveat that any code using such an object would not be portable. Returns ------- - out: int - a Python ``int`` object representing the single element of the array instance. + out: array + an array with the same data and data type as ``self`` and located on the specified ``device``. + Notes ----- - **Lazy implementations** - - The Python language requires the return value to be of type ``int``. Lazy implementations are therefore not able to return any kind of lazy/delayed object here and should raise a ``ValueError`` instead. + - When a provided ``device`` object corresponds to the same device on which an array instance resides, implementations may choose to perform an explicit copy or return ``self``. + - If ``stream`` is provided, the copy operation should be enqueued on the provided ``stream``; otherwise, the copy operation should be enqueued on the default stream/queue. Whether the copy is performed synchronously or asynchronously is implementation-dependent. Accordingly, if synchronization is required to guarantee data safety, this must be clearly explained in a conforming array library's documentation. .. versionchanged:: 2023.12 - Allowed lazy implementations to error. + Clarified behavior when a provided ``device`` object corresponds to the device on which an array instance resides. """ ... @@ -1322,47 +1326,47 @@ class astype[TArray: Array, TDevice, TDtype](Protocol): Copies an array to a specified data type irrespective of :ref:`type-promotion` rules. .. note:: - Casting floating-point ``NaN`` and ``infinity`` values to integral data types is not specified and is implementation-dependent. + Casting floating-point ``NaN`` and ``infinity`` values to integral data types is not specified and is implementation-dependent. .. note:: - Casting a complex floating-point array to a real-valued data type should not be permitted. + Casting a complex floating-point array to a real-valued data type should not be permitted. - Historically, when casting a complex floating-point array to a real-valued data type, libraries such as NumPy have discarded imaginary components such that, for a complex floating-point array ``x``, ``astype(x)`` equals ``astype(real(x))``). This behavior is considered problematic as the choice to discard the imaginary component is arbitrary and introduces more than one way to achieve the same outcome (i.e., for a complex floating-point array ``x``, ``astype(x)`` and ``astype(real(x))`` versus only ``astype(imag(x))``). Instead, in order to avoid ambiguity and to promote clarity, this specification requires that array API consumers explicitly express which component should be cast to a specified real-valued data type. + Historically, when casting a complex floating-point array to a real-valued data type, libraries such as NumPy have discarded imaginary components such that, for a complex floating-point array ``x``, ``astype(x)`` equals ``astype(real(x))``). This behavior is considered problematic as the choice to discard the imaginary component is arbitrary and introduces more than one way to achieve the same outcome (i.e., for a complex floating-point array ``x``, ``astype(x)`` and ``astype(real(x))`` versus only ``astype(imag(x))``). Instead, in order to avoid ambiguity and to promote clarity, this specification requires that array API consumers explicitly express which component should be cast to a specified real-valued data type. .. note:: - When casting a boolean input array to a real-valued data type, a value of ``True`` must cast to a real-valued number equal to ``1``, and a value of ``False`` must cast to a real-valued number equal to ``0``. + When casting a boolean input array to a real-valued data type, a value of ``True`` must cast to a real-valued number equal to ``1``, and a value of ``False`` must cast to a real-valued number equal to ``0``. - When casting a boolean input array to a complex floating-point data type, a value of ``True`` must cast to a complex number equal to ``1 + 0j``, and a value of ``False`` must cast to a complex number equal to ``0 + 0j``. + When casting a boolean input array to a complex floating-point data type, a value of ``True`` must cast to a complex number equal to ``1 + 0j``, and a value of ``False`` must cast to a complex number equal to ``0 + 0j``. .. note:: - When casting a real-valued input array to ``bool``, a value of ``0`` must cast to ``False``, and a non-zero value must cast to ``True``. + When casting a real-valued input array to ``bool``, a value of ``0`` must cast to ``False``, and a non-zero value must cast to ``True``. - When casting a complex floating-point array to ``bool``, a value of ``0 + 0j`` must cast to ``False``, and all other values must cast to ``True``. + When casting a complex floating-point array to ``bool``, a value of ``0 + 0j`` must cast to ``False``, and all other values must cast to ``True``. Parameters ---------- x: array - array to cast. + array to cast. dtype: dtype - desired data type. + desired data type. copy: bool - specifies whether to copy an array when the specified ``dtype`` matches the data type of the input array ``x``. If ``True``, a newly allocated array must always be returned (see :ref:`copy-keyword-argument`). If ``False`` and the specified ``dtype`` matches the data type of the input array, the input array must be returned; otherwise, a newly allocated array must be returned. Default: ``True``. + specifies whether to copy an array when the specified ``dtype`` matches the data type of the input array ``x``. If ``True``, a newly allocated array must always be returned (see :ref:`copy-keyword-argument`). If ``False`` and the specified ``dtype`` matches the data type of the input array, the input array must be returned; otherwise, a newly allocated array must be returned. Default: ``True``. device: Optional[device] - device on which to place the returned array. If ``device`` is ``None``, the output array device must be inferred from ``x``. Default: ``None``. + device on which to place the returned array. If ``device`` is ``None``, the output array device must be inferred from ``x``. Default: ``None``. Returns ------- out: array - an array having the specified data type. The returned array must have the same shape as ``x``. + an array having the specified data type. The returned array must have the same shape as ``x``. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. .. versionchanged:: 2023.12 - Added device keyword argument support. + Added device keyword argument support. """ @@ -1378,14 +1382,14 @@ class can_cast[TArray: Array, TDtype](Protocol): Parameters ---------- from_: Union[dtype, array] - input data type or array from which to cast. + input data type or array from which to cast. to: dtype - desired data type. + desired data type. Returns ------- out: bool - ``True`` if the cast can occur according to type promotion rules (see :ref:`type-promotion`); otherwise, ``False``. + ``True`` if the cast can occur according to type promotion rules (see :ref:`type-promotion`); otherwise, ``False``. Notes ----- @@ -1393,7 +1397,7 @@ class can_cast[TArray: Array, TDtype](Protocol): - When ``from_`` is an array, the function must determine whether the data type of the array can be cast to the desired data type according to the type promotion graph of the array device. As not all devices can support all data types, full support for type promotion rules (see :ref:`type-promotion`) may not be possible. Accordingly, the output of ``can_cast(array, dtype)`` may differ from ``can_cast(array.dtype, dtype)``. .. versionchanged:: 2024.12 - Required that the application of type promotion rules must account for device context. + Required that the application of type promotion rules must account for device context. """ @@ -1409,47 +1413,47 @@ class finfo[TArray: Array, TDtype](Protocol): Parameters ---------- type: Union[dtype, array] - the kind of floating-point data-type about which to get information. If complex, the information is about its component data type. + the kind of floating-point data-type about which to get information. If complex, the information is about its component data type. - .. note:: - Complex floating-point data types are specified to always use the same precision for both its real and imaginary components, so the information should be true for either component. + .. note:: + Complex floating-point data types are specified to always use the same precision for both its real and imaginary components, so the information should be true for either component. Returns ------- out: finfo object - an object having the following attributes: + an object having the following attributes: - - **bits**: *int* + - **bits**: *int* - number of bits occupied by the real-valued floating-point data type. + number of bits occupied by the real-valued floating-point data type. - - **eps**: *float* + - **eps**: *float* - difference between 1.0 and the next smallest representable real-valued floating-point number larger than 1.0 according to the IEEE-754 standard. + difference between 1.0 and the next smallest representable real-valued floating-point number larger than 1.0 according to the IEEE-754 standard. - - **max**: *float* + - **max**: *float* - largest representable real-valued number. + largest representable real-valued number. - - **min**: *float* + - **min**: *float* - smallest representable real-valued number. + smallest representable real-valued number. - - **smallest_normal**: *float* + - **smallest_normal**: *float* - smallest positive real-valued floating-point number with full precision. + smallest positive real-valued floating-point number with full precision. - - **dtype**: dtype + - **dtype**: dtype - real-valued floating-point data type. + real-valued floating-point data type. - .. versionadded:: 2022.12 + .. versionadded:: 2022.12 Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -1465,30 +1469,30 @@ class iinfo[TArray: Array, TDtype](Protocol): Parameters ---------- type: Union[dtype, array] - the kind of integer data-type about which to get information. + the kind of integer data-type about which to get information. Returns ------- out: iinfo object - an object having the following attributes: + an object having the following attributes: - - **bits**: *int* + - **bits**: *int* - number of bits occupied by the type. + number of bits occupied by the type. - - **max**: *int* + - **max**: *int* - largest representable number. + largest representable number. - - **min**: *int* + - **min**: *int* - smallest representable number. + smallest representable number. - - **dtype**: dtype + - **dtype**: dtype - integer data type. + integer data type. - .. versionadded:: 2022.12 + .. versionadded:: 2022.12 """ @@ -1504,32 +1508,32 @@ class isdtype[TDtype](Protocol): Parameters ---------- dtype: dtype - the input dtype. + the input dtype. kind: Union[str, dtype, Tuple[Union[str, dtype], ...]] - data type kind. + data type kind. - - If ``kind`` is a dtype, the function must return a boolean indicating whether the input ``dtype`` is equal to the dtype specified by ``kind``. - - If ``kind`` is a string, the function must return a boolean indicating whether the input ``dtype`` is of a specified data type kind. The following dtype kinds must be supported: + - If ``kind`` is a dtype, the function must return a boolean indicating whether the input ``dtype`` is equal to the dtype specified by ``kind``. + - If ``kind`` is a string, the function must return a boolean indicating whether the input ``dtype`` is of a specified data type kind. The following dtype kinds must be supported: - - ``'bool'``: boolean data types (e.g., ``bool``). - - ``'signed integer'``: signed integer data types (e.g., ``int8``, ``int16``, ``int32``, ``int64``). - - ``'unsigned integer'``: unsigned integer data types (e.g., ``uint8``, ``uint16``, ``uint32``, ``uint64``). - - ``'integral'``: integer data types. Shorthand for ``('signed integer', 'unsigned integer')``. - - ``'real floating'``: real-valued floating-point data types (e.g., ``float32``, ``float64``). - - ``'complex floating'``: complex floating-point data types (e.g., ``complex64``, ``complex128``). - - ``'numeric'``: numeric data types. Shorthand for ``('integral', 'real floating', 'complex floating')``. + - ``'bool'``: boolean data types (e.g., ``bool``). + - ``'signed integer'``: signed integer data types (e.g., ``int8``, ``int16``, ``int32``, ``int64``). + - ``'unsigned integer'``: unsigned integer data types (e.g., ``uint8``, ``uint16``, ``uint32``, ``uint64``). + - ``'integral'``: integer data types. Shorthand for ``('signed integer', 'unsigned integer')``. + - ``'real floating'``: real-valued floating-point data types (e.g., ``float32``, ``float64``). + - ``'complex floating'``: complex floating-point data types (e.g., ``complex64``, ``complex128``). + - ``'numeric'``: numeric data types. Shorthand for ``('integral', 'real floating', 'complex floating')``. - - If ``kind`` is a tuple, the tuple specifies a union of dtypes and/or kinds, and the function must return a boolean indicating whether the input ``dtype`` is either equal to a specified dtype or belongs to at least one specified data type kind. + - If ``kind`` is a tuple, the tuple specifies a union of dtypes and/or kinds, and the function must return a boolean indicating whether the input ``dtype`` is either equal to a specified dtype or belongs to at least one specified data type kind. - .. note:: - A conforming implementation of the array API standard is **not** limited to only including the dtypes described in this specification in the required data type kinds. For example, implementations supporting ``float16`` and ``bfloat16`` can include ``float16`` and ``bfloat16`` in the ``real floating`` data type kind. Similarly, implementations supporting ``int128`` can include ``int128`` in the ``signed integer`` data type kind. + .. note:: + A conforming implementation of the array API standard is **not** limited to only including the dtypes described in this specification in the required data type kinds. For example, implementations supporting ``float16`` and ``bfloat16`` can include ``float16`` and ``bfloat16`` in the ``real floating`` data type kind. Similarly, implementations supporting ``int128`` can include ``int128`` in the ``signed integer`` data type kind. - In short, conforming implementations may extend data type kinds; however, data type kinds must remain consistent (e.g., only integer dtypes may belong to integer data type kinds and only floating-point dtypes may belong to floating-point data type kinds), and extensions must be clearly documented as such in library documentation. + In short, conforming implementations may extend data type kinds; however, data type kinds must remain consistent (e.g., only integer dtypes may belong to integer data type kinds and only floating-point dtypes may belong to floating-point data type kinds), and extensions must be clearly documented as such in library documentation. Returns ------- out: bool - boolean indicating whether a provided dtype is of a specified data type kind. + boolean indicating whether a provided dtype is of a specified data type kind. Notes ----- @@ -1550,12 +1554,12 @@ class result_type[TArray: Array, TDtype](Protocol): Parameters ---------- arrays_and_dtypes: Union[array, int, float, complex, bool, dtype] - an arbitrary number of input arrays, scalars, and/or dtypes. + an arbitrary number of input arrays, scalars, and/or dtypes. Returns ------- out: dtype - the dtype resulting from an operation involving the input arrays, scalars, and/or dtypes. + the dtype resulting from an operation involving the input arrays, scalars, and/or dtypes. Notes ----- @@ -1565,10 +1569,10 @@ class result_type[TArray: Array, TDtype](Protocol): - If two or more arguments are arrays belonging to different devices, behavior is unspecified and thus implementation-dependent. Conforming implementations may choose to ignore device attributes, raise an exception, or some other behavior. .. versionchanged:: 2024.12 - Added scalar argument support. + Added scalar argument support. .. versionchanged:: 2024.12 - Required that the application of type promotion rules must account for device context. + Required that the application of type promotion rules must account for device context. """ @@ -1584,32 +1588,32 @@ class cumulative_prod[TArray: Array, TDtype](Protocol): Parameters ---------- x: array - input array. Should have one or more dimensions (axes). Should have a numeric data type. + input array. Should have one or more dimensions (axes). Should have a numeric data type. axis: Optional[int] - axis along which a cumulative product must be computed. If ``axis`` is negative, the function must determine the axis along which to compute a cumulative product by counting from the last dimension. + axis along which a cumulative product must be computed. If ``axis`` is negative, the function must determine the axis along which to compute a cumulative product by counting from the last dimension. - If ``x`` is a one-dimensional array, providing an ``axis`` is optional; however, if ``x`` has more than one dimension, providing an ``axis`` is required. + If ``x`` is a one-dimensional array, providing an ``axis`` is optional; however, if ``x`` has more than one dimension, providing an ``axis`` is required. dtype: Optional[dtype] - data type of the returned array. If ``None``, the returned array must have the same data type as ``x``, unless ``x`` has an integer data type supporting a smaller range of values than the default integer data type (e.g., ``x`` has an ``int16`` or ``uint32`` data type and the default integer data type is ``int64``). In those latter cases: + data type of the returned array. If ``None``, the returned array must have the same data type as ``x``, unless ``x`` has an integer data type supporting a smaller range of values than the default integer data type (e.g., ``x`` has an ``int16`` or ``uint32`` data type and the default integer data type is ``int64``). In those latter cases: - - if ``x`` has a signed integer data type (e.g., ``int16``), the returned array must have the default integer data type. - - if ``x`` has an unsigned integer data type (e.g., ``uint16``), the returned array must have an unsigned integer data type having the same number of bits as the default integer data type (e.g., if the default integer data type is ``int32``, the returned array must have a ``uint32`` data type). + - if ``x`` has a signed integer data type (e.g., ``int16``), the returned array must have the default integer data type. + - if ``x`` has an unsigned integer data type (e.g., ``uint16``), the returned array must have an unsigned integer data type having the same number of bits as the default integer data type (e.g., if the default integer data type is ``int32``, the returned array must have a ``uint32`` data type). - If the data type (either specified or resolved) differs from the data type of ``x``, the input array should be cast to the specified data type before computing the product (rationale: the ``dtype`` keyword argument is intended to help prevent overflows). Default: ``None``. + If the data type (either specified or resolved) differs from the data type of ``x``, the input array should be cast to the specified data type before computing the product (rationale: the ``dtype`` keyword argument is intended to help prevent overflows). Default: ``None``. include_initial: bool - boolean indicating whether to include the initial value as the first value in the output. By convention, the initial value must be the multiplicative identity (i.e., one). Default: ``False``. + boolean indicating whether to include the initial value as the first value in the output. By convention, the initial value must be the multiplicative identity (i.e., one). Default: ``False``. Returns ------- out: array - an array containing the cumulative products. The returned array must have a data type as described by the ``dtype`` parameter above. + an array containing the cumulative products. The returned array must have a data type as described by the ``dtype`` parameter above. - Let ``N`` be the size of the axis along which to compute the cumulative product. The returned array must have a shape determined according to the following rules: + Let ``N`` be the size of the axis along which to compute the cumulative product. The returned array must have a shape determined according to the following rules: - - if ``include_initial`` is ``True``, the returned array must have the same shape as ``x``, except the size of the axis along which to compute the cumulative product must be ``N+1``. - - if ``include_initial`` is ``False``, the returned array must have the same shape as ``x``. + - if ``include_initial`` is ``True``, the returned array must have the same shape as ``x``, except the size of the axis along which to compute the cumulative product must be ``N+1``. + - if ``include_initial`` is ``False``, the returned array must have the same shape as ``x``. Notes ----- @@ -1635,32 +1639,32 @@ class cumulative_sum[TArray: Array, TDtype](Protocol): Parameters ---------- x: array - input array. Should have one or more dimensions (axes). Should have a numeric data type. + input array. Should have one or more dimensions (axes). Should have a numeric data type. axis: Optional[int] - axis along which a cumulative sum must be computed. If ``axis`` is negative, the function must determine the axis along which to compute a cumulative sum by counting from the last dimension. + axis along which a cumulative sum must be computed. If ``axis`` is negative, the function must determine the axis along which to compute a cumulative sum by counting from the last dimension. - If ``x`` is a one-dimensional array, providing an ``axis`` is optional; however, if ``x`` has more than one dimension, providing an ``axis`` is required. + If ``x`` is a one-dimensional array, providing an ``axis`` is optional; however, if ``x`` has more than one dimension, providing an ``axis`` is required. dtype: Optional[dtype] - data type of the returned array. If ``None``, the returned array must have the same data type as ``x``, unless ``x`` has an integer data type supporting a smaller range of values than the default integer data type (e.g., ``x`` has an ``int16`` or ``uint32`` data type and the default integer data type is ``int64``). In those latter cases: + data type of the returned array. If ``None``, the returned array must have the same data type as ``x``, unless ``x`` has an integer data type supporting a smaller range of values than the default integer data type (e.g., ``x`` has an ``int16`` or ``uint32`` data type and the default integer data type is ``int64``). In those latter cases: - - if ``x`` has a signed integer data type (e.g., ``int16``), the returned array must have the default integer data type. - - if ``x`` has an unsigned integer data type (e.g., ``uint16``), the returned array must have an unsigned integer data type having the same number of bits as the default integer data type (e.g., if the default integer data type is ``int32``, the returned array must have a ``uint32`` data type). + - if ``x`` has a signed integer data type (e.g., ``int16``), the returned array must have the default integer data type. + - if ``x`` has an unsigned integer data type (e.g., ``uint16``), the returned array must have an unsigned integer data type having the same number of bits as the default integer data type (e.g., if the default integer data type is ``int32``, the returned array must have a ``uint32`` data type). - If the data type (either specified or resolved) differs from the data type of ``x``, the input array should be cast to the specified data type before computing the sum (rationale: the ``dtype`` keyword argument is intended to help prevent overflows). Default: ``None``. + If the data type (either specified or resolved) differs from the data type of ``x``, the input array should be cast to the specified data type before computing the sum (rationale: the ``dtype`` keyword argument is intended to help prevent overflows). Default: ``None``. include_initial: bool - boolean indicating whether to include the initial value as the first value in the output. By convention, the initial value must be the additive identity (i.e., zero). Default: ``False``. + boolean indicating whether to include the initial value as the first value in the output. By convention, the initial value must be the additive identity (i.e., zero). Default: ``False``. Returns ------- out: array - an array containing the cumulative sums. The returned array must have a data type as described by the ``dtype`` parameter above. + an array containing the cumulative sums. The returned array must have a data type as described by the ``dtype`` parameter above. - Let ``N`` be the size of the axis along which to compute the cumulative sum. The returned array must have a shape determined according to the following rules: + Let ``N`` be the size of the axis along which to compute the cumulative sum. The returned array must have a shape determined according to the following rules: - - if ``include_initial`` is ``True``, the returned array must have the same shape as ``x``, except the size of the axis along which to compute the cumulative sum must be ``N+1``. - - if ``include_initial`` is ``False``, the returned array must have the same shape as ``x``. + - if ``include_initial`` is ``True``, the returned array must have the same shape as ``x``, except the size of the axis along which to compute the cumulative sum must be ``N+1``. + - if ``include_initial`` is ``False``, the returned array must have the same shape as ``x``. Notes ----- @@ -1673,7 +1677,7 @@ class cumulative_sum[TArray: Array, TDtype](Protocol): .. versionadded:: 2023.12 .. versionchanged:: 2024.12 - Behavior when providing a zero-dimensional array is explicitly left unspecified. + Behavior when providing a zero-dimensional array is explicitly left unspecified. """ @@ -1689,16 +1693,16 @@ class max[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a real-valued data type. + input array. Should have a real-valued data type. axis: Optional[Union[int, Tuple[int, ...]]] - axis or axes along which maximum values must be computed. By default, the maximum value must be computed over the entire array. If a tuple of integers, maximum values must be computed over multiple axes. Default: ``None``. + axis or axes along which maximum values must be computed. By default, the maximum value must be computed over the entire array. If a tuple of integers, maximum values must be computed over multiple axes. Default: ``None``. keepdims: bool - if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. + if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. Returns ------- out: array - if the maximum value was computed over the entire array, a zero-dimensional array containing the maximum value; otherwise, a non-zero-dimensional array containing the maximum values. The returned array must have the same data type as ``x``. + if the maximum value was computed over the entire array, a zero-dimensional array containing the maximum value; otherwise, a non-zero-dimensional array containing the maximum values. The returned array must have the same data type as ``x``. Notes ----- @@ -1715,7 +1719,7 @@ class max[TArray: Array](Protocol): - If ``x_i`` is ``NaN``, the maximum value is ``NaN`` (i.e., ``NaN`` values propagate). .. versionchanged:: 2023.12 - Clarified that the order of signed zeros is implementation-defined. + Clarified that the order of signed zeros is implementation-defined. """ @@ -1731,19 +1735,19 @@ class mean[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a floating-point data type. + input array. Should have a floating-point data type. axis: Optional[Union[int, Tuple[int, ...]]] - axis or axes along which arithmetic means must be computed. By default, the mean must be computed over the entire array. If a tuple of integers, arithmetic means must be computed over multiple axes. Default: ``None``. + axis or axes along which arithmetic means must be computed. By default, the mean must be computed over the entire array. If a tuple of integers, arithmetic means must be computed over multiple axes. Default: ``None``. keepdims: bool - if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. + if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. Returns ------- out: array - if the arithmetic mean was computed over the entire array, a zero-dimensional array containing the arithmetic mean; otherwise, a non-zero-dimensional array containing the arithmetic means. The returned array must have the same data type as ``x``. + if the arithmetic mean was computed over the entire array, a zero-dimensional array containing the arithmetic mean; otherwise, a non-zero-dimensional array containing the arithmetic means. The returned array must have the same data type as ``x``. - .. note:: - While this specification recommends that this function only accept input arrays having a floating-point data type, specification-compliant array libraries may choose to accept input arrays having an integer data type. While mixed data type promotion is implementation-defined, if the input array ``x`` has an integer data type, the returned array must have the default real-valued floating-point data type. + .. note:: + While this specification recommends that this function only accept input arrays having a floating-point data type, specification-compliant array libraries may choose to accept input arrays having an integer data type. While mixed data type promotion is implementation-defined, if the input array ``x`` has an integer data type, the returned array must have the default real-valued floating-point data type. Notes ----- @@ -1761,10 +1765,10 @@ class mean[TArray: Array](Protocol): - Similarly, if ``b`` is ``NaN``, the imaginary component of the result is ``NaN``. .. note:: - Array libraries, such as NumPy, PyTorch, and JAX, currently deviate from this specification in their handling of components which are ``NaN`` when computing the arithmetic mean. In general, consumers of array libraries implementing this specification should use :func:`~array_api.isnan` to test whether the result of computing the arithmetic mean over an array have a complex floating-point data type is ``NaN``, rather than relying on ``NaN`` propagation of individual components. + Array libraries, such as NumPy, PyTorch, and JAX, currently deviate from this specification in their handling of components which are ``NaN`` when computing the arithmetic mean. In general, consumers of array libraries implementing this specification should use :func:`~array_api.isnan` to test whether the result of computing the arithmetic mean over an array have a complex floating-point data type is ``NaN``, rather than relying on ``NaN`` propagation of individual components. .. versionchanged:: 2024.12 - Added complex data type support. + Added complex data type support. """ @@ -1780,16 +1784,16 @@ class min[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a real-valued data type. + input array. Should have a real-valued data type. axis: Optional[Union[int, Tuple[int, ...]]] - axis or axes along which minimum values must be computed. By default, the minimum value must be computed over the entire array. If a tuple of integers, minimum values must be computed over multiple axes. Default: ``None``. + axis or axes along which minimum values must be computed. By default, the minimum value must be computed over the entire array. If a tuple of integers, minimum values must be computed over multiple axes. Default: ``None``. keepdims: bool - if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. + if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. Returns ------- out: array - if the minimum value was computed over the entire array, a zero-dimensional array containing the minimum value; otherwise, a non-zero-dimensional array containing the minimum values. The returned array must have the same data type as ``x``. + if the minimum value was computed over the entire array, a zero-dimensional array containing the minimum value; otherwise, a non-zero-dimensional array containing the minimum values. The returned array must have the same data type as ``x``. Notes ----- @@ -1806,7 +1810,7 @@ class min[TArray: Array](Protocol): - If ``x_i`` is ``NaN``, the minimum value is ``NaN`` (i.e., ``NaN`` values propagate). .. versionchanged:: 2023.12 - Clarified that the order of signed zeros is implementation-defined. + Clarified that the order of signed zeros is implementation-defined. """ @@ -1822,25 +1826,25 @@ class prod[TArray: Array, TDtype](Protocol): Parameters ---------- x: array - input array. Should have a numeric data type. + input array. Should have a numeric data type. axis: Optional[Union[int, Tuple[int, ...]]] - axis or axes along which products must be computed. By default, the product must be computed over the entire array. If a tuple of integers, products must be computed over multiple axes. Default: ``None``. + axis or axes along which products must be computed. By default, the product must be computed over the entire array. If a tuple of integers, products must be computed over multiple axes. Default: ``None``. dtype: Optional[dtype] - data type of the returned array. If ``None``, the returned array must have the same data type as ``x``, unless ``x`` has an integer data type supporting a smaller range of values than the default integer data type (e.g., ``x`` has an ``int16`` or ``uint32`` data type and the default integer data type is ``int64``). In those latter cases: + data type of the returned array. If ``None``, the returned array must have the same data type as ``x``, unless ``x`` has an integer data type supporting a smaller range of values than the default integer data type (e.g., ``x`` has an ``int16`` or ``uint32`` data type and the default integer data type is ``int64``). In those latter cases: - - if ``x`` has a signed integer data type (e.g., ``int16``), the returned array must have the default integer data type. - - if ``x`` has an unsigned integer data type (e.g., ``uint16``), the returned array must have an unsigned integer data type having the same number of bits as the default integer data type (e.g., if the default integer data type is ``int32``, the returned array must have a ``uint32`` data type). + - if ``x`` has a signed integer data type (e.g., ``int16``), the returned array must have the default integer data type. + - if ``x`` has an unsigned integer data type (e.g., ``uint16``), the returned array must have an unsigned integer data type having the same number of bits as the default integer data type (e.g., if the default integer data type is ``int32``, the returned array must have a ``uint32`` data type). - If the data type (either specified or resolved) differs from the data type of ``x``, the input array should be cast to the specified data type before computing the sum (rationale: the ``dtype`` keyword argument is intended to help prevent overflows). Default: ``None``. + If the data type (either specified or resolved) differs from the data type of ``x``, the input array should be cast to the specified data type before computing the sum (rationale: the ``dtype`` keyword argument is intended to help prevent overflows). Default: ``None``. keepdims: bool - if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. + if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. Returns ------- out: array - if the product was computed over the entire array, a zero-dimensional array containing the product; otherwise, a non-zero-dimensional array containing the products. The returned array must have a data type as described by the ``dtype`` parameter above. + if the product was computed over the entire array, a zero-dimensional array containing the product; otherwise, a non-zero-dimensional array containing the products. The returned array must have a data type as described by the ``dtype`` parameter above. Notes ----- @@ -1853,10 +1857,10 @@ class prod[TArray: Array, TDtype](Protocol): For both real-valued and complex floating-point operands, special cases must be handled as if the operation is implemented by successive application of :func:`~array_api.multiply`. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. .. versionchanged:: 2023.12 - Required the function to return a floating-point array having the same data type as the input array when provided a floating-point array. + Required the function to return a floating-point array having the same data type as the input array when provided a floating-point array. """ @@ -1872,21 +1876,21 @@ class std[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a real-valued floating-point data type. + input array. Should have a real-valued floating-point data type. axis: Optional[Union[int, Tuple[int, ...]]] - axis or axes along which standard deviations must be computed. By default, the standard deviation must be computed over the entire array. If a tuple of integers, standard deviations must be computed over multiple axes. Default: ``None``. + axis or axes along which standard deviations must be computed. By default, the standard deviation must be computed over the entire array. If a tuple of integers, standard deviations must be computed over multiple axes. Default: ``None``. correction: Union[int, float] - degrees of freedom adjustment. Setting this parameter to a value other than ``0`` has the effect of adjusting the divisor during the calculation of the standard deviation according to ``N-c`` where ``N`` corresponds to the total number of elements over which the standard deviation is computed and ``c`` corresponds to the provided degrees of freedom adjustment. When computing the standard deviation of a population, setting this parameter to ``0`` is the standard choice (i.e., the provided array contains data constituting an entire population). When computing the corrected sample standard deviation, setting this parameter to ``1`` is the standard choice (i.e., the provided array contains data sampled from a larger population; this is commonly referred to as Bessel's correction). Default: ``0``. + degrees of freedom adjustment. Setting this parameter to a value other than ``0`` has the effect of adjusting the divisor during the calculation of the standard deviation according to ``N-c`` where ``N`` corresponds to the total number of elements over which the standard deviation is computed and ``c`` corresponds to the provided degrees of freedom adjustment. When computing the standard deviation of a population, setting this parameter to ``0`` is the standard choice (i.e., the provided array contains data constituting an entire population). When computing the corrected sample standard deviation, setting this parameter to ``1`` is the standard choice (i.e., the provided array contains data sampled from a larger population; this is commonly referred to as Bessel's correction). Default: ``0``. keepdims: bool - if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. + if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. Returns ------- out: array - if the standard deviation was computed over the entire array, a zero-dimensional array containing the standard deviation; otherwise, a non-zero-dimensional array containing the standard deviations. The returned array must have the same data type as ``x``. + if the standard deviation was computed over the entire array, a zero-dimensional array containing the standard deviation; otherwise, a non-zero-dimensional array containing the standard deviations. The returned array must have the same data type as ``x``. - .. note:: - While this specification recommends that this function only accept input arrays having a real-valued floating-point data type, specification-compliant array libraries may choose to accept input arrays having an integer data type. While mixed data type promotion is implementation-defined, if the input array ``x`` has an integer data type, the returned array must have the default real-valued floating-point data type. + .. note:: + While this specification recommends that this function only accept input arrays having a real-valued floating-point data type, specification-compliant array libraries may choose to accept input arrays having an integer data type. While mixed data type promotion is implementation-defined, if the input array ``x`` has an integer data type, the returned array must have the default real-valued floating-point data type. Notes ----- @@ -1911,25 +1915,25 @@ class sum[TArray: Array, TDtype](Protocol): Parameters ---------- x: array - input array. Should have a numeric data type. + input array. Should have a numeric data type. axis: Optional[Union[int, Tuple[int, ...]]] - axis or axes along which sums must be computed. By default, the sum must be computed over the entire array. If a tuple of integers, sums must be computed over multiple axes. Default: ``None``. + axis or axes along which sums must be computed. By default, the sum must be computed over the entire array. If a tuple of integers, sums must be computed over multiple axes. Default: ``None``. dtype: Optional[dtype] - data type of the returned array. If ``None``, the returned array must have the same data type as ``x``, unless ``x`` has an integer data type supporting a smaller range of values than the default integer data type (e.g., ``x`` has an ``int16`` or ``uint32`` data type and the default integer data type is ``int64``). In those latter cases: + data type of the returned array. If ``None``, the returned array must have the same data type as ``x``, unless ``x`` has an integer data type supporting a smaller range of values than the default integer data type (e.g., ``x`` has an ``int16`` or ``uint32`` data type and the default integer data type is ``int64``). In those latter cases: - - if ``x`` has a signed integer data type (e.g., ``int16``), the returned array must have the default integer data type. - - if ``x`` has an unsigned integer data type (e.g., ``uint16``), the returned array must have an unsigned integer data type having the same number of bits as the default integer data type (e.g., if the default integer data type is ``int32``, the returned array must have a ``uint32`` data type). + - if ``x`` has a signed integer data type (e.g., ``int16``), the returned array must have the default integer data type. + - if ``x`` has an unsigned integer data type (e.g., ``uint16``), the returned array must have an unsigned integer data type having the same number of bits as the default integer data type (e.g., if the default integer data type is ``int32``, the returned array must have a ``uint32`` data type). - If the data type (either specified or resolved) differs from the data type of ``x``, the input array should be cast to the specified data type before computing the sum (rationale: the ``dtype`` keyword argument is intended to help prevent overflows). Default: ``None``. + If the data type (either specified or resolved) differs from the data type of ``x``, the input array should be cast to the specified data type before computing the sum (rationale: the ``dtype`` keyword argument is intended to help prevent overflows). Default: ``None``. keepdims: bool - if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. + if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. Returns ------- out: array - if the sum was computed over the entire array, a zero-dimensional array containing the sum; otherwise, an array containing the sums. The returned array must have a data type as described by the ``dtype`` parameter above. + if the sum was computed over the entire array, a zero-dimensional array containing the sum; otherwise, an array containing the sums. The returned array must have a data type as described by the ``dtype`` parameter above. Notes ----- @@ -1942,10 +1946,10 @@ class sum[TArray: Array, TDtype](Protocol): For both real-valued and complex floating-point operands, special cases must be handled as if the operation is implemented by successive application of :func:`~array_api.add`. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. .. versionchanged:: 2023.12 - Required the function to return a floating-point array having the same data type as the input array when provided a floating-point array. + Required the function to return a floating-point array having the same data type as the input array when provided a floating-point array. """ @@ -1961,22 +1965,22 @@ class var[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a real-valued floating-point data type. + input array. Should have a real-valued floating-point data type. axis: Optional[Union[int, Tuple[int, ...]]] - axis or axes along which variances must be computed. By default, the variance must be computed over the entire array. If a tuple of integers, variances must be computed over multiple axes. Default: ``None``. + axis or axes along which variances must be computed. By default, the variance must be computed over the entire array. If a tuple of integers, variances must be computed over multiple axes. Default: ``None``. correction: Union[int, float] - degrees of freedom adjustment. Setting this parameter to a value other than ``0`` has the effect of adjusting the divisor during the calculation of the variance according to ``N-c`` where ``N`` corresponds to the total number of elements over which the variance is computed and ``c`` corresponds to the provided degrees of freedom adjustment. When computing the variance of a population, setting this parameter to ``0`` is the standard choice (i.e., the provided array contains data constituting an entire population). When computing the unbiased sample variance, setting this parameter to ``1`` is the standard choice (i.e., the provided array contains data sampled from a larger population; this is commonly referred to as Bessel's correction). Default: ``0``. + degrees of freedom adjustment. Setting this parameter to a value other than ``0`` has the effect of adjusting the divisor during the calculation of the variance according to ``N-c`` where ``N`` corresponds to the total number of elements over which the variance is computed and ``c`` corresponds to the provided degrees of freedom adjustment. When computing the variance of a population, setting this parameter to ``0`` is the standard choice (i.e., the provided array contains data constituting an entire population). When computing the unbiased sample variance, setting this parameter to ``1`` is the standard choice (i.e., the provided array contains data sampled from a larger population; this is commonly referred to as Bessel's correction). Default: ``0``. keepdims: bool - if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. + if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. Returns ------- out: array - if the variance was computed over the entire array, a zero-dimensional array containing the variance; otherwise, a non-zero-dimensional array containing the variances. The returned array must have the same data type as ``x``. + if the variance was computed over the entire array, a zero-dimensional array containing the variance; otherwise, a non-zero-dimensional array containing the variances. The returned array must have the same data type as ``x``. .. note:: - While this specification recommends that this function only accept input arrays having a real-valued floating-point data type, specification-compliant array libraries may choose to accept input arrays having an integer data type. While mixed data type promotion is implementation-defined, if the input array ``x`` has an integer data type, the returned array must have the default real-valued floating-point data type. + While this specification recommends that this function only accept input arrays having a real-valued floating-point data type, specification-compliant array libraries may choose to accept input arrays having an integer data type. While mixed data type promotion is implementation-defined, if the input array ``x`` has an integer data type, the returned array must have the default real-valued floating-point data type. Notes ----- @@ -2001,24 +2005,24 @@ class arange[TArray: Array, TDevice, TDtype](Protocol): Parameters ---------- start: Union[int, float] - if ``stop`` is specified, the start of interval (inclusive); otherwise, the end of the interval (exclusive). If ``stop`` is not specified, the default starting value is ``0``. + if ``stop`` is specified, the start of interval (inclusive); otherwise, the end of the interval (exclusive). If ``stop`` is not specified, the default starting value is ``0``. stop: Optional[Union[int, float]] - the end of the interval. Default: ``None``. + the end of the interval. Default: ``None``. step: Union[int, float] - the distance between two adjacent elements (``out[i+1] - out[i]``). Must not be ``0``; may be negative, this results in an empty array if ``stop >= start``. Default: ``1``. + the distance between two adjacent elements (``out[i+1] - out[i]``). Must not be ``0``; may be negative, this results in an empty array if ``stop >= start``. Default: ``1``. dtype: Optional[dtype] - output array data type. If ``dtype`` is ``None``, the output array data type must be inferred from ``start``, ``stop`` and ``step``. If those are all integers, the output array dtype must be the default integer dtype; if one or more have type ``float``, then the output array dtype must be the default real-valued floating-point data type. Default: ``None``. + output array data type. If ``dtype`` is ``None``, the output array data type must be inferred from ``start``, ``stop`` and ``step``. If those are all integers, the output array dtype must be the default integer dtype; if one or more have type ``float``, then the output array dtype must be the default real-valued floating-point data type. Default: ``None``. device: Optional[device] - device on which to place the created array. Default: ``None``. + device on which to place the created array. Default: ``None``. .. note:: - This function cannot guarantee that the interval does not include the ``stop`` value in those cases where ``step`` is not an integer and floating-point rounding errors affect the length of the output array. + This function cannot guarantee that the interval does not include the ``stop`` value in those cases where ``step`` is not an integer and floating-point rounding errors affect the length of the output array. Returns ------- out: array - a one-dimensional array containing evenly spaced values. The length of the output array must be ``ceil((stop-start)/step)`` if ``stop - start`` and ``step`` have the same sign, and length ``0`` otherwise. + a one-dimensional array containing evenly spaced values. The length of the output array must be ``ceil((stop-start)/step)`` if ``stop - start`` and ``step`` have the same sign, and length ``0`` otherwise. """ @@ -2027,58 +2031,58 @@ def __call__(self, start: int | float, /, stop: int | float | None = None, step: @runtime_checkable -class asarray[TSupportsbufferprotocol, TArray: Array, TDevice, TDtype](Protocol): +class asarray[TArray: Array, TDevice, TDtype](Protocol): r""" Convert the input to an array. Parameters ---------- obj: Union[array, bool, int, float, complex, NestedSequence[bool | int | float | complex], SupportsBufferProtocol] - object to be converted to an array. May be a Python scalar, a (possibly nested) sequence of Python scalars, or an object supporting the Python buffer protocol. + object to be converted to an array. May be a Python scalar, a (possibly nested) sequence of Python scalars, or an object supporting the Python buffer protocol. - .. admonition:: Tip - :class: important + .. admonition:: Tip + :class: important - An object supporting the buffer protocol can be turned into a memoryview through ``memoryview(obj)``. + An object supporting the buffer protocol can be turned into a memoryview through ``memoryview(obj)``. dtype: Optional[dtype] - output array data type. If ``dtype`` is ``None``, the output array data type must be inferred from the data type(s) in ``obj``. If all input values are Python scalars, then, in order of precedence, + output array data type. If ``dtype`` is ``None``, the output array data type must be inferred from the data type(s) in ``obj``. If all input values are Python scalars, then, in order of precedence, - - if all values are of type ``bool``, the output data type must be ``bool``. - - if all values are of type ``int`` or are a mixture of ``bool`` and ``int``, the output data type must be the default integer data type. - - if one or more values are ``complex`` numbers, the output data type must be the default complex floating-point data type. - - if one or more values are ``float``\\s, the output data type must be the default real-valued floating-point data type. + - if all values are of type ``bool``, the output data type must be ``bool``. + - if all values are of type ``int`` or are a mixture of ``bool`` and ``int``, the output data type must be the default integer data type. + - if one or more values are ``complex`` numbers, the output data type must be the default complex floating-point data type. + - if one or more values are ``float``\\s, the output data type must be the default real-valued floating-point data type. - Default: ``None``. + Default: ``None``. - .. admonition:: Note - :class: note + .. admonition:: Note + :class: note - If ``dtype`` is not ``None``, then array conversions should obey :ref:`type-promotion` rules. Conversions not specified according to :ref:`type-promotion` rules may or may not be permitted by a conforming array library. To perform an explicit cast, use :func:`array_api.astype`. + If ``dtype`` is not ``None``, then array conversions should obey :ref:`type-promotion` rules. Conversions not specified according to :ref:`type-promotion` rules may or may not be permitted by a conforming array library. To perform an explicit cast, use :func:`array_api.astype`. - .. note:: - If an input value exceeds the precision of the resolved output array data type, behavior is left unspecified and, thus, implementation-defined. + .. note:: + If an input value exceeds the precision of the resolved output array data type, behavior is left unspecified and, thus, implementation-defined. device: Optional[device] - device on which to place the created array. If ``device`` is ``None`` and ``obj`` is an array, the output array device must be inferred from ``obj``. Default: ``None``. + device on which to place the created array. If ``device`` is ``None`` and ``obj`` is an array, the output array device must be inferred from ``obj``. Default: ``None``. copy: Optional[bool] - boolean indicating whether or not to copy the input. If ``True``, the function must always copy (see :ref:`copy-keyword-argument`). If ``False``, the function must never copy for input which supports the buffer protocol and must raise a ``ValueError`` in case a copy would be necessary. If ``None``, the function must reuse existing memory buffer if possible and copy otherwise. Default: ``None``. + boolean indicating whether or not to copy the input. If ``True``, the function must always copy (see :ref:`copy-keyword-argument`). If ``False``, the function must never copy for input which supports the buffer protocol and must raise a ``ValueError`` in case a copy would be necessary. If ``None``, the function must reuse existing memory buffer if possible and copy otherwise. Default: ``None``. Returns ------- out: array - an array containing the data from ``obj``. + an array containing the data from ``obj``. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @abstractmethod - def __call__(self, obj: TArray | bool | int | float | complex | NestedSequence | TSupportsbufferprotocol, /, *, dtype: TDtype | None = None, device: TDevice | None = None, copy: bool | None = None) -> TArray: ... + def __call__(self, obj: TArray | bool | int | float | complex | NestedSequence | SupportsBufferProtocol, /, *, dtype: TDtype | None = None, device: TDevice | None = None, copy: bool | None = None) -> TArray: ... @runtime_checkable @@ -2089,16 +2093,16 @@ class empty[TArray: Array, TDevice, TDtype](Protocol): Parameters ---------- shape: Union[int, Tuple[int, ...]] - output array shape. + output array shape. dtype: Optional[dtype] - output array data type. If ``dtype`` is ``None``, the output array data type must be the default real-valued floating-point data type. Default: ``None``. + output array data type. If ``dtype`` is ``None``, the output array data type must be the default real-valued floating-point data type. Default: ``None``. device: Optional[device] - device on which to place the created array. Default: ``None``. + device on which to place the created array. Default: ``None``. Returns ------- out: array - an array containing uninitialized data. + an array containing uninitialized data. """ @@ -2114,16 +2118,16 @@ class empty_like[TArray: Array, TDevice, TDtype](Protocol): Parameters ---------- x: array - input array from which to derive the output array shape. + input array from which to derive the output array shape. dtype: Optional[dtype] - output array data type. If ``dtype`` is ``None``, the output array data type must be inferred from ``x``. Default: ``None``. + output array data type. If ``dtype`` is ``None``, the output array data type must be inferred from ``x``. Default: ``None``. device: Optional[device] - device on which to place the created array. If ``device`` is ``None``, the output array device must be inferred from ``x``. Default: ``None``. + device on which to place the created array. If ``device`` is ``None``, the output array device must be inferred from ``x``. Default: ``None``. Returns ------- out: array - an array having the same shape as ``x`` and containing uninitialized data. + an array having the same shape as ``x`` and containing uninitialized data. """ @@ -2137,31 +2141,31 @@ class eye[TArray: Array, TDevice, TDtype](Protocol): Returns a two-dimensional array with ones on the ``k``\\th diagonal and zeros elsewhere. .. note:: - An output array having a complex floating-point data type must have the value ``1 + 0j`` along the ``k``\\th diagonal and ``0 + 0j`` elsewhere. + An output array having a complex floating-point data type must have the value ``1 + 0j`` along the ``k``\\th diagonal and ``0 + 0j`` elsewhere. Parameters ---------- n_rows: int - number of rows in the output array. + number of rows in the output array. n_cols: Optional[int] - number of columns in the output array. If ``None``, the default number of columns in the output array is equal to ``n_rows``. Default: ``None``. + number of columns in the output array. If ``None``, the default number of columns in the output array is equal to ``n_rows``. Default: ``None``. k: int - index of the diagonal. A positive value refers to an upper diagonal, a negative value to a lower diagonal, and ``0`` to the main diagonal. Default: ``0``. + index of the diagonal. A positive value refers to an upper diagonal, a negative value to a lower diagonal, and ``0`` to the main diagonal. Default: ``0``. dtype: Optional[dtype] - output array data type. If ``dtype`` is ``None``, the output array data type must be the default real-valued floating-point data type. Default: ``None``. + output array data type. If ``dtype`` is ``None``, the output array data type must be the default real-valued floating-point data type. Default: ``None``. device: Optional[device] - device on which to place the created array. Default: ``None``. + device on which to place the created array. Default: ``None``. Returns ------- out: array - an array where all elements are equal to zero, except for the ``k``\\th diagonal, whose values are equal to one. + an array where all elements are equal to zero, except for the ``k``\\th diagonal, whose values are equal to one. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -2177,44 +2181,44 @@ class from_dlpack[TArray: Array, TDevice](Protocol): Parameters ---------- x: object - input (array) object. + input (array) object. device: Optional[device] - device on which to place the created array. If ``device`` is ``None`` and ``x`` supports DLPack, the output array must be on the same device as ``x``. Default: ``None``. + device on which to place the created array. If ``device`` is ``None`` and ``x`` supports DLPack, the output array must be on the same device as ``x``. Default: ``None``. - The v2023.12 standard only mandates that a compliant library should offer a way for ``from_dlpack`` to return an array - whose underlying memory is accessible to the Python interpreter, when the corresponding ``device`` is provided. If the - array library does not support such cases at all, the function must raise ``BufferError``. If a copy must be made to - enable this support but ``copy`` is set to ``False``, the function must raise ``ValueError``. + The v2023.12 standard only mandates that a compliant library should offer a way for ``from_dlpack`` to return an array + whose underlying memory is accessible to the Python interpreter, when the corresponding ``device`` is provided. If the + array library does not support such cases at all, the function must raise ``BufferError``. If a copy must be made to + enable this support but ``copy`` is set to ``False``, the function must raise ``ValueError``. - Other device kinds will be considered for standardization in a future version of this API standard. + Other device kinds will be considered for standardization in a future version of this API standard. copy: Optional[bool] - boolean indicating whether or not to copy the input. If ``True``, the function must always copy. If ``False``, the function must never copy, and raise ``BufferError`` in case a copy is deemed necessary (e.g. if a cross-device data movement is requested, and it is not possible without a copy). If ``None``, the function must reuse the existing memory buffer if possible and copy otherwise. Default: ``None``. + boolean indicating whether or not to copy the input. If ``True``, the function must always copy. If ``False``, the function must never copy, and raise ``BufferError`` in case a copy is deemed necessary (e.g. if a cross-device data movement is requested, and it is not possible without a copy). If ``None``, the function must reuse the existing memory buffer if possible and copy otherwise. Default: ``None``. Returns ------- out: array - an array containing the data in ``x``. + an array containing the data in ``x``. - .. admonition:: Note - :class: note + .. admonition:: Note + :class: note - The returned array may be either a copy or a view. See :ref:`data-interchange` for details. + The returned array may be either a copy or a view. See :ref:`data-interchange` for details. Raises ------ BufferError - The ``__dlpack__`` and ``__dlpack_device__`` methods on the input array - may raise ``BufferError`` when the data cannot be exported as DLPack - (e.g., incompatible dtype, strides, or device). It may also raise other errors - when export fails for other reasons (e.g., not enough memory available - to materialize the data). ``from_dlpack`` must propagate such - exceptions. + The ``__dlpack__`` and ``__dlpack_device__`` methods on the input array + may raise ``BufferError`` when the data cannot be exported as DLPack + (e.g., incompatible dtype, strides, or device). It may also raise other errors + when export fails for other reasons (e.g., not enough memory available + to materialize the data). ``from_dlpack`` must propagate such + exceptions. AttributeError - If the ``__dlpack__`` and ``__dlpack_device__`` methods are not present - on the input array. This may happen for libraries that are never able - to export their data with DLPack. + If the ``__dlpack__`` and ``__dlpack_device__`` methods are not present + on the input array. This may happen for libraries that are never able + to export their data with DLPack. ValueError - If data exchange is possible via an explicit copy but ``copy`` is set to ``False``. + If data exchange is possible via an explicit copy but ``copy`` is set to ``False``. Notes ----- @@ -2226,24 +2230,24 @@ class from_dlpack[TArray: Array, TDevice](Protocol): .. code:: python - def func(x, y): - xp_x = x.__array_namespace__() - xp_y = y.__array_namespace__() + def func(x, y): + xp_x = x.__array_namespace__() + xp_y = y.__array_namespace__() - # Other functions than `from_dlpack` only work if both arrays are from the same library. So if - # `y` is from a different one than `x`, let's convert `y` into an array of the same type as `x`: - if not xp_x == xp_y: - y = xp_x.from_dlpack(y, copy=True, device=x.device) + # Other functions than `from_dlpack` only work if both arrays are from the same library. So if + # `y` is from a different one than `x`, let's convert `y` into an array of the same type as `x`: + if not xp_x == xp_y: + y = xp_x.from_dlpack(y, copy=True, device=x.device) - # From now on use `xp_x.xxxxx` functions, as both arrays are from the library `xp_x` - ... + # From now on use `xp_x.xxxxx` functions, as both arrays are from the library `xp_x` + ... .. versionchanged:: 2023.12 - Required exceptions to address unsupported use cases. + Required exceptions to address unsupported use cases. .. versionchanged:: 2023.12 - Added device and copy support. + Added device and copy support. """ @@ -2259,33 +2263,33 @@ class full[TArray: Array, TDevice, TDtype](Protocol): Parameters ---------- shape: Union[int, Tuple[int, ...]] - output array shape. + output array shape. fill_value: Union[bool, int, float, complex] - fill value. + fill value. dtype: Optional[dtype] - output array data type. If ``dtype`` is ``None``, the output array data type must be inferred from ``fill_value`` according to the following rules: + output array data type. If ``dtype`` is ``None``, the output array data type must be inferred from ``fill_value`` according to the following rules: - - If the fill value is an ``int``, the output array data type must be the default integer data type. - - If the fill value is a ``float``, the output array data type must be the default real-valued floating-point data type. - - If the fill value is a ``complex`` number, the output array data type must be the default complex floating-point data type. - - If the fill value is a ``bool``, the output array must have a boolean data type. Default: ``None``. + - If the fill value is an ``int``, the output array data type must be the default integer data type. + - If the fill value is a ``float``, the output array data type must be the default real-valued floating-point data type. + - If the fill value is a ``complex`` number, the output array data type must be the default complex floating-point data type. + - If the fill value is a ``bool``, the output array must have a boolean data type. Default: ``None``. - .. note:: - If the ``fill_value`` exceeds the precision of the resolved default output array data type, behavior is left unspecified and, thus, implementation-defined. + .. note:: + If the ``fill_value`` exceeds the precision of the resolved default output array data type, behavior is left unspecified and, thus, implementation-defined. device: Optional[device] - device on which to place the created array. Default: ``None``. + device on which to place the created array. Default: ``None``. Returns ------- out: array - an array where every element is equal to ``fill_value``. + an array where every element is equal to ``fill_value``. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -2301,31 +2305,31 @@ class full_like[TArray: Array, TDevice, TDtype](Protocol): Parameters ---------- x: array - input array from which to derive the output array shape. + input array from which to derive the output array shape. fill_value: Union[bool, int, float, complex] - fill value. + fill value. dtype: Optional[dtype] - output array data type. If ``dtype`` is ``None``, the output array data type must be inferred from ``x``. Default: ``None``. + output array data type. If ``dtype`` is ``None``, the output array data type must be inferred from ``x``. Default: ``None``. - .. note:: - If the ``fill_value`` exceeds the precision of the resolved output array data type, behavior is unspecified and, thus, implementation-defined. + .. note:: + If the ``fill_value`` exceeds the precision of the resolved output array data type, behavior is unspecified and, thus, implementation-defined. - .. note:: - If the ``fill_value`` has a data type which is not of the same data type kind (boolean, integer, or floating-point) as the resolved output array data type (see :ref:`type-promotion`), behavior is unspecified and, thus, implementation-defined. + .. note:: + If the ``fill_value`` has a data type which is not of the same data type kind (boolean, integer, or floating-point) as the resolved output array data type (see :ref:`type-promotion`), behavior is unspecified and, thus, implementation-defined. device: Optional[device] - device on which to place the created array. If ``device`` is ``None``, the output array device must be inferred from ``x``. Default: ``None``. + device on which to place the created array. If ``device`` is ``None``, the output array device must be inferred from ``x``. Default: ``None``. Returns ------- out: array - an array having the same shape as ``x`` and where every element is equal to ``fill_value``. + an array having the same shape as ``x`` and where every element is equal to ``fill_value``. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -2341,59 +2345,59 @@ class linspace[TArray: Array, TDevice, TDtype](Protocol): Let :math:`N` be the number of generated values (which is either ``num`` or ``num+1`` depending on whether ``endpoint`` is ``True`` or ``False``, respectively). For real-valued output arrays, the spacing between values is given by .. math:: - \\Delta_{\\textrm{real}} = \\frac{\\textrm{stop} - \\textrm{start}}{N - 1} + \\Delta_{\\textrm{real}} = \\frac{\\textrm{stop} - \\textrm{start}}{N - 1} For complex output arrays, let ``a = real(start)``, ``b = imag(start)``, ``c = real(stop)``, and ``d = imag(stop)``. The spacing between complex values is given by .. math:: - \\Delta_{\\textrm{complex}} = \\frac{c-a}{N-1} + \\frac{d-b}{N-1} j + \\Delta_{\\textrm{complex}} = \\frac{c-a}{N-1} + \\frac{d-b}{N-1} j Parameters ---------- start: Union[int, float, complex] - the start of the interval. + the start of the interval. stop: Union[int, float, complex] - the end of the interval. If ``endpoint`` is ``False``, the function must generate a sequence of ``num+1`` evenly spaced numbers starting with ``start`` and ending with ``stop`` and exclude the ``stop`` from the returned array such that the returned array consists of evenly spaced numbers over the half-open interval ``[start, stop)``. If ``endpoint`` is ``True``, the output array must consist of evenly spaced numbers over the closed interval ``[start, stop]``. Default: ``True``. + the end of the interval. If ``endpoint`` is ``False``, the function must generate a sequence of ``num+1`` evenly spaced numbers starting with ``start`` and ending with ``stop`` and exclude the ``stop`` from the returned array such that the returned array consists of evenly spaced numbers over the half-open interval ``[start, stop)``. If ``endpoint`` is ``True``, the output array must consist of evenly spaced numbers over the closed interval ``[start, stop]``. Default: ``True``. - .. note:: - The step size changes when `endpoint` is `False`. + .. note:: + The step size changes when `endpoint` is `False`. num: int - number of samples. Must be a nonnegative integer value. + number of samples. Must be a nonnegative integer value. dtype: Optional[dtype] - output array data type. Should be a floating-point data type. If ``dtype`` is ``None``, + output array data type. Should be a floating-point data type. If ``dtype`` is ``None``, - - if either ``start`` or ``stop`` is a ``complex`` number, the output data type must be the default complex floating-point data type. - - if both ``start`` and ``stop`` are real-valued, the output data type must be the default real-valued floating-point data type. + - if either ``start`` or ``stop`` is a ``complex`` number, the output data type must be the default complex floating-point data type. + - if both ``start`` and ``stop`` are real-valued, the output data type must be the default real-valued floating-point data type. - Default: ``None``. + Default: ``None``. - .. admonition:: Note - :class: note + .. admonition:: Note + :class: note - If ``dtype`` is not ``None``, conversion of ``start`` and ``stop`` should obey :ref:`type-promotion` rules. Conversions not specified according to :ref:`type-promotion` rules may or may not be permitted by a conforming array library. + If ``dtype`` is not ``None``, conversion of ``start`` and ``stop`` should obey :ref:`type-promotion` rules. Conversions not specified according to :ref:`type-promotion` rules may or may not be permitted by a conforming array library. device: Optional[device] - device on which to place the created array. Default: ``None``. + device on which to place the created array. Default: ``None``. endpoint: bool - boolean indicating whether to include ``stop`` in the interval. Default: ``True``. + boolean indicating whether to include ``stop`` in the interval. Default: ``True``. Returns ------- out: array - a one-dimensional array containing evenly spaced values. + a one-dimensional array containing evenly spaced values. Notes ----- .. note:: - While this specification recommends that this function only return arrays having a floating-point data type, specification-compliant array libraries may choose to support output arrays having an integer data type (e.g., due to backward compatibility concerns). However, function behavior when generating integer output arrays is unspecified and, thus, is implementation-defined. Accordingly, using this function to generate integer output arrays is not portable. + While this specification recommends that this function only return arrays having a floating-point data type, specification-compliant array libraries may choose to support output arrays having an integer data type (e.g., due to backward compatibility concerns). However, function behavior when generating integer output arrays is unspecified and, thus, is implementation-defined. Accordingly, using this function to generate integer output arrays is not portable. .. note:: - As mixed data type promotion is implementation-defined, behavior when ``start`` or ``stop`` exceeds the maximum safe integer of an output floating-point data type is implementation-defined. An implementation may choose to overflow or raise an exception. + As mixed data type promotion is implementation-defined, behavior when ``start`` or ``stop`` exceeds the maximum safe integer of an output floating-point data type is implementation-defined. An implementation may choose to overflow or raise an exception. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -2409,29 +2413,29 @@ class meshgrid[TArray: Array](Protocol): Parameters ---------- arrays: array - an arbitrary number of one-dimensional arrays representing grid coordinates. Each array should have the same numeric data type. + an arbitrary number of one-dimensional arrays representing grid coordinates. Each array should have the same numeric data type. indexing: Literal["xy", "ij"] - Cartesian ``'xy'`` or matrix ``'ij'`` indexing of output. If provided zero or one one-dimensional vector(s) (i.e., the zero- and one-dimensional cases, respectively), the ``indexing`` keyword has no effect and should be ignored. Default: ``'xy'``. + Cartesian ``'xy'`` or matrix ``'ij'`` indexing of output. If provided zero or one one-dimensional vector(s) (i.e., the zero- and one-dimensional cases, respectively), the ``indexing`` keyword has no effect and should be ignored. Default: ``'xy'``. Returns ------- out: List[array] - list of N arrays, where ``N`` is the number of provided one-dimensional input arrays. Each returned array must have rank ``N``. For ``N`` one-dimensional arrays having lengths ``Ni = len(xi)``, + list of N arrays, where ``N`` is the number of provided one-dimensional input arrays. Each returned array must have rank ``N``. For ``N`` one-dimensional arrays having lengths ``Ni = len(xi)``, - - if matrix indexing ``ij``, then each returned array must have the shape ``(N1, N2, N3, ..., Nn)``. - - if Cartesian indexing ``xy``, then each returned array must have shape ``(N2, N1, N3, ..., Nn)``. + - if matrix indexing ``ij``, then each returned array must have the shape ``(N1, N2, N3, ..., Nn)``. + - if Cartesian indexing ``xy``, then each returned array must have shape ``(N2, N1, N3, ..., Nn)``. - Accordingly, for the two-dimensional case with input one-dimensional arrays of length ``M`` and ``N``, if matrix indexing ``ij``, then each returned array must have shape ``(M, N)``, and, if Cartesian indexing ``xy``, then each returned array must have shape ``(N, M)``. + Accordingly, for the two-dimensional case with input one-dimensional arrays of length ``M`` and ``N``, if matrix indexing ``ij``, then each returned array must have shape ``(M, N)``, and, if Cartesian indexing ``xy``, then each returned array must have shape ``(N, M)``. - Similarly, for the three-dimensional case with input one-dimensional arrays of length ``M``, ``N``, and ``P``, if matrix indexing ``ij``, then each returned array must have shape ``(M, N, P)``, and, if Cartesian indexing ``xy``, then each returned array must have shape ``(N, M, P)``. + Similarly, for the three-dimensional case with input one-dimensional arrays of length ``M``, ``N``, and ``P``, if matrix indexing ``ij``, then each returned array must have shape ``(M, N, P)``, and, if Cartesian indexing ``xy``, then each returned array must have shape ``(N, M, P)``. - Each returned array should have the same data type as the input arrays. + Each returned array should have the same data type as the input arrays. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -2445,27 +2449,27 @@ class ones[TArray: Array, TDevice, TDtype](Protocol): Returns a new array having a specified ``shape`` and filled with ones. .. note:: - An output array having a complex floating-point data type must contain complex numbers having a real component equal to one and an imaginary component equal to zero (i.e., ``1 + 0j``). + An output array having a complex floating-point data type must contain complex numbers having a real component equal to one and an imaginary component equal to zero (i.e., ``1 + 0j``). Parameters ---------- shape: Union[int, Tuple[int, ...]] - output array shape. + output array shape. dtype: Optional[dtype] - output array data type. If ``dtype`` is ``None``, the output array data type must be the default real-valued floating-point data type. Default: ``None``. + output array data type. If ``dtype`` is ``None``, the output array data type must be the default real-valued floating-point data type. Default: ``None``. device: Optional[device] - device on which to place the created array. Default: ``None``. + device on which to place the created array. Default: ``None``. Returns ------- out: array - an array containing ones. + an array containing ones. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -2479,27 +2483,27 @@ class ones_like[TArray: Array, TDevice, TDtype](Protocol): Returns a new array filled with ones and having the same ``shape`` as an input array ``x``. .. note:: - An output array having a complex floating-point data type must contain complex numbers having a real component equal to one and an imaginary component equal to zero (i.e., ``1 + 0j``). + An output array having a complex floating-point data type must contain complex numbers having a real component equal to one and an imaginary component equal to zero (i.e., ``1 + 0j``). Parameters ---------- x: array - input array from which to derive the output array shape. + input array from which to derive the output array shape. dtype: Optional[dtype] - output array data type. If ``dtype`` is ``None``, the output array data type must be inferred from ``x``. Default: ``None``. + output array data type. If ``dtype`` is ``None``, the output array data type must be inferred from ``x``. Default: ``None``. device: Optional[device] - device on which to place the created array. If ``device`` is ``None``, the output array device must be inferred from ``x``. Default: ``None``. + device on which to place the created array. If ``device`` is ``None``, the output array device must be inferred from ``x``. Default: ``None``. Returns ------- out: array - an array having the same shape as ``x`` and filled with ones. + an array having the same shape as ``x`` and filled with ones. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -2513,22 +2517,22 @@ class tril[TArray: Array](Protocol): Returns the lower triangular part of a matrix (or a stack of matrices) ``x``. .. note:: - The lower triangular part of the matrix is defined as the elements on and below the specified diagonal ``k``. + The lower triangular part of the matrix is defined as the elements on and below the specified diagonal ``k``. Parameters ---------- x: array - input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. + input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. k: int - diagonal above which to zero elements. If ``k = 0``, the diagonal is the main diagonal. If ``k < 0``, the diagonal is below the main diagonal. If ``k > 0``, the diagonal is above the main diagonal. Default: ``0``. + diagonal above which to zero elements. If ``k = 0``, the diagonal is the main diagonal. If ``k < 0``, the diagonal is below the main diagonal. If ``k > 0``, the diagonal is above the main diagonal. Default: ``0``. - .. note:: - The main diagonal is defined as the set of indices ``{(i, i)}`` for ``i`` on the interval ``[0, min(M, N) - 1]``. + .. note:: + The main diagonal is defined as the set of indices ``{(i, i)}`` for ``i`` on the interval ``[0, min(M, N) - 1]``. Returns ------- out: array - an array containing the lower triangular part(s). The returned array must have the same shape and data type as ``x``. All elements above the specified diagonal ``k`` must be zeroed. The returned array should be allocated on the same device as ``x``. + an array containing the lower triangular part(s). The returned array must have the same shape and data type as ``x``. All elements above the specified diagonal ``k`` must be zeroed. The returned array should be allocated on the same device as ``x``. """ @@ -2542,22 +2546,22 @@ class triu[TArray: Array](Protocol): Returns the upper triangular part of a matrix (or a stack of matrices) ``x``. .. note:: - The upper triangular part of the matrix is defined as the elements on and above the specified diagonal ``k``. + The upper triangular part of the matrix is defined as the elements on and above the specified diagonal ``k``. Parameters ---------- x: array - input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. + input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. k: int - diagonal below which to zero elements. If ``k = 0``, the diagonal is the main diagonal. If ``k < 0``, the diagonal is below the main diagonal. If ``k > 0``, the diagonal is above the main diagonal. Default: ``0``. + diagonal below which to zero elements. If ``k = 0``, the diagonal is the main diagonal. If ``k < 0``, the diagonal is below the main diagonal. If ``k > 0``, the diagonal is above the main diagonal. Default: ``0``. - .. note:: - The main diagonal is defined as the set of indices ``{(i, i)}`` for ``i`` on the interval ``[0, min(M, N) - 1]``. + .. note:: + The main diagonal is defined as the set of indices ``{(i, i)}`` for ``i`` on the interval ``[0, min(M, N) - 1]``. Returns ------- out: array - an array containing the upper triangular part(s). The returned array must have the same shape and data type as ``x``. All elements below the specified diagonal ``k`` must be zeroed. The returned array should be allocated on the same device as ``x``. + an array containing the upper triangular part(s). The returned array must have the same shape and data type as ``x``. All elements below the specified diagonal ``k`` must be zeroed. The returned array should be allocated on the same device as ``x``. """ @@ -2573,16 +2577,16 @@ class zeros[TArray: Array, TDevice, TDtype](Protocol): Parameters ---------- shape: Union[int, Tuple[int, ...]] - output array shape. + output array shape. dtype: Optional[dtype] - output array data type. If ``dtype`` is ``None``, the output array data type must be the default real-valued floating-point data type. Default: ``None``. + output array data type. If ``dtype`` is ``None``, the output array data type must be the default real-valued floating-point data type. Default: ``None``. device: Optional[device] - device on which to place the created array. Default: ``None``. + device on which to place the created array. Default: ``None``. Returns ------- out: array - an array containing zeros. + an array containing zeros. """ @@ -2598,16 +2602,16 @@ class zeros_like[TArray: Array, TDevice, TDtype](Protocol): Parameters ---------- x: array - input array from which to derive the output array shape. + input array from which to derive the output array shape. dtype: Optional[dtype] - output array data type. If ``dtype`` is ``None``, the output array data type must be inferred from ``x``. Default: ``None``. + output array data type. If ``dtype`` is ``None``, the output array data type must be inferred from ``x``. Default: ``None``. device: Optional[device] - device on which to place the created array. If ``device`` is ``None``, the output array device must be inferred from ``x``. Default: ``None``. + device on which to place the created array. If ``device`` is ``None``, the output array device must be inferred from ``x``. Default: ``None``. Returns ------- out: array - an array having the same shape as ``x`` and filled with zeros. + an array having the same shape as ``x`` and filled with zeros. """ @@ -2625,39 +2629,39 @@ class cholesky[TArray: Array](Protocol): The lower **Cholesky decomposition** of a complex Hermitian or real symmetric positive-definite matrix :math:`x \\in\\ \\mathbb{K}^{n \\times n}` is defined as .. math:: - x = LL^{H} \\qquad \\text{L $\\in\\ \\mathbb{K}^{n \\times n}$} + x = LL^{H} \\qquad \\text{L $\\in\\ \\mathbb{K}^{n \\times n}$} where :math:`L` is a lower triangular matrix and :math:`L^{H}` is the conjugate transpose when :math:`L` is complex-valued and the transpose when :math:`L` is real-valued. The upper Cholesky decomposition is defined similarly .. math:: - x = U^{H}U \\qquad \\text{U $\\in\\ \\mathbb{K}^{n \\times n}$} + x = U^{H}U \\qquad \\text{U $\\in\\ \\mathbb{K}^{n \\times n}$} where :math:`U` is an upper triangular matrix. When ``x`` is a stack of matrices, the function must compute the Cholesky decomposition for each matrix in the stack. .. note:: - Whether an array library explicitly checks whether an input array is Hermitian or a symmetric positive-definite matrix (or a stack of matrices) is implementation-defined. + Whether an array library explicitly checks whether an input array is Hermitian or a symmetric positive-definite matrix (or a stack of matrices) is implementation-defined. Parameters ---------- x: array - input array having shape ``(..., M, M)`` and whose innermost two dimensions form square complex Hermitian or real symmetric positive-definite matrices. Should have a floating-point data type. + input array having shape ``(..., M, M)`` and whose innermost two dimensions form square complex Hermitian or real symmetric positive-definite matrices. Should have a floating-point data type. upper: bool - If ``True``, the result must be the upper-triangular Cholesky factor :math:`U`. If ``False``, the result must be the lower-triangular Cholesky factor :math:`L`. Default: ``False``. + If ``True``, the result must be the upper-triangular Cholesky factor :math:`U`. If ``False``, the result must be the lower-triangular Cholesky factor :math:`L`. Default: ``False``. Returns ------- out: array - an array containing the Cholesky factors for each square matrix. If ``upper`` is ``False``, the returned array must contain lower-triangular matrices; otherwise, the returned array must contain upper-triangular matrices. The returned array must have a floating-point data type determined by :ref:`type-promotion` and must have the same shape as ``x``. + an array containing the Cholesky factors for each square matrix. If ``upper`` is ``False``, the returned array must contain lower-triangular matrices; otherwise, the returned array must contain upper-triangular matrices. The returned array must have a floating-point data type determined by :ref:`type-promotion` and must have the same shape as ``x``. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -2675,20 +2679,20 @@ class cross[TArray: Array](Protocol): Parameters ---------- x1: array - first input array. Must have a numeric data type. The size of the axis over which the cross product is to be computed must be equal to 3. + first input array. Must have a numeric data type. The size of the axis over which the cross product is to be computed must be equal to 3. x2: array - second input array. Must be broadcast compatible with ``x1`` along all axes other than the axis along which the cross-product is computed (see :ref:`broadcasting`). The size of the axis over which the cross product is to be computed must be equal to 3. Must have a numeric data type. + second input array. Must be broadcast compatible with ``x1`` along all axes other than the axis along which the cross-product is computed (see :ref:`broadcasting`). The size of the axis over which the cross product is to be computed must be equal to 3. Must have a numeric data type. - .. note:: - The compute axis (dimension) must not be broadcasted. + .. note:: + The compute axis (dimension) must not be broadcasted. axis: int - the axis (dimension) of ``x1`` and ``x2`` containing the vectors for which to compute the cross product. Should be an integer on the interval ``[-N, -1]``, where ``N`` is ``min(x1.ndim, x2.ndim)``. The function must determine the axis along which to compute the cross product by counting backward from the last dimension (where ``-1`` refers to the last dimension). By default, the function must compute the cross product over the last axis. Default: ``-1``. + the axis (dimension) of ``x1`` and ``x2`` containing the vectors for which to compute the cross product. Should be an integer on the interval ``[-N, -1]``, where ``N`` is ``min(x1.ndim, x2.ndim)``. The function must determine the axis along which to compute the cross product by counting backward from the last dimension (where ``-1`` refers to the last dimension). By default, the function must compute the cross product over the last axis. Default: ``-1``. Returns ------- out: array - an array containing the cross products. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the cross products. The returned array must have a data type determined by :ref:`type-promotion`. Notes @@ -2698,13 +2702,13 @@ class cross[TArray: Array](Protocol): - if the size of the axis over which to compute the cross product is not equal to ``3`` (before broadcasting) for both ``x1`` and ``x2``. .. versionchanged:: 2022.12 - Added support for broadcasting. + Added support for broadcasting. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. .. versionchanged:: 2023.12 - Restricted broadcasting to only non-compute axes and required that ``axis`` be a negative integer. + Restricted broadcasting to only non-compute axes and required that ``axis`` be a negative integer. """ @@ -2720,18 +2724,18 @@ class det[TArray: Array](Protocol): Parameters ---------- x: array - input array having shape ``(..., M, M)`` and whose innermost two dimensions form square matrices. Should have a floating-point data type. + input array having shape ``(..., M, M)`` and whose innermost two dimensions form square matrices. Should have a floating-point data type. Returns ------- out: array - if ``x`` is a two-dimensional array, a zero-dimensional array containing the determinant; otherwise, a non-zero dimensional array containing the determinant for each square matrix. The returned array must have the same data type as ``x``. + if ``x`` is a two-dimensional array, a zero-dimensional array containing the determinant; otherwise, a non-zero dimensional array containing the determinant for each square matrix. The returned array must have the same data type as ``x``. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -2747,20 +2751,20 @@ class diagonal[TArray: Array](Protocol): Parameters ---------- x: array - input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. + input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. offset: int - offset specifying the off-diagonal relative to the main diagonal. + offset specifying the off-diagonal relative to the main diagonal. - - ``offset = 0``: the main diagonal. - - ``offset > 0``: off-diagonal above the main diagonal. - - ``offset < 0``: off-diagonal below the main diagonal. + - ``offset = 0``: the main diagonal. + - ``offset > 0``: off-diagonal above the main diagonal. + - ``offset < 0``: off-diagonal below the main diagonal. - Default: `0`. + Default: `0`. Returns ------- out: array - an array containing the diagonals and whose shape is determined by removing the last two dimensions and appending a dimension equal to the size of the resulting diagonals. The returned array must have the same data type as ``x``. + an array containing the diagonals and whose shape is determined by removing the last two dimensions and appending a dimension equal to the size of the resulting diagonals. The returned array must have the same data type as ``x``. """ @@ -2778,45 +2782,45 @@ class eigh[TArray: Array](Protocol): The **eigenvalue decomposition** of a complex Hermitian or real symmetric matrix :math:`x \\in\\ \\mathbb{K}^{n \\times n}` is defined as .. math:: - x = Q \\Lambda Q^H + x = Q \\Lambda Q^H with :math:`Q \\in \\mathbb{K}^{n \\times n}` and :math:`\\Lambda \\in \\mathbb{R}^n` and where :math:`Q^H` is the conjugate transpose when :math:`Q` is complex and the transpose when :math:`Q` is real-valued and :math:`\\Lambda` is a diagonal matrix whose diagonal elements are the corresponding eigenvalues. When ``x`` is real-valued, :math:`Q` is orthogonal, and, when ``x`` is complex, :math:`Q` is unitary. .. note:: - The eigenvalues of a complex Hermitian or real symmetric matrix are always real. + The eigenvalues of a complex Hermitian or real symmetric matrix are always real. .. warning:: - The eigenvectors of a symmetric matrix are not unique and are not continuous with respect to ``x``. Because eigenvectors are not unique, different hardware and software may compute different eigenvectors. + The eigenvectors of a symmetric matrix are not unique and are not continuous with respect to ``x``. Because eigenvectors are not unique, different hardware and software may compute different eigenvectors. - Non-uniqueness stems from the fact that multiplying an eigenvector by :math:`-1` when ``x`` is real-valued and by :math:`e^{\\phi j}` (:math:`\\phi \\in \\mathbb{R}`) when ``x`` is complex produces another set of valid eigenvectors. + Non-uniqueness stems from the fact that multiplying an eigenvector by :math:`-1` when ``x`` is real-valued and by :math:`e^{\\phi j}` (:math:`\\phi \\in \\mathbb{R}`) when ``x`` is complex produces another set of valid eigenvectors. .. note:: - Whether an array library explicitly checks whether an input array is Hermitian or a symmetric matrix (or a stack of matrices) is implementation-defined. + Whether an array library explicitly checks whether an input array is Hermitian or a symmetric matrix (or a stack of matrices) is implementation-defined. .. note:: - The function ``eig`` will be added in a future version of the specification. + The function ``eig`` will be added in a future version of the specification. Parameters ---------- x: array - input array having shape ``(..., M, M)`` and whose innermost two dimensions form square matrices. Should have a floating-point data type. + input array having shape ``(..., M, M)`` and whose innermost two dimensions form square matrices. Should have a floating-point data type. Returns ------- out: Tuple[array, array] - a namedtuple (``eigenvalues``, ``eigenvectors``) whose + a namedtuple (``eigenvalues``, ``eigenvectors``) whose - - first element must have the field name ``eigenvalues`` (corresponding to :math:`\\operatorname{diag}\\Lambda` above) and must be an array consisting of computed eigenvalues. The array containing the eigenvalues must have shape ``(..., M)`` and must have a real-valued floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``complex128``, then ``eigenvalues`` must be ``float64``). - - second element have have the field name ``eigenvectors`` (corresponding to :math:`Q` above) and must be an array where the columns of the inner most matrices contain the computed eigenvectors. These matrices must be orthogonal. The array containing the eigenvectors must have shape ``(..., M, M)`` and must have the same data type as ``x``. + - first element must have the field name ``eigenvalues`` (corresponding to :math:`\\operatorname{diag}\\Lambda` above) and must be an array consisting of computed eigenvalues. The array containing the eigenvalues must have shape ``(..., M)`` and must have a real-valued floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``complex128``, then ``eigenvalues`` must be ``float64``). + - second element have have the field name ``eigenvectors`` (corresponding to :math:`Q` above) and must be an array where the columns of the inner most matrices contain the computed eigenvectors. These matrices must be orthogonal. The array containing the eigenvectors must have shape ``(..., M, M)`` and must have the same data type as ``x``. Notes ----- .. note:: - Eigenvalue sort order is left unspecified and is thus implementation-dependent. + Eigenvalue sort order is left unspecified and is thus implementation-dependent. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -2834,37 +2838,37 @@ class eigvalsh[TArray: Array](Protocol): The **eigenvalues** of a complex Hermitian or real symmetric matrix :math:`x \\in\\ \\mathbb{K}^{n \\times n}` are defined as the roots (counted with multiplicity) of the polynomial :math:`p` of degree :math:`n` given by .. math:: - p(\\lambda) = \\operatorname{det}(x - \\lambda I_n) + p(\\lambda) = \\operatorname{det}(x - \\lambda I_n) where :math:`\\lambda \\in \\mathbb{R}` and where :math:`I_n` is the *n*-dimensional identity matrix. .. note:; - The eigenvalues of a complex Hermitian or real symmetric matrix are always real. + The eigenvalues of a complex Hermitian or real symmetric matrix are always real. .. note:: - Whether an array library explicitly checks whether an input array is Hermitian or a symmetric matrix (or a stack of matrices) is implementation-defined. + Whether an array library explicitly checks whether an input array is Hermitian or a symmetric matrix (or a stack of matrices) is implementation-defined. .. note:: - The function ``eigvals`` will be added in a future version of the specification. + The function ``eigvals`` will be added in a future version of the specification. Parameters ---------- x: array - input array having shape ``(..., M, M)`` and whose innermost two dimensions form square matrices. Should have a floating-point data type. + input array having shape ``(..., M, M)`` and whose innermost two dimensions form square matrices. Should have a floating-point data type. Returns ------- out: array - an array containing the computed eigenvalues. The returned array must have shape ``(..., M)`` and have a real-valued floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``complex128``, then must have a ``float64`` data type). + an array containing the computed eigenvalues. The returned array must have shape ``(..., M)`` and have a real-valued floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``complex128``, then must have a ``float64`` data type). Notes ----- .. note:: - Eigenvalue sort order is left unspecified and is thus implementation-dependent. + Eigenvalue sort order is left unspecified and is thus implementation-dependent. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -2882,7 +2886,7 @@ class inv[TArray: Array](Protocol): The **inverse matrix** :math:`x^{-1} \\in\\ \\mathbb{K}^{n \\times n}` of a square matrix :math:`x \\in\\ \\mathbb{K}^{n \\times n}` is defined as .. math:: - x^{-1}x = xx^{-1} = I_n + x^{-1}x = xx^{-1} = I_n where :math:`I_n` is the *n*-dimensional identity matrix. @@ -2893,18 +2897,18 @@ class inv[TArray: Array](Protocol): Parameters ---------- x: array - input array having shape ``(..., M, M)`` and whose innermost two dimensions form square matrices. Should have a floating-point data type. + input array having shape ``(..., M, M)`` and whose innermost two dimensions form square matrices. Should have a floating-point data type. Returns ------- out: array - an array containing the multiplicative inverses. The returned array must have a floating-point data type determined by :ref:`type-promotion` and must have the same shape as ``x``. + an array containing the multiplicative inverses. The returned array must have a floating-point data type determined by :ref:`type-promotion` and must have the same shape as ``x``. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -2920,56 +2924,56 @@ class matrix_norm[TArray: Array](Protocol): Parameters ---------- x: array - input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. Should have a floating-point data type. + input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. Should have a floating-point data type. keepdims: bool - If ``True``, the last two axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the last two axes (dimensions) must not be included in the result. Default: ``False``. + If ``True``, the last two axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the last two axes (dimensions) must not be included in the result. Default: ``False``. ord: Optional[Union[int, float, Literal[inf, -inf, 'fro', 'nuc']]] - order of the norm. The following mathematical norms must be supported: + order of the norm. The following mathematical norms must be supported: - +------------------+---------------------------------+ - | ord | description | - +==================+=================================+ - | 'fro' | Frobenius norm | - +------------------+---------------------------------+ - | 'nuc' | nuclear norm | - +------------------+---------------------------------+ - | 1 | max(sum(abs(x), axis=0)) | - +------------------+---------------------------------+ - | 2 | largest singular value | - +------------------+---------------------------------+ - | inf | max(sum(abs(x), axis=1)) | - +------------------+---------------------------------+ + +------------------+---------------------------------+ + | ord | description | + +==================+=================================+ + | 'fro' | Frobenius norm | + +------------------+---------------------------------+ + | 'nuc' | nuclear norm | + +------------------+---------------------------------+ + | 1 | max(sum(abs(x), axis=0)) | + +------------------+---------------------------------+ + | 2 | largest singular value | + +------------------+---------------------------------+ + | inf | max(sum(abs(x), axis=1)) | + +------------------+---------------------------------+ - The following non-mathematical "norms" must be supported: + The following non-mathematical "norms" must be supported: - +------------------+---------------------------------+ - | ord | description | - +==================+=================================+ - | -1 | min(sum(abs(x), axis=0)) | - +------------------+---------------------------------+ - | -2 | smallest singular value | - +------------------+---------------------------------+ - | -inf | min(sum(abs(x), axis=1)) | - +------------------+---------------------------------+ + +------------------+---------------------------------+ + | ord | description | + +==================+=================================+ + | -1 | min(sum(abs(x), axis=0)) | + +------------------+---------------------------------+ + | -2 | smallest singular value | + +------------------+---------------------------------+ + | -inf | min(sum(abs(x), axis=1)) | + +------------------+---------------------------------+ - If ``ord=1``, the norm corresponds to the induced matrix norm where ``p=1`` (i.e., the maximum absolute value column sum). + If ``ord=1``, the norm corresponds to the induced matrix norm where ``p=1`` (i.e., the maximum absolute value column sum). - If ``ord=2``, the norm corresponds to the induced matrix norm where ``p=inf`` (i.e., the maximum absolute value row sum). + If ``ord=2``, the norm corresponds to the induced matrix norm where ``p=inf`` (i.e., the maximum absolute value row sum). - If ``ord=inf``, the norm corresponds to the induced matrix norm where ``p=2`` (i.e., the largest singular value). + If ``ord=inf``, the norm corresponds to the induced matrix norm where ``p=2`` (i.e., the largest singular value). - Default: ``'fro'``. + Default: ``'fro'``. Returns ------- out: array - an array containing the norms for each ``MxN`` matrix. If ``keepdims`` is ``False``, the returned array must have a rank which is two less than the rank of ``x``. If ``x`` has a real-valued data type, the returned array must have a real-valued floating-point data type determined by :ref:`type-promotion`. If ``x`` has a complex-valued data type, the returned array must have a real-valued floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``complex128``, then the returned array must have a ``float64`` data type). + an array containing the norms for each ``MxN`` matrix. If ``keepdims`` is ``False``, the returned array must have a rank which is two less than the rank of ``x``. If ``x`` has a real-valued data type, the returned array must have a real-valued floating-point data type determined by :ref:`type-promotion`. If ``x`` has a complex-valued data type, the returned array must have a real-valued floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``complex128``, then the returned array must have a ``float64`` data type). Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -2986,20 +2990,20 @@ class matrix_power[TArray: Array](Protocol): Parameters ---------- x: array - input array having shape ``(..., M, M)`` and whose innermost two dimensions form square matrices. Should have a floating-point data type. + input array having shape ``(..., M, M)`` and whose innermost two dimensions form square matrices. Should have a floating-point data type. n: int - integer exponent. + integer exponent. Returns ------- out: array - if ``n`` is equal to zero, an array containing the identity matrix for each square matrix. If ``n`` is less than zero, an array containing the inverse of each square matrix raised to the absolute value of ``n``, provided that each square matrix is invertible. If ``n`` is greater than zero, an array containing the result of raising each square matrix to the power ``n``. The returned array must have the same shape as ``x`` and a floating-point data type determined by :ref:`type-promotion`. + if ``n`` is equal to zero, an array containing the identity matrix for each square matrix. If ``n`` is less than zero, an array containing the inverse of each square matrix raised to the absolute value of ``n``, provided that each square matrix is invertible. If ``n`` is greater than zero, an array containing the result of raising each square matrix to the power ``n``. The returned array must have the same shape as ``x`` and a floating-point data type determined by :ref:`type-promotion`. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -3017,20 +3021,20 @@ class matrix_rank[TArray: Array](Protocol): Parameters ---------- x: array - input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. Should have a floating-point data type. + input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. Should have a floating-point data type. rtol: Optional[Union[float, array]] - relative tolerance for small singular values. Singular values approximately less than or equal to ``rtol * largest_singular_value`` are set to zero. If a ``float``, the value is equivalent to a zero-dimensional array having a real-valued floating-point data type determined by :ref:`type-promotion` (as applied to ``x``) and must be broadcast against each matrix. If an ``array``, must have a real-valued floating-point data type and must be compatible with ``shape(x)[:-2]`` (see :ref:`broadcasting`). If ``None``, the default value is ``max(M, N) * eps``, where ``eps`` must be the machine epsilon associated with the real-valued floating-point data type determined by :ref:`type-promotion` (as applied to ``x``). Default: ``None``. + relative tolerance for small singular values. Singular values approximately less than or equal to ``rtol * largest_singular_value`` are set to zero. If a ``float``, the value is equivalent to a zero-dimensional array having a real-valued floating-point data type determined by :ref:`type-promotion` (as applied to ``x``) and must be broadcast against each matrix. If an ``array``, must have a real-valued floating-point data type and must be compatible with ``shape(x)[:-2]`` (see :ref:`broadcasting`). If ``None``, the default value is ``max(M, N) * eps``, where ``eps`` must be the machine epsilon associated with the real-valued floating-point data type determined by :ref:`type-promotion` (as applied to ``x``). Default: ``None``. Returns ------- out: array - an array containing the ranks. The returned array must have the default integer data type and must have shape ``(...)`` (i.e., must have a shape equal to ``shape(x)[:-2]``). + an array containing the ranks. The returned array must have the default integer data type and must have shape ``(...)`` (i.e., must have a shape equal to ``shape(x)[:-2]``). Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -3046,20 +3050,20 @@ class outer[TArray: Array](Protocol): Parameters ---------- x1: array - first one-dimensional input array of size ``N``. Must have a numeric data type. + first one-dimensional input array of size ``N``. Must have a numeric data type. x2: array - second one-dimensional input array of size ``M``. Must have a numeric data type. + second one-dimensional input array of size ``M``. Must have a numeric data type. Returns ------- out: array - a two-dimensional array containing the outer product and whose shape is ``(N, M)``. The returned array must have a data type determined by :ref:`type-promotion`. + a two-dimensional array containing the outer product and whose shape is ``(N, M)``. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -3077,12 +3081,12 @@ class pinv[TArray: Array](Protocol): While the pseudo-inverse can be defined algebraically, one can understand the pseudo-inverse via singular value decomposition (SVD). Namely, if .. math:: - A = U \\Sigma V^H + A = U \\Sigma V^H is a singular decomposition of :math:`A`, then .. math:: - A^{+} = U \\Sigma^{+} V^H + A^{+} = U \\Sigma^{+} V^H where :math:`U` and :math:`V^H` are orthogonal matrices, :math:`\\Sigma` is a diagonal matrix consisting of :math:`A`'s singular values, and :math:`\\Sigma^{+}` is then a diagonal matrix consisting of the reciprocals of :math:`A`'s singular values, leaving zeros in place. During numerical computation, only elements larger than a small tolerance are considered nonzero, and all others replaced by zeros. @@ -3091,20 +3095,20 @@ class pinv[TArray: Array](Protocol): Parameters ---------- x: array - input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. Should have a floating-point data type. + input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. Should have a floating-point data type. rtol: Optional[Union[float, array]] - relative tolerance for small singular values. Singular values approximately less than or equal to ``rtol * largest_singular_value`` are set to zero. If a ``float``, the value is equivalent to a zero-dimensional array having a real-valued floating-point data type determined by :ref:`type-promotion` (as applied to ``x``) and must be broadcast against each matrix. If an ``array``, must have a real-valued floating-point data type and must be compatible with ``shape(x)[:-2]`` (see :ref:`broadcasting`). If ``None``, the default value is ``max(M, N) * eps``, where ``eps`` must be the machine epsilon associated with the real-valued floating-point data type determined by :ref:`type-promotion` (as applied to ``x``). Default: ``None``. + relative tolerance for small singular values. Singular values approximately less than or equal to ``rtol * largest_singular_value`` are set to zero. If a ``float``, the value is equivalent to a zero-dimensional array having a real-valued floating-point data type determined by :ref:`type-promotion` (as applied to ``x``) and must be broadcast against each matrix. If an ``array``, must have a real-valued floating-point data type and must be compatible with ``shape(x)[:-2]`` (see :ref:`broadcasting`). If ``None``, the default value is ``max(M, N) * eps``, where ``eps`` must be the machine epsilon associated with the real-valued floating-point data type determined by :ref:`type-promotion` (as applied to ``x``). Default: ``None``. Returns ------- out: array - an array containing the pseudo-inverse(s). The returned array must have a floating-point data type determined by :ref:`type-promotion` and must have shape ``(..., N, M)`` (i.e., must have the same shape as ``x``, except the innermost two dimensions must be transposed). + an array containing the pseudo-inverse(s). The returned array must have a floating-point data type determined by :ref:`type-promotion` and must have shape ``(..., N, M)`` (i.e., must have the same shape as ``x``, except the innermost two dimensions must be transposed). Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -3122,14 +3126,14 @@ class qr[TArray: Array](Protocol): The **complete QR decomposition** of a matrix :math:`x \\in\\ \\mathbb{K}^{n \\times n}` is defined as .. math:: - x = QR + x = QR where :math:`Q \\in\\ \\mathbb{K}^{m \\times m}` is orthogonal when ``x`` is real-valued and unitary when ``x`` is complex-valued and where :math:`R \\in\\ \\mathbb{K}^{m \\times n}` is an upper triangular matrix with real diagonal (even when ``x`` is complex-valued). When :math:`m \\gt n` (tall matrix), as :math:`R` is upper triangular, the last :math:`m - n` rows are zero. In this case, the last :math:`m - n` columns of :math:`Q` can be dropped to form the **reduced QR decomposition**. .. math:: - x = QR + x = QR where :math:`Q \\in\\ \\mathbb{K}^{m \\times n}` and :math:`R \\in\\ \\mathbb{K}^{n \\times n}`. @@ -3138,41 +3142,41 @@ class qr[TArray: Array](Protocol): When ``x`` is a stack of matrices, the function must compute the QR decomposition for each matrix in the stack. .. note:: - Whether an array library explicitly checks whether an input array is a full column rank matrix (or a stack of full column rank matrices) is implementation-defined. + Whether an array library explicitly checks whether an input array is a full column rank matrix (or a stack of full column rank matrices) is implementation-defined. .. warning:: - The elements in the diagonal of :math:`R` are not necessarily positive. Accordingly, the returned QR decomposition is only unique up to the sign of the diagonal of :math:`R`, and different libraries or inputs on different devices may produce different valid decompositions. + The elements in the diagonal of :math:`R` are not necessarily positive. Accordingly, the returned QR decomposition is only unique up to the sign of the diagonal of :math:`R`, and different libraries or inputs on different devices may produce different valid decompositions. .. warning:: - The QR decomposition is only well-defined if the first ``k = min(m,n)`` columns of every matrix in ``x`` are linearly independent. + The QR decomposition is only well-defined if the first ``k = min(m,n)`` columns of every matrix in ``x`` are linearly independent. Parameters ---------- x: array - input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices of rank ``N``. Should have a floating-point data type. + input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices of rank ``N``. Should have a floating-point data type. mode: Literal['reduced', 'complete'] - decomposition mode. Should be one of the following modes: + decomposition mode. Should be one of the following modes: - - ``'reduced'``: compute only the leading ``K`` columns of ``q``, such that ``q`` and ``r`` have dimensions ``(..., M, K)`` and ``(..., K, N)``, respectively, and where ``K = min(M, N)``. - - ``'complete'``: compute ``q`` and ``r`` with dimensions ``(..., M, M)`` and ``(..., M, N)``, respectively. + - ``'reduced'``: compute only the leading ``K`` columns of ``q``, such that ``q`` and ``r`` have dimensions ``(..., M, K)`` and ``(..., K, N)``, respectively, and where ``K = min(M, N)``. + - ``'complete'``: compute ``q`` and ``r`` with dimensions ``(..., M, M)`` and ``(..., M, N)``, respectively. - Default: ``'reduced'``. + Default: ``'reduced'``. Returns ------- out: Tuple[array, array] - a namedtuple ``(Q, R)`` whose + a namedtuple ``(Q, R)`` whose - - first element must have the field name ``Q`` and must be an array whose shape depends on the value of ``mode`` and contain matrices with orthonormal columns. If ``mode`` is ``'complete'``, the array must have shape ``(..., M, M)``. If ``mode`` is ``'reduced'``, the array must have shape ``(..., M, K)``, where ``K = min(M, N)``. The first ``x.ndim-2`` dimensions must have the same size as those of the input array ``x``. - - second element must have the field name ``R`` and must be an array whose shape depends on the value of ``mode`` and contain upper-triangular matrices. If ``mode`` is ``'complete'``, the array must have shape ``(..., M, N)``. If ``mode`` is ``'reduced'``, the array must have shape ``(..., K, N)``, where ``K = min(M, N)``. The first ``x.ndim-2`` dimensions must have the same size as those of the input ``x``. + - first element must have the field name ``Q`` and must be an array whose shape depends on the value of ``mode`` and contain matrices with orthonormal columns. If ``mode`` is ``'complete'``, the array must have shape ``(..., M, M)``. If ``mode`` is ``'reduced'``, the array must have shape ``(..., M, K)``, where ``K = min(M, N)``. The first ``x.ndim-2`` dimensions must have the same size as those of the input array ``x``. + - second element must have the field name ``R`` and must be an array whose shape depends on the value of ``mode`` and contain upper-triangular matrices. If ``mode`` is ``'complete'``, the array must have shape ``(..., M, N)``. If ``mode`` is ``'reduced'``, the array must have shape ``(..., K, N)``, where ``K = min(M, N)``. The first ``x.ndim-2`` dimensions must have the same size as those of the input ``x``. - Each returned array must have a floating-point data type determined by :ref:`type-promotion`. + Each returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -3186,15 +3190,15 @@ class slogdet[TArray: Array](Protocol): Returns the sign and the natural logarithm of the absolute value of the determinant of a square matrix (or a stack of square matrices) ``x``. .. note:: - The purpose of this function is to calculate the determinant more accurately when the determinant is either very small or very large, as calling ``det`` may overflow or underflow. + The purpose of this function is to calculate the determinant more accurately when the determinant is either very small or very large, as calling ``det`` may overflow or underflow. The sign of the determinant is given by .. math:: - \\operatorname{sign}(\\det x) = \\begin{cases} - 0 & \\textrm{if } \\det x = 0 \\\\ - \\frac{\\det x}{|\\det x|} & \\textrm{otherwise} - \\end{cases} + \\operatorname{sign}(\\det x) = \\begin{cases} + 0 & \\textrm{if } \\det x = 0 \\\\ + \\frac{\\det x}{|\\det x|} & \\textrm{otherwise} + \\end{cases} where :math:`|\\det x|` is the absolute value of the determinant of ``x``. @@ -3211,28 +3215,28 @@ class slogdet[TArray: Array](Protocol): - If the determinant is ``0 + 0j``, the ``sign`` should be ``0 + 0j`` and ``logabsdet`` should be ``-infinity + 0j``. .. note:: - Depending on the underlying algorithm, when the determinant is zero, the returned result may differ from ``-infinity`` (or ``-infinity + 0j``). In all cases, the determinant should be equal to ``sign * exp(logabsdet)`` (although, again, the result may be subject to numerical precision errors). + Depending on the underlying algorithm, when the determinant is zero, the returned result may differ from ``-infinity`` (or ``-infinity + 0j``). In all cases, the determinant should be equal to ``sign * exp(logabsdet)`` (although, again, the result may be subject to numerical precision errors). Parameters ---------- x: array - input array having shape ``(..., M, M)`` and whose innermost two dimensions form square matrices. Should have a floating-point data type. + input array having shape ``(..., M, M)`` and whose innermost two dimensions form square matrices. Should have a floating-point data type. Returns ------- out: Tuple[array, array] - a namedtuple (``sign``, ``logabsdet``) whose + a namedtuple (``sign``, ``logabsdet``) whose - - first element must have the field name ``sign`` and must be an array containing a number representing the sign of the determinant for each square matrix. Must have the same data type as ``x``. - - second element must have the field name ``logabsdet`` and must be an array containing the natural logarithm of the absolute value of the determinant for each square matrix. If ``x`` is real-valued, the returned array must have a real-valued floating-point data type determined by :ref:`type-promotion`. If ``x`` is complex, the returned array must have a real-valued floating-point data type having the same precision as ``x`` (e.g., if ``x`` is ``complex64``, ``logabsdet`` must have a ``float32`` data type). + - first element must have the field name ``sign`` and must be an array containing a number representing the sign of the determinant for each square matrix. Must have the same data type as ``x``. + - second element must have the field name ``logabsdet`` and must be an array containing the natural logarithm of the absolute value of the determinant for each square matrix. If ``x`` is real-valued, the returned array must have a real-valued floating-point data type determined by :ref:`type-promotion`. If ``x`` is complex, the returned array must have a real-valued floating-point data type having the same precision as ``x`` (e.g., if ``x`` is ``complex64``, ``logabsdet`` must have a ``float32`` data type). - Each returned array must have shape ``shape(x)[:-2]``. + Each returned array must have shape ``shape(x)[:-2]``. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -3250,35 +3254,35 @@ class solve[TArray: Array](Protocol): This function computes the solution :math:`X \\in\\ \\mathbb{K}^{m \\times k}` of the **linear system** associated to :math:`A \\in\\ \\mathbb{K}^{m \\times m}` and :math:`B \\in\\ \\mathbb{K}^{m \\times k}` and is defined as .. math:: - AX = B + AX = B This system of linear equations has a unique solution if and only if :math:`A` is invertible. .. note:: - Whether an array library explicitly checks whether ``x1`` is invertible is implementation-defined. + Whether an array library explicitly checks whether ``x1`` is invertible is implementation-defined. When ``x1`` and/or ``x2`` is a stack of matrices, the function must compute a solution for each matrix in the stack. Parameters ---------- x1: array - coefficient array ``A`` having shape ``(..., M, M)`` and whose innermost two dimensions form square matrices. Must be of full rank (i.e., all rows or, equivalently, columns must be linearly independent). Should have a floating-point data type. + coefficient array ``A`` having shape ``(..., M, M)`` and whose innermost two dimensions form square matrices. Must be of full rank (i.e., all rows or, equivalently, columns must be linearly independent). Should have a floating-point data type. x2: array - ordinate (or "dependent variable") array ``B``. If ``x2`` has shape ``(M,)``, ``x2`` is equivalent to an array having shape ``(..., M, 1)``. If ``x2`` has shape ``(..., M, K)``, each column ``k`` defines a set of ordinate values for which to compute a solution, and ``shape(x2)[:-2]`` must be compatible with ``shape(x1)[:-2]`` (see :ref:`broadcasting`). Should have a floating-point data type. + ordinate (or "dependent variable") array ``B``. If ``x2`` has shape ``(M,)``, ``x2`` is equivalent to an array having shape ``(..., M, 1)``. If ``x2`` has shape ``(..., M, K)``, each column ``k`` defines a set of ordinate values for which to compute a solution, and ``shape(x2)[:-2]`` must be compatible with ``shape(x1)[:-2]`` (see :ref:`broadcasting`). Should have a floating-point data type. Returns ------- out: array - an array containing the solution to the system ``AX = B`` for each square matrix. If ``x2`` has shape ``(M,)``, the returned array must have shape equal to ``shape(x1)[:-2] + shape(x2)[-1:]``. Otherwise, if ``x2`` has shape ``(..., M, K)```, the returned array must have shape equal to ``(..., M, K)``, where ``...`` refers to the result of broadcasting ``shape(x1)[:-2]`` and ``shape(x2)[:-2]``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the solution to the system ``AX = B`` for each square matrix. If ``x2`` has shape ``(M,)``, the returned array must have shape equal to ``shape(x1)[:-2] + shape(x2)[-1:]``. Otherwise, if ``x2`` has shape ``(..., M, K)```, the returned array must have shape equal to ``(..., M, K)``, where ``...`` refers to the result of broadcasting ``shape(x1)[:-2]`` and ``shape(x2)[:-2]``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. .. versionchanged:: 2024.12 - Clarified broadcasting semantics and the shape of the output array. + Clarified broadcasting semantics and the shape of the output array. """ @@ -3296,14 +3300,14 @@ class svd[TArray: Array](Protocol): The full **singular value decomposition** of an :math:`m \\times n` matrix :math:`x \\in\\ \\mathbb{K}^{m \\times n}` is a factorization of the form .. math:: - x = U \\Sigma V^H + x = U \\Sigma V^H where :math:`U \\in\\ \\mathbb{K}^{m \\times m}`, :math:`\\Sigma \\in\\ \\mathbb{K}^{m \\times\\ n}`, :math:`\\operatorname{diag}(\\Sigma) \\in\\ \\mathbb{R}^{k}` with :math:`k = \\operatorname{min}(m, n)`, :math:`V^H \\in\\ \\mathbb{K}^{n \\times n}`, and where :math:`V^H` is the conjugate transpose when :math:`V` is complex and the transpose when :math:`V` is real-valued. When ``x`` is real-valued, :math:`U`, :math:`V` (and thus :math:`V^H`) are orthogonal, and, when ``x`` is complex, :math:`U`, :math:`V` (and thus :math:`V^H`) are unitary. When :math:`m \\gt n` (tall matrix), we can drop the last :math:`m - n` columns of :math:`U` to form the reduced SVD .. math:: - x = U \\Sigma V^H + x = U \\Sigma V^H where :math:`U \\in\\ \\mathbb{K}^{m \\times k}`, :math:`\\Sigma \\in\\ \\mathbb{K}^{k \\times\\ k}`, :math:`\\operatorname{diag}(\\Sigma) \\in\\ \\mathbb{R}^{k}`, and :math:`V^H \\in\\ \\mathbb{K}^{k \\times n}`. In this case, :math:`U` and :math:`V` have orthonormal columns. @@ -3314,31 +3318,31 @@ class svd[TArray: Array](Protocol): When ``x`` is a stack of matrices, the function must compute the singular value decomposition for each matrix in the stack. .. warning:: - The returned arrays :math:`U` and :math:`V` are neither unique nor continuous with respect to ``x``. Because :math:`U` and :math:`V` are not unique, different hardware and software may compute different singular vectors. + The returned arrays :math:`U` and :math:`V` are neither unique nor continuous with respect to ``x``. Because :math:`U` and :math:`V` are not unique, different hardware and software may compute different singular vectors. - Non-uniqueness stems from the fact that multiplying any pair of singular vectors :math:`u_k`, :math:`v_k` by :math:`-1` when ``x`` is real-valued and by :math:`e^{\\phi j}` (:math:`\\phi \\in \\mathbb{R}`) when ``x`` is complex produces another two valid singular vectors of the matrix. + Non-uniqueness stems from the fact that multiplying any pair of singular vectors :math:`u_k`, :math:`v_k` by :math:`-1` when ``x`` is real-valued and by :math:`e^{\\phi j}` (:math:`\\phi \\in \\mathbb{R}`) when ``x`` is complex produces another two valid singular vectors of the matrix. Parameters ---------- x: array - input array having shape ``(..., M, N)`` and whose innermost two dimensions form matrices on which to perform singular value decomposition. Should have a floating-point data type. + input array having shape ``(..., M, N)`` and whose innermost two dimensions form matrices on which to perform singular value decomposition. Should have a floating-point data type. full_matrices: bool - If ``True``, compute full-sized ``U`` and ``Vh``, such that ``U`` has shape ``(..., M, M)`` and ``Vh`` has shape ``(..., N, N)``. If ``False``, compute on the leading ``K`` singular vectors, such that ``U`` has shape ``(..., M, K)`` and ``Vh`` has shape ``(..., K, N)`` and where ``K = min(M, N)``. Default: ``True``. + If ``True``, compute full-sized ``U`` and ``Vh``, such that ``U`` has shape ``(..., M, M)`` and ``Vh`` has shape ``(..., N, N)``. If ``False``, compute on the leading ``K`` singular vectors, such that ``U`` has shape ``(..., M, K)`` and ``Vh`` has shape ``(..., K, N)`` and where ``K = min(M, N)``. Default: ``True``. Returns ------- out: Tuple[array, array, array] - a namedtuple ``(U, S, Vh)`` whose + a namedtuple ``(U, S, Vh)`` whose - - first element must have the field name ``U`` and must be an array whose shape depends on the value of ``full_matrices`` and contain matrices with orthonormal columns (i.e., the columns are left singular vectors). If ``full_matrices`` is ``True``, the array must have shape ``(..., M, M)``. If ``full_matrices`` is ``False``, the array must have shape ``(..., M, K)``, where ``K = min(M, N)``. The first ``x.ndim-2`` dimensions must have the same shape as those of the input ``x``. Must have the same data type as ``x``. - - second element must have the field name ``S`` and must be an array with shape ``(..., K)`` that contains the vector(s) of singular values of length ``K``, where ``K = min(M, N)``. For each vector, the singular values must be sorted in descending order by magnitude, such that ``s[..., 0]`` is the largest value, ``s[..., 1]`` is the second largest value, et cetera. The first ``x.ndim-2`` dimensions must have the same shape as those of the input ``x``. Must have a real-valued floating-point data type having the same precision as ``x`` (e.g., if ``x`` is ``complex64``, ``S`` must have a ``float32`` data type). - - third element must have the field name ``Vh`` and must be an array whose shape depends on the value of ``full_matrices`` and contain orthonormal rows (i.e., the rows are the right singular vectors and the array is the adjoint). If ``full_matrices`` is ``True``, the array must have shape ``(..., N, N)``. If ``full_matrices`` is ``False``, the array must have shape ``(..., K, N)`` where ``K = min(M, N)``. The first ``x.ndim-2`` dimensions must have the same shape as those of the input ``x``. Must have the same data type as ``x``. + - first element must have the field name ``U`` and must be an array whose shape depends on the value of ``full_matrices`` and contain matrices with orthonormal columns (i.e., the columns are left singular vectors). If ``full_matrices`` is ``True``, the array must have shape ``(..., M, M)``. If ``full_matrices`` is ``False``, the array must have shape ``(..., M, K)``, where ``K = min(M, N)``. The first ``x.ndim-2`` dimensions must have the same shape as those of the input ``x``. Must have the same data type as ``x``. + - second element must have the field name ``S`` and must be an array with shape ``(..., K)`` that contains the vector(s) of singular values of length ``K``, where ``K = min(M, N)``. For each vector, the singular values must be sorted in descending order by magnitude, such that ``s[..., 0]`` is the largest value, ``s[..., 1]`` is the second largest value, et cetera. The first ``x.ndim-2`` dimensions must have the same shape as those of the input ``x``. Must have a real-valued floating-point data type having the same precision as ``x`` (e.g., if ``x`` is ``complex64``, ``S`` must have a ``float32`` data type). + - third element must have the field name ``Vh`` and must be an array whose shape depends on the value of ``full_matrices`` and contain orthonormal rows (i.e., the rows are the right singular vectors and the array is the adjoint). If ``full_matrices`` is ``True``, the array must have shape ``(..., N, N)``. If ``full_matrices`` is ``False``, the array must have shape ``(..., K, N)`` where ``K = min(M, N)``. The first ``x.ndim-2`` dimensions must have the same shape as those of the input ``x``. Must have the same data type as ``x``. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -3356,18 +3360,18 @@ class svdvals[TArray: Array](Protocol): Parameters ---------- x: array - input array having shape ``(..., M, N)`` and whose innermost two dimensions form matrices on which to perform singular value decomposition. Should have a floating-point data type. + input array having shape ``(..., M, N)`` and whose innermost two dimensions form matrices on which to perform singular value decomposition. Should have a floating-point data type. Returns ------- out: array - an array with shape ``(..., K)`` that contains the vector(s) of singular values of length ``K``, where ``K = min(M, N)``. For each vector, the singular values must be sorted in descending order by magnitude, such that ``s[..., 0]`` is the largest value, ``s[..., 1]`` is the second largest value, et cetera. The first ``x.ndim-2`` dimensions must have the same shape as those of the input ``x``. The returned array must have a real-valued floating-point data type having the same precision as ``x`` (e.g., if ``x`` is ``complex64``, the returned array must have a ``float32`` data type). + an array with shape ``(..., K)`` that contains the vector(s) of singular values of length ``K``, where ``K = min(M, N)``. For each vector, the singular values must be sorted in descending order by magnitude, such that ``s[..., 0]`` is the largest value, ``s[..., 1]`` is the second largest value, et cetera. The first ``x.ndim-2`` dimensions must have the same shape as those of the input ``x``. The returned array must have a real-valued floating-point data type having the same precision as ``x`` (e.g., if ``x`` is ``complex64``, the returned array must have a ``float32`` data type). Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -3383,33 +3387,33 @@ class trace[TArray: Array, TDtype](Protocol): Parameters ---------- x: array - input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. Should have a numeric data type. + input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. Should have a numeric data type. offset: int - offset specifying the off-diagonal relative to the main diagonal. + offset specifying the off-diagonal relative to the main diagonal. - - ``offset = 0``: the main diagonal. - - ``offset > 0``: off-diagonal above the main diagonal. - - ``offset < 0``: off-diagonal below the main diagonal. + - ``offset = 0``: the main diagonal. + - ``offset > 0``: off-diagonal above the main diagonal. + - ``offset < 0``: off-diagonal below the main diagonal. - Default: ``0``. + Default: ``0``. dtype: Optional[dtype] - data type of the returned array. If ``None``, the returned array must have the same data type as ``x``, unless ``x`` has an integer data type supporting a smaller range of values than the default integer data type (e.g., ``x`` has an ``int16`` or ``uint32`` data type and the default integer data type is ``int64``). In those latter cases: + data type of the returned array. If ``None``, the returned array must have the same data type as ``x``, unless ``x`` has an integer data type supporting a smaller range of values than the default integer data type (e.g., ``x`` has an ``int16`` or ``uint32`` data type and the default integer data type is ``int64``). In those latter cases: - - if ``x`` has a signed integer data type (e.g., ``int16``), the returned array must have the default integer data type. - - if ``x`` has an unsigned integer data type (e.g., ``uint16``), the returned array must have an unsigned integer data type having the same number of bits as the default integer data type (e.g., if the default integer data type is ``int32``, the returned array must have a ``uint32`` data type). + - if ``x`` has a signed integer data type (e.g., ``int16``), the returned array must have the default integer data type. + - if ``x`` has an unsigned integer data type (e.g., ``uint16``), the returned array must have an unsigned integer data type having the same number of bits as the default integer data type (e.g., if the default integer data type is ``int32``, the returned array must have a ``uint32`` data type). - If the data type (either specified or resolved) differs from the data type of ``x``, the input array should be cast to the specified data type before computing the sum (rationale: the ``dtype`` keyword argument is intended to help prevent overflows). Default: ``None``. + If the data type (either specified or resolved) differs from the data type of ``x``, the input array should be cast to the specified data type before computing the sum (rationale: the ``dtype`` keyword argument is intended to help prevent overflows). Default: ``None``. Returns ------- out: array - an array containing the traces and whose shape is determined by removing the last two dimensions and storing the traces in the last array dimension. For example, if ``x`` has rank ``k`` and shape ``(I, J, K, ..., L, M, N)``, then an output array has rank ``k-2`` and shape ``(I, J, K, ..., L)`` where + an array containing the traces and whose shape is determined by removing the last two dimensions and storing the traces in the last array dimension. For example, if ``x`` has rank ``k`` and shape ``(I, J, K, ..., L, M, N)``, then an output array has rank ``k-2`` and shape ``(I, J, K, ..., L)`` where - :: + :: - out[i, j, k, ..., l] = trace(a[i, j, k, ..., l, :, :]) + out[i, j, k, ..., l] = trace(a[i, j, k, ..., l, :, :]) - The returned array must have a data type as described by the ``dtype`` parameter above. + The returned array must have a data type as described by the ``dtype`` parameter above. Notes ----- @@ -3422,10 +3426,10 @@ class trace[TArray: Array, TDtype](Protocol): For both real-valued and complex floating-point operands, special cases must be handled as if the operation is implemented by successive application of :func:`~array_api.add`. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. .. versionchanged:: 2023.12 - Required the function to return a floating-point array having the same data type as the input array when provided a floating-point array. + Required the function to return a floating-point array having the same data type as the input array when provided a floating-point array. """ @@ -3441,54 +3445,54 @@ class vector_norm[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a floating-point data type. + input array. Should have a floating-point data type. axis: Optional[Union[int, Tuple[int, ...]]] - If an integer, ``axis`` specifies the axis (dimension) along which to compute vector norms. If an n-tuple, ``axis`` specifies the axes (dimensions) along which to compute batched vector norms. If ``None``, the vector norm must be computed over all array values (i.e., equivalent to computing the vector norm of a flattened array). Negative indices must be supported. Default: ``None``. + If an integer, ``axis`` specifies the axis (dimension) along which to compute vector norms. If an n-tuple, ``axis`` specifies the axes (dimensions) along which to compute batched vector norms. If ``None``, the vector norm must be computed over all array values (i.e., equivalent to computing the vector norm of a flattened array). Negative indices must be supported. Default: ``None``. keepdims: bool - If ``True``, the axes (dimensions) specified by ``axis`` must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the axes (dimensions) specified by ``axis`` must not be included in the result. Default: ``False``. + If ``True``, the axes (dimensions) specified by ``axis`` must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the axes (dimensions) specified by ``axis`` must not be included in the result. Default: ``False``. ord: Union[int, float, Literal[inf, -inf]] - order of the norm. The following mathematical norms must be supported: + order of the norm. The following mathematical norms must be supported: - +------------------+----------------------------+ - | ord | description | - +==================+============================+ - | 1 | L1-norm (Manhattan) | - +------------------+----------------------------+ - | 2 | L2-norm (Euclidean) | - +------------------+----------------------------+ - | inf | infinity norm | - +------------------+----------------------------+ - | (int,float >= 1) | p-norm | - +------------------+----------------------------+ + +------------------+----------------------------+ + | ord | description | + +==================+============================+ + | 1 | L1-norm (Manhattan) | + +------------------+----------------------------+ + | 2 | L2-norm (Euclidean) | + +------------------+----------------------------+ + | inf | infinity norm | + +------------------+----------------------------+ + | (int,float >= 1) | p-norm | + +------------------+----------------------------+ - The following non-mathematical "norms" must be supported: + The following non-mathematical "norms" must be supported: - +------------------+--------------------------------+ - | ord | description | - +==================+================================+ - | 0 | sum(a != 0) | - +------------------+--------------------------------+ - | -1 | 1./sum(1./abs(a)) | - +------------------+--------------------------------+ - | -2 | 1./sqrt(sum(1./abs(a)\\*\\*2)) | - +------------------+--------------------------------+ - | -inf | min(abs(a)) | - +------------------+--------------------------------+ - | (int,float < 1) | sum(abs(a)\\*\\*ord)\\*\\*(1./ord) | - +------------------+--------------------------------+ + +------------------+--------------------------------+ + | ord | description | + +==================+================================+ + | 0 | sum(a != 0) | + +------------------+--------------------------------+ + | -1 | 1./sum(1./abs(a)) | + +------------------+--------------------------------+ + | -2 | 1./sqrt(sum(1./abs(a)\\*\\*2)) | + +------------------+--------------------------------+ + | -inf | min(abs(a)) | + +------------------+--------------------------------+ + | (int,float < 1) | sum(abs(a)\\*\\*ord)\\*\\*(1./ord) | + +------------------+--------------------------------+ - Default: ``2``. + Default: ``2``. Returns ------- out: array - an array containing the vector norms. If ``axis`` is ``None``, the returned array must be a zero-dimensional array containing a vector norm. If ``axis`` is a scalar value (``int`` or ``float``), the returned array must have a rank which is one less than the rank of ``x``. If ``axis`` is a ``n``-tuple, the returned array must have a rank which is ``n`` less than the rank of ``x``. If ``x`` has a real-valued data type, the returned array must have a real-valued floating-point data type determined by :ref:`type-promotion`. If ``x`` has a complex-valued data type, the returned array must have a real-valued floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``complex128``, then the returned array must have a ``float64`` data type). + an array containing the vector norms. If ``axis`` is ``None``, the returned array must be a zero-dimensional array containing a vector norm. If ``axis`` is a scalar value (``int`` or ``float``), the returned array must have a rank which is one less than the rank of ``x``. If ``axis`` is a ``n``-tuple, the returned array must have a rank which is ``n`` less than the rank of ``x``. If ``x`` has a real-valued data type, the returned array must have a real-valued floating-point data type determined by :ref:`type-promotion`. If ``x`` has a complex-valued data type, the returned array must have a real-valued floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``complex128``, then the returned array must have a ``float64`` data type). Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -3503,23 +3507,23 @@ class argsort[TArray: Array](Protocol): Returns the indices that sort an array ``x`` along a specified axis. .. note:: - For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). + For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). Parameters ---------- x : array - input array. Should have a real-valued data type. + input array. Should have a real-valued data type. axis: int - axis along which to sort. If set to ``-1``, the function must sort along the last axis. Default: ``-1``. + axis along which to sort. If set to ``-1``, the function must sort along the last axis. Default: ``-1``. descending: bool - sort order. If ``True``, the returned indices sort ``x`` in descending order (by value). If ``False``, the returned indices sort ``x`` in ascending order (by value). Default: ``False``. + sort order. If ``True``, the returned indices sort ``x`` in descending order (by value). If ``False``, the returned indices sort ``x`` in ascending order (by value). Default: ``False``. stable: bool - sort stability. If ``True``, the returned indices must maintain the relative order of ``x`` values which compare as equal. If ``False``, the returned indices may or may not maintain the relative order of ``x`` values which compare as equal (i.e., the relative order of ``x`` values which compare as equal is implementation-dependent). Default: ``True``. + sort stability. If ``True``, the returned indices must maintain the relative order of ``x`` values which compare as equal. If ``False``, the returned indices may or may not maintain the relative order of ``x`` values which compare as equal (i.e., the relative order of ``x`` values which compare as equal is implementation-dependent). Default: ``True``. Returns ------- out : array - an array of indices. The returned array must have the same shape as ``x``. The returned array must have the default array index data type. + an array of indices. The returned array must have the same shape as ``x``. The returned array must have the default array index data type. """ @@ -3533,23 +3537,23 @@ class sort[TArray: Array](Protocol): Returns a sorted copy of an input array ``x``. .. note:: - For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). + For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). Parameters ---------- x: array - input array. Should have a real-valued data type. + input array. Should have a real-valued data type. axis: int - axis along which to sort. If set to ``-1``, the function must sort along the last axis. Default: ``-1``. + axis along which to sort. If set to ``-1``, the function must sort along the last axis. Default: ``-1``. descending: bool - sort order. If ``True``, the array must be sorted in descending order (by value). If ``False``, the array must be sorted in ascending order (by value). Default: ``False``. + sort order. If ``True``, the array must be sorted in descending order (by value). If ``False``, the array must be sorted in ascending order (by value). Default: ``False``. stable: bool - sort stability. If ``True``, the returned array must maintain the relative order of ``x`` values which compare as equal. If ``False``, the returned array may or may not maintain the relative order of ``x`` values which compare as equal (i.e., the relative order of ``x`` values which compare as equal is implementation-dependent). Default: ``True``. + sort stability. If ``True``, the returned array must maintain the relative order of ``x`` values which compare as equal. If ``False``, the returned array may or may not maintain the relative order of ``x`` values which compare as equal (i.e., the relative order of ``x`` values which compare as equal is implementation-dependent). Default: ``True``. Returns ------- out : array - a sorted array. The returned array must have the same data type and shape as ``x``. + a sorted array. The returned array must have the same data type and shape as ``x``. """ @@ -3565,29 +3569,29 @@ class abs[TArray: Array](Protocol): For real-valued input arrays, the element-wise result has the same magnitude as the respective element in ``x`` but has positive sign. .. note:: - For signed integer data types, the absolute value of the minimum representable integer is implementation-dependent. + For signed integer data types, the absolute value of the minimum representable integer is implementation-dependent. .. note:: - For complex floating-point operands, the complex absolute value is known as the norm, modulus, or magnitude and, for a complex number :math:`z = a + bj` is computed as + For complex floating-point operands, the complex absolute value is known as the norm, modulus, or magnitude and, for a complex number :math:`z = a + bj` is computed as - .. math:: - \\operatorname{abs}(z) = \\sqrt{a^2 + b^2} + .. math:: + \\operatorname{abs}(z) = \\sqrt{a^2 + b^2} .. note:: - For complex floating-point operands, conforming implementations should take care to avoid undue overflow or underflow during intermediate stages of computation. + For complex floating-point operands, conforming implementations should take care to avoid undue overflow or underflow during intermediate stages of computation. .. - TODO: once ``hypot`` is added to the specification, remove the special cases for complex floating-point operands and the note concerning guarding against undue overflow/underflow, and state that special cases must be handled as if implemented as ``hypot(real(x), imag(x))``. + TODO: once ``hypot`` is added to the specification, remove the special cases for complex floating-point operands and the note concerning guarding against undue overflow/underflow, and state that special cases must be handled as if implemented as ``hypot(real(x), imag(x))``. Parameters ---------- x: array - input array. Should have a numeric data type. + input array. Should have a numeric data type. Returns ------- out: array - an array containing the absolute value of each element in ``x``. If ``x`` has a real-valued data type, the returned array must have the same data type as ``x``. If ``x`` has a complex floating-point data type, the returned array must have a real-valued floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``complex128``, then the returned array must have a ``float64`` data type). + an array containing the absolute value of each element in ``x``. If ``x`` has a real-valued data type, the returned array must have the same data type as ``x``. If ``x`` has a complex floating-point data type, the returned array must have a real-valued floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``complex128``, then the returned array must have a ``float64`` data type). Notes ----- @@ -3610,7 +3614,7 @@ class abs[TArray: Array](Protocol): - If ``a`` is ``NaN`` and ``b`` is ``NaN``, the result is ``NaN``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -3626,35 +3630,35 @@ class acos[TArray: Array](Protocol): Each element-wise result is expressed in radians. .. note:: - The principal value of the arc cosine of a complex number :math:`z` is + The principal value of the arc cosine of a complex number :math:`z` is - .. math:: - \\operatorname{acos}(z) = \\frac{1}{2}\\pi + j\\ \\ln(zj + \\sqrt{1-z^2}) + .. math:: + \\operatorname{acos}(z) = \\frac{1}{2}\\pi + j\\ \\ln(zj + \\sqrt{1-z^2}) - For any :math:`z`, + For any :math:`z`, - .. math:: - \\operatorname{acos}(z) = \\pi - \\operatorname{acos}(-z) + .. math:: + \\operatorname{acos}(z) = \\pi - \\operatorname{acos}(-z) .. note:: - For complex floating-point operands, ``acos(conj(x))`` must equal ``conj(acos(x))``. + For complex floating-point operands, ``acos(conj(x))`` must equal ``conj(acos(x))``. .. note:: - The inverse cosine (or arc cosine) is a multi-valued function and requires a branch cut on the complex plane. By convention, a branch cut is placed at the line segments :math:`(-\\infty, -1)` and :math:`(1, \\infty)` of the real axis. + The inverse cosine (or arc cosine) is a multi-valued function and requires a branch cut on the complex plane. By convention, a branch cut is placed at the line segments :math:`(-\\infty, -1)` and :math:`(1, \\infty)` of the real axis. - Accordingly, for complex arguments, the function returns the inverse cosine in the range of a strip unbounded along the imaginary axis and in the interval :math:`[0, \\pi]` along the real axis. + Accordingly, for complex arguments, the function returns the inverse cosine in the range of a strip unbounded along the imaginary axis and in the interval :math:`[0, \\pi]` along the real axis. - *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). + *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). Parameters ---------- x: array - input array. Should have a floating-point data type. + input array. Should have a floating-point data type. Returns ------- out: array - an array containing the inverse cosine of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the inverse cosine of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -3683,7 +3687,7 @@ class acos[TArray: Array](Protocol): - If ``a`` is ``NaN`` and ``b`` is ``NaN``, the result is ``NaN + NaN j``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -3697,42 +3701,42 @@ class acosh[TArray: Array](Protocol): Calculates an implementation-dependent approximation to the inverse hyperbolic cosine for each element ``x_i`` of the input array ``x``. .. note:: - The principal value of the inverse hyperbolic cosine of a complex number :math:`z` is + The principal value of the inverse hyperbolic cosine of a complex number :math:`z` is - .. math:: - \\operatorname{acosh}(z) = \\ln(z + \\sqrt{z+1}\\sqrt{z-1}) + .. math:: + \\operatorname{acosh}(z) = \\ln(z + \\sqrt{z+1}\\sqrt{z-1}) - For any :math:`z`, + For any :math:`z`, - .. math:: - \\operatorname{acosh}(z) = \\frac{\\sqrt{z-1}}{\\sqrt{1-z}}\\operatorname{acos}(z) + .. math:: + \\operatorname{acosh}(z) = \\frac{\\sqrt{z-1}}{\\sqrt{1-z}}\\operatorname{acos}(z) - or simply + or simply - .. math:: - \\operatorname{acosh}(z) = j\\ \\operatorname{acos}(z) + .. math:: + \\operatorname{acosh}(z) = j\\ \\operatorname{acos}(z) - in the upper half of the complex plane. + in the upper half of the complex plane. .. note:: - For complex floating-point operands, ``acosh(conj(x))`` must equal ``conj(acosh(x))``. + For complex floating-point operands, ``acosh(conj(x))`` must equal ``conj(acosh(x))``. .. note:: - The inverse hyperbolic cosine is a multi-valued function and requires a branch cut on the complex plane. By convention, a branch cut is placed at the line segment :math:`(-\\infty, 1)` of the real axis. + The inverse hyperbolic cosine is a multi-valued function and requires a branch cut on the complex plane. By convention, a branch cut is placed at the line segment :math:`(-\\infty, 1)` of the real axis. - Accordingly, for complex arguments, the function returns the inverse hyperbolic cosine in the interval :math:`[0, \\infty)` along the real axis and in the interval :math:`[-\\pi j, +\\pi j]` along the imaginary axis. + Accordingly, for complex arguments, the function returns the inverse hyperbolic cosine in the interval :math:`[0, \\infty)` along the real axis and in the interval :math:`[-\\pi j, +\\pi j]` along the imaginary axis. - *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). + *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). Parameters ---------- x: array - input array whose elements each represent the area of a hyperbolic sector. Should have a floating-point data type. + input array whose elements each represent the area of a hyperbolic sector. Should have a floating-point data type. Returns ------- out: array - an array containing the inverse hyperbolic cosine of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the inverse hyperbolic cosine of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -3761,7 +3765,7 @@ class acosh[TArray: Array](Protocol): - If ``a`` is ``NaN`` and ``b`` is ``NaN``, the result is ``NaN + NaN j``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -3777,14 +3781,14 @@ class add[TArray: Array](Protocol): Parameters ---------- x1: Union[array, int, float, complex] - first input array. Should have a numeric data type. + first input array. Should have a numeric data type. x2: Union[array, int, float, complex] - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a numeric data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a numeric data type. Returns ------- out: array - an array containing the element-wise sums. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise sums. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- @@ -3813,7 +3817,7 @@ class add[TArray: Array](Protocol): - In the remaining cases, when neither ``infinity``, ``+0``, ``-0``, nor a ``NaN`` is involved, and the operands have the same mathematical sign or have different magnitudes, the sum must be computed and rounded to the nearest representable value according to IEEE 754-2019 and a supported round mode. If the magnitude is too large to represent, the operation overflows and the result is an `infinity` of appropriate mathematical sign. .. note:: - Floating-point addition is a commutative operation, but not always associative. + Floating-point addition is a commutative operation, but not always associative. For complex floating-point operands, addition is defined according to the following table. For real components ``a`` and ``c`` and imaginary components ``b`` and ``d``, @@ -3835,10 +3839,10 @@ class add[TArray: Array](Protocol): Hence, if ``z1 = a + bj = -0 + 0j`` and ``z2 = c + dj = -0 - 0j``, the result of ``z1 + z2`` is ``-0 + 0j``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. .. versionchanged:: 2024.12 - Added scalar argument support. + Added scalar argument support. """ @@ -3854,35 +3858,35 @@ class asin[TArray: Array](Protocol): Each element-wise result is expressed in radians. .. note:: - The principal value of the arc sine of a complex number :math:`z` is + The principal value of the arc sine of a complex number :math:`z` is - .. math:: - \\operatorname{asin}(z) = -j\\ \\ln(zj + \\sqrt{1-z^2}) + .. math:: + \\operatorname{asin}(z) = -j\\ \\ln(zj + \\sqrt{1-z^2}) - For any :math:`z`, + For any :math:`z`, - .. math:: - \\operatorname{asin}(z) = \\operatorname{acos}(-z) - \\frac{\\pi}{2} + .. math:: + \\operatorname{asin}(z) = \\operatorname{acos}(-z) - \\frac{\\pi}{2} .. note:: - For complex floating-point operands, ``asin(conj(x))`` must equal ``conj(asin(x))``. + For complex floating-point operands, ``asin(conj(x))`` must equal ``conj(asin(x))``. .. note:: - The inverse sine (or arc sine) is a multi-valued function and requires a branch cut on the complex plane. By convention, a branch cut is placed at the line segments :math:`(-\\infty, -1)` and :math:`(1, \\infty)` of the real axis. + The inverse sine (or arc sine) is a multi-valued function and requires a branch cut on the complex plane. By convention, a branch cut is placed at the line segments :math:`(-\\infty, -1)` and :math:`(1, \\infty)` of the real axis. - Accordingly, for complex arguments, the function returns the inverse sine in the range of a strip unbounded along the imaginary axis and in the interval :math:`[-\\pi/2, +\\pi/2]` along the real axis. + Accordingly, for complex arguments, the function returns the inverse sine in the range of a strip unbounded along the imaginary axis and in the interval :math:`[-\\pi/2, +\\pi/2]` along the real axis. - *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). + *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). Parameters ---------- x: array - input array. Should have a floating-point data type. + input array. Should have a floating-point data type. Returns ------- out: array - an array containing the inverse sine of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the inverse sine of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -3899,7 +3903,7 @@ class asin[TArray: Array](Protocol): For complex floating-point operands, special cases must be handled as if the operation is implemented as ``-1j * asinh(x*1j)``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -3913,35 +3917,35 @@ class asinh[TArray: Array](Protocol): Calculates an implementation-dependent approximation to the inverse hyperbolic sine for each element ``x_i`` in the input array ``x``. .. note:: - The principal value of the inverse hyperbolic sine of a complex number :math:`z` is + The principal value of the inverse hyperbolic sine of a complex number :math:`z` is - .. math:: - \\operatorname{asinh}(z) = \\ln(z + \\sqrt{1+z^2}) + .. math:: + \\operatorname{asinh}(z) = \\ln(z + \\sqrt{1+z^2}) - For any :math:`z`, + For any :math:`z`, - .. math:: - \\operatorname{asinh}(z) = \\frac{\\operatorname{asin}(zj)}{j} + .. math:: + \\operatorname{asinh}(z) = \\frac{\\operatorname{asin}(zj)}{j} .. note:: - For complex floating-point operands, ``asinh(conj(x))`` must equal ``conj(asinh(x))`` and ``asinh(-z)`` must equal ``-asinh(z)``. + For complex floating-point operands, ``asinh(conj(x))`` must equal ``conj(asinh(x))`` and ``asinh(-z)`` must equal ``-asinh(z)``. .. note:: - The inverse hyperbolic sine is a multi-valued function and requires a branch cut on the complex plane. By convention, a branch cut is placed at the line segments :math:`(-\\infty j, -j)` and :math:`(j, \\infty j)` of the imaginary axis. + The inverse hyperbolic sine is a multi-valued function and requires a branch cut on the complex plane. By convention, a branch cut is placed at the line segments :math:`(-\\infty j, -j)` and :math:`(j, \\infty j)` of the imaginary axis. - Accordingly, for complex arguments, the function returns the inverse hyperbolic sine in the range of a strip unbounded along the real axis and in the interval :math:`[-\\pi j/2, +\\pi j/2]` along the imaginary axis. + Accordingly, for complex arguments, the function returns the inverse hyperbolic sine in the range of a strip unbounded along the real axis and in the interval :math:`[-\\pi j/2, +\\pi j/2]` along the imaginary axis. - *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). + *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). Parameters ---------- x: array - input array whose elements each represent the area of a hyperbolic sector. Should have a floating-point data type. + input array whose elements each represent the area of a hyperbolic sector. Should have a floating-point data type. Returns ------- out: array - an array containing the inverse hyperbolic sine of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the inverse hyperbolic sine of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -3968,7 +3972,7 @@ class asinh[TArray: Array](Protocol): - If ``a`` is ``NaN`` and ``b`` is ``NaN``, the result is ``NaN + NaN j``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -3984,30 +3988,30 @@ class atan[TArray: Array](Protocol): Each element-wise result is expressed in radians. .. note:: - The principal value of the inverse tangent of a complex number :math:`z` is + The principal value of the inverse tangent of a complex number :math:`z` is - .. math:: - \\operatorname{atan}(z) = -\\frac{\\ln(1 - zj) - \\ln(1 + zj)}{2}j + .. math:: + \\operatorname{atan}(z) = -\\frac{\\ln(1 - zj) - \\ln(1 + zj)}{2}j .. note:: - For complex floating-point operands, ``atan(conj(x))`` must equal ``conj(atan(x))``. + For complex floating-point operands, ``atan(conj(x))`` must equal ``conj(atan(x))``. .. note:: - The inverse tangent (or arc tangent) is a multi-valued function and requires a branch on the complex plane. By convention, a branch cut is placed at the line segments :math:`(-\\infty j, -j)` and :math:`(+j, \\infty j)` of the imaginary axis. + The inverse tangent (or arc tangent) is a multi-valued function and requires a branch on the complex plane. By convention, a branch cut is placed at the line segments :math:`(-\\infty j, -j)` and :math:`(+j, \\infty j)` of the imaginary axis. - Accordingly, for complex arguments, the function returns the inverse tangent in the range of a strip unbounded along the imaginary axis and in the interval :math:`[-\\pi/2, +\\pi/2]` along the real axis. + Accordingly, for complex arguments, the function returns the inverse tangent in the range of a strip unbounded along the imaginary axis and in the interval :math:`[-\\pi/2, +\\pi/2]` along the real axis. - *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). + *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). Parameters ---------- x: array - input array. Should have a floating-point data type. + input array. Should have a floating-point data type. Returns ------- out: array - an array containing the inverse tangent of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the inverse tangent of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -4024,7 +4028,7 @@ class atan[TArray: Array](Protocol): For complex floating-point operands, special cases must be handled as if the operation is implemented as ``-1j * atanh(x*1j)``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -4040,21 +4044,21 @@ class atan2[TArray: Array](Protocol): The mathematical signs of ``x1_i`` and ``x2_i`` determine the quadrant of each element-wise result. The quadrant (i.e., branch) is chosen such that each element-wise result is the signed angle in radians between the ray ending at the origin and passing through the point ``(1,0)`` and the ray ending at the origin and passing through the point ``(x2_i, x1_i)``. .. note:: - Note the role reversal: the "y-coordinate" is the first function parameter; the "x-coordinate" is the second function parameter. The parameter order is intentional and traditional for the two-argument inverse tangent function where the y-coordinate argument is first and the x-coordinate argument is second. + Note the role reversal: the "y-coordinate" is the first function parameter; the "x-coordinate" is the second function parameter. The parameter order is intentional and traditional for the two-argument inverse tangent function where the y-coordinate argument is first and the x-coordinate argument is second. By IEEE 754 convention, the inverse tangent of the quotient ``x1/x2`` is defined for ``x2_i`` equal to positive or negative zero and for either or both of ``x1_i`` and ``x2_i`` equal to positive or negative ``infinity``. Parameters ---------- x1: Union[array, int, float] - input array corresponding to the y-coordinates. Should have a real-valued floating-point data type. + input array corresponding to the y-coordinates. Should have a real-valued floating-point data type. x2: Union[array, int, float] - input array corresponding to the x-coordinates. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued floating-point data type. + input array corresponding to the x-coordinates. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued floating-point data type. Returns ------- out: array - an array containing the inverse tangent of the quotient ``x1/x2``. The returned array must have a real-valued floating-point data type determined by :ref:`type-promotion`. + an array containing the inverse tangent of the quotient ``x1/x2``. The returned array must have a real-valued floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -4089,7 +4093,7 @@ class atan2[TArray: Array](Protocol): - If ``x1_i`` is ``-infinity`` and ``x2_i`` is ``-infinity``, the result is an implementation-dependent approximation to ``-3π/4``. .. versionchanged:: 2024.12 - Added scalar argument support. + Added scalar argument support. """ @@ -4103,35 +4107,35 @@ class atanh[TArray: Array](Protocol): Calculates an implementation-dependent approximation to the inverse hyperbolic tangent for each element ``x_i`` of the input array ``x``. .. note:: - The principal value of the inverse hyperbolic tangent of a complex number :math:`z` is + The principal value of the inverse hyperbolic tangent of a complex number :math:`z` is - .. math:: - \\operatorname{atanh}(z) = \\frac{\\ln(1+z)-\\ln(z-1)}{2} + .. math:: + \\operatorname{atanh}(z) = \\frac{\\ln(1+z)-\\ln(z-1)}{2} - For any :math:`z`, + For any :math:`z`, - .. math:: - \\operatorname{atanh}(z) = \\frac{\\operatorname{atan}(zj)}{j} + .. math:: + \\operatorname{atanh}(z) = \\frac{\\operatorname{atan}(zj)}{j} .. note:: - For complex floating-point operands, ``atanh(conj(x))`` must equal ``conj(atanh(x))`` and ``atanh(-x)`` must equal ``-atanh(x)``. + For complex floating-point operands, ``atanh(conj(x))`` must equal ``conj(atanh(x))`` and ``atanh(-x)`` must equal ``-atanh(x)``. .. note:: - The inverse hyperbolic tangent is a multi-valued function and requires a branch cut on the complex plane. By convention, a branch cut is placed at the line segments :math:`(-\\infty, 1]` and :math:`[1, \\infty)` of the real axis. + The inverse hyperbolic tangent is a multi-valued function and requires a branch cut on the complex plane. By convention, a branch cut is placed at the line segments :math:`(-\\infty, 1]` and :math:`[1, \\infty)` of the real axis. - Accordingly, for complex arguments, the function returns the inverse hyperbolic tangent in the range of a half-strip unbounded along the real axis and in the interval :math:`[-\\pi j/2, +\\pi j/2]` along the imaginary axis. + Accordingly, for complex arguments, the function returns the inverse hyperbolic tangent in the range of a half-strip unbounded along the real axis and in the interval :math:`[-\\pi j/2, +\\pi j/2]` along the imaginary axis. - *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). + *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). Parameters ---------- x: array - input array whose elements each represent the area of a hyperbolic sector. Should have a floating-point data type. + input array whose elements each represent the area of a hyperbolic sector. Should have a floating-point data type. Returns ------- out: array - an array containing the inverse hyperbolic tangent of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the inverse hyperbolic tangent of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -4162,7 +4166,7 @@ class atanh[TArray: Array](Protocol): - If ``a`` is ``NaN`` and ``b`` is ``NaN``, the result is ``NaN + NaN j``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -4178,21 +4182,21 @@ class bitwise_and[TArray: Array](Protocol): Parameters ---------- x1: Union[array, int, bool] - first input array. Should have an integer or boolean data type. + first input array. Should have an integer or boolean data type. x2: Union[array, int, bool] - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have an integer or boolean data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have an integer or boolean data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- - At least one of ``x1`` or ``x2`` must be an array. .. versionchanged:: 2024.12 - Added scalar argument support. + Added scalar argument support. """ @@ -4208,21 +4212,21 @@ class bitwise_left_shift[TArray: Array](Protocol): Parameters ---------- x1: Union[array, int] - first input array. Should have an integer data type. + first input array. Should have an integer data type. x2: Union[array, int] - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have an integer data type. Each element must be greater than or equal to ``0``. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have an integer data type. Each element must be greater than or equal to ``0``. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- - At least one of ``x1`` or ``x2`` must be an array. .. versionchanged:: 2024.12 - Added scalar argument support. + Added scalar argument support. """ @@ -4238,12 +4242,12 @@ class bitwise_invert[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have an integer or boolean data type. + input array. Should have an integer or boolean data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have the same data type as ``x``. + an array containing the element-wise results. The returned array must have the same data type as ``x``. """ @@ -4259,21 +4263,21 @@ class bitwise_or[TArray: Array](Protocol): Parameters ---------- x1: Union[array, int, bool] - first input array. Should have an integer or boolean data type. + first input array. Should have an integer or boolean data type. x2: Union[array, int, bool] - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have an integer or boolean data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have an integer or boolean data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- - At least one of ``x1`` or ``x2`` must be an array. .. versionchanged:: 2024.12 - Added scalar argument support. + Added scalar argument support. """ @@ -4287,26 +4291,26 @@ class bitwise_right_shift[TArray: Array](Protocol): Shifts the bits of each element ``x1_i`` of the input array ``x1`` to the right according to the respective element ``x2_i`` of the input array ``x2``. .. note:: - This operation must be an arithmetic shift (i.e., sign-propagating) and thus equivalent to floor division by a power of two. + This operation must be an arithmetic shift (i.e., sign-propagating) and thus equivalent to floor division by a power of two. Parameters ---------- x1: Union[array, int] - first input array. Should have an integer data type. + first input array. Should have an integer data type. x2: Union[array, int] - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have an integer data type. Each element must be greater than or equal to ``0``. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have an integer data type. Each element must be greater than or equal to ``0``. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- - At least one of ``x1`` or ``x2`` must be an array. .. versionchanged:: 2024.12 - Added scalar argument support. + Added scalar argument support. """ @@ -4322,21 +4326,21 @@ class bitwise_xor[TArray: Array](Protocol): Parameters ---------- x1: Union[array, int, bool] - first input array. Should have an integer or boolean data type. + first input array. Should have an integer or boolean data type. x2: Union[array, int, bool] - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have an integer or boolean data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have an integer or boolean data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- - At least one of ``x1`` or ``x2`` must be an array. .. versionchanged:: 2024.12 - Added scalar argument support. + Added scalar argument support. """ @@ -4352,12 +4356,12 @@ class ceil[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a real-valued data type. + input array. Should have a real-valued data type. Returns ------- out: array - an array containing the rounded result for each element in ``x``. The returned array must have the same data type as ``x``. + an array containing the rounded result for each element in ``x``. The returned array must have the same data type as ``x``. Notes ----- @@ -4387,16 +4391,16 @@ class clip[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a real-valued data type. + input array. Should have a real-valued data type. min: Optional[Union[int, float, array]] - lower-bound of the range to which to clamp. If ``None``, no lower bound must be applied. Must be compatible with ``x`` and ``max`` (see :ref:`broadcasting`). Should have the same data type as ``x``. Default: ``None``. + lower-bound of the range to which to clamp. If ``None``, no lower bound must be applied. Must be compatible with ``x`` and ``max`` (see :ref:`broadcasting`). Should have the same data type as ``x``. Default: ``None``. max: Optional[Union[int, float, array]] - upper-bound of the range to which to clamp. If ``None``, no upper bound must be applied. Must be compatible with ``x`` and ``min`` (see :ref:`broadcasting`). Should have the same data type as ``x``. Default: ``None``. + upper-bound of the range to which to clamp. If ``None``, no upper bound must be applied. Must be compatible with ``x`` and ``min`` (see :ref:`broadcasting`). Should have the same data type as ``x``. Default: ``None``. Returns ------- out: array - an array containing element-wise results. The returned array should have the same data type as ``x``. + an array containing element-wise results. The returned array should have the same data type as ``x``. Notes ----- @@ -4416,13 +4420,13 @@ class clip[TArray: Array](Protocol): .. versionadded:: 2023.12 .. versionchanged:: 2024.12 - Added special case behavior when one of the operands is ``NaN``. + Added special case behavior when one of the operands is ``NaN``. .. versionchanged:: 2024.12 - Clarified that behavior is only defined when ``x``, ``min``, and ``max`` resolve to arrays having the same data type. + Clarified that behavior is only defined when ``x``, ``min``, and ``max`` resolve to arrays having the same data type. .. versionchanged:: 2024.12 - Clarified that behavior is only defined when elements of ``min`` and ``max`` are inside the bounds of the input array data type. + Clarified that behavior is only defined when elements of ``min`` and ``max`` are inside the bounds of the input array data type. """ @@ -4438,24 +4442,24 @@ class conj[TArray: Array](Protocol): For complex numbers of the form .. math:: - a + bj + a + bj the complex conjugate is defined as .. math:: - a - bj + a - bj Hence, the returned complex conjugates must be computed by negating the imaginary component of each element ``x_i``. Parameters ---------- x: array - input array. Must have a numeric data type. + input array. Must have a numeric data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have the same data type as ``x``. + an array containing the element-wise results. The returned array must have the same data type as ``x``. Notes ----- @@ -4464,7 +4468,7 @@ class conj[TArray: Array](Protocol): .. versionadded:: 2022.12 .. versionchanged:: 2024.12 - Added support for real-valued arrays. + Added support for real-valued arrays. """ @@ -4480,14 +4484,14 @@ class copysign[TArray: Array](Protocol): Parameters ---------- x1: Union[array, int, float] - input array containing magnitudes. Should have a real-valued floating-point data type. + input array containing magnitudes. Should have a real-valued floating-point data type. x2: Union[array, int, float] - input array whose sign bits are applied to the magnitudes of ``x1``. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued floating-point data type. + input array whose sign bits are applied to the magnitudes of ``x1``. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued floating-point data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the element-wise results. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -4514,7 +4518,7 @@ class copysign[TArray: Array](Protocol): .. versionadded:: 2023.12 .. versionchanged:: 2024.12 - Added scalar argument support. + Added scalar argument support. """ @@ -4530,25 +4534,25 @@ class cos[TArray: Array](Protocol): Each element ``x_i`` is assumed to be expressed in radians. .. note:: - The cosine is an entire function on the complex plane and has no branch cuts. + The cosine is an entire function on the complex plane and has no branch cuts. .. note:: - For complex arguments, the mathematical definition of cosine is + For complex arguments, the mathematical definition of cosine is - .. math:: - \\begin{align} \\operatorname{cos}(x) &= \\sum_{n=0}^\\infty \\frac{(-1)^n}{(2n)!} x^{2n} \\\\ &= \\frac{e^{jx} + e^{-jx}}{2} \\\\ &= \\operatorname{cosh}(jx) \\end{align} + .. math:: + \\begin{align} \\operatorname{cos}(x) &= \\sum_{n=0}^\\infty \\frac{(-1)^n}{(2n)!} x^{2n} \\\\ &= \\frac{e^{jx} + e^{-jx}}{2} \\\\ &= \\operatorname{cosh}(jx) \\end{align} - where :math:`\\operatorname{cosh}` is the hyperbolic cosine. + where :math:`\\operatorname{cosh}` is the hyperbolic cosine. Parameters ---------- x: array - input array whose elements are each expressed in radians. Should have a floating-point data type. + input array whose elements are each expressed in radians. Should have a floating-point data type. Returns ------- out: array - an array containing the cosine of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the cosine of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -4565,7 +4569,7 @@ class cos[TArray: Array](Protocol): For complex floating-point operands, special cases must be handled as if the operation is implemented as ``cosh(x*1j)``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -4581,27 +4585,27 @@ class cosh[TArray: Array](Protocol): The mathematical definition of the hyperbolic cosine is .. math:: - \\operatorname{cosh}(x) = \\frac{e^x + e^{-x}}{2} + \\operatorname{cosh}(x) = \\frac{e^x + e^{-x}}{2} .. note:: - The hyperbolic cosine is an entire function in the complex plane and has no branch cuts. The function is periodic, with period :math:`2\\pi j`, with respect to the imaginary component. + The hyperbolic cosine is an entire function in the complex plane and has no branch cuts. The function is periodic, with period :math:`2\\pi j`, with respect to the imaginary component. Parameters ---------- x: array - input array whose elements each represent a hyperbolic angle. Should have a floating-point data type. + input array whose elements each represent a hyperbolic angle. Should have a floating-point data type. Returns ------- out: array - an array containing the hyperbolic cosine of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the hyperbolic cosine of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- **Special cases** .. note:: - For all operands, ``cosh(x)`` must equal ``cosh(-x)``. + For all operands, ``cosh(x)`` must equal ``cosh(-x)``. For real-valued floating-point operands, @@ -4614,7 +4618,7 @@ class cosh[TArray: Array](Protocol): For complex floating-point operands, let ``a = real(x_i)``, ``b = imag(x_i)``, and .. note:: - For complex floating-point operands, ``cosh(conj(x))`` must equal ``conj(cosh(x))``. + For complex floating-point operands, ``cosh(conj(x))`` must equal ``conj(cosh(x))``. - If ``a`` is ``+0`` and ``b`` is ``+0``, the result is ``1 + 0j``. - If ``a`` is ``+0`` and ``b`` is ``+infinity``, the result is ``NaN + 0j`` (sign of the imaginary component is unspecified). @@ -4632,7 +4636,7 @@ class cosh[TArray: Array](Protocol): where ``cis(v)`` is ``cos(v) + sin(v)*1j``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -4648,14 +4652,14 @@ class divide[TArray: Array](Protocol): Parameters ---------- x1: Union[array, int, float, complex] - dividend input array. Should have a numeric data type. + dividend input array. Should have a numeric data type. x2: Union[array, int, float, complex] - divisor input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a numeric data type. + divisor input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a numeric data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the element-wise results. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -4663,7 +4667,7 @@ class divide[TArray: Array](Protocol): - If one or both of the input arrays have integer data types, the result is implementation-dependent, as type promotion between data type "kinds" (e.g., integer versus floating-point) is unspecified. - Specification-compliant libraries may choose to raise an error or return an array containing the element-wise results. If an array is returned, the array must have a real-valued floating-point data type. + Specification-compliant libraries may choose to raise an error or return an array containing the element-wise results. If an array is returned, the array must have a real-valued floating-point data type. **Special cases** @@ -4709,7 +4713,7 @@ class divide[TArray: Array](Protocol): When ``a``, ``b``, ``c``, or ``d`` are all finite numbers (i.e., a value other than ``NaN``, ``+infinity``, or ``-infinity``), division of complex floating-point operands should be computed as if calculated according to the textbook formula for complex number division .. math:: - \\frac{a + bj}{c + dj} = \\frac{(ac + bd) + (bc - ad)j}{c^2 + d^2} + \\frac{a + bj}{c + dj} = \\frac{(ac + bd) + (bc - ad)j}{c^2 + d^2} When at least one of ``a``, ``b``, ``c``, or ``d`` is ``NaN``, ``+infinity``, or ``-infinity``, @@ -4717,13 +4721,13 @@ class divide[TArray: Array](Protocol): - In the remaining cases, the result is implementation dependent. .. note:: - For complex floating-point operands, the results of special cases may be implementation dependent depending on how an implementation chooses to model complex numbers and complex infinity (e.g., complex plane versus Riemann sphere). For those implementations following C99 and its one-infinity model, when at least one component is infinite, even if the other component is ``NaN``, the complex value is infinite, and the usual arithmetic rules do not apply to complex-complex division. In the interest of performance, other implementations may want to avoid the complex branching logic necessary to implement the one-infinity model and choose to implement all complex-complex division according to the textbook formula. Accordingly, special case behavior is unlikely to be consistent across implementations. + For complex floating-point operands, the results of special cases may be implementation dependent depending on how an implementation chooses to model complex numbers and complex infinity (e.g., complex plane versus Riemann sphere). For those implementations following C99 and its one-infinity model, when at least one component is infinite, even if the other component is ``NaN``, the complex value is infinite, and the usual arithmetic rules do not apply to complex-complex division. In the interest of performance, other implementations may want to avoid the complex branching logic necessary to implement the one-infinity model and choose to implement all complex-complex division according to the textbook formula. Accordingly, special case behavior is unlikely to be consistent across implementations. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. .. versionchanged:: 2024.12 - Added scalar argument support. + Added scalar argument support. """ @@ -4739,14 +4743,14 @@ class equal[TArray: Array](Protocol): Parameters ---------- x1: Union[array, int, float, complex, bool] - first input array. May have any data type. + first input array. May have any data type. x2: Union[array, int, float, complex, bool] - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). May have any data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). May have any data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type of ``bool``. + an array containing the element-wise results. The returned array must have a data type of ``bool``. Notes ----- @@ -4770,19 +4774,19 @@ class equal[TArray: Array](Protocol): - In the remaining cases, the result is the logical AND of the equality comparison between the real values ``a`` and ``c`` (real components) and between the real values ``b`` and ``d`` (imaginary components), as described above for real-valued floating-point operands (i.e., ``a == c AND b == d``). .. note:: - For discussion of complex number equality, see :ref:`complex-numbers`. + For discussion of complex number equality, see :ref:`complex-numbers`. .. note:: - Comparison of arrays without a corresponding promotable data type (see :ref:`type-promotion`) is undefined and thus implementation-dependent. + Comparison of arrays without a corresponding promotable data type (see :ref:`type-promotion`) is undefined and thus implementation-dependent. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. .. versionchanged:: 2024.12 - Cross-kind comparisons are explicitly left unspecified. + Cross-kind comparisons are explicitly left unspecified. .. versionchanged:: 2024.12 - Added scalar argument support. + Added scalar argument support. """ @@ -4796,20 +4800,20 @@ class exp[TArray: Array](Protocol): Calculates an implementation-dependent approximation to the exponential function for each element ``x_i`` of the input array ``x`` (``e`` raised to the power of ``x_i``, where ``e`` is the base of the natural logarithm). .. note:: - For complex floating-point operands, ``exp(conj(x))`` must equal ``conj(exp(x))``. + For complex floating-point operands, ``exp(conj(x))`` must equal ``conj(exp(x))``. .. note:: - The exponential function is an entire function in the complex plane and has no branch cuts. + The exponential function is an entire function in the complex plane and has no branch cuts. Parameters ---------- x: array - input array. Should have a floating-point data type. + input array. Should have a floating-point data type. Returns ------- out: array - an array containing the evaluated exponential function result for each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the evaluated exponential function result for each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -4842,7 +4846,7 @@ class exp[TArray: Array](Protocol): where ``cis(v)`` is ``cos(v) + sin(v)*1j``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -4856,23 +4860,23 @@ class expm1[TArray: Array](Protocol): Calculates an implementation-dependent approximation to ``exp(x)-1`` for each element ``x_i`` of the input array ``x``. .. note:: - The purpose of this function is to calculate ``exp(x)-1.0`` more accurately when `x` is close to zero. Accordingly, conforming implementations should avoid implementing this function as simply ``exp(x)-1.0``. See FDLIBM, or some other IEEE 754-2019 compliant mathematical library, for a potential reference implementation. + The purpose of this function is to calculate ``exp(x)-1.0`` more accurately when `x` is close to zero. Accordingly, conforming implementations should avoid implementing this function as simply ``exp(x)-1.0``. See FDLIBM, or some other IEEE 754-2019 compliant mathematical library, for a potential reference implementation. .. note:: - For complex floating-point operands, ``expm1(conj(x))`` must equal ``conj(expm1(x))``. + For complex floating-point operands, ``expm1(conj(x))`` must equal ``conj(expm1(x))``. .. note:: - The exponential function is an entire function in the complex plane and has no branch cuts. + The exponential function is an entire function in the complex plane and has no branch cuts. Parameters ---------- x: array - input array. Should have a floating-point data type. + input array. Should have a floating-point data type. Returns ------- out: array - an array containing the evaluated result for each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the evaluated result for each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -4905,7 +4909,7 @@ class expm1[TArray: Array](Protocol): where ``cis(v)`` is ``cos(v) + sin(v)*1j``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -4921,12 +4925,12 @@ class floor[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a real-valued data type. + input array. Should have a real-valued data type. Returns ------- out: array - an array containing the rounded result for each element in ``x``. The returned array must have the same data type as ``x``. + an array containing the rounded result for each element in ``x``. The returned array must have the same data type as ``x``. Notes ----- @@ -4956,14 +4960,14 @@ class floor_divide[TArray: Array](Protocol): Parameters ---------- x1: Union[array, int, float] - dividend input array. Should have a real-valued data type. + dividend input array. Should have a real-valued data type. x2: Union[array, int, float] - divisor input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued data type. + divisor input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- @@ -4973,13 +4977,13 @@ class floor_divide[TArray: Array](Protocol): **Special cases** .. note:: - Floor division was introduced in Python via `PEP 238 `_ with the goal to disambiguate "true division" (i.e., computing an approximation to the mathematical operation of division) from "floor division" (i.e., rounding the result of division toward negative infinity). The former was computed when one of the operands was a ``float``, while the latter was computed when both operands were ``int``\\s. Overloading the ``/`` operator to support both behaviors led to subtle numerical bugs when integers are possible, but not expected. + Floor division was introduced in Python via `PEP 238 `_ with the goal to disambiguate "true division" (i.e., computing an approximation to the mathematical operation of division) from "floor division" (i.e., rounding the result of division toward negative infinity). The former was computed when one of the operands was a ``float``, while the latter was computed when both operands were ``int``\\s. Overloading the ``/`` operator to support both behaviors led to subtle numerical bugs when integers are possible, but not expected. - To resolve this ambiguity, ``/`` was designated for true division, and ``//`` was designated for floor division. Semantically, floor division was `defined `_ as equivalent to ``a // b == floor(a/b)``; however, special floating-point cases were left ill-defined. + To resolve this ambiguity, ``/`` was designated for true division, and ``//`` was designated for floor division. Semantically, floor division was `defined `_ as equivalent to ``a // b == floor(a/b)``; however, special floating-point cases were left ill-defined. - Accordingly, floor division is not implemented consistently across array libraries for some of the special cases documented below. Namely, when one of the operands is ``infinity``, libraries may diverge with some choosing to strictly follow ``floor(a/b)`` and others choosing to pair ``//`` with ``%`` according to the relation ``b = a % b + b * (a // b)``. The special cases leading to divergent behavior are documented below. + Accordingly, floor division is not implemented consistently across array libraries for some of the special cases documented below. Namely, when one of the operands is ``infinity``, libraries may diverge with some choosing to strictly follow ``floor(a/b)`` and others choosing to pair ``//`` with ``%`` according to the relation ``b = a % b + b * (a // b)``. The special cases leading to divergent behavior are documented below. - This specification prefers floor division to match ``floor(divide(x1, x2))`` in order to avoid surprising and unexpected results; however, array libraries may choose to more strictly follow Python behavior. + This specification prefers floor division to match ``floor(divide(x1, x2))`` in order to avoid surprising and unexpected results; however, array libraries may choose to more strictly follow Python behavior. For floating-point operands, @@ -5007,7 +5011,7 @@ class floor_divide[TArray: Array](Protocol): - In the remaining cases, where neither ``-infinity``, ``+0``, ``-0``, nor ``NaN`` is involved, the quotient must be computed and rounded to the greatest (i.e., closest to `+infinity`) representable integer-value number that is not greater than the division result. If the magnitude is too large to represent, the operation overflows and the result is an ``infinity`` of appropriate mathematical sign. If the magnitude is too small to represent, the operation underflows and the result is a zero of appropriate mathematical sign. .. versionchanged:: 2024.12 - Added scalar argument support. + Added scalar argument support. """ @@ -5023,14 +5027,14 @@ class greater[TArray: Array](Protocol): Parameters ---------- x1: Union[array, int, float] - first input array. Should have a real-valued data type. + first input array. Should have a real-valued data type. x2: Union[array, int, float] - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type of ``bool``. + an array containing the element-wise results. The returned array must have a data type of ``bool``. Notes ----- @@ -5039,10 +5043,10 @@ class greater[TArray: Array](Protocol): - For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). .. versionchanged:: 2024.12 - Cross-kind comparisons are explicitly left unspecified. + Cross-kind comparisons are explicitly left unspecified. .. versionchanged:: 2024.12 - Added scalar argument support. + Added scalar argument support. """ @@ -5058,14 +5062,14 @@ class greater_equal[TArray: Array](Protocol): Parameters ---------- x1: Union[array, int, float] - first input array. Should have a real-valued data type. + first input array. Should have a real-valued data type. x2: Union[array, int, float] - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type of ``bool``. + an array containing the element-wise results. The returned array must have a data type of ``bool``. Notes ----- @@ -5074,10 +5078,10 @@ class greater_equal[TArray: Array](Protocol): - For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). .. versionchanged:: 2024.12 - Cross-kind comparisons are explicitly left unspecified. + Cross-kind comparisons are explicitly left unspecified. .. versionchanged:: 2024.12 - Added scalar argument support. + Added scalar argument support. """ @@ -5091,19 +5095,19 @@ class hypot[TArray: Array](Protocol): Computes the square root of the sum of squares for each element ``x1_i`` of the input array ``x1`` with the respective element ``x2_i`` of the input array ``x2``. .. note:: - The value computed by this function may be interpreted as the length of the hypotenuse of a right-angled triangle with sides of length ``x1_i`` and ``x2_i``, the distance of a point ``(x1_i, x2_i)`` from the origin ``(0, 0)``, or the magnitude of a complex number ``x1_i + x2_i * 1j``. + The value computed by this function may be interpreted as the length of the hypotenuse of a right-angled triangle with sides of length ``x1_i`` and ``x2_i``, the distance of a point ``(x1_i, x2_i)`` from the origin ``(0, 0)``, or the magnitude of a complex number ``x1_i + x2_i * 1j``. Parameters ---------- x1: Union[array, int, float] - first input array. Should have a real-valued floating-point data type. + first input array. Should have a real-valued floating-point data type. x2: Union[array, int, float] - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued floating-point data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued floating-point data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a real-valued floating-point data type determined by :ref:`type-promotion`. + an array containing the element-wise results. The returned array must have a real-valued floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -5125,14 +5129,14 @@ class hypot[TArray: Array](Protocol): For real-valued floating-point operands, ``hypot(x1, x2)`` must equal ``hypot(x2, x1)``, ``hypot(x1, -x2)``, ``hypot(-x1, x2)``, and ``hypot(-x1, -x2)``. .. note:: - IEEE 754-2019 requires support for subnormal (a.k.a., denormal) numbers, which are useful for supporting gradual underflow. However, hardware support for subnormal numbers is not universal, and many platforms (e.g., accelerators) and compilers support toggling denormals-are-zero (DAZ) and/or flush-to-zero (FTZ) behavior to increase performance and to guard against timing attacks. + IEEE 754-2019 requires support for subnormal (a.k.a., denormal) numbers, which are useful for supporting gradual underflow. However, hardware support for subnormal numbers is not universal, and many platforms (e.g., accelerators) and compilers support toggling denormals-are-zero (DAZ) and/or flush-to-zero (FTZ) behavior to increase performance and to guard against timing attacks. - Accordingly, conforming implementations may vary in their support for subnormal numbers. + Accordingly, conforming implementations may vary in their support for subnormal numbers. .. versionadded:: 2023.12 .. versionchanged:: 2024.12 - Added scalar argument support. + Added scalar argument support. """ @@ -5148,12 +5152,12 @@ class imag[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a complex floating-point data type. + input array. Should have a complex floating-point data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a floating-point data type with the same floating-point precision as ``x`` (e.g., if ``x`` is ``complex64``, the returned array must have the floating-point data type ``float32``). + an array containing the element-wise results. The returned array must have a floating-point data type with the same floating-point precision as ``x`` (e.g., if ``x`` is ``complex64``, the returned array must have the floating-point data type ``float32``). Notes ----- @@ -5174,12 +5178,12 @@ class isfinite[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a numeric data type. + input array. Should have a numeric data type. Returns ------- out: array - an array containing test results. The returned array must have a data type of ``bool``. + an array containing test results. The returned array must have a data type of ``bool``. Notes ----- @@ -5199,7 +5203,7 @@ class isfinite[TArray: Array](Protocol): - If ``a`` is a finite number and ``b`` is a finite number, the result is ``True``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -5215,12 +5219,12 @@ class isinf[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a numeric data type. + input array. Should have a numeric data type. Returns ------- out: array - an array containing test results. The returned array must have a data type of ``bool``. + an array containing test results. The returned array must have a data type of ``bool``. Notes ----- @@ -5238,7 +5242,7 @@ class isinf[TArray: Array](Protocol): - In the remaining cases, the result is ``False``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -5254,12 +5258,12 @@ class isnan[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a numeric data type. + input array. Should have a numeric data type. Returns ------- out: array - an array containing test results. The returned array should have a data type of ``bool``. + an array containing test results. The returned array should have a data type of ``bool``. Notes ----- @@ -5276,7 +5280,7 @@ class isnan[TArray: Array](Protocol): - In the remaining cases, the result is ``False``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -5292,14 +5296,14 @@ class less[TArray: Array](Protocol): Parameters ---------- x1: Union[array, int, float] - first input array. Should have a real-valued data type. + first input array. Should have a real-valued data type. x2: Union[array, int, float] - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type of ``bool``. + an array containing the element-wise results. The returned array must have a data type of ``bool``. Notes ----- @@ -5308,10 +5312,10 @@ class less[TArray: Array](Protocol): - For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). .. versionchanged:: 2024.12 - Cross-kind comparisons are explicitly left unspecified. + Cross-kind comparisons are explicitly left unspecified. .. versionchanged:: 2024.12 - Added scalar argument support. + Added scalar argument support. """ @@ -5327,14 +5331,14 @@ class less_equal[TArray: Array](Protocol): Parameters ---------- x1: Union[array, int, float] - first input array. Should have a real-valued data type. + first input array. Should have a real-valued data type. x2: Union[array, int, float] - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type of ``bool``. + an array containing the element-wise results. The returned array must have a data type of ``bool``. Notes ----- @@ -5343,10 +5347,10 @@ class less_equal[TArray: Array](Protocol): - For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). .. versionchanged:: 2024.12 - Cross-kind comparisons are explicitly left unspecified. + Cross-kind comparisons are explicitly left unspecified. .. versionchanged:: 2024.12 - Added scalar argument support. + Added scalar argument support. """ @@ -5360,29 +5364,29 @@ class log[TArray: Array](Protocol): Calculates an implementation-dependent approximation to the natural (base ``e``) logarithm for each element ``x_i`` of the input array ``x``. .. note:: - The natural logarithm of a complex number :math:`z` with polar coordinates :math:`(r,\\theta)` equals :math:`\\ln r + (\\theta + 2n\\pi)j` with principal value :math:`\\ln r + \\theta j`. + The natural logarithm of a complex number :math:`z` with polar coordinates :math:`(r,\\theta)` equals :math:`\\ln r + (\\theta + 2n\\pi)j` with principal value :math:`\\ln r + \\theta j`. .. note:: - For complex floating-point operands, ``log(conj(x))`` must equal ``conj(log(x))``. + For complex floating-point operands, ``log(conj(x))`` must equal ``conj(log(x))``. .. note:: - By convention, the branch cut of the natural logarithm is the negative real axis :math:`(-\\infty, 0)`. + By convention, the branch cut of the natural logarithm is the negative real axis :math:`(-\\infty, 0)`. - The natural logarithm is a continuous function from above the branch cut, taking into account the sign of the imaginary component. + The natural logarithm is a continuous function from above the branch cut, taking into account the sign of the imaginary component. - Accordingly, for complex arguments, the function returns the natural logarithm in the range of a strip in the interval :math:`[-\\pi j, +\\pi j]` along the imaginary axis and mathematically unbounded along the real axis. + Accordingly, for complex arguments, the function returns the natural logarithm in the range of a strip in the interval :math:`[-\\pi j, +\\pi j]` along the imaginary axis and mathematically unbounded along the real axis. - *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). + *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). Parameters ---------- x: array - input array. Should have a floating-point data type. + input array. Should have a floating-point data type. Returns ------- out: array - an array containing the evaluated natural logarithm for each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the evaluated natural logarithm for each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -5412,7 +5416,7 @@ class log[TArray: Array](Protocol): - If ``a`` is ``NaN`` and ``b`` is ``NaN``, the result is ``NaN + NaN j``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -5426,29 +5430,29 @@ class log1p[TArray: Array](Protocol): Calculates an implementation-dependent approximation to ``log(1+x)``, where ``log`` refers to the natural (base ``e``) logarithm, for each element ``x_i`` of the input array ``x``. .. note:: - The purpose of this function is to calculate ``log(1+x)`` more accurately when `x` is close to zero. Accordingly, conforming implementations should avoid implementing this function as simply ``log(1+x)``. See FDLIBM, or some other IEEE 754-2019 compliant mathematical library, for a potential reference implementation. + The purpose of this function is to calculate ``log(1+x)`` more accurately when `x` is close to zero. Accordingly, conforming implementations should avoid implementing this function as simply ``log(1+x)``. See FDLIBM, or some other IEEE 754-2019 compliant mathematical library, for a potential reference implementation. .. note:: - For complex floating-point operands, ``log1p(conj(x))`` must equal ``conj(log1p(x))``. + For complex floating-point operands, ``log1p(conj(x))`` must equal ``conj(log1p(x))``. .. note:: - By convention, the branch cut of the natural logarithm is the negative real axis :math:`(-\\infty, 0)`. + By convention, the branch cut of the natural logarithm is the negative real axis :math:`(-\\infty, 0)`. - The natural logarithm is a continuous function from above the branch cut, taking into account the sign of the imaginary component. + The natural logarithm is a continuous function from above the branch cut, taking into account the sign of the imaginary component. - Accordingly, for complex arguments, the function returns the natural logarithm in the range of a strip in the interval :math:`[-\\pi j, +\\pi j]` along the imaginary axis and mathematically unbounded along the real axis. + Accordingly, for complex arguments, the function returns the natural logarithm in the range of a strip in the interval :math:`[-\\pi j, +\\pi j]` along the imaginary axis and mathematically unbounded along the real axis. - *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). + *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). Parameters ---------- x: array - input array. Should have a floating-point data type. + input array. Should have a floating-point data type. Returns ------- out: array - an array containing the evaluated result for each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the evaluated result for each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -5478,7 +5482,7 @@ class log1p[TArray: Array](Protocol): - If ``a`` is ``NaN`` and ``b`` is ``NaN``, the result is ``NaN + NaN j``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -5492,17 +5496,17 @@ class log2[TArray: Array](Protocol): Calculates an implementation-dependent approximation to the base ``2`` logarithm for each element ``x_i`` of the input array ``x``. .. note:: - For complex floating-point operands, ``log2(conj(x))`` must equal ``conj(log2(x))``. + For complex floating-point operands, ``log2(conj(x))`` must equal ``conj(log2(x))``. Parameters ---------- x: array - input array. Should have a floating-point data type. + input array. Should have a floating-point data type. Returns ------- out: array - an array containing the evaluated base ``2`` logarithm for each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the evaluated base ``2`` logarithm for each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -5519,12 +5523,12 @@ class log2[TArray: Array](Protocol): For complex floating-point operands, special cases must be handled as if the operation is implemented using the standard change of base formula .. math:: - \\log_{2} x = \\frac{\\log_{e} x}{\\log_{e} 2} + \\log_{2} x = \\frac{\\log_{e} x}{\\log_{e} 2} where :math:`\\log_{e}` is the natural logarithm, as implemented by :func:`~array_api.log`. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -5538,17 +5542,17 @@ class log10[TArray: Array](Protocol): Calculates an implementation-dependent approximation to the base ``10`` logarithm for each element ``x_i`` of the input array ``x``. .. note:: - For complex floating-point operands, ``log10(conj(x))`` must equal ``conj(log10(x))``. + For complex floating-point operands, ``log10(conj(x))`` must equal ``conj(log10(x))``. Parameters ---------- x: array - input array. Should have a floating-point data type. + input array. Should have a floating-point data type. Returns ------- out: array - an array containing the evaluated base ``10`` logarithm for each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the evaluated base ``10`` logarithm for each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -5565,12 +5569,12 @@ class log10[TArray: Array](Protocol): For complex floating-point operands, special cases must be handled as if the operation is implemented using the standard change of base formula .. math:: - \\log_{10} x = \\frac{\\log_{e} x}{\\log_{e} 10} + \\log_{10} x = \\frac{\\log_{e} x}{\\log_{e} 10} where :math:`\\log_{e}` is the natural logarithm, as implemented by :func:`~array_api.log`. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -5586,14 +5590,14 @@ class logaddexp[TArray: Array](Protocol): Parameters ---------- x1: Union[array, int, float] - first input array. Should have a real-valued floating-point data type. + first input array. Should have a real-valued floating-point data type. x2: Union[array, int, float] - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued floating-point data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued floating-point data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a real-valued floating-point data type determined by :ref:`type-promotion`. + an array containing the element-wise results. The returned array must have a real-valued floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -5608,7 +5612,7 @@ class logaddexp[TArray: Array](Protocol): - If ``x1_i`` is not ``NaN`` and ``x2_i`` is ``+infinity``, the result is ``+infinity``. .. versionchanged:: 2024.12 - Added scalar argument support. + Added scalar argument support. """ @@ -5622,26 +5626,26 @@ class logical_and[TArray: Array](Protocol): Computes the logical AND for each element ``x1_i`` of the input array ``x1`` with the respective element ``x2_i`` of the input array ``x2``. .. note:: - While this specification recommends that this function only accept input arrays having a boolean data type, specification-compliant array libraries may choose to accept input arrays having real-valued data types. If non-boolean data types are supported, zeros must be considered the equivalent of ``False``, while non-zeros must be considered the equivalent of ``True``. + While this specification recommends that this function only accept input arrays having a boolean data type, specification-compliant array libraries may choose to accept input arrays having real-valued data types. If non-boolean data types are supported, zeros must be considered the equivalent of ``False``, while non-zeros must be considered the equivalent of ``True``. Parameters ---------- x1: Union[array, bool] - first input array. Should have a boolean data type. + first input array. Should have a boolean data type. x2: Union[array, bool] - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a boolean data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a boolean data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type of `bool`. + an array containing the element-wise results. The returned array must have a data type of `bool`. Notes ----- - At least one of ``x1`` or ``x2`` must be an array. .. versionchanged:: 2024.12 - Added scalar argument support. + Added scalar argument support. """ @@ -5655,17 +5659,17 @@ class logical_not[TArray: Array](Protocol): Computes the logical NOT for each element ``x_i`` of the input array ``x``. .. note:: - While this specification recommends that this function only accept input arrays having a boolean data type, specification-compliant array libraries may choose to accept input arrays having real-valued data types. If non-boolean data types are supported, zeros must be considered the equivalent of ``False``, while non-zeros must be considered the equivalent of ``True``. + While this specification recommends that this function only accept input arrays having a boolean data type, specification-compliant array libraries may choose to accept input arrays having real-valued data types. If non-boolean data types are supported, zeros must be considered the equivalent of ``False``, while non-zeros must be considered the equivalent of ``True``. Parameters ---------- x: array - input array. Should have a boolean data type. + input array. Should have a boolean data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type of ``bool``. + an array containing the element-wise results. The returned array must have a data type of ``bool``. """ @@ -5679,26 +5683,26 @@ class logical_or[TArray: Array](Protocol): Computes the logical OR for each element ``x1_i`` of the input array ``x1`` with the respective element ``x2_i`` of the input array ``x2``. .. note:: - While this specification recommends that this function only accept input arrays having a boolean data type, specification-compliant array libraries may choose to accept input arrays having real-valued data types. If non-boolean data types are supported, zeros must be considered the equivalent of ``False``, while non-zeros must be considered the equivalent of ``True``. + While this specification recommends that this function only accept input arrays having a boolean data type, specification-compliant array libraries may choose to accept input arrays having real-valued data types. If non-boolean data types are supported, zeros must be considered the equivalent of ``False``, while non-zeros must be considered the equivalent of ``True``. Parameters ---------- x1: Union[array, bool] - first input array. Should have a boolean data type. + first input array. Should have a boolean data type. x2: Union[array, bool] - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a boolean data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a boolean data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type of ``bool``. + an array containing the element-wise results. The returned array must have a data type of ``bool``. Notes ----- - At least one of ``x1`` or ``x2`` must be an array. .. versionchanged:: 2024.12 - Added scalar argument support. + Added scalar argument support. """ @@ -5712,26 +5716,26 @@ class logical_xor[TArray: Array](Protocol): Computes the logical XOR for each element ``x1_i`` of the input array ``x1`` with the respective element ``x2_i`` of the input array ``x2``. .. note:: - While this specification recommends that this function only accept input arrays having a boolean data type, specification-compliant array libraries may choose to accept input arrays having real-valued data types. If non-boolean data types are supported, zeros must be considered the equivalent of ``False``, while non-zeros must be considered the equivalent of ``True``. + While this specification recommends that this function only accept input arrays having a boolean data type, specification-compliant array libraries may choose to accept input arrays having real-valued data types. If non-boolean data types are supported, zeros must be considered the equivalent of ``False``, while non-zeros must be considered the equivalent of ``True``. Parameters ---------- x1: Union[array, bool] - first input array. Should have a boolean data type. + first input array. Should have a boolean data type. x2: Union[array, bool] - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a boolean data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a boolean data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type of ``bool``. + an array containing the element-wise results. The returned array must have a data type of ``bool``. Notes ----- - At least one of ``x1`` or ``x2`` must be an array. .. versionchanged:: 2024.12 - Added scalar argument support. + Added scalar argument support. """ @@ -5747,14 +5751,14 @@ class maximum[TArray: Array](Protocol): Parameters ---------- x1: Union[array, int, float] - first input array. Should have a real-valued data type. + first input array. Should have a real-valued data type. x2: Union[array, int, float] - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued data type. Returns ------- out: array - an array containing the element-wise maximum values. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise maximum values. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- @@ -5771,7 +5775,7 @@ class maximum[TArray: Array](Protocol): .. versionadded:: 2023.12 .. versionchanged:: 2024.12 - Added scalar argument support. + Added scalar argument support. """ @@ -5787,14 +5791,14 @@ class minimum[TArray: Array](Protocol): Parameters ---------- x1: Union[array, int, float] - first input array. Should have a real-valued data type. + first input array. Should have a real-valued data type. x2: Union[array, int, float] - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued data type. Returns ------- out: array - an array containing the element-wise minimum values. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise minimum values. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- @@ -5811,7 +5815,7 @@ class minimum[TArray: Array](Protocol): .. versionadded:: 2023.12 .. versionchanged:: 2024.12 - Added scalar argument support. + Added scalar argument support. """ @@ -5825,19 +5829,19 @@ class multiply[TArray: Array](Protocol): Calculates the product for each element ``x1_i`` of the input array ``x1`` with the respective element ``x2_i`` of the input array ``x2``. .. note:: - Floating-point multiplication is not always associative due to finite precision. + Floating-point multiplication is not always associative due to finite precision. Parameters ---------- x1: Union[array, int, float, complex] - first input array. Should have a numeric data type. + first input array. Should have a numeric data type. x2: Union[array, int, float, complex] - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a numeric data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a numeric data type. Returns ------- out: array - an array containing the element-wise products. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise products. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- @@ -5874,7 +5878,7 @@ class multiply[TArray: Array](Protocol): When ``a``, ``b``, ``c``, or ``d`` are all finite numbers (i.e., a value other than ``NaN``, ``+infinity``, or ``-infinity``), multiplication of complex floating-point operands should be computed as if calculated according to the textbook formula for complex number multiplication .. math:: - (a + bj) \\cdot (c + dj) = (ac - bd) + (bc + ad)j + (a + bj) \\cdot (c + dj) = (ac - bd) + (bc + ad)j When at least one of ``a``, ``b``, ``c``, or ``d`` is ``NaN``, ``+infinity``, or ``-infinity``, @@ -5882,13 +5886,13 @@ class multiply[TArray: Array](Protocol): - In the remaining cases, the result is implementation dependent. .. note:: - For complex floating-point operands, the results of special cases may be implementation dependent depending on how an implementation chooses to model complex numbers and complex infinity (e.g., complex plane versus Riemann sphere). For those implementations following C99 and its one-infinity model, when at least one component is infinite, even if the other component is ``NaN``, the complex value is infinite, and the usual arithmetic rules do not apply to complex-complex multiplication. In the interest of performance, other implementations may want to avoid the complex branching logic necessary to implement the one-infinity model and choose to implement all complex-complex multiplication according to the textbook formula. Accordingly, special case behavior is unlikely to be consistent across implementations. + For complex floating-point operands, the results of special cases may be implementation dependent depending on how an implementation chooses to model complex numbers and complex infinity (e.g., complex plane versus Riemann sphere). For those implementations following C99 and its one-infinity model, when at least one component is infinite, even if the other component is ``NaN``, the complex value is infinite, and the usual arithmetic rules do not apply to complex-complex multiplication. In the interest of performance, other implementations may want to avoid the complex branching logic necessary to implement the one-infinity model and choose to implement all complex-complex multiplication according to the textbook formula. Accordingly, special case behavior is unlikely to be consistent across implementations. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. .. versionchanged:: 2024.12 - Added scalar argument support. + Added scalar argument support. """ @@ -5902,26 +5906,26 @@ class negative[TArray: Array](Protocol): Computes the numerical negative of each element ``x_i`` (i.e., ``y_i = -x_i``) of the input array ``x``. .. note:: - For signed integer data types, the numerical negative of the minimum representable integer is implementation-dependent. + For signed integer data types, the numerical negative of the minimum representable integer is implementation-dependent. .. note:: - If ``x`` has a complex floating-point data type, both the real and imaginary components for each ``x_i`` must be negated (a result which follows from the rules of complex number multiplication). + If ``x`` has a complex floating-point data type, both the real and imaginary components for each ``x_i`` must be negated (a result which follows from the rules of complex number multiplication). Parameters ---------- x: array - input array. Should have a numeric data type. + input array. Should have a numeric data type. Returns ------- out: array - an array containing the evaluated result for each element in ``x``. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the evaluated result for each element in ``x``. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -5937,14 +5941,14 @@ class nextafter[TArray: Array](Protocol): Parameters ---------- x1: Union[array, int, float] - first input array. Should have a real-valued floating-point data type. + first input array. Should have a real-valued floating-point data type. x2: Union[array, int, float] - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have the same data type as ``x1``. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have the same data type as ``x1``. Returns ------- out: array - an array containing the element-wise results. The returned array must have the same data type as ``x1``. + an array containing the element-wise results. The returned array must have the same data type as ``x1``. Notes ----- @@ -5974,14 +5978,14 @@ class not_equal[TArray: Array](Protocol): Parameters ---------- x1: Union[array, int, float, complex, bool] - first input array. May have any data type. + first input array. May have any data type. x2: Union[array, int, float, complex, bool] - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type of ``bool``. + an array containing the element-wise results. The returned array must have a data type of ``bool``. Notes ----- @@ -6003,19 +6007,19 @@ class not_equal[TArray: Array](Protocol): - In the remaining cases, the result is the logical OR of the equality comparison between the real values ``a`` and ``c`` (real components) and between the real values ``b`` and ``d`` (imaginary components), as described above for real-valued floating-point operands (i.e., ``a != c OR b != d``). .. note:: - For discussion of complex number equality, see :ref:`complex-numbers`. + For discussion of complex number equality, see :ref:`complex-numbers`. .. note:: - Comparison of arrays without a corresponding promotable data type (see :ref:`type-promotion`) is undefined and thus implementation-dependent. + Comparison of arrays without a corresponding promotable data type (see :ref:`type-promotion`) is undefined and thus implementation-dependent. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. .. versionchanged:: 2024.12 - Cross-kind comparisons are explicitly left unspecified. + Cross-kind comparisons are explicitly left unspecified. .. versionchanged:: 2024.12 - Added scalar argument support. + Added scalar argument support. """ @@ -6031,18 +6035,18 @@ class positive[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a numeric data type. + input array. Should have a numeric data type. Returns ------- out: array - an array containing the evaluated result for each element in ``x``. The returned array must have the same data type as ``x``. + an array containing the evaluated result for each element in ``x``. The returned array must have the same data type as ``x``. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -6058,14 +6062,14 @@ class pow[TArray: Array](Protocol): Parameters ---------- x1: Union[array, int, float, complex] - first input array whose elements correspond to the exponentiation base. Should have a numeric data type. + first input array whose elements correspond to the exponentiation base. Should have a numeric data type. x2: Union[array, int, float, complex] - second input array whose elements correspond to the exponentiation exponent. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a numeric data type. + second input array whose elements correspond to the exponentiation exponent. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a numeric data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- @@ -6077,9 +6081,9 @@ class pow[TArray: Array](Protocol): - By convention, the branch cut of the natural logarithm is the negative real axis :math:`(-\\infty, 0)`. - The natural logarithm is a continuous function from above the branch cut, taking into account the sign of the imaginary component. As special cases involving complex floating-point operands should be handled according to ``exp(x2*log(x1))``, exponentiation has the same branch cut for ``x1`` as the natural logarithm (see :func:`~array_api.log`). + The natural logarithm is a continuous function from above the branch cut, taking into account the sign of the imaginary component. As special cases involving complex floating-point operands should be handled according to ``exp(x2*log(x1))``, exponentiation has the same branch cut for ``x1`` as the natural logarithm (see :func:`~array_api.log`). - *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). + *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). **Special cases** @@ -6113,13 +6117,13 @@ class pow[TArray: Array](Protocol): For complex floating-point operands, special cases should be handled as if the operation is implemented as ``exp(x2*log(x1))``. .. note:: - Conforming implementations are allowed to treat special cases involving complex floating-point operands more carefully than as described in this specification. + Conforming implementations are allowed to treat special cases involving complex floating-point operands more carefully than as described in this specification. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. .. versionchanged:: 2024.12 - Added scalar argument support. + Added scalar argument support. """ @@ -6135,12 +6139,12 @@ class real[TArray: Array](Protocol): Parameters ---------- x: array - input array. Must have a numeric data type. + input array. Must have a numeric data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a floating-point data type with the same floating-point precision as ``x`` (e.g., if ``x`` is ``complex64``, the returned array must have the floating-point data type ``float32``). + an array containing the element-wise results. The returned array must have a floating-point data type with the same floating-point precision as ``x`` (e.g., if ``x`` is ``complex64``, the returned array must have the floating-point data type ``float32``). Notes ----- @@ -6149,7 +6153,7 @@ class real[TArray: Array](Protocol): .. versionadded:: 2022.12 .. versionchanged:: 2024.12 - Added support for real-valued arrays. + Added support for real-valued arrays. """ @@ -6165,12 +6169,12 @@ class reciprocal[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a floating-point data type. + input array. Should have a floating-point data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the element-wise results. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -6192,19 +6196,19 @@ class remainder[TArray: Array](Protocol): Returns the remainder of division for each element ``x1_i`` of the input array ``x1`` and the respective element ``x2_i`` of the input array ``x2``. .. note:: - This function is equivalent to the Python modulus operator ``x1_i % x2_i``. + This function is equivalent to the Python modulus operator ``x1_i % x2_i``. Parameters ---------- x1: Union[array, int, float] - dividend input array. Should have a real-valued data type. + dividend input array. Should have a real-valued data type. x2: Union[array, int, float] - divisor input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued data type. + divisor input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued data type. Returns ------- out: array - an array containing the element-wise results. Each element-wise result must have the same sign as the respective element ``x2_i``. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise results. Each element-wise result must have the same sign as the respective element ``x2_i``. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- @@ -6214,7 +6218,7 @@ class remainder[TArray: Array](Protocol): **Special cases** .. note:: - In general, similar to Python's ``%`` operator, this function is **not** recommended for floating-point operands as semantics do not follow IEEE 754. That this function is specified to accept floating-point operands is primarily for reasons of backward compatibility. + In general, similar to Python's ``%`` operator, this function is **not** recommended for floating-point operands as semantics do not follow IEEE 754. That this function is specified to accept floating-point operands is primarily for reasons of backward compatibility. For floating-point operands, @@ -6240,7 +6244,7 @@ class remainder[TArray: Array](Protocol): - In the remaining cases, the result must match that of the Python ``%`` operator. .. versionchanged:: 2024.12 - Added scalar argument support. + Added scalar argument support. """ @@ -6254,26 +6258,26 @@ class round[TArray: Array](Protocol): Rounds each element ``x_i`` of the input array ``x`` to the nearest integer-valued number. .. note:: - For complex floating-point operands, real and imaginary components must be independently rounded to the nearest integer-valued number. + For complex floating-point operands, real and imaginary components must be independently rounded to the nearest integer-valued number. - Rounded real and imaginary components must be equal to their equivalent rounded real-valued floating-point counterparts (i.e., for complex-valued ``x``, ``real(round(x))`` must equal ``round(real(x)))`` and ``imag(round(x))`` must equal ``round(imag(x))``). + Rounded real and imaginary components must be equal to their equivalent rounded real-valued floating-point counterparts (i.e., for complex-valued ``x``, ``real(round(x))`` must equal ``round(real(x)))`` and ``imag(round(x))`` must equal ``round(imag(x))``). Parameters ---------- x: array - input array. Should have a numeric data type. + input array. Should have a numeric data type. Returns ------- out: array - an array containing the rounded result for each element in ``x``. The returned array must have the same data type as ``x``. + an array containing the rounded result for each element in ``x``. The returned array must have the same data type as ``x``. Notes ----- **Special cases** .. note:: - For complex floating-point operands, the following special cases apply to real and imaginary components independently (e.g., if ``real(x_i)`` is ``NaN``, the rounded real component is ``NaN``). + For complex floating-point operands, the following special cases apply to real and imaginary components independently (e.g., if ``real(x_i)`` is ``NaN``, the rounded real component is ``NaN``). - If ``x_i`` is already integer-valued, the result is ``x_i``. @@ -6287,7 +6291,7 @@ class round[TArray: Array](Protocol): - If two integers are equally close to ``x_i``, the result is the even integer closest to ``x_i``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -6303,22 +6307,22 @@ class sign[TArray: Array](Protocol): The sign function (also known as the **signum function**) of a number :math:`x_i` is defined as .. math:: - \\operatorname{sign}(x_i) = \\begin{cases} - 0 & \\textrm{if } x_i = 0 \\\\ - \\frac{x_i}{|x_i|} & \\textrm{otherwise} - \\end{cases} + \\operatorname{sign}(x_i) = \\begin{cases} + 0 & \\textrm{if } x_i = 0 \\\\ + \\frac{x_i}{|x_i|} & \\textrm{otherwise} + \\end{cases} where :math:`|x_i|` is the absolute value of :math:`x_i`. Parameters ---------- x: array - input array. Should have a numeric data type. + input array. Should have a numeric data type. Returns ------- out: array - an array containing the evaluated result for each element in ``x``. The returned array must have the same data type as ``x``. + an array containing the evaluated result for each element in ``x``. The returned array must have the same data type as ``x``. Notes ----- @@ -6338,7 +6342,7 @@ class sign[TArray: Array](Protocol): - In the remaining cases, special cases must be handled according to the rules of complex number division (see :func:`~array_api.divide`). .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -6356,12 +6360,12 @@ class signbit[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a real-valued floating-point data type. + input array. Should have a real-valued floating-point data type. Returns ------- out: array - an array containing the evaluated result for each element in ``x``. The returned array must have a data type of ``bool``. + an array containing the evaluated result for each element in ``x``. The returned array must have a data type of ``bool``. Notes ----- @@ -6394,25 +6398,25 @@ class sin[TArray: Array](Protocol): Each element ``x_i`` is assumed to be expressed in radians. .. note:: - The sine is an entire function on the complex plane and has no branch cuts. + The sine is an entire function on the complex plane and has no branch cuts. .. note:: - For complex arguments, the mathematical definition of sine is + For complex arguments, the mathematical definition of sine is - .. math:: - \\begin{align} \\operatorname{sin}(x) &= \\frac{e^{jx} - e^{-jx}}{2j} \\\\ &= \\frac{\\operatorname{sinh}(jx)}{j} \\\\ &= \\frac{\\operatorname{sinh}(jx)}{j} \\cdot \\frac{j}{j} \\\\ &= -j \\cdot \\operatorname{sinh}(jx) \\end{align} + .. math:: + \\begin{align} \\operatorname{sin}(x) &= \\frac{e^{jx} - e^{-jx}}{2j} \\\\ &= \\frac{\\operatorname{sinh}(jx)}{j} \\\\ &= \\frac{\\operatorname{sinh}(jx)}{j} \\cdot \\frac{j}{j} \\\\ &= -j \\cdot \\operatorname{sinh}(jx) \\end{align} - where :math:`\\operatorname{sinh}` is the hyperbolic sine. + where :math:`\\operatorname{sinh}` is the hyperbolic sine. Parameters ---------- x: array - input array whose elements are each expressed in radians. Should have a floating-point data type. + input array whose elements are each expressed in radians. Should have a floating-point data type. Returns ------- out: array - an array containing the sine of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the sine of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -6428,7 +6432,7 @@ class sin[TArray: Array](Protocol): For complex floating-point operands, special cases must be handled as if the operation is implemented as ``-1j * sinh(x*1j)``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -6444,27 +6448,27 @@ class sinh[TArray: Array](Protocol): The mathematical definition of the hyperbolic sine is .. math:: - \\operatorname{sinh}(x) = \\frac{e^x - e^{-x}}{2} + \\operatorname{sinh}(x) = \\frac{e^x - e^{-x}}{2} .. note:: - The hyperbolic sine is an entire function in the complex plane and has no branch cuts. The function is periodic, with period :math:`2\\pi j`, with respect to the imaginary component. + The hyperbolic sine is an entire function in the complex plane and has no branch cuts. The function is periodic, with period :math:`2\\pi j`, with respect to the imaginary component. Parameters ---------- x: array - input array whose elements each represent a hyperbolic angle. Should have a floating-point data type. + input array whose elements each represent a hyperbolic angle. Should have a floating-point data type. Returns ------- out: array - an array containing the hyperbolic sine of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the hyperbolic sine of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- **Special cases** .. note:: - For all operands, ``sinh(x)`` must equal ``-sinh(-x)``. + For all operands, ``sinh(x)`` must equal ``-sinh(-x)``. For real-valued floating-point operands, @@ -6477,7 +6481,7 @@ class sinh[TArray: Array](Protocol): For complex floating-point operands, let ``a = real(x_i)``, ``b = imag(x_i)``, and .. note:: - For complex floating-point operands, ``sinh(conj(x))`` must equal ``conj(sinh(x))``. + For complex floating-point operands, ``sinh(conj(x))`` must equal ``conj(sinh(x))``. - If ``a`` is ``+0`` and ``b`` is ``+0``, the result is ``+0 + 0j``. - If ``a`` is ``+0`` and ``b`` is ``+infinity``, the result is ``0 + NaN j`` (sign of the real component is unspecified). @@ -6495,7 +6499,7 @@ class sinh[TArray: Array](Protocol): where ``cis(v)`` is ``cos(v) + sin(v)*1j``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -6511,17 +6515,17 @@ class square[TArray: Array](Protocol): The square of a number ``x_i`` is defined as .. math:: - x_i^2 = x_i \\cdot x_i + x_i^2 = x_i \\cdot x_i Parameters ---------- x: array - input array. Should have a numeric data type. + input array. Should have a numeric data type. Returns ------- out: array - an array containing the evaluated result for each element in ``x``. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the evaluated result for each element in ``x``. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- @@ -6530,7 +6534,7 @@ class square[TArray: Array](Protocol): For floating-point operands, special cases must be handled as if the operation is implemented as ``x * x`` (see :func:`~array_api.multiply`). .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -6544,29 +6548,29 @@ class sqrt[TArray: Array](Protocol): Calculates the principal square root for each element ``x_i`` of the input array ``x``. .. note:: - After rounding, each result must be indistinguishable from the infinitely precise result (as required by IEEE 754). + After rounding, each result must be indistinguishable from the infinitely precise result (as required by IEEE 754). .. note:: - For complex floating-point operands, ``sqrt(conj(x))`` must equal ``conj(sqrt(x))``. + For complex floating-point operands, ``sqrt(conj(x))`` must equal ``conj(sqrt(x))``. .. note:: - By convention, the branch cut of the square root is the negative real axis :math:`(-\\infty, 0)`. + By convention, the branch cut of the square root is the negative real axis :math:`(-\\infty, 0)`. - The square root is a continuous function from above the branch cut, taking into account the sign of the imaginary component. + The square root is a continuous function from above the branch cut, taking into account the sign of the imaginary component. - Accordingly, for complex arguments, the function returns the square root in the range of the right half-plane, including the imaginary axis (i.e., the plane defined by :math:`[0, +\\infty)` along the real axis and :math:`(-\\infty, +\\infty)` along the imaginary axis). + Accordingly, for complex arguments, the function returns the square root in the range of the right half-plane, including the imaginary axis (i.e., the plane defined by :math:`[0, +\\infty)` along the real axis and :math:`(-\\infty, +\\infty)` along the imaginary axis). - *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). + *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). Parameters ---------- x: array - input array. Should have a floating-point data type. + input array. Should have a floating-point data type. Returns ------- out: array - an array containing the square root of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the square root of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -6593,7 +6597,7 @@ class sqrt[TArray: Array](Protocol): - If ``a`` is ``NaN`` and ``b`` is ``NaN``, the result is ``NaN + NaN j``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -6609,14 +6613,14 @@ class subtract[TArray: Array](Protocol): Parameters ---------- x1: Union[array, int, float, complex] - first input array. Should have a numeric data type. + first input array. Should have a numeric data type. x2: Union[array, int, float, complex] - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a numeric data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a numeric data type. Returns ------- out: array - an array containing the element-wise differences. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise differences. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- @@ -6624,10 +6628,10 @@ class subtract[TArray: Array](Protocol): - The result of ``x1_i - x2_i`` must be the same as ``x1_i + (-x2_i)`` and must be governed by the same floating-point rules as addition (see :meth:`add`). .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. .. versionchanged:: 2024.12 - Added scalar argument support. + Added scalar argument support. """ @@ -6643,25 +6647,25 @@ class tan[TArray: Array](Protocol): Each element ``x_i`` is assumed to be expressed in radians. .. note:: - Tangent is an analytical function on the complex plane and has no branch cuts. The function is periodic, with period :math:`\\pi j`, with respect to the real component and has first order poles along the real line at coordinates :math:`(\\pi (\\frac{1}{2} + n), 0)`. However, IEEE 754 binary floating-point representation cannot represent the value :math:`\\pi / 2` exactly, and, thus, no argument value is possible for which a pole error occurs. + Tangent is an analytical function on the complex plane and has no branch cuts. The function is periodic, with period :math:`\\pi j`, with respect to the real component and has first order poles along the real line at coordinates :math:`(\\pi (\\frac{1}{2} + n), 0)`. However, IEEE 754 binary floating-point representation cannot represent the value :math:`\\pi / 2` exactly, and, thus, no argument value is possible for which a pole error occurs. .. note:: - For complex arguments, the mathematical definition of tangent is + For complex arguments, the mathematical definition of tangent is - .. math:: - \\begin{align} \\operatorname{tan}(x) &= \\frac{j(e^{-jx} - e^{jx})}{e^{-jx} + e^{jx}} \\\\ &= (-1) \\frac{j(e^{jx} - e^{-jx})}{e^{jx} + e^{-jx}} \\\\ &= -j \\cdot \\operatorname{tanh}(jx) \\end{align} + .. math:: + \\begin{align} \\operatorname{tan}(x) &= \\frac{j(e^{-jx} - e^{jx})}{e^{-jx} + e^{jx}} \\\\ &= (-1) \\frac{j(e^{jx} - e^{-jx})}{e^{jx} + e^{-jx}} \\\\ &= -j \\cdot \\operatorname{tanh}(jx) \\end{align} - where :math:`\\operatorname{tanh}` is the hyperbolic tangent. + where :math:`\\operatorname{tanh}` is the hyperbolic tangent. Parameters ---------- x: array - input array whose elements are expressed in radians. Should have a floating-point data type. + input array whose elements are expressed in radians. Should have a floating-point data type. Returns ------- out: array - an array containing the tangent of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the tangent of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -6677,7 +6681,7 @@ class tan[TArray: Array](Protocol): For complex floating-point operands, special cases must be handled as if the operation is implemented as ``-1j * tanh(x*1j)``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -6693,29 +6697,29 @@ class tanh[TArray: Array](Protocol): The mathematical definition of the hyperbolic tangent is .. math:: - \\begin{align} \\operatorname{tanh}(x) &= \\frac{\\operatorname{sinh}(x)}{\\operatorname{cosh}(x)} \\\\ &= \\frac{e^x - e^{-x}}{e^x + e^{-x}} \\end{align} + \\begin{align} \\operatorname{tanh}(x) &= \\frac{\\operatorname{sinh}(x)}{\\operatorname{cosh}(x)} \\\\ &= \\frac{e^x - e^{-x}}{e^x + e^{-x}} \\end{align} where :math:`\\operatorname{sinh}(x)` is the hyperbolic sine and :math:`\\operatorname{cosh}(x)` is the hyperbolic cosine. .. note:: - The hyperbolic tangent is an analytical function on the complex plane and has no branch cuts. The function is periodic, with period :math:`\\pi j`, with respect to the imaginary component and has first order poles along the imaginary line at coordinates :math:`(0, \\pi (\\frac{1}{2} + n))`. However, IEEE 754 binary floating-point representation cannot represent :math:`\\pi / 2` exactly, and, thus, no argument value is possible such that a pole error occurs. + The hyperbolic tangent is an analytical function on the complex plane and has no branch cuts. The function is periodic, with period :math:`\\pi j`, with respect to the imaginary component and has first order poles along the imaginary line at coordinates :math:`(0, \\pi (\\frac{1}{2} + n))`. However, IEEE 754 binary floating-point representation cannot represent :math:`\\pi / 2` exactly, and, thus, no argument value is possible such that a pole error occurs. Parameters ---------- x: array - input array whose elements each represent a hyperbolic angle. Should have a floating-point data type. + input array whose elements each represent a hyperbolic angle. Should have a floating-point data type. Returns ------- out: array - an array containing the hyperbolic tangent of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the hyperbolic tangent of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- **Special cases** .. note:: - For all operands, ``tanh(-x)`` must equal ``-tanh(x)``. + For all operands, ``tanh(-x)`` must equal ``-tanh(x)``. For real-valued floating-point operands, @@ -6728,7 +6732,7 @@ class tanh[TArray: Array](Protocol): For complex floating-point operands, let ``a = real(x_i)``, ``b = imag(x_i)``, and .. note:: - For complex floating-point operands, ``tanh(conj(x))`` must equal ``conj(tanh(x))``. + For complex floating-point operands, ``tanh(conj(x))`` must equal ``conj(tanh(x))``. - If ``a`` is ``+0`` and ``b`` is ``+0``, the result is ``+0 + 0j``. - If ``a`` is a nonzero finite number and ``b`` is ``+infinity``, the result is ``NaN + NaN j``. @@ -6743,12 +6747,12 @@ class tanh[TArray: Array](Protocol): - If ``a`` is ``NaN`` and ``b`` is ``NaN``, the result is ``NaN + NaN j``. .. warning:: - For historical reasons stemming from the C standard, array libraries may not return the expected result when ``a`` is ``+0`` and ``b`` is either ``+infinity`` or ``NaN``. The result should be ``+0 + NaN j`` in both cases; however, for libraries compiled against older C versions, the result may be ``NaN + NaN j``. + For historical reasons stemming from the C standard, array libraries may not return the expected result when ``a`` is ``+0`` and ``b`` is either ``+infinity`` or ``NaN``. The result should be ``+0 + NaN j`` in both cases; however, for libraries compiled against older C versions, the result may be ``NaN + NaN j``. - Array libraries are not required to patch these older C versions, and, thus, users are advised that results may vary across array library implementations for these special cases. + Array libraries are not required to patch these older C versions, and, thus, users are advised that results may vary across array library implementations for these special cases. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -6764,12 +6768,12 @@ class trunc[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a real-valued data type. + input array. Should have a real-valued data type. Returns ------- out: array - an array containing the rounded result for each element in ``x``. The returned array must have the same data type as ``x``. + an array containing the rounded result for each element in ``x``. The returned array must have the same data type as ``x``. Notes ----- @@ -6799,21 +6803,21 @@ class argmax[TArray: Array](Protocol): When the maximum value occurs multiple times, only the indices corresponding to the first occurrence are returned. .. note:: - For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). + For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). Parameters ---------- x: array - input array. Should have a real-valued data type. + input array. Should have a real-valued data type. axis: Optional[int] - axis along which to search. If ``None``, the function must return the index of the maximum value of the flattened array. Default: ``None``. + axis along which to search. If ``None``, the function must return the index of the maximum value of the flattened array. Default: ``None``. keepdims: bool - if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. + if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. Returns ------- out: array - if ``axis`` is ``None``, a zero-dimensional array containing the index of the first occurrence of the maximum value; otherwise, a non-zero-dimensional array containing the indices of the maximum values. The returned array must have be the default array index data type. + if ``axis`` is ``None``, a zero-dimensional array containing the index of the first occurrence of the maximum value; otherwise, a non-zero-dimensional array containing the indices of the maximum values. The returned array must have be the default array index data type. """ @@ -6829,21 +6833,21 @@ class argmin[TArray: Array](Protocol): When the minimum value occurs multiple times, only the indices corresponding to the first occurrence are returned. .. note:: - For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). + For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). Parameters ---------- x: array - input array. Should have a real-valued data type. + input array. Should have a real-valued data type. axis: Optional[int] - axis along which to search. If ``None``, the function must return the index of the minimum value of the flattened array. Default: ``None``. + axis along which to search. If ``None``, the function must return the index of the minimum value of the flattened array. Default: ``None``. keepdims: bool - if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. + if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. Returns ------- out: array - if ``axis`` is ``None``, a zero-dimensional array containing the index of the first occurrence of the minimum value; otherwise, a non-zero-dimensional array containing the indices of the minimum values. The returned array must have the default array index data type. + if ``axis`` is ``None``, a zero-dimensional array containing the index of the first occurrence of the minimum value; otherwise, a non-zero-dimensional array containing the indices of the minimum values. The returned array must have the default array index data type. """ @@ -6859,16 +6863,16 @@ class count_nonzero[TArray: Array](Protocol): Parameters ---------- x: array - input array. + input array. axis: Optional[Union[int, Tuple[int, ...]]] - axis or axes along which to count non-zero values. By default, the number of non-zero values must be computed over the entire array. If a tuple of integers, the number of non-zero values must be computed over multiple axes. Default: ``None``. + axis or axes along which to count non-zero values. By default, the number of non-zero values must be computed over the entire array. If a tuple of integers, the number of non-zero values must be computed over multiple axes. Default: ``None``. keepdims: bool - if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. + if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. Returns ------- out: array - if the number of non-zeros values was computed over the entire array, a zero-dimensional array containing the total number of non-zero values; otherwise, a non-zero-dimensional array containing the counts along the specified axes. The returned array must have the default array index data type. + if the number of non-zeros values was computed over the entire array, a zero-dimensional array containing the total number of non-zero values; otherwise, a non-zero-dimensional array containing the counts along the specified axes. The returned array must have the default array index data type. Notes ----- @@ -6889,19 +6893,19 @@ class nonzero[TArray: Array](Protocol): Returns the indices of the array elements which are non-zero. .. admonition:: Data-dependent output shape - :class: admonition important + :class: admonition important - The shape of the output array for this function depends on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) may find this function difficult to implement without knowing array values. Accordingly, such libraries may choose to omit this function. See :ref:`data-dependent-output-shapes` section for more details. + The shape of the output array for this function depends on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) may find this function difficult to implement without knowing array values. Accordingly, such libraries may choose to omit this function. See :ref:`data-dependent-output-shapes` section for more details. Parameters ---------- x: array - input array. Must have a positive rank. If ``x`` is zero-dimensional, the function must raise an exception. + input array. Must have a positive rank. If ``x`` is zero-dimensional, the function must raise an exception. Returns ------- out: Tuple[array, ...] - a tuple of ``k`` arrays, one for each dimension of ``x`` and each of size ``n`` (where ``n`` is the total number of non-zero elements), containing the indices of the non-zero elements in that dimension. The indices must be returned in row-major, C-style order. The returned array must have the default array index data type. + a tuple of ``k`` arrays, one for each dimension of ``x`` and each of size ``n`` (where ``n`` is the total number of non-zero elements), containing the indices of the non-zero elements in that dimension. The indices must be returned in row-major, C-style order. The returned array must have the default array index data type. Notes ----- @@ -6909,7 +6913,7 @@ class nonzero[TArray: Array](Protocol): - If ``x`` has a boolean data type, non-zero elements are those elements which are equal to ``True``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -6925,29 +6929,29 @@ class searchsorted[TArray: Array](Protocol): Parameters ---------- x1: array - input array. Must be a one-dimensional array. Should have a real-valued data type. If ``sorter`` is ``None``, must be sorted in ascending order; otherwise, ``sorter`` must be an array of indices that sort ``x1`` in ascending order. + input array. Must be a one-dimensional array. Should have a real-valued data type. If ``sorter`` is ``None``, must be sorted in ascending order; otherwise, ``sorter`` must be an array of indices that sort ``x1`` in ascending order. x2: array - array containing search values. Should have a real-valued data type. + array containing search values. Should have a real-valued data type. side: Literal['left', 'right'] - argument controlling which index is returned if a value lands exactly on an edge. + argument controlling which index is returned if a value lands exactly on an edge. - Let ``v`` be an element of ``x2`` given by ``v = x2[j]``, where ``j`` refers to a valid index (see :ref:`indexing`). + Let ``v`` be an element of ``x2`` given by ``v = x2[j]``, where ``j`` refers to a valid index (see :ref:`indexing`). - - If ``v`` is less than all elements in ``x1``, then ``out[j]`` must be ``0``. - - If ``v`` is greater than all elements in ``x1``, then ``out[j]`` must be ``M``, where ``M`` is the number of elements in ``x1``. - - Otherwise, each returned index ``i = out[j]`` must satisfy an index condition: + - If ``v`` is less than all elements in ``x1``, then ``out[j]`` must be ``0``. + - If ``v`` is greater than all elements in ``x1``, then ``out[j]`` must be ``M``, where ``M`` is the number of elements in ``x1``. + - Otherwise, each returned index ``i = out[j]`` must satisfy an index condition: - - If ``side == 'left'``, then ``x1[i-1] < v <= x1[i]``. - - If ``side == 'right'``, then ``x1[i-1] <= v < x1[i]``. + - If ``side == 'left'``, then ``x1[i-1] < v <= x1[i]``. + - If ``side == 'right'``, then ``x1[i-1] <= v < x1[i]``. - Default: ``'left'``. + Default: ``'left'``. sorter: Optional[array] - array of indices that sort ``x1`` in ascending order. The array must have the same shape as ``x1`` and have an integer data type. Default: ``None``. + array of indices that sort ``x1`` in ascending order. The array must have the same shape as ``x1`` and have an integer data type. Default: ``None``. Returns ------- out: array - an array of indices with the same shape as ``x2``. The returned array must have the default array index data type. + an array of indices with the same shape as ``x2``. The returned array must have the default array index data type. Notes ----- @@ -6958,7 +6962,7 @@ class searchsorted[TArray: Array](Protocol): .. versionadded:: 2023.12 .. versionchanged:: 2024.12 - Fixed incorrect boundary conditions. + Fixed incorrect boundary conditions. """ @@ -6974,16 +6978,16 @@ class where[TArray: Array](Protocol): Parameters ---------- condition: array - when ``True``, yield ``x1_i``; otherwise, yield ``x2_i``. Should have a boolean data type. Must be compatible with ``x1`` and ``x2`` (see :ref:`broadcasting`). + when ``True``, yield ``x1_i``; otherwise, yield ``x2_i``. Should have a boolean data type. Must be compatible with ``x1`` and ``x2`` (see :ref:`broadcasting`). x1: Union[array, int, float, complex, bool] - first input array. Must be compatible with ``condition`` and ``x2`` (see :ref:`broadcasting`). + first input array. Must be compatible with ``condition`` and ``x2`` (see :ref:`broadcasting`). x2: Union[array, int, float, complex, bool] - second input array. Must be compatible with ``condition`` and ``x1`` (see :ref:`broadcasting`). + second input array. Must be compatible with ``condition`` and ``x1`` (see :ref:`broadcasting`). Returns ------- out: array - an array with elements from ``x1`` where ``condition`` is ``True``, and elements from ``x2`` elsewhere. The returned array must have a data type determined by :ref:`type-promotion` rules with the arrays ``x1`` and ``x2``. + an array with elements from ``x1`` where ``condition`` is ``True``, and elements from ``x2`` elsewhere. The returned array must have a data type determined by :ref:`type-promotion` rules with the arrays ``x1`` and ``x2``. Notes ----- @@ -6991,10 +6995,10 @@ class where[TArray: Array](Protocol): - If either ``x1`` or ``x2`` is a scalar value, the returned array must have a data type determined according to :ref:`mixing-scalars-and-arrays`. .. versionchanged:: 2024.12 - Added scalar argument support. + Added scalar argument support. .. versionchanged:: 2024.12 - Clarified that the ``condition`` argument should have a boolean data type. + Clarified that the ``condition`` argument should have a boolean data type. """ @@ -7008,33 +7012,33 @@ class all[TArray: Array](Protocol): Tests whether all input array elements evaluate to ``True`` along a specified axis. .. note:: - Positive infinity, negative infinity, and NaN must evaluate to ``True``. + Positive infinity, negative infinity, and NaN must evaluate to ``True``. .. note:: - If ``x`` has a complex floating-point data type, elements having a non-zero component (real or imaginary) must evaluate to ``True``. + If ``x`` has a complex floating-point data type, elements having a non-zero component (real or imaginary) must evaluate to ``True``. .. note:: - If ``x`` is an empty array or the size of the axis (dimension) along which to evaluate elements is zero, the test result must be ``True``. + If ``x`` is an empty array or the size of the axis (dimension) along which to evaluate elements is zero, the test result must be ``True``. Parameters ---------- x: array - input array. + input array. axis: Optional[Union[int, Tuple[int, ...]]] - axis or axes along which to perform a logical AND reduction. By default, a logical AND reduction must be performed over the entire array. If a tuple of integers, logical AND reductions must be performed over multiple axes. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to perform a reduction by counting backward from the last dimension (where ``-1`` refers to the last dimension). If provided an invalid ``axis``, the function must raise an exception. Default: ``None``. + axis or axes along which to perform a logical AND reduction. By default, a logical AND reduction must be performed over the entire array. If a tuple of integers, logical AND reductions must be performed over multiple axes. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to perform a reduction by counting backward from the last dimension (where ``-1`` refers to the last dimension). If provided an invalid ``axis``, the function must raise an exception. Default: ``None``. keepdims: bool - If ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. + If ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. Returns ------- out: array - if a logical AND reduction was performed over the entire array, the returned array must be a zero-dimensional array containing the test result; otherwise, the returned array must be a non-zero-dimensional array containing the test results. The returned array must have a data type of ``bool``. + if a logical AND reduction was performed over the entire array, the returned array must be a zero-dimensional array containing the test result; otherwise, the returned array must be a non-zero-dimensional array containing the test results. The returned array must have a data type of ``bool``. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -7048,33 +7052,33 @@ class any[TArray: Array](Protocol): Tests whether any input array element evaluates to ``True`` along a specified axis. .. note:: - Positive infinity, negative infinity, and NaN must evaluate to ``True``. + Positive infinity, negative infinity, and NaN must evaluate to ``True``. .. note:: - If ``x`` has a complex floating-point data type, elements having a non-zero component (real or imaginary) must evaluate to ``True``. + If ``x`` has a complex floating-point data type, elements having a non-zero component (real or imaginary) must evaluate to ``True``. .. note:: - If ``x`` is an empty array or the size of the axis (dimension) along which to evaluate elements is zero, the test result must be ``False``. + If ``x`` is an empty array or the size of the axis (dimension) along which to evaluate elements is zero, the test result must be ``False``. Parameters ---------- x: array - input array. + input array. axis: Optional[Union[int, Tuple[int, ...]]] - axis or axes along which to perform a logical OR reduction. By default, a logical OR reduction must be performed over the entire array. If a tuple of integers, logical OR reductions must be performed over multiple axes. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to perform a reduction by counting backward from the last dimension (where ``-1`` refers to the last dimension). If provided an invalid ``axis``, the function must raise an exception. Default: ``None``. + axis or axes along which to perform a logical OR reduction. By default, a logical OR reduction must be performed over the entire array. If a tuple of integers, logical OR reductions must be performed over multiple axes. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to perform a reduction by counting backward from the last dimension (where ``-1`` refers to the last dimension). If provided an invalid ``axis``, the function must raise an exception. Default: ``None``. keepdims: bool - If ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. + If ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. Returns ------- out: array - if a logical OR reduction was performed over the entire array, the returned array must be a zero-dimensional array containing the test result; otherwise, the returned array must be a non-zero-dimensional array containing the test results. The returned array must have a data type of ``bool``. + if a logical OR reduction was performed over the entire array, the returned array must be a zero-dimensional array containing the test result; otherwise, the returned array must be a non-zero-dimensional array containing the test results. The returned array must have a data type of ``bool``. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -7090,25 +7094,25 @@ class diff[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a numeric data type. + input array. Should have a numeric data type. axis: int - axis along which to compute differences. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to compute differences by counting backward from the last dimension (where ``-1`` refers to the last dimension). If provided an invalid ``axis``, the function must raise an exception. Default: ``-1``. + axis along which to compute differences. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to compute differences by counting backward from the last dimension (where ``-1`` refers to the last dimension). If provided an invalid ``axis``, the function must raise an exception. Default: ``-1``. n: int - number of times to recursively compute differences. Default: ``1``. + number of times to recursively compute differences. Default: ``1``. prepend: Optional[array] - values to prepend to a specified axis prior to computing differences. Must have the same shape as ``x``, except for the axis specified by ``axis`` which may have any size. Should have the same data type as ``x``. Default: ``None``. + values to prepend to a specified axis prior to computing differences. Must have the same shape as ``x``, except for the axis specified by ``axis`` which may have any size. Should have the same data type as ``x``. Default: ``None``. append: Optional[array] - values to append to a specified axis prior to computing differences. Must have the same shape as ``x``, except for the axis specified by ``axis`` which may have any size. Should have the same data type as ``x``. Default: ``None``. + values to append to a specified axis prior to computing differences. Must have the same shape as ``x``, except for the axis specified by ``axis`` which may have any size. Should have the same data type as ``x``. Default: ``None``. Returns ------- out: array - an array containing the n-th differences. Should have the same data type as ``x``. Must have the same shape as ``x``, except for the axis specified by ``axis`` which must have a size determined as follows: + an array containing the n-th differences. Should have the same data type as ``x``. Must have the same shape as ``x``, except for the axis specified by ``axis`` which must have a size determined as follows: - - Let ``M`` be the number of elements along an axis specified by ``axis``. - - Let ``N1`` be the number of prepended values along an axis specified by ``axis``. - - Let ``N2`` be the number of appended values along an axis specified by ``axis``. - - The final size of the axis specified by ``axis`` must be ``M + N1 + N2 - n``. + - Let ``M`` be the number of elements along an axis specified by ``axis``. + - Let ``N1`` be the number of prepended values along an axis specified by ``axis``. + - Let ``N2`` be the number of appended values along an axis specified by ``axis``. + - The final size of the axis specified by ``axis`` must be ``M + N1 + N2 - n``. Notes ----- @@ -7124,7 +7128,7 @@ def __call__(self, x: TArray, /, *, axis: int = -1, n: int = 1, prepend: TArray @runtime_checkable -class __array_namespace_info__[TCapabilities, TDatatypes, TDefaultdatatypes, TArray: Array, TDevice, TDtype](Protocol): +class __array_namespace_info__[TArray: Array, TCapabilities, TDatatypes, TDefaultdatatypes, TDevice, TDtype](Protocol): """ Returns a namespace with Array API namespace inspection utilities. @@ -7133,7 +7137,7 @@ class __array_namespace_info__[TCapabilities, TDatatypes, TDefaultdatatypes, TAr Returns ------- out: Info - An object containing Array API namespace inspection utilities. + An object containing Array API namespace inspection utilities. Notes ----- @@ -7141,19 +7145,19 @@ class __array_namespace_info__[TCapabilities, TDatatypes, TDefaultdatatypes, TAr :: - info = xp.__array_namespace_info__() - info.capabilities() - info.devices() - info.dtypes() - info.default_dtypes() - # ... + info = xp.__array_namespace_info__() + info.capabilities() + info.devices() + info.dtypes() + info.default_dtypes() + # ... .. versionadded: 2023.12 """ @abstractmethod - def __call__(self, /) -> Info[TCapabilities, TDatatypes, TDefaultdatatypes, TArray, TDevice, TDtype]: ... + def __call__(self, /) -> Info[TArray, TCapabilities, TDatatypes, TDefaultdatatypes, TDevice, TDtype]: ... @runtime_checkable @@ -7164,18 +7168,18 @@ class take[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have one or more dimensions (axes). + input array. Should have one or more dimensions (axes). indices: array - array indices. The array must be one-dimensional and have an integer data type. If an index is negative, the function must determine the element to select along a specified axis (dimension) by counting from the last element (where ``-1`` refers to the last element). + array indices. The array must be one-dimensional and have an integer data type. If an index is negative, the function must determine the element to select along a specified axis (dimension) by counting from the last element (where ``-1`` refers to the last element). axis: Optional[int] - axis over which to select values. If ``axis`` is negative, the function must determine the axis along which to select values by counting from the last dimension (where ``-1`` refers to the last dimension). + axis over which to select values. If ``axis`` is negative, the function must determine the axis along which to select values by counting from the last dimension (where ``-1`` refers to the last dimension). - If ``x`` is a one-dimensional array, providing an ``axis`` is optional; however, if ``x`` has more than one dimension, providing an ``axis`` is required. + If ``x`` is a one-dimensional array, providing an ``axis`` is optional; however, if ``x`` has more than one dimension, providing an ``axis`` is required. Returns ------- out: array - an array having the same data type as ``x``. The output array must have the same rank (i.e., number of dimensions) as ``x`` and must have the same shape as ``x``, except for the axis specified by ``axis`` whose size must equal the number of elements in ``indices``. + an array having the same data type as ``x``. The output array must have the same rank (i.e., number of dimensions) as ``x`` and must have the same shape as ``x``, except for the axis specified by ``axis`` whose size must equal the number of elements in ``indices``. Notes ----- @@ -7186,13 +7190,13 @@ class take[TArray: Array](Protocol): .. versionadded:: 2022.12 .. versionchanged:: 2023.12 - Out-of-bounds behavior is explicitly left unspecified. + Out-of-bounds behavior is explicitly left unspecified. .. versionchanged:: 2024.12 - Behavior when provided a zero-dimensional input array is explicitly left unspecified. + Behavior when provided a zero-dimensional input array is explicitly left unspecified. .. versionchanged:: 2024.12 - Clarified support for negative indices. + Clarified support for negative indices. """ @@ -7208,16 +7212,16 @@ class take_along_axis[TArray: Array](Protocol): Parameters ---------- x: array - input array. Must be compatible with ``indices``, except for the axis (dimension) specified by ``axis`` (see :ref:`broadcasting`). + input array. Must be compatible with ``indices``, except for the axis (dimension) specified by ``axis`` (see :ref:`broadcasting`). indices: array - array indices. Must have the same rank (i.e., number of dimensions) as ``x``. If an index is negative, the function must determine the element to select along a specified axis (dimension) by counting from the last element (where ``-1`` refers to the last element). + array indices. Must have the same rank (i.e., number of dimensions) as ``x``. If an index is negative, the function must determine the element to select along a specified axis (dimension) by counting from the last element (where ``-1`` refers to the last element). axis: int - axis along which to select values. If ``axis`` is negative, the function must determine the axis along which to select values by counting from the last dimension (where ``-1`` refers to the last dimension). Default: ``-1``. + axis along which to select values. If ``axis`` is negative, the function must determine the axis along which to select values by counting from the last dimension (where ``-1`` refers to the last dimension). Default: ``-1``. Returns ------- out: array - an array having the same data type as ``x``. Must have the same rank (i.e., number of dimensions) as ``x`` and must have a shape determined according to :ref:`broadcasting`, except for the axis (dimension) specified by ``axis`` whose size must equal the size of the corresponding axis (dimension) in ``indices``. + an array having the same data type as ``x``. Must have the same rank (i.e., number of dimensions) as ``x`` and must have a shape determined according to :ref:`broadcasting`, except for the axis (dimension) specified by ``axis`` whose size must equal the size of the corresponding axis (dimension) in ``indices``. Notes ----- @@ -7237,35 +7241,35 @@ class fft[TArray: Array](Protocol): Computes the one-dimensional discrete Fourier transform. .. note:: - Applying the one-dimensional inverse discrete Fourier transform to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e., ``ifft(fft(x)) == x``), provided that the transform and inverse transform are performed with the same arguments (number of elements, axis, and normalization mode). + Applying the one-dimensional inverse discrete Fourier transform to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e., ``ifft(fft(x)) == x``), provided that the transform and inverse transform are performed with the same arguments (number of elements, axis, and normalization mode). Parameters ---------- x: array - input array. Should have a complex floating-point data type. + input array. Should have a complex floating-point data type. n: Optional[int] - number of elements over which to compute the transform along the axis (dimension) specified by ``axis``. Let ``M`` be the size of the input array along the axis specified by ``axis``. When ``n`` is ``None``, the function must set ``n`` equal to ``M``. + number of elements over which to compute the transform along the axis (dimension) specified by ``axis``. Let ``M`` be the size of the input array along the axis specified by ``axis``. When ``n`` is ``None``, the function must set ``n`` equal to ``M``. - - If ``n`` is greater than ``M``, the axis specified by ``axis`` must be zero-padded to size ``n``. - - If ``n`` is less than ``M``, the axis specified by ``axis`` must be trimmed to size ``n``. - - If ``n`` equals ``M``, all elements along the axis specified by ``axis`` must be used when computing the transform. + - If ``n`` is greater than ``M``, the axis specified by ``axis`` must be zero-padded to size ``n``. + - If ``n`` is less than ``M``, the axis specified by ``axis`` must be trimmed to size ``n``. + - If ``n`` equals ``M``, all elements along the axis specified by ``axis`` must be used when computing the transform. - Default: ``None``. + Default: ``None``. axis: int - axis (dimension) of the input array over which to compute the transform. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). Default: ``-1``. + axis (dimension) of the input array over which to compute the transform. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). Default: ``-1``. norm: Literal['backward', 'ortho', 'forward'] - normalization mode. Should be one of the following modes: + normalization mode. Should be one of the following modes: - - ``'backward'``: no normalization. - - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). - - ``'forward'``: normalize by ``1/n``. + - ``'backward'``: no normalization. + - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). + - ``'forward'``: normalize by ``1/n``. - Default: ``'backward'``. + Default: ``'backward'``. Returns ------- out: array - an array transformed along the axis (dimension) specified by ``axis``. The returned array must have the same data type as ``x`` and must have the same shape as ``x``, except for the axis specified by ``axis`` which must have size ``n``. + an array transformed along the axis (dimension) specified by ``axis``. The returned array must have the same data type as ``x`` and must have the same shape as ``x``, except for the axis specified by ``axis`` which must have size ``n``. Notes ----- @@ -7273,7 +7277,7 @@ class fft[TArray: Array](Protocol): .. versionadded:: 2022.12 .. versionchanged:: 2023.12 - Required the input array have a complex floating-point data type and required that the output array have the same data type as the input array. + Required the input array have a complex floating-point data type and required that the output array have the same data type as the input array. """ @@ -7287,35 +7291,35 @@ class ifft[TArray: Array](Protocol): Computes the one-dimensional inverse discrete Fourier transform. .. note:: - Applying the one-dimensional inverse discrete Fourier transform to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e., ``ifft(fft(x)) == x``), provided that the transform and inverse transform are performed with the same arguments (number of elements, axis, and normalization mode). + Applying the one-dimensional inverse discrete Fourier transform to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e., ``ifft(fft(x)) == x``), provided that the transform and inverse transform are performed with the same arguments (number of elements, axis, and normalization mode). Parameters ---------- x: array - input array. Should have a complex floating-point data type. + input array. Should have a complex floating-point data type. n: Optional[int] - number of elements over which to compute the transform along the axis (dimension) specified by ``axis``. Let ``M`` be the size of the input array along the axis specified by ``axis``. When ``n`` is ``None``, the function must set ``n`` equal to ``M``. + number of elements over which to compute the transform along the axis (dimension) specified by ``axis``. Let ``M`` be the size of the input array along the axis specified by ``axis``. When ``n`` is ``None``, the function must set ``n`` equal to ``M``. - - If ``n`` is greater than ``M``, the axis specified by ``axis`` must be zero-padded to size ``n``. - - If ``n`` is less than ``M``, the axis specified by ``axis`` must be trimmed to size ``n``. - - If ``n`` equals ``M``, all elements along the axis specified by ``axis`` must be used when computing the transform. + - If ``n`` is greater than ``M``, the axis specified by ``axis`` must be zero-padded to size ``n``. + - If ``n`` is less than ``M``, the axis specified by ``axis`` must be trimmed to size ``n``. + - If ``n`` equals ``M``, all elements along the axis specified by ``axis`` must be used when computing the transform. - Default: ``None``. + Default: ``None``. axis: int - axis (dimension) of the input array over which to compute the transform. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). Default: ``-1``. + axis (dimension) of the input array over which to compute the transform. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). Default: ``-1``. norm: Literal['backward', 'ortho', 'forward'] - normalization mode. Should be one of the following modes: + normalization mode. Should be one of the following modes: - - ``'backward'``: normalize by ``1/n``. - - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). - - ``'forward'``: no normalization. + - ``'backward'``: normalize by ``1/n``. + - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). + - ``'forward'``: no normalization. - Default: ``'backward'``. + Default: ``'backward'``. Returns ------- out: array - an array transformed along the axis (dimension) specified by ``axis``. The returned array must have the same data type as ``x`` and must have the same shape as ``x``, except for the axis specified by ``axis`` which must have size ``n``. + an array transformed along the axis (dimension) specified by ``axis``. The returned array must have the same data type as ``x`` and must have the same shape as ``x``, except for the axis specified by ``axis`` which must have size ``n``. Notes ----- @@ -7323,7 +7327,7 @@ class ifft[TArray: Array](Protocol): .. versionadded:: 2022.12 .. versionchanged:: 2023.12 - Required the input array have a complex floating-point data type and required that the output array have the same data type as the input array. + Required the input array have a complex floating-point data type and required that the output array have the same data type as the input array. """ @@ -7337,41 +7341,41 @@ class fftn[TArray: Array](Protocol): Computes the n-dimensional discrete Fourier transform. .. note:: - Applying the n-dimensional inverse discrete Fourier transform to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e., ``ifftn(fftn(x)) == x``), provided that the transform and inverse transform are performed with the same arguments (sizes, axes, and normalization mode). + Applying the n-dimensional inverse discrete Fourier transform to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e., ``ifftn(fftn(x)) == x``), provided that the transform and inverse transform are performed with the same arguments (sizes, axes, and normalization mode). Parameters ---------- x: array - input array. Should have a complex floating-point data type. + input array. Should have a complex floating-point data type. s: Optional[Sequence[int]] - number of elements over which to compute the transform along the axes (dimensions) specified by ``axes``. Let ``i`` be the index of the ``n``-th axis specified by ``axes`` (i.e., ``i = axes[n]``) and ``M[i]`` be the size of the input array along axis ``i``. When ``s`` is ``None``, the function must set ``s`` equal to a sequence of integers such that ``s[i]`` equals ``M[i]`` for all ``i``. + number of elements over which to compute the transform along the axes (dimensions) specified by ``axes``. Let ``i`` be the index of the ``n``-th axis specified by ``axes`` (i.e., ``i = axes[n]``) and ``M[i]`` be the size of the input array along axis ``i``. When ``s`` is ``None``, the function must set ``s`` equal to a sequence of integers such that ``s[i]`` equals ``M[i]`` for all ``i``. - - If ``s[i]`` is greater than ``M[i]``, axis ``i`` must be zero-padded to size ``s[i]``. - - If ``s[i]`` is less than ``M[i]``, axis ``i`` must be trimmed to size ``s[i]``. - - If ``s[i]`` equals ``M[i]`` or ``-1``, all elements along axis ``i`` must be used when computing the transform. + - If ``s[i]`` is greater than ``M[i]``, axis ``i`` must be zero-padded to size ``s[i]``. + - If ``s[i]`` is less than ``M[i]``, axis ``i`` must be trimmed to size ``s[i]``. + - If ``s[i]`` equals ``M[i]`` or ``-1``, all elements along axis ``i`` must be used when computing the transform. - If ``s`` is not ``None``, ``axes`` must not be ``None``. Default: ``None``. + If ``s`` is not ``None``, ``axes`` must not be ``None``. Default: ``None``. axes: Optional[Sequence[int]] - axes (dimensions) over which to compute the transform. A valid axis in ``axes`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an axis is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). + axes (dimensions) over which to compute the transform. A valid axis in ``axes`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an axis is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). - If ``s`` is provided, the corresponding ``axes`` to be transformed must also be provided. If ``axes`` is ``None``, the function must compute the transform over all axes. Default: ``None``. + If ``s`` is provided, the corresponding ``axes`` to be transformed must also be provided. If ``axes`` is ``None``, the function must compute the transform over all axes. Default: ``None``. - If ``axes`` contains two or more entries which resolve to the same axis (i.e., resolved axes are not unique), the behavior is unspecified and thus implementation-defined. + If ``axes`` contains two or more entries which resolve to the same axis (i.e., resolved axes are not unique), the behavior is unspecified and thus implementation-defined. norm: Literal['backward', 'ortho', 'forward'] - normalization mode. Should be one of the following modes: + normalization mode. Should be one of the following modes: - - ``'backward'``: no normalization. - - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). - - ``'forward'``: normalize by ``1/n``. + - ``'backward'``: no normalization. + - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). + - ``'forward'``: normalize by ``1/n``. - where ``n = prod(s)`` is the logical FFT size. + where ``n = prod(s)`` is the logical FFT size. - Default: ``'backward'``. + Default: ``'backward'``. Returns ------- out: array - an array transformed along the axes (dimensions) specified by ``axes``. The returned array must have the same data type as ``x`` and must have the same shape as ``x``, except for the axes specified by ``axes`` which must have size ``s[i]``. + an array transformed along the axes (dimensions) specified by ``axes``. The returned array must have the same data type as ``x`` and must have the same shape as ``x``, except for the axes specified by ``axes`` which must have size ``s[i]``. Notes ----- @@ -7379,7 +7383,7 @@ class fftn[TArray: Array](Protocol): .. versionadded:: 2022.12 .. versionchanged:: 2023.12 - Required the input array have a complex floating-point data type and required that the output array have the same data type as the input array. + Required the input array have a complex floating-point data type and required that the output array have the same data type as the input array. """ @@ -7393,41 +7397,41 @@ class ifftn[TArray: Array](Protocol): Computes the n-dimensional inverse discrete Fourier transform. .. note:: - Applying the n-dimensional inverse discrete Fourier transform to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e., ``ifftn(fftn(x)) == x``), provided that the transform and inverse transform are performed with the same arguments (sizes, axes, and normalization mode). + Applying the n-dimensional inverse discrete Fourier transform to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e., ``ifftn(fftn(x)) == x``), provided that the transform and inverse transform are performed with the same arguments (sizes, axes, and normalization mode). Parameters ---------- x: array - input array. Should have a complex floating-point data type. + input array. Should have a complex floating-point data type. s: Optional[Sequence[int]] - number of elements over which to compute the transform along the axes (dimensions) specified by ``axes``. Let ``i`` be the index of the ``n``-th axis specified by ``axes`` (i.e., ``i = axes[n]``) and ``M[i]`` be the size of the input array along axis ``i``. When ``s`` is ``None``, the function must set ``s`` equal to a sequence of integers such that ``s[i]`` equals ``M[i]`` for all ``i``. + number of elements over which to compute the transform along the axes (dimensions) specified by ``axes``. Let ``i`` be the index of the ``n``-th axis specified by ``axes`` (i.e., ``i = axes[n]``) and ``M[i]`` be the size of the input array along axis ``i``. When ``s`` is ``None``, the function must set ``s`` equal to a sequence of integers such that ``s[i]`` equals ``M[i]`` for all ``i``. - - If ``s[i]`` is greater than ``M[i]``, axis ``i`` must be zero-padded to size ``s[i]``. - - If ``s[i]`` is less than ``M[i]``, axis ``i`` must be trimmed to size ``s[i]``. - - If ``s[i]`` equals ``M[i]`` or ``-1``, all elements along axis ``i`` must be used when computing the transform. + - If ``s[i]`` is greater than ``M[i]``, axis ``i`` must be zero-padded to size ``s[i]``. + - If ``s[i]`` is less than ``M[i]``, axis ``i`` must be trimmed to size ``s[i]``. + - If ``s[i]`` equals ``M[i]`` or ``-1``, all elements along axis ``i`` must be used when computing the transform. - If ``s`` is not ``None``, ``axes`` must not be ``None``. Default: ``None``. + If ``s`` is not ``None``, ``axes`` must not be ``None``. Default: ``None``. axes: Optional[Sequence[int]] - axes (dimensions) over which to compute the transform. A valid axis in ``axes`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an axis is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). + axes (dimensions) over which to compute the transform. A valid axis in ``axes`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an axis is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). - If ``s`` is provided, the corresponding ``axes`` to be transformed must also be provided. If ``axes`` is ``None``, the function must compute the transform over all axes. Default: ``None``. + If ``s`` is provided, the corresponding ``axes`` to be transformed must also be provided. If ``axes`` is ``None``, the function must compute the transform over all axes. Default: ``None``. - If ``axes`` contains two or more entries which resolve to the same axis (i.e., resolved axes are not unique), the behavior is unspecified and thus implementation-defined. + If ``axes`` contains two or more entries which resolve to the same axis (i.e., resolved axes are not unique), the behavior is unspecified and thus implementation-defined. norm: Literal['backward', 'ortho', 'forward'] - specify the normalization mode. Should be one of the following modes: + specify the normalization mode. Should be one of the following modes: - - ``'backward'``: normalize by ``1/n``. - - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). - - ``'forward'``: no normalization. + - ``'backward'``: normalize by ``1/n``. + - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). + - ``'forward'``: no normalization. - where ``n = prod(s)`` is the logical FFT size. + where ``n = prod(s)`` is the logical FFT size. - Default: ``'backward'``. + Default: ``'backward'``. Returns ------- out: array - an array transformed along the axes (dimensions) specified by ``axes``. The returned array must have the same data type as ``x`` and must have the same shape as ``x``, except for the axes specified by ``axes`` which must have size ``s[i]``. + an array transformed along the axes (dimensions) specified by ``axes``. The returned array must have the same data type as ``x`` and must have the same shape as ``x``, except for the axes specified by ``axes`` which must have size ``s[i]``. Notes ----- @@ -7435,7 +7439,7 @@ class ifftn[TArray: Array](Protocol): .. versionadded:: 2022.12 .. versionchanged:: 2023.12 - Required the input array have a complex floating-point data type and required that the output array have the same data type as the input array. + Required the input array have a complex floating-point data type and required that the output array have the same data type as the input array. """ @@ -7449,35 +7453,35 @@ class rfft[TArray: Array](Protocol): Computes the one-dimensional discrete Fourier transform for real-valued input. .. note:: - Applying the one-dimensional inverse discrete Fourier transform for real-valued input to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e., ``irfft(rfft(x)) == x``), provided that the transform and inverse transform are performed with the same arguments (axis and normalization mode) and consistent values for the number of elements over which to compute the transforms. + Applying the one-dimensional inverse discrete Fourier transform for real-valued input to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e., ``irfft(rfft(x)) == x``), provided that the transform and inverse transform are performed with the same arguments (axis and normalization mode) and consistent values for the number of elements over which to compute the transforms. Parameters ---------- x: array - input array. Must have a real-valued floating-point data type. + input array. Must have a real-valued floating-point data type. n: Optional[int] - number of elements over which to compute the transform along the axis (dimension) specified by ``axis``. Let ``M`` be the size of the input array along the axis specified by ``axis``. When ``n`` is ``None``, the function must set ``n`` equal to ``M``. + number of elements over which to compute the transform along the axis (dimension) specified by ``axis``. Let ``M`` be the size of the input array along the axis specified by ``axis``. When ``n`` is ``None``, the function must set ``n`` equal to ``M``. - - If ``n`` is greater than ``M``, the axis specified by ``axis`` must be zero-padded to size ``n``. - - If ``n`` is less than ``M``, the axis specified by ``axis`` must be trimmed to size ``n``. - - If ``n`` equals ``M``, all elements along the axis specified by ``axis`` must be used when computing the transform. + - If ``n`` is greater than ``M``, the axis specified by ``axis`` must be zero-padded to size ``n``. + - If ``n`` is less than ``M``, the axis specified by ``axis`` must be trimmed to size ``n``. + - If ``n`` equals ``M``, all elements along the axis specified by ``axis`` must be used when computing the transform. - Default: ``None``. + Default: ``None``. axis: int - axis (dimension) of the input array over which to compute the transform. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). Default: ``-1``. + axis (dimension) of the input array over which to compute the transform. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). Default: ``-1``. norm: Literal['backward', 'ortho', 'forward'] - normalization mode. Should be one of the following modes: + normalization mode. Should be one of the following modes: - - ``'backward'``: no normalization. - - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). - - ``'forward'``: normalize by ``1/n``. + - ``'backward'``: no normalization. + - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). + - ``'forward'``: normalize by ``1/n``. - Default: ``'backward'``. + Default: ``'backward'``. Returns ------- out: array - an array transformed along the axis (dimension) specified by ``axis``. The returned array must have a complex floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``float64``, then the returned array must have a ``complex128`` data type). The returned array must have the same shape as ``x``, except for the axis specified by ``axis`` which must have size ``n//2 + 1``. + an array transformed along the axis (dimension) specified by ``axis``. The returned array must have a complex floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``float64``, then the returned array must have a ``complex128`` data type). The returned array must have the same shape as ``x``, except for the axis specified by ``axis`` which must have size ``n//2 + 1``. Notes ----- @@ -7496,35 +7500,35 @@ class irfft[TArray: Array](Protocol): Computes the one-dimensional inverse of ``rfft`` for complex-valued input. .. note:: - Applying the one-dimensional inverse discrete Fourier transform for real-valued input to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e., ``irfft(rfft(x)) == x``), provided that the transform and inverse transform are performed with the same arguments (axis and normalization mode) and consistent values for the number of elements over which to compute the transforms. + Applying the one-dimensional inverse discrete Fourier transform for real-valued input to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e., ``irfft(rfft(x)) == x``), provided that the transform and inverse transform are performed with the same arguments (axis and normalization mode) and consistent values for the number of elements over which to compute the transforms. Parameters ---------- x: array - input array. Should have a complex floating-point data type. + input array. Should have a complex floating-point data type. n: Optional[int] - number of elements along the transformed axis (dimension) specified by ``axis`` in the **output array**. Let ``M`` be the size of the input array along the axis specified by ``axis``. When ``n`` is ``None``, the function must set ``n`` equal to ``2*(M-1)``. + number of elements along the transformed axis (dimension) specified by ``axis`` in the **output array**. Let ``M`` be the size of the input array along the axis specified by ``axis``. When ``n`` is ``None``, the function must set ``n`` equal to ``2*(M-1)``. - - If ``n//2+1`` is greater than ``M``, the axis of the input array specified by ``axis`` must be zero-padded to size ``n//2+1``. - - If ``n//2+1`` is less than ``M``, the axis of the input array specified by ``axis`` must be trimmed to size ``n//2+1``. - - If ``n//2+1`` equals ``M``, all elements along the axis of the input array specified by ``axis`` must be used when computing the transform. + - If ``n//2+1`` is greater than ``M``, the axis of the input array specified by ``axis`` must be zero-padded to size ``n//2+1``. + - If ``n//2+1`` is less than ``M``, the axis of the input array specified by ``axis`` must be trimmed to size ``n//2+1``. + - If ``n//2+1`` equals ``M``, all elements along the axis of the input array specified by ``axis`` must be used when computing the transform. - Default: ``None``. + Default: ``None``. axis: int - axis (dimension) of the input array over which to compute the transform. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). Default: ``-1``. + axis (dimension) of the input array over which to compute the transform. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). Default: ``-1``. norm: Literal['backward', 'ortho', 'forward'] - normalization mode. Should be one of the following modes: + normalization mode. Should be one of the following modes: - - ``'backward'``: normalize by ``1/n``. - - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). - - ``'forward'``: no normalization. + - ``'backward'``: normalize by ``1/n``. + - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). + - ``'forward'``: no normalization. - Default: ``'backward'``. + Default: ``'backward'``. Returns ------- out: array - an array transformed along the axis (dimension) specified by ``axis``. The returned array must have a real-valued floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``complex128``, then the returned array must have a ``float64`` data type). The returned array must have the same shape as ``x``, except for the axis specified by ``axis`` which must have size ``n``. + an array transformed along the axis (dimension) specified by ``axis``. The returned array must have a real-valued floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``complex128``, then the returned array must have a ``float64`` data type). The returned array must have the same shape as ``x``, except for the axis specified by ``axis`` which must have size ``n``. Notes ----- @@ -7533,7 +7537,7 @@ class irfft[TArray: Array](Protocol): .. versionadded:: 2022.12 .. versionchanged:: 2023.12 - Required the output array have a real-valued floating-point data type having the same precision as the input array. + Required the output array have a real-valued floating-point data type having the same precision as the input array. """ @@ -7547,41 +7551,41 @@ class rfftn[TArray: Array](Protocol): Computes the n-dimensional discrete Fourier transform for real-valued input. .. note:: - Applying the n-dimensional inverse discrete Fourier transform for real-valued input to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e., ``irfftn(rfftn(x)) == x``), provided that the transform and inverse transform are performed with the same arguments (axes and normalization mode) and consistent sizes. + Applying the n-dimensional inverse discrete Fourier transform for real-valued input to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e., ``irfftn(rfftn(x)) == x``), provided that the transform and inverse transform are performed with the same arguments (axes and normalization mode) and consistent sizes. Parameters ---------- x: array - input array. Must have a real-valued floating-point data type. + input array. Must have a real-valued floating-point data type. s: Optional[Sequence[int]] - number of elements over which to compute the transform along axes (dimensions) specified by ``axes``. Let ``i`` be the index of the ``n``-th axis specified by ``axes`` (i.e., ``i = axes[n]``) and ``M[i]`` be the size of the input array along axis ``i``. When ``s`` is ``None``, the function must set ``s`` equal to a sequence of integers such that ``s[i]`` equals ``M[i]`` for all ``i``. + number of elements over which to compute the transform along axes (dimensions) specified by ``axes``. Let ``i`` be the index of the ``n``-th axis specified by ``axes`` (i.e., ``i = axes[n]``) and ``M[i]`` be the size of the input array along axis ``i``. When ``s`` is ``None``, the function must set ``s`` equal to a sequence of integers such that ``s[i]`` equals ``M[i]`` for all ``i``. - - If ``s[i]`` is greater than ``M[i]``, axis ``i`` must be zero-padded to size ``s[i]``. - - If ``s[i]`` is less than ``M[i]``, axis ``i`` must be trimmed to size ``s[i]``. - - If ``s[i]`` equals ``M[i]`` or ``-1``, all elements along axis ``i`` must be used when computing the transform. + - If ``s[i]`` is greater than ``M[i]``, axis ``i`` must be zero-padded to size ``s[i]``. + - If ``s[i]`` is less than ``M[i]``, axis ``i`` must be trimmed to size ``s[i]``. + - If ``s[i]`` equals ``M[i]`` or ``-1``, all elements along axis ``i`` must be used when computing the transform. - If ``s`` is not ``None``, ``axes`` must not be ``None``. Default: ``None``. + If ``s`` is not ``None``, ``axes`` must not be ``None``. Default: ``None``. axes: Optional[Sequence[int]] - axes (dimensions) over which to compute the transform. A valid axis in ``axes`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an axis is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). + axes (dimensions) over which to compute the transform. A valid axis in ``axes`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an axis is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). - If ``s`` is provided, the corresponding ``axes`` to be transformed must also be provided. If ``axes`` is ``None``, the function must compute the transform over all axes. Default: ``None``. + If ``s`` is provided, the corresponding ``axes`` to be transformed must also be provided. If ``axes`` is ``None``, the function must compute the transform over all axes. Default: ``None``. - If ``axes`` contains two or more entries which resolve to the same axis (i.e., resolved axes are not unique), the behavior is unspecified and thus implementation-defined. + If ``axes`` contains two or more entries which resolve to the same axis (i.e., resolved axes are not unique), the behavior is unspecified and thus implementation-defined. norm: Literal['backward', 'ortho', 'forward'] - normalization mode. Should be one of the following modes: + normalization mode. Should be one of the following modes: - - ``'backward'``: no normalization. - - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). - - ``'forward'``: normalize by ``1/n``. + - ``'backward'``: no normalization. + - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). + - ``'forward'``: normalize by ``1/n``. - where ``n = prod(s)``, the logical FFT size. + where ``n = prod(s)``, the logical FFT size. - Default: ``'backward'``. + Default: ``'backward'``. Returns ------- out: array - an array transformed along the axes (dimension) specified by ``axes``. The returned array must have a complex floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``float64``, then the returned array must have a ``complex128`` data type). The returned array must have the same shape as ``x``, except for the last transformed axis which must have size ``s[-1]//2 + 1`` and the remaining transformed axes which must have size ``s[i]``. + an array transformed along the axes (dimension) specified by ``axes``. The returned array must have a complex floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``float64``, then the returned array must have a ``complex128`` data type). The returned array must have the same shape as ``x``, except for the last transformed axis which must have size ``s[-1]//2 + 1`` and the remaining transformed axes which must have size ``s[i]``. Notes ----- @@ -7600,41 +7604,41 @@ class irfftn[TArray: Array](Protocol): Computes the n-dimensional inverse of ``rfftn`` for complex-valued input. .. note:: - Applying the n-dimensional inverse discrete Fourier transform for real-valued input to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e., ``irfftn(rfftn(x)) == x``), provided that the transform and inverse transform are performed with the same arguments (axes and normalization mode) and consistent sizes. + Applying the n-dimensional inverse discrete Fourier transform for real-valued input to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e., ``irfftn(rfftn(x)) == x``), provided that the transform and inverse transform are performed with the same arguments (axes and normalization mode) and consistent sizes. Parameters ---------- x: array - input array. Should have a complex floating-point data type. + input array. Should have a complex floating-point data type. s: Optional[Sequence[int]] - number of elements along the transformed axes (dimensions) specified by ``axes`` in the **output array**. Let ``i`` be the index of the ``n``-th axis specified by ``axes`` (i.e., ``i = axes[n]``) and ``M[i]`` be the size of the input array along axis ``i``. When ``s`` is ``None``, the function must set ``s`` equal to a sequence of integers such that ``s[i]`` equals ``M[i]`` for all ``i``, except for the last transformed axis in which ``s[i]`` equals ``2*(M[i]-1)``. For each ``i``, let ``n`` equal ``s[i]``, except for the last transformed axis in which ``n`` equals ``s[i]//2+1``. + number of elements along the transformed axes (dimensions) specified by ``axes`` in the **output array**. Let ``i`` be the index of the ``n``-th axis specified by ``axes`` (i.e., ``i = axes[n]``) and ``M[i]`` be the size of the input array along axis ``i``. When ``s`` is ``None``, the function must set ``s`` equal to a sequence of integers such that ``s[i]`` equals ``M[i]`` for all ``i``, except for the last transformed axis in which ``s[i]`` equals ``2*(M[i]-1)``. For each ``i``, let ``n`` equal ``s[i]``, except for the last transformed axis in which ``n`` equals ``s[i]//2+1``. - - If ``n`` is greater than ``M[i]``, axis ``i`` of the input array must be zero-padded to size ``n``. - - If ``n`` is less than ``M[i]``, axis ``i`` of the input array must be trimmed to size ``n``. - - If ``n`` equals ``M[i]`` or ``-1``, all elements along axis ``i`` of the input array must be used when computing the transform. + - If ``n`` is greater than ``M[i]``, axis ``i`` of the input array must be zero-padded to size ``n``. + - If ``n`` is less than ``M[i]``, axis ``i`` of the input array must be trimmed to size ``n``. + - If ``n`` equals ``M[i]`` or ``-1``, all elements along axis ``i`` of the input array must be used when computing the transform. - If ``s`` is not ``None``, ``axes`` must not be ``None``. Default: ``None``. + If ``s`` is not ``None``, ``axes`` must not be ``None``. Default: ``None``. axes: Optional[Sequence[int]] - axes (dimensions) over which to compute the transform. A valid axis in ``axes`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an axis is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). + axes (dimensions) over which to compute the transform. A valid axis in ``axes`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an axis is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). - If ``s`` is provided, the corresponding ``axes`` to be transformed must also be provided. If ``axes`` is ``None``, the function must compute the transform over all axes. Default: ``None``. + If ``s`` is provided, the corresponding ``axes`` to be transformed must also be provided. If ``axes`` is ``None``, the function must compute the transform over all axes. Default: ``None``. - If ``axes`` contains two or more entries which resolve to the same axis (i.e., resolved axes are not unique), the behavior is unspecified and thus implementation-defined. + If ``axes`` contains two or more entries which resolve to the same axis (i.e., resolved axes are not unique), the behavior is unspecified and thus implementation-defined. norm: Literal['backward', 'ortho', 'forward'] - normalization mode. Should be one of the following modes: + normalization mode. Should be one of the following modes: - - ``'backward'``: normalize by ``1/n``. - - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). - - ``'forward'``: no normalization. + - ``'backward'``: normalize by ``1/n``. + - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). + - ``'forward'``: no normalization. - where ``n = prod(s)`` is the logical FFT size. + where ``n = prod(s)`` is the logical FFT size. - Default: ``'backward'``. + Default: ``'backward'``. Returns ------- out: array - an array transformed along the axes (dimension) specified by ``axes``. The returned array must have a real-valued floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``complex128``, then the returned array must have a ``float64`` data type). The returned array must have the same shape as ``x``, except for the transformed axes which must have size ``s[i]``. + an array transformed along the axes (dimension) specified by ``axes``. The returned array must have a real-valued floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``complex128``, then the returned array must have a ``float64`` data type). The returned array must have the same shape as ``x``, except for the transformed axes which must have size ``s[i]``. Notes ----- @@ -7643,7 +7647,7 @@ class irfftn[TArray: Array](Protocol): .. versionadded:: 2022.12 .. versionchanged:: 2023.12 - Required the output array have a real-valued floating-point data type having the same precision as the input array. + Required the output array have a real-valued floating-point data type having the same precision as the input array. """ @@ -7659,30 +7663,30 @@ class hfft[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a complex floating-point data type. + input array. Should have a complex floating-point data type. n: Optional[int] - number of elements along the transformed axis (dimension) specified by ``axis`` in the **output array**. Let ``M`` be the size of the input array along the axis specified by ``axis``. When ``n`` is ``None``, the function must set ``n`` equal to ``2*(M-1)``. + number of elements along the transformed axis (dimension) specified by ``axis`` in the **output array**. Let ``M`` be the size of the input array along the axis specified by ``axis``. When ``n`` is ``None``, the function must set ``n`` equal to ``2*(M-1)``. - - If ``n//2+1`` is greater than ``M``, the axis of the input array specified by ``axis`` must be zero-padded to length ``n//2+1``. - - If ``n//2+1`` is less than ``M``, the axis of the input array specified by ``axis`` must be trimmed to size ``n//2+1``. - - If ``n//2+1`` equals ``M``, all elements along the axis of the input array specified by ``axis`` must be used when computing the transform. + - If ``n//2+1`` is greater than ``M``, the axis of the input array specified by ``axis`` must be zero-padded to length ``n//2+1``. + - If ``n//2+1`` is less than ``M``, the axis of the input array specified by ``axis`` must be trimmed to size ``n//2+1``. + - If ``n//2+1`` equals ``M``, all elements along the axis of the input array specified by ``axis`` must be used when computing the transform. - Default: ``None``. + Default: ``None``. axis: int - axis (dimension) of the input array over which to compute the transform. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). Default: ``-1``. + axis (dimension) of the input array over which to compute the transform. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). Default: ``-1``. norm: Literal['backward', 'ortho', 'forward'] - normalization mode. Should be one of the following modes: + normalization mode. Should be one of the following modes: - - ``'backward'``: no normalization. - - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). - - ``'forward'``: normalize by ``1/n``. + - ``'backward'``: no normalization. + - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). + - ``'forward'``: normalize by ``1/n``. - Default: ``'backward'``. + Default: ``'backward'``. Returns ------- out: array - an array transformed along the axis (dimension) specified by ``axis``. The returned array must have a real-valued floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``complex128``, then the returned array must have a ``float64`` data type). The returned array must have the same shape as ``x``, except for the axis specified by ``axis`` which must have size ``n``. + an array transformed along the axis (dimension) specified by ``axis``. The returned array must have a real-valued floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``complex128``, then the returned array must have a ``float64`` data type). The returned array must have the same shape as ``x``, except for the axis specified by ``axis`` which must have size ``n``. Notes ----- @@ -7690,7 +7694,7 @@ class hfft[TArray: Array](Protocol): .. versionadded:: 2022.12 .. versionchanged:: 2023.12 - Required the input array to have a complex floating-point data type and required that the output array have a real-valued data type having the same precision as the input array. + Required the input array to have a complex floating-point data type and required that the output array have a real-valued data type having the same precision as the input array. """ @@ -7706,30 +7710,30 @@ class ihfft[TArray: Array](Protocol): Parameters ---------- x: array - input array. Must have a real-valued floating-point data type. + input array. Must have a real-valued floating-point data type. n: Optional[int] - number of elements over which to compute the transform along the axis (dimension) specified by ``axis``. Let ``M`` be the size of the input array along the axis specified by ``axis``. When ``n`` is ``None``, the function must set ``n`` equal to ``M``. + number of elements over which to compute the transform along the axis (dimension) specified by ``axis``. Let ``M`` be the size of the input array along the axis specified by ``axis``. When ``n`` is ``None``, the function must set ``n`` equal to ``M``. - - If ``n`` is greater than ``M``, the axis specified by ``axis`` must be zero-padded to size ``n``. - - If ``n`` is less than ``M``, the axis specified by ``axis`` must be trimmed to size ``n``. - - If ``n`` equals ``M``, all elements along the axis specified by ``axis`` must be used when computing the transform. + - If ``n`` is greater than ``M``, the axis specified by ``axis`` must be zero-padded to size ``n``. + - If ``n`` is less than ``M``, the axis specified by ``axis`` must be trimmed to size ``n``. + - If ``n`` equals ``M``, all elements along the axis specified by ``axis`` must be used when computing the transform. - Default: ``None``. + Default: ``None``. axis: int - axis (dimension) of the input array over which to compute the transform. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). Default: ``-1``. + axis (dimension) of the input array over which to compute the transform. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). Default: ``-1``. norm: Literal['backward', 'ortho', 'forward'] - normalization mode. Should be one of the following modes: + normalization mode. Should be one of the following modes: - - ``'backward'``: normalize by ``1/n``. - - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). - - ``'forward'``: no normalization. + - ``'backward'``: normalize by ``1/n``. + - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). + - ``'forward'``: no normalization. - Default: ``'backward'``. + Default: ``'backward'``. Returns ------- out: array - an array transformed along the axis (dimension) specified by ``axis``. The returned array must have a complex floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``float64``, then the returned array must have a ``complex128`` data type). The returned array must have the same shape as ``x``, except for the axis specified by ``axis`` which must have size ``n//2 + 1``. + an array transformed along the axis (dimension) specified by ``axis``. The returned array must have a complex floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``float64``, then the returned array must have a ``complex128`` data type). The returned array must have the same shape as ``x``, except for the axis specified by ``axis`` which must have size ``n//2 + 1``. Notes ----- @@ -7751,24 +7755,24 @@ class fftfreq[TArray: Array, TDevice, TDtype](Protocol): .. code-block:: - f = [0, 1, ..., n/2-1, -n/2, ..., -1] / (d*n) # if n is even - f = [0, 1, ..., (n-1)/2, -(n-1)/2, ..., -1] / (d*n) # if n is odd + f = [0, 1, ..., n/2-1, -n/2, ..., -1] / (d*n) # if n is even + f = [0, 1, ..., (n-1)/2, -(n-1)/2, ..., -1] / (d*n) # if n is odd Parameters ---------- n: int - window length. + window length. d: float - sample spacing between individual samples of the Fourier transform input. Default: ``1.0``. + sample spacing between individual samples of the Fourier transform input. Default: ``1.0``. dtype: Optional[dtype] - output array data type. Must be a real-valued floating-point data type. If ``dtype`` is ``None``, the output array data type must be the default real-valued floating-point data type. Default: ``None``. + output array data type. Must be a real-valued floating-point data type. If ``dtype`` is ``None``, the output array data type must be the default real-valued floating-point data type. Default: ``None``. device: Optional[device] - device on which to place the created array. Default: ``None``. + device on which to place the created array. Default: ``None``. Returns ------- out: array - an array of shape ``(n,)`` containing the sample frequencies. + an array of shape ``(n,)`` containing the sample frequencies. Notes ----- @@ -7776,10 +7780,10 @@ class fftfreq[TArray: Array, TDevice, TDtype](Protocol): .. versionadded:: 2022.12 .. versionchanged:: 2023.12 - Required the output array have the default real-valued floating-point data type. + Required the output array have the default real-valued floating-point data type. .. versionchanged:: 2024.12 - Added ``dtype`` keyword argument support. + Added ``dtype`` keyword argument support. """ @@ -7796,26 +7800,26 @@ class rfftfreq[TArray: Array, TDevice, TDtype](Protocol): .. code-block:: - f = [0, 1, ..., n/2-1, n/2] / (d*n) # if n is even - f = [0, 1, ..., (n-1)/2-1, (n-1)/2] / (d*n) # if n is odd + f = [0, 1, ..., n/2-1, n/2] / (d*n) # if n is even + f = [0, 1, ..., (n-1)/2-1, (n-1)/2] / (d*n) # if n is odd The Nyquist frequency component is considered to be positive. Parameters ---------- n: int - window length. + window length. d: float - sample spacing between individual samples of the Fourier transform input. Default: ``1.0``. + sample spacing between individual samples of the Fourier transform input. Default: ``1.0``. dtype: Optional[dtype] - output array data type. Must be a real-valued floating-point data type. If ``dtype`` is ``None``, the output array data type must be the default real-valued floating-point data type. Default: ``None``. + output array data type. Must be a real-valued floating-point data type. If ``dtype`` is ``None``, the output array data type must be the default real-valued floating-point data type. Default: ``None``. device: Optional[device] - device on which to place the created array. Default: ``None``. + device on which to place the created array. Default: ``None``. Returns ------- out: array - an array of shape ``(n//2+1,)`` containing the sample frequencies. + an array of shape ``(n//2+1,)`` containing the sample frequencies. Notes ----- @@ -7823,10 +7827,10 @@ class rfftfreq[TArray: Array, TDevice, TDtype](Protocol): .. versionadded:: 2022.12 .. versionchanged:: 2023.12 - Required the output array have the default real-valued floating-point data type. + Required the output array have the default real-valued floating-point data type. .. versionchanged:: 2024.12 - Added ``dtype`` keyword argument support. + Added ``dtype`` keyword argument support. """ @@ -7842,21 +7846,21 @@ class fftshift[TArray: Array](Protocol): This function swaps half-spaces for all axes (dimensions) specified by ``axes``. .. note:: - ``out[0]`` is the Nyquist component only if the length of the input is even. + ``out[0]`` is the Nyquist component only if the length of the input is even. Parameters ---------- x: array - input array. Should have a floating-point data type. + input array. Should have a floating-point data type. axes: Optional[Union[int, Sequence[int]]] - axes over which to shift. If ``None``, the function must shift all axes. Default: ``None``. + axes over which to shift. If ``None``, the function must shift all axes. Default: ``None``. - If ``axes`` contains two or more entries which resolve to the same axis (i.e., resolved axes are not unique), the behavior is unspecified and thus implementation-defined. + If ``axes`` contains two or more entries which resolve to the same axis (i.e., resolved axes are not unique), the behavior is unspecified and thus implementation-defined. Returns ------- out: array - the shifted array. The returned array must have the same data type and shape as ``x``. + the shifted array. The returned array must have the same data type and shape as ``x``. Notes ----- @@ -7875,21 +7879,21 @@ class ifftshift[TArray: Array](Protocol): Inverse of ``fftshift``. .. note:: - Although identical for even-length ``x``, ``fftshift`` and ``ifftshift`` differ by one sample for odd-length ``x``. + Although identical for even-length ``x``, ``fftshift`` and ``ifftshift`` differ by one sample for odd-length ``x``. Parameters ---------- x: array - input array. Should have a floating-point data type. + input array. Should have a floating-point data type. axes: Optional[Union[int, Sequence[int]]] - axes over which to perform the inverse shift. If ``None``, the function must shift all axes. Default: ``None``. + axes over which to perform the inverse shift. If ``None``, the function must shift all axes. Default: ``None``. - If ``axes`` contains two or more entries which resolve to the same axis (i.e., resolved axes are not unique), the behavior is unspecified and thus implementation-defined. + If ``axes`` contains two or more entries which resolve to the same axis (i.e., resolved axes are not unique), the behavior is unspecified and thus implementation-defined. Returns ------- out: array - the shifted array. The returned array must have the same data type and shape as ``x``. + the shifted array. The returned array must have the same data type and shape as ``x``. Notes ----- @@ -7908,37 +7912,37 @@ class matmul[TArray: Array](Protocol): Computes the matrix product. .. note:: - The ``matmul`` function must implement the same semantics as the built-in ``@`` operator (see `PEP 465 `_). + The ``matmul`` function must implement the same semantics as the built-in ``@`` operator (see `PEP 465 `_). Parameters ---------- x1: array - first input array. Should have a numeric data type. Must have at least one dimension. If ``x1`` is one-dimensional having shape ``(M,)`` and ``x2`` has more than one dimension, ``x1`` must be promoted to a two-dimensional array by prepending ``1`` to its dimensions (i.e., must have shape ``(1, M)``). After matrix multiplication, the prepended dimensions in the returned array must be removed. If ``x1`` has more than one dimension (including after vector-to-matrix promotion), ``shape(x1)[:-2]`` must be compatible with ``shape(x2)[:-2]`` (after vector-to-matrix promotion) (see :ref:`broadcasting`). If ``x1`` has shape ``(..., M, K)``, the innermost two dimensions form matrices on which to perform matrix multiplication. + first input array. Should have a numeric data type. Must have at least one dimension. If ``x1`` is one-dimensional having shape ``(M,)`` and ``x2`` has more than one dimension, ``x1`` must be promoted to a two-dimensional array by prepending ``1`` to its dimensions (i.e., must have shape ``(1, M)``). After matrix multiplication, the prepended dimensions in the returned array must be removed. If ``x1`` has more than one dimension (including after vector-to-matrix promotion), ``shape(x1)[:-2]`` must be compatible with ``shape(x2)[:-2]`` (after vector-to-matrix promotion) (see :ref:`broadcasting`). If ``x1`` has shape ``(..., M, K)``, the innermost two dimensions form matrices on which to perform matrix multiplication. x2: array - second input array. Should have a numeric data type. Must have at least one dimension. If ``x2`` is one-dimensional having shape ``(N,)`` and ``x1`` has more than one dimension, ``x2`` must be promoted to a two-dimensional array by appending ``1`` to its dimensions (i.e., must have shape ``(N, 1)``). After matrix multiplication, the appended dimensions in the returned array must be removed. If ``x2`` has more than one dimension (including after vector-to-matrix promotion), ``shape(x2)[:-2]`` must be compatible with ``shape(x1)[:-2]`` (after vector-to-matrix promotion) (see :ref:`broadcasting`). If ``x2`` has shape ``(..., K, N)``, the innermost two dimensions form matrices on which to perform matrix multiplication. + second input array. Should have a numeric data type. Must have at least one dimension. If ``x2`` is one-dimensional having shape ``(N,)`` and ``x1`` has more than one dimension, ``x2`` must be promoted to a two-dimensional array by appending ``1`` to its dimensions (i.e., must have shape ``(N, 1)``). After matrix multiplication, the appended dimensions in the returned array must be removed. If ``x2`` has more than one dimension (including after vector-to-matrix promotion), ``shape(x2)[:-2]`` must be compatible with ``shape(x1)[:-2]`` (after vector-to-matrix promotion) (see :ref:`broadcasting`). If ``x2`` has shape ``(..., K, N)``, the innermost two dimensions form matrices on which to perform matrix multiplication. .. note:: - If either ``x1`` or ``x2`` has a complex floating-point data type, neither argument must be complex-conjugated or transposed. If conjugation and/or transposition is desired, these operations should be explicitly performed prior to computing the matrix product. + If either ``x1`` or ``x2`` has a complex floating-point data type, neither argument must be complex-conjugated or transposed. If conjugation and/or transposition is desired, these operations should be explicitly performed prior to computing the matrix product. Returns ------- out: array - - if both ``x1`` and ``x2`` are one-dimensional arrays having shape ``(N,)``, a zero-dimensional array containing the inner product as its only element. - - if ``x1`` is a two-dimensional array having shape ``(M, K)`` and ``x2`` is a two-dimensional array having shape ``(K, N)``, a two-dimensional array containing the `conventional matrix product `_ and having shape ``(M, N)``. - - if ``x1`` is a one-dimensional array having shape ``(K,)`` and ``x2`` is an array having shape ``(..., K, N)``, an array having shape ``(..., N)`` (i.e., prepended dimensions during vector-to-matrix promotion must be removed) and containing the `conventional matrix product `_. - - if ``x1`` is an array having shape ``(..., M, K)`` and ``x2`` is a one-dimensional array having shape ``(K,)``, an array having shape ``(..., M)`` (i.e., appended dimensions during vector-to-matrix promotion must be removed) and containing the `conventional matrix product `_. - - if ``x1`` is a two-dimensional array having shape ``(M, K)`` and ``x2`` is an array having shape ``(..., K, N)``, an array having shape ``(..., M, N)`` and containing the `conventional matrix product `_ for each stacked matrix. - - if ``x1`` is an array having shape ``(..., M, K)`` and ``x2`` is a two-dimensional array having shape ``(K, N)``, an array having shape ``(..., M, N)`` and containing the `conventional matrix product `_ for each stacked matrix. - - if either ``x1`` or ``x2`` has more than two dimensions, an array having a shape determined by :ref:`broadcasting` ``shape(x1)[:-2]`` against ``shape(x2)[:-2]`` and containing the `conventional matrix product `_ for each stacked matrix. + - if both ``x1`` and ``x2`` are one-dimensional arrays having shape ``(N,)``, a zero-dimensional array containing the inner product as its only element. + - if ``x1`` is a two-dimensional array having shape ``(M, K)`` and ``x2`` is a two-dimensional array having shape ``(K, N)``, a two-dimensional array containing the `conventional matrix product `_ and having shape ``(M, N)``. + - if ``x1`` is a one-dimensional array having shape ``(K,)`` and ``x2`` is an array having shape ``(..., K, N)``, an array having shape ``(..., N)`` (i.e., prepended dimensions during vector-to-matrix promotion must be removed) and containing the `conventional matrix product `_. + - if ``x1`` is an array having shape ``(..., M, K)`` and ``x2`` is a one-dimensional array having shape ``(K,)``, an array having shape ``(..., M)`` (i.e., appended dimensions during vector-to-matrix promotion must be removed) and containing the `conventional matrix product `_. + - if ``x1`` is a two-dimensional array having shape ``(M, K)`` and ``x2`` is an array having shape ``(..., K, N)``, an array having shape ``(..., M, N)`` and containing the `conventional matrix product `_ for each stacked matrix. + - if ``x1`` is an array having shape ``(..., M, K)`` and ``x2`` is a two-dimensional array having shape ``(K, N)``, an array having shape ``(..., M, N)`` and containing the `conventional matrix product `_ for each stacked matrix. + - if either ``x1`` or ``x2`` has more than two dimensions, an array having a shape determined by :ref:`broadcasting` ``shape(x1)[:-2]`` against ``shape(x2)[:-2]`` and containing the `conventional matrix product `_ for each stacked matrix. - The returned array must have a data type determined by :ref:`type-promotion`. + The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. **Raises** @@ -7962,12 +7966,12 @@ class matrix_transpose[TArray: Array](Protocol): Parameters ---------- x: array - input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. + input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. Returns ------- out: array - an array containing the transpose for each matrix and having shape ``(..., N, M)``. The returned array must have the same data type as ``x``. + an array containing the transpose for each matrix and having shape ``(..., N, M)``. The returned array must have the same data type as ``x``. """ @@ -7981,46 +7985,46 @@ class tensordot[TArray: Array](Protocol): Returns a tensor contraction of ``x1`` and ``x2`` over specific axes. .. note:: - The ``tensordot`` function corresponds to the generalized matrix product. + The ``tensordot`` function corresponds to the generalized matrix product. Parameters ---------- x1: array - first input array. Should have a numeric data type. + first input array. Should have a numeric data type. x2: array - second input array. Should have a numeric data type. Corresponding contracted axes of ``x1`` and ``x2`` must be equal. + second input array. Should have a numeric data type. Corresponding contracted axes of ``x1`` and ``x2`` must be equal. - .. note:: - Contracted axes (dimensions) must not be broadcasted. + .. note:: + Contracted axes (dimensions) must not be broadcasted. axes: Union[int, Tuple[Sequence[int], Sequence[int]]] - number of axes (dimensions) to contract or explicit sequences of axis (dimension) indices for ``x1`` and ``x2``, respectively. + number of axes (dimensions) to contract or explicit sequences of axis (dimension) indices for ``x1`` and ``x2``, respectively. - If ``axes`` is an ``int`` equal to ``N``, then contraction must be performed over the last ``N`` axes of ``x1`` and the first ``N`` axes of ``x2`` in order. The size of each corresponding axis (dimension) must match. Must be nonnegative. + If ``axes`` is an ``int`` equal to ``N``, then contraction must be performed over the last ``N`` axes of ``x1`` and the first ``N`` axes of ``x2`` in order. The size of each corresponding axis (dimension) must match. Must be nonnegative. - - If ``N`` equals ``0``, the result is the tensor (outer) product. - - If ``N`` equals ``1``, the result is the tensor dot product. - - If ``N`` equals ``2``, the result is the tensor double contraction (default). + - If ``N`` equals ``0``, the result is the tensor (outer) product. + - If ``N`` equals ``1``, the result is the tensor dot product. + - If ``N`` equals ``2``, the result is the tensor double contraction (default). - If ``axes`` is a tuple of two sequences ``(x1_axes, x2_axes)``, the first sequence must apply to ``x1`` and the second sequence to ``x2``. Both sequences must have the same length. Each axis (dimension) ``x1_axes[i]`` for ``x1`` must have the same size as the respective axis (dimension) ``x2_axes[i]`` for ``x2``. Each index referred to in a sequence must be unique. If ``x1`` has rank (i.e, number of dimensions) ``N``, a valid ``x1`` axis must reside on the half-open interval ``[-N, N)``. If ``x2`` has rank ``M``, a valid ``x2`` axis must reside on the half-open interval ``[-M, M)``. + If ``axes`` is a tuple of two sequences ``(x1_axes, x2_axes)``, the first sequence must apply to ``x1`` and the second sequence to ``x2``. Both sequences must have the same length. Each axis (dimension) ``x1_axes[i]`` for ``x1`` must have the same size as the respective axis (dimension) ``x2_axes[i]`` for ``x2``. Each index referred to in a sequence must be unique. If ``x1`` has rank (i.e, number of dimensions) ``N``, a valid ``x1`` axis must reside on the half-open interval ``[-N, N)``. If ``x2`` has rank ``M``, a valid ``x2`` axis must reside on the half-open interval ``[-M, M)``. .. note:: - If either ``x1`` or ``x2`` has a complex floating-point data type, neither argument must be complex-conjugated or transposed. If conjugation and/or transposition is desired, these operations should be explicitly performed prior to computing the generalized matrix product. + If either ``x1`` or ``x2`` has a complex floating-point data type, neither argument must be complex-conjugated or transposed. If conjugation and/or transposition is desired, these operations should be explicitly performed prior to computing the generalized matrix product. Returns ------- out: array - an array containing the tensor contraction whose shape consists of the non-contracted axes (dimensions) of the first array ``x1``, followed by the non-contracted axes (dimensions) of the second array ``x2``. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the tensor contraction whose shape consists of the non-contracted axes (dimensions) of the first array ``x1``, followed by the non-contracted axes (dimensions) of the second array ``x2``. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. .. versionchanged:: 2023.12 - Allow negative axes. + Allow negative axes. """ @@ -8036,27 +8040,27 @@ class vecdot[TArray: Array](Protocol): Let :math:`\\mathbf{a}` be a vector in ``x1`` and :math:`\\mathbf{b}` be a corresponding vector in ``x2``. The dot product is defined as .. math:: - \\mathbf{a} \\cdot \\mathbf{b} = \\sum_{i=0}^{n-1} \\overline{a_i}b_i + \\mathbf{a} \\cdot \\mathbf{b} = \\sum_{i=0}^{n-1} \\overline{a_i}b_i over the dimension specified by ``axis`` and where :math:`n` is the dimension size and :math:`\\overline{a_i}` denotes the complex conjugate if :math:`a_i` is complex and the identity if :math:`a_i` is real-valued. Parameters ---------- x1: array - first input array. Should have a floating-point data type. + first input array. Should have a floating-point data type. x2: array - second input array. Must be compatible with ``x1`` for all non-contracted axes (see :ref:`broadcasting`). The size of the axis over which to compute the dot product must be the same size as the respective axis in ``x1``. Should have a floating-point data type. + second input array. Must be compatible with ``x1`` for all non-contracted axes (see :ref:`broadcasting`). The size of the axis over which to compute the dot product must be the same size as the respective axis in ``x1``. Should have a floating-point data type. - .. note:: - The contracted axis (dimension) must not be broadcasted. + .. note:: + The contracted axis (dimension) must not be broadcasted. axis: int - the axis (dimension) of ``x1`` and ``x2`` containing the vectors for which to compute the dot product. Should be an integer on the interval ``[-N, -1]``, where ``N`` is ``min(x1.ndim, x2.ndim)``. The function must determine the axis along which to compute the dot product by counting backward from the last dimension (where ``-1`` refers to the last dimension). By default, the function must compute the dot product over the last axis. Default: ``-1``. + the axis (dimension) of ``x1`` and ``x2`` containing the vectors for which to compute the dot product. Should be an integer on the interval ``[-N, -1]``, where ``N`` is ``min(x1.ndim, x2.ndim)``. The function must determine the axis along which to compute the dot product by counting backward from the last dimension (where ``-1`` refers to the last dimension). By default, the function must compute the dot product over the last axis. Default: ``-1``. Returns ------- out: array - if ``x1`` and ``x2`` are both one-dimensional arrays, a zero-dimensional containing the dot product; otherwise, a non-zero-dimensional array containing the dot products and having rank ``N-1``, where ``N`` is the rank (number of dimensions) of the shape determined according to :ref:`broadcasting` along the non-contracted axes. The returned array must have a data type determined by :ref:`type-promotion`. + if ``x1`` and ``x2`` are both one-dimensional arrays, a zero-dimensional containing the dot product; otherwise, a non-zero-dimensional array containing the dot products and having rank ``N-1``, where ``N`` is the rank (number of dimensions) of the shape determined according to :ref:`broadcasting` along the non-contracted axes. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- @@ -8065,10 +8069,10 @@ class vecdot[TArray: Array](Protocol): - if the size of the axis over which to compute the dot product is not the same (before broadcasting) for both ``x1`` and ``x2``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. .. versionchanged:: 2023.12 - Restricted ``axis`` to only negative integers. + Restricted ``axis`` to only negative integers. """ @@ -8084,12 +8088,12 @@ class broadcast_arrays[TArray: Array](Protocol): Parameters ---------- arrays: array - an arbitrary number of to-be broadcasted arrays. + an arbitrary number of to-be broadcasted arrays. Returns ------- out: List[array] - a list of broadcasted arrays. Each array must have the same shape. Each array must have the same dtype as its corresponding input array. + a list of broadcasted arrays. Each array must have the same shape. Each array must have the same dtype as its corresponding input array. """ @@ -8105,17 +8109,17 @@ class broadcast_to[TArray: Array](Protocol): Parameters ---------- x: array - array to broadcast. Must be capable of being broadcast to the specified ``shape`` (see :ref:`broadcasting`). If the array is incompatible with the specified shape, the function must raise an exception. + array to broadcast. Must be capable of being broadcast to the specified ``shape`` (see :ref:`broadcasting`). If the array is incompatible with the specified shape, the function must raise an exception. shape: Tuple[int, ...] - array shape. + array shape. Returns ------- out: array - an array having the specified shape. Must have the same data type as ``x``. + an array having the specified shape. Must have the same data type as ``x``. .. versionchanged:: 2024.12 - Clarified broadcast behavior. + Clarified broadcast behavior. """ @@ -8131,17 +8135,17 @@ class concat[TArray: Array](Protocol): Parameters ---------- arrays: Union[Tuple[array, ...], List[array]] - input arrays to join. The arrays must have the same shape, except in the dimension specified by ``axis``. + input arrays to join. The arrays must have the same shape, except in the dimension specified by ``axis``. axis: Optional[int] - axis along which the arrays will be joined. If ``axis`` is ``None``, arrays must be flattened before concatenation. If ``axis`` is negative, the function must determine the axis along which to join by counting from the last dimension. Default: ``0``. + axis along which the arrays will be joined. If ``axis`` is ``None``, arrays must be flattened before concatenation. If ``axis`` is negative, the function must determine the axis along which to join by counting from the last dimension. Default: ``0``. Returns ------- out: array - an output array containing the concatenated values. If the input arrays have different data types, normal :ref:`type-promotion` must apply. If the input arrays have the same data type, the output array must have the same data type as the input arrays. + an output array containing the concatenated values. If the input arrays have different data types, normal :ref:`type-promotion` must apply. If the input arrays have the same data type, the output array must have the same data type as the input arrays. - .. note:: - This specification leaves type promotion between data type families (i.e., ``intxx`` and ``floatxx``) unspecified. + .. note:: + This specification leaves type promotion between data type families (i.e., ``intxx`` and ``floatxx``) unspecified. """ @@ -8157,19 +8161,19 @@ class expand_dims[TArray: Array](Protocol): Parameters ---------- x: array - input array. + input array. axis: int - axis position (zero-based). If ``x`` has rank (i.e, number of dimensions) ``N``, a valid ``axis`` must reside on the closed-interval ``[-N-1, N]``. If provided a negative ``axis``, the axis position at which to insert a singleton dimension must be computed as ``N + axis + 1``. Hence, if provided ``-1``, the resolved axis position must be ``N`` (i.e., a singleton dimension must be appended to the input array ``x``). If provided ``-N-1``, the resolved axis position must be ``0`` (i.e., a singleton dimension must be prepended to the input array ``x``). + axis position (zero-based). If ``x`` has rank (i.e, number of dimensions) ``N``, a valid ``axis`` must reside on the closed-interval ``[-N-1, N]``. If provided a negative ``axis``, the axis position at which to insert a singleton dimension must be computed as ``N + axis + 1``. Hence, if provided ``-1``, the resolved axis position must be ``N`` (i.e., a singleton dimension must be appended to the input array ``x``). If provided ``-N-1``, the resolved axis position must be ``0`` (i.e., a singleton dimension must be prepended to the input array ``x``). Returns ------- out: array - an expanded output array having the same data type as ``x``. + an expanded output array having the same data type as ``x``. Raises ------ IndexError - If provided an invalid ``axis`` position, an ``IndexError`` should be raised. + If provided an invalid ``axis`` position, an ``IndexError`` should be raised. """ @@ -8185,14 +8189,14 @@ class flip[TArray: Array](Protocol): Parameters ---------- x: array - input array. + input array. axis: Optional[Union[int, Tuple[int, ...]]] - axis (or axes) along which to flip. If ``axis`` is ``None``, the function must flip all input array axes. If ``axis`` is negative, the function must count from the last dimension. If provided more than one axis, the function must flip only the specified axes. Default: ``None``. + axis (or axes) along which to flip. If ``axis`` is ``None``, the function must flip all input array axes. If ``axis`` is negative, the function must count from the last dimension. If provided more than one axis, the function must flip only the specified axes. Default: ``None``. Returns ------- out: array - an output array having the same data type and shape as ``x`` and whose elements, relative to ``x``, are reordered. + an output array having the same data type and shape as ``x`` and whose elements, relative to ``x``, are reordered. """ @@ -8208,16 +8212,16 @@ class moveaxis[TArray: Array](Protocol): Parameters ---------- x: array - input array. + input array. source: Union[int, Tuple[int, ...]] - Axes to move. Provided axes must be unique. If ``x`` has rank (i.e, number of dimensions) ``N``, a valid axis must reside on the half-open interval ``[-N, N)``. + Axes to move. Provided axes must be unique. If ``x`` has rank (i.e, number of dimensions) ``N``, a valid axis must reside on the half-open interval ``[-N, N)``. destination: Union[int, Tuple[int, ...]] - indices defining the desired positions for each respective ``source`` axis index. Provided indices must be unique. If ``x`` has rank (i.e, number of dimensions) ``N``, a valid axis must reside on the half-open interval ``[-N, N)``. + indices defining the desired positions for each respective ``source`` axis index. Provided indices must be unique. If ``x`` has rank (i.e, number of dimensions) ``N``, a valid axis must reside on the half-open interval ``[-N, N)``. Returns ------- out: array - an array containing reordered axes. The returned array must have the same data type as ``x``. + an array containing reordered axes. The returned array must have the same data type as ``x``. Notes ----- @@ -8238,14 +8242,14 @@ class permute_dims[TArray: Array](Protocol): Parameters ---------- x: array - input array. + input array. axes: Tuple[int, ...] - tuple containing a permutation of ``(0, 1, ..., N-1)`` where ``N`` is the number of axes (dimensions) of ``x``. + tuple containing a permutation of ``(0, 1, ..., N-1)`` where ``N`` is the number of axes (dimensions) of ``x``. Returns ------- out: array - an array containing the axes permutation. The returned array must have the same data type as ``x``. + an array containing the axes permutation. The returned array must have the same data type as ``x``. """ @@ -8259,39 +8263,39 @@ class repeat[TArray: Array](Protocol): Repeats each element of an array a specified number of times on a per-element basis. .. admonition:: Data-dependent output shape - :class: important + :class: important - When ``repeats`` is an array, the shape of the output array for this function depends on the data values in the ``repeats`` array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) may find this function difficult to implement without knowing the values in ``repeats``. Accordingly, such libraries may choose to omit support for ``repeats`` arrays; however, conforming implementations must support providing a literal ``int``. See :ref:`data-dependent-output-shapes` section for more details. + When ``repeats`` is an array, the shape of the output array for this function depends on the data values in the ``repeats`` array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) may find this function difficult to implement without knowing the values in ``repeats``. Accordingly, such libraries may choose to omit support for ``repeats`` arrays; however, conforming implementations must support providing a literal ``int``. See :ref:`data-dependent-output-shapes` section for more details. Parameters ---------- x: array - input array containing elements to repeat. + input array containing elements to repeat. repeats: Union[int, array] - the number of repetitions for each element. + the number of repetitions for each element. - If ``axis`` is ``None``, let ``N = prod(x.shape)`` and + If ``axis`` is ``None``, let ``N = prod(x.shape)`` and - - if ``repeats`` is an array, ``repeats`` must be broadcast compatible with the shape ``(N,)`` (i.e., be a one-dimensional array having shape ``(1,)`` or ``(N,)``). - - if ``repeats`` is an integer, ``repeats`` must be broadcasted to the shape `(N,)`. + - if ``repeats`` is an array, ``repeats`` must be broadcast compatible with the shape ``(N,)`` (i.e., be a one-dimensional array having shape ``(1,)`` or ``(N,)``). + - if ``repeats`` is an integer, ``repeats`` must be broadcasted to the shape `(N,)`. - If ``axis`` is not ``None``, let ``M = x.shape[axis]`` and + If ``axis`` is not ``None``, let ``M = x.shape[axis]`` and - - if ``repeats`` is an array, ``repeats`` must be broadcast compatible with the shape ``(M,)`` (i.e., be a one-dimensional array having shape ``(1,)`` or ``(M,)``). - - if ``repeats`` is an integer, ``repeats`` must be broadcasted to the shape ``(M,)``. + - if ``repeats`` is an array, ``repeats`` must be broadcast compatible with the shape ``(M,)`` (i.e., be a one-dimensional array having shape ``(1,)`` or ``(M,)``). + - if ``repeats`` is an integer, ``repeats`` must be broadcasted to the shape ``(M,)``. - If ``repeats`` is an array, the array must have an integer data type. + If ``repeats`` is an array, the array must have an integer data type. - .. note:: - For specification-conforming array libraries supporting hardware acceleration, providing an array for ``repeats`` may cause device synchronization due to an unknown output shape. For those array libraries where synchronization concerns are applicable, conforming array libraries are advised to include a warning in their documentation regarding potential performance degradation when ``repeats`` is an array. + .. note:: + For specification-conforming array libraries supporting hardware acceleration, providing an array for ``repeats`` may cause device synchronization due to an unknown output shape. For those array libraries where synchronization concerns are applicable, conforming array libraries are advised to include a warning in their documentation regarding potential performance degradation when ``repeats`` is an array. axis: Optional[int] - the axis (dimension) along which to repeat elements. If ``axis`` is `None`, the function must flatten the input array ``x`` and then repeat elements of the flattened input array and return the result as a one-dimensional output array. A flattened input array must be flattened in row-major, C-style order. Default: ``None``. + the axis (dimension) along which to repeat elements. If ``axis`` is `None`, the function must flatten the input array ``x`` and then repeat elements of the flattened input array and return the result as a one-dimensional output array. A flattened input array must be flattened in row-major, C-style order. Default: ``None``. Returns ------- out: array - an output array containing repeated elements. The returned array must have the same data type as ``x``. If ``axis`` is ``None``, the returned array must be a one-dimensional array; otherwise, the returned array must have the same shape as ``x``, except for the axis (dimension) along which elements were repeated. + an output array containing repeated elements. The returned array must have the same data type as ``x``. If ``axis`` is ``None``, the returned array must be a one-dimensional array; otherwise, the returned array must have the same shape as ``x``, except for the axis (dimension) along which elements were repeated. Notes ----- @@ -8312,22 +8316,22 @@ class reshape[TArray: Array](Protocol): Parameters ---------- x: array - input array to reshape. + input array to reshape. shape: Tuple[int, ...] - a new shape compatible with the original shape. One shape dimension is allowed to be ``-1``. When a shape dimension is ``-1``, the corresponding output array shape dimension must be inferred from the length of the array and the remaining dimensions. + a new shape compatible with the original shape. One shape dimension is allowed to be ``-1``. When a shape dimension is ``-1``, the corresponding output array shape dimension must be inferred from the length of the array and the remaining dimensions. copy: Optional[bool] - whether or not to copy the input array. If ``True``, the function must always copy (see :ref:`copy-keyword-argument`). If ``False``, the function must never copy. If ``None``, the function must avoid copying, if possible, and may copy otherwise. Default: ``None``. + whether or not to copy the input array. If ``True``, the function must always copy (see :ref:`copy-keyword-argument`). If ``False``, the function must never copy. If ``None``, the function must avoid copying, if possible, and may copy otherwise. Default: ``None``. Returns ------- out: array - an output array having the same data type and elements as ``x``. + an output array having the same data type and elements as ``x``. Raises ------ ValueError - If ``copy=False`` and a copy would be necessary, a ``ValueError`` - should be raised. + If ``copy=False`` and a copy would be necessary, a ``ValueError`` + should be raised. """ @@ -8343,16 +8347,16 @@ class roll[TArray: Array](Protocol): Parameters ---------- x: array - input array. + input array. shift: Union[int, Tuple[int, ...]] - number of places by which the elements are shifted. If ``shift`` is a tuple, then ``axis`` must be a tuple of the same size, and each of the given axes must be shifted by the corresponding element in ``shift``. If ``shift`` is an ``int`` and ``axis`` a tuple, then the same ``shift`` must be used for all specified axes. If a shift is positive, then array elements must be shifted positively (toward larger indices) along the dimension of ``axis``. If a shift is negative, then array elements must be shifted negatively (toward smaller indices) along the dimension of ``axis``. + number of places by which the elements are shifted. If ``shift`` is a tuple, then ``axis`` must be a tuple of the same size, and each of the given axes must be shifted by the corresponding element in ``shift``. If ``shift`` is an ``int`` and ``axis`` a tuple, then the same ``shift`` must be used for all specified axes. If a shift is positive, then array elements must be shifted positively (toward larger indices) along the dimension of ``axis``. If a shift is negative, then array elements must be shifted negatively (toward smaller indices) along the dimension of ``axis``. axis: Optional[Union[int, Tuple[int, ...]]] - axis (or axes) along which elements to shift. If ``axis`` is ``None``, the array must be flattened, shifted, and then restored to its original shape. Default: ``None``. + axis (or axes) along which elements to shift. If ``axis`` is ``None``, the array must be flattened, shifted, and then restored to its original shape. Default: ``None``. Returns ------- out: array - an output array having the same data type as ``x`` and whose elements, relative to ``x``, are shifted. + an output array having the same data type as ``x`` and whose elements, relative to ``x``, are shifted. """ @@ -8368,20 +8372,20 @@ class squeeze[TArray: Array](Protocol): Parameters ---------- x: array - input array. + input array. axis: Union[int, Tuple[int, ...]] - axis (or axes) to squeeze. + axis (or axes) to squeeze. Returns ------- out: array - an output array having the same data type and elements as ``x``. + an output array having the same data type and elements as ``x``. Raises ------ ValueError - If a specified axis has a size greater than one (i.e., it is not a - singleton dimension), a ``ValueError`` should be raised. + If a specified axis has a size greater than one (i.e., it is not a + singleton dimension), a ``ValueError`` should be raised. """ @@ -8397,17 +8401,17 @@ class stack[TArray: Array](Protocol): Parameters ---------- arrays: Union[Tuple[array, ...], List[array]] - input arrays to join. Each array must have the same shape. + input arrays to join. Each array must have the same shape. axis: int - axis along which the arrays will be joined. Providing an ``axis`` specifies the index of the new axis in the dimensions of the result. For example, if ``axis`` is ``0``, the new axis will be the first dimension and the output array will have shape ``(N, A, B, C)``; if ``axis`` is ``1``, the new axis will be the second dimension and the output array will have shape ``(A, N, B, C)``; and, if ``axis`` is ``-1``, the new axis will be the last dimension and the output array will have shape ``(A, B, C, N)``. A valid ``axis`` must be on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If provided an ``axis`` outside of the required interval, the function must raise an exception. Default: ``0``. + axis along which the arrays will be joined. Providing an ``axis`` specifies the index of the new axis in the dimensions of the result. For example, if ``axis`` is ``0``, the new axis will be the first dimension and the output array will have shape ``(N, A, B, C)``; if ``axis`` is ``1``, the new axis will be the second dimension and the output array will have shape ``(A, N, B, C)``; and, if ``axis`` is ``-1``, the new axis will be the last dimension and the output array will have shape ``(A, B, C, N)``. A valid ``axis`` must be on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If provided an ``axis`` outside of the required interval, the function must raise an exception. Default: ``0``. Returns ------- out: array - an output array having rank ``N+1``, where ``N`` is the rank (number of dimensions) of ``x``. If the input arrays have different data types, normal :ref:`type-promotion` must apply. If the input arrays have the same data type, the output array must have the same data type as the input arrays. + an output array having rank ``N+1``, where ``N`` is the rank (number of dimensions) of ``x``. If the input arrays have different data types, normal :ref:`type-promotion` must apply. If the input arrays have the same data type, the output array must have the same data type as the input arrays. - .. note:: - This specification leaves type promotion between data type families (i.e., ``intxx`` and ``floatxx``) unspecified. + .. note:: + This specification leaves type promotion between data type families (i.e., ``intxx`` and ``floatxx``) unspecified. """ @@ -8423,20 +8427,20 @@ class tile[TArray: Array](Protocol): Parameters ---------- x: array - input array. + input array. repetitions: Tuple[int, ...] - number of repetitions along each axis (dimension). + number of repetitions along each axis (dimension). - Let ``N = len(x.shape)`` and ``M = len(repetitions)``. + Let ``N = len(x.shape)`` and ``M = len(repetitions)``. - If ``N > M``, the function must prepend ones until all axes (dimensions) are specified (e.g., if ``x`` has shape ``(8,6,4,2)`` and ``repetitions`` is the tuple ``(3,3)``, then ``repetitions`` must be treated as ``(1,1,3,3)``). + If ``N > M``, the function must prepend ones until all axes (dimensions) are specified (e.g., if ``x`` has shape ``(8,6,4,2)`` and ``repetitions`` is the tuple ``(3,3)``, then ``repetitions`` must be treated as ``(1,1,3,3)``). - If ``N < M``, the function must prepend singleton axes (dimensions) to ``x`` until ``x`` has as many axes (dimensions) as ``repetitions`` specifies (e.g., if ``x`` has shape ``(4,2)`` and ``repetitions`` is the tuple ``(3,3,3,3)``, then ``x`` must be treated as if it has shape ``(1,1,4,2)``). + If ``N < M``, the function must prepend singleton axes (dimensions) to ``x`` until ``x`` has as many axes (dimensions) as ``repetitions`` specifies (e.g., if ``x`` has shape ``(4,2)`` and ``repetitions`` is the tuple ``(3,3,3,3)``, then ``x`` must be treated as if it has shape ``(1,1,4,2)``). Returns ------- out: array - a tiled output array. The returned array must have the same data type as ``x`` and must have a rank (i.e., number of dimensions) equal to ``max(N, M)``. If ``S`` is the shape of the tiled array after prepending singleton dimensions (if necessary) and ``r`` is the tuple of repetitions after prepending ones (if necessary), then the number of elements along each axis (dimension) must satisfy ``S[i]*r[i]``, where ``i`` refers to the ``i`` th axis (dimension). + a tiled output array. The returned array must have the same data type as ``x`` and must have a rank (i.e., number of dimensions) equal to ``max(N, M)``. If ``S`` is the shape of the tiled array after prepending singleton dimensions (if necessary) and ``r`` is the tuple of repetitions after prepending ones (if necessary), then the number of elements along each axis (dimension) must satisfy ``S[i]*r[i]``, where ``i`` refers to the ``i`` th axis (dimension). Notes ----- @@ -8457,14 +8461,14 @@ class unstack[TArray: Array](Protocol): Parameters ---------- x: array - input array. + input array. axis: int - axis along which the array will be split. A valid ``axis`` must be on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If provided an ``axis`` outside of the required interval, the function must raise an exception. Default: ``0``. + axis along which the array will be split. A valid ``axis`` must be on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If provided an ``axis`` outside of the required interval, the function must raise an exception. Default: ``0``. Returns ------- out: Tuple[array, ...] - tuple of slices along the given dimension. All the arrays have the same shape. + tuple of slices along the given dimension. All the arrays have the same shape. Notes ----- @@ -8483,47 +8487,47 @@ class unique_all[TArray: Array](Protocol): Returns the unique elements of an input array ``x``, the first occurring indices for each unique element in ``x``, the indices from the set of unique elements that reconstruct ``x``, and the corresponding counts for each unique element in ``x``. .. admonition:: Data-dependent output shape - :class: important + :class: important - The shapes of two of the output arrays for this function depend on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) may find this function difficult to implement without knowing array values. Accordingly, such libraries may choose to omit this function. See :ref:`data-dependent-output-shapes` section for more details. + The shapes of two of the output arrays for this function depend on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) may find this function difficult to implement without knowing array values. Accordingly, such libraries may choose to omit this function. See :ref:`data-dependent-output-shapes` section for more details. .. note:: - Uniqueness should be determined based on value equality (see :func:`~array_api.equal`). For input arrays having floating-point data types, value-based equality implies the following behavior. + Uniqueness should be determined based on value equality (see :func:`~array_api.equal`). For input arrays having floating-point data types, value-based equality implies the following behavior. - - As ``nan`` values compare as ``False``, ``nan`` values should be considered distinct. - - As complex floating-point values having at least one ``nan`` component compare as ``False``, complex floating-point values having ``nan`` components should be considered distinct. - - As ``-0`` and ``+0`` compare as ``True``, signed zeros should not be considered distinct, and the corresponding unique element will be implementation-dependent (e.g., an implementation could choose to return ``-0`` if ``-0`` occurs before ``+0``). + - As ``nan`` values compare as ``False``, ``nan`` values should be considered distinct. + - As complex floating-point values having at least one ``nan`` component compare as ``False``, complex floating-point values having ``nan`` components should be considered distinct. + - As ``-0`` and ``+0`` compare as ``True``, signed zeros should not be considered distinct, and the corresponding unique element will be implementation-dependent (e.g., an implementation could choose to return ``-0`` if ``-0`` occurs before ``+0``). - As signed zeros are not distinct, using ``inverse_indices`` to reconstruct the input array is not guaranteed to return an array having the exact same values. + As signed zeros are not distinct, using ``inverse_indices`` to reconstruct the input array is not guaranteed to return an array having the exact same values. - Each ``nan`` value and each complex floating-point value having a ``nan`` component should have a count of one, while the counts for signed zeros should be aggregated as a single count. + Each ``nan`` value and each complex floating-point value having a ``nan`` component should have a count of one, while the counts for signed zeros should be aggregated as a single count. Parameters ---------- x: array - input array. If ``x`` has more than one dimension, the function must flatten ``x`` and return the unique elements of the flattened array. + input array. If ``x`` has more than one dimension, the function must flatten ``x`` and return the unique elements of the flattened array. Returns ------- out: Tuple[array, array, array, array] - a namedtuple ``(values, indices, inverse_indices, counts)`` whose + a namedtuple ``(values, indices, inverse_indices, counts)`` whose - - first element must have the field name ``values`` and must be a one-dimensional array containing the unique elements of ``x``. The array must have the same data type as ``x``. - - second element must have the field name ``indices`` and must be an array containing the indices (first occurrences) of a flattened ``x`` that result in ``values``. The array must have the same shape as ``values`` and must have the default array index data type. - - third element must have the field name ``inverse_indices`` and must be an array containing the indices of ``values`` that reconstruct ``x``. The array must have the same shape as ``x`` and must have the default array index data type. - - fourth element must have the field name ``counts`` and must be an array containing the number of times each unique element occurs in ``x``. The order of the returned counts must match the order of ``values``, such that a specific element in ``counts`` corresponds to the respective unique element in ``values``. The returned array must have same shape as ``values`` and must have the default array index data type. + - first element must have the field name ``values`` and must be a one-dimensional array containing the unique elements of ``x``. The array must have the same data type as ``x``. + - second element must have the field name ``indices`` and must be an array containing the indices (first occurrences) of a flattened ``x`` that result in ``values``. The array must have the same shape as ``values`` and must have the default array index data type. + - third element must have the field name ``inverse_indices`` and must be an array containing the indices of ``values`` that reconstruct ``x``. The array must have the same shape as ``x`` and must have the default array index data type. + - fourth element must have the field name ``counts`` and must be an array containing the number of times each unique element occurs in ``x``. The order of the returned counts must match the order of ``values``, such that a specific element in ``counts`` corresponds to the respective unique element in ``values``. The returned array must have same shape as ``values`` and must have the default array index data type. - .. note:: - The order of unique elements is not specified and may vary between implementations. + .. note:: + The order of unique elements is not specified and may vary between implementations. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. .. versionchanged:: 2023.12 - Clarified flattening behavior and required the order of ``counts`` match the order of ``values``. + Clarified flattening behavior and required the order of ``counts`` match the order of ``values``. """ @@ -8537,43 +8541,43 @@ class unique_counts[TArray: Array](Protocol): Returns the unique elements of an input array ``x`` and the corresponding counts for each unique element in ``x``. .. admonition:: Data-dependent output shape - :class: important + :class: important - The shapes of two of the output arrays for this function depend on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) may find this function difficult to implement without knowing array values. Accordingly, such libraries may choose to omit this function. See :ref:`data-dependent-output-shapes` section for more details. + The shapes of two of the output arrays for this function depend on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) may find this function difficult to implement without knowing array values. Accordingly, such libraries may choose to omit this function. See :ref:`data-dependent-output-shapes` section for more details. .. note:: - Uniqueness should be determined based on value equality (see :func:`~array_api.equal`). For input arrays having floating-point data types, value-based equality implies the following behavior. + Uniqueness should be determined based on value equality (see :func:`~array_api.equal`). For input arrays having floating-point data types, value-based equality implies the following behavior. - - As ``nan`` values compare as ``False``, ``nan`` values should be considered distinct. - - As complex floating-point values having at least one ``nan`` component compare as ``False``, complex floating-point values having ``nan`` components should be considered distinct. - - As ``-0`` and ``+0`` compare as ``True``, signed zeros should not be considered distinct, and the corresponding unique element will be implementation-dependent (e.g., an implementation could choose to return ``-0`` if ``-0`` occurs before ``+0``). + - As ``nan`` values compare as ``False``, ``nan`` values should be considered distinct. + - As complex floating-point values having at least one ``nan`` component compare as ``False``, complex floating-point values having ``nan`` components should be considered distinct. + - As ``-0`` and ``+0`` compare as ``True``, signed zeros should not be considered distinct, and the corresponding unique element will be implementation-dependent (e.g., an implementation could choose to return ``-0`` if ``-0`` occurs before ``+0``). - Each ``nan`` value and each complex floating-point value having a ``nan`` component should have a count of one, while the counts for signed zeros should be aggregated as a single count. + Each ``nan`` value and each complex floating-point value having a ``nan`` component should have a count of one, while the counts for signed zeros should be aggregated as a single count. Parameters ---------- x: array - input array. If ``x`` has more than one dimension, the function must flatten ``x`` and return the unique elements of the flattened array. + input array. If ``x`` has more than one dimension, the function must flatten ``x`` and return the unique elements of the flattened array. Returns ------- out: Tuple[array, array] - a namedtuple `(values, counts)` whose + a namedtuple `(values, counts)` whose - - first element must have the field name ``values`` and must be a one-dimensional array containing the unique elements of ``x``. The array must have the same data type as ``x``. - - second element must have the field name `counts` and must be an array containing the number of times each unique element occurs in ``x``. The order of the returned counts must match the order of ``values``, such that a specific element in ``counts`` corresponds to the respective unique element in ``values``. The returned array must have same shape as ``values`` and must have the default array index data type. + - first element must have the field name ``values`` and must be a one-dimensional array containing the unique elements of ``x``. The array must have the same data type as ``x``. + - second element must have the field name `counts` and must be an array containing the number of times each unique element occurs in ``x``. The order of the returned counts must match the order of ``values``, such that a specific element in ``counts`` corresponds to the respective unique element in ``values``. The returned array must have same shape as ``values`` and must have the default array index data type. - .. note:: - The order of unique elements is not specified and may vary between implementations. + .. note:: + The order of unique elements is not specified and may vary between implementations. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. .. versionchanged:: 2023.12 - Clarified flattening behavior and required the order of ``counts`` match the order of ``values``. + Clarified flattening behavior and required the order of ``counts`` match the order of ``values``. """ @@ -8587,43 +8591,43 @@ class unique_inverse[TArray: Array](Protocol): Returns the unique elements of an input array ``x`` and the indices from the set of unique elements that reconstruct ``x``. .. admonition:: Data-dependent output shape - :class: important + :class: important - The shapes of two of the output arrays for this function depend on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) may find this function difficult to implement without knowing array values. Accordingly, such libraries may choose to omit this function. See :ref:`data-dependent-output-shapes` section for more details. + The shapes of two of the output arrays for this function depend on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) may find this function difficult to implement without knowing array values. Accordingly, such libraries may choose to omit this function. See :ref:`data-dependent-output-shapes` section for more details. .. note:: - Uniqueness should be determined based on value equality (see :func:`~array_api.equal`). For input arrays having floating-point data types, value-based equality implies the following behavior. + Uniqueness should be determined based on value equality (see :func:`~array_api.equal`). For input arrays having floating-point data types, value-based equality implies the following behavior. - - As ``nan`` values compare as ``False``, ``nan`` values should be considered distinct. - - As complex floating-point values having at least one ``nan`` component compare as ``False``, complex floating-point values having ``nan`` components should be considered distinct. - - As ``-0`` and ``+0`` compare as ``True``, signed zeros should not be considered distinct, and the corresponding unique element will be implementation-dependent (e.g., an implementation could choose to return ``-0`` if ``-0`` occurs before ``+0``). + - As ``nan`` values compare as ``False``, ``nan`` values should be considered distinct. + - As complex floating-point values having at least one ``nan`` component compare as ``False``, complex floating-point values having ``nan`` components should be considered distinct. + - As ``-0`` and ``+0`` compare as ``True``, signed zeros should not be considered distinct, and the corresponding unique element will be implementation-dependent (e.g., an implementation could choose to return ``-0`` if ``-0`` occurs before ``+0``). - As signed zeros are not distinct, using ``inverse_indices`` to reconstruct the input array is not guaranteed to return an array having the exact same values. + As signed zeros are not distinct, using ``inverse_indices`` to reconstruct the input array is not guaranteed to return an array having the exact same values. Parameters ---------- x: array - input array. If ``x`` has more than one dimension, the function must flatten ``x`` and return the unique elements of the flattened array. + input array. If ``x`` has more than one dimension, the function must flatten ``x`` and return the unique elements of the flattened array. Returns ------- out: Tuple[array, array] - a namedtuple ``(values, inverse_indices)`` whose + a namedtuple ``(values, inverse_indices)`` whose - - first element must have the field name ``values`` and must be a one-dimensional array containing the unique elements of ``x``. The array must have the same data type as ``x``. - - second element must have the field name ``inverse_indices`` and must be an array containing the indices of ``values`` that reconstruct ``x``. The array must have the same shape as ``x`` and have the default array index data type. + - first element must have the field name ``values`` and must be a one-dimensional array containing the unique elements of ``x``. The array must have the same data type as ``x``. + - second element must have the field name ``inverse_indices`` and must be an array containing the indices of ``values`` that reconstruct ``x``. The array must have the same shape as ``x`` and have the default array index data type. - .. note:: - The order of unique elements is not specified and may vary between implementations. + .. note:: + The order of unique elements is not specified and may vary between implementations. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. .. versionchanged:: 2023.12 - Clarified flattening behavior. + Clarified flattening behavior. """ @@ -8637,38 +8641,38 @@ class unique_values[TArray: Array](Protocol): Returns the unique elements of an input array ``x``. .. admonition:: Data-dependent output shape - :class: important + :class: important - The shapes of two of the output arrays for this function depend on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) may find this function difficult to implement without knowing array values. Accordingly, such libraries may choose to omit this function. See :ref:`data-dependent-output-shapes` section for more details. + The shapes of two of the output arrays for this function depend on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) may find this function difficult to implement without knowing array values. Accordingly, such libraries may choose to omit this function. See :ref:`data-dependent-output-shapes` section for more details. .. note:: - Uniqueness should be determined based on value equality (see :func:`~array_api.equal`). For input arrays having floating-point data types, value-based equality implies the following behavior. + Uniqueness should be determined based on value equality (see :func:`~array_api.equal`). For input arrays having floating-point data types, value-based equality implies the following behavior. - - As ``nan`` values compare as ``False``, ``nan`` values should be considered distinct. - - As complex floating-point values having at least one ``nan`` component compare as ``False``, complex floating-point values having ``nan`` components should be considered distinct. - - As ``-0`` and ``+0`` compare as ``True``, signed zeros should not be considered distinct, and the corresponding unique element will be implementation-dependent (e.g., an implementation could choose to return ``-0`` if ``-0`` occurs before ``+0``). + - As ``nan`` values compare as ``False``, ``nan`` values should be considered distinct. + - As complex floating-point values having at least one ``nan`` component compare as ``False``, complex floating-point values having ``nan`` components should be considered distinct. + - As ``-0`` and ``+0`` compare as ``True``, signed zeros should not be considered distinct, and the corresponding unique element will be implementation-dependent (e.g., an implementation could choose to return ``-0`` if ``-0`` occurs before ``+0``). Parameters ---------- x: array - input array. If ``x`` has more than one dimension, the function must flatten ``x`` and return the unique elements of the flattened array. + input array. If ``x`` has more than one dimension, the function must flatten ``x`` and return the unique elements of the flattened array. Returns ------- out: array - a one-dimensional array containing the set of unique elements in ``x``. The returned array must have the same data type as ``x``. + a one-dimensional array containing the set of unique elements in ``x``. The returned array must have the same data type as ``x``. - .. note:: - The order of unique elements is not specified and may vary between implementations. + .. note:: + The order of unique elements is not specified and may vary between implementations. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. .. versionchanged:: 2023.12 - Required that the output array must be one-dimensional. + Required that the output array must be one-dimensional. """ @@ -8677,7 +8681,7 @@ def __call__(self, x: TArray, /) -> TArray: ... @runtime_checkable -class ArrayNamespace[TCapabilities, TDatatypes, TDefaultdatatypes, TSupportsbufferprotocol, TArray: Array, TDevice, TDtype](Protocol): +class ArrayNamespace[TArray: Array, TCapabilities, TDatatypes, TDefaultdatatypes, TDevice, TDtype](Protocol): astype: astype[TArray, TDevice, TDtype] "Copies an array to a specified data type irrespective of :ref:`type-promotion` rules.\n\n.. note::\n Casting floating-point ``NaN`` and ``infinity`` values to integral data types is not specified and is implementation-dependent.\n\n.. note::\n Casting a complex floating-point array to a real-valued data type should not be permitted.\n\n Historically, when casting a complex floating-point array to a real-valued data type, libraries such as NumPy have discarded imaginary components such that, for a complex floating-point array ``x``, ``astype(x)`` equals ``astype(real(x))``). This behavior is considered problematic as the choice to discard the imaginary component is arbitrary and introduces more than one way to achieve the same outcome (i.e., for a complex floating-point array ``x``, ``astype(x)`` and ``astype(real(x))`` versus only ``astype(imag(x))``). Instead, in order to avoid ambiguity and to promote clarity, this specification requires that array API consumers explicitly express which component should be cast to a specified real-valued data type.\n\n.. note::\n When casting a boolean input array to a real-valued data type, a value of ``True`` must cast to a real-valued number equal to ``1``, and a value of ``False`` must cast to a real-valued number equal to ``0``.\n\n When casting a boolean input array to a complex floating-point data type, a value of ``True`` must cast to a complex number equal to ``1 + 0j``, and a value of ``False`` must cast to a complex number equal to ``0 + 0j``.\n\n.. note::\n When casting a real-valued input array to ``bool``, a value of ``0`` must cast to ``False``, and a non-zero value must cast to ``True``.\n\n When casting a complex floating-point array to ``bool``, a value of ``0 + 0j`` must cast to ``False``, and all other values must cast to ``True``.\n\nParameters\n----------\nx: array\n array to cast.\ndtype: dtype\n desired data type.\ncopy: bool\n specifies whether to copy an array when the specified ``dtype`` matches the data type of the input array ``x``. If ``True``, a newly allocated array must always be returned (see :ref:`copy-keyword-argument`). If ``False`` and the specified ``dtype`` matches the data type of the input array, the input array must be returned; otherwise, a newly allocated array must be returned. Default: ``True``.\ndevice: Optional[device]\n device on which to place the returned array. If ``device`` is ``None``, the output array device must be inferred from ``x``. Default: ``None``.\n\nReturns\n-------\nout: array\n an array having the specified data type. The returned array must have the same shape as ``x``.\n\nNotes\n-----\n\n.. versionchanged:: 2022.12\n Added complex data type support.\n\n.. versionchanged:: 2023.12\n Added device keyword argument support." can_cast: can_cast[TArray, TDtype] @@ -8710,7 +8714,7 @@ class ArrayNamespace[TCapabilities, TDatatypes, TDefaultdatatypes, TSupportsbuff "Calculates the variance of the input array ``x``.\n\nParameters\n----------\nx: array\n input array. Should have a real-valued floating-point data type.\naxis: Optional[Union[int, Tuple[int, ...]]]\n axis or axes along which variances must be computed. By default, the variance must be computed over the entire array. If a tuple of integers, variances must be computed over multiple axes. Default: ``None``.\ncorrection: Union[int, float]\n degrees of freedom adjustment. Setting this parameter to a value other than ``0`` has the effect of adjusting the divisor during the calculation of the variance according to ``N-c`` where ``N`` corresponds to the total number of elements over which the variance is computed and ``c`` corresponds to the provided degrees of freedom adjustment. When computing the variance of a population, setting this parameter to ``0`` is the standard choice (i.e., the provided array contains data constituting an entire population). When computing the unbiased sample variance, setting this parameter to ``1`` is the standard choice (i.e., the provided array contains data sampled from a larger population; this is commonly referred to as Bessel's correction). Default: ``0``.\nkeepdims: bool\n if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``.\n\nReturns\n-------\nout: array\n if the variance was computed over the entire array, a zero-dimensional array containing the variance; otherwise, a non-zero-dimensional array containing the variances. The returned array must have the same data type as ``x``.\n\n\n.. note::\n While this specification recommends that this function only accept input arrays having a real-valued floating-point data type, specification-compliant array libraries may choose to accept input arrays having an integer data type. While mixed data type promotion is implementation-defined, if the input array ``x`` has an integer data type, the returned array must have the default real-valued floating-point data type.\n\nNotes\n-----\n\n**Special Cases**\n\nLet ``N`` equal the number of elements over which to compute the variance.\n\n- If ``N - correction`` is less than or equal to ``0``, the variance is ``NaN``.\n- If ``x_i`` is ``NaN``, the variance is ``NaN`` (i.e., ``NaN`` values propagate)." arange: arange[TArray, TDevice, TDtype] "Returns evenly spaced values within the half-open interval ``[start, stop)`` as a one-dimensional array.\n\nParameters\n----------\nstart: Union[int, float]\n if ``stop`` is specified, the start of interval (inclusive); otherwise, the end of the interval (exclusive). If ``stop`` is not specified, the default starting value is ``0``.\nstop: Optional[Union[int, float]]\n the end of the interval. Default: ``None``.\nstep: Union[int, float]\n the distance between two adjacent elements (``out[i+1] - out[i]``). Must not be ``0``; may be negative, this results in an empty array if ``stop >= start``. Default: ``1``.\ndtype: Optional[dtype]\n output array data type. If ``dtype`` is ``None``, the output array data type must be inferred from ``start``, ``stop`` and ``step``. If those are all integers, the output array dtype must be the default integer dtype; if one or more have type ``float``, then the output array dtype must be the default real-valued floating-point data type. Default: ``None``.\ndevice: Optional[device]\n device on which to place the created array. Default: ``None``.\n\n\n.. note::\n This function cannot guarantee that the interval does not include the ``stop`` value in those cases where ``step`` is not an integer and floating-point rounding errors affect the length of the output array.\n\nReturns\n-------\nout: array\n a one-dimensional array containing evenly spaced values. The length of the output array must be ``ceil((stop-start)/step)`` if ``stop - start`` and ``step`` have the same sign, and length ``0`` otherwise." - asarray: asarray[TSupportsbufferprotocol, TArray, TDevice, TDtype] + asarray: asarray[TArray, TDevice, TDtype] "Convert the input to an array.\n\nParameters\n----------\nobj: Union[array, bool, int, float, complex, NestedSequence[bool | int | float | complex], SupportsBufferProtocol]\n object to be converted to an array. May be a Python scalar, a (possibly nested) sequence of Python scalars, or an object supporting the Python buffer protocol.\n\n .. admonition:: Tip\n :class: important\n\n An object supporting the buffer protocol can be turned into a memoryview through ``memoryview(obj)``.\n\ndtype: Optional[dtype]\n output array data type. If ``dtype`` is ``None``, the output array data type must be inferred from the data type(s) in ``obj``. If all input values are Python scalars, then, in order of precedence,\n\n - if all values are of type ``bool``, the output data type must be ``bool``.\n - if all values are of type ``int`` or are a mixture of ``bool`` and ``int``, the output data type must be the default integer data type.\n - if one or more values are ``complex`` numbers, the output data type must be the default complex floating-point data type.\n - if one or more values are ``float``\\s, the output data type must be the default real-valued floating-point data type.\n\n Default: ``None``.\n\n .. admonition:: Note\n :class: note\n\n If ``dtype`` is not ``None``, then array conversions should obey :ref:`type-promotion` rules. Conversions not specified according to :ref:`type-promotion` rules may or may not be permitted by a conforming array library. To perform an explicit cast, use :func:`array_api.astype`.\n\n .. note::\n If an input value exceeds the precision of the resolved output array data type, behavior is left unspecified and, thus, implementation-defined.\n\ndevice: Optional[device]\n device on which to place the created array. If ``device`` is ``None`` and ``obj`` is an array, the output array device must be inferred from ``obj``. Default: ``None``.\ncopy: Optional[bool]\n boolean indicating whether or not to copy the input. If ``True``, the function must always copy (see :ref:`copy-keyword-argument`). If ``False``, the function must never copy for input which supports the buffer protocol and must raise a ``ValueError`` in case a copy would be necessary. If ``None``, the function must reuse existing memory buffer if possible and copy otherwise. Default: ``None``.\n\nReturns\n-------\nout: array\n an array containing the data from ``obj``.\n\nNotes\n-----\n\n.. versionchanged:: 2022.12\n Added complex data type support." empty: empty[TArray, TDevice, TDtype] "Returns an uninitialized array having a specified `shape`.\n\nParameters\n----------\nshape: Union[int, Tuple[int, ...]]\n output array shape.\ndtype: Optional[dtype]\n output array data type. If ``dtype`` is ``None``, the output array data type must be the default real-valued floating-point data type. Default: ``None``.\ndevice: Optional[device]\n device on which to place the created array. Default: ``None``.\n\nReturns\n-------\nout: array\n an array containing uninitialized data." @@ -8896,7 +8900,7 @@ class ArrayNamespace[TCapabilities, TDatatypes, TDefaultdatatypes, TSupportsbuff "Tests whether any input array element evaluates to ``True`` along a specified axis.\n\n.. note::\n Positive infinity, negative infinity, and NaN must evaluate to ``True``.\n\n.. note::\n If ``x`` has a complex floating-point data type, elements having a non-zero component (real or imaginary) must evaluate to ``True``.\n\n.. note::\n If ``x`` is an empty array or the size of the axis (dimension) along which to evaluate elements is zero, the test result must be ``False``.\n\nParameters\n----------\nx: array\n input array.\naxis: Optional[Union[int, Tuple[int, ...]]]\n axis or axes along which to perform a logical OR reduction. By default, a logical OR reduction must be performed over the entire array. If a tuple of integers, logical OR reductions must be performed over multiple axes. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to perform a reduction by counting backward from the last dimension (where ``-1`` refers to the last dimension). If provided an invalid ``axis``, the function must raise an exception. Default: ``None``.\nkeepdims: bool\n If ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``.\n\nReturns\n-------\nout: array\n if a logical OR reduction was performed over the entire array, the returned array must be a zero-dimensional array containing the test result; otherwise, the returned array must be a non-zero-dimensional array containing the test results. The returned array must have a data type of ``bool``.\n\nNotes\n-----\n\n.. versionchanged:: 2022.12\n Added complex data type support." diff: diff[TArray,] "Calculates the n-th discrete forward difference along a specified axis.\n\nParameters\n----------\nx: array\n input array. Should have a numeric data type.\naxis: int\n axis along which to compute differences. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to compute differences by counting backward from the last dimension (where ``-1`` refers to the last dimension). If provided an invalid ``axis``, the function must raise an exception. Default: ``-1``.\nn: int\n number of times to recursively compute differences. Default: ``1``.\nprepend: Optional[array]\n values to prepend to a specified axis prior to computing differences. Must have the same shape as ``x``, except for the axis specified by ``axis`` which may have any size. Should have the same data type as ``x``. Default: ``None``.\nappend: Optional[array]\n values to append to a specified axis prior to computing differences. Must have the same shape as ``x``, except for the axis specified by ``axis`` which may have any size. Should have the same data type as ``x``. Default: ``None``.\n\nReturns\n-------\nout: array\n an array containing the n-th differences. Should have the same data type as ``x``. Must have the same shape as ``x``, except for the axis specified by ``axis`` which must have a size determined as follows:\n\n - Let ``M`` be the number of elements along an axis specified by ``axis``.\n - Let ``N1`` be the number of prepended values along an axis specified by ``axis``.\n - Let ``N2`` be the number of appended values along an axis specified by ``axis``.\n - The final size of the axis specified by ``axis`` must be ``M + N1 + N2 - n``.\n\nNotes\n-----\n\n- The first-order differences are given by ``out[i] = x[i+1] - x[i]`` along a specified axis. Higher-order differences must be calculated recursively (e.g., by calling ``diff(out, axis=axis, n=n-1)``).\n- If a conforming implementation chooses to support ``prepend`` and ``append`` arrays which have a different data type than ``x``, behavior is unspecified and thus implementation-defined. Implementations may choose to type promote (:ref:`type-promotion`), cast ``prepend`` and/or ``append`` to the same data type as ``x``, or raise an exception.\n\n.. versionadded:: 2024.12" - __array_namespace_info__: __array_namespace_info__[TCapabilities, TDatatypes, TDefaultdatatypes, TArray, TDevice, TDtype] + __array_namespace_info__: __array_namespace_info__[TArray, TCapabilities, TDatatypes, TDefaultdatatypes, TDevice, TDtype] "Returns a namespace with Array API namespace inspection utilities.\n\nSee :ref:`inspection` for a list of inspection APIs.\n\nReturns\n-------\nout: Info\n An object containing Array API namespace inspection utilities.\n\nNotes\n-----\n\nThe returned object may be either a namespace or a class, so long as an Array API user can access inspection utilities as follows:\n\n::\n\n info = xp.__array_namespace_info__()\n info.capabilities()\n info.devices()\n info.dtypes()\n info.default_dtypes()\n # ...\n\n.. versionadded: 2023.12" take: take[TArray,] "Returns elements of an array along an axis.\n\nParameters\n----------\nx: array\n input array. Should have one or more dimensions (axes).\nindices: array\n array indices. The array must be one-dimensional and have an integer data type. If an index is negative, the function must determine the element to select along a specified axis (dimension) by counting from the last element (where ``-1`` refers to the last element).\naxis: Optional[int]\n axis over which to select values. If ``axis`` is negative, the function must determine the axis along which to select values by counting from the last dimension (where ``-1`` refers to the last dimension).\n\n If ``x`` is a one-dimensional array, providing an ``axis`` is optional; however, if ``x`` has more than one dimension, providing an ``axis`` is required.\n\nReturns\n-------\nout: array\n an array having the same data type as ``x``. The output array must have the same rank (i.e., number of dimensions) as ``x`` and must have the same shape as ``x``, except for the axis specified by ``axis`` whose size must equal the number of elements in ``indices``.\n\nNotes\n-----\n\n- Conceptually, ``take(x, indices, axis=3)`` is equivalent to ``x[:,:,:,indices,...]``; however, explicit indexing via arrays of indices is not currently supported in this specification due to concerns regarding ``__setitem__`` and array mutation semantics.\n- This specification does not require bounds checking. The behavior for out-of-bounds indices is left unspecified.\n- When ``x`` is a zero-dimensional array, behavior is unspecified and thus implementation-defined.\n\n.. versionadded:: 2022.12\n\n.. versionchanged:: 2023.12\n Out-of-bounds behavior is explicitly left unspecified.\n\n.. versionchanged:: 2024.12\n Behavior when provided a zero-dimensional input array is explicitly left unspecified.\n\n.. versionchanged:: 2024.12\n Clarified support for negative indices." @@ -8938,15 +8942,15 @@ class ArrayNamespace[TCapabilities, TDatatypes, TDefaultdatatypes, TSupportsbuff "Constructs an array by tiling an input array.\n\nParameters\n----------\nx: array\n input array.\nrepetitions: Tuple[int, ...]\n number of repetitions along each axis (dimension).\n\n Let ``N = len(x.shape)`` and ``M = len(repetitions)``.\n\n If ``N > M``, the function must prepend ones until all axes (dimensions) are specified (e.g., if ``x`` has shape ``(8,6,4,2)`` and ``repetitions`` is the tuple ``(3,3)``, then ``repetitions`` must be treated as ``(1,1,3,3)``).\n\n If ``N < M``, the function must prepend singleton axes (dimensions) to ``x`` until ``x`` has as many axes (dimensions) as ``repetitions`` specifies (e.g., if ``x`` has shape ``(4,2)`` and ``repetitions`` is the tuple ``(3,3,3,3)``, then ``x`` must be treated as if it has shape ``(1,1,4,2)``).\n\nReturns\n-------\nout: array\n a tiled output array. The returned array must have the same data type as ``x`` and must have a rank (i.e., number of dimensions) equal to ``max(N, M)``. If ``S`` is the shape of the tiled array after prepending singleton dimensions (if necessary) and ``r`` is the tuple of repetitions after prepending ones (if necessary), then the number of elements along each axis (dimension) must satisfy ``S[i]*r[i]``, where ``i`` refers to the ``i`` th axis (dimension).\n\nNotes\n-----\n\n.. versionadded:: 2023.12" unstack: unstack[TArray,] "Splits an array into a sequence of arrays along the given axis.\n\nParameters\n----------\nx: array\n input array.\naxis: int\n axis along which the array will be split. A valid ``axis`` must be on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If provided an ``axis`` outside of the required interval, the function must raise an exception. Default: ``0``.\n\nReturns\n-------\nout: Tuple[array, ...]\n tuple of slices along the given dimension. All the arrays have the same shape.\n\nNotes\n-----\n\n.. versionadded:: 2023.12" - e: float + e: TArray "\nIEEE 754 floating-point representation of Euler's constant.\n\n``e = 2.71828182845904523536028747135266249775724709369995...``\n" - inf: float + inf: TArray "\nIEEE 754 floating-point representation of (positive) infinity.\n" - nan: float + nan: TArray "\nIEEE 754 floating-point representation of Not a Number (``NaN``).\n" - newaxis: float + newaxis: TArray "\nAn alias for ``None`` which is useful for indexing arrays.\n" - pi: float + pi: TArray "\nIEEE 754 floating-point representation of the mathematical constant ``π``.\n\n``pi = 3.1415926535897932384626433...``\n" unique_all: unique_all[TArray,] "Returns the unique elements of an input array ``x``, the first occurring indices for each unique element in ``x``, the indices from the set of unique elements that reconstruct ``x``, and the corresponding counts for each unique element in ``x``.\n\n.. admonition:: Data-dependent output shape\n :class: important\n\n The shapes of two of the output arrays for this function depend on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) may find this function difficult to implement without knowing array values. Accordingly, such libraries may choose to omit this function. See :ref:`data-dependent-output-shapes` section for more details.\n\n.. note::\n Uniqueness should be determined based on value equality (see :func:`~array_api.equal`). For input arrays having floating-point data types, value-based equality implies the following behavior.\n\n - As ``nan`` values compare as ``False``, ``nan`` values should be considered distinct.\n - As complex floating-point values having at least one ``nan`` component compare as ``False``, complex floating-point values having ``nan`` components should be considered distinct.\n - As ``-0`` and ``+0`` compare as ``True``, signed zeros should not be considered distinct, and the corresponding unique element will be implementation-dependent (e.g., an implementation could choose to return ``-0`` if ``-0`` occurs before ``+0``).\n\n As signed zeros are not distinct, using ``inverse_indices`` to reconstruct the input array is not guaranteed to return an array having the exact same values.\n\n Each ``nan`` value and each complex floating-point value having a ``nan`` component should have a count of one, while the counts for signed zeros should be aggregated as a single count.\n\nParameters\n----------\nx: array\n input array. If ``x`` has more than one dimension, the function must flatten ``x`` and return the unique elements of the flattened array.\n\nReturns\n-------\nout: Tuple[array, array, array, array]\n a namedtuple ``(values, indices, inverse_indices, counts)`` whose\n\n - first element must have the field name ``values`` and must be a one-dimensional array containing the unique elements of ``x``. The array must have the same data type as ``x``.\n - second element must have the field name ``indices`` and must be an array containing the indices (first occurrences) of a flattened ``x`` that result in ``values``. The array must have the same shape as ``values`` and must have the default array index data type.\n - third element must have the field name ``inverse_indices`` and must be an array containing the indices of ``values`` that reconstruct ``x``. The array must have the same shape as ``x`` and must have the default array index data type.\n - fourth element must have the field name ``counts`` and must be an array containing the number of times each unique element occurs in ``x``. The order of the returned counts must match the order of ``values``, such that a specific element in ``counts`` corresponds to the respective unique element in ``values``. The returned array must have same shape as ``values`` and must have the default array index data type.\n\n .. note::\n The order of unique elements is not specified and may vary between implementations.\n\nNotes\n-----\n\n.. versionchanged:: 2022.12\n Added complex data type support.\n\n.. versionchanged:: 2023.12\n Clarified flattening behavior and required the order of ``counts`` match the order of ``values``." @@ -8956,19 +8960,19 @@ class ArrayNamespace[TCapabilities, TDatatypes, TDefaultdatatypes, TSupportsbuff "Returns the unique elements of an input array ``x`` and the indices from the set of unique elements that reconstruct ``x``.\n\n.. admonition:: Data-dependent output shape\n :class: important\n\n The shapes of two of the output arrays for this function depend on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) may find this function difficult to implement without knowing array values. Accordingly, such libraries may choose to omit this function. See :ref:`data-dependent-output-shapes` section for more details.\n\n.. note::\n Uniqueness should be determined based on value equality (see :func:`~array_api.equal`). For input arrays having floating-point data types, value-based equality implies the following behavior.\n\n - As ``nan`` values compare as ``False``, ``nan`` values should be considered distinct.\n - As complex floating-point values having at least one ``nan`` component compare as ``False``, complex floating-point values having ``nan`` components should be considered distinct.\n - As ``-0`` and ``+0`` compare as ``True``, signed zeros should not be considered distinct, and the corresponding unique element will be implementation-dependent (e.g., an implementation could choose to return ``-0`` if ``-0`` occurs before ``+0``).\n\n As signed zeros are not distinct, using ``inverse_indices`` to reconstruct the input array is not guaranteed to return an array having the exact same values.\n\nParameters\n----------\nx: array\n input array. If ``x`` has more than one dimension, the function must flatten ``x`` and return the unique elements of the flattened array.\n\nReturns\n-------\nout: Tuple[array, array]\n a namedtuple ``(values, inverse_indices)`` whose\n\n - first element must have the field name ``values`` and must be a one-dimensional array containing the unique elements of ``x``. The array must have the same data type as ``x``.\n - second element must have the field name ``inverse_indices`` and must be an array containing the indices of ``values`` that reconstruct ``x``. The array must have the same shape as ``x`` and have the default array index data type.\n\n .. note::\n The order of unique elements is not specified and may vary between implementations.\n\nNotes\n-----\n\n.. versionchanged:: 2022.12\n Added complex data type support.\n\n.. versionchanged:: 2023.12\n Clarified flattening behavior." unique_values: unique_values[TArray,] "Returns the unique elements of an input array ``x``.\n\n.. admonition:: Data-dependent output shape\n :class: important\n\n The shapes of two of the output arrays for this function depend on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) may find this function difficult to implement without knowing array values. Accordingly, such libraries may choose to omit this function. See :ref:`data-dependent-output-shapes` section for more details.\n\n.. note::\n Uniqueness should be determined based on value equality (see :func:`~array_api.equal`). For input arrays having floating-point data types, value-based equality implies the following behavior.\n\n - As ``nan`` values compare as ``False``, ``nan`` values should be considered distinct.\n - As complex floating-point values having at least one ``nan`` component compare as ``False``, complex floating-point values having ``nan`` components should be considered distinct.\n - As ``-0`` and ``+0`` compare as ``True``, signed zeros should not be considered distinct, and the corresponding unique element will be implementation-dependent (e.g., an implementation could choose to return ``-0`` if ``-0`` occurs before ``+0``).\n\nParameters\n----------\nx: array\n input array. If ``x`` has more than one dimension, the function must flatten ``x`` and return the unique elements of the flattened array.\n\nReturns\n-------\nout: array\n a one-dimensional array containing the set of unique elements in ``x``. The returned array must have the same data type as ``x``.\n\n .. note::\n The order of unique elements is not specified and may vary between implementations.\n\nNotes\n-----\n\n.. versionchanged:: 2022.12\n Added complex data type support.\n\n.. versionchanged:: 2023.12\n Required that the output array must be one-dimensional." - bool: float - complex128: float - complex64: float - float32: float - float64: float - int16: float - int32: float - int64: float - int8: float - uint16: float - uint32: float - uint64: float - uint8: float + bool: TDtype + complex128: TDtype + complex64: TDtype + float32: TDtype + float64: TDtype + int16: TDtype + int32: TDtype + int64: TDtype + int8: TDtype + uint16: TDtype + uint32: TDtype + uint64: TDtype + uint8: TDtype Device: TDevice @@ -9055,6 +9059,6 @@ class FftNamespace[TArray: Array, TDevice, TDtype](Protocol): @runtime_checkable -class ArrayNamespaceFull[TCapabilities, TDatatypes, TDefaultdatatypes, TSupportsbufferprotocol, TArray: Array, TDevice, TDtype](ArrayNamespace[TCapabilities, TDatatypes, TDefaultdatatypes, TSupportsbufferprotocol, TArray, TDevice, TDtype], Protocol): +class ArrayNamespaceFull[TArray: Array, TCapabilities, TDatatypes, TDefaultdatatypes, TDevice, TDtype](ArrayNamespace[TArray, TCapabilities, TDatatypes, TDefaultdatatypes, TDevice, TDtype], Protocol): linalg: LinalgNamespace[TArray, TDtype] fft: FftNamespace[TArray, TDevice, TDtype] diff --git a/src/array_api/__init__.py b/src/array_api/__init__.py index 6849410..cff0d62 100644 --- a/src/array_api/__init__.py +++ b/src/array_api/__init__.py @@ -1 +1 @@ -__version__ = "1.1.0" +__version__ = "1.1.1-rc.1" diff --git a/src/array_api/_draft.py b/src/array_api/_draft.py index 95bf18d..818eb75 100644 --- a/src/array_api/_draft.py +++ b/src/array_api/_draft.py @@ -1,8 +1,10 @@ from __future__ import annotations from abc import abstractmethod +from collections.abc import Buffer as SupportsBufferProtocol from collections.abc import Sequence from enum import Enum +from types import EllipsisType as ellipsis from typing import ( Any, Literal, @@ -10,11 +12,13 @@ runtime_checkable, ) +from typing_extensions import CapsuleType as PyCapsule + inf = float("inf") @runtime_checkable -class Info[TCapabilities, TDatatypes, TDefaultdatatypes, TArray: Array, TDevice, TDtype](Protocol): +class Info[TArray: Array, TCapabilities, TDatatypes, TDefaultdatatypes, TDevice, TDtype](Protocol): """Namespace returned by `__array_namespace_info__`.""" def capabilities(self) -> TCapabilities: ... @@ -58,13 +62,13 @@ class finfo_object[TDtype](Protocol): @runtime_checkable -class Array[TPycapsule, TArray: Array, TDevice, TDtype, TEllipsis](Protocol): - def __init__(self: TArray) -> None: +class Array[TArray: Array, TDevice, TDtype](Protocol): + def __init__(self) -> None: """Initialize the attributes for the array object class.""" ... @property - def dtype(self: TArray) -> TDtype: + def dtype(self) -> TDtype: """ Data type of the array elements. @@ -77,7 +81,7 @@ def dtype(self: TArray) -> TDtype: ... @property - def device(self: TArray) -> TDevice: + def device(self) -> TDevice: """ Hardware device the array data resides on. @@ -90,7 +94,7 @@ def device(self: TArray) -> TDevice: ... @property - def mT(self: TArray) -> TArray: + def mT(self) -> TArray: """ Transpose of a matrix (or a stack of matrices). @@ -105,7 +109,7 @@ def mT(self: TArray) -> TArray: ... @property - def ndim(self: TArray) -> int: + def ndim(self) -> int: """ Number of array dimensions (axes). @@ -118,7 +122,7 @@ def ndim(self: TArray) -> int: ... @property - def shape(self: TArray) -> tuple[int | None, ...]: + def shape(self) -> tuple[int | None, ...]: """ Array dimensions. @@ -138,7 +142,7 @@ def shape(self: TArray) -> tuple[int | None, ...]: ... @property - def size(self: TArray) -> int | None: + def size(self) -> int | None: """ Number of elements in an array. @@ -158,7 +162,7 @@ def size(self: TArray) -> int | None: ... @property - def T(self: TArray) -> TArray: + def T(self) -> TArray: """ Transpose of the array. @@ -176,13 +180,93 @@ def T(self: TArray) -> TArray: """ ... - def __array_namespace__(self: TArray, /, *, api_version: str | None = None) -> Any: + def __abs__(self, /) -> TArray: + """ + Calculates the absolute value for each element of an array instance. + + For real-valued input arrays, the element-wise result has the same magnitude as the respective element in ``x`` but has positive sign. + + .. note:: + For signed integer data types, the absolute value of the minimum representable integer is implementation-dependent. + + Parameters + ---------- + self + array instance. Should have a numeric data type. + + Returns + ------- + out: array + an array containing the element-wise absolute value. If ``self`` has a real-valued data type, the returned array must have the same data type as ``self``. If ``self`` has a complex floating-point data type, the returned arrayed must have a real-valued floating-point data type whose precision matches the precision of ``self`` (e.g., if ``self`` is ``complex128``, then the returned array must have a ``float64`` data type). + + Notes + ----- + + .. note:: + Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.abs`. + + .. versionchanged:: 2022.12 + Added complex data type support. + + """ + ... + + def __add__(self, other: int | float | complex | TArray, /) -> TArray: + """ + Calculates the sum for each element of an array instance with the respective element of the array ``other``. + + Parameters + ---------- + self + array instance (augend array). Should have a numeric data type. + other: Union[int, float, array] + addend array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a numeric data type. + + Returns + ------- + out: array + an array containing the element-wise sums. The returned array must have a data type determined by :ref:`type-promotion`. + + Notes + ----- + - Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.add`. + + .. versionchanged:: 2022.12 + Added complex data type support. + + """ + ... + + def __and__(self, other: int | bool | TArray, /) -> TArray: + """ + Evaluates ``self_i & other_i`` for each element of an array instance with the respective element of the array ``other``. + + Parameters + ---------- + self + array instance. Should have an integer or boolean data type. + other: Union[int, bool, array] + other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have an integer or boolean data type. + + Returns + ------- + out: array + an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. + + Notes + ----- + - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.bitwise_and`. + + """ + ... + + def __array_namespace__(self, /, *, api_version: str | None = None) -> Any: """ Returns an object that has all the array API functions on it. Parameters ---------- - self: array + self array instance. api_version: Optional[str] string representing the version of the array API specification to be returned, in ``'YYYY.MM'`` form, for example, ``'2020.10'``. If it is ``None``, it should return the namespace corresponding to latest version of the array API specification. If the given version is invalid or not implemented for the given module, an error should be raised. Default: ``None``. @@ -195,13 +279,94 @@ def __array_namespace__(self: TArray, /, *, api_version: str | None = None) -> A """ ... - def __dlpack__(self: TArray, /, *, stream: int | Any | None = None, max_version: tuple[int, int] | None = None, dl_device: tuple[Enum, int] | None = None, copy: bool | None = None) -> TPycapsule: + def __bool__(self, /) -> bool: + """ + Converts a zero-dimensional array to a Python ``bool`` object. + + Parameters + ---------- + self + zero-dimensional array instance. + + Returns + ------- + out: bool + a Python ``bool`` object representing the single element of the array. + + Notes + ----- + **Special cases** + + For real-valued floating-point operands, + + - If ``self`` is ``NaN``, the result is ``True``. + - If ``self`` is either ``+infinity`` or ``-infinity``, the result is ``True``. + - If ``self`` is either ``+0`` or ``-0``, the result is ``False``. + + For complex floating-point operands, special cases must be handled as if the operation is implemented as the logical OR of ``bool(real(self))`` and ``bool(imag(self))``. + + **Lazy implementations** + + The Python language requires the return value to be of type ``bool``. Lazy implementations are therefore not able to return any kind of lazy/delayed object here and should raise a ``ValueError`` instead. + + .. versionchanged:: 2022.12 + Added boolean and complex data type support. + + .. versionchanged:: 2023.12 + Allowed lazy implementations to error. + + """ + ... + + def __complex__(self, /) -> complex: + """ + Converts a zero-dimensional array to a Python ``complex`` object. + + Parameters + ---------- + self + zero-dimensional array instance. + + Returns + ------- + out: complex + a Python ``complex`` object representing the single element of the array instance. + + Notes + ----- + **Special cases** + + For boolean operands, + + - If ``self`` is ``True``, the result is ``1+0j``. + - If ``self`` is ``False``, the result is ``0+0j``. + + For real-valued floating-point operands, + + - If ``self`` is ``NaN``, the result is ``NaN + NaN j``. + - If ``self`` is ``+infinity``, the result is ``+infinity + 0j``. + - If ``self`` is ``-infinity``, the result is ``-infinity + 0j``. + - If ``self`` is a finite number, the result is ``self + 0j``. + + **Lazy implementations** + + The Python language requires the return value to be of type ``complex``. Lazy implementations are therefore not able to return any kind of lazy/delayed object here and should raise a ``ValueError`` instead. + + .. versionadded:: 2022.12 + + .. versionchanged:: 2023.12 + Allowed lazy implementations to error. + + """ + ... + + def __dlpack__(self, /, *, stream: int | Any | None = None, max_version: tuple[int, int] | None = None, dl_device: tuple[Enum, int] | None = None, copy: bool | None = None) -> PyCapsule: """ Exports the array for consumption by :func:`~array_api.from_dlpack` as a DLPack capsule. Parameters ---------- - self: array + self array instance. stream: Optional[Union[int, Any]] for CUDA and ROCm, a Python integer representing a pointer to a stream, on devices that support streams. ``stream`` is provided by the consumer to the producer to instruct the producer to ensure that operations can safely be performed on the array (e.g., by inserting a dependency between streams via "wait for event"). The pointer must be an integer larger than or equal to ``-1`` (see below for allowed values on each platform). If ``stream`` is ``-1``, the value may be used by the consumer to signal "producer must not perform any synchronization". The ownership of the stream stays with the consumer. On CPU and other device types without streams, only ``None`` is accepted. @@ -365,13 +530,13 @@ def __dlpack__(self: TArray, /, *, stream: int | Any | None = None, max_version: """ ... - def __dlpack_device__(self: TArray, /) -> tuple[Enum, int]: + def __dlpack_device__(self, /) -> tuple[Enum, int]: """ Returns device type and device ID in DLPack format. Meant for use within :func:`~array_api.from_dlpack`. Parameters ---------- - self: array + self array instance. Returns @@ -395,360 +560,319 @@ def __dlpack_device__(self: TArray, /) -> tuple[Enum, int]: """ ... - def to_device(self: TArray, device: TDevice, /, *, stream: int | Any | None = None) -> TArray: + def __eq__(self, other: int | float | complex | bool | TArray, /) -> TArray: # type: ignore[override] """ - Copy the array from the device on which it currently resides to the specified ``device``. + Computes the truth value of ``self_i == other_i`` for each element of an array instance with the respective element of the array ``other``. Parameters ---------- - self: array - array instance. - device: device - a ``device`` object (see :ref:`device-support`). - stream: Optional[Union[int, Any]] - stream object to use during copy. In addition to the types supported in :meth:`array.__dlpack__`, implementations may choose to support any library-specific stream object with the caveat that any code using such an object would not be portable. + self + array instance. May have any data type. + other: Union[int, float, complex, bool, array] + other array. Must be compatible with ``self`` (see :ref:`broadcasting`). May have any data type. Returns ------- out: array - an array with the same data and data type as ``self`` and located on the specified ``device``. - + an array containing the element-wise results. The returned array must have a data type of ``bool``. Notes ----- - - When a provided ``device`` object corresponds to the same device on which an array instance resides, implementations may choose to perform an explicit copy or return ``self``. - - If ``stream`` is provided, the copy operation should be enqueued on the provided ``stream``; otherwise, the copy operation should be enqueued on the default stream/queue. Whether the copy is performed synchronously or asynchronously is implementation-dependent. Accordingly, if synchronization is required to guarantee data safety, this must be clearly explained in a conforming array library's documentation. + - Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.equal`. + - Comparison of arrays without a corresponding promotable data type (see :ref:`type-promotion`) is undefined and thus implementation-dependent. - .. versionchanged:: 2023.12 - Clarified behavior when a provided ``device`` object corresponds to the device on which an array instance resides. + .. versionchanged:: 2022.12 + Added complex data type support. + + .. versionchanged:: 2024.12 + Cross-kind comparisons are explicitly left unspecified. """ ... - def __getitem__(self: TArray, key: int | slice | TEllipsis | None | tuple[int | slice | TEllipsis | TArray | None, ...] | TArray, /) -> TArray: + def __float__(self, /) -> float: """ - Returns ``self[key]``. + Converts a zero-dimensional array to a Python ``float`` object. + + .. note:: + Casting integer values outside the representable bounds of Python's float type is not specified and is implementation-dependent. Parameters ---------- - self: array - array instance. - key: Union[int, slice, ellipsis, None, Tuple[Union[int, slice, ellipsis, array, None], ...], array] - index key. + self + zero-dimensional array instance. Should have a real-valued or boolean data type. If ``self`` has a complex floating-point data type, the function must raise a ``TypeError``. Returns ------- - out: array - an array containing the accessed value(s). The returned array must have the same data type as ``self``. + out: float + a Python ``float`` object representing the single element of the array instance. Notes ----- - - See :ref:`indexing` for details on supported indexing semantics. - - When ``__getitem__`` is defined on an object, Python will automatically define iteration (i.e., the behavior from ``iter(x)``) as ``x[0]``, ``x[1]``, ..., ``x[N-1]``. This can also be implemented directly by defining ``__iter__``. Therefore, for a one-dimensional array ``x``, iteration should produce a sequence of zero-dimensional arrays ``x[0]``, ``x[1]``, ..., ``x[N-1]``, where ``N`` is the number of elements in the array. Iteration behavior for arrays having zero dimensions or more than one dimension is unspecified and thus implementation-defined. - - .. versionchanged:: 2024.12 - Clarified that iteration is defined for one-dimensional arrays. + **Special cases** - """ - ... + For boolean operands, - def __setitem__(self: TArray, key: int | slice | TEllipsis | tuple[int | slice | TEllipsis | TArray, ...] | TArray, value: int | float | complex | bool | TArray, /) -> None: - """ - Sets ``self[key]`` to ``value``. + - If ``self`` is ``True``, the result is ``1``. + - If ``self`` is ``False``, the result is ``0``. - Parameters - ---------- - self: array - array instance. - key: Union[int, slice, ellipsis, Tuple[Union[int, slice, ellipsis, array], ...], array] - index key. - value: Union[int, float, complex, bool, array] - value(s) to set. Must be compatible with ``self[key]`` (see :ref:`broadcasting`). + **Lazy implementations** - Notes - ----- - - See :ref:`indexing` for details on supported indexing semantics. + The Python language requires the return value to be of type ``float``. Lazy implementations are therefore not able to return any kind of lazy/delayed object here and should raise a ``ValueError`` instead. - .. note:: - Indexing semantics when ``key`` is an integer array or a tuple of integers and integer arrays is currently unspecified and thus implementation-defined. This will be revisited in a future revision of this standard. + .. versionchanged:: 2022.12 + Added boolean and complex data type support. - - Setting array values must not affect the data type of ``self``. - - When ``value`` is a Python scalar (i.e., ``int``, ``float``, ``complex``, ``bool``), behavior must follow specification guidance on mixing arrays with Python scalars (see :ref:`type-promotion`). - - When ``value`` is an ``array`` of a different data type than ``self``, how values are cast to the data type of ``self`` is implementation defined. + .. versionchanged:: 2023.12 + Allowed lazy implementations to error. """ ... - def __add__(self: TArray, other: int | float | complex | TArray, /) -> TArray: + def __floordiv__(self, other: int | float | TArray, /) -> TArray: """ - Calculates the sum for each element of an array instance with the respective element of the array ``other``. + Evaluates ``self_i // other_i`` for each element of an array instance with the respective element of the array ``other``. + + .. note:: + For input arrays which promote to an integer data type, the result of division by zero is unspecified and thus implementation-defined. Parameters ---------- - self: array - array instance (augend array). Should have a numeric data type. + self + array instance. Should have a real-valued data type. other: Union[int, float, array] - addend array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a numeric data type. + other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a real-valued data type. Returns ------- out: array - an array containing the element-wise sums. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. - Notes - ----- - - Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.add`. - .. versionchanged:: 2022.12 - Added complex data type support. + .. note:: + Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.floor_divide`. """ ... - def __sub__(self: TArray, other: int | float | complex | TArray, /) -> TArray: + def __ge__(self, other: int | float | TArray, /) -> TArray: """ - Calculates the difference for each element of an array instance with the respective element of the array ``other``. + Computes the truth value of ``self_i >= other_i`` for each element of an array instance with the respective element of the array ``other``. Parameters ---------- - self: array - array instance (minuend array). Should have a numeric data type. - other: Union[int, float, complex, array] - subtrahend array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a numeric data type. + self + array instance. Should have a real-valued data type. + other: Union[int, float, array] + other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a real-valued data type. Returns ------- out: array - an array containing the element-wise differences. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise results. The returned array must have a data type of ``bool``. Notes ----- - - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.subtract`. - - The result of ``self_i - other_i`` must be the same as ``self_i + (-other_i)`` and must be governed by the same floating-point rules as addition (see :meth:`array.__add__`). + - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.greater_equal`. + - Comparison of arrays without a corresponding promotable data type (see :ref:`type-promotion`) is undefined and thus implementation-dependent. + - For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). - .. versionchanged:: 2022.12 - Added complex data type support. + .. versionchanged:: 2024.12 + Cross-kind comparisons are explicitly left unspecified. """ ... - def __mul__(self: TArray, other: int | float | complex | TArray, /) -> TArray: + def __getitem__(self, key: int | slice | ellipsis | None | tuple[int | slice | ellipsis | TArray | None, ...] | TArray, /) -> TArray: """ - Calculates the product for each element of an array instance with the respective element of the array ``other``. - - .. note:: - Floating-point multiplication is not always associative due to finite precision. + Returns ``self[key]``. Parameters ---------- - self: array - array instance. Should have a numeric data type. - other: Union[int, float, complex, array] - other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a numeric data type. + self + array instance. + key: Union[int, slice, ellipsis, None, Tuple[Union[int, slice, ellipsis, array, None], ...], array] + index key. Returns ------- out: array - an array containing the element-wise products. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the accessed value(s). The returned array must have the same data type as ``self``. Notes ----- - - Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.multiply`. + - See :ref:`indexing` for details on supported indexing semantics. + - When ``__getitem__`` is defined on an object, Python will automatically define iteration (i.e., the behavior from ``iter(x)``) as ``x[0]``, ``x[1]``, ..., ``x[N-1]``. This can also be implemented directly by defining ``__iter__``. Therefore, for a one-dimensional array ``x``, iteration should produce a sequence of zero-dimensional arrays ``x[0]``, ``x[1]``, ..., ``x[N-1]``, where ``N`` is the number of elements in the array. Iteration behavior for arrays having zero dimensions or more than one dimension is unspecified and thus implementation-defined. - .. versionchanged:: 2022.12 - Added complex data type support. + .. versionchanged:: 2024.12 + Clarified that iteration is defined for one-dimensional arrays. """ ... - def __matmul__(self: TArray, other: TArray, /) -> TArray: + def __gt__(self, other: int | float | TArray, /) -> TArray: """ - Computes the matrix product. - - .. note:: - The ``matmul`` function must implement the same semantics as the built-in ``@`` operator (see `PEP 465 `_). + Computes the truth value of ``self_i > other_i`` for each element of an array instance with the respective element of the array ``other``. Parameters ---------- - self: array - array instance. Should have a numeric data type. Must have at least one dimension. If ``self`` is one-dimensional having shape ``(M,)`` and ``other`` has more than one dimension, ``self`` must be promoted to a two-dimensional array by prepending ``1`` to its dimensions (i.e., must have shape ``(1, M)``). After matrix multiplication, the prepended dimensions in the returned array must be removed. If ``self`` has more than one dimension (including after vector-to-matrix promotion), ``shape(self)[:-2]`` must be compatible with ``shape(other)[:-2]`` (after vector-to-matrix promotion) (see :ref:`broadcasting`). If ``self`` has shape ``(..., M, K)``, the innermost two dimensions form matrices on which to perform matrix multiplication. - other: array - other array. Should have a numeric data type. Must have at least one dimension. If ``other`` is one-dimensional having shape ``(N,)`` and ``self`` has more than one dimension, ``other`` must be promoted to a two-dimensional array by appending ``1`` to its dimensions (i.e., must have shape ``(N, 1)``). After matrix multiplication, the appended dimensions in the returned array must be removed. If ``other`` has more than one dimension (including after vector-to-matrix promotion), ``shape(other)[:-2]`` must be compatible with ``shape(self)[:-2]`` (after vector-to-matrix promotion) (see :ref:`broadcasting`). If ``other`` has shape ``(..., K, N)``, the innermost two dimensions form matrices on which to perform matrix multiplication. - - - .. note:: - If either ``x1`` or ``x2`` has a complex floating-point data type, neither argument must be complex-conjugated or transposed. If conjugation and/or transposition is desired, these operations should be explicitly performed prior to computing the matrix product. + self + array instance. Should have a real-valued data type. + other: Union[int, float, array] + other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a real-valued data type. Returns ------- out: array - - if both ``self`` and ``other`` are one-dimensional arrays having shape ``(N,)``, a zero-dimensional array containing the inner product as its only element. - - if ``self`` is a two-dimensional array having shape ``(M, K)`` and ``other`` is a two-dimensional array having shape ``(K, N)``, a two-dimensional array containing the `conventional matrix product `_ and having shape ``(M, N)``. - - if ``self`` is a one-dimensional array having shape ``(K,)`` and ``other`` is an array having shape ``(..., K, N)``, an array having shape ``(..., N)`` (i.e., prepended dimensions during vector-to-matrix promotion must be removed) and containing the `conventional matrix product `_. - - if ``self`` is an array having shape ``(..., M, K)`` and ``other`` is a one-dimensional array having shape ``(K,)``, an array having shape ``(..., M)`` (i.e., appended dimensions during vector-to-matrix promotion must be removed) and containing the `conventional matrix product `_. - - if ``self`` is a two-dimensional array having shape ``(M, K)`` and ``other`` is an array having shape ``(..., K, N)``, an array having shape ``(..., M, N)`` and containing the `conventional matrix product `_ for each stacked matrix. - - if ``self`` is an array having shape ``(..., M, K)`` and ``other`` is a two-dimensional array having shape ``(K, N)``, an array having shape ``(..., M, N)`` and containing the `conventional matrix product `_ for each stacked matrix. - - if either ``self`` or ``other`` has more than two dimensions, an array having a shape determined by :ref:`broadcasting` ``shape(self)[:-2]`` against ``shape(other)[:-2]`` and containing the `conventional matrix product `_ for each stacked matrix. - - The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise results. The returned array must have a data type of ``bool``. Notes ----- + - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.greater`. + - Comparison of arrays without a corresponding promotable data type (see :ref:`type-promotion`) is undefined and thus implementation-dependent. + - For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). - .. note:: - Results must equal the results returned by the equivalent function :func:`~array_api.matmul`. - - **Raises** - - - if either ``self`` or ``other`` is a zero-dimensional array. - - if ``self`` is a one-dimensional array having shape ``(K,)``, ``other`` is a one-dimensional array having shape ``(L,)``, and ``K != L``. - - if ``self`` is a one-dimensional array having shape ``(K,)``, ``other`` is an array having shape ``(..., L, N)``, and ``K != L``. - - if ``self`` is an array having shape ``(..., M, K)``, ``other`` is a one-dimensional array having shape ``(L,)``, and ``K != L``. - - if ``self`` is an array having shape ``(..., M, K)``, ``other`` is an array having shape ``(..., L, N)``, and ``K != L``. - - .. versionchanged:: 2022.12 - Added complex data type support. + .. versionchanged:: 2024.12 + Cross-kind comparisons are explicitly left unspecified. """ ... - def __truediv__(self: TArray, other: int | float | complex | TArray, /) -> TArray: + def __index__(self, /) -> int: """ - Evaluates ``self_i / other_i`` for each element of an array instance with the respective element of the array ``other``. + Converts a zero-dimensional integer array to a Python ``int`` object. + + .. note:: + This method is called to implement `operator.index() `_. See also `PEP 357 `_. Parameters ---------- - self: array - array instance. Should have a numeric data type. - other: Union[int, float, complex, array] - other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a numeric data type. + self + zero-dimensional array instance. Should have an integer data type. If ``self`` has a floating-point data type, the function must raise a ``TypeError``. Returns ------- - out: array - an array containing the element-wise results. The returned array should have a floating-point data type determined by :ref:`type-promotion`. + out: int + a Python ``int`` object representing the single element of the array instance. Notes ----- - - Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.divide`. - - - If one or both of ``self`` and ``other`` have integer data types, the result is implementation-dependent, as type promotion between data type "kinds" (e.g., integer versus floating-point) is unspecified. + **Lazy implementations** - Specification-compliant libraries may choose to raise an error or return an array containing the element-wise results. If an array is returned, the array must have a real-valued floating-point data type. + The Python language requires the return value to be of type ``int``. Lazy implementations are therefore not able to return any kind of lazy/delayed object here and should raise a ``ValueError`` instead. - .. versionchanged:: 2022.12 - Added complex data type support. + .. versionchanged:: 2023.12 + Allowed lazy implementations to error. """ ... - def __floordiv__(self: TArray, other: int | float | TArray, /) -> TArray: + def __int__(self, /) -> int: """ - Evaluates ``self_i // other_i`` for each element of an array instance with the respective element of the array ``other``. - - .. note:: - For input arrays which promote to an integer data type, the result of division by zero is unspecified and thus implementation-defined. + Converts a zero-dimensional array to a Python ``int`` object. Parameters ---------- - self: array - array instance. Should have a real-valued data type. - other: Union[int, float, array] - other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a real-valued data type. + self + zero-dimensional array instance. Should have a real-valued or boolean data type. If ``self`` has a complex floating-point data type, the function must raise a ``TypeError``. Returns ------- - out: array - an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. + out: int + a Python ``int`` object representing the single element of the array instance. + Notes + ----- + **Special cases** - .. note:: - Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.floor_divide`. + For boolean operands, - """ - ... + - If ``self`` is ``True``, the result is ``1``. + - If ``self`` is ``False``, the result is ``0``. - def __mod__(self: TArray, other: int | float | TArray, /) -> TArray: - """ - Evaluates ``self_i % other_i`` for each element of an array instance with the respective element of the array ``other``. + For floating-point operands, - Parameters - ---------- - self: array - array instance. Should have a real-valued data type. - other: Union[int, float, array] - other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a real-valued data type. + - If ``self`` is a finite number, the result is the integer part of ``self``. + - If ``self`` is ``-0``, the result is ``0``. - Returns - ------- - out: array - an array containing the element-wise results. Each element-wise result must have the same sign as the respective element ``other_i``. The returned array must have a real-valued floating-point data type determined by :ref:`type-promotion`. + **Raises** + + For floating-point operands, + + - If ``self`` is either ``+infinity`` or ``-infinity``, raise ``OverflowError``. + - If ``self`` is ``NaN``, raise ``ValueError``. Notes ----- - - Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.remainder`. - - For input arrays which promote to an integer data type, the result of division by zero is unspecified and thus implementation-defined. + **Lazy implementations** + + The Python language requires the return value to be of type ``int``. Lazy implementations are therefore not able to return any kind of lazy/delayed object here and should raise a ``ValueError`` instead. + + .. versionchanged:: 2022.12 + Added boolean and complex data type support. + + .. versionchanged:: 2023.12 + Allowed lazy implementations to error. """ ... - def __pow__(self: TArray, other: int | float | complex | TArray, /) -> TArray: + def __invert__(self, /) -> TArray: """ - Calculates an implementation-dependent approximation of exponentiation by raising each element (the base) of an array instance to the power of ``other_i`` (the exponent), where ``other_i`` is the corresponding element of the array ``other``. + Evaluates ``~self_i`` for each element of an array instance. Parameters ---------- - self: array - array instance whose elements correspond to the exponentiation base. Should have a numeric data type. - other: Union[int, float, complex, array] - other array whose elements correspond to the exponentiation exponent. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a numeric data type. + self + array instance. Should have an integer or boolean data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise results. The returned array must have the same data type as `self`. - Notes - ----- - - Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.pow`. - - If both ``self`` and ``other`` have integer data types, the result of ``__pow__`` when `other_i` is negative (i.e., less than zero) is unspecified and thus implementation-dependent. - - If ``self`` has an integer data type and ``other`` has a floating-point data type, behavior is implementation-dependent, as type promotion between data type "kinds" (e.g., integer versus floating-point) is unspecified. - .. versionchanged:: 2022.12 - Added complex data type support. + .. note:: + Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.bitwise_invert`. """ ... - def __lshift__(self: TArray, other: int | TArray, /) -> TArray: + def __le__(self, other: int | float | TArray, /) -> TArray: """ - Evaluates ``self_i << other_i`` for each element of an array instance with the respective element of the array ``other``. + Computes the truth value of ``self_i <= other_i`` for each element of an array instance with the respective element of the array ``other``. Parameters ---------- - self: array - array instance. Should have an integer data type. - other: Union[int, array] - other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have an integer data type. Each element must be greater than or equal to ``0``. + self + array instance. Should have a real-valued data type. + other: Union[int, float, array] + other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a real-valued data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have the same data type as ``self``. + an array containing the element-wise results. The returned array must have a data type of ``bool``. Notes ----- - - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.bitwise_left_shift`. + - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.less_equal`. + - Comparison of arrays without a corresponding promotable data type (see :ref:`type-promotion`) is undefined and thus implementation-dependent. + - For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). + + .. versionchanged:: 2024.12 + Cross-kind comparisons are explicitly left unspecified. """ ... - def __rshift__(self: TArray, other: int | TArray, /) -> TArray: + def __lshift__(self, other: int | TArray, /) -> TArray: """ - Evaluates ``self_i >> other_i`` for each element of an array instance with the respective element of the array ``other``. + Evaluates ``self_i << other_i`` for each element of an array instance with the respective element of the array ``other``. Parameters ---------- - self: array + self array instance. Should have an integer data type. other: Union[int, array] other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have an integer data type. Each element must be greater than or equal to ``0``. @@ -760,105 +884,135 @@ def __rshift__(self: TArray, other: int | TArray, /) -> TArray: Notes ----- - - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.bitwise_right_shift`. + - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.bitwise_left_shift`. """ ... - def __and__(self: TArray, other: int | bool | TArray, /) -> TArray: + def __lt__(self, other: int | float | TArray, /) -> TArray: """ - Evaluates ``self_i & other_i`` for each element of an array instance with the respective element of the array ``other``. + Computes the truth value of ``self_i < other_i`` for each element of an array instance with the respective element of the array ``other``. Parameters ---------- - self: array - array instance. Should have an integer or boolean data type. - other: Union[int, bool, array] - other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have an integer or boolean data type. + self + array instance. Should have a real-valued data type. + other: Union[int, float, array] + other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a real-valued data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise results. The returned array must have a data type of ``bool``. Notes ----- - - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.bitwise_and`. + - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.less`. + - Comparison of arrays without a corresponding promotable data type (see :ref:`type-promotion`) is undefined and thus implementation-dependent. + - For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). + + .. versionchanged:: 2024.12 + Cross-kind comparisons are explicitly left unspecified. """ ... - def __xor__(self: TArray, other: int | bool | TArray, /) -> TArray: + def __matmul__(self, other: TArray, /) -> TArray: """ - Evaluates ``self_i ^ other_i`` for each element of an array instance with the respective element of the array ``other``. + Computes the matrix product. + + .. note:: + The ``matmul`` function must implement the same semantics as the built-in ``@`` operator (see `PEP 465 `_). Parameters ---------- - self: array - array instance. Should have an integer or boolean data type. - other: Union[int, bool, array] - other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have an integer or boolean data type. + self + array instance. Should have a numeric data type. Must have at least one dimension. If ``self`` is one-dimensional having shape ``(M,)`` and ``other`` has more than one dimension, ``self`` must be promoted to a two-dimensional array by prepending ``1`` to its dimensions (i.e., must have shape ``(1, M)``). After matrix multiplication, the prepended dimensions in the returned array must be removed. If ``self`` has more than one dimension (including after vector-to-matrix promotion), ``shape(self)[:-2]`` must be compatible with ``shape(other)[:-2]`` (after vector-to-matrix promotion) (see :ref:`broadcasting`). If ``self`` has shape ``(..., M, K)``, the innermost two dimensions form matrices on which to perform matrix multiplication. + other: array + other array. Should have a numeric data type. Must have at least one dimension. If ``other`` is one-dimensional having shape ``(N,)`` and ``self`` has more than one dimension, ``other`` must be promoted to a two-dimensional array by appending ``1`` to its dimensions (i.e., must have shape ``(N, 1)``). After matrix multiplication, the appended dimensions in the returned array must be removed. If ``other`` has more than one dimension (including after vector-to-matrix promotion), ``shape(other)[:-2]`` must be compatible with ``shape(self)[:-2]`` (after vector-to-matrix promotion) (see :ref:`broadcasting`). If ``other`` has shape ``(..., K, N)``, the innermost two dimensions form matrices on which to perform matrix multiplication. + + + .. note:: + If either ``x1`` or ``x2`` has a complex floating-point data type, neither argument must be complex-conjugated or transposed. If conjugation and/or transposition is desired, these operations should be explicitly performed prior to computing the matrix product. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. + - if both ``self`` and ``other`` are one-dimensional arrays having shape ``(N,)``, a zero-dimensional array containing the inner product as its only element. + - if ``self`` is a two-dimensional array having shape ``(M, K)`` and ``other`` is a two-dimensional array having shape ``(K, N)``, a two-dimensional array containing the `conventional matrix product `_ and having shape ``(M, N)``. + - if ``self`` is a one-dimensional array having shape ``(K,)`` and ``other`` is an array having shape ``(..., K, N)``, an array having shape ``(..., N)`` (i.e., prepended dimensions during vector-to-matrix promotion must be removed) and containing the `conventional matrix product `_. + - if ``self`` is an array having shape ``(..., M, K)`` and ``other`` is a one-dimensional array having shape ``(K,)``, an array having shape ``(..., M)`` (i.e., appended dimensions during vector-to-matrix promotion must be removed) and containing the `conventional matrix product `_. + - if ``self`` is a two-dimensional array having shape ``(M, K)`` and ``other`` is an array having shape ``(..., K, N)``, an array having shape ``(..., M, N)`` and containing the `conventional matrix product `_ for each stacked matrix. + - if ``self`` is an array having shape ``(..., M, K)`` and ``other`` is a two-dimensional array having shape ``(K, N)``, an array having shape ``(..., M, N)`` and containing the `conventional matrix product `_ for each stacked matrix. + - if either ``self`` or ``other`` has more than two dimensions, an array having a shape determined by :ref:`broadcasting` ``shape(self)[:-2]`` against ``shape(other)[:-2]`` and containing the `conventional matrix product `_ for each stacked matrix. + - The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- - - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.bitwise_xor`. + + .. note:: + Results must equal the results returned by the equivalent function :func:`~array_api.matmul`. + + **Raises** + + - if either ``self`` or ``other`` is a zero-dimensional array. + - if ``self`` is a one-dimensional array having shape ``(K,)``, ``other`` is a one-dimensional array having shape ``(L,)``, and ``K != L``. + - if ``self`` is a one-dimensional array having shape ``(K,)``, ``other`` is an array having shape ``(..., L, N)``, and ``K != L``. + - if ``self`` is an array having shape ``(..., M, K)``, ``other`` is a one-dimensional array having shape ``(L,)``, and ``K != L``. + - if ``self`` is an array having shape ``(..., M, K)``, ``other`` is an array having shape ``(..., L, N)``, and ``K != L``. + + .. versionchanged:: 2022.12 + Added complex data type support. """ ... - def __or__(self: TArray, other: int | bool | TArray, /) -> TArray: + def __mod__(self, other: int | float | TArray, /) -> TArray: """ - Evaluates ``self_i | other_i`` for each element of an array instance with the respective element of the array ``other``. + Evaluates ``self_i % other_i`` for each element of an array instance with the respective element of the array ``other``. Parameters ---------- - self: array - array instance. Should have an integer or boolean data type. - other: Union[int, bool, array] - other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have an integer or boolean data type. + self + array instance. Should have a real-valued data type. + other: Union[int, float, array] + other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a real-valued data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise results. Each element-wise result must have the same sign as the respective element ``other_i``. The returned array must have a real-valued floating-point data type determined by :ref:`type-promotion`. Notes ----- - - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.bitwise_or`. + - Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.remainder`. + - For input arrays which promote to an integer data type, the result of division by zero is unspecified and thus implementation-defined. """ ... - def __neg__(self: TArray, /) -> TArray: + def __mul__(self, other: int | float | complex | TArray, /) -> TArray: """ - Evaluates ``-self_i`` for each element of an array instance. - - .. note:: - For signed integer data types, the numerical negative of the minimum representable integer is implementation-dependent. + Calculates the product for each element of an array instance with the respective element of the array ``other``. .. note:: - If ``self`` has a complex floating-point data type, both the real and imaginary components for each ``self_i`` must be negated (a result which follows from the rules of complex number multiplication). + Floating-point multiplication is not always associative due to finite precision. Parameters ---------- - self: array + self array instance. Should have a numeric data type. + other: Union[int, float, complex, array] + other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a numeric data type. Returns ------- out: array - an array containing the evaluated result for each element in ``self``. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise products. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- - - .. note:: - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.negative`. + - Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.multiply`. .. versionchanged:: 2022.12 Added complex data type support. @@ -866,56 +1020,61 @@ def __neg__(self: TArray, /) -> TArray: """ ... - def __pos__(self: TArray, /) -> TArray: + def __ne__(self, other: int | float | complex | bool | TArray, /) -> TArray: # type: ignore[override] """ - Evaluates ``+self_i`` for each element of an array instance. + Computes the truth value of ``self_i != other_i`` for each element of an array instance with the respective element of the array ``other``. Parameters ---------- - self: array - array instance. Should have a numeric data type. + self + array instance. May have any data type. + other: Union[int, float, complex, bool, array] + other array. Must be compatible with ``self`` (see :ref:`broadcasting`). May have any data type. Returns ------- out: array - an array containing the evaluated result for each element. The returned array must have the same data type as ``self``. + an array containing the element-wise results. The returned array must have a data type of ``bool`` (i.e., must be a boolean array). Notes ----- - - .. note:: - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.positive`. + - Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.not_equal`. + - Comparison of arrays without a corresponding promotable data type (see :ref:`type-promotion`) is undefined and thus implementation-dependent. .. versionchanged:: 2022.12 Added complex data type support. + .. versionchanged:: 2024.12 + Cross-kind comparisons are explicitly left unspecified. + """ ... - def __abs__(self: TArray, /) -> TArray: + def __neg__(self, /) -> TArray: """ - Calculates the absolute value for each element of an array instance. + Evaluates ``-self_i`` for each element of an array instance. - For real-valued input arrays, the element-wise result has the same magnitude as the respective element in ``x`` but has positive sign. + .. note:: + For signed integer data types, the numerical negative of the minimum representable integer is implementation-dependent. .. note:: - For signed integer data types, the absolute value of the minimum representable integer is implementation-dependent. + If ``self`` has a complex floating-point data type, both the real and imaginary components for each ``self_i`` must be negated (a result which follows from the rules of complex number multiplication). Parameters ---------- - self: array + self array instance. Should have a numeric data type. Returns ------- out: array - an array containing the element-wise absolute value. If ``self`` has a real-valued data type, the returned array must have the same data type as ``self``. If ``self`` has a complex floating-point data type, the returned arrayed must have a real-valued floating-point data type whose precision matches the precision of ``self`` (e.g., if ``self`` is ``complex128``, then the returned array must have a ``float64`` data type). + an array containing the evaluated result for each element in ``self``. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- .. note:: - Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.abs`. + Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.negative`. .. versionchanged:: 2022.12 Added complex data type support. @@ -923,394 +1082,239 @@ def __abs__(self: TArray, /) -> TArray: """ ... - def __invert__(self: TArray, /) -> TArray: + def __or__(self, other: int | bool | TArray, /) -> TArray: """ - Evaluates ``~self_i`` for each element of an array instance. + Evaluates ``self_i | other_i`` for each element of an array instance with the respective element of the array ``other``. Parameters ---------- - self: array + self array instance. Should have an integer or boolean data type. + other: Union[int, bool, array] + other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have an integer or boolean data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have the same data type as `self`. - - - .. note:: - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.bitwise_invert`. - - """ - ... - - def __lt__(self: TArray, other: int | float | TArray, /) -> TArray: - """ - Computes the truth value of ``self_i < other_i`` for each element of an array instance with the respective element of the array ``other``. - - Parameters - ---------- - self: array - array instance. Should have a real-valued data type. - other: Union[int, float, array] - other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a real-valued data type. - - Returns - ------- - out: array - an array containing the element-wise results. The returned array must have a data type of ``bool``. + an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- - - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.less`. - - Comparison of arrays without a corresponding promotable data type (see :ref:`type-promotion`) is undefined and thus implementation-dependent. - - For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). - - .. versionchanged:: 2024.12 - Cross-kind comparisons are explicitly left unspecified. + - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.bitwise_or`. """ ... - def __le__(self: TArray, other: int | float | TArray, /) -> TArray: + def __pos__(self, /) -> TArray: """ - Computes the truth value of ``self_i <= other_i`` for each element of an array instance with the respective element of the array ``other``. + Evaluates ``+self_i`` for each element of an array instance. Parameters ---------- - self: array - array instance. Should have a real-valued data type. - other: Union[int, float, array] - other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a real-valued data type. + self + array instance. Should have a numeric data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type of ``bool``. + an array containing the evaluated result for each element. The returned array must have the same data type as ``self``. Notes ----- - - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.less_equal`. - - Comparison of arrays without a corresponding promotable data type (see :ref:`type-promotion`) is undefined and thus implementation-dependent. - - For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). - - .. versionchanged:: 2024.12 - Cross-kind comparisons are explicitly left unspecified. - - """ - ... - def __eq__(self: TArray, other: int | float | complex | bool | TArray, /) -> TArray: # type: ignore[override] - """ - Computes the truth value of ``self_i == other_i`` for each element of an array instance with the respective element of the array ``other``. - - Parameters - ---------- - self: array - array instance. May have any data type. - other: Union[int, float, complex, bool, array] - other array. Must be compatible with ``self`` (see :ref:`broadcasting`). May have any data type. - - Returns - ------- - out: array - an array containing the element-wise results. The returned array must have a data type of ``bool``. - - Notes - ----- - - Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.equal`. - - Comparison of arrays without a corresponding promotable data type (see :ref:`type-promotion`) is undefined and thus implementation-dependent. + .. note:: + Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.positive`. .. versionchanged:: 2022.12 Added complex data type support. - .. versionchanged:: 2024.12 - Cross-kind comparisons are explicitly left unspecified. - """ ... - def __ne__(self: TArray, other: int | float | complex | bool | TArray, /) -> TArray: # type: ignore[override] + def __pow__(self, other: int | float | complex | TArray, /) -> TArray: """ - Computes the truth value of ``self_i != other_i`` for each element of an array instance with the respective element of the array ``other``. + Calculates an implementation-dependent approximation of exponentiation by raising each element (the base) of an array instance to the power of ``other_i`` (the exponent), where ``other_i`` is the corresponding element of the array ``other``. Parameters ---------- - self: array - array instance. May have any data type. - other: Union[int, float, complex, bool, array] - other array. Must be compatible with ``self`` (see :ref:`broadcasting`). May have any data type. + self + array instance whose elements correspond to the exponentiation base. Should have a numeric data type. + other: Union[int, float, complex, array] + other array whose elements correspond to the exponentiation exponent. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a numeric data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type of ``bool`` (i.e., must be a boolean array). + an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- - - Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.not_equal`. - - Comparison of arrays without a corresponding promotable data type (see :ref:`type-promotion`) is undefined and thus implementation-dependent. + - Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.pow`. + - If both ``self`` and ``other`` have integer data types, the result of ``__pow__`` when `other_i` is negative (i.e., less than zero) is unspecified and thus implementation-dependent. + - If ``self`` has an integer data type and ``other`` has a floating-point data type, behavior is implementation-dependent, as type promotion between data type "kinds" (e.g., integer versus floating-point) is unspecified. .. versionchanged:: 2022.12 Added complex data type support. - .. versionchanged:: 2024.12 - Cross-kind comparisons are explicitly left unspecified. - """ ... - def __gt__(self: TArray, other: int | float | TArray, /) -> TArray: + def __rshift__(self, other: int | TArray, /) -> TArray: """ - Computes the truth value of ``self_i > other_i`` for each element of an array instance with the respective element of the array ``other``. - - Parameters - ---------- - self: array - array instance. Should have a real-valued data type. - other: Union[int, float, array] - other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a real-valued data type. - - Returns - ------- - out: array - an array containing the element-wise results. The returned array must have a data type of ``bool``. - - Notes - ----- - - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.greater`. - - Comparison of arrays without a corresponding promotable data type (see :ref:`type-promotion`) is undefined and thus implementation-dependent. - - For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). - - .. versionchanged:: 2024.12 - Cross-kind comparisons are explicitly left unspecified. - - """ - ... - - def __ge__(self: TArray, other: int | float | TArray, /) -> TArray: - """ - Computes the truth value of ``self_i >= other_i`` for each element of an array instance with the respective element of the array ``other``. + Evaluates ``self_i >> other_i`` for each element of an array instance with the respective element of the array ``other``. Parameters ---------- - self: array - array instance. Should have a real-valued data type. - other: Union[int, float, array] - other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a real-valued data type. + self + array instance. Should have an integer data type. + other: Union[int, array] + other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have an integer data type. Each element must be greater than or equal to ``0``. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type of ``bool``. + an array containing the element-wise results. The returned array must have the same data type as ``self``. Notes ----- - - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.greater_equal`. - - Comparison of arrays without a corresponding promotable data type (see :ref:`type-promotion`) is undefined and thus implementation-dependent. - - For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). - - .. versionchanged:: 2024.12 - Cross-kind comparisons are explicitly left unspecified. + - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.bitwise_right_shift`. """ ... - def __bool__(self: TArray, /) -> bool: + def __setitem__(self, key: int | slice | ellipsis | tuple[int | slice | ellipsis | TArray, ...] | TArray, value: int | float | complex | bool | TArray, /) -> None: """ - Converts a zero-dimensional array to a Python ``bool`` object. + Sets ``self[key]`` to ``value``. Parameters ---------- - self: array - zero-dimensional array instance. - - Returns - ------- - out: bool - a Python ``bool`` object representing the single element of the array. + self + array instance. + key: Union[int, slice, ellipsis, Tuple[Union[int, slice, ellipsis, array], ...], array] + index key. + value: Union[int, float, complex, bool, array] + value(s) to set. Must be compatible with ``self[key]`` (see :ref:`broadcasting`). Notes ----- - **Special cases** - - For real-valued floating-point operands, - - - If ``self`` is ``NaN``, the result is ``True``. - - If ``self`` is either ``+infinity`` or ``-infinity``, the result is ``True``. - - If ``self`` is either ``+0`` or ``-0``, the result is ``False``. - - For complex floating-point operands, special cases must be handled as if the operation is implemented as the logical OR of ``bool(real(self))`` and ``bool(imag(self))``. - - **Lazy implementations** - - The Python language requires the return value to be of type ``bool``. Lazy implementations are therefore not able to return any kind of lazy/delayed object here and should raise a ``ValueError`` instead. + - See :ref:`indexing` for details on supported indexing semantics. - .. versionchanged:: 2022.12 - Added boolean and complex data type support. + .. note:: + Indexing semantics when ``key`` is an integer array or a tuple of integers and integer arrays is currently unspecified and thus implementation-defined. This will be revisited in a future revision of this standard. - .. versionchanged:: 2023.12 - Allowed lazy implementations to error. + - Setting array values must not affect the data type of ``self``. + - When ``value`` is a Python scalar (i.e., ``int``, ``float``, ``complex``, ``bool``), behavior must follow specification guidance on mixing arrays with Python scalars (see :ref:`type-promotion`). + - When ``value`` is an ``array`` of a different data type than ``self``, how values are cast to the data type of ``self`` is implementation defined. """ ... - def __complex__(self: TArray, /) -> complex: + def __sub__(self, other: int | float | complex | TArray, /) -> TArray: """ - Converts a zero-dimensional array to a Python ``complex`` object. + Calculates the difference for each element of an array instance with the respective element of the array ``other``. Parameters ---------- - self: array - zero-dimensional array instance. + self + array instance (minuend array). Should have a numeric data type. + other: Union[int, float, complex, array] + subtrahend array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a numeric data type. Returns ------- - out: complex - a Python ``complex`` object representing the single element of the array instance. + out: array + an array containing the element-wise differences. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- - **Special cases** - - For boolean operands, - - - If ``self`` is ``True``, the result is ``1+0j``. - - If ``self`` is ``False``, the result is ``0+0j``. - - For real-valued floating-point operands, - - - If ``self`` is ``NaN``, the result is ``NaN + NaN j``. - - If ``self`` is ``+infinity``, the result is ``+infinity + 0j``. - - If ``self`` is ``-infinity``, the result is ``-infinity + 0j``. - - If ``self`` is a finite number, the result is ``self + 0j``. - - **Lazy implementations** - - The Python language requires the return value to be of type ``complex``. Lazy implementations are therefore not able to return any kind of lazy/delayed object here and should raise a ``ValueError`` instead. - - .. versionadded:: 2022.12 + - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.subtract`. + - The result of ``self_i - other_i`` must be the same as ``self_i + (-other_i)`` and must be governed by the same floating-point rules as addition (see :meth:`array.__add__`). - .. versionchanged:: 2023.12 - Allowed lazy implementations to error. + .. versionchanged:: 2022.12 + Added complex data type support. """ ... - def __int__(self: TArray, /) -> int: + def __truediv__(self, other: int | float | complex | TArray, /) -> TArray: """ - Converts a zero-dimensional array to a Python ``int`` object. + Evaluates ``self_i / other_i`` for each element of an array instance with the respective element of the array ``other``. Parameters ---------- - self: array - zero-dimensional array instance. Should have a real-valued or boolean data type. If ``self`` has a complex floating-point data type, the function must raise a ``TypeError``. + self + array instance. Should have a numeric data type. + other: Union[int, float, complex, array] + other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have a numeric data type. Returns ------- - out: int - a Python ``int`` object representing the single element of the array instance. + out: array + an array containing the element-wise results. The returned array should have a floating-point data type determined by :ref:`type-promotion`. Notes ----- - **Special cases** - - For boolean operands, - - - If ``self`` is ``True``, the result is ``1``. - - If ``self`` is ``False``, the result is ``0``. - - For floating-point operands, - - - If ``self`` is a finite number, the result is the integer part of ``self``. - - If ``self`` is ``-0``, the result is ``0``. - - **Raises** - - For floating-point operands, - - - If ``self`` is either ``+infinity`` or ``-infinity``, raise ``OverflowError``. - - If ``self`` is ``NaN``, raise ``ValueError``. + - Element-wise results, including special cases, must equal the results returned by the equivalent element-wise function :func:`~array_api.divide`. - Notes - ----- - **Lazy implementations** + - If one or both of ``self`` and ``other`` have integer data types, the result is implementation-dependent, as type promotion between data type "kinds" (e.g., integer versus floating-point) is unspecified. - The Python language requires the return value to be of type ``int``. Lazy implementations are therefore not able to return any kind of lazy/delayed object here and should raise a ``ValueError`` instead. + Specification-compliant libraries may choose to raise an error or return an array containing the element-wise results. If an array is returned, the array must have a real-valued floating-point data type. .. versionchanged:: 2022.12 - Added boolean and complex data type support. - - .. versionchanged:: 2023.12 - Allowed lazy implementations to error. + Added complex data type support. """ ... - def __float__(self: TArray, /) -> float: + def __xor__(self, other: int | bool | TArray, /) -> TArray: """ - Converts a zero-dimensional array to a Python ``float`` object. - - .. note:: - Casting integer values outside the representable bounds of Python's float type is not specified and is implementation-dependent. + Evaluates ``self_i ^ other_i`` for each element of an array instance with the respective element of the array ``other``. Parameters ---------- - self: array - zero-dimensional array instance. Should have a real-valued or boolean data type. If ``self`` has a complex floating-point data type, the function must raise a ``TypeError``. + self + array instance. Should have an integer or boolean data type. + other: Union[int, bool, array] + other array. Must be compatible with ``self`` (see :ref:`broadcasting`). Should have an integer or boolean data type. Returns ------- - out: float - a Python ``float`` object representing the single element of the array instance. + out: array + an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- - **Special cases** - - For boolean operands, - - - If ``self`` is ``True``, the result is ``1``. - - If ``self`` is ``False``, the result is ``0``. - - **Lazy implementations** - - The Python language requires the return value to be of type ``float``. Lazy implementations are therefore not able to return any kind of lazy/delayed object here and should raise a ``ValueError`` instead. - - .. versionchanged:: 2022.12 - Added boolean and complex data type support. - - .. versionchanged:: 2023.12 - Allowed lazy implementations to error. + - Element-wise results must equal the results returned by the equivalent element-wise function :func:`~array_api.bitwise_xor`. """ ... - def __index__(self: TArray, /) -> int: + def to_device(self, device: TDevice, /, *, stream: int | Any | None = None) -> TArray: """ - Converts a zero-dimensional integer array to a Python ``int`` object. - - .. note:: - This method is called to implement `operator.index() `_. See also `PEP 357 `_. + Copy the array from the device on which it currently resides to the specified ``device``. Parameters ---------- - self: array - zero-dimensional array instance. Should have an integer data type. If ``self`` has a floating-point data type, the function must raise a ``TypeError``. + self + array instance. + device: device + a ``device`` object (see :ref:`device-support`). + stream: Optional[Union[int, Any]] + stream object to use during copy. In addition to the types supported in :meth:`array.__dlpack__`, implementations may choose to support any library-specific stream object with the caveat that any code using such an object would not be portable. Returns ------- - out: int - a Python ``int`` object representing the single element of the array instance. + out: array + an array with the same data and data type as ``self`` and located on the specified ``device``. + Notes ----- - **Lazy implementations** - - The Python language requires the return value to be of type ``int``. Lazy implementations are therefore not able to return any kind of lazy/delayed object here and should raise a ``ValueError`` instead. + - When a provided ``device`` object corresponds to the same device on which an array instance resides, implementations may choose to perform an explicit copy or return ``self``. + - If ``stream`` is provided, the copy operation should be enqueued on the provided ``stream``; otherwise, the copy operation should be enqueued on the default stream/queue. Whether the copy is performed synchronously or asynchronously is implementation-dependent. Accordingly, if synchronization is required to guarantee data safety, this must be clearly explained in a conforming array library's documentation. .. versionchanged:: 2023.12 - Allowed lazy implementations to error. + Clarified behavior when a provided ``device`` object corresponds to the device on which an array instance resides. """ ... @@ -1322,47 +1326,47 @@ class astype[TArray: Array, TDevice, TDtype](Protocol): Copies an array to a specified data type irrespective of :ref:`type-promotion` rules. .. note:: - Casting floating-point ``NaN`` and ``infinity`` values to integral data types is not specified and is implementation-dependent. + Casting floating-point ``NaN`` and ``infinity`` values to integral data types is not specified and is implementation-dependent. .. note:: - Casting a complex floating-point array to a real-valued data type should not be permitted. + Casting a complex floating-point array to a real-valued data type should not be permitted. - Historically, when casting a complex floating-point array to a real-valued data type, libraries such as NumPy have discarded imaginary components such that, for a complex floating-point array ``x``, ``astype(x)`` equals ``astype(real(x))``). This behavior is considered problematic as the choice to discard the imaginary component is arbitrary and introduces more than one way to achieve the same outcome (i.e., for a complex floating-point array ``x``, ``astype(x)`` and ``astype(real(x))`` versus only ``astype(imag(x))``). Instead, in order to avoid ambiguity and to promote clarity, this specification requires that array API consumers explicitly express which component should be cast to a specified real-valued data type. + Historically, when casting a complex floating-point array to a real-valued data type, libraries such as NumPy have discarded imaginary components such that, for a complex floating-point array ``x``, ``astype(x)`` equals ``astype(real(x))``). This behavior is considered problematic as the choice to discard the imaginary component is arbitrary and introduces more than one way to achieve the same outcome (i.e., for a complex floating-point array ``x``, ``astype(x)`` and ``astype(real(x))`` versus only ``astype(imag(x))``). Instead, in order to avoid ambiguity and to promote clarity, this specification requires that array API consumers explicitly express which component should be cast to a specified real-valued data type. .. note:: - When casting a boolean input array to a real-valued data type, a value of ``True`` must cast to a real-valued number equal to ``1``, and a value of ``False`` must cast to a real-valued number equal to ``0``. + When casting a boolean input array to a real-valued data type, a value of ``True`` must cast to a real-valued number equal to ``1``, and a value of ``False`` must cast to a real-valued number equal to ``0``. - When casting a boolean input array to a complex floating-point data type, a value of ``True`` must cast to a complex number equal to ``1 + 0j``, and a value of ``False`` must cast to a complex number equal to ``0 + 0j``. + When casting a boolean input array to a complex floating-point data type, a value of ``True`` must cast to a complex number equal to ``1 + 0j``, and a value of ``False`` must cast to a complex number equal to ``0 + 0j``. .. note:: - When casting a real-valued input array to ``bool``, a value of ``0`` must cast to ``False``, and a non-zero value must cast to ``True``. + When casting a real-valued input array to ``bool``, a value of ``0`` must cast to ``False``, and a non-zero value must cast to ``True``. - When casting a complex floating-point array to ``bool``, a value of ``0 + 0j`` must cast to ``False``, and all other values must cast to ``True``. + When casting a complex floating-point array to ``bool``, a value of ``0 + 0j`` must cast to ``False``, and all other values must cast to ``True``. Parameters ---------- x: array - array to cast. + array to cast. dtype: dtype - desired data type. + desired data type. copy: bool - specifies whether to copy an array when the specified ``dtype`` matches the data type of the input array ``x``. If ``True``, a newly allocated array must always be returned (see :ref:`copy-keyword-argument`). If ``False`` and the specified ``dtype`` matches the data type of the input array, the input array must be returned; otherwise, a newly allocated array must be returned. Default: ``True``. + specifies whether to copy an array when the specified ``dtype`` matches the data type of the input array ``x``. If ``True``, a newly allocated array must always be returned (see :ref:`copy-keyword-argument`). If ``False`` and the specified ``dtype`` matches the data type of the input array, the input array must be returned; otherwise, a newly allocated array must be returned. Default: ``True``. device: Optional[device] - device on which to place the returned array. If ``device`` is ``None``, the output array device must be inferred from ``x``. Default: ``None``. + device on which to place the returned array. If ``device`` is ``None``, the output array device must be inferred from ``x``. Default: ``None``. Returns ------- out: array - an array having the specified data type. The returned array must have the same shape as ``x``. + an array having the specified data type. The returned array must have the same shape as ``x``. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. .. versionchanged:: 2023.12 - Added device keyword argument support. + Added device keyword argument support. """ @@ -1378,14 +1382,14 @@ class can_cast[TArray: Array, TDtype](Protocol): Parameters ---------- from_: Union[dtype, array] - input data type or array from which to cast. + input data type or array from which to cast. to: dtype - desired data type. + desired data type. Returns ------- out: bool - ``True`` if the cast can occur according to type promotion rules (see :ref:`type-promotion`); otherwise, ``False``. + ``True`` if the cast can occur according to type promotion rules (see :ref:`type-promotion`); otherwise, ``False``. Notes ----- @@ -1393,7 +1397,7 @@ class can_cast[TArray: Array, TDtype](Protocol): - When ``from_`` is an array, the function must determine whether the data type of the array can be cast to the desired data type according to the type promotion graph of the array device. As not all devices can support all data types, full support for type promotion rules (see :ref:`type-promotion`) may not be possible. Accordingly, the output of ``can_cast(array, dtype)`` may differ from ``can_cast(array.dtype, dtype)``. .. versionchanged:: 2024.12 - Required that the application of type promotion rules must account for device context. + Required that the application of type promotion rules must account for device context. """ @@ -1409,47 +1413,47 @@ class finfo[TArray: Array, TDtype](Protocol): Parameters ---------- type: Union[dtype, array] - the kind of floating-point data-type about which to get information. If complex, the information is about its component data type. + the kind of floating-point data-type about which to get information. If complex, the information is about its component data type. - .. note:: - Complex floating-point data types are specified to always use the same precision for both its real and imaginary components, so the information should be true for either component. + .. note:: + Complex floating-point data types are specified to always use the same precision for both its real and imaginary components, so the information should be true for either component. Returns ------- out: finfo object - an object having the following attributes: + an object having the following attributes: - - **bits**: *int* + - **bits**: *int* - number of bits occupied by the real-valued floating-point data type. + number of bits occupied by the real-valued floating-point data type. - - **eps**: *float* + - **eps**: *float* - difference between 1.0 and the next smallest representable real-valued floating-point number larger than 1.0 according to the IEEE-754 standard. + difference between 1.0 and the next smallest representable real-valued floating-point number larger than 1.0 according to the IEEE-754 standard. - - **max**: *float* + - **max**: *float* - largest representable real-valued number. + largest representable real-valued number. - - **min**: *float* + - **min**: *float* - smallest representable real-valued number. + smallest representable real-valued number. - - **smallest_normal**: *float* + - **smallest_normal**: *float* - smallest positive real-valued floating-point number with full precision. + smallest positive real-valued floating-point number with full precision. - - **dtype**: dtype + - **dtype**: dtype - real-valued floating-point data type. + real-valued floating-point data type. - .. versionadded:: 2022.12 + .. versionadded:: 2022.12 Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -1465,30 +1469,30 @@ class iinfo[TArray: Array, TDtype](Protocol): Parameters ---------- type: Union[dtype, array] - the kind of integer data-type about which to get information. + the kind of integer data-type about which to get information. Returns ------- out: iinfo object - an object having the following attributes: + an object having the following attributes: - - **bits**: *int* + - **bits**: *int* - number of bits occupied by the type. + number of bits occupied by the type. - - **max**: *int* + - **max**: *int* - largest representable number. + largest representable number. - - **min**: *int* + - **min**: *int* - smallest representable number. + smallest representable number. - - **dtype**: dtype + - **dtype**: dtype - integer data type. + integer data type. - .. versionadded:: 2022.12 + .. versionadded:: 2022.12 """ @@ -1504,32 +1508,32 @@ class isdtype[TDtype](Protocol): Parameters ---------- dtype: dtype - the input dtype. + the input dtype. kind: Union[str, dtype, Tuple[Union[str, dtype], ...]] - data type kind. + data type kind. - - If ``kind`` is a dtype, the function must return a boolean indicating whether the input ``dtype`` is equal to the dtype specified by ``kind``. - - If ``kind`` is a string, the function must return a boolean indicating whether the input ``dtype`` is of a specified data type kind. The following dtype kinds must be supported: + - If ``kind`` is a dtype, the function must return a boolean indicating whether the input ``dtype`` is equal to the dtype specified by ``kind``. + - If ``kind`` is a string, the function must return a boolean indicating whether the input ``dtype`` is of a specified data type kind. The following dtype kinds must be supported: - - ``'bool'``: boolean data types (e.g., ``bool``). - - ``'signed integer'``: signed integer data types (e.g., ``int8``, ``int16``, ``int32``, ``int64``). - - ``'unsigned integer'``: unsigned integer data types (e.g., ``uint8``, ``uint16``, ``uint32``, ``uint64``). - - ``'integral'``: integer data types. Shorthand for ``('signed integer', 'unsigned integer')``. - - ``'real floating'``: real-valued floating-point data types (e.g., ``float32``, ``float64``). - - ``'complex floating'``: complex floating-point data types (e.g., ``complex64``, ``complex128``). - - ``'numeric'``: numeric data types. Shorthand for ``('integral', 'real floating', 'complex floating')``. + - ``'bool'``: boolean data types (e.g., ``bool``). + - ``'signed integer'``: signed integer data types (e.g., ``int8``, ``int16``, ``int32``, ``int64``). + - ``'unsigned integer'``: unsigned integer data types (e.g., ``uint8``, ``uint16``, ``uint32``, ``uint64``). + - ``'integral'``: integer data types. Shorthand for ``('signed integer', 'unsigned integer')``. + - ``'real floating'``: real-valued floating-point data types (e.g., ``float32``, ``float64``). + - ``'complex floating'``: complex floating-point data types (e.g., ``complex64``, ``complex128``). + - ``'numeric'``: numeric data types. Shorthand for ``('integral', 'real floating', 'complex floating')``. - - If ``kind`` is a tuple, the tuple specifies a union of dtypes and/or kinds, and the function must return a boolean indicating whether the input ``dtype`` is either equal to a specified dtype or belongs to at least one specified data type kind. + - If ``kind`` is a tuple, the tuple specifies a union of dtypes and/or kinds, and the function must return a boolean indicating whether the input ``dtype`` is either equal to a specified dtype or belongs to at least one specified data type kind. - .. note:: - A conforming implementation of the array API standard is **not** limited to only including the dtypes described in this specification in the required data type kinds. For example, implementations supporting ``float16`` and ``bfloat16`` can include ``float16`` and ``bfloat16`` in the ``real floating`` data type kind. Similarly, implementations supporting ``int128`` can include ``int128`` in the ``signed integer`` data type kind. + .. note:: + A conforming implementation of the array API standard is **not** limited to only including the dtypes described in this specification in the required data type kinds. For example, implementations supporting ``float16`` and ``bfloat16`` can include ``float16`` and ``bfloat16`` in the ``real floating`` data type kind. Similarly, implementations supporting ``int128`` can include ``int128`` in the ``signed integer`` data type kind. - In short, conforming implementations may extend data type kinds; however, data type kinds must remain consistent (e.g., only integer dtypes may belong to integer data type kinds and only floating-point dtypes may belong to floating-point data type kinds), and extensions must be clearly documented as such in library documentation. + In short, conforming implementations may extend data type kinds; however, data type kinds must remain consistent (e.g., only integer dtypes may belong to integer data type kinds and only floating-point dtypes may belong to floating-point data type kinds), and extensions must be clearly documented as such in library documentation. Returns ------- out: bool - boolean indicating whether a provided dtype is of a specified data type kind. + boolean indicating whether a provided dtype is of a specified data type kind. Notes ----- @@ -1550,12 +1554,12 @@ class result_type[TArray: Array, TDtype](Protocol): Parameters ---------- arrays_and_dtypes: Union[array, int, float, complex, bool, dtype] - an arbitrary number of input arrays, scalars, and/or dtypes. + an arbitrary number of input arrays, scalars, and/or dtypes. Returns ------- out: dtype - the dtype resulting from an operation involving the input arrays, scalars, and/or dtypes. + the dtype resulting from an operation involving the input arrays, scalars, and/or dtypes. Notes ----- @@ -1565,10 +1569,10 @@ class result_type[TArray: Array, TDtype](Protocol): - If two or more arguments are arrays belonging to different devices, behavior is unspecified and thus implementation-dependent. Conforming implementations may choose to ignore device attributes, raise an exception, or some other behavior. .. versionchanged:: 2024.12 - Added scalar argument support. + Added scalar argument support. .. versionchanged:: 2024.12 - Required that the application of type promotion rules must account for device context. + Required that the application of type promotion rules must account for device context. """ @@ -1584,32 +1588,32 @@ class cumulative_prod[TArray: Array, TDtype](Protocol): Parameters ---------- x: array - input array. Should have one or more dimensions (axes). Should have a numeric data type. + input array. **Should** have one or more dimensions (axes). **Should** have a numeric data type. axis: Optional[int] - axis along which a cumulative product must be computed. If ``axis`` is negative, the function must determine the axis along which to compute a cumulative product by counting from the last dimension. + axis along which to compute the cumulative product. A valid axis **must** be an integer on the interval ``[-N, N)``, where ``N`` is the number of axes in ``x``. If an axis is specified as a negative integer, the function **must** determine the axis along which to perform the operation by counting backward from the last axis (where ``-1`` refers to the last axis). If provided an invalid axis, the function **must** raise an exception. - If ``x`` is a one-dimensional array, providing an ``axis`` is optional; however, if ``x`` has more than one dimension, providing an ``axis`` is required. + If ``x`` is a one-dimensional array, providing an ``axis`` **must** be optional; however, if ``x`` has more than one dimension, providing an ``axis`` **must** be required. dtype: Optional[dtype] - data type of the returned array. If ``None``, the returned array must have the same data type as ``x``, unless ``x`` has an integer data type supporting a smaller range of values than the default integer data type (e.g., ``x`` has an ``int16`` or ``uint32`` data type and the default integer data type is ``int64``). In those latter cases: + data type of the returned array. If ``None``, the returned array **must** have the same data type as ``x``, unless ``x`` has an integer data type supporting a smaller range of values than the default integer data type (e.g., ``x`` has an ``int16`` or ``uint32`` data type and the default integer data type is ``int64``). In those latter cases: - - if ``x`` has a signed integer data type (e.g., ``int16``), the returned array must have the default integer data type. - - if ``x`` has an unsigned integer data type (e.g., ``uint16``), the returned array must have an unsigned integer data type having the same number of bits as the default integer data type (e.g., if the default integer data type is ``int32``, the returned array must have a ``uint32`` data type). + - if ``x`` has a signed integer data type (e.g., ``int16``), the returned array **must** have the default integer data type. + - if ``x`` has an unsigned integer data type (e.g., ``uint16``), the returned array **must** have an unsigned integer data type having the same number of bits as the default integer data type (e.g., if the default integer data type is ``int32``, the returned array **must** have a ``uint32`` data type). - If the data type (either specified or resolved) differs from the data type of ``x``, the input array should be cast to the specified data type before computing the product (rationale: the ``dtype`` keyword argument is intended to help prevent overflows). Default: ``None``. + If the data type (either specified or resolved) differs from the data type of ``x``, the input array **should** be cast to the specified data type before computing the product (rationale: the ``dtype`` keyword argument is intended to help prevent overflows). Default: ``None``. include_initial: bool - boolean indicating whether to include the initial value as the first value in the output. By convention, the initial value must be the multiplicative identity (i.e., one). Default: ``False``. + boolean indicating whether to include the initial value as the first value in the output. By convention, the initial value **must** be the multiplicative identity (i.e., one). Default: ``False``. Returns ------- out: array - an array containing the cumulative products. The returned array must have a data type as described by the ``dtype`` parameter above. + an array containing the cumulative products. The returned array **must** have a data type as described by the ``dtype`` parameter above. - Let ``N`` be the size of the axis along which to compute the cumulative product. The returned array must have a shape determined according to the following rules: + Let ``M`` be the size of the axis along which to compute the cumulative product. The returned array **must** have a shape determined according to the following rules: - - if ``include_initial`` is ``True``, the returned array must have the same shape as ``x``, except the size of the axis along which to compute the cumulative product must be ``N+1``. - - if ``include_initial`` is ``False``, the returned array must have the same shape as ``x``. + - if ``include_initial`` is ``True``, the returned array **must** have the same shape as ``x``, except the size of the axis along which to compute the cumulative product **must** be ``M+1``. + - if ``include_initial`` is ``False``, the returned array **must** have the same shape as ``x``. Notes ----- @@ -1617,7 +1621,7 @@ class cumulative_prod[TArray: Array, TDtype](Protocol): **Special Cases** - For both real-valued and complex floating-point operands, special cases must be handled as if the operation is implemented by successive application of :func:`~array_api.multiply`. + For both real-valued and complex floating-point operands, special cases **must** be handled as if the operation is implemented by successive application of :func:`~array_api.multiply`. .. versionadded:: 2024.12 @@ -1635,32 +1639,32 @@ class cumulative_sum[TArray: Array, TDtype](Protocol): Parameters ---------- x: array - input array. Should have one or more dimensions (axes). Should have a numeric data type. + input array. **Should** have one or more dimensions (axes). **Should** have a numeric data type. axis: Optional[int] - axis along which a cumulative sum must be computed. If ``axis`` is negative, the function must determine the axis along which to compute a cumulative sum by counting from the last dimension. + axis along which to compute the cumulative sum. A valid axis **must** be an integer on the interval ``[-N, N)``, where ``N`` is the number of axes in ``x``. If an axis is specified as a negative integer, the function **must** determine the axis along which to perform the operation by counting backward from the last axis (where ``-1`` refers to the last axis). If provided an invalid axis, the function **must** raise an exception. - If ``x`` is a one-dimensional array, providing an ``axis`` is optional; however, if ``x`` has more than one dimension, providing an ``axis`` is required. + If ``x`` is a one-dimensional array, providing an ``axis`` **must** be optional; however, if ``x`` has more than one dimension, providing an ``axis`` **must** be required. dtype: Optional[dtype] - data type of the returned array. If ``None``, the returned array must have the same data type as ``x``, unless ``x`` has an integer data type supporting a smaller range of values than the default integer data type (e.g., ``x`` has an ``int16`` or ``uint32`` data type and the default integer data type is ``int64``). In those latter cases: + data type of the returned array. If ``None``, the returned array **must** have the same data type as ``x``, unless ``x`` has an integer data type supporting a smaller range of values than the default integer data type (e.g., ``x`` has an ``int16`` or ``uint32`` data type and the default integer data type is ``int64``). In those latter cases: - - if ``x`` has a signed integer data type (e.g., ``int16``), the returned array must have the default integer data type. - - if ``x`` has an unsigned integer data type (e.g., ``uint16``), the returned array must have an unsigned integer data type having the same number of bits as the default integer data type (e.g., if the default integer data type is ``int32``, the returned array must have a ``uint32`` data type). + - if ``x`` has a signed integer data type (e.g., ``int16``), the returned array **must** have the default integer data type. + - if ``x`` has an unsigned integer data type (e.g., ``uint16``), the returned array **must** have an unsigned integer data type having the same number of bits as the default integer data type (e.g., if the default integer data type is ``int32``, the returned array **must** have a ``uint32`` data type). - If the data type (either specified or resolved) differs from the data type of ``x``, the input array should be cast to the specified data type before computing the sum (rationale: the ``dtype`` keyword argument is intended to help prevent overflows). Default: ``None``. + If the data type (either specified or resolved) differs from the data type of ``x``, the input array **should** be cast to the specified data type before computing the sum (rationale: the ``dtype`` keyword argument is intended to help prevent overflows). Default: ``None``. include_initial: bool - boolean indicating whether to include the initial value as the first value in the output. By convention, the initial value must be the additive identity (i.e., zero). Default: ``False``. + boolean indicating whether to include the initial value as the first value in the output. By convention, the initial value **must** be the additive identity (i.e., zero). Default: ``False``. Returns ------- out: array - an array containing the cumulative sums. The returned array must have a data type as described by the ``dtype`` parameter above. + an array containing the cumulative sums. The returned array **must** have a data type as described by the ``dtype`` parameter above. - Let ``N`` be the size of the axis along which to compute the cumulative sum. The returned array must have a shape determined according to the following rules: + Let ``M`` be the size of the axis along which to compute the cumulative sum. The returned array **must** have a shape determined according to the following rules: - - if ``include_initial`` is ``True``, the returned array must have the same shape as ``x``, except the size of the axis along which to compute the cumulative sum must be ``N+1``. - - if ``include_initial`` is ``False``, the returned array must have the same shape as ``x``. + - if ``include_initial`` is ``True``, the returned array **must** have the same shape as ``x``, except the size of the axis along which to compute the cumulative sum **must** be ``M+1``. + - if ``include_initial`` is ``False``, the returned array **must** have the same shape as ``x``. Notes ----- @@ -1668,12 +1672,12 @@ class cumulative_sum[TArray: Array, TDtype](Protocol): **Special Cases** - For both real-valued and complex floating-point operands, special cases must be handled as if the operation is implemented by successive application of :func:`~array_api.add`. + For both real-valued and complex floating-point operands, special cases **must** be handled as if the operation is implemented by successive application of :func:`~array_api.add`. .. versionadded:: 2023.12 .. versionchanged:: 2024.12 - Behavior when providing a zero-dimensional array is explicitly left unspecified. + Behavior when providing a zero-dimensional array is explicitly left unspecified. """ @@ -1689,33 +1693,33 @@ class max[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a real-valued data type. + input array. **Should** have a real-valued data type. axis: Optional[Union[int, Tuple[int, ...]]] - axis or axes along which maximum values must be computed. By default, the maximum value must be computed over the entire array. If a tuple of integers, maximum values must be computed over multiple axes. Default: ``None``. + axis or axes along which to compute maximum values. A valid axis **must** be an integer on the interval ``[-N, N)``, where ``N`` is the number of axes in ``x``. If an axis is specified as a negative integer, the function **must** determine the axis along which to perform the operation by counting backward from the last axis (where ``-1`` refers to the last axis). If provided an invalid axis, the function **must** raise an exception. By default, the maximum value **must** be computed over the entire array. If a tuple of integers, maximum values **must** be computed over multiple axes. Default: ``None``. keepdims: bool - if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. + if ``True``, the reduced axes (dimensions) **must** be included in the result as singleton dimensions, and, accordingly, the result **must** be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) **must** not be included in the result. Default: ``False``. Returns ------- out: array - if the maximum value was computed over the entire array, a zero-dimensional array containing the maximum value; otherwise, a non-zero-dimensional array containing the maximum values. The returned array must have the same data type as ``x``. + if the maximum value is computed over the entire array, a zero-dimensional array containing the maximum value; otherwise, a non-zero-dimensional array containing the maximum values. The returned array **must** have the same data type as ``x``. Notes ----- - When the number of elements over which to compute the maximum value is zero, the maximum value is implementation-defined. Specification-compliant libraries may choose to raise an error, return a sentinel value (e.g., if ``x`` is a floating-point input array, return ``NaN``), or return the minimum possible value for the input array ``x`` data type (e.g., if ``x`` is a floating-point array, return ``-infinity``). + - When the number of elements over which to compute the maximum value is zero, the maximum value is implementation-defined. Specification-compliant libraries **may** choose to raise an error, return a sentinel value (e.g., if ``x`` is a floating-point input array, return ``NaN``), or return the minimum possible value for the input array ``x`` data type (e.g., if ``x`` is a floating-point array, return ``-infinity``). - The order of signed zeros is unspecified and thus implementation-defined. When choosing between ``-0`` or ``+0`` as a maximum value, specification-compliant libraries may choose to return either value. + - The order of signed zeros is unspecified and thus implementation-defined. When choosing between ``-0`` or ``+0`` as a maximum value, specification-compliant libraries **may** choose to return either value. - For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-defined (see :ref:`complex-number-ordering`). + - For backward compatibility, conforming implementations **may** support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-defined (see :ref:`complex-number-ordering`). **Special Cases** For floating-point operands, - - If ``x_i`` is ``NaN``, the maximum value is ``NaN`` (i.e., ``NaN`` values propagate). + - If ``x_i`` is ``NaN``, the maximum value **must** be ``NaN`` (i.e., ``NaN`` values propagate). .. versionchanged:: 2023.12 - Clarified that the order of signed zeros is implementation-defined. + Clarified that the order of signed zeros is implementation-defined. """ @@ -1731,40 +1735,39 @@ class mean[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a floating-point data type. + input array. **Should** have a floating-point data type. axis: Optional[Union[int, Tuple[int, ...]]] - axis or axes along which arithmetic means must be computed. By default, the mean must be computed over the entire array. If a tuple of integers, arithmetic means must be computed over multiple axes. Default: ``None``. + axis or axes along which to compute arithmetic means. By default, the mean **must** be computed over the entire array. If a tuple of integers, arithmetic means **must** be computed over multiple axes. A valid axis **must** be an integer on the interval ``[-N, N)``, where ``N`` is the number of axes in ``x``. If an axis is specified as a negative integer, the function **must** determine the axis along which to perform the operation by counting backward from the last axis (where ``-1`` refers to the last axis). If provided an invalid axis, the function **must** raise an exception. Default: ``None``. keepdims: bool - if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. + if ``True``, the reduced axes (dimensions) **must** be included in the result as singleton dimensions, and, accordingly, the result **must** be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) **must** not be included in the result. Default: ``False``. Returns ------- out: array - if the arithmetic mean was computed over the entire array, a zero-dimensional array containing the arithmetic mean; otherwise, a non-zero-dimensional array containing the arithmetic means. The returned array must have the same data type as ``x``. - - .. note:: - While this specification recommends that this function only accept input arrays having a floating-point data type, specification-compliant array libraries may choose to accept input arrays having an integer data type. While mixed data type promotion is implementation-defined, if the input array ``x`` has an integer data type, the returned array must have the default real-valued floating-point data type. + if the arithmetic mean is computed over the entire array, a zero-dimensional array containing the arithmetic mean; otherwise, a non-zero-dimensional array containing the arithmetic means. The returned array **must** have the same data type as ``x``. Notes ----- + - While this specification recommends that this function only accept input arrays having a floating-point data type, specification-compliant array libraries **may** choose to accept input arrays having an integer data type. While mixed data type promotion is implementation-defined, if the input array ``x`` has an integer data type, the returned array **must** have the default real-valued floating-point data type. + **Special Cases** - Let ``N`` equal the number of elements over which to compute the arithmetic mean. For real-valued operands, + Let ``M`` equal the number of elements over which to compute the arithmetic mean. For real-valued operands, - - If ``N`` is ``0``, the arithmetic mean is ``NaN``. - - If ``x_i`` is ``NaN``, the arithmetic mean is ``NaN`` (i.e., ``NaN`` values propagate). + - If ``M`` is ``0``, the arithmetic mean **must** be ``NaN``. + - If ``x_i`` is ``NaN``, the arithmetic mean **must** be ``NaN`` (i.e., ``NaN`` values propagate). - For complex floating-point operands, real-valued floating-point special cases should independently apply to the real and imaginary component operations involving real numbers. For example, let ``a = real(x_i)`` and ``b = imag(x_i)``, and + For complex floating-point operands, real-valued floating-point special cases **should** independently apply to the real and imaginary component operations involving real numbers. For example, let ``a = real(x_i)`` and ``b = imag(x_i)``, and - - If ``N`` is ``0``, the arithmetic mean is ``NaN + NaN j``. - - If ``a`` is ``NaN``, the real component of the result is ``NaN``. - - Similarly, if ``b`` is ``NaN``, the imaginary component of the result is ``NaN``. + - If ``M`` is ``0``, the arithmetic mean **must** be ``NaN + NaN j``. + - If ``a`` is ``NaN``, the real component of the result **must** be ``NaN``. + - Similarly, if ``b`` is ``NaN``, the imaginary component of the result **must** be ``NaN``. .. note:: - Array libraries, such as NumPy, PyTorch, and JAX, currently deviate from this specification in their handling of components which are ``NaN`` when computing the arithmetic mean. In general, consumers of array libraries implementing this specification should use :func:`~array_api.isnan` to test whether the result of computing the arithmetic mean over an array have a complex floating-point data type is ``NaN``, rather than relying on ``NaN`` propagation of individual components. + Array libraries, such as NumPy, PyTorch, and JAX, currently deviate from this specification in their handling of components which are ``NaN`` when computing the arithmetic mean. In general, consumers of array libraries implementing this specification are recommended to use :func:`~array_api.isnan` to test whether the result of computing the arithmetic mean over an array have a complex floating-point data type is ``NaN``, rather than relying on ``NaN`` propagation of individual components. .. versionchanged:: 2024.12 - Added complex data type support. + Added complex data type support. """ @@ -1780,33 +1783,33 @@ class min[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a real-valued data type. + input array. **Should** have a real-valued data type. axis: Optional[Union[int, Tuple[int, ...]]] - axis or axes along which minimum values must be computed. By default, the minimum value must be computed over the entire array. If a tuple of integers, minimum values must be computed over multiple axes. Default: ``None``. + axis or axes along which to compute minimum values. By default, the minimum value **must** be computed over the entire array. If a tuple of integers, minimum values **must** be computed over multiple axes. A valid axis **must** be an integer on the interval ``[-N, N)``, where ``N`` is the number of axes in ``x``. If an axis is specified as a negative integer, the function **must** determine the axis along which to perform the operation by counting backward from the last axis (where ``-1`` refers to the last axis). If provided an invalid axis, the function **must** raise an exception. Default: ``None``. keepdims: bool - if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. + if ``True``, the reduced axes (dimensions) **must** be included in the result as singleton dimensions, and, accordingly, the result **must** be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) **must** not be included in the result. Default: ``False``. Returns ------- out: array - if the minimum value was computed over the entire array, a zero-dimensional array containing the minimum value; otherwise, a non-zero-dimensional array containing the minimum values. The returned array must have the same data type as ``x``. + if the minimum value is computed over the entire array, a zero-dimensional array containing the minimum value; otherwise, a non-zero-dimensional array containing the minimum values. The returned array **must** have the same data type as ``x``. Notes ----- - When the number of elements over which to compute the minimum value is zero, the minimum value is implementation-defined. Specification-compliant libraries may choose to raise an error, return a sentinel value (e.g., if ``x`` is a floating-point input array, return ``NaN``), or return the maximum possible value for the input array ``x`` data type (e.g., if ``x`` is a floating-point array, return ``+infinity``). + - When the number of elements over which to compute the minimum value is zero, the minimum value is implementation-defined. Specification-compliant libraries **may** choose to raise an error, return a sentinel value (e.g., if ``x`` is a floating-point input array, return ``NaN``), or return the maximum possible value for the input array ``x`` data type (e.g., if ``x`` is a floating-point array, return ``+infinity``). - The order of signed zeros is unspecified and thus implementation-defined. When choosing between ``-0`` or ``+0`` as a minimum value, specification-compliant libraries may choose to return either value. + - The order of signed zeros is unspecified and thus implementation-defined. When choosing between ``-0`` or ``+0`` as a minimum value, specification-compliant libraries **may** choose to return either value. - For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-defined (see :ref:`complex-number-ordering`). + - For backward compatibility, conforming implementations **may** support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-defined (see :ref:`complex-number-ordering`). **Special Cases** For floating-point operands, - - If ``x_i`` is ``NaN``, the minimum value is ``NaN`` (i.e., ``NaN`` values propagate). + - If ``x_i`` is ``NaN``, the minimum value **must** be ``NaN`` (i.e., ``NaN`` values propagate). .. versionchanged:: 2023.12 - Clarified that the order of signed zeros is implementation-defined. + Clarified that the order of signed zeros is implementation-defined. """ @@ -1822,41 +1825,41 @@ class prod[TArray: Array, TDtype](Protocol): Parameters ---------- x: array - input array. Should have a numeric data type. + input array. **Should** have a numeric data type. axis: Optional[Union[int, Tuple[int, ...]]] - axis or axes along which products must be computed. By default, the product must be computed over the entire array. If a tuple of integers, products must be computed over multiple axes. Default: ``None``. + axis or axes along which to compute products. By default, the product **must** be computed over the entire array. If a tuple of integers, products **must** be computed over multiple axes. A valid axis **must** be an integer on the interval ``[-N, N)``, where ``N`` is the number of axes in ``x``. If an axis is specified as a negative integer, the function **must** determine the axis along which to perform the operation by counting backward from the last axis (where ``-1`` refers to the last axis). If provided an invalid axis, the function **must** raise an exception. Default: ``None``. dtype: Optional[dtype] - data type of the returned array. If ``None``, the returned array must have the same data type as ``x``, unless ``x`` has an integer data type supporting a smaller range of values than the default integer data type (e.g., ``x`` has an ``int16`` or ``uint32`` data type and the default integer data type is ``int64``). In those latter cases: + data type of the returned array. If ``None``, the returned array **must** have the same data type as ``x``, unless ``x`` has an integer data type supporting a smaller range of values than the default integer data type (e.g., ``x`` has an ``int16`` or ``uint32`` data type and the default integer data type is ``int64``). In those latter cases: - - if ``x`` has a signed integer data type (e.g., ``int16``), the returned array must have the default integer data type. - - if ``x`` has an unsigned integer data type (e.g., ``uint16``), the returned array must have an unsigned integer data type having the same number of bits as the default integer data type (e.g., if the default integer data type is ``int32``, the returned array must have a ``uint32`` data type). + - if ``x`` has a signed integer data type (e.g., ``int16``), the returned array **must** have the default integer data type. + - if ``x`` has an unsigned integer data type (e.g., ``uint16``), the returned array **must** have an unsigned integer data type having the same number of bits as the default integer data type (e.g., if the default integer data type is ``int32``, the returned array **must** have a ``uint32`` data type). - If the data type (either specified or resolved) differs from the data type of ``x``, the input array should be cast to the specified data type before computing the sum (rationale: the ``dtype`` keyword argument is intended to help prevent overflows). Default: ``None``. + If the data type (either specified or resolved) differs from the data type of ``x``, the input array **should** be cast to the specified data type before computing the sum (rationale: the ``dtype`` keyword argument is intended to help prevent overflows). Default: ``None``. keepdims: bool - if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. + if ``True``, the reduced axes (dimensions) **must** be included in the result as singleton dimensions, and, accordingly, the result **must** be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) **must** not be included in the result. Default: ``False``. Returns ------- out: array - if the product was computed over the entire array, a zero-dimensional array containing the product; otherwise, a non-zero-dimensional array containing the products. The returned array must have a data type as described by the ``dtype`` parameter above. + if the product is computed over the entire array, a zero-dimensional array containing the product; otherwise, a non-zero-dimensional array containing the products. The returned array **must** have a data type as described by the ``dtype`` parameter above. Notes ----- **Special Cases** - Let ``N`` equal the number of elements over which to compute the product. + Let ``M`` equal the number of elements over which to compute the product. - - If ``N`` is ``0``, the product is `1` (i.e., the empty product). + - If ``M`` is ``0``, the product **must** be `1` (i.e., the empty product). - For both real-valued and complex floating-point operands, special cases must be handled as if the operation is implemented by successive application of :func:`~array_api.multiply`. + For both real-valued and complex floating-point operands, special cases **must** be handled as if the operation is implemented by successive application of :func:`~array_api.multiply`. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. .. versionchanged:: 2023.12 - Required the function to return a floating-point array having the same data type as the input array when provided a floating-point array. + Required the function to return a floating-point array having the same data type as the input array when provided a floating-point array. """ @@ -1872,30 +1875,29 @@ class std[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a real-valued floating-point data type. + input array. **Should** have a real-valued floating-point data type. axis: Optional[Union[int, Tuple[int, ...]]] - axis or axes along which standard deviations must be computed. By default, the standard deviation must be computed over the entire array. If a tuple of integers, standard deviations must be computed over multiple axes. Default: ``None``. + axis or axes along which to compute standard deviations. By default, the standard deviation **must** be computed over the entire array. If a tuple of integers, standard deviations **must** be computed over multiple axes. A valid axis **must** be an integer on the interval ``[-N, N)``, where ``N`` is the number of axes in ``x``. If an axis is specified as a negative integer, the function **must** determine the axis along which to perform the operation by counting backward from the last axis (where ``-1`` refers to the last axis). If provided an invalid axis, the function **must** raise an exception. Default: ``None``. correction: Union[int, float] - degrees of freedom adjustment. Setting this parameter to a value other than ``0`` has the effect of adjusting the divisor during the calculation of the standard deviation according to ``N-c`` where ``N`` corresponds to the total number of elements over which the standard deviation is computed and ``c`` corresponds to the provided degrees of freedom adjustment. When computing the standard deviation of a population, setting this parameter to ``0`` is the standard choice (i.e., the provided array contains data constituting an entire population). When computing the corrected sample standard deviation, setting this parameter to ``1`` is the standard choice (i.e., the provided array contains data sampled from a larger population; this is commonly referred to as Bessel's correction). Default: ``0``. + degrees of freedom adjustment. Setting this parameter to a value other than ``0`` has the effect of adjusting the divisor during the calculation of the standard deviation according to ``M-c`` where ``M`` corresponds to the total number of elements over which the standard deviation is computed and ``c`` corresponds to the provided degrees of freedom adjustment. When computing the standard deviation of a population, setting this parameter to ``0`` is the standard choice (i.e., the provided array contains data constituting an entire population). When computing the corrected sample standard deviation, setting this parameter to ``1`` is the standard choice (i.e., the provided array contains data sampled from a larger population; this is commonly referred to as Bessel's correction). Default: ``0``. keepdims: bool - if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. + if ``True``, the reduced axes (dimensions) **must** be included in the result as singleton dimensions, and, accordingly, the result **must** be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) **must** not be included in the result. Default: ``False``. Returns ------- out: array - if the standard deviation was computed over the entire array, a zero-dimensional array containing the standard deviation; otherwise, a non-zero-dimensional array containing the standard deviations. The returned array must have the same data type as ``x``. - - .. note:: - While this specification recommends that this function only accept input arrays having a real-valued floating-point data type, specification-compliant array libraries may choose to accept input arrays having an integer data type. While mixed data type promotion is implementation-defined, if the input array ``x`` has an integer data type, the returned array must have the default real-valued floating-point data type. + if the standard deviation is computed over the entire array, a zero-dimensional array containing the standard deviation; otherwise, a non-zero-dimensional array containing the standard deviations. The returned array **must** have the same data type as ``x``. Notes ----- + - While this specification recommends that this function only accept input arrays having a real-valued floating-point data type, specification-compliant array libraries **may** choose to accept input arrays having an integer data type. While mixed data type promotion is implementation-defined, if the input array ``x`` has an integer data type, the returned array **must** have the default real-valued floating-point data type. + **Special Cases** - Let ``N`` equal the number of elements over which to compute the standard deviation. + Let ``M`` equal the number of elements over which to compute the standard deviation. - - If ``N - correction`` is less than or equal to ``0``, the standard deviation is ``NaN``. - - If ``x_i`` is ``NaN``, the standard deviation is ``NaN`` (i.e., ``NaN`` values propagate). + - If ``M - correction`` is less than or equal to ``0``, the standard deviation **must** be ``NaN``. + - If ``x_i`` is ``NaN``, the standard deviation **must** be ``NaN`` (i.e., ``NaN`` values propagate). """ @@ -1911,41 +1913,41 @@ class sum[TArray: Array, TDtype](Protocol): Parameters ---------- x: array - input array. Should have a numeric data type. + input array. **Should** have a numeric data type. axis: Optional[Union[int, Tuple[int, ...]]] - axis or axes along which sums must be computed. By default, the sum must be computed over the entire array. If a tuple of integers, sums must be computed over multiple axes. Default: ``None``. + axis or axes along which sums **must** be computed. By default, the sum **must** be computed over the entire array. If a tuple of integers, sums **must** be computed over multiple axes. A valid axis **must** be an integer on the interval ``[-N, N)``, where ``N`` is the number of axes in ``x``. If an axis is specified as a negative integer, the function **must** determine the axis along which to perform the operation by counting backward from the last axis (where ``-1`` refers to the last axis). If provided an invalid axis, the function **must** raise an exception. Default: ``None``. dtype: Optional[dtype] - data type of the returned array. If ``None``, the returned array must have the same data type as ``x``, unless ``x`` has an integer data type supporting a smaller range of values than the default integer data type (e.g., ``x`` has an ``int16`` or ``uint32`` data type and the default integer data type is ``int64``). In those latter cases: + data type of the returned array. If ``None``, the returned array **must** have the same data type as ``x``, unless ``x`` has an integer data type supporting a smaller range of values than the default integer data type (e.g., ``x`` has an ``int16`` or ``uint32`` data type and the default integer data type is ``int64``). In those latter cases: - - if ``x`` has a signed integer data type (e.g., ``int16``), the returned array must have the default integer data type. - - if ``x`` has an unsigned integer data type (e.g., ``uint16``), the returned array must have an unsigned integer data type having the same number of bits as the default integer data type (e.g., if the default integer data type is ``int32``, the returned array must have a ``uint32`` data type). + - if ``x`` has a signed integer data type (e.g., ``int16``), the returned array **must** have the default integer data type. + - if ``x`` has an unsigned integer data type (e.g., ``uint16``), the returned array **must** have an unsigned integer data type having the same number of bits as the default integer data type (e.g., if the default integer data type is ``int32``, the returned array **must** have a ``uint32`` data type). - If the data type (either specified or resolved) differs from the data type of ``x``, the input array should be cast to the specified data type before computing the sum (rationale: the ``dtype`` keyword argument is intended to help prevent overflows). Default: ``None``. + If the data type (either specified or resolved) differs from the data type of ``x``, the input array **should** be cast to the specified data type before computing the sum (rationale: the ``dtype`` keyword argument is intended to help prevent overflows). Default: ``None``. keepdims: bool - if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. + if ``True``, the reduced axes (dimensions) **must** be included in the result as singleton dimensions, and, accordingly, the result **must** be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) **must** not be included in the result. Default: ``False``. Returns ------- out: array - if the sum was computed over the entire array, a zero-dimensional array containing the sum; otherwise, an array containing the sums. The returned array must have a data type as described by the ``dtype`` parameter above. + if the sum is computed over the entire array, a zero-dimensional array containing the sum; otherwise, an array containing the sums. The returned array **must** have a data type as described by the ``dtype`` parameter above. Notes ----- **Special Cases** - Let ``N`` equal the number of elements over which to compute the sum. + Let ``M`` equal the number of elements over which to compute the sum. - - If ``N`` is ``0``, the sum is ``0`` (i.e., the empty sum). + - If ``M`` is ``0``, the sum **must** be ``0`` (i.e., the empty sum). - For both real-valued and complex floating-point operands, special cases must be handled as if the operation is implemented by successive application of :func:`~array_api.add`. + For both real-valued and complex floating-point operands, special cases **must** be handled as if the operation is implemented by successive application of :func:`~array_api.add`. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. .. versionchanged:: 2023.12 - Required the function to return a floating-point array having the same data type as the input array when provided a floating-point array. + Required the function to return a floating-point array having the same data type as the input array when provided a floating-point array. """ @@ -1961,31 +1963,29 @@ class var[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a real-valued floating-point data type. + input array. **Should** have a real-valued floating-point data type. axis: Optional[Union[int, Tuple[int, ...]]] - axis or axes along which variances must be computed. By default, the variance must be computed over the entire array. If a tuple of integers, variances must be computed over multiple axes. Default: ``None``. + axis or axes along which variances **must** be computed. By default, the variance **must** be computed over the entire array. If a tuple of integers, variances **must** be computed over multiple axes. A valid axis **must** be an integer on the interval ``[-N, N)``, where ``N`` is the number of axes in ``x``. If an axis is specified as a negative integer, the function **must** determine the axis along which to perform the operation by counting backward from the last axis (where ``-1`` refers to the last axis). If provided an invalid axis, the function **must** raise an exception. Default: ``None``. correction: Union[int, float] - degrees of freedom adjustment. Setting this parameter to a value other than ``0`` has the effect of adjusting the divisor during the calculation of the variance according to ``N-c`` where ``N`` corresponds to the total number of elements over which the variance is computed and ``c`` corresponds to the provided degrees of freedom adjustment. When computing the variance of a population, setting this parameter to ``0`` is the standard choice (i.e., the provided array contains data constituting an entire population). When computing the unbiased sample variance, setting this parameter to ``1`` is the standard choice (i.e., the provided array contains data sampled from a larger population; this is commonly referred to as Bessel's correction). Default: ``0``. + degrees of freedom adjustment. Setting this parameter to a value other than ``0`` has the effect of adjusting the divisor during the calculation of the variance according to ``M-c`` where ``M`` corresponds to the total number of elements over which the variance is computed and ``c`` corresponds to the provided degrees of freedom adjustment. When computing the variance of a population, setting this parameter to ``0`` is the standard choice (i.e., the provided array contains data constituting an entire population). When computing the unbiased sample variance, setting this parameter to ``1`` is the standard choice (i.e., the provided array contains data sampled from a larger population; this is commonly referred to as Bessel's correction). Default: ``0``. keepdims: bool - if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``. + if ``True``, the reduced axes (dimensions) **must** be included in the result as singleton dimensions, and, accordingly, the result **must** be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) **must** not be included in the result. Default: ``False``. Returns ------- out: array - if the variance was computed over the entire array, a zero-dimensional array containing the variance; otherwise, a non-zero-dimensional array containing the variances. The returned array must have the same data type as ``x``. - - - .. note:: - While this specification recommends that this function only accept input arrays having a real-valued floating-point data type, specification-compliant array libraries may choose to accept input arrays having an integer data type. While mixed data type promotion is implementation-defined, if the input array ``x`` has an integer data type, the returned array must have the default real-valued floating-point data type. + if the variance is computed over the entire array, a zero-dimensional array containing the variance; otherwise, a non-zero-dimensional array containing the variances. The returned array **must** have the same data type as ``x``. Notes ----- + - While this specification recommends that this function only accept input arrays having a real-valued floating-point data type, specification-compliant array libraries **may** choose to accept input arrays having an integer data type. While mixed data type promotion is implementation-defined, if the input array ``x`` has an integer data type, the returned array **must** have the default real-valued floating-point data type. + **Special Cases** - Let ``N`` equal the number of elements over which to compute the variance. + Let ``M`` equal the number of elements over which to compute the variance. - - If ``N - correction`` is less than or equal to ``0``, the variance is ``NaN``. - - If ``x_i`` is ``NaN``, the variance is ``NaN`` (i.e., ``NaN`` values propagate). + - If ``M - correction`` is less than or equal to ``0``, the variance **must** be ``NaN``. + - If ``x_i`` is ``NaN``, the variance **must** be ``NaN`` (i.e., ``NaN`` values propagate). """ @@ -2001,24 +2001,24 @@ class arange[TArray: Array, TDevice, TDtype](Protocol): Parameters ---------- start: Union[int, float] - if ``stop`` is specified, the start of interval (inclusive); otherwise, the end of the interval (exclusive). If ``stop`` is not specified, the default starting value is ``0``. + if ``stop`` is specified, the start of interval (inclusive); otherwise, the end of the interval (exclusive). If ``stop`` is not specified, the default starting value is ``0``. stop: Optional[Union[int, float]] - the end of the interval. Default: ``None``. + the end of the interval. Default: ``None``. step: Union[int, float] - the distance between two adjacent elements (``out[i+1] - out[i]``). Must not be ``0``; may be negative, this results in an empty array if ``stop >= start``. Default: ``1``. + the distance between two adjacent elements (``out[i+1] - out[i]``). Must not be ``0``; may be negative, this results in an empty array if ``stop >= start``. Default: ``1``. dtype: Optional[dtype] - output array data type. If ``dtype`` is ``None``, the output array data type must be inferred from ``start``, ``stop`` and ``step``. If those are all integers, the output array dtype must be the default integer dtype; if one or more have type ``float``, then the output array dtype must be the default real-valued floating-point data type. Default: ``None``. + output array data type. If ``dtype`` is ``None``, the output array data type must be inferred from ``start``, ``stop`` and ``step``. If those are all integers, the output array dtype must be the default integer dtype; if one or more have type ``float``, then the output array dtype must be the default real-valued floating-point data type. Default: ``None``. device: Optional[device] - device on which to place the created array. Default: ``None``. + device on which to place the created array. Default: ``None``. .. note:: - This function cannot guarantee that the interval does not include the ``stop`` value in those cases where ``step`` is not an integer and floating-point rounding errors affect the length of the output array. + This function cannot guarantee that the interval does not include the ``stop`` value in those cases where ``step`` is not an integer and floating-point rounding errors affect the length of the output array. Returns ------- out: array - a one-dimensional array containing evenly spaced values. The length of the output array must be ``ceil((stop-start)/step)`` if ``stop - start`` and ``step`` have the same sign, and length ``0`` otherwise. + a one-dimensional array containing evenly spaced values. The length of the output array must be ``ceil((stop-start)/step)`` if ``stop - start`` and ``step`` have the same sign, and length ``0`` otherwise. """ @@ -2027,39 +2027,39 @@ def __call__(self, start: int | float, /, stop: int | float | None = None, step: @runtime_checkable -class asarray[TSupportsbufferprotocol, TArray: Array, TDevice, TDtype](Protocol): +class asarray[TArray: Array, TDevice, TDtype](Protocol): r""" Convert the input to an array. Parameters ---------- obj: Union[array, bool, int, float, complex, NestedSequence[bool | int | float | complex], SupportsBufferProtocol] - object to be converted to an array. May be a Python scalar, a (possibly nested) sequence of Python scalars, or an object supporting the Python buffer protocol. + object to be converted to an array. May be a Python scalar, a (possibly nested) sequence of Python scalars, or an object supporting the Python buffer protocol. - .. admonition:: Tip - :class: important + .. admonition:: Tip + :class: important - An object supporting the buffer protocol can be turned into a memoryview through ``memoryview(obj)``. + An object supporting the buffer protocol can be turned into a memoryview through ``memoryview(obj)``. dtype: Optional[dtype] - output array data type. If ``dtype`` is ``None``, the output array data type must be inferred from the data type(s) in ``obj``. If all input values are Python scalars, then, in order of precedence, + output array data type. If ``dtype`` is ``None``, the output array data type must be inferred from the data type(s) in ``obj``. If all input values are Python scalars, then, in order of precedence, - - if all values are of type ``bool``, the output data type must be ``bool``. - - if all values are of type ``int`` or are a mixture of ``bool`` and ``int``, the output data type must be the default integer data type. - - if one or more values are ``complex`` numbers, the output data type must be the default complex floating-point data type. - - if one or more values are ``float``\\s, the output data type must be the default real-valued floating-point data type. + - if all values are of type ``bool``, the output data type must be ``bool``. + - if all values are of type ``int`` or are a mixture of ``bool`` and ``int``, the output data type must be the default integer data type. + - if one or more values are ``complex`` numbers, the output data type must be the default complex floating-point data type. + - if one or more values are ``float``\\s, the output data type must be the default real-valued floating-point data type. - Default: ``None``. + Default: ``None``. device: Optional[device] - device on which to place the created array. If ``device`` is ``None`` and ``obj`` is an array, the output array device must be inferred from ``obj``. Default: ``None``. + device on which to place the created array. If ``device`` is ``None`` and ``obj`` is an array, the output array device must be inferred from ``obj``. Default: ``None``. copy: Optional[bool] - boolean indicating whether or not to copy the input. If ``True``, the function must always copy (see :ref:`copy-keyword-argument`). If ``False``, the function must never copy for input which supports the buffer protocol and must raise a ``ValueError`` in case a copy would be necessary. If ``None``, the function must reuse existing memory buffer if possible and copy otherwise. Default: ``None``. + boolean indicating whether or not to copy the input. If ``True``, the function must always copy (see :ref:`copy-keyword-argument`). If ``False``, the function must never copy for input which supports the buffer protocol and must raise a ``ValueError`` in case a copy would be necessary. If ``None``, the function must reuse existing memory buffer if possible and copy otherwise. Default: ``None``. Returns ------- out: array - an array containing the data from ``obj``. + an array containing the data from ``obj``. Notes ----- @@ -2068,12 +2068,12 @@ class asarray[TSupportsbufferprotocol, TArray: Array, TDevice, TDtype](Protocol) - If an input value exceeds the precision of the resolved output array data type, behavior is unspecified and thus implementation-defined. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @abstractmethod - def __call__(self, obj: TArray | bool | int | float | complex | NestedSequence | TSupportsbufferprotocol, /, *, dtype: TDtype | None = None, device: TDevice | None = None, copy: bool | None = None) -> TArray: ... + def __call__(self, obj: TArray | bool | int | float | complex | NestedSequence | SupportsBufferProtocol, /, *, dtype: TDtype | None = None, device: TDevice | None = None, copy: bool | None = None) -> TArray: ... @runtime_checkable @@ -2084,16 +2084,16 @@ class empty[TArray: Array, TDevice, TDtype](Protocol): Parameters ---------- shape: Union[int, Tuple[int, ...]] - output array shape. + output array shape. dtype: Optional[dtype] - output array data type. If ``dtype`` is ``None``, the output array data type must be the default real-valued floating-point data type. Default: ``None``. + output array data type. If ``dtype`` is ``None``, the output array data type must be the default real-valued floating-point data type. Default: ``None``. device: Optional[device] - device on which to place the created array. Default: ``None``. + device on which to place the created array. Default: ``None``. Returns ------- out: array - an array containing uninitialized data. + an array containing uninitialized data. """ @@ -2109,16 +2109,16 @@ class empty_like[TArray: Array, TDevice, TDtype](Protocol): Parameters ---------- x: array - input array from which to derive the output array shape. + input array from which to derive the output array shape. dtype: Optional[dtype] - output array data type. If ``dtype`` is ``None``, the output array data type must be inferred from ``x``. Default: ``None``. + output array data type. If ``dtype`` is ``None``, the output array data type must be inferred from ``x``. Default: ``None``. device: Optional[device] - device on which to place the created array. If ``device`` is ``None``, the output array device must be inferred from ``x``. Default: ``None``. + device on which to place the created array. If ``device`` is ``None``, the output array device must be inferred from ``x``. Default: ``None``. Returns ------- out: array - an array having the same shape as ``x`` and containing uninitialized data. + an array having the same shape as ``x`` and containing uninitialized data. """ @@ -2132,31 +2132,31 @@ class eye[TArray: Array, TDevice, TDtype](Protocol): Returns a two-dimensional array with ones on the ``k``\\th diagonal and zeros elsewhere. .. note:: - An output array having a complex floating-point data type must have the value ``1 + 0j`` along the ``k``\\th diagonal and ``0 + 0j`` elsewhere. + An output array having a complex floating-point data type must have the value ``1 + 0j`` along the ``k``\\th diagonal and ``0 + 0j`` elsewhere. Parameters ---------- n_rows: int - number of rows in the output array. + number of rows in the output array. n_cols: Optional[int] - number of columns in the output array. If ``None``, the default number of columns in the output array is equal to ``n_rows``. Default: ``None``. + number of columns in the output array. If ``None``, the default number of columns in the output array is equal to ``n_rows``. Default: ``None``. k: int - index of the diagonal. A positive value refers to an upper diagonal, a negative value to a lower diagonal, and ``0`` to the main diagonal. Default: ``0``. + index of the diagonal. A positive value refers to an upper diagonal, a negative value to a lower diagonal, and ``0`` to the main diagonal. Default: ``0``. dtype: Optional[dtype] - output array data type. If ``dtype`` is ``None``, the output array data type must be the default real-valued floating-point data type. Default: ``None``. + output array data type. If ``dtype`` is ``None``, the output array data type must be the default real-valued floating-point data type. Default: ``None``. device: Optional[device] - device on which to place the created array. Default: ``None``. + device on which to place the created array. Default: ``None``. Returns ------- out: array - an array where all elements are equal to zero, except for the ``k``\\th diagonal, whose values are equal to one. + an array where all elements are equal to zero, except for the ``k``\\th diagonal, whose values are equal to one. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -2172,44 +2172,44 @@ class from_dlpack[TArray: Array, TDevice](Protocol): Parameters ---------- x: object - input (array) object. + input (array) object. device: Optional[device] - device on which to place the created array. If ``device`` is ``None`` and ``x`` supports DLPack, the output array must be on the same device as ``x``. Default: ``None``. + device on which to place the created array. If ``device`` is ``None`` and ``x`` supports DLPack, the output array must be on the same device as ``x``. Default: ``None``. - The v2023.12 standard only mandates that a compliant library should offer a way for ``from_dlpack`` to return an array - whose underlying memory is accessible to the Python interpreter, when the corresponding ``device`` is provided. If the - array library does not support such cases at all, the function must raise ``BufferError``. If a copy must be made to - enable this support but ``copy`` is set to ``False``, the function must raise ``ValueError``. + The v2023.12 standard only mandates that a compliant library should offer a way for ``from_dlpack`` to return an array + whose underlying memory is accessible to the Python interpreter, when the corresponding ``device`` is provided. If the + array library does not support such cases at all, the function must raise ``BufferError``. If a copy must be made to + enable this support but ``copy`` is set to ``False``, the function must raise ``ValueError``. - Other device kinds will be considered for standardization in a future version of this API standard. + Other device kinds will be considered for standardization in a future version of this API standard. copy: Optional[bool] - boolean indicating whether or not to copy the input. If ``True``, the function must always copy. If ``False``, the function must never copy, and raise ``BufferError`` in case a copy is deemed necessary (e.g. if a cross-device data movement is requested, and it is not possible without a copy). If ``None``, the function must reuse the existing memory buffer if possible and copy otherwise. Default: ``None``. + boolean indicating whether or not to copy the input. If ``True``, the function must always copy. If ``False``, the function must never copy, and raise ``BufferError`` in case a copy is deemed necessary (e.g. if a cross-device data movement is requested, and it is not possible without a copy). If ``None``, the function must reuse the existing memory buffer if possible and copy otherwise. Default: ``None``. Returns ------- out: array - an array containing the data in ``x``. + an array containing the data in ``x``. - .. admonition:: Note - :class: note + .. admonition:: Note + :class: note - The returned array may be either a copy or a view. See :ref:`data-interchange` for details. + The returned array may be either a copy or a view. See :ref:`data-interchange` for details. Raises ------ BufferError - The ``__dlpack__`` and ``__dlpack_device__`` methods on the input array - may raise ``BufferError`` when the data cannot be exported as DLPack - (e.g., incompatible dtype, strides, or device). It may also raise other errors - when export fails for other reasons (e.g., not enough memory available - to materialize the data). ``from_dlpack`` must propagate such - exceptions. + The ``__dlpack__`` and ``__dlpack_device__`` methods on the input array + may raise ``BufferError`` when the data cannot be exported as DLPack + (e.g., incompatible dtype, strides, or device). It may also raise other errors + when export fails for other reasons (e.g., not enough memory available + to materialize the data). ``from_dlpack`` must propagate such + exceptions. AttributeError - If the ``__dlpack__`` and ``__dlpack_device__`` methods are not present - on the input array. This may happen for libraries that are never able - to export their data with DLPack. + If the ``__dlpack__`` and ``__dlpack_device__`` methods are not present + on the input array. This may happen for libraries that are never able + to export their data with DLPack. ValueError - If data exchange is possible via an explicit copy but ``copy`` is set to ``False``. + If data exchange is possible via an explicit copy but ``copy`` is set to ``False``. Notes ----- @@ -2221,24 +2221,24 @@ class from_dlpack[TArray: Array, TDevice](Protocol): .. code:: python - def func(x, y): - xp_x = x.__array_namespace__() - xp_y = y.__array_namespace__() + def func(x, y): + xp_x = x.__array_namespace__() + xp_y = y.__array_namespace__() - # Other functions than `from_dlpack` only work if both arrays are from the same library. So if - # `y` is from a different one than `x`, let's convert `y` into an array of the same type as `x`: - if not xp_x == xp_y: - y = xp_x.from_dlpack(y, copy=True, device=x.device) + # Other functions than `from_dlpack` only work if both arrays are from the same library. So if + # `y` is from a different one than `x`, let's convert `y` into an array of the same type as `x`: + if not xp_x == xp_y: + y = xp_x.from_dlpack(y, copy=True, device=x.device) - # From now on use `xp_x.xxxxx` functions, as both arrays are from the library `xp_x` - ... + # From now on use `xp_x.xxxxx` functions, as both arrays are from the library `xp_x` + ... .. versionchanged:: 2023.12 - Required exceptions to address unsupported use cases. + Required exceptions to address unsupported use cases. .. versionchanged:: 2023.12 - Added device and copy support. + Added device and copy support. """ @@ -2254,33 +2254,33 @@ class full[TArray: Array, TDevice, TDtype](Protocol): Parameters ---------- shape: Union[int, Tuple[int, ...]] - output array shape. + output array shape. fill_value: Union[bool, int, float, complex] - fill value. + fill value. dtype: Optional[dtype] - output array data type. If ``dtype`` is ``None``, the output array data type must be inferred from ``fill_value`` according to the following rules: + output array data type. If ``dtype`` is ``None``, the output array data type must be inferred from ``fill_value`` according to the following rules: - - If the fill value is an ``int``, the output array data type must be the default integer data type. - - If the fill value is a ``float``, the output array data type must be the default real-valued floating-point data type. - - If the fill value is a ``complex`` number, the output array data type must be the default complex floating-point data type. - - If the fill value is a ``bool``, the output array must have a boolean data type. Default: ``None``. + - If the fill value is an ``int``, the output array data type must be the default integer data type. + - If the fill value is a ``float``, the output array data type must be the default real-valued floating-point data type. + - If the fill value is a ``complex`` number, the output array data type must be the default complex floating-point data type. + - If the fill value is a ``bool``, the output array must have a boolean data type. Default: ``None``. - .. note:: - If the ``fill_value`` exceeds the precision of the resolved default output array data type, behavior is left unspecified and, thus, implementation-defined. + .. note:: + If the ``fill_value`` exceeds the precision of the resolved default output array data type, behavior is left unspecified and, thus, implementation-defined. device: Optional[device] - device on which to place the created array. Default: ``None``. + device on which to place the created array. Default: ``None``. Returns ------- out: array - an array where every element is equal to ``fill_value``. + an array where every element is equal to ``fill_value``. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -2296,31 +2296,31 @@ class full_like[TArray: Array, TDevice, TDtype](Protocol): Parameters ---------- x: array - input array from which to derive the output array shape. + input array from which to derive the output array shape. fill_value: Union[bool, int, float, complex] - fill value. + fill value. dtype: Optional[dtype] - output array data type. If ``dtype`` is ``None``, the output array data type must be inferred from ``x``. Default: ``None``. + output array data type. If ``dtype`` is ``None``, the output array data type must be inferred from ``x``. Default: ``None``. - .. note:: - If the ``fill_value`` exceeds the precision of the resolved output array data type, behavior is unspecified and, thus, implementation-defined. + .. note:: + If the ``fill_value`` exceeds the precision of the resolved output array data type, behavior is unspecified and, thus, implementation-defined. - .. note:: - If the ``fill_value`` has a data type which is not of the same data type kind (boolean, integer, or floating-point) as the resolved output array data type (see :ref:`type-promotion`), behavior is unspecified and, thus, implementation-defined. + .. note:: + If the ``fill_value`` has a data type which is not of the same data type kind (boolean, integer, or floating-point) as the resolved output array data type (see :ref:`type-promotion`), behavior is unspecified and, thus, implementation-defined. device: Optional[device] - device on which to place the created array. If ``device`` is ``None``, the output array device must be inferred from ``x``. Default: ``None``. + device on which to place the created array. If ``device`` is ``None``, the output array device must be inferred from ``x``. Default: ``None``. Returns ------- out: array - an array having the same shape as ``x`` and where every element is equal to ``fill_value``. + an array having the same shape as ``x`` and where every element is equal to ``fill_value``. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -2336,59 +2336,59 @@ class linspace[TArray: Array, TDevice, TDtype](Protocol): Let :math:`N` be the number of generated values (which is either ``num`` or ``num+1`` depending on whether ``endpoint`` is ``True`` or ``False``, respectively). For real-valued output arrays, the spacing between values is given by .. math:: - \\Delta_{\\textrm{real}} = \\frac{\\textrm{stop} - \\textrm{start}}{N - 1} + \\Delta_{\\textrm{real}} = \\frac{\\textrm{stop} - \\textrm{start}}{N - 1} For complex output arrays, let ``a = real(start)``, ``b = imag(start)``, ``c = real(stop)``, and ``d = imag(stop)``. The spacing between complex values is given by .. math:: - \\Delta_{\\textrm{complex}} = \\frac{c-a}{N-1} + \\frac{d-b}{N-1} j + \\Delta_{\\textrm{complex}} = \\frac{c-a}{N-1} + \\frac{d-b}{N-1} j Parameters ---------- start: Union[int, float, complex] - the start of the interval. + the start of the interval. stop: Union[int, float, complex] - the end of the interval. If ``endpoint`` is ``False``, the function must generate a sequence of ``num+1`` evenly spaced numbers starting with ``start`` and ending with ``stop`` and exclude the ``stop`` from the returned array such that the returned array consists of evenly spaced numbers over the half-open interval ``[start, stop)``. If ``endpoint`` is ``True``, the output array must consist of evenly spaced numbers over the closed interval ``[start, stop]``. Default: ``True``. + the end of the interval. If ``endpoint`` is ``False``, the function must generate a sequence of ``num+1`` evenly spaced numbers starting with ``start`` and ending with ``stop`` and exclude the ``stop`` from the returned array such that the returned array consists of evenly spaced numbers over the half-open interval ``[start, stop)``. If ``endpoint`` is ``True``, the output array must consist of evenly spaced numbers over the closed interval ``[start, stop]``. Default: ``True``. - .. note:: - The step size changes when `endpoint` is `False`. + .. note:: + The step size changes when `endpoint` is `False`. num: int - number of samples. Must be a nonnegative integer value. + number of samples. Must be a nonnegative integer value. dtype: Optional[dtype] - output array data type. Should be a floating-point data type. If ``dtype`` is ``None``, + output array data type. Should be a floating-point data type. If ``dtype`` is ``None``, - - if either ``start`` or ``stop`` is a ``complex`` number, the output data type must be the default complex floating-point data type. - - if both ``start`` and ``stop`` are real-valued, the output data type must be the default real-valued floating-point data type. + - if either ``start`` or ``stop`` is a ``complex`` number, the output data type must be the default complex floating-point data type. + - if both ``start`` and ``stop`` are real-valued, the output data type must be the default real-valued floating-point data type. - Default: ``None``. + Default: ``None``. - .. admonition:: Note - :class: note + .. admonition:: Note + :class: note - If ``dtype`` is not ``None``, conversion of ``start`` and ``stop`` should obey :ref:`type-promotion` rules. Conversions not specified according to :ref:`type-promotion` rules may or may not be permitted by a conforming array library. + If ``dtype`` is not ``None``, conversion of ``start`` and ``stop`` should obey :ref:`type-promotion` rules. Conversions not specified according to :ref:`type-promotion` rules may or may not be permitted by a conforming array library. device: Optional[device] - device on which to place the created array. Default: ``None``. + device on which to place the created array. Default: ``None``. endpoint: bool - boolean indicating whether to include ``stop`` in the interval. Default: ``True``. + boolean indicating whether to include ``stop`` in the interval. Default: ``True``. Returns ------- out: array - a one-dimensional array containing evenly spaced values. + a one-dimensional array containing evenly spaced values. Notes ----- .. note:: - While this specification recommends that this function only return arrays having a floating-point data type, specification-compliant array libraries may choose to support output arrays having an integer data type (e.g., due to backward compatibility concerns). However, function behavior when generating integer output arrays is unspecified and, thus, is implementation-defined. Accordingly, using this function to generate integer output arrays is not portable. + While this specification recommends that this function only return arrays having a floating-point data type, specification-compliant array libraries may choose to support output arrays having an integer data type (e.g., due to backward compatibility concerns). However, function behavior when generating integer output arrays is unspecified and, thus, is implementation-defined. Accordingly, using this function to generate integer output arrays is not portable. .. note:: - As mixed data type promotion is implementation-defined, behavior when ``start`` or ``stop`` exceeds the maximum safe integer of an output floating-point data type is implementation-defined. An implementation may choose to overflow or raise an exception. + As mixed data type promotion is implementation-defined, behavior when ``start`` or ``stop`` exceeds the maximum safe integer of an output floating-point data type is implementation-defined. An implementation may choose to overflow or raise an exception. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -2404,29 +2404,29 @@ class meshgrid[TArray: Array](Protocol): Parameters ---------- arrays: array - an arbitrary number of one-dimensional arrays representing grid coordinates. Each array should have the same numeric data type. + an arbitrary number of one-dimensional arrays representing grid coordinates. Each array should have the same numeric data type. indexing: Literal["xy", "ij"] - Cartesian ``'xy'`` or matrix ``'ij'`` indexing of output. If provided zero or one one-dimensional vector(s) (i.e., the zero- and one-dimensional cases, respectively), the ``indexing`` keyword has no effect and should be ignored. Default: ``'xy'``. + Cartesian ``'xy'`` or matrix ``'ij'`` indexing of output. If provided zero or one one-dimensional vector(s) (i.e., the zero- and one-dimensional cases, respectively), the ``indexing`` keyword has no effect and should be ignored. Default: ``'xy'``. Returns ------- out: List[array] - list of N arrays, where ``N`` is the number of provided one-dimensional input arrays. Each returned array must have rank ``N``. For ``N`` one-dimensional arrays having lengths ``Ni = len(xi)``, + list of N arrays, where ``N`` is the number of provided one-dimensional input arrays. Each returned array must have rank ``N``. For ``N`` one-dimensional arrays having lengths ``Ni = len(xi)``, - - if matrix indexing ``ij``, then each returned array must have the shape ``(N1, N2, N3, ..., Nn)``. - - if Cartesian indexing ``xy``, then each returned array must have shape ``(N2, N1, N3, ..., Nn)``. + - if matrix indexing ``ij``, then each returned array must have the shape ``(N1, N2, N3, ..., Nn)``. + - if Cartesian indexing ``xy``, then each returned array must have shape ``(N2, N1, N3, ..., Nn)``. - Accordingly, for the two-dimensional case with input one-dimensional arrays of length ``M`` and ``N``, if matrix indexing ``ij``, then each returned array must have shape ``(M, N)``, and, if Cartesian indexing ``xy``, then each returned array must have shape ``(N, M)``. + Accordingly, for the two-dimensional case with input one-dimensional arrays of length ``M`` and ``N``, if matrix indexing ``ij``, then each returned array must have shape ``(M, N)``, and, if Cartesian indexing ``xy``, then each returned array must have shape ``(N, M)``. - Similarly, for the three-dimensional case with input one-dimensional arrays of length ``M``, ``N``, and ``P``, if matrix indexing ``ij``, then each returned array must have shape ``(M, N, P)``, and, if Cartesian indexing ``xy``, then each returned array must have shape ``(N, M, P)``. + Similarly, for the three-dimensional case with input one-dimensional arrays of length ``M``, ``N``, and ``P``, if matrix indexing ``ij``, then each returned array must have shape ``(M, N, P)``, and, if Cartesian indexing ``xy``, then each returned array must have shape ``(N, M, P)``. - Each returned array should have the same data type as the input arrays. + Each returned array should have the same data type as the input arrays. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -2440,27 +2440,27 @@ class ones[TArray: Array, TDevice, TDtype](Protocol): Returns a new array having a specified ``shape`` and filled with ones. .. note:: - An output array having a complex floating-point data type must contain complex numbers having a real component equal to one and an imaginary component equal to zero (i.e., ``1 + 0j``). + An output array having a complex floating-point data type must contain complex numbers having a real component equal to one and an imaginary component equal to zero (i.e., ``1 + 0j``). Parameters ---------- shape: Union[int, Tuple[int, ...]] - output array shape. + output array shape. dtype: Optional[dtype] - output array data type. If ``dtype`` is ``None``, the output array data type must be the default real-valued floating-point data type. Default: ``None``. + output array data type. If ``dtype`` is ``None``, the output array data type must be the default real-valued floating-point data type. Default: ``None``. device: Optional[device] - device on which to place the created array. Default: ``None``. + device on which to place the created array. Default: ``None``. Returns ------- out: array - an array containing ones. + an array containing ones. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -2474,27 +2474,27 @@ class ones_like[TArray: Array, TDevice, TDtype](Protocol): Returns a new array filled with ones and having the same ``shape`` as an input array ``x``. .. note:: - An output array having a complex floating-point data type must contain complex numbers having a real component equal to one and an imaginary component equal to zero (i.e., ``1 + 0j``). + An output array having a complex floating-point data type must contain complex numbers having a real component equal to one and an imaginary component equal to zero (i.e., ``1 + 0j``). Parameters ---------- x: array - input array from which to derive the output array shape. + input array from which to derive the output array shape. dtype: Optional[dtype] - output array data type. If ``dtype`` is ``None``, the output array data type must be inferred from ``x``. Default: ``None``. + output array data type. If ``dtype`` is ``None``, the output array data type must be inferred from ``x``. Default: ``None``. device: Optional[device] - device on which to place the created array. If ``device`` is ``None``, the output array device must be inferred from ``x``. Default: ``None``. + device on which to place the created array. If ``device`` is ``None``, the output array device must be inferred from ``x``. Default: ``None``. Returns ------- out: array - an array having the same shape as ``x`` and filled with ones. + an array having the same shape as ``x`` and filled with ones. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -2508,22 +2508,22 @@ class tril[TArray: Array](Protocol): Returns the lower triangular part of a matrix (or a stack of matrices) ``x``. .. note:: - The lower triangular part of the matrix is defined as the elements on and below the specified diagonal ``k``. + The lower triangular part of the matrix is defined as the elements on and below the specified diagonal ``k``. Parameters ---------- x: array - input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. + input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. k: int - diagonal above which to zero elements. If ``k = 0``, the diagonal is the main diagonal. If ``k < 0``, the diagonal is below the main diagonal. If ``k > 0``, the diagonal is above the main diagonal. Default: ``0``. + diagonal above which to zero elements. If ``k = 0``, the diagonal is the main diagonal. If ``k < 0``, the diagonal is below the main diagonal. If ``k > 0``, the diagonal is above the main diagonal. Default: ``0``. - .. note:: - The main diagonal is defined as the set of indices ``{(i, i)}`` for ``i`` on the interval ``[0, min(M, N) - 1]``. + .. note:: + The main diagonal is defined as the set of indices ``{(i, i)}`` for ``i`` on the interval ``[0, min(M, N) - 1]``. Returns ------- out: array - an array containing the lower triangular part(s). The returned array must have the same shape and data type as ``x``. All elements above the specified diagonal ``k`` must be zeroed. The returned array should be allocated on the same device as ``x``. + an array containing the lower triangular part(s). The returned array must have the same shape and data type as ``x``. All elements above the specified diagonal ``k`` must be zeroed. The returned array should be allocated on the same device as ``x``. """ @@ -2537,22 +2537,22 @@ class triu[TArray: Array](Protocol): Returns the upper triangular part of a matrix (or a stack of matrices) ``x``. .. note:: - The upper triangular part of the matrix is defined as the elements on and above the specified diagonal ``k``. + The upper triangular part of the matrix is defined as the elements on and above the specified diagonal ``k``. Parameters ---------- x: array - input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. + input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. k: int - diagonal below which to zero elements. If ``k = 0``, the diagonal is the main diagonal. If ``k < 0``, the diagonal is below the main diagonal. If ``k > 0``, the diagonal is above the main diagonal. Default: ``0``. + diagonal below which to zero elements. If ``k = 0``, the diagonal is the main diagonal. If ``k < 0``, the diagonal is below the main diagonal. If ``k > 0``, the diagonal is above the main diagonal. Default: ``0``. - .. note:: - The main diagonal is defined as the set of indices ``{(i, i)}`` for ``i`` on the interval ``[0, min(M, N) - 1]``. + .. note:: + The main diagonal is defined as the set of indices ``{(i, i)}`` for ``i`` on the interval ``[0, min(M, N) - 1]``. Returns ------- out: array - an array containing the upper triangular part(s). The returned array must have the same shape and data type as ``x``. All elements below the specified diagonal ``k`` must be zeroed. The returned array should be allocated on the same device as ``x``. + an array containing the upper triangular part(s). The returned array must have the same shape and data type as ``x``. All elements below the specified diagonal ``k`` must be zeroed. The returned array should be allocated on the same device as ``x``. """ @@ -2568,16 +2568,16 @@ class zeros[TArray: Array, TDevice, TDtype](Protocol): Parameters ---------- shape: Union[int, Tuple[int, ...]] - output array shape. + output array shape. dtype: Optional[dtype] - output array data type. If ``dtype`` is ``None``, the output array data type must be the default real-valued floating-point data type. Default: ``None``. + output array data type. If ``dtype`` is ``None``, the output array data type must be the default real-valued floating-point data type. Default: ``None``. device: Optional[device] - device on which to place the created array. Default: ``None``. + device on which to place the created array. Default: ``None``. Returns ------- out: array - an array containing zeros. + an array containing zeros. """ @@ -2593,16 +2593,16 @@ class zeros_like[TArray: Array, TDevice, TDtype](Protocol): Parameters ---------- x: array - input array from which to derive the output array shape. + input array from which to derive the output array shape. dtype: Optional[dtype] - output array data type. If ``dtype`` is ``None``, the output array data type must be inferred from ``x``. Default: ``None``. + output array data type. If ``dtype`` is ``None``, the output array data type must be inferred from ``x``. Default: ``None``. device: Optional[device] - device on which to place the created array. If ``device`` is ``None``, the output array device must be inferred from ``x``. Default: ``None``. + device on which to place the created array. If ``device`` is ``None``, the output array device must be inferred from ``x``. Default: ``None``. Returns ------- out: array - an array having the same shape as ``x`` and filled with zeros. + an array having the same shape as ``x`` and filled with zeros. """ @@ -2620,39 +2620,39 @@ class cholesky[TArray: Array](Protocol): The lower **Cholesky decomposition** of a complex Hermitian or real symmetric positive-definite matrix :math:`x \\in\\ \\mathbb{K}^{n \\times n}` is defined as .. math:: - x = LL^{H} \\qquad \\text{L $\\in\\ \\mathbb{K}^{n \\times n}$} + x = LL^{H} \\qquad \\text{L $\\in\\ \\mathbb{K}^{n \\times n}$} where :math:`L` is a lower triangular matrix and :math:`L^{H}` is the conjugate transpose when :math:`L` is complex-valued and the transpose when :math:`L` is real-valued. The upper Cholesky decomposition is defined similarly .. math:: - x = U^{H}U \\qquad \\text{U $\\in\\ \\mathbb{K}^{n \\times n}$} + x = U^{H}U \\qquad \\text{U $\\in\\ \\mathbb{K}^{n \\times n}$} where :math:`U` is an upper triangular matrix. When ``x`` is a stack of matrices, the function must compute the Cholesky decomposition for each matrix in the stack. .. note:: - Whether an array library explicitly checks whether an input array is Hermitian or a symmetric positive-definite matrix (or a stack of matrices) is implementation-defined. + Whether an array library explicitly checks whether an input array is Hermitian or a symmetric positive-definite matrix (or a stack of matrices) is implementation-defined. Parameters ---------- x: array - input array having shape ``(..., M, M)`` and whose innermost two dimensions form square complex Hermitian or real symmetric positive-definite matrices. Should have a floating-point data type. + input array having shape ``(..., M, M)`` and whose innermost two dimensions form square complex Hermitian or real symmetric positive-definite matrices. Should have a floating-point data type. upper: bool - If ``True``, the result must be the upper-triangular Cholesky factor :math:`U`. If ``False``, the result must be the lower-triangular Cholesky factor :math:`L`. Default: ``False``. + If ``True``, the result must be the upper-triangular Cholesky factor :math:`U`. If ``False``, the result must be the lower-triangular Cholesky factor :math:`L`. Default: ``False``. Returns ------- out: array - an array containing the Cholesky factors for each square matrix. If ``upper`` is ``False``, the returned array must contain lower-triangular matrices; otherwise, the returned array must contain upper-triangular matrices. The returned array must have a floating-point data type determined by :ref:`type-promotion` and must have the same shape as ``x``. + an array containing the Cholesky factors for each square matrix. If ``upper`` is ``False``, the returned array must contain lower-triangular matrices; otherwise, the returned array must contain upper-triangular matrices. The returned array must have a floating-point data type determined by :ref:`type-promotion` and must have the same shape as ``x``. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -2670,20 +2670,20 @@ class cross[TArray: Array](Protocol): Parameters ---------- x1: array - first input array. Must have a numeric data type. The size of the axis over which the cross product is to be computed must be equal to 3. + first input array. Must have a numeric data type. The size of the axis over which the cross product is to be computed must be equal to 3. x2: array - second input array. Must be broadcast compatible with ``x1`` along all axes other than the axis along which the cross-product is computed (see :ref:`broadcasting`). The size of the axis over which the cross product is to be computed must be equal to 3. Must have a numeric data type. + second input array. Must be broadcast compatible with ``x1`` along all axes other than the axis along which the cross-product is computed (see :ref:`broadcasting`). The size of the axis over which the cross product is to be computed must be equal to 3. Must have a numeric data type. - .. note:: - The compute axis (dimension) must not be broadcasted. + .. note:: + The compute axis (dimension) must not be broadcasted. axis: int - the axis (dimension) of ``x1`` and ``x2`` containing the vectors for which to compute the cross product. Should be an integer on the interval ``[-N, -1]``, where ``N`` is ``min(x1.ndim, x2.ndim)``. The function must determine the axis along which to compute the cross product by counting backward from the last dimension (where ``-1`` refers to the last dimension). By default, the function must compute the cross product over the last axis. Default: ``-1``. + the axis (dimension) of ``x1`` and ``x2`` containing the vectors for which to compute the cross product. Should be an integer on the interval ``[-N, -1]``, where ``N`` is ``min(x1.ndim, x2.ndim)``. The function must determine the axis along which to compute the cross product by counting backward from the last dimension (where ``-1`` refers to the last dimension). By default, the function must compute the cross product over the last axis. Default: ``-1``. Returns ------- out: array - an array containing the cross products. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the cross products. The returned array must have a data type determined by :ref:`type-promotion`. Notes @@ -2693,13 +2693,13 @@ class cross[TArray: Array](Protocol): - if the size of the axis over which to compute the cross product is not equal to ``3`` (before broadcasting) for both ``x1`` and ``x2``. .. versionchanged:: 2022.12 - Added support for broadcasting. + Added support for broadcasting. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. .. versionchanged:: 2023.12 - Restricted broadcasting to only non-compute axes and required that ``axis`` be a negative integer. + Restricted broadcasting to only non-compute axes and required that ``axis`` be a negative integer. """ @@ -2715,18 +2715,18 @@ class det[TArray: Array](Protocol): Parameters ---------- x: array - input array having shape ``(..., M, M)`` and whose innermost two dimensions form square matrices. Should have a floating-point data type. + input array having shape ``(..., M, M)`` and whose innermost two dimensions form square matrices. Should have a floating-point data type. Returns ------- out: array - if ``x`` is a two-dimensional array, a zero-dimensional array containing the determinant; otherwise, a non-zero dimensional array containing the determinant for each square matrix. The returned array must have the same data type as ``x``. + if ``x`` is a two-dimensional array, a zero-dimensional array containing the determinant; otherwise, a non-zero dimensional array containing the determinant for each square matrix. The returned array must have the same data type as ``x``. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -2742,20 +2742,20 @@ class diagonal[TArray: Array](Protocol): Parameters ---------- x: array - input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. + input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. offset: int - offset specifying the off-diagonal relative to the main diagonal. + offset specifying the off-diagonal relative to the main diagonal. - - ``offset = 0``: the main diagonal. - - ``offset > 0``: off-diagonal above the main diagonal. - - ``offset < 0``: off-diagonal below the main diagonal. + - ``offset = 0``: the main diagonal. + - ``offset > 0``: off-diagonal above the main diagonal. + - ``offset < 0``: off-diagonal below the main diagonal. - Default: `0`. + Default: `0`. Returns ------- out: array - an array containing the diagonals and whose shape is determined by removing the last two dimensions and appending a dimension equal to the size of the resulting diagonals. The returned array must have the same data type as ``x``. + an array containing the diagonals and whose shape is determined by removing the last two dimensions and appending a dimension equal to the size of the resulting diagonals. The returned array must have the same data type as ``x``. """ @@ -2773,45 +2773,45 @@ class eigh[TArray: Array](Protocol): The **eigenvalue decomposition** of a complex Hermitian or real symmetric matrix :math:`x \\in\\ \\mathbb{K}^{n \\times n}` is defined as .. math:: - x = Q \\Lambda Q^H + x = Q \\Lambda Q^H with :math:`Q \\in \\mathbb{K}^{n \\times n}` and :math:`\\Lambda \\in \\mathbb{R}^n` and where :math:`Q^H` is the conjugate transpose when :math:`Q` is complex and the transpose when :math:`Q` is real-valued and :math:`\\Lambda` is a diagonal matrix whose diagonal elements are the corresponding eigenvalues. When ``x`` is real-valued, :math:`Q` is orthogonal, and, when ``x`` is complex, :math:`Q` is unitary. .. note:: - The eigenvalues of a complex Hermitian or real symmetric matrix are always real. + The eigenvalues of a complex Hermitian or real symmetric matrix are always real. .. warning:: - The eigenvectors of a symmetric matrix are not unique and are not continuous with respect to ``x``. Because eigenvectors are not unique, different hardware and software may compute different eigenvectors. + The eigenvectors of a symmetric matrix are not unique and are not continuous with respect to ``x``. Because eigenvectors are not unique, different hardware and software may compute different eigenvectors. - Non-uniqueness stems from the fact that multiplying an eigenvector by :math:`-1` when ``x`` is real-valued and by :math:`e^{\\phi j}` (:math:`\\phi \\in \\mathbb{R}`) when ``x`` is complex produces another set of valid eigenvectors. + Non-uniqueness stems from the fact that multiplying an eigenvector by :math:`-1` when ``x`` is real-valued and by :math:`e^{\\phi j}` (:math:`\\phi \\in \\mathbb{R}`) when ``x`` is complex produces another set of valid eigenvectors. .. note:: - Whether an array library explicitly checks whether an input array is Hermitian or a symmetric matrix (or a stack of matrices) is implementation-defined. + Whether an array library explicitly checks whether an input array is Hermitian or a symmetric matrix (or a stack of matrices) is implementation-defined. .. note:: - The function ``eig`` will be added in a future version of the specification. + The function ``eig`` will be added in a future version of the specification. Parameters ---------- x: array - input array having shape ``(..., M, M)`` and whose innermost two dimensions form square matrices. Should have a floating-point data type. + input array having shape ``(..., M, M)`` and whose innermost two dimensions form square matrices. Should have a floating-point data type. Returns ------- out: Tuple[array, array] - a namedtuple (``eigenvalues``, ``eigenvectors``) whose + a namedtuple (``eigenvalues``, ``eigenvectors``) whose - - first element must have the field name ``eigenvalues`` (corresponding to :math:`\\operatorname{diag}\\Lambda` above) and must be an array consisting of computed eigenvalues. The array containing the eigenvalues must have shape ``(..., M)`` and must have a real-valued floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``complex128``, then ``eigenvalues`` must be ``float64``). - - second element have have the field name ``eigenvectors`` (corresponding to :math:`Q` above) and must be an array where the columns of the inner most matrices contain the computed eigenvectors. These matrices must be orthogonal. The array containing the eigenvectors must have shape ``(..., M, M)`` and must have the same data type as ``x``. + - first element must have the field name ``eigenvalues`` (corresponding to :math:`\\operatorname{diag}\\Lambda` above) and must be an array consisting of computed eigenvalues. The array containing the eigenvalues must have shape ``(..., M)`` and must have a real-valued floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``complex128``, then ``eigenvalues`` must be ``float64``). + - second element have have the field name ``eigenvectors`` (corresponding to :math:`Q` above) and must be an array where the columns of the inner most matrices contain the computed eigenvectors. These matrices must be orthogonal. The array containing the eigenvectors must have shape ``(..., M, M)`` and must have the same data type as ``x``. Notes ----- .. note:: - Eigenvalue sort order is left unspecified and is thus implementation-dependent. + Eigenvalue sort order is left unspecified and is thus implementation-dependent. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -2829,37 +2829,37 @@ class eigvalsh[TArray: Array](Protocol): The **eigenvalues** of a complex Hermitian or real symmetric matrix :math:`x \\in\\ \\mathbb{K}^{n \\times n}` are defined as the roots (counted with multiplicity) of the polynomial :math:`p` of degree :math:`n` given by .. math:: - p(\\lambda) = \\operatorname{det}(x - \\lambda I_n) + p(\\lambda) = \\operatorname{det}(x - \\lambda I_n) where :math:`\\lambda \\in \\mathbb{R}` and where :math:`I_n` is the *n*-dimensional identity matrix. .. note:; - The eigenvalues of a complex Hermitian or real symmetric matrix are always real. + The eigenvalues of a complex Hermitian or real symmetric matrix are always real. .. note:: - Whether an array library explicitly checks whether an input array is Hermitian or a symmetric matrix (or a stack of matrices) is implementation-defined. + Whether an array library explicitly checks whether an input array is Hermitian or a symmetric matrix (or a stack of matrices) is implementation-defined. .. note:: - The function ``eigvals`` will be added in a future version of the specification. + The function ``eigvals`` will be added in a future version of the specification. Parameters ---------- x: array - input array having shape ``(..., M, M)`` and whose innermost two dimensions form square matrices. Should have a floating-point data type. + input array having shape ``(..., M, M)`` and whose innermost two dimensions form square matrices. Should have a floating-point data type. Returns ------- out: array - an array containing the computed eigenvalues. The returned array must have shape ``(..., M)`` and have a real-valued floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``complex128``, then must have a ``float64`` data type). + an array containing the computed eigenvalues. The returned array must have shape ``(..., M)`` and have a real-valued floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``complex128``, then must have a ``float64`` data type). Notes ----- .. note:: - Eigenvalue sort order is left unspecified and is thus implementation-dependent. + Eigenvalue sort order is left unspecified and is thus implementation-dependent. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -2877,7 +2877,7 @@ class inv[TArray: Array](Protocol): The **inverse matrix** :math:`x^{-1} \\in\\ \\mathbb{K}^{n \\times n}` of a square matrix :math:`x \\in\\ \\mathbb{K}^{n \\times n}` is defined as .. math:: - x^{-1}x = xx^{-1} = I_n + x^{-1}x = xx^{-1} = I_n where :math:`I_n` is the *n*-dimensional identity matrix. @@ -2888,18 +2888,18 @@ class inv[TArray: Array](Protocol): Parameters ---------- x: array - input array having shape ``(..., M, M)`` and whose innermost two dimensions form square matrices. Should have a floating-point data type. + input array having shape ``(..., M, M)`` and whose innermost two dimensions form square matrices. Should have a floating-point data type. Returns ------- out: array - an array containing the multiplicative inverses. The returned array must have a floating-point data type determined by :ref:`type-promotion` and must have the same shape as ``x``. + an array containing the multiplicative inverses. The returned array must have a floating-point data type determined by :ref:`type-promotion` and must have the same shape as ``x``. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -2915,56 +2915,56 @@ class matrix_norm[TArray: Array](Protocol): Parameters ---------- x: array - input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. Should have a floating-point data type. + input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. Should have a floating-point data type. keepdims: bool - If ``True``, the last two axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the last two axes (dimensions) must not be included in the result. Default: ``False``. + If ``True``, the last two axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the last two axes (dimensions) must not be included in the result. Default: ``False``. ord: Optional[Union[int, float, Literal[inf, -inf, 'fro', 'nuc']]] - order of the norm. The following mathematical norms must be supported: + order of the norm. The following mathematical norms must be supported: - +------------------+---------------------------------+ - | ord | description | - +==================+=================================+ - | 'fro' | Frobenius norm | - +------------------+---------------------------------+ - | 'nuc' | nuclear norm | - +------------------+---------------------------------+ - | 1 | max(sum(abs(x), axis=0)) | - +------------------+---------------------------------+ - | 2 | largest singular value | - +------------------+---------------------------------+ - | inf | max(sum(abs(x), axis=1)) | - +------------------+---------------------------------+ + +------------------+---------------------------------+ + | ord | description | + +==================+=================================+ + | 'fro' | Frobenius norm | + +------------------+---------------------------------+ + | 'nuc' | nuclear norm | + +------------------+---------------------------------+ + | 1 | max(sum(abs(x), axis=0)) | + +------------------+---------------------------------+ + | 2 | largest singular value | + +------------------+---------------------------------+ + | inf | max(sum(abs(x), axis=1)) | + +------------------+---------------------------------+ - The following non-mathematical "norms" must be supported: + The following non-mathematical "norms" must be supported: - +------------------+---------------------------------+ - | ord | description | - +==================+=================================+ - | -1 | min(sum(abs(x), axis=0)) | - +------------------+---------------------------------+ - | -2 | smallest singular value | - +------------------+---------------------------------+ - | -inf | min(sum(abs(x), axis=1)) | - +------------------+---------------------------------+ + +------------------+---------------------------------+ + | ord | description | + +==================+=================================+ + | -1 | min(sum(abs(x), axis=0)) | + +------------------+---------------------------------+ + | -2 | smallest singular value | + +------------------+---------------------------------+ + | -inf | min(sum(abs(x), axis=1)) | + +------------------+---------------------------------+ - If ``ord=1``, the norm corresponds to the induced matrix norm where ``p=1`` (i.e., the maximum absolute value column sum). + If ``ord=1``, the norm corresponds to the induced matrix norm where ``p=1`` (i.e., the maximum absolute value column sum). - If ``ord=2``, the norm corresponds to the induced matrix norm where ``p=inf`` (i.e., the maximum absolute value row sum). + If ``ord=2``, the norm corresponds to the induced matrix norm where ``p=inf`` (i.e., the maximum absolute value row sum). - If ``ord=inf``, the norm corresponds to the induced matrix norm where ``p=2`` (i.e., the largest singular value). + If ``ord=inf``, the norm corresponds to the induced matrix norm where ``p=2`` (i.e., the largest singular value). - Default: ``'fro'``. + Default: ``'fro'``. Returns ------- out: array - an array containing the norms for each ``MxN`` matrix. If ``keepdims`` is ``False``, the returned array must have a rank which is two less than the rank of ``x``. If ``x`` has a real-valued data type, the returned array must have a real-valued floating-point data type determined by :ref:`type-promotion`. If ``x`` has a complex-valued data type, the returned array must have a real-valued floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``complex128``, then the returned array must have a ``float64`` data type). + an array containing the norms for each ``MxN`` matrix. If ``keepdims`` is ``False``, the returned array must have a rank which is two less than the rank of ``x``. If ``x`` has a real-valued data type, the returned array must have a real-valued floating-point data type determined by :ref:`type-promotion`. If ``x`` has a complex-valued data type, the returned array must have a real-valued floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``complex128``, then the returned array must have a ``float64`` data type). Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -2981,20 +2981,20 @@ class matrix_power[TArray: Array](Protocol): Parameters ---------- x: array - input array having shape ``(..., M, M)`` and whose innermost two dimensions form square matrices. Should have a floating-point data type. + input array having shape ``(..., M, M)`` and whose innermost two dimensions form square matrices. Should have a floating-point data type. n: int - integer exponent. + integer exponent. Returns ------- out: array - if ``n`` is equal to zero, an array containing the identity matrix for each square matrix. If ``n`` is less than zero, an array containing the inverse of each square matrix raised to the absolute value of ``n``, provided that each square matrix is invertible. If ``n`` is greater than zero, an array containing the result of raising each square matrix to the power ``n``. The returned array must have the same shape as ``x`` and a floating-point data type determined by :ref:`type-promotion`. + if ``n`` is equal to zero, an array containing the identity matrix for each square matrix. If ``n`` is less than zero, an array containing the inverse of each square matrix raised to the absolute value of ``n``, provided that each square matrix is invertible. If ``n`` is greater than zero, an array containing the result of raising each square matrix to the power ``n``. The returned array must have the same shape as ``x`` and a floating-point data type determined by :ref:`type-promotion`. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -3012,20 +3012,20 @@ class matrix_rank[TArray: Array](Protocol): Parameters ---------- x: array - input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. Should have a floating-point data type. + input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. Should have a floating-point data type. rtol: Optional[Union[float, array]] - relative tolerance for small singular values. Singular values approximately less than or equal to ``rtol * largest_singular_value`` are set to zero. If a ``float``, the value is equivalent to a zero-dimensional array having a real-valued floating-point data type determined by :ref:`type-promotion` (as applied to ``x``) and must be broadcast against each matrix. If an ``array``, must have a real-valued floating-point data type and must be compatible with ``shape(x)[:-2]`` (see :ref:`broadcasting`). If ``None``, the default value is ``max(M, N) * eps``, where ``eps`` must be the machine epsilon associated with the real-valued floating-point data type determined by :ref:`type-promotion` (as applied to ``x``). Default: ``None``. + relative tolerance for small singular values. Singular values approximately less than or equal to ``rtol * largest_singular_value`` are set to zero. If a ``float``, the value is equivalent to a zero-dimensional array having a real-valued floating-point data type determined by :ref:`type-promotion` (as applied to ``x``) and must be broadcast against each matrix. If an ``array``, must have a real-valued floating-point data type and must be compatible with ``shape(x)[:-2]`` (see :ref:`broadcasting`). If ``None``, the default value is ``max(M, N) * eps``, where ``eps`` must be the machine epsilon associated with the real-valued floating-point data type determined by :ref:`type-promotion` (as applied to ``x``). Default: ``None``. Returns ------- out: array - an array containing the ranks. The returned array must have the default integer data type and must have shape ``(...)`` (i.e., must have a shape equal to ``shape(x)[:-2]``). + an array containing the ranks. The returned array must have the default integer data type and must have shape ``(...)`` (i.e., must have a shape equal to ``shape(x)[:-2]``). Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -3041,20 +3041,20 @@ class outer[TArray: Array](Protocol): Parameters ---------- x1: array - first one-dimensional input array of size ``N``. Must have a numeric data type. + first one-dimensional input array of size ``N``. Must have a numeric data type. x2: array - second one-dimensional input array of size ``M``. Must have a numeric data type. + second one-dimensional input array of size ``M``. Must have a numeric data type. Returns ------- out: array - a two-dimensional array containing the outer product and whose shape is ``(N, M)``. The returned array must have a data type determined by :ref:`type-promotion`. + a two-dimensional array containing the outer product and whose shape is ``(N, M)``. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -3072,12 +3072,12 @@ class pinv[TArray: Array](Protocol): While the pseudo-inverse can be defined algebraically, one can understand the pseudo-inverse via singular value decomposition (SVD). Namely, if .. math:: - A = U \\Sigma V^H + A = U \\Sigma V^H is a singular decomposition of :math:`A`, then .. math:: - A^{+} = U \\Sigma^{+} V^H + A^{+} = U \\Sigma^{+} V^H where :math:`U` and :math:`V^H` are orthogonal matrices, :math:`\\Sigma` is a diagonal matrix consisting of :math:`A`'s singular values, and :math:`\\Sigma^{+}` is then a diagonal matrix consisting of the reciprocals of :math:`A`'s singular values, leaving zeros in place. During numerical computation, only elements larger than a small tolerance are considered nonzero, and all others replaced by zeros. @@ -3086,20 +3086,20 @@ class pinv[TArray: Array](Protocol): Parameters ---------- x: array - input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. Should have a floating-point data type. + input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. Should have a floating-point data type. rtol: Optional[Union[float, array]] - relative tolerance for small singular values. Singular values approximately less than or equal to ``rtol * largest_singular_value`` are set to zero. If a ``float``, the value is equivalent to a zero-dimensional array having a real-valued floating-point data type determined by :ref:`type-promotion` (as applied to ``x``) and must be broadcast against each matrix. If an ``array``, must have a real-valued floating-point data type and must be compatible with ``shape(x)[:-2]`` (see :ref:`broadcasting`). If ``None``, the default value is ``max(M, N) * eps``, where ``eps`` must be the machine epsilon associated with the real-valued floating-point data type determined by :ref:`type-promotion` (as applied to ``x``). Default: ``None``. + relative tolerance for small singular values. Singular values approximately less than or equal to ``rtol * largest_singular_value`` are set to zero. If a ``float``, the value is equivalent to a zero-dimensional array having a real-valued floating-point data type determined by :ref:`type-promotion` (as applied to ``x``) and must be broadcast against each matrix. If an ``array``, must have a real-valued floating-point data type and must be compatible with ``shape(x)[:-2]`` (see :ref:`broadcasting`). If ``None``, the default value is ``max(M, N) * eps``, where ``eps`` must be the machine epsilon associated with the real-valued floating-point data type determined by :ref:`type-promotion` (as applied to ``x``). Default: ``None``. Returns ------- out: array - an array containing the pseudo-inverse(s). The returned array must have a floating-point data type determined by :ref:`type-promotion` and must have shape ``(..., N, M)`` (i.e., must have the same shape as ``x``, except the innermost two dimensions must be transposed). + an array containing the pseudo-inverse(s). The returned array must have a floating-point data type determined by :ref:`type-promotion` and must have shape ``(..., N, M)`` (i.e., must have the same shape as ``x``, except the innermost two dimensions must be transposed). Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -3117,14 +3117,14 @@ class qr[TArray: Array](Protocol): The **complete QR decomposition** of a matrix :math:`x \\in\\ \\mathbb{K}^{n \\times n}` is defined as .. math:: - x = QR + x = QR where :math:`Q \\in\\ \\mathbb{K}^{m \\times m}` is orthogonal when ``x`` is real-valued and unitary when ``x`` is complex-valued and where :math:`R \\in\\ \\mathbb{K}^{m \\times n}` is an upper triangular matrix with real diagonal (even when ``x`` is complex-valued). When :math:`m \\gt n` (tall matrix), as :math:`R` is upper triangular, the last :math:`m - n` rows are zero. In this case, the last :math:`m - n` columns of :math:`Q` can be dropped to form the **reduced QR decomposition**. .. math:: - x = QR + x = QR where :math:`Q \\in\\ \\mathbb{K}^{m \\times n}` and :math:`R \\in\\ \\mathbb{K}^{n \\times n}`. @@ -3133,41 +3133,41 @@ class qr[TArray: Array](Protocol): When ``x`` is a stack of matrices, the function must compute the QR decomposition for each matrix in the stack. .. note:: - Whether an array library explicitly checks whether an input array is a full column rank matrix (or a stack of full column rank matrices) is implementation-defined. + Whether an array library explicitly checks whether an input array is a full column rank matrix (or a stack of full column rank matrices) is implementation-defined. .. warning:: - The elements in the diagonal of :math:`R` are not necessarily positive. Accordingly, the returned QR decomposition is only unique up to the sign of the diagonal of :math:`R`, and different libraries or inputs on different devices may produce different valid decompositions. + The elements in the diagonal of :math:`R` are not necessarily positive. Accordingly, the returned QR decomposition is only unique up to the sign of the diagonal of :math:`R`, and different libraries or inputs on different devices may produce different valid decompositions. .. warning:: - The QR decomposition is only well-defined if the first ``k = min(m,n)`` columns of every matrix in ``x`` are linearly independent. + The QR decomposition is only well-defined if the first ``k = min(m,n)`` columns of every matrix in ``x`` are linearly independent. Parameters ---------- x: array - input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices of rank ``N``. Should have a floating-point data type. + input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices of rank ``N``. Should have a floating-point data type. mode: Literal['reduced', 'complete'] - decomposition mode. Should be one of the following modes: + decomposition mode. Should be one of the following modes: - - ``'reduced'``: compute only the leading ``K`` columns of ``q``, such that ``q`` and ``r`` have dimensions ``(..., M, K)`` and ``(..., K, N)``, respectively, and where ``K = min(M, N)``. - - ``'complete'``: compute ``q`` and ``r`` with dimensions ``(..., M, M)`` and ``(..., M, N)``, respectively. + - ``'reduced'``: compute only the leading ``K`` columns of ``q``, such that ``q`` and ``r`` have dimensions ``(..., M, K)`` and ``(..., K, N)``, respectively, and where ``K = min(M, N)``. + - ``'complete'``: compute ``q`` and ``r`` with dimensions ``(..., M, M)`` and ``(..., M, N)``, respectively. - Default: ``'reduced'``. + Default: ``'reduced'``. Returns ------- out: Tuple[array, array] - a namedtuple ``(Q, R)`` whose + a namedtuple ``(Q, R)`` whose - - first element must have the field name ``Q`` and must be an array whose shape depends on the value of ``mode`` and contain matrices with orthonormal columns. If ``mode`` is ``'complete'``, the array must have shape ``(..., M, M)``. If ``mode`` is ``'reduced'``, the array must have shape ``(..., M, K)``, where ``K = min(M, N)``. The first ``x.ndim-2`` dimensions must have the same size as those of the input array ``x``. - - second element must have the field name ``R`` and must be an array whose shape depends on the value of ``mode`` and contain upper-triangular matrices. If ``mode`` is ``'complete'``, the array must have shape ``(..., M, N)``. If ``mode`` is ``'reduced'``, the array must have shape ``(..., K, N)``, where ``K = min(M, N)``. The first ``x.ndim-2`` dimensions must have the same size as those of the input ``x``. + - first element must have the field name ``Q`` and must be an array whose shape depends on the value of ``mode`` and contain matrices with orthonormal columns. If ``mode`` is ``'complete'``, the array must have shape ``(..., M, M)``. If ``mode`` is ``'reduced'``, the array must have shape ``(..., M, K)``, where ``K = min(M, N)``. The first ``x.ndim-2`` dimensions must have the same size as those of the input array ``x``. + - second element must have the field name ``R`` and must be an array whose shape depends on the value of ``mode`` and contain upper-triangular matrices. If ``mode`` is ``'complete'``, the array must have shape ``(..., M, N)``. If ``mode`` is ``'reduced'``, the array must have shape ``(..., K, N)``, where ``K = min(M, N)``. The first ``x.ndim-2`` dimensions must have the same size as those of the input ``x``. - Each returned array must have a floating-point data type determined by :ref:`type-promotion`. + Each returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -3181,15 +3181,15 @@ class slogdet[TArray: Array](Protocol): Returns the sign and the natural logarithm of the absolute value of the determinant of a square matrix (or a stack of square matrices) ``x``. .. note:: - The purpose of this function is to calculate the determinant more accurately when the determinant is either very small or very large, as calling ``det`` may overflow or underflow. + The purpose of this function is to calculate the determinant more accurately when the determinant is either very small or very large, as calling ``det`` may overflow or underflow. The sign of the determinant is given by .. math:: - \\operatorname{sign}(\\det x) = \\begin{cases} - 0 & \\textrm{if } \\det x = 0 \\\\ - \\frac{\\det x}{|\\det x|} & \\textrm{otherwise} - \\end{cases} + \\operatorname{sign}(\\det x) = \\begin{cases} + 0 & \\textrm{if } \\det x = 0 \\\\ + \\frac{\\det x}{|\\det x|} & \\textrm{otherwise} + \\end{cases} where :math:`|\\det x|` is the absolute value of the determinant of ``x``. @@ -3206,28 +3206,28 @@ class slogdet[TArray: Array](Protocol): - If the determinant is ``0 + 0j``, the ``sign`` should be ``0 + 0j`` and ``logabsdet`` should be ``-infinity + 0j``. .. note:: - Depending on the underlying algorithm, when the determinant is zero, the returned result may differ from ``-infinity`` (or ``-infinity + 0j``). In all cases, the determinant should be equal to ``sign * exp(logabsdet)`` (although, again, the result may be subject to numerical precision errors). + Depending on the underlying algorithm, when the determinant is zero, the returned result may differ from ``-infinity`` (or ``-infinity + 0j``). In all cases, the determinant should be equal to ``sign * exp(logabsdet)`` (although, again, the result may be subject to numerical precision errors). Parameters ---------- x: array - input array having shape ``(..., M, M)`` and whose innermost two dimensions form square matrices. Should have a floating-point data type. + input array having shape ``(..., M, M)`` and whose innermost two dimensions form square matrices. Should have a floating-point data type. Returns ------- out: Tuple[array, array] - a namedtuple (``sign``, ``logabsdet``) whose + a namedtuple (``sign``, ``logabsdet``) whose - - first element must have the field name ``sign`` and must be an array containing a number representing the sign of the determinant for each square matrix. Must have the same data type as ``x``. - - second element must have the field name ``logabsdet`` and must be an array containing the natural logarithm of the absolute value of the determinant for each square matrix. If ``x`` is real-valued, the returned array must have a real-valued floating-point data type determined by :ref:`type-promotion`. If ``x`` is complex, the returned array must have a real-valued floating-point data type having the same precision as ``x`` (e.g., if ``x`` is ``complex64``, ``logabsdet`` must have a ``float32`` data type). + - first element must have the field name ``sign`` and must be an array containing a number representing the sign of the determinant for each square matrix. Must have the same data type as ``x``. + - second element must have the field name ``logabsdet`` and must be an array containing the natural logarithm of the absolute value of the determinant for each square matrix. If ``x`` is real-valued, the returned array must have a real-valued floating-point data type determined by :ref:`type-promotion`. If ``x`` is complex, the returned array must have a real-valued floating-point data type having the same precision as ``x`` (e.g., if ``x`` is ``complex64``, ``logabsdet`` must have a ``float32`` data type). - Each returned array must have shape ``shape(x)[:-2]``. + Each returned array must have shape ``shape(x)[:-2]``. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -3245,35 +3245,35 @@ class solve[TArray: Array](Protocol): This function computes the solution :math:`X \\in\\ \\mathbb{K}^{m \\times k}` of the **linear system** associated to :math:`A \\in\\ \\mathbb{K}^{m \\times m}` and :math:`B \\in\\ \\mathbb{K}^{m \\times k}` and is defined as .. math:: - AX = B + AX = B This system of linear equations has a unique solution if and only if :math:`A` is invertible. .. note:: - Whether an array library explicitly checks whether ``x1`` is invertible is implementation-defined. + Whether an array library explicitly checks whether ``x1`` is invertible is implementation-defined. When ``x1`` and/or ``x2`` is a stack of matrices, the function must compute a solution for each matrix in the stack. Parameters ---------- x1: array - coefficient array ``A`` having shape ``(..., M, M)`` and whose innermost two dimensions form square matrices. Must be of full rank (i.e., all rows or, equivalently, columns must be linearly independent). Should have a floating-point data type. + coefficient array ``A`` having shape ``(..., M, M)`` and whose innermost two dimensions form square matrices. Must be of full rank (i.e., all rows or, equivalently, columns must be linearly independent). Should have a floating-point data type. x2: array - ordinate (or "dependent variable") array ``B``. If ``x2`` has shape ``(M,)``, ``x2`` is equivalent to an array having shape ``(..., M, 1)``. If ``x2`` has shape ``(..., M, K)``, each column ``k`` defines a set of ordinate values for which to compute a solution, and ``shape(x2)[:-2]`` must be compatible with ``shape(x1)[:-2]`` (see :ref:`broadcasting`). Should have a floating-point data type. + ordinate (or "dependent variable") array ``B``. If ``x2`` has shape ``(M,)``, ``x2`` is equivalent to an array having shape ``(..., M, 1)``. If ``x2`` has shape ``(..., M, K)``, each column ``k`` defines a set of ordinate values for which to compute a solution, and ``shape(x2)[:-2]`` must be compatible with ``shape(x1)[:-2]`` (see :ref:`broadcasting`). Should have a floating-point data type. Returns ------- out: array - an array containing the solution to the system ``AX = B`` for each square matrix. If ``x2`` has shape ``(M,)``, the returned array must have shape equal to ``shape(x1)[:-2] + shape(x2)[-1:]``. Otherwise, if ``x2`` has shape ``(..., M, K)```, the returned array must have shape equal to ``(..., M, K)``, where ``...`` refers to the result of broadcasting ``shape(x1)[:-2]`` and ``shape(x2)[:-2]``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the solution to the system ``AX = B`` for each square matrix. If ``x2`` has shape ``(M,)``, the returned array must have shape equal to ``shape(x1)[:-2] + shape(x2)[-1:]``. Otherwise, if ``x2`` has shape ``(..., M, K)```, the returned array must have shape equal to ``(..., M, K)``, where ``...`` refers to the result of broadcasting ``shape(x1)[:-2]`` and ``shape(x2)[:-2]``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. .. versionchanged:: 2024.12 - Clarified broadcasting semantics and the shape of the output array. + Clarified broadcasting semantics and the shape of the output array. """ @@ -3291,14 +3291,14 @@ class svd[TArray: Array](Protocol): The full **singular value decomposition** of an :math:`m \\times n` matrix :math:`x \\in\\ \\mathbb{K}^{m \\times n}` is a factorization of the form .. math:: - x = U \\Sigma V^H + x = U \\Sigma V^H where :math:`U \\in\\ \\mathbb{K}^{m \\times m}`, :math:`\\Sigma \\in\\ \\mathbb{K}^{m \\times\\ n}`, :math:`\\operatorname{diag}(\\Sigma) \\in\\ \\mathbb{R}^{k}` with :math:`k = \\operatorname{min}(m, n)`, :math:`V^H \\in\\ \\mathbb{K}^{n \\times n}`, and where :math:`V^H` is the conjugate transpose when :math:`V` is complex and the transpose when :math:`V` is real-valued. When ``x`` is real-valued, :math:`U`, :math:`V` (and thus :math:`V^H`) are orthogonal, and, when ``x`` is complex, :math:`U`, :math:`V` (and thus :math:`V^H`) are unitary. When :math:`m \\gt n` (tall matrix), we can drop the last :math:`m - n` columns of :math:`U` to form the reduced SVD .. math:: - x = U \\Sigma V^H + x = U \\Sigma V^H where :math:`U \\in\\ \\mathbb{K}^{m \\times k}`, :math:`\\Sigma \\in\\ \\mathbb{K}^{k \\times\\ k}`, :math:`\\operatorname{diag}(\\Sigma) \\in\\ \\mathbb{R}^{k}`, and :math:`V^H \\in\\ \\mathbb{K}^{k \\times n}`. In this case, :math:`U` and :math:`V` have orthonormal columns. @@ -3309,31 +3309,31 @@ class svd[TArray: Array](Protocol): When ``x`` is a stack of matrices, the function must compute the singular value decomposition for each matrix in the stack. .. warning:: - The returned arrays :math:`U` and :math:`V` are neither unique nor continuous with respect to ``x``. Because :math:`U` and :math:`V` are not unique, different hardware and software may compute different singular vectors. + The returned arrays :math:`U` and :math:`V` are neither unique nor continuous with respect to ``x``. Because :math:`U` and :math:`V` are not unique, different hardware and software may compute different singular vectors. - Non-uniqueness stems from the fact that multiplying any pair of singular vectors :math:`u_k`, :math:`v_k` by :math:`-1` when ``x`` is real-valued and by :math:`e^{\\phi j}` (:math:`\\phi \\in \\mathbb{R}`) when ``x`` is complex produces another two valid singular vectors of the matrix. + Non-uniqueness stems from the fact that multiplying any pair of singular vectors :math:`u_k`, :math:`v_k` by :math:`-1` when ``x`` is real-valued and by :math:`e^{\\phi j}` (:math:`\\phi \\in \\mathbb{R}`) when ``x`` is complex produces another two valid singular vectors of the matrix. Parameters ---------- x: array - input array having shape ``(..., M, N)`` and whose innermost two dimensions form matrices on which to perform singular value decomposition. Should have a floating-point data type. + input array having shape ``(..., M, N)`` and whose innermost two dimensions form matrices on which to perform singular value decomposition. Should have a floating-point data type. full_matrices: bool - If ``True``, compute full-sized ``U`` and ``Vh``, such that ``U`` has shape ``(..., M, M)`` and ``Vh`` has shape ``(..., N, N)``. If ``False``, compute on the leading ``K`` singular vectors, such that ``U`` has shape ``(..., M, K)`` and ``Vh`` has shape ``(..., K, N)`` and where ``K = min(M, N)``. Default: ``True``. + If ``True``, compute full-sized ``U`` and ``Vh``, such that ``U`` has shape ``(..., M, M)`` and ``Vh`` has shape ``(..., N, N)``. If ``False``, compute on the leading ``K`` singular vectors, such that ``U`` has shape ``(..., M, K)`` and ``Vh`` has shape ``(..., K, N)`` and where ``K = min(M, N)``. Default: ``True``. Returns ------- out: Tuple[array, array, array] - a namedtuple ``(U, S, Vh)`` whose + a namedtuple ``(U, S, Vh)`` whose - - first element must have the field name ``U`` and must be an array whose shape depends on the value of ``full_matrices`` and contain matrices with orthonormal columns (i.e., the columns are left singular vectors). If ``full_matrices`` is ``True``, the array must have shape ``(..., M, M)``. If ``full_matrices`` is ``False``, the array must have shape ``(..., M, K)``, where ``K = min(M, N)``. The first ``x.ndim-2`` dimensions must have the same shape as those of the input ``x``. Must have the same data type as ``x``. - - second element must have the field name ``S`` and must be an array with shape ``(..., K)`` that contains the vector(s) of singular values of length ``K``, where ``K = min(M, N)``. For each vector, the singular values must be sorted in descending order by magnitude, such that ``s[..., 0]`` is the largest value, ``s[..., 1]`` is the second largest value, et cetera. The first ``x.ndim-2`` dimensions must have the same shape as those of the input ``x``. Must have a real-valued floating-point data type having the same precision as ``x`` (e.g., if ``x`` is ``complex64``, ``S`` must have a ``float32`` data type). - - third element must have the field name ``Vh`` and must be an array whose shape depends on the value of ``full_matrices`` and contain orthonormal rows (i.e., the rows are the right singular vectors and the array is the adjoint). If ``full_matrices`` is ``True``, the array must have shape ``(..., N, N)``. If ``full_matrices`` is ``False``, the array must have shape ``(..., K, N)`` where ``K = min(M, N)``. The first ``x.ndim-2`` dimensions must have the same shape as those of the input ``x``. Must have the same data type as ``x``. + - first element must have the field name ``U`` and must be an array whose shape depends on the value of ``full_matrices`` and contain matrices with orthonormal columns (i.e., the columns are left singular vectors). If ``full_matrices`` is ``True``, the array must have shape ``(..., M, M)``. If ``full_matrices`` is ``False``, the array must have shape ``(..., M, K)``, where ``K = min(M, N)``. The first ``x.ndim-2`` dimensions must have the same shape as those of the input ``x``. Must have the same data type as ``x``. + - second element must have the field name ``S`` and must be an array with shape ``(..., K)`` that contains the vector(s) of singular values of length ``K``, where ``K = min(M, N)``. For each vector, the singular values must be sorted in descending order by magnitude, such that ``s[..., 0]`` is the largest value, ``s[..., 1]`` is the second largest value, et cetera. The first ``x.ndim-2`` dimensions must have the same shape as those of the input ``x``. Must have a real-valued floating-point data type having the same precision as ``x`` (e.g., if ``x`` is ``complex64``, ``S`` must have a ``float32`` data type). + - third element must have the field name ``Vh`` and must be an array whose shape depends on the value of ``full_matrices`` and contain orthonormal rows (i.e., the rows are the right singular vectors and the array is the adjoint). If ``full_matrices`` is ``True``, the array must have shape ``(..., N, N)``. If ``full_matrices`` is ``False``, the array must have shape ``(..., K, N)`` where ``K = min(M, N)``. The first ``x.ndim-2`` dimensions must have the same shape as those of the input ``x``. Must have the same data type as ``x``. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -3351,18 +3351,18 @@ class svdvals[TArray: Array](Protocol): Parameters ---------- x: array - input array having shape ``(..., M, N)`` and whose innermost two dimensions form matrices on which to perform singular value decomposition. Should have a floating-point data type. + input array having shape ``(..., M, N)`` and whose innermost two dimensions form matrices on which to perform singular value decomposition. Should have a floating-point data type. Returns ------- out: array - an array with shape ``(..., K)`` that contains the vector(s) of singular values of length ``K``, where ``K = min(M, N)``. For each vector, the singular values must be sorted in descending order by magnitude, such that ``s[..., 0]`` is the largest value, ``s[..., 1]`` is the second largest value, et cetera. The first ``x.ndim-2`` dimensions must have the same shape as those of the input ``x``. The returned array must have a real-valued floating-point data type having the same precision as ``x`` (e.g., if ``x`` is ``complex64``, the returned array must have a ``float32`` data type). + an array with shape ``(..., K)`` that contains the vector(s) of singular values of length ``K``, where ``K = min(M, N)``. For each vector, the singular values must be sorted in descending order by magnitude, such that ``s[..., 0]`` is the largest value, ``s[..., 1]`` is the second largest value, et cetera. The first ``x.ndim-2`` dimensions must have the same shape as those of the input ``x``. The returned array must have a real-valued floating-point data type having the same precision as ``x`` (e.g., if ``x`` is ``complex64``, the returned array must have a ``float32`` data type). Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -3378,33 +3378,33 @@ class trace[TArray: Array, TDtype](Protocol): Parameters ---------- x: array - input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. Should have a numeric data type. + input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. Should have a numeric data type. offset: int - offset specifying the off-diagonal relative to the main diagonal. + offset specifying the off-diagonal relative to the main diagonal. - - ``offset = 0``: the main diagonal. - - ``offset > 0``: off-diagonal above the main diagonal. - - ``offset < 0``: off-diagonal below the main diagonal. + - ``offset = 0``: the main diagonal. + - ``offset > 0``: off-diagonal above the main diagonal. + - ``offset < 0``: off-diagonal below the main diagonal. - Default: ``0``. + Default: ``0``. dtype: Optional[dtype] - data type of the returned array. If ``None``, the returned array must have the same data type as ``x``, unless ``x`` has an integer data type supporting a smaller range of values than the default integer data type (e.g., ``x`` has an ``int16`` or ``uint32`` data type and the default integer data type is ``int64``). In those latter cases: + data type of the returned array. If ``None``, the returned array must have the same data type as ``x``, unless ``x`` has an integer data type supporting a smaller range of values than the default integer data type (e.g., ``x`` has an ``int16`` or ``uint32`` data type and the default integer data type is ``int64``). In those latter cases: - - if ``x`` has a signed integer data type (e.g., ``int16``), the returned array must have the default integer data type. - - if ``x`` has an unsigned integer data type (e.g., ``uint16``), the returned array must have an unsigned integer data type having the same number of bits as the default integer data type (e.g., if the default integer data type is ``int32``, the returned array must have a ``uint32`` data type). + - if ``x`` has a signed integer data type (e.g., ``int16``), the returned array must have the default integer data type. + - if ``x`` has an unsigned integer data type (e.g., ``uint16``), the returned array must have an unsigned integer data type having the same number of bits as the default integer data type (e.g., if the default integer data type is ``int32``, the returned array must have a ``uint32`` data type). - If the data type (either specified or resolved) differs from the data type of ``x``, the input array should be cast to the specified data type before computing the sum (rationale: the ``dtype`` keyword argument is intended to help prevent overflows). Default: ``None``. + If the data type (either specified or resolved) differs from the data type of ``x``, the input array should be cast to the specified data type before computing the sum (rationale: the ``dtype`` keyword argument is intended to help prevent overflows). Default: ``None``. Returns ------- out: array - an array containing the traces and whose shape is determined by removing the last two dimensions and storing the traces in the last array dimension. For example, if ``x`` has rank ``k`` and shape ``(I, J, K, ..., L, M, N)``, then an output array has rank ``k-2`` and shape ``(I, J, K, ..., L)`` where + an array containing the traces and whose shape is determined by removing the last two dimensions and storing the traces in the last array dimension. For example, if ``x`` has rank ``k`` and shape ``(I, J, K, ..., L, M, N)``, then an output array has rank ``k-2`` and shape ``(I, J, K, ..., L)`` where - :: + :: - out[i, j, k, ..., l] = trace(a[i, j, k, ..., l, :, :]) + out[i, j, k, ..., l] = trace(a[i, j, k, ..., l, :, :]) - The returned array must have a data type as described by the ``dtype`` parameter above. + The returned array must have a data type as described by the ``dtype`` parameter above. Notes ----- @@ -3417,10 +3417,10 @@ class trace[TArray: Array, TDtype](Protocol): For both real-valued and complex floating-point operands, special cases must be handled as if the operation is implemented by successive application of :func:`~array_api.add`. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. .. versionchanged:: 2023.12 - Required the function to return a floating-point array having the same data type as the input array when provided a floating-point array. + Required the function to return a floating-point array having the same data type as the input array when provided a floating-point array. """ @@ -3436,54 +3436,54 @@ class vector_norm[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a floating-point data type. + input array. Should have a floating-point data type. axis: Optional[Union[int, Tuple[int, ...]]] - If an integer, ``axis`` specifies the axis (dimension) along which to compute vector norms. If an n-tuple, ``axis`` specifies the axes (dimensions) along which to compute batched vector norms. If ``None``, the vector norm must be computed over all array values (i.e., equivalent to computing the vector norm of a flattened array). Negative indices must be supported. Default: ``None``. + If an integer, ``axis`` specifies the axis (dimension) along which to compute vector norms. If an n-tuple, ``axis`` specifies the axes (dimensions) along which to compute batched vector norms. If ``None``, the vector norm must be computed over all array values (i.e., equivalent to computing the vector norm of a flattened array). Negative indices must be supported. Default: ``None``. keepdims: bool - If ``True``, the axes (dimensions) specified by ``axis`` must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the axes (dimensions) specified by ``axis`` must not be included in the result. Default: ``False``. + If ``True``, the axes (dimensions) specified by ``axis`` must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the axes (dimensions) specified by ``axis`` must not be included in the result. Default: ``False``. ord: Union[int, float, Literal[inf, -inf]] - order of the norm. The following mathematical norms must be supported: + order of the norm. The following mathematical norms must be supported: - +------------------+----------------------------+ - | ord | description | - +==================+============================+ - | 1 | L1-norm (Manhattan) | - +------------------+----------------------------+ - | 2 | L2-norm (Euclidean) | - +------------------+----------------------------+ - | inf | infinity norm | - +------------------+----------------------------+ - | (int,float >= 1) | p-norm | - +------------------+----------------------------+ + +------------------+----------------------------+ + | ord | description | + +==================+============================+ + | 1 | L1-norm (Manhattan) | + +------------------+----------------------------+ + | 2 | L2-norm (Euclidean) | + +------------------+----------------------------+ + | inf | infinity norm | + +------------------+----------------------------+ + | (int,float >= 1) | p-norm | + +------------------+----------------------------+ - The following non-mathematical "norms" must be supported: + The following non-mathematical "norms" must be supported: - +------------------+--------------------------------+ - | ord | description | - +==================+================================+ - | 0 | sum(a != 0) | - +------------------+--------------------------------+ - | -1 | 1./sum(1./abs(a)) | - +------------------+--------------------------------+ - | -2 | 1./sqrt(sum(1./abs(a)\\*\\*2)) | - +------------------+--------------------------------+ - | -inf | min(abs(a)) | - +------------------+--------------------------------+ - | (int,float < 1) | sum(abs(a)\\*\\*ord)\\*\\*(1./ord) | - +------------------+--------------------------------+ + +------------------+--------------------------------+ + | ord | description | + +==================+================================+ + | 0 | sum(a != 0) | + +------------------+--------------------------------+ + | -1 | 1./sum(1./abs(a)) | + +------------------+--------------------------------+ + | -2 | 1./sqrt(sum(1./abs(a)\\*\\*2)) | + +------------------+--------------------------------+ + | -inf | min(abs(a)) | + +------------------+--------------------------------+ + | (int,float < 1) | sum(abs(a)\\*\\*ord)\\*\\*(1./ord) | + +------------------+--------------------------------+ - Default: ``2``. + Default: ``2``. Returns ------- out: array - an array containing the vector norms. If ``axis`` is ``None``, the returned array must be a zero-dimensional array containing a vector norm. If ``axis`` is a scalar value (``int`` or ``float``), the returned array must have a rank which is one less than the rank of ``x``. If ``axis`` is a ``n``-tuple, the returned array must have a rank which is ``n`` less than the rank of ``x``. If ``x`` has a real-valued data type, the returned array must have a real-valued floating-point data type determined by :ref:`type-promotion`. If ``x`` has a complex-valued data type, the returned array must have a real-valued floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``complex128``, then the returned array must have a ``float64`` data type). + an array containing the vector norms. If ``axis`` is ``None``, the returned array must be a zero-dimensional array containing a vector norm. If ``axis`` is a scalar value (``int`` or ``float``), the returned array must have a rank which is one less than the rank of ``x``. If ``axis`` is a ``n``-tuple, the returned array must have a rank which is ``n`` less than the rank of ``x``. If ``x`` has a real-valued data type, the returned array must have a real-valued floating-point data type determined by :ref:`type-promotion`. If ``x`` has a complex-valued data type, the returned array must have a real-valued floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``complex128``, then the returned array must have a ``float64`` data type). Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -3500,18 +3500,18 @@ class argsort[TArray: Array](Protocol): Parameters ---------- x: array - input array. **Should** have a real-valued data type. + input array. **Should** have a real-valued data type. axis: int - axis along which to sort. A valid axis **must** be an integer on the interval ``[-N, N)``, where ``N`` is the number of axes in ``x``. If an axis is specified as a negative integer, the function **must** determine the axis along which to perform the operation by counting backward from the last axis (where ``-1`` refers to the last axis). If provided an invalid axis, the function **must** raise an exception. Default: ``-1``. + axis along which to sort. A valid axis **must** be an integer on the interval ``[-N, N)``, where ``N`` is the number of axes in ``x``. If an axis is specified as a negative integer, the function **must** determine the axis along which to perform the operation by counting backward from the last axis (where ``-1`` refers to the last axis). If provided an invalid axis, the function **must** raise an exception. Default: ``-1``. descending: bool - sort order. If ``True``, the returned indices **must** sort ``x`` in descending order (by value). If ``False``, the returned indices **must** sort ``x`` in ascending order (by value). Default: ``False``. + sort order. If ``True``, the returned indices **must** sort ``x`` in descending order (by value). If ``False``, the returned indices **must** sort ``x`` in ascending order (by value). Default: ``False``. stable: bool - sort stability. If ``True``, the returned indices **must** maintain the relative order of ``x`` values which compare as equal. If ``False``, the returned indices **may** maintain the relative order of ``x`` values which compare as equal (i.e., the relative order of ``x`` values which compare as equal is implementation-dependent). Default: ``True``. + sort stability. If ``True``, the returned indices **must** maintain the relative order of ``x`` values which compare as equal. If ``False``, the returned indices **may** maintain the relative order of ``x`` values which compare as equal (i.e., the relative order of ``x`` values which compare as equal is implementation-dependent). Default: ``True``. Returns ------- out: array - an array of indices. The returned array **must** have the same shape as ``x``. The returned array **must** have the default array index data type. + an array of indices. The returned array **must** have the same shape as ``x``. The returned array **must** have the default array index data type. Notes ----- @@ -3531,18 +3531,18 @@ class sort[TArray: Array](Protocol): Parameters ---------- x: array - input array. **Should** have a real-valued data type. + input array. **Should** have a real-valued data type. axis: int - axis along which to sort. A valid axis **must** be an integer on the interval ``[-N, N)``, where ``N`` is the number of axes in ``x``. If an axis is specified as a negative integer, the function **must** determine the axis along which to perform the operation by counting backward from the last axis (where ``-1`` refers to the last axis). If provided an invalid axis, the function **must** raise an exception. Default: ``-1``. + axis along which to sort. A valid axis **must** be an integer on the interval ``[-N, N)``, where ``N`` is the number of axes in ``x``. If an axis is specified as a negative integer, the function **must** determine the axis along which to perform the operation by counting backward from the last axis (where ``-1`` refers to the last axis). If provided an invalid axis, the function **must** raise an exception. Default: ``-1``. descending: bool - sort order. If ``True``, the array **must** be sorted in descending order (by value). If ``False``, the array **must** be sorted in ascending order (by value). Default: ``False``. + sort order. If ``True``, the array **must** be sorted in descending order (by value). If ``False``, the array **must** be sorted in ascending order (by value). Default: ``False``. stable: bool - sort stability. If ``True``, the returned array **must** maintain the relative order of ``x`` values which compare as equal. If ``False``, the returned array **may** maintain the relative order of ``x`` values which compare as equal (i.e., the relative order of ``x`` values which compare as equal is implementation-dependent). Default: ``True``. + sort stability. If ``True``, the returned array **must** maintain the relative order of ``x`` values which compare as equal. If ``False``, the returned array **may** maintain the relative order of ``x`` values which compare as equal (i.e., the relative order of ``x`` values which compare as equal is implementation-dependent). Default: ``True``. Returns ------- out: array - a sorted array. The returned array **must** have the same data type and shape as ``x``. + a sorted array. The returned array **must** have the same data type and shape as ``x``. Notes ----- @@ -3562,29 +3562,29 @@ class abs[TArray: Array](Protocol): For real-valued input arrays, the element-wise result has the same magnitude as the respective element in ``x`` but has positive sign. .. note:: - For signed integer data types, the absolute value of the minimum representable integer is implementation-dependent. + For signed integer data types, the absolute value of the minimum representable integer is implementation-dependent. .. note:: - For complex floating-point operands, the complex absolute value is known as the norm, modulus, or magnitude and, for a complex number :math:`z = a + bj` is computed as + For complex floating-point operands, the complex absolute value is known as the norm, modulus, or magnitude and, for a complex number :math:`z = a + bj` is computed as - .. math:: - \\operatorname{abs}(z) = \\sqrt{a^2 + b^2} + .. math:: + \\operatorname{abs}(z) = \\sqrt{a^2 + b^2} .. note:: - For complex floating-point operands, conforming implementations should take care to avoid undue overflow or underflow during intermediate stages of computation. + For complex floating-point operands, conforming implementations should take care to avoid undue overflow or underflow during intermediate stages of computation. .. - TODO: once ``hypot`` is added to the specification, remove the special cases for complex floating-point operands and the note concerning guarding against undue overflow/underflow, and state that special cases must be handled as if implemented as ``hypot(real(x), imag(x))``. + TODO: once ``hypot`` is added to the specification, remove the special cases for complex floating-point operands and the note concerning guarding against undue overflow/underflow, and state that special cases must be handled as if implemented as ``hypot(real(x), imag(x))``. Parameters ---------- x: array - input array. Should have a numeric data type. + input array. Should have a numeric data type. Returns ------- out: array - an array containing the absolute value of each element in ``x``. If ``x`` has a real-valued data type, the returned array must have the same data type as ``x``. If ``x`` has a complex floating-point data type, the returned array must have a real-valued floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``complex128``, then the returned array must have a ``float64`` data type). + an array containing the absolute value of each element in ``x``. If ``x`` has a real-valued data type, the returned array must have the same data type as ``x``. If ``x`` has a complex floating-point data type, the returned array must have a real-valued floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``complex128``, then the returned array must have a ``float64`` data type). Notes ----- @@ -3607,7 +3607,7 @@ class abs[TArray: Array](Protocol): - If ``a`` is ``NaN`` and ``b`` is ``NaN``, the result is ``NaN``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -3623,35 +3623,35 @@ class acos[TArray: Array](Protocol): Each element-wise result is expressed in radians. .. note:: - The principal value of the arc cosine of a complex number :math:`z` is + The principal value of the arc cosine of a complex number :math:`z` is - .. math:: - \\operatorname{acos}(z) = \\frac{1}{2}\\pi + j\\ \\ln(zj + \\sqrt{1-z^2}) + .. math:: + \\operatorname{acos}(z) = \\frac{1}{2}\\pi + j\\ \\ln(zj + \\sqrt{1-z^2}) - For any :math:`z`, + For any :math:`z`, - .. math:: - \\operatorname{acos}(z) = \\pi - \\operatorname{acos}(-z) + .. math:: + \\operatorname{acos}(z) = \\pi - \\operatorname{acos}(-z) .. note:: - For complex floating-point operands, ``acos(conj(x))`` must equal ``conj(acos(x))``. + For complex floating-point operands, ``acos(conj(x))`` must equal ``conj(acos(x))``. .. note:: - The inverse cosine (or arc cosine) is a multi-valued function and requires a branch cut on the complex plane. By convention, a branch cut is placed at the line segments :math:`(-\\infty, -1)` and :math:`(1, \\infty)` of the real axis. + The inverse cosine (or arc cosine) is a multi-valued function and requires a branch cut on the complex plane. By convention, a branch cut is placed at the line segments :math:`(-\\infty, -1)` and :math:`(1, \\infty)` of the real axis. - Accordingly, for complex arguments, the function returns the inverse cosine in the range of a strip unbounded along the imaginary axis and in the interval :math:`[0, \\pi]` along the real axis. + Accordingly, for complex arguments, the function returns the inverse cosine in the range of a strip unbounded along the imaginary axis and in the interval :math:`[0, \\pi]` along the real axis. - *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). + *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). Parameters ---------- x: array - input array. Should have a floating-point data type. + input array. Should have a floating-point data type. Returns ------- out: array - an array containing the inverse cosine of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the inverse cosine of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -3680,7 +3680,7 @@ class acos[TArray: Array](Protocol): - If ``a`` is ``NaN`` and ``b`` is ``NaN``, the result is ``NaN + NaN j``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -3694,42 +3694,42 @@ class acosh[TArray: Array](Protocol): Calculates an implementation-dependent approximation to the inverse hyperbolic cosine for each element ``x_i`` of the input array ``x``. .. note:: - The principal value of the inverse hyperbolic cosine of a complex number :math:`z` is + The principal value of the inverse hyperbolic cosine of a complex number :math:`z` is - .. math:: - \\operatorname{acosh}(z) = \\ln(z + \\sqrt{z+1}\\sqrt{z-1}) + .. math:: + \\operatorname{acosh}(z) = \\ln(z + \\sqrt{z+1}\\sqrt{z-1}) - For any :math:`z`, + For any :math:`z`, - .. math:: - \\operatorname{acosh}(z) = \\frac{\\sqrt{z-1}}{\\sqrt{1-z}}\\operatorname{acos}(z) + .. math:: + \\operatorname{acosh}(z) = \\frac{\\sqrt{z-1}}{\\sqrt{1-z}}\\operatorname{acos}(z) - or simply + or simply - .. math:: - \\operatorname{acosh}(z) = j\\ \\operatorname{acos}(z) + .. math:: + \\operatorname{acosh}(z) = j\\ \\operatorname{acos}(z) - in the upper half of the complex plane. + in the upper half of the complex plane. .. note:: - For complex floating-point operands, ``acosh(conj(x))`` must equal ``conj(acosh(x))``. + For complex floating-point operands, ``acosh(conj(x))`` must equal ``conj(acosh(x))``. .. note:: - The inverse hyperbolic cosine is a multi-valued function and requires a branch cut on the complex plane. By convention, a branch cut is placed at the line segment :math:`(-\\infty, 1)` of the real axis. + The inverse hyperbolic cosine is a multi-valued function and requires a branch cut on the complex plane. By convention, a branch cut is placed at the line segment :math:`(-\\infty, 1)` of the real axis. - Accordingly, for complex arguments, the function returns the inverse hyperbolic cosine in the interval :math:`[0, \\infty)` along the real axis and in the interval :math:`[-\\pi j, +\\pi j]` along the imaginary axis. + Accordingly, for complex arguments, the function returns the inverse hyperbolic cosine in the interval :math:`[0, \\infty)` along the real axis and in the interval :math:`[-\\pi j, +\\pi j]` along the imaginary axis. - *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). + *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). Parameters ---------- x: array - input array whose elements each represent the area of a hyperbolic sector. Should have a floating-point data type. + input array whose elements each represent the area of a hyperbolic sector. Should have a floating-point data type. Returns ------- out: array - an array containing the inverse hyperbolic cosine of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the inverse hyperbolic cosine of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -3758,7 +3758,7 @@ class acosh[TArray: Array](Protocol): - If ``a`` is ``NaN`` and ``b`` is ``NaN``, the result is ``NaN + NaN j``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -3774,14 +3774,14 @@ class add[TArray: Array](Protocol): Parameters ---------- x1: Union[array, int, float, complex] - first input array. Should have a numeric data type. + first input array. Should have a numeric data type. x2: Union[array, int, float, complex] - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a numeric data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a numeric data type. Returns ------- out: array - an array containing the element-wise sums. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise sums. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- @@ -3810,7 +3810,7 @@ class add[TArray: Array](Protocol): - In the remaining cases, when neither ``infinity``, ``+0``, ``-0``, nor a ``NaN`` is involved, and the operands have the same mathematical sign or have different magnitudes, the sum must be computed and rounded to the nearest representable value according to IEEE 754-2019 and a supported round mode. If the magnitude is too large to represent, the operation overflows and the result is an `infinity` of appropriate mathematical sign. .. note:: - Floating-point addition is a commutative operation, but not always associative. + Floating-point addition is a commutative operation, but not always associative. For complex floating-point operands, addition is defined according to the following table. For real components ``a`` and ``c`` and imaginary components ``b`` and ``d``, @@ -3832,10 +3832,10 @@ class add[TArray: Array](Protocol): Hence, if ``z1 = a + bj = -0 + 0j`` and ``z2 = c + dj = -0 - 0j``, the result of ``z1 + z2`` is ``-0 + 0j``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. .. versionchanged:: 2024.12 - Added scalar argument support. + Added scalar argument support. """ @@ -3851,35 +3851,35 @@ class asin[TArray: Array](Protocol): Each element-wise result is expressed in radians. .. note:: - The principal value of the arc sine of a complex number :math:`z` is + The principal value of the arc sine of a complex number :math:`z` is - .. math:: - \\operatorname{asin}(z) = -j\\ \\ln(zj + \\sqrt{1-z^2}) + .. math:: + \\operatorname{asin}(z) = -j\\ \\ln(zj + \\sqrt{1-z^2}) - For any :math:`z`, + For any :math:`z`, - .. math:: - \\operatorname{asin}(z) = \\operatorname{acos}(-z) - \\frac{\\pi}{2} + .. math:: + \\operatorname{asin}(z) = \\operatorname{acos}(-z) - \\frac{\\pi}{2} .. note:: - For complex floating-point operands, ``asin(conj(x))`` must equal ``conj(asin(x))``. + For complex floating-point operands, ``asin(conj(x))`` must equal ``conj(asin(x))``. .. note:: - The inverse sine (or arc sine) is a multi-valued function and requires a branch cut on the complex plane. By convention, a branch cut is placed at the line segments :math:`(-\\infty, -1)` and :math:`(1, \\infty)` of the real axis. + The inverse sine (or arc sine) is a multi-valued function and requires a branch cut on the complex plane. By convention, a branch cut is placed at the line segments :math:`(-\\infty, -1)` and :math:`(1, \\infty)` of the real axis. - Accordingly, for complex arguments, the function returns the inverse sine in the range of a strip unbounded along the imaginary axis and in the interval :math:`[-\\pi/2, +\\pi/2]` along the real axis. + Accordingly, for complex arguments, the function returns the inverse sine in the range of a strip unbounded along the imaginary axis and in the interval :math:`[-\\pi/2, +\\pi/2]` along the real axis. - *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). + *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). Parameters ---------- x: array - input array. Should have a floating-point data type. + input array. Should have a floating-point data type. Returns ------- out: array - an array containing the inverse sine of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the inverse sine of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -3896,7 +3896,7 @@ class asin[TArray: Array](Protocol): For complex floating-point operands, special cases must be handled as if the operation is implemented as ``-1j * asinh(x*1j)``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -3910,35 +3910,35 @@ class asinh[TArray: Array](Protocol): Calculates an implementation-dependent approximation to the inverse hyperbolic sine for each element ``x_i`` in the input array ``x``. .. note:: - The principal value of the inverse hyperbolic sine of a complex number :math:`z` is + The principal value of the inverse hyperbolic sine of a complex number :math:`z` is - .. math:: - \\operatorname{asinh}(z) = \\ln(z + \\sqrt{1+z^2}) + .. math:: + \\operatorname{asinh}(z) = \\ln(z + \\sqrt{1+z^2}) - For any :math:`z`, + For any :math:`z`, - .. math:: - \\operatorname{asinh}(z) = \\frac{\\operatorname{asin}(zj)}{j} + .. math:: + \\operatorname{asinh}(z) = \\frac{\\operatorname{asin}(zj)}{j} .. note:: - For complex floating-point operands, ``asinh(conj(x))`` must equal ``conj(asinh(x))`` and ``asinh(-z)`` must equal ``-asinh(z)``. + For complex floating-point operands, ``asinh(conj(x))`` must equal ``conj(asinh(x))`` and ``asinh(-z)`` must equal ``-asinh(z)``. .. note:: - The inverse hyperbolic sine is a multi-valued function and requires a branch cut on the complex plane. By convention, a branch cut is placed at the line segments :math:`(-\\infty j, -j)` and :math:`(j, \\infty j)` of the imaginary axis. + The inverse hyperbolic sine is a multi-valued function and requires a branch cut on the complex plane. By convention, a branch cut is placed at the line segments :math:`(-\\infty j, -j)` and :math:`(j, \\infty j)` of the imaginary axis. - Accordingly, for complex arguments, the function returns the inverse hyperbolic sine in the range of a strip unbounded along the real axis and in the interval :math:`[-\\pi j/2, +\\pi j/2]` along the imaginary axis. + Accordingly, for complex arguments, the function returns the inverse hyperbolic sine in the range of a strip unbounded along the real axis and in the interval :math:`[-\\pi j/2, +\\pi j/2]` along the imaginary axis. - *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). + *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). Parameters ---------- x: array - input array whose elements each represent the area of a hyperbolic sector. Should have a floating-point data type. + input array whose elements each represent the area of a hyperbolic sector. Should have a floating-point data type. Returns ------- out: array - an array containing the inverse hyperbolic sine of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the inverse hyperbolic sine of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -3965,7 +3965,7 @@ class asinh[TArray: Array](Protocol): - If ``a`` is ``NaN`` and ``b`` is ``NaN``, the result is ``NaN + NaN j``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -3981,30 +3981,30 @@ class atan[TArray: Array](Protocol): Each element-wise result is expressed in radians. .. note:: - The principal value of the inverse tangent of a complex number :math:`z` is + The principal value of the inverse tangent of a complex number :math:`z` is - .. math:: - \\operatorname{atan}(z) = -\\frac{\\ln(1 - zj) - \\ln(1 + zj)}{2}j + .. math:: + \\operatorname{atan}(z) = -\\frac{\\ln(1 - zj) - \\ln(1 + zj)}{2}j .. note:: - For complex floating-point operands, ``atan(conj(x))`` must equal ``conj(atan(x))``. + For complex floating-point operands, ``atan(conj(x))`` must equal ``conj(atan(x))``. .. note:: - The inverse tangent (or arc tangent) is a multi-valued function and requires a branch on the complex plane. By convention, a branch cut is placed at the line segments :math:`(-\\infty j, -j)` and :math:`(+j, \\infty j)` of the imaginary axis. + The inverse tangent (or arc tangent) is a multi-valued function and requires a branch on the complex plane. By convention, a branch cut is placed at the line segments :math:`(-\\infty j, -j)` and :math:`(+j, \\infty j)` of the imaginary axis. - Accordingly, for complex arguments, the function returns the inverse tangent in the range of a strip unbounded along the imaginary axis and in the interval :math:`[-\\pi/2, +\\pi/2]` along the real axis. + Accordingly, for complex arguments, the function returns the inverse tangent in the range of a strip unbounded along the imaginary axis and in the interval :math:`[-\\pi/2, +\\pi/2]` along the real axis. - *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). + *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). Parameters ---------- x: array - input array. Should have a floating-point data type. + input array. Should have a floating-point data type. Returns ------- out: array - an array containing the inverse tangent of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the inverse tangent of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -4021,7 +4021,7 @@ class atan[TArray: Array](Protocol): For complex floating-point operands, special cases must be handled as if the operation is implemented as ``-1j * atanh(x*1j)``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -4037,21 +4037,21 @@ class atan2[TArray: Array](Protocol): The mathematical signs of ``x1_i`` and ``x2_i`` determine the quadrant of each element-wise result. The quadrant (i.e., branch) is chosen such that each element-wise result is the signed angle in radians between the ray ending at the origin and passing through the point ``(1,0)`` and the ray ending at the origin and passing through the point ``(x2_i, x1_i)``. .. note:: - Note the role reversal: the "y-coordinate" is the first function parameter; the "x-coordinate" is the second function parameter. The parameter order is intentional and traditional for the two-argument inverse tangent function where the y-coordinate argument is first and the x-coordinate argument is second. + Note the role reversal: the "y-coordinate" is the first function parameter; the "x-coordinate" is the second function parameter. The parameter order is intentional and traditional for the two-argument inverse tangent function where the y-coordinate argument is first and the x-coordinate argument is second. By IEEE 754 convention, the inverse tangent of the quotient ``x1/x2`` is defined for ``x2_i`` equal to positive or negative zero and for either or both of ``x1_i`` and ``x2_i`` equal to positive or negative ``infinity``. Parameters ---------- x1: Union[array, int, float] - input array corresponding to the y-coordinates. Should have a real-valued floating-point data type. + input array corresponding to the y-coordinates. Should have a real-valued floating-point data type. x2: Union[array, int, float] - input array corresponding to the x-coordinates. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued floating-point data type. + input array corresponding to the x-coordinates. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued floating-point data type. Returns ------- out: array - an array containing the inverse tangent of the quotient ``x1/x2``. The returned array must have a real-valued floating-point data type determined by :ref:`type-promotion`. + an array containing the inverse tangent of the quotient ``x1/x2``. The returned array must have a real-valued floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -4086,7 +4086,7 @@ class atan2[TArray: Array](Protocol): - If ``x1_i`` is ``-infinity`` and ``x2_i`` is ``-infinity``, the result is an implementation-dependent approximation to ``-3π/4``. .. versionchanged:: 2024.12 - Added scalar argument support. + Added scalar argument support. """ @@ -4100,35 +4100,35 @@ class atanh[TArray: Array](Protocol): Calculates an implementation-dependent approximation to the inverse hyperbolic tangent for each element ``x_i`` of the input array ``x``. .. note:: - The principal value of the inverse hyperbolic tangent of a complex number :math:`z` is + The principal value of the inverse hyperbolic tangent of a complex number :math:`z` is - .. math:: - \\operatorname{atanh}(z) = \\frac{\\ln(1+z)-\\ln(z-1)}{2} + .. math:: + \\operatorname{atanh}(z) = \\frac{\\ln(1+z)-\\ln(z-1)}{2} - For any :math:`z`, + For any :math:`z`, - .. math:: - \\operatorname{atanh}(z) = \\frac{\\operatorname{atan}(zj)}{j} + .. math:: + \\operatorname{atanh}(z) = \\frac{\\operatorname{atan}(zj)}{j} .. note:: - For complex floating-point operands, ``atanh(conj(x))`` must equal ``conj(atanh(x))`` and ``atanh(-x)`` must equal ``-atanh(x)``. + For complex floating-point operands, ``atanh(conj(x))`` must equal ``conj(atanh(x))`` and ``atanh(-x)`` must equal ``-atanh(x)``. .. note:: - The inverse hyperbolic tangent is a multi-valued function and requires a branch cut on the complex plane. By convention, a branch cut is placed at the line segments :math:`(-\\infty, 1]` and :math:`[1, \\infty)` of the real axis. + The inverse hyperbolic tangent is a multi-valued function and requires a branch cut on the complex plane. By convention, a branch cut is placed at the line segments :math:`(-\\infty, 1]` and :math:`[1, \\infty)` of the real axis. - Accordingly, for complex arguments, the function returns the inverse hyperbolic tangent in the range of a half-strip unbounded along the real axis and in the interval :math:`[-\\pi j/2, +\\pi j/2]` along the imaginary axis. + Accordingly, for complex arguments, the function returns the inverse hyperbolic tangent in the range of a half-strip unbounded along the real axis and in the interval :math:`[-\\pi j/2, +\\pi j/2]` along the imaginary axis. - *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). + *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). Parameters ---------- x: array - input array whose elements each represent the area of a hyperbolic sector. Should have a floating-point data type. + input array whose elements each represent the area of a hyperbolic sector. Should have a floating-point data type. Returns ------- out: array - an array containing the inverse hyperbolic tangent of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the inverse hyperbolic tangent of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -4159,7 +4159,7 @@ class atanh[TArray: Array](Protocol): - If ``a`` is ``NaN`` and ``b`` is ``NaN``, the result is ``NaN + NaN j``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -4175,21 +4175,21 @@ class bitwise_and[TArray: Array](Protocol): Parameters ---------- x1: Union[array, int, bool] - first input array. Should have an integer or boolean data type. + first input array. Should have an integer or boolean data type. x2: Union[array, int, bool] - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have an integer or boolean data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have an integer or boolean data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- - At least one of ``x1`` or ``x2`` must be an array. .. versionchanged:: 2024.12 - Added scalar argument support. + Added scalar argument support. """ @@ -4205,21 +4205,21 @@ class bitwise_left_shift[TArray: Array](Protocol): Parameters ---------- x1: Union[array, int] - first input array. Should have an integer data type. + first input array. Should have an integer data type. x2: Union[array, int] - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have an integer data type. Each element must be greater than or equal to ``0``. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have an integer data type. Each element must be greater than or equal to ``0``. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- - At least one of ``x1`` or ``x2`` must be an array. .. versionchanged:: 2024.12 - Added scalar argument support. + Added scalar argument support. """ @@ -4235,12 +4235,12 @@ class bitwise_invert[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have an integer or boolean data type. + input array. Should have an integer or boolean data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have the same data type as ``x``. + an array containing the element-wise results. The returned array must have the same data type as ``x``. """ @@ -4256,21 +4256,21 @@ class bitwise_or[TArray: Array](Protocol): Parameters ---------- x1: Union[array, int, bool] - first input array. Should have an integer or boolean data type. + first input array. Should have an integer or boolean data type. x2: Union[array, int, bool] - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have an integer or boolean data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have an integer or boolean data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- - At least one of ``x1`` or ``x2`` must be an array. .. versionchanged:: 2024.12 - Added scalar argument support. + Added scalar argument support. """ @@ -4284,26 +4284,26 @@ class bitwise_right_shift[TArray: Array](Protocol): Shifts the bits of each element ``x1_i`` of the input array ``x1`` to the right according to the respective element ``x2_i`` of the input array ``x2``. .. note:: - This operation must be an arithmetic shift (i.e., sign-propagating) and thus equivalent to floor division by a power of two. + This operation must be an arithmetic shift (i.e., sign-propagating) and thus equivalent to floor division by a power of two. Parameters ---------- x1: Union[array, int] - first input array. Should have an integer data type. + first input array. Should have an integer data type. x2: Union[array, int] - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have an integer data type. Each element must be greater than or equal to ``0``. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have an integer data type. Each element must be greater than or equal to ``0``. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- - At least one of ``x1`` or ``x2`` must be an array. .. versionchanged:: 2024.12 - Added scalar argument support. + Added scalar argument support. """ @@ -4319,21 +4319,21 @@ class bitwise_xor[TArray: Array](Protocol): Parameters ---------- x1: Union[array, int, bool] - first input array. Should have an integer or boolean data type. + first input array. Should have an integer or boolean data type. x2: Union[array, int, bool] - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have an integer or boolean data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have an integer or boolean data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- - At least one of ``x1`` or ``x2`` must be an array. .. versionchanged:: 2024.12 - Added scalar argument support. + Added scalar argument support. """ @@ -4349,12 +4349,12 @@ class ceil[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a real-valued data type. + input array. Should have a real-valued data type. Returns ------- out: array - an array containing the rounded result for each element in ``x``. The returned array must have the same data type as ``x``. + an array containing the rounded result for each element in ``x``. The returned array must have the same data type as ``x``. Notes ----- @@ -4384,16 +4384,16 @@ class clip[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a real-valued data type. + input array. Should have a real-valued data type. min: Optional[Union[int, float, array]] - lower-bound of the range to which to clamp. If ``None``, no lower bound must be applied. Must be compatible with ``x`` and ``max`` (see :ref:`broadcasting`). Should have the same data type as ``x``. Default: ``None``. + lower-bound of the range to which to clamp. If ``None``, no lower bound must be applied. Must be compatible with ``x`` and ``max`` (see :ref:`broadcasting`). Should have the same data type as ``x``. Default: ``None``. max: Optional[Union[int, float, array]] - upper-bound of the range to which to clamp. If ``None``, no upper bound must be applied. Must be compatible with ``x`` and ``min`` (see :ref:`broadcasting`). Should have the same data type as ``x``. Default: ``None``. + upper-bound of the range to which to clamp. If ``None``, no upper bound must be applied. Must be compatible with ``x`` and ``min`` (see :ref:`broadcasting`). Should have the same data type as ``x``. Default: ``None``. Returns ------- out: array - an array containing element-wise results. The returned array should have the same data type as ``x``. + an array containing element-wise results. The returned array should have the same data type as ``x``. Notes ----- @@ -4413,13 +4413,13 @@ class clip[TArray: Array](Protocol): .. versionadded:: 2023.12 .. versionchanged:: 2024.12 - Added special case behavior when one of the operands is ``NaN``. + Added special case behavior when one of the operands is ``NaN``. .. versionchanged:: 2024.12 - Clarified that behavior is only defined when ``x``, ``min``, and ``max`` resolve to arrays having the same data type. + Clarified that behavior is only defined when ``x``, ``min``, and ``max`` resolve to arrays having the same data type. .. versionchanged:: 2024.12 - Clarified that behavior is only defined when elements of ``min`` and ``max`` are inside the bounds of the input array data type. + Clarified that behavior is only defined when elements of ``min`` and ``max`` are inside the bounds of the input array data type. """ @@ -4435,24 +4435,24 @@ class conj[TArray: Array](Protocol): For complex numbers of the form .. math:: - a + bj + a + bj the complex conjugate is defined as .. math:: - a - bj + a - bj Hence, the returned complex conjugates must be computed by negating the imaginary component of each element ``x_i``. Parameters ---------- x: array - input array. Must have a numeric data type. + input array. Must have a numeric data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have the same data type as ``x``. + an array containing the element-wise results. The returned array must have the same data type as ``x``. Notes ----- @@ -4461,7 +4461,7 @@ class conj[TArray: Array](Protocol): .. versionadded:: 2022.12 .. versionchanged:: 2024.12 - Added support for real-valued arrays. + Added support for real-valued arrays. """ @@ -4477,14 +4477,14 @@ class copysign[TArray: Array](Protocol): Parameters ---------- x1: Union[array, int, float] - input array containing magnitudes. Should have a real-valued floating-point data type. + input array containing magnitudes. Should have a real-valued floating-point data type. x2: Union[array, int, float] - input array whose sign bits are applied to the magnitudes of ``x1``. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued floating-point data type. + input array whose sign bits are applied to the magnitudes of ``x1``. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued floating-point data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the element-wise results. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -4511,7 +4511,7 @@ class copysign[TArray: Array](Protocol): .. versionadded:: 2023.12 .. versionchanged:: 2024.12 - Added scalar argument support. + Added scalar argument support. """ @@ -4527,25 +4527,25 @@ class cos[TArray: Array](Protocol): Each element ``x_i`` is assumed to be expressed in radians. .. note:: - The cosine is an entire function on the complex plane and has no branch cuts. + The cosine is an entire function on the complex plane and has no branch cuts. .. note:: - For complex arguments, the mathematical definition of cosine is + For complex arguments, the mathematical definition of cosine is - .. math:: - \\begin{align} \\operatorname{cos}(x) &= \\sum_{n=0}^\\infty \\frac{(-1)^n}{(2n)!} x^{2n} \\\\ &= \\frac{e^{jx} + e^{-jx}}{2} \\\\ &= \\operatorname{cosh}(jx) \\end{align} + .. math:: + \\begin{align} \\operatorname{cos}(x) &= \\sum_{n=0}^\\infty \\frac{(-1)^n}{(2n)!} x^{2n} \\\\ &= \\frac{e^{jx} + e^{-jx}}{2} \\\\ &= \\operatorname{cosh}(jx) \\end{align} - where :math:`\\operatorname{cosh}` is the hyperbolic cosine. + where :math:`\\operatorname{cosh}` is the hyperbolic cosine. Parameters ---------- x: array - input array whose elements are each expressed in radians. Should have a floating-point data type. + input array whose elements are each expressed in radians. Should have a floating-point data type. Returns ------- out: array - an array containing the cosine of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the cosine of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -4562,7 +4562,7 @@ class cos[TArray: Array](Protocol): For complex floating-point operands, special cases must be handled as if the operation is implemented as ``cosh(x*1j)``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -4578,27 +4578,27 @@ class cosh[TArray: Array](Protocol): The mathematical definition of the hyperbolic cosine is .. math:: - \\operatorname{cosh}(x) = \\frac{e^x + e^{-x}}{2} + \\operatorname{cosh}(x) = \\frac{e^x + e^{-x}}{2} .. note:: - The hyperbolic cosine is an entire function in the complex plane and has no branch cuts. The function is periodic, with period :math:`2\\pi j`, with respect to the imaginary component. + The hyperbolic cosine is an entire function in the complex plane and has no branch cuts. The function is periodic, with period :math:`2\\pi j`, with respect to the imaginary component. Parameters ---------- x: array - input array whose elements each represent a hyperbolic angle. Should have a floating-point data type. + input array whose elements each represent a hyperbolic angle. Should have a floating-point data type. Returns ------- out: array - an array containing the hyperbolic cosine of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the hyperbolic cosine of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- **Special cases** .. note:: - For all operands, ``cosh(x)`` must equal ``cosh(-x)``. + For all operands, ``cosh(x)`` must equal ``cosh(-x)``. For real-valued floating-point operands, @@ -4611,7 +4611,7 @@ class cosh[TArray: Array](Protocol): For complex floating-point operands, let ``a = real(x_i)``, ``b = imag(x_i)``, and .. note:: - For complex floating-point operands, ``cosh(conj(x))`` must equal ``conj(cosh(x))``. + For complex floating-point operands, ``cosh(conj(x))`` must equal ``conj(cosh(x))``. - If ``a`` is ``+0`` and ``b`` is ``+0``, the result is ``1 + 0j``. - If ``a`` is ``+0`` and ``b`` is ``+infinity``, the result is ``NaN + 0j`` (sign of the imaginary component is unspecified). @@ -4629,7 +4629,7 @@ class cosh[TArray: Array](Protocol): where ``cis(v)`` is ``cos(v) + sin(v)*1j``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -4645,14 +4645,14 @@ class divide[TArray: Array](Protocol): Parameters ---------- x1: Union[array, int, float, complex] - dividend input array. Should have a numeric data type. + dividend input array. Should have a numeric data type. x2: Union[array, int, float, complex] - divisor input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a numeric data type. + divisor input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a numeric data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the element-wise results. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -4660,7 +4660,7 @@ class divide[TArray: Array](Protocol): - If one or both of the input arrays have integer data types, the result is implementation-dependent, as type promotion between data type "kinds" (e.g., integer versus floating-point) is unspecified. - Specification-compliant libraries may choose to raise an error or return an array containing the element-wise results. If an array is returned, the array must have a real-valued floating-point data type. + Specification-compliant libraries may choose to raise an error or return an array containing the element-wise results. If an array is returned, the array must have a real-valued floating-point data type. **Special cases** @@ -4706,7 +4706,7 @@ class divide[TArray: Array](Protocol): When ``a``, ``b``, ``c``, or ``d`` are all finite numbers (i.e., a value other than ``NaN``, ``+infinity``, or ``-infinity``), division of complex floating-point operands should be computed as if calculated according to the textbook formula for complex number division .. math:: - \\frac{a + bj}{c + dj} = \\frac{(ac + bd) + (bc - ad)j}{c^2 + d^2} + \\frac{a + bj}{c + dj} = \\frac{(ac + bd) + (bc - ad)j}{c^2 + d^2} When at least one of ``a``, ``b``, ``c``, or ``d`` is ``NaN``, ``+infinity``, or ``-infinity``, @@ -4714,13 +4714,13 @@ class divide[TArray: Array](Protocol): - In the remaining cases, the result is implementation dependent. .. note:: - For complex floating-point operands, the results of special cases may be implementation dependent depending on how an implementation chooses to model complex numbers and complex infinity (e.g., complex plane versus Riemann sphere). For those implementations following C99 and its one-infinity model, when at least one component is infinite, even if the other component is ``NaN``, the complex value is infinite, and the usual arithmetic rules do not apply to complex-complex division. In the interest of performance, other implementations may want to avoid the complex branching logic necessary to implement the one-infinity model and choose to implement all complex-complex division according to the textbook formula. Accordingly, special case behavior is unlikely to be consistent across implementations. + For complex floating-point operands, the results of special cases may be implementation dependent depending on how an implementation chooses to model complex numbers and complex infinity (e.g., complex plane versus Riemann sphere). For those implementations following C99 and its one-infinity model, when at least one component is infinite, even if the other component is ``NaN``, the complex value is infinite, and the usual arithmetic rules do not apply to complex-complex division. In the interest of performance, other implementations may want to avoid the complex branching logic necessary to implement the one-infinity model and choose to implement all complex-complex division according to the textbook formula. Accordingly, special case behavior is unlikely to be consistent across implementations. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. .. versionchanged:: 2024.12 - Added scalar argument support. + Added scalar argument support. """ @@ -4736,14 +4736,14 @@ class equal[TArray: Array](Protocol): Parameters ---------- x1: Union[array, int, float, complex, bool] - first input array. May have any data type. + first input array. May have any data type. x2: Union[array, int, float, complex, bool] - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). May have any data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). May have any data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type of ``bool``. + an array containing the element-wise results. The returned array must have a data type of ``bool``. Notes ----- @@ -4767,19 +4767,19 @@ class equal[TArray: Array](Protocol): - In the remaining cases, the result is the logical AND of the equality comparison between the real values ``a`` and ``c`` (real components) and between the real values ``b`` and ``d`` (imaginary components), as described above for real-valued floating-point operands (i.e., ``a == c AND b == d``). .. note:: - For discussion of complex number equality, see :ref:`complex-numbers`. + For discussion of complex number equality, see :ref:`complex-numbers`. .. note:: - Comparison of arrays without a corresponding promotable data type (see :ref:`type-promotion`) is undefined and thus implementation-dependent. + Comparison of arrays without a corresponding promotable data type (see :ref:`type-promotion`) is undefined and thus implementation-dependent. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. .. versionchanged:: 2024.12 - Cross-kind comparisons are explicitly left unspecified. + Cross-kind comparisons are explicitly left unspecified. .. versionchanged:: 2024.12 - Added scalar argument support. + Added scalar argument support. """ @@ -4793,20 +4793,20 @@ class exp[TArray: Array](Protocol): Calculates an implementation-dependent approximation to the exponential function for each element ``x_i`` of the input array ``x`` (``e`` raised to the power of ``x_i``, where ``e`` is the base of the natural logarithm). .. note:: - For complex floating-point operands, ``exp(conj(x))`` must equal ``conj(exp(x))``. + For complex floating-point operands, ``exp(conj(x))`` must equal ``conj(exp(x))``. .. note:: - The exponential function is an entire function in the complex plane and has no branch cuts. + The exponential function is an entire function in the complex plane and has no branch cuts. Parameters ---------- x: array - input array. Should have a floating-point data type. + input array. Should have a floating-point data type. Returns ------- out: array - an array containing the evaluated exponential function result for each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the evaluated exponential function result for each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -4839,7 +4839,7 @@ class exp[TArray: Array](Protocol): where ``cis(v)`` is ``cos(v) + sin(v)*1j``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -4853,23 +4853,23 @@ class expm1[TArray: Array](Protocol): Calculates an implementation-dependent approximation to ``exp(x)-1`` for each element ``x_i`` of the input array ``x``. .. note:: - The purpose of this function is to calculate ``exp(x)-1.0`` more accurately when `x` is close to zero. Accordingly, conforming implementations should avoid implementing this function as simply ``exp(x)-1.0``. See FDLIBM, or some other IEEE 754-2019 compliant mathematical library, for a potential reference implementation. + The purpose of this function is to calculate ``exp(x)-1.0`` more accurately when `x` is close to zero. Accordingly, conforming implementations should avoid implementing this function as simply ``exp(x)-1.0``. See FDLIBM, or some other IEEE 754-2019 compliant mathematical library, for a potential reference implementation. .. note:: - For complex floating-point operands, ``expm1(conj(x))`` must equal ``conj(expm1(x))``. + For complex floating-point operands, ``expm1(conj(x))`` must equal ``conj(expm1(x))``. .. note:: - The exponential function is an entire function in the complex plane and has no branch cuts. + The exponential function is an entire function in the complex plane and has no branch cuts. Parameters ---------- x: array - input array. Should have a floating-point data type. + input array. Should have a floating-point data type. Returns ------- out: array - an array containing the evaluated result for each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the evaluated result for each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -4902,7 +4902,7 @@ class expm1[TArray: Array](Protocol): where ``cis(v)`` is ``cos(v) + sin(v)*1j``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -4918,12 +4918,12 @@ class floor[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a real-valued data type. + input array. Should have a real-valued data type. Returns ------- out: array - an array containing the rounded result for each element in ``x``. The returned array must have the same data type as ``x``. + an array containing the rounded result for each element in ``x``. The returned array must have the same data type as ``x``. Notes ----- @@ -4953,14 +4953,14 @@ class floor_divide[TArray: Array](Protocol): Parameters ---------- x1: Union[array, int, float] - dividend input array. Should have a real-valued data type. + dividend input array. Should have a real-valued data type. x2: Union[array, int, float] - divisor input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued data type. + divisor input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- @@ -4970,13 +4970,13 @@ class floor_divide[TArray: Array](Protocol): **Special cases** .. note:: - Floor division was introduced in Python via `PEP 238 `_ with the goal to disambiguate "true division" (i.e., computing an approximation to the mathematical operation of division) from "floor division" (i.e., rounding the result of division toward negative infinity). The former was computed when one of the operands was a ``float``, while the latter was computed when both operands were ``int``\\s. Overloading the ``/`` operator to support both behaviors led to subtle numerical bugs when integers are possible, but not expected. + Floor division was introduced in Python via `PEP 238 `_ with the goal to disambiguate "true division" (i.e., computing an approximation to the mathematical operation of division) from "floor division" (i.e., rounding the result of division toward negative infinity). The former was computed when one of the operands was a ``float``, while the latter was computed when both operands were ``int``\\s. Overloading the ``/`` operator to support both behaviors led to subtle numerical bugs when integers are possible, but not expected. - To resolve this ambiguity, ``/`` was designated for true division, and ``//`` was designated for floor division. Semantically, floor division was `defined `_ as equivalent to ``a // b == floor(a/b)``; however, special floating-point cases were left ill-defined. + To resolve this ambiguity, ``/`` was designated for true division, and ``//`` was designated for floor division. Semantically, floor division was `defined `_ as equivalent to ``a // b == floor(a/b)``; however, special floating-point cases were left ill-defined. - Accordingly, floor division is not implemented consistently across array libraries for some of the special cases documented below. Namely, when one of the operands is ``infinity``, libraries may diverge with some choosing to strictly follow ``floor(a/b)`` and others choosing to pair ``//`` with ``%`` according to the relation ``b = a % b + b * (a // b)``. The special cases leading to divergent behavior are documented below. + Accordingly, floor division is not implemented consistently across array libraries for some of the special cases documented below. Namely, when one of the operands is ``infinity``, libraries may diverge with some choosing to strictly follow ``floor(a/b)`` and others choosing to pair ``//`` with ``%`` according to the relation ``b = a % b + b * (a // b)``. The special cases leading to divergent behavior are documented below. - This specification prefers floor division to match ``floor(divide(x1, x2))`` in order to avoid surprising and unexpected results; however, array libraries may choose to more strictly follow Python behavior. + This specification prefers floor division to match ``floor(divide(x1, x2))`` in order to avoid surprising and unexpected results; however, array libraries may choose to more strictly follow Python behavior. For floating-point operands, @@ -5004,7 +5004,7 @@ class floor_divide[TArray: Array](Protocol): - In the remaining cases, where neither ``-infinity``, ``+0``, ``-0``, nor ``NaN`` is involved, the quotient must be computed and rounded to the greatest (i.e., closest to `+infinity`) representable integer-value number that is not greater than the division result. If the magnitude is too large to represent, the operation overflows and the result is an ``infinity`` of appropriate mathematical sign. If the magnitude is too small to represent, the operation underflows and the result is a zero of appropriate mathematical sign. .. versionchanged:: 2024.12 - Added scalar argument support. + Added scalar argument support. """ @@ -5020,14 +5020,14 @@ class greater[TArray: Array](Protocol): Parameters ---------- x1: Union[array, int, float] - first input array. Should have a real-valued data type. + first input array. Should have a real-valued data type. x2: Union[array, int, float] - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type of ``bool``. + an array containing the element-wise results. The returned array must have a data type of ``bool``. Notes ----- @@ -5036,10 +5036,10 @@ class greater[TArray: Array](Protocol): - For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). .. versionchanged:: 2024.12 - Cross-kind comparisons are explicitly left unspecified. + Cross-kind comparisons are explicitly left unspecified. .. versionchanged:: 2024.12 - Added scalar argument support. + Added scalar argument support. """ @@ -5055,14 +5055,14 @@ class greater_equal[TArray: Array](Protocol): Parameters ---------- x1: Union[array, int, float] - first input array. Should have a real-valued data type. + first input array. Should have a real-valued data type. x2: Union[array, int, float] - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type of ``bool``. + an array containing the element-wise results. The returned array must have a data type of ``bool``. Notes ----- @@ -5071,10 +5071,10 @@ class greater_equal[TArray: Array](Protocol): - For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). .. versionchanged:: 2024.12 - Cross-kind comparisons are explicitly left unspecified. + Cross-kind comparisons are explicitly left unspecified. .. versionchanged:: 2024.12 - Added scalar argument support. + Added scalar argument support. """ @@ -5088,19 +5088,19 @@ class hypot[TArray: Array](Protocol): Computes the square root of the sum of squares for each element ``x1_i`` of the input array ``x1`` with the respective element ``x2_i`` of the input array ``x2``. .. note:: - The value computed by this function may be interpreted as the length of the hypotenuse of a right-angled triangle with sides of length ``x1_i`` and ``x2_i``, the distance of a point ``(x1_i, x2_i)`` from the origin ``(0, 0)``, or the magnitude of a complex number ``x1_i + x2_i * 1j``. + The value computed by this function may be interpreted as the length of the hypotenuse of a right-angled triangle with sides of length ``x1_i`` and ``x2_i``, the distance of a point ``(x1_i, x2_i)`` from the origin ``(0, 0)``, or the magnitude of a complex number ``x1_i + x2_i * 1j``. Parameters ---------- x1: Union[array, int, float] - first input array. Should have a real-valued floating-point data type. + first input array. Should have a real-valued floating-point data type. x2: Union[array, int, float] - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued floating-point data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued floating-point data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a real-valued floating-point data type determined by :ref:`type-promotion`. + an array containing the element-wise results. The returned array must have a real-valued floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -5122,14 +5122,14 @@ class hypot[TArray: Array](Protocol): For real-valued floating-point operands, ``hypot(x1, x2)`` must equal ``hypot(x2, x1)``, ``hypot(x1, -x2)``, ``hypot(-x1, x2)``, and ``hypot(-x1, -x2)``. .. note:: - IEEE 754-2019 requires support for subnormal (a.k.a., denormal) numbers, which are useful for supporting gradual underflow. However, hardware support for subnormal numbers is not universal, and many platforms (e.g., accelerators) and compilers support toggling denormals-are-zero (DAZ) and/or flush-to-zero (FTZ) behavior to increase performance and to guard against timing attacks. + IEEE 754-2019 requires support for subnormal (a.k.a., denormal) numbers, which are useful for supporting gradual underflow. However, hardware support for subnormal numbers is not universal, and many platforms (e.g., accelerators) and compilers support toggling denormals-are-zero (DAZ) and/or flush-to-zero (FTZ) behavior to increase performance and to guard against timing attacks. - Accordingly, conforming implementations may vary in their support for subnormal numbers. + Accordingly, conforming implementations may vary in their support for subnormal numbers. .. versionadded:: 2023.12 .. versionchanged:: 2024.12 - Added scalar argument support. + Added scalar argument support. """ @@ -5145,12 +5145,12 @@ class imag[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a complex floating-point data type. + input array. Should have a complex floating-point data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a floating-point data type with the same floating-point precision as ``x`` (e.g., if ``x`` is ``complex64``, the returned array must have the floating-point data type ``float32``). + an array containing the element-wise results. The returned array must have a floating-point data type with the same floating-point precision as ``x`` (e.g., if ``x`` is ``complex64``, the returned array must have the floating-point data type ``float32``). Notes ----- @@ -5171,12 +5171,12 @@ class isfinite[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a numeric data type. + input array. Should have a numeric data type. Returns ------- out: array - an array containing test results. The returned array must have a data type of ``bool``. + an array containing test results. The returned array must have a data type of ``bool``. Notes ----- @@ -5196,7 +5196,7 @@ class isfinite[TArray: Array](Protocol): - If ``a`` is a finite number and ``b`` is a finite number, the result is ``True``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -5212,12 +5212,12 @@ class isinf[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a numeric data type. + input array. Should have a numeric data type. Returns ------- out: array - an array containing test results. The returned array must have a data type of ``bool``. + an array containing test results. The returned array must have a data type of ``bool``. Notes ----- @@ -5235,7 +5235,7 @@ class isinf[TArray: Array](Protocol): - In the remaining cases, the result is ``False``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -5251,12 +5251,12 @@ class isnan[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a numeric data type. + input array. Should have a numeric data type. Returns ------- out: array - an array containing test results. The returned array should have a data type of ``bool``. + an array containing test results. The returned array should have a data type of ``bool``. Notes ----- @@ -5273,7 +5273,7 @@ class isnan[TArray: Array](Protocol): - In the remaining cases, the result is ``False``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -5289,14 +5289,14 @@ class less[TArray: Array](Protocol): Parameters ---------- x1: Union[array, int, float] - first input array. Should have a real-valued data type. + first input array. Should have a real-valued data type. x2: Union[array, int, float] - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type of ``bool``. + an array containing the element-wise results. The returned array must have a data type of ``bool``. Notes ----- @@ -5305,10 +5305,10 @@ class less[TArray: Array](Protocol): - For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). .. versionchanged:: 2024.12 - Cross-kind comparisons are explicitly left unspecified. + Cross-kind comparisons are explicitly left unspecified. .. versionchanged:: 2024.12 - Added scalar argument support. + Added scalar argument support. """ @@ -5324,14 +5324,14 @@ class less_equal[TArray: Array](Protocol): Parameters ---------- x1: Union[array, int, float] - first input array. Should have a real-valued data type. + first input array. Should have a real-valued data type. x2: Union[array, int, float] - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type of ``bool``. + an array containing the element-wise results. The returned array must have a data type of ``bool``. Notes ----- @@ -5340,10 +5340,10 @@ class less_equal[TArray: Array](Protocol): - For backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see :ref:`complex-number-ordering`). .. versionchanged:: 2024.12 - Cross-kind comparisons are explicitly left unspecified. + Cross-kind comparisons are explicitly left unspecified. .. versionchanged:: 2024.12 - Added scalar argument support. + Added scalar argument support. """ @@ -5357,29 +5357,29 @@ class log[TArray: Array](Protocol): Calculates an implementation-dependent approximation to the natural (base ``e``) logarithm for each element ``x_i`` of the input array ``x``. .. note:: - The natural logarithm of a complex number :math:`z` with polar coordinates :math:`(r,\\theta)` equals :math:`\\ln r + (\\theta + 2n\\pi)j` with principal value :math:`\\ln r + \\theta j`. + The natural logarithm of a complex number :math:`z` with polar coordinates :math:`(r,\\theta)` equals :math:`\\ln r + (\\theta + 2n\\pi)j` with principal value :math:`\\ln r + \\theta j`. .. note:: - For complex floating-point operands, ``log(conj(x))`` must equal ``conj(log(x))``. + For complex floating-point operands, ``log(conj(x))`` must equal ``conj(log(x))``. .. note:: - By convention, the branch cut of the natural logarithm is the negative real axis :math:`(-\\infty, 0)`. + By convention, the branch cut of the natural logarithm is the negative real axis :math:`(-\\infty, 0)`. - The natural logarithm is a continuous function from above the branch cut, taking into account the sign of the imaginary component. + The natural logarithm is a continuous function from above the branch cut, taking into account the sign of the imaginary component. - Accordingly, for complex arguments, the function returns the natural logarithm in the range of a strip in the interval :math:`[-\\pi j, +\\pi j]` along the imaginary axis and mathematically unbounded along the real axis. + Accordingly, for complex arguments, the function returns the natural logarithm in the range of a strip in the interval :math:`[-\\pi j, +\\pi j]` along the imaginary axis and mathematically unbounded along the real axis. - *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). + *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). Parameters ---------- x: array - input array. Should have a floating-point data type. + input array. Should have a floating-point data type. Returns ------- out: array - an array containing the evaluated natural logarithm for each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the evaluated natural logarithm for each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -5409,7 +5409,7 @@ class log[TArray: Array](Protocol): - If ``a`` is ``NaN`` and ``b`` is ``NaN``, the result is ``NaN + NaN j``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -5423,29 +5423,29 @@ class log1p[TArray: Array](Protocol): Calculates an implementation-dependent approximation to ``log(1+x)``, where ``log`` refers to the natural (base ``e``) logarithm, for each element ``x_i`` of the input array ``x``. .. note:: - The purpose of this function is to calculate ``log(1+x)`` more accurately when `x` is close to zero. Accordingly, conforming implementations should avoid implementing this function as simply ``log(1+x)``. See FDLIBM, or some other IEEE 754-2019 compliant mathematical library, for a potential reference implementation. + The purpose of this function is to calculate ``log(1+x)`` more accurately when `x` is close to zero. Accordingly, conforming implementations should avoid implementing this function as simply ``log(1+x)``. See FDLIBM, or some other IEEE 754-2019 compliant mathematical library, for a potential reference implementation. .. note:: - For complex floating-point operands, ``log1p(conj(x))`` must equal ``conj(log1p(x))``. + For complex floating-point operands, ``log1p(conj(x))`` must equal ``conj(log1p(x))``. .. note:: - By convention, the branch cut of the natural logarithm is the negative real axis :math:`(-\\infty, 0)`. + By convention, the branch cut of the natural logarithm is the negative real axis :math:`(-\\infty, 0)`. - The natural logarithm is a continuous function from above the branch cut, taking into account the sign of the imaginary component. + The natural logarithm is a continuous function from above the branch cut, taking into account the sign of the imaginary component. - Accordingly, for complex arguments, the function returns the natural logarithm in the range of a strip in the interval :math:`[-\\pi j, +\\pi j]` along the imaginary axis and mathematically unbounded along the real axis. + Accordingly, for complex arguments, the function returns the natural logarithm in the range of a strip in the interval :math:`[-\\pi j, +\\pi j]` along the imaginary axis and mathematically unbounded along the real axis. - *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). + *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). Parameters ---------- x: array - input array. Should have a floating-point data type. + input array. Should have a floating-point data type. Returns ------- out: array - an array containing the evaluated result for each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the evaluated result for each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -5475,7 +5475,7 @@ class log1p[TArray: Array](Protocol): - If ``a`` is ``NaN`` and ``b`` is ``NaN``, the result is ``NaN + NaN j``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -5489,17 +5489,17 @@ class log2[TArray: Array](Protocol): Calculates an implementation-dependent approximation to the base ``2`` logarithm for each element ``x_i`` of the input array ``x``. .. note:: - For complex floating-point operands, ``log2(conj(x))`` must equal ``conj(log2(x))``. + For complex floating-point operands, ``log2(conj(x))`` must equal ``conj(log2(x))``. Parameters ---------- x: array - input array. Should have a floating-point data type. + input array. Should have a floating-point data type. Returns ------- out: array - an array containing the evaluated base ``2`` logarithm for each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the evaluated base ``2`` logarithm for each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -5516,12 +5516,12 @@ class log2[TArray: Array](Protocol): For complex floating-point operands, special cases must be handled as if the operation is implemented using the standard change of base formula .. math:: - \\log_{2} x = \\frac{\\log_{e} x}{\\log_{e} 2} + \\log_{2} x = \\frac{\\log_{e} x}{\\log_{e} 2} where :math:`\\log_{e}` is the natural logarithm, as implemented by :func:`~array_api.log`. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -5535,17 +5535,17 @@ class log10[TArray: Array](Protocol): Calculates an implementation-dependent approximation to the base ``10`` logarithm for each element ``x_i`` of the input array ``x``. .. note:: - For complex floating-point operands, ``log10(conj(x))`` must equal ``conj(log10(x))``. + For complex floating-point operands, ``log10(conj(x))`` must equal ``conj(log10(x))``. Parameters ---------- x: array - input array. Should have a floating-point data type. + input array. Should have a floating-point data type. Returns ------- out: array - an array containing the evaluated base ``10`` logarithm for each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the evaluated base ``10`` logarithm for each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -5562,12 +5562,12 @@ class log10[TArray: Array](Protocol): For complex floating-point operands, special cases must be handled as if the operation is implemented using the standard change of base formula .. math:: - \\log_{10} x = \\frac{\\log_{e} x}{\\log_{e} 10} + \\log_{10} x = \\frac{\\log_{e} x}{\\log_{e} 10} where :math:`\\log_{e}` is the natural logarithm, as implemented by :func:`~array_api.log`. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -5583,14 +5583,14 @@ class logaddexp[TArray: Array](Protocol): Parameters ---------- x1: Union[array, int, float] - first input array. Should have a real-valued floating-point data type. + first input array. Should have a real-valued floating-point data type. x2: Union[array, int, float] - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued floating-point data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued floating-point data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a real-valued floating-point data type determined by :ref:`type-promotion`. + an array containing the element-wise results. The returned array must have a real-valued floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -5605,7 +5605,7 @@ class logaddexp[TArray: Array](Protocol): - If ``x1_i`` is not ``NaN`` and ``x2_i`` is ``+infinity``, the result is ``+infinity``. .. versionchanged:: 2024.12 - Added scalar argument support. + Added scalar argument support. """ @@ -5619,26 +5619,26 @@ class logical_and[TArray: Array](Protocol): Computes the logical AND for each element ``x1_i`` of the input array ``x1`` with the respective element ``x2_i`` of the input array ``x2``. .. note:: - While this specification recommends that this function only accept input arrays having a boolean data type, specification-compliant array libraries may choose to accept input arrays having real-valued data types. If non-boolean data types are supported, zeros must be considered the equivalent of ``False``, while non-zeros must be considered the equivalent of ``True``. + While this specification recommends that this function only accept input arrays having a boolean data type, specification-compliant array libraries may choose to accept input arrays having real-valued data types. If non-boolean data types are supported, zeros must be considered the equivalent of ``False``, while non-zeros must be considered the equivalent of ``True``. Parameters ---------- x1: Union[array, bool] - first input array. Should have a boolean data type. + first input array. Should have a boolean data type. x2: Union[array, bool] - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a boolean data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a boolean data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type of `bool`. + an array containing the element-wise results. The returned array must have a data type of `bool`. Notes ----- - At least one of ``x1`` or ``x2`` must be an array. .. versionchanged:: 2024.12 - Added scalar argument support. + Added scalar argument support. """ @@ -5652,17 +5652,17 @@ class logical_not[TArray: Array](Protocol): Computes the logical NOT for each element ``x_i`` of the input array ``x``. .. note:: - While this specification recommends that this function only accept input arrays having a boolean data type, specification-compliant array libraries may choose to accept input arrays having real-valued data types. If non-boolean data types are supported, zeros must be considered the equivalent of ``False``, while non-zeros must be considered the equivalent of ``True``. + While this specification recommends that this function only accept input arrays having a boolean data type, specification-compliant array libraries may choose to accept input arrays having real-valued data types. If non-boolean data types are supported, zeros must be considered the equivalent of ``False``, while non-zeros must be considered the equivalent of ``True``. Parameters ---------- x: array - input array. Should have a boolean data type. + input array. Should have a boolean data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type of ``bool``. + an array containing the element-wise results. The returned array must have a data type of ``bool``. """ @@ -5676,26 +5676,26 @@ class logical_or[TArray: Array](Protocol): Computes the logical OR for each element ``x1_i`` of the input array ``x1`` with the respective element ``x2_i`` of the input array ``x2``. .. note:: - While this specification recommends that this function only accept input arrays having a boolean data type, specification-compliant array libraries may choose to accept input arrays having real-valued data types. If non-boolean data types are supported, zeros must be considered the equivalent of ``False``, while non-zeros must be considered the equivalent of ``True``. + While this specification recommends that this function only accept input arrays having a boolean data type, specification-compliant array libraries may choose to accept input arrays having real-valued data types. If non-boolean data types are supported, zeros must be considered the equivalent of ``False``, while non-zeros must be considered the equivalent of ``True``. Parameters ---------- x1: Union[array, bool] - first input array. Should have a boolean data type. + first input array. Should have a boolean data type. x2: Union[array, bool] - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a boolean data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a boolean data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type of ``bool``. + an array containing the element-wise results. The returned array must have a data type of ``bool``. Notes ----- - At least one of ``x1`` or ``x2`` must be an array. .. versionchanged:: 2024.12 - Added scalar argument support. + Added scalar argument support. """ @@ -5709,26 +5709,26 @@ class logical_xor[TArray: Array](Protocol): Computes the logical XOR for each element ``x1_i`` of the input array ``x1`` with the respective element ``x2_i`` of the input array ``x2``. .. note:: - While this specification recommends that this function only accept input arrays having a boolean data type, specification-compliant array libraries may choose to accept input arrays having real-valued data types. If non-boolean data types are supported, zeros must be considered the equivalent of ``False``, while non-zeros must be considered the equivalent of ``True``. + While this specification recommends that this function only accept input arrays having a boolean data type, specification-compliant array libraries may choose to accept input arrays having real-valued data types. If non-boolean data types are supported, zeros must be considered the equivalent of ``False``, while non-zeros must be considered the equivalent of ``True``. Parameters ---------- x1: Union[array, bool] - first input array. Should have a boolean data type. + first input array. Should have a boolean data type. x2: Union[array, bool] - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a boolean data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a boolean data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type of ``bool``. + an array containing the element-wise results. The returned array must have a data type of ``bool``. Notes ----- - At least one of ``x1`` or ``x2`` must be an array. .. versionchanged:: 2024.12 - Added scalar argument support. + Added scalar argument support. """ @@ -5744,14 +5744,14 @@ class maximum[TArray: Array](Protocol): Parameters ---------- x1: Union[array, int, float] - first input array. Should have a real-valued data type. + first input array. Should have a real-valued data type. x2: Union[array, int, float] - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued data type. Returns ------- out: array - an array containing the element-wise maximum values. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise maximum values. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- @@ -5768,7 +5768,7 @@ class maximum[TArray: Array](Protocol): .. versionadded:: 2023.12 .. versionchanged:: 2024.12 - Added scalar argument support. + Added scalar argument support. """ @@ -5784,14 +5784,14 @@ class minimum[TArray: Array](Protocol): Parameters ---------- x1: Union[array, int, float] - first input array. Should have a real-valued data type. + first input array. Should have a real-valued data type. x2: Union[array, int, float] - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued data type. Returns ------- out: array - an array containing the element-wise minimum values. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise minimum values. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- @@ -5808,7 +5808,7 @@ class minimum[TArray: Array](Protocol): .. versionadded:: 2023.12 .. versionchanged:: 2024.12 - Added scalar argument support. + Added scalar argument support. """ @@ -5822,19 +5822,19 @@ class multiply[TArray: Array](Protocol): Calculates the product for each element ``x1_i`` of the input array ``x1`` with the respective element ``x2_i`` of the input array ``x2``. .. note:: - Floating-point multiplication is not always associative due to finite precision. + Floating-point multiplication is not always associative due to finite precision. Parameters ---------- x1: Union[array, int, float, complex] - first input array. Should have a numeric data type. + first input array. Should have a numeric data type. x2: Union[array, int, float, complex] - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a numeric data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a numeric data type. Returns ------- out: array - an array containing the element-wise products. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise products. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- @@ -5871,7 +5871,7 @@ class multiply[TArray: Array](Protocol): When ``a``, ``b``, ``c``, or ``d`` are all finite numbers (i.e., a value other than ``NaN``, ``+infinity``, or ``-infinity``), multiplication of complex floating-point operands should be computed as if calculated according to the textbook formula for complex number multiplication .. math:: - (a + bj) \\cdot (c + dj) = (ac - bd) + (bc + ad)j + (a + bj) \\cdot (c + dj) = (ac - bd) + (bc + ad)j When at least one of ``a``, ``b``, ``c``, or ``d`` is ``NaN``, ``+infinity``, or ``-infinity``, @@ -5879,13 +5879,13 @@ class multiply[TArray: Array](Protocol): - In the remaining cases, the result is implementation dependent. .. note:: - For complex floating-point operands, the results of special cases may be implementation dependent depending on how an implementation chooses to model complex numbers and complex infinity (e.g., complex plane versus Riemann sphere). For those implementations following C99 and its one-infinity model, when at least one component is infinite, even if the other component is ``NaN``, the complex value is infinite, and the usual arithmetic rules do not apply to complex-complex multiplication. In the interest of performance, other implementations may want to avoid the complex branching logic necessary to implement the one-infinity model and choose to implement all complex-complex multiplication according to the textbook formula. Accordingly, special case behavior is unlikely to be consistent across implementations. + For complex floating-point operands, the results of special cases may be implementation dependent depending on how an implementation chooses to model complex numbers and complex infinity (e.g., complex plane versus Riemann sphere). For those implementations following C99 and its one-infinity model, when at least one component is infinite, even if the other component is ``NaN``, the complex value is infinite, and the usual arithmetic rules do not apply to complex-complex multiplication. In the interest of performance, other implementations may want to avoid the complex branching logic necessary to implement the one-infinity model and choose to implement all complex-complex multiplication according to the textbook formula. Accordingly, special case behavior is unlikely to be consistent across implementations. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. .. versionchanged:: 2024.12 - Added scalar argument support. + Added scalar argument support. """ @@ -5899,26 +5899,26 @@ class negative[TArray: Array](Protocol): Computes the numerical negative of each element ``x_i`` (i.e., ``y_i = -x_i``) of the input array ``x``. .. note:: - For signed integer data types, the numerical negative of the minimum representable integer is implementation-dependent. + For signed integer data types, the numerical negative of the minimum representable integer is implementation-dependent. .. note:: - If ``x`` has a complex floating-point data type, both the real and imaginary components for each ``x_i`` must be negated (a result which follows from the rules of complex number multiplication). + If ``x`` has a complex floating-point data type, both the real and imaginary components for each ``x_i`` must be negated (a result which follows from the rules of complex number multiplication). Parameters ---------- x: array - input array. Should have a numeric data type. + input array. Should have a numeric data type. Returns ------- out: array - an array containing the evaluated result for each element in ``x``. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the evaluated result for each element in ``x``. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -5934,14 +5934,14 @@ class nextafter[TArray: Array](Protocol): Parameters ---------- x1: Union[array, int, float] - first input array. Should have a real-valued floating-point data type. + first input array. Should have a real-valued floating-point data type. x2: Union[array, int, float] - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have the same data type as ``x1``. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have the same data type as ``x1``. Returns ------- out: array - an array containing the element-wise results. The returned array must have the same data type as ``x1``. + an array containing the element-wise results. The returned array must have the same data type as ``x1``. Notes ----- @@ -5971,14 +5971,14 @@ class not_equal[TArray: Array](Protocol): Parameters ---------- x1: Union[array, int, float, complex, bool] - first input array. May have any data type. + first input array. May have any data type. x2: Union[array, int, float, complex, bool] - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type of ``bool``. + an array containing the element-wise results. The returned array must have a data type of ``bool``. Notes ----- @@ -6000,19 +6000,19 @@ class not_equal[TArray: Array](Protocol): - In the remaining cases, the result is the logical OR of the equality comparison between the real values ``a`` and ``c`` (real components) and between the real values ``b`` and ``d`` (imaginary components), as described above for real-valued floating-point operands (i.e., ``a != c OR b != d``). .. note:: - For discussion of complex number equality, see :ref:`complex-numbers`. + For discussion of complex number equality, see :ref:`complex-numbers`. .. note:: - Comparison of arrays without a corresponding promotable data type (see :ref:`type-promotion`) is undefined and thus implementation-dependent. + Comparison of arrays without a corresponding promotable data type (see :ref:`type-promotion`) is undefined and thus implementation-dependent. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. .. versionchanged:: 2024.12 - Cross-kind comparisons are explicitly left unspecified. + Cross-kind comparisons are explicitly left unspecified. .. versionchanged:: 2024.12 - Added scalar argument support. + Added scalar argument support. """ @@ -6028,18 +6028,18 @@ class positive[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a numeric data type. + input array. Should have a numeric data type. Returns ------- out: array - an array containing the evaluated result for each element in ``x``. The returned array must have the same data type as ``x``. + an array containing the evaluated result for each element in ``x``. The returned array must have the same data type as ``x``. Notes ----- .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -6055,14 +6055,14 @@ class pow[TArray: Array](Protocol): Parameters ---------- x1: Union[array, int, float, complex] - first input array whose elements correspond to the exponentiation base. Should have a numeric data type. + first input array whose elements correspond to the exponentiation base. Should have a numeric data type. x2: Union[array, int, float, complex] - second input array whose elements correspond to the exponentiation exponent. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a numeric data type. + second input array whose elements correspond to the exponentiation exponent. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a numeric data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise results. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- @@ -6074,9 +6074,9 @@ class pow[TArray: Array](Protocol): - By convention, the branch cut of the natural logarithm is the negative real axis :math:`(-\\infty, 0)`. - The natural logarithm is a continuous function from above the branch cut, taking into account the sign of the imaginary component. As special cases involving complex floating-point operands should be handled according to ``exp(x2*log(x1))``, exponentiation has the same branch cut for ``x1`` as the natural logarithm (see :func:`~array_api.log`). + The natural logarithm is a continuous function from above the branch cut, taking into account the sign of the imaginary component. As special cases involving complex floating-point operands should be handled according to ``exp(x2*log(x1))``, exponentiation has the same branch cut for ``x1`` as the natural logarithm (see :func:`~array_api.log`). - *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). + *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). **Special cases** @@ -6110,13 +6110,13 @@ class pow[TArray: Array](Protocol): For complex floating-point operands, special cases should be handled as if the operation is implemented as ``exp(x2*log(x1))``. .. note:: - Conforming implementations are allowed to treat special cases involving complex floating-point operands more carefully than as described in this specification. + Conforming implementations are allowed to treat special cases involving complex floating-point operands more carefully than as described in this specification. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. .. versionchanged:: 2024.12 - Added scalar argument support. + Added scalar argument support. """ @@ -6132,12 +6132,12 @@ class real[TArray: Array](Protocol): Parameters ---------- x: array - input array. Must have a numeric data type. + input array. Must have a numeric data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a floating-point data type with the same floating-point precision as ``x`` (e.g., if ``x`` is ``complex64``, the returned array must have the floating-point data type ``float32``). + an array containing the element-wise results. The returned array must have a floating-point data type with the same floating-point precision as ``x`` (e.g., if ``x`` is ``complex64``, the returned array must have the floating-point data type ``float32``). Notes ----- @@ -6146,7 +6146,7 @@ class real[TArray: Array](Protocol): .. versionadded:: 2022.12 .. versionchanged:: 2024.12 - Added support for real-valued arrays. + Added support for real-valued arrays. """ @@ -6162,12 +6162,12 @@ class reciprocal[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a floating-point data type. + input array. Should have a floating-point data type. Returns ------- out: array - an array containing the element-wise results. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the element-wise results. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -6189,19 +6189,19 @@ class remainder[TArray: Array](Protocol): Returns the remainder of division for each element ``x1_i`` of the input array ``x1`` and the respective element ``x2_i`` of the input array ``x2``. .. note:: - This function is equivalent to the Python modulus operator ``x1_i % x2_i``. + This function is equivalent to the Python modulus operator ``x1_i % x2_i``. Parameters ---------- x1: Union[array, int, float] - dividend input array. Should have a real-valued data type. + dividend input array. Should have a real-valued data type. x2: Union[array, int, float] - divisor input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued data type. + divisor input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a real-valued data type. Returns ------- out: array - an array containing the element-wise results. Each element-wise result must have the same sign as the respective element ``x2_i``. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise results. Each element-wise result must have the same sign as the respective element ``x2_i``. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- @@ -6211,7 +6211,7 @@ class remainder[TArray: Array](Protocol): **Special cases** .. note:: - In general, similar to Python's ``%`` operator, this function is **not** recommended for floating-point operands as semantics do not follow IEEE 754. That this function is specified to accept floating-point operands is primarily for reasons of backward compatibility. + In general, similar to Python's ``%`` operator, this function is **not** recommended for floating-point operands as semantics do not follow IEEE 754. That this function is specified to accept floating-point operands is primarily for reasons of backward compatibility. For floating-point operands, @@ -6237,7 +6237,7 @@ class remainder[TArray: Array](Protocol): - In the remaining cases, the result must match that of the Python ``%`` operator. .. versionchanged:: 2024.12 - Added scalar argument support. + Added scalar argument support. """ @@ -6251,26 +6251,26 @@ class round[TArray: Array](Protocol): Rounds each element ``x_i`` of the input array ``x`` to the nearest integer-valued number. .. note:: - For complex floating-point operands, real and imaginary components must be independently rounded to the nearest integer-valued number. + For complex floating-point operands, real and imaginary components must be independently rounded to the nearest integer-valued number. - Rounded real and imaginary components must be equal to their equivalent rounded real-valued floating-point counterparts (i.e., for complex-valued ``x``, ``real(round(x))`` must equal ``round(real(x)))`` and ``imag(round(x))`` must equal ``round(imag(x))``). + Rounded real and imaginary components must be equal to their equivalent rounded real-valued floating-point counterparts (i.e., for complex-valued ``x``, ``real(round(x))`` must equal ``round(real(x)))`` and ``imag(round(x))`` must equal ``round(imag(x))``). Parameters ---------- x: array - input array. Should have a numeric data type. + input array. Should have a numeric data type. Returns ------- out: array - an array containing the rounded result for each element in ``x``. The returned array must have the same data type as ``x``. + an array containing the rounded result for each element in ``x``. The returned array must have the same data type as ``x``. Notes ----- **Special cases** .. note:: - For complex floating-point operands, the following special cases apply to real and imaginary components independently (e.g., if ``real(x_i)`` is ``NaN``, the rounded real component is ``NaN``). + For complex floating-point operands, the following special cases apply to real and imaginary components independently (e.g., if ``real(x_i)`` is ``NaN``, the rounded real component is ``NaN``). - If ``x_i`` is already integer-valued, the result is ``x_i``. @@ -6284,7 +6284,7 @@ class round[TArray: Array](Protocol): - If two integers are equally close to ``x_i``, the result is the even integer closest to ``x_i``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -6300,22 +6300,22 @@ class sign[TArray: Array](Protocol): The sign function (also known as the **signum function**) of a number :math:`x_i` is defined as .. math:: - \\operatorname{sign}(x_i) = \\begin{cases} - 0 & \\textrm{if } x_i = 0 \\\\ - \\frac{x_i}{|x_i|} & \\textrm{otherwise} - \\end{cases} + \\operatorname{sign}(x_i) = \\begin{cases} + 0 & \\textrm{if } x_i = 0 \\\\ + \\frac{x_i}{|x_i|} & \\textrm{otherwise} + \\end{cases} where :math:`|x_i|` is the absolute value of :math:`x_i`. Parameters ---------- x: array - input array. Should have a numeric data type. + input array. Should have a numeric data type. Returns ------- out: array - an array containing the evaluated result for each element in ``x``. The returned array must have the same data type as ``x``. + an array containing the evaluated result for each element in ``x``. The returned array must have the same data type as ``x``. Notes ----- @@ -6335,7 +6335,7 @@ class sign[TArray: Array](Protocol): - In the remaining cases, special cases must be handled according to the rules of complex number division (see :func:`~array_api.divide`). .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -6353,12 +6353,12 @@ class signbit[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a real-valued floating-point data type. + input array. Should have a real-valued floating-point data type. Returns ------- out: array - an array containing the evaluated result for each element in ``x``. The returned array must have a data type of ``bool``. + an array containing the evaluated result for each element in ``x``. The returned array must have a data type of ``bool``. Notes ----- @@ -6391,25 +6391,25 @@ class sin[TArray: Array](Protocol): Each element ``x_i`` is assumed to be expressed in radians. .. note:: - The sine is an entire function on the complex plane and has no branch cuts. + The sine is an entire function on the complex plane and has no branch cuts. .. note:: - For complex arguments, the mathematical definition of sine is + For complex arguments, the mathematical definition of sine is - .. math:: - \\begin{align} \\operatorname{sin}(x) &= \\frac{e^{jx} - e^{-jx}}{2j} \\\\ &= \\frac{\\operatorname{sinh}(jx)}{j} \\\\ &= \\frac{\\operatorname{sinh}(jx)}{j} \\cdot \\frac{j}{j} \\\\ &= -j \\cdot \\operatorname{sinh}(jx) \\end{align} + .. math:: + \\begin{align} \\operatorname{sin}(x) &= \\frac{e^{jx} - e^{-jx}}{2j} \\\\ &= \\frac{\\operatorname{sinh}(jx)}{j} \\\\ &= \\frac{\\operatorname{sinh}(jx)}{j} \\cdot \\frac{j}{j} \\\\ &= -j \\cdot \\operatorname{sinh}(jx) \\end{align} - where :math:`\\operatorname{sinh}` is the hyperbolic sine. + where :math:`\\operatorname{sinh}` is the hyperbolic sine. Parameters ---------- x: array - input array whose elements are each expressed in radians. Should have a floating-point data type. + input array whose elements are each expressed in radians. Should have a floating-point data type. Returns ------- out: array - an array containing the sine of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the sine of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -6425,7 +6425,7 @@ class sin[TArray: Array](Protocol): For complex floating-point operands, special cases must be handled as if the operation is implemented as ``-1j * sinh(x*1j)``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -6441,27 +6441,27 @@ class sinh[TArray: Array](Protocol): The mathematical definition of the hyperbolic sine is .. math:: - \\operatorname{sinh}(x) = \\frac{e^x - e^{-x}}{2} + \\operatorname{sinh}(x) = \\frac{e^x - e^{-x}}{2} .. note:: - The hyperbolic sine is an entire function in the complex plane and has no branch cuts. The function is periodic, with period :math:`2\\pi j`, with respect to the imaginary component. + The hyperbolic sine is an entire function in the complex plane and has no branch cuts. The function is periodic, with period :math:`2\\pi j`, with respect to the imaginary component. Parameters ---------- x: array - input array whose elements each represent a hyperbolic angle. Should have a floating-point data type. + input array whose elements each represent a hyperbolic angle. Should have a floating-point data type. Returns ------- out: array - an array containing the hyperbolic sine of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the hyperbolic sine of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- **Special cases** .. note:: - For all operands, ``sinh(x)`` must equal ``-sinh(-x)``. + For all operands, ``sinh(x)`` must equal ``-sinh(-x)``. For real-valued floating-point operands, @@ -6474,7 +6474,7 @@ class sinh[TArray: Array](Protocol): For complex floating-point operands, let ``a = real(x_i)``, ``b = imag(x_i)``, and .. note:: - For complex floating-point operands, ``sinh(conj(x))`` must equal ``conj(sinh(x))``. + For complex floating-point operands, ``sinh(conj(x))`` must equal ``conj(sinh(x))``. - If ``a`` is ``+0`` and ``b`` is ``+0``, the result is ``+0 + 0j``. - If ``a`` is ``+0`` and ``b`` is ``+infinity``, the result is ``0 + NaN j`` (sign of the real component is unspecified). @@ -6492,7 +6492,7 @@ class sinh[TArray: Array](Protocol): where ``cis(v)`` is ``cos(v) + sin(v)*1j``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -6508,17 +6508,17 @@ class square[TArray: Array](Protocol): The square of a number ``x_i`` is defined as .. math:: - x_i^2 = x_i \\cdot x_i + x_i^2 = x_i \\cdot x_i Parameters ---------- x: array - input array. Should have a numeric data type. + input array. Should have a numeric data type. Returns ------- out: array - an array containing the evaluated result for each element in ``x``. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the evaluated result for each element in ``x``. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- @@ -6527,7 +6527,7 @@ class square[TArray: Array](Protocol): For floating-point operands, special cases must be handled as if the operation is implemented as ``x * x`` (see :func:`~array_api.multiply`). .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -6541,29 +6541,29 @@ class sqrt[TArray: Array](Protocol): Calculates the principal square root for each element ``x_i`` of the input array ``x``. .. note:: - After rounding, each result must be indistinguishable from the infinitely precise result (as required by IEEE 754). + After rounding, each result must be indistinguishable from the infinitely precise result (as required by IEEE 754). .. note:: - For complex floating-point operands, ``sqrt(conj(x))`` must equal ``conj(sqrt(x))``. + For complex floating-point operands, ``sqrt(conj(x))`` must equal ``conj(sqrt(x))``. .. note:: - By convention, the branch cut of the square root is the negative real axis :math:`(-\\infty, 0)`. + By convention, the branch cut of the square root is the negative real axis :math:`(-\\infty, 0)`. - The square root is a continuous function from above the branch cut, taking into account the sign of the imaginary component. + The square root is a continuous function from above the branch cut, taking into account the sign of the imaginary component. - Accordingly, for complex arguments, the function returns the square root in the range of the right half-plane, including the imaginary axis (i.e., the plane defined by :math:`[0, +\\infty)` along the real axis and :math:`(-\\infty, +\\infty)` along the imaginary axis). + Accordingly, for complex arguments, the function returns the square root in the range of the right half-plane, including the imaginary axis (i.e., the plane defined by :math:`[0, +\\infty)` along the real axis and :math:`(-\\infty, +\\infty)` along the imaginary axis). - *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). + *Note: branch cuts follow C99 and have provisional status* (see :ref:`branch-cuts`). Parameters ---------- x: array - input array. Should have a floating-point data type. + input array. Should have a floating-point data type. Returns ------- out: array - an array containing the square root of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the square root of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -6590,7 +6590,7 @@ class sqrt[TArray: Array](Protocol): - If ``a`` is ``NaN`` and ``b`` is ``NaN``, the result is ``NaN + NaN j``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -6606,14 +6606,14 @@ class subtract[TArray: Array](Protocol): Parameters ---------- x1: Union[array, int, float, complex] - first input array. Should have a numeric data type. + first input array. Should have a numeric data type. x2: Union[array, int, float, complex] - second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a numeric data type. + second input array. Must be compatible with ``x1`` (see :ref:`broadcasting`). Should have a numeric data type. Returns ------- out: array - an array containing the element-wise differences. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the element-wise differences. The returned array must have a data type determined by :ref:`type-promotion`. Notes ----- @@ -6621,10 +6621,10 @@ class subtract[TArray: Array](Protocol): - The result of ``x1_i - x2_i`` must be the same as ``x1_i + (-x2_i)`` and must be governed by the same floating-point rules as addition (see :meth:`add`). .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. .. versionchanged:: 2024.12 - Added scalar argument support. + Added scalar argument support. """ @@ -6640,25 +6640,25 @@ class tan[TArray: Array](Protocol): Each element ``x_i`` is assumed to be expressed in radians. .. note:: - Tangent is an analytical function on the complex plane and has no branch cuts. The function is periodic, with period :math:`\\pi j`, with respect to the real component and has first order poles along the real line at coordinates :math:`(\\pi (\\frac{1}{2} + n), 0)`. However, IEEE 754 binary floating-point representation cannot represent the value :math:`\\pi / 2` exactly, and, thus, no argument value is possible for which a pole error occurs. + Tangent is an analytical function on the complex plane and has no branch cuts. The function is periodic, with period :math:`\\pi j`, with respect to the real component and has first order poles along the real line at coordinates :math:`(\\pi (\\frac{1}{2} + n), 0)`. However, IEEE 754 binary floating-point representation cannot represent the value :math:`\\pi / 2` exactly, and, thus, no argument value is possible for which a pole error occurs. .. note:: - For complex arguments, the mathematical definition of tangent is + For complex arguments, the mathematical definition of tangent is - .. math:: - \\begin{align} \\operatorname{tan}(x) &= \\frac{j(e^{-jx} - e^{jx})}{e^{-jx} + e^{jx}} \\\\ &= (-1) \\frac{j(e^{jx} - e^{-jx})}{e^{jx} + e^{-jx}} \\\\ &= -j \\cdot \\operatorname{tanh}(jx) \\end{align} + .. math:: + \\begin{align} \\operatorname{tan}(x) &= \\frac{j(e^{-jx} - e^{jx})}{e^{-jx} + e^{jx}} \\\\ &= (-1) \\frac{j(e^{jx} - e^{-jx})}{e^{jx} + e^{-jx}} \\\\ &= -j \\cdot \\operatorname{tanh}(jx) \\end{align} - where :math:`\\operatorname{tanh}` is the hyperbolic tangent. + where :math:`\\operatorname{tanh}` is the hyperbolic tangent. Parameters ---------- x: array - input array whose elements are expressed in radians. Should have a floating-point data type. + input array whose elements are expressed in radians. Should have a floating-point data type. Returns ------- out: array - an array containing the tangent of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the tangent of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- @@ -6674,7 +6674,7 @@ class tan[TArray: Array](Protocol): For complex floating-point operands, special cases must be handled as if the operation is implemented as ``-1j * tanh(x*1j)``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -6690,29 +6690,29 @@ class tanh[TArray: Array](Protocol): The mathematical definition of the hyperbolic tangent is .. math:: - \\begin{align} \\operatorname{tanh}(x) &= \\frac{\\operatorname{sinh}(x)}{\\operatorname{cosh}(x)} \\\\ &= \\frac{e^x - e^{-x}}{e^x + e^{-x}} \\end{align} + \\begin{align} \\operatorname{tanh}(x) &= \\frac{\\operatorname{sinh}(x)}{\\operatorname{cosh}(x)} \\\\ &= \\frac{e^x - e^{-x}}{e^x + e^{-x}} \\end{align} where :math:`\\operatorname{sinh}(x)` is the hyperbolic sine and :math:`\\operatorname{cosh}(x)` is the hyperbolic cosine. .. note:: - The hyperbolic tangent is an analytical function on the complex plane and has no branch cuts. The function is periodic, with period :math:`\\pi j`, with respect to the imaginary component and has first order poles along the imaginary line at coordinates :math:`(0, \\pi (\\frac{1}{2} + n))`. However, IEEE 754 binary floating-point representation cannot represent :math:`\\pi / 2` exactly, and, thus, no argument value is possible such that a pole error occurs. + The hyperbolic tangent is an analytical function on the complex plane and has no branch cuts. The function is periodic, with period :math:`\\pi j`, with respect to the imaginary component and has first order poles along the imaginary line at coordinates :math:`(0, \\pi (\\frac{1}{2} + n))`. However, IEEE 754 binary floating-point representation cannot represent :math:`\\pi / 2` exactly, and, thus, no argument value is possible such that a pole error occurs. Parameters ---------- x: array - input array whose elements each represent a hyperbolic angle. Should have a floating-point data type. + input array whose elements each represent a hyperbolic angle. Should have a floating-point data type. Returns ------- out: array - an array containing the hyperbolic tangent of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. + an array containing the hyperbolic tangent of each element in ``x``. The returned array must have a floating-point data type determined by :ref:`type-promotion`. Notes ----- **Special cases** .. note:: - For all operands, ``tanh(-x)`` must equal ``-tanh(x)``. + For all operands, ``tanh(-x)`` must equal ``-tanh(x)``. For real-valued floating-point operands, @@ -6725,7 +6725,7 @@ class tanh[TArray: Array](Protocol): For complex floating-point operands, let ``a = real(x_i)``, ``b = imag(x_i)``, and .. note:: - For complex floating-point operands, ``tanh(conj(x))`` must equal ``conj(tanh(x))``. + For complex floating-point operands, ``tanh(conj(x))`` must equal ``conj(tanh(x))``. - If ``a`` is ``+0`` and ``b`` is ``+0``, the result is ``+0 + 0j``. - If ``a`` is a nonzero finite number and ``b`` is ``+infinity``, the result is ``NaN + NaN j``. @@ -6740,12 +6740,12 @@ class tanh[TArray: Array](Protocol): - If ``a`` is ``NaN`` and ``b`` is ``NaN``, the result is ``NaN + NaN j``. .. warning:: - For historical reasons stemming from the C standard, array libraries may not return the expected result when ``a`` is ``+0`` and ``b`` is either ``+infinity`` or ``NaN``. The result should be ``+0 + NaN j`` in both cases; however, for libraries compiled against older C versions, the result may be ``NaN + NaN j``. + For historical reasons stemming from the C standard, array libraries may not return the expected result when ``a`` is ``+0`` and ``b`` is either ``+infinity`` or ``NaN``. The result should be ``+0 + NaN j`` in both cases; however, for libraries compiled against older C versions, the result may be ``NaN + NaN j``. - Array libraries are not required to patch these older C versions, and, thus, users are advised that results may vary across array library implementations for these special cases. + Array libraries are not required to patch these older C versions, and, thus, users are advised that results may vary across array library implementations for these special cases. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -6761,12 +6761,12 @@ class trunc[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a real-valued data type. + input array. Should have a real-valued data type. Returns ------- out: array - an array containing the rounded result for each element in ``x``. The returned array must have the same data type as ``x``. + an array containing the rounded result for each element in ``x``. The returned array must have the same data type as ``x``. Notes ----- @@ -6798,16 +6798,16 @@ class argmax[TArray: Array](Protocol): Parameters ---------- x: array - input array. **Should** have a real-valued data type. + input array. **Should** have a real-valued data type. axis: Optional[int] - axis along which to search. If ``None``, the function **must** return the index of the maximum value of the flattened array. If not ``None``, a valid axis **must** be an integer on the interval ``[-N, N)``, where ``N`` is the number of axes in ``x``. If an axis is specified as a negative integer, the function **must** determine the axis along which to perform the operation by counting backward from the last axis (where ``-1`` refers to the last axis). If provided an invalid axis, the function **must** raise an exception. Default: ``None``. + axis along which to search. If ``None``, the function **must** return the index of the maximum value of the flattened array. If not ``None``, a valid axis **must** be an integer on the interval ``[-N, N)``, where ``N`` is the number of axes in ``x``. If an axis is specified as a negative integer, the function **must** determine the axis along which to perform the operation by counting backward from the last axis (where ``-1`` refers to the last axis). If provided an invalid axis, the function **must** raise an exception. Default: ``None``. keepdims: bool - if ``True``, the reduced axes **must** be included in the result as singleton dimensions, and, accordingly, the result **must** be broadcast-compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes **must not** be included in the result. Default: ``False``. + if ``True``, the reduced axes **must** be included in the result as singleton dimensions, and, accordingly, the result **must** be broadcast-compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes **must not** be included in the result. Default: ``False``. Returns ------- out: array - if ``axis`` is ``None``, a zero-dimensional array containing the index of the first occurrence of the maximum value; otherwise, a non-zero-dimensional array containing the indices of the maximum values. The returned array **must** have be the default array index data type. + if ``axis`` is ``None``, a zero-dimensional array containing the index of the first occurrence of the maximum value; otherwise, a non-zero-dimensional array containing the indices of the maximum values. The returned array **must** have be the default array index data type. Notes ----- @@ -6829,16 +6829,16 @@ class argmin[TArray: Array](Protocol): Parameters ---------- x: array - input array. **Should** have a real-valued data type. + input array. **Should** have a real-valued data type. axis: Optional[int] - axis along which to search. If ``None``, the function **must** return the index of the minimum value of the flattened array. If not ``None``, a valid axis **must** be an integer on the interval ``[-N, N)``, where ``N`` is the number of axes in ``x``. If an axis is specified as a negative integer, the function **must** determine the axis along which to perform the operation by counting backward from the last axis (where ``-1`` refers to the last axis). If provided an invalid axis, the function **must** raise an exception. Default: ``None``. + axis along which to search. If ``None``, the function **must** return the index of the minimum value of the flattened array. If not ``None``, a valid axis **must** be an integer on the interval ``[-N, N)``, where ``N`` is the number of axes in ``x``. If an axis is specified as a negative integer, the function **must** determine the axis along which to perform the operation by counting backward from the last axis (where ``-1`` refers to the last axis). If provided an invalid axis, the function **must** raise an exception. Default: ``None``. keepdims: bool - if ``True``, the reduced axes **must** be included in the result as singleton dimensions, and, accordingly, the result **must** be broadcast-compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes **must not** be included in the result. Default: ``False``. + if ``True``, the reduced axes **must** be included in the result as singleton dimensions, and, accordingly, the result **must** be broadcast-compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes **must not** be included in the result. Default: ``False``. Returns ------- out: array - if ``axis`` is ``None``, a zero-dimensional array containing the index of the first occurrence of the minimum value; otherwise, a non-zero-dimensional array containing the indices of the minimum values. The returned array **must** have the default array index data type. + if ``axis`` is ``None``, a zero-dimensional array containing the index of the first occurrence of the minimum value; otherwise, a non-zero-dimensional array containing the indices of the minimum values. The returned array **must** have the default array index data type. Notes ----- @@ -6858,16 +6858,16 @@ class count_nonzero[TArray: Array](Protocol): Parameters ---------- x: array - input array. + input array. axis: Optional[Union[int, Tuple[int, ...]]] - axis or axes along which to count non-zero values. By default, the number of non-zero values must be computed over the entire array. If a tuple of integers, the number of non-zero values must be computed over multiple axes. A valid axis **must** be an integer on the interval ``[-N, N)``, where ``N`` is the number of axes in ``x``. If an axis is specified as a negative integer, the function **must** determine the axis along which to perform the operation by counting backward from the last axis (where ``-1`` refers to the last axis). If provided an invalid axis, the function **must** raise an exception. Default: ``None``. + axis or axes along which to count non-zero values. By default, the number of non-zero values must be computed over the entire array. If a tuple of integers, the number of non-zero values must be computed over multiple axes. A valid axis **must** be an integer on the interval ``[-N, N)``, where ``N`` is the number of axes in ``x``. If an axis is specified as a negative integer, the function **must** determine the axis along which to perform the operation by counting backward from the last axis (where ``-1`` refers to the last axis). If provided an invalid axis, the function **must** raise an exception. Default: ``None``. keepdims: bool - if ``True``, the reduced axes **must** be included in the result as singleton dimensions, and, accordingly, the result **must** be broadcast-compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes **must not** be included in the result. Default: ``False``. + if ``True``, the reduced axes **must** be included in the result as singleton dimensions, and, accordingly, the result **must** be broadcast-compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes **must not** be included in the result. Default: ``False``. Returns ------- out: array - if the number of non-zeros values was computed over the entire array, a zero-dimensional array containing the total number of non-zero values; otherwise, a non-zero-dimensional array containing the counts along the specified axes. The returned array **must** have the default array index data type. + if the number of non-zeros values was computed over the entire array, a zero-dimensional array containing the total number of non-zero values; otherwise, a non-zero-dimensional array containing the counts along the specified axes. The returned array **must** have the default array index data type. Notes ----- @@ -6888,19 +6888,19 @@ class nonzero[TArray: Array](Protocol): Returns the indices of the array elements which are non-zero. .. admonition:: Data-dependent output shape - :class: admonition important + :class: admonition important - The shape of the output array for this function depends on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) may find this function difficult to implement without knowing array values. Accordingly, such libraries may choose to omit this function. See :ref:`data-dependent-output-shapes` section for more details. + The shape of the output array for this function depends on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) may find this function difficult to implement without knowing array values. Accordingly, such libraries may choose to omit this function. See :ref:`data-dependent-output-shapes` section for more details. Parameters ---------- x: array - input array. **Must** have one or more dimensions. If ``x`` is zero-dimensional, the function **must** raise an exception. + input array. **Must** have one or more dimensions. If ``x`` is zero-dimensional, the function **must** raise an exception. Returns ------- out: Tuple[array, ...] - a tuple of ``k`` arrays, one for each dimension of ``x`` and each of size ``n`` (where ``n`` is the total number of non-zero elements), containing the indices of the non-zero elements in that dimension. The indices **must** be returned in row-major, C-style order. The returned array **must** have the default array index data type. + a tuple of ``k`` arrays, one for each dimension of ``x`` and each of size ``n`` (where ``n`` is the total number of non-zero elements), containing the indices of the non-zero elements in that dimension. The indices **must** be returned in row-major, C-style order. The returned array **must** have the default array index data type. Notes ----- @@ -6908,7 +6908,7 @@ class nonzero[TArray: Array](Protocol): - If ``x`` has a boolean data type, non-zero elements are those elements which are equal to ``True``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -6924,29 +6924,29 @@ class searchsorted[TArray: Array](Protocol): Parameters ---------- x1: array - input array. **Must** be a one-dimensional array. **Should** have a real-valued data type. If ``sorter`` is ``None``, **must** be sorted in ascending order; otherwise, ``sorter`` **must** be an array of indices that sort ``x1`` in ascending order. + input array. **Must** be a one-dimensional array. **Should** have a real-valued data type. If ``sorter`` is ``None``, **must** be sorted in ascending order; otherwise, ``sorter`` **must** be an array of indices that sort ``x1`` in ascending order. x2: array - array containing search values. **Should** have a real-valued data type. + array containing search values. **Should** have a real-valued data type. side: Literal['left', 'right'] - argument controlling which index is returned if a value lands exactly on an edge. + argument controlling which index is returned if a value lands exactly on an edge. - Let ``v`` be an element of ``x2`` given by ``v = x2[j]``, where ``j`` refers to a valid index (see :ref:`indexing`). + Let ``v`` be an element of ``x2`` given by ``v = x2[j]``, where ``j`` refers to a valid index (see :ref:`indexing`). - - If ``v`` is less than all elements in ``x1``, then ``out[j]`` **must** be ``0``. - - If ``v`` is greater than all elements in ``x1``, then ``out[j]`` **must** be ``M``, where ``M`` is the number of elements in ``x1``. - - Otherwise, each returned index ``i = out[j]`` **must** satisfy an index condition: + - If ``v`` is less than all elements in ``x1``, then ``out[j]`` **must** be ``0``. + - If ``v`` is greater than all elements in ``x1``, then ``out[j]`` **must** be ``M``, where ``M`` is the number of elements in ``x1``. + - Otherwise, each returned index ``i = out[j]`` **must** satisfy an index condition: - - If ``side == 'left'``, then ``x1[i-1] < v <= x1[i]``. - - If ``side == 'right'``, then ``x1[i-1] <= v < x1[i]``. + - If ``side == 'left'``, then ``x1[i-1] < v <= x1[i]``. + - If ``side == 'right'``, then ``x1[i-1] <= v < x1[i]``. - Default: ``'left'``. + Default: ``'left'``. sorter: Optional[array] - array of indices that sort ``x1`` in ascending order. The array **must** have the same shape as ``x1`` and have an integer data type. Default: ``None``. + array of indices that sort ``x1`` in ascending order. The array **must** have the same shape as ``x1`` and have an integer data type. Default: ``None``. Returns ------- out: array - an array of indices with the same shape as ``x2``. The returned array **must** have the default array index data type. + an array of indices with the same shape as ``x2``. The returned array **must** have the default array index data type. Notes ----- @@ -6956,7 +6956,7 @@ class searchsorted[TArray: Array](Protocol): .. versionadded:: 2023.12 .. versionchanged:: 2024.12 - Fixed incorrect boundary conditions. + Fixed incorrect boundary conditions. """ @@ -6972,16 +6972,16 @@ class where[TArray: Array](Protocol): Parameters ---------- condition: array - when ``True``, yield ``x1_i``; otherwise, yield ``x2_i``. **Should** have a boolean data type. **Must** be broadcast-compatible with ``x1`` and ``x2`` (see :ref:`broadcasting`). + when ``True``, yield ``x1_i``; otherwise, yield ``x2_i``. **Should** have a boolean data type. **Must** be broadcast-compatible with ``x1`` and ``x2`` (see :ref:`broadcasting`). x1: Union[array, int, float, complex, bool] - first input array. **Must** be broadcast-compatible with ``condition`` and ``x2`` (see :ref:`broadcasting`). + first input array. **Must** be broadcast-compatible with ``condition`` and ``x2`` (see :ref:`broadcasting`). x2: Union[array, int, float, complex, bool] - second input array. **Must** be broadcast-compatible with ``condition`` and ``x1`` (see :ref:`broadcasting`). + second input array. **Must** be broadcast-compatible with ``condition`` and ``x1`` (see :ref:`broadcasting`). Returns ------- out: array - an array with elements from ``x1`` where ``condition`` is ``True``, and elements from ``x2`` elsewhere. The returned array **must** have a data type determined by :ref:`type-promotion` rules with the arrays ``x1`` and ``x2``. + an array with elements from ``x1`` where ``condition`` is ``True``, and elements from ``x2`` elsewhere. The returned array **must** have a data type determined by :ref:`type-promotion` rules with the arrays ``x1`` and ``x2``. Notes ----- @@ -6989,10 +6989,10 @@ class where[TArray: Array](Protocol): - If either ``x1`` or ``x2`` is a scalar value, the returned array **must** have a data type determined according to :ref:`mixing-scalars-and-arrays`. .. versionchanged:: 2024.12 - Added scalar argument support. + Added scalar argument support. .. versionchanged:: 2024.12 - Clarified that the ``condition`` argument should have a boolean data type. + Clarified that the ``condition`` argument should have a boolean data type. """ @@ -7008,16 +7008,16 @@ class all[TArray: Array](Protocol): Parameters ---------- x: array - input array. + input array. axis: Optional[Union[int, Tuple[int, ...]]] - axis or axes along which to perform a logical AND reduction. By default, a logical AND reduction **must** be performed over the entire array. If a tuple of integers, logical AND reductions **must** be performed over multiple axes. A valid ``axis`` **must** be an integer on the interval ``[-N, N)``, where ``N`` is the number of axes in ``x``. If an ``axis`` is specified as a negative integer, the function **must** determine the axis along which to perform a reduction by counting backward from the last axis (where ``-1`` refers to the last axis). If provided an invalid ``axis``, the function **must** raise an exception. Default: ``None``. + axis or axes along which to perform a logical AND reduction. By default, a logical AND reduction **must** be performed over the entire array. If a tuple of integers, logical AND reductions **must** be performed over multiple axes. A valid ``axis`` **must** be an integer on the interval ``[-N, N)``, where ``N`` is the number of axes in ``x``. If an ``axis`` is specified as a negative integer, the function **must** determine the axis along which to perform a reduction by counting backward from the last axis (where ``-1`` refers to the last axis). If provided an invalid ``axis``, the function **must** raise an exception. Default: ``None``. keepdims: bool - If ``True``, the reduced axes **must** be included in the result as singleton dimensions, and, accordingly, the result **must** be broadcast-compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes **must not** be included in the result. Default: ``False``. + If ``True``, the reduced axes **must** be included in the result as singleton dimensions, and, accordingly, the result **must** be broadcast-compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes **must not** be included in the result. Default: ``False``. Returns ------- out: array - if a logical AND reduction was performed over the entire array, the returned array **must** be a zero-dimensional array containing the test result. Otherwise, the returned array **must** be a non-zero-dimensional array containing the test results. The returned array **must** have a data type of ``bool``. + if a logical AND reduction was performed over the entire array, the returned array **must** be a zero-dimensional array containing the test result. Otherwise, the returned array **must** be a non-zero-dimensional array containing the test results. The returned array **must** have a data type of ``bool``. Notes ----- @@ -7026,7 +7026,7 @@ class all[TArray: Array](Protocol): - If ``x`` is an empty array or the size of the axis along which to evaluate elements is zero, the test result **must** be ``True``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -7042,16 +7042,16 @@ class any[TArray: Array](Protocol): Parameters ---------- x: array - input array. + input array. axis: Optional[Union[int, Tuple[int, ...]]] - axis or axes along which to perform a logical OR reduction. By default, a logical OR reduction **must** be performed over the entire array. If a tuple of integers, logical OR reductions **must** be performed over multiple axes. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the number of axes in ``x``. If an ``axis`` is specified as a negative integer, the function **must** determine the axis along which to perform a reduction by counting backward from the last dimension (where ``-1`` refers to the last axis). If provided an invalid ``axis``, the function **must** raise an exception. Default: ``None``. + axis or axes along which to perform a logical OR reduction. By default, a logical OR reduction **must** be performed over the entire array. If a tuple of integers, logical OR reductions **must** be performed over multiple axes. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the number of axes in ``x``. If an ``axis`` is specified as a negative integer, the function **must** determine the axis along which to perform a reduction by counting backward from the last dimension (where ``-1`` refers to the last axis). If provided an invalid ``axis``, the function **must** raise an exception. Default: ``None``. keepdims: bool - If ``True``, the reduced axes **must** be included in the result as singleton dimensions, and, accordingly, the result **must** be broadcast-compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes **must not** be included in the result. Default: ``False``. + If ``True``, the reduced axes **must** be included in the result as singleton dimensions, and, accordingly, the result **must** be broadcast-compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes **must not** be included in the result. Default: ``False``. Returns ------- out: array - if a logical OR reduction was performed over the entire array, the returned array **must** be a zero-dimensional array containing the test result. Otherwise, the returned array **must** be a non-zero-dimensional array containing the test results. The returned array **must** have a data type of ``bool``. + if a logical OR reduction was performed over the entire array, the returned array **must** be a zero-dimensional array containing the test result. Otherwise, the returned array **must** be a non-zero-dimensional array containing the test results. The returned array **must** have a data type of ``bool``. Notes ----- @@ -7060,7 +7060,7 @@ class any[TArray: Array](Protocol): - If ``x`` is an empty array or the size of the axis along which to evaluate elements is zero, the test result **must** be ``False``. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. """ @@ -7076,25 +7076,25 @@ class diff[TArray: Array](Protocol): Parameters ---------- x: array - input array. **Should** have a numeric data type. + input array. **Should** have a numeric data type. axis: int - axis along which to compute differences. A valid ``axis`` **must** be an integer on the interval ``[-N, N)``, where ``N`` is the number of axes in ``x``. If an ``axis`` is specified as a negative integer, the function **must** determine the axis along which to compute differences by counting backward from the last axis (where ``-1`` refers to the last axis). If provided an invalid ``axis``, the function **must** raise an exception. Default: ``-1``. + axis along which to compute differences. A valid ``axis`` **must** be an integer on the interval ``[-N, N)``, where ``N`` is the number of axes in ``x``. If an ``axis`` is specified as a negative integer, the function **must** determine the axis along which to compute differences by counting backward from the last axis (where ``-1`` refers to the last axis). If provided an invalid ``axis``, the function **must** raise an exception. Default: ``-1``. n: int - number of times to recursively compute differences. Default: ``1``. + number of times to recursively compute differences. Default: ``1``. prepend: Optional[array] - values to prepend to a specified axis prior to computing differences. **Must** have the same shape as ``x``, except for the axis specified by ``axis`` which can have any size. **Should** have the same data type as ``x``. Default: ``None``. + values to prepend to a specified axis prior to computing differences. **Must** have the same shape as ``x``, except for the axis specified by ``axis`` which can have any size. **Should** have the same data type as ``x``. Default: ``None``. append: Optional[array] - values to append to a specified axis prior to computing differences. **Must** have the same shape as ``x``, except for the axis specified by ``axis`` which can have any size. **Should** have the same data type as ``x``. Default: ``None``. + values to append to a specified axis prior to computing differences. **Must** have the same shape as ``x``, except for the axis specified by ``axis`` which can have any size. **Should** have the same data type as ``x``. Default: ``None``. Returns ------- out: array - an array containing the n-th differences. **Should** have the same data type as ``x``. **Must** have the same shape as ``x``, except for the axis specified by ``axis`` which **must** have a size determined as follows: + an array containing the n-th differences. **Should** have the same data type as ``x``. **Must** have the same shape as ``x``, except for the axis specified by ``axis`` which **must** have a size determined as follows: - - Let ``M`` be the number of elements along an axis specified by ``axis``. - - Let ``N1`` be the number of prepended values along an axis specified by ``axis``. - - Let ``N2`` be the number of appended values along an axis specified by ``axis``. - - The final size of the axis specified by ``axis`` **must** be ``M + N1 + N2 - n``. + - Let ``M`` be the number of elements along an axis specified by ``axis``. + - Let ``N1`` be the number of prepended values along an axis specified by ``axis``. + - Let ``N2`` be the number of appended values along an axis specified by ``axis``. + - The final size of the axis specified by ``axis`` **must** be ``M + N1 + N2 - n``. Notes ----- @@ -7110,36 +7110,36 @@ def __call__(self, x: TArray, /, *, axis: int = -1, n: int = 1, prepend: TArray @runtime_checkable -class __array_namespace_info__[TCapabilities, TDatatypes, TDefaultdatatypes, TArray: Array, TDevice, TDtype](Protocol): +class __array_namespace_info__[TArray: Array, TCapabilities, TDatatypes, TDefaultdatatypes, TDevice, TDtype](Protocol): """ Returns a namespace with Array API namespace inspection utilities. - See :ref:`inspection` for a list of inspection APIs. - Returns ------- out: Info - An object containing Array API namespace inspection utilities. + an object containing Array API namespace inspection utilities. Notes ----- - The returned object may be either a namespace or a class, so long as an Array API user can access inspection utilities as follows: + - See :ref:`inspection` for a list of inspection APIs. + + - The returned object **may** be either a namespace or a class, as long as an Array API user can access inspection utilities as follows: :: - info = xp.__array_namespace_info__() - info.capabilities() - info.devices() - info.dtypes() - info.default_dtypes() - # ... + info = xp.__array_namespace_info__() + info.capabilities() + info.devices() + info.dtypes() + info.default_dtypes() + # ... .. versionadded: 2023.12 """ @abstractmethod - def __call__(self, /) -> Info[TCapabilities, TDatatypes, TDefaultdatatypes, TArray, TDevice, TDtype]: ... + def __call__(self, /) -> Info[TArray, TCapabilities, TDatatypes, TDefaultdatatypes, TDevice, TDtype]: ... @runtime_checkable @@ -7150,35 +7150,35 @@ class take[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have one or more dimensions (axes). + input array. **Should** have one or more axes. indices: array - array indices. The array must be one-dimensional and have an integer data type. If an index is negative, the function must determine the element to select along a specified axis (dimension) by counting from the last element (where ``-1`` refers to the last element). + array indices. The array **must** be one-dimensional and have an integer data type. If an index is negative, the function **must** determine the element to select along a specified axis by counting from the last element (where ``-1`` refers to the last element). axis: Optional[int] - axis over which to select values. If ``axis`` is negative, the function must determine the axis along which to select values by counting from the last dimension (where ``-1`` refers to the last dimension). + axis over which to select values. If ``axis`` is negative, the function **must** determine the axis along which to select values by counting from the last axis (where ``-1`` refers to the last axis). - If ``x`` is a one-dimensional array, providing an ``axis`` is optional; however, if ``x`` has more than one dimension, providing an ``axis`` is required. + If ``x`` is a one-dimensional array, providing an ``axis`` **must** be optional; however, if ``x`` has more than one axis, providing an ``axis`` **must** be required. Returns ------- out: array - an array having the same data type as ``x``. The output array must have the same rank (i.e., number of dimensions) as ``x`` and must have the same shape as ``x``, except for the axis specified by ``axis`` whose size must equal the number of elements in ``indices``. + an array having the same data type as ``x``. The output array **must** have the same number of axes as ``x`` and **must** have the same shape as ``x``, except for the axis specified by ``axis`` whose size **must** equal the number of elements in ``indices``. Notes ----- - - Conceptually, ``take(x, indices, axis=3)`` is equivalent to ``x[:,:,:,indices,...]``; however, explicit indexing via arrays of indices is not currently supported in this specification due to concerns regarding ``__setitem__`` and array mutation semantics. - - This specification does not require bounds checking. The behavior for out-of-bounds indices is left unspecified. + - This specification does not require bounds checking. The behavior for out-of-bounds indices is unspecified and thus implementation-defined. + - When ``x`` is a zero-dimensional array, behavior is unspecified and thus implementation-defined. .. versionadded:: 2022.12 .. versionchanged:: 2023.12 - Out-of-bounds behavior is explicitly left unspecified. + Out-of-bounds behavior is explicitly left unspecified. .. versionchanged:: 2024.12 - Behavior when provided a zero-dimensional input array is explicitly left unspecified. + Behavior when provided a zero-dimensional input array is explicitly left unspecified. .. versionchanged:: 2024.12 - Clarified support for negative indices. + Clarified support for negative indices. """ @@ -7194,20 +7194,20 @@ class take_along_axis[TArray: Array](Protocol): Parameters ---------- x: array - input array. Must be compatible with ``indices``, except for the axis (dimension) specified by ``axis`` (see :ref:`broadcasting`). + input array. **Must** be compatible with ``indices``, except for the axis specified by ``axis`` (see :ref:`broadcasting`). indices: array - array indices. Must have the same rank (i.e., number of dimensions) as ``x``. If an index is negative, the function must determine the element to select along a specified axis (dimension) by counting from the last element (where ``-1`` refers to the last element). + array indices. **Must** have the same number of axes as ``x`` and **must** be compatible with ``x``, except for the axis specified by ``axis`` (see :ref:`broadcasting`). If an index is negative, the function **must** determine the element to select along a specified axis by counting from the last element (where ``-1`` refers to the last element). axis: int - axis along which to select values. If ``axis`` is negative, the function must determine the axis along which to select values by counting from the last dimension (where ``-1`` refers to the last dimension). Default: ``-1``. + axis along which to select values. A valid axis **must** be an integer on the interval ``[-N, N)``, where ``N`` is the number of axes in ``x``. If an axis is specified as a negative integer, the function **must** determine the axis along which to perform the operation by counting backward from the last axis (where ``-1`` refers to the last axis). If provided an invalid axis, the function **must** raise an exception. Default: ``-1``. Returns ------- out: array - an array having the same data type as ``x``. Must have the same rank (i.e., number of dimensions) as ``x`` and must have a shape determined according to :ref:`broadcasting`, except for the axis (dimension) specified by ``axis`` whose size must equal the size of the corresponding axis (dimension) in ``indices``. + an array containing elements from ``x``. The returned array **must** have the same data type as ``x``. The returned array **must** have the same number of axes as ``x`` and **must** have a shape determined according to :ref:`broadcasting`, except for the axis specified by ``axis`` whose size **must** equal the size of the corresponding axis in ``indices``. Notes ----- - - This specification does not require bounds checking. The behavior for out-of-bounds indices is left unspecified. + - This specification does not require bounds checking. The behavior for out-of-bounds indices is unspecified and thus implementation-defined. .. versionadded:: 2024.12 @@ -7223,35 +7223,35 @@ class fft[TArray: Array](Protocol): Computes the one-dimensional discrete Fourier transform. .. note:: - Applying the one-dimensional inverse discrete Fourier transform to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e., ``ifft(fft(x)) == x``), provided that the transform and inverse transform are performed with the same arguments (number of elements, axis, and normalization mode). + Applying the one-dimensional inverse discrete Fourier transform to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e., ``ifft(fft(x)) == x``), provided that the transform and inverse transform are performed with the same arguments (number of elements, axis, and normalization mode). Parameters ---------- x: array - input array. Should have a complex floating-point data type. + input array. Should have a complex floating-point data type. n: Optional[int] - number of elements over which to compute the transform along the axis (dimension) specified by ``axis``. Let ``M`` be the size of the input array along the axis specified by ``axis``. When ``n`` is ``None``, the function must set ``n`` equal to ``M``. + number of elements over which to compute the transform along the axis (dimension) specified by ``axis``. Let ``M`` be the size of the input array along the axis specified by ``axis``. When ``n`` is ``None``, the function must set ``n`` equal to ``M``. - - If ``n`` is greater than ``M``, the axis specified by ``axis`` must be zero-padded to size ``n``. - - If ``n`` is less than ``M``, the axis specified by ``axis`` must be trimmed to size ``n``. - - If ``n`` equals ``M``, all elements along the axis specified by ``axis`` must be used when computing the transform. + - If ``n`` is greater than ``M``, the axis specified by ``axis`` must be zero-padded to size ``n``. + - If ``n`` is less than ``M``, the axis specified by ``axis`` must be trimmed to size ``n``. + - If ``n`` equals ``M``, all elements along the axis specified by ``axis`` must be used when computing the transform. - Default: ``None``. + Default: ``None``. axis: int - axis (dimension) of the input array over which to compute the transform. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). Default: ``-1``. + axis (dimension) of the input array over which to compute the transform. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). Default: ``-1``. norm: Literal['backward', 'ortho', 'forward'] - normalization mode. Should be one of the following modes: + normalization mode. Should be one of the following modes: - - ``'backward'``: no normalization. - - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). - - ``'forward'``: normalize by ``1/n``. + - ``'backward'``: no normalization. + - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). + - ``'forward'``: normalize by ``1/n``. - Default: ``'backward'``. + Default: ``'backward'``. Returns ------- out: array - an array transformed along the axis (dimension) specified by ``axis``. The returned array must have the same data type as ``x`` and must have the same shape as ``x``, except for the axis specified by ``axis`` which must have size ``n``. + an array transformed along the axis (dimension) specified by ``axis``. The returned array must have the same data type as ``x`` and must have the same shape as ``x``, except for the axis specified by ``axis`` which must have size ``n``. Notes ----- @@ -7259,7 +7259,7 @@ class fft[TArray: Array](Protocol): .. versionadded:: 2022.12 .. versionchanged:: 2023.12 - Required the input array have a complex floating-point data type and required that the output array have the same data type as the input array. + Required the input array have a complex floating-point data type and required that the output array have the same data type as the input array. """ @@ -7273,35 +7273,35 @@ class ifft[TArray: Array](Protocol): Computes the one-dimensional inverse discrete Fourier transform. .. note:: - Applying the one-dimensional inverse discrete Fourier transform to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e., ``ifft(fft(x)) == x``), provided that the transform and inverse transform are performed with the same arguments (number of elements, axis, and normalization mode). + Applying the one-dimensional inverse discrete Fourier transform to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e., ``ifft(fft(x)) == x``), provided that the transform and inverse transform are performed with the same arguments (number of elements, axis, and normalization mode). Parameters ---------- x: array - input array. Should have a complex floating-point data type. + input array. Should have a complex floating-point data type. n: Optional[int] - number of elements over which to compute the transform along the axis (dimension) specified by ``axis``. Let ``M`` be the size of the input array along the axis specified by ``axis``. When ``n`` is ``None``, the function must set ``n`` equal to ``M``. + number of elements over which to compute the transform along the axis (dimension) specified by ``axis``. Let ``M`` be the size of the input array along the axis specified by ``axis``. When ``n`` is ``None``, the function must set ``n`` equal to ``M``. - - If ``n`` is greater than ``M``, the axis specified by ``axis`` must be zero-padded to size ``n``. - - If ``n`` is less than ``M``, the axis specified by ``axis`` must be trimmed to size ``n``. - - If ``n`` equals ``M``, all elements along the axis specified by ``axis`` must be used when computing the transform. + - If ``n`` is greater than ``M``, the axis specified by ``axis`` must be zero-padded to size ``n``. + - If ``n`` is less than ``M``, the axis specified by ``axis`` must be trimmed to size ``n``. + - If ``n`` equals ``M``, all elements along the axis specified by ``axis`` must be used when computing the transform. - Default: ``None``. + Default: ``None``. axis: int - axis (dimension) of the input array over which to compute the transform. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). Default: ``-1``. + axis (dimension) of the input array over which to compute the transform. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). Default: ``-1``. norm: Literal['backward', 'ortho', 'forward'] - normalization mode. Should be one of the following modes: + normalization mode. Should be one of the following modes: - - ``'backward'``: normalize by ``1/n``. - - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). - - ``'forward'``: no normalization. + - ``'backward'``: normalize by ``1/n``. + - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). + - ``'forward'``: no normalization. - Default: ``'backward'``. + Default: ``'backward'``. Returns ------- out: array - an array transformed along the axis (dimension) specified by ``axis``. The returned array must have the same data type as ``x`` and must have the same shape as ``x``, except for the axis specified by ``axis`` which must have size ``n``. + an array transformed along the axis (dimension) specified by ``axis``. The returned array must have the same data type as ``x`` and must have the same shape as ``x``, except for the axis specified by ``axis`` which must have size ``n``. Notes ----- @@ -7309,7 +7309,7 @@ class ifft[TArray: Array](Protocol): .. versionadded:: 2022.12 .. versionchanged:: 2023.12 - Required the input array have a complex floating-point data type and required that the output array have the same data type as the input array. + Required the input array have a complex floating-point data type and required that the output array have the same data type as the input array. """ @@ -7323,41 +7323,41 @@ class fftn[TArray: Array](Protocol): Computes the n-dimensional discrete Fourier transform. .. note:: - Applying the n-dimensional inverse discrete Fourier transform to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e., ``ifftn(fftn(x)) == x``), provided that the transform and inverse transform are performed with the same arguments (sizes, axes, and normalization mode). + Applying the n-dimensional inverse discrete Fourier transform to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e., ``ifftn(fftn(x)) == x``), provided that the transform and inverse transform are performed with the same arguments (sizes, axes, and normalization mode). Parameters ---------- x: array - input array. Should have a complex floating-point data type. + input array. Should have a complex floating-point data type. s: Optional[Sequence[int]] - number of elements over which to compute the transform along the axes (dimensions) specified by ``axes``. Let ``i`` be the index of the ``n``-th axis specified by ``axes`` (i.e., ``i = axes[n]``) and ``M[i]`` be the size of the input array along axis ``i``. When ``s`` is ``None``, the function must set ``s`` equal to a sequence of integers such that ``s[i]`` equals ``M[i]`` for all ``i``. + number of elements over which to compute the transform along the axes (dimensions) specified by ``axes``. Let ``i`` be the index of the ``n``-th axis specified by ``axes`` (i.e., ``i = axes[n]``) and ``M[i]`` be the size of the input array along axis ``i``. When ``s`` is ``None``, the function must set ``s`` equal to a sequence of integers such that ``s[i]`` equals ``M[i]`` for all ``i``. - - If ``s[i]`` is greater than ``M[i]``, axis ``i`` must be zero-padded to size ``s[i]``. - - If ``s[i]`` is less than ``M[i]``, axis ``i`` must be trimmed to size ``s[i]``. - - If ``s[i]`` equals ``M[i]`` or ``-1``, all elements along axis ``i`` must be used when computing the transform. + - If ``s[i]`` is greater than ``M[i]``, axis ``i`` must be zero-padded to size ``s[i]``. + - If ``s[i]`` is less than ``M[i]``, axis ``i`` must be trimmed to size ``s[i]``. + - If ``s[i]`` equals ``M[i]`` or ``-1``, all elements along axis ``i`` must be used when computing the transform. - If ``s`` is not ``None``, ``axes`` must not be ``None``. Default: ``None``. + If ``s`` is not ``None``, ``axes`` must not be ``None``. Default: ``None``. axes: Optional[Sequence[int]] - axes (dimensions) over which to compute the transform. A valid axis in ``axes`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an axis is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). + axes (dimensions) over which to compute the transform. A valid axis in ``axes`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an axis is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). - If ``s`` is provided, the corresponding ``axes`` to be transformed must also be provided. If ``axes`` is ``None``, the function must compute the transform over all axes. Default: ``None``. + If ``s`` is provided, the corresponding ``axes`` to be transformed must also be provided. If ``axes`` is ``None``, the function must compute the transform over all axes. Default: ``None``. - If ``axes`` contains two or more entries which resolve to the same axis (i.e., resolved axes are not unique), the behavior is unspecified and thus implementation-defined. + If ``axes`` contains two or more entries which resolve to the same axis (i.e., resolved axes are not unique), the behavior is unspecified and thus implementation-defined. norm: Literal['backward', 'ortho', 'forward'] - normalization mode. Should be one of the following modes: + normalization mode. Should be one of the following modes: - - ``'backward'``: no normalization. - - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). - - ``'forward'``: normalize by ``1/n``. + - ``'backward'``: no normalization. + - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). + - ``'forward'``: normalize by ``1/n``. - where ``n = prod(s)`` is the logical FFT size. + where ``n = prod(s)`` is the logical FFT size. - Default: ``'backward'``. + Default: ``'backward'``. Returns ------- out: array - an array transformed along the axes (dimensions) specified by ``axes``. The returned array must have the same data type as ``x`` and must have the same shape as ``x``, except for the axes specified by ``axes`` which must have size ``s[i]``. + an array transformed along the axes (dimensions) specified by ``axes``. The returned array must have the same data type as ``x`` and must have the same shape as ``x``, except for the axes specified by ``axes`` which must have size ``s[i]``. Notes ----- @@ -7365,7 +7365,7 @@ class fftn[TArray: Array](Protocol): .. versionadded:: 2022.12 .. versionchanged:: 2023.12 - Required the input array have a complex floating-point data type and required that the output array have the same data type as the input array. + Required the input array have a complex floating-point data type and required that the output array have the same data type as the input array. """ @@ -7379,41 +7379,41 @@ class ifftn[TArray: Array](Protocol): Computes the n-dimensional inverse discrete Fourier transform. .. note:: - Applying the n-dimensional inverse discrete Fourier transform to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e., ``ifftn(fftn(x)) == x``), provided that the transform and inverse transform are performed with the same arguments (sizes, axes, and normalization mode). + Applying the n-dimensional inverse discrete Fourier transform to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e., ``ifftn(fftn(x)) == x``), provided that the transform and inverse transform are performed with the same arguments (sizes, axes, and normalization mode). Parameters ---------- x: array - input array. Should have a complex floating-point data type. + input array. Should have a complex floating-point data type. s: Optional[Sequence[int]] - number of elements over which to compute the transform along the axes (dimensions) specified by ``axes``. Let ``i`` be the index of the ``n``-th axis specified by ``axes`` (i.e., ``i = axes[n]``) and ``M[i]`` be the size of the input array along axis ``i``. When ``s`` is ``None``, the function must set ``s`` equal to a sequence of integers such that ``s[i]`` equals ``M[i]`` for all ``i``. + number of elements over which to compute the transform along the axes (dimensions) specified by ``axes``. Let ``i`` be the index of the ``n``-th axis specified by ``axes`` (i.e., ``i = axes[n]``) and ``M[i]`` be the size of the input array along axis ``i``. When ``s`` is ``None``, the function must set ``s`` equal to a sequence of integers such that ``s[i]`` equals ``M[i]`` for all ``i``. - - If ``s[i]`` is greater than ``M[i]``, axis ``i`` must be zero-padded to size ``s[i]``. - - If ``s[i]`` is less than ``M[i]``, axis ``i`` must be trimmed to size ``s[i]``. - - If ``s[i]`` equals ``M[i]`` or ``-1``, all elements along axis ``i`` must be used when computing the transform. + - If ``s[i]`` is greater than ``M[i]``, axis ``i`` must be zero-padded to size ``s[i]``. + - If ``s[i]`` is less than ``M[i]``, axis ``i`` must be trimmed to size ``s[i]``. + - If ``s[i]`` equals ``M[i]`` or ``-1``, all elements along axis ``i`` must be used when computing the transform. - If ``s`` is not ``None``, ``axes`` must not be ``None``. Default: ``None``. + If ``s`` is not ``None``, ``axes`` must not be ``None``. Default: ``None``. axes: Optional[Sequence[int]] - axes (dimensions) over which to compute the transform. A valid axis in ``axes`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an axis is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). + axes (dimensions) over which to compute the transform. A valid axis in ``axes`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an axis is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). - If ``s`` is provided, the corresponding ``axes`` to be transformed must also be provided. If ``axes`` is ``None``, the function must compute the transform over all axes. Default: ``None``. + If ``s`` is provided, the corresponding ``axes`` to be transformed must also be provided. If ``axes`` is ``None``, the function must compute the transform over all axes. Default: ``None``. - If ``axes`` contains two or more entries which resolve to the same axis (i.e., resolved axes are not unique), the behavior is unspecified and thus implementation-defined. + If ``axes`` contains two or more entries which resolve to the same axis (i.e., resolved axes are not unique), the behavior is unspecified and thus implementation-defined. norm: Literal['backward', 'ortho', 'forward'] - specify the normalization mode. Should be one of the following modes: + specify the normalization mode. Should be one of the following modes: - - ``'backward'``: normalize by ``1/n``. - - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). - - ``'forward'``: no normalization. + - ``'backward'``: normalize by ``1/n``. + - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). + - ``'forward'``: no normalization. - where ``n = prod(s)`` is the logical FFT size. + where ``n = prod(s)`` is the logical FFT size. - Default: ``'backward'``. + Default: ``'backward'``. Returns ------- out: array - an array transformed along the axes (dimensions) specified by ``axes``. The returned array must have the same data type as ``x`` and must have the same shape as ``x``, except for the axes specified by ``axes`` which must have size ``s[i]``. + an array transformed along the axes (dimensions) specified by ``axes``. The returned array must have the same data type as ``x`` and must have the same shape as ``x``, except for the axes specified by ``axes`` which must have size ``s[i]``. Notes ----- @@ -7421,7 +7421,7 @@ class ifftn[TArray: Array](Protocol): .. versionadded:: 2022.12 .. versionchanged:: 2023.12 - Required the input array have a complex floating-point data type and required that the output array have the same data type as the input array. + Required the input array have a complex floating-point data type and required that the output array have the same data type as the input array. """ @@ -7435,35 +7435,35 @@ class rfft[TArray: Array](Protocol): Computes the one-dimensional discrete Fourier transform for real-valued input. .. note:: - Applying the one-dimensional inverse discrete Fourier transform for real-valued input to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e., ``irfft(rfft(x)) == x``), provided that the transform and inverse transform are performed with the same arguments (axis and normalization mode) and consistent values for the number of elements over which to compute the transforms. + Applying the one-dimensional inverse discrete Fourier transform for real-valued input to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e., ``irfft(rfft(x)) == x``), provided that the transform and inverse transform are performed with the same arguments (axis and normalization mode) and consistent values for the number of elements over which to compute the transforms. Parameters ---------- x: array - input array. Must have a real-valued floating-point data type. + input array. Must have a real-valued floating-point data type. n: Optional[int] - number of elements over which to compute the transform along the axis (dimension) specified by ``axis``. Let ``M`` be the size of the input array along the axis specified by ``axis``. When ``n`` is ``None``, the function must set ``n`` equal to ``M``. + number of elements over which to compute the transform along the axis (dimension) specified by ``axis``. Let ``M`` be the size of the input array along the axis specified by ``axis``. When ``n`` is ``None``, the function must set ``n`` equal to ``M``. - - If ``n`` is greater than ``M``, the axis specified by ``axis`` must be zero-padded to size ``n``. - - If ``n`` is less than ``M``, the axis specified by ``axis`` must be trimmed to size ``n``. - - If ``n`` equals ``M``, all elements along the axis specified by ``axis`` must be used when computing the transform. + - If ``n`` is greater than ``M``, the axis specified by ``axis`` must be zero-padded to size ``n``. + - If ``n`` is less than ``M``, the axis specified by ``axis`` must be trimmed to size ``n``. + - If ``n`` equals ``M``, all elements along the axis specified by ``axis`` must be used when computing the transform. - Default: ``None``. + Default: ``None``. axis: int - axis (dimension) of the input array over which to compute the transform. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). Default: ``-1``. + axis (dimension) of the input array over which to compute the transform. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). Default: ``-1``. norm: Literal['backward', 'ortho', 'forward'] - normalization mode. Should be one of the following modes: + normalization mode. Should be one of the following modes: - - ``'backward'``: no normalization. - - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). - - ``'forward'``: normalize by ``1/n``. + - ``'backward'``: no normalization. + - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). + - ``'forward'``: normalize by ``1/n``. - Default: ``'backward'``. + Default: ``'backward'``. Returns ------- out: array - an array transformed along the axis (dimension) specified by ``axis``. The returned array must have a complex floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``float64``, then the returned array must have a ``complex128`` data type). The returned array must have the same shape as ``x``, except for the axis specified by ``axis`` which must have size ``n//2 + 1``. + an array transformed along the axis (dimension) specified by ``axis``. The returned array must have a complex floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``float64``, then the returned array must have a ``complex128`` data type). The returned array must have the same shape as ``x``, except for the axis specified by ``axis`` which must have size ``n//2 + 1``. Notes ----- @@ -7482,35 +7482,35 @@ class irfft[TArray: Array](Protocol): Computes the one-dimensional inverse of ``rfft`` for complex-valued input. .. note:: - Applying the one-dimensional inverse discrete Fourier transform for real-valued input to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e., ``irfft(rfft(x)) == x``), provided that the transform and inverse transform are performed with the same arguments (axis and normalization mode) and consistent values for the number of elements over which to compute the transforms. + Applying the one-dimensional inverse discrete Fourier transform for real-valued input to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e., ``irfft(rfft(x)) == x``), provided that the transform and inverse transform are performed with the same arguments (axis and normalization mode) and consistent values for the number of elements over which to compute the transforms. Parameters ---------- x: array - input array. Should have a complex floating-point data type. + input array. Should have a complex floating-point data type. n: Optional[int] - number of elements along the transformed axis (dimension) specified by ``axis`` in the **output array**. Let ``M`` be the size of the input array along the axis specified by ``axis``. When ``n`` is ``None``, the function must set ``n`` equal to ``2*(M-1)``. + number of elements along the transformed axis (dimension) specified by ``axis`` in the **output array**. Let ``M`` be the size of the input array along the axis specified by ``axis``. When ``n`` is ``None``, the function must set ``n`` equal to ``2*(M-1)``. - - If ``n//2+1`` is greater than ``M``, the axis of the input array specified by ``axis`` must be zero-padded to size ``n//2+1``. - - If ``n//2+1`` is less than ``M``, the axis of the input array specified by ``axis`` must be trimmed to size ``n//2+1``. - - If ``n//2+1`` equals ``M``, all elements along the axis of the input array specified by ``axis`` must be used when computing the transform. + - If ``n//2+1`` is greater than ``M``, the axis of the input array specified by ``axis`` must be zero-padded to size ``n//2+1``. + - If ``n//2+1`` is less than ``M``, the axis of the input array specified by ``axis`` must be trimmed to size ``n//2+1``. + - If ``n//2+1`` equals ``M``, all elements along the axis of the input array specified by ``axis`` must be used when computing the transform. - Default: ``None``. + Default: ``None``. axis: int - axis (dimension) of the input array over which to compute the transform. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). Default: ``-1``. + axis (dimension) of the input array over which to compute the transform. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). Default: ``-1``. norm: Literal['backward', 'ortho', 'forward'] - normalization mode. Should be one of the following modes: + normalization mode. Should be one of the following modes: - - ``'backward'``: normalize by ``1/n``. - - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). - - ``'forward'``: no normalization. + - ``'backward'``: normalize by ``1/n``. + - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). + - ``'forward'``: no normalization. - Default: ``'backward'``. + Default: ``'backward'``. Returns ------- out: array - an array transformed along the axis (dimension) specified by ``axis``. The returned array must have a real-valued floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``complex128``, then the returned array must have a ``float64`` data type). The returned array must have the same shape as ``x``, except for the axis specified by ``axis`` which must have size ``n``. + an array transformed along the axis (dimension) specified by ``axis``. The returned array must have a real-valued floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``complex128``, then the returned array must have a ``float64`` data type). The returned array must have the same shape as ``x``, except for the axis specified by ``axis`` which must have size ``n``. Notes ----- @@ -7519,7 +7519,7 @@ class irfft[TArray: Array](Protocol): .. versionadded:: 2022.12 .. versionchanged:: 2023.12 - Required the output array have a real-valued floating-point data type having the same precision as the input array. + Required the output array have a real-valued floating-point data type having the same precision as the input array. """ @@ -7533,41 +7533,41 @@ class rfftn[TArray: Array](Protocol): Computes the n-dimensional discrete Fourier transform for real-valued input. .. note:: - Applying the n-dimensional inverse discrete Fourier transform for real-valued input to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e., ``irfftn(rfftn(x)) == x``), provided that the transform and inverse transform are performed with the same arguments (axes and normalization mode) and consistent sizes. + Applying the n-dimensional inverse discrete Fourier transform for real-valued input to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e., ``irfftn(rfftn(x)) == x``), provided that the transform and inverse transform are performed with the same arguments (axes and normalization mode) and consistent sizes. Parameters ---------- x: array - input array. Must have a real-valued floating-point data type. + input array. Must have a real-valued floating-point data type. s: Optional[Sequence[int]] - number of elements over which to compute the transform along axes (dimensions) specified by ``axes``. Let ``i`` be the index of the ``n``-th axis specified by ``axes`` (i.e., ``i = axes[n]``) and ``M[i]`` be the size of the input array along axis ``i``. When ``s`` is ``None``, the function must set ``s`` equal to a sequence of integers such that ``s[i]`` equals ``M[i]`` for all ``i``. + number of elements over which to compute the transform along axes (dimensions) specified by ``axes``. Let ``i`` be the index of the ``n``-th axis specified by ``axes`` (i.e., ``i = axes[n]``) and ``M[i]`` be the size of the input array along axis ``i``. When ``s`` is ``None``, the function must set ``s`` equal to a sequence of integers such that ``s[i]`` equals ``M[i]`` for all ``i``. - - If ``s[i]`` is greater than ``M[i]``, axis ``i`` must be zero-padded to size ``s[i]``. - - If ``s[i]`` is less than ``M[i]``, axis ``i`` must be trimmed to size ``s[i]``. - - If ``s[i]`` equals ``M[i]`` or ``-1``, all elements along axis ``i`` must be used when computing the transform. + - If ``s[i]`` is greater than ``M[i]``, axis ``i`` must be zero-padded to size ``s[i]``. + - If ``s[i]`` is less than ``M[i]``, axis ``i`` must be trimmed to size ``s[i]``. + - If ``s[i]`` equals ``M[i]`` or ``-1``, all elements along axis ``i`` must be used when computing the transform. - If ``s`` is not ``None``, ``axes`` must not be ``None``. Default: ``None``. + If ``s`` is not ``None``, ``axes`` must not be ``None``. Default: ``None``. axes: Optional[Sequence[int]] - axes (dimensions) over which to compute the transform. A valid axis in ``axes`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an axis is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). + axes (dimensions) over which to compute the transform. A valid axis in ``axes`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an axis is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). - If ``s`` is provided, the corresponding ``axes`` to be transformed must also be provided. If ``axes`` is ``None``, the function must compute the transform over all axes. Default: ``None``. + If ``s`` is provided, the corresponding ``axes`` to be transformed must also be provided. If ``axes`` is ``None``, the function must compute the transform over all axes. Default: ``None``. - If ``axes`` contains two or more entries which resolve to the same axis (i.e., resolved axes are not unique), the behavior is unspecified and thus implementation-defined. + If ``axes`` contains two or more entries which resolve to the same axis (i.e., resolved axes are not unique), the behavior is unspecified and thus implementation-defined. norm: Literal['backward', 'ortho', 'forward'] - normalization mode. Should be one of the following modes: + normalization mode. Should be one of the following modes: - - ``'backward'``: no normalization. - - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). - - ``'forward'``: normalize by ``1/n``. + - ``'backward'``: no normalization. + - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). + - ``'forward'``: normalize by ``1/n``. - where ``n = prod(s)``, the logical FFT size. + where ``n = prod(s)``, the logical FFT size. - Default: ``'backward'``. + Default: ``'backward'``. Returns ------- out: array - an array transformed along the axes (dimension) specified by ``axes``. The returned array must have a complex floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``float64``, then the returned array must have a ``complex128`` data type). The returned array must have the same shape as ``x``, except for the last transformed axis which must have size ``s[-1]//2 + 1`` and the remaining transformed axes which must have size ``s[i]``. + an array transformed along the axes (dimension) specified by ``axes``. The returned array must have a complex floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``float64``, then the returned array must have a ``complex128`` data type). The returned array must have the same shape as ``x``, except for the last transformed axis which must have size ``s[-1]//2 + 1`` and the remaining transformed axes which must have size ``s[i]``. Notes ----- @@ -7586,41 +7586,41 @@ class irfftn[TArray: Array](Protocol): Computes the n-dimensional inverse of ``rfftn`` for complex-valued input. .. note:: - Applying the n-dimensional inverse discrete Fourier transform for real-valued input to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e., ``irfftn(rfftn(x)) == x``), provided that the transform and inverse transform are performed with the same arguments (axes and normalization mode) and consistent sizes. + Applying the n-dimensional inverse discrete Fourier transform for real-valued input to the output of this function must return the original (i.e., non-transformed) input array within numerical accuracy (i.e., ``irfftn(rfftn(x)) == x``), provided that the transform and inverse transform are performed with the same arguments (axes and normalization mode) and consistent sizes. Parameters ---------- x: array - input array. Should have a complex floating-point data type. + input array. Should have a complex floating-point data type. s: Optional[Sequence[int]] - number of elements along the transformed axes (dimensions) specified by ``axes`` in the **output array**. Let ``i`` be the index of the ``n``-th axis specified by ``axes`` (i.e., ``i = axes[n]``) and ``M[i]`` be the size of the input array along axis ``i``. When ``s`` is ``None``, the function must set ``s`` equal to a sequence of integers such that ``s[i]`` equals ``M[i]`` for all ``i``, except for the last transformed axis in which ``s[i]`` equals ``2*(M[i]-1)``. For each ``i``, let ``n`` equal ``s[i]``, except for the last transformed axis in which ``n`` equals ``s[i]//2+1``. + number of elements along the transformed axes (dimensions) specified by ``axes`` in the **output array**. Let ``i`` be the index of the ``n``-th axis specified by ``axes`` (i.e., ``i = axes[n]``) and ``M[i]`` be the size of the input array along axis ``i``. When ``s`` is ``None``, the function must set ``s`` equal to a sequence of integers such that ``s[i]`` equals ``M[i]`` for all ``i``, except for the last transformed axis in which ``s[i]`` equals ``2*(M[i]-1)``. For each ``i``, let ``n`` equal ``s[i]``, except for the last transformed axis in which ``n`` equals ``s[i]//2+1``. - - If ``n`` is greater than ``M[i]``, axis ``i`` of the input array must be zero-padded to size ``n``. - - If ``n`` is less than ``M[i]``, axis ``i`` of the input array must be trimmed to size ``n``. - - If ``n`` equals ``M[i]`` or ``-1``, all elements along axis ``i`` of the input array must be used when computing the transform. + - If ``n`` is greater than ``M[i]``, axis ``i`` of the input array must be zero-padded to size ``n``. + - If ``n`` is less than ``M[i]``, axis ``i`` of the input array must be trimmed to size ``n``. + - If ``n`` equals ``M[i]`` or ``-1``, all elements along axis ``i`` of the input array must be used when computing the transform. - If ``s`` is not ``None``, ``axes`` must not be ``None``. Default: ``None``. + If ``s`` is not ``None``, ``axes`` must not be ``None``. Default: ``None``. axes: Optional[Sequence[int]] - axes (dimensions) over which to compute the transform. A valid axis in ``axes`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an axis is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). + axes (dimensions) over which to compute the transform. A valid axis in ``axes`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an axis is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). - If ``s`` is provided, the corresponding ``axes`` to be transformed must also be provided. If ``axes`` is ``None``, the function must compute the transform over all axes. Default: ``None``. + If ``s`` is provided, the corresponding ``axes`` to be transformed must also be provided. If ``axes`` is ``None``, the function must compute the transform over all axes. Default: ``None``. - If ``axes`` contains two or more entries which resolve to the same axis (i.e., resolved axes are not unique), the behavior is unspecified and thus implementation-defined. + If ``axes`` contains two or more entries which resolve to the same axis (i.e., resolved axes are not unique), the behavior is unspecified and thus implementation-defined. norm: Literal['backward', 'ortho', 'forward'] - normalization mode. Should be one of the following modes: + normalization mode. Should be one of the following modes: - - ``'backward'``: normalize by ``1/n``. - - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). - - ``'forward'``: no normalization. + - ``'backward'``: normalize by ``1/n``. + - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). + - ``'forward'``: no normalization. - where ``n = prod(s)`` is the logical FFT size. + where ``n = prod(s)`` is the logical FFT size. - Default: ``'backward'``. + Default: ``'backward'``. Returns ------- out: array - an array transformed along the axes (dimension) specified by ``axes``. The returned array must have a real-valued floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``complex128``, then the returned array must have a ``float64`` data type). The returned array must have the same shape as ``x``, except for the transformed axes which must have size ``s[i]``. + an array transformed along the axes (dimension) specified by ``axes``. The returned array must have a real-valued floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``complex128``, then the returned array must have a ``float64`` data type). The returned array must have the same shape as ``x``, except for the transformed axes which must have size ``s[i]``. Notes ----- @@ -7629,7 +7629,7 @@ class irfftn[TArray: Array](Protocol): .. versionadded:: 2022.12 .. versionchanged:: 2023.12 - Required the output array have a real-valued floating-point data type having the same precision as the input array. + Required the output array have a real-valued floating-point data type having the same precision as the input array. """ @@ -7645,30 +7645,30 @@ class hfft[TArray: Array](Protocol): Parameters ---------- x: array - input array. Should have a complex floating-point data type. + input array. Should have a complex floating-point data type. n: Optional[int] - number of elements along the transformed axis (dimension) specified by ``axis`` in the **output array**. Let ``M`` be the size of the input array along the axis specified by ``axis``. When ``n`` is ``None``, the function must set ``n`` equal to ``2*(M-1)``. + number of elements along the transformed axis (dimension) specified by ``axis`` in the **output array**. Let ``M`` be the size of the input array along the axis specified by ``axis``. When ``n`` is ``None``, the function must set ``n`` equal to ``2*(M-1)``. - - If ``n//2+1`` is greater than ``M``, the axis of the input array specified by ``axis`` must be zero-padded to length ``n//2+1``. - - If ``n//2+1`` is less than ``M``, the axis of the input array specified by ``axis`` must be trimmed to size ``n//2+1``. - - If ``n//2+1`` equals ``M``, all elements along the axis of the input array specified by ``axis`` must be used when computing the transform. + - If ``n//2+1`` is greater than ``M``, the axis of the input array specified by ``axis`` must be zero-padded to length ``n//2+1``. + - If ``n//2+1`` is less than ``M``, the axis of the input array specified by ``axis`` must be trimmed to size ``n//2+1``. + - If ``n//2+1`` equals ``M``, all elements along the axis of the input array specified by ``axis`` must be used when computing the transform. - Default: ``None``. + Default: ``None``. axis: int - axis (dimension) of the input array over which to compute the transform. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). Default: ``-1``. + axis (dimension) of the input array over which to compute the transform. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). Default: ``-1``. norm: Literal['backward', 'ortho', 'forward'] - normalization mode. Should be one of the following modes: + normalization mode. Should be one of the following modes: - - ``'backward'``: no normalization. - - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). - - ``'forward'``: normalize by ``1/n``. + - ``'backward'``: no normalization. + - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). + - ``'forward'``: normalize by ``1/n``. - Default: ``'backward'``. + Default: ``'backward'``. Returns ------- out: array - an array transformed along the axis (dimension) specified by ``axis``. The returned array must have a real-valued floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``complex128``, then the returned array must have a ``float64`` data type). The returned array must have the same shape as ``x``, except for the axis specified by ``axis`` which must have size ``n``. + an array transformed along the axis (dimension) specified by ``axis``. The returned array must have a real-valued floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``complex128``, then the returned array must have a ``float64`` data type). The returned array must have the same shape as ``x``, except for the axis specified by ``axis`` which must have size ``n``. Notes ----- @@ -7676,7 +7676,7 @@ class hfft[TArray: Array](Protocol): .. versionadded:: 2022.12 .. versionchanged:: 2023.12 - Required the input array to have a complex floating-point data type and required that the output array have a real-valued data type having the same precision as the input array. + Required the input array to have a complex floating-point data type and required that the output array have a real-valued data type having the same precision as the input array. """ @@ -7692,30 +7692,30 @@ class ihfft[TArray: Array](Protocol): Parameters ---------- x: array - input array. Must have a real-valued floating-point data type. + input array. Must have a real-valued floating-point data type. n: Optional[int] - number of elements over which to compute the transform along the axis (dimension) specified by ``axis``. Let ``M`` be the size of the input array along the axis specified by ``axis``. When ``n`` is ``None``, the function must set ``n`` equal to ``M``. + number of elements over which to compute the transform along the axis (dimension) specified by ``axis``. Let ``M`` be the size of the input array along the axis specified by ``axis``. When ``n`` is ``None``, the function must set ``n`` equal to ``M``. - - If ``n`` is greater than ``M``, the axis specified by ``axis`` must be zero-padded to size ``n``. - - If ``n`` is less than ``M``, the axis specified by ``axis`` must be trimmed to size ``n``. - - If ``n`` equals ``M``, all elements along the axis specified by ``axis`` must be used when computing the transform. + - If ``n`` is greater than ``M``, the axis specified by ``axis`` must be zero-padded to size ``n``. + - If ``n`` is less than ``M``, the axis specified by ``axis`` must be trimmed to size ``n``. + - If ``n`` equals ``M``, all elements along the axis specified by ``axis`` must be used when computing the transform. - Default: ``None``. + Default: ``None``. axis: int - axis (dimension) of the input array over which to compute the transform. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). Default: ``-1``. + axis (dimension) of the input array over which to compute the transform. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If an ``axis`` is specified as a negative integer, the function must determine the axis along which to compute the transform by counting backward from the last dimension (where ``-1`` refers to the last dimension). Default: ``-1``. norm: Literal['backward', 'ortho', 'forward'] - normalization mode. Should be one of the following modes: + normalization mode. Should be one of the following modes: - - ``'backward'``: normalize by ``1/n``. - - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). - - ``'forward'``: no normalization. + - ``'backward'``: normalize by ``1/n``. + - ``'ortho'``: normalize by ``1/sqrt(n)`` (i.e., make the FFT orthonormal). + - ``'forward'``: no normalization. - Default: ``'backward'``. + Default: ``'backward'``. Returns ------- out: array - an array transformed along the axis (dimension) specified by ``axis``. The returned array must have a complex floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``float64``, then the returned array must have a ``complex128`` data type). The returned array must have the same shape as ``x``, except for the axis specified by ``axis`` which must have size ``n//2 + 1``. + an array transformed along the axis (dimension) specified by ``axis``. The returned array must have a complex floating-point data type whose precision matches the precision of ``x`` (e.g., if ``x`` is ``float64``, then the returned array must have a ``complex128`` data type). The returned array must have the same shape as ``x``, except for the axis specified by ``axis`` which must have size ``n//2 + 1``. Notes ----- @@ -7737,24 +7737,24 @@ class fftfreq[TArray: Array, TDevice, TDtype](Protocol): .. code-block:: - f = [0, 1, ..., n/2-1, -n/2, ..., -1] / (d*n) # if n is even - f = [0, 1, ..., (n-1)/2, -(n-1)/2, ..., -1] / (d*n) # if n is odd + f = [0, 1, ..., n/2-1, -n/2, ..., -1] / (d*n) # if n is even + f = [0, 1, ..., (n-1)/2, -(n-1)/2, ..., -1] / (d*n) # if n is odd Parameters ---------- n: int - window length. + window length. d: float - sample spacing between individual samples of the Fourier transform input. Default: ``1.0``. + sample spacing between individual samples of the Fourier transform input. Default: ``1.0``. dtype: Optional[dtype] - output array data type. Must be a real-valued floating-point data type. If ``dtype`` is ``None``, the output array data type must be the default real-valued floating-point data type. Default: ``None``. + output array data type. Must be a real-valued floating-point data type. If ``dtype`` is ``None``, the output array data type must be the default real-valued floating-point data type. Default: ``None``. device: Optional[device] - device on which to place the created array. Default: ``None``. + device on which to place the created array. Default: ``None``. Returns ------- out: array - an array of shape ``(n,)`` containing the sample frequencies. + an array of shape ``(n,)`` containing the sample frequencies. Notes ----- @@ -7762,10 +7762,10 @@ class fftfreq[TArray: Array, TDevice, TDtype](Protocol): .. versionadded:: 2022.12 .. versionchanged:: 2023.12 - Required the output array have the default real-valued floating-point data type. + Required the output array have the default real-valued floating-point data type. .. versionchanged:: 2024.12 - Added ``dtype`` keyword argument support. + Added ``dtype`` keyword argument support. """ @@ -7782,26 +7782,26 @@ class rfftfreq[TArray: Array, TDevice, TDtype](Protocol): .. code-block:: - f = [0, 1, ..., n/2-1, n/2] / (d*n) # if n is even - f = [0, 1, ..., (n-1)/2-1, (n-1)/2] / (d*n) # if n is odd + f = [0, 1, ..., n/2-1, n/2] / (d*n) # if n is even + f = [0, 1, ..., (n-1)/2-1, (n-1)/2] / (d*n) # if n is odd The Nyquist frequency component is considered to be positive. Parameters ---------- n: int - window length. + window length. d: float - sample spacing between individual samples of the Fourier transform input. Default: ``1.0``. + sample spacing between individual samples of the Fourier transform input. Default: ``1.0``. dtype: Optional[dtype] - output array data type. Must be a real-valued floating-point data type. If ``dtype`` is ``None``, the output array data type must be the default real-valued floating-point data type. Default: ``None``. + output array data type. Must be a real-valued floating-point data type. If ``dtype`` is ``None``, the output array data type must be the default real-valued floating-point data type. Default: ``None``. device: Optional[device] - device on which to place the created array. Default: ``None``. + device on which to place the created array. Default: ``None``. Returns ------- out: array - an array of shape ``(n//2+1,)`` containing the sample frequencies. + an array of shape ``(n//2+1,)`` containing the sample frequencies. Notes ----- @@ -7809,10 +7809,10 @@ class rfftfreq[TArray: Array, TDevice, TDtype](Protocol): .. versionadded:: 2022.12 .. versionchanged:: 2023.12 - Required the output array have the default real-valued floating-point data type. + Required the output array have the default real-valued floating-point data type. .. versionchanged:: 2024.12 - Added ``dtype`` keyword argument support. + Added ``dtype`` keyword argument support. """ @@ -7828,21 +7828,21 @@ class fftshift[TArray: Array](Protocol): This function swaps half-spaces for all axes (dimensions) specified by ``axes``. .. note:: - ``out[0]`` is the Nyquist component only if the length of the input is even. + ``out[0]`` is the Nyquist component only if the length of the input is even. Parameters ---------- x: array - input array. Should have a floating-point data type. + input array. Should have a floating-point data type. axes: Optional[Union[int, Sequence[int]]] - axes over which to shift. If ``None``, the function must shift all axes. Default: ``None``. + axes over which to shift. If ``None``, the function must shift all axes. Default: ``None``. - If ``axes`` contains two or more entries which resolve to the same axis (i.e., resolved axes are not unique), the behavior is unspecified and thus implementation-defined. + If ``axes`` contains two or more entries which resolve to the same axis (i.e., resolved axes are not unique), the behavior is unspecified and thus implementation-defined. Returns ------- out: array - the shifted array. The returned array must have the same data type and shape as ``x``. + the shifted array. The returned array must have the same data type and shape as ``x``. Notes ----- @@ -7861,21 +7861,21 @@ class ifftshift[TArray: Array](Protocol): Inverse of ``fftshift``. .. note:: - Although identical for even-length ``x``, ``fftshift`` and ``ifftshift`` differ by one sample for odd-length ``x``. + Although identical for even-length ``x``, ``fftshift`` and ``ifftshift`` differ by one sample for odd-length ``x``. Parameters ---------- x: array - input array. Should have a floating-point data type. + input array. Should have a floating-point data type. axes: Optional[Union[int, Sequence[int]]] - axes over which to perform the inverse shift. If ``None``, the function must shift all axes. Default: ``None``. + axes over which to perform the inverse shift. If ``None``, the function must shift all axes. Default: ``None``. - If ``axes`` contains two or more entries which resolve to the same axis (i.e., resolved axes are not unique), the behavior is unspecified and thus implementation-defined. + If ``axes`` contains two or more entries which resolve to the same axis (i.e., resolved axes are not unique), the behavior is unspecified and thus implementation-defined. Returns ------- out: array - the shifted array. The returned array must have the same data type and shape as ``x``. + the shifted array. The returned array must have the same data type and shape as ``x``. Notes ----- @@ -7893,46 +7893,56 @@ class matmul[TArray: Array](Protocol): """ Computes the matrix product. - .. note:: - The ``matmul`` function must implement the same semantics as the built-in ``@`` operator (see `PEP 465 `_). - Parameters ---------- x1: array - first input array. Should have a numeric data type. Must have at least one dimension. If ``x1`` is one-dimensional having shape ``(M,)`` and ``x2`` has more than one dimension, ``x1`` must be promoted to a two-dimensional array by prepending ``1`` to its dimensions (i.e., must have shape ``(1, M)``). After matrix multiplication, the prepended dimensions in the returned array must be removed. If ``x1`` has more than one dimension (including after vector-to-matrix promotion), ``shape(x1)[:-2]`` must be compatible with ``shape(x2)[:-2]`` (after vector-to-matrix promotion) (see :ref:`broadcasting`). If ``x1`` has shape ``(..., M, K)``, the innermost two dimensions form matrices on which to perform matrix multiplication. - x2: array - second input array. Should have a numeric data type. Must have at least one dimension. If ``x2`` is one-dimensional having shape ``(N,)`` and ``x1`` has more than one dimension, ``x2`` must be promoted to a two-dimensional array by appending ``1`` to its dimensions (i.e., must have shape ``(N, 1)``). After matrix multiplication, the appended dimensions in the returned array must be removed. If ``x2`` has more than one dimension (including after vector-to-matrix promotion), ``shape(x2)[:-2]`` must be compatible with ``shape(x1)[:-2]`` (after vector-to-matrix promotion) (see :ref:`broadcasting`). If ``x2`` has shape ``(..., K, N)``, the innermost two dimensions form matrices on which to perform matrix multiplication. + first input array. **Should** have a numeric data type. **Must** have at least one dimension. + - If ``x1`` is a one-dimensional array having shape ``(M,)`` and ``x2`` has more than one dimension, ``x1`` **must** be promoted to a two-dimensional array by prepending ``1`` to its dimensions (i.e., **must** have shape ``(1, M)``). After matrix multiplication, the prepended dimensions in the returned array **must** be removed. + - If ``x1`` has more than one dimension (including after vector-to-matrix promotion), ``shape(x1)[:-2]`` **must** be compatible with ``shape(x2)[:-2]`` (after vector-to-matrix promotion) (see :ref:`broadcasting`). + - If ``x1`` has shape ``(..., M, K)``, the innermost two dimensions form matrices on which to perform matrix multiplication. - .. note:: - If either ``x1`` or ``x2`` has a complex floating-point data type, neither argument must be complex-conjugated or transposed. If conjugation and/or transposition is desired, these operations should be explicitly performed prior to computing the matrix product. + x2: array + second input array. **Should** have a numeric data type. **Must** have at least one dimension. + + - If ``x2`` is one-dimensional array having shape ``(N,)`` and ``x1`` has more than one dimension, ``x2`` **must** be promoted to a two-dimensional array by appending ``1`` to its dimensions (i.e., **must** have shape ``(N, 1)``). After matrix multiplication, the appended dimensions in the returned array **must** be removed. + - If ``x2`` has more than one dimension (including after vector-to-matrix promotion), ``shape(x2)[:-2]`` **must** be compatible with ``shape(x1)[:-2]`` (after vector-to-matrix promotion) (see :ref:`broadcasting`). + - If ``x2`` has shape ``(..., K, N)``, the innermost two dimensions form matrices on which to perform matrix multiplication. Returns ------- out: array - - if both ``x1`` and ``x2`` are one-dimensional arrays having shape ``(N,)``, a zero-dimensional array containing the inner product as its only element. - - if ``x1`` is a two-dimensional array having shape ``(M, K)`` and ``x2`` is a two-dimensional array having shape ``(K, N)``, a two-dimensional array containing the `conventional matrix product `_ and having shape ``(M, N)``. - - if ``x1`` is a one-dimensional array having shape ``(K,)`` and ``x2`` is an array having shape ``(..., K, N)``, an array having shape ``(..., N)`` (i.e., prepended dimensions during vector-to-matrix promotion must be removed) and containing the `conventional matrix product `_. - - if ``x1`` is an array having shape ``(..., M, K)`` and ``x2`` is a one-dimensional array having shape ``(K,)``, an array having shape ``(..., M)`` (i.e., appended dimensions during vector-to-matrix promotion must be removed) and containing the `conventional matrix product `_. - - if ``x1`` is a two-dimensional array having shape ``(M, K)`` and ``x2`` is an array having shape ``(..., K, N)``, an array having shape ``(..., M, N)`` and containing the `conventional matrix product `_ for each stacked matrix. - - if ``x1`` is an array having shape ``(..., M, K)`` and ``x2`` is a two-dimensional array having shape ``(K, N)``, an array having shape ``(..., M, N)`` and containing the `conventional matrix product `_ for each stacked matrix. - - if either ``x1`` or ``x2`` has more than two dimensions, an array having a shape determined by :ref:`broadcasting` ``shape(x1)[:-2]`` against ``shape(x2)[:-2]`` and containing the `conventional matrix product `_ for each stacked matrix. + output array. + + - If both ``x1`` and ``x2`` are one-dimensional arrays having shape ``(N,)``, the returned array **must** be a zero-dimensional array and **must** contain the inner product as its only element. + - If ``x1`` is a two-dimensional array having shape ``(M, K)`` and ``x2`` is a two-dimensional array having shape ``(K, N)``, the returned array **must** be a two-dimensional array and **must** contain the `conventional matrix product `_ and having shape ``(M, N)``. + - If ``x1`` is a one-dimensional array having shape ``(K,)`` and ``x2`` is an array having shape ``(..., K, N)``, the returned array **must** be an array having shape ``(..., N)`` (i.e., prepended dimensions during vector-to-matrix promotion **must** be removed) and **must** contain the `conventional matrix product `_. + - If ``x1`` is an array having shape ``(..., M, K)`` and ``x2`` is a one-dimensional array having shape ``(K,)``, the returned array **must** be an array having shape ``(..., M)`` (i.e., appended dimensions during vector-to-matrix promotion **must** be removed) and **must** contain the `conventional matrix product `_. + - If ``x1`` is a two-dimensional array having shape ``(M, K)`` and ``x2`` is an array having shape ``(..., K, N)``, the returned array **must** be an array having shape ``(..., M, N)`` and **must** contain the `conventional matrix product `_ for each stacked matrix. + - If ``x1`` is an array having shape ``(..., M, K)`` and ``x2`` is a two-dimensional array having shape ``(K, N)``, the returned array **must** be an array having shape ``(..., M, N)`` and **must** contain the `conventional matrix product `_ for each stacked matrix. + - If either ``x1`` or ``x2`` has more than two dimensions, the returned array **must** be an array having a shape determined by :ref:`broadcasting` ``shape(x1)[:-2]`` against ``shape(x2)[:-2]`` and **must** contain the `conventional matrix product `_ for each stacked matrix. + + The returned array **must** have a data type determined by :ref:`type-promotion`. + + Raises + ------ + Exception + an exception **should** be raised in the following circumstances: - The returned array must have a data type determined by :ref:`type-promotion`. + - if either ``x1`` or ``x2`` is a zero-dimensional array. + - if ``x1`` is a one-dimensional array having shape ``(K,)``, ``x2`` is a one-dimensional array having shape ``(L,)``, and ``K != L``. + - if ``x1`` is a one-dimensional array having shape ``(K,)``, ``x2`` is an array having shape ``(..., L, N)``, and ``K != L``. + - if ``x1`` is an array having shape ``(..., M, K)``, ``x2`` is a one-dimensional array having shape ``(L,)``, and ``K != L``. + - if ``x1`` is an array having shape ``(..., M, K)``, ``x2`` is an array having shape ``(..., L, N)``, and ``K != L``. Notes ----- + - The ``matmul`` function **must** implement the same semantics as the built-in ``@`` operator (see `PEP 465 `_). - .. versionchanged:: 2022.12 - Added complex data type support. - - **Raises** + - If either ``x1`` or ``x2`` has a complex floating-point data type, the function **must not** complex-conjugate or tranpose either argument. If conjugation and/or transposition is desired, a user can explicitly perform these operations prior to computing the matrix product. - - if either ``x1`` or ``x2`` is a zero-dimensional array. - - if ``x1`` is a one-dimensional array having shape ``(K,)``, ``x2`` is a one-dimensional array having shape ``(L,)``, and ``K != L``. - - if ``x1`` is a one-dimensional array having shape ``(K,)``, ``x2`` is an array having shape ``(..., L, N)``, and ``K != L``. - - if ``x1`` is an array having shape ``(..., M, K)``, ``x2`` is a one-dimensional array having shape ``(L,)``, and ``K != L``. - - if ``x1`` is an array having shape ``(..., M, K)``, ``x2`` is an array having shape ``(..., L, N)``, and ``K != L``. + .. versionchanged:: 2022.12 + Added complex data type support. """ @@ -7948,12 +7958,12 @@ class matrix_transpose[TArray: Array](Protocol): Parameters ---------- x: array - input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. + input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices. Returns ------- out: array - an array containing the transpose for each matrix and having shape ``(..., N, M)``. The returned array must have the same data type as ``x``. + an array containing the transpose for each matrix. The returned array **must** have shape ``(..., N, M)``. The returned array **must** have the same data type as ``x``. """ @@ -7966,47 +7976,41 @@ class tensordot[TArray: Array](Protocol): """ Returns a tensor contraction of ``x1`` and ``x2`` over specific axes. - .. note:: - The ``tensordot`` function corresponds to the generalized matrix product. - Parameters ---------- x1: array - first input array. Should have a numeric data type. + first input array. **Should** have a numeric data type. x2: array - second input array. Should have a numeric data type. Corresponding contracted axes of ``x1`` and ``x2`` must be equal. - - .. note:: - Contracted axes (dimensions) must not be broadcasted. + second input array. **Should** have a numeric data type. Corresponding contracted axes of ``x1`` and ``x2`` **must** be equal. axes: Union[int, Tuple[Sequence[int], Sequence[int]]] - number of axes (dimensions) to contract or explicit sequences of axis (dimension) indices for ``x1`` and ``x2``, respectively. + number of axes to contract or explicit sequences of axis indices for ``x1`` and ``x2``, respectively. - If ``axes`` is an ``int`` equal to ``N``, then contraction must be performed over the last ``N`` axes of ``x1`` and the first ``N`` axes of ``x2`` in order. The size of each corresponding axis (dimension) must match. Must be nonnegative. + If ``axes`` is an ``int`` equal to ``N``, then contraction **must** be performed over the last ``N`` axes of ``x1`` and the first ``N`` axes of ``x2`` in order. The size of each corresponding axis **must** match. An integer ``axes`` value **must** be nonnegative. - - If ``N`` equals ``0``, the result is the tensor (outer) product. - - If ``N`` equals ``1``, the result is the tensor dot product. - - If ``N`` equals ``2``, the result is the tensor double contraction (default). + - If ``N`` equals ``0``, the result **must** be the tensor (outer) product. + - If ``N`` equals ``1``, the result **must** be the tensor dot product. + - If ``N`` equals ``2``, the result **must** be the tensor double contraction (default). - If ``axes`` is a tuple of two sequences ``(x1_axes, x2_axes)``, the first sequence must apply to ``x1`` and the second sequence to ``x2``. Both sequences must have the same length. Each axis (dimension) ``x1_axes[i]`` for ``x1`` must have the same size as the respective axis (dimension) ``x2_axes[i]`` for ``x2``. Each index referred to in a sequence must be unique. If ``x1`` has rank (i.e, number of dimensions) ``N``, a valid ``x1`` axis must reside on the half-open interval ``[-N, N)``. If ``x2`` has rank ``M``, a valid ``x2`` axis must reside on the half-open interval ``[-M, M)``. + If ``axes`` is a tuple of two sequences ``(x1_axes, x2_axes)``, the first sequence **must** apply to ``x1`` and the second sequence **must** apply to ``x2``. Both sequences **must** have the same length. Each axis ``x1_axes[i]`` for ``x1`` **must** have the same size as the respective axis ``x2_axes[i]`` for ``x2``. Each index referred to in a sequence **must** be unique. A valid axis **must** be an integer on the interval ``[-S, S)``, where ``S`` is the number of axes in respective array. Hence, if ``x1`` has ``N`` axes, a valid ``x1`` axes **must** be an integer on the interval ``[-N, N)``. If ``x2`` has ``M`` axes, a valid ``x2`` axes **must** be an integer on the interval ``[-M, M)``. If an axis is specified as a negative integer, the function **must** determine the axis along which to perform the operation by counting backward from the last axis (where ``-1`` refers to the last axis). If provided an invalid axis, the function **must** raise an exception. - .. note:: - If either ``x1`` or ``x2`` has a complex floating-point data type, neither argument must be complex-conjugated or transposed. If conjugation and/or transposition is desired, these operations should be explicitly performed prior to computing the generalized matrix product. - Returns ------- out: array - an array containing the tensor contraction whose shape consists of the non-contracted axes (dimensions) of the first array ``x1``, followed by the non-contracted axes (dimensions) of the second array ``x2``. The returned array must have a data type determined by :ref:`type-promotion`. + an array containing the tensor contraction. The returned array **must** have a shape which consists of the non-contracted axes of the first array ``x1``, followed by the non-contracted axes of the second array ``x2``. The returned array **must** have a data type determined by :ref:`type-promotion`. Notes ----- + - The ``tensordot`` function corresponds to the generalized matrix product. + - Contracted axes **must** not be broadcasted. + - If either ``x1`` or ``x2`` has a complex floating-point data type, the function **must not** complex-conjugate or transpose either argument. If conjugation and/or transposition is desired, a user can explicitly perform these operations prior to computing the generalized matrix product. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. .. versionchanged:: 2023.12 - Allow negative axes. + Allow negative axes. """ @@ -8022,39 +8026,40 @@ class vecdot[TArray: Array](Protocol): Let :math:`\\mathbf{a}` be a vector in ``x1`` and :math:`\\mathbf{b}` be a corresponding vector in ``x2``. The dot product is defined as .. math:: - \\mathbf{a} \\cdot \\mathbf{b} = \\sum_{i=0}^{n-1} \\overline{a_i}b_i + \\mathbf{a} \\cdot \\mathbf{b} = \\sum_{i=0}^{n-1} \\overline{a_i}b_i - over the dimension specified by ``axis`` and where :math:`n` is the dimension size and :math:`\\overline{a_i}` denotes the complex conjugate if :math:`a_i` is complex and the identity if :math:`a_i` is real-valued. + over the axis specified by ``axis`` and where :math:`n` is the axis size and :math:`\\overline{a_i}` denotes the complex conjugate if :math:`a_i` is complex and the identity if :math:`a_i` is real-valued. Parameters ---------- x1: array - first input array. Should have a floating-point data type. + first input array. **Should** have a floating-point data type. x2: array - second input array. Must be compatible with ``x1`` for all non-contracted axes (see :ref:`broadcasting`). The size of the axis over which to compute the dot product must be the same size as the respective axis in ``x1``. Should have a floating-point data type. - - .. note:: - The contracted axis (dimension) must not be broadcasted. - + second input array. **Must** be compatible with ``x1`` for all non-contracted axes (see :ref:`broadcasting`). The size of the axis over which to compute the dot product **must** be the same size as the respective axis in ``x1``. **Should** have a floating-point data type. axis: int - the axis (dimension) of ``x1`` and ``x2`` containing the vectors for which to compute the dot product. Should be an integer on the interval ``[-N, -1]``, where ``N`` is ``min(x1.ndim, x2.ndim)``. The function must determine the axis along which to compute the dot product by counting backward from the last dimension (where ``-1`` refers to the last dimension). By default, the function must compute the dot product over the last axis. Default: ``-1``. + axis of ``x1`` and ``x2`` containing the vectors for which to compute the dot product. **Should** be an integer on the interval ``[-N, -1]``, where ``N`` is ``min(x1.ndim, x2.ndim)``. The function **must** determine the axis along which to perform the operation by counting backward from the last axis (where ``-1`` refers to the last axis). By default, the function **must** compute the dot product over the last axis. Default: ``-1``. Returns ------- out: array - if ``x1`` and ``x2`` are both one-dimensional arrays, a zero-dimensional containing the dot product; otherwise, a non-zero-dimensional array containing the dot products and having rank ``N-1``, where ``N`` is the rank (number of dimensions) of the shape determined according to :ref:`broadcasting` along the non-contracted axes. The returned array must have a data type determined by :ref:`type-promotion`. + if ``x1`` and ``x2`` are both one-dimensional arrays, a zero-dimensional containing the dot product; otherwise, a non-zero-dimensional array containing the dot products and having ``N-1`` axes, where ``N`` is number of axes in the shape determined according to :ref:`broadcasting` along the non-contracted axes. The returned array **must** have a data type determined by :ref:`type-promotion`. + + Raises + ------ + Exception + an exception **should** be raised in the following circumstances: + + - if the size of the axis over which to compute the dot product is not the same (before broadcasting) for both ``x1`` and ``x2``. Notes ----- - **Raises** - - - if the size of the axis over which to compute the dot product is not the same (before broadcasting) for both ``x1`` and ``x2``. + - The contracted axis **must** not be broadcasted. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. .. versionchanged:: 2023.12 - Restricted ``axis`` to only negative integers. + Restricted ``axis`` to only negative integers. """ @@ -8070,12 +8075,12 @@ class broadcast_arrays[TArray: Array](Protocol): Parameters ---------- arrays: array - an arbitrary number of to-be broadcasted arrays. + an arbitrary number of to-be broadcasted arrays. Returns ------- out: List[array] - a list of broadcasted arrays. Each array must have the same shape. Each array must have the same dtype as its corresponding input array. + a list of broadcasted arrays. Each array **must** have the same shape. Each array **must** have the same dtype as its corresponding input array. """ @@ -8091,17 +8096,17 @@ class broadcast_to[TArray: Array](Protocol): Parameters ---------- x: array - array to broadcast. Must be capable of being broadcast to the specified ``shape`` (see :ref:`broadcasting`). If the array is incompatible with the specified shape, the function must raise an exception. + array to broadcast. **Must** be capable of being broadcast to the specified ``shape`` (see :ref:`broadcasting`). If the array is incompatible with the specified shape, the function **must** raise an exception. shape: Tuple[int, ...] - array shape. + array shape. Returns ------- out: array - an array having the specified shape. Must have the same data type as ``x``. + an array having the specified shape. **Must** have the same data type as ``x``. .. versionchanged:: 2024.12 - Clarified broadcast behavior. + Clarified broadcast behavior. """ @@ -8117,17 +8122,17 @@ class concat[TArray: Array](Protocol): Parameters ---------- arrays: Union[Tuple[array, ...], List[array]] - input arrays to join. The arrays must have the same shape, except in the dimension specified by ``axis``. + input arrays to join. The arrays **must** have the same shape, except in the dimension specified by ``axis``. axis: Optional[int] - axis along which the arrays will be joined. If ``axis`` is ``None``, arrays must be flattened before concatenation. If ``axis`` is negative, the function must determine the axis along which to join by counting from the last dimension. Default: ``0``. + axis along which to join the arrays. A valid axis **must** be an integer on the interval ``[-N, N)``, where ``N`` is the number of axes in each array. If an axis is specified as a negative integer, the function **must** determine the axis along which to perform the operation by counting backward from the last axis (where ``-1`` refers to the last axis). If provided an invalid axis, the function **must** raise an exception. If ``axis`` is ``None``, arrays **must** be flattened before concatenation. Default: ``0``. Returns ------- out: array - an output array containing the concatenated values. If the input arrays have different data types, normal :ref:`type-promotion` must apply. If the input arrays have the same data type, the output array must have the same data type as the input arrays. + an output array containing the concatenated values. If the input arrays have different data types, normal :ref:`type-promotion` **must** apply. If the input arrays have the same data type, the output array **must** have the same data type as the input arrays. - .. note:: - This specification leaves type promotion between data type families (i.e., ``intxx`` and ``floatxx``) unspecified. + .. note:: + This specification leaves type promotion between data type families (i.e., ``intxx`` and ``floatxx``) unspecified and thus implementation-defined. """ @@ -8138,24 +8143,24 @@ def __call__(self, arrays: tuple[TArray, ...] | list[TArray], /, *, axis: int | @runtime_checkable class expand_dims[TArray: Array](Protocol): """ - Expands the shape of an array by inserting a new axis (dimension) of size one at the position specified by ``axis``. + Expands the shape of an array by inserting a new axis of size one at the position specified by ``axis``. Parameters ---------- x: array - input array. + input array. axis: int - axis position (zero-based). If ``x`` has rank (i.e, number of dimensions) ``N``, a valid ``axis`` must reside on the closed-interval ``[-N-1, N]``. If provided a negative ``axis``, the axis position at which to insert a singleton dimension must be computed as ``N + axis + 1``. Hence, if provided ``-1``, the resolved axis position must be ``N`` (i.e., a singleton dimension must be appended to the input array ``x``). If provided ``-N-1``, the resolved axis position must be ``0`` (i.e., a singleton dimension must be prepended to the input array ``x``). + axis position (zero-based). A valid ``axis`` **must** reside on the closed-interval ``[-N-1, N]``, where ``N`` is the number of axes in ``x``. If an axis is specified as a negative integer, the axis position at which to insert a singleton dimension **must** be computed as ``N + axis + 1``. Hence, if provided ``-1``, the resolved axis position **must** be ``N`` (i.e., a singleton dimension **must** be appended to the input array ``x``). If provided ``-N-1``, the resolved axis position **must** be ``0`` (i.e., a singleton dimension **must** be prepended to the input array ``x``). If provided an invalid axis, the function **must** raise an exception. Default: ``0``. Returns ------- out: array - an expanded output array having the same data type as ``x``. + an expanded output array. **Must** have the same data type as ``x``. Raises ------ IndexError - If provided an invalid ``axis`` position, an ``IndexError`` should be raised. + If provided an invalid ``axis``, an ``IndexError`` **should** be raised. """ @@ -8166,19 +8171,19 @@ def __call__(self, x: TArray, /, *, axis: int = 0) -> TArray: ... @runtime_checkable class flip[TArray: Array](Protocol): """ - Reverses the order of elements in an array along the given axis. The shape of the array must be preserved. + Reverses the order of elements in an array along the given axis. Parameters ---------- x: array - input array. + input array. axis: Optional[Union[int, Tuple[int, ...]]] - axis (or axes) along which to flip. If ``axis`` is ``None``, the function must flip all input array axes. If ``axis`` is negative, the function must count from the last dimension. If provided more than one axis, the function must flip only the specified axes. Default: ``None``. + axis (or axes) along which to reverse elements. A valid axis **must** be an integer on the interval ``[-N, N)``, where ``N`` is the number of axes in ``x``. If an axis is specified as a negative integer, the function **must** determine the axis along which to perform the operation by counting backward from the last axis (where ``-1`` refers to the last axis). If provided an invalid axis, the function **must** raise an exception. If ``axis`` is ``None``, the function **must** flip all input array axes. If provided more than one axis, the function **must** flip only the specified axes. Default: ``None``. Returns ------- out: array - an output array having the same data type and shape as ``x`` and whose elements, relative to ``x``, are reordered. + an output array. The returned array **must** have the same data type and shape as ``x``. The returned array must have the same elements as ``x``, but which are reordered relative to ``x``. """ @@ -8189,21 +8194,21 @@ def __call__(self, x: TArray, /, *, axis: int | tuple[int, ...] | None = None) - @runtime_checkable class moveaxis[TArray: Array](Protocol): """ - Moves array axes (dimensions) to new positions, while leaving other axes in their original positions. + Moves array axes to new positions, while leaving other axes in their original positions. Parameters ---------- x: array - input array. + input array. source: Union[int, Tuple[int, ...]] - Axes to move. Provided axes must be unique. If ``x`` has rank (i.e, number of dimensions) ``N``, a valid axis must reside on the half-open interval ``[-N, N)``. + axis (or axes) to move. Provided source axes **must** be unique. A valid axis **must** be an integer on the interval ``[-N, N)``, where ``N`` is the number of axes in ``x``. If an axis is specified as a negative integer, the function **must** determine the axis along which to perform the operation by counting backward from the last axis (where ``-1`` refers to the last axis). If provided an invalid axis, the function **must** raise an exception. destination: Union[int, Tuple[int, ...]] - indices defining the desired positions for each respective ``source`` axis index. Provided indices must be unique. If ``x`` has rank (i.e, number of dimensions) ``N``, a valid axis must reside on the half-open interval ``[-N, N)``. + axis (or axes) defining the desired position(s) for each respective ``source`` axis index. Provided destination axes **must** be unique. A valid axis **must** be an integer on the interval ``[-N, N)``, where ``N`` is the number of axes in ``x``. If an axis is specified as a negative integer, the function **must** determine the axis along which to perform the operation by counting backward from the last axis (where ``-1`` refers to the last axis). If provided an invalid axis, the function **must** raise an exception. Returns ------- out: array - an array containing reordered axes. The returned array must have the same data type as ``x``. + an array containing reordered axes. The returned array **must** have the same data type as ``x``. Notes ----- @@ -8219,19 +8224,19 @@ def __call__(self, x: TArray, source: int | tuple[int, ...], destination: int | @runtime_checkable class permute_dims[TArray: Array](Protocol): """ - Permutes the axes (dimensions) of an array ``x``. + Permutes the axes of an array ``x``. Parameters ---------- x: array - input array. + input array. axes: Tuple[int, ...] - tuple containing a permutation of ``(0, 1, ..., N-1)`` where ``N`` is the number of axes (dimensions) of ``x``. + tuple containing a permutation of ``(0, 1, ..., N-1)`` where ``N`` is the number of axes in ``x``. Returns ------- out: array - an array containing the axes permutation. The returned array must have the same data type as ``x``. + an array containing the axes permutation. The returned array **must** have the same data type as ``x``. """ @@ -8245,42 +8250,40 @@ class repeat[TArray: Array](Protocol): Repeats each element of an array a specified number of times on a per-element basis. .. admonition:: Data-dependent output shape - :class: important + :class: important - When ``repeats`` is an array, the shape of the output array for this function depends on the data values in the ``repeats`` array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) may find this function difficult to implement without knowing the values in ``repeats``. Accordingly, such libraries may choose to omit support for ``repeats`` arrays; however, conforming implementations must support providing a literal ``int``. See :ref:`data-dependent-output-shapes` section for more details. + When ``repeats`` is an array, the shape of the output array for this function depends on the data values in the ``repeats`` array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) can find this function difficult to implement without knowing the values in ``repeats``. Accordingly, such libraries **may** choose to omit support for ``repeats`` arrays; however, conforming implementations **must** support providing a literal ``int``. See :ref:`data-dependent-output-shapes` section for more details. Parameters ---------- x: array - input array containing elements to repeat. + input array containing elements to repeat. repeats: Union[int, array] - the number of repetitions for each element. - - If ``axis`` is ``None``, let ``N = prod(x.shape)`` and + the number of repetitions for each element. - - if ``repeats`` is an array, ``repeats`` must be broadcast compatible with the shape ``(N,)`` (i.e., be a one-dimensional array having shape ``(1,)`` or ``(N,)``). - - if ``repeats`` is an integer, ``repeats`` must be broadcasted to the shape `(N,)`. + If ``axis`` is ``None``, let ``M = prod(x.shape)`` and - If ``axis`` is not ``None``, let ``M = x.shape[axis]`` and + - if ``repeats`` is an array, ``repeats`` **must** be broadcast compatible with the shape ``(M,)`` (i.e., be a one-dimensional array having shape ``(1,)`` or ``(M,)``). + - if ``repeats`` is an integer, ``repeats`` **must** be broadcasted to the shape `(M,)`. - - if ``repeats`` is an array, ``repeats`` must be broadcast compatible with the shape ``(M,)`` (i.e., be a one-dimensional array having shape ``(1,)`` or ``(M,)``). - - if ``repeats`` is an integer, ``repeats`` must be broadcasted to the shape ``(M,)``. + If ``axis`` is not ``None``, let ``S = x.shape[axis]`` and - If ``repeats`` is an array, the array must have an integer data type. + - if ``repeats`` is an array, ``repeats`` **must** be broadcast compatible with the shape ``(S,)`` (i.e., be a one-dimensional array having shape ``(1,)`` or ``(S,)``). + - if ``repeats`` is an integer, ``repeats`` **must** be broadcasted to the shape ``(S,)``. - .. note:: - For specification-conforming array libraries supporting hardware acceleration, providing an array for ``repeats`` may cause device synchronization due to an unknown output shape. For those array libraries where synchronization concerns are applicable, conforming array libraries are advised to include a warning in their documentation regarding potential performance degradation when ``repeats`` is an array. + If ``repeats`` is an array, the array **must** have an integer data type. axis: Optional[int] - the axis (dimension) along which to repeat elements. If ``axis`` is `None`, the function must flatten the input array ``x`` and then repeat elements of the flattened input array and return the result as a one-dimensional output array. A flattened input array must be flattened in row-major, C-style order. Default: ``None``. + the axis along which to repeat elements. A valid axis **must** be an integer on the interval ``[-N, N)``, where ``N`` is the number of axes in ``x``. If an axis is specified as a negative integer, the function **must** determine the axis along which to perform the operation by counting backward from the last axis (where ``-1`` refers to the last axis). If provided an invalid axis, the function **must** raise an exception. If ``axis`` is `None`, the function **must** flatten the input array ``x`` and then repeat elements of the flattened input array and return the result as a one-dimensional output array. A flattened input array **must** be flattened in row-major, C-style order. Default: ``None``. Returns ------- out: array - an output array containing repeated elements. The returned array must have the same data type as ``x``. If ``axis`` is ``None``, the returned array must be a one-dimensional array; otherwise, the returned array must have the same shape as ``x``, except for the axis (dimension) along which elements were repeated. + an output array containing repeated elements. The returned array **must** have the same data type as ``x``. If ``axis`` is ``None``, the returned array **must** be a one-dimensional array; otherwise, the returned array **must** have the same shape as ``x``, except for the axis along which elements were repeated. Notes ----- + - For specification-conforming array libraries supporting hardware acceleration, providing an array for ``repeats`` can cause device synchronization due to an unknown output shape. For those array libraries where synchronization concerns are applicable, conforming array libraries **should** include a warning in their documentation regarding potential performance degradation when ``repeats`` is an array. .. versionadded:: 2023.12 @@ -8298,22 +8301,21 @@ class reshape[TArray: Array](Protocol): Parameters ---------- x: array - input array to reshape. + input array to reshape. shape: Tuple[int, ...] - a new shape compatible with the original shape. One shape dimension is allowed to be ``-1``. When a shape dimension is ``-1``, the corresponding output array shape dimension must be inferred from the length of the array and the remaining dimensions. + a new shape compatible with the original shape. Only one shape dimension **must** be allowed to be ``-1``. When a shape dimension is ``-1``, the corresponding output array shape dimension **must** be inferred from the length of the array and the remaining dimensions. copy: Optional[bool] - whether or not to copy the input array. If ``True``, the function must always copy (see :ref:`copy-keyword-argument`). If ``False``, the function must never copy. If ``None``, the function must avoid copying, if possible, and may copy otherwise. Default: ``None``. + whether or not to copy the input array. If ``True``, the function **must** always copy (see :ref:`copy-keyword-argument`). If ``False``, the function **must** never copy. If ``None``, the function **must** avoid copying, if possible, and **may** copy otherwise. Default: ``None``. Returns ------- out: array - an output array having the same data type and elements as ``x``. + an output array. The returned array **must** have the same data type and the same elements as ``x``. Raises ------ ValueError - If ``copy=False`` and a copy would be necessary, a ``ValueError`` - should be raised. + If ``copy=False`` and a copy would be necessary, a ``ValueError`` **should** be raised. """ @@ -8324,21 +8326,25 @@ def __call__(self, x: TArray, /, shape: tuple[int, ...], *, copy: bool | None = @runtime_checkable class roll[TArray: Array](Protocol): """ - Rolls array elements along a specified axis. Array elements that roll beyond the last position are re-introduced at the first position. Array elements that roll beyond the first position are re-introduced at the last position. + Rolls array elements along a specified axis. + + Array elements that roll beyond the last position are re-introduced at the first position. + + Array elements that roll beyond the first position are re-introduced at the last position. Parameters ---------- x: array - input array. + input array. shift: Union[int, Tuple[int, ...]] - number of places by which the elements are shifted. If ``shift`` is a tuple, then ``axis`` must be a tuple of the same size, and each of the given axes must be shifted by the corresponding element in ``shift``. If ``shift`` is an ``int`` and ``axis`` a tuple, then the same ``shift`` must be used for all specified axes. If a shift is positive, then array elements must be shifted positively (toward larger indices) along the dimension of ``axis``. If a shift is negative, then array elements must be shifted negatively (toward smaller indices) along the dimension of ``axis``. + number of places by which the elements are shifted. If ``shift`` is a tuple, then ``axis`` **must** be a tuple of the same size, and each of the given axes **must** be shifted by the corresponding element in ``shift``. If ``shift`` is an ``int`` and ``axis`` a tuple, then the same ``shift`` **must** be used for all specified axes. If a shift is positive, then array elements **must** be shifted positively (toward larger indices) along the dimension of ``axis``. If a shift is negative, then array elements **must** be shifted negatively (toward smaller indices) along the dimension of ``axis``. axis: Optional[Union[int, Tuple[int, ...]]] - axis (or axes) along which elements to shift. If ``axis`` is ``None``, the array must be flattened, shifted, and then restored to its original shape. Default: ``None``. + axis (or axes) along which elements to shift. A valid axis **must** be an integer on the interval ``[-N, N)``, where ``N`` is the number of axes in ``x``. If an axis is specified as a negative integer, the function **must** determine the axis along which to perform the operation by counting backward from the last axis (where ``-1`` refers to the last axis). If provided an invalid axis, the function **must** raise an exception. If ``axis`` is ``None``, the array **must** be flattened, shifted, and then restored to its original shape. Default: ``None``. Returns ------- out: array - an output array having the same data type as ``x`` and whose elements, relative to ``x``, are shifted. + an output array. The returned array **must** have the same data type as ``x``. The returned array **must** have the same elements as ``x``, but which are shifted relative to ``x``. """ @@ -8349,25 +8355,24 @@ def __call__(self, x: TArray, /, shift: int | tuple[int, ...], *, axis: int | tu @runtime_checkable class squeeze[TArray: Array](Protocol): """ - Removes singleton dimensions (axes) from ``x``. + Removes singleton axes from ``x``. Parameters ---------- x: array - input array. + input array. axis: Union[int, Tuple[int, ...]] - axis (or axes) to squeeze. + axis (or axes) to squeeze. A valid axis **must** be an integer on the interval ``[-N, N)``, where ``N`` is the number of axes in ``x``. If an axis is specified as a negative integer, the function **must** determine the axis along which to perform the operation by counting backward from the last axis (where ``-1`` refers to the last axis). If provided an invalid axis, the function **must** raise an exception. Returns ------- out: array - an output array having the same data type and elements as ``x``. + an output array. The returned array **must** have the same data type and the same elements as ``x``. Raises ------ ValueError - If a specified axis has a size greater than one (i.e., it is not a - singleton dimension), a ``ValueError`` should be raised. + If a specified axis has a size greater than one (i.e., it is not a singleton axis), a ``ValueError`` **should** be raised. """ @@ -8383,17 +8388,18 @@ class stack[TArray: Array](Protocol): Parameters ---------- arrays: Union[Tuple[array, ...], List[array]] - input arrays to join. Each array must have the same shape. + input arrays to join. Each array **must** have the same shape. axis: int - axis along which the arrays will be joined. Providing an ``axis`` specifies the index of the new axis in the dimensions of the result. For example, if ``axis`` is ``0``, the new axis will be the first dimension and the output array will have shape ``(N, A, B, C)``; if ``axis`` is ``1``, the new axis will be the second dimension and the output array will have shape ``(A, N, B, C)``; and, if ``axis`` is ``-1``, the new axis will be the last dimension and the output array will have shape ``(A, B, C, N)``. A valid ``axis`` must be on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If provided an ``axis`` outside of the required interval, the function must raise an exception. Default: ``0``. + axis along which to join the arrays. Providing an ``axis`` specifies the index of the new axis in the shape of the result. For example, if ``axis`` is ``0``, the new axis **must** be the first dimension and the output array **must** have shape ``(N, A, B, C)``; if ``axis`` is ``1``, the new axis will be the second dimension and the output array will have shape ``(A, N, B, C)``; and, if ``axis`` is ``-1``, the new axis will be the last dimension and the output array will have shape ``(A, B, C, N)``. A valid axis **must** be an integer on the interval ``[-N, N)``, where ``N`` is the number of axes in ``x``. If an axis is specified as a negative integer, the function **must** determine the axis along which to perform the operation by counting backward from the last axis (where ``-1`` refers to the last axis). If provided an invalid axis, the function **must** raise an exception. Default: ``0``. Returns ------- out: array - an output array having rank ``N+1``, where ``N`` is the rank (number of dimensions) of ``x``. If the input arrays have different data types, normal :ref:`type-promotion` must apply. If the input arrays have the same data type, the output array must have the same data type as the input arrays. + an output array. The returned array **must** have ``N+1`` axes, where ``N`` is the number of axes in ``x``. If the input arrays have different data types, normal :ref:`type-promotion` **must** apply. If the input arrays have the same data type, the output array **must** have the same data type as the input arrays. - .. note:: - This specification leaves type promotion between data type families (i.e., ``intxx`` and ``floatxx``) unspecified. + Notes + ----- + - This specification leaves type promotion between data type families (i.e., ``intxx`` and ``floatxx``) unspecified and thus implementation-defined. """ @@ -8409,20 +8415,20 @@ class tile[TArray: Array](Protocol): Parameters ---------- x: array - input array. + input array. repetitions: Tuple[int, ...] - number of repetitions along each axis (dimension). + number of repetitions along each axis. - Let ``N = len(x.shape)`` and ``M = len(repetitions)``. + Let ``N = len(x.shape)`` and ``M = len(repetitions)``. - If ``N > M``, the function must prepend ones until all axes (dimensions) are specified (e.g., if ``x`` has shape ``(8,6,4,2)`` and ``repetitions`` is the tuple ``(3,3)``, then ``repetitions`` must be treated as ``(1,1,3,3)``). + If ``N > M``, the function **must** prepend ones until all axes are specified (e.g., if ``x`` has shape ``(8,6,4,2)`` and ``repetitions`` is the tuple ``(3,3)``, then ``repetitions`` **must** be treated as ``(1,1,3,3)``). - If ``N < M``, the function must prepend singleton axes (dimensions) to ``x`` until ``x`` has as many axes (dimensions) as ``repetitions`` specifies (e.g., if ``x`` has shape ``(4,2)`` and ``repetitions`` is the tuple ``(3,3,3,3)``, then ``x`` must be treated as if it has shape ``(1,1,4,2)``). + If ``N < M``, the function **must** prepend singleton axes to ``x`` until ``x`` has as many axes as ``repetitions`` specifies (e.g., if ``x`` has shape ``(4,2)`` and ``repetitions`` is the tuple ``(3,3,3,3)``, then ``x`` **must** be treated as if it has shape ``(1,1,4,2)``). Returns ------- out: array - a tiled output array. The returned array must have the same data type as ``x`` and must have a rank (i.e., number of dimensions) equal to ``max(N, M)``. If ``S`` is the shape of the tiled array after prepending singleton dimensions (if necessary) and ``r`` is the tuple of repetitions after prepending ones (if necessary), then the number of elements along each axis (dimension) must satisfy ``S[i]*r[i]``, where ``i`` refers to the ``i`` th axis (dimension). + a tiled output array. The returned array **must** have the same data type as ``x`` and **must** have a number of axes equal to ``max(N, M)``. If ``S`` is the shape of the tiled array after prepending singleton dimensions (if necessary) and ``r`` is the tuple of repetitions after prepending ones (if necessary), then the number of elements along each axis **must** satisfy ``S[i]*r[i]``, where ``i`` refers to the ``i`` th axis. Notes ----- @@ -8443,14 +8449,14 @@ class unstack[TArray: Array](Protocol): Parameters ---------- x: array - input array. + input array. axis: int - axis along which the array will be split. A valid ``axis`` must be on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If provided an ``axis`` outside of the required interval, the function must raise an exception. Default: ``0``. + axis along which to split an array. A valid axis **must** be an integer on the interval ``[-N, N)``, where ``N`` is the number of axes in ``x``. If an axis is specified as a negative integer, the function **must** determine the axis along which to perform the operation by counting backward from the last axis (where ``-1`` refers to the last axis). If provided an invalid axis, the function **must** raise an exception. Default: ``0``. Returns ------- out: Tuple[array, ...] - tuple of slices along the given dimension. All the arrays have the same shape. + tuple of slices along the given dimension. Each returned array **must** have the same shape. Notes ----- @@ -8469,47 +8475,44 @@ class unique_all[TArray: Array](Protocol): Returns the unique elements of an input array ``x``, the first occurring indices for each unique element in ``x``, the indices from the set of unique elements that reconstruct ``x``, and the corresponding counts for each unique element in ``x``. .. admonition:: Data-dependent output shape - :class: important - - The shapes of two of the output arrays for this function depend on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) may find this function difficult to implement without knowing array values. Accordingly, such libraries may choose to omit this function. See :ref:`data-dependent-output-shapes` section for more details. - - .. note:: - Uniqueness should be determined based on value equality (see :func:`~array_api.equal`). For input arrays having floating-point data types, value-based equality implies the following behavior. - - - As ``nan`` values compare as ``False``, ``nan`` values should be considered distinct. - - As complex floating-point values having at least one ``nan`` component compare as ``False``, complex floating-point values having ``nan`` components should be considered distinct. - - As ``-0`` and ``+0`` compare as ``True``, signed zeros should not be considered distinct, and the corresponding unique element will be implementation-dependent (e.g., an implementation could choose to return ``-0`` if ``-0`` occurs before ``+0``). + :class: important - As signed zeros are not distinct, using ``inverse_indices`` to reconstruct the input array is not guaranteed to return an array having the exact same values. - - Each ``nan`` value and each complex floating-point value having a ``nan`` component should have a count of one, while the counts for signed zeros should be aggregated as a single count. + The shapes of two of the output arrays for this function depend on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, et cetera) can find this function difficult to implement without knowing array values. Accordingly, such libraries **may** choose to omit this function. See :ref:`data-dependent-output-shapes` section for more details. Parameters ---------- x: array - input array. If ``x`` has more than one dimension, the function must flatten ``x`` and return the unique elements of the flattened array. + input array. If ``x`` has more than one dimension, the function **must** flatten ``x`` and return the unique elements of the flattened array. Returns ------- out: Tuple[array, array, array, array] - a namedtuple ``(values, indices, inverse_indices, counts)`` whose - - - first element must have the field name ``values`` and must be a one-dimensional array containing the unique elements of ``x``. The array must have the same data type as ``x``. - - second element must have the field name ``indices`` and must be an array containing the indices (first occurrences) of a flattened ``x`` that result in ``values``. The array must have the same shape as ``values`` and must have the default array index data type. - - third element must have the field name ``inverse_indices`` and must be an array containing the indices of ``values`` that reconstruct ``x``. The array must have the same shape as ``x`` and must have the default array index data type. - - fourth element must have the field name ``counts`` and must be an array containing the number of times each unique element occurs in ``x``. The order of the returned counts must match the order of ``values``, such that a specific element in ``counts`` corresponds to the respective unique element in ``values``. The returned array must have same shape as ``values`` and must have the default array index data type. + a namedtuple ``(values, indices, inverse_indices, counts)`` whose - .. note:: - The order of unique elements is not specified and may vary between implementations. + - first element **must** have the field name ``values`` and **must** be a one-dimensional array containing the unique elements of ``x``. The array **must** have the same data type as ``x``. + - second element **must** have the field name ``indices`` and **must** be an array containing the indices (first occurrences) of a flattened ``x`` that result in ``values``. The array **must** have the same shape as ``values`` and **must** have the default array index data type. + - third element **must** have the field name ``inverse_indices`` and **must** be an array containing the indices of ``values`` that reconstruct ``x``. The array **must** have the same shape as ``x`` and **must** have the default array index data type. + - fourth element **must** have the field name ``counts`` and **must** be an array containing the number of times each unique element occurs in ``x``. The order of the returned counts **must** match the order of ``values``, such that a specific element in ``counts`` corresponds to the respective unique element in ``values``. The returned array **must** have same shape as ``values`` and **must** have the default array index data type. Notes ----- + - The order of unique elements returned by this function is unspecified and thus implementation-defined. As a consequence, element order **may** vary between implementations. + + - Uniqueness **should** be determined based on value equality (see :func:`~array_api.equal`). For input arrays having floating-point data types, value-based equality implies the following behavior. + + - As ``nan`` values compare as ``False``, ``nan`` values **should** be considered distinct. + - As complex floating-point values having at least one ``nan`` component compare as ``False``, complex floating-point values having ``nan`` components **should** be considered distinct. + - As ``-0`` and ``+0`` compare as ``True``, signed zeros **should not** be considered distinct, and the corresponding unique element **may** be implementation-defined (e.g., an implementation **may** choose to return ``-0`` if ``-0`` occurs before ``+0``). + + As signed zeros are not distinct, using ``inverse_indices`` to reconstruct the input array is not guaranteed to return an array having the exact same values. + + Each ``nan`` value and each complex floating-point value having a ``nan`` component **should** have a count of one, while the counts for signed zeros **should** be aggregated as a single count. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. .. versionchanged:: 2023.12 - Clarified flattening behavior and required the order of ``counts`` match the order of ``values``. + Clarified flattening behavior and required the order of ``counts`` match the order of ``values``. """ @@ -8523,43 +8526,40 @@ class unique_counts[TArray: Array](Protocol): Returns the unique elements of an input array ``x`` and the corresponding counts for each unique element in ``x``. .. admonition:: Data-dependent output shape - :class: important - - The shapes of two of the output arrays for this function depend on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) may find this function difficult to implement without knowing array values. Accordingly, such libraries may choose to omit this function. See :ref:`data-dependent-output-shapes` section for more details. + :class: important - .. note:: - Uniqueness should be determined based on value equality (see :func:`~array_api.equal`). For input arrays having floating-point data types, value-based equality implies the following behavior. - - - As ``nan`` values compare as ``False``, ``nan`` values should be considered distinct. - - As complex floating-point values having at least one ``nan`` component compare as ``False``, complex floating-point values having ``nan`` components should be considered distinct. - - As ``-0`` and ``+0`` compare as ``True``, signed zeros should not be considered distinct, and the corresponding unique element will be implementation-dependent (e.g., an implementation could choose to return ``-0`` if ``-0`` occurs before ``+0``). - - Each ``nan`` value and each complex floating-point value having a ``nan`` component should have a count of one, while the counts for signed zeros should be aggregated as a single count. + The shapes of two of the output arrays for this function depend on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) can find this function difficult to implement without knowing array values. Accordingly, such libraries **may** choose to omit this function. See :ref:`data-dependent-output-shapes` section for more details. Parameters ---------- x: array - input array. If ``x`` has more than one dimension, the function must flatten ``x`` and return the unique elements of the flattened array. + input array. If ``x`` has more than one dimension, the function **must** flatten ``x`` and return the unique elements of the flattened array. Returns ------- out: Tuple[array, array] - a namedtuple `(values, counts)` whose - - - first element must have the field name ``values`` and must be a one-dimensional array containing the unique elements of ``x``. The array must have the same data type as ``x``. - - second element must have the field name `counts` and must be an array containing the number of times each unique element occurs in ``x``. The order of the returned counts must match the order of ``values``, such that a specific element in ``counts`` corresponds to the respective unique element in ``values``. The returned array must have same shape as ``values`` and must have the default array index data type. + a namedtuple `(values, counts)` whose - .. note:: - The order of unique elements is not specified and may vary between implementations. + - first element **must** have the field name ``values`` and **must** be a one-dimensional array containing the unique elements of ``x``. The array **must** have the same data type as ``x``. + - second element **must** have the field name `counts` and **must** be an array containing the number of times each unique element occurs in ``x``. The order of the returned counts **must** match the order of ``values``, such that a specific element in ``counts`` corresponds to the respective unique element in ``values``. The returned array **must** have same shape as ``values`` and **must** have the default array index data type. Notes ----- + - The order of unique elements returned by this function is unspecified and thus implementation-defined. As a consequence, element order **may** vary between implementations. + + - Uniqueness **should** be determined based on value equality (see :func:`~array_api.equal`). For input arrays having floating-point data types, value-based equality implies the following behavior. + + - As ``nan`` values compare as ``False``, ``nan`` values **should** be considered distinct. + - As complex floating-point values having at least one ``nan`` component compare as ``False``, complex floating-point values having ``nan`` components **should** be considered distinct. + - As ``-0`` and ``+0`` compare as ``True``, signed zeros **should not** be considered distinct, and the corresponding unique element **may** be implementation-defined (e.g., an implementation **may** choose to return ``-0`` if ``-0`` occurs before ``+0``). + + Each ``nan`` value and each complex floating-point value having a ``nan`` component **should** have a count of one, while the counts for signed zeros **should** be aggregated as a single count. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. .. versionchanged:: 2023.12 - Clarified flattening behavior and required the order of ``counts`` match the order of ``values``. + Clarified flattening behavior and required the order of ``counts`` match the order of ``values``. """ @@ -8573,43 +8573,40 @@ class unique_inverse[TArray: Array](Protocol): Returns the unique elements of an input array ``x`` and the indices from the set of unique elements that reconstruct ``x``. .. admonition:: Data-dependent output shape - :class: important + :class: important - The shapes of two of the output arrays for this function depend on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) may find this function difficult to implement without knowing array values. Accordingly, such libraries may choose to omit this function. See :ref:`data-dependent-output-shapes` section for more details. - - .. note:: - Uniqueness should be determined based on value equality (see :func:`~array_api.equal`). For input arrays having floating-point data types, value-based equality implies the following behavior. - - - As ``nan`` values compare as ``False``, ``nan`` values should be considered distinct. - - As complex floating-point values having at least one ``nan`` component compare as ``False``, complex floating-point values having ``nan`` components should be considered distinct. - - As ``-0`` and ``+0`` compare as ``True``, signed zeros should not be considered distinct, and the corresponding unique element will be implementation-dependent (e.g., an implementation could choose to return ``-0`` if ``-0`` occurs before ``+0``). - - As signed zeros are not distinct, using ``inverse_indices`` to reconstruct the input array is not guaranteed to return an array having the exact same values. + The shapes of two of the output arrays for this function depend on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) can find this function difficult to implement without knowing array values. Accordingly, such libraries **may** choose to omit this function. See :ref:`data-dependent-output-shapes` section for more details. Parameters ---------- x: array - input array. If ``x`` has more than one dimension, the function must flatten ``x`` and return the unique elements of the flattened array. + input array. If ``x`` has more than one dimension, the function **must** flatten ``x`` and return the unique elements of the flattened array. Returns ------- out: Tuple[array, array] - a namedtuple ``(values, inverse_indices)`` whose + a namedtuple ``(values, inverse_indices)`` whose - - first element must have the field name ``values`` and must be a one-dimensional array containing the unique elements of ``x``. The array must have the same data type as ``x``. - - second element must have the field name ``inverse_indices`` and must be an array containing the indices of ``values`` that reconstruct ``x``. The array must have the same shape as ``x`` and have the default array index data type. - - .. note:: - The order of unique elements is not specified and may vary between implementations. + - first element **must** have the field name ``values`` and **must** be a one-dimensional array containing the unique elements of ``x``. The array **must** have the same data type as ``x``. + - second element **must** have the field name ``inverse_indices`` and **must** be an array containing the indices of ``values`` that reconstruct ``x``. The array **must** have the same shape as ``x`` and have the default array index data type. Notes ----- + - The order of unique elements returned by this function is unspecified and thus implementation-defined. As a consequence, element order **may** vary between implementations. + + - Uniqueness **should** be determined based on value equality (see :func:`~array_api.equal`). For input arrays having floating-point data types, value-based equality implies the following behavior. + + - As ``nan`` values compare as ``False``, ``nan`` values **should** be considered distinct. + - As complex floating-point values having at least one ``nan`` component compare as ``False``, complex floating-point values having ``nan`` components **should** be considered distinct. + - As ``-0`` and ``+0`` compare as ``True``, signed zeros **should not** be considered distinct, and the corresponding unique element **may** be implementation-defined (e.g., an implementation **may** choose to return ``-0`` if ``-0`` occurs before ``+0``). + + As signed zeros are not distinct, using ``inverse_indices`` to reconstruct the input array is not guaranteed to return an array having the exact same values. .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. .. versionchanged:: 2023.12 - Clarified flattening behavior. + Clarified flattening behavior. """ @@ -8623,38 +8620,35 @@ class unique_values[TArray: Array](Protocol): Returns the unique elements of an input array ``x``. .. admonition:: Data-dependent output shape - :class: important - - The shapes of two of the output arrays for this function depend on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) may find this function difficult to implement without knowing array values. Accordingly, such libraries may choose to omit this function. See :ref:`data-dependent-output-shapes` section for more details. - - .. note:: - Uniqueness should be determined based on value equality (see :func:`~array_api.equal`). For input arrays having floating-point data types, value-based equality implies the following behavior. + :class: important - - As ``nan`` values compare as ``False``, ``nan`` values should be considered distinct. - - As complex floating-point values having at least one ``nan`` component compare as ``False``, complex floating-point values having ``nan`` components should be considered distinct. - - As ``-0`` and ``+0`` compare as ``True``, signed zeros should not be considered distinct, and the corresponding unique element will be implementation-dependent (e.g., an implementation could choose to return ``-0`` if ``-0`` occurs before ``+0``). + The shapes of two of the output arrays for this function depend on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) can find this function difficult to implement without knowing array values. Accordingly, such libraries **may** choose to omit this function. See :ref:`data-dependent-output-shapes` section for more details. Parameters ---------- x: array - input array. If ``x`` has more than one dimension, the function must flatten ``x`` and return the unique elements of the flattened array. + input array. If ``x`` has more than one dimension, the function **must** flatten ``x`` and return the unique elements of the flattened array. Returns ------- out: array - a one-dimensional array containing the set of unique elements in ``x``. The returned array must have the same data type as ``x``. - - .. note:: - The order of unique elements is not specified and may vary between implementations. + a one-dimensional array containing the set of unique elements in ``x``. The returned array **must** have the same data type as ``x``. Notes ----- + - The order of unique elements returned by this function is unspecified and thus implementation-defined. As a consequence, element order **may** vary between implementations. + + - Uniqueness **should** be determined based on value equality (see :func:`~array_api.equal`). For input arrays having floating-point data types, value-based equality implies the following behavior. + + - As ``nan`` values compare as ``False``, ``nan`` values **should** be considered distinct. + - As complex floating-point values having at least one ``nan`` component compare as ``False``, complex floating-point values having ``nan`` components **should** be considered distinct. + - As ``-0`` and ``+0`` compare as ``True``, signed zeros **should not** be considered distinct, and the corresponding unique element **may** be implementation-defined (e.g., an implementation **may** choose to return ``-0`` if ``-0`` occurs before ``+0``). .. versionchanged:: 2022.12 - Added complex data type support. + Added complex data type support. .. versionchanged:: 2023.12 - Required that the output array must be one-dimensional. + Required that the output array must be one-dimensional. """ @@ -8663,7 +8657,7 @@ def __call__(self, x: TArray, /) -> TArray: ... @runtime_checkable -class ArrayNamespace[TCapabilities, TDatatypes, TDefaultdatatypes, TSupportsbufferprotocol, TArray: Array, TDevice, TDtype](Protocol): +class ArrayNamespace[TArray: Array, TCapabilities, TDatatypes, TDefaultdatatypes, TDevice, TDtype](Protocol): astype: astype[TArray, TDevice, TDtype] "Copies an array to a specified data type irrespective of :ref:`type-promotion` rules.\n\n.. note::\n Casting floating-point ``NaN`` and ``infinity`` values to integral data types is not specified and is implementation-dependent.\n\n.. note::\n Casting a complex floating-point array to a real-valued data type should not be permitted.\n\n Historically, when casting a complex floating-point array to a real-valued data type, libraries such as NumPy have discarded imaginary components such that, for a complex floating-point array ``x``, ``astype(x)`` equals ``astype(real(x))``). This behavior is considered problematic as the choice to discard the imaginary component is arbitrary and introduces more than one way to achieve the same outcome (i.e., for a complex floating-point array ``x``, ``astype(x)`` and ``astype(real(x))`` versus only ``astype(imag(x))``). Instead, in order to avoid ambiguity and to promote clarity, this specification requires that array API consumers explicitly express which component should be cast to a specified real-valued data type.\n\n.. note::\n When casting a boolean input array to a real-valued data type, a value of ``True`` must cast to a real-valued number equal to ``1``, and a value of ``False`` must cast to a real-valued number equal to ``0``.\n\n When casting a boolean input array to a complex floating-point data type, a value of ``True`` must cast to a complex number equal to ``1 + 0j``, and a value of ``False`` must cast to a complex number equal to ``0 + 0j``.\n\n.. note::\n When casting a real-valued input array to ``bool``, a value of ``0`` must cast to ``False``, and a non-zero value must cast to ``True``.\n\n When casting a complex floating-point array to ``bool``, a value of ``0 + 0j`` must cast to ``False``, and all other values must cast to ``True``.\n\nParameters\n----------\nx: array\n array to cast.\ndtype: dtype\n desired data type.\ncopy: bool\n specifies whether to copy an array when the specified ``dtype`` matches the data type of the input array ``x``. If ``True``, a newly allocated array must always be returned (see :ref:`copy-keyword-argument`). If ``False`` and the specified ``dtype`` matches the data type of the input array, the input array must be returned; otherwise, a newly allocated array must be returned. Default: ``True``.\ndevice: Optional[device]\n device on which to place the returned array. If ``device`` is ``None``, the output array device must be inferred from ``x``. Default: ``None``.\n\nReturns\n-------\nout: array\n an array having the specified data type. The returned array must have the same shape as ``x``.\n\nNotes\n-----\n\n.. versionchanged:: 2022.12\n Added complex data type support.\n\n.. versionchanged:: 2023.12\n Added device keyword argument support." can_cast: can_cast[TArray, TDtype] @@ -8677,26 +8671,26 @@ class ArrayNamespace[TCapabilities, TDatatypes, TDefaultdatatypes, TSupportsbuff result_type: result_type[TArray, TDtype] "Returns the dtype that results from applying type promotion rules (see :ref:`type-promotion`) to the arguments.\n\nParameters\n----------\narrays_and_dtypes: Union[array, int, float, complex, bool, dtype]\n an arbitrary number of input arrays, scalars, and/or dtypes.\n\nReturns\n-------\nout: dtype\n the dtype resulting from an operation involving the input arrays, scalars, and/or dtypes.\n\nNotes\n-----\n\n- At least one argument must be an array or a dtype.\n- If provided array and/or dtype arguments having mixed data type kinds (e.g., integer and floating-point), the returned dtype is unspecified and thus implementation-dependent.\n- If at least one argument is an array, the function must determine the resulting dtype according to the type promotion graph of the array device which is shared among all array arguments. As not all devices can support all data types, full support for type promotion rules (see :ref:`type-promotion`) may not be possible. Accordingly, the returned dtype may differ from that determined from the complete type promotion graph defined in this specification (see :ref:`type-promotion`).\n- If two or more arguments are arrays belonging to different devices, behavior is unspecified and thus implementation-dependent. Conforming implementations may choose to ignore device attributes, raise an exception, or some other behavior.\n\n.. versionchanged:: 2024.12\n Added scalar argument support.\n\n.. versionchanged:: 2024.12\n Required that the application of type promotion rules must account for device context." cumulative_prod: cumulative_prod[TArray, TDtype] - "Calculates the cumulative product of elements in the input array ``x``.\n\nParameters\n----------\nx: array\n input array. Should have one or more dimensions (axes). Should have a numeric data type.\naxis: Optional[int]\n axis along which a cumulative product must be computed. If ``axis`` is negative, the function must determine the axis along which to compute a cumulative product by counting from the last dimension.\n\n If ``x`` is a one-dimensional array, providing an ``axis`` is optional; however, if ``x`` has more than one dimension, providing an ``axis`` is required.\n\ndtype: Optional[dtype]\n data type of the returned array. If ``None``, the returned array must have the same data type as ``x``, unless ``x`` has an integer data type supporting a smaller range of values than the default integer data type (e.g., ``x`` has an ``int16`` or ``uint32`` data type and the default integer data type is ``int64``). In those latter cases:\n\n - if ``x`` has a signed integer data type (e.g., ``int16``), the returned array must have the default integer data type.\n - if ``x`` has an unsigned integer data type (e.g., ``uint16``), the returned array must have an unsigned integer data type having the same number of bits as the default integer data type (e.g., if the default integer data type is ``int32``, the returned array must have a ``uint32`` data type).\n\n If the data type (either specified or resolved) differs from the data type of ``x``, the input array should be cast to the specified data type before computing the product (rationale: the ``dtype`` keyword argument is intended to help prevent overflows). Default: ``None``.\n\ninclude_initial: bool\n boolean indicating whether to include the initial value as the first value in the output. By convention, the initial value must be the multiplicative identity (i.e., one). Default: ``False``.\n\nReturns\n-------\nout: array\n an array containing the cumulative products. The returned array must have a data type as described by the ``dtype`` parameter above.\n\n Let ``N`` be the size of the axis along which to compute the cumulative product. The returned array must have a shape determined according to the following rules:\n\n - if ``include_initial`` is ``True``, the returned array must have the same shape as ``x``, except the size of the axis along which to compute the cumulative product must be ``N+1``.\n - if ``include_initial`` is ``False``, the returned array must have the same shape as ``x``.\n\nNotes\n-----\n\n- When ``x`` is a zero-dimensional array, behavior is unspecified and thus implementation-defined.\n\n**Special Cases**\n\nFor both real-valued and complex floating-point operands, special cases must be handled as if the operation is implemented by successive application of :func:`~array_api.multiply`.\n\n.. versionadded:: 2024.12" + "Calculates the cumulative product of elements in the input array ``x``.\n\nParameters\n----------\nx: array\n input array. **Should** have one or more dimensions (axes). **Should** have a numeric data type.\naxis: Optional[int]\n axis along which to compute the cumulative product. A valid axis **must** be an integer on the interval ``[-N, N)``, where ``N`` is the number of axes in ``x``. If an axis is specified as a negative integer, the function **must** determine the axis along which to perform the operation by counting backward from the last axis (where ``-1`` refers to the last axis). If provided an invalid axis, the function **must** raise an exception.\n\n If ``x`` is a one-dimensional array, providing an ``axis`` **must** be optional; however, if ``x`` has more than one dimension, providing an ``axis`` **must** be required.\n\ndtype: Optional[dtype]\n data type of the returned array. If ``None``, the returned array **must** have the same data type as ``x``, unless ``x`` has an integer data type supporting a smaller range of values than the default integer data type (e.g., ``x`` has an ``int16`` or ``uint32`` data type and the default integer data type is ``int64``). In those latter cases:\n\n - if ``x`` has a signed integer data type (e.g., ``int16``), the returned array **must** have the default integer data type.\n - if ``x`` has an unsigned integer data type (e.g., ``uint16``), the returned array **must** have an unsigned integer data type having the same number of bits as the default integer data type (e.g., if the default integer data type is ``int32``, the returned array **must** have a ``uint32`` data type).\n\n If the data type (either specified or resolved) differs from the data type of ``x``, the input array **should** be cast to the specified data type before computing the product (rationale: the ``dtype`` keyword argument is intended to help prevent overflows). Default: ``None``.\n\ninclude_initial: bool\n boolean indicating whether to include the initial value as the first value in the output. By convention, the initial value **must** be the multiplicative identity (i.e., one). Default: ``False``.\n\nReturns\n-------\nout: array\n an array containing the cumulative products. The returned array **must** have a data type as described by the ``dtype`` parameter above.\n\n Let ``M`` be the size of the axis along which to compute the cumulative product. The returned array **must** have a shape determined according to the following rules:\n\n - if ``include_initial`` is ``True``, the returned array **must** have the same shape as ``x``, except the size of the axis along which to compute the cumulative product **must** be ``M+1``.\n - if ``include_initial`` is ``False``, the returned array **must** have the same shape as ``x``.\n\nNotes\n-----\n\n- When ``x`` is a zero-dimensional array, behavior is unspecified and thus implementation-defined.\n\n**Special Cases**\n\nFor both real-valued and complex floating-point operands, special cases **must** be handled as if the operation is implemented by successive application of :func:`~array_api.multiply`.\n\n.. versionadded:: 2024.12" cumulative_sum: cumulative_sum[TArray, TDtype] - "Calculates the cumulative sum of elements in the input array ``x``.\n\nParameters\n----------\nx: array\n input array. Should have one or more dimensions (axes). Should have a numeric data type.\naxis: Optional[int]\n axis along which a cumulative sum must be computed. If ``axis`` is negative, the function must determine the axis along which to compute a cumulative sum by counting from the last dimension.\n\n If ``x`` is a one-dimensional array, providing an ``axis`` is optional; however, if ``x`` has more than one dimension, providing an ``axis`` is required.\n\ndtype: Optional[dtype]\n data type of the returned array. If ``None``, the returned array must have the same data type as ``x``, unless ``x`` has an integer data type supporting a smaller range of values than the default integer data type (e.g., ``x`` has an ``int16`` or ``uint32`` data type and the default integer data type is ``int64``). In those latter cases:\n\n - if ``x`` has a signed integer data type (e.g., ``int16``), the returned array must have the default integer data type.\n - if ``x`` has an unsigned integer data type (e.g., ``uint16``), the returned array must have an unsigned integer data type having the same number of bits as the default integer data type (e.g., if the default integer data type is ``int32``, the returned array must have a ``uint32`` data type).\n\n If the data type (either specified or resolved) differs from the data type of ``x``, the input array should be cast to the specified data type before computing the sum (rationale: the ``dtype`` keyword argument is intended to help prevent overflows). Default: ``None``.\n\ninclude_initial: bool\n boolean indicating whether to include the initial value as the first value in the output. By convention, the initial value must be the additive identity (i.e., zero). Default: ``False``.\n\nReturns\n-------\nout: array\n an array containing the cumulative sums. The returned array must have a data type as described by the ``dtype`` parameter above.\n\n Let ``N`` be the size of the axis along which to compute the cumulative sum. The returned array must have a shape determined according to the following rules:\n\n - if ``include_initial`` is ``True``, the returned array must have the same shape as ``x``, except the size of the axis along which to compute the cumulative sum must be ``N+1``.\n - if ``include_initial`` is ``False``, the returned array must have the same shape as ``x``.\n\nNotes\n-----\n\n- When ``x`` is a zero-dimensional array, behavior is unspecified and thus implementation-defined.\n\n**Special Cases**\n\nFor both real-valued and complex floating-point operands, special cases must be handled as if the operation is implemented by successive application of :func:`~array_api.add`.\n\n.. versionadded:: 2023.12\n\n.. versionchanged:: 2024.12\n Behavior when providing a zero-dimensional array is explicitly left unspecified." + "Calculates the cumulative sum of elements in the input array ``x``.\n\nParameters\n----------\nx: array\n input array. **Should** have one or more dimensions (axes). **Should** have a numeric data type.\naxis: Optional[int]\n axis along which to compute the cumulative sum. A valid axis **must** be an integer on the interval ``[-N, N)``, where ``N`` is the number of axes in ``x``. If an axis is specified as a negative integer, the function **must** determine the axis along which to perform the operation by counting backward from the last axis (where ``-1`` refers to the last axis). If provided an invalid axis, the function **must** raise an exception.\n\n If ``x`` is a one-dimensional array, providing an ``axis`` **must** be optional; however, if ``x`` has more than one dimension, providing an ``axis`` **must** be required.\n\ndtype: Optional[dtype]\n data type of the returned array. If ``None``, the returned array **must** have the same data type as ``x``, unless ``x`` has an integer data type supporting a smaller range of values than the default integer data type (e.g., ``x`` has an ``int16`` or ``uint32`` data type and the default integer data type is ``int64``). In those latter cases:\n\n - if ``x`` has a signed integer data type (e.g., ``int16``), the returned array **must** have the default integer data type.\n - if ``x`` has an unsigned integer data type (e.g., ``uint16``), the returned array **must** have an unsigned integer data type having the same number of bits as the default integer data type (e.g., if the default integer data type is ``int32``, the returned array **must** have a ``uint32`` data type).\n\n If the data type (either specified or resolved) differs from the data type of ``x``, the input array **should** be cast to the specified data type before computing the sum (rationale: the ``dtype`` keyword argument is intended to help prevent overflows). Default: ``None``.\n\ninclude_initial: bool\n boolean indicating whether to include the initial value as the first value in the output. By convention, the initial value **must** be the additive identity (i.e., zero). Default: ``False``.\n\nReturns\n-------\nout: array\n an array containing the cumulative sums. The returned array **must** have a data type as described by the ``dtype`` parameter above.\n\n Let ``M`` be the size of the axis along which to compute the cumulative sum. The returned array **must** have a shape determined according to the following rules:\n\n - if ``include_initial`` is ``True``, the returned array **must** have the same shape as ``x``, except the size of the axis along which to compute the cumulative sum **must** be ``M+1``.\n - if ``include_initial`` is ``False``, the returned array **must** have the same shape as ``x``.\n\nNotes\n-----\n\n- When ``x`` is a zero-dimensional array, behavior is unspecified and thus implementation-defined.\n\n**Special Cases**\n\nFor both real-valued and complex floating-point operands, special cases **must** be handled as if the operation is implemented by successive application of :func:`~array_api.add`.\n\n.. versionadded:: 2023.12\n\n.. versionchanged:: 2024.12\n Behavior when providing a zero-dimensional array is explicitly left unspecified." max: max[TArray,] - "Calculates the maximum value of the input array ``x``.\n\nParameters\n----------\nx: array\n input array. Should have a real-valued data type.\naxis: Optional[Union[int, Tuple[int, ...]]]\n axis or axes along which maximum values must be computed. By default, the maximum value must be computed over the entire array. If a tuple of integers, maximum values must be computed over multiple axes. Default: ``None``.\nkeepdims: bool\n if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``.\n\nReturns\n-------\nout: array\n if the maximum value was computed over the entire array, a zero-dimensional array containing the maximum value; otherwise, a non-zero-dimensional array containing the maximum values. The returned array must have the same data type as ``x``.\n\nNotes\n-----\n\nWhen the number of elements over which to compute the maximum value is zero, the maximum value is implementation-defined. Specification-compliant libraries may choose to raise an error, return a sentinel value (e.g., if ``x`` is a floating-point input array, return ``NaN``), or return the minimum possible value for the input array ``x`` data type (e.g., if ``x`` is a floating-point array, return ``-infinity``).\n\nThe order of signed zeros is unspecified and thus implementation-defined. When choosing between ``-0`` or ``+0`` as a maximum value, specification-compliant libraries may choose to return either value.\n\nFor backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-defined (see :ref:`complex-number-ordering`).\n\n**Special Cases**\n\nFor floating-point operands,\n\n- If ``x_i`` is ``NaN``, the maximum value is ``NaN`` (i.e., ``NaN`` values propagate).\n\n.. versionchanged:: 2023.12\n Clarified that the order of signed zeros is implementation-defined." + "Calculates the maximum value of the input array ``x``.\n\nParameters\n----------\nx: array\n input array. **Should** have a real-valued data type.\naxis: Optional[Union[int, Tuple[int, ...]]]\n axis or axes along which to compute maximum values. A valid axis **must** be an integer on the interval ``[-N, N)``, where ``N`` is the number of axes in ``x``. If an axis is specified as a negative integer, the function **must** determine the axis along which to perform the operation by counting backward from the last axis (where ``-1`` refers to the last axis). If provided an invalid axis, the function **must** raise an exception. By default, the maximum value **must** be computed over the entire array. If a tuple of integers, maximum values **must** be computed over multiple axes. Default: ``None``.\nkeepdims: bool\n if ``True``, the reduced axes (dimensions) **must** be included in the result as singleton dimensions, and, accordingly, the result **must** be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) **must** not be included in the result. Default: ``False``.\n\nReturns\n-------\nout: array\n if the maximum value is computed over the entire array, a zero-dimensional array containing the maximum value; otherwise, a non-zero-dimensional array containing the maximum values. The returned array **must** have the same data type as ``x``.\n\nNotes\n-----\n\n- When the number of elements over which to compute the maximum value is zero, the maximum value is implementation-defined. Specification-compliant libraries **may** choose to raise an error, return a sentinel value (e.g., if ``x`` is a floating-point input array, return ``NaN``), or return the minimum possible value for the input array ``x`` data type (e.g., if ``x`` is a floating-point array, return ``-infinity``).\n\n- The order of signed zeros is unspecified and thus implementation-defined. When choosing between ``-0`` or ``+0`` as a maximum value, specification-compliant libraries **may** choose to return either value.\n\n- For backward compatibility, conforming implementations **may** support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-defined (see :ref:`complex-number-ordering`).\n\n**Special Cases**\n\nFor floating-point operands,\n\n- If ``x_i`` is ``NaN``, the maximum value **must** be ``NaN`` (i.e., ``NaN`` values propagate).\n\n.. versionchanged:: 2023.12\n Clarified that the order of signed zeros is implementation-defined." mean: mean[TArray,] - "Calculates the arithmetic mean of the input array ``x``.\n\nParameters\n----------\nx: array\n input array. Should have a floating-point data type.\naxis: Optional[Union[int, Tuple[int, ...]]]\n axis or axes along which arithmetic means must be computed. By default, the mean must be computed over the entire array. If a tuple of integers, arithmetic means must be computed over multiple axes. Default: ``None``.\nkeepdims: bool\n if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``.\n\nReturns\n-------\nout: array\n if the arithmetic mean was computed over the entire array, a zero-dimensional array containing the arithmetic mean; otherwise, a non-zero-dimensional array containing the arithmetic means. The returned array must have the same data type as ``x``.\n\n .. note::\n While this specification recommends that this function only accept input arrays having a floating-point data type, specification-compliant array libraries may choose to accept input arrays having an integer data type. While mixed data type promotion is implementation-defined, if the input array ``x`` has an integer data type, the returned array must have the default real-valued floating-point data type.\n\nNotes\n-----\n\n**Special Cases**\n\nLet ``N`` equal the number of elements over which to compute the arithmetic mean. For real-valued operands,\n\n- If ``N`` is ``0``, the arithmetic mean is ``NaN``.\n- If ``x_i`` is ``NaN``, the arithmetic mean is ``NaN`` (i.e., ``NaN`` values propagate).\n\nFor complex floating-point operands, real-valued floating-point special cases should independently apply to the real and imaginary component operations involving real numbers. For example, let ``a = real(x_i)`` and ``b = imag(x_i)``, and\n\n- If ``N`` is ``0``, the arithmetic mean is ``NaN + NaN j``.\n- If ``a`` is ``NaN``, the real component of the result is ``NaN``.\n- Similarly, if ``b`` is ``NaN``, the imaginary component of the result is ``NaN``.\n\n.. note::\n Array libraries, such as NumPy, PyTorch, and JAX, currently deviate from this specification in their handling of components which are ``NaN`` when computing the arithmetic mean. In general, consumers of array libraries implementing this specification should use :func:`~array_api.isnan` to test whether the result of computing the arithmetic mean over an array have a complex floating-point data type is ``NaN``, rather than relying on ``NaN`` propagation of individual components.\n\n.. versionchanged:: 2024.12\n Added complex data type support." + "Calculates the arithmetic mean of the input array ``x``.\n\nParameters\n----------\nx: array\n input array. **Should** have a floating-point data type.\naxis: Optional[Union[int, Tuple[int, ...]]]\n axis or axes along which to compute arithmetic means. By default, the mean **must** be computed over the entire array. If a tuple of integers, arithmetic means **must** be computed over multiple axes. A valid axis **must** be an integer on the interval ``[-N, N)``, where ``N`` is the number of axes in ``x``. If an axis is specified as a negative integer, the function **must** determine the axis along which to perform the operation by counting backward from the last axis (where ``-1`` refers to the last axis). If provided an invalid axis, the function **must** raise an exception. Default: ``None``.\nkeepdims: bool\n if ``True``, the reduced axes (dimensions) **must** be included in the result as singleton dimensions, and, accordingly, the result **must** be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) **must** not be included in the result. Default: ``False``.\n\nReturns\n-------\nout: array\n if the arithmetic mean is computed over the entire array, a zero-dimensional array containing the arithmetic mean; otherwise, a non-zero-dimensional array containing the arithmetic means. The returned array **must** have the same data type as ``x``.\n\nNotes\n-----\n\n- While this specification recommends that this function only accept input arrays having a floating-point data type, specification-compliant array libraries **may** choose to accept input arrays having an integer data type. While mixed data type promotion is implementation-defined, if the input array ``x`` has an integer data type, the returned array **must** have the default real-valued floating-point data type.\n\n**Special Cases**\n\nLet ``M`` equal the number of elements over which to compute the arithmetic mean. For real-valued operands,\n\n- If ``M`` is ``0``, the arithmetic mean **must** be ``NaN``.\n- If ``x_i`` is ``NaN``, the arithmetic mean **must** be ``NaN`` (i.e., ``NaN`` values propagate).\n\nFor complex floating-point operands, real-valued floating-point special cases **should** independently apply to the real and imaginary component operations involving real numbers. For example, let ``a = real(x_i)`` and ``b = imag(x_i)``, and\n\n- If ``M`` is ``0``, the arithmetic mean **must** be ``NaN + NaN j``.\n- If ``a`` is ``NaN``, the real component of the result **must** be ``NaN``.\n- Similarly, if ``b`` is ``NaN``, the imaginary component of the result **must** be ``NaN``.\n\n.. note::\n Array libraries, such as NumPy, PyTorch, and JAX, currently deviate from this specification in their handling of components which are ``NaN`` when computing the arithmetic mean. In general, consumers of array libraries implementing this specification are recommended to use :func:`~array_api.isnan` to test whether the result of computing the arithmetic mean over an array have a complex floating-point data type is ``NaN``, rather than relying on ``NaN`` propagation of individual components.\n\n.. versionchanged:: 2024.12\n Added complex data type support." min: min[TArray,] - "Calculates the minimum value of the input array ``x``.\n\nParameters\n----------\nx: array\n input array. Should have a real-valued data type.\naxis: Optional[Union[int, Tuple[int, ...]]]\n axis or axes along which minimum values must be computed. By default, the minimum value must be computed over the entire array. If a tuple of integers, minimum values must be computed over multiple axes. Default: ``None``.\nkeepdims: bool\n if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``.\n\nReturns\n-------\nout: array\n if the minimum value was computed over the entire array, a zero-dimensional array containing the minimum value; otherwise, a non-zero-dimensional array containing the minimum values. The returned array must have the same data type as ``x``.\n\nNotes\n-----\n\nWhen the number of elements over which to compute the minimum value is zero, the minimum value is implementation-defined. Specification-compliant libraries may choose to raise an error, return a sentinel value (e.g., if ``x`` is a floating-point input array, return ``NaN``), or return the maximum possible value for the input array ``x`` data type (e.g., if ``x`` is a floating-point array, return ``+infinity``).\n\nThe order of signed zeros is unspecified and thus implementation-defined. When choosing between ``-0`` or ``+0`` as a minimum value, specification-compliant libraries may choose to return either value.\n\nFor backward compatibility, conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-defined (see :ref:`complex-number-ordering`).\n\n**Special Cases**\n\nFor floating-point operands,\n\n- If ``x_i`` is ``NaN``, the minimum value is ``NaN`` (i.e., ``NaN`` values propagate).\n\n.. versionchanged:: 2023.12\n Clarified that the order of signed zeros is implementation-defined." + "Calculates the minimum value of the input array ``x``.\n\nParameters\n----------\nx: array\n input array. **Should** have a real-valued data type.\naxis: Optional[Union[int, Tuple[int, ...]]]\n axis or axes along which to compute minimum values. By default, the minimum value **must** be computed over the entire array. If a tuple of integers, minimum values **must** be computed over multiple axes. A valid axis **must** be an integer on the interval ``[-N, N)``, where ``N`` is the number of axes in ``x``. If an axis is specified as a negative integer, the function **must** determine the axis along which to perform the operation by counting backward from the last axis (where ``-1`` refers to the last axis). If provided an invalid axis, the function **must** raise an exception. Default: ``None``.\nkeepdims: bool\n if ``True``, the reduced axes (dimensions) **must** be included in the result as singleton dimensions, and, accordingly, the result **must** be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) **must** not be included in the result. Default: ``False``.\n\nReturns\n-------\nout: array\n if the minimum value is computed over the entire array, a zero-dimensional array containing the minimum value; otherwise, a non-zero-dimensional array containing the minimum values. The returned array **must** have the same data type as ``x``.\n\nNotes\n-----\n\n- When the number of elements over which to compute the minimum value is zero, the minimum value is implementation-defined. Specification-compliant libraries **may** choose to raise an error, return a sentinel value (e.g., if ``x`` is a floating-point input array, return ``NaN``), or return the maximum possible value for the input array ``x`` data type (e.g., if ``x`` is a floating-point array, return ``+infinity``).\n\n- The order of signed zeros is unspecified and thus implementation-defined. When choosing between ``-0`` or ``+0`` as a minimum value, specification-compliant libraries **may** choose to return either value.\n\n- For backward compatibility, conforming implementations **may** support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-defined (see :ref:`complex-number-ordering`).\n\n**Special Cases**\n\nFor floating-point operands,\n\n- If ``x_i`` is ``NaN``, the minimum value **must** be ``NaN`` (i.e., ``NaN`` values propagate).\n\n.. versionchanged:: 2023.12\n Clarified that the order of signed zeros is implementation-defined." prod: prod[TArray, TDtype] - "Calculates the product of input array ``x`` elements.\n\nParameters\n----------\nx: array\n input array. Should have a numeric data type.\naxis: Optional[Union[int, Tuple[int, ...]]]\n axis or axes along which products must be computed. By default, the product must be computed over the entire array. If a tuple of integers, products must be computed over multiple axes. Default: ``None``.\n\ndtype: Optional[dtype]\n data type of the returned array. If ``None``, the returned array must have the same data type as ``x``, unless ``x`` has an integer data type supporting a smaller range of values than the default integer data type (e.g., ``x`` has an ``int16`` or ``uint32`` data type and the default integer data type is ``int64``). In those latter cases:\n\n - if ``x`` has a signed integer data type (e.g., ``int16``), the returned array must have the default integer data type.\n - if ``x`` has an unsigned integer data type (e.g., ``uint16``), the returned array must have an unsigned integer data type having the same number of bits as the default integer data type (e.g., if the default integer data type is ``int32``, the returned array must have a ``uint32`` data type).\n\n If the data type (either specified or resolved) differs from the data type of ``x``, the input array should be cast to the specified data type before computing the sum (rationale: the ``dtype`` keyword argument is intended to help prevent overflows). Default: ``None``.\n\nkeepdims: bool\n if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``.\n\nReturns\n-------\nout: array\n if the product was computed over the entire array, a zero-dimensional array containing the product; otherwise, a non-zero-dimensional array containing the products. The returned array must have a data type as described by the ``dtype`` parameter above.\n\nNotes\n-----\n\n**Special Cases**\n\nLet ``N`` equal the number of elements over which to compute the product.\n\n- If ``N`` is ``0``, the product is `1` (i.e., the empty product).\n\nFor both real-valued and complex floating-point operands, special cases must be handled as if the operation is implemented by successive application of :func:`~array_api.multiply`.\n\n.. versionchanged:: 2022.12\n Added complex data type support.\n\n.. versionchanged:: 2023.12\n Required the function to return a floating-point array having the same data type as the input array when provided a floating-point array." + "Calculates the product of input array ``x`` elements.\n\nParameters\n----------\nx: array\n input array. **Should** have a numeric data type.\naxis: Optional[Union[int, Tuple[int, ...]]]\n axis or axes along which to compute products. By default, the product **must** be computed over the entire array. If a tuple of integers, products **must** be computed over multiple axes. A valid axis **must** be an integer on the interval ``[-N, N)``, where ``N`` is the number of axes in ``x``. If an axis is specified as a negative integer, the function **must** determine the axis along which to perform the operation by counting backward from the last axis (where ``-1`` refers to the last axis). If provided an invalid axis, the function **must** raise an exception. Default: ``None``.\n\ndtype: Optional[dtype]\n data type of the returned array. If ``None``, the returned array **must** have the same data type as ``x``, unless ``x`` has an integer data type supporting a smaller range of values than the default integer data type (e.g., ``x`` has an ``int16`` or ``uint32`` data type and the default integer data type is ``int64``). In those latter cases:\n\n - if ``x`` has a signed integer data type (e.g., ``int16``), the returned array **must** have the default integer data type.\n - if ``x`` has an unsigned integer data type (e.g., ``uint16``), the returned array **must** have an unsigned integer data type having the same number of bits as the default integer data type (e.g., if the default integer data type is ``int32``, the returned array **must** have a ``uint32`` data type).\n\n If the data type (either specified or resolved) differs from the data type of ``x``, the input array **should** be cast to the specified data type before computing the sum (rationale: the ``dtype`` keyword argument is intended to help prevent overflows). Default: ``None``.\n\nkeepdims: bool\n if ``True``, the reduced axes (dimensions) **must** be included in the result as singleton dimensions, and, accordingly, the result **must** be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) **must** not be included in the result. Default: ``False``.\n\nReturns\n-------\nout: array\n if the product is computed over the entire array, a zero-dimensional array containing the product; otherwise, a non-zero-dimensional array containing the products. The returned array **must** have a data type as described by the ``dtype`` parameter above.\n\nNotes\n-----\n\n**Special Cases**\n\nLet ``M`` equal the number of elements over which to compute the product.\n\n- If ``M`` is ``0``, the product **must** be `1` (i.e., the empty product).\n\nFor both real-valued and complex floating-point operands, special cases **must** be handled as if the operation is implemented by successive application of :func:`~array_api.multiply`.\n\n.. versionchanged:: 2022.12\n Added complex data type support.\n\n.. versionchanged:: 2023.12\n Required the function to return a floating-point array having the same data type as the input array when provided a floating-point array." std: std[TArray,] - "Calculates the standard deviation of the input array ``x``.\n\nParameters\n----------\nx: array\n input array. Should have a real-valued floating-point data type.\naxis: Optional[Union[int, Tuple[int, ...]]]\n axis or axes along which standard deviations must be computed. By default, the standard deviation must be computed over the entire array. If a tuple of integers, standard deviations must be computed over multiple axes. Default: ``None``.\ncorrection: Union[int, float]\n degrees of freedom adjustment. Setting this parameter to a value other than ``0`` has the effect of adjusting the divisor during the calculation of the standard deviation according to ``N-c`` where ``N`` corresponds to the total number of elements over which the standard deviation is computed and ``c`` corresponds to the provided degrees of freedom adjustment. When computing the standard deviation of a population, setting this parameter to ``0`` is the standard choice (i.e., the provided array contains data constituting an entire population). When computing the corrected sample standard deviation, setting this parameter to ``1`` is the standard choice (i.e., the provided array contains data sampled from a larger population; this is commonly referred to as Bessel's correction). Default: ``0``.\nkeepdims: bool\n if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``.\n\nReturns\n-------\nout: array\n if the standard deviation was computed over the entire array, a zero-dimensional array containing the standard deviation; otherwise, a non-zero-dimensional array containing the standard deviations. The returned array must have the same data type as ``x``.\n\n .. note::\n While this specification recommends that this function only accept input arrays having a real-valued floating-point data type, specification-compliant array libraries may choose to accept input arrays having an integer data type. While mixed data type promotion is implementation-defined, if the input array ``x`` has an integer data type, the returned array must have the default real-valued floating-point data type.\n\nNotes\n-----\n\n**Special Cases**\n\nLet ``N`` equal the number of elements over which to compute the standard deviation.\n\n- If ``N - correction`` is less than or equal to ``0``, the standard deviation is ``NaN``.\n- If ``x_i`` is ``NaN``, the standard deviation is ``NaN`` (i.e., ``NaN`` values propagate)." + "Calculates the standard deviation of the input array ``x``.\n\nParameters\n----------\nx: array\n input array. **Should** have a real-valued floating-point data type.\naxis: Optional[Union[int, Tuple[int, ...]]]\n axis or axes along which to compute standard deviations. By default, the standard deviation **must** be computed over the entire array. If a tuple of integers, standard deviations **must** be computed over multiple axes. A valid axis **must** be an integer on the interval ``[-N, N)``, where ``N`` is the number of axes in ``x``. If an axis is specified as a negative integer, the function **must** determine the axis along which to perform the operation by counting backward from the last axis (where ``-1`` refers to the last axis). If provided an invalid axis, the function **must** raise an exception. Default: ``None``.\ncorrection: Union[int, float]\n degrees of freedom adjustment. Setting this parameter to a value other than ``0`` has the effect of adjusting the divisor during the calculation of the standard deviation according to ``M-c`` where ``M`` corresponds to the total number of elements over which the standard deviation is computed and ``c`` corresponds to the provided degrees of freedom adjustment. When computing the standard deviation of a population, setting this parameter to ``0`` is the standard choice (i.e., the provided array contains data constituting an entire population). When computing the corrected sample standard deviation, setting this parameter to ``1`` is the standard choice (i.e., the provided array contains data sampled from a larger population; this is commonly referred to as Bessel's correction). Default: ``0``.\nkeepdims: bool\n if ``True``, the reduced axes (dimensions) **must** be included in the result as singleton dimensions, and, accordingly, the result **must** be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) **must** not be included in the result. Default: ``False``.\n\nReturns\n-------\nout: array\n if the standard deviation is computed over the entire array, a zero-dimensional array containing the standard deviation; otherwise, a non-zero-dimensional array containing the standard deviations. The returned array **must** have the same data type as ``x``.\n\nNotes\n-----\n\n- While this specification recommends that this function only accept input arrays having a real-valued floating-point data type, specification-compliant array libraries **may** choose to accept input arrays having an integer data type. While mixed data type promotion is implementation-defined, if the input array ``x`` has an integer data type, the returned array **must** have the default real-valued floating-point data type.\n\n**Special Cases**\n\nLet ``M`` equal the number of elements over which to compute the standard deviation.\n\n- If ``M - correction`` is less than or equal to ``0``, the standard deviation **must** be ``NaN``.\n- If ``x_i`` is ``NaN``, the standard deviation **must** be ``NaN`` (i.e., ``NaN`` values propagate)." sum: sum[TArray, TDtype] - "Calculates the sum of the input array ``x``.\n\nParameters\n----------\nx: array\n input array. Should have a numeric data type.\naxis: Optional[Union[int, Tuple[int, ...]]]\n axis or axes along which sums must be computed. By default, the sum must be computed over the entire array. If a tuple of integers, sums must be computed over multiple axes. Default: ``None``.\n\ndtype: Optional[dtype]\n data type of the returned array. If ``None``, the returned array must have the same data type as ``x``, unless ``x`` has an integer data type supporting a smaller range of values than the default integer data type (e.g., ``x`` has an ``int16`` or ``uint32`` data type and the default integer data type is ``int64``). In those latter cases:\n\n - if ``x`` has a signed integer data type (e.g., ``int16``), the returned array must have the default integer data type.\n - if ``x`` has an unsigned integer data type (e.g., ``uint16``), the returned array must have an unsigned integer data type having the same number of bits as the default integer data type (e.g., if the default integer data type is ``int32``, the returned array must have a ``uint32`` data type).\n\n If the data type (either specified or resolved) differs from the data type of ``x``, the input array should be cast to the specified data type before computing the sum (rationale: the ``dtype`` keyword argument is intended to help prevent overflows). Default: ``None``.\n\nkeepdims: bool\n if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``.\n\nReturns\n-------\nout: array\n if the sum was computed over the entire array, a zero-dimensional array containing the sum; otherwise, an array containing the sums. The returned array must have a data type as described by the ``dtype`` parameter above.\n\nNotes\n-----\n\n**Special Cases**\n\nLet ``N`` equal the number of elements over which to compute the sum.\n\n- If ``N`` is ``0``, the sum is ``0`` (i.e., the empty sum).\n\nFor both real-valued and complex floating-point operands, special cases must be handled as if the operation is implemented by successive application of :func:`~array_api.add`.\n\n.. versionchanged:: 2022.12\n Added complex data type support.\n\n.. versionchanged:: 2023.12\n Required the function to return a floating-point array having the same data type as the input array when provided a floating-point array." + "Calculates the sum of the input array ``x``.\n\nParameters\n----------\nx: array\n input array. **Should** have a numeric data type.\naxis: Optional[Union[int, Tuple[int, ...]]]\n axis or axes along which sums **must** be computed. By default, the sum **must** be computed over the entire array. If a tuple of integers, sums **must** be computed over multiple axes. A valid axis **must** be an integer on the interval ``[-N, N)``, where ``N`` is the number of axes in ``x``. If an axis is specified as a negative integer, the function **must** determine the axis along which to perform the operation by counting backward from the last axis (where ``-1`` refers to the last axis). If provided an invalid axis, the function **must** raise an exception. Default: ``None``.\n\ndtype: Optional[dtype]\n data type of the returned array. If ``None``, the returned array **must** have the same data type as ``x``, unless ``x`` has an integer data type supporting a smaller range of values than the default integer data type (e.g., ``x`` has an ``int16`` or ``uint32`` data type and the default integer data type is ``int64``). In those latter cases:\n\n - if ``x`` has a signed integer data type (e.g., ``int16``), the returned array **must** have the default integer data type.\n - if ``x`` has an unsigned integer data type (e.g., ``uint16``), the returned array **must** have an unsigned integer data type having the same number of bits as the default integer data type (e.g., if the default integer data type is ``int32``, the returned array **must** have a ``uint32`` data type).\n\n If the data type (either specified or resolved) differs from the data type of ``x``, the input array **should** be cast to the specified data type before computing the sum (rationale: the ``dtype`` keyword argument is intended to help prevent overflows). Default: ``None``.\n\nkeepdims: bool\n if ``True``, the reduced axes (dimensions) **must** be included in the result as singleton dimensions, and, accordingly, the result **must** be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) **must** not be included in the result. Default: ``False``.\n\nReturns\n-------\nout: array\n if the sum is computed over the entire array, a zero-dimensional array containing the sum; otherwise, an array containing the sums. The returned array **must** have a data type as described by the ``dtype`` parameter above.\n\nNotes\n-----\n\n**Special Cases**\n\nLet ``M`` equal the number of elements over which to compute the sum.\n\n- If ``M`` is ``0``, the sum **must** be ``0`` (i.e., the empty sum).\n\nFor both real-valued and complex floating-point operands, special cases **must** be handled as if the operation is implemented by successive application of :func:`~array_api.add`.\n\n.. versionchanged:: 2022.12\n Added complex data type support.\n\n.. versionchanged:: 2023.12\n Required the function to return a floating-point array having the same data type as the input array when provided a floating-point array." var: var[TArray,] - "Calculates the variance of the input array ``x``.\n\nParameters\n----------\nx: array\n input array. Should have a real-valued floating-point data type.\naxis: Optional[Union[int, Tuple[int, ...]]]\n axis or axes along which variances must be computed. By default, the variance must be computed over the entire array. If a tuple of integers, variances must be computed over multiple axes. Default: ``None``.\ncorrection: Union[int, float]\n degrees of freedom adjustment. Setting this parameter to a value other than ``0`` has the effect of adjusting the divisor during the calculation of the variance according to ``N-c`` where ``N`` corresponds to the total number of elements over which the variance is computed and ``c`` corresponds to the provided degrees of freedom adjustment. When computing the variance of a population, setting this parameter to ``0`` is the standard choice (i.e., the provided array contains data constituting an entire population). When computing the unbiased sample variance, setting this parameter to ``1`` is the standard choice (i.e., the provided array contains data sampled from a larger population; this is commonly referred to as Bessel's correction). Default: ``0``.\nkeepdims: bool\n if ``True``, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) must not be included in the result. Default: ``False``.\n\nReturns\n-------\nout: array\n if the variance was computed over the entire array, a zero-dimensional array containing the variance; otherwise, a non-zero-dimensional array containing the variances. The returned array must have the same data type as ``x``.\n\n\n.. note::\n While this specification recommends that this function only accept input arrays having a real-valued floating-point data type, specification-compliant array libraries may choose to accept input arrays having an integer data type. While mixed data type promotion is implementation-defined, if the input array ``x`` has an integer data type, the returned array must have the default real-valued floating-point data type.\n\nNotes\n-----\n\n**Special Cases**\n\nLet ``N`` equal the number of elements over which to compute the variance.\n\n- If ``N - correction`` is less than or equal to ``0``, the variance is ``NaN``.\n- If ``x_i`` is ``NaN``, the variance is ``NaN`` (i.e., ``NaN`` values propagate)." + "Calculates the variance of the input array ``x``.\n\nParameters\n----------\nx: array\n input array. **Should** have a real-valued floating-point data type.\naxis: Optional[Union[int, Tuple[int, ...]]]\n axis or axes along which variances **must** be computed. By default, the variance **must** be computed over the entire array. If a tuple of integers, variances **must** be computed over multiple axes. A valid axis **must** be an integer on the interval ``[-N, N)``, where ``N`` is the number of axes in ``x``. If an axis is specified as a negative integer, the function **must** determine the axis along which to perform the operation by counting backward from the last axis (where ``-1`` refers to the last axis). If provided an invalid axis, the function **must** raise an exception. Default: ``None``.\ncorrection: Union[int, float]\n degrees of freedom adjustment. Setting this parameter to a value other than ``0`` has the effect of adjusting the divisor during the calculation of the variance according to ``M-c`` where ``M`` corresponds to the total number of elements over which the variance is computed and ``c`` corresponds to the provided degrees of freedom adjustment. When computing the variance of a population, setting this parameter to ``0`` is the standard choice (i.e., the provided array contains data constituting an entire population). When computing the unbiased sample variance, setting this parameter to ``1`` is the standard choice (i.e., the provided array contains data sampled from a larger population; this is commonly referred to as Bessel's correction). Default: ``0``.\nkeepdims: bool\n if ``True``, the reduced axes (dimensions) **must** be included in the result as singleton dimensions, and, accordingly, the result **must** be compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes (dimensions) **must** not be included in the result. Default: ``False``.\n\nReturns\n-------\nout: array\n if the variance is computed over the entire array, a zero-dimensional array containing the variance; otherwise, a non-zero-dimensional array containing the variances. The returned array **must** have the same data type as ``x``.\n\nNotes\n-----\n\n- While this specification recommends that this function only accept input arrays having a real-valued floating-point data type, specification-compliant array libraries **may** choose to accept input arrays having an integer data type. While mixed data type promotion is implementation-defined, if the input array ``x`` has an integer data type, the returned array **must** have the default real-valued floating-point data type.\n\n**Special Cases**\n\nLet ``M`` equal the number of elements over which to compute the variance.\n\n- If ``M - correction`` is less than or equal to ``0``, the variance **must** be ``NaN``.\n- If ``x_i`` is ``NaN``, the variance **must** be ``NaN`` (i.e., ``NaN`` values propagate)." arange: arange[TArray, TDevice, TDtype] "Returns evenly spaced values within the half-open interval ``[start, stop)`` as a one-dimensional array.\n\nParameters\n----------\nstart: Union[int, float]\n if ``stop`` is specified, the start of interval (inclusive); otherwise, the end of the interval (exclusive). If ``stop`` is not specified, the default starting value is ``0``.\nstop: Optional[Union[int, float]]\n the end of the interval. Default: ``None``.\nstep: Union[int, float]\n the distance between two adjacent elements (``out[i+1] - out[i]``). Must not be ``0``; may be negative, this results in an empty array if ``stop >= start``. Default: ``1``.\ndtype: Optional[dtype]\n output array data type. If ``dtype`` is ``None``, the output array data type must be inferred from ``start``, ``stop`` and ``step``. If those are all integers, the output array dtype must be the default integer dtype; if one or more have type ``float``, then the output array dtype must be the default real-valued floating-point data type. Default: ``None``.\ndevice: Optional[device]\n device on which to place the created array. Default: ``None``.\n\n\n.. note::\n This function cannot guarantee that the interval does not include the ``stop`` value in those cases where ``step`` is not an integer and floating-point rounding errors affect the length of the output array.\n\nReturns\n-------\nout: array\n a one-dimensional array containing evenly spaced values. The length of the output array must be ``ceil((stop-start)/step)`` if ``stop - start`` and ``step`` have the same sign, and length ``0`` otherwise." - asarray: asarray[TSupportsbufferprotocol, TArray, TDevice, TDtype] + asarray: asarray[TArray, TDevice, TDtype] "Convert the input to an array.\n\nParameters\n----------\nobj: Union[array, bool, int, float, complex, NestedSequence[bool | int | float | complex], SupportsBufferProtocol]\n object to be converted to an array. May be a Python scalar, a (possibly nested) sequence of Python scalars, or an object supporting the Python buffer protocol.\n\n .. admonition:: Tip\n :class: important\n\n An object supporting the buffer protocol can be turned into a memoryview through ``memoryview(obj)``.\n\ndtype: Optional[dtype]\n output array data type. If ``dtype`` is ``None``, the output array data type must be inferred from the data type(s) in ``obj``. If all input values are Python scalars, then, in order of precedence,\n\n - if all values are of type ``bool``, the output data type must be ``bool``.\n - if all values are of type ``int`` or are a mixture of ``bool`` and ``int``, the output data type must be the default integer data type.\n - if one or more values are ``complex`` numbers, the output data type must be the default complex floating-point data type.\n - if one or more values are ``float``\\s, the output data type must be the default real-valued floating-point data type.\n\n Default: ``None``.\n\ndevice: Optional[device]\n device on which to place the created array. If ``device`` is ``None`` and ``obj`` is an array, the output array device must be inferred from ``obj``. Default: ``None``.\ncopy: Optional[bool]\n boolean indicating whether or not to copy the input. If ``True``, the function must always copy (see :ref:`copy-keyword-argument`). If ``False``, the function must never copy for input which supports the buffer protocol and must raise a ``ValueError`` in case a copy would be necessary. If ``None``, the function must reuse existing memory buffer if possible and copy otherwise. Default: ``None``.\n\nReturns\n-------\nout: array\n an array containing the data from ``obj``.\n\nNotes\n-----\n\n- If ``obj`` is a sequence with some elements being arrays, behavior is unspecified and thus implementation-defined. Conforming implementations may perform a conversion or raise an exception. To join a sequence of arrays along a new axis, see :func:`~array_api.stack`.\n- If ``dtype`` is not ``None``, then array conversions should obey :ref:`type-promotion` rules. Conversions not specified according to :ref:`type-promotion` rules may or may not be permitted by a conforming array library. To perform an explicit cast, use :func:`array_api.astype`.\n- If an input value exceeds the precision of the resolved output array data type, behavior is unspecified and thus implementation-defined.\n\n.. versionchanged:: 2022.12\n Added complex data type support." empty: empty[TArray, TDevice, TDtype] "Returns an uninitialized array having a specified `shape`.\n\nParameters\n----------\nshape: Union[int, Tuple[int, ...]]\n output array shape.\ndtype: Optional[dtype]\n output array data type. If ``dtype`` is ``None``, the output array data type must be the default real-valued floating-point data type. Default: ``None``.\ndevice: Optional[device]\n device on which to place the created array. Default: ``None``.\n\nReturns\n-------\nout: array\n an array containing uninitialized data." @@ -8882,79 +8876,79 @@ class ArrayNamespace[TCapabilities, TDatatypes, TDefaultdatatypes, TSupportsbuff "Tests whether any input array element evaluates to ``True`` along a specified axis.\n\nParameters\n----------\nx: array\n input array.\naxis: Optional[Union[int, Tuple[int, ...]]]\n axis or axes along which to perform a logical OR reduction. By default, a logical OR reduction **must** be performed over the entire array. If a tuple of integers, logical OR reductions **must** be performed over multiple axes. A valid ``axis`` must be an integer on the interval ``[-N, N)``, where ``N`` is the number of axes in ``x``. If an ``axis`` is specified as a negative integer, the function **must** determine the axis along which to perform a reduction by counting backward from the last dimension (where ``-1`` refers to the last axis). If provided an invalid ``axis``, the function **must** raise an exception. Default: ``None``.\nkeepdims: bool\n If ``True``, the reduced axes **must** be included in the result as singleton dimensions, and, accordingly, the result **must** be broadcast-compatible with the input array (see :ref:`broadcasting`). Otherwise, if ``False``, the reduced axes **must not** be included in the result. Default: ``False``.\n\nReturns\n-------\nout: array\n if a logical OR reduction was performed over the entire array, the returned array **must** be a zero-dimensional array containing the test result. Otherwise, the returned array **must** be a non-zero-dimensional array containing the test results. The returned array **must** have a data type of ``bool``.\n\nNotes\n-----\n\n- Positive infinity, negative infinity, and NaN **must** evaluate to ``True``.\n- If ``x`` has a complex floating-point data type, elements having a non-zero component (real or imaginary) **must** evaluate to ``True``.\n- If ``x`` is an empty array or the size of the axis along which to evaluate elements is zero, the test result **must** be ``False``.\n\n.. versionchanged:: 2022.12\n Added complex data type support." diff: diff[TArray,] "Calculates the n-th discrete forward difference along a specified axis.\n\nParameters\n----------\nx: array\n input array. **Should** have a numeric data type.\naxis: int\n axis along which to compute differences. A valid ``axis`` **must** be an integer on the interval ``[-N, N)``, where ``N`` is the number of axes in ``x``. If an ``axis`` is specified as a negative integer, the function **must** determine the axis along which to compute differences by counting backward from the last axis (where ``-1`` refers to the last axis). If provided an invalid ``axis``, the function **must** raise an exception. Default: ``-1``.\nn: int\n number of times to recursively compute differences. Default: ``1``.\nprepend: Optional[array]\n values to prepend to a specified axis prior to computing differences. **Must** have the same shape as ``x``, except for the axis specified by ``axis`` which can have any size. **Should** have the same data type as ``x``. Default: ``None``.\nappend: Optional[array]\n values to append to a specified axis prior to computing differences. **Must** have the same shape as ``x``, except for the axis specified by ``axis`` which can have any size. **Should** have the same data type as ``x``. Default: ``None``.\n\nReturns\n-------\nout: array\n an array containing the n-th differences. **Should** have the same data type as ``x``. **Must** have the same shape as ``x``, except for the axis specified by ``axis`` which **must** have a size determined as follows:\n\n - Let ``M`` be the number of elements along an axis specified by ``axis``.\n - Let ``N1`` be the number of prepended values along an axis specified by ``axis``.\n - Let ``N2`` be the number of appended values along an axis specified by ``axis``.\n - The final size of the axis specified by ``axis`` **must** be ``M + N1 + N2 - n``.\n\nNotes\n-----\n\n- The first-order differences are given by ``out[i] = x[i+1] - x[i]`` along a specified axis. Higher-order differences **must** be calculated recursively (e.g., by calling ``diff(out, axis=axis, n=n-1)``).\n- If a conforming implementation chooses to support ``prepend`` and ``append`` arrays which have a different data type than ``x``, behavior is unspecified and thus implementation-defined. Implementations **may** choose to type promote (:ref:`type-promotion`), cast ``prepend`` and/or ``append`` to the same data type as ``x``, or raise an exception.\n\n.. versionadded:: 2024.12" - __array_namespace_info__: __array_namespace_info__[TCapabilities, TDatatypes, TDefaultdatatypes, TArray, TDevice, TDtype] - "Returns a namespace with Array API namespace inspection utilities.\n\nSee :ref:`inspection` for a list of inspection APIs.\n\nReturns\n-------\nout: Info\n An object containing Array API namespace inspection utilities.\n\nNotes\n-----\n\nThe returned object may be either a namespace or a class, so long as an Array API user can access inspection utilities as follows:\n\n::\n\n info = xp.__array_namespace_info__()\n info.capabilities()\n info.devices()\n info.dtypes()\n info.default_dtypes()\n # ...\n\n.. versionadded: 2023.12" + __array_namespace_info__: __array_namespace_info__[TArray, TCapabilities, TDatatypes, TDefaultdatatypes, TDevice, TDtype] + "Returns a namespace with Array API namespace inspection utilities.\n\nReturns\n-------\nout: Info\n an object containing Array API namespace inspection utilities.\n\nNotes\n-----\n\n- See :ref:`inspection` for a list of inspection APIs.\n\n- The returned object **may** be either a namespace or a class, as long as an Array API user can access inspection utilities as follows:\n\n::\n\n info = xp.__array_namespace_info__()\n info.capabilities()\n info.devices()\n info.dtypes()\n info.default_dtypes()\n # ...\n\n.. versionadded: 2023.12" take: take[TArray,] - "Returns elements of an array along an axis.\n\nParameters\n----------\nx: array\n input array. Should have one or more dimensions (axes).\nindices: array\n array indices. The array must be one-dimensional and have an integer data type. If an index is negative, the function must determine the element to select along a specified axis (dimension) by counting from the last element (where ``-1`` refers to the last element).\naxis: Optional[int]\n axis over which to select values. If ``axis`` is negative, the function must determine the axis along which to select values by counting from the last dimension (where ``-1`` refers to the last dimension).\n\n If ``x`` is a one-dimensional array, providing an ``axis`` is optional; however, if ``x`` has more than one dimension, providing an ``axis`` is required.\n\nReturns\n-------\nout: array\n an array having the same data type as ``x``. The output array must have the same rank (i.e., number of dimensions) as ``x`` and must have the same shape as ``x``, except for the axis specified by ``axis`` whose size must equal the number of elements in ``indices``.\n\nNotes\n-----\n\n- Conceptually, ``take(x, indices, axis=3)`` is equivalent to ``x[:,:,:,indices,...]``; however, explicit indexing via arrays of indices is not currently supported in this specification due to concerns regarding ``__setitem__`` and array mutation semantics.\n- This specification does not require bounds checking. The behavior for out-of-bounds indices is left unspecified.\n- When ``x`` is a zero-dimensional array, behavior is unspecified and thus implementation-defined.\n\n.. versionadded:: 2022.12\n\n.. versionchanged:: 2023.12\n Out-of-bounds behavior is explicitly left unspecified.\n\n.. versionchanged:: 2024.12\n Behavior when provided a zero-dimensional input array is explicitly left unspecified.\n\n.. versionchanged:: 2024.12\n Clarified support for negative indices." + "Returns elements of an array along an axis.\n\nParameters\n----------\nx: array\n input array. **Should** have one or more axes.\nindices: array\n array indices. The array **must** be one-dimensional and have an integer data type. If an index is negative, the function **must** determine the element to select along a specified axis by counting from the last element (where ``-1`` refers to the last element).\naxis: Optional[int]\n axis over which to select values. If ``axis`` is negative, the function **must** determine the axis along which to select values by counting from the last axis (where ``-1`` refers to the last axis).\n\n If ``x`` is a one-dimensional array, providing an ``axis`` **must** be optional; however, if ``x`` has more than one axis, providing an ``axis`` **must** be required.\n\nReturns\n-------\nout: array\n an array having the same data type as ``x``. The output array **must** have the same number of axes as ``x`` and **must** have the same shape as ``x``, except for the axis specified by ``axis`` whose size **must** equal the number of elements in ``indices``.\n\nNotes\n-----\n\n- This specification does not require bounds checking. The behavior for out-of-bounds indices is unspecified and thus implementation-defined.\n\n- When ``x`` is a zero-dimensional array, behavior is unspecified and thus implementation-defined.\n\n.. versionadded:: 2022.12\n\n.. versionchanged:: 2023.12\n Out-of-bounds behavior is explicitly left unspecified.\n\n.. versionchanged:: 2024.12\n Behavior when provided a zero-dimensional input array is explicitly left unspecified.\n\n.. versionchanged:: 2024.12\n Clarified support for negative indices." take_along_axis: take_along_axis[TArray,] - "Returns elements from an array at the one-dimensional indices specified by ``indices`` along a provided ``axis``.\n\nParameters\n----------\nx: array\n input array. Must be compatible with ``indices``, except for the axis (dimension) specified by ``axis`` (see :ref:`broadcasting`).\nindices: array\n array indices. Must have the same rank (i.e., number of dimensions) as ``x``. If an index is negative, the function must determine the element to select along a specified axis (dimension) by counting from the last element (where ``-1`` refers to the last element).\naxis: int\n axis along which to select values. If ``axis`` is negative, the function must determine the axis along which to select values by counting from the last dimension (where ``-1`` refers to the last dimension). Default: ``-1``.\n\nReturns\n-------\nout: array\n an array having the same data type as ``x``. Must have the same rank (i.e., number of dimensions) as ``x`` and must have a shape determined according to :ref:`broadcasting`, except for the axis (dimension) specified by ``axis`` whose size must equal the size of the corresponding axis (dimension) in ``indices``.\n\nNotes\n-----\n\n- This specification does not require bounds checking. The behavior for out-of-bounds indices is left unspecified.\n\n.. versionadded:: 2024.12" + "Returns elements from an array at the one-dimensional indices specified by ``indices`` along a provided ``axis``.\n\nParameters\n----------\nx: array\n input array. **Must** be compatible with ``indices``, except for the axis specified by ``axis`` (see :ref:`broadcasting`).\nindices: array\n array indices. **Must** have the same number of axes as ``x`` and **must** be compatible with ``x``, except for the axis specified by ``axis`` (see :ref:`broadcasting`). If an index is negative, the function **must** determine the element to select along a specified axis by counting from the last element (where ``-1`` refers to the last element).\naxis: int\n axis along which to select values. A valid axis **must** be an integer on the interval ``[-N, N)``, where ``N`` is the number of axes in ``x``. If an axis is specified as a negative integer, the function **must** determine the axis along which to perform the operation by counting backward from the last axis (where ``-1`` refers to the last axis). If provided an invalid axis, the function **must** raise an exception. Default: ``-1``.\n\nReturns\n-------\nout: array\n an array containing elements from ``x``. The returned array **must** have the same data type as ``x``. The returned array **must** have the same number of axes as ``x`` and **must** have a shape determined according to :ref:`broadcasting`, except for the axis specified by ``axis`` whose size **must** equal the size of the corresponding axis in ``indices``.\n\nNotes\n-----\n\n- This specification does not require bounds checking. The behavior for out-of-bounds indices is unspecified and thus implementation-defined.\n\n.. versionadded:: 2024.12" matmul: matmul[TArray,] - "Computes the matrix product.\n\n.. note::\n The ``matmul`` function must implement the same semantics as the built-in ``@`` operator (see `PEP 465 `_).\n\nParameters\n----------\nx1: array\n first input array. Should have a numeric data type. Must have at least one dimension. If ``x1`` is one-dimensional having shape ``(M,)`` and ``x2`` has more than one dimension, ``x1`` must be promoted to a two-dimensional array by prepending ``1`` to its dimensions (i.e., must have shape ``(1, M)``). After matrix multiplication, the prepended dimensions in the returned array must be removed. If ``x1`` has more than one dimension (including after vector-to-matrix promotion), ``shape(x1)[:-2]`` must be compatible with ``shape(x2)[:-2]`` (after vector-to-matrix promotion) (see :ref:`broadcasting`). If ``x1`` has shape ``(..., M, K)``, the innermost two dimensions form matrices on which to perform matrix multiplication.\nx2: array\n second input array. Should have a numeric data type. Must have at least one dimension. If ``x2`` is one-dimensional having shape ``(N,)`` and ``x1`` has more than one dimension, ``x2`` must be promoted to a two-dimensional array by appending ``1`` to its dimensions (i.e., must have shape ``(N, 1)``). After matrix multiplication, the appended dimensions in the returned array must be removed. If ``x2`` has more than one dimension (including after vector-to-matrix promotion), ``shape(x2)[:-2]`` must be compatible with ``shape(x1)[:-2]`` (after vector-to-matrix promotion) (see :ref:`broadcasting`). If ``x2`` has shape ``(..., K, N)``, the innermost two dimensions form matrices on which to perform matrix multiplication.\n\n\n.. note::\n If either ``x1`` or ``x2`` has a complex floating-point data type, neither argument must be complex-conjugated or transposed. If conjugation and/or transposition is desired, these operations should be explicitly performed prior to computing the matrix product.\n\nReturns\n-------\nout: array\n - if both ``x1`` and ``x2`` are one-dimensional arrays having shape ``(N,)``, a zero-dimensional array containing the inner product as its only element.\n - if ``x1`` is a two-dimensional array having shape ``(M, K)`` and ``x2`` is a two-dimensional array having shape ``(K, N)``, a two-dimensional array containing the `conventional matrix product `_ and having shape ``(M, N)``.\n - if ``x1`` is a one-dimensional array having shape ``(K,)`` and ``x2`` is an array having shape ``(..., K, N)``, an array having shape ``(..., N)`` (i.e., prepended dimensions during vector-to-matrix promotion must be removed) and containing the `conventional matrix product `_.\n - if ``x1`` is an array having shape ``(..., M, K)`` and ``x2`` is a one-dimensional array having shape ``(K,)``, an array having shape ``(..., M)`` (i.e., appended dimensions during vector-to-matrix promotion must be removed) and containing the `conventional matrix product `_.\n - if ``x1`` is a two-dimensional array having shape ``(M, K)`` and ``x2`` is an array having shape ``(..., K, N)``, an array having shape ``(..., M, N)`` and containing the `conventional matrix product `_ for each stacked matrix.\n - if ``x1`` is an array having shape ``(..., M, K)`` and ``x2`` is a two-dimensional array having shape ``(K, N)``, an array having shape ``(..., M, N)`` and containing the `conventional matrix product `_ for each stacked matrix.\n - if either ``x1`` or ``x2`` has more than two dimensions, an array having a shape determined by :ref:`broadcasting` ``shape(x1)[:-2]`` against ``shape(x2)[:-2]`` and containing the `conventional matrix product `_ for each stacked matrix.\n\n The returned array must have a data type determined by :ref:`type-promotion`.\n\nNotes\n-----\n\n.. versionchanged:: 2022.12\n Added complex data type support.\n\n**Raises**\n\n- if either ``x1`` or ``x2`` is a zero-dimensional array.\n- if ``x1`` is a one-dimensional array having shape ``(K,)``, ``x2`` is a one-dimensional array having shape ``(L,)``, and ``K != L``.\n- if ``x1`` is a one-dimensional array having shape ``(K,)``, ``x2`` is an array having shape ``(..., L, N)``, and ``K != L``.\n- if ``x1`` is an array having shape ``(..., M, K)``, ``x2`` is a one-dimensional array having shape ``(L,)``, and ``K != L``.\n- if ``x1`` is an array having shape ``(..., M, K)``, ``x2`` is an array having shape ``(..., L, N)``, and ``K != L``." + "Computes the matrix product.\n\nParameters\n----------\nx1: array\n first input array. **Should** have a numeric data type. **Must** have at least one dimension.\n\n - If ``x1`` is a one-dimensional array having shape ``(M,)`` and ``x2`` has more than one dimension, ``x1`` **must** be promoted to a two-dimensional array by prepending ``1`` to its dimensions (i.e., **must** have shape ``(1, M)``). After matrix multiplication, the prepended dimensions in the returned array **must** be removed.\n - If ``x1`` has more than one dimension (including after vector-to-matrix promotion), ``shape(x1)[:-2]`` **must** be compatible with ``shape(x2)[:-2]`` (after vector-to-matrix promotion) (see :ref:`broadcasting`).\n - If ``x1`` has shape ``(..., M, K)``, the innermost two dimensions form matrices on which to perform matrix multiplication.\n\nx2: array\n second input array. **Should** have a numeric data type. **Must** have at least one dimension.\n\n - If ``x2`` is one-dimensional array having shape ``(N,)`` and ``x1`` has more than one dimension, ``x2`` **must** be promoted to a two-dimensional array by appending ``1`` to its dimensions (i.e., **must** have shape ``(N, 1)``). After matrix multiplication, the appended dimensions in the returned array **must** be removed.\n - If ``x2`` has more than one dimension (including after vector-to-matrix promotion), ``shape(x2)[:-2]`` **must** be compatible with ``shape(x1)[:-2]`` (after vector-to-matrix promotion) (see :ref:`broadcasting`).\n - If ``x2`` has shape ``(..., K, N)``, the innermost two dimensions form matrices on which to perform matrix multiplication.\n\nReturns\n-------\nout: array\n output array.\n\n - If both ``x1`` and ``x2`` are one-dimensional arrays having shape ``(N,)``, the returned array **must** be a zero-dimensional array and **must** contain the inner product as its only element.\n - If ``x1`` is a two-dimensional array having shape ``(M, K)`` and ``x2`` is a two-dimensional array having shape ``(K, N)``, the returned array **must** be a two-dimensional array and **must** contain the `conventional matrix product `_ and having shape ``(M, N)``.\n - If ``x1`` is a one-dimensional array having shape ``(K,)`` and ``x2`` is an array having shape ``(..., K, N)``, the returned array **must** be an array having shape ``(..., N)`` (i.e., prepended dimensions during vector-to-matrix promotion **must** be removed) and **must** contain the `conventional matrix product `_.\n - If ``x1`` is an array having shape ``(..., M, K)`` and ``x2`` is a one-dimensional array having shape ``(K,)``, the returned array **must** be an array having shape ``(..., M)`` (i.e., appended dimensions during vector-to-matrix promotion **must** be removed) and **must** contain the `conventional matrix product `_.\n - If ``x1`` is a two-dimensional array having shape ``(M, K)`` and ``x2`` is an array having shape ``(..., K, N)``, the returned array **must** be an array having shape ``(..., M, N)`` and **must** contain the `conventional matrix product `_ for each stacked matrix.\n - If ``x1`` is an array having shape ``(..., M, K)`` and ``x2`` is a two-dimensional array having shape ``(K, N)``, the returned array **must** be an array having shape ``(..., M, N)`` and **must** contain the `conventional matrix product `_ for each stacked matrix.\n - If either ``x1`` or ``x2`` has more than two dimensions, the returned array **must** be an array having a shape determined by :ref:`broadcasting` ``shape(x1)[:-2]`` against ``shape(x2)[:-2]`` and **must** contain the `conventional matrix product `_ for each stacked matrix.\n\n The returned array **must** have a data type determined by :ref:`type-promotion`.\n\nRaises\n------\nException\n an exception **should** be raised in the following circumstances:\n\n - if either ``x1`` or ``x2`` is a zero-dimensional array.\n - if ``x1`` is a one-dimensional array having shape ``(K,)``, ``x2`` is a one-dimensional array having shape ``(L,)``, and ``K != L``.\n - if ``x1`` is a one-dimensional array having shape ``(K,)``, ``x2`` is an array having shape ``(..., L, N)``, and ``K != L``.\n - if ``x1`` is an array having shape ``(..., M, K)``, ``x2`` is a one-dimensional array having shape ``(L,)``, and ``K != L``.\n - if ``x1`` is an array having shape ``(..., M, K)``, ``x2`` is an array having shape ``(..., L, N)``, and ``K != L``.\n\nNotes\n-----\n\n- The ``matmul`` function **must** implement the same semantics as the built-in ``@`` operator (see `PEP 465 `_).\n\n- If either ``x1`` or ``x2`` has a complex floating-point data type, the function **must not** complex-conjugate or tranpose either argument. If conjugation and/or transposition is desired, a user can explicitly perform these operations prior to computing the matrix product.\n\n.. versionchanged:: 2022.12\n Added complex data type support." matrix_transpose: matrix_transpose[TArray,] - "Transposes a matrix (or a stack of matrices) ``x``.\n\nParameters\n----------\nx: array\n input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices.\n\nReturns\n-------\nout: array\n an array containing the transpose for each matrix and having shape ``(..., N, M)``. The returned array must have the same data type as ``x``." + "Transposes a matrix (or a stack of matrices) ``x``.\n\nParameters\n----------\nx: array\n input array having shape ``(..., M, N)`` and whose innermost two dimensions form ``MxN`` matrices.\n\nReturns\n-------\nout: array\n an array containing the transpose for each matrix. The returned array **must** have shape ``(..., N, M)``. The returned array **must** have the same data type as ``x``." tensordot: tensordot[TArray,] - "Returns a tensor contraction of ``x1`` and ``x2`` over specific axes.\n\n.. note::\n The ``tensordot`` function corresponds to the generalized matrix product.\n\nParameters\n----------\nx1: array\n first input array. Should have a numeric data type.\nx2: array\n second input array. Should have a numeric data type. Corresponding contracted axes of ``x1`` and ``x2`` must be equal.\n\n .. note::\n Contracted axes (dimensions) must not be broadcasted.\n\naxes: Union[int, Tuple[Sequence[int], Sequence[int]]]\n number of axes (dimensions) to contract or explicit sequences of axis (dimension) indices for ``x1`` and ``x2``, respectively.\n\n If ``axes`` is an ``int`` equal to ``N``, then contraction must be performed over the last ``N`` axes of ``x1`` and the first ``N`` axes of ``x2`` in order. The size of each corresponding axis (dimension) must match. Must be nonnegative.\n\n - If ``N`` equals ``0``, the result is the tensor (outer) product.\n - If ``N`` equals ``1``, the result is the tensor dot product.\n - If ``N`` equals ``2``, the result is the tensor double contraction (default).\n\n If ``axes`` is a tuple of two sequences ``(x1_axes, x2_axes)``, the first sequence must apply to ``x1`` and the second sequence to ``x2``. Both sequences must have the same length. Each axis (dimension) ``x1_axes[i]`` for ``x1`` must have the same size as the respective axis (dimension) ``x2_axes[i]`` for ``x2``. Each index referred to in a sequence must be unique. If ``x1`` has rank (i.e, number of dimensions) ``N``, a valid ``x1`` axis must reside on the half-open interval ``[-N, N)``. If ``x2`` has rank ``M``, a valid ``x2`` axis must reside on the half-open interval ``[-M, M)``.\n\n\n.. note::\n If either ``x1`` or ``x2`` has a complex floating-point data type, neither argument must be complex-conjugated or transposed. If conjugation and/or transposition is desired, these operations should be explicitly performed prior to computing the generalized matrix product.\n\nReturns\n-------\nout: array\n an array containing the tensor contraction whose shape consists of the non-contracted axes (dimensions) of the first array ``x1``, followed by the non-contracted axes (dimensions) of the second array ``x2``. The returned array must have a data type determined by :ref:`type-promotion`.\n\nNotes\n-----\n\n.. versionchanged:: 2022.12\n Added complex data type support.\n\n.. versionchanged:: 2023.12\n Allow negative axes." + "Returns a tensor contraction of ``x1`` and ``x2`` over specific axes.\n\nParameters\n----------\nx1: array\n first input array. **Should** have a numeric data type.\nx2: array\n second input array. **Should** have a numeric data type. Corresponding contracted axes of ``x1`` and ``x2`` **must** be equal.\n\naxes: Union[int, Tuple[Sequence[int], Sequence[int]]]\n number of axes to contract or explicit sequences of axis indices for ``x1`` and ``x2``, respectively.\n\n If ``axes`` is an ``int`` equal to ``N``, then contraction **must** be performed over the last ``N`` axes of ``x1`` and the first ``N`` axes of ``x2`` in order. The size of each corresponding axis **must** match. An integer ``axes`` value **must** be nonnegative.\n\n - If ``N`` equals ``0``, the result **must** be the tensor (outer) product.\n - If ``N`` equals ``1``, the result **must** be the tensor dot product.\n - If ``N`` equals ``2``, the result **must** be the tensor double contraction (default).\n\n If ``axes`` is a tuple of two sequences ``(x1_axes, x2_axes)``, the first sequence **must** apply to ``x1`` and the second sequence **must** apply to ``x2``. Both sequences **must** have the same length. Each axis ``x1_axes[i]`` for ``x1`` **must** have the same size as the respective axis ``x2_axes[i]`` for ``x2``. Each index referred to in a sequence **must** be unique. A valid axis **must** be an integer on the interval ``[-S, S)``, where ``S`` is the number of axes in respective array. Hence, if ``x1`` has ``N`` axes, a valid ``x1`` axes **must** be an integer on the interval ``[-N, N)``. If ``x2`` has ``M`` axes, a valid ``x2`` axes **must** be an integer on the interval ``[-M, M)``. If an axis is specified as a negative integer, the function **must** determine the axis along which to perform the operation by counting backward from the last axis (where ``-1`` refers to the last axis). If provided an invalid axis, the function **must** raise an exception.\n\n\nReturns\n-------\nout: array\n an array containing the tensor contraction. The returned array **must** have a shape which consists of the non-contracted axes of the first array ``x1``, followed by the non-contracted axes of the second array ``x2``. The returned array **must** have a data type determined by :ref:`type-promotion`.\n\nNotes\n-----\n\n- The ``tensordot`` function corresponds to the generalized matrix product.\n- Contracted axes **must** not be broadcasted.\n- If either ``x1`` or ``x2`` has a complex floating-point data type, the function **must not** complex-conjugate or transpose either argument. If conjugation and/or transposition is desired, a user can explicitly perform these operations prior to computing the generalized matrix product.\n\n.. versionchanged:: 2022.12\n Added complex data type support.\n\n.. versionchanged:: 2023.12\n Allow negative axes." vecdot: vecdot[TArray,] - "Computes the (vector) dot product of two arrays.\n\nLet :math:`\\mathbf{a}` be a vector in ``x1`` and :math:`\\mathbf{b}` be a corresponding vector in ``x2``. The dot product is defined as\n\n.. math::\n \\mathbf{a} \\cdot \\mathbf{b} = \\sum_{i=0}^{n-1} \\overline{a_i}b_i\n\nover the dimension specified by ``axis`` and where :math:`n` is the dimension size and :math:`\\overline{a_i}` denotes the complex conjugate if :math:`a_i` is complex and the identity if :math:`a_i` is real-valued.\n\nParameters\n----------\nx1: array\n first input array. Should have a floating-point data type.\nx2: array\n second input array. Must be compatible with ``x1`` for all non-contracted axes (see :ref:`broadcasting`). The size of the axis over which to compute the dot product must be the same size as the respective axis in ``x1``. Should have a floating-point data type.\n\n .. note::\n The contracted axis (dimension) must not be broadcasted.\n\naxis: int\n the axis (dimension) of ``x1`` and ``x2`` containing the vectors for which to compute the dot product. Should be an integer on the interval ``[-N, -1]``, where ``N`` is ``min(x1.ndim, x2.ndim)``. The function must determine the axis along which to compute the dot product by counting backward from the last dimension (where ``-1`` refers to the last dimension). By default, the function must compute the dot product over the last axis. Default: ``-1``.\n\nReturns\n-------\nout: array\n if ``x1`` and ``x2`` are both one-dimensional arrays, a zero-dimensional containing the dot product; otherwise, a non-zero-dimensional array containing the dot products and having rank ``N-1``, where ``N`` is the rank (number of dimensions) of the shape determined according to :ref:`broadcasting` along the non-contracted axes. The returned array must have a data type determined by :ref:`type-promotion`.\n\nNotes\n-----\n\n**Raises**\n\n- if the size of the axis over which to compute the dot product is not the same (before broadcasting) for both ``x1`` and ``x2``.\n\n.. versionchanged:: 2022.12\n Added complex data type support.\n\n.. versionchanged:: 2023.12\n Restricted ``axis`` to only negative integers." + "Computes the (vector) dot product of two arrays.\n\nLet :math:`\\mathbf{a}` be a vector in ``x1`` and :math:`\\mathbf{b}` be a corresponding vector in ``x2``. The dot product is defined as\n\n.. math::\n \\mathbf{a} \\cdot \\mathbf{b} = \\sum_{i=0}^{n-1} \\overline{a_i}b_i\n\nover the axis specified by ``axis`` and where :math:`n` is the axis size and :math:`\\overline{a_i}` denotes the complex conjugate if :math:`a_i` is complex and the identity if :math:`a_i` is real-valued.\n\nParameters\n----------\nx1: array\n first input array. **Should** have a floating-point data type.\nx2: array\n second input array. **Must** be compatible with ``x1`` for all non-contracted axes (see :ref:`broadcasting`). The size of the axis over which to compute the dot product **must** be the same size as the respective axis in ``x1``. **Should** have a floating-point data type.\naxis: int\n axis of ``x1`` and ``x2`` containing the vectors for which to compute the dot product. **Should** be an integer on the interval ``[-N, -1]``, where ``N`` is ``min(x1.ndim, x2.ndim)``. The function **must** determine the axis along which to perform the operation by counting backward from the last axis (where ``-1`` refers to the last axis). By default, the function **must** compute the dot product over the last axis. Default: ``-1``.\n\nReturns\n-------\nout: array\n if ``x1`` and ``x2`` are both one-dimensional arrays, a zero-dimensional containing the dot product; otherwise, a non-zero-dimensional array containing the dot products and having ``N-1`` axes, where ``N`` is number of axes in the shape determined according to :ref:`broadcasting` along the non-contracted axes. The returned array **must** have a data type determined by :ref:`type-promotion`.\n\nRaises\n------\nException\n an exception **should** be raised in the following circumstances:\n\n - if the size of the axis over which to compute the dot product is not the same (before broadcasting) for both ``x1`` and ``x2``.\n\nNotes\n-----\n\n- The contracted axis **must** not be broadcasted.\n\n.. versionchanged:: 2022.12\n Added complex data type support.\n\n.. versionchanged:: 2023.12\n Restricted ``axis`` to only negative integers." broadcast_arrays: broadcast_arrays[TArray,] - "Broadcasts one or more arrays against one another.\n\nParameters\n----------\narrays: array\n an arbitrary number of to-be broadcasted arrays.\n\nReturns\n-------\nout: List[array]\n a list of broadcasted arrays. Each array must have the same shape. Each array must have the same dtype as its corresponding input array." + "Broadcasts one or more arrays against one another.\n\nParameters\n----------\narrays: array\n an arbitrary number of to-be broadcasted arrays.\n\nReturns\n-------\nout: List[array]\n a list of broadcasted arrays. Each array **must** have the same shape. Each array **must** have the same dtype as its corresponding input array." broadcast_to: broadcast_to[TArray,] - "Broadcasts an array to a specified shape.\n\nParameters\n----------\nx: array\n array to broadcast. Must be capable of being broadcast to the specified ``shape`` (see :ref:`broadcasting`). If the array is incompatible with the specified shape, the function must raise an exception.\nshape: Tuple[int, ...]\n array shape.\n\nReturns\n-------\nout: array\n an array having the specified shape. Must have the same data type as ``x``.\n\n.. versionchanged:: 2024.12\n Clarified broadcast behavior." + "Broadcasts an array to a specified shape.\n\nParameters\n----------\nx: array\n array to broadcast. **Must** be capable of being broadcast to the specified ``shape`` (see :ref:`broadcasting`). If the array is incompatible with the specified shape, the function **must** raise an exception.\nshape: Tuple[int, ...]\n array shape.\n\nReturns\n-------\nout: array\n an array having the specified shape. **Must** have the same data type as ``x``.\n\n.. versionchanged:: 2024.12\n Clarified broadcast behavior." concat: concat[TArray,] - "Joins a sequence of arrays along an existing axis.\n\nParameters\n----------\narrays: Union[Tuple[array, ...], List[array]]\n input arrays to join. The arrays must have the same shape, except in the dimension specified by ``axis``.\naxis: Optional[int]\n axis along which the arrays will be joined. If ``axis`` is ``None``, arrays must be flattened before concatenation. If ``axis`` is negative, the function must determine the axis along which to join by counting from the last dimension. Default: ``0``.\n\nReturns\n-------\nout: array\n an output array containing the concatenated values. If the input arrays have different data types, normal :ref:`type-promotion` must apply. If the input arrays have the same data type, the output array must have the same data type as the input arrays.\n\n .. note::\n This specification leaves type promotion between data type families (i.e., ``intxx`` and ``floatxx``) unspecified." + "Joins a sequence of arrays along an existing axis.\n\nParameters\n----------\narrays: Union[Tuple[array, ...], List[array]]\n input arrays to join. The arrays **must** have the same shape, except in the dimension specified by ``axis``.\naxis: Optional[int]\n axis along which to join the arrays. A valid axis **must** be an integer on the interval ``[-N, N)``, where ``N`` is the number of axes in each array. If an axis is specified as a negative integer, the function **must** determine the axis along which to perform the operation by counting backward from the last axis (where ``-1`` refers to the last axis). If provided an invalid axis, the function **must** raise an exception. If ``axis`` is ``None``, arrays **must** be flattened before concatenation. Default: ``0``.\n\nReturns\n-------\nout: array\n an output array containing the concatenated values. If the input arrays have different data types, normal :ref:`type-promotion` **must** apply. If the input arrays have the same data type, the output array **must** have the same data type as the input arrays.\n\n .. note::\n This specification leaves type promotion between data type families (i.e., ``intxx`` and ``floatxx``) unspecified and thus implementation-defined." expand_dims: expand_dims[TArray,] - "Expands the shape of an array by inserting a new axis (dimension) of size one at the position specified by ``axis``.\n\nParameters\n----------\nx: array\n input array.\naxis: int\n axis position (zero-based). If ``x`` has rank (i.e, number of dimensions) ``N``, a valid ``axis`` must reside on the closed-interval ``[-N-1, N]``. If provided a negative ``axis``, the axis position at which to insert a singleton dimension must be computed as ``N + axis + 1``. Hence, if provided ``-1``, the resolved axis position must be ``N`` (i.e., a singleton dimension must be appended to the input array ``x``). If provided ``-N-1``, the resolved axis position must be ``0`` (i.e., a singleton dimension must be prepended to the input array ``x``).\n\nReturns\n-------\nout: array\n an expanded output array having the same data type as ``x``.\n\nRaises\n------\nIndexError\n If provided an invalid ``axis`` position, an ``IndexError`` should be raised." + "Expands the shape of an array by inserting a new axis of size one at the position specified by ``axis``.\n\nParameters\n----------\nx: array\n input array.\naxis: int\n axis position (zero-based). A valid ``axis`` **must** reside on the closed-interval ``[-N-1, N]``, where ``N`` is the number of axes in ``x``. If an axis is specified as a negative integer, the axis position at which to insert a singleton dimension **must** be computed as ``N + axis + 1``. Hence, if provided ``-1``, the resolved axis position **must** be ``N`` (i.e., a singleton dimension **must** be appended to the input array ``x``). If provided ``-N-1``, the resolved axis position **must** be ``0`` (i.e., a singleton dimension **must** be prepended to the input array ``x``). If provided an invalid axis, the function **must** raise an exception. Default: ``0``.\n\nReturns\n-------\nout: array\n an expanded output array. **Must** have the same data type as ``x``.\n\nRaises\n------\nIndexError\n If provided an invalid ``axis``, an ``IndexError`` **should** be raised." flip: flip[TArray,] - "Reverses the order of elements in an array along the given axis. The shape of the array must be preserved.\n\nParameters\n----------\nx: array\n input array.\naxis: Optional[Union[int, Tuple[int, ...]]]\n axis (or axes) along which to flip. If ``axis`` is ``None``, the function must flip all input array axes. If ``axis`` is negative, the function must count from the last dimension. If provided more than one axis, the function must flip only the specified axes. Default: ``None``.\n\nReturns\n-------\nout: array\n an output array having the same data type and shape as ``x`` and whose elements, relative to ``x``, are reordered." + "Reverses the order of elements in an array along the given axis.\n\nParameters\n----------\nx: array\n input array.\naxis: Optional[Union[int, Tuple[int, ...]]]\n axis (or axes) along which to reverse elements. A valid axis **must** be an integer on the interval ``[-N, N)``, where ``N`` is the number of axes in ``x``. If an axis is specified as a negative integer, the function **must** determine the axis along which to perform the operation by counting backward from the last axis (where ``-1`` refers to the last axis). If provided an invalid axis, the function **must** raise an exception. If ``axis`` is ``None``, the function **must** flip all input array axes. If provided more than one axis, the function **must** flip only the specified axes. Default: ``None``.\n\nReturns\n-------\nout: array\n an output array. The returned array **must** have the same data type and shape as ``x``. The returned array must have the same elements as ``x``, but which are reordered relative to ``x``." moveaxis: moveaxis[TArray,] - "Moves array axes (dimensions) to new positions, while leaving other axes in their original positions.\n\nParameters\n----------\nx: array\n input array.\nsource: Union[int, Tuple[int, ...]]\n Axes to move. Provided axes must be unique. If ``x`` has rank (i.e, number of dimensions) ``N``, a valid axis must reside on the half-open interval ``[-N, N)``.\ndestination: Union[int, Tuple[int, ...]]\n indices defining the desired positions for each respective ``source`` axis index. Provided indices must be unique. If ``x`` has rank (i.e, number of dimensions) ``N``, a valid axis must reside on the half-open interval ``[-N, N)``.\n\nReturns\n-------\nout: array\n an array containing reordered axes. The returned array must have the same data type as ``x``.\n\nNotes\n-----\n\n.. versionadded:: 2023.12" + "Moves array axes to new positions, while leaving other axes in their original positions.\n\nParameters\n----------\nx: array\n input array.\nsource: Union[int, Tuple[int, ...]]\n axis (or axes) to move. Provided source axes **must** be unique. A valid axis **must** be an integer on the interval ``[-N, N)``, where ``N`` is the number of axes in ``x``. If an axis is specified as a negative integer, the function **must** determine the axis along which to perform the operation by counting backward from the last axis (where ``-1`` refers to the last axis). If provided an invalid axis, the function **must** raise an exception.\ndestination: Union[int, Tuple[int, ...]]\n axis (or axes) defining the desired position(s) for each respective ``source`` axis index. Provided destination axes **must** be unique. A valid axis **must** be an integer on the interval ``[-N, N)``, where ``N`` is the number of axes in ``x``. If an axis is specified as a negative integer, the function **must** determine the axis along which to perform the operation by counting backward from the last axis (where ``-1`` refers to the last axis). If provided an invalid axis, the function **must** raise an exception.\n\nReturns\n-------\nout: array\n an array containing reordered axes. The returned array **must** have the same data type as ``x``.\n\nNotes\n-----\n\n.. versionadded:: 2023.12" permute_dims: permute_dims[TArray,] - "Permutes the axes (dimensions) of an array ``x``.\n\nParameters\n----------\nx: array\n input array.\naxes: Tuple[int, ...]\n tuple containing a permutation of ``(0, 1, ..., N-1)`` where ``N`` is the number of axes (dimensions) of ``x``.\n\nReturns\n-------\nout: array\n an array containing the axes permutation. The returned array must have the same data type as ``x``." + "Permutes the axes of an array ``x``.\n\nParameters\n----------\nx: array\n input array.\naxes: Tuple[int, ...]\n tuple containing a permutation of ``(0, 1, ..., N-1)`` where ``N`` is the number of axes in ``x``.\n\nReturns\n-------\nout: array\n an array containing the axes permutation. The returned array **must** have the same data type as ``x``." repeat: repeat[TArray,] - "Repeats each element of an array a specified number of times on a per-element basis.\n\n.. admonition:: Data-dependent output shape\n :class: important\n\n When ``repeats`` is an array, the shape of the output array for this function depends on the data values in the ``repeats`` array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) may find this function difficult to implement without knowing the values in ``repeats``. Accordingly, such libraries may choose to omit support for ``repeats`` arrays; however, conforming implementations must support providing a literal ``int``. See :ref:`data-dependent-output-shapes` section for more details.\n\nParameters\n----------\nx: array\n input array containing elements to repeat.\nrepeats: Union[int, array]\n the number of repetitions for each element.\n\n If ``axis`` is ``None``, let ``N = prod(x.shape)`` and\n\n - if ``repeats`` is an array, ``repeats`` must be broadcast compatible with the shape ``(N,)`` (i.e., be a one-dimensional array having shape ``(1,)`` or ``(N,)``).\n - if ``repeats`` is an integer, ``repeats`` must be broadcasted to the shape `(N,)`.\n\n If ``axis`` is not ``None``, let ``M = x.shape[axis]`` and\n\n - if ``repeats`` is an array, ``repeats`` must be broadcast compatible with the shape ``(M,)`` (i.e., be a one-dimensional array having shape ``(1,)`` or ``(M,)``).\n - if ``repeats`` is an integer, ``repeats`` must be broadcasted to the shape ``(M,)``.\n\n If ``repeats`` is an array, the array must have an integer data type.\n\n .. note::\n For specification-conforming array libraries supporting hardware acceleration, providing an array for ``repeats`` may cause device synchronization due to an unknown output shape. For those array libraries where synchronization concerns are applicable, conforming array libraries are advised to include a warning in their documentation regarding potential performance degradation when ``repeats`` is an array.\n\naxis: Optional[int]\n the axis (dimension) along which to repeat elements. If ``axis`` is `None`, the function must flatten the input array ``x`` and then repeat elements of the flattened input array and return the result as a one-dimensional output array. A flattened input array must be flattened in row-major, C-style order. Default: ``None``.\n\nReturns\n-------\nout: array\n an output array containing repeated elements. The returned array must have the same data type as ``x``. If ``axis`` is ``None``, the returned array must be a one-dimensional array; otherwise, the returned array must have the same shape as ``x``, except for the axis (dimension) along which elements were repeated.\n\nNotes\n-----\n\n.. versionadded:: 2023.12" + "Repeats each element of an array a specified number of times on a per-element basis.\n\n.. admonition:: Data-dependent output shape\n :class: important\n\n When ``repeats`` is an array, the shape of the output array for this function depends on the data values in the ``repeats`` array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) can find this function difficult to implement without knowing the values in ``repeats``. Accordingly, such libraries **may** choose to omit support for ``repeats`` arrays; however, conforming implementations **must** support providing a literal ``int``. See :ref:`data-dependent-output-shapes` section for more details.\n\nParameters\n----------\nx: array\n input array containing elements to repeat.\nrepeats: Union[int, array]\n the number of repetitions for each element.\n\n If ``axis`` is ``None``, let ``M = prod(x.shape)`` and\n\n - if ``repeats`` is an array, ``repeats`` **must** be broadcast compatible with the shape ``(M,)`` (i.e., be a one-dimensional array having shape ``(1,)`` or ``(M,)``).\n - if ``repeats`` is an integer, ``repeats`` **must** be broadcasted to the shape `(M,)`.\n\n If ``axis`` is not ``None``, let ``S = x.shape[axis]`` and\n\n - if ``repeats`` is an array, ``repeats`` **must** be broadcast compatible with the shape ``(S,)`` (i.e., be a one-dimensional array having shape ``(1,)`` or ``(S,)``).\n - if ``repeats`` is an integer, ``repeats`` **must** be broadcasted to the shape ``(S,)``.\n\n If ``repeats`` is an array, the array **must** have an integer data type.\n\naxis: Optional[int]\n the axis along which to repeat elements. A valid axis **must** be an integer on the interval ``[-N, N)``, where ``N`` is the number of axes in ``x``. If an axis is specified as a negative integer, the function **must** determine the axis along which to perform the operation by counting backward from the last axis (where ``-1`` refers to the last axis). If provided an invalid axis, the function **must** raise an exception. If ``axis`` is `None`, the function **must** flatten the input array ``x`` and then repeat elements of the flattened input array and return the result as a one-dimensional output array. A flattened input array **must** be flattened in row-major, C-style order. Default: ``None``.\n\nReturns\n-------\nout: array\n an output array containing repeated elements. The returned array **must** have the same data type as ``x``. If ``axis`` is ``None``, the returned array **must** be a one-dimensional array; otherwise, the returned array **must** have the same shape as ``x``, except for the axis along which elements were repeated.\n\nNotes\n-----\n\n- For specification-conforming array libraries supporting hardware acceleration, providing an array for ``repeats`` can cause device synchronization due to an unknown output shape. For those array libraries where synchronization concerns are applicable, conforming array libraries **should** include a warning in their documentation regarding potential performance degradation when ``repeats`` is an array.\n\n.. versionadded:: 2023.12" reshape: reshape[TArray,] - "Reshapes an array without changing its data.\n\nParameters\n----------\nx: array\n input array to reshape.\nshape: Tuple[int, ...]\n a new shape compatible with the original shape. One shape dimension is allowed to be ``-1``. When a shape dimension is ``-1``, the corresponding output array shape dimension must be inferred from the length of the array and the remaining dimensions.\ncopy: Optional[bool]\n whether or not to copy the input array. If ``True``, the function must always copy (see :ref:`copy-keyword-argument`). If ``False``, the function must never copy. If ``None``, the function must avoid copying, if possible, and may copy otherwise. Default: ``None``.\n\nReturns\n-------\nout: array\n an output array having the same data type and elements as ``x``.\n\nRaises\n------\nValueError\n If ``copy=False`` and a copy would be necessary, a ``ValueError``\n should be raised." + "Reshapes an array without changing its data.\n\nParameters\n----------\nx: array\n input array to reshape.\nshape: Tuple[int, ...]\n a new shape compatible with the original shape. Only one shape dimension **must** be allowed to be ``-1``. When a shape dimension is ``-1``, the corresponding output array shape dimension **must** be inferred from the length of the array and the remaining dimensions.\ncopy: Optional[bool]\n whether or not to copy the input array. If ``True``, the function **must** always copy (see :ref:`copy-keyword-argument`). If ``False``, the function **must** never copy. If ``None``, the function **must** avoid copying, if possible, and **may** copy otherwise. Default: ``None``.\n\nReturns\n-------\nout: array\n an output array. The returned array **must** have the same data type and the same elements as ``x``.\n\nRaises\n------\nValueError\n If ``copy=False`` and a copy would be necessary, a ``ValueError`` **should** be raised." roll: roll[TArray,] - "Rolls array elements along a specified axis. Array elements that roll beyond the last position are re-introduced at the first position. Array elements that roll beyond the first position are re-introduced at the last position.\n\nParameters\n----------\nx: array\n input array.\nshift: Union[int, Tuple[int, ...]]\n number of places by which the elements are shifted. If ``shift`` is a tuple, then ``axis`` must be a tuple of the same size, and each of the given axes must be shifted by the corresponding element in ``shift``. If ``shift`` is an ``int`` and ``axis`` a tuple, then the same ``shift`` must be used for all specified axes. If a shift is positive, then array elements must be shifted positively (toward larger indices) along the dimension of ``axis``. If a shift is negative, then array elements must be shifted negatively (toward smaller indices) along the dimension of ``axis``.\naxis: Optional[Union[int, Tuple[int, ...]]]\n axis (or axes) along which elements to shift. If ``axis`` is ``None``, the array must be flattened, shifted, and then restored to its original shape. Default: ``None``.\n\nReturns\n-------\nout: array\n an output array having the same data type as ``x`` and whose elements, relative to ``x``, are shifted." + "Rolls array elements along a specified axis.\n\nArray elements that roll beyond the last position are re-introduced at the first position.\n\nArray elements that roll beyond the first position are re-introduced at the last position.\n\nParameters\n----------\nx: array\n input array.\nshift: Union[int, Tuple[int, ...]]\n number of places by which the elements are shifted. If ``shift`` is a tuple, then ``axis`` **must** be a tuple of the same size, and each of the given axes **must** be shifted by the corresponding element in ``shift``. If ``shift`` is an ``int`` and ``axis`` a tuple, then the same ``shift`` **must** be used for all specified axes. If a shift is positive, then array elements **must** be shifted positively (toward larger indices) along the dimension of ``axis``. If a shift is negative, then array elements **must** be shifted negatively (toward smaller indices) along the dimension of ``axis``.\naxis: Optional[Union[int, Tuple[int, ...]]]\n axis (or axes) along which elements to shift. A valid axis **must** be an integer on the interval ``[-N, N)``, where ``N`` is the number of axes in ``x``. If an axis is specified as a negative integer, the function **must** determine the axis along which to perform the operation by counting backward from the last axis (where ``-1`` refers to the last axis). If provided an invalid axis, the function **must** raise an exception. If ``axis`` is ``None``, the array **must** be flattened, shifted, and then restored to its original shape. Default: ``None``.\n\nReturns\n-------\nout: array\n an output array. The returned array **must** have the same data type as ``x``. The returned array **must** have the same elements as ``x``, but which are shifted relative to ``x``." squeeze: squeeze[TArray,] - "Removes singleton dimensions (axes) from ``x``.\n\nParameters\n----------\nx: array\n input array.\naxis: Union[int, Tuple[int, ...]]\n axis (or axes) to squeeze.\n\nReturns\n-------\nout: array\n an output array having the same data type and elements as ``x``.\n\nRaises\n------\nValueError\n If a specified axis has a size greater than one (i.e., it is not a\n singleton dimension), a ``ValueError`` should be raised." + "Removes singleton axes from ``x``.\n\nParameters\n----------\nx: array\n input array.\naxis: Union[int, Tuple[int, ...]]\n axis (or axes) to squeeze. A valid axis **must** be an integer on the interval ``[-N, N)``, where ``N`` is the number of axes in ``x``. If an axis is specified as a negative integer, the function **must** determine the axis along which to perform the operation by counting backward from the last axis (where ``-1`` refers to the last axis). If provided an invalid axis, the function **must** raise an exception.\n\nReturns\n-------\nout: array\n an output array. The returned array **must** have the same data type and the same elements as ``x``.\n\nRaises\n------\nValueError\n If a specified axis has a size greater than one (i.e., it is not a singleton axis), a ``ValueError`` **should** be raised." stack: stack[TArray,] - "Joins a sequence of arrays along a new axis.\n\nParameters\n----------\narrays: Union[Tuple[array, ...], List[array]]\n input arrays to join. Each array must have the same shape.\naxis: int\n axis along which the arrays will be joined. Providing an ``axis`` specifies the index of the new axis in the dimensions of the result. For example, if ``axis`` is ``0``, the new axis will be the first dimension and the output array will have shape ``(N, A, B, C)``; if ``axis`` is ``1``, the new axis will be the second dimension and the output array will have shape ``(A, N, B, C)``; and, if ``axis`` is ``-1``, the new axis will be the last dimension and the output array will have shape ``(A, B, C, N)``. A valid ``axis`` must be on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If provided an ``axis`` outside of the required interval, the function must raise an exception. Default: ``0``.\n\nReturns\n-------\nout: array\n an output array having rank ``N+1``, where ``N`` is the rank (number of dimensions) of ``x``. If the input arrays have different data types, normal :ref:`type-promotion` must apply. If the input arrays have the same data type, the output array must have the same data type as the input arrays.\n\n .. note::\n This specification leaves type promotion between data type families (i.e., ``intxx`` and ``floatxx``) unspecified." + "Joins a sequence of arrays along a new axis.\n\nParameters\n----------\narrays: Union[Tuple[array, ...], List[array]]\n input arrays to join. Each array **must** have the same shape.\naxis: int\n axis along which to join the arrays. Providing an ``axis`` specifies the index of the new axis in the shape of the result. For example, if ``axis`` is ``0``, the new axis **must** be the first dimension and the output array **must** have shape ``(N, A, B, C)``; if ``axis`` is ``1``, the new axis will be the second dimension and the output array will have shape ``(A, N, B, C)``; and, if ``axis`` is ``-1``, the new axis will be the last dimension and the output array will have shape ``(A, B, C, N)``. A valid axis **must** be an integer on the interval ``[-N, N)``, where ``N`` is the number of axes in ``x``. If an axis is specified as a negative integer, the function **must** determine the axis along which to perform the operation by counting backward from the last axis (where ``-1`` refers to the last axis). If provided an invalid axis, the function **must** raise an exception. Default: ``0``.\n\nReturns\n-------\nout: array\n an output array. The returned array **must** have ``N+1`` axes, where ``N`` is the number of axes in ``x``. If the input arrays have different data types, normal :ref:`type-promotion` **must** apply. If the input arrays have the same data type, the output array **must** have the same data type as the input arrays.\n\nNotes\n-----\n\n- This specification leaves type promotion between data type families (i.e., ``intxx`` and ``floatxx``) unspecified and thus implementation-defined." tile: tile[TArray,] - "Constructs an array by tiling an input array.\n\nParameters\n----------\nx: array\n input array.\nrepetitions: Tuple[int, ...]\n number of repetitions along each axis (dimension).\n\n Let ``N = len(x.shape)`` and ``M = len(repetitions)``.\n\n If ``N > M``, the function must prepend ones until all axes (dimensions) are specified (e.g., if ``x`` has shape ``(8,6,4,2)`` and ``repetitions`` is the tuple ``(3,3)``, then ``repetitions`` must be treated as ``(1,1,3,3)``).\n\n If ``N < M``, the function must prepend singleton axes (dimensions) to ``x`` until ``x`` has as many axes (dimensions) as ``repetitions`` specifies (e.g., if ``x`` has shape ``(4,2)`` and ``repetitions`` is the tuple ``(3,3,3,3)``, then ``x`` must be treated as if it has shape ``(1,1,4,2)``).\n\nReturns\n-------\nout: array\n a tiled output array. The returned array must have the same data type as ``x`` and must have a rank (i.e., number of dimensions) equal to ``max(N, M)``. If ``S`` is the shape of the tiled array after prepending singleton dimensions (if necessary) and ``r`` is the tuple of repetitions after prepending ones (if necessary), then the number of elements along each axis (dimension) must satisfy ``S[i]*r[i]``, where ``i`` refers to the ``i`` th axis (dimension).\n\nNotes\n-----\n\n.. versionadded:: 2023.12" + "Constructs an array by tiling an input array.\n\nParameters\n----------\nx: array\n input array.\nrepetitions: Tuple[int, ...]\n number of repetitions along each axis.\n\n Let ``N = len(x.shape)`` and ``M = len(repetitions)``.\n\n If ``N > M``, the function **must** prepend ones until all axes are specified (e.g., if ``x`` has shape ``(8,6,4,2)`` and ``repetitions`` is the tuple ``(3,3)``, then ``repetitions`` **must** be treated as ``(1,1,3,3)``).\n\n If ``N < M``, the function **must** prepend singleton axes to ``x`` until ``x`` has as many axes as ``repetitions`` specifies (e.g., if ``x`` has shape ``(4,2)`` and ``repetitions`` is the tuple ``(3,3,3,3)``, then ``x`` **must** be treated as if it has shape ``(1,1,4,2)``).\n\nReturns\n-------\nout: array\n a tiled output array. The returned array **must** have the same data type as ``x`` and **must** have a number of axes equal to ``max(N, M)``. If ``S`` is the shape of the tiled array after prepending singleton dimensions (if necessary) and ``r`` is the tuple of repetitions after prepending ones (if necessary), then the number of elements along each axis **must** satisfy ``S[i]*r[i]``, where ``i`` refers to the ``i`` th axis.\n\nNotes\n-----\n\n.. versionadded:: 2023.12" unstack: unstack[TArray,] - "Splits an array into a sequence of arrays along the given axis.\n\nParameters\n----------\nx: array\n input array.\naxis: int\n axis along which the array will be split. A valid ``axis`` must be on the interval ``[-N, N)``, where ``N`` is the rank (number of dimensions) of ``x``. If provided an ``axis`` outside of the required interval, the function must raise an exception. Default: ``0``.\n\nReturns\n-------\nout: Tuple[array, ...]\n tuple of slices along the given dimension. All the arrays have the same shape.\n\nNotes\n-----\n\n.. versionadded:: 2023.12" - e: float + "Splits an array into a sequence of arrays along the given axis.\n\nParameters\n----------\nx: array\n input array.\naxis: int\n axis along which to split an array. A valid axis **must** be an integer on the interval ``[-N, N)``, where ``N`` is the number of axes in ``x``. If an axis is specified as a negative integer, the function **must** determine the axis along which to perform the operation by counting backward from the last axis (where ``-1`` refers to the last axis). If provided an invalid axis, the function **must** raise an exception. Default: ``0``.\n\nReturns\n-------\nout: Tuple[array, ...]\n tuple of slices along the given dimension. Each returned array **must** have the same shape.\n\nNotes\n-----\n\n.. versionadded:: 2023.12" + e: TArray "\nIEEE 754 floating-point representation of Euler's constant.\n\n``e = 2.71828182845904523536028747135266249775724709369995...``\n" - inf: float + inf: TArray "\nIEEE 754 floating-point representation of (positive) infinity.\n" - nan: float + nan: TArray "\nIEEE 754 floating-point representation of Not a Number (``NaN``).\n" - newaxis: float + newaxis: TArray "\nAn alias for ``None`` which is useful for indexing arrays.\n" - pi: float + pi: TArray "\nIEEE 754 floating-point representation of the mathematical constant ``π``.\n\n``pi = 3.1415926535897932384626433...``\n" unique_all: unique_all[TArray,] - "Returns the unique elements of an input array ``x``, the first occurring indices for each unique element in ``x``, the indices from the set of unique elements that reconstruct ``x``, and the corresponding counts for each unique element in ``x``.\n\n.. admonition:: Data-dependent output shape\n :class: important\n\n The shapes of two of the output arrays for this function depend on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) may find this function difficult to implement without knowing array values. Accordingly, such libraries may choose to omit this function. See :ref:`data-dependent-output-shapes` section for more details.\n\n.. note::\n Uniqueness should be determined based on value equality (see :func:`~array_api.equal`). For input arrays having floating-point data types, value-based equality implies the following behavior.\n\n - As ``nan`` values compare as ``False``, ``nan`` values should be considered distinct.\n - As complex floating-point values having at least one ``nan`` component compare as ``False``, complex floating-point values having ``nan`` components should be considered distinct.\n - As ``-0`` and ``+0`` compare as ``True``, signed zeros should not be considered distinct, and the corresponding unique element will be implementation-dependent (e.g., an implementation could choose to return ``-0`` if ``-0`` occurs before ``+0``).\n\n As signed zeros are not distinct, using ``inverse_indices`` to reconstruct the input array is not guaranteed to return an array having the exact same values.\n\n Each ``nan`` value and each complex floating-point value having a ``nan`` component should have a count of one, while the counts for signed zeros should be aggregated as a single count.\n\nParameters\n----------\nx: array\n input array. If ``x`` has more than one dimension, the function must flatten ``x`` and return the unique elements of the flattened array.\n\nReturns\n-------\nout: Tuple[array, array, array, array]\n a namedtuple ``(values, indices, inverse_indices, counts)`` whose\n\n - first element must have the field name ``values`` and must be a one-dimensional array containing the unique elements of ``x``. The array must have the same data type as ``x``.\n - second element must have the field name ``indices`` and must be an array containing the indices (first occurrences) of a flattened ``x`` that result in ``values``. The array must have the same shape as ``values`` and must have the default array index data type.\n - third element must have the field name ``inverse_indices`` and must be an array containing the indices of ``values`` that reconstruct ``x``. The array must have the same shape as ``x`` and must have the default array index data type.\n - fourth element must have the field name ``counts`` and must be an array containing the number of times each unique element occurs in ``x``. The order of the returned counts must match the order of ``values``, such that a specific element in ``counts`` corresponds to the respective unique element in ``values``. The returned array must have same shape as ``values`` and must have the default array index data type.\n\n .. note::\n The order of unique elements is not specified and may vary between implementations.\n\nNotes\n-----\n\n.. versionchanged:: 2022.12\n Added complex data type support.\n\n.. versionchanged:: 2023.12\n Clarified flattening behavior and required the order of ``counts`` match the order of ``values``." + "Returns the unique elements of an input array ``x``, the first occurring indices for each unique element in ``x``, the indices from the set of unique elements that reconstruct ``x``, and the corresponding counts for each unique element in ``x``.\n\n.. admonition:: Data-dependent output shape\n :class: important\n\n The shapes of two of the output arrays for this function depend on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, et cetera) can find this function difficult to implement without knowing array values. Accordingly, such libraries **may** choose to omit this function. See :ref:`data-dependent-output-shapes` section for more details.\n\nParameters\n----------\nx: array\n input array. If ``x`` has more than one dimension, the function **must** flatten ``x`` and return the unique elements of the flattened array.\n\nReturns\n-------\nout: Tuple[array, array, array, array]\n a namedtuple ``(values, indices, inverse_indices, counts)`` whose\n\n - first element **must** have the field name ``values`` and **must** be a one-dimensional array containing the unique elements of ``x``. The array **must** have the same data type as ``x``.\n - second element **must** have the field name ``indices`` and **must** be an array containing the indices (first occurrences) of a flattened ``x`` that result in ``values``. The array **must** have the same shape as ``values`` and **must** have the default array index data type.\n - third element **must** have the field name ``inverse_indices`` and **must** be an array containing the indices of ``values`` that reconstruct ``x``. The array **must** have the same shape as ``x`` and **must** have the default array index data type.\n - fourth element **must** have the field name ``counts`` and **must** be an array containing the number of times each unique element occurs in ``x``. The order of the returned counts **must** match the order of ``values``, such that a specific element in ``counts`` corresponds to the respective unique element in ``values``. The returned array **must** have same shape as ``values`` and **must** have the default array index data type.\n\nNotes\n-----\n\n- The order of unique elements returned by this function is unspecified and thus implementation-defined. As a consequence, element order **may** vary between implementations.\n\n- Uniqueness **should** be determined based on value equality (see :func:`~array_api.equal`). For input arrays having floating-point data types, value-based equality implies the following behavior.\n\n - As ``nan`` values compare as ``False``, ``nan`` values **should** be considered distinct.\n - As complex floating-point values having at least one ``nan`` component compare as ``False``, complex floating-point values having ``nan`` components **should** be considered distinct.\n - As ``-0`` and ``+0`` compare as ``True``, signed zeros **should not** be considered distinct, and the corresponding unique element **may** be implementation-defined (e.g., an implementation **may** choose to return ``-0`` if ``-0`` occurs before ``+0``).\n\n As signed zeros are not distinct, using ``inverse_indices`` to reconstruct the input array is not guaranteed to return an array having the exact same values.\n\n Each ``nan`` value and each complex floating-point value having a ``nan`` component **should** have a count of one, while the counts for signed zeros **should** be aggregated as a single count.\n\n.. versionchanged:: 2022.12\n Added complex data type support.\n\n.. versionchanged:: 2023.12\n Clarified flattening behavior and required the order of ``counts`` match the order of ``values``." unique_counts: unique_counts[TArray,] - "Returns the unique elements of an input array ``x`` and the corresponding counts for each unique element in ``x``.\n\n.. admonition:: Data-dependent output shape\n :class: important\n\n The shapes of two of the output arrays for this function depend on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) may find this function difficult to implement without knowing array values. Accordingly, such libraries may choose to omit this function. See :ref:`data-dependent-output-shapes` section for more details.\n\n.. note::\n Uniqueness should be determined based on value equality (see :func:`~array_api.equal`). For input arrays having floating-point data types, value-based equality implies the following behavior.\n\n - As ``nan`` values compare as ``False``, ``nan`` values should be considered distinct.\n - As complex floating-point values having at least one ``nan`` component compare as ``False``, complex floating-point values having ``nan`` components should be considered distinct.\n - As ``-0`` and ``+0`` compare as ``True``, signed zeros should not be considered distinct, and the corresponding unique element will be implementation-dependent (e.g., an implementation could choose to return ``-0`` if ``-0`` occurs before ``+0``).\n\n Each ``nan`` value and each complex floating-point value having a ``nan`` component should have a count of one, while the counts for signed zeros should be aggregated as a single count.\n\nParameters\n----------\nx: array\n input array. If ``x`` has more than one dimension, the function must flatten ``x`` and return the unique elements of the flattened array.\n\nReturns\n-------\nout: Tuple[array, array]\n a namedtuple `(values, counts)` whose\n\n - first element must have the field name ``values`` and must be a one-dimensional array containing the unique elements of ``x``. The array must have the same data type as ``x``.\n - second element must have the field name `counts` and must be an array containing the number of times each unique element occurs in ``x``. The order of the returned counts must match the order of ``values``, such that a specific element in ``counts`` corresponds to the respective unique element in ``values``. The returned array must have same shape as ``values`` and must have the default array index data type.\n\n .. note::\n The order of unique elements is not specified and may vary between implementations.\n\nNotes\n-----\n\n.. versionchanged:: 2022.12\n Added complex data type support.\n\n.. versionchanged:: 2023.12\n Clarified flattening behavior and required the order of ``counts`` match the order of ``values``." + "Returns the unique elements of an input array ``x`` and the corresponding counts for each unique element in ``x``.\n\n.. admonition:: Data-dependent output shape\n :class: important\n\n The shapes of two of the output arrays for this function depend on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) can find this function difficult to implement without knowing array values. Accordingly, such libraries **may** choose to omit this function. See :ref:`data-dependent-output-shapes` section for more details.\n\nParameters\n----------\nx: array\n input array. If ``x`` has more than one dimension, the function **must** flatten ``x`` and return the unique elements of the flattened array.\n\nReturns\n-------\nout: Tuple[array, array]\n a namedtuple `(values, counts)` whose\n\n - first element **must** have the field name ``values`` and **must** be a one-dimensional array containing the unique elements of ``x``. The array **must** have the same data type as ``x``.\n - second element **must** have the field name `counts` and **must** be an array containing the number of times each unique element occurs in ``x``. The order of the returned counts **must** match the order of ``values``, such that a specific element in ``counts`` corresponds to the respective unique element in ``values``. The returned array **must** have same shape as ``values`` and **must** have the default array index data type.\n\nNotes\n-----\n\n- The order of unique elements returned by this function is unspecified and thus implementation-defined. As a consequence, element order **may** vary between implementations.\n\n- Uniqueness **should** be determined based on value equality (see :func:`~array_api.equal`). For input arrays having floating-point data types, value-based equality implies the following behavior.\n\n - As ``nan`` values compare as ``False``, ``nan`` values **should** be considered distinct.\n - As complex floating-point values having at least one ``nan`` component compare as ``False``, complex floating-point values having ``nan`` components **should** be considered distinct.\n - As ``-0`` and ``+0`` compare as ``True``, signed zeros **should not** be considered distinct, and the corresponding unique element **may** be implementation-defined (e.g., an implementation **may** choose to return ``-0`` if ``-0`` occurs before ``+0``).\n\n Each ``nan`` value and each complex floating-point value having a ``nan`` component **should** have a count of one, while the counts for signed zeros **should** be aggregated as a single count.\n\n.. versionchanged:: 2022.12\n Added complex data type support.\n\n.. versionchanged:: 2023.12\n Clarified flattening behavior and required the order of ``counts`` match the order of ``values``." unique_inverse: unique_inverse[TArray,] - "Returns the unique elements of an input array ``x`` and the indices from the set of unique elements that reconstruct ``x``.\n\n.. admonition:: Data-dependent output shape\n :class: important\n\n The shapes of two of the output arrays for this function depend on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) may find this function difficult to implement without knowing array values. Accordingly, such libraries may choose to omit this function. See :ref:`data-dependent-output-shapes` section for more details.\n\n.. note::\n Uniqueness should be determined based on value equality (see :func:`~array_api.equal`). For input arrays having floating-point data types, value-based equality implies the following behavior.\n\n - As ``nan`` values compare as ``False``, ``nan`` values should be considered distinct.\n - As complex floating-point values having at least one ``nan`` component compare as ``False``, complex floating-point values having ``nan`` components should be considered distinct.\n - As ``-0`` and ``+0`` compare as ``True``, signed zeros should not be considered distinct, and the corresponding unique element will be implementation-dependent (e.g., an implementation could choose to return ``-0`` if ``-0`` occurs before ``+0``).\n\n As signed zeros are not distinct, using ``inverse_indices`` to reconstruct the input array is not guaranteed to return an array having the exact same values.\n\nParameters\n----------\nx: array\n input array. If ``x`` has more than one dimension, the function must flatten ``x`` and return the unique elements of the flattened array.\n\nReturns\n-------\nout: Tuple[array, array]\n a namedtuple ``(values, inverse_indices)`` whose\n\n - first element must have the field name ``values`` and must be a one-dimensional array containing the unique elements of ``x``. The array must have the same data type as ``x``.\n - second element must have the field name ``inverse_indices`` and must be an array containing the indices of ``values`` that reconstruct ``x``. The array must have the same shape as ``x`` and have the default array index data type.\n\n .. note::\n The order of unique elements is not specified and may vary between implementations.\n\nNotes\n-----\n\n.. versionchanged:: 2022.12\n Added complex data type support.\n\n.. versionchanged:: 2023.12\n Clarified flattening behavior." + "Returns the unique elements of an input array ``x`` and the indices from the set of unique elements that reconstruct ``x``.\n\n.. admonition:: Data-dependent output shape\n :class: important\n\n The shapes of two of the output arrays for this function depend on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) can find this function difficult to implement without knowing array values. Accordingly, such libraries **may** choose to omit this function. See :ref:`data-dependent-output-shapes` section for more details.\n\nParameters\n----------\nx: array\n input array. If ``x`` has more than one dimension, the function **must** flatten ``x`` and return the unique elements of the flattened array.\n\nReturns\n-------\nout: Tuple[array, array]\n a namedtuple ``(values, inverse_indices)`` whose\n\n - first element **must** have the field name ``values`` and **must** be a one-dimensional array containing the unique elements of ``x``. The array **must** have the same data type as ``x``.\n - second element **must** have the field name ``inverse_indices`` and **must** be an array containing the indices of ``values`` that reconstruct ``x``. The array **must** have the same shape as ``x`` and have the default array index data type.\n\nNotes\n-----\n\n- The order of unique elements returned by this function is unspecified and thus implementation-defined. As a consequence, element order **may** vary between implementations.\n\n- Uniqueness **should** be determined based on value equality (see :func:`~array_api.equal`). For input arrays having floating-point data types, value-based equality implies the following behavior.\n\n - As ``nan`` values compare as ``False``, ``nan`` values **should** be considered distinct.\n - As complex floating-point values having at least one ``nan`` component compare as ``False``, complex floating-point values having ``nan`` components **should** be considered distinct.\n - As ``-0`` and ``+0`` compare as ``True``, signed zeros **should not** be considered distinct, and the corresponding unique element **may** be implementation-defined (e.g., an implementation **may** choose to return ``-0`` if ``-0`` occurs before ``+0``).\n\n As signed zeros are not distinct, using ``inverse_indices`` to reconstruct the input array is not guaranteed to return an array having the exact same values.\n\n.. versionchanged:: 2022.12\n Added complex data type support.\n\n.. versionchanged:: 2023.12\n Clarified flattening behavior." unique_values: unique_values[TArray,] - "Returns the unique elements of an input array ``x``.\n\n.. admonition:: Data-dependent output shape\n :class: important\n\n The shapes of two of the output arrays for this function depend on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) may find this function difficult to implement without knowing array values. Accordingly, such libraries may choose to omit this function. See :ref:`data-dependent-output-shapes` section for more details.\n\n.. note::\n Uniqueness should be determined based on value equality (see :func:`~array_api.equal`). For input arrays having floating-point data types, value-based equality implies the following behavior.\n\n - As ``nan`` values compare as ``False``, ``nan`` values should be considered distinct.\n - As complex floating-point values having at least one ``nan`` component compare as ``False``, complex floating-point values having ``nan`` components should be considered distinct.\n - As ``-0`` and ``+0`` compare as ``True``, signed zeros should not be considered distinct, and the corresponding unique element will be implementation-dependent (e.g., an implementation could choose to return ``-0`` if ``-0`` occurs before ``+0``).\n\nParameters\n----------\nx: array\n input array. If ``x`` has more than one dimension, the function must flatten ``x`` and return the unique elements of the flattened array.\n\nReturns\n-------\nout: array\n a one-dimensional array containing the set of unique elements in ``x``. The returned array must have the same data type as ``x``.\n\n .. note::\n The order of unique elements is not specified and may vary between implementations.\n\nNotes\n-----\n\n.. versionchanged:: 2022.12\n Added complex data type support.\n\n.. versionchanged:: 2023.12\n Required that the output array must be one-dimensional." - bool: float - complex128: float - complex64: float - float32: float - float64: float - int16: float - int32: float - int64: float - int8: float - uint16: float - uint32: float - uint64: float - uint8: float + "Returns the unique elements of an input array ``x``.\n\n.. admonition:: Data-dependent output shape\n :class: important\n\n The shapes of two of the output arrays for this function depend on the data values in the input array; hence, array libraries which build computation graphs (e.g., JAX, Dask, etc.) can find this function difficult to implement without knowing array values. Accordingly, such libraries **may** choose to omit this function. See :ref:`data-dependent-output-shapes` section for more details.\n\nParameters\n----------\nx: array\n input array. If ``x`` has more than one dimension, the function **must** flatten ``x`` and return the unique elements of the flattened array.\n\nReturns\n-------\nout: array\n a one-dimensional array containing the set of unique elements in ``x``. The returned array **must** have the same data type as ``x``.\n\nNotes\n-----\n\n- The order of unique elements returned by this function is unspecified and thus implementation-defined. As a consequence, element order **may** vary between implementations.\n\n- Uniqueness **should** be determined based on value equality (see :func:`~array_api.equal`). For input arrays having floating-point data types, value-based equality implies the following behavior.\n\n - As ``nan`` values compare as ``False``, ``nan`` values **should** be considered distinct.\n - As complex floating-point values having at least one ``nan`` component compare as ``False``, complex floating-point values having ``nan`` components **should** be considered distinct.\n - As ``-0`` and ``+0`` compare as ``True``, signed zeros **should not** be considered distinct, and the corresponding unique element **may** be implementation-defined (e.g., an implementation **may** choose to return ``-0`` if ``-0`` occurs before ``+0``).\n\n.. versionchanged:: 2022.12\n Added complex data type support.\n\n.. versionchanged:: 2023.12\n Required that the output array must be one-dimensional." + bool: TDtype + complex128: TDtype + complex64: TDtype + float32: TDtype + float64: TDtype + int16: TDtype + int32: TDtype + int64: TDtype + int8: TDtype + uint16: TDtype + uint32: TDtype + uint64: TDtype + uint8: TDtype Device: TDevice @@ -9041,6 +9035,6 @@ class FftNamespace[TArray: Array, TDevice, TDtype](Protocol): @runtime_checkable -class ArrayNamespaceFull[TCapabilities, TDatatypes, TDefaultdatatypes, TSupportsbufferprotocol, TArray: Array, TDevice, TDtype](ArrayNamespace[TCapabilities, TDatatypes, TDefaultdatatypes, TSupportsbufferprotocol, TArray, TDevice, TDtype], Protocol): +class ArrayNamespaceFull[TArray: Array, TCapabilities, TDatatypes, TDefaultdatatypes, TDevice, TDtype](ArrayNamespace[TArray, TCapabilities, TDatatypes, TDefaultdatatypes, TDevice, TDtype], Protocol): linalg: LinalgNamespace[TArray, TDtype] fft: FftNamespace[TArray, TDevice, TDtype] diff --git a/src/array_api/cli/_main.py b/src/array_api/cli/_main.py index 35b6aa5..0980b9e 100644 --- a/src/array_api/cli/_main.py +++ b/src/array_api/cli/_main.py @@ -60,7 +60,7 @@ def _function_to_protocol(stmt: ast.FunctionDef, typevars: Sequence[TypeVarInfo] """ stmt = deepcopy(stmt) name = stmt.name - docstring = ast.get_docstring(stmt) + docstring = ast.get_docstring(stmt, False) stmt.name = "__call__" stmt.body = [ast.Expr(value=ast.Constant(value=Ellipsis))] stmt.args.posonlyargs.insert(0, ast.arg(arg="self")) @@ -79,7 +79,6 @@ def _function_to_protocol(stmt: ast.FunctionDef, typevars: Sequence[TypeVarInfo] ) args = ast.unparse(stmt.args) + (ast.unparse(stmt.returns) if stmt.returns else "") typevars = [typevar for typevar in typevars if typevar.name in args] - typevars = sorted(typevars, key=lambda x: x.name) # Construct the protocol stmt_new = ast.ClassDef( @@ -89,7 +88,7 @@ def _function_to_protocol(stmt: ast.FunctionDef, typevars: Sequence[TypeVarInfo] bases=[ ast.Name(id="Protocol"), ], - body=([ast.Expr(value=ast.Constant(docstring, kind=None))] if docstring is not None else []) + [stmt], + body=([ast.Expr(value=ast.Constant(docstring))] if docstring is not None else []) + [stmt], type_params=[ast.TypeVar(name=t.name, bound=ast.Name(id=t.bound) if t.bound else None) for t in typevars], ) return ProtocolData( @@ -117,7 +116,6 @@ def _class_to_protocol(stmt: ast.ClassDef, typevars: Sequence[TypeVarInfo]) -> P """ unp = ast.unparse(stmt) typevars = [typevar for typevar in typevars if typevar.name in unp] - typevars = sorted(typevars, key=lambda x: x.name) stmt.bases = [ ast.Name(id="Protocol"), ] @@ -170,7 +168,7 @@ def _attributes_to_protocol(name: str, attributes: Sequence[ModuleAttributes], b if a.docstring is not None: body.append(ast.Expr(value=ast.Constant(a.docstring))) if typevars is None: - typevars = sorted({x for attribute in attributes for x in attribute.typevars_used}, key=lambda x: x.name) + typevars = sorted({x for attribute in attributes for x in attribute.typevars_used}, key=lambda x: x.name.lower()) return ProtocolData( stmt=ast.ClassDef( name=name, @@ -221,8 +219,9 @@ def generate(body_module: dict[str, list[ast.stmt]], out_path: Path) -> None: ) ) typevars += [TypeVarInfo(name=x) for x in ["Capabilities", "DefaultDataTypes", "DataTypes"]] - typevars = sorted(typevars, key=lambda x: x.name) - print(list(typevars)) + typevars = [t for t in typevars if t.name not in ["ellipsis", "PyCapsule", "SupportsBufferProtocol"]] + print(typevars) + typevars = sorted(typevars, key=lambda x: x.name.lower()) # Dict of module attributes per submodule module_attributes: defaultdict[str, list[ModuleAttributes]] = defaultdict(list) @@ -273,7 +272,7 @@ def generate(body_module: dict[str, list[ast.stmt]], out_path: Path) -> None: if isinstance(docstring_expr.value, ast.Constant): docstring = docstring_expr.value.value # add to module attributes - module_attributes[submodule].append(ModuleAttributes(id, ast.Name(id="float"), docstring, [])) + module_attributes[submodule].append(ModuleAttributes(id, ast.Name(id="array"), docstring, [])) elif isinstance(b, ast.ClassDef): data = _class_to_protocol(b, typevars) # add to output, do not add to module attributes @@ -286,7 +285,7 @@ def generate(body_module: dict[str, list[ast.stmt]], out_path: Path) -> None: # Manual addition for d in ["bool", "complex128", "complex64", "float32", "float64", "int16", "int32", "int64", "int8", "uint16", "uint32", "uint64", "uint8"]: - module_attributes[""].append(ModuleAttributes(d, ast.Name("float"), None, [])) + module_attributes[""].append(ModuleAttributes(d, ast.Name("dtype"), None, [])) module_attributes[""].append(ModuleAttributes("Device", ast.Name("device"), None, [])) # Create Protocols for the main namespace @@ -346,7 +345,11 @@ def generate(body_module: dict[str, list[ast.stmt]], out_path: Path) -> None: List, runtime_checkable, ) +from types import EllipsisType as ellipsis +from typing_extensions import CapsuleType as PyCapsule +from collections.abc import Buffer as SupportsBufferProtocol inf = float("inf") + """ + text ) @@ -388,5 +391,5 @@ def generate_all( if "2021" in dir_path.name: continue # get module bodies - body_module = {path.stem: ast.parse(path.read_text("utf-8").replace("Dtype", "dtype").replace("Device", "device")).body for path in dir_path.rglob("*.py")} + body_module = {path.stem: ast.parse(path.read_text("utf-8").replace("self: array", "self").replace("Dtype", "dtype").replace("Device", "device")).body for path in dir_path.rglob("*.py")} generate(body_module, (Path(out_path) / dir_path.name).with_suffix(".py")) diff --git a/src/array_api_compat/__init__.pyi b/src/array_api_compat/__init__.pyi index 9a5a077..01214b7 100644 --- a/src/array_api_compat/__init__.pyi +++ b/src/array_api_compat/__init__.pyi @@ -1,9 +1,11 @@ from typing import Any, Literal -from array_api._2024_12 import ArrayNamespace +from array_api._2024_12 import Array, ArrayNamespaceFull -def array_namespace( - *xs: Any | complex | None, - api_version: Literal["v2024.12"] | None = None, +# return full namespace for convenience +# because optional attributes are not supported +def array_namespace[TArray: Array]( + *xs: TArray | complex | None, + api_version: Literal["2024.12"] | None = None, use_compat: bool | None = None, -) -> ArrayNamespace: ... +) -> ArrayNamespaceFull[TArray, Any, Any, Any, Any, Any]: ... diff --git a/uv.lock b/uv.lock index 76ecf91..31b54a3 100644 --- a/uv.lock +++ b/uv.lock @@ -1014,12 +1014,13 @@ wheels = [ [[package]] name = "types-array-api" -version = "1.1.0" +version = "1.1.1rc1" source = { editable = "." } dependencies = [ { name = "attrs" }, { name = "rich" }, { name = "typer" }, + { name = "typing-extensions" }, ] [package.dev-dependencies] @@ -1043,6 +1044,7 @@ requires-dist = [ { name = "attrs", specifier = ">=25.3.0" }, { name = "rich", specifier = ">=10" }, { name = "typer", specifier = ">=0.15,<1" }, + { name = "typing-extensions", specifier = ">=4.14.0" }, ] [package.metadata.requires-dev]