Algorithm Search⌘K

Definitionadvanced

Dual quaternion

Also called unit dual quaternion.

A quaternion with dual number entries; unit dual quaternions represent rigid motions as quaternions represent rotations.

A dual quaternion is a quaternion whose four entries are dual numbers a+εba + \varepsilon b with ε2=0\varepsilon^2 = 0, or, the same thing, a pair of quaternions written σ=r+εd\sigma = r + \varepsilon d. A unit dual quaternion holds a rigid motion of space in 8 numbers: the real part rr is the unit quaternion of the rotation, and the dual part dd is half the translation times rr. The product of two unit dual quaternions is the composition of their motions, in the same way as the product of unit quaternions composes rotations. Unit dual quaternions double cover the special Euclidean group SE(3): σ\sigma and −σ-\sigma give the same motion, as qq and −q-q give the same rotation. A unit dual quaternion is also the algebraic form of a screw motion: its dual angle holds the rotation angle and the slide, and its dual axis holds the screw axis as a line. Clifford introduced the algebra in 1873 under the name biquaternions, and Study used it in 1891 for the motions of space.

Definition

A dual number is a^=a+εb\hat a = a + \varepsilon b with real a,ba, b and ε2=0\varepsilon^2 = 0, ε≠0\varepsilon \neq 0. For a smooth function, f(a+εb)=f(a)+εbf′(a)f(a + \varepsilon b) = f(a) + \varepsilon b f'(a); for example cos⁡(θ+εd)=cos⁡θ−εdsin⁡θ\cos(\theta + \varepsilon d) = \cos\theta - \varepsilon d \sin\theta.

A dual quaternion is σ=r+εd\sigma = r + \varepsilon d with Hamilton quaternions rr (the real part) and dd (the dual part), scalar first. The product follows from ε2=0\varepsilon^2 = 0:

(r1+εd1)(r2+εd2)=r1r2+ε(r1d2+d1r2).(r_1 + \varepsilon d_1)(r_2 + \varepsilon d_2) = r_1 r_2 + \varepsilon (r_1 d_2 + d_1 r_2).

It is associative and not commutative. Two conjugates are used: the quaternion conjugate σ∗=r∗+εd∗\sigma^* = r^* + \varepsilon d^*, and the combined conjugate r∗−εd∗r^* - \varepsilon d^*, which moves points. The norm is σσ∗=∣r∣2+2ε(r⋅d)\sigma \sigma^* = |r|^2 + 2\varepsilon (r \cdot d), where r⋅dr \cdot d is the dot product of the two 4-vectors.

σ\sigma is a unit dual quaternion when σσ∗=1\sigma \sigma^* = 1, that is

∣r∣=1andr⋅d=0.|r| = 1 \quad\text{and}\quad r \cdot d = 0 .

These are two scalar conditions on 8 numbers, so the unit dual quaternions form a 6-dimensional set, one dimension for each degree of freedom of a rigid body. Each unit dual quaternion has the inverse σ−1=σ∗\sigma^{-1} = \sigma^*.

The rigid motion of a unit dual quaternion. Let x↦Rx+tx \mapsto R x + t be a rigid motion, and let rr be a unit quaternion of RR. Write tt and xx as pure quaternions (0,t)(0, t) and (0,x)(0, x). The dual quaternion of the motion is

σ=r+ε 12 t r,t=2 d r∗.\sigma = r + \varepsilon\, \tfrac12\, t\, r, \qquad t = 2\, d\, r^* .

It is unit: r⋅dr \cdot d is the scalar part of r∗d=12r∗trr^* d = \tfrac12 r^* t r, which is a pure quaternion, so r⋅d=0r \cdot d = 0. A point is the dual quaternion 1+εx1 + \varepsilon x, and the motion acts by the sandwich

σ (1+εx) (r∗−εd∗)=1+ε(Rx+t).\sigma\,(1 + \varepsilon x)\,(r^* - \varepsilon d^*) = 1 + \varepsilon (R x + t).

To check it, expand to 1+ε(dr∗+rxr∗−rd∗)1 + \varepsilon (d r^* + r x r^* - r d^*), and use dr∗=12td r^* = \tfrac12 t, rd∗=12rr∗t∗=−12tr d^* = \tfrac12 r r^* t^* = -\tfrac12 t and rxr∗=Rxr x r^* = R x. Composition is the product: if σ1\sigma_1 and σ2\sigma_2 belong to T1T_1 and T2T_2, then

σ1σ2=r1r2+ε 12(t1+r1t2r1∗) r1r2,\sigma_1 \sigma_2 = r_1 r_2 + \varepsilon\, \tfrac12 (t_1 + r_1 t_2 r_1^*)\, r_1 r_2 ,

which is the dual quaternion of T1T2T_1 T_2, with rotation R1R2R_1 R_2 and translation R1t2+t1R_1 t_2 + t_1. The map from unit dual quaternions to SE(3) is a group homomorphism onto SE(3), and its kernel is {1,−1}\{1, -1\}: σ\sigma and −σ-\sigma have the same RR, and the same t=2dr∗t = 2 d r^*. So unit dual quaternions double cover SE(3), as unit quaternions double cover the rotation group.

Screw form. By Chasles' theorem, every rigid motion is a screw motion: a rotation by θ\theta about a line with unit direction ss through a point qq, and a slide ds=hθd_s = h\theta along it, with pitch hh. Let the dual angle be θ^=θ+εds\hat\theta = \theta + \varepsilon d_s, and let the dual axis be s^=s+εm\hat s = s + \varepsilon m with the moment m=q×sm = q \times s (the Plücker coordinates of the line). Then

σ=cos⁡θ^2+s^sin⁡θ^2=(cos⁡θ2, ssin⁡θ2)+ε(−ds2sin⁡θ2, msin⁡θ2+ds2cos⁡θ2 s).\sigma = \cos\frac{\hat\theta}{2} + \hat s \sin\frac{\hat\theta}{2} = \Big(\cos\frac{\theta}{2},\ s \sin\frac{\theta}{2}\Big) + \varepsilon \Big(-\frac{d_s}{2}\sin\frac{\theta}{2},\ m \sin\frac{\theta}{2} + \frac{d_s}{2} \cos\frac{\theta}{2}\, s\Big).

This is the same shape as (cos⁡θ2,ssin⁡θ2)(\cos\frac{\theta}{2}, s \sin\frac{\theta}{2}) for a rotation, with dual numbers in place of reals. Because s^θ^=θ(s+εv)\hat s \hat\theta = \theta (s + \varepsilon v) with v=−s×q+hsv = -s \times q + h s, the unit twist S=(s,v)\mathcal S = (s, v) gives σ=exp⁡(θ2(s+εv))\sigma = \exp\big(\tfrac{\theta}{2}(s + \varepsilon v)\big), the dual quaternion form of the exponential e[S]θe^{[\mathcal S]\theta}.

Operations. The code on this page follows these lines; quaternion products are Hamilton products.

  1. MUL(a, b), FROM-POSE(q, t), TO-POSE(σ), APPLY(σ, x)
  2. 1(r1, d1) ← a ; (r2, d2) ← b
  3. 2MUL returns (r1 r2, r1 d2 + d1 r2)
  4. 3FROM-POSE returns (q, ½ (0, t) q)
  5. 4TO-POSE: (r, d) ← σ ; return (r, vector part of 2 d r*)
  6. 5APPLY: y ← MUL(MUL(σ, (1, (0, x))), (r*, -d*))
  7. 6APPLY returns the vector part of the dual part of y

One product costs three quaternion products, 48 multiplications and 40 additions. The product of two 4x4 rigid transforms costs 36 multiplications and 27 additions, so the dual quaternion product is not faster; its gains are 8 numbers in place of 12, a cheap renormalization and the smooth blending below. After many products, rounding moves σ\sigma off the unit conditions. To renormalize, divide both parts by ∣r∣|r| and then remove from dd its component along rr: d←d−(r⋅d) rd \leftarrow d - (r \cdot d)\, r.

Examples and non-examples

A quarter turn with a translation. Let R=Rz(π/2)R = R_z(\pi/2) and t=(1,1,0)t = (1, 1, 0). Then r=(cos⁡π4,0,0,sin⁡π4)=(0.70711,0,0,0.70711)r = (\cos\frac{\pi}{4}, 0, 0, \sin\frac{\pi}{4}) = (0.70711, 0, 0, 0.70711). The product (0,1,1,0)(0.70711,0,0,0.70711)(0, 1, 1, 0)(0.70711, 0, 0, 0.70711) is (0,1.41421,0,0)(0, 1.41421, 0, 0), so d=(0,0.70711,0,0)d = (0, 0.70711, 0, 0) and

σ=(0.70711,0,0,0.70711)+ε(0,0.70711,0,0).\sigma = (0.70711, 0, 0, 0.70711) + \varepsilon (0, 0.70711, 0, 0).

The unit conditions hold: ∣r∣=1|r| = 1 and r⋅d=0r \cdot d = 0. The point x=(1,0,0)x = (1, 0, 0) goes to Rx+t=(0,1,0)+(1,1,0)=(1,2,0)R x + t = (0, 1, 0) + (1, 1, 0) = (1, 2, 0). The same motion is the screw with axis s=(0,0,1)s = (0, 0, 1) through q=(0,1,0)q = (0, 1, 0), pitch 0 and θ=π/2\theta = \pi/2: the moment is m=q×s=(1,0,0)m = q \times s = (1, 0, 0), and the screw form gives (0.70711,0,0,0.70711)+ε (0,0.70711⋅(1,0,0))(0.70711, 0, 0, 0.70711) + \varepsilon\, (0, 0.70711 \cdot (1, 0, 0)), the same σ\sigma. The point (0,1,0)(0, 1, 0) is on the axis, and indeed R(0,1,0)+t=(−1,0,0)+(1,1,0)=(0,1,0)R (0, 1, 0) + t = (-1, 0, 0) + (1, 1, 0) = (0, 1, 0).

Composition. Apply the same motion twice. The real part is r2=(0,0,0,1)r^2 = (0, 0, 0, 1), a half turn about zz. The dual part is rd+dr=(0,0.5,0.5,0)+(0,0.5,−0.5,0)=(0,1,0,0)r d + d r = (0, 0.5, 0.5, 0) + (0, 0.5, -0.5, 0) = (0, 1, 0, 0). Then t=2dr∗=2(0,1,0,0)(0,0,0,−1)=(0,0,2,0)t = 2 d r^* = 2 (0, 1, 0, 0)(0, 0, 0, -1) = (0, 0, 2, 0), so the translation is (0,2,0)(0, 2, 0). The matrix product gives the same: Rz(π/2)(1,1,0)+(1,1,0)=(−1,1,0)+(1,1,0)=(0,2,0)R_z(\pi/2) (1, 1, 0) + (1, 1, 0) = (-1, 1, 0) + (1, 1, 0) = (0, 2, 0).

Pure translation and pure rotation. A translation by tt is 1+ε12(0,t)1 + \varepsilon \tfrac12 (0, t). A rotation about a line through the origin is r+ε 0r + \varepsilon\, 0. A half turn about the xx axis is (0,1,0,0)+ε 0(0, 1, 0, 0) + \varepsilon\, 0.

The double cover. −σ=(−0.70711,0,0,−0.70711)+ε(0,−0.70711,0,0)-\sigma = (-0.70711, 0, 0, -0.70711) + \varepsilon (0, -0.70711, 0, 0) is a different dual quaternion with the same motion: R(−r)=R(r)R(-r) = R(r), and 2(−d)(−r)∗=2dr∗2(-d)(-r)^* = 2 d r^*. A program that compares or averages dual quaternions must handle both signs.

Non-example: a dual quaternion that is not unit. σ=1+ε(1,0,0,0)\sigma = 1 + \varepsilon (1, 0, 0, 0) has ∣r∣=1|r| = 1 but r⋅d=1r \cdot d = 1. The formula 2dr∗2 d r^* gives (2,0,0,0)(2, 0, 0, 0), which has a scalar part and so is not a translation. σ\sigma is not a rigid motion; to use it, first renormalize, which here gives 11.

Non-example: a dual quaternion with zero real part. σ=ε (1,0,0,0)\sigma = \varepsilon\, (1, 0, 0, 0) has no inverse, because ε⋅ε=0\varepsilon \cdot \varepsilon = 0. Dual quaternions are not a division algebra.

Non-example: linear blending without normalization. The average 12(σ1+σ2)\tfrac12 (\sigma_1 + \sigma_2) of two unit dual quaternions is usually not unit. Kavan, Collins, Žára and O'Sullivan blend ∑iwiσi\sum_i w_i \sigma_i and then normalize; before the sum they flip the sign of each σi\sigma_i whose real part has a negative dot product with that of the first, so that all lie on one side of the double cover. The result is a rigid motion, which is why this blending removes the volume loss of linear blend skinning.

  • Unit quaternion rotation is the real part alone; a dual quaternion with d=0d = 0 is a rotation about a line through the origin.
  • Screw motion and Chasles' theorem give the geometric meaning of the dual angle and the dual axis.
  • Twists and the SE(3) exponential give the same motion as e[S]θe^{[\mathcal S]\theta}; the dual quaternion is exp⁡(θ2(s+εv))\exp(\frac{\theta}{2}(s + \varepsilon v)).
  • The homogeneous transformation matrix is the 4x4 form of the same element of SE(3).
  • Screw linear interpolation, σ1(σ1∗σ2)τ\sigma_1 (\sigma_1^* \sigma_2)^\tau for τ∈[0,1]\tau \in [0, 1], moves along the constant screw from σ1\sigma_1 to σ2\sigma_2; it is the dual form of spherical linear interpolation.
  • Study's kinematic mapping sends a motion to the point [σ][\sigma] of real projective 7-space; the condition r⋅d=0r \cdot d = 0 is the Study quadric.
  • Daniilidis writes the hand-eye equation AX=XBAX = XB with dual quaternions, which solves for the rotation and the translation in one step.

Code

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

dual_quaternion.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dual-quaternion/. The authors are listed in prov/YTDVB1.jsonl.
"""Unit dual quaternions as rigid motions.

A quaternion is a list (w, x, y, z), Hamilton convention, scalar first.
A dual quaternion is a pair (r, d) of quaternions, r + eps d with eps^2 = 0.
It is a unit dual quaternion when |r| = 1 and r . d = 0.

- from_pose(q, t) gives the unit dual quaternion of the rigid motion
  x -> R(q) x + t, and to_pose inverts it.
- mul is the product, which composes motions: mul(a_of(T1), a_of(T2))
  is the dual quaternion of T1 T2.
- apply moves a point by sigma (1 + eps x) conj_both(sigma).
- from_screw builds cos(theta_hat / 2) + s_hat sin(theta_hat / 2) from a
  screw axis line, a pitch and an angle.
- to_matrix gives the 4x4 pose matrix.

sigma and -sigma give the same rigid motion.
"""

import math


def qmul(a, b):
    """Return the Hamilton product a b."""
    a1, b1, c1, d1 = a
    a2, b2, c2, d2 = b
    return [
        a1 * a2 - b1 * b2 - c1 * c2 - d1 * d2,
        a1 * b2 + b1 * a2 + c1 * d2 - d1 * c2,
        a1 * c2 - b1 * d2 + c1 * a2 + d1 * b2,
        a1 * d2 + b1 * c2 - c1 * b2 + d1 * a2,
    ]


def qconj(a):
    """Return the quaternion conjugate (w, -x, -y, -z)."""
    return [a[0], -a[1], -a[2], -a[3]]


def mul(a, b):
    """Return the dual quaternion product a b."""
    r1, d1 = a  # @line L1
    r2, d2 = b  # @line L1
    rd = qmul(r1, d2)  # @line L2
    dr = qmul(d1, r2)  # @line L2
    return [qmul(r1, r2), [x + y for x, y in zip(rd, dr)]]  # @line L2


def conj_both(a):
    """Return r* - eps d*, the conjugate used to move points."""
    return [qconj(a[0]), [-x for x in qconj(a[1])]]


def from_pose(q, t):
    """Return the unit dual quaternion of x -> R(q) x + t for a unit q."""
    return [list(q), [0.5 * x for x in qmul([0.0, t[0], t[1], t[2]], q)]]  # @line L3


def to_pose(a):
    """Return (q, t) with the unit quaternion q and the translation t."""
    r, d = a  # @line L4
    t = qmul(d, qconj(r))  # @line L4
    return list(r), [2.0 * t[1], 2.0 * t[2], 2.0 * t[3]]  # @line L4


def apply(a, x):
    """Return R x + t, from sigma (1 + eps x) conj_both(sigma)."""
    point = [[1.0, 0.0, 0.0, 0.0], [0.0, x[0], x[1], x[2]]]  # @line L5
    out = mul(mul(a, point), conj_both(a))  # @line L5
    return out[1][1:]  # @line L6


def from_screw(s, q, h, theta):
    """Return the dual quaternion of the screw motion about the line through
    q with unit direction s, with pitch h and angle theta.

    The dual angle is theta + eps d with d = h theta, and the dual axis is
    s + eps m with the moment m = q x s.
    """
    m = [q[1] * s[2] - q[2] * s[1], q[2] * s[0] - q[0] * s[2], q[0] * s[1] - q[1] * s[0]]
    d = h * theta
    c, sn = math.cos(theta / 2.0), math.sin(theta / 2.0)
    real = [c, sn * s[0], sn * s[1], sn * s[2]]
    dual = [-0.5 * d * sn] + [sn * m[i] + 0.5 * d * c * s[i] for i in range(3)]
    return [real, dual]


def to_matrix(a):
    """Return the 4x4 pose matrix [[R, t], [0, 1]] of a unit dual quaternion."""
    (w, x, y, z), t = to_pose(a)
    rot = [
        [1.0 - 2.0 * (y * y + z * z), 2.0 * (x * y - w * z), 2.0 * (x * z + w * y)],
        [2.0 * (x * y + w * z), 1.0 - 2.0 * (x * x + z * z), 2.0 * (y * z - w * x)],
        [2.0 * (x * z - w * y), 2.0 * (y * z + w * x), 1.0 - 2.0 * (x * x + y * y)],
    ]
    return [rot[0] + [t[0]], rot[1] + [t[1]], rot[2] + [t[2]], [0.0, 0.0, 0.0, 1.0]]
rbm.py 482 lines
# SPDX-License-Identifier: MIT
# Shared helper of the robotics pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small linear algebra, rotations, poses and quaternions for the robotics pages.

Conventions (Lynch and Park, Modern Robotics, 2017):
- A matrix is a list of rows. A vector is a flat list.
- hat3(w) is the skew-symmetric matrix [w], so that [w] x = w x x.
- A twist or screw is a 6-vector (omega, v), angular part first.
  hat6(V) is the 4x4 matrix [[[omega], v], [0, 0]].
- A pose T is the 4x4 matrix [[R, p], [0, 1]].
- so3_exp and so3_log use exponential coordinates w = omega_hat * theta,
  with theta = |w| in [0, pi] for so3_log.
- se3_exp and se3_log use 6-vectors (w, v) = S * theta.
- Quaternions are Hamilton, scalar first: q = (w, x, y, z), with i j = k.
- Angles are in radians.

The helper holds no algorithm of a robotics page except the four maps
so3_exp, so3_log, se3_exp and se3_log. The pages so3-logarithm-map and
se3-exponential-map hold their own complete versions with comments.
"""

import math

# Below this angle, the coefficient functions of the exponential and the
# logarithm are evaluated by their Taylor series. The first omitted term
# of each series is of order theta^6 and is below 3e-16 for theta < 1e-2;
# it also multiplies [w] or [w]^2, which are small. Above the threshold,
# the closed forms such as (1 - cos(theta)) / theta^2 lose at most about
# 1e-16 / theta^2 to cancellation, which [w] or [w]^2 brings to 1e-14.
SERIES_THETA = 1e-2

# Above pi - NEAR_PI, so3_log takes the axis from the symmetric part of R
# (which is (R + I) / 2 at theta = pi) and not from the skew part.
NEAR_PI = 1e-2

# A pivot whose magnitude is at most PIVOT_TOL times the largest entry of
# the matrix makes solve, inv and pinv_right raise ValueError.
PIVOT_TOL = 1e-12


# ---------------------------------------------------------------- matrices


def zeros(n, m):
    """Return the n by m zero matrix."""
    return [[0.0] * m for _ in range(n)]


def eye(n):
    """Return the n by n identity matrix."""
    return [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]


def _is_matrix(a):
    return len(a) > 0 and isinstance(a[0], list)


def add(a, b):
    """Return a + b for two vectors or two matrices of the same shape."""
    if _is_matrix(a):
        return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
    return [x + y for x, y in zip(a, b)]


def sub(a, b):
    """Return a - b for two vectors or two matrices of the same shape."""
    if _is_matrix(a):
        return [[x - y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
    return [x - y for x, y in zip(a, b)]


def scale(a, s):
    """Return s * a for a vector or a matrix a and a number s."""
    if _is_matrix(a):
        return [[s * x for x in row] for row in a]
    return [s * x for x in a]


def transpose(a):
    """Return the transpose of the matrix a."""
    return [list(col) for col in zip(*a)]


def mul(a, b):
    """Return the matrix product a b."""
    bt = transpose(b)
    return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]


def matvec(a, x):
    """Return the product of the matrix a and the vector x."""
    return [sum(p * q for p, q in zip(row, x)) for row in a]


def dot(x, y):
    """Return the dot product of two vectors."""
    return sum(p * q for p, q in zip(x, y))


def norm(x):
    """Return the Euclidean norm of a vector."""
    return math.sqrt(dot(x, x))


def cross(a, b):
    """Return the cross product a x b of two 3-vectors."""
    return [
        a[1] * b[2] - a[2] * b[1],
        a[2] * b[0] - a[0] * b[2],
        a[0] * b[1] - a[1] * b[0],
    ]


def _max_abs(a):
    return max((abs(x) for row in a for x in row), default=0.0)


def solve(a, b):
    """Solve a x = b by Gaussian elimination with partial pivoting.

    a is a square matrix. b is a vector or a matrix with one column per
    right-hand side; the result has the same shape as b. Raise ValueError
    if a pivot is at most PIVOT_TOL times the largest entry of a.
    """
    n = len(a)
    vec = not _is_matrix(b)
    rhs = [[x] for x in b] if vec else [list(row) for row in b]
    m = [list(map(float, row)) + list(map(float, r)) for row, r in zip(a, rhs)]
    k = len(rhs[0]) if rhs else 0
    tol = PIVOT_TOL * _max_abs(a)
    for c in range(n):
        piv = max(range(c, n), key=lambda r: abs(m[r][c]))
        if abs(m[piv][c]) <= tol or m[piv][c] == 0.0:
            raise ValueError("matrix is singular to working precision")
        m[c], m[piv] = m[piv], m[c]
        for r in range(c + 1, n):
            f = m[r][c] / m[c][c]
            if f != 0.0:
                row_r, row_c = m[r], m[c]
                for j in range(c, n + k):
                    row_r[j] -= f * row_c[j]
    x = [[0.0] * k for _ in range(n)]
    for r in range(n - 1, -1, -1):
        for j in range(k):
            s = m[r][n + j] - sum(m[r][i] * x[i][j] for i in range(r + 1, n))
            x[r][j] = s / m[r][r]
    return [row[0] for row in x] if vec else x


def inv(a):
    """Return the inverse of the square matrix a (see solve for errors)."""
    return solve(a, eye(len(a)))


def det(a):
    """Return the determinant of the square matrix a by elimination."""
    n = len(a)
    m = [list(map(float, row)) for row in a]
    d = 1.0
    for c in range(n):
        piv = max(range(c, n), key=lambda r: abs(m[r][c]))
        if m[piv][c] == 0.0:
            return 0.0
        if piv != c:
            m[c], m[piv] = m[piv], m[c]
            d = -d
        d *= m[c][c]
        for r in range(c + 1, n):
            f = m[r][c] / m[c][c]
            for j in range(c, n):
                m[r][j] -= f * m[c][j]
    return d


def cholesky(a):
    """Return the lower triangular L with a = L L^T.

    a must be symmetric positive definite. Raise ValueError if a diagonal
    entry of the factor is not positive.
    """
    n = len(a)
    low = zeros(n, n)
    for i in range(n):
        for j in range(i + 1):
            s = a[i][j] - sum(low[i][k] * low[j][k] for k in range(j))
            if i == j:
                if s <= 0.0:
                    raise ValueError("matrix is not positive definite")
                low[i][i] = math.sqrt(s)
            else:
                low[i][j] = s / low[j][j]
    return low


def pinv_right(j):
    """Return the right pseudoinverse J^T (J J^T)^(-1) of a J with full row rank."""
    jt = transpose(j)
    return mul(jt, inv(mul(j, jt)))


# ---------------------------------------------------------------- hat and vee


def hat3(w):
    """Return the 3x3 skew-symmetric matrix [w] of a 3-vector w."""
    return [
        [0.0, -w[2], w[1]],
        [w[2], 0.0, -w[0]],
        [-w[1], w[0], 0.0],
    ]


def vee3(m):
    """Return the 3-vector w of a skew-symmetric matrix m = [w]."""
    return [m[2][1], m[0][2], m[1][0]]


def hat6(v):
    """Return the 4x4 matrix [V] = [[[omega], v], [0, 0]] of V = (omega, v)."""
    w = hat3(v[:3])
    return [
        [w[0][0], w[0][1], w[0][2], v[3]],
        [w[1][0], w[1][1], w[1][2], v[4]],
        [w[2][0], w[2][1], w[2][2], v[5]],
        [0.0, 0.0, 0.0, 0.0],
    ]


def vee6(m):
    """Return the 6-vector (omega, v) of a 4x4 matrix [V]."""
    return [m[2][1], m[0][2], m[1][0], m[0][3], m[1][3], m[2][3]]


# ---------------------------------------------------------------- rotations


def rot_x(a):
    """Return the rotation by a radians about the x axis."""
    c, s = math.cos(a), math.sin(a)
    return [[1.0, 0.0, 0.0], [0.0, c, -s], [0.0, s, c]]


def rot_y(a):
    """Return the rotation by a radians about the y axis."""
    c, s = math.cos(a), math.sin(a)
    return [[c, 0.0, s], [0.0, 1.0, 0.0], [-s, 0.0, c]]


def rot_z(a):
    """Return the rotation by a radians about the z axis."""
    c, s = math.cos(a), math.sin(a)
    return [[c, -s, 0.0], [s, c, 0.0], [0.0, 0.0, 1.0]]


def rpy(roll, pitch, yaw):
    """Return R = Rz(yaw) Ry(pitch) Rx(roll)."""
    return mul(rot_z(yaw), mul(rot_y(pitch), rot_x(roll)))


def so3_exp(w):
    """Return exp([w]) for exponential coordinates w = omega_hat * theta.

    Rodrigues' formula in the form I + A [w] + B [w]^2 with
    A = sin(theta) / theta and B = (1 - cos(theta)) / theta^2.
    """
    t = norm(w)
    if t < SERIES_THETA:
        t2 = t * t
        a = 1.0 - t2 / 6.0 + t2 * t2 / 120.0
        b = 0.5 - t2 / 24.0 + t2 * t2 / 720.0
    else:
        a = math.sin(t) / t
        b = (1.0 - math.cos(t)) / (t * t)
    k = hat3(w)
    k2 = mul(k, k)
    return [[(1.0 if i == j else 0.0) + a * k[i][j] + b * k2[i][j] for j in range(3)] for i in range(3)]


def so3_log(r):
    """Return w = omega_hat * theta with exp([w]) = r and theta in [0, pi].

    theta = atan2(|s|, c), where c = (trace(r) - 1) / 2 = cos(theta) and
    s = vee(r - r^T) / 2 = sin(theta) omega_hat. For theta below
    SERIES_THETA, w = s (1 + theta^2 / 6 + 7 theta^4 / 360). For theta
    above pi - NEAR_PI, the axis comes from the symmetric part
    ((r + r^T) / 2 - c I) / (1 - c) = omega_hat omega_hat^T, and its sign
    from s. At theta = pi both signs are valid; the sign is then chosen so
    that the largest component of the axis is positive.
    """
    c = (r[0][0] + r[1][1] + r[2][2] - 1.0) / 2.0
    c = max(-1.0, min(1.0, c))
    s = [(r[2][1] - r[1][2]) / 2.0, (r[0][2] - r[2][0]) / 2.0, (r[1][0] - r[0][1]) / 2.0]
    sn = norm(s)
    t = math.atan2(sn, c)
    if t < SERIES_THETA:
        t2 = t * t
        f = 1.0 + t2 / 6.0 + 7.0 * t2 * t2 / 360.0
        return [f * x for x in s]
    if t <= math.pi - NEAR_PI:
        return [t / sn * x for x in s]
    b = [[(r[i][j] + r[j][i]) / 2.0 - (c if i == j else 0.0) for j in range(3)] for i in range(3)]
    # b = (1 - c) omega_hat omega_hat^T. Its column k with the largest
    # diagonal entry is (1 - c) omega_k omega_hat, with omega_k^2 >= 1/3.
    k = max(range(3), key=lambda i: b[i][i])
    col = [b[i][k] for i in range(3)]
    axis = [x / norm(col) for x in col]
    if dot(axis, s) < 0.0 or (dot(axis, s) == 0.0 and axis[k] < 0.0):
        axis = [-x for x in axis]
    return [t * x for x in axis]


# ---------------------------------------------------------------- poses


def make_T(r, p):
    """Return the 4x4 pose [[r, p], [0, 1]]."""
    return [
        [r[0][0], r[0][1], r[0][2], p[0]],
        [r[1][0], r[1][1], r[1][2], p[1]],
        [r[2][0], r[2][1], r[2][2], p[2]],
        [0.0, 0.0, 0.0, 1.0],
    ]


def _rp(t):
    return [row[:3] for row in t[:3]], [t[0][3], t[1][3], t[2][3]]


def T_inv(t):
    """Return the inverse [[R^T, -R^T p], [0, 1]] of a pose t."""
    r, p = _rp(t)
    rt = transpose(r)
    return make_T(rt, [-x for x in matvec(rt, p)])


def T_apply(t, x):
    """Return R x + p, the image of the point x under the pose t."""
    r, p = _rp(t)
    return add(matvec(r, x), p)


def se3_exp(xi):
    """Return exp([xi]) for a 6-vector xi = (w, v) = S * theta.

    The rotation is so3_exp(w). The translation is G v with
    G = I + B [w] + C [w]^2, B = (1 - cos(theta)) / theta^2 and
    C = (theta - sin(theta)) / theta^3, theta = |w|. For w = 0 this is a
    translation by v.
    """
    w, v = xi[:3], xi[3:]
    t = norm(w)
    if t < SERIES_THETA:
        t2 = t * t
        b = 0.5 - t2 / 24.0 + t2 * t2 / 720.0
        c = 1.0 / 6.0 - t2 / 120.0 + t2 * t2 / 5040.0
    else:
        b = (1.0 - math.cos(t)) / (t * t)
        c = (t - math.sin(t)) / (t * t * t)
    k = hat3(w)
    k2 = mul(k, k)
    g = [[(1.0 if i == j else 0.0) + b * k[i][j] + c * k2[i][j] for j in range(3)] for i in range(3)]
    return make_T(so3_exp(w), matvec(g, v))


def se3_log(t):
    """Return the 6-vector xi = (w, v) with se3_exp(xi) = t and |w| in [0, pi].

    w = so3_log(R) and v = G^(-1) p with
    G^(-1) = I - [w] / 2 + D [w]^2, D = (1 - (theta / 2) cot(theta / 2)) / theta^2.
    """
    r, p = _rp(t)
    w = so3_log(r)
    th = norm(w)
    if th < SERIES_THETA:
        t2 = th * th
        d = 1.0 / 12.0 + t2 / 720.0 + t2 * t2 / 30240.0
    else:
        half = th / 2.0
        d = (1.0 - half * math.cos(half) / math.sin(half)) / (th * th)
    k = hat3(w)
    k2 = mul(k, k)
    gi = [[(1.0 if i == j else 0.0) - 0.5 * k[i][j] + d * k2[i][j] for j in range(3)] for i in range(3)]
    return w + matvec(gi, p)


def adjoint(t):
    """Return the 6x6 adjoint [[R, 0], [[p] R, R]] of a pose t."""
    r, p = _rp(t)
    pr = mul(hat3(p), r)
    out = zeros(6, 6)
    for i in range(3):
        for j in range(3):
            out[i][j] = r[i][j]
            out[i + 3][j + 3] = r[i][j]
            out[i + 3][j] = pr[i][j]
    return out


# ---------------------------------------------------------------- quaternions


def quat_mul(q, r):
    """Return the Hamilton product q r of quaternions (w, x, y, z)."""
    a1, b1, c1, d1 = q
    a2, b2, c2, d2 = r
    return [
        a1 * a2 - b1 * b2 - c1 * c2 - d1 * d2,
        a1 * b2 + b1 * a2 + c1 * d2 - d1 * c2,
        a1 * c2 - b1 * d2 + c1 * a2 + d1 * b2,
        a1 * d2 + b1 * c2 - c1 * b2 + d1 * a2,
    ]


def quat_conj(q):
    """Return the conjugate (w, -x, -y, -z)."""
    return [q[0], -q[1], -q[2], -q[3]]


def quat_to_rot(q):
    """Return the rotation matrix of the quaternion q, so that (0, R v) = q (0, v) q*.

    q need not be of unit length; the result is the rotation of q / |q|.
    """
    w, x, y, z = q
    n = w * w + x * x + y * y + z * z
    s = 2.0 / n
    return [
        [1.0 - s * (y * y + z * z), s * (x * y - w * z), s * (x * z + w * y)],
        [s * (x * y + w * z), 1.0 - s * (x * x + z * z), s * (y * z - w * x)],
        [s * (x * z - w * y), s * (y * z + w * x), 1.0 - s * (x * x + y * y)],
    ]


def quat_from_axis_angle(axis, angle):
    """Return (cos(angle / 2), sin(angle / 2) axis / |axis|).

    A zero axis is allowed only with angle 0 (the identity); otherwise
    raise ValueError.
    """
    n = norm(axis)
    if n == 0.0:
        if angle == 0.0:
            return [1.0, 0.0, 0.0, 0.0]
        raise ValueError("zero axis with a nonzero angle")
    s = math.sin(angle / 2.0) / n
    return [math.cos(angle / 2.0), s * axis[0], s * axis[1], s * axis[2]]


# ---------------------------------------------------------------- derivatives


def num_jacobian(f, x, h=1e-6):
    """Return the Jacobian of f at x by central differences with step h.

    f maps a list of n numbers to a list of m numbers; the result is m by n.
    """
    cols = []
    for i in range(len(x)):
        xp = list(x)
        xm = list(x)
        xp[i] += h
        xm[i] -= h
        fp, fm = f(xp), f(xm)
        cols.append([(a - b) / (2.0 * h) for a, b in zip(fp, fm)])
    return transpose(cols)


# ---------------------------------------------------------------- self-test


def self_test():
    """Check the area check values; return True or raise AssertionError."""
    r = so3_exp([2.0 * math.pi / 3.0 / math.sqrt(3.0)] * 3)
    want = [[0.0, 0.0, 1.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]
    assert max(abs(r[i][j] - want[i][j]) for i in range(3) for j in range(3)) < 1e-12
    w = so3_log(want)
    assert abs(norm(w) - 2.0943951) < 1e-7
    assert max(abs(x - 2.0 * math.pi / 3.0 / math.sqrt(3.0)) for x in w) < 1e-12
    t = se3_exp([0.0, 0.0, math.pi / 2.0, math.pi / 2.0, 0.0, 0.0])
    want_t = make_T(rot_z(math.pi / 2.0), [1.0, 1.0, 0.0])
    assert max(abs(t[i][j] - want_t[i][j]) for i in range(4) for j in range(4)) < 1e-12
    return True
test_dual_quaternion.py 119 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dual-quaternion/. The authors are listed in prov/YTDVB1.jsonl.
"""Tests of the dual quaternion operations against the 4x4 poses of rbm."""

import math
import random

import rbm
from dual_quaternion import apply, conj_both, from_pose, from_screw, mul, to_matrix, to_pose

TOL = 1e-12


def maxdiff(a, b):
    if a and isinstance(a[0], list):
        return max(abs(x - y) for ra, rb in zip(a, b) for x, y in zip(ra, rb))
    return max(abs(x - y) for x, y in zip(a, b))


def quat_of(r):
    """Unit quaternion of a rotation matrix, through so3_log (rbm has no direct map)."""
    w = rbm.so3_log(r)
    th = rbm.norm(w)
    if th == 0.0:
        return [1.0, 0.0, 0.0, 0.0]
    return rbm.quat_from_axis_angle(w, th)


def dq_of(t):
    return from_pose(quat_of([row[:3] for row in t[:3]]), [t[0][3], t[1][3], t[2][3]])


def random_pose(rng):
    xi = [rng.uniform(-1.5, 1.5) for _ in range(3)] + [rng.uniform(-3.0, 3.0) for _ in range(3)]
    return rbm.se3_exp(xi)


def same_up_to_sign(a, b):
    fa = a[0] + a[1]
    fb = b[0] + b[1]
    return min(maxdiff(fa, fb), maxdiff(fa, [-x for x in fb]))


def test_check_values():
    h = math.pi / 2.0
    t = rbm.se3_exp([0.0, 0.0, h, h, 0.0, 0.0])
    s = dq_of(t)
    c = math.sqrt(0.5)
    assert maxdiff(s[0], [c, 0.0, 0.0, c]) < TOL
    assert maxdiff(s[1], [0.0, c, 0.0, 0.0]) < TOL
    q, p = to_pose(s)
    assert maxdiff(p, [1.0, 1.0, 0.0]) < TOL
    assert maxdiff(to_matrix(s), rbm.make_T(rbm.rot_z(h), [1.0, 1.0, 0.0])) < TOL
    # The same motion as the screw about the line through (0, 1, 0), pitch 0.
    assert same_up_to_sign(from_screw([0.0, 0.0, 1.0], [0.0, 1.0, 0.0], 0.0, h), s) < TOL
    # A half turn about x has the quaternion (0, 1, 0, 0).
    assert maxdiff(quat_of(rbm.rot_x(math.pi)), [0.0, 1.0, 0.0, 0.0]) < TOL


def test_unit_conditions_and_round_trip():
    rng = random.Random(1)
    for _ in range(200):
        t = random_pose(rng)
        s = dq_of(t)
        assert abs(rbm.dot(s[0], s[0]) - 1.0) < TOL
        assert abs(rbm.dot(s[0], s[1])) < TOL
        assert maxdiff(to_matrix(s), t) < 1e-11


def test_product_composes_poses():
    rng = random.Random(2)
    for _ in range(200):
        t1, t2 = random_pose(rng), random_pose(rng)
        assert same_up_to_sign(mul(dq_of(t1), dq_of(t2)), dq_of(rbm.mul(t1, t2))) < 1e-11
        assert maxdiff(to_matrix(mul(dq_of(t1), dq_of(t2))), rbm.mul(t1, t2)) < 1e-11


def test_apply_moves_points():
    rng = random.Random(3)
    for _ in range(200):
        t = random_pose(rng)
        x = [rng.uniform(-2.0, 2.0) for _ in range(3)]
        assert maxdiff(apply(dq_of(t), x), rbm.T_apply(t, x)) < 1e-11


def test_double_cover():
    rng = random.Random(4)
    for _ in range(100):
        s = dq_of(random_pose(rng))
        neg = [[-x for x in s[0]], [-x for x in s[1]]]
        assert maxdiff(to_matrix(neg), to_matrix(s)) < TOL
        x = [rng.uniform(-2.0, 2.0) for _ in range(3)]
        assert maxdiff(apply(neg, x), apply(s, x)) < TOL


def test_inverse_is_the_conjugate():
    rng = random.Random(5)
    for _ in range(100):
        t = random_pose(rng)
        s = dq_of(t)
        inv = [rbm.quat_conj(s[0]), rbm.quat_conj(s[1])]
        assert maxdiff(to_matrix(inv), rbm.T_inv(t)) < 1e-11
        one = mul(s, inv)
        assert maxdiff(one[0] + one[1], [1.0, 0, 0, 0, 0, 0, 0, 0]) < 1e-12
        assert len(conj_both(s)) == 2


def test_screw_form_matches_exponential():
    rng = random.Random(6)
    for _ in range(200):
        w = [rng.gauss(0.0, 1.0) for _ in range(3)]
        s = [x / rbm.norm(w) for x in w]
        q = [rng.uniform(-2.0, 2.0) for _ in range(3)]
        h = rng.uniform(-1.0, 1.0)
        th = rng.uniform(-3.0, 3.0)
        v = rbm.add(rbm.scale(rbm.cross(s, q), -1.0), rbm.scale(s, h))
        t = rbm.se3_exp([x * th for x in s + v])
        assert same_up_to_sign(from_screw(s, q, h, th), dq_of(t)) < 1e-11
        assert maxdiff(to_matrix(from_screw(s, q, h, th)), t) < 1e-11

References

  1. W. K. Clifford, Preliminary sketch of biquaternions, Proceedings of the London Mathematical Society s1-4, 381 to 395, 1873, the whole paper (biquaternions, with a unit whose square is zero, and their use for motors)
  2. E. Study, Von den Bewegungen und Umlegungen, Mathematische Annalen 39(4), 441 to 565, 1891, the whole paper (dual numbers and the representation of the motions of space)
  3. Konstantinos Daniilidis, Hand-eye calibration using dual quaternions, The International Journal of Robotics Research 18(3), 286 to 298, 1999, the dual quaternion of a screw motion and the hand-eye calibration that uses it
  4. Ladislav Kavan, Steven Collins, Jiří Žára and Carol O'Sullivan, Geometric skinning with approximate dual quaternion blending, ACM Transactions on Graphics 27(4), article 105, 2008, the dual quaternion product, the conversion from a rigid transformation, the sign choice and the blending with normalization

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/YTDVB1/text.yaml