unxts.interop.xarray 2.0.1__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.
Files changed (24) hide show
  1. {unxts_interop_xarray-2.0.1 → unxts_interop_xarray-2.1.0}/.gitignore +4 -1
  2. {unxts_interop_xarray-2.0.1 → unxts_interop_xarray-2.1.0}/PKG-INFO +1 -1
  3. unxts_interop_xarray-2.1.0/docs/api.md +99 -0
  4. unxts_interop_xarray-2.1.0/docs/index.md +105 -0
  5. unxts_interop_xarray-2.1.0/docs/sharp-bits.md +42 -0
  6. unxts_interop_xarray-2.1.0/docs/tutorial-first-dataset.md +158 -0
  7. {unxts_interop_xarray-2.0.1 → unxts_interop_xarray-2.1.0}/docs/xarray-guide.md +11 -147
  8. {unxts_interop_xarray-2.0.1 → unxts_interop_xarray-2.1.0}/src/unxts/interop/xarray/_src/conversion.py +39 -22
  9. {unxts_interop_xarray-2.0.1 → unxts_interop_xarray-2.1.0}/src/unxts/interop/xarray/_version.py +2 -2
  10. unxts_interop_xarray-2.0.1/docs/index.md +0 -224
  11. {unxts_interop_xarray-2.0.1 → unxts_interop_xarray-2.1.0}/LICENSE +0 -0
  12. {unxts_interop_xarray-2.0.1 → unxts_interop_xarray-2.1.0}/README.md +0 -0
  13. {unxts_interop_xarray-2.0.1 → unxts_interop_xarray-2.1.0}/docs/_data/README.md +0 -0
  14. {unxts_interop_xarray-2.0.1 → unxts_interop_xarray-2.1.0}/docs/_data/generate_sample_data.py +0 -0
  15. {unxts_interop_xarray-2.0.1 → unxts_interop_xarray-2.1.0}/docs/_data/sample_data.nc +0 -0
  16. {unxts_interop_xarray-2.0.1 → unxts_interop_xarray-2.1.0}/pyproject.toml +0 -0
  17. {unxts_interop_xarray-2.0.1 → unxts_interop_xarray-2.1.0}/src/unxts/interop/xarray/__init__.py +0 -0
  18. {unxts_interop_xarray-2.0.1 → unxts_interop_xarray-2.1.0}/src/unxts/interop/xarray/_src/__init__.py +0 -0
  19. {unxts_interop_xarray-2.0.1 → unxts_interop_xarray-2.1.0}/src/unxts/interop/xarray/_src/accessors.py +0 -0
  20. {unxts_interop_xarray-2.0.1 → unxts_interop_xarray-2.1.0}/src/unxts/interop/xarray/py.typed +0 -0
  21. {unxts_interop_xarray-2.0.1/tests → unxts_interop_xarray-2.1.0/tests/smoke}/test_public_api.py +0 -0
  22. {unxts_interop_xarray-2.0.1/tests → unxts_interop_xarray-2.1.0/tests/unit}/test_conversion_edges.py +0 -0
  23. {unxts_interop_xarray-2.0.1/tests → unxts_interop_xarray-2.1.0/tests/unit}/test_stale_units_attrs.py +0 -0
  24. {unxts_interop_xarray-2.0.1/tests → unxts_interop_xarray-2.1.0/tests/unit}/test_unknown_unit_keys.py +0 -0
@@ -80,7 +80,7 @@ instance/
80
80
 
81
81
  # Sphinx documentation
82
82
  docs/_build/
83
- docs/guides/perf.ipynb
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.interop.xarray
3
- Version: 2.0.1
3
+ Version: 2.1.0
4
4
  Summary: xarray integration for unxt (canonical: unxts.interop.xarray)
5
5
  Project-URL: Bug Tracker, https://github.com/GalacticDynamics/unxt/issues
6
6
  Project-URL: Homepage, https://github.com/GalacticDynamics/unxt
@@ -0,0 +1,99 @@
1
+ # API
2
+
3
+ For task-shaped guidance see [How to use unxt with xarray](xarray-guide).
4
+
5
+ ## The `.unxt` accessor
6
+
7
+ Registered on both `DataArray` and `Dataset` when `unxts.interop.xarray` is imported.
8
+
9
+ | Member | Signature | Returns |
10
+ | --- | --- | --- |
11
+ | `.unxt.quantify` | `(units=None, **unit_kwargs)` | a copy with `Quantity` data |
12
+ | `.unxt.dequantify` | `(format=None, unit_attribute="units")` | a copy with plain arrays and unit attributes |
13
+ | `.unxt.units` | property | mapping of name → unit; the data itself is under the `None` key (`DataArray` only) |
14
+
15
+ `quantify`'s `units` accepts a unit string or object (applied to the data), or a mapping of names to units; `**unit_kwargs` is the keyword spelling of the same mapping, so `quantify(time="s")` and `quantify({"time": "s"})` are equivalent. On a `Dataset`, `units` must be a mapping — variables are named. Anything not named is read from that object's `units` attribute, and variables with no `units` attribute are left as plain arrays.
16
+
17
+ `dequantify`'s `format` is passed to {func}`format` to render each unit; the default `None` uses `str(unit)`. `unit_attribute` is the attribute the unit string is written to.
18
+
19
+ ## Lower-level functions
20
+
21
+ These are the layer underneath the accessor, for inspecting or manipulating units without going through a `DataArray` or `Dataset`.
22
+
23
+ The `.unxt` accessor covers most workflows, but the four underlying functions are also exported for use in pipelines, custom integrations, or cases where you need direct control.
24
+
25
+ ## `extract_unit_attributes`
26
+
27
+ Reads `"units"` attrs from each variable and coordinate — without converting anything to a Quantity. Use this to inspect declared units before committing to a conversion.
28
+
29
+ ```python
30
+ import xarray as xr
31
+ from unxts.interop.xarray import extract_unit_attributes
32
+
33
+ ds = xr.Dataset(
34
+ {
35
+ "temperature": ("time", [273.0, 293.0], {"units": "K"}),
36
+ "pressure": ("time", [101325.0, 102000.0]),
37
+ }
38
+ )
39
+ print(extract_unit_attributes(ds))
40
+ # {'temperature': Unit("K")}
41
+ ```
42
+
43
+ ## `attach_units`
44
+
45
+ Attaches units to a DataArray or Dataset, converting plain array data into Quantities. Use `None` as the key for a DataArray's own data (as opposed to a named coordinate).
46
+
47
+ ```python
48
+ import xarray as xr
49
+ from unxts.interop.xarray import attach_units
50
+
51
+ da = xr.DataArray([1.0, 2.0, 3.0], dims=["x"])
52
+ quantified = attach_units(da, {None: "m"})
53
+ print(quantified.data)
54
+ # Quantity(Array([1., 2., 3.], dtype=float32), unit='m')
55
+ ```
56
+
57
+ Use `attach_units` directly when you already have a units mapping (e.g., from a file header or a prior `extract_unit_attributes` call) and want to skip the attribute-reading step.
58
+
59
+ ## `extract_units`
60
+
61
+ Reads the units from **existing Quantities** in a DataArray or Dataset. This is the inverse of `attach_units` — use it when you need the units for computation before stripping them.
62
+
63
+ ```python
64
+ import xarray as xr
65
+ import unxt as u
66
+ from unxts.interop.xarray import extract_units
67
+
68
+ q = u.Quantity([1.0, 2.0], "m")
69
+ da = xr.DataArray(q, dims=["x"])
70
+ print(extract_units(da))
71
+ # {None: Unit("m")}
72
+ ```
73
+
74
+ ## `strip_units`
75
+
76
+ Removes Quantity wrappers, returning plain arrays. The unit information is discarded unless you capture it with `extract_units` first.
77
+
78
+ ```python
79
+ import xarray as xr
80
+ import unxt as u
81
+ from unxts.interop.xarray import strip_units
82
+
83
+ q = u.Quantity([1.0, 2.0], "m")
84
+ da = xr.DataArray(q, dims=["x"])
85
+ stripped = strip_units(da)
86
+ print(stripped.data)
87
+ # Array([1., 2.], dtype=float32)
88
+ ```
89
+
90
+ ## When to use the low-level API
91
+
92
+ | Task | Use |
93
+ | --- | --- |
94
+ | Interactive quantify/dequantify | `.unxt.quantify()` / `.unxt.dequantify()` |
95
+ | Inspect declared units without converting | `extract_unit_attributes` |
96
+ | Attach a pre-built units mapping | `attach_units` |
97
+ | Read units from already-quantified data | `extract_units` |
98
+ | Strip Quantities to plain arrays | `strip_units` |
99
+ | Build a custom quantify/dequantify pipeline | All four, composed manually |
@@ -0,0 +1,105 @@
1
+ # `unxts.interop.xarray`
2
+
3
+ ```{toctree}
4
+ :maxdepth: 1
5
+ :hidden:
6
+
7
+ tutorial-first-dataset
8
+ xarray-guide
9
+ api
10
+ sharp-bits
11
+ ```
12
+
13
+ `unxts.interop.xarray` is the canonical location for [xarray](https://docs.xarray.dev/) integration. It adds a `.unxt` accessor to `DataArray` and `Dataset` that converts between `xarray`'s unit _metadata_ — a `units` string in `.attrs` — and real `unxt.Quantity` values, so units become part of the data rather than a label beside it.
14
+
15
+ Importing the package registers the accessor as an import side effect.
16
+
17
+ ## Install
18
+
19
+ The recommended install adds `unxts.interop.xarray` alongside `unxt` via the `interop-xarray` [extra](https://peps.python.org/pep-0508/#extras), so it, `unxt` and `xarray` are resolved together as a compatible set:
20
+
21
+ ::::{tab-set}
22
+
23
+ :::{tab-item} uv
24
+
25
+ ```bash
26
+ uv add "unxt[interop-xarray]"
27
+ ```
28
+
29
+ :::
30
+
31
+ :::{tab-item} pip
32
+
33
+ ```bash
34
+ pip install "unxt[interop-xarray]"
35
+ ```
36
+
37
+ :::
38
+
39
+ ::::
40
+
41
+ Or install the package directly:
42
+
43
+ ::::{tab-set}
44
+
45
+ :::{tab-item} uv
46
+
47
+ ```bash
48
+ uv add unxts.interop.xarray
49
+ ```
50
+
51
+ :::
52
+
53
+ :::{tab-item} pip
54
+
55
+ ```bash
56
+ pip install unxts.interop.xarray
57
+ ```
58
+
59
+ :::
60
+
61
+ ::::
62
+
63
+ ## At a glance
64
+
65
+ ```python
66
+ import numpy as np
67
+ import xarray as xr
68
+
69
+ import unxts.interop.xarray # registers the .unxt accessor
70
+
71
+ da = xr.DataArray(np.array([1.0, 2.0, 3.0]), dims="x", attrs={"units": "m"})
72
+
73
+ q = da.unxt.quantify()
74
+ q.data
75
+ # Quantity(Array([1., 2., 3.], dtype=float32), unit='m')
76
+
77
+ plain = q.unxt.dequantify()
78
+ plain.attrs["units"]
79
+ # 'm'
80
+ ```
81
+
82
+ `quantify()` reads the `units` attribute and turns the values into a `Quantity`; `dequantify()` reverses it, putting the unit back in `.attrs`.
83
+
84
+ ## Pages
85
+
86
+ **Tutorial**
87
+
88
+ - [Turn unit labels into real units](tutorial-first-dataset) — start here: watch `xarray` add kilometres to hours without complaint, then quantify and watch the same operation refuse.
89
+
90
+ **How-to**
91
+
92
+ - [How to use unxt with xarray](xarray-guide) — quantifying and dequantifying `DataArray`s and `Dataset`s, coordinates, unit conversion, JAX transforms, and round-tripping through NetCDF.
93
+
94
+ **Reference**
95
+
96
+ - [API](api) — the functions underneath the accessor: `extract_unit_attributes`, `attach_units`, `extract_units`, `strip_units`.
97
+
98
+ **Discussion**
99
+
100
+ - [The xarray sharp bits](sharp-bits) — why dimension coordinates cannot hold quantities, and which operations drop units.
101
+
102
+ ## See also
103
+
104
+ - [xarray documentation](https://docs.xarray.dev/)
105
+ - [unxt documentation](https://unxt.readthedocs.io/)
@@ -0,0 +1,42 @@
1
+ # The xarray sharp bits
2
+
3
+ Two things about the integration surprise people. Both follow from how `xarray` itself works rather than from anything `unxts.interop.xarray` chose, which is why neither is going to be fixed.
4
+
5
+ ## Dimension coordinates cannot hold quantities
6
+
7
+ `xarray` backs every _dimension coordinate_ (one named like its dimension, shown with a `*` in the repr) with a `pandas.Index`. Building that index coerces the data to a plain `numpy` array, so a dimension coordinate cannot hold a `Quantity`. This is inherent to `xarray`'s indexing model, not something `unxts.interop.xarray` can override, and it affects every duck-array unit library (including `pint-xarray`) the same way.
8
+
9
+ Assigning one **raises** rather than dropping the unit on the floor — `Quantity.__array__` refuses to hand a dimensionful value to a consumer that cannot see its unit. `quantify()` handles this for you by leaving dimension coordinates plain.
10
+
11
+ **Workaround**: store the unitful values on a _non-dimension_ coordinate, keeping a plain index on the dimension itself:
12
+
13
+ ```{code-block} python
14
+ >>> import unxt as u
15
+ >>> import xarray as xr
16
+
17
+ >>> data = [10.0, 20.0, 30.0]
18
+ >>> quantities = u.Q([1.0, 2.0, 3.0], "m")
19
+
20
+ >>> # Dimension coordinate: refused, because the unit could not survive
21
+ >>> try:
22
+ ... xr.DataArray(data, dims=["x"], coords={"x": quantities})
23
+ ... except Exception as e:
24
+ ... print(type(e).__name__)
25
+ UnitConversionError
26
+
27
+ >>> # Non-dimension coordinate: the Quantity (and its unit) is preserved
28
+ >>> da = xr.DataArray(data, dims=["i"],
29
+ ... coords={"i": [0, 1, 2], "x": ("i", quantities)})
30
+ >>> da.coords["x"].data
31
+ Quantity(Array([1., 2., 3.], dtype=float32), unit='m')
32
+
33
+ ```
34
+
35
+ ## Operations that drop units
36
+
37
+ A few `xarray` operations route through code paths that cannot preserve a `Quantity`:
38
+
39
+ - **`rolling` / sliding-window reductions** use `numpy.lib.stride_tricks`, which has no Array API (or `jax.numpy`) equivalent, so they are unsupported on JAX-backed data generally — not specific to units.
40
+ - **`interp`** delegates to `scipy`/`numpy` interpolation internally and returns a plain array (the same behavior as `pint-xarray`).
41
+
42
+ For these, `dequantify`, operate, then re-`quantify`, or work on `.data` with `unxt`/`quaxed` directly.
@@ -0,0 +1,158 @@
1
+ # Turn unit labels into real units
2
+
3
+ An `xarray` object can carry a `units` string in its attributes, but that string is only a label — nothing checks it, and `xarray` will happily add kilometres to hours. In this tutorial we will watch exactly that happen, then turn those labels into real `unxt` quantities so the same mistake becomes an error, compute with them, and put the labels back.
4
+
5
+ You need `unxt`, `unxts.interop.xarray` and `xarray` installed, and nothing else.
6
+
7
+ ## Set up
8
+
9
+ ```{code-block} python
10
+ >>> import numpy as np
11
+ >>> import xarray as xr
12
+ >>> import unxt as u
13
+ >>> import unxts.interop.xarray # registers the .unxt accessor
14
+
15
+ ```
16
+
17
+ That import is the setup. It attaches a `.unxt` accessor to `DataArray` and `Dataset`.
18
+
19
+ ## Build some labelled data
20
+
21
+ Three legs of a journey — distances in kilometres, times in hours — with the units recorded the way `xarray` users normally record them, as an attribute:
22
+
23
+ ```{code-block} python
24
+ >>> dist = xr.DataArray(np.array([90.0, 180.0, 270.0]),
25
+ ... dims="leg", attrs={"units": "km"})
26
+ >>> time = xr.DataArray(np.array([1.0, 2.0, 3.0]),
27
+ ... dims="leg", attrs={"units": "h"})
28
+
29
+ ```
30
+
31
+ ## Watch the labels fail to protect you
32
+
33
+ Add a distance to a time. This is meaningless, so let's see what `xarray` does about it:
34
+
35
+ ```{code-block} python
36
+ >>> (dist + time).values
37
+ array([ 91., 182., 273.])
38
+
39
+ ```
40
+
41
+ It did the addition. 90 km plus 1 hour is 91 of something, and we now have an array of nonsense that looks exactly like data.
42
+
43
+ Worse, look at what happened to the units:
44
+
45
+ ```{code-block} python
46
+ >>> (dist + time).attrs
47
+ {}
48
+
49
+ ```
50
+
51
+ Gone. The attribute could not survive an operation it had no part in, so the result is not even mislabelled — it is unlabelled. Nothing raised, nothing warned.
52
+
53
+ ## Make the units real
54
+
55
+ Now `quantify()`. It reads the `units` attribute and replaces the plain array with an `unxt.Quantity`:
56
+
57
+ ```{code-block} python
58
+ >>> qd = dist.unxt.quantify()
59
+ >>> qt = time.unxt.quantify()
60
+
61
+ >>> qd.data
62
+ Quantity(Array([ 90., 180., 270.], dtype=float32), unit='km')
63
+
64
+ ```
65
+
66
+ The unit is no longer a string beside the numbers — it is part of them. You can ask an object what units it found, before or after:
67
+
68
+ ```{code-block} python
69
+ >>> dist.unxt.units
70
+ {None: Unit("km")}
71
+
72
+ ```
73
+
74
+ (The data itself lives under the `None` key; named coordinates appear under their own names.)
75
+
76
+ ## Try the mistake again
77
+
78
+ Same addition, now on quantified data:
79
+
80
+ ```{code-block} python
81
+ >>> try:
82
+ ... qd + qt
83
+ ... except Exception as e:
84
+ ... print(type(e).__name__)
85
+ UnitConversionError
86
+
87
+ ```
88
+
89
+ There it is. The operation that quietly produced nonsense a moment ago now refuses to run at all.
90
+
91
+ ## Compute something that does make sense
92
+
93
+ Distance divided by time is a speed, and the unit follows from the arithmetic:
94
+
95
+ ```{code-block} python
96
+ >>> speed = qd / qt
97
+ >>> speed.data
98
+ Quantity(Array([90., 90., 90.], dtype=float32), unit='km / h')
99
+
100
+ ```
101
+
102
+ Notice `km / h` — we never wrote it down. Ninety kilometres per hour on every leg, which is what the numbers say.
103
+
104
+ ## Put the labels back
105
+
106
+ When you are done computing — writing to NetCDF, handing off to a library that does not know about quantities — `dequantify()` reverses the first step, moving the unit back into the attributes:
107
+
108
+ ```{code-block} python
109
+ >>> speed.unxt.dequantify().attrs
110
+ {'units': 'km / h'}
111
+
112
+ ```
113
+
114
+ The derived unit was written out as a label, ready to be stored.
115
+
116
+ ## Do it to a whole dataset
117
+
118
+ Both methods work on a `Dataset`, converting every variable that has a `units` attribute:
119
+
120
+ ```{code-block} python
121
+ >>> ds = xr.Dataset({"d": dist, "t": time})
122
+ >>> qds = ds.unxt.quantify()
123
+
124
+ >>> qds["d"].data
125
+ Quantity(Array([ 90., 180., 270.], dtype=float32), unit='km')
126
+
127
+ >>> qds["t"].data
128
+ Quantity(Array([1., 2., 3.], dtype=float32), unit='h')
129
+
130
+ ```
131
+
132
+ And the round trip returns the labels exactly as they started:
133
+
134
+ ```{code-block} python
135
+ >>> qds.unxt.dequantify()["d"].attrs
136
+ {'units': 'km'}
137
+
138
+ ```
139
+
140
+ ## Convert while you are in there
141
+
142
+ One thing worth knowing before you go: once quantified, the data converts like any other quantity.
143
+
144
+ ```{code-block} python
145
+ >>> qd.data.uconvert("m")
146
+ Quantity(Array([ 90000., 180000., 270000.], dtype=float32), unit='m')
147
+
148
+ ```
149
+
150
+ ## What we built
151
+
152
+ You took a dataset whose units were decorative, made them real, watched a bug that had been silent become an exception, computed a derived quantity whose unit came out of the arithmetic, and wrote the labels back for storage. That round trip — `quantify`, compute, `dequantify` — is the shape of nearly every workflow with this package.
153
+
154
+ ## Where to go next
155
+
156
+ - [How to use unxt with xarray](xarray-guide) — coordinates, per-variable units, JAX transforms, and NetCDF round trips.
157
+ - [The xarray sharp bits](sharp-bits) — why dimension coordinates cannot hold quantities.
158
+ - [API](api) — the accessor's parameters and the lower-level functions.
@@ -1,43 +1,33 @@
1
- # `xarray` Integration Guide
1
+ # How to use unxt with xarray
2
2
 
3
- This guide shows how to use `unxts.interop.xarray` to integrate JAX-based physical quantities with `xarray`'s labeled multi-dimensional arrays.
3
+ This guide shows you how to move between `xarray`'s unit _metadata_ — a `units` string in `.attrs` — and real `unxt` quantities, in both directions, for `DataArray`s and `Dataset`s alike.
4
4
 
5
- ## Overview
5
+ It assumes you already know `xarray`; if you have not quantified anything before, start with [Turn unit labels into real units](tutorial-first-dataset). If you want the functions underneath the `.unxt` accessor, see [API](api); for the two cases where the integration cannot do what you would expect, see [The xarray sharp bits](sharp-bits).
6
6
 
7
- `unxts.interop.xarray` provides seamless integration between:
8
-
9
- - **`unxt`**: JAX-based physical quantities with dimension checking
10
- - **`xarray`**: N-dimensional labeled arrays for scientific computing
11
-
12
- The integration enables you to:
13
-
14
- - Attach physical units to `xarray` DataArrays and Datasets
15
- - Preserve units through `xarray` operations
16
- - Convert between unit-aware (Quantity) and plain arrays with metadata
17
- - Use JAX transformations (jit, vmap, grad) on unit-aware `xarray` objects
18
-
19
- ## Installation
7
+ ## Install
20
8
 
21
9
  ::::{tab-set}
22
10
 
23
- :::{tab-item} pip
11
+ :::{tab-item} uv
24
12
 
25
13
  ```bash
26
- pip install unxts.interop.xarray
14
+ uv add "unxt[interop-xarray]"
27
15
  ```
28
16
 
29
17
  :::
30
18
 
31
- :::{tab-item} uv
19
+ :::{tab-item} pip
32
20
 
33
21
  ```bash
34
- uv add unxts.interop.xarray
22
+ pip install "unxt[interop-xarray]"
35
23
  ```
36
24
 
37
25
  :::
38
26
 
39
27
  ::::
40
28
 
29
+ Importing `unxts.interop.xarray` registers the `.unxt` accessor as a side effect, so import it once at startup — before you reach for `.unxt` on any object.
30
+
41
31
  ## Basic Usage
42
32
 
43
33
  ### The `.unxt` Accessor
@@ -161,7 +151,7 @@ print(quantified.coords["time"].data)
161
151
 
162
152
  **Dimension coordinates cannot hold Quantities.** xarray automatically coerces dimension coordinates (those named after their dimension, shown with `*` in the repr) to plain NumPy arrays via `pandas.Index`. This silently drops the Quantity wrapper and its unit — there is no error or warning.
163
153
 
164
- The workaround is to use _non-dimension_ coordinates: give the coordinate a name different from its dimension (e.g., `"time"` attached to dimension `"i"`). See [Limitations: Dimension Coordinates Cannot Hold Quantities](#dimension-coordinates-cannot-hold-quantities) for the full explanation and workaround.
154
+ The workaround is to use _non-dimension_ coordinates: give the coordinate a name different from its dimension (e.g., `"time"` attached to dimension `"i"`). See [The xarray sharp bits](sharp-bits) for the full explanation and workaround.
165
155
 
166
156
  :::
167
157
 
@@ -516,129 +506,3 @@ da_km = xr.DataArray(converted, dims=plain.dims).unxt.dequantify()
516
506
  print(da_km.attrs["units"])
517
507
  # 'km'
518
508
  ```
519
-
520
- ## Lower-Level API
521
-
522
- The `.unxt` accessor covers most workflows, but the four underlying functions are also exported for use in pipelines, custom integrations, or cases where you need direct control.
523
-
524
- ### `extract_unit_attributes`
525
-
526
- Reads `"units"` attrs from each variable and coordinate — without converting anything to a Quantity. Use this to inspect declared units before committing to a conversion.
527
-
528
- ```python
529
- import xarray as xr
530
- from unxts.interop.xarray import extract_unit_attributes
531
-
532
- ds = xr.Dataset(
533
- {
534
- "temperature": ("time", [273.0, 293.0], {"units": "K"}),
535
- "pressure": ("time", [101325.0, 102000.0]),
536
- }
537
- )
538
- print(extract_unit_attributes(ds))
539
- # {'temperature': Unit("K")}
540
- ```
541
-
542
- ### `attach_units`
543
-
544
- Attaches units to a DataArray or Dataset, converting plain array data into Quantities. Use `None` as the key for a DataArray's own data (as opposed to a named coordinate).
545
-
546
- ```python
547
- import xarray as xr
548
- from unxts.interop.xarray import attach_units
549
-
550
- da = xr.DataArray([1.0, 2.0, 3.0], dims=["x"])
551
- quantified = attach_units(da, {None: "m"})
552
- print(quantified.data)
553
- # Quantity(Array([1., 2., 3.], dtype=float32), unit='m')
554
- ```
555
-
556
- Use `attach_units` directly when you already have a units mapping (e.g., from a file header or a prior `extract_unit_attributes` call) and want to skip the attribute-reading step.
557
-
558
- ### `extract_units`
559
-
560
- Reads the units from **existing Quantities** in a DataArray or Dataset. This is the inverse of `attach_units` — use it when you need the units for computation before stripping them.
561
-
562
- ```python
563
- import xarray as xr
564
- import unxt as u
565
- from unxts.interop.xarray import extract_units
566
-
567
- q = u.Quantity([1.0, 2.0], "m")
568
- da = xr.DataArray(q, dims=["x"])
569
- print(extract_units(da))
570
- # {None: Unit("m")}
571
- ```
572
-
573
- ### `strip_units`
574
-
575
- Removes Quantity wrappers, returning plain arrays. The unit information is discarded unless you capture it with `extract_units` first.
576
-
577
- ```python
578
- import xarray as xr
579
- import unxt as u
580
- from unxts.interop.xarray import strip_units
581
-
582
- q = u.Quantity([1.0, 2.0], "m")
583
- da = xr.DataArray(q, dims=["x"])
584
- stripped = strip_units(da)
585
- print(stripped.data)
586
- # Array([1., 2.], dtype=float32)
587
- ```
588
-
589
- ### When to use the low-level API
590
-
591
- | Task | Use |
592
- | --- | --- |
593
- | Interactive quantify/dequantify | `.unxt.quantify()` / `.unxt.dequantify()` |
594
- | Inspect declared units without converting | `extract_unit_attributes` |
595
- | Attach a pre-built units mapping | `attach_units` |
596
- | Read units from already-quantified data | `extract_units` |
597
- | Strip Quantities to plain arrays | `strip_units` |
598
- | Build a custom quantify/dequantify pipeline | All four, composed manually |
599
-
600
- ## Limitations
601
-
602
- ### Dimension Coordinates Cannot Hold Quantities
603
-
604
- `xarray` backs every _dimension coordinate_ (one named like its dimension, shown with a `*` in the repr) with a `pandas.Index`. Building that index coerces the data to a plain `numpy` array, so a dimension coordinate cannot hold a `Quantity`. This is inherent to `xarray`'s indexing model, not something `unxts.interop.xarray` can override, and it affects every duck-array unit library (including `pint-xarray`) the same way.
605
-
606
- Assigning one now **raises** rather than dropping the unit on the floor — `Quantity.__array__` refuses to hand a dimensionful value to a consumer that cannot see its unit. `quantify()` handles this for you by leaving dimension coordinates plain.
607
-
608
- **Workaround**: store the unitful values on a _non-dimension_ coordinate, keeping a plain index on the dimension itself:
609
-
610
- ```python
611
- import unxt as u
612
- import xarray as xr
613
-
614
- data = [10.0, 20.0, 30.0]
615
- quantities = u.Quantity([1.0, 2.0, 3.0], "m")
616
-
617
- # Dimension coordinate: refused, because the unit could not survive
618
- try:
619
- xr.DataArray(data, dims=["x"], coords={"x": quantities})
620
- except Exception as e:
621
- print(type(e).__name__)
622
- # UnitConversionError
623
-
624
- # Non-dimension coordinate: the Quantity (and its unit) is preserved
625
- da = xr.DataArray(data, dims=["i"], coords={"i": [0, 1, 2], "x": ("i", quantities)})
626
- print(da.coords["x"].data)
627
- # Quantity(Array([1., 2., 3.], dtype=float32), unit='m')
628
- ```
629
-
630
- ### Operations That Drop Units
631
-
632
- A few `xarray` operations route through code paths that cannot preserve a `Quantity`:
633
-
634
- - **`rolling` / sliding-window reductions** use `numpy.lib.stride_tricks`, which has no Array API (or `jax.numpy`) equivalent, so they are unsupported on JAX-backed data generally — not specific to units.
635
- - **`interp`** delegates to `scipy`/`numpy` interpolation internally and returns a plain array (the same behavior as `pint-xarray`).
636
-
637
- For these, `dequantify`, operate, then re-`quantify`, or work on `.data` with `unxt`/`quaxed` directly.
638
-
639
- ## See Also
640
-
641
- - [unxt documentation](https://unxt.readthedocs.io/) - Core unitful quantities
642
- - [xarray documentation](https://docs.xarray.dev/) - Labeled arrays
643
- - [JAX documentation](https://jax.readthedocs.io/) - Composable transformations
644
- - [Astropy units](https://docs.astropy.org/en/stable/units/) - Unit definitions
@@ -268,35 +268,54 @@ def extract_units(obj: object, /) -> dict:
268
268
  raise TypeError(msg)
269
269
 
270
270
 
271
- def _reject_unknown_unit_names(
271
+ #: What a unit mapping is allowed to carry as a value.
272
+ _UNIT_VALUE_TYPES: Final = (u.AbstractUnit, str, type(None))
273
+
274
+
275
+ def _validate_units(
272
276
  units: "Mapping[Hashable, Any]", valid_names: "set[Any]", obj_kind: str
273
277
  ) -> None:
274
- """Raise if units names something that is not a variable/coordinate.
278
+ """Reject a unit mapping with unknown names or non-unit values.
275
279
 
276
- Without this, a typo in a **unit_kwargs name (e.g.
277
- quantify(temperatrue="K")) is silently dropped by units.get(name),
280
+ *Names*: without this, a typo in a ``**unit_kwargs`` name (e.g.
281
+ ``quantify(temperatrue="K")``) is silently dropped by ``units.get(name)``,
278
282
  leaving the data unquantified with no error or warning.
283
+
284
+ *Values*: this replaces what the parametrized
285
+ ``Mapping[Hashable, AbstractUnit | str | None]`` annotation used to do at
286
+ dispatch time. That annotation made the whole ``attach_units`` plum function
287
+ non-faithful -- disabling its method caching -- and its failure mode was to
288
+ fall through to the ``object`` overload, whose message blames the *object*'s
289
+ type rather than naming the offending unit value.
279
290
  """
280
291
  # Sort so the message is deterministic: `units` insertion order follows the
281
292
  # accessor's ``set(...)`` iteration, which is not stable across processes.
282
293
  unknown = sorted(repr(k) for k in units if k not in valid_names)
283
- if not unknown:
284
- return
285
- # ``None`` is the DataArray's own-data key; render it explicitly so the
286
- # message stays helpful (and non-empty) when there are no other names.
287
- names = ("None (the data)" if n is None else repr(n) for n in valid_names)
288
- valid = ", ".join(sorted(names)) or "(none)"
289
- msg = (
290
- f"got unit(s) for name(s) not in the {obj_kind}: {', '.join(unknown)}. "
291
- f"Valid names: {valid}."
294
+ if unknown:
295
+ # ``None`` is the DataArray's own-data key; render it explicitly so the
296
+ # message stays helpful (and non-empty) when there are no other names.
297
+ names = ("None (the data)" if n is None else repr(n) for n in valid_names)
298
+ valid = ", ".join(sorted(names)) or "(none)"
299
+ msg = (
300
+ f"got unit(s) for name(s) not in the {obj_kind}: {', '.join(unknown)}. "
301
+ f"Valid names: {valid}."
302
+ )
303
+ raise ValueError(msg)
304
+
305
+ bad = sorted(
306
+ f"{'None (the data)' if k is None else repr(k)} -> {type(v).__name__}"
307
+ for k, v in units.items()
308
+ if not isinstance(v, _UNIT_VALUE_TYPES)
292
309
  )
293
- raise ValueError(msg)
310
+ if bad:
311
+ msg = (
312
+ f"unit values must be a unit, a unit string, or None; got {', '.join(bad)}."
313
+ )
314
+ raise TypeError(msg)
294
315
 
295
316
 
296
317
  @dispatch
297
- def attach_units(
298
- obj: DataArray, units: Mapping[Hashable, u.AbstractUnit | str | None]
299
- ) -> DataArray:
318
+ def attach_units(obj: DataArray, units: Mapping) -> DataArray:
300
319
  """Attach units to a DataArray's variables.
301
320
 
302
321
  Parameters
@@ -329,7 +348,7 @@ def attach_units(
329
348
  {}
330
349
 
331
350
  """
332
- _reject_unknown_unit_names(units, {None} | set(obj.coords), "DataArray")
351
+ _validate_units(units, {None} | set(obj.coords), "DataArray")
333
352
 
334
353
  # Handle the data array itself (None key = the DataArray's own data)
335
354
  data_unit = units.get(None)
@@ -372,9 +391,7 @@ def attach_units(
372
391
 
373
392
 
374
393
  @dispatch
375
- def attach_units(
376
- obj: Dataset, units: Mapping[Hashable, u.AbstractUnit | str | None]
377
- ) -> Dataset:
394
+ def attach_units(obj: Dataset, units: Mapping) -> Dataset:
378
395
  """Attach units to a Dataset's variables.
379
396
 
380
397
  Parameters
@@ -390,7 +407,7 @@ def attach_units(
390
407
  New Dataset with units attached as Quantities.
391
408
 
392
409
  """
393
- _reject_unknown_unit_names(units, set(obj.data_vars) | set(obj.coords), "Dataset")
410
+ _validate_units(units, set(obj.data_vars) | set(obj.coords), "Dataset")
394
411
 
395
412
  # Handle all variables in dataset
396
413
  new_vars = {}
@@ -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.1'
22
- __version_tuple__ = version_tuple = (2, 0, 1)
21
+ __version__ = version = '2.1.0'
22
+ __version_tuple__ = version_tuple = (2, 1, 0)
23
23
 
24
24
  __commit_id__ = commit_id = None
@@ -1,224 +0,0 @@
1
- # unxts.interop.xarray
2
-
3
- ```{toctree}
4
- :maxdepth: 1
5
- :hidden:
6
-
7
- xarray-guide
8
- ```
9
-
10
- `xarray` integration for unxt - JAX-based physical quantities with `xarray`'s labeled arrays.
11
-
12
- :::{note}
13
-
14
- `unxts.interop.xarray` is the canonical package, superseding the deprecated `unxt-xarray` distribution. Once installed, it registers the `.unxt` xarray accessor on import.
15
-
16
- :::
17
-
18
- ## Installation
19
-
20
- The recommended install adds `unxts.interop.xarray` alongside `unxt` via the `interop-xarray` [extra](https://peps.python.org/pep-0508/#extras), so it, `unxt`, and `xarray` are resolved together as a compatible set:
21
-
22
- ::::{tab-set}
23
-
24
- :::{tab-item} uv
25
-
26
- ```bash
27
- uv add "unxt[interop-xarray]"
28
- ```
29
-
30
- :::
31
-
32
- :::{tab-item} pip
33
-
34
- ```bash
35
- pip install "unxt[interop-xarray]"
36
- ```
37
-
38
- :::
39
-
40
- ::::
41
-
42
- Or install the package directly:
43
-
44
- ::::{tab-set}
45
-
46
- :::{tab-item} uv
47
-
48
- ```bash
49
- uv add unxts.interop.xarray
50
- ```
51
-
52
- :::
53
-
54
- :::{tab-item} pip
55
-
56
- ```bash
57
- pip install unxts.interop.xarray
58
- ```
59
-
60
- :::
61
-
62
- ::::
63
-
64
- ## Quick Start
65
-
66
- ```python
67
- import xarray as xr
68
- import unxt as u
69
- import unxts.interop.xarray # This registers the .unxt accessor
70
-
71
- # Create DataArray with unit attributes
72
- da = xr.DataArray(
73
- [1.0, 2.0, 3.0],
74
- dims=["x"],
75
- attrs={"units": "m"},
76
- )
77
-
78
- # Convert to unxt Quantities
79
- quantified = da.unxt.quantify()
80
- print(quantified.data)
81
- # Quantity(Array([1., 2., 3.], dtype=float32), unit='m')
82
-
83
- # Convert back to plain arrays with unit attributes
84
- dequantified = quantified.unxt.dequantify()
85
- print(dequantified.attrs["units"])
86
- # 'm'
87
- ```
88
-
89
- ## Usage
90
-
91
- ### DataArray Operations
92
-
93
- The `.unxt` accessor provides two main methods for `DataArray`:
94
-
95
- #### `quantify()`
96
-
97
- Convert a DataArray with unit attributes into one containing unxt Quantities:
98
-
99
- ```python
100
- import xarray as xr
101
- import unxts.interop.xarray
102
-
103
- # From attributes
104
- da = xr.DataArray([1.0, 2.0, 3.0], dims=["x"], attrs={"units": "m"})
105
- q = da.unxt.quantify()
106
-
107
- # With explicit units
108
- da = xr.DataArray([1.0, 2.0, 3.0], dims=["x"])
109
- q = da.unxt.quantify("km")
110
-
111
- # With coordinate units. Use a *non-dimension* coordinate ("time" on dim "i"):
112
- # a dimension coordinate is coerced to a plain array by xarray, dropping its unit.
113
- da = xr.DataArray(
114
- [1.0, 2.0],
115
- dims=["i"],
116
- coords={"time": ("i", [0.0, 1.0])},
117
- attrs={"units": "m"},
118
- )
119
- q = da.unxt.quantify(time="s") # Specify units for the "time" coord
120
- ```
121
-
122
- #### `dequantify()`
123
-
124
- Convert Quantities back to plain arrays with unit attributes:
125
-
126
- ```python
127
- import unxt as u
128
-
129
- q = u.Quantity([1.0, 2.0, 3.0], "m")
130
- da = xr.DataArray(q, dims=["x"])
131
-
132
- plain = da.unxt.dequantify()
133
- print(plain.attrs["units"]) # 'm'
134
- print(type(plain.data)) # Array (not Quantity)
135
- ```
136
-
137
- ### Dataset Operations
138
-
139
- The accessor works similarly for `Dataset` objects:
140
-
141
- ```python
142
- import xarray as xr
143
- import unxts.interop.xarray
144
-
145
- # Create Dataset with unit attributes
146
- ds = xr.Dataset(
147
- {
148
- "temperature": ("time", [20.0, 25.0, 30.0], {"units": "deg_C"}),
149
- "pressure": ("time", [1.0, 1.1, 1.2], {"units": "bar"}),
150
- }
151
- )
152
-
153
- # Quantify all variables
154
- q_ds = ds.unxt.quantify()
155
- print(q_ds["temperature"].data)
156
- # Quantity(Array([20., 25., 30.], dtype=float32), unit='deg_C')
157
-
158
- # Dequantify back
159
- plain_ds = q_ds.unxt.dequantify()
160
- print(plain_ds["temperature"].attrs["units"]) # 'deg_C'
161
- ```
162
-
163
- ## Advanced Usage
164
-
165
- ### Custom Unit Attributes
166
-
167
- By default, units are stored in the `"units"` attribute. You can customize this:
168
-
169
- ```python
170
- da = xr.DataArray([1.0, 2.0], dims=["x"])
171
- q_da = xr.DataArray(u.Quantity([1.0, 2.0], "m"), dims=["x"])
172
-
173
- # Use custom attribute name
174
- plain = q_da.unxt.dequantify(unit_attribute="unit_str")
175
- print(plain.attrs["unit_str"]) # 'm'
176
- ```
177
-
178
- ### Format Strings
179
-
180
- Control how units are formatted when dequantifying:
181
-
182
- ```python
183
- import unxt as u
184
-
185
- q = u.Quantity([1.0, 2.0], "m/s")
186
- da = xr.DataArray(q, dims=["x"])
187
-
188
- # Default format
189
- plain = da.unxt.dequantify()
190
- print(plain.attrs["units"]) # 'm / s'
191
-
192
- # Custom format (if supported by unit system)
193
- # plain = da.unxt.dequantify(format="{:~}") # Compact format
194
- ```
195
-
196
- ### Partial Quantification
197
-
198
- You can quantify only specific variables in a Dataset:
199
-
200
- ```python
201
- ds = xr.Dataset(
202
- {
203
- "with_units": ("x", [1.0, 2.0], {"units": "m"}),
204
- "without_units": ("y", [3.0, 4.0]),
205
- }
206
- )
207
-
208
- q_ds = ds.unxt.quantify()
209
- # Only "with_units" is quantified
210
- ```
211
-
212
- ## Best Practices
213
-
214
- 1. **Consistent Units**: Ensure unit attributes are consistent across your workflow
215
- 2. **Explicit is Better**: Use explicit units in `quantify()` when possible for clarity
216
- 3. **Preserve Attributes**: Other attributes (like `long_name`, `description`) are preserved
217
- 4. **JAX Compatibility**: Remember that quantified data is JAX arrays - use `jax.numpy` operations
218
-
219
- ## See Also
220
-
221
- - [unxt documentation](https://unxt.readthedocs.io/)
222
- - [xarray documentation](https://docs.xarray.dev/)
223
- - [pint-xarray](https://pint-xarray.readthedocs.io/) - The original inspiration
224
- - [JAX documentation](https://jax.readthedocs.io/)