Algorithmadvanced
Sparse extended information filter
Also called SEIF.
Online SLAM in information form that bounds the landmarks linked to the robot. The bound gives near constant time steps, but its sparsification is an approximation that makes the map overconfident.
- Solves
- Online SLAM
- Time
- O(k^3) mean · motion · sparsificationO(1) update
- Space
- O(n^2) extra
- Where
- k = the bound on the active landmarks; n = the number of landmarks
- Model
- Real RAM
- Properties
- deterministicnot exactonlinerecursive
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Sebastian Thrun, Yufeng Liu, Daphne Koller, Andrew Y. Ng, Zoubin Ghahramani, Hugh Durrant Whyte, 2004
The sparse extended information filter (SEIF) solves online SLAM in information form, as the extended information filter (EIF) does, but it keeps the information matrix sparse. A landmark is active if links it to the robot pose. Each motion step links all active landmarks to each other, which is how the EIF matrix fills in. The SEIF keeps at most landmarks active: when there are more, a sparsification step removes the links from the pose to the oldest ones. This step is an approximation, while the EIF is exact up to linearization. With a bounded active set and sparse storage, the motion step, the update and the sparsification touch a constant number of entries. The price is an estimate that is overconfident, and a mean that the filter recovers only approximately.
In plain words
The filter keeps a table of how much it knows about the robot and about each landmark, and how they relate. When the robot drives, everything that it relates to the robot becomes related to everything else, so the table fills up and becomes slow to work with. The filter limits how many landmarks may be related to the robot at the same time. When one more is seen, it cuts the relation to the landmark seen longest ago, and moves that knowledge to the map. This cut keeps the work per step small and does not change the best guess. But it pretends that some map knowledge is exact, so the filter believes its map more than it should.
The problem
The input is the belief at time in information form, and , an estimate of the mean , the list of active landmarks, a control and the readings with known correspondences. The motion model has the noise on the pose, and a reading of landmark is with . The output is the belief at time in the same form, with at most active landmarks. The state is the pose and the landmarks, as in EKF SLAM.
The algorithm
SEIF(ξ, Ω, μ, u_t, z_t)- 1
δ, G_x ← motion offset and pose Jacobian at μ ▷ μ_x moves to μ_x + δ - 2
Φ ← Tᵀ Ω T, with T = G_x⁻¹ on the pose block and I elsewhere - 3
κ ← Φ F_xᵀ R_t (I + F_x Φ F_xᵀ R_t)⁻¹ F_x Φ - 4
ξ ← ξ + (Φ - κ - Ω) μ + (Φ - κ) F_xᵀ δ; Ω ← Φ - κ - 5
μ_x ← μ_x + δ - 6
for each reading z^i of landmark j in z_t do - 7
if m_j is new then add m_j with zero information and μ_j from z^i - 8
H ← ∂h/∂(x, m_j) at μ - 9
Ω ← Ω + Hᵀ Q⁻¹ H; ξ ← ξ + Hᵀ Q⁻¹ (z^i - h(μ) + H μ); mark m_j as active and most recent - 10
if more than k landmarks are active then - 11
m_0 ← the active landmarks seen least recently, beyond k; m_+ ← the other active ones - 12
Ω̃ ← Ω_1 - Ω_2 + Ω_3; ξ ← ξ + (Ω̃ - Ω) μ; Ω ← Ω̃ - 13
for each block b in (the pose with m_+, then a few passive landmarks) do μ_b ← Ω_bb⁻¹ (ξ_b - Ω_b,rest μ_rest) - 14
return ξ, Ω, μ
selects the pose from the state. Lines L1 to L5 are the EIF prediction in a form that touches only the pose and the active landmarks. moves the information to the new pose, and removes what the motion noise destroys. Lines L8 and L9 are the EIF update, linearized at the estimate , and the innovation has its bearing wrapped.
Line L12. Let be the passive landmarks. The step replaces the belief by . In matrix form, with the pose, and :
- is the Schur complement of in , the information of given ;
- is the Schur complement of in , the information of given ;
- is the Schur complement of in , the information of the map.
is the conditional of the pose, which has no entry for , and has no entry for the pose. So the links from the pose to become zero. The change of keeps the mean.
Line L13. The filter does not store , so it cannot read the mean. Each block solve sets to the best value with the other entries fixed. The code solves the pose with the active landmarks as one block, and then visits a few passive landmarks in turn. This is block coordinate descent, one sweep per step. With one block per variable and no joint block, the error of the mean was up to 0.55 m in our runs; the joint block brings it close to zero.
Example
Take the 1-D example at the end of the EIF page: the robot at and the landmarks and on a line, with
Both landmarks are active. Let : , seen least recently, goes to , and . There is no passive landmark. The three pieces of line L12 are on , on , and on . The sum is
The link between and is now zero, and , so the mean does not change. The standard deviations stay at 0.137, 0.180 and 0.224, and the covariance of and of also stays. Only the covariance of and changes, from 0.0100 to 0.0045: given , the filter now treats the pose and as independent. In this example nothing becomes overconfident, because no landmark is passive. In a real map, is not empty, and the conditional at treats the passive landmarks as known.
Correctness
The correctness proof shows the following. The motion step equals the EIF prediction exactly, by a matrix inversion identity that also holds for a singular , and it changes only the block of the pose and the active landmarks. The update is the EIF update. The sparsification gives zero links from the pose to and to the passive landmarks, a positive definite , the same mean and the same marginal of the map. If no landmark is passive, the marginal of the pose with is also exact. The mean recovery never increases and has the exact mean as a fixed point.
What the proof does not give is consistency. Conditioning on removes the uncertainty of the passive landmarks from the pose conditional. On random matrices, this does not always shrink the marginal variances, so overconfidence is not a theorem. It is a measurement: Eustice, Walter and Leonard (2005) found the global map overconfident and the map relative to the robot close to consistent. The tests compare the step with dense formulas and a dense EIF, and measure the effect in simulation.
Proof: What the SEIF computes exactly, and where it approximatesfull
Setting. The state is with the pose and the landmarks . The belief is stored as , and an estimate of the mean . A landmark is active if the block is not zero. The filter keeps the invariant that every landmark that links to is in the active list. We prove four claims. The motion step (lines L1 to L5) and the update (lines L6 to L9) are the EIF steps of the extended information filter, done on the local block only. The sparsification (lines L10 to L12) removes the links from the pose to and keeps some marginals exact, but it is an approximation. The mean recovery (line L13) never moves away from the solution of . The claims about assume that when the step starts; with an approximate , each step linearizes at, and keeps, that approximate mean.
The motion step is the EIF prediction (lines L1 to L5)
Line L1 computes the offset and the pose Jacobian at , so the linearized motion is with , and the predicted mean is , where selects the pose. The motion noise is with positive semidefinite. The EIF prediction is and .
The transport. is invertible, because the motion Jacobian has determinant 1 in the code's model. Let . Then , which line L2 computes.
The noise. Write . We claim , which is with from line L3. First, is invertible: has the same nonzero eigenvalues as , which is positive semidefinite. Write . Then
This form needs no inverse of , so it also holds for a singular , as for straight motion with no noise on one axis. So line L4 sets , the EIF result.
Locality. changes only the pose columns, so differs from only in the pose rows and columns, and is zero for every passive . The matrix is the outer product of the pose columns of , so it is zero outside the rows and columns of the pose and the active landmarks. So the code, which computes and on this local block only, gives the full result, and the motion does not make a passive landmark active.
The vector. Line L4 adds to . If , the result is , and line L5 sets . The added vector is zero outside the local block, because and the pose columns of are.
The update is additive and local (lines L6 to L9)
Line L7 adds a new landmark with zero information, so it does not change the belief of the other variables. Lines L8 and L9 are the EIF update linearized at ; the EIF page proves that they give the information form of the EKF posterior. The Jacobian has nonzero columns only for the pose and the observed landmark, so the update changes a 5 by 5 block of and 5 entries of in the plane. It links the pose to the observed landmark, which the code therefore makes active, so the invariant holds.
The sparsification (lines L10 to L12)
Let be the landmarks to deactivate, the active landmarks to keep and the passive landmarks. The exact belief factors as . Line L12 replaces it by
The formula. Let hold , and . Fixing at any value leaves a Gaussian over with information matrix . Removing variables by integration gives the Schur complement on the rest (see the Schur complement). So , the Schur complement of in , is the information matrix of , and , the Schur complement of in , is that of . The exponent of a ratio of densities is the difference of the exponents, so (with placed on the block) is the information matrix of as a function of . It does not depend on the value of , which shifts only the linear term. , the Schur complement of in , is the information matrix of . The exponent of a product is the sum, so is the information matrix of . The test file checks the code against this formula, built from full size matrices, on random cases.
Claim 1: the links from to are zero. has entries only in the rows and columns of and , and has no row or column of . So and . The code writes exact zeros there, to remove the rounding.
Claim 2: only the block changes. and live on . , and is zero outside the columns of and , because of the invariant. So differs from only on .
Claim 3: is positive definite. is the product of a Gaussian conditional with a positive definite conditional covariance and a Gaussian marginal with a positive definite covariance. So it is a proper Gaussian density, and its information matrix is positive definite.
Claim 4: the mean does not change. Line L12 sets . If , then , so . This agrees with the densities: under , the mean of given and is , and has the mean .
Claim 5: the map marginal is exact. . So the covariance of the landmarks does not change in this step. Only the covariances that involve the pose can change.
Claim 6: with no passive landmarks, the marginal of is exact. If is empty, then . The only change is the dependence between and given , which the step removes.
Where the approximation is. If is not empty, the conditional is taken at the fixed value in place of the uncertain . For Gaussians, : conditioning on more variables never adds uncertainty. So the step treats the passive landmarks as known when it describes the pose. This does not make every marginal variance of the pose smaller: on random positive definite matrices, the pose variances shrank in only some of the cases that we tried. So the overconfidence of the SEIF is a measurement, not a theorem. Eustice, Walter and Leonard (2005) showed it in experiments for the global map and found the map relative to a local frame close to consistent. The test file measures the same effect: the mean normalized landmark error is larger with a small bound on the active landmarks than without sparsification.
The mean recovery (line L13)
is the unique minimizer of , because is positive definite. Line L13 solves for a block , with the other entries fixed. This sets to the minimizer of over , because is positive definite. So never increases, and is a fixed point. If all blocks are visited in turn on a fixed , this is block Gauss-Seidel on a positive definite system, which converges to (see the Gauss-Seidel method). The rate can be slow when the map is strongly correlated, and the SEIF visits only a few passive blocks per step while changes. So the mean is an approximation in each step, and its error is not bounded by a theorem.
Complexity
The code stores as dense rows to stay short. The counts below assume a sparse store, which the SEIF needs.
- Motion (lines L1 to L5): on the block of the pose and the active landmarks, so constant for a fixed . The dense EIF needs or more.
- Update (lines L6 to L9): per reading, plus the lookup of the landmark.
- Sparsification (lines L10 to L12): , on the block .
- Mean (line L13): for the joint block, plus a few passive blocks, each one a scan of its row of . A row is short when each landmark links to few others, which holds for a local map but is not guaranteed.
- Memory: the number of nonzero entries of . Landmarks that were active at the same time stay linked, so this is near for a robot that sees few landmarks at a time, and in the worst case.
So the constant time claim of the SEIF holds for the motion, the update and the sparsification, with a bounded active set and a sparse store. It does not hold for an exact mean, which needs a sparse solve of the full system.
Properties
- Approximate. The sparsification changes the belief. The bound trades speed for accuracy.
- Overconfident in practice (measurement). In the test file, 6 runs of 30 steps with 10 landmarks give a mean normalized landmark error (NEES, 2 for a consistent filter) of 1.78 without sparsification, 1.88 with and 2.60 with . The mean landmark errors are 0.22 m, 0.22 m and 0.27 m. In 20 runs of 40 steps with , the median NEES was 5.2, and two runs reached 250 and 14644, with a small covariance and a large error.
- The mean is approximate. Each step does one sweep of block coordinate descent. The error of the mean then enters the linearization of the next steps.
- Additive readings. As in the EIF, a reading changes only the pose and one landmark, and readings can be added in any order.
- No zero pattern for old poses. The SEIF keeps only the current pose. Methods that keep the whole path, as GraphSLAM and iSAM2, get an exactly sparse matrix without an approximation.
Variants and improvements
- Exactly sparse extended information filter (ESEIF). Walter, Eustice and Leonard (2007) control the number of active landmarks by marginalizing out the pose and relocating it from a few readings, so that the sparsity needs no approximate conditional.
- Choice of . The code deactivates the landmarks seen least recently. Other rules choose by distance or by the size of the link.
- Exact mean on demand. A sparse Cholesky or conjugate gradient solve gives the exact mean when it matters, for example before data association or a loop closure.
- Multi-robot merging. Because readings add, the information of several robots can be merged by adding their matrices, after the robots agree on a common frame.
When to use it
The SEIF matters mostly as a step in the history of SLAM: it showed that the information form can be sparse and that each step can then cost constant time. For a new system, prefer FastSLAM for many landmarks with a filter, or a smoothing back end such as GraphSLAM or iSAM2, which gets sparsity without an approximation. Use the SEIF when you need a filter with a fixed cost per step and can accept an overconfident global map, for example if you use mainly the map near the robot.
Pitfalls
- Overconfidence. The covariance of the global map is too small. A gate for data association that uses it rejects true matches. Check the estimate with a ground truth run before trusting it.
- A stale mean. Lines L1, L8 and L9 linearize at . If the mean recovery is too weak, the linearization drifts. Solve the pose and the active landmarks jointly.
- The vector and the mean must agree. Each change of must update with the same . Do not wrap the heading in alone: encodes it too.
- A link left behind. Rounding leaves tiny values in the entries that line L12 sets to zero. Write exact zeros, or the sparse store fills in again.
- New landmarks. A landmark with zero information has no mean in until a reading arrives. Set its mean from the reading at line L7.
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
# 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)
sparse_extended_information_filter.py 330 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sparse-extended-information-filter/. The authors are listed in prov/1KKHWC.jsonl.
"""The sparse extended information filter (SEIF) for planar SLAM.
After Thrun, Burgard and Fox (2005), Chapter 12, and Thrun et al. (2004).
The state is y = (x, y, theta, m1x, m1y, m2x, m2y, ...). The filter keeps
the information matrix Omega, the information vector xi and an estimate mu
of the mean. A landmark is *active* if Omega links it to the pose. The
sparsification step keeps at most max_active active landmarks: it removes
the links between the pose and the other ones by an approximation, so that
Omega stays sparse.
Motion, update and sparsification change only the entries of the pose and
of the active landmarks. Omega is stored as a dense list of rows to keep
the code short; with a sparse store, these steps cost constant time when
the number of active landmarks is bounded. The mean recovery scans whole
rows of Omega here, which a sparse store would also avoid.
The models are the velocity motion model with the control noise
M = diag(a1 v^2 + a2 w^2, a3 v^2 + a4 w^2) and range-bearing readings with
the noise covariance Q, as on the EKF SLAM page.
"""
import math
import rbm
import robest
STRAIGHT = 1e-9
# ---------------------------------------------------------------- planar models
def motion_offset(x, u, dt):
"""Return delta with motion(x) = x + delta, and the Jacobians G (3x3) and V (3x2)."""
th = x[2]
v, w = u
if abs(w) < STRAIGHT:
c, s = math.cos(th), math.sin(th)
delta = [v * dt * c, v * dt * s, 0.0]
g = [[1.0, 0.0, -v * dt * s], [0.0, 1.0, v * dt * c], [0.0, 0.0, 1.0]]
vj = [[dt * c, -v * dt * dt * s / 2.0], [dt * s, v * dt * dt * c / 2.0], [0.0, dt]]
return delta, g, vj
r = v / w
s0, c0 = math.sin(th), math.cos(th)
s1, c1 = math.sin(th + w * dt), math.cos(th + w * dt)
delta = [-r * s0 + r * s1, r * c0 - r * c1, w * dt]
g = [[1.0, 0.0, r * (c1 - c0)], [0.0, 1.0, r * (s1 - s0)], [0.0, 0.0, 1.0]]
vj = [
[(s1 - s0) / w, v * (s0 - s1) / (w * w) + v * c1 * dt / w],
[(c0 - c1) / w, -v * (c0 - c1) / (w * w) + v * s1 * dt / w],
[0.0, dt],
]
return delta, g, vj
def measure(x, m):
"""Return the expected (range, bearing) of the landmark m from the pose x."""
dx, dy = m[0] - x[0], m[1] - x[1]
return [math.hypot(dx, dy), robest.wrap_angle(math.atan2(dy, dx) - x[2])]
def measure_jacobian(x, m):
"""Return the 2x5 Jacobian of measure with respect to (x, y, theta, mx, my)."""
dx, dy = m[0] - x[0], m[1] - x[1]
q = dx * dx + dy * dy
s = math.sqrt(q)
return [
[-dx / s, -dy / s, 0.0, dx / s, dy / s],
[dy / q, -dx / q, -1.0, -dy / q, dx / q],
]
def inverse_measure(x, z):
"""Return the landmark that gives the reading z = (r, phi) from the pose x."""
a = x[2] + z[1]
return [x[0] + z[0] * math.cos(a), x[1] + z[0] * math.sin(a)]
# ---------------------------------------------------------------- small helpers
def sub_matrix(a, rows, cols):
return [[a[r][c] for c in cols] for r in rows]
def marginalize(block, keep, out):
"""Return the information matrix of the variables keep after the variables out are removed.
block is a dict-like accessor block(r, c); keep and out are lists of
indices. The result is Omega_kk - Omega_ko Omega_oo^(-1) Omega_ok.
"""
okk = [[block(r, c) for c in keep] for r in keep]
if not out:
return okk
oko = [[block(r, c) for c in out] for r in keep]
ooo = [[block(r, c) for c in out] for r in out]
sol = rbm.solve(ooo, rbm.transpose(oko)) # Omega_oo^(-1) Omega_ok
return rbm.sub(okk, rbm.mul(oko, sol))
def sparsify_info(om, xi, mu, x, mp, m0):
"""Remove the links between the variables x and m0, in place: line L12.
om and xi are the information matrix and vector, mu the mean, and x, mp
and m0 lists of indices. Every variable that om links to x must be in
mp or m0; the other variables (the passive ones, m-) are fixed at
their mean. The new matrix is Omega1 - Omega2 + Omega3, where
Omega1 is the information of (x, m+) given m- after m0 is removed,
Omega2 is the information of m+ given m- after x and m0 are removed,
Omega3 is the information of all variables but x after x is removed.
It describes p(x | m+, m- = mu-) p(m). The mean mu does not change,
and xi changes by (new Omega - Omega) mu. Only the block of x, m+ and
m0 changes.
"""
s = x + mp + m0
pos = {g: a for a, g in enumerate(s)}
k = len(s)
nx = len(x)
def blk(r, c):
return om[r][c]
o1 = marginalize(blk, x + mp, m0)
o2 = marginalize(blk, mp, x + m0)
oxs = [[om[r][c] for c in s] for r in x] # Omega[x, S]
sol = rbm.solve(sub_matrix(om, x, x), oxs) # Omega_xx^(-1) Omega[x, S]
new = sub_matrix(om, s, s)
for a in range(k):
for b in range(k):
new[a][b] -= sum(oxs[c][a] * sol[c][b] for c in range(nx)) # Omega3 - Omega, on S
for a, ra in enumerate(x + mp):
for b, rb in enumerate(x + mp):
new[pos[ra]][pos[rb]] += o1[a][b]
for a, ra in enumerate(mp):
for b, rb in enumerate(mp):
new[pos[ra]][pos[rb]] -= o2[a][b]
new = [[(new[a][b] + new[b][a]) / 2.0 for b in range(k)] for a in range(k)]
for a in range(nx):
for b in m0:
new[a][pos[b]] = 0.0 # zero by the formula, up to rounding
new[pos[b]][a] = 0.0
diff = [sum((new[a][b] - om[s[a]][s[b]]) * mu[s[b]] for b in range(k)) for a in range(k)]
for a in range(k):
xi[s[a]] += diff[a] # @line L12
for b in range(k):
om[s[a]][s[b]] = new[a][b]
# ---------------------------------------------------------------- the filter
class Seif:
"""A SEIF over the pose and the landmarks seen so far."""
def __init__(self, pose, pose_cov, max_active, alphas, q):
self.mu = list(pose)
self.omega = rbm.inv(pose_cov)
self.xi = rbm.matvec(self.omega, self.mu)
self.ids = [] # landmark identifiers in the order of the state
self.active = [] # active slots, the most recently seen last
self.max_active = max_active
self.alphas = alphas
self.q = q
self.qinv = rbm.inv(q)
self.next_cd = 0 # round robin pointer of the mean recovery
# -------------------------------------------------------- indices
@staticmethod
def index(slot):
return 3 + 2 * slot
def block_indices(self, slots):
out = []
for s in slots:
j = self.index(s)
out.extend([j, j + 1])
return out
def local(self):
"""Return the indices of the pose and of the active landmarks."""
return [0, 1, 2] + self.block_indices(self.active)
# -------------------------------------------------------- motion: lines L1 to L5
def motion(self, u, dt):
mu = self.mu
delta, g, vj = motion_offset(mu, u, dt) # @line L1
v, w = u
a1, a2, a3, a4 = self.alphas
m = [[a1 * v * v + a2 * w * w, 0.0], [0.0, a3 * v * v + a4 * w * w]]
r = rbm.mul(rbm.mul(vj, m), rbm.transpose(vj))
idx = self.local()
k = len(idx)
old = sub_matrix(self.omega, idx, idx)
# Phi = (I + Psi)^T Omega (I + Psi) with I + Psi = G^(-1) on the pose: only the
# pose rows and columns change, and only in the local block.
ginv = rbm.inv(g)
tmat = rbm.eye(k)
for a in range(3):
for b in range(3):
tmat[a][b] = ginv[a][b]
phi = rbm.mul(rbm.mul(rbm.transpose(tmat), old), tmat) # @line L2
phi_xx = [row[:3] for row in phi[:3]]
inner = rbm.mul(r, rbm.inv(rbm.add(rbm.eye(3), rbm.mul(phi_xx, r)))) # R (I + Phi_xx R)^(-1)
phi_x = [row[:3] for row in phi] # Phi F_x^T, k by 3
kappa = rbm.mul(rbm.mul(phi_x, inner), rbm.transpose(phi_x)) # @line L3
new = rbm.sub(phi, kappa)
new = [[(new[a][b] + new[b][a]) / 2.0 for b in range(k)] for a in range(k)]
dmu = [sum((new[a][b] - old[a][b]) * mu[idx[b]] for b in range(k)) for a in range(k)]
ndelta = [sum(new[a][b] * delta[b] for b in range(3)) for a in range(k)]
for a in range(k):
self.xi[idx[a]] += dmu[a] + ndelta[a] # @line L4
for b in range(k):
self.omega[idx[a]][idx[b]] = new[a][b]
for a in range(3):
mu[a] += delta[a] # @line L5
# The heading is not wrapped here: xi encodes the mean, and wrapping
# mu alone would make the two disagree by a multiple of 2 pi.
# -------------------------------------------------------- readings: lines L6 to L9
def add_landmark(self, lid, mean):
n = len(self.mu)
for row in self.omega:
row.extend([0.0, 0.0])
self.omega.append([0.0] * (n + 2))
self.omega.append([0.0] * (n + 2))
self.xi.extend([0.0, 0.0])
self.mu.extend(mean)
self.ids.append(lid)
return len(self.ids) - 1
def update(self, zs, lids):
for z, lid in zip(zs, lids): # @line L6
if lid not in self.ids:
self.add_landmark(lid, inverse_measure(self.mu, z)) # @line L7
slot = self.ids.index(lid)
j = self.index(slot)
idx = [0, 1, 2, j, j + 1]
mu = self.mu
m = mu[j:j + 2]
zhat = measure(mu, m)
h = measure_jacobian(mu, m) # @line L8
nu = [z[0] - zhat[0], robest.wrap_angle(z[1] - zhat[1])]
target = [nu[a] + sum(h[a][c] * mu[idx[c]] for c in range(5)) for a in range(2)]
hq = rbm.mul(rbm.transpose(h), self.qinv)
info = rbm.mul(hq, h)
vec = rbm.matvec(hq, target)
for a in range(5):
self.xi[idx[a]] += vec[a] # @line L9
for b in range(5):
self.omega[idx[a]][idx[b]] += info[a][b]
if slot in self.active:
self.active.remove(slot)
self.active.append(slot)
# -------------------------------------------------------- sparsification: lines L10 to L12
def sparsify(self):
"""Deactivate the landmarks seen least recently until at most max_active remain."""
if len(self.active) <= self.max_active: # @line L10
return []
cut = len(self.active) - self.max_active
m0_slots, mp_slots = self.active[:cut], self.active[cut:] # @line L11
self.sparsify_slots(m0_slots, mp_slots)
self.active = mp_slots
return m0_slots
def sparsify_slots(self, m0_slots, mp_slots):
"""Remove the links between the pose and the landmarks m0, keeping those to m+."""
sparsify_info(self.omega, self.xi, self.mu, [0, 1, 2], self.block_indices(mp_slots), self.block_indices(m0_slots))
# -------------------------------------------------------- mean recovery: line L13
def recover_mean(self, extra=2, sweeps=1, joint=True):
"""Block coordinate descent on Omega mu = xi.
With joint=True, the pose and the active landmarks form one block,
solved together; otherwise each is its own block, as in plain
coordinate descent. Then `extra` passive landmarks, in round robin
order, are solved one at a time. Each block solve costs constant
time for a bounded active set, apart from the row scans."""
n_lm = len(self.ids)
others = [s for s in range(n_lm) if s not in self.active]
chosen = []
for _ in range(min(extra, len(others))):
self.next_cd %= n_lm
while self.next_cd in self.active:
self.next_cd = (self.next_cd + 1) % n_lm
chosen.append(self.next_cd)
self.next_cd += 1
if joint:
blocks = [self.local()]
else:
blocks = [[0, 1, 2]] + [[self.index(s), self.index(s) + 1] for s in self.active]
blocks += [[self.index(s), self.index(s) + 1] for s in chosen]
for _ in range(sweeps):
for b in blocks:
self.solve_block(b) # @line L13
def solve_block(self, b):
"""Set mu[b] to the minimizer of the quadratic with all other entries fixed."""
om, mu = self.omega, self.mu
rhs = []
for r in b:
row = om[r]
acc = self.xi[r] - sum(row[c] * mu[c] for c in range(len(mu)))
acc += sum(row[c] * mu[c] for c in b)
rhs.append(acc)
new = rbm.solve(sub_matrix(om, b, b), rhs)
for a, r in enumerate(b):
mu[r] = new[a]
def recover_mean_exact(self):
"""Set mu = Omega^(-1) xi by a dense solve, O(n^3)."""
self.mu = rbm.solve(self.omega, self.xi)
# -------------------------------------------------------- one step
def step(self, u, dt, zs, lids, extra=2):
"""One SEIF step: lines L1 to L14."""
self.motion(u, dt)
self.update(zs, lids)
self.sparsify()
self.recover_mean(extra)
return self.mu # @line L14
test_sparse_extended_information_filter.py 245 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sparse-extended-information-filter/. The authors are listed in prov/1KKHWC.jsonl.
import copy
import math
import random
import rbm
import robest
from sparse_extended_information_filter import Seif, measure, motion_offset, sparsify_info
ALPHAS = (0.01, 0.005, 0.005, 0.01)
Q = [[0.01, 0.0], [0.0, 0.0009]]
LANDMARKS = [[2.0, 2.0], [4.0, -1.0], [6.0, 2.5], [8.0, -1.5], [10.0, 2.0], [5.0, 4.0], [3.0, -3.0], [9.0, 4.0], [1.0, -2.0], [7.0, 0.5]]
def max_abs_diff(a, b):
if isinstance(a[0], list):
return max(abs(x - y) for ra, rb in zip(a, b) for x, y in zip(ra, rb))
return max(abs(x - y) for x, y in zip(a, b))
def small_filter(max_active=10):
f = Seif([0.0, 0.0, 0.1], [[0.01, 0.0, 0.0], [0.0, 0.01, 0.0], [0.0, 0.0, 0.01]], max_active, ALPHAS, Q)
f.update([[2.0, 0.5], [3.0, -0.4], [2.5, 0.1], [1.5, 1.0]], [0, 1, 2, 3])
f.recover_mean_exact()
return f
def pose_links(f):
"""Return the slots of the landmarks that Omega links to the pose."""
out = []
for s in range(len(f.ids)):
j = f.index(s)
if any(f.omega[a][c] != 0.0 for a in range(3) for c in (j, j + 1)):
out.append(s)
return out
def test_motion_equals_the_dense_information_filter_prediction():
f = small_filter()
omega, mu = copy.deepcopy(f.omega), list(f.mu)
n = len(mu)
u = (0.5, 0.2)
f.motion(u, 1.0)
delta, g, vj = motion_offset(mu, u, 1.0)
v, w = u
m = [[ALPHAS[0] * v * v + ALPHAS[1] * w * w, 0.0], [0.0, ALPHAS[2] * v * v + ALPHAS[3] * w * w]]
r = rbm.mul(rbm.mul(vj, m), rbm.transpose(vj))
big_g, big_r = rbm.eye(n), rbm.zeros(n, n)
for a in range(3):
for b in range(3):
big_g[a][b] = g[a][b]
big_r[a][b] = r[a][b]
want = rbm.inv(rbm.add(rbm.mul(rbm.mul(big_g, rbm.inv(omega)), rbm.transpose(big_g)), big_r))
mu_bar = [mu[i] + (delta[i] if i < 3 else 0.0) for i in range(n)]
assert max_abs_diff(f.omega, want) < 1e-10
assert max_abs_diff(f.xi, rbm.matvec(want, mu_bar)) < 1e-10
assert max_abs_diff(f.mu, mu_bar) == 0.0
def test_update_changes_only_the_pose_and_the_landmark():
f = small_filter()
f.motion((0.5, 0.2), 1.0)
before, xi = copy.deepcopy(f.omega), list(f.xi)
f.update([[2.4, 0.2]], [1])
touched = {0, 1, 2, f.index(1), f.index(1) + 1}
n = len(f.mu)
for r in range(n):
for c in range(n):
if r not in touched or c not in touched:
assert f.omega[r][c] == before[r][c]
if r not in touched:
assert f.xi[r] == xi[r]
def marginal_info(m, idx_out, n):
"""Full size: M - M[:, out] M[out, out]^(-1) M[out, :], the information after the variables out are removed."""
if not idx_out:
return [list(row) for row in m]
moo = [[m[r][c] for c in idx_out] for r in idx_out]
mxo = [[m[r][c] for c in idx_out] for r in range(n)]
sol = rbm.solve(moo, rbm.transpose(mxo))
return rbm.sub(m, rbm.mul(mxo, sol))
def test_sparsification_matches_the_textbook_formula():
rng = random.Random(1)
n = 3 + 2 * 6
x, mp, m0 = [0, 1, 2], [11, 12, 13, 14], [7, 8, 9, 10]
for _ in range(10):
a = [[rng.gauss(0.0, 1.0) for _ in range(n)] for _ in range(n)]
om = rbm.add(rbm.mul(a, rbm.transpose(a)), rbm.eye(n))
for j in (3, 4, 5, 6): # landmarks 0 and 1 are passive
for i in x:
om[i][j] = om[j][i] = 0.0
mu = [rng.gauss(0.0, 1.0) for _ in range(n)]
xi = rbm.matvec(om, mu)
s = x + mp + m0
om0 = [[om[r][c] if r in s and c in s else 0.0 for c in range(n)] for r in range(n)]
# with om0, removing a variable that om0 does not hold is the same as fixing it
o1 = marginal_info(om0, m0, n)
o2 = marginal_info(om0, x + m0, n)
o3 = marginal_info(om, x, n)
want = rbm.add(rbm.sub(o1, o2), o3)
got_om, got_xi = copy.deepcopy(om), list(xi)
sparsify_info(got_om, got_xi, mu, x, mp, m0)
assert max_abs_diff(got_om, want) < 1e-10
assert max_abs_diff(got_xi, rbm.add(xi, rbm.matvec(rbm.sub(want, om), mu))) < 1e-9
def test_sparsification_cuts_the_links_and_keeps_the_mean():
f = small_filter()
f.motion((0.5, 0.2), 1.0)
f.recover_mean_exact()
before = copy.deepcopy(f.omega)
mu = list(f.mu)
f.max_active = 2
m0 = f.sparsify()
assert m0 == [0, 1]
assert pose_links(f) == [2, 3]
assert max_abs_diff(rbm.solve(f.omega, f.xi), mu) < 1e-9
rbm.cholesky(f.omega) # still positive definite
n = len(mu)
# no landmark is passive here, so the marginal of the map and the marginal of the pose with m+ do not change
s_old, s_new = rbm.inv(before), rbm.inv(f.omega)
mp = [0, 1, 2] + [f.index(2), f.index(2) + 1, f.index(3), f.index(3) + 1]
assert max(abs(s_old[r][c] - s_new[r][c]) for r in mp for c in mp) < 1e-9
lm = list(range(3, n))
assert max(abs(s_old[r][c] - s_new[r][c]) for r in lm for c in lm) < 1e-9
# but the covariance between the pose and the removed landmarks changes
assert max(abs(s_old[r][c] - s_new[r][c]) for r in range(3) for c in range(3, 7)) > 1e-4
def simulate(seed, max_active, exact, steps=30, extra=2):
rng = random.Random(seed)
f = Seif([0.0, 0.0, 0.0], [[1e-4, 0.0, 0.0], [0.0, 1e-4, 0.0], [0.0, 0.0, 1e-4]], max_active, ALPHAS, Q)
x = [0.0, 0.0, 0.0]
links = []
for t in range(steps):
u = (0.5, 0.08 if t < steps // 2 else -0.08)
v, w = u
m = [[ALPHAS[0] * v * v + ALPHAS[1] * w * w, 0.0], [0.0, ALPHAS[2] * v * v + ALPHAS[3] * w * w]]
noisy = robest.gauss_sample(rng, list(u), m)
d, _, _ = motion_offset(x, noisy, 1.0)
x = [x[i] + d[i] for i in range(3)]
zs, ids = [], []
for i, lm in enumerate(LANDMARKS):
z = measure(x, lm)
if z[0] < 4.0 and abs(z[1]) < 1.4:
zs.append([z[0] + rng.gauss(0.0, 0.1), z[1] + rng.gauss(0.0, 0.03)])
ids.append(i)
f.motion(u, 1.0)
f.update(zs, ids)
f.sparsify()
if exact:
f.recover_mean_exact()
else:
f.recover_mean(extra)
links.append(len(pose_links(f)))
return f, x, links
def landmark_stats(f):
sigma = rbm.inv(f.omega)
mu = rbm.solve(f.omega, f.xi)
nees, err = [], []
for s, lid in enumerate(f.ids):
j = f.index(s)
e = [mu[j] - LANDMARKS[lid][0], mu[j + 1] - LANDMARKS[lid][1]]
cov = [[sigma[j][j], sigma[j][j + 1]], [sigma[j + 1][j], sigma[j + 1][j + 1]]]
nees.append(robest.mahalanobis2(e, [0.0, 0.0], cov))
err.append(math.hypot(*e))
return sum(nees) / len(nees), sum(err) / len(err)
def test_the_active_set_stays_bounded():
for seed in (1, 2):
f, _, links = simulate(seed, 3, exact=False, steps=20)
assert max(links) <= 3
assert len(f.ids) >= 5
def energy(f):
"""0.5 mu^T Omega mu - xi^T mu, which block coordinate descent never increases."""
w = rbm.matvec(f.omega, f.mu)
return 0.5 * sum(a * b for a, b in zip(f.mu, w)) - sum(a * b for a, b in zip(f.xi, f.mu))
def test_mean_recovery_descends_and_converges_slowly():
f, _, _ = simulate(3, 3, exact=False, steps=15)
exact = rbm.solve(f.omega, f.xi)
last, errors = energy(f), []
for _ in range(400):
f.recover_mean(extra=len(f.ids))
e = energy(f)
assert e <= last + 1e-9
last = e
errors.append(max_abs_diff(f.mu, exact))
# linear convergence, but slow: the map is strongly correlated
assert errors[9] > 0.05
assert errors[-1] < 2e-3
# the exact mean is a fixed point
f.mu = list(exact)
f.recover_mean(extra=len(f.ids), joint=False)
assert max_abs_diff(f.mu, exact) < 1e-9
def test_sparsification_makes_the_map_overconfident_in_simulation():
"""A measurement, not a theorem: 6 runs of 30 steps with 10 landmarks.
Without sparsification (max_active = 100) the filter is the EIF, and the
mean normalized landmark error is near 2, the dimension. With at most 3
active landmarks it is larger: the reported covariance is too small for
the real error.
"""
full, sparse, err_full, err_sparse = [], [], [], []
for seed in range(6):
nees, err = landmark_stats(simulate(seed, 100, exact=True)[0])
full.append(nees)
err_full.append(err)
nees, err = landmark_stats(simulate(seed, 3, exact=False)[0])
sparse.append(nees)
err_sparse.append(err)
mean_full, mean_sparse = sum(full) / 6, sum(sparse) / 6
assert 1.0 < mean_full < 4.0
assert mean_sparse > mean_full
assert sum(err_sparse) / 6 < 2.0 * sum(err_full) / 6
def test_example_of_the_page():
"""The state (x, A, B) on a line after the example of the EIF page; B is deactivated."""
om = [[85.0, -35.0, -10.0], [-35.0, 47.5, -2.5], [-10.0, -2.5, 22.5]]
xi = [-33.75, 46.25, 97.5]
mu = rbm.solve(om, xi)
before = rbm.inv(om)
sparsify_info(om, xi, mu, [0], [1], [2])
want = [[80.5556, -36.1111, 0.0], [-36.1111, 49.2760, -6.6176], [0.0, -6.6176, 21.3235]]
assert max_abs_diff(om, want) < 1e-4
assert max_abs_diff(rbm.solve(om, xi), mu) < 1e-12
after = rbm.inv(om)
for i in range(3):
assert abs(after[i][i] - before[i][i]) < 1e-12 # no passive landmark: the variances stay
assert abs(before[0][2] - 0.01) < 1e-9
assert abs(after[0][2] - 0.0045) < 1e-4
History
Thrun, Liu, Koller, Ng, Ghahramani and Durrant-Whyte (2004) observed that the normalized information matrix of the EIF in SLAM has a few strong entries and many weak ones. They proposed the SEIF, which bounds the active landmarks, keeps sparse by the sparsification step, and recovers the mean by a few steps of an iterative method. Thrun, Burgard and Fox present it in Chapter 12 of Probabilistic Robotics (2005). Eustice, Walter and Leonard (2005) analyzed the sparsification and showed that it makes the global map overconfident. Walter, Eustice and Leonard (2007) proposed the exactly sparse ESEIF. Later work moved to smoothing over the whole path, where the information matrix is sparse without an approximation.
References
- Sebastian Thrun, Wolfram Burgard and Dieter Fox, Probabilistic Robotics, MIT Press, 2005, Chapter 12 (the sparse extended information filter)
- Sebastian Thrun, Yufeng Liu, Daphne Koller, Andrew Y. Ng, Zoubin Ghahramani and Hugh Durrant-Whyte, Simultaneous localization and mapping with sparse extended information filters, International Journal of Robotics Research 23(7-8), 2004, pages 693 to 716, the SEIF, its motion update, measurement update, sparsification and mean recovery
- Ryan M. Eustice, Matthew R. Walter and John J. Leonard, Sparse extended information filters: insights into sparsification, IEEE/RSJ International Conference on Intelligent Robots and Systems, 2005, pages 3281 to 3288, the analysis of the sparsification step and the experiments on the consistency of the global and the relative map
- Matthew R. Walter, Ryan M. Eustice and John J. Leonard, Exactly sparse extended information filters for feature-based SLAM, International Journal of Robotics Research 26(4), 2007, pages 335 to 359, the exactly sparse extended information filter (ESEIF)
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 1KKHWC Edit this page History Report an error Markdown