Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

✨ feat: add Quantity API #16

Merged
merged 7 commits into from
Dec 5, 2024
Merged
Show file tree
Hide file tree
Changes from 6 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
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,7 @@ ignore = [
"PLR09", # Too many <...>
"PLR2004", # Magic value used in comparison
"RET505", # Unnecessary `else`/`elif` after `return` statement
"RUF022", # `__all__` is not sorted
]

[tool.ruff.lint.per-file-ignores]
Expand Down
8 changes: 7 additions & 1 deletion src/quantity/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,13 @@
Copyright (c) 2024 Astropy Developers. All rights reserved.
"""

from . import api
from ._src import Quantity
from .version import version as __version__ # noqa: F401

__all__ = ["Quantity"]
__all__ = [
# modules
"api",
# functions and classes
"Quantity",
]
96 changes: 96 additions & 0 deletions src/quantity/_src/api.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
"""The Quantity API. Private module."""

__all__ = ["Quantity", "QuantityArray", "Unit"]

from typing import Protocol, runtime_checkable

from astropy.units import UnitBase as Unit

from .array_api import Array


@runtime_checkable
class Quantity(Protocol):
"""Minimal definition of the Quantity API.

At minimum a Quantity must have the following attributes:

- `value`: the numerical value of the quantity (adhering to the Array API)
- `unit`: the unit of the quantity

In practice, Quantities themselves must adhere to the Array API, not just
their values. This stricter requirement is described by the `QuantityArray`
protocol.

See Also
--------
QuantityArray : A Quantity that adheres to the Array API

Examples
--------
>>> import numpy as np
>>> import astropy.units as u
>>> from quantity import Quantity
>>> from quantity import api

>>> issubclass(Quantity, api.Quantity)
True

>>> q = Quantity(value=np.array([1, 2, 3]), unit=u.m)
>>> isinstance(q, api.Quantity)
True

"""

#: The numerical value of the quantity, adhering to the Array API.
value: Array

#: The unit of the quantity.
unit: Unit

@classmethod
def __subclasshook__(cls: type, c: type) -> bool:
"""Enable the subclass check for data descriptors."""
return (
hasattr(c, "value") or "value" in getattr(c, "__annotations__", ())
) and (hasattr(c, "unit") or "unit" in getattr(c, "__annotations__", ()))


@runtime_checkable
class QuantityArray(Quantity, Array, Protocol):
"""An array-valued Quantity.

A QuantityArray is a Quantity that itself adheres to the Array API. This
means that the QuantityArray has properties like `shape`, `dtype`, and the
`__array_namespace__` method, among many other properties and methods. To
understand the full requirements of the Array API, see the `Array` protocol.
The `Quantity` protocol describes the minimal requirements for a Quantity,
separate from the Array API. QuantityArray is the combination of these two
protocols and is the most complete description of a Quantity.

See Also
--------
Quantity : The minimal Quantity API, separate from the Array API

Examples
--------
>>> import numpy as np
>>> import astropy.units as u
>>> from quantity import Quantity
>>> from quantity import api

>>> issubclass(Quantity, api.QuantityArray)
True

>>> q = Quantity(value=np.array([1, 2, 3]), unit=u.m)
>>> isinstance(q, api.QuantityArray)
True

"""

...

@classmethod
def __subclasshook__(cls: type, c: type) -> bool:
"""Enable the subclass check for data descriptors."""
return Quantity.__subclasscheck__(c) and issubclass(c, Array)
25 changes: 25 additions & 0 deletions src/quantity/_src/array_api.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
"""Minimal definition of the Array API.

NOTE: this module will be deprecated when
https://github.com/data-apis/array-api-typing is released.

"""

from __future__ import annotations

__all__ = ["HasArrayNameSpace", "Array"]

from typing import Any, Protocol, runtime_checkable


class HasArrayNameSpace(Protocol):
"""Minimal definition of the Array API."""

def __array_namespace__(self) -> Any: ...


@runtime_checkable
class Array(HasArrayNameSpace, Protocol):
"""Minimal definition of the Array API."""

def __pow__(self, other: Any) -> Array: ...
18 changes: 10 additions & 8 deletions src/quantity/_src/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,25 +10,27 @@
import numpy as np
from astropy.units.quantity_helper import UFUNC_HELPERS

from .api import QuantityArray
from .utils import has_array_namespace

if TYPE_CHECKING:
from typing import Any

from .api import Unit
from .array_api import Array


DIMENSIONLESS = u.dimensionless_unscaled

PYTHON_NUMBER = float | int | complex


def get_value_and_unit(arg, default_unit=None):
# HACK: interoperability with astropy Quantity. Have protocol?
try:
unit = arg.unit
except AttributeError:
return arg, default_unit
else:
return arg.value, unit
def get_value_and_unit(
arg: QuantityArray | Array, default_unit: Unit | None = None
) -> tuple[Array, Unit]:
return (
(arg.value, arg.unit) if isinstance(arg, QuantityArray) else (arg, default_unit)
)


def value_in_unit(value, unit):
Expand Down
16 changes: 16 additions & 0 deletions src/quantity/api.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""Quantity-2.0: the Quantity API.

This module provides runtime-checkable Protocol objects that define the Quantity
API. In particular there are:

- `Quantity`: the minimal definition of a Quantity, separate from the Array API.
- `QuantityArray`: a Quantity that adheres to the Array API. This is the most
complete definition of a Quantity, inheriting from the Quantity API and
adding the requirements for the Array API.

"""
# Copyright (c) 2024 Astropy Developers. All rights reserved.

from ._src.api import Quantity, QuantityArray

__all__ = ["Quantity", "QuantityArray"]
58 changes: 58 additions & 0 deletions tests/test_api.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Test the Quantity class Array API compatibility."""

import astropy.units as u
import numpy as np
import pytest

from quantity import Quantity, api

from .conftest import ARRAY_NAMESPACES


def test_issubclass_api():
"""Test that Quantity is a subclass of api.Quantity and api.QuantityArray."""
assert issubclass(Quantity, api.Quantity)
assert issubclass(Quantity, api.QuantityArray)


def test_ndarray():
"""Test that ndarray does not satisfy the Quantity API."""
assert not issubclass(np.ndarray, api.Quantity)
assert not isinstance(np.array([1, 2, 3]), api.Quantity)


def test_astropy_quantity():
"""Test that astropy.units.Quantity works with the Quantity API."""
assert issubclass(u.Quantity, api.Quantity)
assert isinstance(u.Quantity(np.array([1, 2, 3]), u.m), api.Quantity)


# ------------------------------


@pytest.fixture
Copy link
Contributor

Choose a reason for hiding this comment

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

I thought about a structure like this when I wrote test_operations, but I rather dislike that it requiers every method to have that explicit fixture: I think setup_class() is considerably nicer: one just does tests on a given setup, which includes a given array type. Unfortunately, I could not seem to find a clean way in which one can properly parametrize classes by their setup, though I'll admit that I've never really understood the whole fixture process -- I find them rather unreadable (it seems pytest makes up its own language within a language rather than just using standard python stuff).

Anyway, long & short, I'd prefer to stick to one way of parametrizing over the array namespaces, ideally one that doesn't require to do setup in each method...

Since that is somewhat orthogonal to the goals of this PR, OK to just push back what I had and merge? (I'm definitely not stuck to my class creation code, but would like something that does not add boilerplate to each test!)

Copy link
Member Author

Choose a reason for hiding this comment

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

Alternatively we can just make a class-scoped fixture (https://docs.pytest.org/en/7.1.x/how-to/fixtures.html#scope-sharing-fixtures-across-classes-modules-packages-or-session) by moving def array_and_quantity(request): into the class and adding the argument to the fixture. It neatly replaces class_setup.

Copy link
Member Author

Choose a reason for hiding this comment

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

try running pytest in verbose mode, it now repeats the whole class as a block for each array library.

def array_and_quantity(request):
xp = request.param.xp
value = xp.asarray([1.0, 2.0, 3.0])
q = Quantity(value, u.m)
return value, q


@pytest.mark.parametrize("array_and_quantity", ARRAY_NAMESPACES, indirect=True)
class TestIsinstanceAPI:
"""Check Quantities are properly recognized independent of the array type."""

def test_issubclass_api(self, array_and_quantity):
v, q = array_and_quantity
assert not issubclass(type(v), api.Quantity)
assert not issubclass(type(v), api.QuantityArray)
assert issubclass(type(q), api.Quantity)
assert issubclass(type(q), api.QuantityArray)

def test_isinstance_api(self, array_and_quantity):
v, q = array_and_quantity
assert not isinstance(v, api.Quantity)
assert not isinstance(v, api.QuantityArray)
assert isinstance(q, api.Quantity)
assert isinstance(q, api.QuantityArray)
Loading