Package: quaternionic
Quaternionic arraysThis module subclasses numpy's array type, interpreting the array as an array of quaternions, and
accelerating the algebra using numba.  This enables natural manipulations, like multiplying
quaternions asa*b, while also working with standard numpy functions, as innp.log(q).  There is
also basic initial support for symbolic manipulation of quaternions by creating quaternionic arrays
with sympy symbols as elements, though this is a work in progress.This package has evolved from thequaternionpackage, which
adds a quaternion dtype directly to numpy.  In some ways, that is a better approach because dtypes
are built in to numpy, making it more robust than this package.  However, that approach has its own
limitations, including that it is harder to maintain, and requires much of the code to be written in
C, which also makes it harder to distribute.  This package is written entirely in python code, but
should actually have comparable performance because it is compiled by numba.  Moreover, because the
core code is written in pure python, it is reusable for purposes other than the core purpose of this
package, which is to provide the numeric array type.InstallationBecause this package is pure python code, installation is very simple.  In particular, with
a reasonably modern installation, you can just runcondainstall-cconda-forgequaternionicorpython-mpipinstallquaternionicThese will download and install the package.  (Usingpython -m pipinstead of justpiporpip3helps avoid problems that new python users frequently run into; the reason is explained by a veteran
python core contributorhere.)You can also install the package from source if you havepipversion 10.0 or greater by runningpython -m pip install .— or if you havepoetryby runningpoetry install— from the top-level
directory.Note that only python 3.8 or greater is supported.  (I have also tried to support PyPy3, although
I cannot test this asscipydoes not currently install.  Pull requests are welcome.)  In any case,
I strongly recommend installing by way of an environment manager — especiallyconda, though other managers likevirtualenvorpipenvshould also work.For development work, the best current option ispoetry.  From the
top-level directory, you can runpoetry run <some command>to run the command in an isolated
environment.UsageBasic constructionThe key function isquaternionic.array, which takes nearly the same arguments asnumpy.array,
except that whatever array will result must have a final axis of size 4 (and thedtypemust befloat).  As long as these conditions are satisfied, we can create new arrays or just reinterpret
existing arrays:importnumpyasnpimportquaternionica=np.random.normal(size=(17,11,4))# Just some random numbers; last dimension is 4q1=quaternionic.array(a)# Reinterpret an existing arrayq2=quaternionic.array([1.2,2.3,3.4,4.5])# Create a new arrayIn this example,q1is an array of 187 (17*11) quaternions, just to demonstrate that any number of
dimensions may be used, as long as the final dimension has size 4.Here, the original arrayawill still exist just as it was, and will behave just as a normal numpy
array — including changing its values (which will change the values inq1), slicing, math, etc.
However,q1will be another"view"into the same
data.  Operations onq1will be quaternionic.  For example, whereas1/areturns the element-wise
inverse of each float in the array,1/q1returns thequaternionicinverse of each quaternion.
Similarly, if you multiply two quaternionic arrays, their product will be computed with the usual
quaternion multiplication, rather than element-wise multiplication of floats as numpy usually
performs.:warning: WARNINGBecause of an unfortunate choice by the numpy developers, thenp.copyfunction will not preserve the quaternionic nature of an array by default; the result will just be a plain array of floats.  You could pass the optional argumentsubok=True, as inq3 = np.copy(q1, subok=True), but it's easier to just use the member function:q3 = q1.copy().AlgebraAll the usual quaternion operations are available, includingAdditionq1 + q2Subtractionq1 - q2Multiplicationq1 * q2Divisionq1 / q2Scalar multiplicationq1 * s == s * q1Scalar divisionq1 / sands / q1Reciprocalnp.reciprocal(q1) == 1/q1Exponentialnp.exp(q1)Logarithmnp.log(q1)Square-rootnp.sqrt(q1)Conjugatenp.conjugate(q1) == np.conj(q1)All numpyufuncsthat make sense for
quaternions are supported.  When the arrays have different shapes, the usual numpybroadcastingrules take effect.AttributesIn addition to the basic numpy array features, we also have a number of extra properties that are
particularly useful for quaternions, includingMethods to extract and/or set componentsw,x,y,zi,j,k(equivalent tox,y,z)scalar,vector(equivalent tow, [x,y,z])real,imag(equivalent toscalar,vector)Methods related to normsabs(square-root of sum of squares of components)norm(sum of squares of components)modulus,magnitude(equal toabs)absolute_square,abs2,mag2(equal tonorm)normalizedinverseMethods related to array infrastructurendarray(the numpy array underlying the quaternionic array)flattened(all dimensions but last are flattened into one)iterator(iterate over all quaternions)Note that this package makes a distinction betweenabsandnorm— the latter being equal to the
square of the former.  This version of the norm is also known as the "Cayley" norm, commonly used
when emphasizing the properties of an object in an algebra, as opposed to the "Euclidean" norm more
common when emphasizing the properties of an object in a vector space — though of course, algebras
are vector spaces with additional structure.  This choice agrees with theBoost library's
implementation of
quaternions,
as well as this package's forerunnerquaternion.
This also agrees with the corresponding functions on theC++ standard library's complex
numbers.  Because this may be confusing, a number
of aliases are also provided that may be less confusing.  For example, some people find the pairabsandabs2(meaning the square ofabs) to be more sensible.RotationsThe most common application of quaternions is to representing rotations by means of unit
quaternions.  Note that this package does notrestrictquaternions to have unit norms, since it is
usually better for numerical purposes not to do so.  For example, whereas rotation of a vector $v$
by a quaternion is usually implemented as $R, v, \bar{R}$, it is generally better to drop the
assumption that the quaternion has unit magnitude and implement rotation as $R, v, R^{-1}$.  This
is almost always more efficient, and more accurate.  That is what this package does by default
whenever rotations are involved.Although this package does not restrict to unit quaternions, there are several converters to and
from other representations of rotations.  First, we haveto_vector_part,from_vector_partThese convert between the standard 3-d vector representation and their equivalent quaternions, which
allows them to be manipulated as vectors — as inR * from_vector_part(v) * R.conjugate().  However,
note that you may not need to convert to/from quaternions.  For example, to rotate vectorsvbyR, you can useR.rotate(v)It may also be relevant to consider a vector as a "generator" of
rotations, in which case the actual rotation is obtained by applyingexpto the generator.  Thisdoesrequire conversion to a quaternionic array.  We also have converters that deal with standard
representations of rotations:to_rotation_matrix,from_rotation_matrixto_transformation_matrix(for non-unit quaternions)to_axis_angle,from_axis_angleto_euler_angles,from_euler_angles(though using Euler angles is almost always a bad idea)to_euler_phases,from_euler_phases(see above)to_spherical_coordinates,from_spherical_coordinatesto_angular_velocity,from_angular_velocityto_minimal_rotationNote that the last two items relate to quaternion-valued functions of time.  Converting to an angular
velocity requires differentiation, while converting from angular velocity requires integration (as
explored inthis paper).  The"minimal rotation"modifies an input rotation-function-of-time to
have the same effect on thezaxis, while minimizing the amount of rotation that actually happens.For these converters, the "to" functions are properties on the individual arrays, whereas the "from"
functions are "classmethod"s that take the corresponding objects as inputs.  For example, we could
writeq1=quaternionic.array(np.random.rand(100,4)).normalizedm=q1.to_rotation_matrixto obtain the matrixmfroma quaternionic arrayq1.  (Here,mis actually a series of 100
3x3 matrices corresponding to the 100 quaternions inq1.)  On the other hand, to obtain a
quaternionic array from some matrixm, we would writeq2=quaternionic.array.from_rotation_matrix(m)Also note that, because the unit quaternions form a "double cover" of the rotation group (meaning
that quaternionsqand-qrepresent the same rotation), these functions are not perfect inverses
of each other.  In this case, for example,q1andq2may have opposite signs.  We can, however,
prove that these quaternions represent the same rotations by measuring the "distance" between the
quaternions as rotations:np.max(quaternionic.distance.rotation.intrinsic(q1,q2))# Typically around 1e-15Also note the classmethodrandomThis constructs a quaternionic array in which each component is randomly selected from a normal
(Gaussian) distribution centered at 0 with scale 1, which means that the result is isotropic
(spherically symmetric).  It is also possible to pass thenormalizeargument to this function,
which results in truly random unit quaternions.Distance functionsThequaternionic.distancecontains four distance functions:rotor.intrinsicrotor.chordalrotation.intrinsicrotation.chordalThe "rotor" distances do not account for possible differences in signs, meaning that rotor distances
can be large even when they represent identical rotations; the "rotation" functions just return the
smaller of the distance betweenq1andq2or the distance betweenq1and-q2.  So, for
example, either "rotation" distance betweenqand-qis always zero, whereas neither "rotor"
distance betweenqand-qwill ever be zero (unlessqis zero).  The "intrinsic" functions
measure the geodesic distance within the manifold ofunitquaternions, and is somewhat slower but
may be more meaningful; the "chordal" functions measure the Euclidean distance in the (linear) space
of all quaternions, and is faster but its precise value is not necessarily as meaningful.These functions satisfy some important conditions.  For each of these functionsd, and for any
nonzero quaternionsq1andq2, andunitquaternionsq3andq4, we havesymmetry:d(q1, q2) = d(q2, q1)invariance:d(q3*q1, q3*q2) = d(q1, q2) = d(q1*q4, q2*q4)identity:d(q1, q1) = 0positive-definiteness:For rotor functionsd(q1, q2) > 0wheneverq1 ≠ q2For rotation functionsd(q1, q2) > 0wheneverq1 ≠ q2andq1 ≠ -q2Note that the rotation functions also satisfy both the usual identity propertyd(q1, q1) = 0and
the opposite-identity propertyd(q1, -q1) = 0.SeeMoakher (2002)for a nice general discussion.InterpolationFinally, there are also capabilities related to interpolation, for example as functions of time:slerp (spherical linear interpolation)squad (spherical quadratic interpolation)Related packagesOther python packages with some quaternion features includequaternion(core written in C; very fast; adds
quaterniondtypeto numpy; namednumpy-quaternionon pypi due to name conflict)clifford(very powerful; more general geometric algebras)rowan(many features; similar approach to this package;
no acceleration or overloading)pyquaternion(many features; pure python; no
acceleration or overloading)quaternions(basic pure python package; no
acceleration; specialized for rotations only)scipy.spatial.transform.Rotation.as_quat(quaternion output forRotationobject)mathutils(a Blender package with python
bindings)Quaternion(extremely limited capabilities; unmaintained)Also note that there is some capability to do symbolic manipulations of quaternions in these
packages:galgebra(more general geometric algebras; analogous toclifford, but for symbolic calculations)sympy.algebras.quaternion