skoro v0.0.0

Rotations and rigid motions

The crate skoro-spatial declares the rotations, the rigid motions and the extended poses as embedded types stored as quaternions up to sign, with the Cayley chart, global on each group, and declared volumes, so that they carry the normal in whatever sign their quaternions are given, and writes their maps as composites whose derivatives are the core's.

Attitudes, poses and the states of a navigation filter live on curved spaces: the rotations SO(3)SO(3), the rigid motions SE(3)SE(3), and the extended poses SE2(3)SE_2(3), a pose with a velocity. The crate skoro-spatial declares each as an embedded type on the core’s public interface, stored as unit quaternions up to their sign, with a chart that is global on the group and a volume that is declared, so that a quantity of any of them can be scored by the normal, observed in whatever sign it is given, and simulated like any other. Everything a model computes with them, compositions, actions on vectors, exponentials, Jacobians, Euler angles, is a composite of the core’s operations, and its derivatives are the core’s. This page shows how the types are made, the maps on them, and where those maps stop being smooth. The mathematics is in three notes: rotations and unit quaternions, rigid motions, and removable singularities in floating point.

The three types#

A rotation is stored as a unit quaternion q=(w,x,y,z)q = (w, x, y, z), a rigid motion as (q,p)(q, p) with a position pp, and an extended pose as (q,v,p)(q, v, p) with a velocity before the position: storage 44, 77 and 1010, dimension 33, 66 and 99. The tangent coordinates are the rotation’s ϕ\phi first, then one vector for each translation, all in the frame of the point, so that noise on a pose is noise in its own frame, as odometry has it.

A quaternion and its negation are the same rotation, and the types are the groups themselves, stored up to that sign: each declares that it is stored up to a group, here the one that negates the quaternion and keeps the translations, so that qq and −q-q store one point. The rotation’s chart is the Cayley chart, the first-order quaternion update, normalized,

q⊕v=q⊗(1, v/2)1+∣v∣2/4,p⊖q=2 w vec⁡(r)w2,r=qˉ⊗p, w=w(r), q \oplus \tangent = q \otimes \frac{(1,\ \tangent / 2)}{\sqrt{1 + \lvert \tangent \rvert^2 / 4}}, \qquad p \ominus q = \frac{2\, w\, \operatorname{vec}(r)}{w^2}, \quad r = \bar q \otimes p,\ w = w(r),

rational but for one square root, and the same for qq and −q-q: negating either quaternion negates rr, whose vector part and scalar part change sign together. To first order v\tangent is the rotation vector, and the angle of the turn 1⊕v1 \oplus \tangent is 2arctan⁡(∣v∣/2)2 \arctan(\lvert \tangent \rvert / 2), so the chart reaches every rotation by less than a half-turn from its base point, which is all of SO(3)SO(3) but a set of measure zero. Its log-volume, against Haar measure, is λ(v)=−2log⁡(1+∣v∣2/4)\lambda(\tangent) = -2 \log(1 + \lvert \tangent \rvert^2 / 4). The inverse is written over w2w^2 so that the only reciprocal it takes is of a positive number, the one kind the core’s primitives take. A motion moves its rotation by this chart and its translations in its own frame, (q,p)⊕(ϕ,ρ)=(q⊕ϕ, p+Rρ)(q, p) \oplus (\phi, \rho) = (q \oplus \phi,\ p + R \rho) with RR the rotation’s matrix, which is global too, with the same volume. One generic declaration makes all three, for kk translations:

crates/skoro-spatial/src/types.rs lines 115–162
fn declare(kind: Kind) -> Result<Arc<Embedded>, Error> {
    let k = kind.translations();
    let (n, d) = (4 + 3 * k, 3 + 3 * k);
    let (storage, tangent) = (Space::Vector(n), Space::Vector(d));
    let [name, retract, local, project, log_volume] = kind.names();
    let define = |name, inputs: &[Space], body: &dyn Fn(&[QDyn]) -> QDyn| {
        Composite::define(name, Vec::new(), inputs, |q| body(q)).map_err(|f| f.error)
    };
    let r = define(retract, &[storage.clone(), tangent.clone()], &|q| {
        let (x, t) = (q[0], q[1]);
        let unit = normalize(x.slice(0..4));
        let moved = (0..k)
            .map(|i| block(x, 4, i) + rotate(unit, block(t, 3, i)))
            .collect();
        assemble(mul(unit, cayley(t.slice(0..3))), moved, storage.clone())
    })?;
    let q = define(local, &[storage.clone(), storage.clone()], &|q| {
        let (x, y) = (q[0], q[1]);
        let (a, b) = (x.slice(0..4), y.slice(0..4));
        let moved = (0..k)
            .map(|i| unrotate(a, block(y, 4, i) - block(x, 4, i)))
            .collect();
        assemble(cayley_inverse(mul(conjugate(a), b)), moved, tangent.clone())
    })?;
    let p = define(project, std::slice::from_ref(&storage), &|q| {
        let x = q[0];
        let kept = (0..k).map(|i| block(x, 4, i)).collect();
        assemble(normalize(x.slice(0..4)), kept, storage.clone())
    })?;
    let lambda = define(log_volume, &[storage.clone(), tangent.clone()], &|q| {
        let phi = q[1].slice(0..3);
        ((phi * phi).sum() * 0.25 + 1.0).log() * -2.0
    })?;
    // The sign of the quaternion, the translations kept.
    let signs: Vec<i8> = (0..n).map(|i| if i < 4 { -1 } else { 1 }).collect();
    let sign = Linear::signs(&signs).ok_or_else(|| Error::InvalidDeclaration {
        name: name.to_string(),
        reason: "its sign is not a signed permutation".to_string(),
    })?;
    let declaration = Embedded::declare(name, Vec::new(), n, d, r, q, Some(p))?
        .stored_up_to(vec![sign])?
        .with_volume(Volume::global(lambda))?;
    match kind {
        Kind::Rotation => declaration.with_mass(Mass::new(LOG_MASS, uniform_rotation)),
        // The translations fill ℝ³: a pose's measure has infinite mass.
        Kind::Pose | Kind::ExtendedPose => Ok(declaration),
    }
}

The retraction normalizes its base point. On the type this changes nothing; off it, it keeps a point that a long run of retractions has carried off the sphere by rounding from passing that error on to every later step.

Haar measure on the rotations, normalized at the chart’s centre, has the finite mass 8π28\pi^2, so the rotations declare it, with Shoemake’s map from three variates to a unit quaternion of a uniform rotation; the poses and the extended poses, whose translations fill R3\R^3, have infinite mass and declare none:

crates/skoro-spatial/src/types.rs lines 102–113
/// A unit quaternion `(w, x, y, z)` of a uniform rotation, from three variates: Shoemake's map.
fn uniform_rotation(u: &[f64], q: &mut [f64]) {
    let (a, b) = ((1.0 - u[0]).sqrt(), u[0].sqrt());
    let (phi, psi) = (TAU * u[1], TAU * u[2]);
    q[0] = a * phi.cos();
    q[1] = a * phi.sin();
    q[2] = b * psi.cos();
    q[3] = b * psi.sin();
}

/// `log 8π²`: the mass of Haar measure on `SO(3)`, normalized at the chart's centre.
const LOG_MASS: f64 = 4.368901313378636;

A rotation of which nothing is known is given the uniform distribution by it. A pose with an unknown attitude is a model’s to write, from a uniform rotation and a position of its own. The markers name the three declarations:

crates/skoro-spatial/src/types.rs lines 172–192
/// `skoro.spatial.rotation`: storage 4, dimension 3.
pub static ROTATION: LazyLock<Arc<Embedded>> = LazyLock::new(|| declared(Kind::Rotation));
/// `skoro.spatial.pose`: storage 7, dimension 6.
pub static POSE: LazyLock<Arc<Embedded>> = LazyLock::new(|| declared(Kind::Pose));
/// `skoro.spatial.extended_pose`: storage 10, dimension 9.
pub static EXTENDED_POSE: LazyLock<Arc<Embedded>> = LazyLock::new(|| declared(Kind::ExtendedPose));

/// A rotation, stored as a unit quaternion `(w, x, y, z)` of either sign. Tangent coordinates are
/// the Cayley coordinates in the frame of the point, the rotation vector to first order.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Default)]
pub struct Rotation;

/// `(q, p)`: a rigid motion, its quaternion of either sign, its tangent coordinates `(φ, ρ)` in the
/// frame of the motion.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Default)]
pub struct Pose;

/// `(q, v, p)`: an extended pose, its quaternion of either sign, its tangent coordinates
/// `(φ, η, ρ)` in its own frame.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Default)]
pub struct ExtendedPose;

So a quantity of Rotation is a rotation, and its value is stored as either of its quaternions. A constant made from a host value is normalized there, and refused when it is zero or not finite, its sign kept; an observed quaternion, from a sensor or a file, is observed in whatever sign it comes in; and every term, every derivative and every map below gives the same at either. Which quaternion a value carries is decided by how it was made: a retraction keeps the side of its base point, so a draw of the normal carries its mean’s sign, a composition carries the product’s, and an observation the sign it was given.

Computing with them#

* composes, and acts on vectors, as the mathematics writes it:

crates/skoro-spatial/src/rotation.rs lines 268–302
/// `q₁ * q₂ = P(q₁ ⊗ q₂)`.
impl QMul for Rotation {
    type Output = Rotation;
    #[track_caller]
    fn mul(lhs: Q<Rotation>, rhs: Q<Rotation>) -> Q<Rotation> {
        COMPOSE.call(&[lhs.untyped(), rhs.untyped()]).narrow()
    }
}

/// `q * x = π(q) x`.
impl QMul<Vector<3>> for Rotation {
    type Output = Vector<3>;
    #[track_caller]
    fn mul(lhs: Q<Rotation>, rhs: Q<Vector<3>>) -> Q<Vector<3>> {
        ROTATE.call(&[lhs.untyped(), rhs.untyped()]).narrow()
    }
}

/// `q * x = π(q) x`, refusing a vector not of length 3 (`SpaceMismatch`).
impl QMul<VectorDyn> for Rotation {
    type Output = VectorDyn;
    #[track_caller]
    fn mul(lhs: Q<Rotation>, rhs: Q<VectorDyn>) -> Q<VectorDyn> {
        ROTATE.call(&[lhs.untyped(), rhs.untyped()]).narrow()
    }
}

/// `q * X = π(q) X`: each column rotated.
impl<const N: usize> QMul<Matrix<3, N>> for Rotation {
    type Output = Matrix<3, N>;
    #[track_caller]
    fn mul(lhs: Q<Rotation>, rhs: Q<Matrix<3, N>>) -> Q<Matrix<3, N>> {
        lhs.matrix().matmul(rhs)
    }
}

The other maps of a rotation are methods of its handle, through an extension trait, since the core owns Q:

crates/skoro-spatial/src/rotation.rs lines 304–349
/// The maps of a rotation, as methods of its handle.
pub trait RotationMaps: Sized {
    /// `P(q̄)`.
    fn inverse(self) -> Q<Rotation>;
    /// `P(q̄₁ ⊗ q₂)`: the rotation from `self` to `other`, in the frame of `self`.
    fn between(self, other: Q<Rotation>) -> Q<Rotation>;
    /// `π(q)ᵀ x`: a vector of the outer frame in the frame of `self`.
    fn unrotate(self, x: Q<Vector<3>>) -> Q<Vector<3>>;
    /// `π(q)`, the rotation matrix.
    fn matrix(self) -> Q<Matrix<3, 3>>;
    /// The adjoint, `π(q)`, carrying a perturbation in the frame of `self` to the outer frame:
    /// `q ⊕ t = (1 ⊕ π(q) t) q`.
    fn adjoint(self) -> Q<Matrix<3, 3>>;
    /// The rotation vector of the shorter turn, `rv(q) = Log(s(q) q)` with `s(q)` the sign of `w`
    /// and `Log(q) = 2 atan2(n, w) u / n`: the inverse of `exp` on the ball of radius π, of
    /// length in [0, π], the same whichever sign the rotation is stored in, and a discretization
    /// at the half-turns, where the two turns are equally short and either is selected.
    fn log(self) -> Q<Vector<3>>;
    /// The axis and the angle of `log`, the angle in [0, π], the same whichever sign the rotation
    /// is stored in. The axis is `(1, 0, 0)` at the identity, where it is a discretization, and at
    /// a half-turn, where `a` and `-a` name one rotation, the axis of the side `log` selects.
    fn axis_angle(self) -> (Q<Vector<3>>, Q<Real>);
    /// `sign⟨q, r⟩ q`: the same rotation, stored on the side of `reference`, a discretization
    /// where the two are orthogonal. As a map of the rotations it is the identity: it chooses
    /// which of the two quaternions stores the rotation, and nothing else, as a quaternion
    /// reported with `w ≥ 0` is `aligned_with(rotation::identity())`.
    fn aligned_with(self, reference: Q<Rotation>) -> Q<Rotation>;
    /// The angles of `convention`, in the order of its axes: `α` and `γ` in (-π, π], `β` in
    /// [0, π] for a proper sequence and in [-π/2, π/2] for a Tait–Bryan one. `α` and `γ` are cut
    /// where they are π: their values jump there by 2π, and their derivatives do not, so angles
    /// are compared by [`angle_residual`](crate::angle_residual) rather than subtracted. At gimbal
    /// lock, `γ` is 0, a discretization; near it, `α` and `γ` alone are ill-conditioned, their
    /// derivatives growing like `1 / sin(β/2)`, while `β` and the combination of `α` and `γ` the
    /// lock determines stay accurate.
    fn euler(self, convention: Euler) -> Q<Vector<3>>;
    /// The angle between two rotations, `|rv(q̄₁ ⊗ q₂)| ∈ [0, π]`: the length of the shorter turn
    /// from one to the other. It has no derivative where it is 0, where its passes are
    /// non-finite, and where it is π, a discretization whose passes are those of the side
    /// selected.
    fn angle_to(self, other: Q<Rotation>) -> Q<Real>;
    /// `q₁ ⊗ Exp(t rv(q̄₁ ⊗ q₂))`: the geodesic of the rotations from `self` at `t = 0` to `other`
    /// at `t = 1`, at a constant rate along the shorter of the two turns from one to the other,
    /// the same rotations whichever sign either is stored in; a discretization where they are a
    /// half-turn apart and the two turns are equally short.
    fn slerp(self, other: Q<Rotation>, t: Q<Real>) -> Q<Rotation>;
}

Every one of them is a map of the rotations, not of the quaternions that store them: a value out of the type is the same whichever sign its inputs are stored in, and a rotation into it is the same rotation. The logarithm is the rotation vector of the shorter turn, of length at most π\pi, its axis and angle are that vector’s, and the interpolation goes along the shorter turn; each of these three is a discretization at the half-turns, where the two turns are equally short. aligned_with chooses which quaternion stores a rotation, and is the identity on the rotations.

and the rotations are made by free functions in rotation, from a rotation vector, an axis and an angle, a pair of directions, Euler angles or a matrix:

crates/skoro-spatial/src/rotation.rs lines 414–464
/// The identity rotation, stored as `(1, 0, 0, 0)`; `(-1, 0, 0, 0)` stores the same rotation,
/// and every map gives the same at either.
#[track_caller]
pub fn identity() -> Q<Rotation> {
    constant(Rotation, [1.0, 0.0, 0.0, 0.0])
}

/// `Exp(ω) = (cos(θ/2), sin(θ/2) ω / θ)`, `θ = |ω|`: the rotation about `ω` by its length.
#[track_caller]
pub fn exp(omega: Q<Vector<3>>) -> Q<Rotation> {
    EXP.call(&[omega.untyped()]).narrow()
}

/// The rotation by `angle` about `axis ≠ 0`: `(cos(θ/2), sin(θ/2) a / |a|)`.
#[track_caller]
pub fn about(axis: Q<Vector<3>>, angle: Q<Real>) -> Q<Rotation> {
    ABOUT.call(&[axis.untyped(), angle.untyped()]).narrow()
}

/// `q_e(θ) = (cos(θ/2), sin(θ/2) e)`, the rotation by `angle` about a coordinate axis.
#[track_caller]
pub fn elementary(axis: Axis, angle: Q<Real>) -> Q<Rotation> {
    about(constant(Vector::<3>, axis.unit()), angle)
}

/// The rotation of least angle carrying the direction of `a` to that of `b`,
/// `P(|a| |b| + a·b, a × b)`. Undefined where `b` is opposite to `a`, or either is zero:
/// non-finite where the argument vanishes exactly, and ill-conditioned near it, its error the
/// rounding over the angle by which `b` falls short of `-a`, so that at directions opposite only
/// up to rounding it is finite and meaningless.
#[track_caller]
pub fn from_two_vectors(a: Q<Vector<3>>, b: Q<Vector<3>>) -> Q<Rotation> {
    FROM_TWO_VECTORS.call(&[a.untyped(), b.untyped()]).narrow()
}

/// The rotation of the Euler angles `angles` of `convention`, listed in the order of its axes:
/// `q_i(α) ⊗ q_j(β) ⊗ q_k(γ)` for an intrinsic sequence `(i, j, k)`, `q_k(γ) ⊗ q_j(β) ⊗ q_i(α)`
/// for an extrinsic one.
#[track_caller]
pub fn from_euler(angles: Q<Vector<3>>, convention: Euler) -> Q<Rotation> {
    crate::euler::from_euler(angles, convention)
}

/// The unit quaternion over a rotation matrix, `P(c_m(X))` with `m` the index of the largest of
/// the four candidates' diagonal entries: the point over `X` whose `m`-th coordinate is positive.
/// A discretization where the choice of `m` changes; a matrix near a rotation gives a nearby unit
/// quaternion.
#[track_caller]
pub fn from_matrix(m: Q<Matrix<3, 3>>) -> Q<Rotation> {
    FROM_MATRIX.call(&[m.untyped()]).narrow()
}

so3 holds the Euclidean maps of rotation vectors: hat and vee, and the left and right Jacobians of the exponential and their inverses. A rigid motion composes, acts on points, and has its parts, its homogeneous matrix and its adjoint, its exponential and logarithm in body twists, and interpolations along the screw or along each part, all of the shorter turn:

crates/skoro-spatial/src/pose.rs lines 342–399
/// `T₁ * T₂ = (P(q₁ ⊗ q₂), p₁ + R₁ p₂)`.
impl QMul for Pose {
    type Output = Pose;
    #[track_caller]
    fn mul(lhs: Q<Pose>, rhs: Q<Pose>) -> Q<Pose> {
        COMPOSE.call(&[lhs.untyped(), rhs.untyped()]).narrow()
    }
}

/// `T * x = R x + p`, the action on a point.
impl QMul<Vector<3>> for Pose {
    type Output = Vector<3>;
    #[track_caller]
    fn mul(lhs: Q<Pose>, rhs: Q<Vector<3>>) -> Q<Vector<3>> {
        TRANSFORM.call(&[lhs.untyped(), rhs.untyped()]).narrow()
    }
}

/// The maps of a rigid motion, as methods of its handle. Tangent coordinates are `(φ, ρ)`,
/// rotation first, in the frame of the motion.
pub trait PoseMaps: Sized {
    /// `(P(q̄), -Rᵀ p)`.
    fn inverse(self) -> Q<Pose>;
    /// `T₁⁻¹ T₂`: the motion from `self` to `other`, in the frame of `self`.
    fn between(self, other: Q<Pose>) -> Q<Pose>;
    /// `R x`: a direction carried by the rotation alone.
    fn rotate(self, x: Q<Vector<3>>) -> Q<Vector<3>>;
    /// `Rᵀ (x - p)`: a point of the outer frame in the frame of `self`.
    fn untransform(self, x: Q<Vector<3>>) -> Q<Vector<3>>;
    /// The rotation `q`.
    fn rotation(self) -> Q<Rotation>;
    /// The position `p`.
    fn position(self) -> Q<Vector<3>>;
    /// The homogeneous matrix, `R` and `p` over `(0, 1)`.
    fn matrix(self) -> Q<Matrix<4, 4>>;
    /// The adjoint `((R, 0), ([p]× R, R))` in the order `(φ, ρ)`, carrying a perturbation in the
    /// frame of `self` to the outer frame to first order.
    fn adjoint(self) -> Q<Matrix<6, 6>>;
    /// `Log(q, p) = (φ, J_l(φ)⁻¹ p)` with `φ = rv(q)`, the rotation vector of the shorter turn:
    /// the inverse of `pose::exp` on the ball of radius π in the rotation, the same whichever
    /// sign the quaternion is stored in, and a discretization at the half-turns, where `J_l(φ)⁻¹ p`
    /// is finite and the two turns equally short.
    fn log(self) -> Q<Vector<6>>;
    /// `T₁ Exp(t Log(T₁⁻¹ T₂))`: the screw motion at a constant twist from `self` at `t = 0` to
    /// `other` at `t = 1`, along the shorter turn; a discretization where the rotations are a
    /// half-turn apart.
    fn interpolate(self, other: Q<Pose>, t: Q<Real>) -> Q<Pose>;
    /// `(q₁ ⊗ Exp(t rv(q̄₁ ⊗ q₂)), (1 - t) p₁ + t p₂)`: the rotation along its geodesic, the shorter
    /// turn, and the position along a line, the geodesic of the product.
    fn interpolate_parts(self, other: Q<Pose>, t: Q<Real>) -> Q<Pose>;
    /// The same storage as a value of the product `S³ × ℝ³`, whose chart moves the position in a
    /// fixed frame.
    #[expect(
        clippy::wrong_self_convention,
        reason = "a handle is Copy, and taken by value as every map takes it"
    )]
    fn as_product(self) -> Q<ProductDyn>;
}

with pose::identity, from_parts, from_product, exp, and the Jacobians jl, jr, jl_inv and jr_inv in the order (ϕ,ρ)(\phi, \rho). The extended poses have the same maps through ExtendedPoseMaps and extended_pose, with the velocity carried as the position is. as_product reads a pose as a value of the core’s product S3×R3S^3 \times \R^3, whose chart moves the position in a fixed frame: a pose whose noise is in the world’s frame, a GPS fix for one, is a quantity of that product instead.

No frame is assumed: an earth frame, a gravity or a sensor’s mounting is a rotation or a motion the model composes, or a constant it holds.

Some of these maps are needed before a model runs, or after it, on values that are not in it: a start for an estimator computed from the measurements, or a quaternion to report. host holds them, in double precision on arrays: the alignment and canonical, the representative with w≥0w \ge 0 to report, the composition of quaternions, the matrix, the exponential and logarithm, the Euler angles, and a motion’s composition and action, each computing what the graph’s map computes:

crates/skoro-spatial/src/host.rs lines 32–44
/// `T₁ * T₂ = (P(q₁ ⊗ q₂), p₁ + R₁ p₂)` on poses in storage order, `(w, x, y, z)` then the
/// position: as `Q<Pose> * Q<Pose>` computes it, with no choice of the quaternion's sign.
pub fn pose_compose(a: [f64; 7], b: [f64; 7]) -> [f64; 7] {
    let q = compose([a[0], a[1], a[2], a[3]], [b[0], b[1], b[2], b[3]]);
    let p = pose_transform(a, [b[4], b[5], b[6]]);
    [q[0], q[1], q[2], q[3], p[0], p[1], p[2]]
}

/// `T * x = R x + p`: as `Q<Pose> * Q<Vector<3>>` computes it.
pub fn pose_transform(t: [f64; 7], x: [f64; 3]) -> [f64; 3] {
    let r = matrix([t[0], t[1], t[2], t[3]]);
    std::array::from_fn(|i| t[4 + i] + r[i][0] * x[0] + r[i][1] * x[1] + r[i][2] * x[2])
}

Derivatives#

No map writes a derivative. Each is a composite of the core’s primitives, so its derivatives of both orders are those of its parts, and in the charts they are the Jacobians of the textbooks: the tangent pass of rotation::exp at ω\omega, read in the chart at its value, is so3::jr(ω), and likewise for the motions, as the note proves and the crate’s tests check. The second derivatives of a map of a rotation agree with those taken in exponential coordinates; on a pose they differ by a term of second order, since the pose’s chart is not its exponential.

The exponential, the logarithm and the Jacobians are smooth at the identity, but their closed forms divide by the angle there. Each coefficient is computed by a truncated series below a cutoff and by its closed form above it, selected by the core’s selection, with each formula given a harmless argument on the rows where the other is chosen, so that every pass is finite at the identity too. The cutoff is one for both precisions and for every device, since a composite does not know where it will run, and the note gives the two conditions that place it:

crates/skoro-spatial/src/series.rs lines 16–19
/// The cutoff in `θ²` below which the series of `a`, `b`, `A`, `B`, `C`, `D` and `E` are used,
/// chosen so that the closed form above it meets the GPU's error designed for
/// (archive/wgpu-accuracy/math, "Conditions on a cutoff").
pub(crate) const CUTOFF: f64 = 1.0;

At θ2=1\theta^2 = 1, the closed forms above the cutoff agree with double precision in single precision on a GPU, whose sine is accurate only to an absolute error (see queries). Their derivatives agree too, to second order. The series below it keep as many terms as double precision needs there, up to θ22\theta^{22} for the inverse Jacobians’ coefficient.

Euler angles#

Euler names a convention: one of the twelve sequences of axes and whether the turns are about the axes as the previous turns left them (intrinsic) or about the fixed axes (extrinsic). Euler::YAW_PITCH_ROLL is the aerospace convention, intrinsic about (z,y,x)(z, y, x). rotation::from_euler is smooth everywhere. The way back, euler, is not, and no formula could make it so: the note proves that it has two singularities.

The wrap. The first and last angles are returned in (−π,π](-\pi, \pi], and jump by 2π2\pi where they cross ±π\pm\pi. Any real-valued angle must be cut somewhere; the jump is in the value alone, and the derivatives of every order are the same on both sides. What breaks is a difference of angles, which is taken on the circle instead:

crates/skoro-spatial/src/euler.rs lines 319–328
/// The residual of angles on the circle, elementwise: `a ⊖ b = atan2(sin(a - b), cos(a - b))`, in
/// (-π, π]. It is cut where `a - b` is an odd multiple of π, as far as an angle can be from the one
/// it is compared with, and elsewhere has the derivatives of `a - b`, across the wrap of either
/// angle too. `b + angle_residual(a, b)` is `a` brought within a half-turn of `b`, continuous along
/// any path that stays within a half-turn of it.
#[track_caller]
pub fn angle_residual<M: Angles>(a: Q<M>, b: Q<M>) -> Q<M> {
    let d = a.untyped() - b.untyped();
    d.sin().atan2(d.cos()).narrow()
}

Gimbal lock. Where the middle angle is 00 or π\pi for a proper sequence, or ±π/2\pm\pi/2 for a Tait–Bryan one, only the sum or the difference of the other two is determined. The composite returns the last angle as 00 there, where one of two norms vanishes to within 10−3410^{-34} of the quaternion’s, which changes the rotation the angles give back by less than double precision’s rounding. Near the lock the first and last angles alone are ill-conditioned, their derivatives growing like 1/sin⁡(β/2)1 / \sin(\beta / 2), while the middle angle and the determined combination stay accurate.

Euler angles are therefore a way into and out of a model, from a configuration file or to a display, and a model’s noise is put in the charts.

Where a map is undefined#

Some maps are undefined at a point the mathematics names: the inverse retraction at the half-turns from its base point, the inverses of the Jacobians at an angle of 2π2\pi, from_two_vectors at opposite directions. At a row exactly there, the composite’s values or passes are non-finite. At a row that rounding leaves just off it, they are finite: large, where the map grows without bound, and where only its conditioning does, as in the direction of the rotation carrying a vector to its opposite, meaningless. Each map’s documentation says which.

The inverse retraction’s cut matters most, since every term on these types reads its value through it. A value given exactly a half-turn from its mean, a measurement a half-turn from its prediction or a start a half-turn from a prior’s mean, makes the term non-finite, and the linearization refuses that point with NotFinite, naming the term and the row; near the cut the residual is large, and an estimator started there crawls away from it. A half-turn between a value and its mean is the largest error a rotation can have, so an estimate that fits its data never meets the cut: it is a fact about a start, and a start is chosen away from it.

A normal with a large scale reaches the cut too, by the law and not by a start: its scale is in the chart’s coordinates, and once it passes one radian the normal’s mass goes towards the half-turns from its mean. The normal says what that means, and why “unknown” is the uniform distribution instead.

On the host#

host does in double precision what a model does before its values are loaded or after it has run: composing, converting between quaternions, matrices, Euler angles and rotation vectors, for constants and observations given in those forms, and choosing the quaternion with w≥0w \ge 0 to report.

How this came to be

The development behind this page, newest first: