unxts.api 2.0.2__tar.gz → 2.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {unxts_api-2.0.2 → unxts_api-2.1.0}/.gitignore +4 -1
- {unxts_api-2.0.2 → unxts_api-2.1.0}/PKG-INFO +1 -1
- {unxts_api-2.0.2 → unxts_api-2.1.0}/docs/api.md +15 -1
- {unxts_api-2.0.2 → unxts_api-2.1.0}/docs/extending.md +36 -38
- unxts_api-2.1.0/docs/index.md +102 -0
- unxts_api-2.1.0/docs/tutorial-your-own-type.md +153 -0
- unxts_api-2.1.0/docs/why-abstract-dispatch.md +35 -0
- {unxts_api-2.0.2 → unxts_api-2.1.0}/pyproject.toml +1 -1
- {unxts_api-2.0.2 → unxts_api-2.1.0}/src/unxts/api/_version.py +2 -2
- {unxts_api-2.0.2/tests → unxts_api-2.1.0/tests/smoke}/test_public_api.py +0 -10
- unxts_api-2.1.0/tests/unit/test_wrap_to.py +13 -0
- unxts_api-2.0.2/docs/index.md +0 -229
- {unxts_api-2.0.2 → unxts_api-2.1.0}/LICENSE +0 -0
- {unxts_api-2.0.2 → unxts_api-2.1.0}/README.md +0 -0
- {unxts_api-2.0.2 → unxts_api-2.1.0}/src/unxts/api/__init__.py +0 -0
- {unxts_api-2.0.2 → unxts_api-2.1.0}/src/unxts/api/_src/__init__.py +0 -0
- {unxts_api-2.0.2 → unxts_api-2.1.0}/src/unxts/api/_src/dimensions.py +0 -0
- {unxts_api-2.0.2 → unxts_api-2.1.0}/src/unxts/api/_src/quantity.py +0 -0
- {unxts_api-2.0.2 → unxts_api-2.1.0}/src/unxts/api/_src/units.py +0 -0
- {unxts_api-2.0.2 → unxts_api-2.1.0}/src/unxts/api/_src/unitsystems.py +0 -0
- {unxts_api-2.0.2 → unxts_api-2.1.0}/src/unxts/api/py.typed +0 -0
|
@@ -80,7 +80,7 @@ instance/
|
|
|
80
80
|
|
|
81
81
|
# Sphinx documentation
|
|
82
82
|
docs/_build/
|
|
83
|
-
docs/
|
|
83
|
+
docs/how-to/optimize-performance.ipynb
|
|
84
84
|
|
|
85
85
|
# PyBuilder
|
|
86
86
|
.pybuilder/
|
|
@@ -164,3 +164,6 @@ Thumbs.db
|
|
|
164
164
|
*~
|
|
165
165
|
*.swp
|
|
166
166
|
/.codspeed
|
|
167
|
+
|
|
168
|
+
# graphify knowledge graph (generated; `nox -s graph`)
|
|
169
|
+
/graphify-out/
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: unxts.api
|
|
3
|
-
Version: 2.0
|
|
3
|
+
Version: 2.1.0
|
|
4
4
|
Summary: Abstract dispatch API definitions for unxt (canonical: unxts.api)
|
|
5
5
|
Project-URL: Bug Tracker, https://github.com/GalacticDynamics/unxt/issues
|
|
6
6
|
Project-URL: Homepage, https://github.com/GalacticDynamics/unxt
|
|
@@ -1,4 +1,18 @@
|
|
|
1
|
-
#
|
|
1
|
+
# API
|
|
2
|
+
|
|
3
|
+
Every abstract function `unxts.api` declares, with its signature, the implementations `unxt` registers for it, and an illustrative call.
|
|
4
|
+
|
|
5
|
+
The **Example Implementations** lists below are illustrative and hand-written, so they lag the code. For the authoritative set at any moment, ask the dispatch function itself — `plum` keeps the registry:
|
|
6
|
+
|
|
7
|
+
```{code-block} python
|
|
8
|
+
>>> import unxt # registers unxt's implementations
|
|
9
|
+
>>> import unxts.api as uapi
|
|
10
|
+
|
|
11
|
+
>>> len(uapi.dimension.methods) >= 2
|
|
12
|
+
True
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
Note the `import unxt`: the abstract functions carry no implementations until a provider is imported, so `f.methods` reflects whatever is loaded — including implementations added by third-party packages that this page cannot know about.
|
|
2
16
|
|
|
3
17
|
## Dimensions
|
|
4
18
|
|
|
@@ -1,8 +1,10 @@
|
|
|
1
|
-
#
|
|
1
|
+
# How to extend unxt with your own types
|
|
2
2
|
|
|
3
|
-
This guide shows how to
|
|
3
|
+
This guide shows you how to make your own type work with `unxt`'s functions — `unit_of`, `dimension_of`, `uconvert`, `ustrip` and the rest — by registering implementations through `unxts.api`'s multiple dispatch. You do not need to modify `unxt`, and your type does not need to inherit from anything.
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
For _why_ the API is built this way, see [Why an abstract dispatch API](why-abstract-dispatch).
|
|
6
|
+
|
|
7
|
+
## What you are extending
|
|
6
8
|
|
|
7
9
|
`unxt` uses [plum](https://beartype.github.io/plum/) for multiple dispatch, which means:
|
|
8
10
|
|
|
@@ -10,7 +12,7 @@ This guide shows how to extend `unxt` using the multiple dispatch system provide
|
|
|
10
12
|
- The **runtime types** of arguments determine which implementation executes
|
|
11
13
|
- You can **add new implementations** without modifying unxt's source code
|
|
12
14
|
|
|
13
|
-
##
|
|
15
|
+
## Register your first implementation
|
|
14
16
|
|
|
15
17
|
Let's say you have a custom quantity type and want it to work with unxt's functions:
|
|
16
18
|
|
|
@@ -50,42 +52,30 @@ u.unit_of(temp) # Unit("K")
|
|
|
50
52
|
u.dimension_of(temp) # PhysicalType('temperature')
|
|
51
53
|
```
|
|
52
54
|
|
|
53
|
-
##
|
|
54
|
-
|
|
55
|
-
### Step 1: Import the Abstract Function
|
|
56
|
-
|
|
57
|
-
Import the abstract function from `unxts.api`:
|
|
58
|
-
|
|
59
|
-
```python
|
|
60
|
-
from unxts.api import unit_of, dimension_of, uconvert
|
|
61
|
-
```
|
|
62
|
-
|
|
63
|
-
### Step 2: Use `@dispatch` Decorator
|
|
55
|
+
## What registration actually does
|
|
64
56
|
|
|
65
|
-
|
|
57
|
+
A bare `@dispatch` needs no import of the function you are extending. `plum.dispatch` is one shared dispatcher, and it files module-level functions under their bare `__name__`, so a function you call `unit_of` becomes part of _the_ `unit_of` wherever you define it:
|
|
66
58
|
|
|
67
59
|
```python
|
|
68
60
|
from plum import dispatch
|
|
61
|
+
import unxt as u
|
|
69
62
|
|
|
70
63
|
|
|
71
64
|
@dispatch
|
|
72
65
|
def unit_of(obj: Temperature, /) -> u.AbstractUnit:
|
|
73
|
-
"""
|
|
66
|
+
"""Get unit from Temperature."""
|
|
74
67
|
return u.unit(obj.unit_str)
|
|
75
|
-
```
|
|
76
68
|
|
|
77
|
-
### Step 3: Implement the Logic
|
|
78
69
|
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
```python
|
|
82
|
-
@dispatch
|
|
83
|
-
def unit_of(obj: Temperature, /) -> u.AbstractUnit:
|
|
84
|
-
"""Get unit from Temperature object."""
|
|
85
|
-
return u.unit(obj.unit_str)
|
|
70
|
+
assert unit_of is u.unit_of # the same object, with one more method
|
|
86
71
|
```
|
|
87
72
|
|
|
88
|
-
|
|
73
|
+
Two consequences worth keeping in mind:
|
|
74
|
+
|
|
75
|
+
- **The name is the whole key.** A `@dispatch def unit_of` you meant as a private helper joins `unxt`'s function too. Name these after the API function you intend to extend, and nothing else.
|
|
76
|
+
- **The annotations are the contract.** Dispatch selects on the annotated argument types, so an unannotated parameter matches anything and a wrong annotation silently never fires.
|
|
77
|
+
|
|
78
|
+
## Common patterns
|
|
89
79
|
|
|
90
80
|
### Adding Unit Support to Custom Types
|
|
91
81
|
|
|
@@ -227,7 +217,7 @@ sys["length"] # Unit("kpc")
|
|
|
227
217
|
sys["time"] # Unit("Myr")
|
|
228
218
|
```
|
|
229
219
|
|
|
230
|
-
##
|
|
220
|
+
## Harder cases
|
|
231
221
|
|
|
232
222
|
### Conditional Dispatch Based on Multiple Arguments
|
|
233
223
|
|
|
@@ -247,15 +237,22 @@ class SpecialQuantity:
|
|
|
247
237
|
@dispatch
|
|
248
238
|
def uconvert(to_unit: str, obj: SpecialQuantity, /):
|
|
249
239
|
"""Convert SpecialQuantity when target is a string."""
|
|
250
|
-
|
|
251
|
-
return SpecialQuantity(
|
|
240
|
+
value = u.ustrip(to_unit, u.Q(obj.value, obj.unit))
|
|
241
|
+
return SpecialQuantity(value, to_unit)
|
|
252
242
|
|
|
253
243
|
|
|
254
244
|
@dispatch
|
|
255
245
|
def uconvert(to_unit: u.AbstractUnit, obj: SpecialQuantity, /):
|
|
256
|
-
"""Convert SpecialQuantity when target is
|
|
257
|
-
|
|
258
|
-
return SpecialQuantity(
|
|
246
|
+
"""Convert SpecialQuantity when target is a Unit object."""
|
|
247
|
+
value = u.ustrip(to_unit, u.Q(obj.value, obj.unit))
|
|
248
|
+
return SpecialQuantity(value, str(to_unit))
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
# Both branches now resolve: `ustrip` takes (unit, quantity), so the raw value
|
|
252
|
+
# and its unit have to be assembled into a Quantity first.
|
|
253
|
+
sq = SpecialQuantity(1000.0, "m")
|
|
254
|
+
u.uconvert("km", sq).unit # 'km'
|
|
255
|
+
u.uconvert(u.unit("km"), sq).unit # 'km'
|
|
259
256
|
```
|
|
260
257
|
|
|
261
258
|
### Handling Multiple Dispatch Signatures
|
|
@@ -313,7 +310,7 @@ class MyClass:
|
|
|
313
310
|
u.unit_of(MyClass()) # None
|
|
314
311
|
```
|
|
315
312
|
|
|
316
|
-
##
|
|
313
|
+
## When dispatch does not do what you expect
|
|
317
314
|
|
|
318
315
|
### Viewing All Implementations
|
|
319
316
|
|
|
@@ -413,7 +410,7 @@ def my_func(obj: C, /):
|
|
|
413
410
|
my_func(C()) # "C" - now unambiguous
|
|
414
411
|
```
|
|
415
412
|
|
|
416
|
-
##
|
|
413
|
+
## Rules worth following
|
|
417
414
|
|
|
418
415
|
### 1. Use Type Annotations
|
|
419
416
|
|
|
@@ -502,7 +499,7 @@ def test_temperature_conversion():
|
|
|
502
499
|
assert abs(temp_k.value - 273.15) < 1e-10
|
|
503
500
|
```
|
|
504
501
|
|
|
505
|
-
##
|
|
502
|
+
## Shipping it in a package
|
|
506
503
|
|
|
507
504
|
### Minimal Dependency Package
|
|
508
505
|
|
|
@@ -560,8 +557,9 @@ else:
|
|
|
560
557
|
|
|
561
558
|
Users can use your package with or without unxt!
|
|
562
559
|
|
|
563
|
-
## See
|
|
560
|
+
## See also
|
|
564
561
|
|
|
565
|
-
- [
|
|
562
|
+
- [API](api) — what each abstract function promises.
|
|
563
|
+
- [Why an abstract dispatch API](why-abstract-dispatch) — and what it costs.
|
|
566
564
|
- [plum Documentation](https://beartype.github.io/plum/)
|
|
567
565
|
- [unxt Documentation](https://unxt.readthedocs.io/)
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
# `unxts.api`
|
|
2
|
+
|
|
3
|
+
```{toctree}
|
|
4
|
+
:maxdepth: 1
|
|
5
|
+
:hidden:
|
|
6
|
+
|
|
7
|
+
tutorial-your-own-type
|
|
8
|
+
why-abstract-dispatch
|
|
9
|
+
extending
|
|
10
|
+
api
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Abstract dispatch API for [unxt](https://github.com/GalacticDynamics/unxt).
|
|
14
|
+
|
|
15
|
+
:::{note}
|
|
16
|
+
|
|
17
|
+
`unxts.api` is the canonical package. The legacy `unxt-api` distribution remains available as a thin backward-compatible shim that re-exports this package, so existing `import unxt_api` code keeps working unchanged.
|
|
18
|
+
|
|
19
|
+
:::
|
|
20
|
+
|
|
21
|
+
`unxts.api` declares the abstract dispatch interfaces that `unxt` and other packages implement. It depends only on `plum` — not on `jax`, `numpy` or `astropy` — so a package can speak `unxt`'s API without pulling in its implementation.
|
|
22
|
+
|
|
23
|
+
## Install
|
|
24
|
+
|
|
25
|
+
::::{tab-set}
|
|
26
|
+
|
|
27
|
+
:::{tab-item} uv
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
uv add unxts.api
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
:::
|
|
34
|
+
|
|
35
|
+
:::{tab-item} pip
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
pip install unxts.api
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
:::
|
|
42
|
+
|
|
43
|
+
::::
|
|
44
|
+
|
|
45
|
+
## At a glance
|
|
46
|
+
|
|
47
|
+
`unxts.api` declares the function; `unxt` registers the implementation that runs.
|
|
48
|
+
|
|
49
|
+
```python
|
|
50
|
+
import unxt as u
|
|
51
|
+
|
|
52
|
+
q = u.Q(5, "m")
|
|
53
|
+
u.uconvert("km", q)
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
`u.uconvert` here is `unxt`'s registered implementation of the abstract `unxts.api.uconvert`. To make your own type work with the same call, you register an implementation of your own — see [Extending](extending).
|
|
57
|
+
|
|
58
|
+
## Pages
|
|
59
|
+
|
|
60
|
+
**Tutorial**
|
|
61
|
+
|
|
62
|
+
- [Teach unxt about your own type](tutorial-your-own-type) — start here: make `unit_of`, `dimension_of`, `ustrip` and `uconvert` work on a class of your own.
|
|
63
|
+
|
|
64
|
+
**Discussion**
|
|
65
|
+
|
|
66
|
+
- [Why an abstract dispatch API](why-abstract-dispatch) — what the separation between interface and implementation buys, and what it costs.
|
|
67
|
+
|
|
68
|
+
**How-to**
|
|
69
|
+
|
|
70
|
+
- [How to extend unxt with your own types](extending) — registering implementations, the common patterns, and debugging dispatch.
|
|
71
|
+
|
|
72
|
+
**Reference**
|
|
73
|
+
|
|
74
|
+
- [API](api) — every abstract function, its signature and its registered implementations in `unxt`.
|
|
75
|
+
|
|
76
|
+
## Public API
|
|
77
|
+
|
|
78
|
+
The abstract functions, by domain:
|
|
79
|
+
|
|
80
|
+
| Domain | Functions |
|
|
81
|
+
| --- | --- |
|
|
82
|
+
| Dimensions | {func}`~unxt.dims.dimension`, {func}`~unxt.dims.dimension_of` |
|
|
83
|
+
| Units | {func}`~unxt.units.unit`, {func}`~unxt.units.unit_of` |
|
|
84
|
+
| Quantities | {func}`~unxt.quantity.uconvert`, {func}`~unxt.quantity.uconvert_value`, {func}`~unxt.quantity.ustrip`, {func}`~unxt.quantity.is_unit_convertible`, {func}`~unxt.quantity.wrap_to` |
|
|
85
|
+
| Unit systems | {func}`~unxt.unitsystems.unitsystem_of` |
|
|
86
|
+
|
|
87
|
+
Every one is a [plum](https://beartype.github.io/plum/) dispatch function, so `f.methods` lists what is currently registered:
|
|
88
|
+
|
|
89
|
+
```python
|
|
90
|
+
import unxts.api as uapi
|
|
91
|
+
|
|
92
|
+
uapi.dimension.methods
|
|
93
|
+
uapi.unit_of.methods
|
|
94
|
+
uapi.uconvert.methods
|
|
95
|
+
uapi.uconvert_value.methods
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
## See also
|
|
99
|
+
|
|
100
|
+
- [unxt documentation](https://unxt.readthedocs.io/) — the concrete implementation.
|
|
101
|
+
- [plum documentation](https://beartype.github.io/plum/) — the dispatch library.
|
|
102
|
+
- [unxt on GitHub](https://github.com/GalacticDynamics/unxt)
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
# Teach unxt about your own type
|
|
2
|
+
|
|
3
|
+
Take a class that `unxt` has never heard of. By the end of this page, `unxt`'s own functions will work on it — `unit_of`, `dimension_of`, `ustrip`, `uconvert` — with nothing subclassed and not a line of `unxt` touched. A function written against `unxt`'s API will accept our class as readily as it accepts a `Quantity`.
|
|
4
|
+
|
|
5
|
+
You need `unxt` installed and nothing else. (`unxts.api` comes with it.)
|
|
6
|
+
|
|
7
|
+
## Set up
|
|
8
|
+
|
|
9
|
+
```{code-block} python
|
|
10
|
+
>>> from plum import dispatch
|
|
11
|
+
>>> import unxt as u
|
|
12
|
+
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## Start with a type unxt does not know
|
|
16
|
+
|
|
17
|
+
Here is a small class standing in for whatever your project already has — a raw instrument reading, a number with a unit name attached:
|
|
18
|
+
|
|
19
|
+
```{code-block} python
|
|
20
|
+
>>> class Reading:
|
|
21
|
+
... """A raw instrument reading: a number and a unit name."""
|
|
22
|
+
... def __init__(self, value, unit):
|
|
23
|
+
... self.value = value
|
|
24
|
+
... self.unit = unit
|
|
25
|
+
... def __repr__(self):
|
|
26
|
+
... return f"Reading({self.value}, {self.unit!r})"
|
|
27
|
+
|
|
28
|
+
>>> r = Reading(2000.0, "m")
|
|
29
|
+
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
Ask `unxt` about it:
|
|
33
|
+
|
|
34
|
+
```{code-block} python
|
|
35
|
+
>>> print(u.unit_of(r))
|
|
36
|
+
None
|
|
37
|
+
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
`None` — not an error. `unit_of` has a fallback for objects it does not recognise, and as far as it is concerned our `Reading` is just some object. The `"m"` sitting right there in the attribute means nothing to it yet.
|
|
41
|
+
|
|
42
|
+
## Register the first implementation
|
|
43
|
+
|
|
44
|
+
Now we tell `unxt` how to find the unit. Define a function named `unit_of`, annotate the argument with our type, and decorate it with `plum`'s `dispatch`:
|
|
45
|
+
|
|
46
|
+
```{code-block} python
|
|
47
|
+
>>> @dispatch
|
|
48
|
+
... def unit_of(obj: Reading, /):
|
|
49
|
+
... return u.unit(obj.unit)
|
|
50
|
+
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
That is the entire registration. Ask again:
|
|
54
|
+
|
|
55
|
+
```{code-block} python
|
|
56
|
+
>>> u.unit_of(r)
|
|
57
|
+
Unit("m")
|
|
58
|
+
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
Look carefully at what just happened. We called `u.unit_of` — `unxt`'s function, the one we did not modify — and it dispatched into the implementation we wrote a moment ago:
|
|
62
|
+
|
|
63
|
+
```{code-block} python
|
|
64
|
+
>>> unit_of is u.unit_of
|
|
65
|
+
True
|
|
66
|
+
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
The same object, with one more method on it. We never imported `unit_of`, and we did not need to: `plum.dispatch` is a single shared dispatcher, and it files module-level functions under their bare `__name__`. Writing `@dispatch` on a function called `unit_of` puts your implementation into the one and only `unit_of`, wherever in your codebase you wrote it.
|
|
70
|
+
|
|
71
|
+
That cuts both ways, so it is worth saying plainly: the name is the whole key. A `@dispatch def unit_of` you meant as your own private helper would join `unxt`'s function too. Name these after the API function you intend to extend, and nothing else.
|
|
72
|
+
|
|
73
|
+
## Add the dimension
|
|
74
|
+
|
|
75
|
+
Same pattern. Once `unxt` can get the unit, the dimension follows from it:
|
|
76
|
+
|
|
77
|
+
```{code-block} python
|
|
78
|
+
>>> @dispatch
|
|
79
|
+
... def dimension_of(obj: Reading, /):
|
|
80
|
+
... return u.dimension_of(u.unit_of(obj))
|
|
81
|
+
|
|
82
|
+
>>> u.dimension_of(r)
|
|
83
|
+
PhysicalType('length')
|
|
84
|
+
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
Notice our implementation called `u.unit_of(obj)` — the function we had just extended. Registrations compose; each one you add makes the next one shorter.
|
|
88
|
+
|
|
89
|
+
## Watch generic code accept it
|
|
90
|
+
|
|
91
|
+
Here is the payoff. Write a function that knows nothing about `Reading` and only uses `unxt`'s API:
|
|
92
|
+
|
|
93
|
+
```{code-block} python
|
|
94
|
+
>>> def describe(x):
|
|
95
|
+
... return f"{u.dimension_of(x)} measured in {u.unit_of(x)}"
|
|
96
|
+
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
Hand it a `Quantity`:
|
|
100
|
+
|
|
101
|
+
```{code-block} python
|
|
102
|
+
>>> describe(u.Q(5.0, "m"))
|
|
103
|
+
'length measured in m'
|
|
104
|
+
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
and hand it our `Reading`:
|
|
108
|
+
|
|
109
|
+
```{code-block} python
|
|
110
|
+
>>> describe(r)
|
|
111
|
+
'length measured in m'
|
|
112
|
+
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
The same function, unchanged, for both. `describe` could have been written by someone else, in another library, before our class existed — this is what the abstract API is for.
|
|
116
|
+
|
|
117
|
+
## Make it convert
|
|
118
|
+
|
|
119
|
+
Two more registrations and `Reading` supports unit conversion. `ustrip` returns the bare number in the requested unit:
|
|
120
|
+
|
|
121
|
+
```{code-block} python
|
|
122
|
+
>>> @dispatch
|
|
123
|
+
... def ustrip(to: u.AbstractUnit, obj: Reading, /):
|
|
124
|
+
... return u.ustrip(to, u.Q(obj.value, obj.unit))
|
|
125
|
+
|
|
126
|
+
>>> u.ustrip(u.unit("km"), r)
|
|
127
|
+
Array(2., dtype=float32, weak_type=True)
|
|
128
|
+
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
and `uconvert` returns a converted object of our own type:
|
|
132
|
+
|
|
133
|
+
```{code-block} python
|
|
134
|
+
>>> @dispatch
|
|
135
|
+
... def uconvert(to: u.AbstractUnit, obj: Reading, /):
|
|
136
|
+
... return Reading(float(u.ustrip(to, obj)), str(to))
|
|
137
|
+
|
|
138
|
+
>>> u.uconvert(u.unit("km"), r)
|
|
139
|
+
Reading(2.0, 'km')
|
|
140
|
+
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
2000 metres came back as 2.0 kilometres, still a `Reading`. We borrowed `unxt`'s conversion machinery for the arithmetic and kept our own type on the outside.
|
|
144
|
+
|
|
145
|
+
## What we built
|
|
146
|
+
|
|
147
|
+
`Reading` now answers to four of `unxt`'s functions, and generic unit-aware code works on it. We never subclassed an `unxt` class, never edited `unxt`, and never imported `jax` — which is the point of `unxts.api` being a separate package: a library can speak this API while leaving the choice of whether to install `unxt` itself to its users.
|
|
148
|
+
|
|
149
|
+
## Where to go next
|
|
150
|
+
|
|
151
|
+
- [How to extend unxt with your own types](extending) — the rest of the patterns: conversion in both directions, fallbacks, and debugging dispatch.
|
|
152
|
+
- [API](api) — every abstract function and what it promises.
|
|
153
|
+
- [Why an abstract dispatch API](why-abstract-dispatch) — and what the approach costs.
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
# Why an abstract dispatch API
|
|
2
|
+
|
|
3
|
+
`unxts.api` contains almost no code. It declares a dozen functions with `plum.dispatch.abstract` and implements none of them; `unxt` supplies the bodies. Splitting a package in half like that is unusual enough to be worth justifying.
|
|
4
|
+
|
|
5
|
+
## The dependency argument
|
|
6
|
+
|
|
7
|
+
`unxt` depends on JAX, NumPy and astropy. That is the right cost for a library whose job is unitful JAX arrays, and the wrong cost for a library that merely wants to _interoperate_ with one.
|
|
8
|
+
|
|
9
|
+
Consider a package defining its own physical-quantity type. It would like `unit_of(my_thing)` to work, so that code written against `unxt`'s API accepts its type too. Without the split, that means depending on `unxt` — and therefore on JAX — to gain an interface it will never call into. With the split, it depends on `unxts.api` and `plum`, and its users decide whether `unxt` is also installed.
|
|
10
|
+
|
|
11
|
+
That is the concrete win, and it is why the boundary is drawn where it is: at the point where "what functions exist and what they mean" separates from "how they work on JAX arrays".
|
|
12
|
+
|
|
13
|
+
## Why dispatch rather than an ABC
|
|
14
|
+
|
|
15
|
+
The conventional way to express "here is an interface, implement it" is an abstract base class. Multiple dispatch is a better fit here for one reason: the types being extended are usually **not yours to subclass**.
|
|
16
|
+
|
|
17
|
+
`unxt` supports astropy quantities, and — through the `unxts.interop.*` packages — `gala` unit systems and `xarray` objects. None of those can be made to inherit from an `unxt` base class; they belong to other projects. With dispatch, support is added from the outside, by registering a function on a type you do not own. The same mechanism serves third parties adding support for _their_ types without anyone modifying `unxt`.
|
|
18
|
+
|
|
19
|
+
A second, smaller benefit: dispatch selects on _all_ arguments, not just the first. `uconvert_value(to_unit, from_unit, value)` genuinely varies with the combination of unit types, and a method on one receiver would have to re-dispatch internally on the others.
|
|
20
|
+
|
|
21
|
+
## What it costs
|
|
22
|
+
|
|
23
|
+
The separation is not free, and it is honest to name the costs:
|
|
24
|
+
|
|
25
|
+
- **Errors move to call time.** A missing implementation surfaces as `plum.NotFoundLookupError` when the call happens, not as an unimplemented abstract method at class definition. A static type checker will not catch it.
|
|
26
|
+
- **The contract lives in prose.** An abstract signature annotated `Any -> Any` documents very little; what `dimension_of` is _supposed_ to return for your type is stated in the [reference](api) rather than enforced.
|
|
27
|
+
- **Registration is a side effect.** Implementations arrive when a module is imported. That makes import order matter in a way it would not with explicit registration, and it is why `unxts.parametric` documents that you must import it for its primitive rules to exist.
|
|
28
|
+
|
|
29
|
+
These are real, and they are the reason the API package stays small: the wider the abstract surface, the more contract there is to keep honest in prose.
|
|
30
|
+
|
|
31
|
+
## See also
|
|
32
|
+
|
|
33
|
+
- [How to extend unxt with your own types](extending) — the mechanics.
|
|
34
|
+
- [API](api) — what each abstract function promises.
|
|
35
|
+
- [About unxt's API conventions](../../explanation/api-conventions) — why `unxt` pairs a functional and an object-oriented form for each of these.
|
|
@@ -46,7 +46,7 @@ requires = ["hatch-vcs", "hatchling"]
|
|
|
46
46
|
# cycle); as a dev/test-group dependency the cycle is dev-only and uv resolves
|
|
47
47
|
# it within the workspace.
|
|
48
48
|
test = [
|
|
49
|
-
"optional-dependencies>=0.
|
|
49
|
+
"optional-dependencies>=0.4.1",
|
|
50
50
|
"pytest>=8.4.2",
|
|
51
51
|
"pytest-arraydiff>=0.6.1",
|
|
52
52
|
"pytest-cov>=6.2.1",
|
|
@@ -18,7 +18,7 @@ version_tuple: tuple[int | str, ...]
|
|
|
18
18
|
commit_id: str | None
|
|
19
19
|
__commit_id__: str | None
|
|
20
20
|
|
|
21
|
-
__version__ = version = '2.0
|
|
22
|
-
__version_tuple__ = version_tuple = (2,
|
|
21
|
+
__version__ = version = '2.1.0'
|
|
22
|
+
__version_tuple__ = version_tuple = (2, 1, 0)
|
|
23
23
|
|
|
24
24
|
__commit_id__ = commit_id = None
|
|
@@ -17,13 +17,3 @@ def test_dispatch_functions_are_callable():
|
|
|
17
17
|
|
|
18
18
|
def test_version_is_a_string():
|
|
19
19
|
assert isinstance(unxts.api.__version__, str)
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
def test_wrap_to_keyword_form_redirects_to_positional():
|
|
23
|
-
"""``wrap_to(x, min=..., max=...)`` forwards to the positional method."""
|
|
24
|
-
|
|
25
|
-
@unxts.api.wrap_to.dispatch
|
|
26
|
-
def _(x: int, min: int, max: int, /) -> tuple:
|
|
27
|
-
return (x, min, max)
|
|
28
|
-
|
|
29
|
-
assert unxts.api.wrap_to(1, min=2, max=3) == (1, 2, 3)
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"""Tests for unxts.api.wrap_to dispatch behavior."""
|
|
2
|
+
|
|
3
|
+
import unxts.api
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def test_wrap_to_keyword_form_redirects_to_positional():
|
|
7
|
+
"""``wrap_to(x, min=..., max=...)`` forwards to the positional method."""
|
|
8
|
+
|
|
9
|
+
@unxts.api.wrap_to.dispatch
|
|
10
|
+
def _(x: int, min: int, max: int, /) -> tuple:
|
|
11
|
+
return (x, min, max)
|
|
12
|
+
|
|
13
|
+
assert unxts.api.wrap_to(1, min=2, max=3) == (1, 2, 3)
|
unxts_api-2.0.2/docs/index.md
DELETED
|
@@ -1,229 +0,0 @@
|
|
|
1
|
-
# `unxts.api`
|
|
2
|
-
|
|
3
|
-
```{toctree}
|
|
4
|
-
:maxdepth: 1
|
|
5
|
-
:hidden:
|
|
6
|
-
|
|
7
|
-
api
|
|
8
|
-
extending
|
|
9
|
-
```
|
|
10
|
-
|
|
11
|
-
Abstract dispatch API for [unxt](https://github.com/GalacticDynamics/unxt).
|
|
12
|
-
|
|
13
|
-
:::{note}
|
|
14
|
-
|
|
15
|
-
`unxts.api` is the canonical package. The legacy `unxt-api` distribution remains available as a thin backward-compatible shim that re-exports this package, so existing `import unxt_api` code keeps working unchanged.
|
|
16
|
-
|
|
17
|
-
:::
|
|
18
|
-
|
|
19
|
-
`unxts.api` defines the abstract dispatch interfaces that `unxt` and other packages implement. It provides a minimal dependency foundation for packages that want to define or use `unxt`'s multiple-dispatch-based API without pulling in the full `unxt` implementation.
|
|
20
|
-
|
|
21
|
-
The `unxts.api` package serves several important purposes:
|
|
22
|
-
|
|
23
|
-
1. **Minimal Dependencies**: Depends only on `plum`, not on `jax`, `numpy`, or `astropy`
|
|
24
|
-
2. **Extensibility**: Allows third-party packages to register their own implementations
|
|
25
|
-
3. **Type Safety**: Provides a clear contract for what functions exist and what they should do
|
|
26
|
-
4. **Separation of Concerns**: API definitions are separate from implementation details
|
|
27
|
-
|
|
28
|
-
## Installation
|
|
29
|
-
|
|
30
|
-
::::{tab-set}
|
|
31
|
-
|
|
32
|
-
:::{tab-item} pip
|
|
33
|
-
|
|
34
|
-
```bash
|
|
35
|
-
pip install unxts.api
|
|
36
|
-
```
|
|
37
|
-
|
|
38
|
-
:::
|
|
39
|
-
|
|
40
|
-
:::{tab-item} uv
|
|
41
|
-
|
|
42
|
-
```bash
|
|
43
|
-
uv add unxts.api
|
|
44
|
-
```
|
|
45
|
-
|
|
46
|
-
:::
|
|
47
|
-
|
|
48
|
-
::::
|
|
49
|
-
|
|
50
|
-
## Core API
|
|
51
|
-
|
|
52
|
-
The `unxts.api` package defines abstract dispatch functions organized by domain:
|
|
53
|
-
|
|
54
|
-
- **Dimensions** ({func}`~unxt.dims.dimension`, {func}`~unxt.dims.dimension_of`) - Working with physical dimensions
|
|
55
|
-
- **Units** ({func}`~unxt.units.unit`, {func}`~unxt.units.unit_of`) - Constructing and inspecting units
|
|
56
|
-
- **Quantities** ({func}`~unxt.quantity.uconvert`, {func}`~unxt.quantity.uconvert_value`, {func}`~unxt.quantity.ustrip`, {func}`~unxt.quantity.is_unit_convertible`, {func}`~unxt.quantity.wrap_to`) - Unit conversion and quantity operations
|
|
57
|
-
- **Unit Systems** ({func}`~unxt.unitsystems.unitsystem_of`) - Inspecting unit systems
|
|
58
|
-
|
|
59
|
-
## Using Multiple Dispatch
|
|
60
|
-
|
|
61
|
-
All functions in `unxts.api` use [plum](https://beartype.github.io/plum/) for multiple dispatch. This means:
|
|
62
|
-
|
|
63
|
-
1. **Functions can have multiple implementations** based on argument types
|
|
64
|
-
2. **You can register your own implementations** for custom types
|
|
65
|
-
3. **Type annotations drive dispatch** - the runtime types of arguments determine which implementation runs
|
|
66
|
-
|
|
67
|
-
### Viewing All Implementations
|
|
68
|
-
|
|
69
|
-
To see all registered implementations of a function:
|
|
70
|
-
|
|
71
|
-
```python
|
|
72
|
-
import unxts.api as uapi
|
|
73
|
-
|
|
74
|
-
# View all dimension() implementations
|
|
75
|
-
uapi.dimension.methods
|
|
76
|
-
|
|
77
|
-
# View all uconvert() implementations
|
|
78
|
-
uapi.uconvert.methods
|
|
79
|
-
|
|
80
|
-
# View all unit_of() implementations
|
|
81
|
-
uapi.unit_of.methods
|
|
82
|
-
```
|
|
83
|
-
|
|
84
|
-
### Registering Custom Implementations
|
|
85
|
-
|
|
86
|
-
You can extend `unxts.api`'s dispatch system with your own types:
|
|
87
|
-
|
|
88
|
-
```python
|
|
89
|
-
from plum import dispatch
|
|
90
|
-
|
|
91
|
-
import unxt as u # concrete provider for the abstract API (unit(), ...)
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
class MyCustomQuantity:
|
|
95
|
-
def __init__(self, value, unit_str):
|
|
96
|
-
self.value = value
|
|
97
|
-
self.unit_str = unit_str
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
# Register an implementation of the abstract ``unit_of`` for your type. A bare
|
|
101
|
-
# ``@dispatch`` extends the existing dispatch function of the same name.
|
|
102
|
-
@dispatch
|
|
103
|
-
def unit_of(obj: MyCustomQuantity, /):
|
|
104
|
-
"""Get unit from MyCustomQuantity."""
|
|
105
|
-
return u.unit(obj.unit_str)
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
# Now it works with the dispatch system
|
|
109
|
-
my_q = MyCustomQuantity(5.0, "m")
|
|
110
|
-
u.unit_of(my_q) # Unit("m")
|
|
111
|
-
```
|
|
112
|
-
|
|
113
|
-
<!-- ## Design Philosophy
|
|
114
|
-
|
|
115
|
-
### Why Abstract Dispatch?
|
|
116
|
-
|
|
117
|
-
The abstract dispatch pattern used in `unxts.api` provides several benefits:
|
|
118
|
-
|
|
119
|
-
1. **Extensibility**: Third-party packages can add support for their types
|
|
120
|
-
without modifying unxt
|
|
121
|
-
2. **Type Safety**: The abstract signatures document what the API expects
|
|
122
|
-
3. **Flexibility**: Multiple implementations can coexist, selected automatically
|
|
123
|
-
by type
|
|
124
|
-
4. **Loose Coupling**: Packages can depend on the API without the full
|
|
125
|
-
implementation
|
|
126
|
-
|
|
127
|
-
### API vs Implementation
|
|
128
|
-
|
|
129
|
-
- **`unxts.api`**: Defines _what_ functions exist and their contracts (this
|
|
130
|
-
package)
|
|
131
|
-
- **`unxt`**: Provides _how_ those functions work with JAX arrays and physical
|
|
132
|
-
units
|
|
133
|
-
|
|
134
|
-
This separation allows:
|
|
135
|
-
|
|
136
|
-
- Lightweight packages to depend only on the API
|
|
137
|
-
- Multiple implementations of the same API
|
|
138
|
-
- Clear boundaries between interface and implementation -->
|
|
139
|
-
|
|
140
|
-
## Integration with `unxt`
|
|
141
|
-
|
|
142
|
-
The `unxt` package provides the concrete implementations of all `unxts.api` functions. When you use:
|
|
143
|
-
|
|
144
|
-
```python
|
|
145
|
-
import unxt as u
|
|
146
|
-
|
|
147
|
-
q = u.Q(5, "m")
|
|
148
|
-
u.uconvert("km", q)
|
|
149
|
-
```
|
|
150
|
-
|
|
151
|
-
The `u.uconvert` function is the implementation registered by `unxt` for the abstract `uapi.uconvert` function.
|
|
152
|
-
|
|
153
|
-
## For Package Authors
|
|
154
|
-
|
|
155
|
-
If you're writing a package that works with physical quantities:
|
|
156
|
-
|
|
157
|
-
### Minimal Dependency Approach
|
|
158
|
-
|
|
159
|
-
Depend on `unxts.api` to use the dispatch system without pulling in `jax`:
|
|
160
|
-
|
|
161
|
-
```toml
|
|
162
|
-
# pyproject.toml
|
|
163
|
-
[project]
|
|
164
|
-
dependencies = ["unxts.api>=X.Y.Z"]
|
|
165
|
-
```
|
|
166
|
-
|
|
167
|
-
Then register your implementations:
|
|
168
|
-
|
|
169
|
-
```python
|
|
170
|
-
from plum import dispatch
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
# Define a custom type (example)
|
|
174
|
-
class YourType:
|
|
175
|
-
def __init__(self, value, unit_str, dim_str):
|
|
176
|
-
self.value = value
|
|
177
|
-
self.unit = unit_str
|
|
178
|
-
self.dimension = dim_str
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
@dispatch
|
|
182
|
-
def unit_of(obj: YourType, /):
|
|
183
|
-
"""Get unit from your type."""
|
|
184
|
-
return obj.unit
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
@dispatch
|
|
188
|
-
def dimension_of(obj: YourType, /):
|
|
189
|
-
"""Get dimension from your type."""
|
|
190
|
-
return obj.dimension
|
|
191
|
-
```
|
|
192
|
-
|
|
193
|
-
### Full Integration Approach
|
|
194
|
-
|
|
195
|
-
If you need JAX and want full `unxt` functionality:
|
|
196
|
-
|
|
197
|
-
```toml
|
|
198
|
-
# pyproject.toml
|
|
199
|
-
[project]
|
|
200
|
-
dependencies = [
|
|
201
|
-
"unxt>=X.Y.Z", # Includes unxts.api transitively
|
|
202
|
-
]
|
|
203
|
-
```
|
|
204
|
-
|
|
205
|
-
Then use `unxt`'s types directly:
|
|
206
|
-
|
|
207
|
-
```python
|
|
208
|
-
import unxt as u
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
@dispatch
|
|
212
|
-
def your_function(q: u.Q, /):
|
|
213
|
-
"""Work with unxt quantities."""
|
|
214
|
-
return q * 2
|
|
215
|
-
```
|
|
216
|
-
|
|
217
|
-
## See Also
|
|
218
|
-
|
|
219
|
-
- [unxt Documentation](https://unxt.readthedocs.io/) - Full implementation with examples
|
|
220
|
-
- [plum Documentation](https://beartype.github.io/plum/) - Multiple dispatch library
|
|
221
|
-
- [unxt on GitHub](https://github.com/GalacticDynamics/unxt)
|
|
222
|
-
|
|
223
|
-
## License
|
|
224
|
-
|
|
225
|
-
BSD 3-Clause License. See [LICENSE](https://github.com/GalacticDynamics/unxt/blob/main/LICENSE) for details.
|
|
226
|
-
|
|
227
|
-
## Contributing
|
|
228
|
-
|
|
229
|
-
Contributions are welcome! Please see the main [unxt repository](https://github.com/GalacticDynamics/unxt) for contributing guidelines.
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|