polymath Module
PolyMath Library
PDS Ring-Moon Systems Node, SETI Institute
PolyMath expands on the NumPy module and introduces a variety of additional data types and features to simplify 3-D geometry calculations. It is a product of the the [PDS Ring-Moon Systems Node](https://pds-rings.seti.org). The PolyMath classes are:
Scalar: A single zero-dimensional number=.Vector: An arbitrary 1-D object.Pair: A subclass of Vector representing a vector with two coordinates.Vector3: A subclass of Vector representing a vector with three coordinates.Matrix: An arbitrary 2-D matrix.Matrix3: A subclass of Matrix representing a unitary 3x3 rotation matrix.Quaternion: A subclass of Vector representing a 4-component quaternion.Boolean: A True or False value.Qube: The superclass of all of the above, supporting objects of arbitrary dimension.
Importantly, each of these classes can represent not just a single object, but also an
arbitrary array of these objects. Mathematical operations on arrays follow NumPy’s rules
of “broadcasting”; see https://numpy.org/doc/stable/user/basics.broadcasting.html for
these details. The key advantage of PolyMath’s approach is that it separates each object’s
shape from any internal dimensions (e.g., (3,3) for a Matrix3 object), largely
eliminating any need to ever do “index bookkeeping”. For example, suppose S is a
Scalar and V is a Vector. Then, in PolyMath, you can write:
S * V
whereas, in NumPy, you would have to write:
S[..., np.newaxis] * V
to get the same result. This capability makes it possible to write out algorithms as if each operation is on a single vector, scalar, or matrix, ignoring the internal dimensionality of each PolyMath object.
PolyMath has the following additional features:
Derivatives: An object can have arbitrary derivatives, or an array thereof. These get carried through all math operations so, for example, if X.d_dt is the derivative of X with respect to t, then X.sin().d_dt is the derivative of sin(X) with respect to t. This means that you can write out math operations in the most straightforward manner, without worrying about how any derivatives get calculated.
Masks: Objects can have arbitrary boolean masks, which are equal to True where the object’s value is undefined. This is similar to NumPy’s MaskedArray class, but with added capabilities. For example, if an object is mostly masked, you can use the
shrink()method to speed up math operations by excluding all the masked elements.Units: Objects can have arbitrary units, as defined by PolyMath’s Unit class.
Read-only status: It is easy to define an object to be read-only, which will then prevent it from being modified further. This can be useful for preventing NumPy errors that can arise when multiple objects share memory (a common situation) and one of them gets modified by accident.
Indexing: An object can be indexed in a variety of ways that expand upon NumPy’s indexing rules.
Pickling: Python’s pickle module can be used to save and re-load objects in a way that makes for extremely efficient storage.
PolyMath provides the mathematical underpinnings of the OOPS Library. As an illustration of its power, here are some examples of how OOPS uses PolyMath objects to describe a data product:
los is a single
Vector3that represents the lines of sight represented by each sample in the data product. If the product is a 1000x1000 image, then los will have an internal shape of (1000,1000). If the product is a single detector, then los will have no internal shape.time is a
Scalarthat represents the time that the photons arrived at the detector. If the instrument is a simple, shuttered camera, then all photons arrive at the same time and time can have a single value. However, if a raster-scanning device obtains a 1000x1000 image, then time will have an internal shape of (1000,1000), with each element representing the unique arrival time at that pixel. For a “pushbroom” camera, the detector receives the image line by line, so time will have an internal shape of (1000,1) or (1,1000), depending on the orientation of the detector.cmatrix is a
Matrix3that represents the rotation matrix from the instrument’s internal coordinates to the J2000 frame, which is fixed relative to the sky. If the instrument is not rotating during an observation, then a single matrix is required. However, if the camera is on a rotating platform and it samples photons at different times, then cmatrix may need to have an internal shape of (1000,1000) to describe a 1000x1000 image. Furthermore, the rate of change of cmatrix can be described by a derivative with respect to time. When one calculates where the lines of sight intercepted a target body, the time derivative of cmatrix can then be used to determine the amount of smear in the image.
Although different types of data products might have very different internal representations, PolyMath makes it possible to write a geometry calculation just once and then re-use it for all of these situations.
As a specific example, OOPS can determine where each line of sight sampled by a data
product intercepted the surface of a particular planetary body. The intercept points are
represented by a single Vector3 given in the body’s coordinate frame. From this
object, it is straightforward to derive latitude, longitude, emission angle, etc. If the
product is a 1000x1000 image, then the Vector3 will have an internal shape of
(1000,1000). Furthermore, if the body does not entirely fill the field of view, the lines
of sight that did not intercept the body are masked. It is not uncommon for a body to only
partially fill a field of view. In this case, OOPS can speed up calculations, sometimes
substantially, by omitting the masked elements of the Vector3 object.
Math Operations
All standard mathematical operators and indexing/slicing options are defined for PolyMath
objects, where appropriate: +, -, *, /, %, //,`**`, along with their in-place
variants. Equality tests ==, != are available for all objects; comparison operators
<, <=, >, >= are supported for Scalars and Booleans. Where appropriate, methods
such as abs(), len(), mean(), sum(),
identity(), reciprocal(), int(),
Matrix.inverse(), and Matrix.transpose() (or property Matrix.T).
Scalar supports most common math functions such as sin(),
cos(), tan(), arcsin(), arccos(),
arctan(), arctan2(), sqrt(),
log(), exp(), sign(), int(),
frac(), min(), max(), argmin(),
argmax(), minimum(), maximum(),
median(), and sort(). It also supports quadratic equations via
solve_quadratic() and eval_quadratic().
Vector supports functions such as norm(), norm_sq(),
unit(), dot(), cross(), ucross(),
outer() (outer product), perp() (perpendicular vector),
proj() (projection), and sep() (separation angle).
Element-by-element operations are also supported using element_mul() and
element_div().
Vector3 supports additional functions such as
from_ra_dec_length(), to_ra_dec_length(),
from_cylindrical(), to_cylindrical(),
longitude(), latitude(), spin() (rotate one
vector about another), and offset_angles() (the angles from the three
primary axes).
Pair supports additional functions such as swapxy(),
rot90() (for rotation by a multiple of 90 degrees), and angle()
(for the vector’s angular direction).
Matrix3 functions rotate() and unrotate() apply a
rotation to another object. Methods x_rotation(),
y_rotation(), z_rotation(), axis_rotation(),
pole_rotation(), from_euler(), and unitary()
are convenient, alternative ways to define a rotation matrix. Use
to_euler() and to_quaternion() to reverse these definitions.
Quaternion supports functions such as conj() (conjugate),
to_parts() (for the Scalar and Vector3 components),
from_parts() (to construct from the Scalar and Vector3 components),
to_rotation() (for the transform as a direction Vector3 and rotation
angle), from_matrix3(), to_matrix3(),
from_euler(), and to_euler().
The values (or vals) property of each object returns its value
as a NumPy array. For Scalar objects with no shape, values is a
Python-native value of float or int; for Boolean objects with no shape,
values is a Python-native bool.
One can generally mix PolyMath arithmetic with scalars, NumPy ndarrays, NumPy MaskedArrays, or anything array-like.
Shapes and Broadcasting
The PolyMath subclasses, e.g., Scalar, Vector3, and Matrix3,
define one or more possibly multidimensional items. Unlike NumPy ndarrays, this class
makes a clear distinction between the dimensions associated with the items and any
additional, leading dimensions that define an array of such items.
Each object’s shape property contains the shape of its leading axes, whereas
its item property defines the shape of individual elements. For example, a
2x2 array of Matrix3 objects would have shape=(2,2) and items=(3,3). Its
values property would be a NumPy array with shape (2,2,3,3). In addition,
ndims (or ndim) contains the number of dimensions in the
shape; size is the number of items; rank is the number of
dimensions in the items; isize is the number of item elements.
To change the shape of an object, use methods reshape(),
flatten(), move_axis(), roll_axis(), and
swap_axes(). These all return a shallow copy of an object, which shares memory
with the original object.
Standard NumPy rules of broadcasting apply, but only on the shape
dimensions, not on the item dimensions. For example, if you multiply a
Matrix3 with shape (2,2) by a Vector3 object with shape (5,1,2), you
would get a new (rotated) Vector3 object with shape (5,2,2). See the complete
rules of broadcasting here:
https://numpy.org/doc/stable/user/basics.broadcasting.html
If necessary, you can explicitly broadcast objects to a new shape using methods
broadcast() and broadcast_to(); these return shallow, read-only
copies. Use broadcasted_shape() to determine the shape that will result from
an operation involving multiple PolyMath objects and NumPy arrays.
Derivatives
PolyMath objects can track associated derivatives and partial derivatives, which are
represented by a dictionary of other PolyMath objects. A common use case is to let X
be a Vector3 object describing the position of one or more bodies or points on a
surface and to use the time-derivative of X to describe the velocity. The
derivs property of an object is a dictionary of each derivative, keyed by
its name. For example, a time-derivative is often keyed by t. For convenience, you can
also reference each derivative by the attribute name “d_d” plus the key, so the
time-derivative of X can be accessed via X.d_dt. This feature makes it possible to
write an algorithm describing the positions of bodies or features, and to have any
time-derivatives carried along in the calculation with no additional programming effort.
The denominators of partial derivatives are represented by splitting the item shape into a
numerator shape plus a denominator shape. As a result, for example, the partial
derivatives of a Vector3 object (item shape (3,)) with respect to a Pair
(item shape (2,)) will have overall item shape (3,2). Properties numer gives
the numerator shape, nrank is the number of dimensions, and
nsize gives the number of elements. Similarly, denom is the
denominator shape, drank is the number of dimensions, and
dsize is the number of elements.
The PolyMath subclasses generally do not constrain the shape of the denominator, just
the numerator. As a result, the aforementioned partial derivatives can still be
represented by a Vector3 object.
Methods insert_deriv(), insert_derivs(),
delete_deriv(), delete_derivs(), and rename_deriv()
can be used to add, remove, or modify derivatives after it has been constructed. You can
also obtain a shallow copy of an object with one or more derivatives removed using
without_deriv() and without_derivs(). For convenience, the
wod property is equivalent to without_derivs(). Note that the
presence of derivatives inside an object can slow computational performance significantly,
so it can useful to suppress derivatives from a calculation if they are not needed. Note
that many math functions have a recursive option that defaults to True; set it to False
to ignore derivatives within the given calculation.
A number of methods are focused on modifying the numerator and denominator components of
objects: extract_numer(), extract_denom(),
extract_denoms(), slice_numer(), transpose_numer(),
reshape_numer(), flatten_numer(), transpose_denom(),
reshape_denom(), flatten_denom(), join_items(),
split_items(), and swap_items().
The function chain() can be used for chain-multiplication of derivatives; this
is also implemented via the “@” operator.
Masks
Every object has a boolean mask, which identifies undefined values or array elements. Operations that would otherwise raise errors such as 1/0 and sqrt(-1) are masked, so that run-time warnings and exceptions can be avoided. A common use case is to have a “backplane” array describing the geometric content of a planetary image, where the mask identifies the pixels that do not intersect the surface.
Each object has a property mask, which contains the mask. A single value of
False means that the object is entirely unmasked; a single value of True means it is
entirely masked. Otherwise, mask is a NumPy array with boolean values, with
a shape that matches that of the object itself (excluding its items). For example, a
Vector3 object with shape (5,2) could have a mask value represented
by a NumPy array of shape (5,2), even though its values property has shape
(5,2,3).
The mvals property of an object returns its values property as
a NumPy MaskedArray.
Each object also has a property antimask, which is the “logical not” of the
mask. Use the antimask as an index to select only the unmasked
elements of an object. You can also use the shrink() method to temporarily
eliminate masked elements from an object, potentially speeding up calculations; use
unshrink() when you are done to restore the original shape.
Under normal circumstances, a masked value should be understood to mean, “this value does not exist.” For example, a calculation of observed intercept points on a moon is masked if a line of sight missed the moon, because that line of sight does not exist. This is similar to NumPy’s not-a-number (“NaN”) concept, but there are important differences. For example,
Two masked values of the same class are considered equal. This is different from the behavior of NaN.
Unary and binary operations involving masked values always return masked values.
Because masked values are treated as if they do not exist,
max()returns the maximum among the unmasked values;all()returns True if all the unmasked values are True (or nonzero).
However, PolyMath also provides boolean methods to support an alternative interpretation of masked values as indeterminate rather than nonexistent. These follow the rules of “three-valued logic”:
tvl_and()returns False if one value is False but the other is masked, because the result would be False regardless of the second value.tvl_or()returns True if one value is True but the other is masked, because the result would be True regardless of the second value.tvl_all()returns True only if and only all values are True; if any value is False, it returns False; if the only values are True or indeterminate, its value is indeterminate (meaning masked).tvl_any()returns True if any value is True; it returns False if every value is False; if the only values are False or indeterminate, its value is indeterminate.tvl_eq()andtvl_ne()are indeterminate if either value is indeterminate.
You can only define an object’s mask at the time it is constructed. To change a mask, use
remask() or remask_or(), which return a shallow copy of the object
(sharing memory with the original) but with a new mask. You can also use a variety of
methods to construct an object with a new mask: mask_where(),
mask_where_eq(), mask_where_ge(), mask_where_gt(),
mask_where_le(), mask_where_lt(), mask_where_ne(),
mask_where_between(), mask_where_outside(), and
clip().
Units
PolyMath objects also support embedded unit using the Unit class. However, the
internal values in a PolyMath object are always held in standard units of kilometers,
seconds and radians, or arbitrary combinations thereof. The unit is primarily used to
affect the appearance of numbers during input and output. The unit_ or
units property of any object will reveal the class:Unit object, or
possibly None if the object is unitless.
A Unit allows for exact conversions between units. It is described by three
integer exponents applying to dimensions of length, time, and angle. Conversion factors
are describe by three (usually) integer values representing a numerator, denominator, and
an exponent on pi. For example, Unit.DEGREE is represented by exponents (0,0,1)
and factors (1,180,1), indicating that the conversion factor is pi/180. Most other
common units are described by class constants; see the Unit class for details.
Normally, you specify the unit of an object at the time it is constructed. However, the
method set_unit() is available to set the unit_ property
afterward.
Read-only Objects
PolyMath objects can be either read-only or read-write. Read-only objects are prevented from modification to the extent that Python makes this possible. Operations on read-only objects should always return read-only objects.
The as_readonly() method can be used to set an object (and its
derivatives) to read-only status. It is not possible to convert an object from
read-only back to read-write; use copy() instead. The
readonly property is True if the object is read-only; False if it is
read-write.
Alternative Constructors
Aside from the explicit constructor methods, numerous methods are available to construct
objects from other objects. Methods include copy(), clone(),
cast(), zeros(), ones(), filled(),
as_this_type(), as_all_constant(), as_size_zero(),
masked_single(), as_numeric(), as_float(),
as_int(), and as_bool(). There are also methods to convert between
classes, such as Vector.from_scalars(), Vector.to_scalar(),
Vector.to_scalars(), Matrix3.twovec() (a rotation matrix defined by two
vectors), Matrix.row_vector(), Matrix.row_vectors(),
Matrix.column_vector(), Matrix.column_vectors`, and Matrix.to_vector`.
Indexing
Using an index on a Qube object is very similar to using one on a NumPy array, but there are a few important differences. For purposes of retrieving selected values from an object:
True and False can be applied to objects with shape (). True leaves the object unchanged; False masks the object.
An index of True selects the entire associated axis in the object, equivalent to a colon or slice(None). An index of False reduces the associated axis to length one and masks the object entirely.
A
Booleanobject can be used as an index. If this index is unmasked, it is the same as indexing with a boolean NumPy ndarray. If it is masked, the values of the returned object are masked wherever theBoolean’s value is masked. When using aBooleanindex to set items inside an object, locations where theBooleanindex are masked are not changed.A
Scalarobject composed of integers can be used as an index. If this index is unmasked, it is equivalent to indexing with an integer or integer NumPy ndarray. If it is masked, the values of the returned object are masked wherever theScalaris masked. When using aScalarindex to set items inside an object, locations where theScalarindex are masked are not changed.A
Pairobject composed of integers can be used as an index. Each (i,j) value is treated is the index of two consecutive axes, and the associated value is returned. Where thePairis masked, a masked value is returned. Similarly, aVectorwith three or more integer elements is treated as the index of three or more consecutive axes.As in NumPy, an integer valued array can be used to index a PolyMath object. In this case, the shape of the index array appears within the shape of the returned object. For example, if A has shape (6,7,8,9) and B has shape (3,1), then A[B] has shape (3,1,7,8,9); A[:,B] has shape (6,3,1,8,9), and A[…,B] has shape (6,7,8,3,1).
When multiple arrays are used for indexing at the same time, the broadcasted shape of these array appears at the location of the first array-valued index. In the same example as above, suppose C has shape (4,). Then A[B,C] has shape (3,4,8,9), A[:,B,C] has shape (6,3,4,9), and A[:,B,:,C] has shape (6,3,4,8). Note that this behavior is slightly different from how NumPy handles indexing with multiple arrays.
Several methods can be used to convert PolyMath objects to objects than be used for
indexing NumPy arrays. You can obtain integer indices from Scalar.as_index(),
Vector.as_index(), Scalar.as_index_and_mask(), and
Vector.as_index_and_mask(). You can obtain boolean masks from
Boolean.as_index(), as_mask_where_nonzero(),
as_mask_where_zero(), as_mask_where_nonzero_or_masked(), and
as_mask_where_zero_or_masked().
Iterators
Every Polymath object can be used as an iterator, in which case it performs an iteration
over the object’s leading axis. Alternatively, ndenumerate() iterates over
every item in a multidimensional object.
Pickling
Because objects such as backplanes can be numerous and also quite large, we provide a
variety of methods, both lossless and lossy, for compressing them during storage. As one
example of optimization, only the un-masked elements of an object are stored; upon
retrieval, all masked elements will have the value of the object’s default
attribute.
Arrays with integer elements are losslessly compressed using BZ2 compression. The numeric range is checked and values are stored using the fewest number of bytes sufficient to cover the range. Arrays with boolean elements are converted to bit arrays and then compressed using BZ2. These steps allow for extremely efficient data storage.
This module employs a variety of options for compressing floating point values.
Very small arrays are stored using BZ2 compression.
Constant arrays are stored as a single value plus a shape.
Array values are divided by a specified constant and then stored as integers, using BZ2 compression, as described above.
Arrays are compressed, with or without loss, using fpzip. This is a highly effective algorithm, especially for arrays such as backplanes that often exhibit smooth variations from pixel to pixel. See https://pypi.org/project/rms-fpzip/.
For each object, the user can define the floating-point compression method using
set_pickle_digits(). One can also define the global default compression method
using set_default_pickle_digits(). The inputs to these functions are as
follows:
digits (str, int, or float): The number of digits to preserve.
“double”: preserve full precision using lossless fpzip compression.
“single”: convert the array to single precision and then store it using lossless fpzip compression.
an number 7-16, defining the number of significant digits to preserve.
reference (str or float): How to interpret a numeric value of digits.
“fpzip”: Use lossy fpzip compression, preserving the given number of digits.
a number: Preserve every number to the exact same absolute precision, scaling the number of digits by this value. For example, if digits = 8 and reference = 100, all values will be rounded to the nearest 1.e-6 before storage. This method uses option 3 above, where values are converted to integers for storage.
The remaining options for reference provide a variety of ways for its value to be generated automatically.
“smallest”: Absolute accuracy will be 10**(-digits) times the non-zero array value closest to zero. This option guarantees that every value will preserve at least the requested number of digits. This is reasonable if you expect all values to fall within a similar dynamic range.
“largest”: Absolute accuracy will be 10**(-digits) times the value in the array furthest from zero. This option is useful for arrays that contain a limited range of values, such as the components of a unit vector or angles that are known to fall between zero and 2*pi. In this case, it is probably not necessary to preserve the extra precision in values that just happen to fall very close zero.
“mean”: Absolute accuracy will be 10**(-digits) times the mean of the absolute values in the array.
“median”: Absolute accuracy will be 10**(-digits) times the median of the absolute values in the array. This is a good choice if a minority of values in the array are very different from the others, such as noise spikes or undefined geometry. In such a case, we want the precision to be based on the more “typical” values.
“logmean”: Absolute accuracy will be 10**(-digits) times the log-mean of the absolute values in the array.
- class Boolean(*values, **keywords)[source]
Bases:
ScalarRepresent boolean values in the PolyMath framework.
This class handles boolean values with masking support. Masked values are considered unknown, neither True nor False.
- FALSE = Boolean(False)
- MASKED = Boolean(--; mask)
- TRUE = Boolean(True)
- __abs__(*, recursive=True)[source]
The absolute value of this Boolean as an integer.
This is an override of
Qube.__abs__().- Parameters:
recursive (bool, optional) – Ignored for Boolean.
- Returns:
An integer Scalar with ones where this object is True, zeros where False.
- Return type:
- __add__(arg, *, recursive=True)[source]
self + arg, element-by-element addition after this Boolean is converted to an integer Scalar.
This is an override of
Qube.__add__().
- __floordiv__(arg)[source]
self // arg, element-by-element floor division after this Boolean is converted to an integer Scalar.
This is an override of
Qube.__floordiv__().
- __ge__(arg, *, builtins=True)[source]
self <= arg, element-by-element “greater than or equal” after this Boolean is converted to integer Scalar.
This is an override of
Qube.__ge__().- Parameters:
arg – The scalar to compare with.
builtins (bool, optional) – If True and the result is a single unmasked scalar, return a Python bool instead of a Boolean object.
- Returns:
True where this int value is greater than or equal to the argument.
- Return type:
Boolean or bool
- Raises:
ValueError – If either object has denominators.
- __gt__(arg, *, builtins=True)[source]
self > arg, element-by-element “greater than” after this Boolean is converted to an integer Scalar.
This is an override of
Qube.__gt__().- Parameters:
arg – The scalar to compare with.
builtins (bool, optional) – If True and the result is a single unmasked scalar, return a Python bool instead of a Boolean object.
- Returns:
True where this int value is greater than the argument.
- Return type:
Boolean or bool
- Raises:
ValueError – If either object has denominators.
- __iadd__(arg)[source]
self += arg; in-place addition is not supported for Boolean.
This is an override of
Qube.__iadd__().- Parameters:
arg (Qube, np.ndarray, float, int, or bool) – The argument.
- Raises:
ValueError – Always; in-place addition is not supported for Boolean.
- __ifloordiv__(arg)[source]
self //= arg; in-place division is not supported for Boolean.
This is an override of
Qube.__ifloordiv__().- Parameters:
arg (Qube, np.ndarray, float, int, or bool) – The argument.
- Raises:
ValueError – Always; in-place floor division is not supported for Boolean.
- __imod__(arg)[source]
Raise exception as in-place modulo is not supported for Boolean.
This is an override of
Qube.__imod__().- Parameters:
arg (Qube, np.ndarray, float, int, or bool) – The argument.
- Raises:
ValueError – Always; in-place modulo is not supported for Boolean.
- __imul__(arg)[source]
In-place multiplication is not supported for Boolean.
This is an override of
Qube.__imul__().- Parameters:
arg (Qube, np.ndarray, float, int, or bool) – The argument.
- Raises:
ValueError – Always; in-place multiplication is not supported for Boolean.
- __isub__(arg)[source]
self -= arg; in-place subtraction is not supported for Boolean.
This is an override of
Qube.__isub__().- Parameters:
arg (Qube, np.ndarray, float, int, or bool) – The argument.
- Raises:
ValueError – Always; in-place subtraction is not supported for Boolean.
- __itruediv__(arg)[source]
self /= arg; in-place division is not supported for Boolean.
This is an override of
Qube.__itruediv__().- Parameters:
arg (Qube, np.ndarray, float, int, or bool) – The argument.
- Raises:
ValueError – Always; in-place division is not supported for Boolean.
- __le__(arg, *, builtins=True)[source]
self <= arg, element-by-element “less than or equal” after this Boolean is converted to integer Scalar.
This is an override of
Qube.__le__().- Parameters:
arg – The scalar to compare with.
builtins (bool, optional) – If True and the result is a single unmasked scalar, return a Python bool instead of a Boolean object.
- Returns:
True where this int value is less than or equal to the argument.
- Return type:
Boolean or bool
- Raises:
ValueError – If either object has denominators.
- __lt__(arg, *, builtins=True)[source]
self < arg, element-by-element “less than” after this Boolean is converted to an integer Scalar.
This is an override of
Qube.__lt__().- Parameters:
arg – The scalar to compare with.
builtins (bool, optional) – If True and the result is a single unmasked scalar, return a Python bool instead of a Boolean object.
- Returns:
True where this int value is less than the argument.
- Return type:
Boolean or bool
- Raises:
ValueError – If either object has denominators.
- __mod__(arg)[source]
self % arg, element-by-element modulus after this Boolean is converted to an integer Scalar.
This is an override of
Qube.__mod__().
- __mul__(arg, *, recursive=True)[source]
self * arg, element-by-element multiplication after this Boolean is converted to an integer Scalar.
This is an override of
Qube.__mul__().
- __neg__(*, recursive=True)[source]
The negated integer equivalent of this Boolean.
This is an override of
Qube.__neg__().- Parameters:
recursive (bool, optional) – Ignored for Boolean.
- Returns:
A negated integer Scalar (-1 where True, 0 where False).
- Return type:
- __pos__(*, recursive=True)[source]
The integer equivalent of this Boolean.
This is an override of
Qube.__pos__().- Parameters:
recursive (bool, optional) – Ignored for Boolean.
- Returns:
An integer Scalar with ones where this object is True, zeros where False.
- Return type:
- __pow__(arg)[source]
self ** arg, element-by-element exponentiation after this Boolean is converted to an integer Scalar.
This is an override of
Qube.__pow__().
- __radd__(arg, *, recursive=True)[source]
arg + self, element-by-element addition after this Boolean is converted to an integer Scalar.
This is an override of
Qube.__radd__().
- __rfloordiv__(arg)[source]
arg // self, element-by-element floor division after this Boolean is converted to an integer Scalar.
This is an override of
Qube.__rfloordiv__().
- __rmod__(arg)[source]
arg % self, element-by-element modulus after this Boolean is converted to an integer Scalar.
This is an override of
Qube.__rmod__().
- __rmul__(arg, *, recursive=True)[source]
arg * self, element-by-element multiplication after this Boolean is converted to an integer Scalar.
This is an override of
Qube.__rmul__().
- __rsub__(arg, *, recursive=True)[source]
arg - self, element-by-element subtraction after this Boolean is converted to an integer Scalar.
This is an override of
Qube.__rsub__().
- __rtruediv__(arg, *, recursive=True)[source]
arg / self, element-by-element division after this Boolean is converted to a floating-point Scalar.
This is an override of
Qube.__rtruediv__().
- __sub__(arg, *, recursive=True)[source]
self - arg, element-by-element subtraction after this Boolean is converted to an integer Scalar.
This is an override of
Qube.__sub__().
- __truediv__(arg, *, recursive=True)[source]
self / arg, element-by-element division after this Boolean is converted to a floating-point Scalar.
This is an override of
Qube.__truediv__().
- static as_boolean(arg, *, recursive=True)[source]
Convert the argument to Boolean if possible.
- Parameters:
arg (object) – The object to convert to Boolean.
recursive (bool, optional) – This parameter is ignored for Boolean class but included for compatibility.
- Returns:
The converted Boolean object.
- Return type:
- as_index()[source]
An object suitable for indexing a NumPy ndarray.
- Returns:
A boolean array with False values where masked.
- Return type:
ndarray
- identity()[source]
An object of this subclass equivalent to the identity.
This is an override of
Qube.identity().- Returns:
A read-only Boolean with value True.
- Return type:
- sum(axis=None, *, value=True, builtins=None, recursive=True, masked=None, out=None)[source]
The sum of the unmasked values along the specified axis or axes.
This is an override of
Qube.sum(), adding the value option to count False values instead of True values.- Parameters:
axis (int or tuple, optional) – An integer axis or a tuple of axes. The sum is determined across these axes, leaving any remaining axes in the returned value. If None (the default), then the sum is performed across all axes of the object.
value (bool, optional) – True to count True values; False to count False values.
builtins (bool, optional) – If True and the result is a single unmasked scalar, the result is returned as a Python int or float instead of as an instance of Qube. Default is that specified by Qube.prefer_builtins().
recursive (bool, optional) – Ignored for class Boolean.
masked (bool, optional) – The value to return if builtins is True but the returned value is masked. Default is to return a masked value instead of a builtin type.
out (object, optional) – Ignored. Enables “np.sum(Qube)” to work.
- Returns:
The sum of matched values (True or False) along the specified axis or axes.
- Return type:
- class Matrix(*values, **keywords)[source]
Bases:
QubeA Qube of arbitrary 2-D matrices.
This class represents arbitrary 2D matrices in the PolyMath framework and provides operations for matrix arithmetic, transposition, and inversion.
- IDENTITY2 = Matrix([1. 0.] [0. 1.])
- IDENTITY3 = Matrix([1. 0. 0.] [0. 1. 0.] [0. 0. 1.])
- MASKED2 = Matrix([-- --] [-- --]; mask)
- MASKED3 = Matrix([-- -- --] [-- -- --] [-- -- --]; mask)
- property T
The transpose of this matrix.
- Returns:
Transpose of this matrix with derivatives included.
- Return type:
- UNIT33 = Matrix([1. 0. 0.] [0. 1. 0.] [0. 0. 1.])
- XAXIS_COL = Matrix([1.] [0.] [0.])
- XAXIS_ROW = Matrix([1. 0. 0.])
- YAXIS_COL = Matrix([0.] [1.] [0.])
- YAXIS_ROW = Matrix([0. 1. 0.])
- ZAXIS_COL = Matrix([0.] [0.] [1.])
- ZAXIS_ROW = Matrix([0. 0. 1.])
- ZERO33 = Matrix([0. 0. 0.] [0. 0. 0.] [0. 0. 0.])
- ZERO3_COL = Matrix([0.] [0.] [0.])
- ZERO3_ROW = Matrix([0. 0. 0.])
- __abs__()[source]
Raise a TypeError; absolute value is not defined for matrices.
This is an override of
Qube.__abs__().
- __floordiv__(arg)[source]
Raise a TypeError; floor division is not defined for matrices.
This is an override of
Qube.__floordiv__().
- __ifloordiv__(arg)[source]
Raise a TypeError; floor division is not defined for matrices.
This is an override of
Qube.__ifloordiv__().
- __imod__(arg)[source]
Raise a TypeError; modulo is not defined for matrices.
This is an override of
Qube.__imod__().
- __mod__(arg)[source]
Raise a TypeError; modulo is not defined for matrices.
This is an override of
Qube.__mod__().
- __rfloordiv__(arg)[source]
Raise a TypeError; floor division is not defined for matrices.
This is an override of
Qube.__rfloordiv__().
- __rmod__(arg)[source]
Raise a TypeError; modulo is not defined for matrices.
This is an override of
Qube.__rmod__().
- static as_matrix(arg, *, recursive=True)[source]
Convert the argument to a Matrix if possible.
- Parameters:
arg – The object to convert to a Matrix.
recursive (bool, optional) – True to include derivatives in the result.
- Returns:
The argument converted to a Matrix.
- Return type:
- column_vector(column, *, recursive=True, classes=(<class 'polymath.vector3.Vector3'>, <class 'polymath.vector.Vector'>))[source]
The selected column of a Matrix as a Vector.
If the Matrix is M x N, then this will return a Vector of length M. By default, if M == 3, it will return a Vector3 object instead.
- Parameters:
column – Index of the column to return.
recursive (bool, optional) – True to return corresponding vectors of derivatives.
classes (tuple, optional) – A list of classes; an instance of the first suitable class is returned.
- Returns:
The selected column as a vector.
- Return type:
- column_vectors(recursive=True, classes=(<class 'polymath.vector3.Vector3'>, <class 'polymath.vector.Vector'>))[source]
A tuple of Vector objects, one for each column of this Matrix.
If the Matrix is M x N, then this will return N Vectors of length M. By default, if M == 3, it will return Vector3 objects instead.
- Parameters:
recursive (bool, optional) – True to return corresponding vectors of derivatives.
classes (tuple, optional) – A list of classes; instances of the first suitable class are returned.
- Returns:
A tuple of Vector objects, one for each column.
- Return type:
tuple
- static from_scalars(*args, recursive=True, shape=None, classes=[])[source]
Construct a Matrix or subclass by combining scalars.
- Parameters:
*args – Any number of Scalars or arguments that can be casted to Scalars. They need not have the same shape, but it must be possible to broadcast them to the same shape. A value of None is converted to a zero-valued Scalar that matches the denominator shape of the other arguments.
recursive (bool, optional) – True to include all the derivatives. The returned object will have derivatives representing the union of all the derivatives found amongst the scalars.
shape (tuple, optional) – The Matrix’s item shape. If not specified but the number of Scalars is a perfect square, a square matrix is returned.
classes (list, optional) – An arbitrary list defining the preferred class of the returned object. The first suitable class in the list will be used. Default is [Matrix].
- Returns:
A Matrix constructed from the given scalars.
- Return type:
- Raises:
TypeError – If the input would result in an int matrix, which is not allowed.
ValueError – If the number of Scalars does not match the specified shape.
- identity()[source]
An identity matrix of the same size and subclass as this.
This method overrides
Qube.identity().- Raises:
ValueError – If the matrix is not square.
- inverse(*, recursive=True, nozeros=False)[source]
The inverse of this matrix.
The returned object will have the same subclass as this object. Matrices with determinant equal to zero are masked.
- Parameters:
recursive (bool, optional) – True to include the derivatives of the inverse.
nozeros (bool, optional) – False to mask out any matrices with zero-valued determinants. Set to True only if you know in advance that all determinants are nonzero.
- Returns:
- Inverse of this matrix. It will have the same subclass as this object.
Matrices with a determinant equal to zero will be masked.
- Return type:
- Raises:
ValueError – If the matrix is not square or has denominators.
ValueError – If nozeros is True but a determinant of zero is encountered.
- is_diagonal(*, delta=0.0)[source]
A Boolean equal to True where the matrix is diagonal.
Masked matrices return True.
- Parameters:
delta (float, optional) – The fractional limit on what can be treated as equivalent to zero in the off-diagonal terms. It is scaled by the RMS value of all the elements in the matrix.
- Returns:
True where the matrix is diagonal.
- Return type:
- Raises:
ValueError – If the matrix is not square or has denominators.
- reciprocal(*, recursive=True, nozeros=False)[source]
Return an object equivalent to the reciprocal of this object.
For a Matrix, the reciprocal is the inverse. This overrides
Qube.reciprocal().- Parameters:
recursive (bool, optional) – True to return the derivatives of the reciprocal too; otherwise, derivatives are removed.
nozeros (bool, optional) – False to mask out any matrices with zero-valued determinants. Set to True only if you know in advance that all determinants are nonzero.
- Returns:
The matrix inverse.
- Return type:
- Raises:
ValueError – If the matrix is not square, has denominators, or has a determinant of zero.
- row_vector(row, *, recursive=True, classes=(<class 'polymath.vector3.Vector3'>, <class 'polymath.vector.Vector'>))[source]
The selected row of a Matrix as a Vector.
If the Matrix is M x N, then this will return a Vector of length N. By default, if N == 3, it will return a Vector3 object instead.
- row_vectors(*, recursive=True, classes=(<class 'polymath.vector3.Vector3'>, <class 'polymath.vector.Vector'>))[source]
A tuple of Vector objects, one for each row of this Matrix.
If the Matrix is M x N, then this will return M Vectors of length N. By default, if N == 3, it will return Vector3 objects instead.
- Parameters:
recursive (bool, optional) – True to return corresponding vectors of derivatives.
classes (tuple, optional) – A list of classes; instances of the first suitable class are returned.
- Returns:
A tuple of Vector objects, one for each row.
- Return type:
tuple
- to_scalar(indx0, indx1, *, recursive=True)[source]
One of the elements of a Matrix as a Scalar.
- Parameters:
indx0 (int) – Index along the first matrix axis.
indx1 (int) – Index along the second matrix axis.
recursive (bool, optional) – True to extract the derivatives as well.
- Returns:
One element of the Matrix as a Scalar.
- Return type:
- to_vector(axis, indx, *, recursive=True, classes=[])[source]
One of the components of a Matrix as a Vector.
- Parameters:
axis – Axis index from which to extract vector.
indx – Index of the vector along this axis.
classes (list, optional) – A list of the Vector subclasses to return. The first valid one will be used.
recursive (bool, optional) – True to extract the derivatives as well.
- Returns:
One component of the Matrix as a Vector.
- Return type:
- transpose(*, recursive=True)[source]
The transpose of this matrix.
- Parameters:
recursive (bool, optional) – True to include the transposed derivatives; False to return an object without derivatives.
- Returns:
Transpose of this matrix.
- Return type:
- unitary()[source]
The nearest unitary matrix as a Matrix3.
Uses the algorithm from https://wikipedia.org/wiki/Orthogonal_matrix#Nearest_orthogonal_matrix
- Returns:
The nearest unitary (orthogonal) matrix.
- Return type:
- Raises:
ValueError – If the matrix has denominators or is not 3x3.
- class Matrix3(*values, **keywords)[source]
Bases:
MatrixRepresent 3x3 rotation matrices in the PolyMath framework.
This class provides functionality for working with 3x3 rotation matrices, including creating matrices from rotations about axes and converting between different rotation representations.
- IDENTITY = Matrix3([1. 0. 0.] [0. 1. 0.] [0. 0. 1.])
- MASKED = Matrix3([-- -- --] [-- -- --] [-- -- --]; mask)
- __add__(arg)[source]
Raise a TypeError; “self + arg” is not permitted for Matrix3 objects.
This is an override of
Qube.__add__().
- __iadd__(arg)[source]
Raise a TypeError; “self += arg” is not permitted for Matrix3 objects.
This is an override of
Qube.__iadd__().
- __imul__(arg)[source]
self * arg, in-place matrix multiplication.
This overrides
Qube.__imul__().- Parameters:
arg – The Matrix3 by which to multiply this Matrix3.
- Returns:
This object, the result of the multiplication.
- Return type:
- Raises:
ValueError – If arg cannot be converted to a Matrix3 or if this Matrix3 is not writeable.
- __isub__(arg)[source]
Raise a TypeError; “self -= arg” is not permitted for Matrix3 objects.
This is an override of
Qube.__isub__().
- __mul__(arg, *, recursive=True)[source]
self * arg, matrix multiplication.
Matrix3 times Scalar returns the same type of Scalar. This overrides
Qube.__mul__().- Parameters:
arg – The object to multiply with this Matrix3.
recursive (bool, optional) – True to include derivatives in the result.
- Returns:
The result of the multiplication.
- Return type:
- Raises:
ValueError – If multiplication with the given type is not supported.
- __neg__()[source]
Raise a TypeError; “-self” is not permitted for Matrix3 objects.
This is an override of
Qube.__neg__().
- __radd__(arg)[source]
Raise a TypeError; “arg + self” is not permitted for Matrix3 objects.
This is an override of
Qube.__radd__().
- __rmul__(arg, *, recursive=True)[source]
arg * self, matrix multiplication.
Matrix3 times Scalar returns the same type of Scalar. This overrides
Qube.__rmul__().- Parameters:
arg – The object to multiply with this Matrix3.
recursive (bool, optional) – True to include derivatives in the result.
- Returns:
The result of the multiplication.
- Return type:
- Raises:
ValueError – If multiplication with the given type is not supported.
- __rsub__(arg)[source]
Raise a TypeError; “arg - self” is not permitted for Matrix3 objects.
This is an override of
Qube.__rsub__().
- __sub__(arg)[source]
Raise a TypeError; “self - arg” is not permitted for Matrix3 objects.
This is an override of
Qube.__sub__().
- static as_matrix3(arg, *, recursive=True)[source]
Convert the argument to Matrix3. The result is not checked to be unitary.
Quaternions are converted to matrices.
- Parameters:
arg – The object to convert to Matrix3.
recursive (bool, optional) – True to include derivatives in the returned result.
- Returns:
The argument converted to a Matrix3.
- Return type:
- static axis_rotation(angle, axis=2, *, recursive=True)[source]
A rotation matrix about one of the three primary axes.
The returned matrix rotates a vector counterclockwise by the specified angle about the specified axis (0 for X, 1 for Y, 2 for Z). The same matrix rotates a coordinate system clockwise by the same angle.
- Parameters:
angle – The rotation angle in radians.
axis (int, optional) – The axis to rotate around (0=X, 1=Y, 2=Z).
recursive (bool, optional) – True to include derivatives in the result.
- Returns:
A rotation matrix about the specified axis.
- Return type:
- static from_euler(ai, aj, ak, axes='rzxz')[source]
Create a homogeneous rotation matrix from Euler angles and axis sequence.
- Parameters:
ai – First Euler angle (roll).
aj – Second Euler angle (pitch).
ak – Third Euler angle (yaw).
axes (str, optional) – One of 24 axis sequences as string or encoded tuple.
- Returns:
A rotation matrix representing the specified Euler angles.
- Return type:
- Raises:
KeyError – If the axes string is not recognized.
ValueError – If any of the angles has an invalid unit.
Examples
>>> R = Matrix3.from_euler(1, 2, 3, 'syxz') >>> np.allclose(np.sum(R[0]), -1.34786452) True >>> R = Matrix3.from_euler(1, 2, 3, (0, 1, 0, 1)) >>> np.allclose(np.sum(R[0]), -0.383436184) True
- mean(axis=None, *, recursive=True, builtins=None, dtype=None, out=None)[source]
Calculate the mean of the unmasked values along the specified axis.
This operation is not supported for Matrix3 objects. This overrides
Qube.mean().- Parameters:
axis (int or tuple, optional) – The axis or axes over which the mean is to be performed, leaving any remaining axes in the returned value. If not specified, the mean is performed across all axes.
recursive (bool, optional) – True to include the means of the derivatives inside the returned Scalar.
builtins – If True and the result is a single unmasked scalar, the result is returned as a Python int or float instead of as an instance of Scalar. Default is specified by Qube.prefer_builtins().
dtype – Ignored. Enables “np.mean(Qube)” to work.
out – Ignored. Enables “np.mean(Qube)” to work.
- Raises:
TypeError – Always raised as this method is not supported for Matrix3.
- static pole_rotation(ra, dec)[source]
Create a rotation matrix to a frame defined by right ascension and declination.
The returned matrix rotates coordinates into a frame where the Z-axis is defined by (ra, dec) and the X-axis points along the new equatorial plane’s ascending node on the original equator.
- Parameters:
ra – The right ascension of the Z-axis in radians.
dec – The declination of the Z-axis in radians.
- Returns:
A rotation matrix to the frame defined by (ra,dec).
- Return type:
- Raises:
ValueError – If ra or dec has an invalid unit.
Notes
Derivatives are not supported.
- reciprocal(*, recursive=True, nozeros=False)[source]
Return the reciprocal of this Matrix3, which is its transpose.
- Parameters:
recursive (bool, optional) – True to return the derivatives of the reciprocal too; otherwise, derivatives are removed.
nozeros (bool, optional) – Ignored for Matrix3.
- Returns:
The transpose of this matrix.
- Return type:
- rotate(arg, *, recursive=True)[source]
Rotate an object by this Matrix3, returning an instance of the same subclass.
- Parameters:
arg – The object to rotate.
recursive (bool, optional) – If True, the rotated derivatives are included in the object returned.
- Returns:
The rotated object of the same type as the input.
- Return type:
- sum(axis=None, *, recursive=True, builtins=None, out=None)[source]
Calculate the sum of the unmasked values along the specified axis.
This operation is not supported for Matrix3 objects. This overrides
Qube.sum().- Parameters:
axis (int or tuple, optional) – The axis or axes over which the sum is to be performed, leaving any remaining axes in the returned value. If not specified, the sum is performed across all axes.
recursive (bool, optional) – True to include the sums of the derivatives inside the returned Scalar.
builtins – If True and the result is a single unmasked scalar, the result is returned as a Python int or float instead of as an instance of Qube. Default is specified by Qube.prefer_builtins().
out – Ignored. Enables “np.sum(Qube)” to work.
- Raises:
TypeError – Always raised as this method is not supported for Matrix3.
- to_euler(axes='rzxz')[source]
Convert this Matrix3 to three Euler angles given a specified axis sequence.
- Parameters:
axes (str, optional) – One of 24 axis sequences as string or encoded tuple.
- Returns:
Three Scalars representing the Euler angles (roll, pitch, yaw).
- Return type:
tuple
- Raises:
KeyError – If the axes string is not recognized.
Notes
Many Euler angle triplets can describe one matrix.
Examples
>>> R0 = Matrix3.from_euler(1, 2, 3, 'syxz') >>> al, be, ga = R0.to_euler('syxz') >>> R1 = Matrix3.from_euler(al, be, ga, 'syxz') >>> np.allclose(R0, R1) True
- to_quaternion(recursive=True)[source]
Convert this Matrix3 to an equivalent unit Quaternion.
- Parameters:
recursive (bool, optional) – True to include derivatives in the result.
- Returns:
A unit quaternion representing the same rotation.
- Return type:
- static twovec(vector1, axis1, vector2, axis2, *, recursive=True)[source]
A rotation matrix defined by two vectors.
The returned matrix rotates to a right-handed coordinate frame having vector1 pointing along a specified axis (axis1=0 for X, 1 for Y, 2 for Z) and vector2 pointing into the half-plane defined by (axis1, axis2).
- Parameters:
vector1 (Vector or array-like) – The first vector that defines the rotation.
axis1 (int) – The axis to which vector1 should point (0=X, 1=Y, 2=Z).
vector2 (Vector or array-like) – The second vector that defines the rotation.
axis2 (int) – The axis defining the half-plane for vector2 (0=X, 1=Y, 2=Z).
recursive (bool, optional) – True to include derivatives in the result.
- Returns:
A rotation matrix determined by the input vectors.
- Return type:
- Raises:
ValueError – If an input Vector has a denominator, or if any derivatives have mismatched denominators.
- unrotate(arg, *, recursive=True)[source]
Rotate an object by the inverse of this Matrix3, returning the same subclass.
- Parameters:
arg – The object to unrotate.
recursive (bool, optional) – If True, the un-rotated derivatives are included in the object returned.
- Returns:
The unrotated object of the same type as the input.
- Return type:
- static x_rotation(angle, *, recursive=True)[source]
A rotation matrix about X-axis.
The returned matrix rotates a vector counterclockwise about the X-axis by the specified angle in radians. The same matrix rotates a coordinate system clockwise by the same angle.
- static y_rotation(angle, *, recursive=True)[source]
A rotation matrix about Y-axis.
The returned matrix rotates a vector counterclockwise about the Y-axis by the specified angle in radians. The same matrix rotates a coordinate system clockwise by the same angle.
- Parameters:
(Scalar (angle) – The rotation angle in radians.
array-like – The rotation angle in radians.
float (or) – The rotation angle in radians.
recursive (bool, optional) – True to include derivatives in the result.
- Returns:
A rotation matrix about the Y-axis.
- Return type:
- Raises:
ValueError – If the angle has an invalid unit
- static z_rotation(angle, *, recursive=True)[source]
A rotation matrix about Z-axis.
The returned matrix rotates a vector counterclockwise about the Z-axis by the specified angle in radians. The same matrix rotates a coordinate system clockwise by the same angle.
- Parameters:
angle – The rotation angle in radians.
recursive (bool, optional) – True to include derivatives in the result.
- Returns:
A rotation matrix about the Z-axis.
- Return type:
- Raises:
ValueError – If the angle has an invalid unit
- class Pair(*values, **keywords)[source]
Bases:
VectorRepresent coordinate pairs or 2-vectors in the PolyMath framework.
This class provides specialized functionality for working with 2-element vectors, including coordinate pair operations and 2D transformations.
- HALF = Pair(0.5 0.5)
- IDENTITY = Pair([[1. 0.] [0. 1.]]; denom=(2,))
- INT00 = Pair(0 0)
- INT11 = Pair(1 1)
- MASKED = Pair(-- --; mask)
- ONES = Pair(1. 1.)
- XAXIS = Pair(1. 0.)
- YAXIS = Pair(0. 1.)
- ZERO = Pair(0. 0.)
- ZEROS = Pair(0. 0.)
- angle(*, recursive=True)[source]
The polar angle of this Pair measured from the X-axis toward the Y-axis.
The returned value will always fall between zero and 2*pi.
- Parameters:
recursive (bool, optional) – True to include the derivatives.
- Returns:
The angle in radians, between 0 and 2π.
- Return type:
- static as_pair(arg, *, recursive=True)[source]
Convert the argument to Pair if possible.
- Parameters:
arg (object) – The object to convert to Pair.
recursive (bool, optional) – If True, derivatives will also be converted.
- Returns:
The converted Pair object.
- Return type:
Notes
As a special case, as_pair() of a single value returns a Pair with the value repeated.
- clip2d(lower, upper, *, remask=False)[source]
A copy with values clipped to fall within 2D limits.
Values get moved to the nearest location within a rectangle defined by the lower and upper limits.
- Parameters:
lower (Pair or None) – Coordinates of the lower limit. None or masked value to ignore.
upper (Pair or None) – Coordinates of the upper limit (inclusive). None or a masked value to ignore.
remask (bool, optional) – True to include the new mask into the object’s mask; False to replace the values but leave them unmasked.
- Returns:
A new Pair with values clipped to the specified limits.
- Return type:
- Raises:
ValueError – If lower or upper has more than two values.
- static from_scalars(x, y, *, recursive=True, readonly=False)[source]
Construct a Pair by combining two scalars.
- Parameters:
x (Scalar or convertible) – First component of the pair.
y (Scalar or convertible) – Second component of the pair.
recursive (bool, optional) – True to include all the derivatives. The returned object will have derivatives representing the union of all the derivatives found amongst the scalars.
readonly (bool, optional) – True to return a read-only object; False to return something potentially writable.
- Returns:
A new Pair object constructed from the two scalars.
- Return type:
Notes
Input arguments need not have the same shape, but it must be possible to cast them to the same shape. A value of None is converted to a zero-valued Scalar that matches the denominator shape of the other arguments.
- class Polynomial(*values, **keywords)[source]
Bases:
VectorRepresent polynomials in the PolyMath framework.
This is a Vector subclass in which the elements are interpreted as the coefficients of a polynomial in a single variable x. Coefficients appear in order of decreasing exponent. Mathematical operations, polynomial root-solving are supported. Coefficients can have derivatives and these can be used to determine derivatives of the values or roots.
- __add__(arg)[source]
Add this polynomial to another polynomial or scalar.
- Parameters:
arg – The polynomial or scalar to add to this polynomial.
- Returns:
The sum of the polynomials.
- Return type:
- __eq__(arg)[source]
Check if this polynomial equals another polynomial.
- Parameters:
arg – The polynomial to compare with this polynomial.
- Returns:
True if the polynomials are equal, False otherwise.
- Return type:
bool
- __iadd__(arg)[source]
Add another polynomial to this polynomial in-place.
- Parameters:
arg – The polynomial to add to this polynomial.
- Returns:
This polynomial modified in-place.
- Return type:
- __imul__(arg)[source]
Multiply this polynomial by another polynomial or scalar in-place.
- Parameters:
arg – The polynomial or scalar to multiply with this polynomial.
- Returns:
This polynomial modified in-place.
- Return type:
- __init__(*args, **kwargs)[source]
Initialize a Polynomial object.
- Parameters:
*args – Arguments to pass to the Vector constructor. If a single argument is a subclass of Vector, it is quickly converted to class Polynomial.
**kwargs – Keyword arguments to pass to the Vector constructor.
Notes
If a single argument is a subclass of Vector, it is quickly converted to class Polynomial. Otherwise, the constructor takes the same inputs as the constructor for class Vector.
- __isub__(arg)[source]
Subtract another polynomial from this polynomial in-place.
- Parameters:
arg – The polynomial to subtract from this polynomial.
- Returns:
This polynomial modified in-place.
- Return type:
- __itruediv__(arg)[source]
Divide this polynomial by another polynomial or scalar in-place.
- Parameters:
arg – The polynomial or scalar by which to divide this polynomial.
- Returns:
This polynomial modified in-place.
- Return type:
- __mul__(arg)[source]
Multiply this polynomial by another polynomial or scalar.
- Parameters:
arg – The polynomial or scalar to multiply with this polynomial.
- Returns:
The product of the polynomials.
- Return type:
- Raises:
ValueError – If the polynomials have incompatible denominators.
- __ne__(arg)[source]
Check if this polynomial does not equal another polynomial.
- Parameters:
arg – The polynomial to compare with this polynomial.
- Returns:
True if the polynomials are not equal, False otherwise.
- Return type:
bool
- __neg__()[source]
Return the negation of this polynomial.
- Returns:
The negated polynomial.
- Return type:
- __pow__(arg)[source]
Raise this polynomial to the specified power.
- Parameters:
arg – The exponent (must be a non-negative integer).
- Returns:
This polynomial raised to the specified power.
- Return type:
- Raises:
ValueError – If the exponent is negative or not an integer.
- __radd__(arg)[source]
Add this polynomial to another polynomial or scalar (right addition).
- Parameters:
arg – The polynomial or scalar to add to this polynomial.
- Returns:
The sum of the polynomials.
- Return type:
- __rmul__(arg)[source]
Multiply another polynomial or scalar by this polynomial.
- Parameters:
arg – The polynomial or scalar to multiply with this polynomial.
- Returns:
The product of the polynomials.
- Return type:
- __rsub__(arg)[source]
Subtract this polynomial from another polynomial or scalar.
- Parameters:
arg – The polynomial or scalar from which to subtract this polynomial.
- Returns:
The difference of the polynomials.
- Return type:
- __sub__(arg)[source]
Subtract another polynomial or scalar from this polynomial.
- Parameters:
arg – The polynomial or scalar to subtract from this polynomial.
- Returns:
The difference of the polynomials.
- Return type:
- __truediv__(arg)[source]
Divide this polynomial by another polynomial or scalar.
- Parameters:
arg – The polynomial or scalar by which to divide this polynomial.
- Returns:
The quotient of the polynomials.
- Return type:
- static as_polynomial(arg, *, recursive=True)[source]
A shallow copy of the given object as class Polynomial.
- Parameters:
arg – Object to convert to Polynomial.
recursive (bool, optional) – True to include derivatives in the conversion.
- Returns:
The converted object as a Polynomial.
- Return type:
- as_vector(*, recursive=True)[source]
A shallow copy of this Polynomial as class Vector.
- Parameters:
recursive (bool, optional) – True to include derivatives in the conversion.
- Returns:
This polynomial converted to a Vector.
- Return type:
- at_least_order(order, *, recursive=True)[source]
A shallow copy with at least this minimum order.
Extra leading polynomial coefficients are filled with zeros.
- Parameters:
order (int) – Minimum order of the Polynomial.
recursive (bool, optional) – True to include derivatives in the conversion.
- Returns:
A copy with at least the specified minimum order.
- Return type:
- deriv(recursive=True)[source]
Return the first derivative of this Polynomial.
- Parameters:
recursive (bool, optional) – True to evaluate derivatives as well. Defaults to True.
- Returns:
The derivative polynomial.
- Return type:
- eval(x, recursive=True)[source]
Evaluate the polynomial at x.
- Parameters:
x – Scalar at which to evaluate the Polynomial.
recursive (bool, optional) – True to evaluate derivatives as well. Defaults to True.
- Returns:
- A Scalar of values. Note that the shapes of self and x are
broadcasted together.
- Return type:
- invert_line(*, recursive=True)[source]
The inversion of this linear polynomial.
- Parameters:
recursive (bool, optional) – True to include derivatives in the conversion.
- Returns:
The inverted linear polynomial.
- Return type:
- Raises:
ValueError – If the polynomial is not first-order.
- property order
The order of the polynomial, i.e., the largest exponent.
- Returns:
The order of the polynomial.
- Return type:
int
- roots(recursive=True)[source]
Find the roots of the polynomial.
- Parameters:
recursive (bool, optional) – True to evaluate derivatives at the roots as well. Defaults to True.
- Returns:
- A Scalar of roots. This has the same shape as self but an extra
leading axis matching the order of the polynomial. The leading index selects among the roots of the polynomial. Roots appear in increasing order and without any duplicates. If fewer real roots exist, the set of roots is padded at the end with masked values.
- Return type:
- Raises:
ValueError – If the polynomial is of order zero.
- set_order(order, *, recursive=True)[source]
This Polynomial expressed with exactly this order.
Extra polynomial coefficients are filled with zeros. If this Polynomial exceeds this order requested, raise an exception.
- Parameters:
order (int) – Exact order of the Polynomial.
recursive (bool, optional) – True to include derivatives in the conversion.
- Returns:
A copy with exactly the specified order.
- Return type:
- Raises:
ValueError – If this Polynomial exceeds the order requested.
- class Quaternion(*values, **keywords)[source]
Bases:
VectorRepresent quaternions and support conversions between rotation representations.
This class handles quaternions and supports conversions between quaternions, rotation matrices, and sets of Euler angles.
- IDENTITY = Quaternion(1. 0. 0. 0.)
- MASKED = Quaternion(-- -- -- --; mask)
- XAXIS = Quaternion(0. 1. 0. 0.)
- YAXIS = Quaternion(0. 0. 1. 0.)
- ZAXIS = Quaternion(0. 0. 0. 1.)
- ZERO = Quaternion(0. 0. 0. 0.)
- __mul__(arg, *, recursive=True)[source]
The product of this quaternion and another object.
- Parameters:
arg – The object to multiply with this quaternion.
recursive (bool, optional) – If True, the returned object will include derivatives.
- Returns:
The product of this quaternion and the argument.
- Return type:
- Raises:
ValueError – If both this quaternion and arg have denominators.
- __rmul__(arg, *, recursive=True)[source]
The product of another object and this quaternion.
- Parameters:
arg – The object to multiply with this quaternion.
recursive (bool, optional) – If True, the returned object will include derivatives.
- Returns:
The product of the argument and this quaternion.
- Return type:
- __truediv__(arg, *, recursive=True)[source]
The result of dividing this quaternion by another object.
- Parameters:
arg – The object to divide this quaternion by.
recursive (bool, optional) – If True, the returned object will include derivatives.
- Returns:
The result of dividing this quaternion by the argument.
- Return type:
- static as_quaternion(arg, *, recursive=True)[source]
Convert the argument to a Quaternion if possible.
- Parameters:
arg (object) – The object to convert to Quaternion.
recursive (bool, optional) – If True, derivatives will also be converted.
- Returns:
The converted Quaternion object.
- Return type:
- conj(*, recursive=True)[source]
The complex conjugate of this quaternion.
The conjugate of a quaternion [s, v] is [s, -v], where s is the scalar part and v is the vector part.
- Parameters:
recursive (bool, optional) – If True, derivatives will also be conjugated.
- Returns:
The conjugate quaternion.
- Return type:
- static from_euler(ai, aj, ak, axes='rzxz')[source]
Construct a Quaternion from Euler rotation angles.
- Parameters:
ai (scalar) – First rotation angle in radians.
aj (scalar) – Second rotation angle in radians.
ak (scalar) – Third rotation angle in radians.
axes (str, optional) – One of 24 axis sequences as string or encoded tuple.
- Returns:
A quaternion representing the specified rotation.
- Return type:
Notes
A triple of Euler angles can be applied/interpreted in 24 ways, which can be specified using a 4-character string or encoded 4-tuple:
- Axes 4-string*: e.g. ‘sxyz’ or ‘ryxy’
First character: rotations are applied to ‘s’tatic or ‘r’otating frame
Remaining characters: successive rotation axis ‘x’, ‘y’, or ‘z’
- Axes 4-tuple*: e.g. (0, 0, 0, 0) or (1, 1, 1, 1)
inner axis: code of axis (‘x’:0, ‘y’:1, ‘z’:2) of rightmost matrix.
parity: even (0) if inner axis ‘x’ is followed by ‘y’, ‘y’ is followed by ‘z’, or ‘z’ is followed by ‘x’. Otherwise odd (1).
repetition: first and last axis are same (1) or different (0).
frame: rotations are applied to static (0) or rotating (1) frame.
>>> q = quaternion_from_euler(1, 2, 3, 'ryxz') >>> numpy.allclose(q, [0.435953, 0.310622, -0.718287, 0.444435]) True
- static from_euler_via_matrix(ai, aj, ak, axes='rzxz')[source]
Construct a Quaternion from Euler angles via an intermediate Matrix3.
- Parameters:
ai (scalar) – First rotation angle in radians.
aj (scalar) – Second rotation angle in radians.
ak (scalar) – Third rotation angle in radians.
axes (str, optional) – One of 24 axis sequences as string or encoded tuple.
- Returns:
A quaternion representing the specified rotation.
- Return type:
Notes
This method uses the Matrix3.from_euler() method, and then converts the result to a Quaternion.
- static from_matrix3(matrix, *, recursive=True)[source]
Convert a Matrix3 to a Quaternion.
- Parameters:
matrix (Matrix3) – The rotation matrix to convert.
recursive (bool, optional) – If True, the returned Quaternion will include derivatives. Note that this feature is not currently implemented and will raise NotImplementedError.
- Returns:
A quaternion representing the same rotation as the input matrix.
- Return type:
- Raises:
NotImplementedError – If recursive is True and matrix has derivatives.
- static from_parts(scalar, vector, *, recursive=True)[source]
Construct a Quaternion from separate scalar and vector components.
- Parameters:
- Returns:
A new Quaternion constructed from the scalar and vector parts.
- Return type:
- Raises:
ValueError – If scalar and vector denominators are incompatible.
- static from_rotation(angle, vector, *, recursive=True)[source]
Construct a Quaternion for an angular rotation about an axis vector.
- Parameters:
- Returns:
A new Quaternion representing the specified rotation.
- Return type:
- identity()[source]
The identity-valued Quaternion.
This method overrides
identity()for the base class.- Returns:
A read-only identity quaternion [1,0,0,0].
- Return type:
- static mul_values(a, b)[source]
Multiply two quaternion arrays element-wise.
- Parameters:
a (ndarray) – First quaternion array.
b (ndarray) – Second quaternion array.
- Returns:
The product of the two quaternion arrays.
- Return type:
ndarray
- reciprocal(*, recursive=True)[source]
The reciprocal of this quaternion.
- Parameters:
recursive (bool, optional) – True to return the derivatives of the reciprocal too; otherwise, derivatives are removed.
- Returns:
The quaternion reciprocal (conjugate divided by norm squared).
- Return type:
- to_euler(axes='rzxz')[source]
Extract Euler angles from this quaternion.
- Parameters:
axes (str, optional) – One of 24 axis sequences as string or encoded tuple.
- Returns:
A tuple of three Scalars containing the Euler angles.
- Return type:
tuple
Notes
This method uses the to_matrix3() method, and then from_matrix3() method on the result.
- to_matrix3(*, recursive=True, partials=False)[source]
Convert this Quaternion to a rotation Matrix3.
- Parameters:
recursive (bool, optional) – If True, the returned Matrix3 will contain derivatives of the Quaternion. These are represented as Matrix objects, not Matrix3 objects, because they are not unitary.
partials (bool, optional) – If True, instead of returning just the Matrix3, return a tuple containing the Matrix3 and its (3x3x4) partial derivatives with respect to the components of the quaternion.
- Returns:
If partials is False, returns a Matrix3 representing the rotation. If partials is True, returns a tuple of (Matrix3, partial_derivatives).
- Return type:
Matrix3 or tuple
- Raises:
ValueError – If this Quaternion has denominator axes.
- to_parts(*, recursive=True)[source]
Split the Quaternion into its scalar and vector components.
- Parameters:
recursive (bool, optional) – If True, derivatives will also be split.
- Returns:
A tuple containing (scalar_part, vector_part) where scalar_part is a Scalar and vector_part is a Vector3.
- Return type:
tuple
- to_rotation(*, recursive=True)[source]
Extract the rotation angle and unit vector defined by this Quaternion.
- Parameters:
recursive (bool, optional) – If True, derivatives will be included.
- Returns:
A tuple containing (angle, unit_vector) where angle is a Scalar representing the rotation angle in radians, and unit_vector is a Vector3 representing the rotation axis.
- Return type:
tuple
- class Qube(*values, **keywords)[source]
Bases:
objectThe base class for all PolyMath subclasses.
The PolyMath subclasses, e.g., Scalar, Vector3, Matrix3, etc., define one or more possibly multidimensional items. Unlike NumPy ndarrays, this class makes a clear distinction between the dimensions associated with the items and any additional, leading dimensions that define an array of such items.
The “shape” is defined by the leading axes only, so a 2x2 array of 3x3 matrices would have shape (2,2,3,3) according to NumPy but has shape (2,2) according to PolyMath. Standard NumPy rules of broadcasting apply, but only on the array dimensions, not on the item dimensions. In other words, you can multiply a (2,2) array of 3x3 matrices by a (5,1,2) array of 3-vectors, yielding a (5,2,2) array of 3-vectors.
PolyMath objects are designed as lightweight wrappers on NumPy ndarrays. All standard mathematical operators and indexing/slicing options are defined. One can generally mix PolyMath arithmetic with scalars, NumPy ndarrays, NumPy MaskedArrays, or anything array-like.
In every object, a boolean mask is maintained in order to identify undefined array elements. Operations that would otherwise raise errors such as 1/0 and sqrt(-1) are masked out so that run-time errors can be avoided. See more about masks below.
PolyMath objects also support embedded units using the Unit class. However, the internal values in a PolyMath object are always held in standard units of kilometers, seconds and radians, or arbitrary combinations thereof. The unit is primarily used to affect the appearance of numbers during input and output.
PolyMath objects can be either read-only or read-write. Read-only objects are prevented from modification to the extent that Python makes this possible. Operations on read-only objects should always return read-only objects.
PolyMath objects can track associated derivatives and partial derivatives, which are represented by other PolyMath objects. Mathematical operations generally carry all derivatives along so that, for example, if x.d_dt is the derivative of x with respect to t, then x.sin().d_dt will be the derivative of sin(x) with respect to t.
The denominators of partial derivatives are represented by splitting the item shape into a numerator shape plus a denominator shape. As a result, for example, the partial derivatives of a Vector3 object (item shape (3,)) with respect to a Pair (item shape (2,)) will have overall item shape (3,2).
The PolyMath subclasses generally do not constrain the shape of the denominator, just the numerator. As a result, the aforementioned partial derivatives can still be represented by a Vector3 object.
- Properties:
- shape (tuple):
The leading axes of the object, i.e., those that are not considered part of the items.
- rank (int):
The number of axes belonging to the items.
- nrank (int):
The number of numerator axes associated with the items.
- drank (int):
The number of denominator axes associated with the items.
- item (tuple):
The shape of the individual items.
- numer (tuple):
The shape of the numerator items.
- denom (tuple):
The shape of the denominator items.
- values (numpy.ndarray, float, int, or bool):
The object’s data, with shape object.shape + object.item. If the object has a unit, then the values are in default units (km, sec, etc.) rather than in the specified unit.
- vals (numpy.ndarray, float, int, or bool):
Alternative name for values.
- mask (numpy.ndarray or bool):
The array’s mask. A scalar False means the object is entirely unmasked; a scalar True means it is entirely masked. Otherwise, it is a boolean array of shape object.shape.
- unit (Unit or None):
The unit of the array, if any. None indicates no unit.
- derivs (dict):
A dictionary of the names and values of any derivatives, each represented by additional PolyMath object.
- readonly (bool):
True if the object cannot (or at least should not) be modified. A determined user may be able to alter a read-only object, but the API makes this more difficult.
- size (int):
The number of elements in the shape.
- isize (int):
The number of elements in each item.
- nsize (int):
The number of elements in the numerator of the items.
- dsize (int):
The number of elements in the denominator of the items.
- __abs__(*, recursive=True)
abs(self), element-by-element absolute value.
- Parameters:
recursive (bool, optional) – True to include derivatives in return.
- Returns:
The result.
- Return type:
- __add__(arg, *, recursive=True)
self + arg, element-by-element addition.
- __and__(arg)
self & arg, element-by-element logical “and”.
- __array_priority__ = 1
- __bool__()
True if nonzero, otherwise False, element by element.
This method also supports “if a == b: …” and “if a != b: …” statements using the internal attributes _truth_if_all and _truth_if_any. In this case, equality requires that every unmasked element of a and b be equal and both objects be masked at the same locations.
Comparison of objects of shape () is also supported.
Any other if-test involving PolyMath objects requires an explict call to all() or any().
- Returns:
True where the elements of self are nonzero or True.
- Return type:
- __eq__(arg)
self == arg, element by element.
- __float__()
This object as a single float.
- __floordiv__(arg)
self // arg, element-by-element floor division.
Cases of divide-by-zero are masked. Derivatives are ignored.
- __ge__(arg)
self >= arg, element by element.
This general method always raises ValueError. It is overriden by
Scalar.__ge__()andBoolean.__ge__().
- __getitem__(indx)
- __getstate__()
The state is defined by a dictionary containing most of the Qube attributes.
“_cache” is removed.
“_mask”, and “_values” are replaced by encodings, as discussed below.
“PICKLE_VERSION” is added, with a value defined by the current version.
New attribute “MASK_ENCODING” is a list of the steps that have been applied to the mask. Each item in the list is a tuple, one of:
(‘CORNERS’, corners), where corners is the tuple returned by Qube._find_corners()
(‘BOOL’, shape, size), where the mask has been converted to packed bits and BZ2-compressed; shape is its final shape; size is its final size.
The list will be empty if no compression has been applied.
New attribute “VALS_ENCODING” is a list of the steps that have been applied to the values. Each item in the list is a tuple, one of: * (‘ALL_MASKED’,) if the object is fully masked, so no values are saved. * (‘ANTIMASKED’,) if the antimask has been applied. * (‘FLOAT’, digits, reference) for any floating-point compression performed. * (‘BOOL’, shape, size) if packbits plus BZ2 compression was performed. * (‘INT’, shape) if BZ2 compression of integers was performed.
- __gt__(arg)
self > arg, element by element.
This general method always raises ValueError. It is overriden by
Scalar.__gt__()andBoolean.__gt__().
- __iadd__(arg)
self += arg, element-by-element in-place addition.
- __iand__(arg)
self &= arg, element-by-element in-place logical “and”.
- __ifloordiv__(arg)
self //= arg, element-by-element in-place floor division.
Cases of divide-by-zero are masked. Derivatives are ignored.
- __imod__(arg)
self %= arg, element-by-element in-place modulus.
Cases of divide-by-zero are masked. Derivatives in the numerator are supported, but not in the denominator.
- __imul__(arg)
Element-by-element in-place multiplication.
- __init__(arg, mask=False, *, derivs={}, unit=None, nrank=None, drank=None, example=None, default=None, op='')[source]
Default constructor.
- Parameters:
arg (Qube, array-like, float, in, or bool) – An object to define the numeric value(s) of the returned object. If this object is read-only, then the returned object will be entirely read-only. Otherwise, the object will be read-writable. The values are generally given in standard units of km, seconds and radians, regardless of the specified unit.
mask (Boolean, array-like, or bool, optional) – The mask for the object. Use None to copy the mask from the example object. False (the default) leaves the object un-masked.
derivs (dict, optional) – Derivatives represented as PolyMath objects. Use None to make a copy of the derivs attribute of the example object, or {} (the default) for no derivatives. All derivatives are broadcasted to the shape of the object if necessary.
unit (Unit, optional) – The unit of the object. Use None to infer the unit from the example object; use False to suppress the unit.
nrank (int, optional) – The number of numerator axes in the returned object; None to derive the rank from the input data and/or the subclass.
drank (int, optional) – The number of denominator axes in the returned object; None to derive it from the input data and/or the subclass.
example (Qube, optional) – Another Qube object from which to copy any input arguments except derivs that have not been explicitly specified.
default (array-like, float, int, or bool) – Value to use where masked. This is typically a constant that will not “break” most arithmetic calculations. If it is an array, it must be of the same shape as the items.
op (str, optional) – Name of an operation to include in an error message if something goes wrong.
- Raises:
TypeError – If the data type of arg or mask is invalid.
TypeError – If example is not an instance of Qube.
ValueError – If the shape of mask is incompatible with object.
ValueError – If derivs or unit are specified but are disallowed by the Qube subclass.
ValueError – If nrank is incompatible with the Qube subclass.
ValueError – If drank is specified but the Qube subclass disallows derivatives.
ValueError – If the dimensions of arg are incompatible with the subclass.
- __int__()
This object as a single int; floats always round down.
- __invert__()
~self, unary inversion, element by element.
This is boolean “not”, not bit inversion.
- __ior__(arg)
self &= arg, element-by-element in-place logical “or”.
- __isub__(arg)
self -= arg, element-by-element in-place subtraction.
- __iter__()
Return an iterator over the first axis of this object.
- Returns:
An iterator that iterates over the first axis of the object.
- Return type:
QubeIterator
- __itruediv__(arg)
self /= arg, element-by-element in-place division.
Cases of divide-by-zero are masked.
- __ixor__(arg)
self ^= arg, element-by-element in-place logical exclusive “or”.
- __le__(arg)
self <= arg, element by element.
This general method always raises ValueError. It is overriden by
Scalar.__le__()andBoolean.__le__().
- __len__()
Number of elements along first axis.
- __lt__(arg)
self < arg, element by element.
This general method always raises ValueError. It is overriden by
Scalar.__lt__()andBoolean.__lt__().
- __mod__(arg, *, recursive=True)
self % arg, element-by-element modulus.
Cases of divide-by-zero are masked. Derivatives in the numerator are supported, but not in the denominator.
- __mul__(arg, *, recursive=True)
self * arg, element-by-element multiplication.
- __ne__(arg)
self != arg, element by element.
- __neg__(*, recursive=True)
-self, element-by-element negation.
- Parameters:
recursive (bool, optional) – True to include derivatives in return.
- Returns:
The result.
- Return type:
- static __new__(subtype, *values, **keywords)[source]
Create a new, un-initialized object given a Qube subclass.
- __or__(arg)
self | arg, element-by-element logical “or”.
- __pos__(*, recursive=True)
+self, element by element.
- Parameters:
recursive (bool, optional) – True to include derivatives in return.
- Returns:
The result.
- Return type:
- __pow__(arg)
arg ** self, element-by-element exponentiation.
Derivatives are not supported.
This general method supports single integer exponents between -15 and 15 are handled using repeated multiplications. It will handle any class that supports __mul__() (and reciprocal() if the exponent is negative), such as Matrix objects and Quaternions.
It is overridden by Scalar to obtain the normal behavior of the “**” operator.
- __radd__(arg, *, recursive=True)
arg + self, element-by-element addition.
- __rand__(arg)
arg & self, element-by-element logical “and”.
- __repr__()[source]
Express the value as a string.
The format of the returned string is Class([value, value, …], suffixes, …), where the quanity inside square brackets is the result of str() applied to a NumPy ndarray.
The suffixes are, in order…
“denom=(shape)” if the object has a denominator;
“mask” if the object has a mask
the name of the unit of the object has a unit
the names of all the derivatives in alphabetical order
- Returns:
String representation
- Return type:
str
- __rfloordiv__(arg)
arg // self, element-by-element floor division.
Cases of divide-by-zero are masked. Derivatives are ignored.
- __rmod__(arg, *, recursive=True)
arg % self, element-by-element modulus.
Cases of divide-by-zero are masked. Derivatives in the numerator are supported, but not in the denominator.
- __rmul__(arg, *, recursive=True)
arg * self, element-by-element multiplication.
- __ror__(arg)
arg | self, element-by-element logical “or”.
- __rsub__(arg, *, recursive=True)
arg - self, element-by-element subtraction.
- __rtruediv__(arg, *, recursive=True)
arg / self, element-by-element division.
Cases of divide-by-zero are masked.
- __rxor__(arg)
arg | self, element-by-element logical exclusive “or”.
- __setitem__(indx, arg)
- __setstate__(state)
- __str__()[source]
Express the value as a string.
The format of the returned string is Class([value, value, …], suffixes, …), where the quanity inside square brackets is the result of str() applied to a NumPy ndarray.
The suffixes are, in order…
“denom=(shape)” if the object has a denominator;
“mask” if the object has a mask
the name of the unit of the object has a unit
the names of all the derivatives in alphabetical order
- Returns:
String representation
- Return type:
str
- __sub__(arg, *, recursive=True)
self - arg, element-by-element subtraction.
- __truediv__(arg, *, recursive=True)
self / arg, element-by-element division.
Cases of divide-by-zero are masked.
- __xor__(arg)
self | arg, element-by-element logical exclusive “or”.
- abs()
abs(self), element-by-element absolute value.
- all(axis=None, *, builtins=None, masked=None, out=None)
True if all the unmasked items are nonzero.
- Parameters:
axis (int or tuple, optional) – Axis or a tuple of axes. The any operation is performed across these axes, leaving any remaining axes in the returned value. If None (the default), then the any operation is performed across all axes of the object.
builtins (bool, optional) – If True and the result is a single unmasked scalar, the result is returned as a Python boolean instead of as an instance of Boolean. Default is to use the global setting defined by Qube.prefer_builtins().
masked (bool, optional) – The value to return if builtins is True but the returned value is masked. Default is to return a masked Boolean instead of a builtin type in this case.
out (any, optional) – Ignored. This enables “np.any(Qube)” to work.
- all_true_or_masked(axis=None, *, builtins=None)
True if all of the items are nonzero or masked.
This differs from the all() method in how it handles the case of every value being masked. This method returns True, whereas all() returns a masked Boolean value.
- Parameters:
axis (int or tuple, optional) – Axis or a tuple of axes. The any operation is performed across these axes, leaving any remaining axes in the returned value. If None (the default), then the any operation is performed across all axes of the object.
builtins (bool, optional) – If True and the result is a single unmasked scalar, the result is returned as a Python boolean instead of as an instance of Boolean. Default is to use the global setting defined by Qube.prefer_builtins().
- static and_(*masks)[source]
The logical “and” of two or more masks, avoiding array operations if possible.
- Parameters:
*masks (array-like or bool) – One or more boolean masks.
- Returns:
New mask array or bool.
- Return type:
(np.ndarray or bool)
- property antimask
The inverse of the mask of this object, True wherever an element is valid.
- any(axis=None, *, builtins=None, masked=None, out=None)
True if any of the unmasked items are nonzero.
- Parameters:
axis (int or tuple, optional) – Axis or a tuple of axes. The any operation is performed across these axes, leaving any remaining axes in the returned value. If None (the default), then the any operation is performed across all axes of the object.
builtins (bool, optional) – If True and the result is a single unmasked scalar, the result is returned as a Python boolean instead of as an instance of Boolean. Default is to use the global setting defined by Qube.prefer_builtins().
masked (bool, optional) – The value to return if builtins is True but the returned value is masked. Default is to return a masked Boolean instead of a builtin type in this case.
out (any, optional) – Ignored. This enables “np.any(Qube)” to work.
- Returns:
Result of operation.
- Return type:
(Boolean or bool)
- any_true_or_masked(axis=None, *, builtins=None)
True if any of the items are nonzero or masked.
This differs from the any() method in how it handles the case of every value being masked. This method returns True, whereas any() returns a masked Boolean value.
- Parameters:
axis (int or tuple, optional) – Axis or a tuple of axes. The any operation is performed across these axes, leaving any remaining axes in the returned value. If None (the default), then the any operation is performed across all axes of the object.
builtins (bool, optional) – If True and the result is a single unmasked scalar, the result is returned as a Python boolean instead of as an instance of Boolean. Default is to use the global setting defined by Qube.prefer_builtins().
- as_all_constant(constant=None, *, recursive=True)[source]
A shallow, read-only copy of this object with constant values.
Derivatives are all set to zero. The mask is unchanged.
- Parameters:
constant (array-like, float, int, or bool, optional) – The constant value for each item. This must have the same shape as this object’s items. Use None for values of zero appropriate to the Qube subclass.
- Returns:
A shallow copy of this object with constant values.
- Return type:
- as_all_masked(*, recursive=True)[source]
A shallow copy of this object with everything masked.
- Parameters:
recursive (bool, optional) – True to mask any derivatives; False to strip derivatives.
- Returns:
This object but fully masked.
- Return type:
- as_bool(copy=False, builtins=False)[source]
A boolean version of this object.
Scalars are converted to Booleans.
- Parameters:
copy (bool, optional) – True to ensure that a new object with an independent copy of the values is returned.
builtins (bool, optional) – True to return a Python float if the returned value has shape (), is unmasked, and has no derivatives.
- Returns:
- A copy of object converted to bools; if the values are already bools and
copy is False, this object is returned unchanged.
- Return type:
- Raises:
TypeError – If this object cannot contain bools.
- as_builtin(masked=None)[source]
This object as a Python built-in class (float, int, or bool) if the conversion can be done without loss of information.
- Parameters:
masked (float, int, or bool, optional) – Value to return if the shape of this object is () and it is masked.
- Returns:
This object’s values attribute if its shape is () and it is unmasked; the value of masked if the shape is () and it is masked; otherwise, this object.
- Return type:
(Qube, float, int, bool, or None)
- static as_diagonal(arg, axis, classes=(), recursive=True)
Return a copy with one axis converted to a diagonal across two.
- Parameters:
arg (Qube) – The object to convert.
axis (int) – The item axis to convert to two.
classes (class, list, or tuple, optional) – The class of the object returned. If a list is provided, the object will be an instance of the first suitable class in the list. Otherwise, a generic Qube object will be returned.
recursive (bool, optional) – True to include derivatives in the returned object.
- Returns:
A copy with the specified axis converted to a diagonal.
- Return type:
- Raises:
ValueError – If the axis is out of range.
- as_float(*, recursive=True, copy=False, builtins=False)[source]
A floating-point version of this object.
Booleans are converted to Scalars.
- Parameters:
recursive (bool, optional) – True to include any derivatives; False to remove them.
copy (bool, optional) – True to ensure that a new object with an independent copy of the values is returned.
builtins (bool, optional) – True to return a Python float if the returned value has shape (), is unmasked, and has no derivatives.
- Returns:
The result.
- Return type:
- Raises:
TypeError – If this object cannot contain floats.
- as_int(copy=False, builtins=False)[source]
An integer version of this object.
Booleans are converted to Scalars.
- Parameters:
copy (bool, optional) – True to ensure that a new object with an independent copy of the values is returned.
builtins (bool, optional) – True to return a Python float if the returned value has shape (), is unmasked, and has no derivatives.
- Returns:
The result.
- Return type:
Qube or int
- Raises:
TypeError – If this object cannot contain integers.
- as_mask_where_nonzero()[source]
A boolean scalar or NumPy ndarray where values are nonzero and unmasked.
- as_mask_where_nonzero_or_masked()[source]
A boolean scalar or NumPy ndarray where values are nonzero or masked.
- as_mask_where_zero_or_masked()[source]
A boolean scalar or NumPy ndarray where values are zero or masked.
- as_numeric(*, recursive=True)[source]
A numeric version of this object.
Booleans are converted to Scalars.
- Parameters:
recursive (bool, optional) – True to include any derivatives; False to remove them.
- Returns:
This object if it is already numeric; a Boolean is converted to a Scalar.
- Return type:
- as_one_masked(*, recursive=True)[source]
This object reduced to shape () and masked.
- Parameters:
recursive (bool, optional) – True to mask any derivatives; False to strip derivatives.
- Returns:
This object but fully masked and with shape ()
- Return type:
- as_readonly(*, recursive=True)[source]
Convert this object to read-only. It is modified in place and returned.
If this object is already read-only, it is returned as is. Otherwise, the internal _values and _mask arrays are modified as necessary. Once this happens, the internal arrays will also cease to be writable in any other object that shares them.
Note that as_readonly() cannot be undone. Use copy() to create a writable copy of a readonly object.
- Parameters:
recursive (bool, optional) – True also to convert the derivatives to read-only; False to strip the derivatives.
- Returns:
This object, converted to read-only if necessary.
- Return type:
- as_size_zero(axis=0, *, recursive=True)[source]
A shallow, read-only copy of this object with size zero.
- Parameters:
axis (int, optional) – The axis index (positive or negative) to collapse to length zero; the other axes are left unchanged. Use None for an object of shape (0,).
- Returns:
A shallow copy of this object with size zero.
- Return type:
- as_this_type(arg, *, recursive=True, coerce=True, op='')[source]
The argument converted to this class and data type.
If the object is already of the correct class and type, it is returned unchanged.
- Parameters:
arg (array-like, float, int, or bool) – The object to the class of this object. If the argument is a scalar or NumPy ndarray, a new instance of this object’s class is created.
recursive (bool, optional) – True to convert the derivatives as well.
coerce (bool, optional) – True to coerce the data type silently; False to leave the data type unchanged.
op (str, optional) – Name of operator to use in an error message.
- Returns:
The argument converted to the type of this object.
- Return type:
- broadcast(*, recursive=True, _protected=True)
Broadcast one or objects to their common shape.
Python scalars are returned unchanged because they already broadcast with anything.
- Parameters:
*objects (Qube, array-like, int, float, None, or tuple) – Zero or more array objects. Values of None are assigned shape (). A list or tuple is treated as the definition of an additional shape.
recursive (bool, optional) – True to broadcast the derivatives to the same shape; False to strip the derivatives from the returned objects.
_protected (bool, optional) – False to prevent the arrays being set to readonly. Note that this is a potentially dangerous option, because memory is shared among the elements within each of the returned objects.
- Returns:
A tuple of objects, all broadcased to the common shape. Python scalars are returned unchanged because they already broadcast with anything.
- Raises:
ValueError – If an object dimension is incompatible with the broadcast.
Notes
Returned objects must be treated as read-only because of the mechanism NumPy uses to broadcast arrays. The returned objects are marked read-only but their internal arrays are not protected.
- broadcast_into_shape(shape, *, recursive=True, _protected=True)
This object broadcasted to the specified shape. DEPRECATED name; use broadcast_to.
- Parameters:
shape (tuple) – The shape into which the object is to be broadcast.
recursive (bool, optional) – True to broadcast the derivatives as well. Otherwise, they are removed.
_protected (bool, optional) – False to prevent the arrays being set to readonly. Note that this is a potentially dangerous option, because some elements of the returned array share memory with one another and with the original object.
- Returns:
The broadcasted object; self if the shape already matches.
Notes
Both the original object and the returned array are normally set to read-only, because they share memory with one another and because memory is shared among the elements of the returned array. The _protected option overrides this, leaving both arrays writable.
- broadcast_to(shape, *, recursive=True, _protected=True)
This object broadcasted to the specified shape.
- Parameters:
shape (tuple) – The shape into which the object is to be broadcast.
recursive (bool, optional) – True to broadcast the derivatives as well. Otherwise, they are removed.
_protected (bool, optional) – False to prevent the arrays being set to readonly. Note that this is a potentially dangerous option, because some elements of the returned array share memory with one another and with the original object.
- Returns:
The broadcasted object; self if the shape already matches.
Notes
Both the original object and the returned array are normally set to read-only, because they share memory with one another and because memory is shared among the elements of the returned array. The _protected option overrides this, leaving both arrays writable.
- broadcasted_shape(*, item=())
The shape defined by a broadcast across the objects.
- Parameters:
*objects (Qube, array-like, int, float, None, or tuple) – Zero or more array objects. Values of None are assigned shape (). A list or tuple is treated as the definition of an additional shape.
item (list or tuple, optional) – A list or tuple to be appended to the shape. This makes it possible to use the returned shape in the declaration of a NumPy array containing items that are not scalars.
- Returns:
The broadcast shape, comprising the maximum value of each corresponding axis, with the item shape appended if any.
- Raises:
ValueError – If an object dimension is incompatible with the broadcast.
- cast(classes)[source]
A shallow copy of this object casted to another Qube subclass.
- Parameters:
classes (class or list) – A Qube subclass or list of subclasses. The object will be casted to the first suitable class in the list.
- Returns:
A shallow copy of this object. If the object is already of the selected class or if no suitable class is found, it is returned without modification.
- Return type:
- chain(arg)
The chain multiplication of this derivative by another.
Returns the denominator of the first object times the numerator of the second argument. The result will be an instance of the same class. This operation is never recursive.
- clip(lower, upper, *, remask=True, inclusive=True)
Return a copy with values clipped to fall within a pair of limits.
Values below the lower limit become equal to the lower limit; values above the upper limit become equal to the upper limit.
- Parameters:
lower (object, optional) – The numerical lower limit or an object of the same shape and type as this, containing lower limits. None or masked values to ignore.
upper (object, optional) – The numerical upper limit or an object of the same shape and type as this, containing upper limits. None or masked values to ignore.
remask (bool, optional) – True to leave the new values masked; False to replace the values but leave them unmasked.
inclusive (bool, optional) – True to leave values that exactly match the upper limit unmasked; False to mask them.
- Returns:
A copy with values clipped to the specified limits.
- Return type:
- Raises:
ValueError – If this object has denominators or item rank > 0.
- clone(*, recursive=True, preserve=[], retain_cache=False)[source]
Fast construction of a shallow copy.
- Parameters:
recursive (bool, optional) – True to clone the derivatives of this object; False to ignore them.
preserve (list, optional) – Name(s) of derivatives to include even if recursive is False.
retain_cache (bool, optional) – True to retain cache except “unshrunk” and “wod”; False to return clone with an empty cache.
- Returns:
The shallow clone.
- Return type:
- collapse_mask(*, recursive=True)[source]
A shallow copy where a mask entirely containing either True or False is converted to a single boolean.
- Parameters:
recursive (bool, optional) – True to collapse the mask of any derivatives.
- Returns:
A shallow copy of this object with a collapsed mask.
- Return type:
- copy(*, recursive=True, readonly=False)[source]
Deep copy operation with additional options.
- Parameters:
recursive (bool, optional) – True to copy the derivatives; False, to return an object without derivatives.
readonly (bool, optional) – True to return a read-only copy, or this object if it is already read-only. Otherwise, this return is guaranteed to be an entirely new copy, independent of this object and suitable for modification.
- Returns:
A copy of this object.
- Return type:
- property corners
Corners of a “hypercube” that contain all the unmasked array elements.
- Returns:
The first tuple defines the lower coordinates of the unmasked region, and the second tuple defines the upper coordinates.
- Return type:
(tuple, tuple)
- static cross(arg1, arg2, axis1=-1, axis2=0, *, classes=(), recursive=True)
Calculate the cross product of two objects.
Axis lengths must be either two or three, and must be equal. At least one of the objects must be lacking a denominator.
- Parameters:
arg1 (Qube) – The first operand.
arg2 (Qube) – The second operand.
axis1 (int, optional) – The item axis of the first object. Defaults to -1.
axis2 (int, optional) – The item axis of the second object. Defaults to 0.
classes (class, list, or tuple, optional) – The class of the object returned. If a list is provided, the object will be an instance of the first suitable class in the list. Otherwise, a generic Qube object will be returned.
recursive (bool, optional) – True to include derivatives in the returned object.
- Returns:
The cross product of the two objects.
- Return type:
- Raises:
ValueError – If both objects have denominators, if axes are out of range, or if axis lengths are incompatible.
- property default
The default element value for this object.
- delete_deriv(key, *, override=False)[source]
Delete a single derivative from this object, given the key.
Derivatives cannot be deleted from a read-only object without explicitly setting override=True.
- Parameters:
key (str) – The key of the derivative to remove. If the key does not exist, the object is unchanged.
override (bool, optional) – True to allow the deleting of derivatives from a read-only object.
- Raises:
ValueError – If this object is read-only and override is False.
- delete_derivs(*, override=False, preserve=None)[source]
Delete all derivatives from this object.
Derivatives cannot be deleted from a read-only object without explicitly setting override=True.
- Parameters:
override (bool, optional) – True to allow the deleting of derivatives from a read-only object.
preserve (list, tuple or set, optional) – The names of derivatives to retain. All others are removed.
- Raises:
ValueError – If this object is read-only and override is False.
- property denom
The shape of the element denominator in this object as a tuple.
- property derivs
The dictionary of derivatives of this object.
- static dot(arg1, arg2, axis1=-1, axis2=0, *, classes=(), recursive=True)
Calculate the dot product of two objects.
The axes must be in the numerator, and only one of the objects can have a denominator (which makes this suitable for first derivatives but not second derivatives).
- Parameters:
arg1 (Qube) – The first operand as a subclass of Qube.
arg2 (Qube) – The second operand as a subclass of Qube.
axis1 (int, optional) – The item axis of this object for the dot product. Default is -1.
axis2 (int, optional) – The item axis of the arg2 object for the dot product. Default is 0.
classes (class, list, or tuple, optional) – The class of the object returned. If a list is provided, the object will be an instance of the first suitable class in the list. Otherwise, a generic Qube object will be returned.
recursive (bool, optional) – True to include derivatives in the returned object.
- Returns:
The dot product of the two objects.
- Return type:
- Raises:
ValueError – If both objects have denominators or if axes are out of range.
- property drank
The rank of the element denominator in this object.
- property dsize
The number of denominator components in this object’s items.
- expand_mask(*, recursive=True)[source]
A shallow copy where a single mask value of True or False is converted to an array.
If the object’s mask is already an array, it is returned unchanged.
- Parameters:
recursive (bool, optional) – True to expand the mask of any derivatives.
- Returns:
A shallow copy of this object with an expanded mask.
- Return type:
- extract_denom(axis, index, classes=())
Extract an object from one denominator axis.
- Parameters:
axis (int) – The item axis from which to extract a slice.
index (int) – The index value at which to extract the slice.
classes (class, list, or tuple, optional) – The class of the object returned. If a list is provided, the object will be an instance of the first suitable class in the list. Otherwise, a generic Qube object will be returned.
- Returns:
An object extracted from the specified denominator axis.
- Return type:
- Raises:
ValueError – If the axis is out of range.
- extract_denoms()
A tuple of objects extracted from one object with a 1-D denominator.
Returns a list of objects with the same class as self, but drank = 0.
- Returns:
A list of objects with drank = 0.
- Return type:
list
- Raises:
ValueError – If the object does not have a 1-D denominator.
- extract_numer(axis, index, classes=(), *, recursive=True)
Extract an object from one numerator axis.
- Parameters:
axis (int) – The item axis from which to extract a slice.
index (int) – The index value at which to extract the slice.
classes (class, list, or tuple, optional) – The class of the object returned. If a list is provided, the object will be an instance of the first suitable class in the list. Otherwise, a generic Qube object will be returned.
recursive (bool, optional) – True to include matching slices of the derivatives in the returned object; otherwise, the returned object will not contain derivatives.
- Returns:
An object extracted from the specified numerator axis.
- Return type:
- Raises:
ValueError – If the axis is out of range.
- classmethod filled(shape, fill=0, *, numer=None, denom=(), mask=False)[source]
Internal object of this class and shape, filled with a constant.
- Parameters:
shape (tuple) – Shape of the object.
dtype (str, optional) – One of “bool”, “int”, or “float”, defining the data type. Ignored if cls has a default dtype.
numer (tuple, optional) – Numerator shape; None to use default for cls.
denom (tuple, optional) – Denominator shape.
mask (array-like or bool, optional) – Mask to apply.
- Returns:
The new object.
- Return type:
- Raises:
ValueError – If fill is not compatible with the cls.
- flatten(*, recursive=True)
Return a shallow copy of the object flattened to one dimension.
- Parameters:
recursive (bool, optional) – True to apply the same flattening to the derivatives. Otherwise, derivatives are deleted from the returned object.
- Returns:
A shallow copy flattened to one dimension.
- Return type:
- flatten_denom()
This object with a new denominator shape such that drank == 1.
- flatten_numer(classes=(), *, recursive=True)
This object with a new numerator shape such that nrank == 1.
- Parameters:
classes (class, list, or tuple, optional) – The class of the object returned. If a list is provided, the object will be an instance of the first suitable class in the list. Otherwise, a generic Qube object will be returned.
recursive (bool, optional) – True to include matching slices of the derivatives in the returned object; otherwise, the returned object will not contain derivatives.
- Returns:
The flattened object.
- Return type:
- classmethod from_scalars(*scalars, recursive=True, readonly=False, classes=[])[source]
A new instance constructed from Scalars or arrays given as arguments.
Defined as a class method so it can also be used to generate instances of any 1-D subclass.
- Parameters:
*scalars (Qube, array-like, float, or int) – One or more Scalars or objects that can be converted to Scalars.
recursive (bool, optional) – True to construct the derivatives as the union of the derivatives of all the components’ derivatives. False to return an object without derivatives.
readonly (bool, optional) – True to return a read-only object; False (the default) to return something potentially writable.
classes – (class or list[class]): A list defining the preferred class of the returned object. The first suitable class in the list will be used; default is [Vector].
- Returns:
A new object constructed from the inputs and using the first suitable class within classes.
- Return type:
- Raises:
ValueError – If two of the scalars have incompatible denominators.
- identity()
An object of this subclass equivalent to the identity.
This method is overridden by
Scalar.identity(),Matrix.identity()andBoolean.identity()
- insert_deriv(key, deriv, *, override=True)[source]
Insert or replace a derivative in this object.
To prevent recursion, any internal derivatives of a derivative object are stripped away. If the object is read-only, then derivatives will also be converted to read-only.
Derivatives cannot be integers. They are converted to floating-point if necessary.
You cannot replace the pre-existing value of a derivative in a read-only object unless you explicit set override=True. However, inserting a new derivative into a read-only object is not prevented.
- Parameters:
key (str) – The name of the derivative. Each derivative also becomes accessible as an object attribute with “d_d” in front of the name. For example, the time-derivative of this object might be keyed by “t”, in which case it can also be accessed as attribute “d_dt”.
deriv (Qube) – The derivative. Derivatives must have the same leading shape and the same numerator as the object; denominator items are used for partial derivatives.
override (bool, optional) – True to allow the value of a pre-existing derivative to be replaced.
- Returns:
This object after the derivative has been inserted.
- Return type:
- Raises:
TypeError – If the derivative class is invalid or if derivatives are disallowed for the object class.
ValueError – If the shape is invalid, or if the key already exists when override is False.
- insert_derivs(derivs, *, override=False)[source]
Insert or replace the derivatives in this object from a dictionary.
You cannot replace the pre-existing values of any derivative in a read-only object unless you explicit set override=True. However, inserting a new derivative into a read-only object is not prevented.
- Parameters:
derivs (dict) – The dictionary of derivatives keyed by their names.
override (bool, optional) – True to allow the value of a pre-existing derivative to be replaced.
- Returns:
This object after the derivatives has been inserted.
- Return type:
- Raises:
TypeError – If a derivative class is invalid.
ValueError – If derivatives are disallowed for the object, if a shape is invalid, or if a key already exists when override is False.
- into_unit(recursive=False)[source]
The values property of this object, converted to its unit.
- Parameters:
recursive (bool, optional) – If True, also return the derivatives converted to their units.
- Returns:
The values attribute of this object, converted to this object’s units. If recursive is True, it returns a tuple (values, derivs), where derivs is a dictionary of the derivative values converted to their units.
- Return type:
(numpy.ndarray, float, int, bool, or tuple)
- static is_above(arg, high, inclusive=True)
Check if arg is outside a range with upper end at high.
- Parameters:
arg (object) – The value to check.
high (object) – The upper limit of the range.
inclusive (bool, optional) – True to include the upper limit in the range; False to exclude it.
- Returns:
True if arg is outside the range with upper end at high.
- Return type:
bool
- static is_below(arg, high, inclusive=True)
Check if arg is inside a range with upper end at high.
- Parameters:
arg (object) – The value to check.
high (object) – The upper limit of the range.
inclusive (bool, optional) – True to include the upper limit in the range; False to exclude it.
- Returns:
True if arg is inside the range with upper end at high.
- Return type:
bool
- static is_inside(arg, low, high, inclusive=True)
Check if arg is inside the range low to high.
- Parameters:
arg (object) – The value to check.
low (object) – The lower limit of the range.
high (object) – The upper limit of the range.
inclusive (bool, optional) – True to include the upper limit in the range; False to exclude it.
- Returns:
True if arg is inside the range low to high.
- Return type:
bool
- static is_outside(arg, low, high, inclusive=True)
Check if arg is outside the range low to high.
- Parameters:
arg (object) – The value to check.
low (object) – The lower limit of the range.
high (object) – The upper limit of the range.
inclusive (bool, optional) – True to include the upper limit in the range; False to exclude it.
- Returns:
True if arg is outside the range low to high.
- Return type:
bool
- property isize
The number of components in this object’s items.
- property item
The shape of the elements in this object as a tuple.
- join_items(classes)
The object with denominator axes joined to the numerator.
Derivatives are removed.
- Parameters:
classes (class, list, or tuple, optional) – The class of the object returned. If a list is provided, the object will be an instance of the first suitable class in the list. Otherwise, a generic Qube object will be returned.
- Returns:
The object with joined items.
- Return type:
- len()
Number of elements along first axis.
- logical_not()
The negation of this object, True where it is zero or False.
- property mask
The boolean mask of this object as a NumPy.ndarray or bool.
- mask_where(mask, replace=None, *, remask=True, recursive=True)
Return a copy of this object after a mask has been applied.
If the mask is empty, this object is returned unchanged.
- Parameters:
mask (array-like) – The mask to apply as a boolean array.
replace (object, optional) – A single replacement value or an object of the same shape and class as this object, containing replacement values. These are inserted into returned object at every masked location. Use None to leave values unchanged.
remask (bool, optional) – True to leave the new values masked; False to replace the values but leave them unmasked.
recursive (bool, optional) – True to mask the derivatives as well; False to leave them unmasked.
- Returns:
A copy of this object with the mask applied.
- Return type:
- Raises:
ValueError – If the replacement shape is incompatible with the object shape.
- mask_where_between(lower, upper, *, mask_endpoints=False, replace=None, remask=True)
Return a copy with values between two limits masked.
Instead of or in addition to masking the items, the values can be replaced. If no items need to be masked, this object is returned unchanged.
- Parameters:
lower (Qube, array-like, float, or int) – The lower limit as a number or an object that can be broadcasted to the shape of this object’s values (including its item shape). Masked limits are ignored.
upper (Qube, array-like, float, or int) – The upper limit as a number or an object that can be broadcasted to the shape of this object’s values (including its item shape). Masked limits are ignored.
mask_endpoints (bool or tuple, optional) – True to mask the endpoints, where values are equal to the lower or upper limits; False to exclude the endpoints. Use a tuple of two values to handle the endpoints differently.
replace (Qube, array-like, float, or int, optional) – A single replacement value or an object that can be broadcasted to the shape of this object’s values (including its item shape). Masked replacements become masked. Use None to leave values unchanged.
remask (bool, optional) – True to leave the new values masked; False to replace the values but leave them unmasked.
- Returns:
A copy with values between the specified limits masked.
- Return type:
- Raises:
ValueError – If this object has denominators or item rank > 0.
- mask_where_eq(match, replace=None, *, remask=True)
Return a copy of this object with items equal to a value masked.
Instead of or in addition to masking the items, the values can be replaced. If no items need to be masked, this object is returned unchanged.
- Parameters:
match (object) – The item value to match.
replace (object, optional) – A single replacement value or an object of the same shape and class as this object, containing replacement values. These are inserted into returned object at every masked location. Use None to leave values unchanged.
remask (bool, optional) – True to leave the new values masked; False to replace the values but leave them unmasked.
- Returns:
A copy of this object with matching items masked.
- Return type:
- mask_where_ge(limit, replace=None, *, remask=True)
Return a copy of this object with items >= a limit value masked.
Instead of or in addition to masking the items, the values can be replaced. If no items need to be masked, this object is returned unchanged.
- Parameters:
limit (object) – The limiting value.
replace (object, optional) – A single replacement value or an object of the same shape and class as this object, containing replacement values. These are inserted into returned object at every masked location. Use None to leave values unchanged.
remask (bool, optional) – True to leave the new values masked; False to replace the values but leave them unmasked.
- Returns:
A copy of this object with items >= limit masked.
- Return type:
- Raises:
ValueError – If this object has denominators or item rank > 0.
- mask_where_gt(limit, replace=None, *, remask=True)
Return a copy with items greater than a limit value masked.
Instead of or in addition to masking the items, the values can be replaced. If no items need to be masked, this object is returned unchanged.
- Parameters:
limit (object) – The limiting value.
replace (object, optional) – A single replacement value or an object of the same shape and class as this object, containing replacement values. These are inserted into returned object at every masked location. Use None to leave values unchanged.
remask (bool, optional) – True to leave the new values masked; False to replace the values but leave them unmasked.
- Returns:
A copy of this object with items > limit masked.
- Return type:
- Raises:
ValueError – If this object has denominators or item rank > 0.
- mask_where_le(limit, replace=None, *, remask=True)
Return a copy of this object with items <= a limit value masked.
Instead of or in addition to masking the items, the values can be replaced. If no items need to be masked, this object is returned unchanged.
- Parameters:
limit (object) – The limiting value.
replace (object, optional) – A single replacement value or an object of the same shape and class as this object, containing replacement values. These are inserted into returned object at every masked location. Use None to leave values unchanged.
remask (bool, optional) – True to leave the new values masked; False to replace the values but leave them unmasked.
- Returns:
A copy of this object with items <= limit masked.
- Return type:
- Raises:
ValueError – If this object has denominators or item rank > 0.
- mask_where_lt(limit, replace=None, *, remask=True)
Return a copy with items less than a limit value masked.
Instead of or in addition to masking the items, the values can be replaced. If no items need to be masked, this object is returned unchanged.
- Parameters:
limit (object) – The limiting value.
replace (object, optional) – A single replacement value or an object of the same shape and class as this object, containing replacement values. These are inserted into returned object at every masked location. Use None to leave values unchanged.
remask (bool, optional) – True to leave the new values masked; False to replace the values but leave them unmasked.
- Returns:
A copy of this object with items < limit masked.
- Return type:
- Raises:
ValueError – If this object has denominators or item rank > 0.
- mask_where_ne(match, replace=None, *, remask=True)
Return a copy of this object with items not equal to a value masked.
Instead of or in addition to masking the items, the values can be replaced. If no items need to be masked, this object is returned unchanged.
- Parameters:
match (object) – The item value to match.
replace (object, optional) – A single replacement value or an object of the same shape and class as this object, containing replacement values. These are inserted into returned object at every masked location. Use None to leave values unchanged.
remask (bool, optional) – True to leave the new values masked; False to replace the values but leave them unmasked.
- Returns:
A copy of this object with non-matching items masked.
- Return type:
- mask_where_outside(lower, upper, *, mask_endpoints=False, replace=None, remask=True)
Return a copy with values outside two limits masked.
Instead of or in addition to masking the items, the values can be replaced. If no items need to be masked, this object is returned unchanged.
- Parameters:
lower (Qube, array-like, float, or int) – The lower limit as a number or an object that can be broadcasted to the shape of this object’s values (including its item shape). Masked limits are ignored.
upper (Qube, array-like, float, or int) – The upper limit as a number or an object that can be broadcasted to the shape of this object’s values (including its item shape). Masked limits are ignored.
mask_endpoints (bool or tuple, optional) – True to mask the endpoints, where values are equal to the lower or upper limits; False to exclude the endpoints. Use a tuple of two values to handle the endpoints differently.
replace (Qube, array-like, float, or int, optional) – A single replacement value or an object that can be broadcasted to the shape of this object’s values (including its item shape). Masked replacements become masked. Use None to leave values unchanged.
remask (bool, optional) – True to leave the new values masked; False to replace the values but leave them unmasked.
- Returns:
A copy with values outside the specified limits masked.
- Return type:
- Raises:
ValueError – If this object has denominators or item rank > 0.
- mean(axis=None, *, recursive=True, builtins=None, masked=None, dtype=None, out=None)
The mean of the unmasked values along the specified axis or axes.
- Parameters:
axis (int or tuple, optional) – An integer axis or a tuple of axes. The sum is determined across these axes, leaving any remaining axes in the returned value. If None (the default), then the sum is performed across all axes if the object.
recursive (bool, optional) – True to include the sums of the derivatives inside the returned Scalar.
builtins (bool, optional) – If True and the result is a single unmasked scalar, the result is returned as a Python boolean instead of as an instance of Boolean. Default is to use the global setting defined by Qube.prefer_builtins().
masked (bool, optional) – The value to return if builtins is True but the returned value is masked. Default is to return a masked value instead of a builtin type.
dtype (optional) – Ignored. This enables “np.sum(Qube)” to work.
out (optional) – Ignored. This enables “np.sum(Qube)” to work.
- move_axis(source, destination, *, recursive=True, rank=None)
A shallow copy of the object with the specified axis moved to a new position.
- Parameters:
source (int or tuple) – Axis to move or tuple of axes to move.
destination (int or tuple) – Destination of moved axis or axes.
recursive (bool, optional) – True to perform the same axis move on the derivatives. Otherwise, derivatives are deleted from the returned object.
rank (int, optional) – Rank to assume for the object, which could be larger than len(self.shape) because of broadcasting.
- Returns:
A shallow copy with the specified axis moved to the new position.
- Return type:
- Raises:
ValueError – If the rank is too small for the object shape.
ValueError – If any axis is out of range.
- property mvals
This object as a NumPy ma.MaskedArray.
- ndenumerate()
Iterate across all axes of this object.
This method provides an iterator that returns tuples containing the index and the corresponding item at that index.
- Returns:
An iterator yielding (index_tuple, item_at_index) pairs.
- Return type:
QubeNDIterator
- property ndim
The number of dimensions in this object (excluding items).
- property ndims
The number of dimensions in this object (excluding items).
- static norm(arg, axis=-1, *, classes=(), recursive=True)
Calculate the norm of an object along one axis.
The axes must be in the numerator. The denominator must have zero rank.
- Parameters:
arg (Qube) – The object for which to calculate the norm.
axis (int, optional) – The numerator axis for the norm. Defaults to -1.
classes (class, list, or tuple, optional) – The class of the object returned. If a list is provided, the object will be an instance of the first suitable class in the list. Otherwise, a generic Qube object will be returned.
recursive (bool, optional) – True to include derivatives in the returned object.
- Returns:
The norm of the object along the specified axis.
- Return type:
- Raises:
ValueError – If the object has denominators or if the axis is out of range.
- static norm_sq(arg, axis=-1, *, classes=(), recursive=True)
Calculate the square of the norm of an object along one axis.
The axes must be in the numerator. The denominator must have zero rank.
- Parameters:
arg – The object for which to calculate the norm-squared.
axis (int, optional) – The item axis for the norm. Default is -1.
classes (class, list, or tuple, optional) – The class of the object returned. If a list is provided, the object will be an instance of the first suitable class in the list. Otherwise, a generic Qube object will be returned.
recursive (bool, optional) – True to include derivatives in the returned object.
- Returns:
The square of the norm of the object along the specified axis.
- Return type:
- Raises:
ValueError – If the object has denominators or if the axis is out of range.
- property nrank
The rank of the element numerator in this object.
- property nsize
The number of numerator components in this object’s items.
- property numer
The shape of the element numerator in this object as a tuple.
- classmethod ones(shape, dtype='float', *, numer=None, denom=(), mask=False)[source]
New object of this class and shape, filled with ones.
- Parameters:
shape (tuple) – Shape of the object.
dtype (str, optional) – One of “bool”, “int”, or “float”, defining the data type. Ignored if cls has a default dtype.
numer (tuple, optional) – Numerator shape; None to use default for cls.
denom (tuple, optional) – Denominator shape.
mask (array-like or bool, optional) – Mask to apply.
- Returns:
The new object.
- Return type:
- static or_(*masks)[source]
The logical “or” of two or more masks, avoiding array operations if possible.
- Parameters:
*masks (array-like or bool) – One or more boolean masks.
- Returns:
New mask array or bool.
- Return type:
(np.ndarray or bool)
- static outer(arg1, arg2, classes=(), recursive=True)
Calculate the outer product of two objects.
The item shape of the returned object is obtained by concatenating the two numerators and then the two denominators, and each element is the product of the corresponding elements of the two objects.
- Parameters:
arg1 (Qube) – The first operand.
arg2 (Qube) – The second operand.
classes (class, list, or tuple, optional) – The class of the object returned. If a list is provided, the object will be an instance of the first suitable class in the list. Otherwise, a generic Qube object will be returned.
recursive (bool, optional) – True to include derivatives in the returned object.
- Returns:
The outer product of the two objects.
- Return type:
- Raises:
ValueError – If both objects have denominators.
- pickle = <module 'polymath.extensions.pickler' from '/home/docs/checkouts/readthedocs.org/user_builds/rms-polymath/checkouts/stable/polymath/extensions/pickler.py'>
- pickle_digits()
The digits of floating-point precision to include when pickling this object and its derivatives.
- Returns:
One of “double”, “single”, or a number of digits roughly in the range 7-16.
- Return type:
(str, float, or int)
- pickle_reference()
The reference value to use when determining the number of digits of floating-point precision in this object and its derivatives.
- Returns:
One of “fpzip”, “smallest”, “largest”, “mean”, “median”, “logmean”, or a number.
- Return type:
(str, float, or int)
- static prefer_builtins(status=None)[source]
Set a global flag defining whether certain functions return a Python builtin type, rather than a Qube subclass, if possible.
- Parameters:
status (bool, optional) – True to favor Python builtin types; False otherwise. Omit this input to leave the global setting unchanged (but return it).
- Returns:
True if builtins are globally preferred; False otherwise.
- Return type:
bool
- property rank
The rank of this object.
- property readonly
True if this object is read-only; False otherwise.
- reciprocal(*, recursive=True, nozeros=False)
An object equivalent to the reciprocal of this object.
This method is not implemented for the base class. It is overridden by
Scalar.reciprocal(),Vector.reciprocal(),Matrix.reciprocal(), andQuaternion.reciprocal().- Input:
- recursive (bool, optional): True to return the derivatives of the reciprocal too;
otherwise, derivatives are removed.
- nozeros (bool, optional): False (the default) to mask out any zero-valued items in
this object prior to the divide. Set to True only if you know in advance that this object has no zero-valued items.
- remask(mask, *, recursive=True, check=True)[source]
A shallow copy of this object with a replaced mask.
This is much quicker than masked_where(), for cases where only the mask of this object is changing.
- Parameters:
mask (array-like or bool) – The new mask to be applied to the object.
recursive (bool, optional) – True to apply the same mask to any derivatives.
check (bool, optional) – True to check for an array containing all False values, and if so, replace it with a single value of False.
- Returns:
A shallow copy of this object with a new mask.
- Return type:
- Raises:
TypeError – If the data type of mask is invalid.
ValueError – If the mask is incompatible with the required shape.
- remask_or(mask, *, recursive=True, check=True)[source]
A shallow copy of this object, in which the current mask is “or-ed” with the given mask.
This is much quicker than masked_where(), for cases where only the mask is changing.
- Parameters:
mask (array-like or bool) – The new mask to be applied to the object.
recursive (bool, optional) – True to apply the same mask to any derivatives.
check (bool, optional) – True to check for an array containing all False values, and if so, replace it with a single value of False.
- Returns:
A shallow copy of this object with a new mask.
- Return type:
- Raises:
TypeError – If the data type of mask is invalid for a mask.
ValueError – If the mask is incompatible with the required shape.
- rename_deriv(key, new_key, *, method='insert')[source]
A shallow copy of this object with a derivative renamed.
A read-only object remains read-only.
- Parameters:
key (str) – The current key of the derivative.
new_key (str) – The new name of the derivative.
method (str) –
How to rename the derivative, one of these options:`
”insert”: Iinsert the new derivative; raise a ValueError if a derivative of the same name already exists.
”replace”: Replace an existing derivative of the same name.
”add”: Add this derivative to an existing derivative of the same name.
- Returns:
The copy, with the same subclass as self.
- Return type:
- Raises:
KeyError – If the key derivative does not exist.
ValueError – If method is “insert” and a derivative of the given name already exists.
- require_writable(force=False)[source]
Ensure that this object is writeable.
DEPRECATED NAME; use require_writeable().
- Parameters:
force (bool, optional) – True to return a new copy if this object is read-only; otherwise, if this object is not writeable, raise a ValueError.
- Returns:
This object if already writeable; otherwise a new writeable copy.
- Return type:
- Raises:
ValueError – If this object is read-only but force is False.
- require_writeable(force=False)[source]
Ensure that this object is writeable.
- Parameters:
force (bool, optional) – True to return a new copy if this object is read-only; otherwise, if this object is not writeable, raise a ValueError.
- Returns:
This object if already writeable; otherwise a new writeable copy.
- Return type:
- Raises:
ValueError – If this object is read-only but force is False.
- reshape(shape, *, recursive=True)
Return a shallow copy of the object with a new leading shape.
- Parameters:
shape (tuple or int) – A tuple defining the new leading shape. A value of -1 can appear at one location in the new shape, and the size of that shape will be determined based on this object’s size.
recursive (bool, optional) – True to apply the same shape to the derivatives. Otherwise, derivatives are deleted from the returned object.
- Returns:
- A shallow copy with the new shape. If the shape is unchanged, this object is
returned without modification. The read-only status is preserved.
- Return type:
- Raises:
ValueError – If the new shape is incompatible with the current shape.
- reshape_denom(shape)
This object with a new shape for denominator items.
- Parameters:
shape (tuple) – The new denominator shape.
- Returns:
The reshaped object.
- Return type:
- Raises:
ValueError – If the denominator size would be changed by the reshape operation.
- reshape_numer(shape, classes=(), recursive=True)
This object with a new shape for numerator items.
- Parameters:
shape (tuple) – The new shape for numerator items.
classes (class, list, or tuple, optional) – The class of the object returned. If a list is provided, the object will be an instance of the first suitable class in the list. Otherwise, a generic Qube object will be returned.
recursive (bool, optional) – True to reshape the derivatives in the same way; otherwise, the returned object will not contain derivatives.
- Returns:
The reshaped object.
- Return type:
- Raises:
ValueError – If the item size would be changed by the reshape operation.
- rms()
Calculate the root-mean-square values of all items as a Scalar.
Useful for looking at the overall magnitude of the differences between two objects.
- Returns:
The root-mean-square values of all items.
- Return type:
- roll_axis(axis, start=0, *, recursive=True, rank=None)
A shallow copy of the object with the specified axis rolled to a new position.
- Parameters:
axis (int) – The axis to roll.
start (int, optional) – The axis will be rolled to fall in front of this axis.
recursive (bool, optional) – True to perform the same axis roll on the derivatives. Otherwise, derivatives are deleted from the returned object.
rank (int, optional) – Rank to assume for the object, which could be larger than len(self.shape) because of broadcasting.
- Returns:
A shallow copy with the axis rolled to the new position.
- Return type:
- Raises:
ValueError – If the rank is too small for the object shape.
ValueError – If the axis or start is out of range.
- static set_default_pickle_digits(digits='double', reference='fpzip')
Set the default number of decimal digits of precision in the storage of floating-point values and their derivatives.
- Parameters:
digits (int, float, str or tuple, optional) – The number of digits to preserve when pickling this object. If two values are given, the second applies to any derivatives. If a number is specified, this is the number of decimal digits to preserve when this object is pickled. It need not be an integer. It is truncated to the range supported by single and double precision. Alternatively, use “double” to preserve full double precision; use “single” for single precision.
reference (int, float, str or tuple, optional) – A value defining the number to use when assessing how many digits are preserved. If two values are given, the second applies to any derivatives. If a number is specified, the number of digits will be relative to this value. For example, if the reference=100 and digits=8, the precision will be 1.e-6. Alternatively, use one of these strings to let the precision be referenced to the values in the array: “smallest”, “largest”, “mean”, “median”, “logmean”, or “fpzip”.
Notes
The reference options are:
“smallest”: Reference precision to the value closest to zero. This option guarantees that the requested number of digits are preserved for every value.
“largest”: Reference precision to the value furthest from zero; this is a good choice for values that are known to have a limited range that includes zero, e.g., the components of a unit vector, or an angle between zero and two pi.
“mean”: Reference the mean absolute value.
“median”: Reference the median absolute value. This is a good choice if a minority of values are very different from the others, but those values should not dominate the precision determination.
“logmean”: Reference the mean of the log of absolute values.
“fpzip”: Employ fpzip compression.
- set_pickle_digits(digits='double', reference='fpzip')
Set the desired number of decimal digits of precision in the storage of this object’s floating-point values and their derivatives.
This attribute is ignored for integer and boolean values.
- Parameters:
digits (int, float, str or tuple, optional) – The number of digits to preserve when pickling this object. If two values are given, the second applies to any derivatives. If a number is specified, this is the number of decimal digits to preserve when this object is pickled. It need not be an integer. It is truncated to the range supported by single and double precision. Alternatively, use “double” to preserve full double precision; use “single” for single precision.
reference (int, float, str or tuple, optional) – A value defining the number to use when assessing how many digits are preserved. If two values are given, the second applies to any derivatives. If a number is specified, the number of digits will be relative to this value. For example, if the reference=100 and digits=8, the absolute precision will be 1.e-6. Alternatively, use one of these strings to let the precision be referenced to the values in the array: “smallest”, “largest”, “mean”, “median”, “logmean”, or “fpzip”.
Notes
The reference options are:
“smallest”: Reference precision to the value closest to zero. This option guarantees that the requested number of digits are preserved for every value.
“largest”: Reference precision to the value furthest from zero; this is a good choice for values that are known to have a limited range that includes zero, e.g., the components of a unit vector, or an angle between zero and two pi.
“mean”: Reference the mean absolute value.
“median”: Reference the median absolute value. This is a good choice if a minority of values are very different from the others, but those values should not dominate the precision determination.
“logmean”: Reference the mean of the log of absolute values.
“fpzip”: Employ fpzip compression.
- set_unit(unit, *, override=False)[source]
Set the unit of this object.
- Parameters:
unit (Unit or None) – The new unit.
override (bool, optional) – If True, the unit can be modified on a read-only object.
- Raises:
ValueError – If this object is read-only and override is False.
- property shape
The shape of this object as a tuple.
- shrink(antimask)
A 1-D version of this object, containing only the samples in the antimask provided.
The antimask array value of True indicates that an element should be included; False means that is should be discarded. A scalar value of True or False applies to the entire object.
The purpose is to speed up calculations by first eliminating all the objects that are masked. Any calculation involving un-shrunken objects should produce the same result if the same objects are all shrunken by a common antimask first, the calculation is performed, and then the result is un-shrunken afterward.
Shrunken objects are always converted to read-only.
- property size
The number of elements in this object’s shape.
- slice_numer(axis, index1, index2, classes=(), *, recursive=True)
Extract an object sliced from one numerator axis.
- Parameters:
axis (int) – The item axis from which to extract a slice.
index1 (int) – The starting index value at which to extract the slice.
index2 (int) – The ending index value at which to extract the slice.
classes (class, list, or tuple, optional) – The class of the object returned. If a list is provided, the object will be an instance of the first suitable class in the list. Otherwise, a generic Qube object will be returned.
recursive (bool, optional) – True to include matching slices of the derivatives in the returned object; otherwise, the returned object will not contain derivatives.
- Returns:
An object sliced from the specified numerator axis.
- Return type:
- Raises:
ValueError – If the axis is out of range.
- split_items(nrank, classes)
The object with numerator axes converted to denominator axes.
Derivatives are removed.
- Parameters:
nrank (int) – Number of numerator axes to retain.
classes (class, list, or tuple, optional) – The class of the object returned. If a list is provided, the object will be an instance of the first suitable class in the list. Otherwise, a generic Qube object will be returned.
- Returns:
The object with split items.
- Return type:
- static stack(*args, recursive=True)
Stack objects into one with a new leading axis.
- Parameters:
*args – Any number of Scalars or arguments that can be casted to Scalars. They need not have the same shape, but it must be possible to cast them to the same shape. A value of None is converted to a zero-valued Scalar that matches the denominator shape of the other arguments.
recursive (bool, optional) – True to include all the derivatives. The returned object will have derivatives representing the union of all the derivatives found amongst the scalars.
- Returns:
A stacked object with a new leading axis.
- Return type:
- Raises:
TypeError – If an unexpected keyword argument is provided.
ValueError – If the arguments have incompatible denominators.
- sum(axis=None, *, recursive=True, builtins=None, masked=None, out=None)
The sum of the unmasked values along the specified axis or axes.
This method is overridden by
Boolean.sum().- Parameters:
axis (int or tuple, optional) – An integer axis or a tuple of axes. The sum is determined across these axes, leaving any remaining axes in the returned value. If None (the default), then the sum is performed across all axes if the object.
recursive (bool, optional) – True to include the sums of the derivatives inside the returned Scalar.
builtins (bool, optional) – If True and the result is a single unmasked scalar, the result is returned as a Python boolean instead of as an instance of Boolean. Default is to use the global setting defined by Qube.prefer_builtins().
masked (bool, optional) – The value to return if builtins is True but the returned value is masked. Default is to return a masked value instead of a builtin type.
out (optional) – Ignored. This enables “np.sum(Qube)” to work.
- swap_axes(axis1, axis2, *, recursive=True)
Return a shallow copy of the object with two leading axes swapped.
- Parameters:
axis1 (int) – The first index of the swap. Negative indices are relative to the last index before the numerator items begin.
axis2 (int) – The second index of the swap.
recursive (bool, optional) – True to perform the same swap on the derivatives. Otherwise, derivatives are deleted from the returned object.
- Returns:
A shallow copy with the specified axes swapped.
- Return type:
- Raises:
ValueError – If either axis is out of range.
- swap_items(classes)
A new object with the numerator and denominator axes exchanged.
Derivatives are removed.
- Parameters:
classes (class, list, or tuple, optional) – The class of the object returned. If a list is provided, the object will be an instance of the first suitable class in the list. Otherwise, a generic Qube object will be returned.
- Returns:
The object with swapped items.
- Return type:
- transpose_denom(axis1=0, axis2=1)
A copy of this object with two denominator axes transposed.
- Parameters:
axis1 (int, optional) – The first axis to transpose from among the denominator axes. Negative values count backward from the last axis.
axis2 (int, optional) – The second axis to transpose.
- Returns:
The transposed object.
- Return type:
- Raises:
ValueError – If either axis is out of range.
- transpose_numer(axis1=0, axis2=1, *, recursive=True)
A copy of this object with two numerator axes transposed.
- Parameters:
axis1 (int, optional) – The first axis to transpose from among the numerator axes. Negative values count backward from the last numerator axis.
axis2 (int, optional) – The second axis to transpose.
recursive (bool, optional) – True to transpose the same axes of the derivatives; False to return an object without derivatives.
- Returns:
A copy with the specified numerator axes transposed.
- Return type:
- Raises:
ValueError – If either axis is out of range.
- tvl_all(axis=None, builtins=None, masked=None)
Return True if all unmasked values are True using three-valued logic.
Masked values are treated as indeterminate rather than being ignored. These are the rules:
True if and only if all the items are True and unmasked.
False if any unmasked value is False.
otherwise, Masked.
- Parameters:
axis (int or tuple, optional) – An integer axis or a tuple of axes. The all operation is performed across these axes, leaving any remaining axes in the returned value. If None (the default), then the all operation is performed across all axes of the object.
builtins (bool, optional) – If True and the result is a single unmasked scalar, the result is returned as a Python boolean instead of as an instance of Boolean. Default is to use the global setting defined by Qube.prefer_builtins().
masked (bool, optional) – The value to return if builtins is True but the returned value is masked. Default is to return a masked value instead of a builtin type.
- Returns:
The result of the three-valued logic “all” operation.
- Return type:
(Boolean or bool)
- tvl_and(arg, builtins=None, masked=None)
Return the three-valued logic “and” operator result.
Masked values are treated as indeterminate rather than being ignored. These are the rules:
False and anything = False
True and True = True
True and Masked = Masked
- Parameters:
arg (Qube or bool) – The right-hand operand for the AND operation.
builtins (bool, optional) – If True and the result is a single unmasked scalar, the result is returned as a Python boolean instead of as an instance of Boolean. Default is to use the global setting defined by Qube.prefer_builtins().
masked (bool, optional) – The value to return if builtins is True but the returned value is masked. Default is to return a masked value instead of a builtin type.
- Returns:
The result of the three-valued logic “and” operation.
- Return type:
(Boolean or bool)
- tvl_any(axis=None, builtins=None, masked=None)
Return True if any unmasked value is True using three-valued logic.
Masked values are treated as indeterminate rather than being ignored. These are the rules:
True if any unmasked value is True;
False if and only if all the items are False and unmasked;
otherwise, Masked.
- Parameters:
axis (int or tuple, optional) – An integer axis or a tuple of axes. The any operation is performed across these axes, leaving any remaining axes in the returned value. If None (the default), then the any operation is performed across all axes of the object.
builtins (bool, optional) – If True and the result is a single unmasked scalar, the result is returned as a Python boolean instead of as an instance of Boolean. Default is to use the global setting defined by Qube.prefer_builtins().
masked (bool, optional) – The value to return if builtins is True but the returned value is masked. Default is to return a masked value instead of a builtin type.
- Returns:
The result of the three-valued logic “any” operation.
- Return type:
(Boolean or bool)
- tvl_eq(arg, builtins=None)
Return the three-valued logic “equals” operator result.
Masked values are treated as indeterminate, so if either value is masked, the returned value is masked.
- Parameters:
arg (Qube or bool) – The right-hand operand for the equality comparison.
builtins (bool, optional) – If True and the result is a single unmasked scalar, the result is returned as a Python boolean instead of as an instance of Boolean. Default is to use the global setting defined by Qube.prefer_builtins().
- Returns:
The result of the three-valued logic equality comparison.
- Return type:
(Boolean or bool)
- tvl_ge(arg, builtins=None)
Return the three-valued logic “greater than or equal to” operator result.
Masked values are treated as indeterminate, so if either value is masked, the returned value is masked.
- Parameters:
arg (Qube or number) – The right-hand operand for the comparison.
builtins (bool, optional) – If True and the result is a single unmasked scalar, the result is returned as a Python boolean instead of as an instance of Boolean. Default is to use the global setting defined by Qube.prefer_builtins().
- Returns:
The result of the three-valued logic “greater than or equal to” comparison.
- Return type:
(Boolean or bool)
- tvl_gt(arg, builtins=None)
Return the three-valued logic “greater than” operator result.
Masked values are treated as indeterminate, so if either value is masked, the returned value is masked.
- Parameters:
arg (Qube or number) – The right-hand operand for the comparison.
builtins (bool, optional) – If True and the result is a single unmasked scalar, the result is returned as a Python boolean instead of as an instance of Boolean. Default is to use the global setting defined by Qube.prefer_builtins().
- Returns:
The result of the three-valued logic “greater than” comparison.
- Return type:
(Boolean or bool)
- tvl_le(arg, builtins=None)
Return the three-valued logic “less than or equal to” operator result.
Masked values are treated as indeterminate, so if either value is masked, the returned value is masked.
- Parameters:
arg (Qube or number) – The right-hand operand for the comparison.
builtins (bool, optional) – If True and the result is a single unmasked scalar, the result is returned as a Python boolean instead of as an instance of Boolean. Default is to use the global setting defined by Qube.prefer_builtins().
- Returns:
The result of the three-valued logic “less than or equal to” comparison.
- Return type:
(Boolean or bool)
- tvl_lt(arg, builtins=None)
Return the three-valued logic “less than” operator result.
Masked values are treated as indeterminate, so if either value is masked, the returned value is masked.
- Parameters:
arg (Qube or number) – The right-hand operand for the comparison.
builtins (bool, optional) – If True and the result is a single unmasked scalar, the result is returned as a Python boolean instead of as an instance of Boolean. Default is to use the global setting defined by Qube.prefer_builtins().
- Returns:
The result of the three-valued logic “less than” comparison.
- Return type:
(Boolean or bool)
- tvl_ne(arg, builtins=None)
Return the three-valued logic “not equal” operator result.
Masked values are treated as indeterminate, so if either value is masked, the returned value is masked.
- Parameters:
arg (Qube or bool) – The right-hand operand for the inequality comparison.
builtins (bool, optional) – If True and the result is a single unmasked scalar, the result is returned as a Python boolean instead of as an instance of Boolean. Default is to use the global setting defined by Qube.prefer_builtins().
- Returns:
The result of the three-valued logic inequality comparison.
- Return type:
(Boolean or bool)
- tvl_or(arg, builtins=None, masked=None)
Return the three-valued logic “or” operator result.
Masked values are treated as indeterminate rather than being ignored. These are the rules:
True or anything = True
False or False = False
False or Masked = Masked
- Parameters:
arg (Qube or bool) – The right-hand operand for the OR operation.
builtins (bool, optional) – If True and the result is a single unmasked scalar, the result is returned as a Python boolean instead of as an instance of Boolean. Default is to use the global setting defined by Qube.prefer_builtins().
masked (bool, optional) – The value to return if builtins is True but the returned value is masked. Default is to return a masked value instead of a builtin type. value specified by Qube.PREFER_BUILTIN_TYPES.
- Returns:
The result of the three-valued logic “or” operation.
- Return type:
(Boolean or bool)
- unique_deriv_name(key, *objects)[source]
A unique name for a derivative to apply to one or more objects.
- Parameters:
key (str) – The name to use, with a suffix appended if needed.
*objects (Qube) – One or more Qube objects.
- Returns:
The given key, or with a numeric suffix if needed to make it unique.
- Return type:
str
- property unit_
The Unit of this object.
- property units
The Unit of this object; alternative name for unit_.
- unshrink(antimask, shape=())
Convert an object to its un-shrunken shape, based on a given antimask.
If this object was previously shrunken, the antimask must match the one used to shrink it. Otherwise, the size of this object’s last axis must match the number of True values in the antimask.
- Parameters:
antimask (array-like) – The antimask to apply.
shape (tuple, optional) – In cases where the antimask is a literal False, this defines the shape of the returned object. Normally, the rightmost axes of the returned object match those of the antimask.
- Returns:
The un-shrunken object, which will be read-only.
- Return type:
- property vals
The value of this object as a numpy.ndarray, float, int, or bool.
- property values
The value of this object as a numpy.ndarray, float, int, or bool.
- with_deriv(key, value, *, method='insert')[source]
A shallow copy of this object with a derivative inserted or added.
A read-only object remains read-only.
- Parameters:
key (str) – The key of the derivative to insert.
value (Qube) – The value for this derivative.
method (str) –
How to insert the derivative, one of these options:`
”insert”: Iinsert the new derivative; raise a ValueError if a derivative of the same name already exists.
”replace”: Replace an existing derivative of the same name.
”add”: Add this derivative to an existing derivative of the same name.
- Returns:
The copy, with the same subclass as self.
- Return type:
- Raises:
ValueError – If method is “insert” and a derivative of the given name already exists.
- without_deriv(key)[source]
A shallow copy of this object without a particular derivative.
A read-only object remains read-only.
- Parameters:
key (str) – The key of the derivative to remove.
- Returns:
The copy, with the same subclass as self.
- Return type:
- without_derivs(*, preserve=None)[source]
A shallow copy of this object without derivatives.
A read-only object remains read-only, and is cached for later use.
- Parameters:
preserve (list, tuple, or set, optional) – The names of derivatives to retain. All others are removed.
- Returns:
The copy, with the same subclass as self.
- Return type:
- without_mask(*, recursive=True)[source]
A shallow copy of this object without its mask. Note that masked values will be revealed.
- Parameters:
recursive (bool, optional) – True to unmask any derivatives; False to strip derivatives.
- Returns:
This object without a mask.
- Return type:
- without_unit(*, recursive=True)[source]
A shallow copy of this object without units.
A read-only object remains read-only. If recursive is True, derivatives are also stripped of their units.
- Parameters:
recursive (bool, optional) – True to include derivatives with their units stripped; False to omit all derivatives.
- Returns:
A shallow copy of this object with the unit stripped.
- Return type:
- property wod
A shallow clone without derivatives, cached.
Read-only objects remain read-only.
- zero()
An object of this subclass containing all zeros.
The returned object has the same denominator shape as this object.
This is default behavior and may need to be overridden by some subclasses.
- classmethod zeros(shape, dtype='float', *, numer=None, denom=(), mask=False)[source]
New object of this class and shape, filled with zeros.
- Parameters:
shape (tuple) – Shape of the object.
dtype (str, optional) – One of “bool”, “int”, or “float”, defining the data type. Ignored if cls has a default dtype.
numer (tuple, optional) – Numerator shape; None to use default for cls.
denom (tuple, optional) – Denominator shape.
mask (array-like or bool, optional) – Mask to apply.
- Returns:
The new object.
- Return type:
- class Scalar(*values, **keywords)[source]
Bases:
QubeRepresent dimensionless scalar values in the PolyMath framework.
This class provides functionality for working with scalar values including mathematical operations, trigonometric functions, and statistical methods. Scalars can have units, derivatives, and support masking for undefined values.
- HALFPI = Scalar(1.5707963267948966)
- INF = Scalar(inf)
- MASKED = Scalar(--; mask)
- NEGINF = Scalar(-inf)
- ONE = Scalar(1)
- PI = Scalar(3.141592653589793)
- THREE = Scalar(3)
- TWO = Scalar(2)
- TWOPI = Scalar(6.283185307179586)
- ZERO = Scalar(0)
- __abs__(*, recursive=True)[source]
abs(self), element-by-element absolute value.
This is an override of
Qube.__abs__().- Parameters:
recursive (bool, optional) – True to include the derivatives. For every element that has its sign flipped, the sign will also be flipped in that element’s derivatives.
- Returns:
The absolute value.
- Return type:
- __ge__(arg, *, builtins=True)[source]
self >= arg, element-by-element “less than or equal”.
This is an override of
Qube.__ge__().- Parameters:
arg – The scalar to compare with.
builtins (bool, optional) – If True and the result is a single unmasked scalar, return a Python bool instead of a Boolean object.
- Returns:
True where this scalar is greater than or equal to the argument.
- Return type:
Boolean or bool
- Raises:
ValueError – If either object has denominators.
- __gt__(arg, *, builtins=True)[source]
self > arg, element-by-element “greater than”.
This is an override of
Qube.__gt__().- Parameters:
arg – The scalar to compare with.
builtins (bool, optional) – If True and the result is a single unmasked scalar, return a Python bool instead of a Boolean object.
- Returns:
True where this scalar is greater than the argument.
- Return type:
Boolean or bool
- Raises:
ValueError – If either object has denominators.
- __le__(arg, *, builtins=True)[source]
self <= arg, element-by-element “less than or equal”.
This is an override of
Qube.__le__().- Parameters:
arg – The scalar to compare with.
builtins (bool, optional) – If True and the result is a single unmasked scalar, return a Python bool instead of a Boolean object.
- Returns:
True where this scalar is less than or equal to the argument.
- Return type:
Boolean or bool
- Raises:
ValueError – If either object has denominators.
- __lt__(arg, *, builtins=True)[source]
self < arg, element-by-element “less than”.
This is an override of
Qube.__lt__().- Parameters:
arg – The scalar to compare with.
builtins (bool, optional) – If True and the result is a single unmasked scalar, return a Python bool instead of a Boolean object.
- Returns:
True where this scalar is less than the argument.
- Return type:
Boolean or bool
- Raises:
ValueError – If either object has denominators.
- __pow__(expo, *, recursive=True)[source]
arg ** self, element-by-element exponentiation.
Derivatives are not supported.
This general method supports single integer exponents between -15 and 15 are handled using repeated multiplications. It will handle any class that supports __mul__() (and reciprocal() if the exponent is negative), such as Matrix objects and Quaternions.
It is overridden by Scalar to obtain the normal behavior of the “**” operator.
- __round__(digits)[source]
This scalar rounded to the specified number of digits.
- Parameters:
digits (int) – The number of decimal digits to round to.
- Returns:
The rounded scalar.
- Return type:
- abs(*, recursive=True)[source]
Element-by-element absolute value.
- Parameters:
recursive (bool, optional) – True to include the derivatives. If True, for every element that has its sign flipped, the sign will also be flipped in that element’s derivatives.
- Returns:
The absolute value.
- Return type:
- arccos(*, recursive=True, check=True)[source]
The arccosine of each value.
- Parameters:
recursive (bool, optional) – True to include the derivatives of the arccosine inside the returned object. Defaults to True.
check (bool, optional) – True to mask out the locations of any values outside the domain [-1,1]. If False, a ValueError will be raised if any value is encountered where the arccosine is undefined. Check=True is slightly faster if we already know at the time of the call that all input values are valid.
- Returns:
The arccosine values.
- Return type:
- Raises:
ValueError – If this object has denominators.
ValueError – If check is False and any value is outside domain (-1,1).
- arcsin(*, recursive=True, check=True)[source]
The arcsine of each value.
- Parameters:
recursive (bool, optional) – True to include the derivatives of the arcsine inside the returned object. Defaults to True.
check (bool, optional) – True to mask out the locations of any values outside the domain [-1,1]. If False, a ValueError will be raised if any value is encountered where the arcsine is undefined. Check=True is slightly faster if we already know at the time of the call that all input values are valid.
- Returns:
The arcsine values.
- Return type:
- Raises:
ValueError – If this object has denominators.
ValueError – If check is False and any value is outside domain (-1,1).
- arctan(*, recursive=True)[source]
The arctangent of each value.
- Parameters:
recursive (bool, optional) – True to include the derivatives of the arctangent inside the returned object.
- Returns:
The arctangent values.
- Return type:
- Raises:
ValueError – If this object has denominators.
- arctan2(arg, *, recursive=True)[source]
The four-quadrant value of arctan2(y,x).
If this object is read-only, the returned object will also be read-only.
- Parameters:
arg – The second argument to arctan2().
recursive (bool, optional) – True to include the derivatives of the arctangent inside the returned object. This is the result of merging the derivatives in both this object and the argument object.
- Returns:
The four-quadrant arctangent values.
- Return type:
- Raises:
ValueError – If either object has denominators.
- argmax(axis=None, *, builtins=None, masked=None)[source]
The index of the maximum of the unmasked values along the specified axis.
This returns an integer Scalar array of the same shape as self, except that the specified axis has been removed. Each value indicates the index of the maximum along that axis. The index is masked where the values along the axis are all masked.
If axis is None, then it returns the index of the maximum argument after flattening the array.
- Parameters:
axis (int, optional) – An optional integer axis. If None, it returns the index of the maximum argument in the flattened array.
builtins (bool, optional) – If True and the result is a single unmasked scalar, the result is returned as a Python int instead of an instance of Scalar. Default is the value specified by Qube.prefer_builtins().
masked – Value to return if builtins is True but the returned value is masked. Default is to return a masked value instead of a builtin type.
- Returns:
The index of the maximum value.
- Return type:
Scalar or int
- Raises:
ValueError – If this object has denominators.
ValueError – If this object has shape ().
- argmin(axis=None, *, builtins=None, masked=None)[source]
The index of the minimum of the unmasked values along the specified axis.
This returns an integer Scalar array of the same shape as self, except that the specified axis has been removed. Each value indicates the index of the minimum along that axis. The index is masked where the values along the axis are all masked.
- Parameters:
axis (int, optional) – An optional integer axis. If None, it returns the index of the minimum argument in the flattened array.
builtins (bool, optional) – If True and the result is a single unmasked scalar, the result is returned as a Python int instead of an instance of Scalar. Default is the value specified by Qube.prefer_builtins().
masked – Value to return if builtins is True but the returned value is masked. Default is to return a masked value instead of a builtin type.
- Returns:
The index of the minimum value.
- Return type:
Scalar or int
- Raises:
ValueError – If this object has denominators.
ValueError – If this object has shape ().
- as_index(*, masked=None)[source]
Make this object suitable for indexing an N-dimensional NumPy array.
- Parameters:
masked – The value to insert in the place of a masked item. If None and the object contains masked elements, the array will be flattened and masked elements will be skipped.
- Returns:
An array suitable for indexing.
- Return type:
ndarray
- as_index_and_mask(*, purge=False, masked=None)[source]
Make this object suitable for indexing and masking an N-dimensional array.
- Parameters:
purge (bool, optional) – True to eliminate masked elements from the index; False to retain them but leave them masked.
masked – The index value to insert in place of any masked item. This may be needed because each value in the returned index array must be an integer and in range. If None (the default), then masked values in the index will retain their unmasked values when the index is applied.
- Returns:
A tuple containing (index_array, mask_array).
- Return type:
tuple
- Raises:
IndexError – If this object contains floating-point values.
ValueError – If this object has a denominator.
- static as_scalar(arg, *, recursive=True)[source]
Convert the argument to Scalar if possible.
- Parameters:
arg – The object to convert to Scalar.
recursive (bool, optional) – True to include derivatives in the conversion.
- Returns:
The converted Scalar object.
- Return type:
- cos(*, recursive=True)[source]
The cosine of each value.
- Parameters:
recursive (bool, optional) – True to include the derivatives of the cosine inside the returned object. Defaults to True.
- Returns:
The cosine values.
- Return type:
- Raises:
ValueError – If this object has denominators.
- eval_quadratic(a, b, c, *, recursive=True)[source]
Evaluate a quadratic function for this Scalar.
- The value returned is:
a * self**2 + b * self + c
- Parameters:
a – The coefficient of x**2.
b – The coefficient of x.
c – The constant term.
recursive (bool, optional) – True to include derivatives in the evaluation.
- Returns:
The result of the quadratic evaluation.
- Return type:
- exp(*, recursive=True, check=False)[source]
This Scalar raised to the given power or powers.
If this object is read-only, the returned object will also be read-only.
- Parameters:
recursive (bool, optional) – True to include the derivatives of the function inside the returned object.
check (bool, optional) – True to mask out the locations of any values that will overflow to infinity. If False, a ValueError will be raised any value overflows. Check=True is slightly faster if we already know at the time of the call that all input values are valid.
- Returns:
The exponential values.
- Return type:
- Raises:
ValueError – If this object has denominators.
ValueError – If check is False and any value overflows.
- frac(*, recursive=True)[source]
An object containing the fractional components of all values.
The returned object is an instance of the same subclass as this object.
- Parameters:
recursive (bool, optional) – True to include the derivatives of the returned object. frac() leaves the derivatives unchanged.
- Returns:
An object with fractional components.
- Return type:
- Raises:
ValueError – If this object has denominators.
- identity()[source]
An object of this subclass equivalent to the identity.
This is an override of
Qube.identity().- Returns:
A read-only identity scalar with value 1.
- Return type:
- int(top=None, *, remask=False, clip=False, inclusive=True, shift=None, builtins=None, masked=None)[source]
An integer (floor) version of this Scalar.
If this object already contains integers, it is returned as is. Otherwise, a copy is returned. Derivatives are always removed. Units are disallowed.
Class Vector has a similar method
Vector.int().- Parameters:
top (int, optional) – Optional nominal maximum integer value.
remask (bool, optional) – If True, values less than zero or greater than the specified top value (if provided) are masked.
clip (bool, optional) – If True, values less than zero or greater than the specified top value are clipped.
inclusive (bool, optional) – True to leave the top value unmasked; False to mask it.
shift (bool, optional) – True to shift any occurrences of the top value down by one; False to leave them unchanged. Default None lets shift match the input value of inclusive.
builtins (bool, optional) – If True and the result is a single unmasked scalar, the result is returned as a Python int instead of an instance of Scalar. Default is the value specified by Qube.prefer_builtins().
masked – Value to return if builtins is True but the returned value is masked. Default is to return a masked value instead of a builtin type.
- Returns:
The integer version of this scalar.
- Return type:
Scalar or int
- Raises:
ValueError – If this object has denominators.
- log(*, recursive=True, check=True)[source]
The natural log, masking undefined values.
If this object is read-only, the returned object will also be read-only.
- Parameters:
recursive (bool, optional) – True to include the derivatives of the log inside the returned object. Defaults to True.
check (bool, optional) – True to mask out the locations of any values <= 0 before taking the log. If False, a ValueError will be raised any value <= 0 is encountered. Check=True is slightly faster if we already know at the time of the call that all input values are valid. Defaults to True.
- Returns:
The natural logarithm values.
- Return type:
- Raises:
ValueError – If this object has denominators.
ValueError – If check is False and any value is non-positive.
- max(axis=None, *, builtins=None, masked=None, out=None)[source]
The maximum of the unmasked values.
- Parameters:
axis (int or tuple, optional) – An integer axis or a tuple of axes. The maximum is determined across these axes, leaving any remaining axes in the returned value. If None (the default), then the maximum is performed across all axes if the object.
builtins (bool, optional) – If True and the result is a single unmasked scalar, the result is returned as a Python int or float instead of an instance of Scalar. Default is the value specified by Qube.prefer_builtins().
masked – Value to return if builtins is True but the returned value is masked. Default is to return a masked value instead of a builtin type.
out – Ignored. Enables “np.max(Scalar)” to work.
- Returns:
The maximum values.
- Return type:
Scalar or float or int
- Raises:
ValueError – If this object has denominators.
- static maximum(*args)[source]
A Scalar composed of the maximum among the given Scalars after they are all broadcasted to the same shape.
Masked values are ignored in the comparisons. Derivatives are removed.
- median(axis=None, *, builtins=None, masked=None, out=None)[source]
The median of the unmasked values.
- Parameters:
axis (int or tuple, optional) – An integer axis or a tuple of axes. The median is determined across these axes, leaving any remaining axes in the returned value. If None (the default), then the median is performed across all axes of the object.
builtins (bool, optional) – If True and the result is a single unmasked scalar, the result is returned as a Python int or float instead of an instance of Scalar. Default is the value specified by Qube.prefer_builtins().
masked – Value to return if builtins is True but the returned value is masked. Default is to return a masked value instead of a builtin type.
out – Ignored. Enables “np.median(Scalar)” to work.
- Returns:
The median values.
- Return type:
Scalar or float or int
- Raises:
ValueError – If this object has denominators.
- min(axis=None, *, builtins=None, masked=None, out=None)[source]
The minimum of the unmasked values.
- Parameters:
axis (int or tuple, optional) – An integer axis or a tuple of axes. The minimum is determined across these axes, leaving any remaining axes in the returned value. If None (the default), then the minimum is performed across all axes if the object.
builtins (bool, optional) – If True and the result is a single unmasked scalar, the result is returned as a Python int or float instead of an instance of Scalar. Default is the value specified by Qube.prefer_builtins().
masked – Value to return if builtins is True but the returned value is masked. Default is to return a masked value instead of a builtin type.
out – Ignored. Enables “np.min(Scalar)” to work.
- Returns:
The minimum values.
- Return type:
Scalar or float or int
- Raises:
ValueError – If this object has denominators.
- static minimum(*args)[source]
A Scalar composed of the minimum among the given Scalars after they are all broadcasted to the same shape.
- reciprocal(*, recursive=True, nozeros=False)[source]
An object equivalent to the reciprocal of this object.
This is an override of
Qube.reciprocal().- Parameters:
recursive (bool, optional) – True to return the derivatives of the reciprocal too; otherwise, derivatives are removed.
nozeros (bool, optional) – False (the default) to mask out any zero-valued items in this object prior to the divide. Set to True only if you know in advance that this object has no zero-valued items.
- Returns:
The reciprocal of this object.
- Return type:
- Raises:
ValueError – If this object has denominators.
ValueError – If nozeros is True and a zero value is encountered.
- sign(*, zeros=True, builtins=None, masked=None)[source]
The sign of each value as +1, -1 or 0.
- Parameters:
zeros (bool, optional) – If zeros is False, then only values of +1 and -1 are returned; sign(0) = +1 instead of 0.
builtins (bool, optional) – If True and the result is a single unmasked scalar, the result is returned as a Python int instead of an instance of Scalar. Default is the value specified by Qube.prefer_builtins().
masked – Value to return if builtins is True but the returned value is masked. Default is to return a masked value instead of a builtin type.
- Returns:
The sign values.
- Return type:
Scalar or int
- sin(*, recursive=True)[source]
The sine of each value.
- Parameters:
recursive (bool, optional) – True to include the derivatives of the sine inside the returned object. Defaults to True.
- Returns:
The sine values.
- Return type:
- Raises:
ValueError – If this object has denominators.
- static solve_quadratic(a, b, c, *, recursive=True, include_antimask=False)[source]
A tuple containing the two results of a quadratic equation as Scalars.
- Duplicates and complex values are masked. The formula solved is:
a * x**2 + b * x + c = 0
The solution is implemented to provide maximal precision.
- Parameters:
a – The coefficient of x**2.
b – The coefficient of x.
c – The constant term.
recursive (bool, optional) – True to include derivatives in the solution.
include_antimask (bool, optional) – If True, a Boolean is also returned containing True where the solution exists (because the discriminant is nonnegative).
- Returns:
A tuple containing (x0, x1) or (x0, x1, antimask) if include_antimask is True.
- Return type:
tuple
- sort(axis=0)[source]
The array sorted along the specified axis from minimum to maximum.
Masked values appear at the end.
- Parameters:
axis (int) – An integer axis to sort along.
- Returns:
The sorted array.
- Return type:
- Raises:
ValueError – If this object has denominators.
- sqrt(*, recursive=True, check=True)[source]
The square root, masking imaginary values.
If this object is read-only, the returned object will also be read-only.
- Parameters:
recursive (bool, optional) – True to include the derivatives of the square root inside the returned object.
check (bool, optional) – True to mask out the locations of any values < 0 before taking the square root. If False, a ValueError will be raised any negative value encountered. Check=True is slightly faster if we already know at the time of the call that all input values are valid.
- Returns:
The square root values.
- Return type:
- Raises:
ValueError – If this object has denominators.
ValueError – If check is False and any value is negative.
- tan(*, recursive=True)[source]
The tangent of each value.
- Parameters:
recursive (bool, optional) – True to include the derivatives of the tangent inside the returned object. Defaults to True.
- Returns:
The tangent values.
- Return type:
- Raises:
ValueError – If this object has denominators.
- to_scalar(indx, *, recursive=True)[source]
This scalar (duplicates Vector.to_scalar behavior).
- Parameters:
indx (int) – Index of the vector component; must be zero.
recursive (bool, optional) – True to include the derivatives.
- Returns:
This scalar object.
- Return type:
- Raises:
ValueError – If indx is not zero.
- class Unit(exponents, triple, name=None)[source]
Bases:
objectClass to represent units and provide conversion methods.
- exponents
Three integers representing the exponents on dimensions of length, time, and angle, respectively.
- Type:
tuple
- triple
Three integers representing the exact factor that one must multiply a value in this unit by to a value in standard units involving (km, seconds, and radians). This factor is represented by three numbers, (numer, denom, and expo), where the exact factor equals (numer/denom * pi**expo).
- Type:
tuple
- name
An optional name for this unit. Alternatively, a name can be defined by a dictionary keyed by unit names, returning exponents. For example, the name “km/s” can be given by {“km”:1, “s”:-1}.
- Type:
str, dict or None
Examples
degree unit is represented by exponents (0, 0, 1) and triple (1, 180, 1), because one multiplies degrees by pi/180 to obtain radians.
m/s uni is represented by exponents (1, -1, 0) and triple (1, 1000, 0), because one multiples meters per second by 1/1000 to obtain km per second.
Notes
Most common unit values are defined as class constants, e.g., Unit.DEGREE and Unit.STER.
In most situations, a given Unit value of None is equivalent to Unit.UNITLESS, the Unit associated with a dimensionless value.
- ARCHOUR = Unit(archour)
- ARCHOURS = Unit(archours)
- ARCMIN = Unit(arcmin)
- ARCMINUTE = Unit(arcminute)
- ARCMINUTES = Unit(arcminutes)
- ARCSEC = Unit(arcsec)
- ARCSECOND = Unit(arcsecond)
- ARCSECONDS = Unit(arcseconds)
- CENTIMETER = Unit(centimeter)
- CENTIMETERS = Unit(centimeters)
- CM = Unit(cm)
- CYCLE = Unit(cycle)
- CYCLES = Unit(cycles)
- D = Unit(d)
- DAY = Unit(day)
- DAYS = Unit(days)
- DEG = Unit(deg)
- DEGREE = Unit(degree)
- DEGREES = Unit(degrees)
- H = Unit(h)
- HOUR = Unit(hour)
- HOURS = Unit(hours)
- KILOMETER = Unit(kilometer)
- KILOMETERS = Unit(kilometers)
- KM = Unit(km)
- M = Unit(m)
- METER = Unit(meter)
- METERS = Unit(meters)
- MICRON = Unit(micron)
- MICRONS = Unit(microns)
- MILLIMETER = Unit(millimeter)
- MILLIMETERS = Unit(millimeters)
- MILLIRAD = Unit(millirad)
- MIN = Unit(min)
- MINUTE = Unit(minute)
- MINUTES = Unit(minutes)
- MM = Unit(mm)
- MRAD = Unit(mrad)
- MS = Unit(ms)
- MSEC = Unit(msec)
- RAD = Unit(rad)
- RADIAN = Unit(radian)
- RADIANS = Unit(radians)
- REV = Unit(rev)
- REVS = Unit(revs)
- ROTATION = Unit(rotation)
- ROTATIONS = Unit(rotations)
- S = Unit(s)
- SEC = Unit(sec)
- SECOND = Unit(second )
- SECONDS = Unit(seconds)
- STER = Unit(ster)
- UNITLESS = Unit()
- __eq__(arg)[source]
Check if this Unit object equals another.
- Parameters:
arg (Unit or None) – The Unit object to compare with.
- Returns:
True if the Unit objects are equal, False otherwise.
- Return type:
bool
- __init__(exponents, triple, name=None)[source]
Initialize a Unit object.
- Parameters:
exponents (tuple) – A tuple of integers defining the exponents on distance, time and angle that are used for this unit.
triple (tuple) –
A tuple containing:
[0] The numerator of a factor that converts from a value in this unit to a value using standard units of km, seconds, and radians.
[1] The denominator of this same factor.
[2] The exponent on pi that should multiply the numerator of this factor.
name (str or dict, optional) – The name of the unit. It is represented by a string or by a dictionary of unit exponents keyed by the unit names.
Notes
For example, a unit of degrees would have a triple (1,180,1). This defines a factor pi/180, which converts from degrees to radians.
- __ne__(arg)[source]
Check if this Unit object does not equal another.
- Parameters:
arg (Unit or None) – The Unit object to compare with.
- Returns:
True if the Unit objects are not equal, False otherwise.
- Return type:
bool
- __pow__(power)[source]
Raise this Unit object to the specified power.
- Parameters:
power (int or float) – The exponent. Must be an integer or half-integer.
- Returns:
This Unit object raised to the specified power.
- Return type:
- Raises:
ValueError – If the power is not an integer or half-integer.
- __repr__()[source]
Return a detailed string representation of this Unit object.
- Returns:
A detailed string representation of the unit.
- Return type:
str
- __rtruediv__(arg)[source]
Divide a scalar by this Unit object.
- Parameters:
arg (None or numbers.Real) – The scalar to divide.
- Returns:
The reciprocal of this Unit object multiplied by arg.
- Return type:
- Raises:
NotImplementedError – If the argument type is not supported.
- __str__()[source]
Return a string representation of this Unit object.
- Returns:
A string representation of the unit.
- Return type:
str
- static as_unit(arg)[source]
Convert the given argument to a Unit object.
- Parameters:
arg – The argument to convert. Can be an object of class Unit, one of the standard unit names, or None.
- Returns:
The converted Unit object, or None if arg is None.
- Return type:
Unit or None
- Raises:
ValueError – If the argument is not a recognized unit.
- convert(value, unit, info='')[source]
Convert the unit of a scalar or NumPy array.
The value is assumed to be in this unit, and it is returned in the new unit specified. Conversions are exact whenever possible.
- Parameters:
value (scalar or ndarray) – The value to convert.
unit (Unit or None) – The target unit. If None, converts to unitless.
info (str, optional) – Info to embed into the error message.
- Returns:
The converted value in the target unit.
- Return type:
scalar or ndarray
- Raises:
ValueError – If the units are incompatible for conversion.
- copy()[source]
Return a copy of this Unit object.
- Returns:
A copy of this Unit object.
- Return type:
- create_name()[source]
Create a name for this Unit object based on its exponents.
- Returns:
A name for this Unit object.
- Return type:
str
- static div_names(name1, name2)[source]
Divide two unit names.
- Parameters:
name1 (str, dict, or None) – The numerator unit name.
name2 (str, dict, or None) – The denominator unit name.
- Returns:
The quotient of the two unit names, or None if both arguments are None.
- Return type:
str or dict or None
- from_this(value)[source]
Convert a scalar or numpy array in this unit to a standard unit.
- Parameters:
value (scalar or ndarray) – The value to convert from this unit to standard units of km, seconds and radians.
- Returns:
The value converted to a standard unit.
- Return type:
scalar or ndarray
- static from_unit(unit, value)[source]
Convert a scalar or numpy array in the given unit to a standard unit.
- Parameters:
unit (Unit or None) – The unit to convert from.
value (scalar or ndarray) – The value to convert.
- Returns:
- The converted value in standard unit of km, seconds and
radians.
- Return type:
scalar or ndarray
- property from_unit_factor
- get_name()[source]
Get the name of this Unit object.
- Returns:
The name of this Unit object.
- Return type:
str or dict or None
- into_this(value)[source]
Convert a scalar or numpy array from a standard unit to this unit.
- Parameters:
value (scalar or ndarray) – The value to convert from a standard unit to this unit.
- Returns:
The converted value in this unit.
- Return type:
scalar or ndarray
- static into_unit(unit, value)[source]
Convert a scalar or numpy array from a standard unit to given unit.
- Parameters:
unit (Unit or None) – The unit to convert to.
value (scalar or ndarray) – The value to convert.
- Returns:
The converted value in the given unit.
- Return type:
scalar or ndarray
- property into_unit_factor
- static is_angle(arg)[source]
Check if the argument could be used as an angle.
- Parameters:
arg (Unit or None) – The unit object to check.
- Returns:
True if the argument could be used as an angle.
- Return type:
bool
- static is_unitless(arg)[source]
True if the argument is unitless.
- Parameters:
arg (Unit or None) – The unit object to check.
- Returns:
True if the argument is unitless.
- Return type:
bool
- static name_power(name, power)[source]
Raise a unit name to the specified power.
- Parameters:
name (str, dict, or None) – The unit name to raise to a power.
power (int or float) – The exponent.
- Returns:
The unit name raised to the specified power, or None if name is None.
- Return type:
str or dict or None
- static name_to_dict(name)[source]
Convert a unit name string to a dictionary.
- Parameters:
name (str or dict) – The unit name to convert.
- Returns:
A dictionary representation of the unit name.
- Return type:
dict
- Raises:
ValueError – If the name format is invalid.
- static name_to_str(namedict)[source]
Convert a unit name dictionary to a string.
- Parameters:
namedict (dict or None) – The unit name dictionary to convert.
- Returns:
A string representation of the unit name, or empty string if namedict is None.
- Return type:
str
Notes
This method contains nested helper functions for ordering keys and concatenating units.
- static require_angle(arg, info='')[source]
Raise a ValueError if the argument could not be used as an angle.
- Parameters:
arg (Unit or None) – The unit object to check.
info (str, optional) – Info to embed into the error message.
- Raises:
ValueError – If the units are incompatible with an angle.
- static require_compatible(first, second, info='')[source]
Raise a ValueError if the arguments are not compatible units.
- static require_match(first, second, info='')[source]
Raise a ValueError if the units are not the same.
- static require_unitless(arg, info='')[source]
Raise a ValueError if the argument is not unitless.
- Parameters:
arg (Unit or None) – The unit object to check.
info (str, optional) – Info to embed into the error message.
- Raises:
ValueError – If a unit is not permitted.
- set_name(name)[source]
Set the name of this Unit object.
- Parameters:
name (str or dict) – The new name for this Unit object.
- sqrt(name=None)[source]
Return the square root of this Unit object.
- Parameters:
name (str or dict, optional) – The name for the resulting unit.
- Returns:
The square root of this Unit object.
- Return type:
- Raises:
ValueError – If the exponents are not even numbers.
- static unit_power(unit, power, name=None)[source]
Raise a Unit object to the specified power.
- Parameters:
unit (Unit or None) – The Unit object to raise to a power.
power (int or float) – The exponent. Must be an integer or half-integer.
name (str or dict, optional) – The name for the resulting unit.
- Returns:
The Unit object raised to the specified power, or None if unit is None.
- Return type:
Unit or None
- Raises:
ValueError – If the power is not an integer or half-integer.
- class Vector(*values, **keywords)[source]
Bases:
QubeRepresentation of 1-D vectors of arbitrary length in the PolyMath framework.
This class handles arbitrary length one-dimensional vectors and provides operations for vector arithmetic, dot products, and other mathematical operations.
- MASKED2 = Vector(-- --; mask)
- MASKED3 = Vector(-- -- --; mask)
- XAXIS2 = Vector(1. 0.)
- XAXIS3 = Vector(1. 0. 0.)
- YAXIS2 = Vector(0. 1.)
- YAXIS3 = Vector(0. 1. 0.)
- ZAXIS3 = Vector(0. 0. 1.)
- ZERO2 = Vector(0. 0.)
- ZERO3 = Vector(0. 0. 0.)
- __abs__(recursive=True)[source]
Return the Euclidean norm of this Vector.
- Parameters:
recursive (bool, optional) – If True, include derivatives in the result.
- Returns:
The Euclidean norm (magnitude) of the Vector.
- Return type:
- __init__(arg, *args, **kwargs)[source]
Initialize a Vector object.
- Parameters:
arg (ndarray, float, int, list, or tuple) – The input data to construct the Vector. A Python scalar will be converted to an array of shape (1,).
*args – Additional arguments passed to the Qube constructor.
**kwargs – Additional “keyword=value” arguments passd to the Qube constructor.
- as_column(recursive=True)[source]
Convert the Vector to an Nx1 column matrix.
- Parameters:
recursive (bool, optional) – If True, include derivatives in the result.
- Returns:
An Nx1 matrix representation of this Vector.
- Return type:
- as_diagonal(*, recursive=True)[source]
Convert the vector to a diagonal matrix.
- Parameters:
recursive (bool, optional) – If True, include derivatives in the result.
- Returns:
A diagonal matrix where the diagonal elements are the components of this Vector.
- Return type:
- as_index(masked=None)[source]
Convert this object to a form suitable for indexing a NumPy array.
The returned object is a tuple of NumPy arrays, each containing indices along the corresponding axis of the array being indexed.
- Parameters:
masked (scalar, list, tuple, or array, optional) – The index or indices to insert in place of masked items. If None and the object contains masked elements, the array will be flattened and masked elements will be skipped over.
- Returns:
A tuple of NumPy arrays suitable for indexing.
- Return type:
tuple
- as_index_and_mask(purge=False, masked=None)[source]
Convert this object to a form suitable for indexing and masking an array.
- Parameters:
purge (bool, optional) – True to eliminate masked elements from the index; False to retain them but leave them masked.
masked (scalar, optional) – The index value to insert in place of any masked item. This may be needed because each value in the returned index array must be an integer and in range. If None, masked values in the index will retain their unmasked values when the index is applied.
- Returns:
A tuple containing (index, mask), where index is suitable for indexing a NumPy ndarray and mask indicates which values are masked.
- Return type:
tuple
- Raises:
TypeError – If this object contains floating-point values.
ValueError – If this object has a unit or a denominator.
- as_row(*, recursive=True)[source]
Convert the Vector to a 1xN row matrix.
- Parameters:
recursive (bool, optional) – If True, include derivatives in the result.
- Returns:
A 1xN matrix representation of this Vector.
- Return type:
- static as_vector(arg, *, recursive=True)[source]
Convert the argument to a Vector if possible.
- Parameters:
arg (object) – The object to convert to Vector.
recursive (bool, optional) – If True, derivatives will also be converted.
- Returns:
The converted Vector object.
- Return type:
- clip_component(axis, lower, upper, remask=False)[source]
Return a copy with component values clipped to specified range.
Creates a copy of this object where values of a specified component that are outside a given range are shifted to the closest in-range value.
- Parameters:
axis (int) – The index of the component to use for comparison.
lower (scalar or Scalar) – The lower limit for clipping; None to ignore. This can be a single scalar or a Scalar object of the same shape as the object.
upper (scalar or Scalar) – The upper limit for clipping; None to ignore. This can be a single scalar or a Scalar object of the same shape as the object.
remask (bool, optional) – True to mask the clipped values in the object’s mask; False to replace the values but leave them unmasked.
- Returns:
A copy with clipped component values. If no items need to be clipped, this object is returned unchanged.
- Return type:
- Raises:
ValueError – If this Vector has denominators.
- classmethod combos(*args)[source]
Create a vector with every combination of components of given scalars.
Masks are also combined in the analogous manner. Units and derivatives are ignored.
- Parameters:
*args – Scalar objects to combine.
- Returns:
A vector with shape defined by concatenating the shapes of all the arguments.
- Return type:
- Raises:
ValueError – If any scalar input has a denominator.
- cross_product_as_matrix(*, recursive=True)[source]
Convert to a Matrix whose multiply equals a cross product with this vector.
This method creates a 3×3 antisymmetric matrix that, when multiplied with another vector, produces the same result as the cross product of this vector with that vector.
- Parameters:
recursive (bool, optional) – If True, include derivatives in the result.
- Returns:
A 3×3 matrix that represents the cross product operation.
- Return type:
- Raises:
ValueError – If this Vector doesn’t have exactly 3 components or if it has denominators.
- element_div(arg, recursive=True)[source]
Perform element-by-element division of two vectors.
- Parameters:
arg (Vector or vector-like) – The vector to divide by element-wise.
recursive (bool, optional) – If True, include derivatives in the result.
- Returns:
The element-wise division of this vector by the argument.
- Return type:
- Raises:
ValueError – If the numerator shapes are incompatible or if the argument has a denominator.
- element_mul(arg, *, recursive=True)[source]
Perform element-by-element multiplication of two vectors.
- Parameters:
arg (Vector or vector-like) – The vector to multiply element-wise.
recursive (bool, optional) – If True, include derivatives in the result.
- Returns:
The element-wise product of this vector and the argument.
- Return type:
- Raises:
ValueError – If the numerator shapes are incompatible or if both this vector and the argument have denominators.
- static from_scalars(*args, recursive=True, readonly=False)[source]
Construct a Vector by combining scalar components.
- Parameters:
*args – Scalar objects defining the vector’s components. They need not have the same shape, but it must be possible to cast them to the same shape. A value of None is converted to a zero-valued Scalar that matches the denominator shape of the other arguments.
recursive (bool, optional) – True to include all the derivatives. The returned object will have derivatives representing the union of all the derivatives found among the arguments.
readonly (bool, optional) – True to return a read-only object; False to return something potentially writable.
- Returns:
A vector constructed from the provided scalar components.
- Return type:
- identity()[source]
Raise an error as identity is not supported for Vectors.
- Raises:
ValueError – Always, as identity operation is not supported for Vectors.
- int(top=None, remask=False, clip=False, inclusive=True, shift=None)[source]
Return an integer (floor) version of this Vector.
If this object already contains integers, it is returned as is. Otherwise, a copy is returned with values converted to np.intp. Derivatives are always removed and units are disallowed.
Class Scalar has a similar method
Scalar.int().- Parameters:
top (tuple, optional) – Tuple of maximum integer values for each component, equivalent to the array shape.
remask (bool, optional) – If True, values less than zero or greater than the specified top values (if provided) are masked.
clip (bool or tuple of bool, optional) – If True, values less than zero or greater than the specified top values are clipped. Use a tuple of booleans to handle the axes differently.
inclusive (bool or tuple of bool, optional) – True to leave the top limits unmasked; False to mask them. Use a tuple of booleans to handle the axes differently.
shift (bool or tuple of bool, optional) – True to shift any occurrences of the top limit down by one; False to leave them unchanged. Use a tuple of booleans to handle the axes differently. Default is None, which sets shift to match the value of inclusive.
- Returns:
An integer version of this Vector.
- Return type:
- Raises:
ValueError – If this object has a unit or a denominator.
- mask_where_component_ge(axis, limit, replace=None, remask=True)[source]
Return a copy with masked values where a component is >= a limit.
Creates a copy of this object where values of a specified component that are greater than or equal to a limit value are masked.
- Parameters:
axis (int) – The index of the component to use for comparison.
limit (scalar or Scalar) – The limiting value or a Scalar of limiting values.
replace (scalar or array, optional) – A single replacement value or an array of replacement values, inserted at every masked location. Use None to to leave values unchanged.
remask (bool, optional) – True to include the new mask in the object’s mask; False to replace the values but leave them unmasked.
- Returns:
A copy with masked or replaced values where the component is greater than or equal to the limit. If no items need to be masked, this object is returned unchanged.
- Return type:
- mask_where_component_gt(axis, limit, replace=None, remask=True)[source]
Return a copy with masked values where a component is > a limit.
Creates a copy of this object where values of a specified component that are greater than a limit value are masked.
- Parameters:
axis (int) – The index of the component to use for comparison.
limit (scalar or Scalar) – The limiting value or a Scalar of limiting values.
replace (scalar or array, optional) – A single replacement value or an array of replacement values, inserted at every masked location. Use None to leave values unchanged.
remask (bool, optional) – True to include the new mask in the object’s mask; False to replace the values but leave them unmasked.
- Returns:
A copy with masked or replaced values where the component is greater than the limit. If no items need to be masked, this object is returned unchanged.
- Return type:
- mask_where_component_le(axis, limit, replace=None, remask=True)[source]
Return a copy with masked values where a component is <= a limit.
Creates a copy of this object where values of a specified component that are less than or equal to a limit value are masked.
- Parameters:
axis (int) – The index of the component to use for comparison.
limit (scalar or Scalar) – The limiting value or a Scalar of limiting values.
replace (scalar or array, optional) – A single replacement value or an array of replacement values, inserted at every masked location. Use None to leave values unchanged.
remask (bool, optional) – True to include the new mask in the object’s mask; False to replace the values but leave them unmasked.
- Returns:
A copy with masked or replaced values where the component is less than or equal to the limit. If no items need to be masked, this object is returned unchanged.
- Return type:
- mask_where_component_lt(axis, limit, replace=None, remask=True)[source]
Return a copy with masked values where a component is < a limit.
Creates a copy of this object where values of a specified component that are less than a limit value are masked.
- Parameters:
axis (int) – The index of the component to use for comparison.
limit (scalar or Scalar) – The limiting value or a Scalar of limiting values.
replace (scalar or array, optional) – A single replacement value or an array of replacement values, inserted at every masked location. Use None to leave values unchanged.
remask (bool, optional) – True to include the new mask in the object’s mask; False to replace the values but leave them unmasked.
- Returns:
A copy with masked or replaced values where the component is less than the limit. If no items need to be masked, this object is returned unchanged.
- Return type:
- norm(*, recursive=True)[source]
Calculate the Euclidean length (magnitude) of this Vector.
- Parameters:
recursive (bool, optional) – If True, include derivatives in the result.
- Returns:
The Euclidean norm of this Vector.
- Return type:
- norm_sq(*, recursive=True)[source]
Calculate the squared length of this Vector.
- Parameters:
recursive (bool, optional) – If True, include derivatives in the result.
- Returns:
The squared Euclidean norm of this Vector.
- Return type:
- outer(arg, *, recursive=True)[source]
Return the outer product of two vectors, resulting in a Matrix.
- reciprocal(nozeros=False)[source]
Return the reciprocal of this Vector as a Jacobian..
This Vector must be a Jacobian, i.e., the derivative of one Vector with respect to another. The reciprocal is therefore the matrix inverse, the derivative of the second vector with respect to the first.
This method overrides
reciprocal()for the base class.- Parameters:
nozeros (bool, optional) – False to mask out any matrices with zero-valued determinants. Set to True only if you know in advance that all determinants are nonzero.
- Raises:
ValueError – If the two Vectors do not have the same dimension (meaning the matrix in not square).
ValueError – If nozeros is True but a determinant of zero is encountered.
- sep(arg, *, recursive=True)[source]
Calculate the separation angle between this vector and another.
Works for vectors of length 2 or 3.
- to_pair(axes=(0, 1), *, recursive=True)[source]
Return a Pair containing two selected components of this Vector.
Overrides the default method to include an ‘axes’ argument, which can extract any two components of a Vector very efficiently.
- Parameters:
axes (tuple, optional) – Indices of the two components to extract, positive or negative.
recursive (bool, optional) – If True, include derivatives in the result.
- Returns:
A Pair object containing the two selected components.
- Return type:
- to_scalar(indx, *, recursive=True)[source]
Return one of the components of this Vector as a Scalar.
- Parameters:
indx (int) – Index of the vector component.
recursive (bool, optional) – True to include the derivatives.
- Returns:
The component at the specified index.
- Return type:
- to_scalars(*, recursive=True)[source]
Return all the components of this Vector as a tuple of Scalars.
- Parameters:
recursive (bool, optional) – True to include the derivatives.
- Returns:
A tuple containing each component as a Scalar.
- Return type:
tuple
- ucross(arg, *, recursive=True)[source]
Calculate the unit vector in the direction of the cross product.
Works only for vectors of length 3.
- unit(*, recursive=True)[source]
Convert this vector to a unit vector (normalized to length 1).
- Parameters:
recursive (bool, optional) – If True, include derivatives in the result.
- Returns:
A unit vector in the same direction as this Vector.
- Return type:
- vector_scale(factor, recursive=True)[source]
Stretch this Vector along a direction defined by a scaling vector.
Components of the vector perpendicular to the scaling vector are unchanged. The scaling amount is determined by the magnitude of the scaling vector.
- vector_unscale(factor, recursive=True)[source]
Un-stretch this Vector along a direction defined by a scaling vector.
Components of the vector perpendicular to the scaling vector are unchanged. The un-scaling amount is determined by the magnitude of the scaling vector.
- class Vector3(*values, **keywords)[source]
Bases:
VectorRepresent 3-dimensional vectors in the PolyMath framework.
This class provides specialized functionality for working with 3-element vectors, including coordinate transformations and 3D operations.
- AXES = (Vector3(1. 0. 0.), Vector3(0. 1. 0.), Vector3(0. 0. 1.))
- IDENTITY = Vector3([[1. 0. 0.] [0. 1. 0.] [0. 0. 1.]]; denom=(3,))
- MASKED = Vector3(-- -- --; mask)
- ONES = Vector3(1. 1. 1.)
- XAXIS = Vector3(1. 0. 0.)
- YAXIS = Vector3(0. 1. 0.)
- ZAXIS = Vector3(0. 0. 1.)
- ZERO = Vector3(0. 0. 0.)
- ZERO_POS_VEL = Vector3(0. 0. 0.; d_dt)
- static as_vector3(arg, *, recursive=True)[source]
Convert the argument to Vector3 if possible.
- Parameters:
arg (object) – The object to convert to Vector3.
recursive (bool, optional) – If True, derivatives will also be converted.
- Returns:
The converted Vector3 object.
- Return type:
- static from_cylindrical(radius, longitude, z=0.0, *, recursive=True)[source]
Construct a Vector3 from cylindrical coordinates.
- Parameters:
radius (Scalar) – Distance from the cylindrical axis.
longitude (Scalar) – Longitude in radians. Zero is along the x-axis.
z (Scalar, optional) – Distance above/below the equatorial plane.
recursive (bool, optional) – True to include all the derivatives. The returned object will have derivatives representing the union of all the derivatives in radius, longitude and z.
- Returns:
A new Vector3 object constructed from the cylindrical coordinates.
- Return type:
Notes
Input arguments need not have the same shape, but it must be possible to cast them to the same shape.
- static from_ra_dec_length(ra, dec, length=1.0, *, recursive=True)[source]
Construct a Vector3 from right ascension, declination and optional length.
- Parameters:
ra (Scalar) – Right ascension in radians.
dec (Scalar) – Declination in radians.
length (Scalar, optional) – Length of the vector.
recursive (bool, optional) – True to include all the derivatives. The returned object will have derivatives representing the union of all the derivatives in ra, dec and length.
- Returns:
A new Vector3 object constructed from the spherical coordinates.
- Return type:
Notes
Input arguments need not have the same shape, but it must be possible to cast them to the same shape.
- static from_scalars(x, y, z, *, recursive=True, readonly=False)[source]
Construct a Vector3 by combining three scalars.
- Parameters:
x (Scalar or convertible) – First component of the vector.
y (Scalar or convertible) – Second component of the vector.
z (Scalar or convertible) – Third component of the vector.
recursive (bool, optional) – True to include all the derivatives. The returned object will have derivatives representing the union of all the derivatives found among x, y and z.
readonly (bool, optional) – True to return a read-only object; False to return something potentially writable.
- Returns:
A new Vector3 object constructed from the three scalars.
- Return type:
Notes
Input arguments need not have the same shape, but it must be possible to cast them to the same shape. A value of None is converted to a zero-valued Scalar that matches the denominator shape of the other arguments.
- latitude(*, recursive=True)[source]
Return the latitude (elevation angle) of this Vector3.
- Parameters:
recursive (bool, optional) – True to include the derivatives.
- Returns:
The latitude in radians, measured from the equatorial plane toward the Z-axis.
- Return type:
- longitude(*, recursive=True)[source]
Return the longitude (azimuthal angle) of this Vector3.
- Parameters:
recursive (bool, optional) – True to include the derivatives.
- Returns:
The longitude in radians, measured from the X-axis toward the Y-axis.
- Return type:
- offset_angles(vector, *, recursive=True)[source]
Return the angular offset between this Vector3 and another.
- Parameters:
vector (Vector3) – The vector to measure the offset from.
recursive (bool, optional) – True to include the derivatives.
- Returns:
(longitude_offset, latitude_offset) angles in radians.
- Return type:
tuple
- spin(pole, angle=None, *, recursive=True)[source]
Return this Vector3 rotated about a pole vector.
- Parameters:
- Returns:
The rotated vector.
- Return type:
Notes
If angle is None, the pole vector’s magnitude is used as the rotation angle.