Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,8 @@ ignore = [
"FIX", # flake8-fixme
"ISC001", # Conflicts with formatter
"PYI041", # Use `float` instead of `int | float`
"TD002", # Missing author in TODO
"TD003", # Missing issue link for this TODO
]

[tool.ruff.lint.pydocstyle]
Expand Down
27 changes: 25 additions & 2 deletions src/array_api_typing/__init__.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,35 @@
"""Static typing support for the array API standard."""

__all__ = (
__all__ = ( # noqa: RUF022
# ==================
# Array
"Array",
"HasArrayNamespace",
"HasDType",
"HasMatrixTranspose",
"HasNDim",
"HasShape",
"HasSize",
"HasTranspose",
# ==================
# Namespace
"ArrayNamespace",
"DoesAsType",
"HasAsType",
# ==================
"__version__",
"__version_tuple__",
)

from ._array import Array, HasArrayNamespace, HasDType
from ._array import (
Array,
HasArrayNamespace,
HasDType,
HasMatrixTranspose,
HasNDim,
HasShape,
HasSize,
HasTranspose,
)
from ._namespace import ArrayNamespace, DoesAsType, HasAsType
from ._version import version as __version__, version_tuple as __version_tuple__
132 changes: 130 additions & 2 deletions src/array_api_typing/_array.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
__all__ = (
"Array",
"HasArrayNamespace",
"HasDType",
"HasDevice",
"HasMatrixTranspose",
"HasNDim",
"HasShape",
"HasSize",
"HasTranspose",
)

from types import ModuleType
from typing import Literal, Protocol
from typing import Literal, Protocol, Self
from typing_extensions import TypeVar

NamespaceT_co = TypeVar("NamespaceT_co", covariant=True, default=ModuleType)
Expand Down Expand Up @@ -67,10 +74,131 @@ def dtype(self, /) -> DTypeT_co:
...


class HasDevice(Protocol):
"""Protocol for array classes that have a device attribute."""

@property
def device(self) -> object: # TODO: more specific type
"""Hardware device the array data resides on."""
...


class HasMatrixTranspose(Protocol):
"""Protocol for array classes that have a matrix transpose attribute."""

@property
def mT(self) -> Self: # noqa: N802
"""Transpose of a matrix (or a stack of matrices).

If an array instance has fewer than two dimensions, an error should be
raised.

Returns:
Self: array whose last two dimensions (axes) are permuted in reverse
order relative to original array (i.e., for an array instance
having shape `(..., M, N)`, the returned array must have shape
`(..., N, M))`. The returned array must have the same data type
as the original array.

"""
...


class HasNDim(Protocol):
"""Protocol for array classes that have a number of dimensions attribute."""

@property
def ndim(self) -> int:
"""Number of array dimensions (axes).

Returns:
int: number of array dimensions (axes).

"""
...


class HasShape(Protocol):
"""Protocol for array classes that have a shape attribute."""

@property
def shape(self) -> tuple[int | None, ...]:
"""Shape of the array.

Returns:
tuple[int | None, ...]: array dimensions. An array dimension must be None
if and only if a dimension is unknown.

Notes:
For array libraries having graph-based computational models, array
dimensions may be unknown due to data-dependent operations (e.g.,
boolean indexing; `A[:, B > 0]`) and thus cannot be statically
resolved without knowing array contents.

"""
...


class HasSize(Protocol):
"""Protocol for array classes that have a size attribute."""

@property
def size(self) -> int | None:
"""Number of elements in an array.

Returns:
int | None: number of elements in an array. The returned value must
be `None` if and only if one or more array dimensions are
unknown.

Notes:
This must equal the product of the array's dimensions.

"""
...


class HasTranspose(Protocol):
"""Protocol for array classes that support the transpose operation."""

@property
def T(self) -> Self: # noqa: N802
"""Transpose of the array.

The array instance must be two-dimensional. If the array instance is not
two-dimensional, an error should be raised.

Returns:
Self: two-dimensional array whose first and last dimensions (axes)
are permuted in reverse order relative to original array. The
returned array must have the same data type as the original
array.

Notes:
Limiting the transpose to two-dimensional arrays (matrices) deviates
from the NumPy et al practice of reversing all axes for arrays
having more than two-dimensions. This is intentional, as reversing
all axes was found to be problematic (e.g., conflicting with the
mathematical definition of a transpose which is limited to matrices;
not operating on batches of matrices; et cetera). In order to
reverse all axes, one is recommended to use the functional
`PermuteDims` interface found in this specification.

"""
...


class Array(
HasArrayNamespace[NamespaceT_co],
# ------ Attributes -------
HasDType[DTypeT_co],
HasDevice,
HasMatrixTranspose,
HasNDim,
HasShape,
HasSize,
HasTranspose,
# ------- Methods ---------
HasArrayNamespace[NamespaceT_co],
# -------------------------
Protocol[DTypeT_co, NamespaceT_co],
):
Expand Down
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These empty files snuck in. I'll remove when rebasing after #34 is in.

Empty file.
Empty file.
112 changes: 112 additions & 0 deletions src/array_api_typing/_namespace.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
from typing import Protocol, TypeVar

from ._array import HasDType

__all__ = (
"ArrayNamespace",
# Data Type Functions
"DoesAsType",
"HasAsType",
)

DTypeT = TypeVar("DTypeT")
ToDTypeT = TypeVar("ToDTypeT")

# ===================================================================
# Creation Functions
# TODO: arange, asarray, empty, empty_like, eye, from_dlpack, full, full_like,
# linspace, meshgrid, ones, ones_like, tril, triu, zeros, zeros_like

# ===================================================================
# Data Type Functions
# TODO: broadcast_arrays, broadcast_to, can_cast, finfo, iinfo,
# result_type


class DoesAsType(Protocol):
"""Copies an array to a specified data type irrespective of Type Promotion Rules rules.

Note:
Casting floating-point ``NaN`` and ``infinity`` values to integral data
types is not specified and is implementation-dependent.

Note:
When casting a boolean input array to a numeric data type, a value of
`True` must cast to a numeric value equal to ``1``, and a value of
`False` must cast to a numeric value equal to ``0``.

When casting a numeric input array to bool, a value of ``0`` must cast
to `False`, and a non-zero value must cast to `True`.

Args:
x: The array to cast.
dtype: desired data type.
copy: 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 must be
returned. Default: `True`.

""" # noqa: E501

def __call__(
self, x: HasDType[DTypeT], dtype: ToDTypeT, /, *, copy: bool = True
) -> HasDType[ToDTypeT]: ...


class HasAsType(Protocol):
"""Protocol for namespaces that have an ``astype`` function."""

astype: DoesAsType


# ===================================================================
# Element-wise Functions
# TODO: abs, acos, acosh, add, asin, asinh, atan, atan2, atanh, bitwise_and,
# bitwise_invert, bitwise_left_shift, bitwise_or, bitwise_right_shift,
# bitwise_xor, ceil, cos, cosh, divide, equal, exp, exp2, expm1, floor,
# floor_divide, greater, greater_equal, isfinite, isinf, isnan, less,
# less_equal, log, log1p, log2, log10, logical_and, logical_not, logical_or,
# logical_xor, multiply, negative, not_equal, positive, pow, remainder, round,
# sign, sin, sinh, square, sqrt, subtract, tan, tanh, trunc


# ===================================================================
# Linear Algebra Functions
# TODO: matmul, matrix_transpose, tensordot, vecdot

# ===================================================================
# Manipulation Functions
# TODO: concat, expand_dims, flip, permute_dims, reshape, roll, squeeze, stack

# ===================================================================
# Searching Functions
# TODO: argmax, argmin, nonzero, where

# ===================================================================
# Set Functions
# TODO: unique_all, unique_counts, unique_inverse, unique_values

# ===================================================================
# Sorting Functions
# TODO: argsort, sort

# ===================================================================
# Statistical Functions
# TODO: max, mean, min, prod, std, sum, var

# ===================================================================
# Utility Functions
# TODO: all, any

# ===================================================================
# Full Namespace


class ArrayNamespace(
# Data Type Functions
HasAsType,
Protocol,
):
"""Protocol for an Array API-compatible namespace."""
34 changes: 31 additions & 3 deletions tests/integration/test_numpy1p0.pyi
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# mypy: disable-error-code="no-redef"

from types import ModuleType
from typing import Any
from typing import Any, assert_type

import numpy.array_api as np # type: ignore[import-not-found, unused-ignore]
from numpy import dtype
Expand Down Expand Up @@ -49,5 +49,33 @@ a_ns: xpt.Array[Any, ModuleType] = nparr
# Note that `np.array_api` uses dtype objects, not dtype classes, so we can't
# type annotate specific dtypes like `np.float32` or `np.int32`.
_: xpt.Array[dtype[Any]] = nparr
_: xpt.Array[dtype[Any]] = nparr_i32
_: xpt.Array[dtype[Any]] = nparr_f32
x_f32: xpt.Array[dtype[Any]] = nparr_f32
x_i32: xpt.Array[dtype[Any]] = nparr_i32

# Check Attribute `.dtype`
assert_type(x_f32.dtype, dtype[Any])
assert_type(x_i32.dtype, dtype[Any])

# Check Attribute `.device`
assert_type(x_f32.device, object)
assert_type(x_i32.device, object)

# Check Attribute `.mT`
assert_type(x_f32.mT, xpt.Array[dtype[Any]])
assert_type(x_i32.mT, xpt.Array[dtype[Any]])

# Check Attribute `.ndim`
assert_type(x_f32.ndim, int)
assert_type(x_i32.ndim, int)

# Check Attribute `.shape`
assert_type(x_f32.shape, tuple[int | None, ...])
assert_type(x_i32.shape, tuple[int | None, ...])

# Check Attribute `.size`
assert_type(x_f32.size, int | None)
assert_type(x_i32.size, int | None)

# Check Attribute `.T`
assert_type(x_f32.T, xpt.Array[dtype[Any]])
assert_type(x_i32.T, xpt.Array[dtype[Any]])
Loading
Loading