unxts.api 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.
@@ -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,29 @@
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2023, Nathaniel Starkman.
4
+ All rights reserved.
5
+
6
+ Redistribution and use in source and binary forms, with or without
7
+ modification, are permitted provided that the following conditions are met:
8
+
9
+ * Redistributions of source code must retain the above copyright notice, this
10
+ list of conditions and the following disclaimer.
11
+
12
+ * Redistributions in binary form must reproduce the above copyright notice,
13
+ this list of conditions and the following disclaimer in the documentation
14
+ and/or other materials provided with the distribution.
15
+
16
+ * Neither the name of the copyright holder nor the names of its
17
+ contributors may be used to endorse or promote products derived from
18
+ this software without specific prior written permission.
19
+
20
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
23
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
24
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
26
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
27
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
28
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,42 @@
1
+ Metadata-Version: 2.4
2
+ Name: unxts.api
3
+ Version: 2.0.0
4
+ Summary: Abstract dispatch API definitions for unxt (canonical: unxts.api)
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-Expression: BSD-3-Clause
9
+ License-File: LICENSE
10
+ Classifier: Development Status :: 5 - Production/Stable
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Intended Audience :: Science/Research
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.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Programming Language :: Python :: 3.14
20
+ Classifier: Topic :: Scientific/Engineering
21
+ Classifier: Typing :: Typed
22
+ Requires-Python: >=3.12
23
+ Requires-Dist: plum-dispatch>=2.5.7
24
+ Description-Content-Type: text/markdown
25
+
26
+ # unxts.api
27
+
28
+ Abstract dispatch API definitions for [unxt](https://github.com/GalacticDynamics/unxt).
29
+
30
+ This is the canonical package (`unxts.api`). It defines the abstract single-dispatch functions that libraries implement to support `unxt`-style unit-aware quantities.
31
+
32
+ ## Install
33
+
34
+ ```bash
35
+ pip install unxts.api
36
+ ```
37
+
38
+ ## Usage
39
+
40
+ ```python
41
+ import unxts.api as uapi
42
+ ```
@@ -0,0 +1,17 @@
1
+ # unxts.api
2
+
3
+ Abstract dispatch API definitions for [unxt](https://github.com/GalacticDynamics/unxt).
4
+
5
+ This is the canonical package (`unxts.api`). It defines the abstract single-dispatch functions that libraries implement to support `unxt`-style unit-aware quantities.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ pip install unxts.api
11
+ ```
12
+
13
+ ## Usage
14
+
15
+ ```python
16
+ import unxts.api as uapi
17
+ ```
@@ -0,0 +1,405 @@
1
+ # `unxts.api` API
2
+
3
+ ## Dimensions
4
+
5
+ ### `dimension(obj)`
6
+
7
+ Construct a dimension from various inputs.
8
+
9
+ **Abstract Signature:**
10
+
11
+ ```python
12
+ from typing import Any
13
+ import plum
14
+
15
+
16
+ @plum.dispatch.abstract
17
+ def dimension(obj: Any, /) -> Any:
18
+ """Construct the dimension."""
19
+ ```
20
+
21
+ **Example Implementations** (in `unxt`):
22
+
23
+ - `dimension(dimension: AbstractDimension)` - Identity operation
24
+ - `dimension(s: str)` - Construct from string (e.g., `"length"`, `"velocity"`)
25
+
26
+ **Examples:**
27
+
28
+ ```python
29
+ import unxt as u
30
+
31
+ # From string
32
+ length_dim = u.dimension("length")
33
+
34
+ # From unit
35
+ meter_dim = u.dimension_of(u.unit("m"))
36
+ ```
37
+
38
+ ### `dimension_of(obj)`
39
+
40
+ Return the dimension of an object.
41
+
42
+ **Abstract Signature:**
43
+
44
+ ```python
45
+ from typing import Any
46
+ import plum
47
+
48
+
49
+ @plum.dispatch.abstract
50
+ def dimension_of(obj: Any, /) -> Any:
51
+ """Return the dimension of the given units."""
52
+ ```
53
+
54
+ **Example Implementations** (in `unxt`):
55
+
56
+ - `dimension_of(unit: AbstractUnit)` - Get dimension from unit
57
+ - `dimension_of(quantity: Quantity)` - Get dimension from quantity
58
+
59
+ **Examples:**
60
+
61
+ ```python
62
+ import unxt as u
63
+
64
+ # From unit
65
+ u.dimension_of(u.unit("km")) # PhysicalType('length')
66
+
67
+ # From quantity
68
+ q = u.Q(5, "kg")
69
+ u.dimension_of(q) # PhysicalType('mass')
70
+ ```
71
+
72
+ ## Units
73
+
74
+ ### `unit(obj)`
75
+
76
+ Construct units from various inputs.
77
+
78
+ **Abstract Signature:**
79
+
80
+ ```python
81
+ from typing import Any
82
+ import plum
83
+
84
+
85
+ @plum.dispatch.abstract
86
+ def unit(obj: Any, /) -> Any:
87
+ """Construct the units from a units object."""
88
+ ```
89
+
90
+ **Example Implementations** (in `unxt`):
91
+
92
+ - `unit(unit: AbstractUnit)` - Identity operation
93
+ - `unit(s: str)` - Parse unit from string (e.g., `"m"`, `"km/s"`)
94
+
95
+ **Examples:**
96
+
97
+ ```python
98
+ import unxt as u
99
+
100
+ # From string
101
+ meter = u.unit("m")
102
+ velocity = u.unit("km/s")
103
+ ```
104
+
105
+ ### `unit_of(obj)`
106
+
107
+ Return the units of an object.
108
+
109
+ **Abstract Signature:**
110
+
111
+ ```python
112
+ from typing import Any
113
+ import plum
114
+
115
+
116
+ @plum.dispatch.abstract
117
+ def unit_of(obj: Any, /) -> Any:
118
+ """Return the units of an object."""
119
+ ```
120
+
121
+ **Example Implementations** (in `unxt`):
122
+
123
+ - `unit_of(obj: Any)` - Returns `None` for objects without units
124
+ - `unit_of(unit: AbstractUnit)` - Identity operation
125
+ - `unit_of(quantity: Quantity)` - Extract unit from quantity
126
+
127
+ **Examples:**
128
+
129
+ ```python
130
+ import unxt as u
131
+
132
+ # From quantity
133
+ q = u.Q(5, "m")
134
+ u.unit_of(q) # Unit("m")
135
+
136
+ # From non-quantity
137
+ u.unit_of(5) # None
138
+ ```
139
+
140
+ ## Quantities
141
+
142
+ ### `uconvert_value(to_unit, from_unit, value)`
143
+
144
+ Convert a numerical value from one set of units to another.
145
+
146
+ This is a low-level unit conversion function that operates on raw numerical values (numbers, arrays, etc.) rather than `Quantity` objects. It performs the pure numerical conversion between units, without wrapping the result in a `Quantity`.
147
+
148
+ **Abstract Signature:**
149
+
150
+ ```python
151
+ from typing import Any
152
+ import plum
153
+
154
+
155
+ @plum.dispatch.abstract
156
+ def uconvert_value(uto: Any, ufrom: Any, x: Any, /) -> Any:
157
+ """Convert the value from specified units to specified units.
158
+
159
+ General signature: ``(to_unit, from_unit, value) -> converted_value``
160
+ """
161
+ ```
162
+
163
+ **Key Features:**
164
+
165
+ - **Pure value conversion**: Converts raw numbers/arrays without `Quantity` wrapping
166
+ - **Flexible unit specification**: Accepts unit objects, strings, or unit systems
167
+ - **Multiple implementations**: Dispatches on unit type combinations
168
+ - **High performance**: Suitable for batch conversions and internal operations
169
+
170
+ **Example Implementations** (in `unxt`):
171
+
172
+ - `uconvert_value(to_unit: AbstractUnit, from_unit: AbstractUnit, value: ArrayLike)` - Convert value between two unit objects
173
+ - `uconvert_value(to_unit: str, from_unit: str, value: ArrayLike)` - Convert value using unit strings
174
+ - `uconvert_value(to_unitsys: AbstractUnitSystem, from_unit: AbstractUnit, value: ArrayLike)` - Convert to the preferred units of a unit system
175
+ - `uconvert_value(to_unitsys: AbstractUnitSystem, from_unit: str, value: ArrayLike)` - Convert to unit system preferred units using string input
176
+
177
+ **Relationship to Other Functions:**
178
+
179
+ - **vs `uconvert()`**: `uconvert_value()` operates on raw values; `uconvert()` operates on `Quantity` objects and returns `Quantity` objects. Internally, `uconvert()` often delegates to `uconvert_value()` to perform the numerical conversion step.
180
+ - **vs `ustrip()`**: `ustrip()` combines unit stripping with conversion in one operation; `uconvert_value()` only performs the conversion.
181
+
182
+ **Examples:**
183
+
184
+ ```python
185
+ import unxt as u
186
+ import numpy as np
187
+
188
+ # Convert using unit objects
189
+ u.uconvert_value(u.unit("m"), u.unit("km"), 1)
190
+ # Array(1000., dtype=float32, ...)
191
+
192
+ # Convert using unit strings
193
+ u.uconvert_value("m", "km", 1)
194
+ # Array(1000., dtype=float32, ...)
195
+
196
+ # Convert array values
197
+ u.uconvert_value("m", "km", np.array([1, 2, 3]))
198
+ # Array([1000., 2000., 3000.], dtype=float32, ...)
199
+
200
+ # Convert to unit system preferred units
201
+ u.uconvert_value(u.unitsystems.galactic, "km", 1e17)
202
+ # Converts the 1e17 km value to the galactic system's preferred length unit (kpc)
203
+ # 3.2407792894443648
204
+
205
+ # Verify the target unit
206
+ u.unitsystems.galactic[u.dimension("length")]
207
+ # Unit("kpc")
208
+
209
+ # Batch conversion in a pipeline
210
+ values_in_km = np.array([100, 500, 1000])
211
+ values_in_m = u.uconvert_value("m", "km", values_in_km)
212
+ # Array([100000., 500000., 1000000.], dtype=float32, ...)
213
+ ```
214
+
215
+ **Error Handling:**
216
+
217
+ The function will raise a `plum.NotFoundLookupError` if no dispatch is registered for the given unit type combination. This ensures type safety and prevents silent failures.
218
+
219
+ ```python
220
+ import plum
221
+
222
+
223
+ class CustomUnit: # incompatible unit types without registered dispatch
224
+ pass
225
+
226
+
227
+ try:
228
+ u.uconvert_value(CustomUnit(), CustomUnit(), 5)
229
+ except plum.NotFoundLookupError:
230
+ print("Incompatible unit types for conversion.")
231
+ ```
232
+
233
+ ### `uconvert(to_unit, quantity)`
234
+
235
+ Convert a quantity to the specified units.
236
+
237
+ **Abstract Signature:**
238
+
239
+ ```python
240
+ from typing import Any
241
+ import plum
242
+
243
+
244
+ @plum.dispatch.abstract
245
+ def uconvert(u: Any, x: Any, /) -> Any:
246
+ """Convert the quantity to the specified units."""
247
+ ```
248
+
249
+ **Example Implementations** (in `unxt`):
250
+
251
+ - `uconvert(to_unit: str | AbstractUnit, quantity: Quantity)` - Convert quantity to new units
252
+
253
+ **Examples:**
254
+
255
+ ```python
256
+ import unxt as u
257
+
258
+ # Convert quantity
259
+ q = u.Q(1, "km")
260
+ u.uconvert("m", q) # Quantity(Array(1000., ...), unit='m')
261
+ ```
262
+
263
+ ### `ustrip(quantity)` / `ustrip(to_unit, quantity)`
264
+
265
+ Strip units from a quantity, optionally converting first.
266
+
267
+ **Abstract Signature:**
268
+
269
+ ```python
270
+ from typing import Any
271
+ import plum
272
+
273
+
274
+ @plum.dispatch.abstract
275
+ def ustrip(*args: Any) -> Any:
276
+ """Strip the units from the quantity, first converting if necessary."""
277
+ ```
278
+
279
+ **Example Implementations** (in `unxt`):
280
+
281
+ - `ustrip(quantity: Quantity)` - Get value in current units
282
+ - `ustrip(to_unit: str | AbstractUnit, quantity: Quantity)` - Convert then get value.
283
+
284
+ **Examples:**
285
+
286
+ ```python
287
+ import unxt as u
288
+
289
+ # Strip current units
290
+ q = u.Q(5, "km")
291
+ u.ustrip(q) # Array(5., ...)
292
+
293
+ # Convert then strip
294
+ u.ustrip("m", q) # Array(5000., ...)
295
+ ```
296
+
297
+ ### `is_unit_convertible(to_unit, from_obj)`
298
+
299
+ Check if units are convertible.
300
+
301
+ **Abstract Signature:**
302
+
303
+ ```python
304
+ from typing import Any
305
+ import plum
306
+
307
+
308
+ @plum.dispatch.abstract
309
+ def is_unit_convertible(to_unit: Any, from_: Any, /) -> bool:
310
+ """Check if the units are convertible."""
311
+ ```
312
+
313
+ **Example Implementations** (in `unxt`):
314
+
315
+ - `is_unit_convertible(to_unit: AbstractUnit, from_unit: AbstractUnit)` - Check unit compatibility
316
+ - `is_unit_convertible(to_unit: AbstractUnit, from_quantity: Quantity)` - Check if quantity can convert
317
+
318
+ **Examples:**
319
+
320
+ ```python
321
+ import unxt as u
322
+
323
+ # Check unit compatibility
324
+ u.is_unit_convertible(u.unit("km"), u.unit("m")) # True
325
+ u.is_unit_convertible(u.unit("kg"), u.unit("m")) # False
326
+
327
+ # Check quantity
328
+ q = u.Q(5, "m")
329
+ u.is_unit_convertible(u.unit("km"), q) # True
330
+ u.is_unit_convertible(u.unit("kg"), q) # False
331
+ ```
332
+
333
+ ### `wrap_to(value, min, max)`
334
+
335
+ Wrap a value to the range [min, max).
336
+
337
+ **Abstract Signature:**
338
+
339
+ ```python
340
+ from typing import Any
341
+ import plum
342
+
343
+
344
+ @plum.dispatch.abstract
345
+ def wrap_to(x: Any, min: Any, max: Any, /) -> Any:
346
+ """Wrap to the range [min, max)."""
347
+ ```
348
+
349
+ **Example Implementations** (in `unxt`):
350
+
351
+ - `wrap_to(x: AbstractQuantity, min: AbstractQuantity, max: AbstractQuantity)` - Wrap values to a range. The dispatch is on `AbstractQuantity` and preserves the concrete input type (an `Angle` in, an `Angle` out).
352
+
353
+ **Examples:**
354
+
355
+ ```python
356
+ import unxt as u
357
+
358
+ # Wrap an angle to [0, 360) degrees. Use ``Angle`` so the result is an ``Angle``
359
+ # (``wrap_to`` preserves the input type; a plain ``Quantity`` in gives a
360
+ # ``Quantity`` out).
361
+ angle = u.Angle(370, "deg")
362
+ min_angle = u.Angle(0, "deg")
363
+ max_angle = u.Angle(360, "deg")
364
+
365
+ u.quantity.wrap_to(angle, min_angle, max_angle) # Angle(Array(10, ...), unit='deg')
366
+
367
+ # Can also use keyword arguments
368
+ u.quantity.wrap_to(angle, min=min_angle, max=max_angle)
369
+ ```
370
+
371
+ ## Unit Systems
372
+
373
+ ### `unitsystem_of(obj)`
374
+
375
+ Return the unit system of an object.
376
+
377
+ **Abstract Signature:**
378
+
379
+ ```python
380
+ from typing import Any
381
+ import plum
382
+
383
+
384
+ @plum.dispatch.abstract
385
+ def unitsystem_of(obj: Any, /) -> Any:
386
+ """Return the unit system of an object."""
387
+ ```
388
+
389
+ **Example Implementations** (in `unxt`):
390
+
391
+ - `unitsystem_of(quantity: Quantity)` - Get unit system if quantity has one
392
+ - `unitsystem_of(unitsystem: AbstractUnitSystem)` - Identity operation
393
+
394
+ **Examples:**
395
+
396
+ ```python
397
+ import unxt as u
398
+
399
+ # From unit system
400
+ sys = u.unitsystem("m", "s", "kg", "rad")
401
+ u.unitsystem_of(sys) # Returns sys
402
+
403
+ # From quantity (if it has an associated system)
404
+ # This depends on how the quantity was constructed
405
+ ```