Algorithm Search⌘K

Algorithmcore

TRIAD method

Also called TRIAD algorithm.

Builds an attitude from exactly two vector observations by forming an orthonormal triad in each frame.

Time
O(1) worst
Space
O(1) extra
Where
n = the number of vector pairs, which is 2 for TRIAD
Properties
deterministicnot exactofflineiterative
Origin
Harold D. Black, 1964

The TRIAD method computes the attitude of a body from two measured directions, such as the Sun and the Earth's magnetic field, whose directions in a reference frame are known. It builds an orthonormal frame, a triad, from the two measured vectors and the same kind of frame from the two reference vectors, and returns the rotation that carries one frame onto the other. It costs a few cross products. The result matches the first pair exactly and uses the second pair only to fix the rotation about the first, so with noise it is not the least-squares solution of Wahba's problem; Davenport's q-method and QUEST are. The Kabsch algorithm solves the same fitting problem for many points by an SVD and is optimal; TRIAD is the cheap exact-for-two-vectors cousin.

In plain words

Imagine you can see the Sun and also feel which way a compass needle points. Each gives you one direction. One direction alone leaves you free to spin about it. The second direction stops that spin. TRIAD takes the first direction as the main axis, uses the second only to decide which way is "up" around that axis, and adds a third axis at right angles to both. It does the same with the map directions. The rotation that lines up the two sets of axes is your attitude. The first direction is matched perfectly and all the noise of both sensors goes into the second one, so you should put the more trusted sensor first.

The problem

Given body vectors b1,b2b_1, b_2 and reference vectors r1,r2r_1, r_2 in R3\mathbb{R}^3, nonzero and not parallel within each pair, find a rotation A∈SO(3)A \in SO(3) with Ari≈biA r_i \approx b_i. The convention is that of Wahba's problem: A=Rbs=RsbTA = R_{bs} = R_{sb}^T maps reference coordinates to body coordinates. TRIAD imposes the extra condition Ar1/∣r1∣=b1/∣b1∣A r_1 / |r_1| = b_1 / |b_1| exactly.

The algorithm

  1. TRIAD(b_1, b_2, r_1, r_2) ▷ returns A with A r_1 ∥ b_1
  2. 1for each pair (v_1, v_2) in ((b_1, b_2), (r_1, r_2)) do t_1 ← v_1 / |v_1|
  3. 2c ← v_1 × v_2
  4. 3if |c| ≤ τ |v_1| |v_2| then error "the vectors are parallel"
  5. 4t_2 ← c / |c|
  6. 5t_3 ← t_1 × t_2
  7. 6return A ← Σ_{k=1}^{3} t_{b,k} t_{r,k}^T ▷ T_b T_r^T

Lines L1 to L5 build the triad T(v1,v2)=(t1,t2,t3)T(v_1, v_2) = (t_1, t_2, t_3) for each pair: t1t_1 along the first vector, t2t_2 normal to the plane of the pair, and t3t_3 in the plane, completing a right-handed frame. Line L6 is the product TbTrTT_b T_r^T of the body triad with the transpose of the reference triad, so Atr,k=tb,kA t_{r,k} = t_{b,k} for each kk. The tolerance τ\tau is relative; the code uses τ=10−12\tau = 10^{-12}.

Example

Take the data of the Wahba's problem page: r1=e1r_1 = e_1, r2=e2r_2 = e_2, and the true attitude AA with rows (0,1,0)(0, 1, 0), (0,0,1)(0, 0, 1), (1,0,0)(1, 0, 0), so b1=(0,0,1)b_1 = (0, 0, 1) and b2=(1,0,0)b_2 = (1, 0, 0).

  • Reference triad: tr,1=e1t_{r,1} = e_1, tr,2=e1×e2=e3t_{r,2} = e_1 \times e_2 = e_3, tr,3=tr,1×tr,2=e1×e3=−e2t_{r,3} = t_{r,1} \times t_{r,2} = e_1 \times e_3 = -e_2.
  • Body triad: tb,1=(0,0,1)t_{b,1} = (0, 0, 1), tb,2=(0,0,1)×(1,0,0)=(0,1,0)t_{b,2} = (0, 0, 1) \times (1, 0, 0) = (0, 1, 0), tb,3=(0,0,1)×(0,1,0)=(−1,0,0)t_{b,3} = (0, 0, 1) \times (0, 1, 0) = (-1, 0, 0).
  • A=tb,1e1T+tb,2e3T−tb,3e2TA = t_{b,1} e_1^T + t_{b,2} e_3^T - t_{b,3} e_2^T has columns Ae1=(0,0,1)A e_1 = (0, 0, 1), Ae2=(1,0,0)A e_2 = (1, 0, 0), Ae3=(0,1,0)A e_3 = (0, 1, 0). These are the columns of the true AA, so the answer is exact.

Now tilt b2b_2 by 22 degrees toward b1b_1: b2=(0.999391,0,−0.034899)b_2 = (0.999391, 0, -0.034899). With b1b_1 first, the body triad does not change, because tb,2t_{b,2} is still the normal (0,1,0)(0, 1, 0) of the same plane. TRIAD returns the true AA again, b1b_1 is matched exactly, and b2b_2 is missed by 22 degrees. The Wahba loss is 6.0917×10−46.0917 \times 10^{-4}, twice the optimal 3.0461×10−43.0461 \times 10^{-4}, where each vector is missed by 11 degree. With the order swapped, b2b_2 is matched exactly and the attitude is 22 degrees off the true one, at the same loss.

Correctness

The output is always a rotation: each triad is orthonormal with determinant 11, and a product of rotations is a rotation. It matches the first pair exactly, and the second pair lands in the plane of b1b_1 and b2b_2 at the reference angle from b1b_1. For noise-free data bi=A0rib_i = A_0 r_i, the rule (Qx)×(Qy)=Q(x×y)(Q x) \times (Q y) = Q (x \times y) for a rotation QQ gives Tb=A0TrT_b = A_0 T_r, so TRIAD returns A0A_0. These are theorems under the stated hypotheses; the full statements and proofs are in the correctness proof. With noise, TRIAD does not minimize the Wahba loss: the example above has twice the optimal loss.

Proof: TRIAD returns a rotation that matches the first pair exactly and recovers the true attitude from noise-free datafull

Setting. The input is two body vectors b1,b2b_1, b_2 and two reference vectors r1,r2r_1, r_2 in R3\mathbb{R}^3. For a pair of vectors v1,v2v_1, v_2, lines L1 to L5 build

t1=v1∣v1∣,t2=v1×v2∣v1×v2∣,t3=t1×t2,t_1 = \frac{v_1}{|v_1|}, \qquad t_2 = \frac{v_1 \times v_2}{|v_1 \times v_2|}, \qquad t_3 = t_1 \times t_2,

and T(v1,v2)T(v_1, v_2) is the matrix with columns t1,t2,t3t_1, t_2, t_3. Line L6 returns A=TbTrTA = T_b T_r^T with Tb=T(b1,b2)T_b = T(b_1, b_2) and Tr=T(r1,r2)T_r = T(r_1, r_2). The word rotation means an element of SO(3)SO(3), a real 3×33 \times 3 matrix QQ with QTQ=IQ^T Q = I and det⁡Q=1\det Q = 1.

Assumptions.

  • (N) v1×v2≠0v_1 \times v_2 \ne 0 for both pairs, that is, no vector is zero and the two vectors of a pair are not parallel. Line L3 tests this and raises an error otherwise.
  • (E) For the third claim only: there is a rotation A0A_0 and scalars s1,s2>0s_1, s_2 > 0 with bi=siA0rib_i = s_i A_0 r_i.

Claim.

  1. AA is a rotation.
  2. Ar1/∣r1∣=b1/∣b1∣A r_1 / |r_1| = b_1 / |b_1|.
  3. Ar2A r_2 lies in the plane spanned by b1b_1 and b2b_2, on the same side of the line of b1b_1 as b2b_2, and the angle from b1b_1 to Ar2A r_2 equals the angle from r1r_1 to r2r_2.
  4. Under (E), A=A0A = A_0.
  5. Without (N), no rotation is determined by the data: if b1×b2=0b_1 \times b_2 = 0 and r1×r2=0r_1 \times r_2 = 0 with nonzero vectors, and AA maps r1r_1 to the direction of b1b_1, then so does AA followed by any rotation about b1b_1.

Proof.

Claim 1. By (N), t1t_1 and t2t_2 are well defined unit vectors. The vector v1×v2v_1 \times v_2 is orthogonal to v1v_1, so t1⋅t2=0t_1 \cdot t_2 = 0. The cross product of two orthogonal unit vectors is a unit vector orthogonal to both, so t1,t2,t3t_1, t_2, t_3 are orthonormal and TTT=IT^T T = I. Also det⁡T=t1⋅(t2×t3)\det T = t_1 \cdot (t_2 \times t_3). By the rule a×(b×c)=b(a⋅c)−c(a⋅b)a \times (b \times c) = b (a \cdot c) - c (a \cdot b), t2×(t1×t2)=t1(t2⋅t2)−t2(t2⋅t1)=t1t_2 \times (t_1 \times t_2) = t_1 (t_2 \cdot t_2) - t_2 (t_2 \cdot t_1) = t_1, so det⁡T=t1⋅t1=1\det T = t_1 \cdot t_1 = 1. So TbT_b and TrT_r are rotations, and A=TbTrTA = T_b T_r^T is a rotation, because SO(3)SO(3) is closed under products and transposes.

Claim 2. Since TrT_r is orthogonal, TrTtr,1=e1T_r^T t_{r,1} = e_1, so Atr,1=Tbe1=tb,1A t_{r,1} = T_b e_1 = t_{b,1}. This is Ar1/∣r1∣=b1/∣b1∣A r_1 / |r_1| = b_1 / |b_1|.

Claim 3. The same argument gives Atr,k=tb,kA t_{r,k} = t_{b,k} for k=2,3k = 2, 3. For any pair, we show that

v2∣v2∣=cos⁡θ t1−sin⁡θ t3,\frac{v_2}{|v_2|} = \cos\theta \, t_1 - \sin\theta \, t_3,

where θ∈(0,π)\theta \in (0, \pi) is the angle from v1v_1 to v2v_2. To see this, write v2/∣v2∣=cos⁡θ t1+wv_2 / |v_2| = \cos\theta \, t_1 + w with w⊥t1w \perp t_1 and ∣w∣=sin⁡θ|w| = \sin\theta. Then v1×v2v_1 \times v_2 is a positive multiple of t1×wt_1 \times w, so t2=t1×w/∣w∣t_2 = t_1 \times w / |w|. By the triple product rule, t1×(t1×w)=t1(t1⋅w)−w=−wt_1 \times (t_1 \times w) = t_1 (t_1 \cdot w) - w = -w, so t3=−w/∣w∣t_3 = -w / |w|. Apply this to the reference pair, with angle θr\theta_r, and apply AA:

Ar2∣r2∣=cos⁡θr tb,1−sin⁡θr tb,3.\frac{A r_2}{|r_2|} = \cos\theta_r \, t_{b,1} - \sin\theta_r \, t_{b,3}.

The vectors tb,1t_{b,1} and −tb,3-t_{b,3} span the plane of b1b_1 and b2b_2, and −tb,3-t_{b,3} points to the side of b2b_2. So Ar2A r_2 is in that plane, on the side of b2b_2, at the angle θr\theta_r from b1b_1.

Claim 4. For a rotation QQ and vectors x,yx, y, (Qx)×(Qy)=Q(x×y)(Q x) \times (Q y) = Q (x \times y), and ∣Qx∣=∣x∣|Q x| = |x|. Under (E), b1×b2=s1s2A0(r1×r2)b_1 \times b_2 = s_1 s_2 A_0 (r_1 \times r_2), so each line L1 to L5 for the body pair gives A0A_0 times the result for the reference pair: tb,k=A0tr,kt_{b,k} = A_0 t_{r,k}. So Tb=A0TrT_b = A_0 T_r and A=A0TrTrT=A0A = A_0 T_r T_r^T = A_0. The scalars sis_i drop out because each line normalizes.

Claim 5. Let RϕR_\phi be the rotation by ϕ\phi about the unit vector u=b1/∣b1∣u = b_1 / |b_1|. Then Rϕu=uR_\phi u = u, so RϕAr1/∣r1∣=uR_\phi A r_1 / |r_1| = u. Since b2b_2 is parallel to b1b_1 and r2r_2 is parallel to r1r_1, the second pair is matched by RϕAR_\phi A exactly when it is matched by AA. So every RϕAR_\phi A fits the data equally well, and the data do not fix the rotation about b1b_1. ■\blacksquare

Remarks.

  • Claims 2 and 3 show where the noise goes. All of the error of the pair (b2,r2)(b_2, r_2) is put on the second pair: Ar2A r_2 misses b2b_2 by the angle ∣θb−θr∣|\theta_b - \theta_r| inside the plane of b1b_1 and b2b_2, and Ar1A r_1 is exact. A least-squares solution of Wahba's problem shares the error between the pairs, so TRIAD is not its minimizer when θb≠θr\theta_b \ne \theta_r. Claim 4 shows that the two agree when the data are exact.
  • In floating point, line L3 uses the relative test ∣v1×v2∣≤τ∣v1∣∣v2∣|v_1 \times v_2| \le \tau |v_1| |v_2| with τ=10−12\tau = 10^{-12}. Near that limit, t2t_2 is the normalized difference of nearly equal products, and its relative error grows like ε/sin⁡θ\varepsilon / \sin\theta for unit roundoff ε\varepsilon. This is the same loss of accuracy that noise causes, scaled up by 1/sin⁡θ1 / \sin\theta.

Complexity

In the real RAM model, TRIAD performs four cross products, four normalizations and one 3×33 \times 3 outer-product sum: a fixed number of arithmetic operations and square roots, so O(1)O(1) time and O(1)O(1) extra memory. It does no iteration and needs no eigensolver.

Properties

  • Exact for noise-free data (theorem). Two non-parallel exact pairs give the true attitude.
  • First vector exact (theorem). Ar1A r_1 points along b1b_1 for any valid input, with or without noise.
  • Not optimal (theorem by example). With noise its Wahba loss is in general higher than the minimum, as in the example.
  • Order dependent (measurement). With noise, swapping the pairs changes the answer; in the tests a swap moved the attitude by more than 10−310^{-3} rad for noise of a few hundredths of a radian.
  • Scale free. Only the directions of the inputs matter, so the vectors need not be unit.
  • Sensitive near parallel vectors (measurement). With a fixed noise level of 0.010.01 rad, the mean attitude error grew as the angle between the reference vectors fell from 9090 degrees to 1717 degrees to 33 degrees.

Variants and improvements

  • Best sensor first (heuristic). Since the first pair is matched exactly, put the more accurate measurement first. Shuster and Oh (1981) analyze the error of TRIAD in terms of the two sensor accuracies.
  • Bisector triad (measurement). Build both triads from v1+v2v_1 + v_2 and v1−v2v_1 - v_2 instead of v1v_1 and v2v_2. The two pairs are then treated alike. In 200 random noisy draws with equal weights, this gave the same rotation as the q-method to 10−1410^{-14}.
  • Optimal methods. For more than two vectors, or for unequal weights done right, use the q-method, QUEST or the SVD of the attitude profile matrix.

When to use it

Use TRIAD when there are exactly two directions, one of them much better than the other, and the cost must be minimal, for example a small satellite with a Sun sensor and a magnetometer, or a quick first guess for a filter. Use an optimal solver of Wahba's problem when the two sensors are of similar quality, when there are more than two directions, or when a covariance of the result is needed.

Pitfalls

  • Nearly parallel vectors. When the two directions are close, v1×v2v_1 \times v_2 is small and its direction is dominated by noise. The attitude error grows roughly like the noise divided by the sine of the angle between the vectors (heuristic, from the proof). A tolerance test only rejects the exact case.
  • Frame conventions. TRIAD returns A=RbsA = R_{bs}, which maps reference coordinates to body coordinates. The attitude of the body in the reference frame is ATA^T. Mixing the two is the most common bug.
  • Mixed pairs. b1b_1 must be the measurement of r1r_1, and b2b_2 of r2r_2. Swapping only one side gives a wrong rotation with no warning.
  • No uncertainty. TRIAD returns no covariance. The error depends on the order, on the angle between the vectors and on both sensor noises.

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.

rbm.pyI0RawGitHub
# 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
triad_method.py 55 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/triad-method/. The authors are listed in prov/FY3PHK.jsonl.

"""The TRIAD method of Black (1964) for the attitude from two vector pairs.

Vectors are lists of 3 floats and matrices are lists of rows, as in rbm.py.
The reference vectors r1, r2 are known in the space frame {s} (for example
the direction of the Sun and the magnetic field from a model). The body
vectors b1, b2 are the same directions measured in the body frame {b}.
The method returns the attitude matrix A = R_bs, so that b_i = A r_i for
noise-free data. The rotation R_sb of the body in space is A^T.

The first pair is matched exactly: A r1 / |r1| = b1 / |b1|. The second pair
only fixes the rotation about that direction. The method is not the least
squares solution of Wahba's problem.
"""

import rbm

COLLINEAR_TOL = 1e-12  # |b1 x b2| / (|b1| |b2|) below this counts as collinear


def _unit(v):
    n = rbm.norm(v)
    if n == 0.0:
        raise ValueError("zero vector")
    return [x / n for x in v]


def _triad_frame(v1, v2):
    """Return the columns t1, t2, t3 of the orthonormal frame built from v1, v2."""
    t1 = _unit(v1)  # @line L1
    c = rbm.cross(v1, v2)  # @line L2
    if rbm.norm(c) <= COLLINEAR_TOL * rbm.norm(v1) * rbm.norm(v2):  # @line L3
        raise ValueError("the two vectors are collinear; TRIAD needs two independent directions")
    t2 = _unit(c)  # @line L4
    t3 = rbm.cross(t1, t2)  # @line L5
    return t1, t2, t3


def triad(b1, b2, r1, r2):
    """Return A = R_bs with A r1 parallel to b1, from two body and two reference vectors."""
    tb = _triad_frame(b1, b2)  # @line L1
    tr = _triad_frame(r1, r2)  # @line L1
    # A = [t1 t2 t3]_b [t1 t2 t3]_r^T, a sum of three outer products
    return [[sum(tb[k][i] * tr[k][j] for k in range(3)) for j in range(3)] for i in range(3)]  # @line L6


def wahba_loss(A, bs, rs, weights):
    """Return L(A) = 1/2 sum a_i |b_i - A r_i|^2 (the cost of Wahba's problem)."""
    total = 0.0
    for a, b, r in zip(weights, bs, rs):
        d = rbm.sub(b, rbm.matvec(A, r))
        total += 0.5 * a * rbm.dot(d, d)
    return total
test_triad_method.py 175 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/triad-method/. The authors are listed in prov/FY3PHK.jsonl.

import math
import random

import pytest

import rbm
from triad_method import triad, 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_rotation(rng):
    q = [rng.gauss(0.0, 1.0) for _ in range(4)]
    return rbm.quat_to_rot(q)


def max_diff(a, b):
    return max(abs(a[i][j] - b[i][j]) for i in range(3) for j in range(3))


def angle_between(u, v):
    c = rbm.dot(u, v) / (rbm.norm(u) * rbm.norm(v))
    return math.acos(max(-1.0, min(1.0, c)))


def rotation_angle(a, b):
    """Return the angle of the rotation a b^T."""
    return rbm.norm(rbm.so3_log(rbm.mul(a, rbm.transpose(b))))


def test_check_rotation():
    # The area check rotation: R_sb is 120 degrees about (1, 1, 1) / sqrt(3),
    # so A = R_bs = R_sb^T.
    r_sb = [[0.0, 0.0, 1.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]
    a_true = rbm.transpose(r_sb)
    r1, r2 = [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]
    b1, b2 = rbm.matvec(a_true, r1), rbm.matvec(a_true, r2)
    assert b1 == [0.0, 0.0, 1.0] and b2 == [1.0, 0.0, 0.0]
    assert max_diff(triad(b1, b2, r1, r2), a_true) < 1e-15
    # The other order of the pairs gives the same matrix for exact data.
    assert max_diff(triad(b2, b1, r2, r1), a_true) < 1e-15


def test_noise_free_recovery():
    rng = random.Random(1)
    for _ in range(200):
        a_true = random_rotation(rng)
        r1, r2 = random_unit(rng), random_unit(rng)
        s1, s2 = rng.uniform(0.1, 10.0), rng.uniform(0.1, 10.0)
        # Body vectors need not be unit: TRIAD uses only their directions.
        b1 = rbm.scale(rbm.matvec(a_true, r1), s1)
        b2 = rbm.scale(rbm.matvec(a_true, r2), s2)
        assert max_diff(triad(b1, b2, r1, r2), a_true) < 1e-12


def test_output_is_a_rotation_with_noise():
    rng = random.Random(2)
    for _ in range(200):
        r1, r2 = random_unit(rng), random_unit(rng)
        b1, b2 = random_unit(rng), random_unit(rng)
        a = triad(b1, b2, r1, r2)
        ata = rbm.mul(rbm.transpose(a), a)
        assert max_diff(ata, rbm.eye(3)) < 1e-13
        assert abs(rbm.det(a) - 1.0) < 1e-13


def test_first_vector_matched_exactly():
    rng = random.Random(3)
    a_true = random_rotation(rng)
    for _ in range(200):
        r1, r2 = random_unit(rng), random_unit(rng)
        b1 = rbm.matvec(rbm.mul(rbm.so3_exp([rng.gauss(0.0, 0.05) for _ in range(3)]), a_true), r1)
        b2 = rbm.matvec(rbm.mul(rbm.so3_exp([rng.gauss(0.0, 0.05) for _ in range(3)]), a_true), r2)
        a = triad(b1, b2, r1, r2)
        assert rbm.norm(rbm.sub(rbm.matvec(a, r1), b1)) < 1e-12
        # The second pair is matched only up to the angle the noise put
        # between the pairs: the angle of b2 to the plane is not removed.
        assert angle_between(rbm.matvec(a, r2), b2) < 0.5


def test_collinear_input_is_rejected():
    with pytest.raises(ValueError):
        triad([0.0, 0.0, 1.0], [0.0, 0.0, -2.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0])
    with pytest.raises(ValueError):
        triad([0.0, 0.0, 1.0], [1.0, 0.0, 0.0], [1.0, 0.0, 0.0], [3.0, 0.0, 0.0])
    with pytest.raises(ValueError):
        triad([0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0])


def descend_wahba(a, bs, rs, weights, steps=400):
    """Minimize the Wahba loss on SO(3) by gradient steps from a.

    With A = A0 exp([w]) and B = sum a_i b_i r_i^T, the loss is
    lambda0 - tr(A^T B), and its gradient in w is -vee(A^T B - B^T A).
    A step of size h along that direction lowers the loss for small h.
    """
    bmat = rbm.zeros(3, 3)
    for wi, b, r in zip(weights, bs, rs):
        for i in range(3):
            for j in range(3):
                bmat[i][j] += wi * b[i] * r[j]
    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.25)))
    return a


def test_triad_is_not_optimal():
    # Measurement: TRIAD loss >= optimal loss, and in most noisy draws the
    # gap is strictly positive, so TRIAD is not the Wahba minimizer.
    rng = random.Random(4)
    gaps = []
    for _ in range(30):
        a_true = random_rotation(rng)
        r1, r2 = random_unit(rng), random_unit(rng)
        bs = []
        for r in (r1, r2):
            noise = rbm.so3_exp([rng.gauss(0.0, 0.05) for _ in range(3)])
            bs.append(rbm.matvec(rbm.mul(noise, a_true), r))
        weights = [0.5, 0.5]
        a_triad = triad(bs[0], bs[1], r1, r2)
        a_opt = descend_wahba(a_triad, bs, [r1, r2], weights)
        lt = wahba_loss(a_triad, bs, [r1, r2], weights)
        lo = wahba_loss(a_opt, bs, [r1, r2], weights)
        assert lo <= lt + 1e-15
        gaps.append(lt - lo)
    assert sum(1 for g in gaps if g > 1e-6) >= 25


def test_order_matters_with_noise():
    rng = random.Random(5)
    a_true = random_rotation(rng)
    r1, r2 = random_unit(rng), random_unit(rng)
    b1 = rbm.matvec(rbm.mul(rbm.so3_exp([0.03, -0.02, 0.01]), a_true), r1)
    b2 = rbm.matvec(rbm.mul(rbm.so3_exp([-0.01, 0.04, 0.02]), a_true), r2)
    a12 = triad(b1, b2, r1, r2)
    a21 = triad(b2, b1, r2, r1)
    assert rotation_angle(a12, a21) > 1e-3
    assert rbm.norm(rbm.sub(rbm.matvec(a21, r2), b2)) < 1e-12


def test_order_does_not_matter_without_noise():
    rng = random.Random(6)
    a_true = random_rotation(rng)
    r1, r2 = random_unit(rng), random_unit(rng)
    b1, b2 = rbm.matvec(a_true, r1), rbm.matvec(a_true, r2)
    assert max_diff(triad(b1, b2, r1, r2), triad(b2, b1, r2, r1)) < 1e-12


def test_error_grows_as_vectors_become_parallel():
    # Measurement: with fixed noise, the attitude error grows as the angle
    # between the two reference directions shrinks.
    rng = random.Random(7)
    errs = []
    for sep in (math.pi / 2.0, 0.3, 0.05):
        total = 0.0
        for _ in range(50):
            a_true = random_rotation(rng)
            r1 = [0.0, 0.0, 1.0]
            r2 = [math.sin(sep), 0.0, math.cos(sep)]
            b1 = rbm.matvec(rbm.mul(rbm.so3_exp([rng.gauss(0.0, 0.01) for _ in range(3)]), a_true), r1)
            b2 = rbm.matvec(rbm.mul(rbm.so3_exp([rng.gauss(0.0, 0.01) for _ in range(3)]), a_true), r2)
            total += rotation_angle(triad(b1, b2, r1, r2), a_true)
        errs.append(total / 50)
    assert errs[0] < errs[1] < errs[2]

History

Black (1964) described the method for a satellite with two passive sensors, one year before Wahba posed the least-squares problem. The name TRIAD refers to the two triads it builds. Shuster and Oh (1981) analyzed its errors and compared it with the optimal solution of Wahba's problem by their QUEST algorithm. Markley and Crassidis (2014) present it with the other static methods of attitude determination.

References

  1. Harold D. Black, A passive system for determining the attitude of a satellite, AIAA Journal 2(7), 1964, pages 1350 to 1351, the construction of the attitude from two vector measurements by two orthonormal triads
  2. 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 TRIAD algorithm and its error analysis, compared with the optimal QUEST solution
  3. F. Landis Markley and John L. Crassidis, Fundamentals of Spacecraft Attitude Determination and Control, Springer, 2014, Chapter 5 (static attitude determination), the TRIAD section

About this page

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

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example