Algorithmresearch
Invariant extended Kalman filter
Also called InEKF.
Barrau and Bonnabel's EKF on a matrix Lie group with an invariant error, whose propagation does not depend on the estimate for group-affine systems.
- Time
- O(T k^3) worst
- Space
- O(k^2) extra
- Where
- T = the number of time steps; k = the dimension of the group
- Model
- Real RAM
- Properties
- deterministicnot exactonlinerecursive
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Axel Barrau, Silvère Bonnabel, 2017
The invariant extended Kalman filter, or InEKF, is an extended Kalman filter whose state lives on a matrix Lie group, such as the planar poses or the special Euclidean group , and whose error is a group difference or rather than a vector difference. Barrau and Bonnabel (2017) showed that for a wide class of dynamics, which they call group affine, this error evolves by an exactly linear law in logarithmic coordinates, whatever the estimate is. The linearization in the propagation step is then exact for the noise-free part, and with a matching measurement the gain and covariance do not depend on the estimate at all. The usual EKF evaluates its Jacobians at the estimate, so a bad estimate gives bad Jacobians; the InEKF removes that loop. It is close to the error-state Kalman filter, which also keeps a nominal state and a small error, but the InEKF chooses the error so that the dynamics leave it invariant.
In plain words
A robot that drives with odometry and gets position fixes from GPS is easy to model but hard to filter well, because heading and position are tied together by turning. A standard filter linearizes the motion around its current guess, so a wrong guess makes the filter wrong in a way that feeds on itself. This filter measures its error in the robot's own frame. With that choice, the way the error moves no longer depends on the guess, so the filter computes the same uncertainty and the same correction strength whether its guess is good or bad. In practice it recovers from large heading errors that make a standard filter diverge.
The problem
The pose moves as , where is the body twist over one step of a car and is the matrix exponential of . Odometry reads with . A position sensor reads with . Estimate with a covariance, online. The filter writes the true pose as and keeps the covariance of the error . Here is the inverse of the left-invariant error of Barrau and Bonnabel (2017); the two carry the same information.
The algorithm
Write for the adjoint matrix with and .
INEKF-STEP(χ̂, P, u_m, Q, Y, N) ▷ one odometry increment and one position fix; returns (χ̂, P)- 1
χ̂ ← χ̂ exp(u_m) ▷ propagate the estimate - 2
F ← Ad_{exp(-u_m)} - 3
P ← F P F^T + Q - 4
z ← first two entries of χ̂^{-1} (Y, 1) ▷ innovation in the body frame, R̂^T (Y - p̂) - 5
N̂ ← R̂^T N R̂ ; S ← H P H^T + N̂ - 6
K ← P H^T S^{-1} - 7
χ̂ ← χ̂ exp(K z) ▷ update on the group - 8
P ← (I - K H) P (I - K H)^T + K N̂ K^T ▷ Joseph form
Lines L1 to L3 are the prediction. The matrix comes from the identity , which holds exactly for noise-free odometry. Line L4 moves the position fix into the frame of the estimate; for the true pose the result would be , so measures the error directly and its Jacobian is the constant . Line L5 rotates the sensor noise into the same frame. When , the rotation has no effect, so , and are built only from , , and the odometry. Line L7 applies the correction on the group, so stays a valid pose.
Example
The car drives at m/s and turns at rad/s, with s and a position fix at every step. The data are exact, but the filter uses and . It starts with a heading error of rad ( degrees) and a position error of m, with .
| after correction | heading error (degrees) | position error (m) |
|---|---|---|
| 1 | 143.0 | 0.030 |
| 2 | 128.6 | |
| 5 | 36.2 | |
| 10 | 6.58 | 0.039 |
| 20 | 1.43 | |
| 50 | 0.029 | 0.0011 |
The first fix puts the position in the right place, and the heading follows as the car moves and the fixes reveal its direction. Two runs of the filter from different estimates, with the same fixes and odometry, produced the same and to . In a test with noisy data, the normalized estimation error squared averaged over 10 runs of 60 steps, close to the error dimension , which a consistent filter should give. All numbers are measurements of the code.
Correctness
The proof shows four facts for this model; the first is a theorem with no linearization at all, a case of Theorem 2 of Barrau and Bonnabel (2017).
- With exact odometry, for an error of any size and any .
- The innovation satisfies to first order, with constant .
- After line L7, the error is to first order, so line L8 gives its covariance for any gain.
- With , the sequences and do not depend on the estimates.
The correctness proof has the derivations. Barrau and Bonnabel (2017) also prove that, under conditions on the noise matrices and the observability of the system, the InEKF is a locally stable observer around any trajectory; this page does not restate the conditions.
Proof: On SE(2) with odometry and position fixes, the invariant error propagates exactly and the gain does not depend on the estimatefull
Setting. A pose is an element of the special Euclidean group , written as the matrix with a planar rotation. A tangent vector is , and is the matrix exponential of . In closed form, with and . The adjoint of is the matrix with for all .
The models are as follows. The robot moves by , where is the body twist over one step. Odometry reads with . A position sensor reads with . The filter keeps and , and its error is
This is the inverse of the left-invariant error of Barrau and Bonnabel (2017); the two carry the same information.
Assumptions.
- (X) For Claim 1: odometry is exact, .
- (L) For Claims 2 and 3: terms of second order in and in the noise are dropped, as in every extended Kalman filter.
Claim.
- Exact propagation (lines L1 to L3). If and , then for every , of any size, and whatever is. With odometry noise, to first order, where and .
- Measurement (lines L4 and L5). The innovation $z = $ the first two entries of satisfies to first order, with the constant matrix . The noise has covariance , which equals when .
- Update (lines L6 to L8). After , the new error is to first order, so the Joseph form gives its covariance for any .
- Independence. If , the sequences and depend only on , , and the odometry readings , not on the estimates or on the position readings.
Proof.
Claim 1. From and with ,
No term was dropped, so holds exactly whenever the logarithm is taken in the range where is one to one, and does not appear. This is the log-linear property of Barrau and Bonnabel (2017), Theorem 2, for this system; the dynamics are group affine. With noise, and . The last two factors equal , where is the right Jacobian of at , which is . Combining the two exponentials to first order gives . The code uses and adds (line L3), which is the first-order covariance for a short step.
Claim 2. From , the position is . The inverse of maps to , so
Since , , which is . The covariance of is , and for it is .
Claim 3. The new error is . By the Baker-Campbell-Hausdorff formula, , and with Claim 2, to first order. As for any linear Kalman update, its covariance is for every , and minimizes its trace. This is the Kalman filter step on , done by lines L6 and L8, and line L7 applies the estimate of to .
Claim 4. By induction on . is given. Line L3 computes from , and ; depends only on . Lines L5, L6 and L8 compute and from , and ; is constant, and under the hypothesis. No line that changes or reads or .
Remarks.
- Claim 4 is the main difference from the extended Kalman filter on the same system. There, and are evaluated at the estimate, so a wrong estimate gives a wrong gain, which can make the error worse. Here the gain is the same as it would be at the true pose. The tests check this: two runs from different estimates on the same data gave the same and to .
- The convergence of the filter is not part of these claims. Barrau and Bonnabel (2017) prove a stability result for the deterministic invariant filter under observability conditions; the tests measure convergence from a heading error of 143 degrees and a position error of 12.8 m.
- With an anisotropic , depends on , and Claim 4 holds only in the weaker sense that depends on the heading estimate, not on the position estimate.
Complexity
In the real RAM model, with the group of dimension , each step costs : a few products, one exponential and one solve. Over steps the time is . For a group of dimension with measurements of size at most , a step costs and the memory is for , as for any Kalman filter.
Properties
- Log-linear error (theorem). For group-affine dynamics, the noise-free error obeys a linear recursion in the Lie algebra exactly, not only to first order. A test propagated an error of size for 60 steps and matched the linear recursion to (measurement).
- Estimate-free gain (theorem, for this model). With isotropic position noise, and do not depend on .
- Consistency (measurement). The NEES of against the dimension , above.
- Stays on the group. The update multiplies by an exponential, so stays a rotation.
- Choice of error matters. A left-invariant error suits measurements of the form , such as the position fix here, where . A right-invariant error suits measurements of the form , such as a known landmark or direction seen from the body. With the other choice the Jacobian depends on the estimate again (heuristic summary of Barrau and Bonnabel, 2017).
Variants and improvements
- Other groups. The same construction runs on for a 3D pose, and on a larger matrix group that holds attitude, velocity and position together for inertial navigation.
- Attitude only. On the rotation group with direction measurements, the invariant filter is close to the multiplicative filter of the error-state Kalman filter page, which also uses a group error.
- Biases. Sensor biases do not fit the group structure. The usual remedy is to carry them as an extra vector state; the error then loses part of its invariance, and the exactness results hold only in part (heuristic).
- SLAM. Landmark positions can be added to the group, which gives an invariant form of EKF SLAM (heuristic; this page does not cover it).
When to use it
Use it when the state is a pose or another matrix Lie group element, the dynamics are group affine (rigid-body kinematics, odometry, inertial navigation with gravity), and the measurements are of the invariant form, for example position fixes, landmark bearings in the body frame or known directions. It is most useful when the initial heading is poor, where a standard EKF can diverge. When the system is not group affine, the gain still uses a group error, but the exactness results do not apply.
Pitfalls
- Left and right. The error convention, the side of the exponential in the update and the form of must agree. Mixing a right update with a left error gives a filter that runs but is wrong.
- Rotating the noise. The measurement noise in the body frame is . Using directly is correct only when is isotropic.
- Noise Jacobian. The odometry noise enters through a Jacobian close to for small steps. Using directly, as in line L3, is the common first-order choice.
- Not a global guarantee. The stability results are local. In the example the filter recovered from degrees, but that is a measurement, not a theorem.
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/invariant-extended-kalman-filter/. The authors are listed in prov/5ADY95.jsonl.
"""An invariant extended Kalman filter for a planar robot with GPS.
Vectors are lists of floats and matrices are lists of rows, as in rbm.py.
The state is a pose chi = (R(theta), p) in SE(2), stored as the 3x3 matrix
[[R, p], [0, 1]]. A tangent vector is xi = (xi_theta, xi_x, xi_y), and
exp(xi) is the matrix exponential of [[0, -xi_theta, xi_x],
[xi_theta, 0, xi_y], [0, 0, 0]].
Motion: chi_{k+1} = chi_k exp(u_k), where u_k is the body twist increment
over one step (for a car, u = (omega dt, v dt, 0)). Odometry reads
u_m = u + n with n ~ N(0, Q). GPS reads Y = p + V with V ~ N(0, N).
The error is e = chi_hat^-1 chi = exp(xi), so chi = chi_hat exp(xi). This is
the inverse of the left-invariant error eta^L = chi^-1 chi_hat of Barrau and
Bonnabel (2017). With noise-free odometry it evolves as
xi_{k+1} = Ad_{exp(-u_m)} xi_k exactly, whatever chi_hat is.
"""
import math
import rbm
SERIES = 1e-4 # below this |theta|, the coefficient functions use series
def _coeffs(t):
"""Return (sin t / t, (1 - cos t) / t)."""
if abs(t) < SERIES:
t2 = t * t
return 1.0 - t2 / 6.0 + t2 * t2 / 120.0, t / 2.0 - t * t2 / 24.0
return math.sin(t) / t, (1.0 - math.cos(t)) / t
def se2_exp(xi):
"""Return exp(xi) as a 3x3 matrix, with p = V(theta) (xi_x, xi_y)."""
t, x, y = xi
a, b = _coeffs(t)
c, s = math.cos(t), math.sin(t)
return [[c, -s, a * x - b * y], [s, c, b * x + a * y], [0.0, 0.0, 1.0]]
def se2_log(m):
"""Return xi with exp(xi) = m and xi_theta in (-pi, pi]."""
t = math.atan2(m[1][0], m[0][0])
px, py = m[0][2], m[1][2]
if abs(t) < SERIES:
h = 1.0 - t * t / 12.0
else:
h = (t / 2.0) * math.sin(t) / (1.0 - math.cos(t)) # (t/2) cot(t/2)
# V^-1 = [[h, t/2], [-t/2, h]]
return [t, h * px + (t / 2.0) * py, -(t / 2.0) * px + h * py]
def se2_inv(m):
"""Return the inverse [[R^T, -R^T p], [0, 1]]."""
c, s = m[0][0], m[1][0]
px, py = m[0][2], m[1][2]
return [[c, s, -(c * px + s * py)], [-s, c, s * px - c * py], [0.0, 0.0, 1.0]]
def se2_adjoint(m):
"""Return Ad_m = [[1, 0, 0], [p_y, R], [-p_x, R]], so that m exp(xi) m^-1 = exp(Ad_m xi)."""
c, s = m[0][0], m[1][0]
px, py = m[0][2], m[1][2]
return [[1.0, 0.0, 0.0], [py, c, -s], [-px, s, c]]
def inekf_predict(chi, p, u_m, q):
"""Return (chi, P) after one odometry increment u_m with noise covariance q."""
chi = rbm.mul(chi, se2_exp(u_m)) # @line L1
f = se2_adjoint(se2_exp([-x for x in u_m])) # @line L2
p = rbm.add(rbm.mul(rbm.mul(f, p), rbm.transpose(f)), q) # @line L3
return chi, p
H = [[0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
def inekf_correct(chi, p, y, n):
"""Return (chi, P, K) after one GPS reading y with noise covariance n (2x2)."""
inv = se2_inv(chi)
z = [inv[0][0] * y[0] + inv[0][1] * y[1] + inv[0][2], inv[1][0] * y[0] + inv[1][1] * y[1] + inv[1][2]] # @line L4
r = [[chi[0][0], chi[0][1]], [chi[1][0], chi[1][1]]]
n_hat = rbm.mul(rbm.mul(rbm.transpose(r), n), r) # R^T N R, equal to N if N is isotropic # @line L5
ht = rbm.transpose(H)
s = rbm.add(rbm.mul(rbm.mul(H, p), ht), n_hat) # @line L5
pht = rbm.mul(p, ht)
k = rbm.transpose(rbm.solve(s, rbm.transpose(pht))) # K = P H^T S^-1 # @line L6
chi = rbm.mul(chi, se2_exp(rbm.matvec(k, z))) # @line L7
ikh = rbm.sub(rbm.eye(3), rbm.mul(k, H))
p = rbm.add(rbm.mul(rbm.mul(ikh, p), rbm.transpose(ikh)), rbm.mul(rbm.mul(k, n_hat), rbm.transpose(k))) # @line L8
return chi, p, k
def pose(theta, x, y):
"""Return the SE(2) matrix of the pose (theta, x, y)."""
c, s = math.cos(theta), math.sin(theta)
return [[c, -s, x], [s, c, y], [0.0, 0.0, 1.0]]
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_invariant_extended_kalman_filter.py 161 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/invariant-extended-kalman-filter/. The authors are listed in prov/5ADY95.jsonl.
import math
import random
import pytest
import rbm
import robest
from invariant_extended_kalman_filter import (
H,
inekf_correct,
inekf_predict,
pose,
se2_adjoint,
se2_exp,
se2_inv,
se2_log,
)
DT = 0.1
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 diag(values):
return [[values[i] if i == j else 0.0 for j in range(len(values))] for i in range(len(values))]
def twist(k):
"""The body twist increment of a car at step k: (omega dt, v dt, 0)."""
return [0.3 * math.sin(0.05 * k) * DT, 1.0 * DT, 0.0]
def error_of(chi_hat, chi):
return se2_log(rbm.mul(se2_inv(chi_hat), chi))
def test_exp_log_and_adjoint():
rng = random.Random(1)
for _ in range(200):
xi = [rng.uniform(-3.0, 3.0), rng.uniform(-5.0, 5.0), rng.uniform(-5.0, 5.0)]
assert max(abs(a - b) for a, b in zip(se2_log(se2_exp(xi)), xi)) < 1e-12
small = [x * 1e-6 for x in xi]
assert max(abs(a - b) for a, b in zip(se2_log(se2_exp(small)), small)) < 1e-18
m = pose(rng.uniform(-3.0, 3.0), rng.uniform(-5.0, 5.0), rng.uniform(-5.0, 5.0))
lhs = rbm.mul(rbm.mul(m, se2_exp(xi)), se2_inv(m))
assert max_diff(lhs, se2_exp(rbm.matvec(se2_adjoint(m), xi))) < 1e-12
assert max_diff(rbm.mul(m, se2_inv(m)), rbm.eye(3)) < 1e-14
def test_propagation_jacobian_and_observation_matrix():
u = [0.4, 0.9, -0.3]
num_f = rbm.num_jacobian(lambda xi: se2_log(rbm.mul(rbm.mul(se2_exp([-x for x in u]), se2_exp(xi)), se2_exp(u))), [0.0] * 3)
assert max_diff(num_f, se2_adjoint(se2_exp([-x for x in u]))) < 1e-8
chi_hat = pose(1.2, 3.0, -4.0)
def innovation(xi):
chi = rbm.mul(chi_hat, se2_exp(xi))
y = [chi[0][2], chi[1][2]]
inv = se2_inv(chi_hat)
return [inv[0][0] * y[0] + inv[0][1] * y[1] + inv[0][2], inv[1][0] * y[0] + inv[1][1] * y[1] + inv[1][2]]
assert max_diff(rbm.num_jacobian(innovation, [0.0] * 3), H) < 1e-8
def test_log_linear_error_is_exact_for_a_large_error():
# Barrau and Bonnabel, Theorem 2: for group affine dynamics the error
# follows the linear recursion exactly, not only to first order.
chi_hat = pose(0.5, 1.0, 2.0)
xi = [1.0, 2.0, -1.5]
chi = rbm.mul(chi_hat, se2_exp(xi))
for k in range(60):
u = twist(k)
chi_hat, _ = inekf_predict(chi_hat, rbm.eye(3), u, rbm.zeros(3, 3))
chi = rbm.mul(chi, se2_exp(u))
xi = rbm.matvec(se2_adjoint(se2_exp([-x for x in u])), xi)
assert max(abs(a - b) for a, b in zip(error_of(chi_hat, chi), xi)) < 1e-9
def run_filter(chi_hat, p, ys, q, n):
gains = []
for k, y in enumerate(ys):
chi_hat, p = inekf_predict(chi_hat, p, twist(k), q)
chi_hat, p, kk = inekf_correct(chi_hat, p, y, n)
gains.append(kk)
return chi_hat, p, gains
def test_gain_and_covariance_do_not_depend_on_the_estimate():
rng = random.Random(2)
ys = [[rng.uniform(-10.0, 10.0), rng.uniform(-10.0, 10.0)] for _ in range(40)]
q = diag([0.01 ** 2, 0.05 ** 2, 0.02 ** 2])
n = diag([0.5 ** 2, 0.5 ** 2])
p0 = diag([0.5, 4.0, 4.0])
_, p1, k1 = run_filter(pose(0.0, 0.0, 0.0), p0, ys, q, n)
_, p2, k2 = run_filter(pose(2.8, -30.0, 17.0), p0, ys, q, n)
assert max_diff(p1, p2) < 1e-12
assert max(max_diff(a, b) for a, b in zip(k1, k2)) < 1e-12
def test_converges_from_a_large_error_with_exact_data():
chi = pose(0.0, 0.0, 0.0)
chi_hat = pose(2.5, 10.0, -8.0)
p = diag([math.pi ** 2, 100.0, 100.0])
q = diag([0.01 ** 2, 0.01 ** 2, 0.01 ** 2])
n = diag([0.1 ** 2, 0.1 ** 2])
for k in range(150):
u = twist(k)
chi_hat, p = inekf_predict(chi_hat, p, u, q)
chi = rbm.mul(chi, se2_exp(u))
chi_hat, p, _ = inekf_correct(chi_hat, p, [chi[0][2], chi[1][2]], n)
err = error_of(chi_hat, chi)
assert abs(err[0]) < 1e-3
assert math.hypot(err[1], err[2]) < 1e-2
def test_nees_is_near_the_state_dimension():
# Measurement: average NEES over 10 runs of 60 steps. A consistent
# filter gives about 3. The bound is loose and labeled as a measurement.
rng = random.Random(3)
q = diag([0.02 ** 2, 0.05 ** 2, 0.05 ** 2])
n = diag([0.3 ** 2, 0.3 ** 2])
p0 = diag([0.3 ** 2, 1.0, 1.0])
total, count = 0.0, 0
for _ in range(10):
chi = pose(0.0, 0.0, 0.0)
chi_hat = rbm.mul(chi, se2_exp([-x for x in robest.gauss_sample(rng, [0.0] * 3, p0)]))
p = [row[:] for row in p0]
for k in range(60):
u = twist(k)
u_m = robest.gauss_sample(rng, u, q)
chi_hat, p = inekf_predict(chi_hat, p, u_m, q)
chi = rbm.mul(chi, se2_exp(u))
y = robest.gauss_sample(rng, [chi[0][2], chi[1][2]], n)
chi_hat, p, _ = inekf_correct(chi_hat, p, y, n)
total += robest.mahalanobis2(error_of(chi_hat, chi), [0.0] * 3, p)
count += 1
mean = total / count
assert 1.5 < mean < 5.0
def test_covariance_stays_symmetric_positive_definite():
rng = random.Random(4)
p = diag([1.0, 1.0, 1.0])
chi_hat = pose(0.0, 0.0, 0.0)
q = diag([1e-4, 1e-3, 1e-3])
n = diag([0.01, 0.01])
for k in range(50):
chi_hat, p = inekf_predict(chi_hat, p, twist(k), q)
chi_hat, p, _ = inekf_correct(chi_hat, p, [rng.uniform(-1, 1), rng.uniform(-1, 1)], n)
assert max_diff(p, rbm.transpose(p)) < 1e-14
rbm.cholesky(p)
def test_singular_innovation_covariance_is_rejected():
with pytest.raises(ValueError):
inekf_correct(pose(0.0, 0.0, 0.0), rbm.zeros(3, 3), [1.0, 1.0], rbm.zeros(2, 2))
History
Bonnabel, with Martin and Rouchon, worked on observers that keep the symmetries of the system in the 2000s, and this led to invariant versions of the extended Kalman filter. Barrau and Bonnabel (2017) gave the general group-affine framework, the log-linear property and stability proofs, and their car example with odometry and position fixes is the model on this page. Their filter has since been used for inertial navigation and for legged and wheeled robots.
References
- Axel Barrau and Silvère Bonnabel, The invariant extended Kalman filter as a stable observer, IEEE Transactions on Automatic Control 62(4), 2017, pages 1797 to 1812, Theorem 2 (the log-linear property of the invariant error for group-affine systems), the definitions of the left and right invariant filters, and the stability results
- Axel Barrau and Silvère Bonnabel, The invariant extended Kalman filter as a stable observer, arXiv:1410.1465, Section 4 (the car example with odometry and position measurements)
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 5ADY95 Edit this page History Report an error Markdown