ArrayWUnits#

class ArrayWUnits(values: int | float | list | ndarray[tuple[Any, ...], dtype[_ScalarT]], units: Units | list[Units] | ndarray[Units] | None)#

Bases: object

Defines a representation of numerical values and their associated units.

The values and units are attached and computed together during mathematical operations. Supports scalar and matrix definitions.

Note that “scalar” definitions are still treated as 1x1 matrices internally.

Parameters:
valuesint or float or list or numpy.ndarray

The numerical value or values of the associated object. Accepts scalar or matrix/vector inputs:

  • int or float - a scalar value

  • np.ndarray - a matrix or vector of values

unitsUnit or list or numpy.ndarray

The units associated with the given numerical value or values. If a single Unit object is passed, then all numerical values are assumed to be the same unit.

To assign separate units to individual elements in a given numerical matrix/vector, pass either a list or np.ndarray with the same size as the numerical values. Each element of this list or np.ndarray should be the desired Unit of the corresponding element in the given numerical values.

Attributes:
homogeneous_units

Boolean flag indicating whether or not all units are homogeneous.

shape

The number of columns and rows within the ArrayWUnits object.

size

The number of elements contained within the ArrayWUnits object.

units

The unit or units associated with the object.

values

The numerical value or values associated with the object.

Methods

T()

Transpose operator for ArrayWUnits objects.

angle_between(other)

Angle between two vectors.

append(other[, axis])

Return an ArrayWUnits object with given ArrayWUnits object appended to the back.

atleast_2d([awu_in])

Rescast the ArrayWUnits object as arrays with atleast two dimensions.

convert_to(to_convert_to)

Convert all elements of an ArrayWUnits object to the given units.

cos()

Trigonometric cosine operator for ArrayWUnits objects.

cross(other)

Cross product operation between two ArrayWUnits objects.

empty(shape)

Initializes a new ArrayWUnits object of the given shape without initializing value entries.

exp()

Exponential operator for ArrayWUnits objects.

exp2()

Exponential base 2 operator for ArrayWUnits objects.

from_row_units(values, row_units)

Attach one unit to each row of a numeric array, without validation.

from_trusted(values, units)

Construct an ArrayWUnits without input validation (fast path).

get_value_in_target_units(quantity, target_units)

Method to extract a value of an AWU quantity if its units match the desired target units.

inverse()

Inverse operator for ArrayWUnits objects.

log()

Natural log operator for ArrayWUnits objects.

log10()

Log base 10 operator for ArrayWUnits objects.

log2()

Log base 2 operator for ArrayWUnits objects.

norm()

Matrix or vector norm operator for ArrayWUnits objects.

pseudo_inverse()

Pseudo-inverse operator for ArrayWUnits objects.

sin()

Trigonometric sine operator for ArrayWUnits objects.

sqrt()

Returns the element-wise square root of the ArrayWUnits object (equivalent to awu ** 0.5).

summation()

Sum all elements in the ArrayWUnits object, if units allow.

tan()

Trigonometric tangent operator for ArrayWUnits objects.

transpose()

Transpose operator for ArrayWUnits objects.

unitary()

Converts a given ArrayWUnits vector into a unit vector with the same units.

values_in(quantity, units)

Strip a quantity to bare numbers in the given units.

See also

scarabaeus.Units

Scarabaeus-defined representation of physical units.

scarabaeus.Dimensions

Scarabaeus-defined representation of physical dimensions.

scarabaeus.ArrayWFrame

Attaches a reference frame to ArrayWUnits.

Notes

While both values and units can optionally be given as multiple different object types, internally they are always converted to np.ndarray objects to ensure numpy functionality.

Examples

Create a scalar value with associated units:

>>> import scarabaeus as scb
>>> km, sec = scb.Units.get_units(['km', 'sec'])  # define units
>>> ten_km = scb.ArrayWUnits(10, km)
>>> print(ten_km)
10 km

Create a vector of values with different units:

>>> import numpy as np
>>> nums = np.array([1, 2, 3, 4]).reshape(-1, 1)
>>> units = np.array([km, km, km/sec, km/sec]).reshape(-1, 1)
>>> state_vec2D = scb.ArrayWUnits(nums, units)
>>> print(state_vec2D)
[[1]
 [2]
 [3]
 [4]] [non-homogeneous]
classmethod from_row_units(values: ndarray, row_units) → ArrayWUnits#

Attach one unit to each row of a numeric array, without validation.

A state [r, v] has km rows and km/s rows, and a Jacobian of it has the same rows divided by the units of each column’s parameter. This builds the per-element unit array that from_trusted() takes, so a numeric result can be returned as an ArrayWUnits at the cost of one object array.

Parameters:
valuesnumpy.ndarray

Numeric array, as from_trusted() requires. Every element of a row gets that row’s unit.

row_unitssequence of Units

One unit per row, len(values) of them, not all equal.

Returns:
ArrayWUnits

values with the units of its rows. The unit array is new, so a caller can change single elements of it, e.g. one column whose parameter has other units.

classmethod from_trusted(values: ndarray, units: Units) → ArrayWUnits#

Construct an ArrayWUnits without input validation (fast path).

This bypasses the __init__ type checks and the validating values / units setters. It is intended for hot inner loops (force-model partial collection, the propagation RHS) where the caller can already guarantee the inputs are well-formed; everywhere else use the normal constructor.

Parameters:
valuesnumpy.ndarray

Numeric array. Must already be a numpy.ndarray of a numeric dtype (no list/scalar conditioning is performed).

unitsUnits or numpy.ndarray

A single homogeneous Units object applied to all elements, or an object array of per-element Units shaped like values that are not all equal (the validating setter would collapse equal ones into a single Units). The array is stored, not copied, so pass one the caller does not reuse.

Returns:
ArrayWUnits

An instance equivalent to ArrayWUnits(values, units), but built without validation overhead.

static empty(shape: int | tuple[int, int]) → Self#

Initializes a new ArrayWUnits object of the given shape without initializing value entries. Units are set as unitless.

ArrayWUnits equivalent of Numpy empty() function.

Parameters:
shapeint | tuple[int, int]

The shape of the empty ArrayWUnits. One-dimensional arrays should be given as integers while n-dimensional arrays should be given as a tuple of integers.

Returns:
outArrayWUnits

An ArrayWUnits object of given shape with empty values and unitless units.

References

static get_value_in_target_units(quantity, target_units: Units) → ndarray#

Method to extract a value of an AWU quantity if its units match the desired target units. If that’s not the case, a warning is displayed and a conversion is attempted. If that also fails, then an error is generated on the quantity of interest not having the proper units.

Parameters:
quantityArrayWUnits

An ArrayWUnits object containing a value and unit (e.g. quantity.values and quantity.units)

target_unitsUnits

The target unit to check on the quantity

Returns:
valuenumpy.ndarray

A numpy array corresponding to quantity.values, if the units match

static values_in(quantity, units) → ndarray#

Strip a quantity to bare numbers in the given units.

Public methods take ArrayWUnits or ArrayWFrame input, strip it here once, run their numeric core on plain arrays and attach units to the result again. Unlike get_value_in_target_units(), a quantity in other units of the same dimension is converted without a warning, since it is valid input.

Parameters:
quantityArrayWUnits, ArrayWFrame, array_like, float or None

Value to strip. An ArrayWFrame gives its quantity; bare numbers are taken to be in units already. None, an optional argument left out, is returned as None.

unitsUnits or array_like of Units

Target units: one for every element, one per element, or one per row, e.g. the km and km/s rows of a state Jacobian.

Returns:
numpy.ndarray or None

A new float array in units, shaped like the quantity. Elements already in their target units are copied, not converted, so their numbers are unchanged to the last bit.

Raises:
ValueError

If units matches neither the elements nor the rows of the quantity, or, from convert_to(), if a unit has different dimensions from its target.

T() → Self#

Transpose operator for ArrayWUnits objects.

angle_between(other)#

Angle between two vectors.

append(other: Self, axis: int = None) → Self#

Return an ArrayWUnits object with given ArrayWUnits object appended to the back.

ArrayWUnits equivalent of Numpy append() function.

Parameters:
otherArrayWUnits

The ArrayWUnits object to be appended.

axisint, optional

The axis along which given ArrayWUnits objects are added. If not given, both self and given ArrayWUnits object are flattened before appending. Defaults to None.

Returns:
outArrayWUnits

ArrayWUnits object with given ArrayWUnits appended to the end. If axis is None, out is is a flattened ArrayWUnits object.

References

Examples

Append two ArrayWUnits vectors:

>>> import scarabaeus as scb
>>> kg, km = scb.Units.get_units(['kg', 'km'])  # define units
>>> one = scb.ArrayWUnits([[1], [2], [3]], kg) # create AWU's
>>> two = scb.ArrayWUnits(4, kg)
>>> one.append(two) # no axis specified gives a flattened row vector
[1. 2. 3. 4.] [kg ... kg]

Append compatible vector to matrix

>>> import numpy as np
>>> mat_units = np.array([[kg, km, km], [km, kg, km], [km, km, kg]])
>>> mat = scb.ArrayWUnits(np.eye(3), mat_units)
>>> print(mat)
[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]] [non-homogeneous]
>>> row = scb.ArrayWUnits(np.ones((1, 3)), km)
>>> print(row)
[[1. 1. 1.]] [km ... km]
>>> appended = mat.append(row, 0)   # append to first axis
>>> print(appended)
[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]
 [1. 1. 1.]] [non-homogeneous]
atleast_2d(awu_in: Self = None) → Self#

Rescast the ArrayWUnits object as arrays with atleast two dimensions.

ArrayWUnits equivalent of Numpy atleast_2d() function.

Parameters:
awu_inArrayWUnits, optional

The AWU to recast.

Returns:
outArrayWUnits

The recast AWU.

References

convert_to(to_convert_to: Units) → Self#

Convert all elements of an ArrayWUnits object to the given units.

Valid for ArrayWUnits objects containing non-homogeneous units as long as those units are all of the same dimension.

Parameters:
to_convert_toUnits

The desired unit the ArrayWUnits is to be converted to.

Returns:
convertedArrayWUnits

The ArrayWUnits object with converted units.

Examples

Convert 0.05 N to mN and back to N:

>>> import scarabaeus as scb
>>> N, mN = scb.Units.get_units(['N', 'mN'])  # define units
>>> p05N = scb.ArrayWUnits(0.05, N)           # 0.05 N
>>> print(p05N)
0.05 N
>>> p05N_in_mN = p05N.convert_to(mN)          # convert to mN
>>> print(p05N_in_mN)
50.0 mN
>>> back_to_p05N = p05N_in_mN.convert_to(N)   # and back to N
>>> print(back_to_p05N)
0.05 N
cos() → Self#

Trigonometric cosine operator for ArrayWUnits objects.

cross(other: Self) → Self#

Cross product operation between two ArrayWUnits objects.

exp() → Self#

Exponential operator for ArrayWUnits objects.

exp2() → Self#

Exponential base 2 operator for ArrayWUnits objects.

inverse() → Self#

Inverse operator for ArrayWUnits objects.

Only valid for square matrices.

log() → Self#

Natural log operator for ArrayWUnits objects.

log10() → Self#

Log base 10 operator for ArrayWUnits objects.

log2() → Self#

Log base 2 operator for ArrayWUnits objects.

norm() → Self#

Matrix or vector norm operator for ArrayWUnits objects.

pseudo_inverse() → Self#

Pseudo-inverse operator for ArrayWUnits objects.

sin() → Self#

Trigonometric sine operator for ArrayWUnits objects.

sqrt() → Self#

Returns the element-wise square root of the ArrayWUnits object (equivalent to awu ** 0.5).

summation() → Self#

Sum all elements in the ArrayWUnits object, if units allow.

tan() → Self#

Trigonometric tangent operator for ArrayWUnits objects.

transpose() → Self#

Transpose operator for ArrayWUnits objects.

unitary() → Self#

Converts a given ArrayWUnits vector into a unit vector with the same units.

Only valid for vectorial ArrayWUnits.

property homogeneous_units: bool#

Boolean flag indicating whether or not all units are homogeneous.

True if all units are homogeneous. Otherwise False.

property shape: tuple[int, int]#

The number of columns and rows within the ArrayWUnits object.

property size: int#

The number of elements contained within the ArrayWUnits object.

property units: Units | ndarray[Units]#

The unit or units associated with the object.

The type is dependent on the homogeneity of the associated units:

  • Units object if the object is a scalar value or all values in the numerical matrix/vector are assigned the same units.

  • Numpy array of Units objects if the values in the numerical matrix/vector are not assigned the same units.

property values: ndarray#

The numerical value or values associated with the object.