Algorithmadvanced
Davenport's q-method
Also called q-method.
Solves Wahba's problem as the eigenvector of the largest eigenvalue of a 4x4 symmetric matrix built from the observations.
- Solves
- Wahba's problem
- Time
- O(n) worst
- Space
- O(1) extra
- Where
- n = the number of vector pairs
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Paul B. Davenport, 1968
Davenport's q-method solves Wahba's problem exactly. It writes the attitude as a unit quaternion , shows that the Wahba loss is a constant minus the quadratic form for a symmetric matrix built from the data, and so reduces the constrained least-squares problem to one symmetric eigenproblem: the optimal quaternion is the eigenvector of the largest eigenvalue of . The method is optimal for any number of weighted vector pairs and never returns a reflection. QUEST computes the same eigenvector faster, without a full eigensolver. Quaternion superposition, which fits two point sets in structural biology and vision, uses the same matrix construction under another name; this page covers the attitude form with directions, weights and the loss.
In plain words
You have several directions measured on a vehicle and the same directions from a map, and you want the rotation that fits them best. Searching over all rotations directly is awkward, because a rotation is a constrained object. The q-method uses a trick. It describes the rotation by four numbers whose squares add up to one, and it packs all the measurements into a small table of four rows and four columns. The quality of the fit for any rotation is then a simple product of the four numbers with that table. A standard tool from linear algebra finds the four numbers that make this product largest. Those four numbers give the best rotation, and the leftover gives how bad the best fit still is.
The problem
Given unit vectors (body frame) and (reference frame) and weights for , find the rotation that minimizes . The output is the Hamilton quaternion , scalar first, of , as on the unit quaternion rotation page, together with the minimum loss.
The algorithm
Q-METHOD(b_{1..n}, r_{1..n}, a_{1..n}) ▷ returns q of R_sb = A^T and the loss- 1
B ← Σ_i a_i b_i r_i^T ; λ_0 ← Σ_i a_i - 2
σ ← tr B ; S ← B + B^T ; z ← (B_23 - B_32, B_31 - B_13, B_12 - B_21) - 3
K ← [[σ, z^T], [z, S - σ I]] ▷ symmetric 4 × 4, tr K = 0 - 4
(λ_1..λ_4, q^(1)..q^(4)) ← eigenpairs of K ▷ Jacobi sweeps - 5
j ← index of the largest λ_j - 6
q ← q^(j), negated if q_0 < 0 - 7
return q, λ_0 - λ_j
Line L1 forms the attitude profile matrix; all data enter only through and . The vector of line L2 equals . Line L4 uses the cyclic Jacobi eigenvalue algorithm, which is accurate for small symmetric matrices; any symmetric eigensolver works. The sign choice of line L6 does not change the rotation, since and give the same rotation. The attitude matrix is .
Example
Use the data of the Wahba's problem page: , , , and , which is the true tilted by degrees toward .
- Line L1: has rows , , , and .
- Line L2: , .
- Line L3:
- Line L4: the eigenvalues are , , and ; they sum to .
- Lines L5 to L7: , and the loss is .
The true attitude has , the rotation by degrees about . The estimate misses and by degree each. Its loss is half that of the TRIAD method, which matches exactly and misses by degrees.
With three exact axes, , , for , the matrix is with the all-ones matrix. Its eigenvalues are once and three times, the top eigenvector is , and the loss is .
Correctness
For unit vectors the loss is . Writing by a unit quaternion, a direct expansion gives . Every rotation has a unit quaternion, so minimizing over rotations is maximizing the Rayleigh quotient of over unit vectors, and by the spectral theorem the maximum is , reached at its eigenvectors. So the q-method returns an optimal attitude with loss , and the answer is unique when is simple. This is a theorem for unit vectors and positive weights; the correctness proof gives every step.
Proof: The eigenvector of the largest eigenvalue of K minimizes Wahba's lossfull
Setting. The data are unit vectors (body frame) and (reference frame) with weights , . The loss of a rotation is
Line L1 forms and . Lines L2 and L3 form , , and
A unit quaternion , scalar first, gives the rotation in the Hamilton convention. The algorithm returns , and the attitude is .
Assumptions.
- (D) . The code normalizes its input, so this holds for any nonzero input.
- (S) Line L4 returns an orthonormal basis of eigenvectors of with their eigenvalues. This is exact in the claim. The cyclic Jacobi method of the code converges to such a basis for every real symmetric matrix; see Jacobi eigenvalue algorithm.
Claim. Let be the largest eigenvalue of and a unit eigenvector for it. Then minimizes over , and the minimum is . If is a simple eigenvalue, the minimizer is unique. Also and .
Proof.
Step 1: the loss is linear in . By (D), , so
because and .
Step 2: the gain is a quadratic form in . With ,
- ,
- ,
- . Written out, the sum is , so the term is .
The sum is . So for every unit ,
Step 3: maximize the quadratic form. The map from the unit sphere in onto is onto (every rotation has an axis and an angle , and maps to it). So minimizing over is the same as maximizing over unit . is real and symmetric, so by the spectral theorem it has an orthonormal eigenbasis with eigenvalues . For a unit , , with equality exactly when for every with . So the eigenvector of line L6 is a maximizer, the minimum loss is (line L7), and when is simple the maximizers are , which give the same rotation. Line L6 picks the sign with ; it does not change .
Step 4: the two facts about . . And for every , so .
Remarks.
- If is not simple, every unit vector in its eigenspace is optimal, and the problem has many solutions. This happens when the data do not fix the attitude, for example when all are parallel. With two or more non-parallel pairs and exact data, is simple.
- In floating point, the Jacobi method returns eigenvalues with an absolute error of a small multiple of for unit roundoff . The eigenvector error is that amount divided by the gap . A small gap means the attitude is poorly fixed by the data, so this error is of the same size as the statistical uncertainty of the answer.
Complexity
In the real RAM model, line L1 costs multiply-adds and lines L2 and L3 cost . Line L4 works on a fixed matrix. Each Jacobi sweep costs a fixed number of operations, and the code caps the sweeps at 50, so line L4 is ; the cyclic Jacobi method converges quadratically in its last sweeps. The total is time and extra memory beyond the input. The constant is large next to that of TRIAD: a full eigensolver does many more operations than a few cross products, and QUEST removes most of them.
Properties
- Optimal (theorem). The output minimizes the Wahba loss over .
- Never a reflection. Every unit quaternion gives a proper rotation, so no sign fix is needed, unlike the SVD method.
- Any number of vectors. Works for non-parallel vectors with any positive weights; with exact data it recovers the true attitude.
- Gives the loss for free. is the minimum loss, a check of how well the data agree.
- Uniqueness test. If the two largest eigenvalues are equal, the data do not fix the attitude. The gap measures how well it is fixed.
- Traceless. , a cheap check of the construction.
Variants and improvements
- QUEST. Finds by Newton's method on the characteristic polynomial of , starting from , and the eigenvector in closed form. Same answer, less work.
- SVD method. Maximizes with the SVD of (Markley, 1988). The Kabsch algorithm is the same idea for point sets.
- Quaternion superposition. The same matrix for two point sets with weights, used in structural biology; see quaternion superposition.
- Power iteration. Since only the top eigenvector is needed, one can iterate on with , so that all eigenvalues are nonnegative; every eigenvalue of lies in . It converges at the rate of the ratio of the two largest shifted eigenvalues, which can be slow (heuristic).
When to use it
Use the q-method when you need the optimal attitude from any number of weighted directions and a robust symmetric eigensolver is available, which is the case on any modern computer. It is the reference against which faster methods are tested. When the cost of an eigensolver matters, or when the attitude is computed thousands of times a second, use QUEST. When there are exactly two directions and one is far better than the other, TRIAD is simpler.
Pitfalls
- Convention of . With and the quaternion of , . Other books use the quaternion of itself, which flips the sign of or of the vector part. Test the code on exact data.
- Unnormalized input. The identity needs unit vectors. With other lengths the optimal rotation is still the top eigenvector, but is no longer the loss.
- Degenerate data. With all parallel, is a double eigenvalue and any vector in its eigenspace is returned. The answer is then arbitrary in the rotation about that direction.
- Quaternion sign. and are the same rotation. Fix a sign, for example , before comparing with another estimate.
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
# Part of https://algorithm.tamnd.com/davenport-q-method/. The authors are listed in prov/98191D.jsonl.
"""Davenport's q-method for Wahba's problem.
Vectors are lists of 3 floats and matrices are lists of rows, as in rbm.py.
The reference vectors r_i are known in the space frame {s}; the body vectors
b_i are the same directions measured in the body frame {b}. The attitude
matrix is A = R_bs, so that b_i = A r_i for noise-free data. Wahba's loss is
L(A) = 1/2 sum_i a_i |b_i - A r_i|^2,
with unit vectors and weights a_i > 0. The method returns the Hamilton
quaternion q (scalar first) of R_sb = A^T, so A = quat_to_rot(q)^T. With
B = sum_i a_i b_i r_i^T, the loss is lambda0 - q^T K q, where
lambda0 = sum_i a_i and K is Davenport's symmetric 4x4 matrix. The best q is
a unit eigenvector of K for its largest eigenvalue.
"""
import math
import rbm
JACOBI_TOL = 1e-15 # stop when the off-diagonal norm is below this times |K|
JACOBI_MAX_SWEEPS = 50
def _unit(v):
n = rbm.norm(v)
if n == 0.0:
raise ValueError("zero vector")
return [x / n for x in v]
def attitude_profile(bs, rs, weights):
"""Return B = sum a_i b_i r_i^T and lambda0 = sum a_i, after making all vectors unit."""
if not (len(bs) == len(rs) == len(weights)) or len(bs) == 0:
raise ValueError("need the same positive number of body vectors, reference vectors and weights")
bmat = rbm.zeros(3, 3)
for a, b, r in zip(weights, bs, rs):
if a <= 0.0:
raise ValueError("weights must be positive")
bu, ru = _unit(b), _unit(r)
for i in range(3):
for j in range(3):
bmat[i][j] += a * bu[i] * ru[j]
return bmat, float(sum(weights))
def davenport_matrix(bmat):
"""Return K = [[sigma, z^T], [z, S - sigma I]] for the attitude profile matrix B."""
sigma = bmat[0][0] + bmat[1][1] + bmat[2][2] # @line L2
s = [[bmat[i][j] + bmat[j][i] for j in range(3)] for i in range(3)] # @line L2
# z = sum a_i b_i x r_i, read off the skew part of B: z_k = eps_kij B_ij
z = [bmat[1][2] - bmat[2][1], bmat[2][0] - bmat[0][2], bmat[0][1] - bmat[1][0]] # @line L2
k = [[sigma, z[0], z[1], z[2]]] # @line L3
for i in range(3):
k.append([z[i]] + [s[i][j] - (sigma if i == j else 0.0) for j in range(3)])
return k
def jacobi_eigen(a, tol=JACOBI_TOL, max_sweeps=JACOBI_MAX_SWEEPS):
"""Return (eigenvalues, V) of a symmetric matrix by the cyclic Jacobi method.
The columns of V are orthonormal eigenvectors: a V = V diag(eigenvalues).
"""
n = len(a)
m = [list(map(float, row)) for row in a]
v = rbm.eye(n)
scale = math.sqrt(sum(x * x for row in m for x in row)) or 1.0
for _ in range(max_sweeps):
off = math.sqrt(sum(m[i][j] ** 2 for i in range(n) for j in range(n) if i != j))
if off <= tol * scale:
break
for p in range(n - 1):
for q in range(p + 1, n):
if m[p][q] == 0.0:
continue
theta = (m[q][q] - m[p][p]) / (2.0 * m[p][q])
t = (1.0 if theta >= 0.0 else -1.0) / (abs(theta) + math.sqrt(theta * theta + 1.0))
c = 1.0 / math.sqrt(t * t + 1.0)
s = t * c
for k in range(n): # columns p and q of m
mkp, mkq = m[k][p], m[k][q]
m[k][p] = c * mkp - s * mkq
m[k][q] = s * mkp + c * mkq
for k in range(n): # rows p and q of m
mpk, mqk = m[p][k], m[q][k]
m[p][k] = c * mpk - s * mqk
m[q][k] = s * mpk + c * mqk
for k in range(n):
vkp, vkq = v[k][p], v[k][q]
v[k][p] = c * vkp - s * vkq
v[k][q] = s * vkp + c * vkq
else:
raise ArithmeticError("Jacobi did not converge")
return [m[i][i] for i in range(n)], v
def q_method(bs, rs, weights):
"""Return (q, loss): the optimal Hamilton quaternion of R_sb and the minimal Wahba loss."""
bmat, lam0 = attitude_profile(bs, rs, weights) # @line L1
k = davenport_matrix(bmat) # @line L3
vals, vecs = jacobi_eigen(k) # @line L4
j = max(range(4), key=lambda i: vals[i]) # @line L5
q = [vecs[i][j] for i in range(4)] # @line L6
n = rbm.norm(q)
q = [x / n for x in q]
if q[0] < 0.0: # q and -q give the same rotation # @line L6
q = [-x for x in q]
return q, max(0.0, lam0 - vals[j]) # @line L7
def attitude_matrix(q):
"""Return A = R_bs for the Hamilton quaternion q of R_sb."""
return rbm.transpose(rbm.quat_to_rot(q))
def wahba_loss(amat, bs, rs, weights):
"""Return L(A) = 1/2 sum a_i |b_i - A r_i|^2 with unit vectors."""
total = 0.0
for a, b, r in zip(weights, bs, rs):
d = rbm.sub(_unit(b), rbm.matvec(amat, _unit(r)))
total += 0.5 * a * rbm.dot(d, d)
return total
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_davenport_q_method.py 167 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/davenport-q-method/. The authors are listed in prov/98191D.jsonl.
import math
import random
import pytest
import rbm
from davenport_q_method import (
attitude_matrix,
attitude_profile,
davenport_matrix,
jacobi_eigen,
q_method,
wahba_loss,
)
def random_unit(rng):
while True:
v = [rng.gauss(0.0, 1.0) for _ in range(3)]
n = rbm.norm(v)
if n > 1e-3:
return [x / n for x in v]
def random_quat(rng):
q = [rng.gauss(0.0, 1.0) for _ in range(4)]
n = rbm.norm(q)
q = [x / n for x in q]
return q if q[0] >= 0.0 else [-x for x in q]
def max_diff(a, b):
return max(abs(a[i][j] - b[i][j]) for i in range(len(a)) for j in range(len(a[0])))
def same_rotation(q, p):
"""Return the distance between q and p up to sign."""
return min(rbm.norm(rbm.sub(q, p)), rbm.norm(rbm.add(q, p)))
def make_data(rng, q_true, n, noise):
a_true = attitude_matrix(q_true)
rs = [random_unit(rng) for _ in range(n)]
bs = []
for r in rs:
b = rbm.matvec(rbm.mul(rbm.so3_exp([rng.gauss(0.0, noise) for _ in range(3)]), a_true), r)
bs.append(b)
weights = [rng.uniform(0.2, 1.0) for _ in range(n)]
return bs, rs, weights
def test_check_rotation():
# R_sb is 120 degrees about (1, 1, 1) / sqrt(3): q = (1/2, 1/2, 1/2, 1/2).
r_sb = [[0.0, 0.0, 1.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]
rs = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
bs = [rbm.matvec(rbm.transpose(r_sb), r) for r in rs]
q, loss = q_method(bs, rs, [1.0, 1.0, 1.0])
assert max(abs(x - 0.5) for x in q) < 1e-12
assert loss < 1e-12
def test_quarter_turn_about_z():
r_sb = rbm.rot_z(math.pi / 2.0)
rs = [[1.0, 0.0, 0.0], [0.0, 0.0, 1.0]]
bs = [rbm.matvec(rbm.transpose(r_sb), r) for r in rs]
q, _ = q_method(bs, rs, [1.0, 1.0])
h = math.sqrt(0.5)
assert rbm.norm(rbm.sub(q, [h, 0.0, 0.0, h])) < 1e-12
def test_quaternion_quadratic_form_is_trace():
# q^T K q = tr(A B^T) for every unit q, with A = attitude_matrix(q).
rng = random.Random(1)
for _ in range(50):
bs, rs, w = make_data(rng, random_quat(rng), 4, 0.3)
bmat, _ = attitude_profile(bs, rs, w)
k = davenport_matrix(bmat)
q = random_quat(rng)
qkq = rbm.dot(q, rbm.matvec(k, q))
a = attitude_matrix(q)
tr = sum(a[i][j] * bmat[i][j] for i in range(3) for j in range(3))
assert abs(qkq - tr) < 1e-12
assert abs(k[0][0] + k[1][1] + k[2][2] + k[3][3]) < 1e-12
def test_noise_free_recovery():
rng = random.Random(2)
for _ in range(100):
q_true = random_quat(rng)
bs, rs, w = make_data(rng, q_true, rng.randint(2, 6), 0.0)
q, loss = q_method(bs, rs, w)
assert same_rotation(q, q_true) < 1e-10
assert loss < 1e-12
def test_rotation_by_pi():
rng = random.Random(3)
for _ in range(20):
axis = random_unit(rng)
q_true = [0.0] + axis
bs, rs, w = make_data(rng, q_true, 3, 0.0)
q, _ = q_method(bs, rs, w)
assert same_rotation(q, q_true) < 1e-10
def test_eigen_residual_and_loss_formula():
rng = random.Random(4)
for _ in range(50):
bs, rs, w = make_data(rng, random_quat(rng), 5, 0.1)
bmat, lam0 = attitude_profile(bs, rs, w)
k = davenport_matrix(bmat)
vals, vecs = jacobi_eigen(k)
for j in range(4):
v = [vecs[i][j] for i in range(4)]
res = rbm.sub(rbm.matvec(k, v), rbm.scale(v, vals[j]))
assert rbm.norm(res) < 1e-12
vt_v = rbm.mul(rbm.transpose(vecs), vecs)
assert max_diff(vt_v, rbm.eye(4)) < 1e-13
q, loss = q_method(bs, rs, w)
assert abs(rbm.norm(q) - 1.0) < 1e-14 and q[0] >= 0.0
assert abs(loss - wahba_loss(attitude_matrix(q), bs, rs, w)) < 1e-12
assert abs(loss - (lam0 - max(vals))) < 1e-12
def descend(a, bmat, steps=300):
for _ in range(steps):
m = rbm.mul(rbm.transpose(a), bmat)
g = [m[2][1] - m[1][2], m[0][2] - m[2][0], m[1][0] - m[0][1]]
a = rbm.mul(a, rbm.so3_exp(rbm.scale(g, 0.2)))
return a
def test_optimal_against_multistart_descent():
rng = random.Random(5)
for _ in range(10):
bs, rs, w = make_data(rng, random_quat(rng), 3, 0.4)
q, loss = q_method(bs, rs, w)
bmat, _ = attitude_profile(bs, rs, w)
for _ in range(4):
a0 = attitude_matrix(random_quat(rng))
assert wahba_loss(descend(a0, bmat), bs, rs, w) >= loss - 1e-12
# A random rotation never beats the q-method.
for _ in range(20):
assert wahba_loss(attitude_matrix(random_quat(rng)), bs, rs, w) >= loss - 1e-12
def test_bad_input():
with pytest.raises(ValueError):
q_method([[1.0, 0.0, 0.0]], [[1.0, 0.0, 0.0]], [0.0])
with pytest.raises(ValueError):
q_method([[1.0, 0.0, 0.0]], [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]], [1.0])
with pytest.raises(ValueError):
q_method([[0.0, 0.0, 0.0]], [[1.0, 0.0, 0.0]], [1.0])
def test_single_vector_gives_degenerate_maximum():
# One pair fixes the attitude only up to a rotation about b: lambda_max is double.
vals, _ = jacobi_eigen(davenport_matrix(attitude_profile([[0.0, 0.0, 1.0]], [[1.0, 0.0, 0.0]], [1.0])[0]))
vals.sort()
assert abs(vals[3] - vals[2]) < 1e-12
q, loss = q_method([[0.0, 0.0, 1.0]], [[1.0, 0.0, 0.0]], [1.0])
assert loss < 1e-12
a = attitude_matrix(q)
assert rbm.norm(rbm.sub(rbm.matvec(a, [1.0, 0.0, 0.0]), [0.0, 0.0, 1.0])) < 1e-12
History
Wahba posed the problem in 1965. The eigenvector solution is credited to Paul Davenport, and the method carries his name. Shuster and Oh (1981) designed QUEST to get the same answer without a full eigensolver. Markley and Mortari (2000) surveyed the q-method and its faster relatives. The same quaternion matrix was found independently for point-set registration, which is why it appears as quaternion superposition in other fields.
References
- F. Landis Markley and John L. Crassidis, Fundamentals of Spacecraft Attitude Determination and Control, Springer, 2014, Chapter 5 (static attitude determination), the sections on Wahba's problem and Davenport's q-method
- F. Landis Markley and Daniele Mortari, Quaternion attitude estimation using vector observations, Journal of the Astronautical Sciences 48(2-3), 2000, pages 359 to 380, the derivation of the q-method and its comparison with QUEST, the SVD method and other solutions
- Paul B. Davenport, A vector approach to the algebra of rotations with applications, NASA Technical Note D-4696, 1968, the report as a whole, which develops the quaternion algebra of rotations that the q-method uses
- Grace Wahba, A least squares estimate of satellite attitude, SIAM Review 7(3), 1965, page 409, the problem that the q-method solves
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.
| 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 98191D Edit this page History Report an error Markdown