unxts.interop.xarray 2.0.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_interop_xarray-2.0.0/.gitignore +166 -0
- unxts_interop_xarray-2.0.0/PKG-INFO +43 -0
- unxts_interop_xarray-2.0.0/README.md +17 -0
- unxts_interop_xarray-2.0.0/docs/index.md +12 -0
- unxts_interop_xarray-2.0.0/pyproject.toml +78 -0
- unxts_interop_xarray-2.0.0/src/unxts/interop/xarray/__init__.py +22 -0
- unxts_interop_xarray-2.0.0/src/unxts/interop/xarray/_src/__init__.py +21 -0
- unxts_interop_xarray-2.0.0/src/unxts/interop/xarray/_src/accessors.py +376 -0
- unxts_interop_xarray-2.0.0/src/unxts/interop/xarray/_src/conversion.py +393 -0
- unxts_interop_xarray-2.0.0/src/unxts/interop/xarray/_version.py +24 -0
- unxts_interop_xarray-2.0.0/src/unxts/interop/xarray/py.typed +0 -0
- unxts_interop_xarray-2.0.0/tests/test_public_api.py +24 -0
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
# -----------------------------------------------
|
|
2
|
+
# Project-Specific
|
|
3
|
+
|
|
4
|
+
# Version files
|
|
5
|
+
_version.py
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
# -----------------------------------------------
|
|
9
|
+
# General
|
|
10
|
+
|
|
11
|
+
# Byte-compiled / optimized / DLL files
|
|
12
|
+
__pycache__/
|
|
13
|
+
*.py[cod]
|
|
14
|
+
*$py.class
|
|
15
|
+
|
|
16
|
+
# C extensions
|
|
17
|
+
*.so
|
|
18
|
+
|
|
19
|
+
# Distribution / packaging
|
|
20
|
+
.Python
|
|
21
|
+
build/
|
|
22
|
+
develop-eggs/
|
|
23
|
+
dist/
|
|
24
|
+
downloads/
|
|
25
|
+
eggs/
|
|
26
|
+
.eggs/
|
|
27
|
+
lib/
|
|
28
|
+
lib64/
|
|
29
|
+
parts/
|
|
30
|
+
sdist/
|
|
31
|
+
var/
|
|
32
|
+
wheels/
|
|
33
|
+
share/python-wheels/
|
|
34
|
+
*.egg-info/
|
|
35
|
+
.installed.cfg
|
|
36
|
+
*.egg
|
|
37
|
+
MANIFEST
|
|
38
|
+
|
|
39
|
+
# PyInstaller
|
|
40
|
+
# Usually these files are written by a python script from a template
|
|
41
|
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
|
42
|
+
*.manifest
|
|
43
|
+
*.spec
|
|
44
|
+
|
|
45
|
+
# Installer logs
|
|
46
|
+
pip-log.txt
|
|
47
|
+
pip-delete-this-directory.txt
|
|
48
|
+
|
|
49
|
+
# Unit test / coverage reports
|
|
50
|
+
htmlcov/
|
|
51
|
+
.tox/
|
|
52
|
+
.nox/
|
|
53
|
+
.coverage
|
|
54
|
+
.coverage.*
|
|
55
|
+
.cache
|
|
56
|
+
nosetests.xml
|
|
57
|
+
coverage.xml
|
|
58
|
+
*.cover
|
|
59
|
+
*.py,cover
|
|
60
|
+
.hypothesis/
|
|
61
|
+
.pytest_cache/
|
|
62
|
+
cover/
|
|
63
|
+
|
|
64
|
+
# Translations
|
|
65
|
+
*.mo
|
|
66
|
+
*.pot
|
|
67
|
+
|
|
68
|
+
# Django stuff:
|
|
69
|
+
*.log
|
|
70
|
+
local_settings.py
|
|
71
|
+
db.sqlite3
|
|
72
|
+
db.sqlite3-journal
|
|
73
|
+
|
|
74
|
+
# Flask stuff:
|
|
75
|
+
instance/
|
|
76
|
+
.webassets-cache
|
|
77
|
+
|
|
78
|
+
# Scrapy stuff:
|
|
79
|
+
.scrapy
|
|
80
|
+
|
|
81
|
+
# Sphinx documentation
|
|
82
|
+
docs/_build/
|
|
83
|
+
docs/guides/perf.ipynb
|
|
84
|
+
|
|
85
|
+
# PyBuilder
|
|
86
|
+
.pybuilder/
|
|
87
|
+
target/
|
|
88
|
+
|
|
89
|
+
# Jupyter Notebook
|
|
90
|
+
.ipynb_checkpoints
|
|
91
|
+
|
|
92
|
+
# IPython
|
|
93
|
+
profile_default/
|
|
94
|
+
ipython_config.py
|
|
95
|
+
|
|
96
|
+
# pyenv
|
|
97
|
+
# For a library or package, you might want to ignore these files since the code is
|
|
98
|
+
# intended to run in multiple environments; otherwise, check them in:
|
|
99
|
+
# .python-version
|
|
100
|
+
|
|
101
|
+
# pipenv
|
|
102
|
+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
|
103
|
+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
|
104
|
+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
|
105
|
+
# install all needed dependencies.
|
|
106
|
+
#Pipfile.lock
|
|
107
|
+
|
|
108
|
+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
|
|
109
|
+
__pypackages__/
|
|
110
|
+
|
|
111
|
+
# Celery stuff
|
|
112
|
+
celerybeat-schedule
|
|
113
|
+
celerybeat.pid
|
|
114
|
+
|
|
115
|
+
# SageMath parsed files
|
|
116
|
+
*.sage.py
|
|
117
|
+
|
|
118
|
+
# Environments
|
|
119
|
+
.env
|
|
120
|
+
.venv
|
|
121
|
+
env/
|
|
122
|
+
venv/
|
|
123
|
+
ENV/
|
|
124
|
+
env.bak/
|
|
125
|
+
venv.bak/
|
|
126
|
+
|
|
127
|
+
# Spyder project settings
|
|
128
|
+
.spyderproject
|
|
129
|
+
.spyproject
|
|
130
|
+
|
|
131
|
+
# Rope project settings
|
|
132
|
+
.ropeproject
|
|
133
|
+
|
|
134
|
+
# mkdocs documentation
|
|
135
|
+
/site
|
|
136
|
+
|
|
137
|
+
# mypy
|
|
138
|
+
.mypy_cache/
|
|
139
|
+
.dmypy.json
|
|
140
|
+
dmypy.json
|
|
141
|
+
|
|
142
|
+
# Pyre type checker
|
|
143
|
+
.pyre/
|
|
144
|
+
|
|
145
|
+
# pytype static type analyzer
|
|
146
|
+
.pytype/
|
|
147
|
+
|
|
148
|
+
# Cython debug symbols
|
|
149
|
+
cython_debug/
|
|
150
|
+
|
|
151
|
+
# ruff
|
|
152
|
+
.ruff_cache/
|
|
153
|
+
|
|
154
|
+
# OS specific stuff
|
|
155
|
+
.DS_Store
|
|
156
|
+
.DS_Store?
|
|
157
|
+
._*
|
|
158
|
+
.Spotlight-V100
|
|
159
|
+
.Trashes
|
|
160
|
+
ehthumbs.db
|
|
161
|
+
Thumbs.db
|
|
162
|
+
|
|
163
|
+
# Common editor files
|
|
164
|
+
*~
|
|
165
|
+
*.swp
|
|
166
|
+
/.codspeed
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: unxts.interop.xarray
|
|
3
|
+
Version: 2.0.0
|
|
4
|
+
Summary: xarray integration for unxt (canonical: unxts.interop.xarray)
|
|
5
|
+
Project-URL: Bug Tracker, https://github.com/GalacticDynamics/unxt/issues
|
|
6
|
+
Project-URL: Homepage, https://github.com/GalacticDynamics/unxt
|
|
7
|
+
Author-email: GalacticDynamics <nstarman@users.noreply.github.com>, Nathaniel Starkman <nstarman@users.noreply.github.com>
|
|
8
|
+
License: BSD-3-Clause
|
|
9
|
+
Classifier: Development Status :: 4 - Beta
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: Intended Audience :: Science/Research
|
|
12
|
+
Classifier: License :: OSI Approved :: BSD License
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
20
|
+
Classifier: Topic :: Scientific/Engineering
|
|
21
|
+
Classifier: Typing :: Typed
|
|
22
|
+
Requires-Python: >=3.11
|
|
23
|
+
Requires-Dist: unxt
|
|
24
|
+
Requires-Dist: xarray>=2024.1.0
|
|
25
|
+
Description-Content-Type: text/markdown
|
|
26
|
+
|
|
27
|
+
# unxts.interop.xarray
|
|
28
|
+
|
|
29
|
+
xarray integration for [unxt](https://github.com/GalacticDynamics/unxt).
|
|
30
|
+
|
|
31
|
+
This is the canonical package (`unxts.interop.xarray`). It provides xarray accessors and conversion utilities for unxt's JAX-based quantities.
|
|
32
|
+
|
|
33
|
+
## Install
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
pip install unxts.interop.xarray
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
## Usage
|
|
40
|
+
|
|
41
|
+
```python
|
|
42
|
+
import unxts.interop.xarray
|
|
43
|
+
```
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
# unxts.interop.xarray
|
|
2
|
+
|
|
3
|
+
xarray integration for [unxt](https://github.com/GalacticDynamics/unxt).
|
|
4
|
+
|
|
5
|
+
This is the canonical package (`unxts.interop.xarray`). It provides xarray accessors and conversion utilities for unxt's JAX-based quantities.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
pip install unxts.interop.xarray
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Usage
|
|
14
|
+
|
|
15
|
+
```python
|
|
16
|
+
import unxts.interop.xarray
|
|
17
|
+
```
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
# `unxts.interop.xarray`
|
|
2
|
+
|
|
3
|
+
```{toctree}
|
|
4
|
+
:maxdepth: 1
|
|
5
|
+
:hidden:
|
|
6
|
+
```
|
|
7
|
+
|
|
8
|
+
Canonical [xarray](https://xarray.dev/) integration for [unxt](https://github.com/GalacticDynamics/unxt).
|
|
9
|
+
|
|
10
|
+
`unxts.interop.xarray` is the canonical location for xarray integration, superseding the deprecated `unxt-xarray` package.
|
|
11
|
+
|
|
12
|
+
Install: `pip install unxts.interop.xarray`
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
authors = [
|
|
3
|
+
{ name = "GalacticDynamics", email = "nstarman@users.noreply.github.com" },
|
|
4
|
+
{ name = "Nathaniel Starkman", email = "nstarman@users.noreply.github.com" },
|
|
5
|
+
]
|
|
6
|
+
classifiers = [
|
|
7
|
+
"Development Status :: 4 - Beta",
|
|
8
|
+
"Intended Audience :: Developers",
|
|
9
|
+
"Intended Audience :: Science/Research",
|
|
10
|
+
"License :: OSI Approved :: BSD License",
|
|
11
|
+
"Operating System :: OS Independent",
|
|
12
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
13
|
+
"Programming Language :: Python :: 3",
|
|
14
|
+
"Programming Language :: Python :: 3.11",
|
|
15
|
+
"Programming Language :: Python :: 3.12",
|
|
16
|
+
"Programming Language :: Python :: 3.13",
|
|
17
|
+
"Programming Language :: Python",
|
|
18
|
+
"Topic :: Scientific/Engineering",
|
|
19
|
+
"Typing :: Typed",
|
|
20
|
+
]
|
|
21
|
+
dependencies = ["unxt", "xarray>=2024.1.0"]
|
|
22
|
+
description = "xarray integration for unxt (canonical: unxts.interop.xarray)"
|
|
23
|
+
dynamic = ["version"]
|
|
24
|
+
license.text = "BSD-3-Clause"
|
|
25
|
+
name = "unxts.interop.xarray"
|
|
26
|
+
readme = "README.md"
|
|
27
|
+
requires-python = ">=3.11"
|
|
28
|
+
|
|
29
|
+
[project.urls]
|
|
30
|
+
"Bug Tracker" = "https://github.com/GalacticDynamics/unxt/issues"
|
|
31
|
+
Homepage = "https://github.com/GalacticDynamics/unxt"
|
|
32
|
+
|
|
33
|
+
[build-system]
|
|
34
|
+
build-backend = "hatchling.build"
|
|
35
|
+
requires = ["hatch-vcs", "hatchling"]
|
|
36
|
+
|
|
37
|
+
[dependency-groups]
|
|
38
|
+
test = [
|
|
39
|
+
"pytest>=8.4.2",
|
|
40
|
+
"pytest-arraydiff>=0.6.1",
|
|
41
|
+
"pytest-cov>=6.2.1",
|
|
42
|
+
"pytest-env>=1.1.5",
|
|
43
|
+
"pytest-github-actions-annotate-failures>=0.3.0",
|
|
44
|
+
"sybil[pytest]>=9.2.0",
|
|
45
|
+
]
|
|
46
|
+
|
|
47
|
+
[tool.hatch.version]
|
|
48
|
+
source = "vcs"
|
|
49
|
+
|
|
50
|
+
[tool.hatch.version.raw-options]
|
|
51
|
+
local_scheme = "no-local-version"
|
|
52
|
+
root = "../.."
|
|
53
|
+
search_parent_directories = true
|
|
54
|
+
|
|
55
|
+
[tool.hatch.version.raw-options.scm.git]
|
|
56
|
+
describe_command = [
|
|
57
|
+
"git",
|
|
58
|
+
"describe",
|
|
59
|
+
"--dirty",
|
|
60
|
+
"--tags",
|
|
61
|
+
"--long",
|
|
62
|
+
"--match",
|
|
63
|
+
"unxts-interop-xarray-v*",
|
|
64
|
+
]
|
|
65
|
+
|
|
66
|
+
[tool.hatch.build.hooks.vcs]
|
|
67
|
+
version-file = "src/unxts/interop/xarray/_version.py"
|
|
68
|
+
version-file-template = """\
|
|
69
|
+
version: str = {version!r}
|
|
70
|
+
version_tuple: tuple[int, int, int] | tuple[int, int, int, str, str]
|
|
71
|
+
version_tuple = {version_tuple!r}
|
|
72
|
+
"""
|
|
73
|
+
|
|
74
|
+
[tool.hatch.build.targets.wheel]
|
|
75
|
+
packages = ["src/unxts"]
|
|
76
|
+
|
|
77
|
+
[tool.uv.sources]
|
|
78
|
+
unxt = { workspace = true }
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""xarray integration for unxt.
|
|
2
|
+
|
|
3
|
+
This is the canonical package (unxts.interop.xarray).
|
|
4
|
+
The legacy ``unxt-xarray`` package is deprecated; migrate to
|
|
5
|
+
``unxts.interop.xarray``.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
__all__ = (
|
|
9
|
+
"attach_units",
|
|
10
|
+
"extract_unit_attributes",
|
|
11
|
+
"extract_units",
|
|
12
|
+
"strip_units",
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
from ._src import accessors as _accessors # noqa: F401 -- registers .unxt accessor
|
|
16
|
+
from ._src.conversion import (
|
|
17
|
+
attach_units,
|
|
18
|
+
extract_unit_attributes,
|
|
19
|
+
extract_units,
|
|
20
|
+
strip_units,
|
|
21
|
+
)
|
|
22
|
+
from ._version import version as __version__ # noqa: F401
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""Private implementation modules.
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2023 Galactic Dynamics. All rights reserved.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
__all__ = (
|
|
7
|
+
"UnxtDataArrayAccessor",
|
|
8
|
+
"UnxtDatasetAccessor",
|
|
9
|
+
"attach_units",
|
|
10
|
+
"extract_unit_attributes",
|
|
11
|
+
"extract_units",
|
|
12
|
+
"strip_units",
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
from .accessors import UnxtDataArrayAccessor, UnxtDatasetAccessor
|
|
16
|
+
from .conversion import (
|
|
17
|
+
attach_units,
|
|
18
|
+
extract_unit_attributes,
|
|
19
|
+
extract_units,
|
|
20
|
+
strip_units,
|
|
21
|
+
)
|
|
@@ -0,0 +1,376 @@
|
|
|
1
|
+
"""xarray accessors for unxt integration.
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2023 Galactic Dynamics. All rights reserved.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
__all__ = ("UnxtDataArrayAccessor", "UnxtDatasetAccessor")
|
|
7
|
+
|
|
8
|
+
import builtins
|
|
9
|
+
from collections.abc import Hashable, Mapping
|
|
10
|
+
|
|
11
|
+
from xarray import (
|
|
12
|
+
DataArray,
|
|
13
|
+
Dataset,
|
|
14
|
+
register_dataarray_accessor,
|
|
15
|
+
register_dataset_accessor,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
import unxt as u
|
|
19
|
+
from .conversion import (
|
|
20
|
+
UNIT_ATTR,
|
|
21
|
+
attach_units,
|
|
22
|
+
extract_unit_attributes,
|
|
23
|
+
extract_units,
|
|
24
|
+
strip_units,
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@register_dataarray_accessor("unxt")
|
|
29
|
+
class UnxtDataArrayAccessor:
|
|
30
|
+
"""Access methods for DataArrays with unxt units.
|
|
31
|
+
|
|
32
|
+
Methods and attributes can be accessed through the `.unxt` attribute.
|
|
33
|
+
|
|
34
|
+
Examples
|
|
35
|
+
--------
|
|
36
|
+
>>> import xarray as xr
|
|
37
|
+
>>> import unxt as u
|
|
38
|
+
>>> import unxts.interop.xarray # registers the accessor
|
|
39
|
+
|
|
40
|
+
>>> da = xr.DataArray([1.0, 2.0, 3.0], dims=["x"], attrs={"units": "m"})
|
|
41
|
+
>>> q = da.unxt.quantify()
|
|
42
|
+
>>> q.data
|
|
43
|
+
Quantity(Array([1., 2., 3.], dtype=float32), unit='m')
|
|
44
|
+
>>> da.unxt.units
|
|
45
|
+
{None: Unit("m")}
|
|
46
|
+
|
|
47
|
+
"""
|
|
48
|
+
|
|
49
|
+
def __init__(self, da: DataArray) -> None:
|
|
50
|
+
self._da = da
|
|
51
|
+
|
|
52
|
+
@property
|
|
53
|
+
def units(self) -> dict[Hashable, u.AbstractUnit | None]:
|
|
54
|
+
"""Units discovered from unit attributes on data and coordinates.
|
|
55
|
+
|
|
56
|
+
Returns
|
|
57
|
+
-------
|
|
58
|
+
dict[Hashable, AbstractUnit | None]
|
|
59
|
+
Mapping of names to normalized unit objects where the DataArray data
|
|
60
|
+
is under the `None` key.
|
|
61
|
+
|
|
62
|
+
"""
|
|
63
|
+
return extract_unit_attributes(self._da)
|
|
64
|
+
|
|
65
|
+
def quantify(
|
|
66
|
+
self,
|
|
67
|
+
units: str
|
|
68
|
+
| u.AbstractUnit
|
|
69
|
+
| Mapping[Hashable, str | u.AbstractUnit | None]
|
|
70
|
+
| None = None,
|
|
71
|
+
**unit_kwargs: str | u.AbstractUnit | None,
|
|
72
|
+
) -> DataArray:
|
|
73
|
+
"""Attach units to the DataArray.
|
|
74
|
+
|
|
75
|
+
Units can be specified as a string, unit object, or mapping of coordinate
|
|
76
|
+
names to units. If not specified, units are read from the "units" attribute.
|
|
77
|
+
|
|
78
|
+
Parameters
|
|
79
|
+
----------
|
|
80
|
+
units : str | AbstractUnit | Mapping | None, optional
|
|
81
|
+
Units to attach. Can be:
|
|
82
|
+
- A string or unit object to apply to the data array
|
|
83
|
+
- A dict-like mapping coordinate/variable names to units
|
|
84
|
+
- None to use the "units" attribute
|
|
85
|
+
**unit_kwargs
|
|
86
|
+
Keyword form of units for coordinate names.
|
|
87
|
+
|
|
88
|
+
Returns
|
|
89
|
+
-------
|
|
90
|
+
DataArray
|
|
91
|
+
DataArray with data and coordinates as unxt Quantities.
|
|
92
|
+
|
|
93
|
+
Examples
|
|
94
|
+
--------
|
|
95
|
+
>>> import xarray as xr
|
|
96
|
+
>>> import unxts.interop.xarray
|
|
97
|
+
|
|
98
|
+
Quantify using attribute:
|
|
99
|
+
|
|
100
|
+
>>> da = xr.DataArray([1.0, 2.0], dims=["x"], attrs={"units": "m"})
|
|
101
|
+
>>> da.data
|
|
102
|
+
array([1., 2.])
|
|
103
|
+
|
|
104
|
+
>>> q = da.unxt.quantify()
|
|
105
|
+
>>> q.data
|
|
106
|
+
Quantity(Array([1., 2.], dtype=float32), unit='m')
|
|
107
|
+
|
|
108
|
+
Quantify with explicit unit:
|
|
109
|
+
|
|
110
|
+
>>> da = xr.DataArray([1.0, 2.0], dims=["x"])
|
|
111
|
+
>>> q = da.unxt.quantify("km")
|
|
112
|
+
>>> q.data
|
|
113
|
+
Quantity(Array([1., 2.], dtype=float32), unit='km')
|
|
114
|
+
|
|
115
|
+
Quantify with coordinate units (use non-dimension coordinates to preserve
|
|
116
|
+
Quantity data on coordinates):
|
|
117
|
+
|
|
118
|
+
>>> da = xr.DataArray(
|
|
119
|
+
... [1.0, 2.0],
|
|
120
|
+
... dims=["i"],
|
|
121
|
+
... coords={"i": [0, 1], "x": ("i", [0.0, 1.0], {"units": "s"})},
|
|
122
|
+
... attrs={"units": "m"},
|
|
123
|
+
... )
|
|
124
|
+
>>> q = da.unxt.quantify()
|
|
125
|
+
>>> q.data
|
|
126
|
+
Quantity(Array([1., 2.], dtype=float32), unit='m')
|
|
127
|
+
>>> q.coords["x"].data
|
|
128
|
+
Quantity(Array([0., 1.], dtype=float32), unit='s')
|
|
129
|
+
|
|
130
|
+
"""
|
|
131
|
+
# Combine explicit units with unit_kwargs
|
|
132
|
+
if units is None:
|
|
133
|
+
units = unit_kwargs
|
|
134
|
+
elif isinstance(units, (str, u.AbstractUnit)):
|
|
135
|
+
# Single unit for the data array (None key = the DataArray's own data)
|
|
136
|
+
combined_units = {None: units}
|
|
137
|
+
combined_units.update(unit_kwargs)
|
|
138
|
+
units = combined_units
|
|
139
|
+
elif isinstance(units, Mapping):
|
|
140
|
+
combined_units = dict(units)
|
|
141
|
+
combined_units.update(unit_kwargs)
|
|
142
|
+
units = combined_units
|
|
143
|
+
else:
|
|
144
|
+
msg = f"units must be a string, AbstractUnit, or Mapping, got {type(units)}"
|
|
145
|
+
raise TypeError(msg)
|
|
146
|
+
|
|
147
|
+
# Discover unit attributes through the accessor property.
|
|
148
|
+
unit_attrs = self.units
|
|
149
|
+
|
|
150
|
+
# Merge: explicit units override attributes
|
|
151
|
+
final_units: dict[Hashable, str | u.AbstractUnit | None] = {}
|
|
152
|
+
for name in set(list(unit_attrs.keys()) + list(units.keys())):
|
|
153
|
+
if name in units:
|
|
154
|
+
final_units[name] = units[name]
|
|
155
|
+
elif name in unit_attrs:
|
|
156
|
+
final_units[name] = unit_attrs[name]
|
|
157
|
+
|
|
158
|
+
# Attach units
|
|
159
|
+
return attach_units(self._da, final_units)
|
|
160
|
+
|
|
161
|
+
def dequantify(
|
|
162
|
+
self, format: str | None = None, unit_attribute: str = UNIT_ATTR
|
|
163
|
+
) -> DataArray:
|
|
164
|
+
"""Convert quantities back to plain arrays with unit attributes.
|
|
165
|
+
|
|
166
|
+
Parameters
|
|
167
|
+
----------
|
|
168
|
+
format : str | None, optional
|
|
169
|
+
Format spec for unit representation (passed to ``builtins.format``).
|
|
170
|
+
If None, uses ``str(unit)``.
|
|
171
|
+
unit_attribute : str, optional
|
|
172
|
+
Name of attribute to store units in. Default is "units".
|
|
173
|
+
|
|
174
|
+
Returns
|
|
175
|
+
-------
|
|
176
|
+
DataArray
|
|
177
|
+
DataArray with plain arrays and unit attributes.
|
|
178
|
+
|
|
179
|
+
Examples
|
|
180
|
+
--------
|
|
181
|
+
>>> import xarray as xr
|
|
182
|
+
>>> import unxt as u
|
|
183
|
+
>>> import unxts.interop.xarray
|
|
184
|
+
|
|
185
|
+
>>> q = u.ParametricQuantity([1.0, 2.0], "m")
|
|
186
|
+
>>> da = xr.DataArray(q, dims=["x"])
|
|
187
|
+
>>> dequantified = da.unxt.dequantify()
|
|
188
|
+
>>> dequantified.data
|
|
189
|
+
Array([1., 2.], dtype=float32)
|
|
190
|
+
>>> dequantified.attrs["units"]
|
|
191
|
+
'm'
|
|
192
|
+
|
|
193
|
+
"""
|
|
194
|
+
# Extract units from quantities
|
|
195
|
+
units = extract_units(self._da)
|
|
196
|
+
|
|
197
|
+
# Strip quantities, converting to plain arrays
|
|
198
|
+
stripped = strip_units(self._da)
|
|
199
|
+
|
|
200
|
+
# Format units as strings for attributes
|
|
201
|
+
unit_strs: dict[Hashable, str] = {}
|
|
202
|
+
for name, unit in units.items():
|
|
203
|
+
if unit is not None:
|
|
204
|
+
if format is not None:
|
|
205
|
+
unit_strs[name] = builtins.format(unit, format)
|
|
206
|
+
else:
|
|
207
|
+
unit_strs[name] = str(unit)
|
|
208
|
+
|
|
209
|
+
# Add unit attributes
|
|
210
|
+
if None in unit_strs:
|
|
211
|
+
stripped.attrs[unit_attribute] = unit_strs[None]
|
|
212
|
+
|
|
213
|
+
for name, unit_str in unit_strs.items():
|
|
214
|
+
if name is None:
|
|
215
|
+
continue
|
|
216
|
+
if name in stripped.coords:
|
|
217
|
+
stripped.coords[name].attrs[unit_attribute] = unit_str
|
|
218
|
+
|
|
219
|
+
return stripped
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
@register_dataset_accessor("unxt")
|
|
223
|
+
class UnxtDatasetAccessor:
|
|
224
|
+
"""Access methods for Datasets with unxt units.
|
|
225
|
+
|
|
226
|
+
Methods and attributes can be accessed through the `.unxt` attribute.
|
|
227
|
+
|
|
228
|
+
Examples
|
|
229
|
+
--------
|
|
230
|
+
>>> import xarray as xr
|
|
231
|
+
>>> import unxts.interop.xarray
|
|
232
|
+
|
|
233
|
+
>>> ds = xr.Dataset(
|
|
234
|
+
... {
|
|
235
|
+
... "a": ("x", [1.0, 2.0], {"units": "m"}),
|
|
236
|
+
... "b": ("y", [3.0, 4.0], {"units": "s"}),
|
|
237
|
+
... }
|
|
238
|
+
... )
|
|
239
|
+
>>> q = ds.unxt.quantify()
|
|
240
|
+
>>> q["a"].data
|
|
241
|
+
Quantity(Array([1., 2.], dtype=float32), unit='m')
|
|
242
|
+
>>> q["b"].data
|
|
243
|
+
Quantity(Array([3., 4.], dtype=float32), unit='s')
|
|
244
|
+
|
|
245
|
+
"""
|
|
246
|
+
|
|
247
|
+
def __init__(self, ds: Dataset, /) -> None:
|
|
248
|
+
self._ds = ds
|
|
249
|
+
|
|
250
|
+
def quantify(
|
|
251
|
+
self,
|
|
252
|
+
units: Mapping[Hashable, str | u.AbstractUnit | None] | None = None,
|
|
253
|
+
**unit_kwargs: str | u.AbstractUnit | None,
|
|
254
|
+
) -> Dataset:
|
|
255
|
+
"""Attach units to the Dataset.
|
|
256
|
+
|
|
257
|
+
Units can be specified as a mapping of variable names to units.
|
|
258
|
+
If not specified, units are read from the "units" attribute of each variable.
|
|
259
|
+
|
|
260
|
+
Parameters
|
|
261
|
+
----------
|
|
262
|
+
units : Mapping | None, optional
|
|
263
|
+
Mapping of variable/coordinate names to units.
|
|
264
|
+
If None, uses the "units" attribute.
|
|
265
|
+
**unit_kwargs
|
|
266
|
+
Keyword form of units for variable names.
|
|
267
|
+
|
|
268
|
+
Returns
|
|
269
|
+
-------
|
|
270
|
+
Dataset
|
|
271
|
+
Dataset with variables and coordinates as unxt Quantities.
|
|
272
|
+
|
|
273
|
+
Examples
|
|
274
|
+
--------
|
|
275
|
+
>>> import xarray as xr
|
|
276
|
+
>>> import unxts.interop.xarray
|
|
277
|
+
|
|
278
|
+
Quantify using attributes:
|
|
279
|
+
|
|
280
|
+
>>> ds = xr.Dataset(
|
|
281
|
+
... {
|
|
282
|
+
... "a": ("x", [1.0, 2.0], {"units": "m"}),
|
|
283
|
+
... "b": ("y", [3.0, 4.0], {"units": "s"}),
|
|
284
|
+
... }
|
|
285
|
+
... )
|
|
286
|
+
>>> q = ds.unxt.quantify()
|
|
287
|
+
>>> q["a"].data
|
|
288
|
+
Quantity(Array([1., 2.], dtype=float32), unit='m')
|
|
289
|
+
|
|
290
|
+
Quantify with explicit units:
|
|
291
|
+
|
|
292
|
+
>>> ds = xr.Dataset({"a": ("x", [1.0, 2.0])})
|
|
293
|
+
>>> q = ds.unxt.quantify(a="km")
|
|
294
|
+
>>> q["a"].data
|
|
295
|
+
Quantity(Array([1., 2.], dtype=float32), unit='km')
|
|
296
|
+
|
|
297
|
+
"""
|
|
298
|
+
# Combine explicit units with unit_kwargs
|
|
299
|
+
if units is None:
|
|
300
|
+
units = unit_kwargs
|
|
301
|
+
else:
|
|
302
|
+
combined_units = dict(units)
|
|
303
|
+
combined_units.update(unit_kwargs)
|
|
304
|
+
units = combined_units
|
|
305
|
+
|
|
306
|
+
# Extract unit attributes
|
|
307
|
+
unit_attrs = extract_unit_attributes(self._ds)
|
|
308
|
+
|
|
309
|
+
# Merge: explicit units override attributes
|
|
310
|
+
final_units: dict[Hashable, u.AbstractUnit | str | None] = {}
|
|
311
|
+
for name in set(list(unit_attrs.keys()) + list(units.keys())):
|
|
312
|
+
if name in units:
|
|
313
|
+
final_units[name] = units[name]
|
|
314
|
+
elif name in unit_attrs:
|
|
315
|
+
final_units[name] = unit_attrs[name]
|
|
316
|
+
|
|
317
|
+
# Attach units
|
|
318
|
+
return attach_units(self._ds, final_units)
|
|
319
|
+
|
|
320
|
+
def dequantify(
|
|
321
|
+
self, format: str | None = None, unit_attribute: str = UNIT_ATTR
|
|
322
|
+
) -> Dataset:
|
|
323
|
+
"""Convert quantities back to plain arrays with unit attributes.
|
|
324
|
+
|
|
325
|
+
Parameters
|
|
326
|
+
----------
|
|
327
|
+
format : str | None, optional
|
|
328
|
+
Format spec for unit representation (passed to ``builtins.format``).
|
|
329
|
+
If None, uses ``str(unit)``.
|
|
330
|
+
unit_attribute : str, optional
|
|
331
|
+
Name of attribute to store units in. Default is "units".
|
|
332
|
+
|
|
333
|
+
Returns
|
|
334
|
+
-------
|
|
335
|
+
Dataset
|
|
336
|
+
Dataset with plain arrays and unit attributes.
|
|
337
|
+
|
|
338
|
+
Examples
|
|
339
|
+
--------
|
|
340
|
+
>>> import xarray as xr
|
|
341
|
+
>>> import unxt as u
|
|
342
|
+
>>> import unxts.interop.xarray
|
|
343
|
+
|
|
344
|
+
>>> q1 = u.ParametricQuantity([1.0, 2.0], "m")
|
|
345
|
+
>>> q2 = u.ParametricQuantity([3.0, 4.0], "s")
|
|
346
|
+
>>> ds = xr.Dataset({"a": ("x", q1), "b": ("y", q2)})
|
|
347
|
+
>>> dequantified = ds.unxt.dequantify()
|
|
348
|
+
>>> dequantified["a"].attrs["units"]
|
|
349
|
+
'm'
|
|
350
|
+
>>> dequantified["b"].attrs["units"]
|
|
351
|
+
's'
|
|
352
|
+
|
|
353
|
+
"""
|
|
354
|
+
# Extract units from quantities
|
|
355
|
+
units = extract_units(self._ds)
|
|
356
|
+
|
|
357
|
+
# Strip quantities, converting to plain arrays
|
|
358
|
+
stripped = strip_units(self._ds)
|
|
359
|
+
|
|
360
|
+
# Format units as strings for attributes
|
|
361
|
+
unit_strs: dict[Hashable, str] = {}
|
|
362
|
+
for name, unit in units.items():
|
|
363
|
+
if unit is not None:
|
|
364
|
+
if format is not None:
|
|
365
|
+
unit_strs[name] = builtins.format(unit, format)
|
|
366
|
+
else:
|
|
367
|
+
unit_strs[name] = str(unit)
|
|
368
|
+
|
|
369
|
+
# Add unit attributes to variables
|
|
370
|
+
for name, unit_str in unit_strs.items():
|
|
371
|
+
if name in stripped.data_vars:
|
|
372
|
+
stripped[name].attrs[unit_attribute] = unit_str
|
|
373
|
+
elif name in stripped.coords:
|
|
374
|
+
stripped.coords[name].attrs[unit_attribute] = unit_str
|
|
375
|
+
|
|
376
|
+
return stripped
|
|
@@ -0,0 +1,393 @@
|
|
|
1
|
+
"""Unit conversion functions for xarray objects.
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2023 Galactic Dynamics. All rights reserved.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
__all__ = (
|
|
7
|
+
"attach_units",
|
|
8
|
+
"extract_units",
|
|
9
|
+
"extract_unit_attributes",
|
|
10
|
+
"strip_units",
|
|
11
|
+
)
|
|
12
|
+
|
|
13
|
+
from collections.abc import Hashable, Mapping
|
|
14
|
+
from typing import Any, Final
|
|
15
|
+
|
|
16
|
+
from plum import dispatch
|
|
17
|
+
from xarray import DataArray, Dataset, Variable
|
|
18
|
+
|
|
19
|
+
import unxt as u
|
|
20
|
+
from unxt.quantity import AllowValue
|
|
21
|
+
|
|
22
|
+
# Name of the attribute used to store units
|
|
23
|
+
UNIT_ATTR: Final = "units"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _array_attach_units(
|
|
27
|
+
data: Any, /, unit: u.AbstractUnit | str | None
|
|
28
|
+
) -> u.Quantity | Any:
|
|
29
|
+
"""Attach units to array data.
|
|
30
|
+
|
|
31
|
+
Parameters
|
|
32
|
+
----------
|
|
33
|
+
data : array-like
|
|
34
|
+
The data to attach units to.
|
|
35
|
+
unit : AbstractUnit | str | None
|
|
36
|
+
The unit to attach. If None, returns data unchanged.
|
|
37
|
+
|
|
38
|
+
Returns
|
|
39
|
+
-------
|
|
40
|
+
Quantity | array-like
|
|
41
|
+
If unit is not None, returns a Quantity. Otherwise returns data unchanged.
|
|
42
|
+
|
|
43
|
+
Examples
|
|
44
|
+
--------
|
|
45
|
+
>>> import jax.numpy as jnp
|
|
46
|
+
>>> import unxt as u
|
|
47
|
+
>>> from unxts.interop.xarray._src.conversion import _array_attach_units
|
|
48
|
+
|
|
49
|
+
>>> data = jnp.array([1.0, 2.0, 3.0])
|
|
50
|
+
>>> q = _array_attach_units(data, "m")
|
|
51
|
+
>>> q
|
|
52
|
+
Quantity(Array([1., 2., 3.], dtype=float32), unit='m')
|
|
53
|
+
|
|
54
|
+
>>> _array_attach_units(data, None) is data
|
|
55
|
+
True
|
|
56
|
+
|
|
57
|
+
"""
|
|
58
|
+
return data if unit is None else u.Q(data, u.unit(unit))
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@dispatch
|
|
62
|
+
def extract_unit_attributes(obj: DataArray, /) -> dict[Hashable, u.AbstractUnit | None]:
|
|
63
|
+
"""Extract unit attributes from a DataArray.
|
|
64
|
+
|
|
65
|
+
Parameters
|
|
66
|
+
----------
|
|
67
|
+
obj : DataArray
|
|
68
|
+
The DataArray to extract unit attributes from.
|
|
69
|
+
|
|
70
|
+
Returns
|
|
71
|
+
-------
|
|
72
|
+
dict[Hashable, AbstractUnit | None]
|
|
73
|
+
Mapping of variable names to normalized unit objects.
|
|
74
|
+
The DataArray's own data units are stored under the ``None`` key.
|
|
75
|
+
|
|
76
|
+
Examples
|
|
77
|
+
--------
|
|
78
|
+
>>> import xarray as xr
|
|
79
|
+
>>> from unxts.interop.xarray._src.conversion import extract_unit_attributes
|
|
80
|
+
|
|
81
|
+
>>> da = xr.DataArray([1.0, 2.0], dims=["x"], attrs={"units": "m"})
|
|
82
|
+
>>> extract_unit_attributes(da)
|
|
83
|
+
{None: Unit("m")}
|
|
84
|
+
|
|
85
|
+
"""
|
|
86
|
+
units: dict[Hashable, u.AbstractUnit | None] = {}
|
|
87
|
+
|
|
88
|
+
# For DataArray, use None as the key for the data variable
|
|
89
|
+
if (v := obj.attrs.get(UNIT_ATTR)) is not None:
|
|
90
|
+
units[None] = u.unit(v)
|
|
91
|
+
|
|
92
|
+
# Extract from coordinates
|
|
93
|
+
for name, coord in obj.coords.items():
|
|
94
|
+
if (v := coord.attrs.get(UNIT_ATTR)) is not None:
|
|
95
|
+
units[name] = u.unit(v)
|
|
96
|
+
|
|
97
|
+
return units
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
@dispatch
|
|
101
|
+
def extract_unit_attributes(obj: Dataset, /) -> dict[Hashable, u.AbstractUnit | None]:
|
|
102
|
+
"""Extract unit attributes from a Dataset.
|
|
103
|
+
|
|
104
|
+
Parameters
|
|
105
|
+
----------
|
|
106
|
+
obj : Dataset
|
|
107
|
+
The Dataset to extract unit attributes from.
|
|
108
|
+
|
|
109
|
+
Returns
|
|
110
|
+
-------
|
|
111
|
+
dict[Hashable, AbstractUnit | None]
|
|
112
|
+
Mapping of variable names to normalized unit objects.
|
|
113
|
+
|
|
114
|
+
Examples
|
|
115
|
+
--------
|
|
116
|
+
>>> import xarray as xr
|
|
117
|
+
>>> from unxts.interop.xarray._src.conversion import extract_unit_attributes
|
|
118
|
+
|
|
119
|
+
>>> ds = xr.Dataset({"a": ("x", [1, 2], {"units": "m"}), "b": ("y", [3, 4])})
|
|
120
|
+
>>> extract_unit_attributes(ds)
|
|
121
|
+
{'a': Unit("m")}
|
|
122
|
+
|
|
123
|
+
"""
|
|
124
|
+
units: dict[Hashable, u.AbstractUnit | None] = {}
|
|
125
|
+
|
|
126
|
+
# Extract from all variables (data and coords)
|
|
127
|
+
for name, var in obj.variables.items():
|
|
128
|
+
if (v := var.attrs.get(UNIT_ATTR)) is not None:
|
|
129
|
+
units[name] = u.unit(v)
|
|
130
|
+
|
|
131
|
+
return units
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
@dispatch
|
|
135
|
+
def extract_unit_attributes(obj: object, /) -> dict:
|
|
136
|
+
msg = f"Cannot extract unit attributes from type: {type(obj)}"
|
|
137
|
+
raise TypeError(msg)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
@dispatch
|
|
141
|
+
def extract_units(obj: DataArray, /) -> dict[Hashable, u.AbstractUnit | None]:
|
|
142
|
+
"""Extract units from Quantities in a DataArray.
|
|
143
|
+
|
|
144
|
+
Parameters
|
|
145
|
+
----------
|
|
146
|
+
obj : DataArray
|
|
147
|
+
The DataArray to extract units from.
|
|
148
|
+
|
|
149
|
+
Returns
|
|
150
|
+
-------
|
|
151
|
+
dict[Hashable, AbstractUnit | None]
|
|
152
|
+
Mapping of variable names to their units.
|
|
153
|
+
The DataArray's own data units are stored under the ``None`` key.
|
|
154
|
+
|
|
155
|
+
Examples
|
|
156
|
+
--------
|
|
157
|
+
>>> import jax.numpy as jnp
|
|
158
|
+
>>> import xarray as xr
|
|
159
|
+
>>> import unxt as u
|
|
160
|
+
>>> from unxts.interop.xarray._src.conversion import extract_units
|
|
161
|
+
|
|
162
|
+
>>> q = u.ParametricQuantity([1.0, 2.0], "m")
|
|
163
|
+
>>> da = xr.DataArray(q, dims=["x"])
|
|
164
|
+
>>> units = extract_units(da)
|
|
165
|
+
>>> units[None]
|
|
166
|
+
Unit("m")
|
|
167
|
+
|
|
168
|
+
"""
|
|
169
|
+
units: dict[Hashable, u.AbstractUnit | None] = {}
|
|
170
|
+
|
|
171
|
+
# Extract from data
|
|
172
|
+
if (unit := u.unit_of(obj.data)) is not None:
|
|
173
|
+
units[None] = unit
|
|
174
|
+
|
|
175
|
+
# Extract from coordinates
|
|
176
|
+
for name, coord in obj.coords.items():
|
|
177
|
+
if (unit := u.unit_of(coord.data)) is not None:
|
|
178
|
+
units[name] = unit
|
|
179
|
+
|
|
180
|
+
return units
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
@dispatch
|
|
184
|
+
def extract_units(obj: Dataset, /) -> dict[Hashable, u.AbstractUnit | None]:
|
|
185
|
+
"""Extract units from Quantities in a Dataset.
|
|
186
|
+
|
|
187
|
+
Parameters
|
|
188
|
+
----------
|
|
189
|
+
obj : Dataset
|
|
190
|
+
The Dataset to extract units from.
|
|
191
|
+
|
|
192
|
+
Returns
|
|
193
|
+
-------
|
|
194
|
+
dict[Hashable, AbstractUnit | None]
|
|
195
|
+
Mapping of variable names to their units.
|
|
196
|
+
|
|
197
|
+
"""
|
|
198
|
+
units: dict[Hashable, u.AbstractUnit | None] = {}
|
|
199
|
+
|
|
200
|
+
# Extract from all variables
|
|
201
|
+
for name, var in obj.variables.items():
|
|
202
|
+
if (unit := u.unit_of(var.data)) is not None:
|
|
203
|
+
units[name] = unit
|
|
204
|
+
|
|
205
|
+
return units
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
@dispatch
|
|
209
|
+
def extract_units(obj: object, /) -> dict:
|
|
210
|
+
msg = f"Cannot extract units from type: {type(obj)}"
|
|
211
|
+
raise TypeError(msg)
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
@dispatch
|
|
215
|
+
def attach_units(
|
|
216
|
+
obj: DataArray, units: Mapping[Hashable, u.AbstractUnit | str | None]
|
|
217
|
+
) -> DataArray:
|
|
218
|
+
"""Attach units to a DataArray's variables.
|
|
219
|
+
|
|
220
|
+
Parameters
|
|
221
|
+
----------
|
|
222
|
+
obj : DataArray
|
|
223
|
+
The DataArray to attach units to.
|
|
224
|
+
units : Mapping[Hashable, AbstractUnit | str | None]
|
|
225
|
+
Mapping of variable names to units.
|
|
226
|
+
Use ``None`` as the key to attach units to the DataArray's own data.
|
|
227
|
+
|
|
228
|
+
Returns
|
|
229
|
+
-------
|
|
230
|
+
DataArray
|
|
231
|
+
New DataArray with units attached as Quantities.
|
|
232
|
+
|
|
233
|
+
Examples
|
|
234
|
+
--------
|
|
235
|
+
>>> import xarray as xr
|
|
236
|
+
>>> from unxts.interop.xarray._src.conversion import attach_units
|
|
237
|
+
|
|
238
|
+
>>> da = xr.DataArray([1.0, 2.0], dims=["x"])
|
|
239
|
+
>>> quantified = attach_units(da, {None: "m"})
|
|
240
|
+
>>> quantified.data
|
|
241
|
+
Quantity(Array([1., 2.], dtype=float32), unit='m')
|
|
242
|
+
|
|
243
|
+
"""
|
|
244
|
+
# Handle the data array itself (None key = the DataArray's own data)
|
|
245
|
+
data_unit = units.get(None)
|
|
246
|
+
new_data = _array_attach_units(obj.data, data_unit)
|
|
247
|
+
|
|
248
|
+
# Handle coordinates - need to preserve as Variable objects
|
|
249
|
+
new_coords = {}
|
|
250
|
+
for name, coord in obj.coords.items():
|
|
251
|
+
unit = units.get(name)
|
|
252
|
+
new_coords[name] = (
|
|
253
|
+
coord
|
|
254
|
+
if unit is None
|
|
255
|
+
else Variable(
|
|
256
|
+
coord.dims, _array_attach_units(coord.data, unit), dict(coord.attrs)
|
|
257
|
+
)
|
|
258
|
+
)
|
|
259
|
+
|
|
260
|
+
return DataArray(
|
|
261
|
+
data=new_data,
|
|
262
|
+
coords=new_coords,
|
|
263
|
+
dims=obj.dims,
|
|
264
|
+
name=obj.name,
|
|
265
|
+
attrs=dict(obj.attrs),
|
|
266
|
+
)
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
@dispatch
|
|
270
|
+
def attach_units(
|
|
271
|
+
obj: Dataset, units: Mapping[Hashable, u.AbstractUnit | str | None]
|
|
272
|
+
) -> Dataset:
|
|
273
|
+
"""Attach units to a Dataset's variables.
|
|
274
|
+
|
|
275
|
+
Parameters
|
|
276
|
+
----------
|
|
277
|
+
obj : Dataset
|
|
278
|
+
The Dataset to attach units to.
|
|
279
|
+
units : Mapping[Hashable, AbstractUnit | str | None]
|
|
280
|
+
Mapping of variable names to units.
|
|
281
|
+
|
|
282
|
+
Returns
|
|
283
|
+
-------
|
|
284
|
+
Dataset
|
|
285
|
+
New Dataset with units attached as Quantities.
|
|
286
|
+
|
|
287
|
+
"""
|
|
288
|
+
# Handle all variables in dataset
|
|
289
|
+
new_vars = {}
|
|
290
|
+
for name, var in obj.data_vars.items():
|
|
291
|
+
new_data = _array_attach_units(var.data, units.get(name))
|
|
292
|
+
new_vars[name] = (var.dims, new_data, dict(var.attrs))
|
|
293
|
+
|
|
294
|
+
# Handle coordinates
|
|
295
|
+
new_coords = {}
|
|
296
|
+
for name, coord in obj.coords.items():
|
|
297
|
+
unit = units.get(name)
|
|
298
|
+
new_coords[name] = (
|
|
299
|
+
coord
|
|
300
|
+
if unit is None
|
|
301
|
+
else Variable(
|
|
302
|
+
coord.dims, _array_attach_units(coord.data, unit), dict(coord.attrs)
|
|
303
|
+
)
|
|
304
|
+
)
|
|
305
|
+
|
|
306
|
+
return Dataset(data_vars=new_vars, coords=new_coords, attrs=dict(obj.attrs))
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
@dispatch
|
|
310
|
+
def attach_units(obj: object, units: Mapping) -> object:
|
|
311
|
+
msg = f"Cannot attach units to type: {type(obj)}"
|
|
312
|
+
raise TypeError(msg)
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
@dispatch
|
|
316
|
+
def strip_units(obj: DataArray) -> DataArray:
|
|
317
|
+
"""Strip units from a DataArray, converting Quantities to plain arrays.
|
|
318
|
+
|
|
319
|
+
Parameters
|
|
320
|
+
----------
|
|
321
|
+
obj : DataArray
|
|
322
|
+
The DataArray to strip units from.
|
|
323
|
+
|
|
324
|
+
Returns
|
|
325
|
+
-------
|
|
326
|
+
DataArray
|
|
327
|
+
New DataArray with plain arrays instead of Quantities.
|
|
328
|
+
|
|
329
|
+
Examples
|
|
330
|
+
--------
|
|
331
|
+
>>> import xarray as xr
|
|
332
|
+
>>> import unxt as u
|
|
333
|
+
>>> from unxts.interop.xarray._src.conversion import strip_units
|
|
334
|
+
|
|
335
|
+
>>> q = u.ParametricQuantity([1.0, 2.0], "m")
|
|
336
|
+
>>> da = xr.DataArray(q, dims=["x"])
|
|
337
|
+
>>> stripped = strip_units(da)
|
|
338
|
+
>>> stripped.data
|
|
339
|
+
Array([1., 2.], dtype=float32)
|
|
340
|
+
|
|
341
|
+
"""
|
|
342
|
+
# Strip units from data
|
|
343
|
+
new_data = u.ustrip(AllowValue, obj.data)
|
|
344
|
+
|
|
345
|
+
# Strip units from coordinates
|
|
346
|
+
new_coords = {}
|
|
347
|
+
for name, coord in obj.coords.items():
|
|
348
|
+
new_coord_data = u.ustrip(AllowValue, coord.data)
|
|
349
|
+
new_coords[name] = Variable(coord.dims, new_coord_data, dict(coord.attrs))
|
|
350
|
+
|
|
351
|
+
return DataArray(
|
|
352
|
+
data=new_data,
|
|
353
|
+
coords=new_coords,
|
|
354
|
+
dims=obj.dims,
|
|
355
|
+
name=obj.name,
|
|
356
|
+
attrs=dict(obj.attrs),
|
|
357
|
+
)
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
@dispatch
|
|
361
|
+
def strip_units(obj: Dataset) -> Dataset:
|
|
362
|
+
"""Strip units from a Dataset, converting Quantities to plain arrays.
|
|
363
|
+
|
|
364
|
+
Parameters
|
|
365
|
+
----------
|
|
366
|
+
obj : Dataset
|
|
367
|
+
The Dataset to strip units from.
|
|
368
|
+
|
|
369
|
+
Returns
|
|
370
|
+
-------
|
|
371
|
+
Dataset
|
|
372
|
+
New Dataset with plain arrays instead of Quantities.
|
|
373
|
+
|
|
374
|
+
"""
|
|
375
|
+
# Strip units from all variables
|
|
376
|
+
new_vars = {}
|
|
377
|
+
for name, var in obj.data_vars.items():
|
|
378
|
+
new_data = u.ustrip(AllowValue, var.data)
|
|
379
|
+
new_vars[name] = (var.dims, new_data, dict(var.attrs))
|
|
380
|
+
|
|
381
|
+
# Strip units from coordinates
|
|
382
|
+
new_coords = {}
|
|
383
|
+
for name, coord in obj.coords.items():
|
|
384
|
+
new_coord_data = u.ustrip(AllowValue, coord.data)
|
|
385
|
+
new_coords[name] = Variable(coord.dims, new_coord_data, dict(coord.attrs))
|
|
386
|
+
|
|
387
|
+
return Dataset(data_vars=new_vars, coords=new_coords, attrs=dict(obj.attrs))
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
@dispatch
|
|
391
|
+
def strip_units(obj: object) -> object:
|
|
392
|
+
msg = f"Cannot strip units from type: {type(obj)}"
|
|
393
|
+
raise TypeError(msg)
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
# file generated by vcs-versioning
|
|
2
|
+
# don't change, don't track in version control
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
__all__ = [
|
|
6
|
+
"__version__",
|
|
7
|
+
"__version_tuple__",
|
|
8
|
+
"version",
|
|
9
|
+
"version_tuple",
|
|
10
|
+
"__commit_id__",
|
|
11
|
+
"commit_id",
|
|
12
|
+
]
|
|
13
|
+
|
|
14
|
+
version: str
|
|
15
|
+
__version__: str
|
|
16
|
+
__version_tuple__: tuple[int | str, ...]
|
|
17
|
+
version_tuple: tuple[int | str, ...]
|
|
18
|
+
commit_id: str | None
|
|
19
|
+
__commit_id__: str | None
|
|
20
|
+
|
|
21
|
+
__version__ = version = '2.0.0'
|
|
22
|
+
__version_tuple__ = version_tuple = (2, 0, 0)
|
|
23
|
+
|
|
24
|
+
__commit_id__ = commit_id = None
|
|
File without changes
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""Smoke tests for the unxts.interop.xarray public API."""
|
|
2
|
+
|
|
3
|
+
import unxts.interop.xarray as ux
|
|
4
|
+
import xarray as xr
|
|
5
|
+
|
|
6
|
+
import unxt as u
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def test_all_symbols_present():
|
|
10
|
+
for name in ux.__all__:
|
|
11
|
+
assert hasattr(ux, name), f"unxts.interop.xarray missing: {name}"
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def test_accessor_registered_on_import():
|
|
15
|
+
da = xr.DataArray([1.0, 2.0])
|
|
16
|
+
assert hasattr(da, "unxt")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def test_attach_and_strip_round_trip():
|
|
20
|
+
da = xr.DataArray([1.0, 2.0])
|
|
21
|
+
attached = ux.attach_units(da, {None: "m"})
|
|
22
|
+
assert isinstance(attached.data, u.AbstractQuantity)
|
|
23
|
+
stripped = ux.strip_units(attached)
|
|
24
|
+
assert not isinstance(stripped.data, u.AbstractQuantity)
|