Algorithmadvanced
QUEST algorithm
Also called quaternion estimator.
Shuster's fast solution of Wahba's problem that finds the largest eigenvalue of Davenport's matrix by Newton iteration on its characteristic polynomial.
- Solves
- Wahba's problem
- Time
- O(n + k) worst
- Space
- O(1) extra
- Where
- k = the number of Newton steps; n = the number of vector pairs
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Malcolm D. Shuster, S. D. Oh, 1981
QUEST, the quaternion estimator, computes the optimal attitude of Wahba's problem, the same answer as Davenport's q-method, but without a general eigensolver. It finds the largest eigenvalue of Davenport's matrix by Newton's method on the characteristic polynomial, starting from the sum of the weights, which is already very close. It then reads the eigenvector off a closed-form column of the adjugate of . When the attitude is near a rotation by , that column vanishes, and QUEST rotates the reference frame by about a coordinate axis and solves again. Quaternion superposition in other fields solves the same eigenproblem; the Newton start at the sum of the weights is what makes QUEST fast for attitude data.
In plain words
The q-method finds the best rotation by asking a general linear algebra tool for the largest special number of a four by four table, and its matching direction. That tool is slow for a small flight computer. QUEST notices two things. First, when the measurements fit well, that largest number is very close to the sum of the sensor weights, so a few steps of a classic root-finding method from that start finish the job. Second, once the number is known, the matching direction has a ready-made formula, with no search. The formula breaks down only for rotations close to a half turn. For those, QUEST turns the map frame by a half turn first, solves the easy case, and turns the answer back.
The problem
As for the q-method: given unit vectors and with weights , find the rotation that minimizes , and return the Hamilton quaternion of and the minimum loss. With , , and , the answer is the top eigenvector of , and the loss is with .
The algorithm
Let and . The characteristic polynomial of is
with , , and . Let be the rotation by about the axis , and .
QUEST(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
compute σ, S, z, κ, Δ from B, then the coefficients of ψ - 3
λ ← λ_0 - 4
repeat λ ← λ - ψ(λ) / ψ'(λ) until the step is ≤ tol · λ_0 - 5
for k in (none, x, y, z) do B_k ← B P_k ; recompute σ, S, z, κ, Δ from B_k - 6
α ← λ² - σ² + κ ; β ← λ - σ ; γ ← (λ + σ) α - Δ ; x ← (α I + β S + S²) z - 7
if |(γ, x)| ≥ ½ |ψ'(λ)| then leave the loop - 8
q ← (0, e_k) ⊗ (γ, x) / |(γ, x)|, negated if q_0 < 0 ▷ (0, e_none) means 1 - 9
return q, λ_0 - λ
Line L4 is Newton's method; the code uses and at most 50 steps. In exact arithmetic every step from is positive, so the code also stops, without moving, at the first step that is not positive: in floating point the last iterates can swing by one unit of roundoff around the root. Line L6 is the first column of , which at equals , so its norm is . Line L7 accepts a frame in which . Such a frame exists, because turning the reference vectors by about moves into the scalar place, and one of the four components of a unit quaternion has absolute value at least . The polynomial and are the same in every frame. If no frame passes the test because of rounding, the code keeps the frame with the longest column.
Example
Use the noisy data of the q-method page: , , unit weights, and .
- Lines L1 and L2: , , and , with .
- Lines L3 and L4: the Newton iterates are , , , . Three steps reach the last digit, because is only above .
- Line L6 in the unrotated frame: and . The norm is , so line L7 accepts the frame.
- Line L8: , the same as the q-method, and line L9 returns the loss . The ratio is , as the formula says.
For a case that needs a rotated frame, let the true be the rotation by about , with the same two reference vectors and exact data. Its quaternion is , so and the unrotated column is zero up to rounding. The frames and also have a zero scalar part, since . The frame has , passes the test, and line L8 returns .
Correctness
Three facts make QUEST correct; each is a theorem when is a simple eigenvalue and the arithmetic is exact. First, is the characteristic polynomial of , and is the first column of , by the Cayley-Hamilton theorem for and a Schur complement. Second, is symmetric, so has only real roots and is increasing and convex to the right of ; since , Newton's method from decreases monotonically to . Third, the adjugate at a simple eigenvalue is , so the column is a multiple of , and the frame rule keeps the multiple away from zero. The q-method proof then shows that is optimal. The full argument is in the correctness proof.
Proof: QUEST finds the largest eigenvalue by a monotone Newton iteration and the optimal quaternion by an adjugate columnfull
Setting. The notation is that of the q-method: unit vectors , weights , , , , , , and
The proof of the q-method shows that the optimal attitude is given by a unit eigenvector of for its largest eigenvalue , and that the minimum loss is . Let and , so that . For a real put and
with , , and .
Assumptions.
- (D) and .
- (U) is a simple eigenvalue of . This holds when the data fix the attitude; see the remarks of the q-method proof.
- (X) Arithmetic is exact. The remarks discuss rounding.
Claim.
- , and is the first column of , for every real .
- Newton's method on from (lines L2 to L4) gives a nonincreasing sequence that converges to .
- At , . So when , (line L8), and .
- At least one of the four frames of line L5 has , and the quaternion of line L8 in that frame gives the optimal attitude.
Proof.
Claim 1. Write in blocks: , , . First, , because and . Next, by the Cayley-Hamilton theorem for , . Then
Here , so the last two terms are , and . So , which means . Now compute . The lower block is . The top entry is
Expanding, with , and :
The coefficient of is . The coefficient of is . The constant is . So . When , the Schur complement gives . Both sides are polynomials in that agree at all but at most three points, so for all . Finally, . When is invertible this gives , and again both sides are polynomials in , so the identity holds for every .
Claim 2. is real and symmetric, so has four real roots . By Rolle's theorem the roots of and of are real and lie in . The leading coefficients of are positive, so for all three are positive: is increasing and convex on . The proof of the q-method gives . If , then and the first step is zero. Otherwise, let . The Newton step satisfies , since and are positive. By convexity, the tangent line at lies below on and is negative at , so its root is at least . So the iterates decrease and stay at or above . They converge to some , and the step must be at the limit, so and . Under (U), and the convergence is quadratic.
Claim 3. For not an eigenvalue, in an orthonormal eigenbasis. This is a polynomial identity, so it holds at , where every term but has the factor . So with , because . By Claim 1, the first column is . Its norm is , since .
Claim 4. For , let be the rotation by about , the diagonal matrix with in place and in the other two places. Line L5 replaces the reference vectors by . Since , , so the new problem has the attitude and the profile . Its loss is the same function of the data, so its is the same and the Newton result is reused. In terms of , , and the quaternion of is , so up to sign. The scalar part of is . So the four frames (none, , , ) have . These four numbers have squares that sum to , so the largest is at least . By Claim 3, line L7 accepts a frame exactly when its , so it accepts one, and in that frame because under (U). Line L8 normalizes to and returns . Both signs give the same attitude, which is optimal by the q-method proof.
Remarks.
- With rounding, is a few units of roundoff away from , and is computed at that . Claim 3 shows why a frame with near is bad: the column is then the difference of large terms that should cancel, and its direction carries a relative error of order . The rule bounds that factor by .
- If is a double root, , Newton converges only linearly, and the adjugate is the zero matrix, so no frame works: every column is zero up to rounding, and its direction means nothing. The code raises an error only when all four columns are exactly zero. The problem then has a whole set of solutions, and the q-method with a full eigensolver is the right tool.
Complexity
In the real RAM model, line L1 costs . Lines L2 to L8 work on fixed and objects: each Newton step evaluates a quartic and its derivative, and each frame costs a few products. So the time is for Newton steps, and the extra memory is . Measured over 1000 random problems of 2 to 6 vectors for each noise level, counting the last step that triggers the stop: at a noise of rad, at rad, and at rad. Newton converges quadratically at a simple root, so grows like the logarithm of the number of correct digits wanted.
Properties
- Optimal (theorem). Same answer as the q-method, up to rounding.
- Monotone Newton (theorem). The iterates never go below and never increase, so no safeguard is needed.
- Few steps (measurement). With good data, is the small minimum loss, so the start is already close; the example needed 3 steps for full precision.
- Robust near . The sequential rotations keep in the frame used, which bounds the loss of accuracy in line L8 by a factor of about 2.
- Gives the loss. is the minimum loss.
Variants and improvements
- No Newton step (heuristic). Using in line L6 skips line L4. The error this causes is small when the data fit well, since then is small, but it is not optimal.
- Covariance. With weights equal to inverse sensor variances, Shuster and Oh (1981) also give the covariance of the attitude error from the same quantities.
- Other fast methods. FOAM and ESOQ compute the same optimal attitude from other closed forms; Markley and Mortari (2000) compare their speed and robustness with QUEST.
- Recursive use. In attitude estimation, QUEST can run at each step on new measurements, or its output can serve as the measurement of a filter.
When to use it
Use QUEST when the optimal attitude from several vector observations must be computed fast and often, as on a star tracker or in a loop that runs at a high rate. Use the q-method with a full eigensolver when the data may be degenerate or when the second eigenvalue is also wanted, and TRIAD when there are exactly two vectors and optimality does not matter.
Pitfalls
- Rotations near . Without the sequential rotations, the column of line L6 is the difference of large nearly equal terms, and the computed quaternion can point anywhere. The test of line L7 must use ; a fixed threshold on the norm depends on the scale of the weights.
- Double eigenvalue. If is not simple, Newton converges slowly and the adjugate is zero in every frame. The data do not fix the attitude, and QUEST cannot tell which solution to return.
- Stopping rule. Stop on the size of the Newton step relative to , not on , and also stop on a step that is not positive. Near a root, is computed with cancellation. A first version of the code used only ; with a noise of rad it swung forever between two neighbors of the root and hit the step limit.
- Conventions. QUEST returns the quaternion of with the conventions of the q-method page; a sign error in gives the inverse rotation.
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/quest-algorithm/. The authors are listed in prov/Z02XZG.jsonl.
"""QUEST, the quaternion estimator of Shuster and Oh (1981), for Wahba's problem.
Vectors are lists of 3 floats and matrices are lists of rows, as in rbm.py.
The conventions are those of the q-method page: b_i = A r_i with A = R_bs,
B = sum a_i b_i r_i^T, sigma = tr B, S = B + B^T, z = sum a_i b_i x r_i,
and K = [[sigma, z^T], [z, S - sigma I]]. The result is the Hamilton
quaternion q (scalar first) of R_sb = A^T.
QUEST finds lambda_max of K as the largest root of the characteristic
polynomial
psi(l) = l^4 - (a + b) l^2 - c l + (a b + c sigma - d),
a = sigma^2 - kappa, b = sigma^2 + z^T z, c = Delta + z^T S z,
d = z^T S^2 z, kappa = tr adj S, Delta = det S,
by Newton's method from lambda0 = sum a_i. The eigenvector is a column of
adj(l I - K), which is (gamma, x) with
alpha = l^2 - sigma^2 + kappa, beta = l - sigma,
gamma = (l + sigma) alpha - Delta, x = (alpha I + beta S + S^2) z.
That column is psi'(l) q0 q, so it vanishes when q0 = 0 (a rotation by pi).
The method of sequential rotations then rotates the reference vectors by
pi about a coordinate axis and solves again.
"""
import rbm
NEWTON_TOL = 1e-15 # stop when the Newton step is below this times lambda0
NEWTON_MAX_ITER = 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 profile_terms(bmat):
"""Return sigma, S, z, kappa, Delta for the attitude profile matrix B."""
sigma = bmat[0][0] + bmat[1][1] + bmat[2][2]
s = [[bmat[i][j] + bmat[j][i] for j in range(3)] for i in range(3)]
z = [bmat[1][2] - bmat[2][1], bmat[2][0] - bmat[0][2], bmat[0][1] - bmat[1][0]]
# kappa = trace of the adjugate = sum of the principal 2x2 minors
kappa = (s[1][1] * s[2][2] - s[1][2] * s[2][1]) + (s[0][0] * s[2][2] - s[0][2] * s[2][0]) + (
s[0][0] * s[1][1] - s[0][1] * s[1][0]
)
delta = rbm.det(s)
return sigma, s, z, kappa, delta
def char_poly(bmat):
"""Return (p2, p1, p0) with psi(l) = l^4 + p2 l^2 + p1 l + p0 = det(l I - K)."""
sigma, s, z, kappa, delta = profile_terms(bmat)
sz = rbm.matvec(s, z)
a = sigma * sigma - kappa
b = sigma * sigma + rbm.dot(z, z)
c = delta + rbm.dot(z, sz)
d = rbm.dot(sz, sz)
return -(a + b), -c, a * b + c * sigma - d
def newton_lambda(bmat, lam0, tol=NEWTON_TOL, max_iter=NEWTON_MAX_ITER):
"""Return (lambda_max, number of Newton steps), starting from lambda0."""
p2, p1, p0 = char_poly(bmat) # @line L2
lam = lam0 # @line L3
for it in range(1, max_iter + 1):
psi = ((lam * lam + p2) * lam + p1) * lam + p0 # @line L4
dpsi = (4.0 * lam * lam + 2.0 * p2) * lam + p1 # @line L4
if dpsi == 0.0:
return lam, it
step = psi / dpsi # @line L4
# From above, every exact Newton step is positive. A step that is not
# positive, or tiny, means rounding has taken over: stop there.
if step <= tol * lam0:
if step > 0.0:
lam -= step
return lam, it
lam -= step # @line L4
raise ArithmeticError("Newton did not converge")
def adjugate_column(bmat, lam):
"""Return (gamma, x) = the first column of adj(lam I - K), and psi'(lam)."""
sigma, s, z, kappa, delta = profile_terms(bmat)
alpha = lam * lam - sigma * sigma + kappa # @line L6
beta = lam - sigma # @line L6
gamma = (lam + sigma) * alpha - delta # @line L6
sz = rbm.matvec(s, z)
ssz = rbm.matvec(s, sz)
x = [alpha * z[i] + beta * sz[i] + ssz[i] for i in range(3)] # @line L6
p2, p1, _ = char_poly(bmat)
dpsi = (4.0 * lam * lam + 2.0 * p2) * lam + p1
return [gamma] + x, dpsi
def _rotated_profile(bmat, k):
"""Return B P_k, the profile after the reference vectors turn by pi about axis k."""
if k is None:
return bmat
sign = [1.0 if j == k else -1.0 for j in range(3)]
return [[bmat[i][j] * sign[j] for j in range(3)] for i in range(3)]
def quest(bs, rs, weights, tol=NEWTON_TOL, max_iter=NEWTON_MAX_ITER):
"""Return (q, loss, info) for Wahba's problem.
q is the Hamilton quaternion of R_sb with q0 >= 0, loss = lambda0 - lambda_max,
and info holds the number of Newton steps and the frame used (None, 0, 1 or 2).
"""
bmat, lam0 = attitude_profile(bs, rs, weights) # @line L1
lam, iters = newton_lambda(bmat, lam0, tol, max_iter) # @line L4
best = None
for k in (None, 0, 1, 2): # @line L5
col, dpsi = adjugate_column(_rotated_profile(bmat, k), lam) # @line L6
n = rbm.norm(col)
if best is None or n > best[0]:
best = (n, k, col)
if n >= 0.5 * abs(dpsi): # |q0| >= 1/2 in this frame # @line L7
break
n, k, col = best
if n == 0.0:
raise ArithmeticError("no frame gave a nonzero eigenvector; lambda_max is not simple")
qk = [x / n for x in col] # @line L8
if k is None:
q = qk
else:
# R_sb = P_k R'_sb, and the quaternion of P_k is (0, e_k).
p = [0.0, 0.0, 0.0, 0.0]
p[k + 1] = 1.0
q = rbm.quat_mul(p, qk) # @line L8
if q[0] < 0.0:
q = [-x for x in q]
return q, max(0.0, lam0 - lam), {"iterations": iters, "frame": k} # @line L9
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_quest_algorithm.py 218 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/quest-algorithm/. The authors are listed in prov/Z02XZG.jsonl.
import math
import random
import pytest
import rbm
from quest_algorithm import (
adjugate_column,
attitude_matrix,
attitude_profile,
char_poly,
newton_lambda,
quest,
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 same_rotation(q, p):
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 = [rbm.matvec(rbm.mul(rbm.so3_exp([rng.gauss(0.0, noise) for _ in range(3)]), a_true), r) for r in rs]
weights = [rng.uniform(0.2, 1.0) for _ in range(n)]
return bs, rs, weights
def davenport_k(bmat):
sigma = bmat[0][0] + bmat[1][1] + bmat[2][2]
z = [bmat[1][2] - bmat[2][1], bmat[2][0] - bmat[0][2], bmat[0][1] - bmat[1][0]]
k = [[sigma] + z]
for i in range(3):
k.append([z[i]] + [bmat[i][j] + bmat[j][i] - (sigma if i == j else 0.0) for j in range(3)])
return k
def power_top(k, lam0, steps=1000):
"""Top eigenvector of K by power iteration on K + lam0 I (all eigenvalues >= 0)."""
m = [[k[i][j] + (lam0 if i == j else 0.0) for j in range(4)] for i in range(4)]
v = [1.0, 0.3, -0.2, 0.1]
for _ in range(steps):
v = rbm.matvec(m, v)
n = rbm.norm(v)
v = [x / n for x in v]
return v
def test_check_rotation():
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, info = quest(bs, rs, [1.0, 1.0, 1.0])
assert max(abs(x - 0.5) for x in q) < 1e-12
assert loss < 1e-12
assert info["frame"] is None
def test_characteristic_polynomial_matches_determinant():
rng = random.Random(1)
for _ in range(30):
bs, rs, w = make_data(rng, random_quat(rng), 4, 0.5)
bmat, _ = attitude_profile(bs, rs, w)
k = davenport_k(bmat)
p2, p1, p0 = char_poly(bmat)
for lam in (-1.3, 0.0, 0.7, 2.1):
psi = lam ** 4 + p2 * lam * lam + p1 * lam + p0
want = rbm.det([[(lam if i == j else 0.0) - k[i][j] for j in range(4)] for i in range(4)])
assert abs(psi - want) < 1e-11
def test_against_power_iteration():
rng = random.Random(2)
for _ in range(20):
bs, rs, w = make_data(rng, random_quat(rng), 3, 0.2)
bmat, lam0 = attitude_profile(bs, rs, w)
k = davenport_k(bmat)
v = power_top(k, lam0)
q, loss, _ = quest(bs, rs, w)
assert same_rotation(q, v) < 1e-8
res = rbm.sub(rbm.matvec(k, q), rbm.scale(q, lam0 - loss))
assert rbm.norm(res) < 1e-10
assert abs(loss - wahba_loss(attitude_matrix(q), bs, rs, w)) < 1e-12
def test_rayleigh_quotient_never_exceeds_lambda_max():
rng = random.Random(3)
bs, rs, w = make_data(rng, random_quat(rng), 4, 0.3)
bmat, lam0 = attitude_profile(bs, rs, w)
k = davenport_k(bmat)
_, loss, _ = quest(bs, rs, w)
lam = lam0 - loss
for _ in range(500):
v = random_quat(rng)
assert rbm.dot(v, rbm.matvec(k, v)) <= lam + 1e-12
def test_noise_free_recovery_and_one_newton_step():
rng = random.Random(4)
for _ in range(100):
q_true = random_quat(rng)
bs, rs, w = make_data(rng, q_true, 3, 0.0)
q, loss, info = quest(bs, rs, w)
assert same_rotation(q, q_true) < 1e-9
assert loss < 1e-12
# lambda0 is already the root, so the first step is tiny.
assert info["iterations"] <= 2
def test_newton_iterations_with_noise():
# Measurement: from lambda0, Newton needs few steps at sensor-level noise.
rng = random.Random(5)
worst = 0
for _ in range(100):
bs, rs, w = make_data(rng, random_quat(rng), 3, 0.01)
_, _, info = quest(bs, rs, w)
worst = max(worst, info["iterations"])
assert worst <= 4
def test_newton_stops_at_the_rounding_floor():
# With large noise the gap below lambda_max is small, psi' is small, and
# the last Newton steps swing by one unit of roundoff. The stopping rule
# must end there instead of running to the step limit.
rng = random.Random(11)
worst = 0
for noise in (0.05, 0.2, 0.5):
for _ in range(150):
n = rng.randint(2, 6)
bs, rs, w = make_data(rng, random_quat(rng), n, noise)
q, loss, info = quest(bs, rs, w)
worst = max(worst, info["iterations"])
assert abs(rbm.norm(q) - 1.0) < 1e-12
assert wahba_loss(attitude_matrix(q), bs, rs, w) == pytest.approx(loss, abs=1e-10)
assert worst <= 10
def test_newton_monotone_from_above():
# All roots of psi are real, so Newton from lambda0 >= lambda_max decreases
# monotonically to lambda_max.
rng = random.Random(6)
bs, rs, w = make_data(rng, random_quat(rng), 3, 0.8)
bmat, lam0 = attitude_profile(bs, rs, w)
p2, p1, p0 = char_poly(bmat)
lam, prev = lam0, lam0 + 1.0
for _ in range(30):
psi = lam ** 4 + p2 * lam * lam + p1 * lam + p0
dpsi = 4.0 * lam ** 3 + 2.0 * p2 * lam + p1
if psi == 0.0:
break
assert lam <= prev + 1e-14 * lam0
prev, lam = lam, lam - psi / dpsi
lam_n, _ = newton_lambda(bmat, lam0)
assert abs(lam - lam_n) < 1e-12
def test_rotation_by_pi_uses_another_frame():
rng = random.Random(7)
for _ in range(30):
q_true = [0.0] + random_unit(rng)
bs, rs, w = make_data(rng, q_true, 3, 0.0)
bmat, lam0 = attitude_profile(bs, rs, w)
col, dpsi = adjugate_column(bmat, lam0)
assert rbm.norm(col) < 1e-9 * abs(dpsi)
q, _, info = quest(bs, rs, w)
assert info["frame"] is not None
assert same_rotation(q, q_true) < 1e-9
def test_near_pi_with_noise():
rng = random.Random(8)
for _ in range(30):
axis = random_unit(rng)
q_true = rbm.quat_from_axis_angle(axis, math.pi - 1e-7)
bs, rs, w = make_data(rng, q_true, 4, 0.001)
q, loss, _ = quest(bs, rs, w)
bmat, lam0 = attitude_profile(bs, rs, w)
v = power_top(davenport_k(bmat), lam0)
assert same_rotation(q, v) < 1e-8
assert abs(rbm.norm(q) - 1.0) < 1e-14
def test_adjugate_column_norm_is_dpsi_times_q0():
rng = random.Random(9)
for _ in range(30):
q_true = random_quat(rng)
bs, rs, w = make_data(rng, q_true, 3, 0.05)
bmat, lam0 = attitude_profile(bs, rs, w)
lam, _ = newton_lambda(bmat, lam0)
col, dpsi = adjugate_column(bmat, lam)
q, _, _ = quest(bs, rs, w)
assert abs(rbm.norm(col) - abs(dpsi) * abs(q[0])) < 1e-9
def test_bad_input():
with pytest.raises(ValueError):
quest([[1.0, 0.0, 0.0]], [[1.0, 0.0, 0.0]], [-1.0])
with pytest.raises(ValueError):
quest([], [], [])
History
Shuster and Oh (1981) introduced QUEST in a paper on three-axis attitude determination that also analyzed the TRIAD method. Their goal was the optimal answer of Wahba's problem at a cost close to that of TRIAD, by replacing the general eigensolver of Davenport's q-method with a Newton iteration and a closed-form eigenvector. The method of sequential rotations, in the same paper, handles the attitudes near a rotation by . Markley and Mortari (2000) later compared QUEST with the other fast solutions of Wahba's problem.
References
- M. D. Shuster and S. D. Oh, Three-axis attitude determination from vector observations, Journal of Guidance and Control 4(1), 1981, pages 70 to 77, the QUEST algorithm: the characteristic equation, the Newton iteration from the sum of the weights, the closed-form eigenvector and the method of sequential rotations
- 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 sections on QUEST and on the speed and robustness of the solutions of Wahba's problem
- F. Landis Markley and John L. Crassidis, Fundamentals of Spacecraft Attitude Determination and Control, Springer, 2014, Chapter 5 (static attitude determination), the section on QUEST
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 Z02XZG Edit this page History Report an error Markdown