Algorithmadvanced
Error-state Kalman filter
Also called ESKF, indirect Kalman filter.
Propagates a nominal state with the full model and a small error state with a Kalman filter, then folds the error into the nominal.
- Time
- O(T + m) worst
- Space
- O(1) extra
- Where
- T = the number of gyro samples; m = the number of vector measurements
- Model
- Real RAM
- Properties
- deterministicnot exactonlinerecursive
- Evidence
- Proof sketchCode in 1 languages
- Origin
- E. J. Lefferts, F. Landis Markley, Malcolm D. Shuster, 1982
The error-state Kalman filter splits the state in two. A nominal state, here a unit quaternion for the attitude and a gyro bias, is propagated with the full nonlinear model and no noise. A small error state, three angles and three bias errors, is estimated by a linear Kalman filter. After each correction, the estimated error is folded into the nominal state and reset to zero. Because the error is small and lives in a vector space of the right dimension, the linearization is accurate and the covariance has no constraint to respect, unlike a filter on the four quaternion numbers. For attitude with a gyro bias, this is the multiplicative extended Kalman filter of spacecraft practice, and the same design runs inside most visual-inertial and lidar-inertial odometry systems. The extended Kalman filter is the general method it refines; the invariant extended Kalman filter picks a different error so that its dynamics do not depend on the estimate.
In plain words
Tracking an orientation with a standard estimator is awkward, because an orientation is not a plain list of numbers that can be added and averaged. This filter avoids the problem. It keeps a best guess of the orientation and moves it forward with the gyro readings, exactly as if they were perfect. Next to it, it keeps a small correction, a few angles, together with a measure of how unsure it is about that correction. Small angles do behave like plain numbers, so the standard estimator works well on them. When another sensor, such as gravity or a compass, gives new information, the filter updates the small correction, applies it to the best guess, and starts again with a zero correction.
The problem
The attitude , with quaternion , and the gyro bias evolve as follows over a sample of length . The gyro reads with white noise of standard deviation per axis; the truth turns by ; the bias walks as with of variance per axis. A vector sensor reads for a known unit direction , with noise of standard deviation per axis. Estimate with a covariance, online. The error state is with and , the local error of Solà (2017).
The algorithm
Write for the unit quaternion of the rotation vector , for its rotation matrix, and for the rotation of .
ESKF-STEP(q, b, P, ω_m, δt, {(y, d)}) ▷ one gyro sample, then any direction measurements; returns (q, b, P)- 1
ω̂ ← ω_m - b - 2
q ← q ⊗ q{ω̂ δt}, normalized ▷ nominal state, no noise - 3
F ← [[Exp(ω̂ δt)^T, -I δt], [0, I]] - 4
P ← F P F^T + diag(σ_g² δt² I, σ_w² δt I) - 5
for each measured direction (y, d) do ŷ ← R(q)^T d - 6
H ← [[ŷ]_×, 0] - 7
K ← P H^T (H P H^T + σ_v² I)^{-1} - 8
(δθ̂, δb̂) ← K (y - ŷ) - 9
P ← (I - K H) P (I - K H)^T + σ_v² K K^T ▷ Joseph form - 10
q ← q ⊗ q{δθ̂}, normalized ; b ← b + δb̂ ▷ injection - 11
G ← diag(I - [½ δθ̂]_×, I) ; P ← G P G^T ▷ reset, δx̂ ← 0
Lines L1 to L4 are the prediction. The nominal state takes the whole motion, and the error state has mean zero, so only its covariance moves. The block is exact to first order in the error; the block replaces , with the right Jacobian of , which is accurate when is small. Lines L5 to L9 are a linear Kalman correction of the error state with the measurement Jacobian of the Jacobian linearization. Line L10 moves the estimated error into the nominal state, and line L11 accounts for the change of the error's reference frame. A filter without line L11, , is a common and usually harmless simplification.
Example
The body turns with rad/s. The gyro runs at 100 Hz with rad/s, the bias walk has , and every s two directions are measured, and , with . The filter starts degrees off with zero bias error and .
| time (s) | attitude error (degrees) |
|---|---|
| 0.1 (after the first correction) | 7.29 |
| 0.2 | 2.15 |
| 0.5 | 1.85 |
| 1 | 2.62 |
| 2 | 2.02 |
| 4 | 0.86 |
The first correction removes three quarters of the error. After that the error stays at the level the noise allows; at s the filter's own standard deviation of each angle is about to degrees, and the bias error is rad/s. The normalized estimation error squared, which a consistent filter keeps near the error dimension , averaged , and for three random seeds over runs of s each. All numbers are measurements of the code.
Correctness
The filter is correct in the sense of every extended Kalman filter: each line is exact for the first-order model of the error. The proof derives that model. The prediction Jacobian follows from and the identity . The measurement Jacobian follows from . The reset Jacobian is the right Jacobian . The Joseph form gives the error covariance for any gain and stays symmetric positive semidefinite. These are theorems under the assumption that second-order terms can be dropped; the correctness proof has the derivations. Convergence and consistency are not theorems here; the example measures them.
Proof: The error-state Kalman filter uses the first-order model of the attitude and bias errorfull
Setting. The true state is a rotation (with unit quaternion ) and a gyro bias . The filter keeps a nominal state with rotation , and a covariance of the error state , defined by
where is the exponential map from a rotation vector to and is its inverse near the identity. This is the local error of Sola (2017). The right Jacobian of is defined by , and . For a rotation , .
The models are as follows. Over one sample of length the gyro reads , where is the true body rate, constant over the sample, and is white with covariance . The truth moves by and with white of covariance . A vector sensor reads for a known unit direction , with white of covariance .
Assumptions.
- (L) The error and the noise are small enough that terms of second order in them can be dropped. This is the standing assumption of every extended Kalman filter.
- (W) is small, so that .
Claim. To first order in and the noise:
- Prediction (lines L1 to L4). With , the nominal step , gives with
and under (W) the code uses for the top right block. 2. Measurement (lines L5 and L6). With , with . 3. Update (lines L7 to L9). Given the linear model of Claim 2 and a prior , the vector with is the linear minimum mean-square estimate of , and the Joseph form is the covariance of its error. It is symmetric and positive semidefinite for any . 4. Injection and reset (lines L10 and L11). After and , the new error is with , and equals up to .
Proof.
Claim 1. The true rate over the sample is . So
By the definition of , the last factor is to first order. With , . So , and to first order . The bias error is . The noise term has covariance . Lines L3 and L4 apply , which is the covariance of when is independent of . The mean of stays , so no mean is propagated: the nominal step of line L2 carries it.
Claim 2. . The bias does not enter the measurement.
Claim 3. For a zero-mean with covariance , independent noise , and , the error of the estimate is . Its covariance is for every , which is the Joseph form; as a sum of two matrices of the form with , it is symmetric and positive semidefinite. The that minimizes its trace is , by the derivation of the Kalman filter. is positive definite when , so the inverse exists.
Claim 4. After injection, write . The new error satisfies . So to first order in . For the bias, exactly. The covariance of is (line L11), and the mean of is again.
Remarks.
- The claims are first-order statements. They do not prove that the filter converges or that matches the true error. Those are measurements in the tests: from 30 degrees of initial error the attitude error fell below 1.5 degrees within 4 s, and the mean of the normalized estimation error squared over 4 runs was between 3 and 12 for a 6-dimensional error.
- The code keeps the quaternion of , multiplies by for , and renormalizes after each product. This changes nothing in exact arithmetic.
- The test of the prediction Jacobian compares with finite differences. The rotation block matches to ; the bias block differs from the finite differences by about , which is the term dropped under (W).
Complexity
In the real RAM model, with the state size fixed at 6, a prediction costs : two products and one exponential. A correction costs : a solve and a few products. Over gyro samples and measurements the time is , and the memory is . For a general error state of dimension with measurements of dimension , a step costs , as for any Kalman filter.
Properties
- Minimal error. The error has 3 attitude components, the number of degrees of freedom, so is and has no singular direction from a unit-norm constraint.
- Small error, accurate linearization (heuristic). The error stays near zero, far from any singularity of the parametrization, and the Jacobians are evaluated where the linear model is best.
- Unit quaternion. The nominal quaternion is renormalized after each product; after 200 steps its norm differed from by less than (measurement).
- Partial observability. One direction says nothing about rotation about itself, because . If the attitude block of is a multiple of and has no correlation with the bias, a correction with leaves the variance of the error about unchanged (theorem from ; also a test). With correlations, the other states can still carry some information about that angle.
- Jacobians match. The rotation block of and the matrix matched finite differences to ; the bias block differed by about , the term dropped in (measurement).
Variants and improvements
- Global error. With the error is expressed in the space frame. The Jacobians change, and Solà (2017), Section 7, gives them.
- Full inertial state. Add position, velocity and accelerometer bias to the nominal and error states for inertial navigation; the same three phases (predict, correct, inject and reset) apply.
- Invariant error. Choosing the error as a group difference that the dynamics leave invariant gives the invariant extended Kalman filter, whose error propagation does not depend on the estimate.
- Sigma points. An unscented Kalman filter on the same error state avoids the Jacobians.
- No covariance. When no covariance is needed, the nonlinear complementary filter solves the same problem with two gains.
When to use it
Use it when the attitude, or a pose, must be fused with other states and sensors under a stated noise model, and an uncertainty is needed, for example in visual-inertial odometry or spacecraft attitude determination. It is the default design when the state contains rotations. For very large initial errors, where first-order models fail, start it from a static solution of Wahba's problem or use a filter with a global convergence proof.
Pitfalls
- Quaternion conventions. Hamilton and JPL quaternions multiply in opposite orders, and a local error in one is a global error in the other. Solà (2017) uses Hamilton; Trawny and Roumeliotis (2005) use JPL. Mixing formulas from the two breaks the filter silently.
- Noise units. A gyro data sheet gives a noise density in rad/s per square root of Hz. The variance per sample of length is then density for the rate, or density for the angle. The code takes as the standard deviation per sample of the rate, so the angle variance is .
- Forgetting the injection. If the estimated error is not moved into the nominal state, the error state no longer has mean zero and the prediction is wrong.
- Symmetry of . The form loses symmetry and definiteness in floating point. The Joseph form of line L9 keeps both.
- Large errors. With an error of tens of degrees, the first-order model is poor. The example converged from degrees, but no theorem promises it.
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/error-state-kalman-filter/. The authors are listed in prov/2VDFY7.jsonl.
"""An error-state Kalman filter for attitude and gyro bias.
Vectors are lists of floats and matrices are lists of rows, as in rbm.py.
The nominal state is a unit Hamilton quaternion q (scalar first) of R_sb,
the attitude of the body in the space frame, and a gyro bias b. The error
state is dx = (dtheta, db) with the local (right) convention of Sola (2017):
q_true = q (x) q{dtheta}, b_true = b + db,
where q{v} is the unit quaternion of the rotation vector v. A gyro reads
omega_m = omega + b_true + n with white noise n of standard deviation
sigma_g (rad/s) per sample, and the bias drifts as a random walk with
standard deviation sigma_w sqrt(dt). A vector sensor reads the body form
y = R_true^T d + v of a known unit direction d in {s}, with white noise v
of standard deviation sigma_v per axis.
The filter keeps the nominal state outside the Kalman filter and runs a
linear Kalman filter on dx, whose mean is zero between corrections.
"""
import rbm
def quat_of_rotvec(v):
"""Return q{v} = (cos(|v|/2), sin(|v|/2) v/|v|), with q{0} = (1, 0, 0, 0)."""
return rbm.quat_from_axis_angle(v, rbm.norm(v))
def _normalize(q):
n = rbm.norm(q)
return [x / n for x in q]
def _block(a, b, c, d):
"""Return the 6x6 matrix [[a, b], [c, d]] from four 3x3 blocks."""
return [a[i] + b[i] for i in range(3)] + [c[i] + d[i] for i in range(3)]
def eskf_predict(q, b, p, omega_m, dt, sigma_g, sigma_w):
"""Return (q, b, P) after one gyro sample of length dt."""
w = rbm.sub(omega_m, b) # @line L1
wdt = rbm.scale(w, dt)
q = _normalize(rbm.quat_mul(q, quat_of_rotvec(wdt))) # @line L2
z3 = rbm.zeros(3, 3)
f = _block(rbm.transpose(rbm.so3_exp(wdt)), rbm.scale(rbm.eye(3), -dt), z3, rbm.eye(3)) # @line L3
qg = sigma_g * sigma_g * dt * dt
qw = sigma_w * sigma_w * dt
p = rbm.mul(rbm.mul(f, p), rbm.transpose(f)) # @line L4
for i in range(3):
p[i][i] += qg # @line L4
p[i + 3][i + 3] += qw # @line L4
return q, list(b), p
def eskf_correct(q, b, p, y, d, sigma_v):
"""Return (q, b, P) after one direction measurement y of the known direction d."""
y_hat = rbm.matvec(rbm.transpose(rbm.quat_to_rot(q)), d) # @line L5
h = [row + [0.0, 0.0, 0.0] for row in rbm.hat3(y_hat)] # @line L6
ht = rbm.transpose(h)
s = rbm.mul(rbm.mul(h, p), ht)
for i in range(3):
s[i][i] += sigma_v * sigma_v
pht = rbm.mul(p, ht)
k = rbm.transpose(rbm.solve(s, rbm.transpose(pht))) # K = P H^T S^-1, S symmetric # @line L7
dx = rbm.matvec(k, rbm.sub(y, y_hat)) # @line L8
ikh = rbm.sub(rbm.eye(6), rbm.mul(k, h))
p = rbm.mul(rbm.mul(ikh, p), rbm.transpose(ikh)) # @line L9
kkt = rbm.mul(k, rbm.transpose(k))
p = rbm.add(p, rbm.scale(kkt, sigma_v * sigma_v)) # Joseph form # @line L9
dtheta, db = dx[:3], dx[3:]
q = _normalize(rbm.quat_mul(q, quat_of_rotvec(dtheta))) # @line L10
b = rbm.add(b, db) # @line L10
g = rbm.sub(rbm.eye(3), rbm.hat3(rbm.scale(dtheta, 0.5)))
z3 = rbm.zeros(3, 3)
gm = _block(g, z3, z3, rbm.eye(3)) # @line L11
p = rbm.mul(rbm.mul(gm, p), rbm.transpose(gm)) # @line L11
return q, b, p
def attitude_error(q_true, q):
"""Return dtheta with q_true = q (x) q{dtheta} (the local attitude error)."""
r = rbm.mul(rbm.transpose(rbm.quat_to_rot(q)), rbm.quat_to_rot(q_true))
return rbm.so3_log(r)
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
robest.py 149 lines
# SPDX-License-Identifier: MIT
# Shared helper of the robotics pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small estimation helpers for the localization and SLAM pages.
Vectors are lists of floats and matrices are lists of rows, as in rbm.py.
The notation follows Thrun, Burgard and Fox, Probabilistic Robotics (2005).
wrap_angle(a) a wrapped to [-pi, pi)
gauss_sample(rng, mean, cov) one draw of N(mean, cov), by a Cholesky factor
gauss_pdf(x, mean, cov) the density of N(mean, cov) at x
mahalanobis2(x, mean, cov) (x - mean)^T cov^(-1) (x - mean)
low_variance_resample(rng, w) indices of a systematic (low variance) resample
logodds(p), prob_from_logodds(l) l = log(p / (1 - p)) and its inverse
CHI2[(dof, level)] chi-square quantiles for gates, dof 1 to 3
gauss_pdf and mahalanobis2 also take plain numbers: then cov is a variance.
This module holds no filter, no SLAM back end and no planner.
"""
import math
import rbm
CHI2 = {
(1, 0.95): 3.841,
(1, 0.99): 6.635,
(2, 0.95): 5.991,
(2, 0.99): 9.210,
(3, 0.95): 7.815,
(3, 0.99): 11.345,
}
_TWO_PI = 2.0 * math.pi
def wrap_angle(a):
"""Return a + 2 pi k in [-pi, pi), with ((a + pi) mod 2 pi) - pi.
An angle that is already in [-pi, pi) comes back unchanged, so that
small angles keep all their digits.
"""
if -math.pi <= a < math.pi:
return float(a)
w = math.fmod(a + math.pi, _TWO_PI)
if w < 0.0:
w += _TWO_PI
w -= math.pi
if w >= math.pi: # rounding can give exactly pi
w -= _TWO_PI
return w
def _as_vector(x):
if isinstance(x, (int, float)):
return [float(x)], True
return [float(v) for v in x], False
def _as_matrix(cov, scalar):
if scalar:
if isinstance(cov, (int, float)):
return [[float(cov)]]
return [[float(cov[0][0])]]
return [[float(v) for v in row] for row in cov]
def gauss_sample(rng, mean, cov):
"""Draw x = mean + L z, with cov = L L^T and z standard normal.
rng is a random.Random. cov must be symmetric positive definite.
A number for mean (with a variance for cov) gives a number.
"""
mu, scalar = _as_vector(mean)
if scalar:
var = float(cov) if isinstance(cov, (int, float)) else float(cov[0][0])
if var < 0.0:
raise ValueError("negative variance")
return mu[0] + math.sqrt(var) * rng.gauss(0.0, 1.0)
L = rbm.cholesky(_as_matrix(cov, False))
z = [rng.gauss(0.0, 1.0) for _ in mu]
return [mu[i] + sum(L[i][j] * z[j] for j in range(i + 1)) for i in range(len(mu))]
def mahalanobis2(x, mean, cov):
"""Return the squared Mahalanobis distance (x - mean)^T cov^(-1) (x - mean)."""
xv, scalar = _as_vector(x)
mv, _ = _as_vector(mean)
if len(xv) != len(mv):
raise ValueError("x and mean differ in size")
d = [a - b for a, b in zip(xv, mv)]
S = _as_matrix(cov, scalar)
if len(d) == 1:
return d[0] * d[0] / S[0][0]
y = rbm.solve(S, d)
return sum(a * b for a, b in zip(d, y))
def gauss_pdf(x, mean, cov):
"""Return the density of N(mean, cov) at x."""
xv, scalar = _as_vector(x)
S = _as_matrix(cov, scalar)
k = len(xv)
det = S[0][0] if k == 1 else rbm.det(S)
if det <= 0.0:
raise ValueError("covariance is not positive definite")
m2 = mahalanobis2(xv, mean if not scalar else [mean], S)
return math.exp(-0.5 * m2) / math.sqrt((_TWO_PI ** k) * det)
def low_variance_resample(rng, weights):
"""Return len(weights) indices drawn by the low variance sampler.
This is systematic resampling (Thrun et al. 2005, Table 4.4): one
uniform offset r in [0, 1/N), and the N points r + m / N select the
indices through the cumulative weights. The weights need not sum to 1.
"""
n = len(weights)
if n == 0:
return []
total = float(sum(weights))
if total <= 0.0 or any(w < 0.0 for w in weights):
raise ValueError("weights must be nonnegative with a positive sum")
r = rng.random() / n
c = weights[0] / total
i = 0
out = []
for m in range(n):
u = r + m / n
while u > c and i < n - 1:
i += 1
c += weights[i] / total
out.append(i)
return out
def logodds(p):
"""Return log(p / (1 - p)) for p in (0, 1)."""
if not 0.0 < p < 1.0:
raise ValueError("p must be in (0, 1)")
return math.log(p / (1.0 - p))
def prob_from_logodds(l):
"""Return p = 1 - 1 / (1 + exp(l)), the inverse of logodds, without overflow."""
if l >= 0.0:
return 1.0 / (1.0 + math.exp(-l))
e = math.exp(l)
return e / (1.0 + e)
test_error_state_kalman_filter.py 154 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/error-state-kalman-filter/. The authors are listed in prov/2VDFY7.jsonl.
import math
import random
import pytest
import rbm
import robest
from error_state_kalman_filter import attitude_error, eskf_correct, eskf_predict, quat_of_rotvec
DIRS = [[0.0, 0.0, 1.0], [1.0, 0.0, 0.0]]
DT = 0.01
SIGMA_G = 0.05
SIGMA_W = 0.002
SIGMA_V = 0.05
def max_diff(a, b):
return max(abs(a[i][j] - b[i][j]) for i in range(len(a)) for j in range(len(a[0])))
def omega_at(t):
return [0.4 * math.sin(0.7 * t), 0.3 * math.cos(0.4 * t), 0.2]
def diag(values):
return [[values[i] if i == j else 0.0 for j in range(len(values))] for i in range(len(values))]
def test_predict_jacobian_matches_finite_differences():
q = rbm.quat_from_axis_angle([0.3, -0.5, 0.8], 1.1)
b = [0.02, -0.01, 0.03]
omega_m = [0.9, -0.4, 0.6]
dt = 0.01
def propagate_error(dx):
q_t = rbm.quat_mul(q, quat_of_rotvec(dx[:3]))
b_t = rbm.add(b, dx[3:])
q_t1 = rbm.quat_mul(q_t, quat_of_rotvec(rbm.scale(rbm.sub(omega_m, b_t), dt)))
q1 = rbm.quat_mul(q, quat_of_rotvec(rbm.scale(rbm.sub(omega_m, b), dt)))
return attitude_error(q_t1, q1) + list(dx[3:])
num = rbm.num_jacobian(propagate_error, [0.0] * 6, h=1e-6)
_, _, f = eskf_predict(q, b, rbm.eye(6), omega_m, dt, 0.0, 0.0)
# With P = I and Q = 0 the predicted covariance is F F^T. Rebuild F itself:
wdt = rbm.scale(rbm.sub(omega_m, b), dt)
rt = rbm.transpose(rbm.so3_exp(wdt))
f_model = [rt[i] + [(-dt if i == j else 0.0) for j in range(3)] for i in range(3)]
f_model += [[0.0] * 3 + [1.0 if i == j else 0.0 for j in range(3)] for i in range(3)]
assert max_diff(rbm.mul(f_model, rbm.transpose(f_model)), f) < 1e-15
# The rotation block is exact; the bias block -I dt is the first-order
# form of -J_r(omega dt) dt, off by about |omega| dt^2 / 2.
assert max_diff([row[:3] for row in num[:3]], [row[:3] for row in f_model[:3]]) < 1e-8
assert max_diff(num, f_model) < 1e-4
def test_measurement_jacobian_matches_finite_differences():
q = rbm.quat_from_axis_angle([-0.2, 0.7, 0.4], 2.0)
for d in DIRS + [[0.6, -0.48, 0.64]]:
def h_of(dx):
r = rbm.quat_to_rot(rbm.quat_mul(q, quat_of_rotvec(dx[:3])))
return rbm.matvec(rbm.transpose(r), d)
num = rbm.num_jacobian(h_of, [0.0] * 6, h=1e-6)
y_hat = h_of([0.0] * 6)
h = [row + [0.0, 0.0, 0.0] for row in rbm.hat3(y_hat)]
assert max_diff(num, h) < 1e-8
def test_reset_jacobian():
a = [0.01, -0.02, 0.015]
def reset(dtheta):
return attitude_error(quat_of_rotvec(dtheta), quat_of_rotvec(a))
num = rbm.num_jacobian(reset, a, h=1e-7)
g = rbm.sub(rbm.eye(3), rbm.hat3(rbm.scale(a, 0.5)))
assert max_diff(num, g) < 1e-3 # error O(|a|^2)
assert max_diff(num, rbm.eye(3)) > 5e-3 # the identity is a worse guess
def run(rng, steps, dx0, p0, correct_every=10):
q_t = rbm.quat_from_axis_angle([0.1, 0.2, 0.9], 0.7)
b_t = [0.01, -0.02, 0.015]
q = rbm.quat_mul(q_t, quat_of_rotvec(rbm.scale(dx0[:3], -1.0)))
b = rbm.sub(b_t, dx0[3:])
p = [row[:] for row in p0]
nees = []
for k in range(steps):
om = omega_at(k * DT)
gyro = [om[i] + b_t[i] + rng.gauss(0.0, SIGMA_G) for i in range(3)]
q, b, p = eskf_predict(q, b, p, gyro, DT, SIGMA_G, SIGMA_W)
q_t = rbm.quat_mul(q_t, quat_of_rotvec(rbm.scale(om, DT)))
b_t = [x + rng.gauss(0.0, SIGMA_W * math.sqrt(DT)) for x in b_t]
if (k + 1) % correct_every == 0:
r_t = rbm.quat_to_rot(q_t)
for d in DIRS:
y = [x + rng.gauss(0.0, SIGMA_V) for x in rbm.matvec(rbm.transpose(r_t), d)]
q, b, p = eskf_correct(q, b, p, y, d, SIGMA_V)
err = attitude_error(q_t, q) + rbm.sub(b_t, b)
nees.append(robest.mahalanobis2(err, [0.0] * 6, p))
return q_t, q, b_t, b, p, nees
def test_converges_from_thirty_degrees():
rng = random.Random(1)
p0 = diag([0.3 ** 2] * 3 + [0.05 ** 2] * 3)
dx0 = [math.radians(30.0) / math.sqrt(3.0)] * 3 + [0.0, 0.0, 0.0]
q_t, q, b_t, b, p, _ = run(rng, 400, dx0, p0)
assert rbm.norm(attitude_error(q_t, q)) < math.radians(1.5)
# The covariance stays symmetric and positive definite.
assert max_diff(p, rbm.transpose(p)) < 1e-15
rbm.cholesky(p)
def test_quaternion_stays_unit():
rng = random.Random(2)
p0 = diag([0.1 ** 2] * 3 + [0.02 ** 2] * 3)
_, q, _, _, _, _ = run(rng, 200, [0.05, -0.05, 0.02, 0.0, 0.0, 0.0], p0)
assert abs(rbm.norm(q) - 1.0) < 1e-14
def test_nees_is_near_the_state_dimension():
# Measurement: average NEES over 4 runs of 20 corrections each. A
# consistent filter gives about 6, the error-state dimension. Seeds 3, 4
# and 5 gave 7.3, 5.1 and 9.0. The bound is loose because the runs are
# short and the samples are correlated.
rng = random.Random(3)
p0 = diag([0.1 ** 2] * 3 + [0.02 ** 2] * 3)
total, count = 0.0, 0
for _ in range(4):
dx0 = robest.gauss_sample(rng, [0.0] * 6, p0)
*_, nees = run(rng, 200, dx0, p0)
total += sum(nees)
count += len(nees)
mean = total / count
assert 3.0 < mean < 12.0
def test_correct_with_zero_innovation_keeps_the_mean():
q = rbm.quat_from_axis_angle([1.0, 1.0, 0.0], 0.4)
b = [0.01, 0.02, 0.03]
p = diag([0.01] * 3 + [0.001] * 3)
d = DIRS[0]
y = rbm.matvec(rbm.transpose(rbm.quat_to_rot(q)), d)
q2, b2, p2 = eskf_correct(q, b, p, y, d, SIGMA_V)
assert rbm.norm(rbm.sub(q, q2)) < 1e-15 and b2 == b
# A direction gives no information about rotation about itself.
assert rbm.dot(y, rbm.matvec([row[:3] for row in p2[:3]], y)) == pytest.approx(
rbm.dot(y, rbm.matvec([row[:3] for row in p[:3]], y)), rel=1e-12
)
assert p2[0][0] < p[0][0] or p2[1][1] < p[1][1]
History
Kalman filters that estimate the error of a navigation solution, rather than the solution itself, were used in inertial navigation from the 1960s and are called indirect filters. Lefferts, Markley and Shuster (1982) wrote the attitude version with a reference quaternion and a three-component error, which became the standard spacecraft attitude filter. Trawny and Roumeliotis (2005) and Solà (2017) wrote detailed tutorials on the design, and Solà's notes made the name error-state Kalman filter common in robotics.
References
- Joan Solà, Quaternion kinematics for the error-state Kalman filter, arXiv:1711.02508, 2017, Section 5 (error-state kinematics and the Jacobians of the discrete-time system), Sections 6.1 to 6.3 (observation, injection of the error and the reset with its Jacobian) and Section 7 (the variant with a global angular error)
- E. J. Lefferts, F. L. Markley and M. D. Shuster, Kalman filtering for spacecraft attitude estimation, Journal of Guidance, Control, and Dynamics 5(5), 1982, pages 417 to 429, the filters with a reference quaternion and a three-component attitude error, and the gyro bias in the state
- Nikolas Trawny and Stergios I. Roumeliotis, Indirect Kalman filter for 3D attitude estimation, Technical Report 2005-002, University of Minnesota, 2005, the indirect filter for attitude and gyro bias with a quaternion and a small-angle error
- F. Landis Markley and John L. Crassidis, Fundamentals of Spacecraft Attitude Determination and Control, Springer, 2014, Chapter 6 (sequential attitude filtering), the multiplicative extended Kalman filter
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 2VDFY7 Edit this page History Report an error Markdown