ArrayWUnits#
- class ArrayWUnits(values: int | float | list | ndarray[tuple[Any, ...], dtype[_ScalarT]], units: Units | list[Units] | ndarray[Units] | None)#
Bases:
objectDefines 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:
intorfloat- a scalar valuenp.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
listornp.ndarraywith the same size as the numerical values. Each element of thislistornp.ndarrayshould be the desired Unit of the corresponding element in the given numerical values.
- Attributes:
homogeneous_unitsBoolean flag indicating whether or not all units are homogeneous.
shapeThe number of columns and rows within the ArrayWUnits object.
sizeThe number of elements contained within the ArrayWUnits object.
unitsThe unit or units associated with the object.
valuesThe 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
ArrayWUnitswithout 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 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).Sum all elements in the ArrayWUnits object, if units allow.
tan()Trigonometric tangent operator for ArrayWUnits objects.
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.UnitsScarabaeus-defined representation of physical units.
scarabaeus.DimensionsScarabaeus-defined representation of physical dimensions.
scarabaeus.ArrayWFrameAttaches a reference frame to ArrayWUnits.
Notes
While both
valuesandunitscan optionally be given as multiple different object types, internally they are always converted tonp.ndarrayobjects 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 thatfrom_trusted()takes, so a numeric result can be returned as anArrayWUnitsat 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
valueswith 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
ArrayWUnitswithout input validation (fast path).This bypasses the
__init__type checks and the validatingvalues/unitssetters. 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.ndarrayof a numeric dtype (no list/scalar conditioning is performed).- unitsUnits or numpy.ndarray
A single homogeneous
Unitsobject applied to all elements, or an object array of per-elementUnitsshaped likevaluesthat are not all equal (the validating setter would collapse equal ones into a singleUnits). 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
ArrayWUnitsorArrayWFrameinput, strip it here once, run their numeric core on plain arrays and attach units to the result again. Unlikeget_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
unitsalready. 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
unitsmatches neither the elements nor the rows of the quantity, or, fromconvert_to(), if a unit has different dimensions from its target.
- 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
axisisNone,outis 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
- sqrt() Self#
Returns the element-wise square root of the ArrayWUnits object (equivalent to
awu ** 0.5).
- 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.
Trueif all units are homogeneous. OtherwiseFalse.
- 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.