unxt.quantity#
Quantities in JAX.
This module provides JAX-compatible quantity types with automatic unit handling, conversions, and a rich set of mathematical operations that preserve dimensional correctness.
## Core Classes
`Quantity`: The default quantity class, no dimension parametrization, aliased as Q.
`StaticQuantity`: Quantity holding a static NumPy value, for use as a JAX static argument.
`Angle`: Specialized quantity type for angular measurements with wrapping support.
Dimension-parametrized quantities with runtime checking (ParametricQuantity, aliased PQ) now live in the separate unxts.parametric package.
## Key Functions
`uconvert`: Convert a quantity to different units.
`ustrip`: Extract the numerical value from a quantity.
`is_unit_convertible`: Check if two units are convertible to each other.
`wrap_to`: Wrap angular quantities to a specified range.
## Examples
### Creating quantities with units:
>>> import unxt as u
>>> import jax
>>> import jax.numpy as jnp
>>> distance = u.Q(100, "m")
>>> distance
Quantity(Array(100, dtype=int32...), unit='m')
Create from arrays
>>> velocities = u.Q([10, 20, 30], "m/s")
>>> velocities
Quantity(Array([10, 20, 30], dtype=int32), unit='m / s')
Unit conversions and arithmetic:
Convert units
>>> distance_km = u.uconvert("km", distance)
>>> distance_km
Quantity(Array(0.1, dtype=float32...), unit='km')
Arithmetic preserves units.
>>> time = u.Q(5, "s") # use Quantity alias
>>> velocity = distance / time
>>> velocity
Quantity(Array(20., dtype=float32...), unit='m / s')
Strip units for numerical operations
>>> u.ustrip("m", distance)
Array(100, dtype=int32...)
### Working with angles:
Create angle quantities
>>> theta = u.Angle(180, "deg")
>>> theta
Angle(Array(180, dtype=int32...), unit='deg')
Convert to radians
>>> theta_rad = u.uconvert("rad", theta)
>>> theta_rad
Angle(Array(3.1415927, dtype=float32...), unit='rad')
Wrap angles to a range
>>> angle = u.Angle(450, "deg")
>>> wrapped = u.quantity.wrap_to(angle, u.Angle(0, "deg"), u.Angle(360, "deg"))
>>> wrapped
Angle(Array(90, dtype=int32...), unit='deg')
### Advanced usage with JAX transformations:
Quantities work with JAX transformations
>>> def kinetic_energy(mass, velocity):
... return 0.5 * mass * velocity**2
>>> mass = u.Q(2.0, "kg")
>>> vel = u.Q(10.0, "m/s")
>>> energy = kinetic_energy(mass, vel)
>>> energy
Quantity(Array(100., dtype=float32...), unit='m2 kg / s2')
Convert to standard energy units
>>> u.uconvert("J", energy)
Quantity(Array(100., dtype=float32...), unit='J')
JIT compilation works seamlessly
>>> @jax.jit
... def compute_force(mass, accel):
... return mass * accel
>>> force = compute_force(u.Q(5.0, "kg"), u.Q(9.8, "m/s^2"))
>>> force
Quantity(Array(49., dtype=float32...), unit='kg m / s2')
- class unxt.quantity.Quantity(value: Any, unit: Any)#
Bases:
AbstractQuantityThe default quantity: units without dimension parametrization.
This class is not parametrized by its dimensionality, making it a single class (and a single JAX pytree type) regardless of dimension. For runtime dimension checking and dimension-specific dispatch, see unxts.parametric.ParametricQuantity.
Examples
>>> import unxt as u >>> u.Quantity(1, "m") Quantity(Array(1, dtype=int32...), unit='m')
- value: Shaped[Array, '*shape'] | Shaped[StaticValue, '*shape']#
The value of the Quantity.
- unit: UnitBase | FunctionUnitBase#
The unit associated with this value.
- property T: AbstractQuantity#
Transpose of the array.
Examples
>>> import unxt as u >>> q = u.Q([[0, 1], [1, 2]], "m") >>> q.T Quantity(Array([[0, 1], [1, 2]], dtype=int32), unit='m')
- argmax(*args: Any, **kwargs: Any)#
Return the indices of the maximum value.
Examples
>>> import unxt as u >>> q = u.Q([1, 2, 3], "m") >>> q.argmax() Array(2, dtype=int32)
- argmin(*args: Any, **kwargs: Any)#
Return the indices of the minimum value.
Examples
>>> import unxt as u >>> q = u.Q([1, 2, 3], "m") >>> q.argmin() Array(0, dtype=int32)
- astype(*args: Any, **kwargs: Any)#
Copy the array and cast to a specified dtype.
Examples
>>> import unxt as u >>> q = u.Q([1, 2, 3], "m") >>> q.dtype dtype('int32')
>>> q.astype(float) Quantity(Array([1., 2., 3.], dtype=float32), unit='m')
- Parameters:
- Return type:
- property at: _QuantityIndexUpdateHelper#
Helper property for index update functionality.
The
atproperty provides a functionally pure equivalent of in-place array modifications.In particular:
Alternate syntax
Equivalent In-place expression
x = x.at[idx].set(y)x[idx] = yx = x.at[idx].add(y)x[idx] += yx = x.at[idx].subtract(y)x[idx] -= yx = x.at[idx].multiply(y)x[idx] *= yx = x.at[idx].divide(y)x[idx] /= yx = x.at[idx].power(y)x[idx] **= yx = x.at[idx].min(y)x[idx] = minimum(x[idx], y)x = x.at[idx].max(y)x[idx] = maximum(x[idx], y)x = x.at[idx].apply(ufunc)ufunc.at(x, idx)x = x.at[idx].get()x = x[idx]None of the
x.atexpressions modify the originalx; instead they return a modified copy ofx. However, inside ajit()compiled function, expressions likex = x.at[idx].set(y)are guaranteed to be applied in-place.Unlike NumPy in-place operations such as
x[idx] += y, if multiple indices refer to the same location, all updates will be applied (NumPy would only apply the last update, rather than applying all updates.) The order in which conflicting updates are applied is implementation-defined and may be nondeterministic (e.g., due to concurrency on some hardware platforms).By default, JAX assumes that all indices are in-bounds. Alternative out-of-bound index semantics can be specified via the
modeparameter (see below).- Parameters:
mode โ
string specifying out-of-bound indexing mode. Options are:
"promise_in_bounds": (default) The user promises that indices are in bounds. No additional checking will be performed. In practice, this means that out-of-bounds indices inget()will be clipped, and out-of-bounds indices inset(),add(), etc. will be dropped."clip": clamp out of bounds indices into valid range."drop": ignore out-of-bound indices."fill": alias for"drop". For get(), the optionalfill_valueargument specifies the value that will be returned.
See
jax.lax.GatherScatterModefor more details.wrap_negative_indices โ If True (default) then negative indices indicate position from the end of the array, similar to Python and NumPy indexing. If False, then negative indices are considered out-of-bounds and behave according to the
modeparameter.fill_value โ Only applies to the
get()method: the fill value to return for out-of-bounds slices whenmodeis'fill'. Ignored otherwise. Defaults toNaNfor inexact types, the largest negative value for signed types, the largest positive value for unsigned types, andTruefor booleans.indices_are_sorted โ If True, the implementation will assume that the (normalized) indices passed to
at[]are sorted in ascending order, which can lead to more efficient execution on some backends. If True but the indices are not actually sorted, the output is undefined.unique_indices โ If True, the implementation will assume that the (normalized) indices passed to
at[]are unique, which can result in more efficient execution on some backends. If True but the indices are not actually unique, the output is undefined.
Examples
>>> x = jnp.arange(5.0) >>> x Array([0., 1., 2., 3., 4.], dtype=float32) >>> x.at[2].get() Array(2., dtype=float32) >>> x.at[2].add(10) Array([ 0., 1., 12., 3., 4.], dtype=float32)
By default, out-of-bound indices are ignored in updates, but this behavior can be controlled with the
modeparameter:>>> x.at[10].add(10) # dropped Array([0., 1., 2., 3., 4.], dtype=float32) >>> x.at[20].add(10, mode='clip') # clipped Array([ 0., 1., 2., 3., 14.], dtype=float32)
For
get(), out-of-bound indices are clipped by default:>>> x.at[20].get() # out-of-bounds indices clipped Array(4., dtype=float32) >>> x.at[20].get(mode='fill') # out-of-bounds indices filled with NaN Array(nan, dtype=float32) >>> x.at[20].get(mode='fill', fill_value=-1) # custom fill value Array(-1., dtype=float32)
Negative indices count from the end of the array, but this behavior can be disabled by setting
wrap_negative_indices = False:>>> x.at[-1].set(99) Array([ 0., 1., 2., 3., 99.], dtype=float32) >>> x.at[-1].set(99, wrap_negative_indices=False, mode='drop') # dropped! Array([0., 1., 2., 3., 4.], dtype=float32)
- block_until_ready()#
Block until the array is ready.
- Return type:
Examples
>>> import unxt as u >>> q = u.Q(1, "m") >>> q.block_until_ready() is q True
- decompose(bases: Sequence[UnitBase | FunctionUnitBase | str], /)#
Decompose the quantity into the given bases.
Examples
>>> from unxt import Quantity
>>> q = Quantity(1, "m") >>> q.decompose(["cm", "s"]) Quantity(Array(100., dtype=float32, ...), unit='cm')
- Parameters:
bases (
Sequence[UnitBase|FunctionUnitBase|str])- Return type:
- property device: Device#
Device where the array is located.
Examples
>>> import unxt as u >>> u.Q(1, "m").device CpuDevice(id=0)
- devices()#
Return the devices where the array is located.
Examples
>>> import unxt as u >>> q = u.Q(1, "m") >>> q.devices() {CpuDevice(id=0)}
- property dtype: dtype#
Data type of the array.
Examples
>>> import unxt as u >>> u.Q(1, "m").dtype dtype('int32')
- flatten()#
Return a flattened version of the array.
- Return type:
Examples
>>> import unxt as u >>> q = u.Q([[1, 2], [3, 4]], "m") >>> q.flatten() Quantity(Array([1, 2, 3, 4], dtype=int32), unit='m')
- classmethod from_(cls: type[AbstractQuantity], *args: Any, **kwargs: Any)#
- from_(cls: type[AbstractQuantity], value: ArrayLike | list[Shaped[Array, ''] | Shaped[ndarray, ''] | bool | number | bool | int | float | complex] | tuple[Shaped[Array, ''] | Shaped[ndarray, ''] | bool | number | bool | int | float | complex, ...], unit: Any, /, *, dtype: Any = None) AbstractQuantity
- Parameters:
- Return type:
Construct a unxt.AbstractQuantity from an array-like value and a unit.
- Parameters:
- Return type:
Examples
For this example weโll use the Quantity class. The same applies to any subclass of AbstractQuantity.
>>> import jax.numpy as jnp >>> import unxt as u
>>> x = jnp.array([1.0, 2, 3]) >>> u.Q.from_(x, "m") Quantity(Array([1., 2., 3.], dtype=float32), unit='m')
>>> u.Q.from_([1.0, 2, 3], "m") Quantity(Array([1., 2., 3.], dtype=float32), unit='m')
>>> u.Q.from_((1.0, 2, 3), "m") Quantity(Array([1., 2., 3.], dtype=float32), unit='m')
- from_(cls: type[AbstractQuantity], value: ArrayLike | list[Shaped[Array, ''] | Shaped[ndarray, ''] | bool | number | bool | int | float | complex] | tuple[Shaped[Array, ''] | Shaped[ndarray, ''] | bool | number | bool | int | float | complex, ...], /, *, unit: Any, dtype: Any = None) AbstractQuantity
- Parameters:
- Return type:
Make a unxt.AbstractQuantity from an array-like value and a unit kwarg.
Examples
For this example weโll use the unxt.Quantity class. The same applies to any subclass of unxt.AbstractQuantity.
>>> import unxt as u >>> u.Q.from_([1.0, 2, 3], unit="m") Quantity(Array([1., 2., 3.], dtype=float32), unit='m')
- from_(cls: type[AbstractQuantity], *, value: Any, unit: Any, dtype: Any = None) AbstractQuantity
- Parameters:
- Return type:
Construct a AbstractQuantity from value and unit kwargs.
Examples
For this example weโll use the Quantity class. The same applies to any subclass of AbstractQuantity.
>>> import unxt as u >>> u.Q.from_(value=[1.0, 2, 3], unit="m") Quantity(Array([1., 2., 3.], dtype=float32), unit='m')
- from_(cls: type[AbstractQuantity], mapping: Mapping[str, Any]) AbstractQuantity
- Parameters:
- Return type:
Construct a quantity from a Mapping.
Examples
For this example weโll use the Quantity class. The same applies to any subclass of AbstractQuantity.
>>> import jax.numpy as jnp >>> import unxt as u
>>> x = jnp.array([1.0, 2, 3]) >>> q = u.Q.from_({"value": x, "unit": "m"}) >>> q Quantity(Array([1., 2., 3.], dtype=float32), unit='m')
>>> u.Q.from_({"value": q, "unit": "km"}) Quantity(Array([0.001, 0.002, 0.003], dtype=float32), unit='km')
- from_(cls: type[AbstractQuantity], value: AbstractQuantity, unit: Any, /, *, dtype: Any = None) AbstractQuantity
- Parameters:
- Return type:
Construct a quantity from another quantity.
The value is converted to the new unit.
Examples
>>> import unxt as u
>>> q = u.Q(1, "m") >>> u.Q.from_(q, "cm") Quantity(Array(100., dtype=float32, ...), unit='cm')
- from_(cls: type[AbstractQuantity], value: AbstractQuantity, unit: NoneType, /, *, dtype: Any = None) AbstractQuantity
- Parameters:
- Return type:
Construct a quantity from another quantity.
The value is converted to the new unit.
Examples
>>> import unxt as u
>>> q = u.Q(1, "m") >>> u.Q.from_(q, None) Quantity(Array(1, dtype=int32...), unit='m')
- from_(cls: type[AbstractQuantity], value: AbstractQuantity, /, *, unit: Any | None = None, dtype: Any = None) AbstractQuantity
- Parameters:
- Return type:
Construct a quantity from another quantity.
The unit is unchanged.
- from_(cls: type[StaticQuantity], value: ArrayLike | list[Shaped[Array, ''] | Shaped[ndarray, ''] | bool | number | bool | int | float | complex] | tuple[Shaped[Array, ''] | Shaped[ndarray, ''] | bool | number | bool | int | float | complex, ...], unit: Any, /, *, dtype: Any = None) StaticQuantity
- Parameters:
- Return type:
Construct a StaticQuantity, keeping the value on NumPy dtypes.
The generic
AbstractQuantity.from_routes the value throughjnp.asarray, which applies JAXโs x64-disabled dtype rules and silently downcasts int64 / float64 to int32 / float32. A StaticQuantity stores its value verbatim, so hand the value straight to__init__and let theStaticValue.from_converter convert it โ that preserves the NumPy dtype. Delegating (rather than callingnp.asarrayhere) also keeps.from_and__init__under the same policy for JAX inputs, instead of materialising an array the constructor would reject. (The keyword-unitoverload delegates here, so it is covered too.)Examples
>>> import numpy as np >>> import unxt as u
>>> u.StaticQuantity.from_( ... np.array([1, 2, 3], dtype=np.int64), "m" ... ).value.array.dtype dtype('int64')
.from_applies the same JAX-input policy as__init__โ it delegates rather than converting first, so the two cannot drift:>>> import jax.numpy as jnp >>> u.StaticQuantity.from_(jnp.array([1.0, 2.0]), "m") StaticQuantity(array([1., 2.], dtype=float32), unit='m')
- from_(cls: type[AbstractQuantity], value: Quantity, /, **kwargs: Any) AbstractQuantity
- Parameters:
- Return type:
Construct a quantity from an astropy Quantity.
The value is converted to the new unit.
Examples
>>> import unxt as u >>> import astropy.units as apyu
>>> u.Q.from_(apyu.Quantity(1, "m")) Quantity(Array(1., dtype=float32), unit='m')
- from_(cls: type[AbstractQuantity], value: Quantity, u: Any, /, **kwargs: Any) AbstractQuantity
- Parameters:
- Return type:
Construct a quantity from an astropy Quantity, converting to a target unit.
The value is converted to the new unit.
Examples
>>> import unxt as u >>> import astropy.units as apyu
>>> u.Q.from_(apyu.Quantity(1, "m"), "cm") Quantity(Array(100., dtype=float32), unit='cm')
- Parameters:
cls (
type[AbstractQuantity])args (
Any)kwargs (
Any)
- Return type:
- is_equivalent(other: AbstractQuantity, /)#
Whether
selfandotherare physically equal (unit-aware).The method form of unxt.equivalent; unlike
==(which is unit-blind for StaticValue-backed quantities) this accounts for unit conversion.Examples
>>> import unxt as u >>> u.Q(1000.0, "m").is_equivalent(u.Q(1.0, "km")) Quantity(Array(True, dtype=bool...), unit='')
- Parameters:
other (
AbstractQuantity)- Return type:
- property mT: AbstractQuantity#
Matrix transpose of the array.
Examples
>>> import unxt as u >>> q = u.Q([[0, 1], [1, 2]], "m") >>> q.mT Quantity(Array([[0, 1], [1, 2]], dtype=int32), unit='m')
- max(*args: Any, **kwargs: Any)#
Return the maximum value.
Examples
>>> import unxt as u >>> q = u.Q([1, 2, 3], "m") >>> q.max() Quantity(Array(3, dtype=int32), unit='m')
- Parameters:
- Return type:
- mean(*args: Any, **kwargs: Any)#
Return the mean value.
Examples
>>> import unxt as u >>> q = u.Q([1, 2, 3], "m") >>> q.mean() Quantity(Array(2., dtype=float32), unit='m')
- Parameters:
- Return type:
- min(*args: Any, **kwargs: Any)#
Return the minimum value.
Examples
>>> import unxt as u >>> q = u.Q([1, 2, 3], "m") >>> q.min() Quantity(Array(1, dtype=int32), unit='m')
- Parameters:
- Return type:
- property ndim: int#
Number of dimensions.
Examples
>>> import unxt as u >>> q = u.Q([[1]], "m") >>> q.ndim 2
- ravel()#
Return a flattened version of the array.
- Return type:
Examples
>>> import unxt as u >>> q = u.Q([[1, 2], [3, 4]], "m") >>> q.ravel() Quantity(Array([1, 2, 3, 4], dtype=int32), unit='m')
- reshape(*args: Any, order: str = 'C')#
Return a reshaped version of the array.
Examples
>>> import unxt as u >>> q = u.Q([1, 2, 3, 4], "m") >>> q.reshape(2, 2) Quantity(Array([[1, 2], [3, 4]], dtype=int32), unit='m')
- Parameters:
- Return type:
- round(*args: Any, **kwargs: Any)#
Round the array to the given number of decimals.
Examples
>>> import unxt as u >>> q = u.Q([1.1, 2.2, 3.3], "m") >>> q.round(0) Quantity(Array([1., 2., 3.], dtype=float32), unit='m')
- Parameters:
- Return type:
- property sharding: Any#
Return the sharding configuration of the array.
Examples
>>> import unxt as u >>> q = u.Q([1, 2, 3], "m") >>> q.sharding SingleDeviceSharding(device=..., memory_kind=...)
- property size: int#
Total number of elements.
Examples
>>> import unxt as u >>> q = u.Q([1, 2, 3], "m") >>> q.size 3
- squeeze(*args: Any, **kwargs: Any)#
Return the array with all single-dimensional entries removed.
Examples
>>> import unxt as u >>> q = u.Q([[[1], [2], [3]]], "m") >>> q.squeeze() Quantity(Array([1, 2, 3], dtype=int32), unit='m')
- Parameters:
- Return type:
- to(u: Any, /)#
Convert the quantity to the given units.
See unxt.quantity.AbstractQuantity.uconvert.
Examples
>>> from unxt import Quantity
>>> q = Quantity(1, "m") >>> q.to("cm") Quantity(Array(100., dtype=float32, ...), unit='cm')
- Parameters:
u (
Any)- Return type:
- to_device(device: None | Device = None)#
Move the array to a new device.
Examples
>>> import unxt as u >>> q = u.Q(1, "m") >>> q.to_device(None) Quantity(Array(1, dtype=int32...), unit='m')
- Parameters:
- Return type:
- to_value(u: Any, /)#
Return the value in the given units.
See unxt.AbstractQuantity.ustrip.
Examples
>>> from unxt import Quantity
>>> q = Quantity(1, "m") >>> q.to_value("cm") Array(100., dtype=float32, weak_type=True)
- final class unxt.quantity.StaticQuantity(value: Any, unit: Any)#
Bases:
AbstractQuantityA non-parametric quantity whose value is always a static NumPy array.
Unlike ~unxt.Quantity, its value is stored as a static (hashable) NumPy array, which lets a StaticQuantity be passed as a static argument to a jax.jit-compiled function. It accepts Python scalars and array-like inputs convertible to NumPy arrays; a concrete (eager) JAX array is materialised back to NumPy, and only a traced value โ which cannot be static โ is rejected.
Examples
>>> import numpy as np >>> import unxt as u
Basic construction:
>>> q = u.StaticQuantity(np.array([1.0, 2.0]), "m") >>> q StaticQuantity(array([1., 2.]), unit='m')
Values are static and hashable:
>>> isinstance(hash(q), int) True
A concrete JAX array is materialised back to NumPy (a static value is just data); only traced values (under
jit/vmap/grad) are rejected:>>> import jax.numpy as jnp >>> u.StaticQuantity(jnp.array([1.0, 2.0]), "m") StaticQuantity(array([1., 2.], dtype=float32), unit='m')
The Wadler-Lindig representation hides the internal static wrapper:
>>> import wadler_lindig as wl >>> wl.pprint(q, short_arrays=False) StaticQuantity(array([1., 2.]), unit='m')
- value: StaticValue#
The static value of the AbstractQuantity.
- unit: UnitBase | FunctionUnitBase#
The unit associated with this value.
- property T: AbstractQuantity#
Transpose of the array.
Examples
>>> import unxt as u >>> q = u.Q([[0, 1], [1, 2]], "m") >>> q.T Quantity(Array([[0, 1], [1, 2]], dtype=int32), unit='m')
- argmax(*args: Any, **kwargs: Any)#
Return the indices of the maximum value.
Examples
>>> import unxt as u >>> q = u.Q([1, 2, 3], "m") >>> q.argmax() Array(2, dtype=int32)
- argmin(*args: Any, **kwargs: Any)#
Return the indices of the minimum value.
Examples
>>> import unxt as u >>> q = u.Q([1, 2, 3], "m") >>> q.argmin() Array(0, dtype=int32)
- astype(*args: Any, **kwargs: Any)#
Copy the array and cast to a specified dtype.
Examples
>>> import unxt as u >>> q = u.Q([1, 2, 3], "m") >>> q.dtype dtype('int32')
>>> q.astype(float) Quantity(Array([1., 2., 3.], dtype=float32), unit='m')
- Parameters:
- Return type:
- property at: _QuantityIndexUpdateHelper#
Helper property for index update functionality.
The
atproperty provides a functionally pure equivalent of in-place array modifications.In particular:
Alternate syntax
Equivalent In-place expression
x = x.at[idx].set(y)x[idx] = yx = x.at[idx].add(y)x[idx] += yx = x.at[idx].subtract(y)x[idx] -= yx = x.at[idx].multiply(y)x[idx] *= yx = x.at[idx].divide(y)x[idx] /= yx = x.at[idx].power(y)x[idx] **= yx = x.at[idx].min(y)x[idx] = minimum(x[idx], y)x = x.at[idx].max(y)x[idx] = maximum(x[idx], y)x = x.at[idx].apply(ufunc)ufunc.at(x, idx)x = x.at[idx].get()x = x[idx]None of the
x.atexpressions modify the originalx; instead they return a modified copy ofx. However, inside ajit()compiled function, expressions likex = x.at[idx].set(y)are guaranteed to be applied in-place.Unlike NumPy in-place operations such as
x[idx] += y, if multiple indices refer to the same location, all updates will be applied (NumPy would only apply the last update, rather than applying all updates.) The order in which conflicting updates are applied is implementation-defined and may be nondeterministic (e.g., due to concurrency on some hardware platforms).By default, JAX assumes that all indices are in-bounds. Alternative out-of-bound index semantics can be specified via the
modeparameter (see below).- Parameters:
mode โ
string specifying out-of-bound indexing mode. Options are:
"promise_in_bounds": (default) The user promises that indices are in bounds. No additional checking will be performed. In practice, this means that out-of-bounds indices inget()will be clipped, and out-of-bounds indices inset(),add(), etc. will be dropped."clip": clamp out of bounds indices into valid range."drop": ignore out-of-bound indices."fill": alias for"drop". For get(), the optionalfill_valueargument specifies the value that will be returned.
See
jax.lax.GatherScatterModefor more details.wrap_negative_indices โ If True (default) then negative indices indicate position from the end of the array, similar to Python and NumPy indexing. If False, then negative indices are considered out-of-bounds and behave according to the
modeparameter.fill_value โ Only applies to the
get()method: the fill value to return for out-of-bounds slices whenmodeis'fill'. Ignored otherwise. Defaults toNaNfor inexact types, the largest negative value for signed types, the largest positive value for unsigned types, andTruefor booleans.indices_are_sorted โ If True, the implementation will assume that the (normalized) indices passed to
at[]are sorted in ascending order, which can lead to more efficient execution on some backends. If True but the indices are not actually sorted, the output is undefined.unique_indices โ If True, the implementation will assume that the (normalized) indices passed to
at[]are unique, which can result in more efficient execution on some backends. If True but the indices are not actually unique, the output is undefined.
Examples
>>> x = jnp.arange(5.0) >>> x Array([0., 1., 2., 3., 4.], dtype=float32) >>> x.at[2].get() Array(2., dtype=float32) >>> x.at[2].add(10) Array([ 0., 1., 12., 3., 4.], dtype=float32)
By default, out-of-bound indices are ignored in updates, but this behavior can be controlled with the
modeparameter:>>> x.at[10].add(10) # dropped Array([0., 1., 2., 3., 4.], dtype=float32) >>> x.at[20].add(10, mode='clip') # clipped Array([ 0., 1., 2., 3., 14.], dtype=float32)
For
get(), out-of-bound indices are clipped by default:>>> x.at[20].get() # out-of-bounds indices clipped Array(4., dtype=float32) >>> x.at[20].get(mode='fill') # out-of-bounds indices filled with NaN Array(nan, dtype=float32) >>> x.at[20].get(mode='fill', fill_value=-1) # custom fill value Array(-1., dtype=float32)
Negative indices count from the end of the array, but this behavior can be disabled by setting
wrap_negative_indices = False:>>> x.at[-1].set(99) Array([ 0., 1., 2., 3., 99.], dtype=float32) >>> x.at[-1].set(99, wrap_negative_indices=False, mode='drop') # dropped! Array([0., 1., 2., 3., 4.], dtype=float32)
- block_until_ready()#
Block until the array is ready.
- Return type:
Examples
>>> import unxt as u >>> q = u.Q(1, "m") >>> q.block_until_ready() is q True
- decompose(bases: Sequence[UnitBase | FunctionUnitBase | str], /)#
Decompose the quantity into the given bases.
Examples
>>> from unxt import Quantity
>>> q = Quantity(1, "m") >>> q.decompose(["cm", "s"]) Quantity(Array(100., dtype=float32, ...), unit='cm')
- Parameters:
bases (
Sequence[UnitBase|FunctionUnitBase|str])- Return type:
- property device: Device#
Device where the array is located.
Examples
>>> import unxt as u >>> u.Q(1, "m").device CpuDevice(id=0)
- devices()#
Return the devices where the array is located.
Examples
>>> import unxt as u >>> q = u.Q(1, "m") >>> q.devices() {CpuDevice(id=0)}
- property dtype: dtype#
Data type of the array.
Examples
>>> import unxt as u >>> u.Q(1, "m").dtype dtype('int32')
- flatten()#
Return a flattened version of the array.
- Return type:
Examples
>>> import unxt as u >>> q = u.Q([[1, 2], [3, 4]], "m") >>> q.flatten() Quantity(Array([1, 2, 3, 4], dtype=int32), unit='m')
- classmethod from_(cls: type[AbstractQuantity], *args: Any, **kwargs: Any)#
- from_(cls: type[AbstractQuantity], value: ArrayLike | list[Shaped[Array, ''] | Shaped[ndarray, ''] | bool | number | bool | int | float | complex] | tuple[Shaped[Array, ''] | Shaped[ndarray, ''] | bool | number | bool | int | float | complex, ...], unit: Any, /, *, dtype: Any = None) AbstractQuantity
- Parameters:
- Return type:
Construct a unxt.AbstractQuantity from an array-like value and a unit.
- Parameters:
- Return type:
Examples
For this example weโll use the Quantity class. The same applies to any subclass of AbstractQuantity.
>>> import jax.numpy as jnp >>> import unxt as u
>>> x = jnp.array([1.0, 2, 3]) >>> u.Q.from_(x, "m") Quantity(Array([1., 2., 3.], dtype=float32), unit='m')
>>> u.Q.from_([1.0, 2, 3], "m") Quantity(Array([1., 2., 3.], dtype=float32), unit='m')
>>> u.Q.from_((1.0, 2, 3), "m") Quantity(Array([1., 2., 3.], dtype=float32), unit='m')
- from_(cls: type[AbstractQuantity], value: ArrayLike | list[Shaped[Array, ''] | Shaped[ndarray, ''] | bool | number | bool | int | float | complex] | tuple[Shaped[Array, ''] | Shaped[ndarray, ''] | bool | number | bool | int | float | complex, ...], /, *, unit: Any, dtype: Any = None) AbstractQuantity
- Parameters:
- Return type:
Make a unxt.AbstractQuantity from an array-like value and a unit kwarg.
Examples
For this example weโll use the unxt.Quantity class. The same applies to any subclass of unxt.AbstractQuantity.
>>> import unxt as u >>> u.Q.from_([1.0, 2, 3], unit="m") Quantity(Array([1., 2., 3.], dtype=float32), unit='m')
- from_(cls: type[AbstractQuantity], *, value: Any, unit: Any, dtype: Any = None) AbstractQuantity
- Parameters:
- Return type:
Construct a AbstractQuantity from value and unit kwargs.
Examples
For this example weโll use the Quantity class. The same applies to any subclass of AbstractQuantity.
>>> import unxt as u >>> u.Q.from_(value=[1.0, 2, 3], unit="m") Quantity(Array([1., 2., 3.], dtype=float32), unit='m')
- from_(cls: type[AbstractQuantity], mapping: Mapping[str, Any]) AbstractQuantity
- Parameters:
- Return type:
Construct a quantity from a Mapping.
Examples
For this example weโll use the Quantity class. The same applies to any subclass of AbstractQuantity.
>>> import jax.numpy as jnp >>> import unxt as u
>>> x = jnp.array([1.0, 2, 3]) >>> q = u.Q.from_({"value": x, "unit": "m"}) >>> q Quantity(Array([1., 2., 3.], dtype=float32), unit='m')
>>> u.Q.from_({"value": q, "unit": "km"}) Quantity(Array([0.001, 0.002, 0.003], dtype=float32), unit='km')
- from_(cls: type[AbstractQuantity], value: AbstractQuantity, unit: Any, /, *, dtype: Any = None) AbstractQuantity
- Parameters:
- Return type:
Construct a quantity from another quantity.
The value is converted to the new unit.
Examples
>>> import unxt as u
>>> q = u.Q(1, "m") >>> u.Q.from_(q, "cm") Quantity(Array(100., dtype=float32, ...), unit='cm')
- from_(cls: type[AbstractQuantity], value: AbstractQuantity, unit: NoneType, /, *, dtype: Any = None) AbstractQuantity
- Parameters:
- Return type:
Construct a quantity from another quantity.
The value is converted to the new unit.
Examples
>>> import unxt as u
>>> q = u.Q(1, "m") >>> u.Q.from_(q, None) Quantity(Array(1, dtype=int32...), unit='m')
- from_(cls: type[AbstractQuantity], value: AbstractQuantity, /, *, unit: Any | None = None, dtype: Any = None) AbstractQuantity
- Parameters:
- Return type:
Construct a quantity from another quantity.
The unit is unchanged.
- from_(cls: type[StaticQuantity], value: ArrayLike | list[Shaped[Array, ''] | Shaped[ndarray, ''] | bool | number | bool | int | float | complex] | tuple[Shaped[Array, ''] | Shaped[ndarray, ''] | bool | number | bool | int | float | complex, ...], unit: Any, /, *, dtype: Any = None) StaticQuantity
- Parameters:
- Return type:
Construct a StaticQuantity, keeping the value on NumPy dtypes.
The generic
AbstractQuantity.from_routes the value throughjnp.asarray, which applies JAXโs x64-disabled dtype rules and silently downcasts int64 / float64 to int32 / float32. A StaticQuantity stores its value verbatim, so hand the value straight to__init__and let theStaticValue.from_converter convert it โ that preserves the NumPy dtype. Delegating (rather than callingnp.asarrayhere) also keeps.from_and__init__under the same policy for JAX inputs, instead of materialising an array the constructor would reject. (The keyword-unitoverload delegates here, so it is covered too.)Examples
>>> import numpy as np >>> import unxt as u
>>> u.StaticQuantity.from_( ... np.array([1, 2, 3], dtype=np.int64), "m" ... ).value.array.dtype dtype('int64')
.from_applies the same JAX-input policy as__init__โ it delegates rather than converting first, so the two cannot drift:>>> import jax.numpy as jnp >>> u.StaticQuantity.from_(jnp.array([1.0, 2.0]), "m") StaticQuantity(array([1., 2.], dtype=float32), unit='m')
- from_(cls: type[AbstractQuantity], value: Quantity, /, **kwargs: Any) AbstractQuantity
- Parameters:
- Return type:
Construct a quantity from an astropy Quantity.
The value is converted to the new unit.
Examples
>>> import unxt as u >>> import astropy.units as apyu
>>> u.Q.from_(apyu.Quantity(1, "m")) Quantity(Array(1., dtype=float32), unit='m')
- from_(cls: type[AbstractQuantity], value: Quantity, u: Any, /, **kwargs: Any) AbstractQuantity
- Parameters:
- Return type:
Construct a quantity from an astropy Quantity, converting to a target unit.
The value is converted to the new unit.
Examples
>>> import unxt as u >>> import astropy.units as apyu
>>> u.Q.from_(apyu.Quantity(1, "m"), "cm") Quantity(Array(100., dtype=float32), unit='cm')
- Parameters:
cls (
type[AbstractQuantity])args (
Any)kwargs (
Any)
- Return type:
- is_equivalent(other: AbstractQuantity, /)#
Whether
selfandotherare physically equal (unit-aware).The method form of unxt.equivalent; unlike
==(which is unit-blind for StaticValue-backed quantities) this accounts for unit conversion.Examples
>>> import unxt as u >>> u.Q(1000.0, "m").is_equivalent(u.Q(1.0, "km")) Quantity(Array(True, dtype=bool...), unit='')
- Parameters:
other (
AbstractQuantity)- Return type:
- property mT: AbstractQuantity#
Matrix transpose of the array.
Examples
>>> import unxt as u >>> q = u.Q([[0, 1], [1, 2]], "m") >>> q.mT Quantity(Array([[0, 1], [1, 2]], dtype=int32), unit='m')
- max(*args: Any, **kwargs: Any)#
Return the maximum value.
Examples
>>> import unxt as u >>> q = u.Q([1, 2, 3], "m") >>> q.max() Quantity(Array(3, dtype=int32), unit='m')
- Parameters:
- Return type:
- mean(*args: Any, **kwargs: Any)#
Return the mean value.
Examples
>>> import unxt as u >>> q = u.Q([1, 2, 3], "m") >>> q.mean() Quantity(Array(2., dtype=float32), unit='m')
- Parameters:
- Return type:
- min(*args: Any, **kwargs: Any)#
Return the minimum value.
Examples
>>> import unxt as u >>> q = u.Q([1, 2, 3], "m") >>> q.min() Quantity(Array(1, dtype=int32), unit='m')
- Parameters:
- Return type:
- property ndim: int#
Number of dimensions.
Examples
>>> import unxt as u >>> q = u.Q([[1]], "m") >>> q.ndim 2
- ravel()#
Return a flattened version of the array.
- Return type:
Examples
>>> import unxt as u >>> q = u.Q([[1, 2], [3, 4]], "m") >>> q.ravel() Quantity(Array([1, 2, 3, 4], dtype=int32), unit='m')
- reshape(*args: Any, order: str = 'C')#
Return a reshaped version of the array.
Examples
>>> import unxt as u >>> q = u.Q([1, 2, 3, 4], "m") >>> q.reshape(2, 2) Quantity(Array([[1, 2], [3, 4]], dtype=int32), unit='m')
- Parameters:
- Return type:
- round(*args: Any, **kwargs: Any)#
Round the array to the given number of decimals.
Examples
>>> import unxt as u >>> q = u.Q([1.1, 2.2, 3.3], "m") >>> q.round(0) Quantity(Array([1., 2., 3.], dtype=float32), unit='m')
- Parameters:
- Return type:
- property sharding: Any#
Return the sharding configuration of the array.
Examples
>>> import unxt as u >>> q = u.Q([1, 2, 3], "m") >>> q.sharding SingleDeviceSharding(device=..., memory_kind=...)
- property size: int#
Total number of elements.
Examples
>>> import unxt as u >>> q = u.Q([1, 2, 3], "m") >>> q.size 3
- squeeze(*args: Any, **kwargs: Any)#
Return the array with all single-dimensional entries removed.
Examples
>>> import unxt as u >>> q = u.Q([[[1], [2], [3]]], "m") >>> q.squeeze() Quantity(Array([1, 2, 3], dtype=int32), unit='m')
- Parameters:
- Return type:
- to(u: Any, /)#
Convert the quantity to the given units.
See unxt.quantity.AbstractQuantity.uconvert.
Examples
>>> from unxt import Quantity
>>> q = Quantity(1, "m") >>> q.to("cm") Quantity(Array(100., dtype=float32, ...), unit='cm')
- Parameters:
u (
Any)- Return type:
- to_device(device: None | Device = None)#
Move the array to a new device.
Examples
>>> import unxt as u >>> q = u.Q(1, "m") >>> q.to_device(None) Quantity(Array(1, dtype=int32...), unit='m')
- Parameters:
- Return type:
- to_value(u: Any, /)#
Return the value in the given units.
See unxt.AbstractQuantity.ustrip.
Examples
>>> from unxt import Quantity
>>> q = Quantity(1, "m") >>> q.to_value("cm") Array(100., dtype=float32, weak_type=True)
- final class unxt.quantity.StaticValue(array: object, /)#
Bases:
objectImmutable static value wrapper for StaticQuantity.
This stores a read-only NumPy array and is used to keep the value static while avoiding Equinoxโs static-array warnings. Arithmetic operations degrade to the wrapped array unless both operands are StaticValue, in which case a StaticValue is returned.
Note that since the array is immutable, hashing is supported. The hash is computed from the arrayโs dtype, shape, and bytes.
Equality semantics
StaticValue equality returns a scalar bool, not an element-wise array. This is intentional: it mirrors Pythonโs structural-equality contract (like
tuple.__eq__) and is a prerequisite for using aQuantity(StaticValue, ...)as astatic_argnamesargument injax.jit(). JAX needs a scalarboolto decide whether a cached compilation can be reused.This is fundamentally different from a normal
Quantity(backed by a JAX array), whose==operator follows NumPy broadcasting rules and returns an element-wise boolean array.Examples
>>> import numpy as np >>> from unxt.quantity import StaticValue
Equality between two StaticValue objects returns a plain bool:
>>> StaticValue(np.array([1.0, 2.0])) == StaticValue(np.array([1.0, 2.0])) True >>> StaticValue(np.array([1.0, 2.0])) == StaticValue(np.array([9.0, 9.0])) False
Equality with a NumPy array returns an element-wise boolean array (same as NumPy):
>>> StaticValue(np.array([1.0, 2.0])) == np.array([1.0, 9.0]) array([ True, False])
- Parameters:
array (
object)
- classmethod from_(cls: type[StaticValue], *args: Any, **kwargs: Any)#
Create a StaticValue from given arguments.
- from_(cls: type[StaticValue], value: object, /) StaticValue
- Parameters:
- Return type:
Convert a value for StaticQuantity.
- from_(cls: type[StaticValue], value: StaticValue, /) StaticValue
- Parameters:
- Return type:
Convert a value for StaticQuantity.
- from_(cls: type[StaticValue], value: Array | jax._src.core.Tracer, /) StaticValue
- Parameters:
- Return type:
Materialise a concrete JAX array to NumPy, or reject a traced value.
A concrete (eager)
jax.Arrayis just data, so it can back a static value โ materialise it. This also lets ops on aStaticQuantitystay static: the primitive rules rebuild viareplace(x, value=<jax array>), and that concrete array round-trips back to NumPy here instead of raising.A tracer (under
jit/vmap/grad) is a placeholder for a value that does not exist yet, so it genuinely cannot be static and is rejected.- from_(cls: StaticValue, value: AbstractQuantity, /) StaticValue
- Parameters:
- Return type:
Disallow conversion of AbstractQuantity to a value.
- Parameters:
cls (
type[StaticValue])args (
Any)kwargs (
Any)
- Return type:
- class unxt.quantity.AbstractQuantity#
Bases:
AstropyQuantityCompatMixin,NumPyCompatMixin,IPythonReprMixin,ArrayValue,NumpyBinaryOpsMixin[Any,AbstractQuantity],NumpyComparisonMixin[Any,Bool[Array, '*shape']],NumpyUnaryMixin[AbstractQuantity],NumpyRoundMixin[AbstractQuantity],NumpyTruncMixin[AbstractQuantity],NumpyFloorMixin[AbstractQuantity],NumpyCeilMixin[AbstractQuantity],LaxLenMixin,LaxLengthHintMixinRepresents a quantity with a value and a unit.
- short_name#
Optional short name for the class used in wadler-lindig printing when
use_short_name=True. Defaults toNone.- Type:
str | None
Examples
>>> import unxt as u
From an integer:
>>> u.Q(1, "m") Quantity(Array(1, dtype=int32...), unit='m')
From a float:
>>> u.Q(1.0, "m") Quantity(Array(1., dtype=float32...), unit='m')
From a list:
>>> u.Q([1, 2, 3], "m") Quantity(Array([1, 2, 3], dtype=int32), unit='m')
From a tuple:
>>> u.Q((1, 2, 3), "m") Quantity(Array([1, 2, 3], dtype=int32), unit='m')
From a numpy.ndarray:
>>> import numpy as np >>> u.Q(np.array([1, 2, 3]), "m") Quantity(Array([1, 2, 3], dtype=int32), unit='m')
From a jax.Array:
>>> import jax.numpy as jnp >>> u.Q(jnp.array([1, 2, 3]), "m") Quantity(Array([1, 2, 3], dtype=int32), unit='m')
The unit can also be given as a astropy.units.Unit:
>>> import astropy.units as apyu >>> u.Q(1, apyu.m) Quantity(Array(1, dtype=int32...), unit='m')
- value: AbstractVar[Shaped[Array, '*shape'] | Shaped[StaticValue, '*shape']]#
The value of the AbstractQuantity.
- unit: AbstractVar[UnitBase | FunctionUnitBase]#
The unit associated with this value.
- classmethod from_(cls: type[AbstractQuantity], *args: Any, **kwargs: Any)#
- from_(cls: type[AbstractQuantity], value: ArrayLike | list[Shaped[Array, ''] | Shaped[ndarray, ''] | bool | number | bool | int | float | complex] | tuple[Shaped[Array, ''] | Shaped[ndarray, ''] | bool | number | bool | int | float | complex, ...], unit: Any, /, *, dtype: Any = None) AbstractQuantity
- Parameters:
- Return type:
Construct a unxt.AbstractQuantity from an array-like value and a unit.
- Parameters:
- Return type:
Examples
For this example weโll use the Quantity class. The same applies to any subclass of AbstractQuantity.
>>> import jax.numpy as jnp >>> import unxt as u
>>> x = jnp.array([1.0, 2, 3]) >>> u.Q.from_(x, "m") Quantity(Array([1., 2., 3.], dtype=float32), unit='m')
>>> u.Q.from_([1.0, 2, 3], "m") Quantity(Array([1., 2., 3.], dtype=float32), unit='m')
>>> u.Q.from_((1.0, 2, 3), "m") Quantity(Array([1., 2., 3.], dtype=float32), unit='m')
- from_(cls: type[AbstractQuantity], value: ArrayLike | list[Shaped[Array, ''] | Shaped[ndarray, ''] | bool | number | bool | int | float | complex] | tuple[Shaped[Array, ''] | Shaped[ndarray, ''] | bool | number | bool | int | float | complex, ...], /, *, unit: Any, dtype: Any = None) AbstractQuantity
- Parameters:
- Return type:
Make a unxt.AbstractQuantity from an array-like value and a unit kwarg.
Examples
For this example weโll use the unxt.Quantity class. The same applies to any subclass of unxt.AbstractQuantity.
>>> import unxt as u >>> u.Q.from_([1.0, 2, 3], unit="m") Quantity(Array([1., 2., 3.], dtype=float32), unit='m')
- from_(cls: type[AbstractQuantity], *, value: Any, unit: Any, dtype: Any = None) AbstractQuantity
- Parameters:
- Return type:
Construct a AbstractQuantity from value and unit kwargs.
Examples
For this example weโll use the Quantity class. The same applies to any subclass of AbstractQuantity.
>>> import unxt as u >>> u.Q.from_(value=[1.0, 2, 3], unit="m") Quantity(Array([1., 2., 3.], dtype=float32), unit='m')
- from_(cls: type[AbstractQuantity], mapping: Mapping[str, Any]) AbstractQuantity
- Parameters:
- Return type:
Construct a quantity from a Mapping.
Examples
For this example weโll use the Quantity class. The same applies to any subclass of AbstractQuantity.
>>> import jax.numpy as jnp >>> import unxt as u
>>> x = jnp.array([1.0, 2, 3]) >>> q = u.Q.from_({"value": x, "unit": "m"}) >>> q Quantity(Array([1., 2., 3.], dtype=float32), unit='m')
>>> u.Q.from_({"value": q, "unit": "km"}) Quantity(Array([0.001, 0.002, 0.003], dtype=float32), unit='km')
- from_(cls: type[AbstractQuantity], value: AbstractQuantity, unit: Any, /, *, dtype: Any = None) AbstractQuantity
- Parameters:
- Return type:
Construct a quantity from another quantity.
The value is converted to the new unit.
Examples
>>> import unxt as u
>>> q = u.Q(1, "m") >>> u.Q.from_(q, "cm") Quantity(Array(100., dtype=float32, ...), unit='cm')
- from_(cls: type[AbstractQuantity], value: AbstractQuantity, unit: NoneType, /, *, dtype: Any = None) AbstractQuantity
- Parameters:
- Return type:
Construct a quantity from another quantity.
The value is converted to the new unit.
Examples
>>> import unxt as u
>>> q = u.Q(1, "m") >>> u.Q.from_(q, None) Quantity(Array(1, dtype=int32...), unit='m')
- from_(cls: type[AbstractQuantity], value: AbstractQuantity, /, *, unit: Any | None = None, dtype: Any = None) AbstractQuantity
- Parameters:
- Return type:
Construct a quantity from another quantity.
The unit is unchanged.
- from_(cls: type[StaticQuantity], value: ArrayLike | list[Shaped[Array, ''] | Shaped[ndarray, ''] | bool | number | bool | int | float | complex] | tuple[Shaped[Array, ''] | Shaped[ndarray, ''] | bool | number | bool | int | float | complex, ...], unit: Any, /, *, dtype: Any = None) StaticQuantity
- Parameters:
- Return type:
Construct a StaticQuantity, keeping the value on NumPy dtypes.
The generic
AbstractQuantity.from_routes the value throughjnp.asarray, which applies JAXโs x64-disabled dtype rules and silently downcasts int64 / float64 to int32 / float32. A StaticQuantity stores its value verbatim, so hand the value straight to__init__and let theStaticValue.from_converter convert it โ that preserves the NumPy dtype. Delegating (rather than callingnp.asarrayhere) also keeps.from_and__init__under the same policy for JAX inputs, instead of materialising an array the constructor would reject. (The keyword-unitoverload delegates here, so it is covered too.)Examples
>>> import numpy as np >>> import unxt as u
>>> u.StaticQuantity.from_( ... np.array([1, 2, 3], dtype=np.int64), "m" ... ).value.array.dtype dtype('int64')
.from_applies the same JAX-input policy as__init__โ it delegates rather than converting first, so the two cannot drift:>>> import jax.numpy as jnp >>> u.StaticQuantity.from_(jnp.array([1.0, 2.0]), "m") StaticQuantity(array([1., 2.], dtype=float32), unit='m')
- from_(cls: type[AbstractQuantity], value: Quantity, /, **kwargs: Any) AbstractQuantity
- Parameters:
- Return type:
Construct a quantity from an astropy Quantity.
The value is converted to the new unit.
Examples
>>> import unxt as u >>> import astropy.units as apyu
>>> u.Q.from_(apyu.Quantity(1, "m")) Quantity(Array(1., dtype=float32), unit='m')
- from_(cls: type[AbstractQuantity], value: Quantity, u: Any, /, **kwargs: Any) AbstractQuantity
- Parameters:
- Return type:
Construct a quantity from an astropy Quantity, converting to a target unit.
The value is converted to the new unit.
Examples
>>> import unxt as u >>> import astropy.units as apyu
>>> u.Q.from_(apyu.Quantity(1, "m"), "cm") Quantity(Array(100., dtype=float32), unit='cm')
- Parameters:
cls (
type[AbstractQuantity])args (
Any)kwargs (
Any)
- Return type:
- uconvert(u: Any, /)#
Convert the quantity to the given units.
See also
Noneconvert a quantity to a new unit.
Examples
>>> import unxt as u
>>> q = u.Q(1, "m") >>> q.uconvert("cm") Quantity(Array(100., dtype=float32, ...), unit='cm')
- Parameters:
u (
Any)- Return type:
- ustrip(u: Any, /)#
Return the value in the given units.
See also
Nonestrip the units from a quantity.
Examples
>>> import unxt as u
>>> q = u.Q(1, "m") >>> q.ustrip("cm") Array(100., dtype=float32, weak_type=True)
- property dtype: dtype#
Data type of the array.
Examples
>>> import unxt as u >>> u.Q(1, "m").dtype dtype('int32')
- property device: Device#
Device where the array is located.
Examples
>>> import unxt as u >>> u.Q(1, "m").device CpuDevice(id=0)
- property mT: AbstractQuantity#
Matrix transpose of the array.
Examples
>>> import unxt as u >>> q = u.Q([[0, 1], [1, 2]], "m") >>> q.mT Quantity(Array([[0, 1], [1, 2]], dtype=int32), unit='m')
- property ndim: int#
Number of dimensions.
Examples
>>> import unxt as u >>> q = u.Q([[1]], "m") >>> q.ndim 2
- property size: int#
Total number of elements.
Examples
>>> import unxt as u >>> q = u.Q([1, 2, 3], "m") >>> q.size 3
- property T: AbstractQuantity#
Transpose of the array.
Examples
>>> import unxt as u >>> q = u.Q([[0, 1], [1, 2]], "m") >>> q.T Quantity(Array([[0, 1], [1, 2]], dtype=int32), unit='m')
- to_device(device: None | Device = None)#
Move the array to a new device.
Examples
>>> import unxt as u >>> q = u.Q(1, "m") >>> q.to_device(None) Quantity(Array(1, dtype=int32...), unit='m')
- Parameters:
- Return type:
- argmax(*args: Any, **kwargs: Any)#
Return the indices of the maximum value.
Examples
>>> import unxt as u >>> q = u.Q([1, 2, 3], "m") >>> q.argmax() Array(2, dtype=int32)
- argmin(*args: Any, **kwargs: Any)#
Return the indices of the minimum value.
Examples
>>> import unxt as u >>> q = u.Q([1, 2, 3], "m") >>> q.argmin() Array(0, dtype=int32)
- astype(*args: Any, **kwargs: Any)#
Copy the array and cast to a specified dtype.
Examples
>>> import unxt as u >>> q = u.Q([1, 2, 3], "m") >>> q.dtype dtype('int32')
>>> q.astype(float) Quantity(Array([1., 2., 3.], dtype=float32), unit='m')
- Parameters:
- Return type:
- property at: _QuantityIndexUpdateHelper#
Helper property for index update functionality.
The
atproperty provides a functionally pure equivalent of in-place array modifications.In particular:
Alternate syntax
Equivalent In-place expression
x = x.at[idx].set(y)x[idx] = yx = x.at[idx].add(y)x[idx] += yx = x.at[idx].subtract(y)x[idx] -= yx = x.at[idx].multiply(y)x[idx] *= yx = x.at[idx].divide(y)x[idx] /= yx = x.at[idx].power(y)x[idx] **= yx = x.at[idx].min(y)x[idx] = minimum(x[idx], y)x = x.at[idx].max(y)x[idx] = maximum(x[idx], y)x = x.at[idx].apply(ufunc)ufunc.at(x, idx)x = x.at[idx].get()x = x[idx]None of the
x.atexpressions modify the originalx; instead they return a modified copy ofx. However, inside ajit()compiled function, expressions likex = x.at[idx].set(y)are guaranteed to be applied in-place.Unlike NumPy in-place operations such as
x[idx] += y, if multiple indices refer to the same location, all updates will be applied (NumPy would only apply the last update, rather than applying all updates.) The order in which conflicting updates are applied is implementation-defined and may be nondeterministic (e.g., due to concurrency on some hardware platforms).By default, JAX assumes that all indices are in-bounds. Alternative out-of-bound index semantics can be specified via the
modeparameter (see below).- Parameters:
mode โ
string specifying out-of-bound indexing mode. Options are:
"promise_in_bounds": (default) The user promises that indices are in bounds. No additional checking will be performed. In practice, this means that out-of-bounds indices inget()will be clipped, and out-of-bounds indices inset(),add(), etc. will be dropped."clip": clamp out of bounds indices into valid range."drop": ignore out-of-bound indices."fill": alias for"drop". For get(), the optionalfill_valueargument specifies the value that will be returned.
See
jax.lax.GatherScatterModefor more details.wrap_negative_indices โ If True (default) then negative indices indicate position from the end of the array, similar to Python and NumPy indexing. If False, then negative indices are considered out-of-bounds and behave according to the
modeparameter.fill_value โ Only applies to the
get()method: the fill value to return for out-of-bounds slices whenmodeis'fill'. Ignored otherwise. Defaults toNaNfor inexact types, the largest negative value for signed types, the largest positive value for unsigned types, andTruefor booleans.indices_are_sorted โ If True, the implementation will assume that the (normalized) indices passed to
at[]are sorted in ascending order, which can lead to more efficient execution on some backends. If True but the indices are not actually sorted, the output is undefined.unique_indices โ If True, the implementation will assume that the (normalized) indices passed to
at[]are unique, which can result in more efficient execution on some backends. If True but the indices are not actually unique, the output is undefined.
Examples
>>> x = jnp.arange(5.0) >>> x Array([0., 1., 2., 3., 4.], dtype=float32) >>> x.at[2].get() Array(2., dtype=float32) >>> x.at[2].add(10) Array([ 0., 1., 12., 3., 4.], dtype=float32)
By default, out-of-bound indices are ignored in updates, but this behavior can be controlled with the
modeparameter:>>> x.at[10].add(10) # dropped Array([0., 1., 2., 3., 4.], dtype=float32) >>> x.at[20].add(10, mode='clip') # clipped Array([ 0., 1., 2., 3., 14.], dtype=float32)
For
get(), out-of-bound indices are clipped by default:>>> x.at[20].get() # out-of-bounds indices clipped Array(4., dtype=float32) >>> x.at[20].get(mode='fill') # out-of-bounds indices filled with NaN Array(nan, dtype=float32) >>> x.at[20].get(mode='fill', fill_value=-1) # custom fill value Array(-1., dtype=float32)
Negative indices count from the end of the array, but this behavior can be disabled by setting
wrap_negative_indices = False:>>> x.at[-1].set(99) Array([ 0., 1., 2., 3., 99.], dtype=float32) >>> x.at[-1].set(99, wrap_negative_indices=False, mode='drop') # dropped! Array([0., 1., 2., 3., 4.], dtype=float32)
- block_until_ready()#
Block until the array is ready.
- Return type:
Examples
>>> import unxt as u >>> q = u.Q(1, "m") >>> q.block_until_ready() is q True
- devices()#
Return the devices where the array is located.
Examples
>>> import unxt as u >>> q = u.Q(1, "m") >>> q.devices() {CpuDevice(id=0)}
- flatten()#
Return a flattened version of the array.
- Return type:
Examples
>>> import unxt as u >>> q = u.Q([[1, 2], [3, 4]], "m") >>> q.flatten() Quantity(Array([1, 2, 3, 4], dtype=int32), unit='m')
- max(*args: Any, **kwargs: Any)#
Return the maximum value.
Examples
>>> import unxt as u >>> q = u.Q([1, 2, 3], "m") >>> q.max() Quantity(Array(3, dtype=int32), unit='m')
- Parameters:
- Return type:
- mean(*args: Any, **kwargs: Any)#
Return the mean value.
Examples
>>> import unxt as u >>> q = u.Q([1, 2, 3], "m") >>> q.mean() Quantity(Array(2., dtype=float32), unit='m')
- Parameters:
- Return type:
- min(*args: Any, **kwargs: Any)#
Return the minimum value.
Examples
>>> import unxt as u >>> q = u.Q([1, 2, 3], "m") >>> q.min() Quantity(Array(1, dtype=int32), unit='m')
- Parameters:
- Return type:
- ravel()#
Return a flattened version of the array.
- Return type:
Examples
>>> import unxt as u >>> q = u.Q([[1, 2], [3, 4]], "m") >>> q.ravel() Quantity(Array([1, 2, 3, 4], dtype=int32), unit='m')
- reshape(*args: Any, order: str = 'C')#
Return a reshaped version of the array.
Examples
>>> import unxt as u >>> q = u.Q([1, 2, 3, 4], "m") >>> q.reshape(2, 2) Quantity(Array([[1, 2], [3, 4]], dtype=int32), unit='m')
- Parameters:
- Return type:
- round(*args: Any, **kwargs: Any)#
Round the array to the given number of decimals.
Examples
>>> import unxt as u >>> q = u.Q([1.1, 2.2, 3.3], "m") >>> q.round(0) Quantity(Array([1., 2., 3.], dtype=float32), unit='m')
- Parameters:
- Return type:
- property sharding: Any#
Return the sharding configuration of the array.
Examples
>>> import unxt as u >>> q = u.Q([1, 2, 3], "m") >>> q.sharding SingleDeviceSharding(device=..., memory_kind=...)
- squeeze(*args: Any, **kwargs: Any)#
Return the array with all single-dimensional entries removed.
Examples
>>> import unxt as u >>> q = u.Q([[[1], [2], [3]]], "m") >>> q.squeeze() Quantity(Array([1, 2, 3], dtype=int32), unit='m')
- Parameters:
- Return type:
- is_equivalent(other: AbstractQuantity, /)#
Whether
selfandotherare physically equal (unit-aware).The method form of unxt.equivalent; unlike
==(which is unit-blind for StaticValue-backed quantities) this accounts for unit conversion.Examples
>>> import unxt as u >>> u.Q(1000.0, "m").is_equivalent(u.Q(1.0, "km")) Quantity(Array(True, dtype=bool...), unit='')
- Parameters:
other (
AbstractQuantity)- Return type:
- decompose(bases: Sequence[UnitBase | FunctionUnitBase | str], /)#
Decompose the quantity into the given bases.
Examples
>>> from unxt import Quantity
>>> q = Quantity(1, "m") >>> q.decompose(["cm", "s"]) Quantity(Array(100., dtype=float32, ...), unit='cm')
- Parameters:
bases (
Sequence[UnitBase|FunctionUnitBase|str])- Return type:
- to(u: Any, /)#
Convert the quantity to the given units.
See unxt.quantity.AbstractQuantity.uconvert.
Examples
>>> from unxt import Quantity
>>> q = Quantity(1, "m") >>> q.to("cm") Quantity(Array(100., dtype=float32, ...), unit='cm')
- Parameters:
u (
Any)- Return type:
- class unxt.quantity.AbstractAngle#
Bases:
AbstractQuantityAngular quantity.
See also
Nonea concrete implementation of this class.
Examples
For this example, we will use the concrete implementation of unxt.AbstractAngle, unxt.Angle.
>>> from unxt import Angle
>>> Angle(90, "deg") Angle(Array(90, dtype=int32...), unit='deg')
Angles have to have dimensions of angle.
>>> try: ... Angle(90, "m") ... except ValueError as e: ... print(e) Angle must have units with angular dimensions.
- value: AbstractVar[Shaped[Array, '*shape'] | Shaped[StaticValue, '*shape']]#
The value of the unxt.AbstractQuantity.
- unit: AbstractVar[UnitBase | FunctionUnitBase]#
The unit associated with this value.
- property T: AbstractQuantity#
Transpose of the array.
Examples
>>> import unxt as u >>> q = u.Q([[0, 1], [1, 2]], "m") >>> q.T Quantity(Array([[0, 1], [1, 2]], dtype=int32), unit='m')
- argmax(*args: Any, **kwargs: Any)#
Return the indices of the maximum value.
Examples
>>> import unxt as u >>> q = u.Q([1, 2, 3], "m") >>> q.argmax() Array(2, dtype=int32)
- argmin(*args: Any, **kwargs: Any)#
Return the indices of the minimum value.
Examples
>>> import unxt as u >>> q = u.Q([1, 2, 3], "m") >>> q.argmin() Array(0, dtype=int32)
- astype(*args: Any, **kwargs: Any)#
Copy the array and cast to a specified dtype.
Examples
>>> import unxt as u >>> q = u.Q([1, 2, 3], "m") >>> q.dtype dtype('int32')
>>> q.astype(float) Quantity(Array([1., 2., 3.], dtype=float32), unit='m')
- Parameters:
- Return type:
- property at: _QuantityIndexUpdateHelper#
Helper property for index update functionality.
The
atproperty provides a functionally pure equivalent of in-place array modifications.In particular:
Alternate syntax
Equivalent In-place expression
x = x.at[idx].set(y)x[idx] = yx = x.at[idx].add(y)x[idx] += yx = x.at[idx].subtract(y)x[idx] -= yx = x.at[idx].multiply(y)x[idx] *= yx = x.at[idx].divide(y)x[idx] /= yx = x.at[idx].power(y)x[idx] **= yx = x.at[idx].min(y)x[idx] = minimum(x[idx], y)x = x.at[idx].max(y)x[idx] = maximum(x[idx], y)x = x.at[idx].apply(ufunc)ufunc.at(x, idx)x = x.at[idx].get()x = x[idx]None of the
x.atexpressions modify the originalx; instead they return a modified copy ofx. However, inside ajit()compiled function, expressions likex = x.at[idx].set(y)are guaranteed to be applied in-place.Unlike NumPy in-place operations such as
x[idx] += y, if multiple indices refer to the same location, all updates will be applied (NumPy would only apply the last update, rather than applying all updates.) The order in which conflicting updates are applied is implementation-defined and may be nondeterministic (e.g., due to concurrency on some hardware platforms).By default, JAX assumes that all indices are in-bounds. Alternative out-of-bound index semantics can be specified via the
modeparameter (see below).- Parameters:
mode โ
string specifying out-of-bound indexing mode. Options are:
"promise_in_bounds": (default) The user promises that indices are in bounds. No additional checking will be performed. In practice, this means that out-of-bounds indices inget()will be clipped, and out-of-bounds indices inset(),add(), etc. will be dropped."clip": clamp out of bounds indices into valid range."drop": ignore out-of-bound indices."fill": alias for"drop". For get(), the optionalfill_valueargument specifies the value that will be returned.
See
jax.lax.GatherScatterModefor more details.wrap_negative_indices โ If True (default) then negative indices indicate position from the end of the array, similar to Python and NumPy indexing. If False, then negative indices are considered out-of-bounds and behave according to the
modeparameter.fill_value โ Only applies to the
get()method: the fill value to return for out-of-bounds slices whenmodeis'fill'. Ignored otherwise. Defaults toNaNfor inexact types, the largest negative value for signed types, the largest positive value for unsigned types, andTruefor booleans.indices_are_sorted โ If True, the implementation will assume that the (normalized) indices passed to
at[]are sorted in ascending order, which can lead to more efficient execution on some backends. If True but the indices are not actually sorted, the output is undefined.unique_indices โ If True, the implementation will assume that the (normalized) indices passed to
at[]are unique, which can result in more efficient execution on some backends. If True but the indices are not actually unique, the output is undefined.
Examples
>>> x = jnp.arange(5.0) >>> x Array([0., 1., 2., 3., 4.], dtype=float32) >>> x.at[2].get() Array(2., dtype=float32) >>> x.at[2].add(10) Array([ 0., 1., 12., 3., 4.], dtype=float32)
By default, out-of-bound indices are ignored in updates, but this behavior can be controlled with the
modeparameter:>>> x.at[10].add(10) # dropped Array([0., 1., 2., 3., 4.], dtype=float32) >>> x.at[20].add(10, mode='clip') # clipped Array([ 0., 1., 2., 3., 14.], dtype=float32)
For
get(), out-of-bound indices are clipped by default:>>> x.at[20].get() # out-of-bounds indices clipped Array(4., dtype=float32) >>> x.at[20].get(mode='fill') # out-of-bounds indices filled with NaN Array(nan, dtype=float32) >>> x.at[20].get(mode='fill', fill_value=-1) # custom fill value Array(-1., dtype=float32)
Negative indices count from the end of the array, but this behavior can be disabled by setting
wrap_negative_indices = False:>>> x.at[-1].set(99) Array([ 0., 1., 2., 3., 99.], dtype=float32) >>> x.at[-1].set(99, wrap_negative_indices=False, mode='drop') # dropped! Array([0., 1., 2., 3., 4.], dtype=float32)
- block_until_ready()#
Block until the array is ready.
- Return type:
Examples
>>> import unxt as u >>> q = u.Q(1, "m") >>> q.block_until_ready() is q True
- decompose(bases: Sequence[UnitBase | FunctionUnitBase | str], /)#
Decompose the quantity into the given bases.
Examples
>>> from unxt import Quantity
>>> q = Quantity(1, "m") >>> q.decompose(["cm", "s"]) Quantity(Array(100., dtype=float32, ...), unit='cm')
- Parameters:
bases (
Sequence[UnitBase|FunctionUnitBase|str])- Return type:
- property device: Device#
Device where the array is located.
Examples
>>> import unxt as u >>> u.Q(1, "m").device CpuDevice(id=0)
- devices()#
Return the devices where the array is located.
Examples
>>> import unxt as u >>> q = u.Q(1, "m") >>> q.devices() {CpuDevice(id=0)}
- property dtype: dtype#
Data type of the array.
Examples
>>> import unxt as u >>> u.Q(1, "m").dtype dtype('int32')
- flatten()#
Return a flattened version of the array.
- Return type:
Examples
>>> import unxt as u >>> q = u.Q([[1, 2], [3, 4]], "m") >>> q.flatten() Quantity(Array([1, 2, 3, 4], dtype=int32), unit='m')
- classmethod from_(cls: type[AbstractQuantity], *args: Any, **kwargs: Any)#
- from_(cls: type[AbstractQuantity], value: ArrayLike | list[Shaped[Array, ''] | Shaped[ndarray, ''] | bool | number | bool | int | float | complex] | tuple[Shaped[Array, ''] | Shaped[ndarray, ''] | bool | number | bool | int | float | complex, ...], unit: Any, /, *, dtype: Any = None) AbstractQuantity
- Parameters:
- Return type:
Construct a unxt.AbstractQuantity from an array-like value and a unit.
- Parameters:
- Return type:
Examples
For this example weโll use the Quantity class. The same applies to any subclass of AbstractQuantity.
>>> import jax.numpy as jnp >>> import unxt as u
>>> x = jnp.array([1.0, 2, 3]) >>> u.Q.from_(x, "m") Quantity(Array([1., 2., 3.], dtype=float32), unit='m')
>>> u.Q.from_([1.0, 2, 3], "m") Quantity(Array([1., 2., 3.], dtype=float32), unit='m')
>>> u.Q.from_((1.0, 2, 3), "m") Quantity(Array([1., 2., 3.], dtype=float32), unit='m')
- from_(cls: type[AbstractQuantity], value: ArrayLike | list[Shaped[Array, ''] | Shaped[ndarray, ''] | bool | number | bool | int | float | complex] | tuple[Shaped[Array, ''] | Shaped[ndarray, ''] | bool | number | bool | int | float | complex, ...], /, *, unit: Any, dtype: Any = None) AbstractQuantity
- Parameters:
- Return type:
Make a unxt.AbstractQuantity from an array-like value and a unit kwarg.
Examples
For this example weโll use the unxt.Quantity class. The same applies to any subclass of unxt.AbstractQuantity.
>>> import unxt as u >>> u.Q.from_([1.0, 2, 3], unit="m") Quantity(Array([1., 2., 3.], dtype=float32), unit='m')
- from_(cls: type[AbstractQuantity], *, value: Any, unit: Any, dtype: Any = None) AbstractQuantity
- Parameters:
- Return type:
Construct a AbstractQuantity from value and unit kwargs.
Examples
For this example weโll use the Quantity class. The same applies to any subclass of AbstractQuantity.
>>> import unxt as u >>> u.Q.from_(value=[1.0, 2, 3], unit="m") Quantity(Array([1., 2., 3.], dtype=float32), unit='m')
- from_(cls: type[AbstractQuantity], mapping: Mapping[str, Any]) AbstractQuantity
- Parameters:
- Return type:
Construct a quantity from a Mapping.
Examples
For this example weโll use the Quantity class. The same applies to any subclass of AbstractQuantity.
>>> import jax.numpy as jnp >>> import unxt as u
>>> x = jnp.array([1.0, 2, 3]) >>> q = u.Q.from_({"value": x, "unit": "m"}) >>> q Quantity(Array([1., 2., 3.], dtype=float32), unit='m')
>>> u.Q.from_({"value": q, "unit": "km"}) Quantity(Array([0.001, 0.002, 0.003], dtype=float32), unit='km')
- from_(cls: type[AbstractQuantity], value: AbstractQuantity, unit: Any, /, *, dtype: Any = None) AbstractQuantity
- Parameters:
- Return type:
Construct a quantity from another quantity.
The value is converted to the new unit.
Examples
>>> import unxt as u
>>> q = u.Q(1, "m") >>> u.Q.from_(q, "cm") Quantity(Array(100., dtype=float32, ...), unit='cm')
- from_(cls: type[AbstractQuantity], value: AbstractQuantity, unit: NoneType, /, *, dtype: Any = None) AbstractQuantity
- Parameters:
- Return type:
Construct a quantity from another quantity.
The value is converted to the new unit.
Examples
>>> import unxt as u
>>> q = u.Q(1, "m") >>> u.Q.from_(q, None) Quantity(Array(1, dtype=int32...), unit='m')
- from_(cls: type[AbstractQuantity], value: AbstractQuantity, /, *, unit: Any | None = None, dtype: Any = None) AbstractQuantity
- Parameters:
- Return type:
Construct a quantity from another quantity.
The unit is unchanged.
- from_(cls: type[StaticQuantity], value: ArrayLike | list[Shaped[Array, ''] | Shaped[ndarray, ''] | bool | number | bool | int | float | complex] | tuple[Shaped[Array, ''] | Shaped[ndarray, ''] | bool | number | bool | int | float | complex, ...], unit: Any, /, *, dtype: Any = None) StaticQuantity
- Parameters:
- Return type:
Construct a StaticQuantity, keeping the value on NumPy dtypes.
The generic
AbstractQuantity.from_routes the value throughjnp.asarray, which applies JAXโs x64-disabled dtype rules and silently downcasts int64 / float64 to int32 / float32. A StaticQuantity stores its value verbatim, so hand the value straight to__init__and let theStaticValue.from_converter convert it โ that preserves the NumPy dtype. Delegating (rather than callingnp.asarrayhere) also keeps.from_and__init__under the same policy for JAX inputs, instead of materialising an array the constructor would reject. (The keyword-unitoverload delegates here, so it is covered too.)Examples
>>> import numpy as np >>> import unxt as u
>>> u.StaticQuantity.from_( ... np.array([1, 2, 3], dtype=np.int64), "m" ... ).value.array.dtype dtype('int64')
.from_applies the same JAX-input policy as__init__โ it delegates rather than converting first, so the two cannot drift:>>> import jax.numpy as jnp >>> u.StaticQuantity.from_(jnp.array([1.0, 2.0]), "m") StaticQuantity(array([1., 2.], dtype=float32), unit='m')
- from_(cls: type[AbstractQuantity], value: Quantity, /, **kwargs: Any) AbstractQuantity
- Parameters:
- Return type:
Construct a quantity from an astropy Quantity.
The value is converted to the new unit.
Examples
>>> import unxt as u >>> import astropy.units as apyu
>>> u.Q.from_(apyu.Quantity(1, "m")) Quantity(Array(1., dtype=float32), unit='m')
- from_(cls: type[AbstractQuantity], value: Quantity, u: Any, /, **kwargs: Any) AbstractQuantity
- Parameters:
- Return type:
Construct a quantity from an astropy Quantity, converting to a target unit.
The value is converted to the new unit.
Examples
>>> import unxt as u >>> import astropy.units as apyu
>>> u.Q.from_(apyu.Quantity(1, "m"), "cm") Quantity(Array(100., dtype=float32), unit='cm')
- Parameters:
cls (
type[AbstractQuantity])args (
Any)kwargs (
Any)
- Return type:
- is_equivalent(other: AbstractQuantity, /)#
Whether
selfandotherare physically equal (unit-aware).The method form of unxt.equivalent; unlike
==(which is unit-blind for StaticValue-backed quantities) this accounts for unit conversion.Examples
>>> import unxt as u >>> u.Q(1000.0, "m").is_equivalent(u.Q(1.0, "km")) Quantity(Array(True, dtype=bool...), unit='')
- Parameters:
other (
AbstractQuantity)- Return type:
- property mT: AbstractQuantity#
Matrix transpose of the array.
Examples
>>> import unxt as u >>> q = u.Q([[0, 1], [1, 2]], "m") >>> q.mT Quantity(Array([[0, 1], [1, 2]], dtype=int32), unit='m')
- max(*args: Any, **kwargs: Any)#
Return the maximum value.
Examples
>>> import unxt as u >>> q = u.Q([1, 2, 3], "m") >>> q.max() Quantity(Array(3, dtype=int32), unit='m')
- Parameters:
- Return type:
- mean(*args: Any, **kwargs: Any)#
Return the mean value.
Examples
>>> import unxt as u >>> q = u.Q([1, 2, 3], "m") >>> q.mean() Quantity(Array(2., dtype=float32), unit='m')
- Parameters:
- Return type:
- min(*args: Any, **kwargs: Any)#
Return the minimum value.
Examples
>>> import unxt as u >>> q = u.Q([1, 2, 3], "m") >>> q.min() Quantity(Array(1, dtype=int32), unit='m')
- Parameters:
- Return type:
- property ndim: int#
Number of dimensions.
Examples
>>> import unxt as u >>> q = u.Q([[1]], "m") >>> q.ndim 2
- ravel()#
Return a flattened version of the array.
- Return type:
Examples
>>> import unxt as u >>> q = u.Q([[1, 2], [3, 4]], "m") >>> q.ravel() Quantity(Array([1, 2, 3, 4], dtype=int32), unit='m')
- reshape(*args: Any, order: str = 'C')#
Return a reshaped version of the array.
Examples
>>> import unxt as u >>> q = u.Q([1, 2, 3, 4], "m") >>> q.reshape(2, 2) Quantity(Array([[1, 2], [3, 4]], dtype=int32), unit='m')
- Parameters:
- Return type:
- round(*args: Any, **kwargs: Any)#
Round the array to the given number of decimals.
Examples
>>> import unxt as u >>> q = u.Q([1.1, 2.2, 3.3], "m") >>> q.round(0) Quantity(Array([1., 2., 3.], dtype=float32), unit='m')
- Parameters:
- Return type:
- property sharding: Any#
Return the sharding configuration of the array.
Examples
>>> import unxt as u >>> q = u.Q([1, 2, 3], "m") >>> q.sharding SingleDeviceSharding(device=..., memory_kind=...)
- property size: int#
Total number of elements.
Examples
>>> import unxt as u >>> q = u.Q([1, 2, 3], "m") >>> q.size 3
- squeeze(*args: Any, **kwargs: Any)#
Return the array with all single-dimensional entries removed.
Examples
>>> import unxt as u >>> q = u.Q([[[1], [2], [3]]], "m") >>> q.squeeze() Quantity(Array([1, 2, 3], dtype=int32), unit='m')
- Parameters:
- Return type:
- to(u: Any, /)#
Convert the quantity to the given units.
See unxt.quantity.AbstractQuantity.uconvert.
Examples
>>> from unxt import Quantity
>>> q = Quantity(1, "m") >>> q.to("cm") Quantity(Array(100., dtype=float32, ...), unit='cm')
- Parameters:
u (
Any)- Return type:
- to_device(device: None | Device = None)#
Move the array to a new device.
Examples
>>> import unxt as u >>> q = u.Q(1, "m") >>> q.to_device(None) Quantity(Array(1, dtype=int32...), unit='m')
- Parameters:
- Return type:
- to_value(u: Any, /)#
Return the value in the given units.
See unxt.AbstractQuantity.ustrip.
Examples
>>> from unxt import Quantity
>>> q = Quantity(1, "m") >>> q.to_value("cm") Array(100., dtype=float32, weak_type=True)
- uconvert(u: Any, /)#
Convert the quantity to the given units.
See also
Noneconvert a quantity to a new unit.
Examples
>>> import unxt as u
>>> q = u.Q(1, "m") >>> q.uconvert("cm") Quantity(Array(100., dtype=float32, ...), unit='cm')
- Parameters:
u (
Any)- Return type:
- ustrip(u: Any, /)#
Return the value in the given units.
See also
Nonestrip the units from a quantity.
Examples
>>> import unxt as u
>>> q = u.Q(1, "m") >>> q.ustrip("cm") Array(100., dtype=float32, weak_type=True)
- wrap_to(min: AbstractQuantity, max: AbstractQuantity)#
Wrap the angle to the range [min, max).
- Parameters:
min (
AbstractQuantity) โ The minimum, maximum value of the range.max (
AbstractQuantity) โ The minimum, maximum value of the range.
- Return type:
See also
Nonefunctional version of this method.
- Return type:
- Parameters:
min (AbstractQuantity)
max (AbstractQuantity)
Examples
>>> import unxt as u >>> angle = u.Angle(370, "deg") >>> angle.wrap_to(min=u.Q(0, "deg"), max=u.Q(360, "deg")) Angle(Array(10, dtype=int32...), unit='deg')
- final class unxt.quantity.Angle(value: Any, unit: Any)#
Bases:
AbstractAngleAngular quantity.
Examples
>>> import unxt as u
Create an Angle:
>>> q = u.Angle(1, "rad") >>> q Angle(Array(1, dtype=int32...), unit='rad')
Wrap an Angle to a range:
>>> q = u.Angle(370, "deg") >>> q.wrap_to(u.Q(0, "deg"), u.Q(360, "deg")) Angle(Array(10, dtype=int32...), unit='deg')
Create an Angle array:
>>> q = u.Angle([1, 2, 3], "deg") >>> q Angle(Array([1, 2, 3], dtype=int32), unit='deg')
Do math on an Angle:
>>> 2 * q Angle(Array([2, 4, 6], dtype=int32), unit='deg')
>>> q % u.Q(4, "deg") Angle(Array([1, 2, 3], dtype=int32), unit='deg')
- value: Real[Array, '*shape'] | Real[StaticValue, '*shape']#
The value of the unxt.AbstractQuantity.
- property T: AbstractQuantity#
Transpose of the array.
Examples
>>> import unxt as u >>> q = u.Q([[0, 1], [1, 2]], "m") >>> q.T Quantity(Array([[0, 1], [1, 2]], dtype=int32), unit='m')
- argmax(*args: Any, **kwargs: Any)#
Return the indices of the maximum value.
Examples
>>> import unxt as u >>> q = u.Q([1, 2, 3], "m") >>> q.argmax() Array(2, dtype=int32)
- argmin(*args: Any, **kwargs: Any)#
Return the indices of the minimum value.
Examples
>>> import unxt as u >>> q = u.Q([1, 2, 3], "m") >>> q.argmin() Array(0, dtype=int32)
- astype(*args: Any, **kwargs: Any)#
Copy the array and cast to a specified dtype.
Examples
>>> import unxt as u >>> q = u.Q([1, 2, 3], "m") >>> q.dtype dtype('int32')
>>> q.astype(float) Quantity(Array([1., 2., 3.], dtype=float32), unit='m')
- Parameters:
- Return type:
- property at: _QuantityIndexUpdateHelper#
Helper property for index update functionality.
The
atproperty provides a functionally pure equivalent of in-place array modifications.In particular:
Alternate syntax
Equivalent In-place expression
x = x.at[idx].set(y)x[idx] = yx = x.at[idx].add(y)x[idx] += yx = x.at[idx].subtract(y)x[idx] -= yx = x.at[idx].multiply(y)x[idx] *= yx = x.at[idx].divide(y)x[idx] /= yx = x.at[idx].power(y)x[idx] **= yx = x.at[idx].min(y)x[idx] = minimum(x[idx], y)x = x.at[idx].max(y)x[idx] = maximum(x[idx], y)x = x.at[idx].apply(ufunc)ufunc.at(x, idx)x = x.at[idx].get()x = x[idx]None of the
x.atexpressions modify the originalx; instead they return a modified copy ofx. However, inside ajit()compiled function, expressions likex = x.at[idx].set(y)are guaranteed to be applied in-place.Unlike NumPy in-place operations such as
x[idx] += y, if multiple indices refer to the same location, all updates will be applied (NumPy would only apply the last update, rather than applying all updates.) The order in which conflicting updates are applied is implementation-defined and may be nondeterministic (e.g., due to concurrency on some hardware platforms).By default, JAX assumes that all indices are in-bounds. Alternative out-of-bound index semantics can be specified via the
modeparameter (see below).- Parameters:
mode โ
string specifying out-of-bound indexing mode. Options are:
"promise_in_bounds": (default) The user promises that indices are in bounds. No additional checking will be performed. In practice, this means that out-of-bounds indices inget()will be clipped, and out-of-bounds indices inset(),add(), etc. will be dropped."clip": clamp out of bounds indices into valid range."drop": ignore out-of-bound indices."fill": alias for"drop". For get(), the optionalfill_valueargument specifies the value that will be returned.
See
jax.lax.GatherScatterModefor more details.wrap_negative_indices โ If True (default) then negative indices indicate position from the end of the array, similar to Python and NumPy indexing. If False, then negative indices are considered out-of-bounds and behave according to the
modeparameter.fill_value โ Only applies to the
get()method: the fill value to return for out-of-bounds slices whenmodeis'fill'. Ignored otherwise. Defaults toNaNfor inexact types, the largest negative value for signed types, the largest positive value for unsigned types, andTruefor booleans.indices_are_sorted โ If True, the implementation will assume that the (normalized) indices passed to
at[]are sorted in ascending order, which can lead to more efficient execution on some backends. If True but the indices are not actually sorted, the output is undefined.unique_indices โ If True, the implementation will assume that the (normalized) indices passed to
at[]are unique, which can result in more efficient execution on some backends. If True but the indices are not actually unique, the output is undefined.
Examples
>>> x = jnp.arange(5.0) >>> x Array([0., 1., 2., 3., 4.], dtype=float32) >>> x.at[2].get() Array(2., dtype=float32) >>> x.at[2].add(10) Array([ 0., 1., 12., 3., 4.], dtype=float32)
By default, out-of-bound indices are ignored in updates, but this behavior can be controlled with the
modeparameter:>>> x.at[10].add(10) # dropped Array([0., 1., 2., 3., 4.], dtype=float32) >>> x.at[20].add(10, mode='clip') # clipped Array([ 0., 1., 2., 3., 14.], dtype=float32)
For
get(), out-of-bound indices are clipped by default:>>> x.at[20].get() # out-of-bounds indices clipped Array(4., dtype=float32) >>> x.at[20].get(mode='fill') # out-of-bounds indices filled with NaN Array(nan, dtype=float32) >>> x.at[20].get(mode='fill', fill_value=-1) # custom fill value Array(-1., dtype=float32)
Negative indices count from the end of the array, but this behavior can be disabled by setting
wrap_negative_indices = False:>>> x.at[-1].set(99) Array([ 0., 1., 2., 3., 99.], dtype=float32) >>> x.at[-1].set(99, wrap_negative_indices=False, mode='drop') # dropped! Array([0., 1., 2., 3., 4.], dtype=float32)
- block_until_ready()#
Block until the array is ready.
- Return type:
Examples
>>> import unxt as u >>> q = u.Q(1, "m") >>> q.block_until_ready() is q True
- decompose(bases: Sequence[UnitBase | FunctionUnitBase | str], /)#
Decompose the quantity into the given bases.
Examples
>>> from unxt import Quantity
>>> q = Quantity(1, "m") >>> q.decompose(["cm", "s"]) Quantity(Array(100., dtype=float32, ...), unit='cm')
- Parameters:
bases (
Sequence[UnitBase|FunctionUnitBase|str])- Return type:
- property device: Device#
Device where the array is located.
Examples
>>> import unxt as u >>> u.Q(1, "m").device CpuDevice(id=0)
- devices()#
Return the devices where the array is located.
Examples
>>> import unxt as u >>> q = u.Q(1, "m") >>> q.devices() {CpuDevice(id=0)}
- property dtype: dtype#
Data type of the array.
Examples
>>> import unxt as u >>> u.Q(1, "m").dtype dtype('int32')
- flatten()#
Return a flattened version of the array.
- Return type:
Examples
>>> import unxt as u >>> q = u.Q([[1, 2], [3, 4]], "m") >>> q.flatten() Quantity(Array([1, 2, 3, 4], dtype=int32), unit='m')
- classmethod from_(cls: type[AbstractQuantity], *args: Any, **kwargs: Any)#
- from_(cls: type[AbstractQuantity], value: ArrayLike | list[Shaped[Array, ''] | Shaped[ndarray, ''] | bool | number | bool | int | float | complex] | tuple[Shaped[Array, ''] | Shaped[ndarray, ''] | bool | number | bool | int | float | complex, ...], unit: Any, /, *, dtype: Any = None) AbstractQuantity
- Parameters:
- Return type:
Construct a unxt.AbstractQuantity from an array-like value and a unit.
- Parameters:
- Return type:
Examples
For this example weโll use the Quantity class. The same applies to any subclass of AbstractQuantity.
>>> import jax.numpy as jnp >>> import unxt as u
>>> x = jnp.array([1.0, 2, 3]) >>> u.Q.from_(x, "m") Quantity(Array([1., 2., 3.], dtype=float32), unit='m')
>>> u.Q.from_([1.0, 2, 3], "m") Quantity(Array([1., 2., 3.], dtype=float32), unit='m')
>>> u.Q.from_((1.0, 2, 3), "m") Quantity(Array([1., 2., 3.], dtype=float32), unit='m')
- from_(cls: type[AbstractQuantity], value: ArrayLike | list[Shaped[Array, ''] | Shaped[ndarray, ''] | bool | number | bool | int | float | complex] | tuple[Shaped[Array, ''] | Shaped[ndarray, ''] | bool | number | bool | int | float | complex, ...], /, *, unit: Any, dtype: Any = None) AbstractQuantity
- Parameters:
- Return type:
Make a unxt.AbstractQuantity from an array-like value and a unit kwarg.
Examples
For this example weโll use the unxt.Quantity class. The same applies to any subclass of unxt.AbstractQuantity.
>>> import unxt as u >>> u.Q.from_([1.0, 2, 3], unit="m") Quantity(Array([1., 2., 3.], dtype=float32), unit='m')
- from_(cls: type[AbstractQuantity], *, value: Any, unit: Any, dtype: Any = None) AbstractQuantity
- Parameters:
- Return type:
Construct a AbstractQuantity from value and unit kwargs.
Examples
For this example weโll use the Quantity class. The same applies to any subclass of AbstractQuantity.
>>> import unxt as u >>> u.Q.from_(value=[1.0, 2, 3], unit="m") Quantity(Array([1., 2., 3.], dtype=float32), unit='m')
- from_(cls: type[AbstractQuantity], mapping: Mapping[str, Any]) AbstractQuantity
- Parameters:
- Return type:
Construct a quantity from a Mapping.
Examples
For this example weโll use the Quantity class. The same applies to any subclass of AbstractQuantity.
>>> import jax.numpy as jnp >>> import unxt as u
>>> x = jnp.array([1.0, 2, 3]) >>> q = u.Q.from_({"value": x, "unit": "m"}) >>> q Quantity(Array([1., 2., 3.], dtype=float32), unit='m')
>>> u.Q.from_({"value": q, "unit": "km"}) Quantity(Array([0.001, 0.002, 0.003], dtype=float32), unit='km')
- from_(cls: type[AbstractQuantity], value: AbstractQuantity, unit: Any, /, *, dtype: Any = None) AbstractQuantity
- Parameters:
- Return type:
Construct a quantity from another quantity.
The value is converted to the new unit.
Examples
>>> import unxt as u
>>> q = u.Q(1, "m") >>> u.Q.from_(q, "cm") Quantity(Array(100., dtype=float32, ...), unit='cm')
- from_(cls: type[AbstractQuantity], value: AbstractQuantity, unit: NoneType, /, *, dtype: Any = None) AbstractQuantity
- Parameters:
- Return type:
Construct a quantity from another quantity.
The value is converted to the new unit.
Examples
>>> import unxt as u
>>> q = u.Q(1, "m") >>> u.Q.from_(q, None) Quantity(Array(1, dtype=int32...), unit='m')
- from_(cls: type[AbstractQuantity], value: AbstractQuantity, /, *, unit: Any | None = None, dtype: Any = None) AbstractQuantity
- Parameters:
- Return type:
Construct a quantity from another quantity.
The unit is unchanged.
- from_(cls: type[StaticQuantity], value: ArrayLike | list[Shaped[Array, ''] | Shaped[ndarray, ''] | bool | number | bool | int | float | complex] | tuple[Shaped[Array, ''] | Shaped[ndarray, ''] | bool | number | bool | int | float | complex, ...], unit: Any, /, *, dtype: Any = None) StaticQuantity
- Parameters:
- Return type:
Construct a StaticQuantity, keeping the value on NumPy dtypes.
The generic
AbstractQuantity.from_routes the value throughjnp.asarray, which applies JAXโs x64-disabled dtype rules and silently downcasts int64 / float64 to int32 / float32. A StaticQuantity stores its value verbatim, so hand the value straight to__init__and let theStaticValue.from_converter convert it โ that preserves the NumPy dtype. Delegating (rather than callingnp.asarrayhere) also keeps.from_and__init__under the same policy for JAX inputs, instead of materialising an array the constructor would reject. (The keyword-unitoverload delegates here, so it is covered too.)Examples
>>> import numpy as np >>> import unxt as u
>>> u.StaticQuantity.from_( ... np.array([1, 2, 3], dtype=np.int64), "m" ... ).value.array.dtype dtype('int64')
.from_applies the same JAX-input policy as__init__โ it delegates rather than converting first, so the two cannot drift:>>> import jax.numpy as jnp >>> u.StaticQuantity.from_(jnp.array([1.0, 2.0]), "m") StaticQuantity(array([1., 2.], dtype=float32), unit='m')
- from_(cls: type[AbstractQuantity], value: Quantity, /, **kwargs: Any) AbstractQuantity
- Parameters:
- Return type:
Construct a quantity from an astropy Quantity.
The value is converted to the new unit.
Examples
>>> import unxt as u >>> import astropy.units as apyu
>>> u.Q.from_(apyu.Quantity(1, "m")) Quantity(Array(1., dtype=float32), unit='m')
- from_(cls: type[AbstractQuantity], value: Quantity, u: Any, /, **kwargs: Any) AbstractQuantity
- Parameters:
- Return type:
Construct a quantity from an astropy Quantity, converting to a target unit.
The value is converted to the new unit.
Examples
>>> import unxt as u >>> import astropy.units as apyu
>>> u.Q.from_(apyu.Quantity(1, "m"), "cm") Quantity(Array(100., dtype=float32), unit='cm')
- Parameters:
cls (
type[AbstractQuantity])args (
Any)kwargs (
Any)
- Return type:
- is_equivalent(other: AbstractQuantity, /)#
Whether
selfandotherare physically equal (unit-aware).The method form of unxt.equivalent; unlike
==(which is unit-blind for StaticValue-backed quantities) this accounts for unit conversion.Examples
>>> import unxt as u >>> u.Q(1000.0, "m").is_equivalent(u.Q(1.0, "km")) Quantity(Array(True, dtype=bool...), unit='')
- Parameters:
other (
AbstractQuantity)- Return type:
- property mT: AbstractQuantity#
Matrix transpose of the array.
Examples
>>> import unxt as u >>> q = u.Q([[0, 1], [1, 2]], "m") >>> q.mT Quantity(Array([[0, 1], [1, 2]], dtype=int32), unit='m')
- max(*args: Any, **kwargs: Any)#
Return the maximum value.
Examples
>>> import unxt as u >>> q = u.Q([1, 2, 3], "m") >>> q.max() Quantity(Array(3, dtype=int32), unit='m')
- Parameters:
- Return type:
- mean(*args: Any, **kwargs: Any)#
Return the mean value.
Examples
>>> import unxt as u >>> q = u.Q([1, 2, 3], "m") >>> q.mean() Quantity(Array(2., dtype=float32), unit='m')
- Parameters:
- Return type:
- min(*args: Any, **kwargs: Any)#
Return the minimum value.
Examples
>>> import unxt as u >>> q = u.Q([1, 2, 3], "m") >>> q.min() Quantity(Array(1, dtype=int32), unit='m')
- Parameters:
- Return type:
- property ndim: int#
Number of dimensions.
Examples
>>> import unxt as u >>> q = u.Q([[1]], "m") >>> q.ndim 2
- ravel()#
Return a flattened version of the array.
- Return type:
Examples
>>> import unxt as u >>> q = u.Q([[1, 2], [3, 4]], "m") >>> q.ravel() Quantity(Array([1, 2, 3, 4], dtype=int32), unit='m')
- reshape(*args: Any, order: str = 'C')#
Return a reshaped version of the array.
Examples
>>> import unxt as u >>> q = u.Q([1, 2, 3, 4], "m") >>> q.reshape(2, 2) Quantity(Array([[1, 2], [3, 4]], dtype=int32), unit='m')
- Parameters:
- Return type:
- round(*args: Any, **kwargs: Any)#
Round the array to the given number of decimals.
Examples
>>> import unxt as u >>> q = u.Q([1.1, 2.2, 3.3], "m") >>> q.round(0) Quantity(Array([1., 2., 3.], dtype=float32), unit='m')
- Parameters:
- Return type:
- property sharding: Any#
Return the sharding configuration of the array.
Examples
>>> import unxt as u >>> q = u.Q([1, 2, 3], "m") >>> q.sharding SingleDeviceSharding(device=..., memory_kind=...)
- property size: int#
Total number of elements.
Examples
>>> import unxt as u >>> q = u.Q([1, 2, 3], "m") >>> q.size 3
- squeeze(*args: Any, **kwargs: Any)#
Return the array with all single-dimensional entries removed.
Examples
>>> import unxt as u >>> q = u.Q([[[1], [2], [3]]], "m") >>> q.squeeze() Quantity(Array([1, 2, 3], dtype=int32), unit='m')
- Parameters:
- Return type:
- to(u: Any, /)#
Convert the quantity to the given units.
See unxt.quantity.AbstractQuantity.uconvert.
Examples
>>> from unxt import Quantity
>>> q = Quantity(1, "m") >>> q.to("cm") Quantity(Array(100., dtype=float32, ...), unit='cm')
- Parameters:
u (
Any)- Return type:
- to_device(device: None | Device = None)#
Move the array to a new device.
Examples
>>> import unxt as u >>> q = u.Q(1, "m") >>> q.to_device(None) Quantity(Array(1, dtype=int32...), unit='m')
- Parameters:
- Return type:
- to_value(u: Any, /)#
Return the value in the given units.
See unxt.AbstractQuantity.ustrip.
Examples
>>> from unxt import Quantity
>>> q = Quantity(1, "m") >>> q.to_value("cm") Array(100., dtype=float32, weak_type=True)
- uconvert(u: Any, /)#
Convert the quantity to the given units.
See also
Noneconvert a quantity to a new unit.
Examples
>>> import unxt as u
>>> q = u.Q(1, "m") >>> q.uconvert("cm") Quantity(Array(100., dtype=float32, ...), unit='cm')
- Parameters:
u (
Any)- Return type:
- ustrip(u: Any, /)#
Return the value in the given units.
See also
Nonestrip the units from a quantity.
Examples
>>> import unxt as u
>>> q = u.Q(1, "m") >>> q.ustrip("cm") Array(100., dtype=float32, weak_type=True)
- wrap_to(min: AbstractQuantity, max: AbstractQuantity)#
Wrap the angle to the range [min, max).
- Parameters:
min (
AbstractQuantity) โ The minimum, maximum value of the range.max (
AbstractQuantity) โ The minimum, maximum value of the range.
- Return type:
See also
Nonefunctional version of this method.
- Return type:
- Parameters:
min (AbstractQuantity)
max (AbstractQuantity)
Examples
>>> import unxt as u >>> angle = u.Angle(370, "deg") >>> angle.wrap_to(min=u.Q(0, "deg"), max=u.Q(360, "deg")) Angle(Array(10, dtype=int32...), unit='deg')
- unit: UnitBase | FunctionUnitBase#
The unit associated with this value.
- unxt.quantity.uconvert_value(uto: Any, ufrom: Any, x: Any, /)#
Convert the value from specified units to specified units.
General signature:
(to_unit, from_unit, value) -> converted_value. Other signatures are defined via method dispatch. Seeuconvert_value.methodsfor details.Examples
>>> import unxt as u # implements `unxts.api.uconvert_value`
>>> u.uconvert_value(u.unit("m"), u.unit("km"), 1) 1000.0
>>> u.uconvert_value("m", "km", 1) 1000.0
For further examples, see the other method dispatches.
- unxt.quantity.uconvert_value(tousys: AbstractUnitSystem, ufrom: UnitBase | FunctionUnitBase, x: ArrayLike, /) ArrayLike
Convert the value from units to a unitsystemโs preferred units.
Examples
>>> import unxt as u >>> u.uconvert_value(u.unitsystems.galactic, u.unit("km"), 1e17) # kpc 3.2407792894443648
>>> u.unitsystems.galactic[u.dimension("length")] # checking the units Unit("kpc")
- unxt.quantity.uconvert_value(tousys: AbstractUnitSystem, ufrom: str, x: ArrayLike, /) ArrayLike
Convert the value from units to a unitsystemโs preferred units.
Examples
>>> import unxt as u >>> u.uconvert_value(u.unitsystems.galactic, "km", 1e17) # in kpc 3.2407792894443648
>>> u.unitsystems.galactic[u.dimension("length")] # checking the units Unit("kpc")
Convert the value to the specified units.
Examples
>>> import unxt as u
>>> u.uconvert_value("m", "km", 1) 1000.0
- unxt.quantity.uconvert_value(uto: Any, ufrom: Any, x: AbstractQuantity, /) AbstractQuantity
Convert the quantity to the specified units.
This is a convenience dispatch so that users can use the lower-level function with a Quantity and not break their code. This dispatch simply calls uconvert, checking first that the units are convertible.
Examples
>>> import unxt as u
>>> q = u.Q(1, "km") >>> u.uconvert_value("m", "km", q) Quantity(Array(1000., dtype=float32...), unit='m')
- unxt.quantity.uconvert_value(uto: UnitBase | Unit | FunctionUnitBase | StructuredUnit, ufrom: UnitBase | Unit | FunctionUnitBase | StructuredUnit, x: ArrayLike, /) ArrayLike
Convert the value to the specified units.
Examples
>>> import astropy.units as apyu >>> import unxt as u
>>> u.uconvert_value(apyu.Unit("km"), apyu.Unit("m"), 1000) 1.0
- unxt.quantity.uconvert_value(uto: UnitBase | Unit | FunctionUnitBase | StructuredUnit, ufrom: UnitBase | Unit | FunctionUnitBase | StructuredUnit, x: Quantity, /) Quantity
Convert an astropy quantity to the specified units.
This is a convenience dispatch mirroring the AbstractQuantity one: users may pass a quantity to the lower-level value function and it keeps working. Like that dispatch, it checks that the quantityโs own unit is convertible to the caller-supplied
ufromโ ~unxt.is_unit_convertible takes the target first, sois_unit_convertible(ufrom, x.unit)reads โx.unit->ufromโ โ then defers to the quantityโs own unit for the arithmetic, returning a relabelled quantity rather than a bare value.This dispatch is required: an astropy ~astropy.units.Quantity subclasses numpy.ndarray, so it satisfies the
x: ArrayLikeannotation of the bare-value dispatch above and is not rejected even under beartype. That bodyโsufrom.to(uto, x)converts the magnitude but returns a quantity still carryingufromโs unit, mislabelling the result (e.g.uconvert_value("m", "km", 1 km)gave1000.0 km).Examples
>>> import astropy.units as apyu >>> import unxt as u
>>> u.uconvert_value(apyu.Unit("m"), apyu.Unit("km"), apyu.Quantity(1.0, "km")) <Quantity 1000. m>
>>> u.uconvert_value(apyu.Unit("m"), apyu.Unit("m"), apyu.Quantity(5.0, "m")) <Quantity 5. m>
- unxt.quantity.uconvert(u: Any, x: Any, /)#
Convert the quantity to the specified units.
General signature:
(to_unit, quantity) -> converted_quantity. Other signatures are defined via method dispatch. Seeuconvert.methodsfor details.Internally, {func}`unxts.api.uconvert` often calls to {func}`unxts.api.uconvert_value` to perform the numerical conversion on the Quantityโs value.
Examples
>>> import unxt as u # implements `unxts.api.uconvert`
>>> q = u.Q(1, "km") >>> u.uconvert(u.unit("m"), q) Quantity(Array(1000., dtype=float32, ...), unit='m')
>>> u.uconvert("m", q) Quantity(Array(1000., dtype=float32, ...), unit='m')
For further examples, see the other method dispatches.
- unxt.quantity.uconvert(ustr: str, x: AbstractQuantity, /) AbstractQuantity
Convert the quantity to the specified units.
Examples
>>> from unxt import Quantity, units
>>> x = Quantity(1000, "m") >>> uconvert("km", x) Quantity(Array(1., dtype=float32...), unit='km')
- unxt.quantity.uconvert(usys: AbstractUnitSystem, x: AbstractQuantity, /) AbstractQuantity
Convert the quantity to the specified units.
Examples
>>> from unxt import Quantity, units >>> from unxt.unitsystems import galactic
>>> q = Quantity(1e17, "km") >>> uconvert(galactic, q) Quantity(Array(3.2407792, dtype=float32...), unit='kpc')
- unxt.quantity.uconvert(u: UnitBase | Unit | FunctionUnitBase | StructuredUnit, x: AbstractQuantity, /) AbstractQuantity
Convert the quantity to the specified units.
Examples
>>> import astropy.units as apyu >>> import unxt as u
>>> x = u.Q(1000, "m") >>> u.uconvert(u.unit("km"), x) Quantity(Array(1., dtype=float32, ...), unit='km')
>>> x = u.Q([1, 2, 3], "Kelvin") >>> with apyu.add_enabled_equivalencies(apyu.temperature()): ... y = x.uconvert("deg_C") >>> y Quantity( Array([-272.15, -271.15, -270.15], dtype=float32, ...), unit='deg_C' )
>>> x = u.Q([1, 2, 3], "radian") >>> with apyu.add_enabled_equivalencies(apyu.dimensionless_angles()): ... y = x.uconvert("") >>> y Quantity(Array([1., 2., 3.], dtype=float32, ...), unit='')
- unxt.quantity.ustrip(*args: Any)#
Strip the units from the quantity, first converting if necessary.
General signature:
(to_unit, quantity) -> value_array. Other signatures are defined via method dispatch. Seeustrip.methodsfor details.Examples
>>> import unxt as u # implements `unxts.api.ustrip`
>>> q = u.Q(1, "km") >>> ustrip(u.unit("m"), q) Array(1000., dtype=float32, ...)
>>> u.ustrip("m", q) Array(1000., dtype=float32, ...)
For further examples, see the other method dispatches.
- unxt.quantity.ustrip(flag: type[AllowValue], unit: Any, x: Any, /) Any
Strip the units from a value. This is a no-op.
Examples
>>> import jax.numpy as jnp >>> import unxt as u >>> from unxt.quantity import AllowValue
>>> x = jnp.array(1) >>> y = u.ustrip(AllowValue, "km", x) >>> y is x True
>>> x = 1_000 >>> y = u.ustrip(AllowValue, "km", x) >>> y is x True
>>> x = "hello" >>> y = u.ustrip(AllowValue, "km", x) >>> y is x True
- unxt.quantity.ustrip(flag: type[AllowValue], x: Any, /) Any
Strip the units from a value. This is a no-op.
Examples
>>> import jax.numpy as jnp >>> import unxt as u >>> from unxt.quantity import AllowValue
>>> x = jnp.array(1) >>> y = u.ustrip(AllowValue, x) >>> y is x True
>>> x = 1_000 >>> y = u.ustrip(AllowValue, x) >>> y is x True
>>> x = "hello" >>> y = u.ustrip(AllowValue, x) >>> y is x True
- unxt.quantity.ustrip(flag: type[AllowValue], unit: Any, x: AbstractQuantity, /) Any
Strip the units from a quantity.
Examples
>>> import unxt as u >>> from unxt.quantity import AllowValue >>> q = u.Q(1000, "m") >>> u.ustrip(AllowValue, "km", q) Array(1., dtype=float32, ...)
- unxt.quantity.ustrip(flag: type[AllowValue], x: AbstractQuantity, /) Any
Strip the units from a quantity.
Examples
>>> import jax.numpy as jnp >>> import unxt as u >>> from unxt.quantity import AllowValue
>>> x = u.Q(1, "kpc") >>> y = u.ustrip(AllowValue, x) >>> not isinstance(y, u.Q) True >>> y == 1 Array(True, dtype=bool...)
- unxt.quantity.ustrip(x: StaticQuantity, /) ndarray
Strip the units from a static quantity.
- unxt.quantity.ustrip(x: AbstractQuantity, /) Array | ndarray
Strip the units from the quantity.
Examples
>>> import unxt as u
>>> q = u.Q(1000, "m") >>> u.ustrip(q) Array(1000, dtype=int32...)
>>> u.ustrip(q) is q.value True
- unxt.quantity.ustrip(u: UnitBase | FunctionUnitBase, x: AbstractQuantity, /) Array | ndarray
Strip the units from the quantity.
Examples
>>> import unxt as u
>>> q = u.Q(1000, "m") >>> u.ustrip(u.unit("km"), q) Array(1., dtype=float32...)
- unxt.quantity.ustrip(u: str, x: AbstractQuantity, /) Array | ndarray
Strip the units from the quantity.
Examples
>>> import unxt as u
>>> q = u.Q(1000, "m") >>> u.ustrip("km", q) Array(1., dtype=float32...)
- unxt.quantity.ustrip(u: AbstractUnitSystem, x: AbstractQuantity, /) Array | ndarray
Strip the units from the quantity.
Examples
>>> import unxt as u >>> from unxt.unitsystems import galactic
>>> q = u.Q(1e17, "km") >>> u.ustrip(galactic, q) Array(3.2407792, dtype=float32...)
Strip the units from the quantity.
Examples
>>> import astropy.units as apyu >>> import unxt as u
>>> x = apyu.Quantity(1000, "m") >>> float(u.ustrip(u.unit("m"), x)) 1000.0
- unxt.quantity.ustrip(flag: type[AllowValue], u: Any, x: Quantity, /) Any
Strip the units from a quantity.
Examples
>>> import astropy.units as apyu >>> import unxt as u >>> from unxt.quantity import AllowValue >>> q = apyu.Quantity(1000, "m") >>> float(u.ustrip(AllowValue, "km", q)) 1.0
- unxt.quantity.ustrip(flag: type[AllowValue], x: Quantity, /) Any
Strip the units from an astropy quantity, allowing bare values through.
The two-argument
AllowValueform takes no target unit, so it returns the value in the quantityโs own unit. This dispatch disambiguatesustrip(AllowValue, <astropy Quantity>), which otherwise matched bothustrip(type[AllowValue], Any)andustrip(Any, AstropyQuantity)with neither dominating. It mirrors the(type[AllowValue], AbstractQuantity)form for unxt quantities.Examples
>>> import astropy.units as apyu >>> import unxt as u >>> from unxt.quantity import AllowValue >>> q = apyu.Quantity(1000, "m") >>> float(u.ustrip(AllowValue, q)) 1000.0
- unxt.quantity.is_unit_convertible(to_unit: Any, from_: Any, /)#
Check if the units are convertible.
General signature is
(to_unit, from_unit) -> bool. Other signatures are defined via method dispatch. Seeis_unit_convertible.methodsfor details.Examples
>>> import unxt as u # implements `unxts.api.is_unit_convertible` >>> u.is_unit_convertible(u.unit("m"), u.unit("km")) True
>>> u.is_unit_convertible(u.unit("m"), u.unit("s")) False
- unxt.quantity.is_unit_convertible(to_unit: Any, from_: Any, /) bool
Check if a unit can be converted to another unit.
- Parameters:
- Return type:
Examples
>>> from unxt import is_unit_convertible >>> is_unit_convertible("cm", "m") True
>>> is_unit_convertible("m", "Gyr") False
- unxt.quantity.is_unit_convertible(to_unit: Any, from_: AbstractQuantity, /) bool
Check if a quantity can be converted to another unit.
Examples
>>> from unxt import Quantity, is_unit_convertible >>> q = Quantity(1, "m")
>>> is_unit_convertible("cm", q) True
>>> is_unit_convertible("Gyr", q) False
- unxt.quantity.wrap_to(x: Any, min: Any, max: Any, /)#
Wrap to the range [min, max).
General signature:
(x, min, max) -> wrapped_x. Other signatures are defined via method dispatch. Seewrap_to.methodsfor details.Examples
>>> import unxt as u >>> >>> angle = u.Angle(370, "deg") >>> min, max = u.Q(0, "deg"), u.Q(360, "deg") >>> >>> u.quantity.wrap_to(angle, min, max) Angle(Array(10, dtype=int32...), unit='deg') >>> >>> u.quantity.wrap_to(angle, min=min, max=max) Angle(Array(10, dtype=int32...), unit='deg')
- unxt.quantity.wrap_to(x: Any, /, *, min: Any, max: Any) Any
Wrap to the range [min, max).
- unxt.quantity.wrap_to(angle: AbstractQuantity, min: AbstractQuantity, max: AbstractQuantity, /) AbstractQuantity
Wrap to the range [min, max).
Examples
>>> import unxt as u
>>> angle = u.Angle(370, "deg") >>> u.quantity.wrap_to(angle, min=u.Q(0, "deg"), max=u.Q(360, "deg")) Angle(Array(10, dtype=int32...), unit='deg')
- unxt.quantity.is_any_quantity(obj: Any, /)#
Check if an object is an instance of unxt.quantity.AbstractQuantity.
Examples
>>> import unxt as u
>>> q = u.Q(1, "m") >>> is_any_quantity(q) True
- Parameters:
obj (
Any)- Return type:
TypeGuard[AbstractQuantity]
- unxt.quantity.convert_to_quantity_value(obj: Any, /)#
Convert for the value field of an AbstractQuantity subclass.
- unxt.quantity.convert_to_quantity_value(obj: StaticValue, /) StaticValue
Allow static values in quantity-like classes.
- unxt.quantity.convert_to_quantity_value(obj: ArrayValue, /) Any
Convert a quax.ArrayValue for the value field.
>>> import warnings >>> import jax >>> import jax.numpy as jnp >>> from jaxtyping import Array >>> from quax import ArrayValue
>>> class MyArray(ArrayValue): ... value: Array ... ... def aval(self): ... return jax.core.ShapedArray(self.value.shape, self.value.dtype) ... ... def materialise(self): ... return self.value
>>> x = MyArray(jnp.array([1, 2, 3])) >>> with warnings.catch_warnings(record=True, action="always") as w: ... y = convert_to_quantity_value(x) >>> y MyArray(value=i32[3]) >>> print(f"Warning caught: {w[-1].message}") Warning caught: 'quax.ArrayValue' subclass 'MyArray' ...
Convert an array-like object to a jax.numpy.ndarray.
>>> import jax.numpy as jnp >>> from unxt.quantity import convert_to_quantity_value
>>> convert_to_quantity_value([1, 2, 3]) Array([1, 2, 3], dtype=int32)
- unxt.quantity.convert_to_quantity_value(obj: AbstractQuantity, /) NoReturn
Disallow conversion of AbstractQuantity to a value.
>>> import unxt as u >>> from unxt.quantity import convert_to_quantity_value
>>> try: ... convert_to_quantity_value(u.Q(1, "m")) ... except TypeError as e: ... print(e) Cannot convert 'Quantity' to a value. For a Quantity, use the `.from_` constructor instead.
- unxt.quantity.convert_to_quantity_value(obj: Quantity, /) NoReturn
Disallow conversion of AstropyQuantity to a value.
>>> import astropy.units as apyu >>> from unxt.quantity import convert_to_quantity_value
>>> try: ... convert_to_quantity_value(apyu.Quantity(1, "m")) ... except TypeError as e: ... print(e) Cannot convert 'Quantity' to a value. For a Quantity, use the `.from_` constructor instead.
- class unxt.quantity.AllowValue#
Bases:
objectA flag to allow a value to be passed through unxt.ustrip.
Examples
>>> import jax.numpy as jnp >>> import unxt as u >>> from unxt.quantity import AllowValue
>>> x = jnp.array(1) >>> y = u.ustrip(AllowValue, "km", x) >>> y is x True
>>> u.ustrip(AllowValue, "km", u.Q(1000, "m")) Array(1., dtype=float32, ...)
This is a flag, so it cannot be instantiated.
>>> try: ... AllowValue() ... except TypeError as e: ... print(e) Cannot instantiate AllowValue
- Return type:
- unxt.quantity.equivalent(a: AbstractUnitSystem, b: AbstractUnitSystem, /)#
Check if two unit systems are equivalent.
- unxt.quantity.equivalent(a: AbstractQuantity, b: AbstractQuantity, /) Any
- Parameters:
- Return type:
Whether two quantities are physically equal, accounting for units.
This is the unit-aware counterpart to
==(which is unit-blind for StaticValue-backed quantities โ see AbstractQuantity.__eq__). The result mirrors==โs shape: a scalar bool for StaticValue-backed operands, and an element-wise dimensionless Quantity of booleans for array-backed ones. Quantities with incompatible dimensions are never equivalent (and this never raises).Examples
>>> import numpy as np >>> import unxt as u >>> from unxt.quantity import StaticValue
Physically-equal static quantities in different units are equivalent, even though unit-blind
==reportsFalse:>>> a = u.Q(StaticValue(np.array([1.0, 2.0])), "m") >>> b = u.Q(StaticValue(np.array([0.001, 0.002])), "km") >>> a == b False >>> u.equivalent(a, b) True >>> a.is_equivalent(b) True
Array-backed quantities compare element-wise (unit-aware):
>>> u.equivalent(u.Q([1.0, 2.0], "m"), u.Q([0.001, 0.009], "km")) Quantity(Array([ True, False], dtype=bool), unit='')
Incompatible dimensions are never equivalent:
>>> u.equivalent(u.Q(1.0, "m"), u.Q(1.0, "s")) False
- Parameters:
- Return type:
- unxt.quantity.register_ufunc(ufunc: ufunc, /)#
Register a unit-aware handler for a NumPy ufunc.
The decorated function is called as
handler(ufunc, method, *inputs, **kwargs)and must return a unit-carrying result. It may itself be plum-dispatched on the input types.Examples
>>> import numpy as np >>> import unxt as u
>>> doubler = np.frompyfunc(lambda x: 2 * x, 1, 1)
>>> @u.quantity.register_ufunc(doubler) ... def _(ufunc, method, x, /, **kw): ... return u.Q(2 * x.value, x.unit)
>>> doubler(u.Q(3.0, "m")) Quantity(Array(6., dtype=float32...), unit='m')