Algorithm Search⌘K

Algorithmadvanced

Nonlinear complementary filter on SO(3)

Also called Mahony filter, explicit complementary filter.

Mahony's attitude observer that corrects integrated gyroscope rates with a feedback term from vector measurements, with gyro bias estimation.

Time
O(T n) worst
Space
O(1) extra
Where
T = the number of time steps; n = the number of measured directions
Properties
deterministicnot exactonlinerecursive
Origin
Robert Mahony, Tarek Hamel, Jean Michel Pflimlin, 2008

The nonlinear complementary filter estimates the attitude of a rigid body, a rotation in SO(3)SO(3), and the bias of its gyroscope. It integrates the gyro rate and corrects it with a feedback term built from vector measurements, such as gravity from an accelerometer and the magnetic field from a magnetometer. The correction is a weighted sum of cross products between the measured directions and the directions that the current estimate predicts, and an integral of the same term estimates the gyro bias. This page covers the explicit form of Mahony, Hamel and Pflimlin (2008), which uses the vectors directly and needs no attitude reconstruction. It is a deterministic state observer with a Lyapunov proof, not a stochastic filter: it has two gains and no covariance. The error-state Kalman filter solves the same attitude estimation problem with a noise model and a covariance, at more cost.

In plain words

A gyroscope tells you how fast you are turning, so adding up its readings tracks your orientation. But a small error in each reading adds up, and after a while the estimate drifts away. A gravity sensor and a compass do not drift, but they are noisy and easily disturbed. This filter mixes the two. It follows the gyro from moment to moment, and it keeps nudging the estimate so that the predicted gravity and compass directions turn toward the measured ones. A slow memory of these nudges learns the constant error of the gyro and removes it. Two knobs set how hard it nudges and how fast it learns. It is cheap and needs no model of the sensor noise.

The problem

The attitude R=RsbR = R_{sb} follows R˙=R[Ω]×\dot R = R [\Omega]_\times, with Ω\Omega the body angular velocity and [⋅]×[\cdot]_\times the skew-symmetric matrix of a vector. A gyro reads Ωy=Ω+b\Omega_y = \Omega + b with a slowly varying bias bb. For i=1,…,ni = 1, \ldots, n, a sensor reads vi≈RTv0iv_i \approx R^T v_{0i}, the body form of a known unit direction v0iv_{0i} of the space frame. From these signals, estimate RR and bb online, with an error that goes to zero when the bias is constant and the measurements are exact.

The algorithm

Choose weights ki>0k_i > 0, a proportional gain kP>0k_P > 0 and an integral gain kI>0k_I > 0. Start from any R^∈SO(3)\hat R \in SO(3) and b^\hat b, often 00.

  1. ECF-STEP(R̂, b̂, Ω_y, v_{1..n}, v0_{1..n}, k_{1..n}, k_P, k_I, δt) ▷ returns the new (R̂, b̂)
  2. 1v̂_i ← R̂^T v0_i for each i ▷ predicted body directions
  3. 2ω_mes ← Σ_i k_i v_i × v̂_i ▷ correction
  4. 3b̂ ← b̂ - k_I ω_mes δt ▷ integral term: bias estimate
  5. 4R̂ ← R̂ exp([Ω_y - b̂ + k_P ω_mes]_× δt) ▷ corrected gyro rate

Lines L1 and L2 compare each measured direction with its prediction. The cross product vi×v^iv_i \times \hat v_i is the axis about which R^\hat R must turn to bring v^i\hat v_i toward viv_i, scaled by the sine of the angle between them. Line L3 integrates that error into the bias estimate, as the integral part of a PI controller. Line L4 integrates the corrected rate with the matrix exponential, here the Rodrigues rotation formula, which keeps R^\hat R a rotation. In continuous time the filter is b^˙=−kIωmes\dot{\hat b} = -k_I \omega_{mes} and R^˙=R^[Ωy−b^+kPωmes]×\dot{\hat R} = \hat R [\Omega_y - \hat b + k_P \omega_{mes}]_\times, which is equation 32 of Mahony et al. (2008); L3 and L4 are one step of it. The same filter can run on a unit quaternion with the quaternion kinematic equation.

Example

The body turns with Ω(t)=(0.3sin⁡0.5t, 0.2cos⁡0.3t, 0.1)\Omega(t) = (0.3 \sin 0.5 t, \ 0.2 \cos 0.3 t, \ 0.1) rad/s, and the gyro has the constant bias b=(0.02,−0.03,0.01)b = (0.02, -0.03, 0.01) rad/s. Two directions are measured without noise: v01=e3v_{01} = e_3 (gravity) with k1=1k_1 = 1, and v02=e1v_{02} = e_1 (a magnetic north) with k2=0.5k_2 = 0.5. The gains are kP=2k_P = 2 and kI=0.5k_I = 0.5, the step is δt=0.02\delta t = 0.02 s, and the start is b^=0\hat b = 0 with R^=exp⁡([(1.5,−1,0.5)]×)R\hat R = \exp([(1.5, -1, 0.5)]_\times) R, an error of 107.2107.2 degrees. The Lyapunov function of the next section is VV.

time (s) attitude error (degrees) VV
0 107.2
1 17.35 0.141
2 7.49
5 6.29
10 1.03
20 0.127
30 0.0033 8.4×10−98.4 \times 10^{-9}

The first second removes most of the error by the proportional term. The rest falls slowly while the integral term learns the bias; at t=30t = 30 s, b^=(0.0200,−0.0300,0.0101)\hat b = (0.0200, -0.0300, 0.0101). These numbers are measurements of the code.

Correctness

Let b~=b^−b\tilde b = \hat b - b, Emes=∑iki(1−vi⋅v^i)E_{mes} = \sum_i k_i (1 - v_i \cdot \hat v_i) and V=Emes+∣b~∣2/(2kI)V = E_{mes} + |\tilde b|^2 / (2 k_I). For a constant bias and exact measurements, the continuous filter gives V˙=−kP∣ωmes∣2≤0\dot V = -k_P |\omega_{mes}|^2 \le 0, so the error never grows; the correctness proof derives this identity. Convergence needs more. Mahony et al. (2008), Theorem 5.1, prove that with at least two non-parallel directions, a bounded angular velocity and M0=∑ikiv0iv0iTM_0 = \sum_i k_i v_{0i} v_{0i}^T with three distinct eigenvalues, the estimate converges to the true attitude and bias from almost every start. The exceptions are the starts that lead to three unstable equilibria, where R^RT\hat R R^T is a rotation by π\pi about an eigenvector of M0M_0. Their Lyapunov function has the same form as VV, with their own error convention. Almost-global is the best possible for a continuous observer on SO(3)SO(3).

Proof: The explicit complementary filter has a Lyapunov function that decreases at the rate k_P times the squared correctionfull

Setting. The attitude is a rotation R(t)=RsbR(t) = R_{sb} with R˙=R[Ω]×\dot R = R [\Omega]_\times, where Ω\Omega is the body angular velocity and [w]×[w]_\times is the skew-symmetric matrix of a vector. A gyro reads Ωy=Ω+b\Omega_y = \Omega + b. For i=1,…,ni = 1, \ldots, n, a vector sensor reads vi=RTv0iv_i = R^T v_{0i}, the body form of a known unit direction v0iv_{0i}, with weight ki>0k_i > 0. The filter state is (R^,b^)(\hat R, \hat b), and in continuous time it runs

v^i=R^Tv0i,ωmes=∑iki vi×v^i,b^˙=−kI ωmes,R^˙=R^ [Ωy−b^+kP ωmes]×,\hat v_i = \hat R^T v_{0i}, \quad \omega_{mes} = \sum_i k_i \, v_i \times \hat v_i, \quad \dot{\hat b} = -k_I \, \omega_{mes}, \quad \dot{\hat R} = \hat R \, [\Omega_y - \hat b + k_P \, \omega_{mes}]_\times ,

with gains kP,kI>0k_P, k_I > 0. Lines L1 to L4 of the code are one step of length δt\delta t of these equations, with the exponential map for the last one. Let b~=b^−b\tilde b = \hat b - b and

Emes=∑iki(1−vi⋅v^i),V=Emes+∣b~∣22kI.E_{mes} = \sum_i k_i (1 - v_i \cdot \hat v_i), \qquad V = E_{mes} + \frac{|\tilde b|^2}{2 k_I}.

Assumptions.

  • (B) The bias bb is constant.
  • (V) The directions v0iv_{0i} are constant and the measurements are exact: vi=RTv0iv_i = R^T v_{0i}.
  • (Ω) Ω(t)\Omega(t) is continuous and bounded.

Claim. Along every solution, V˙=−kP ∣ωmes∣2≤0\dot V = -k_P \, |\omega_{mes}|^2 \le 0. So VV never increases, b~\tilde b stays bounded, and ∫0∞∣ωmes∣2 dt≤V(0)/kP\int_0^\infty |\omega_{mes}|^2 \, dt \le V(0) / k_P.

Proof. For a rotation Q(t)Q(t) with Q˙=Q[w]×\dot Q = Q [w]_\times, the transpose satisfies ddtQT=−[w]×QT\frac{d}{dt} Q^T = -[w]_\times Q^T, so ddt(QTv0)=−w×(QTv0)\frac{d}{dt}(Q^T v_0) = -w \times (Q^T v_0) for a constant v0v_0. Apply this to RR with w=Ωw = \Omega and to R^\hat R with w=w^=Ωy−b^+kPωmes=Ω−b~+kPωmesw = \hat w = \Omega_y - \hat b + k_P \omega_{mes} = \Omega - \tilde b + k_P \omega_{mes}, where (B) gives Ωy−b^=Ω−b~\Omega_y - \hat b = \Omega - \tilde b. By (V),

ddt(vi⋅v^i)=−(Ω×vi)⋅v^i−vi⋅(w^×v^i).\frac{d}{dt}(v_i \cdot \hat v_i) = -(\Omega \times v_i) \cdot \hat v_i - v_i \cdot (\hat w \times \hat v_i).

By the cyclic rule of the triple product, (Ω×vi)⋅v^i=Ω⋅(vi×v^i)(\Omega \times v_i) \cdot \hat v_i = \Omega \cdot (v_i \times \hat v_i) and vi⋅(w^×v^i)=w^⋅(v^i×vi)=−w^⋅(vi×v^i)v_i \cdot (\hat w \times \hat v_i) = \hat w \cdot (\hat v_i \times v_i) = -\hat w \cdot (v_i \times \hat v_i). So

ddt(vi⋅v^i)=(w^−Ω)⋅(vi×v^i)=(kPωmes−b~)⋅(vi×v^i).\frac{d}{dt}(v_i \cdot \hat v_i) = (\hat w - \Omega) \cdot (v_i \times \hat v_i) = (k_P \omega_{mes} - \tilde b) \cdot (v_i \times \hat v_i).

Multiply by kik_i and sum over ii:

E˙mes=−(kPωmes−b~)⋅ωmes=−kP∣ωmes∣2+b~⋅ωmes.\dot E_{mes} = -(k_P \omega_{mes} - \tilde b) \cdot \omega_{mes} = -k_P |\omega_{mes}|^2 + \tilde b \cdot \omega_{mes}.

By (B), b~˙=b^˙=−kIωmes\dot{\tilde b} = \dot{\hat b} = -k_I \omega_{mes}, so ddt∣b~∣22kI=−b~⋅ωmes\frac{d}{dt} \frac{|\tilde b|^2}{2 k_I} = -\tilde b \cdot \omega_{mes}. The cross terms cancel, and V˙=−kP∣ωmes∣2\dot V = -k_P |\omega_{mes}|^2. Integrate from 00 to TT: V(T)+kP∫0T∣ωmes∣2dt=V(0)V(T) + k_P \int_0^T |\omega_{mes}|^2 dt = V(0). Since V≥0V \ge 0 (each 1−vi⋅v^i≥01 - v_i \cdot \hat v_i \ge 0 for unit vectors), the integral is at most V(0)/kPV(0) / k_P for every TT, and ∣b~∣2≤2kIV(0)|\tilde b|^2 \le 2 k_I V(0). ■\blacksquare

What the claim does not give. V˙≤0\dot V \le 0 alone shows only that the error does not grow. Convergence needs more. Mahony, Hamel and Pflimlin (2008), Theorem 5.1, prove it under (B) and (V) with n≥2n \ge 2 non-parallel directions, a bounded angular velocity, and M0=∑ikiv0iv0iTM_0 = \sum_i k_i v_{0i} v_{0i}^T with three distinct eigenvalues. Their Lyapunov function has the same form as VV above, with their own error convention. The result is that the estimate (R^,b^)(\hat R, \hat b) converges to (R,b)(R, b) from every initial condition except a set of measure zero: the solutions that tend to the three unstable equilibria where R^RT\hat R R^T is a rotation by π\pi about an eigenvector of M0M_0. This is almost-global stability. It is the best that a continuous filter on SO(3)SO(3) can do: a continuous flow on a manifold that is not contractible, such as SO(3)SO(3), cannot have an equilibrium whose basin of attraction is the whole manifold.

About the code. The code integrates the equations with the step R^←R^exp⁡(w^ δt)\hat R \leftarrow \hat R \exp(\hat w \, \delta t). This keeps R^\hat R on SO(3)SO(3) up to rounding, because the exponential of a skew-symmetric matrix is a rotation. The decrease of VV is a property of the continuous system. For the discrete step it holds only up to a term of order δt2\delta t^2 per step. The tests measure it: with kP=2k_P = 2, kI=0.5k_I = 0.5 and δt=0.02\delta t = 0.02 s, the computed VV did not increase by more than 10−910^{-9} in any of 600 steps from an initial error of 107 degrees, and it fell below one percent of its initial value.

Complexity

In the real RAM model, one step costs O(n)O(n) for lines L1 and L2 (one matrix-vector product and one cross product per direction) and O(1)O(1) for lines L3 and L4 (one exponential of a 3×33 \times 3 skew-symmetric matrix and one 3×33 \times 3 product). Over TT steps the time is O(Tn)O(T n). The memory is O(1)O(1): the filter keeps only R^\hat R and b^\hat b.

Properties

  • Almost-global convergence (theorem). Under the hypotheses of Theorem 5.1 of Mahony et al. (2008), quoted above.
  • Lyapunov decrease (theorem). V˙=−kP∣ωmes∣2\dot V = -k_P |\omega_{mes}|^2 in continuous time. In the discrete code, VV rose by less than 10−910^{-9} at any step over 600 steps of the example (measurement).
  • Stays on SO(3)SO(3). The exponential update keeps R^\hat R a rotation; after 600 steps, R^TR^\hat R^T \hat R differed from II by less than 10−1210^{-12} (measurement).
  • Deterministic and cheap. No covariance, no matrix inverse, no linearization.
  • Bias observability. With one direction only, the attitude about that direction and the bias along it are not observable. The filter then aligns that one direction and leaves the rest to the gyro.

Variants and improvements

  • Direct and passive filters. Mahony et al. (2008) also give a direct and a passive complementary filter, which take a full attitude measurement, for example a solution of Wahba's problem, in place of the separate vectors.
  • Gains (heuristic). The filter acts as a low-pass filter on the vector measurements and a high-pass filter on the gyro, with a crossover near kPk_P rad/s. kIk_I is usually an order of magnitude below kPk_P, so that the bias estimate is slow.
  • Time-varying weights. A weight kik_i can be lowered when its sensor is unreliable, for example the accelerometer during strong acceleration.
  • Kalman filters. When a noise model and a covariance are needed, use the error-state Kalman filter or, on matrix Lie groups, the invariant extended Kalman filter.

When to use it

Use it on small embedded systems, such as drones, phones and hobby IMUs, where a few hundred operations per step is the budget, the noise statistics are poorly known, and a proof of convergence from large errors is worth more than optimal noise rejection. Use a Kalman filter when the attitude is fused with other states, such as position and velocity, or when an uncertainty is needed downstream.

Pitfalls

  • Accelerometers measure more than gravity. During acceleration, v1v_1 is not the gravity direction, and the filter turns the estimate the wrong way. Lower k1k_1 or ignore the accelerometer when ∣a∣|a| differs from gg.
  • Magnetic disturbance. Nearby iron and motor currents bend the magnetic field. Weight the magnetometer low, or use only its horizontal part.
  • Normalize. The cross product weighs each direction by its length. Use unit vectors, or the weights kik_i mean something else.
  • Order of the bias update. The code uses the new b^\hat b of line L3 in line L4. Using the old one is also a valid discretization, but the two give slightly different numbers.
  • Equal eigenvalues of M0M_0. If two eigenvalues of M0M_0 are equal, for example for two orthogonal directions with equal weights, Theorem 5.1 does not apply, and the bad equilibria are no longer three isolated points (heuristic). Choose unequal weights, as in the example.

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.

nonlinear_complementary_filter.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/nonlinear-complementary-filter/. The authors are listed in prov/R8HFJF.jsonl.

"""The explicit complementary filter of Mahony, Hamel and Pflimlin (2008).

Vectors are lists of 3 floats and matrices are lists of rows, as in rbm.py.
R is the attitude R_sb of the body in the space frame {s}, so the kinematics
are dR/dt = R [Omega] with Omega the body angular velocity. A gyro reads
Omega_y = Omega + b with a slowly varying bias b. A vector sensor reads the
body form v_i = R^T v0_i of a known direction v0_i (gravity, the magnetic
field). The filter keeps an estimate (R_hat, b_hat) and runs, in continuous
time,

    v_hat_i  = R_hat^T v0_i
    w_mes    = sum_i k_i v_i x v_hat_i
    db_hat   = -k_I w_mes dt
    dR_hat   = R_hat [Omega_y - b_hat + k_P w_mes] dt.

This module integrates those equations with one step of the exponential map
per sample, which keeps R_hat exactly on SO(3) up to rounding.
"""

import rbm


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


def ecf_step(r_hat, b_hat, omega_y, vs, v0s, ks, k_p, k_i, dt):
    """Return (R_hat, b_hat, w_mes) after one step of length dt.

    omega_y is the gyro reading, vs the measured body vectors, v0s the known
    space vectors, ks their weights, k_p and k_i the gains.
    """
    rt = rbm.transpose(r_hat)
    v_hats = [rbm.matvec(rt, _unit(v0)) for v0 in v0s]  # @line L1
    w_mes = [0.0, 0.0, 0.0]
    for k, v, vh in zip(ks, vs, v_hats):
        c = rbm.cross(_unit(v), vh)
        w_mes = [w_mes[j] + k * c[j] for j in range(3)]  # @line L2
    b_new = [b_hat[j] - k_i * w_mes[j] * dt for j in range(3)]  # @line L3
    w = [(omega_y[j] - b_new[j] + k_p * w_mes[j]) * dt for j in range(3)]
    r_new = rbm.mul(r_hat, rbm.so3_exp(w))  # @line L4
    return r_new, b_new, w_mes


def measurement_error(r_hat, vs, v0s, ks):
    """Return E_mes = sum_i k_i (1 - v_i . v_hat_i)."""
    rt = rbm.transpose(r_hat)
    return sum(k * (1.0 - rbm.dot(_unit(v), rbm.matvec(rt, _unit(v0)))) for k, v, v0 in zip(ks, vs, v0s))
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_nonlinear_complementary_filter.py 114 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/nonlinear-complementary-filter/. The authors are listed in prov/R8HFJF.jsonl.

import math
import random

import pytest

import rbm
from nonlinear_complementary_filter import ecf_step, measurement_error

V0S = [[0.0, 0.0, 1.0], [1.0, 0.0, 0.0]]  # gravity up and magnetic north
KS = [1.0, 0.5]  # M0 = diag(0.5, 0, 1) has three distinct eigenvalues
BIAS = [0.02, -0.03, 0.01]


def omega_at(t):
    return [0.3 * math.sin(0.5 * t), 0.2 * math.cos(0.3 * t), 0.1]


def angle(r_hat, r):
    return rbm.norm(rbm.so3_log(rbm.mul(r_hat, rbm.transpose(r))))


def lyapunov(r_hat, b_hat, r, k_i):
    """V = E_mes + |b - b_hat|^2 / (2 k_I); its time derivative is -k_P |w_mes|^2."""
    vs = [rbm.matvec(rbm.transpose(r), v0) for v0 in V0S]
    bt = rbm.sub(BIAS, b_hat)
    return measurement_error(r_hat, vs, V0S, KS) + rbm.dot(bt, bt) / (2.0 * k_i)


def simulate(r_hat, b_hat, steps, k_p=2.0, k_i=0.5, dt=0.02, rng=None, noise=0.0, v0s=V0S, ks=KS, bias=BIAS):
    r = rbm.eye(3)
    history = []
    for k in range(steps):
        om = omega_at(k * dt)
        rt = rbm.transpose(r)
        vs = [rbm.matvec(rt, v0) for v0 in v0s]
        gyro = [o + b for o, b in zip(om, bias)]
        if rng is not None:
            vs = [[x + rng.gauss(0.0, noise) for x in v] for v in vs]
            gyro = [x + rng.gauss(0.0, noise) for x in gyro]
        r_hat, b_hat, _ = ecf_step(r_hat, b_hat, gyro, vs, v0s, ks, k_p, k_i, dt)
        r = rbm.mul(r, rbm.so3_exp([o * dt for o in om]))
        history.append((r_hat, b_hat, r))
    return history


def test_converges_from_large_error_and_learns_bias():
    hist = simulate(rbm.so3_exp([1.5, -1.0, 0.5]), [0.0, 0.0, 0.0], 800)
    r_hat, b_hat, r = hist[-1]
    assert angle(r_hat, r) < 2e-2
    assert rbm.norm(rbm.sub(b_hat, BIAS)) < 2e-2
    # The error keeps shrinking: compare with the error halfway.
    assert angle(r_hat, r) < 0.2 * angle(hist[400][0], hist[400][2])


def test_lyapunov_function_never_increases():
    k_i = 0.5
    hist = simulate(rbm.so3_exp([1.5, -1.0, 0.5]), [0.0, 0.0, 0.0], 600, k_i=k_i)
    vals = [lyapunov(rh, bh, r, k_i) for rh, bh, r in hist]
    for a, b in zip(vals, vals[1:]):
        assert b <= a + 1e-9
    assert vals[-1] < 1e-2 * vals[0]


def test_estimate_stays_on_so3():
    hist = simulate(rbm.so3_exp([0.4, 0.2, -0.3]), [0.0, 0.0, 0.0], 600, rng=random.Random(1), noise=0.01)
    r_hat = hist[-1][0]
    rtr = rbm.mul(rbm.transpose(r_hat), r_hat)
    assert max(abs(rtr[i][j] - (1.0 if i == j else 0.0)) for i in range(3) for j in range(3)) < 1e-12
    assert abs(rbm.det(r_hat) - 1.0) < 1e-12


def test_unstable_equilibria_are_fixed_points():
    # R_hat = D_i R with b_hat = b gives w_mes = 0 exactly.
    for d in ([1.0, -1.0, -1.0], [-1.0, 1.0, -1.0], [-1.0, -1.0, 1.0]):
        dm = [[d[i] if i == j else 0.0 for j in range(3)] for i in range(3)]
        r = rbm.so3_exp([0.3, -0.2, 0.7])
        vs = [rbm.matvec(rbm.transpose(r), v0) for v0 in V0S]
        _, _, w = ecf_step(rbm.mul(dm, r), BIAS, [0.0, 0.0, 0.0], vs, V0S, KS, 1.0, 0.3, 0.01)
        assert rbm.norm(w) < 1e-15


def test_unstable_equilibrium_is_left_after_a_small_push():
    d1 = [[1.0, 0.0, 0.0], [0.0, -1.0, 0.0], [0.0, 0.0, -1.0]]
    start = rbm.mul(rbm.so3_exp([0.0, 1e-3, 1e-3]), d1)
    hist = simulate(start, list(BIAS), 1000)
    r_hat, _, r = hist[-1]
    assert angle(r_hat, r) < 5e-2


def test_single_direction_aligns_that_direction():
    # Corollary 5.2 setting: one vector, no bias. v_hat tends to v, the
    # rotation about v0 is not observable.
    v0s, ks = [[0.0, 0.0, 1.0]], [1.0]
    hist = simulate(rbm.so3_exp([1.0, 0.5, 0.0]), [0.0, 0.0, 0.0], 800, k_i=0.0, v0s=v0s, ks=ks, bias=[0.0, 0.0, 0.0])
    r_hat, _, r = hist[-1]
    v = rbm.matvec(rbm.transpose(r), v0s[0])
    v_hat = rbm.matvec(rbm.transpose(r_hat), v0s[0])
    assert rbm.norm(rbm.sub(v, v_hat)) < 1e-4


def test_noisy_run_stays_close():
    # Measurement: with noise of 0.01 on every channel, the error after
    # convergence stays below 2 degrees in this run.
    hist = simulate(rbm.so3_exp([0.5, 0.5, 0.5]), [0.0, 0.0, 0.0], 800, rng=random.Random(2), noise=0.01)
    worst = max(angle(rh, r) for rh, _, r in hist[500:])
    assert worst < math.radians(2.0)


def test_zero_measurement_vector_is_rejected():
    with pytest.raises(ValueError):
        ecf_step(rbm.eye(3), [0.0] * 3, [0.0] * 3, [[0.0, 0.0, 0.0]], [[0.0, 0.0, 1.0]], [1.0], 1.0, 0.1, 0.01)

History

Complementary filters, which blend a high-frequency sensor with a low-frequency one, are older than this method. Mahony, Hamel and Pflimlin (2008) posed the problem on SO(3)SO(3), wrote the passive and explicit filters, and proved their almost-global stability with Lyapunov arguments. Their motivation was attitude estimation for small aerial robots with low-cost inertial sensors.

References

  1. Robert Mahony, Tarek Hamel and Jean-Michel Pflimlin, Nonlinear complementary filters on the special orthogonal group, IEEE Transactions on Automatic Control 53(5), 2008, Section V (the explicit complementary filter with bias correction, equation 32, Theorem 5.1 and Corollary 5.2)
  2. F. Landis Markley and John L. Crassidis, Fundamentals of Spacecraft Attitude Determination and Control, Springer, 2014, Chapter 6 (sequential attitude filtering), for the Kalman filter alternatives

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
  • at least three sources
  • a scene preset for the example