Algorithmadvanced
Shepperd's method
Also called quaternion from rotation matrix.
Converts a rotation matrix to a unit quaternion by taking the square root of the largest of the four squared components, so that every division is by a number of at least 2.
- Time
- Θ(1) worst
- Space
- Θ(1) extra
- Where
- n = the size of the matrix, fixed at n = 3
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
Shepperd's method converts a 3 by 3 rotation matrix into the unit quaternion of the same rotation. Each of the four squares is a linear function of the diagonal of , and each product of two components is a sum or a difference of two entries off the diagonal. The method takes the square root of the largest square, which is at least , and gets the other three components by division by four times that component. The simple formula that always divides by fails for rotations by angles near , where is near zero; Shepperd's choice makes the result accurate in floating point for every rotation.
In plain words
A quaternion stores a turn as four numbers. A rotation matrix stores the same turn as nine numbers. From the matrix you can find the square of each of the four numbers by simple sums. You can also find the product of each pair of numbers. So you take one number as a square root, and you get the other three from the products by division. If the number you divide by is almost zero, the answer is bad. The method always takes the largest of the four numbers first, so the division is always safe. The quaternion and its negative give the same turn, so the method picks the sign that makes the first number not negative.
The problem
The input is a matrix in the special orthogonal group SO(3), so and . The output is a unit quaternion in the Hamilton convention, scalar first, such that is the vector part of for every . Both and are correct answers. The method returns the one with , which is unique when , that is, when the rotation angle is less than .
For a unit quaternion, the rotation matrix is
With and , this gives ten identities:
The algorithm
The four squares grow in the same order as the four numbers , because, for example, and . So line L2 finds the largest square without computing all four.
SHEPPERD(R) ▷ R in SO(3); returns q = (w, x, y, z) with w ≥ 0- 1
t ← r₁₁ + r₂₂ + r₃₃ - 2
k ← the index of the largest of (t, r₁₁, r₂₂, r₃₃), from 0 to 3 - 3
if k = 0 then ▷ w² is the largest square - 4
w ← √(1 + t) / 2 - 5
(x, y, z) ← (r₃₂ - r₂₃, r₁₃ - r₃₁, r₂₁ - r₁₂) / (4w) - 6
else if k = 1 then ▷ x² is the largest square - 7
x ← √(1 + 2r₁₁ - t) / 2 - 8
(w, y, z) ← (r₃₂ - r₂₃, r₂₁ + r₁₂, r₁₃ + r₃₁) / (4x) - 9
else if k = 2 then ▷ y² is the largest square - 10
y ← √(1 + 2r₂₂ - t) / 2 - 11
(w, x, z) ← (r₁₃ - r₃₁, r₂₁ + r₁₂, r₃₂ + r₂₃) / (4y) - 12
else ▷ z² is the largest square - 13
z ← √(1 + 2r₃₃ - t) / 2 - 14
(w, x, y) ← (r₂₁ - r₁₂, r₁₃ + r₃₁, r₃₂ + r₂₃) / (4z) - 15
if w < 0 then q ← -q ▷ q and -q are the same rotation - 16
return q = (w, x, y, z)
Lines L4, L7, L10 and L13 are the square identities, each solved for one component with the positive root. Lines L5, L8, L11 and L14 are the product identities, each divided by four times the component that is already known. Line L15 picks one of the two signs.
Example
Take the rotation by 170 degrees about the axis . Its exact quaternion is . Rodrigues' formula gives, to 7 digits,
- Line L1: .
- Line L2: the largest of is , so . The four squares are , , and .
- Line L13: , and .
- Line L14: , , and .
- Line L15: , so the sign stays.
The result agrees with the exact quaternion in all 7 digits.
Two short checks use the values of the area. For , and ; line L2 takes the first of the two equal values, , and lines L4 and L5 give and , so . For the rotation by about , , and . Line L7 gives , line L8 gives , and the output is . The formula that always divides by divides by zero here.
The table is a measurement in IEEE double precision with the implementation of this page. The axis is , comes from Rodrigues' formula, and the error is the largest component error against the exact quaternion, up to the sign.
| angle | error of the formula that divides by | error of SHEPPERD |
|---|---|---|
| 1.7e-14 | 1.1e-16 | |
| 5.2e-10 | 2.2e-16 | |
| 9.2e-7 | 2.2e-16 | |
| 3.5e-2 | 1.1e-16 | |
| division by zero | 2.2e-16 |
At , rounds to 0, and the simple formula has nothing left to divide by.
Correctness
The ten identities follow from the matrix of by direct expansion and from . The four numbers sum to 4, so the largest one is at least 1, and the component that line L2 selects has an absolute value of at least . The square root in that branch is of a number of at least 1, so it is defined, and the divisor is at least 2. The branch returns that component with a positive sign and the other three from the product identities, which gives one of ; both are the same rotation, and line L15 picks the one with . Every unit quaternion gives a rotation, and every rotation has a unit quaternion by Euler's rotation theorem, so there is always a to find. The proof gives the details and a first-order error bound in floating point.
Proof: SHEPPERD returns a unit quaternion of the input rotationfull
We use the notation of the page. A quaternion is in the Hamilton convention, scalar first, with . For a unit quaternion , the map the vector part of is linear, and its matrix is
With , the diagonal entries become the form and so on that the page uses. The proof is first in exact arithmetic, and the last section gives a first-order error bound in floating point.
Every rotation has a unit quaternion
Lemma 1. For every there is a unit quaternion with , and the unit quaternions with this property are exactly and .
Proof. By Euler's rotation theorem, for a unit axis and an angle . Put . Expanding with , and the identities , and gives , which is Rodrigues' formula, so . The entries of are quadratic in , so . Conversely, suppose for unit and . Then , because of a product is the product of the matrices and . Write with . From the diagonal of and we get and , so and . Hence .
The ten identities
Lemma 2. Let be a unit quaternion and , with . Then
Proof. From the first form of , . Also , so . The cases of and are the same with the indices moved. The six product identities come from the sums and the differences of the symmetric pairs of entries: for example and .
Line L2 picks the largest square
Lemma 3. The index of line L2 is the index of a largest number among , and this number is at least .
Proof. By Lemma 2, , , , and in the same way , and . So the map keeps the order of every pair, and the largest entry of one list has the same index as the largest entry of the other. The four squares sum to 1, so the largest is at least .
The branch returns plus or minus q
Theorem. For every , SHEPPERD returns a unit quaternion with and .
Proof. Let be a unit quaternion with (Lemma 1), and let be the index of line L2. Write for . Replace by if needed so that ; this is possible because by Lemma 3. The branch of index computes by the square identity of Lemma 2, and the radicand is at least 1, so the root is defined. It then divides three product sums by , and by the product identities of Lemma 2 each quotient is . So the branch returns exactly . Line L15 replaces by if . In both cases the output is , so it has length 1, , and .
Uniqueness. If the rotation angle is less than , then , and by Lemma 1 only one of has . At the angle , , and the output is the one of whose component is positive.
Floating point
Let the entries of the input have absolute errors at most , with small, and ignore the rounding of the few operations of the method, which adds terms of the order of the unit roundoff . The selected square is a sum of four entries with coefficients (for example ), so its error is at most . The derivative of is , and , so the error of is at most to first order. Each other component is , where the numerator has an error of at most . To first order,
So every component has an error of at most , for every rotation.
For comparison, the formula that always uses has and , which is about when is close to 1. At the angle , , so the error grows like . With of the order of , this is the growth of the table on the page.
Complexity
The input has a fixed size, so time and space are . The method uses 3 comparisons, one square root, about 10 additions and 4 divisions (or one division and 3 multiplications). It uses no trigonometric function. The route through the logarithm map and the axis and angle needs an atan2, a sine and a cosine, and has its own branches near and .
Properties
- Accuracy. For a rotation matrix with rounding errors of the order of the unit roundoff in its entries, every output component has an absolute error of order , at every angle. The formula that divides by has an error of order at the angle , as the table shows.
- No special cases. No branch tests for the identity or for the angle . The rotations by about , and use the branches , and the identity uses .
- Uniqueness. With line L15, the output is unique for every rotation by an angle less than . At the angle , and both and have ; the output is then the one with a positive component .
- Continuity. All four branches compute the same in exact arithmetic, so the switch between branches does not make a jump. The only jump is the sign flip of line L15 at the angle , which no continuous choice can avoid.
- Input that is not orthogonal. If is close to a rotation, the output is close to the quaternion of that rotation, but its length is not exactly 1. Normalize it if the length matters.
Variants and improvements
- Normalization at the end. Divide by its length. This costs one more square root and makes the output a unit quaternion even when is slightly off SO(3).
- The sign of a time series. For a sequence of rotations, as in a recorded trajectory, choose the sign of each quaternion so that its dot product with the previous one is positive, and not by . This keeps the sequence continuous, which spherical linear interpolation and filters need.
- The eigenvector method. Build the 4 by 4 symmetric matrix of the Davenport q-method from and take the eigenvector of its largest eigenvalue. This gives the quaternion of a nearby rotation for a matrix that is far from orthogonal, at the cost of an eigenvalue problem.
- Through the logarithm. Compute with the logarithm map of SO(3), then . This needs trigonometric functions, and it must handle the angle with its own branch.
- The JPL convention. Some attitude papers write the quaternion with the scalar last and with . In that convention the signs of the three differences in lines L5, L8, L11 and L14 change. Convert at the interface, and do not mix the two.
When to use it
Use the method whenever a rotation matrix must become a quaternion: after forward kinematics, from the output of a camera pose or a point set alignment such as the Kabsch algorithm, or to store attitude in a filter state. It is the standard step before spherical linear interpolation, before an integration of the quaternion kinematic equation, and before rotation averaging methods that work on quaternions.
Pitfalls
- The formula that divides by . It is the first one in many books, and it is correct, but only for angles well below . Its error grows as near , and it divides by zero at . This is a loss of accuracy by cancellation in .
- A transposed matrix. If maps world coordinates to body coordinates, the method returns the conjugate quaternion. Check which way the matrix maps before you convert.
- Equal values in line L2. Ties are harmless: any branch with the largest square works, because its component is at least .
- Comparing quaternions. Two correct results can differ in sign. Compare and by , or compare the matrices.
- A matrix that is not a rotation. A reflection () also gives four numbers, but they mean nothing. Check when the input is not trusted.
Implementations
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.
# 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
shepperd_method.py 68 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/shepperd-method/. The authors are listed in prov/DK6ZQE.jsonl.
"""Shepperd's method: the unit quaternion of a rotation matrix.
Quaternions use the Hamilton convention, scalar first, q = (w, x, y, z),
and q acts on a vector v by (0, R v) = q (0, v) q*. For such a q,
4 w^2 = 1 + t 4 w x = r32 - r23 4 x y = r21 + r12
4 x^2 = 1 + 2 r11 - t 4 w y = r13 - r31 4 x z = r13 + r31
4 y^2 = 1 + 2 r22 - t 4 w z = r21 - r12 4 y z = r32 + r23
4 z^2 = 1 + 2 r33 - t
where t = r11 + r22 + r33 is the trace (indices from 1 in the comments,
from 0 in the code). The four squares sum to 4, so the largest one is at
least 1. Shepperd's method takes the square root of the largest one, and
gets the other three components from the off-diagonal sums and differences,
divided by four times that component, which is at least 2.
shepperd(R) is the method. quat_textbook(R) is the method that always
divides by 4 w; it is here to show the loss of accuracy near the angle pi.
Matrices are lists of rows. Vectors and quaternions are lists.
"""
import math
def shepperd(r):
"""Return the unit quaternion (w, x, y, z), with w >= 0, of the rotation r."""
t = r[0][0] + r[1][1] + r[2][2] # @line L1
k = max(range(4), key=lambda i: (t, r[0][0], r[1][1], r[2][2])[i]) # @line L2
if k == 0: # @line L3
w = math.sqrt(1.0 + t) / 2.0 # @line L4
f = 4.0 * w
q = [w, (r[2][1] - r[1][2]) / f, (r[0][2] - r[2][0]) / f, (r[1][0] - r[0][1]) / f] # @line L5
elif k == 1: # @line L6
x = math.sqrt(1.0 + 2.0 * r[0][0] - t) / 2.0 # @line L7
f = 4.0 * x
q = [(r[2][1] - r[1][2]) / f, x, (r[1][0] + r[0][1]) / f, (r[0][2] + r[2][0]) / f] # @line L8
elif k == 2: # @line L9
y = math.sqrt(1.0 + 2.0 * r[1][1] - t) / 2.0 # @line L10
f = 4.0 * y
q = [(r[0][2] - r[2][0]) / f, (r[1][0] + r[0][1]) / f, y, (r[2][1] + r[1][2]) / f] # @line L11
else: # @line L12
z = math.sqrt(1.0 + 2.0 * r[2][2] - t) / 2.0 # @line L13
f = 4.0 * z
q = [(r[1][0] - r[0][1]) / f, (r[0][2] + r[2][0]) / f, (r[2][1] + r[1][2]) / f, z] # @line L14
if q[0] < 0.0: # @line L15
q = [-a for a in q]
return q # @line L16
def branch(r):
"""Return the index (0 for w, 1 for x, 2 for y, 3 for z) that line L2 picks."""
t = r[0][0] + r[1][1] + r[2][2]
return max(range(4), key=lambda i: (t, r[0][0], r[1][1], r[2][2])[i])
def quat_textbook(r):
"""Return the quaternion by the formula that always divides by 4 w.
w = sqrt(1 + t) / 2, and x, y, z from the skew part. It fails at w = 0
(a rotation by pi) and loses accuracy when w is small.
"""
t = r[0][0] + r[1][1] + r[2][2]
w = math.sqrt(max(0.0, 1.0 + t)) / 2.0
f = 4.0 * w
return [w, (r[2][1] - r[1][2]) / f, (r[0][2] - r[2][0]) / f, (r[1][0] - r[0][1]) / f]
test_shepperd_method.py 135 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/shepperd-method/. The authors are listed in prov/DK6ZQE.jsonl.
"""Tests of Shepperd's method.
The references are the shared helper rbm: quat_to_rot (quaternion to
matrix) for the round trip, and so3_log with quat_from_axis_angle as a
second, independent way from the matrix to the quaternion.
"""
import math
import random
import rbm
from shepperd_method import branch, quat_textbook, shepperd
def unit(rng, n=3):
while True:
v = [rng.gauss(0.0, 1.0) for _ in range(n)]
s = math.sqrt(sum(x * x for x in v))
if s > 1e-3:
return [x / s for x in v]
def mdiff(a, b):
return max(abs(a[i][j] - b[i][j]) for i in range(3) for j in range(3))
def qdiff(p, q):
"""Distance of two quaternions up to the sign, since q and -q agree."""
return min(max(abs(a - b) for a, b in zip(p, q)), max(abs(a + b) for a, b in zip(p, q)))
def test_check_values():
q = shepperd(rbm.rot_z(math.pi / 2.0))
assert qdiff(q, [math.sqrt(0.5), 0.0, 0.0, math.sqrt(0.5)]) < 1e-15
assert abs(q[0] - 0.70711) < 1e-5 and abs(q[3] - 0.70711) < 1e-5
# The rotation by 2 pi / 3 about (1, 1, 1) / sqrt(3).
q = shepperd([[0.0, 0.0, 1.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]])
assert q == [0.5, 0.5, 0.5, 0.5]
# The rotation by pi about x: w = 0, and the x branch is used.
r = [[1.0, 0.0, 0.0], [0.0, -1.0, 0.0], [0.0, 0.0, -1.0]]
assert branch(r) == 1
assert shepperd(r) == [0.0, 1.0, 0.0, 0.0]
def test_rotations_by_pi_about_each_axis():
# The identity and the three half turns use the four branches.
cases = [
([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], 0, [1.0, 0.0, 0.0, 0.0]),
([[1.0, 0.0, 0.0], [0.0, -1.0, 0.0], [0.0, 0.0, -1.0]], 1, [0.0, 1.0, 0.0, 0.0]),
([[-1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, -1.0]], 2, [0.0, 0.0, 1.0, 0.0]),
([[-1.0, 0.0, 0.0], [0.0, -1.0, 0.0], [0.0, 0.0, 1.0]], 3, [0.0, 0.0, 0.0, 1.0]),
]
for r, k, want in cases:
assert branch(r) == k
assert shepperd(r) == want
def test_all_four_branches_on_random_rotations():
rng = random.Random(1)
seen = [0, 0, 0, 0]
for _ in range(2000):
q0 = unit(rng, 4)
r = rbm.quat_to_rot(q0)
q = shepperd(r)
seen[branch(r)] += 1
assert abs(sum(a * a for a in q) - 1.0) < 1e-14
assert q[0] >= 0.0
assert qdiff(q, q0) < 1e-14
assert mdiff(rbm.quat_to_rot(q), r) < 1e-14
# Each branch is used for a fair share of uniform random rotations.
assert min(seen) > 200
def test_branch_picks_the_largest_component():
rng = random.Random(2)
for _ in range(500):
q0 = unit(rng, 4)
k = branch(rbm.quat_to_rot(q0))
# Ties are broken by rounding, so allow a tiny gap.
assert abs(q0[k]) >= max(abs(a) for a in q0) - 1e-12
assert abs(q0[k]) >= 0.5 - 1e-12
def test_against_log_and_axis_angle():
rng = random.Random(3)
for _ in range(300):
axis = unit(rng)
angle = rng.uniform(0.0, math.pi - 0.05)
r = rbm.so3_exp([angle * a for a in axis])
w = rbm.so3_log(r)
th = math.sqrt(sum(x * x for x in w))
ref = rbm.quat_from_axis_angle(w, th) if th > 0.0 else [1.0, 0.0, 0.0, 0.0]
assert qdiff(shepperd(r), ref) < 1e-13
def test_half_turns_about_random_axes():
rng = random.Random(4)
for _ in range(300):
u = unit(rng)
# R = 2 u u^T - I is the rotation by pi about u, built exactly.
r = [[2.0 * u[i] * u[j] - (1.0 if i == j else 0.0) for j in range(3)] for i in range(3)]
q = shepperd(r)
assert qdiff(q, [0.0] + u) < 1e-15
assert mdiff(rbm.quat_to_rot(q), r) < 1e-15
def test_near_pi_textbook_formula_fails():
axis = [2.0 / 7.0, 3.0 / 7.0, 6.0 / 7.0]
for d, bad in ((1e-3, 1e-10), (1e-5, 1e-7), (1e-7, 1e-3)):
angle = math.pi - d
r = rbm.so3_exp([angle * a for a in axis])
ref = rbm.quat_from_axis_angle(axis, angle)
assert qdiff(shepperd(r), ref) < 1e-15
assert qdiff(quat_textbook(r), ref) > bad
r = [[1.0, 0.0, 0.0], [0.0, -1.0, 0.0], [0.0, 0.0, -1.0]]
try:
quat_textbook(r)
except ZeroDivisionError:
pass
else:
raise AssertionError("the textbook formula should divide by zero at w = 0")
def test_matrix_with_small_error():
# A rotation with entries rounded to 7 digits still gives a quaternion
# within about 1e-7, and of length within 1e-6 of 1.
rng = random.Random(5)
for _ in range(200):
q0 = unit(rng, 4)
r = [[round(x, 7) for x in row] for row in rbm.quat_to_rot(q0)]
q = shepperd(r)
assert qdiff(q, q0) < 1e-6
assert abs(math.sqrt(sum(a * a for a in q)) - 1.0) < 1e-6
History
Shepperd, at the Charles Stark Draper Laboratory, published the method in 1978 as a short engineering note in the Journal of Guidance and Control. The note gives the four candidate squares from the trace and the diagonal and selects the largest one to avoid a division by a small number. Lynch and Park (2017) print the formula that divides by in Appendix B.3, together with the form of in terms of . Sola (2017) lists the conversions and compares the Hamilton and JPL conventions.
References
- S. W. Shepperd, Quaternion from rotation matrix, Journal of Guidance and Control 1(3), 223-224, 1978, the whole note (the four candidate squares from the trace and the diagonal, and the choice of the largest one)
- Kevin M. Lynch and Frank C. Park, Modern Robotics, Mechanics, Planning, and Control, Cambridge University Press, 2017, Appendix B, Section B.3 (unit quaternions, equations B.9 to B.12, with the formula that divides by 4 q0)
- Joan Sola, Quaternion kinematics for the error-state Kalman filter, 2017, Section 2.5 (rotation matrix and quaternion) and Section 3 (Hamilton and JPL conventions)
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag DK6ZQE Edit this page History Report an error Markdown