Algorithm Search⌘K

Algorithmcore

EKF SLAM

Also called extended Kalman filter SLAM, stochastic map.

Keeps one joint Gaussian over the robot pose and all m landmarks. Each reading updates the full covariance in O(m^2) time, which limits it to maps of a few hundred landmarks.

Time
O(k m) associationO(m) predictionO(k m^2) update
Space
O(m^2) extra
Where
k = the number of readings in one step; m = the number of landmarks in the map
Properties
deterministicnot exactonlinerecursive
Origin
Randall Smith, Matthew Self, Peter Cheeseman, 1986

EKF SLAM solves the online SLAM problem with one extended Kalman filter whose state holds the robot pose and the positions of all landmarks. The belief is one Gaussian N(μ,Σ)N(\mu, \Sigma) over (x,y,θ,m1,x,m1,y,…,mm,x,mm,y)(x, y, \theta, m_{1,x}, m_{1,y}, \dots, m_{m,x}, m_{m,y}). A motion moves only the pose part. A reading of a landmark corrects the pose and every landmark at once, because the covariance Σ\Sigma links them all. A landmark enters the state at its first reading. This is the oldest SLAM algorithm, and the EKF SLAM convergence theorem explains its behavior in the linear case. Its cost is O(m2)O(m^2) per reading for mm landmarks, because each update changes all of Σ\Sigma. It differs from EKF localization, which has a fixed map and a 3 by 3 covariance, and from FastSLAM, which samples the path and keeps one small filter per landmark.

In plain words

The robot keeps one best guess of where it is and of where each landmark is, and it also keeps a table that says how the errors of all these guesses depend on each other. When the robot drives, its own guess becomes less sure, and the landmark guesses stay the same. When it sees a new landmark, it adds the landmark to its list, as sure as its own position allows. When it sees a known landmark again, it corrects its own position, and through the table it also corrects every landmark that it saw from nearby. The table grows with the square of the number of landmarks, and each correction touches all of it.

The problem

The input is a Gaussian prior on the start pose, usually the origin with zero covariance, and at each time step a control ut=(vt,ωt)u_t = (v_t, \omega_t) held for Δt\Delta t seconds and a set of readings zti=(rti,ϕti)z_t^i = (r_t^i, \phi_t^i) of point landmarks. The correspondence ctic_t^i, the landmark of reading ii, is given or must be estimated. The output after each step is a Gaussian approximation of the online SLAM posterior p(xt,m∣z1:t,u1:t,c1:t)p(x_t, m \mid z_{1:t}, u_{1:t}, c_{1:t}) over the current pose and the map.

State. μ=(μx,μm1,…,μmn)\mu = (\mu_x, \mu_{m_1}, \dots, \mu_{m_n}) with μx=(x,y,θ)\mu_x = (x, y, \theta), where nn is the number of landmarks seen so far. Σ\Sigma has the blocks Σxx\Sigma_{xx} (3 by 3), Σxm\Sigma_{xm} (3 by 2n2n) and Σmm\Sigma_{mm} (2n2n by 2n2n).

Models. The motion is the velocity motion model g(ut,xt−1)g(u_t, x_{t-1}) with the control noise Mt=diag(α1v2+α2ω2,α3v2+α4ω2)M_t = \mathrm{diag}(\alpha_1 v^2 + \alpha_2 \omega^2, \alpha_3 v^2 + \alpha_4 \omega^2), as in EKF localization. The landmarks do not move. A reading of landmark jj follows the landmark measurement model

h(x,mj)=(qatan2⁡(δy,δx)−θ),δ=mj−(x,y),q=δ⊤δ,h(x, m_j) = \begin{pmatrix} \sqrt{q} \\ \operatorname{atan2}(\delta_y, \delta_x) - \theta \end{pmatrix}, \qquad \delta = m_j - (x, y), \quad q = \delta^\top \delta,

plus noise N(0,Q)N(0, Q) with Q=diag(σr2,σϕ2)Q = \mathrm{diag}(\sigma_r^2, \sigma_\phi^2). The inverse model gives the landmark from a pose and a reading: f(x,z)=(x+rcos⁡(ϕ+θ), y+rsin⁡(ϕ+θ))f(x, z) = (x + r \cos(\phi + \theta),\ y + r \sin(\phi + \theta)).

The algorithm

  1. EKF-SLAM(μ, Σ, u_t, z_t) ▷ μ = (μ_x, μ_m1, ..., μ_mn), μ_x = (x, y, θ)
  2. 1G ← ∂g/∂x and V ← ∂g/∂u at (u_t, μ_x); M ← diag(α1 v² + α2 ω², α3 v² + α4 ω²)
  3. 2μ_x ← g(u_t, μ_x)
  4. 3Σ_xx ← G Σ_xx Gᵀ + V M Vᵀ
  5. 4Σ_xm ← G Σ_xm; Σ_mx ← Σ_xmᵀ ▷ Σ_mm does not change
  6. 5for each reading z^i = (r^i, φ^i) in z_t do
  7. 6j ← c^i if known, else the landmark with the smallest Mahalanobis distance, or new if it fails the gate
  8. 7if j is new then append f(μ_x, z^i) to μ and grow Σ (below); continue
  9. 8ẑ ← h(μ_x, μ_mj); H ← ∂h/∂(x, m_j), zero in all other columns
  10. 9S ← H Σ Hᵀ + Q; K ← Σ Hᵀ S⁻¹
  11. 10μ ← μ + K wrap(z^i - ẑ)
  12. 11Σ ← (I - K H) Σ
  13. 12return μ, Σ

Line L7, a new landmark. With Gx=∂f/∂xG_x = \partial f / \partial x (2 by 3) and Gz=∂f/∂zG_z = \partial f / \partial z (2 by 2) at (μx,zi)(\mu_x, z^i), the new landmark gets the mean f(μx,zi)f(\mu_x, z^i), the cross covariance GxΣx⋅G_x \Sigma_{x\cdot} with the whole old state, and the covariance GxΣxxGx⊤+GzQGz⊤G_x \Sigma_{xx} G_x^\top + G_z Q G_z^\top. The correctness proof shows that this is the exact posterior for a landmark with a flat prior, in the linear case. The reading is not used a second time for an update, because that would count it twice. Thrun et al. (Section 10.2) instead put all landmarks in the state from the start, with a very large initial covariance, and initialize a landmark at its first reading; the result is close to the one here.

Line L8, the Jacobian. With δ\delta and qq as above,

∂h∂(x,y,θ,mj,x,mj,y)=1q(−q δx−q δy0q δxq δyδy−δx−q−δyδx).\frac{\partial h}{\partial (x, y, \theta, m_{j,x}, m_{j,y})} = \frac{1}{q} \begin{pmatrix} -\sqrt{q}\,\delta_x & -\sqrt{q}\,\delta_y & 0 & \sqrt{q}\,\delta_x & \sqrt{q}\,\delta_y \\ \delta_y & -\delta_x & -q & -\delta_y & \delta_x \end{pmatrix}.

HH has only these 5 nonzero columns. So ΣH⊤\Sigma H^\top costs O(n)O(n), but line L11 still changes every entry of Σ\Sigma.

Line L6, unknown correspondences. For each landmark jj in the map, compute the innovation νj\nu_j and SjS_j as in lines L8 and L9, and its squared Mahalanobis distance dj2=νj⊤Sj−1νjd_j^2 = \nu_j^\top S_j^{-1} \nu_j. Take the landmark with the smallest dj2d_j^2 if dj2≤9.210d_j^2 \le 9.210, the 0.990.99 quantile of the chi-square distribution with 2 degrees of freedom. If no landmark passes, the reading starts a new landmark. Thrun et al. (Section 10.3) use the same rule with a threshold α\alpha on the distance. The code also has a second, larger threshold: a reading between the two is dropped, so that a reading of a known landmark with a large error does not create a copy. See data association in SLAM and JCBB for joint tests.

Example

Take α=(0.01,0.005,0.005,0.01)\alpha = (0.01, 0.005, 0.005, 0.01), σr=0.1\sigma_r = 0.1 m and σϕ=0.03\sigma_\phi = 0.03 rad. The robot starts at the origin with Σ=0\Sigma = 0; the start pose defines the frame of the map.

Step 1, drive. The control is v=1v = 1 m/s and ω=0\omega = 0 for 1 s, so M=diag(0.01,0.005)M = \mathrm{diag}(0.01, 0.005). Lines L2 and L3 give μx=(1,0,0)\mu_x = (1, 0, 0) and

Σxx=(0.010000.001250.002500.00250.005).\Sigma_{xx} = \begin{pmatrix} 0.01 & 0 & 0 \\ 0 & 0.00125 & 0.0025 \\ 0 & 0.0025 & 0.005 \end{pmatrix}.

The heading noise moves the robot sideways, so yy and θ\theta are correlated.

Step 1, a new landmark A. The reading is z=(2.0,0.5)z = (2.0, 0.5). Line L7 puts A at (1+2cos⁡0.5, 2sin⁡0.5)=(2.7552,0.9589)(1 + 2 \cos 0.5,\ 2 \sin 0.5) = (2.7552, 0.9589) with variances 0.023130.02313 and 0.03050.0305, larger than those of the reading alone, because the uncertainty of the pose carries over. The new cross terms are not zero: for example Cov(x,mA,x)=0.01\mathrm{Cov}(x, m_{A,x}) = 0.01 and Cov(θ,mA,y)=0.01128\mathrm{Cov}(\theta, m_{A,y}) = 0.01128. The robot and the landmark are now correlated.

Step 2, drive again. The same control gives μx=(2,0,0)\mu_x = (2, 0, 0). The pose variances grow to (0.02,0.0125,0.01)(0.02, 0.0125, 0.01), so the standard deviations are (0.141,0.112,0.100)(0.141, 0.112, 0.100). The landmark block does not change.

Step 2, see A again. The reading is z=(1.28,0.95)z = (1.28, 0.95), and line L8 predicts z^=(1.2206,0.9036)\hat z = (1.2206, 0.9036). After lines L9 to L11:

  • the pose is (2.0041,−0.0141,−0.0282)(2.0041, -0.0141, -0.0282), and its standard deviations shrink to (0.128,0.109,0.084)(0.128, 0.109, 0.084);
  • landmark A moves to (2.7629,0.9790)(2.7629, 0.9790), and its standard deviations shrink from (0.152,0.175)(0.152, 0.175) to (0.142,0.170)(0.142, 0.170), although the reading was taken from a less certain pose;
  • the correlation between yy and mA,ym_{A,y} is 0.9480.948: both are now known mostly relative to each other.

The landmark improved because it is correlated with the pose at the time of its first reading, and that pose is correlated with the current one through the odometry. With many landmarks, this is how one reading corrects the whole map.

Correctness

For linear motion and measurement models with Gaussian noise, EKF SLAM is the Kalman filter on the joint state of robot and map, so its output is the exact online SLAM posterior. The correctness proof shows the three parts: the prediction moves only the pose block and the cross block (lines L2 to L4); the addition of a landmark is the exact posterior for a flat prior (line L7); and the sparse update of lines L8 to L11 equals the dense Kalman update. The tests check the last claim as a whole: on a linear model with three landmarks, the filter matches the marginal of the batch least squares solution over all poses and landmarks within 10−910^{-9}.

For the nonlinear planar models, the filter uses Jacobians at the current mean, and the result is an approximation with no error bound. In simulation with the noise of the model, the tests measure a mean normalized pose error of 2.59 for 3 degrees of freedom and 2.13 for the 2 degrees of freedom of each landmark, over 10 runs of 25 steps; values near the dimension mean that the covariance matches the real error. This is a measurement for these noise levels, not a guarantee (see Pitfalls).

Proof: EKF SLAM is the exact Kalman filter of the joint state in the linear casefull

Setting. The joint state is y=(x,m)y = (x, m), where x∈Rrx \in \mathbb{R}^r is the robot state and m=(m1,…,mn)m = (m_1, \dots, m_n) stacks the landmarks that are already in the map, each in R2\mathbb{R}^2. The belief is N(μ,Σ)N(\mu, \Sigma) over yy. We prove the claims for the linear Gaussian SLAM model:

  • motion: xt=Fxt−1+But+wtx_t = F x_{t-1} + B u_t + w_t with wt∼N(0,R)w_t \sim N(0, R), and the landmarks do not move;
  • a reading of landmark jj: z=Hxx+Hmmj+vz = H_x x + H_m m_j + v with v∼N(0,Q)v \sim N(0, Q) and HmH_m invertible (a reading fixes the landmark when the robot state is known);
  • all noises are independent of each other and of the state, and Σ\Sigma, RR and QQ are symmetric, with QQ positive definite.

For the planar models of the page, EKF SLAM applies the same steps to the models linearized at the current mean: F=GtF = G_t, R=VtMtVt⊤R = V_t M_t V_t^\top, HxH_x and HmH_m the Jacobians of the range and bearing, and the inverse model mj=f(x,z)m_j = f(x, z) with Jacobians GxG_x and GzG_z.

Claim. In the linear Gaussian model, if y∼N(μ,Σ)y \sim N(\mu, \Sigma) before a step, then:

  1. after lines L2 to L4, N(μ,Σ)N(\mu, \Sigma) is the exact distribution of the joint state after the motion;
  2. after line L7 for a new landmark, N(μ,Σ)N(\mu, \Sigma) is the exact posterior over the enlarged state, for a landmark with a flat prior;
  3. after lines L8 to L11 for a reading of a known landmark, N(μ,Σ)N(\mu, \Sigma) is the exact posterior given the reading.

So EKF SLAM computes the exact online SLAM posterior p(xt,m∣z1:t,u1:t)p(x_t, m \mid z_{1:t}, u_{1:t}) in the linear Gaussian case. For nonlinear models it computes the same quantities for the linearized models, which is an approximation with no general error bound.

Proof.

Part 1, the prediction. Write the step on the joint state as yt=Ayt−1+(But,0)+(wt,0)y_t = A y_{t-1} + (B u_t, 0) + (w_t, 0) with A=(F00I)A = \begin{pmatrix} F & 0 \\ 0 & I \end{pmatrix}, because the landmarks do not move. An affine image of a Gaussian vector plus an independent Gaussian vector is Gaussian, with mean Aμ+(But,0)A \mu + (B u_t, 0) and covariance AΣA⊤+diag(R,0)A \Sigma A^\top + \mathrm{diag}(R, 0). In blocks,

AΣA⊤+diag(R,0)=(FΣxxF⊤+RFΣxmΣmxF⊤Σmm).A \Sigma A^\top + \mathrm{diag}(R, 0) = \begin{pmatrix} F \Sigma_{xx} F^\top + R & F \Sigma_{xm} \\ \Sigma_{mx} F^\top & \Sigma_{mm} \end{pmatrix}.

The mean of xx is Fμx+ButF \mu_x + B u_t (line L2) and the mean of mm does not change. The robot block is line L3, the cross block is line L4, and the map block stays as it is. This proves part 1. The code changes only the first rr rows and columns, which costs O(r2n)O(r^2 n) operations, so O(n)O(n) for a fixed rr.

Part 2, a new landmark. Let yy be the state before the reading, with y∼N(μ,Σ)y \sim N(\mu, \Sigma) given the past data DD, and let the new landmark mnewm_{new} have a flat prior: its density is constant and it is independent of yy before the reading. The reading is z=Hxx+Hmmnew+vz = H_x x + H_m m_{new} + v. By Bayes' rule,

p(y,mnew∣D,z)∝p(y∣D) N(z; Hxx+Hmmnew, Q).p(y, m_{new} \mid D, z) \propto p(y \mid D)\, N(z;\ H_x x + H_m m_{new},\ Q).

As a function of mnewm_{new} for fixed yy, the Gaussian factor equals ∣det⁡Hm∣−1N(mnew; Hm−1(z−Hxx), Hm−1QHm−⊤)|\det H_m|^{-1} N(m_{new};\ H_m^{-1}(z - H_x x),\ H_m^{-1} Q H_m^{-\top}). Its integral over mnewm_{new} is ∣det⁡Hm∣−1|\det H_m|^{-1}, which does not depend on yy. Hence the marginal of yy is still N(μ,Σ)N(\mu, \Sigma): the first reading of a landmark carries no information about the rest of the state. The conditional of mnewm_{new} given yy is N(Gxx+Gzz, GzQGz⊤)N(G_x x + G_z z,\ G_z Q G_z^\top) with Gx=−Hm−1HxG_x = -H_m^{-1} H_x and Gz=Hm−1G_z = H_m^{-1}, which is the linear inverse model mnew=Gxx+Gz(z−v)m_{new} = G_x x + G_z (z - v). A Gaussian marginal times a linear Gaussian conditional gives a joint Gaussian with

E[mnew]=Gxμx+Gzz,Cov(mnew,y)=GxΣx⋅,Cov(mnew)=GxΣxxGx⊤+GzQGz⊤.E[m_{new}] = G_x \mu_x + G_z z, \qquad \mathrm{Cov}(m_{new}, y) = G_x \Sigma_{x\cdot}, \qquad \mathrm{Cov}(m_{new}) = G_x \Sigma_{xx} G_x^\top + G_z Q G_z^\top.

These are the new mean, the new rows and the new diagonal block that line L7 (the function augment) appends. This proves part 2. The new rows cost O(rn)O(r n) to compute.

Part 3, a reading of a known landmark. The reading of landmark jj is z=Hy+vz = H y + v, where the full Jacobian HH has the block HxH_x in the robot columns, HmH_m in the columns of mjm_j, and zeros elsewhere. The Kalman update for a linear measurement of a Gaussian state gives the exact posterior (see the Kalman filter):

S=HΣH⊤+Q,K=ΣH⊤S−1,μ′=μ+K(z−Hμ),Σ′=(I−KH)Σ.S = H \Sigma H^\top + Q, \quad K = \Sigma H^\top S^{-1}, \quad \mu' = \mu + K (z - H \mu), \quad \Sigma' = (I - K H) \Sigma.

The code computes the same quantities in a cheaper order. Let idx\mathrm{idx} be the columns where HH is not zero, and hh the matrix of those columns. Then ΣH⊤=Σ:,idx h⊤\Sigma H^\top = \Sigma_{:,\mathrm{idx}}\, h^\top, an n×2n \times 2 matrix that costs O(n)O(n), and S=h (ΣH⊤)idx,:+QS = h\, (\Sigma H^\top)_{\mathrm{idx},:} + Q. Line L9 forms S−1S^{-1} and K=(ΣH⊤)S−1K = (\Sigma H^\top) S^{-1}, and line L10 adds KνK \nu with ν=z−Hμ\nu = z - H \mu. Because Σ\Sigma is symmetric, KHΣ=K(ΣH⊤)⊤K H \Sigma = K (\Sigma H^\top)^\top, so line L11 computes Σrc′=Σrc−∑aKra(ΣH⊤)ca\Sigma'_{rc} = \Sigma_{rc} - \sum_a K_{ra} (\Sigma H^\top)_{ca}, which is (I−KH)Σ(I - K H)\Sigma. The matrix K(ΣH⊤)⊤=(ΣH⊤)S−1(ΣH⊤)⊤K (\Sigma H^\top)^\top = (\Sigma H^\top) S^{-1} (\Sigma H^\top)^\top is symmetric, so the code computes each entry once for c≥rc \ge r and copies it. This proves part 3. Every entry of Σ\Sigma changes, which costs O(n2)O(n^2).

The whole step. By induction over the steps and the readings, parts 1 to 3 keep the invariant "N(μ,Σ)N(\mu, \Sigma) is the exact posterior over the robot state and all landmarks seen so far". The readings of one step are independent given the state, so applying them one after the other is the same as one update with all of them stacked. □\square

The nonlinear case. For the planar models, lines L1, L7 and L8 evaluate the Jacobians at the current mean. Parts 1 to 3 then hold for the linearized models, and not for the true ones. The linearization point moves with the estimate, so the filter can believe it has information that it does not have, for example about the heading. Julier and Uhlmann (2001) and Huang and Dissanayake (2007) show that this makes the nonlinear EKF SLAM inconsistent over long runs: the covariance becomes too small compared with the real error. The tests measure the normalized error on short runs only.

What the tests check. Part 1: the map block does not change and the cross block is GΣxmG \Sigma_{xm}. Part 2: the new block equals the joint Gaussian of the inverse model. Part 3: the sparse update equals the dense Kalman update within 10−1210^{-12}. The whole claim: on a linear model with three landmarks, the filter equals the marginal of the batch weighted least squares solution over all poses and landmarks within 10−910^{-9}, for the mean and the covariance.

Complexity

Let mm be the number of landmarks in the map and kk the number of readings in one step. Costs are in the real RAM model.

  • Prediction: O(m)O(m). Lines L3 and L4 change only the 3 rows and 3 columns of the pose. The map block is untouched, because the landmarks do not move.
  • Update: O(m2)O(m^2) per reading. ΣH⊤\Sigma H^\top costs O(m)O(m) because HH has 5 nonzero columns, but line L11 changes all (3+2m)2(3 + 2m)^2 entries of Σ\Sigma. So a step costs O(km2)O(k m^2).
  • A new landmark: O(m)O(m) for the new rows, plus the time to grow the arrays.
  • Association: O(m)O(m) per reading for the distances, so O(km)O(k m) per step. The distances use only the 5 by 5 block of Σ\Sigma of the pose and the landmark.
  • Memory: O(m2)O(m^2) for Σ\Sigma.

The quadratic cost is the main limit of EKF SLAM. With m=1000m = 1000, Σ\Sigma has about 4 million entries, and every reading changes all of them. Information filters (EIF, SEIF), particle filters (FastSLAM), submaps and graph methods (GraphSLAM) avoid this cost in different ways.

Properties

  • Correlations are the map. After a while, the landmark estimates are strongly correlated with each other. Their positions relative to each other are known much better than their positions in the world frame. Dropping the cross terms to save time makes the filter overconfident and can make it diverge.
  • Monotone map uncertainty, in the linear case. The determinant of the covariance of any set of landmarks never increases, and the covariance of each landmark stays above the covariance of the first pose. These are theorems of Dissanayake et al. (2001) for the linear Gaussian model; see the convergence theorem. The tests check both on random linear runs.
  • Unimodal. The belief has one peak. It cannot keep two hypotheses about a loop closure or an association.
  • Deterministic. The same data give the same result.
  • Order dependent, a little. Each update relinearizes at the new mean, so the order of the readings changes the result slightly. With linear models it does not.

Variants and improvements

  • Unknown correspondences. Nearest neighbor with a chi-square gate, as here, or the maximum likelihood landmark (Thrun et al., Section 10.3). For many readings in one step, joint compatibility branch and bound tests the pairings together and rejects sets that are only individually compatible.
  • Information form. The extended information filter stores Σ−1\Sigma^{-1}. Its update is cheap, but its prediction and its mean recovery are expensive. The sparse extended information filter bounds the number of links per pose, at the cost of an approximation.
  • Submaps. Build small independent EKF maps and join them later, so that each update is cheap. The joining needs care with the shared landmarks.
  • Unscented and iterated filters. The unscented Kalman filter replaces the Jacobians by sigma points, and the iterated EKF relinearizes the update. Both reduce linearization errors but keep the quadratic cost.
  • Consistent Jacobians. Huang and Dissanayake (2007) relate the inconsistency to Jacobians that are evaluated at different estimates of the same quantity. Later filters fix the linearization point of each state to reduce the overconfidence.
  • Smoothing. GraphSLAM and square root SAM keep all poses and solve the full SLAM problem, which avoids the early fixing of linearization points and gives a sparse system.
  • Monocular SLAM. MonoSLAM is EKF SLAM with one camera as the only sensor.

When to use it

Use EKF SLAM for small maps with distinct point landmarks, up to a few hundred, when a full covariance is useful, for example for active exploration or to gate associations. Use it as a reference: on small linear problems it is exact, which makes it a good test for other methods. For large maps or raw range scans, use GraphSLAM or pose graph optimization, FastSLAM, or grid-based Rao-Blackwellized SLAM.

Pitfalls

  • A wrong association. A reading matched to the wrong landmark corrects the whole map in the wrong way, and the filter cannot undo it. The gate reduces the risk; joint tests reduce it more.
  • Inconsistency of the nonlinear filter. Julier and Uhlmann (2001) showed that for a stationary robot that observes a landmark, the nonlinear EKF SLAM reports a heading variance that keeps shrinking, although the readings carry no information about the heading. Over long runs the covariance becomes too small, so later readings fail the gate. Huang and Dissanayake (2007) analyze the cause. Check the normalized error in simulation before trusting the covariance.
  • Angles. Wrap the bearing innovation and the heading after each update, as in EKF localization.
  • The first pose. Starting with Σxx=0\Sigma_{xx} = 0 fixes the frame of the map. The pose covariance then has rank 2 after the first control, so any test that inverts it must wait one more step.
  • Symmetry and positive definiteness. Rounding can make Σ\Sigma slightly asymmetric or indefinite after many updates. Compute each entry once and copy it, as the code does, or use the Joseph form.
  • A duplicate landmark. With one threshold, a reading of a known landmark with a large error creates a second copy of it. A second, larger threshold for new landmarks, or a check on landmarks that are seen only once, avoids this.

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.

ekf_slam.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ekf-slam/. The authors are listed in prov/P959WA.jsonl.

"""EKF SLAM: one Gaussian over the robot pose and all landmark positions.

The state is mu = [x, y, theta, m1x, m1y, m2x, m2y, ...] and Sigma is its
covariance, a list of rows. The planar models follow Thrun, Burgard and Fox
(2005), Chapter 10: the velocity motion model with the control noise
M = diag(a1 v^2 + a2 omega^2, a3 v^2 + a4 omega^2), and range-bearing
readings z = (r, phi) with the noise covariance Q. A landmark enters the
state at its first reading, through the inverse measurement model.

The three core steps are generic, so that the tests can run them on a linear
model too. They change mu and Sigma in place:

  predict(mu, sigma, rdim, mu_x, g, rx)        robot block and cross terms, O(n)
  augment(mu, sigma, idx, new_mean, gs, gz, q)  add a landmark, O(n)
  update(mu, sigma, idx, nu, h, q)              one reading, O(n^2)

Here n = len(mu), rdim is the size of the robot state, idx lists the state
entries that a reading depends on, and h is the Jacobian with respect to
those entries only (all other columns of the full Jacobian are zero).
"""

import math

import rbm
import robest

STRAIGHT = 1e-9  # below this |omega|, the robot moves on a straight line
RDIM = 3  # the planar pose (x, y, theta)


# ---------------------------------------------------------------- planar models


def motion(x, u, dt):
    """Return the noise-free pose after the control u = (v, omega) for dt seconds."""
    px, py, th = x[0], x[1], x[2]
    v, w = u
    if abs(w) < STRAIGHT:
        return [px + v * dt * math.cos(th), py + v * dt * math.sin(th), th]
    r = v / w
    return [
        px - r * math.sin(th) + r * math.sin(th + w * dt),
        py + r * math.cos(th) - r * math.cos(th + w * dt),
        robest.wrap_angle(th + w * dt),
    ]


def motion_jacobians(x, u, dt):
    """Return G = d motion / d pose (3x3) and V = d motion / d u (3x2)."""
    th = x[2]
    v, w = u
    if abs(w) < STRAIGHT:
        c, s = math.cos(th), math.sin(th)
        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 g, vj
    s0, c0 = math.sin(th), math.cos(th)
    s1, c1 = math.sin(th + w * dt), math.cos(th + w * dt)
    g = [[1.0, 0.0, v / w * (c1 - c0)], [0.0, 1.0, v / w * (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 g, vj


def control_noise(u, alphas):
    """Return M = diag(a1 v^2 + a2 omega^2, a3 v^2 + a4 omega^2)."""
    v, w = u
    a1, a2, a3, a4 = alphas
    return [[a1 * v * v + a2 * w * w, 0.0], [0.0, a3 * v * v + a4 * w * w]]


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_jacobians(x, m):
    """Return Hx = d measure / d pose (2x3) and Hm = d measure / d m (2x2)."""
    dx, dy = m[0] - x[0], m[1] - x[1]
    q = dx * dx + dy * dy
    sq = math.sqrt(q)
    hx = [[-dx / sq, -dy / sq, 0.0], [dy / q, -dx / q, -1.0]]
    hm = [[dx / sq, dy / sq], [-dy / q, dx / q]]
    return hx, hm


def inverse_measure(x, z):
    """Return the landmark position 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)]


def inverse_jacobians(x, z):
    """Return Gx = d inverse_measure / d pose (2x3) and Gz = d inverse_measure / d z (2x2)."""
    a = x[2] + z[1]
    c, s = math.cos(a), math.sin(a)
    gx = [[1.0, 0.0, -z[0] * s], [0.0, 1.0, z[0] * c]]
    gz = [[c, -z[0] * s], [s, z[0] * c]]
    return gx, gz


# ---------------------------------------------------------------- generic core


def predict(mu, sigma, rdim, mu_x, g, rx):
    """Move the robot part of the belief, in place: lines L2 to L4.

    mu_x is the predicted robot state, g the Jacobian of the motion with
    respect to the robot state, and rx the covariance of the motion noise in
    robot coordinates. The map block of Sigma does not change, so the cost
    is O(n) for a fixed rdim.
    """
    n = len(mu)
    mu[:rdim] = mu_x  # @line L2
    sxx = [row[:rdim] for row in sigma[:rdim]]
    sxx = rbm.add(rbm.mul(rbm.mul(g, sxx), rbm.transpose(g)), rx)  # @line L3
    sxm = rbm.mul(g, [row[rdim:] for row in sigma[:rdim]]) if n > rdim else [[] for _ in range(rdim)]  # @line L4
    for i in range(rdim):
        sigma[i][:rdim] = sxx[i]
        sigma[i][rdim:] = sxm[i]
    for j in range(n - rdim):
        for i in range(rdim):
            sigma[rdim + j][i] = sxm[i][j]


def augment(mu, sigma, idx, new_mean, gs, gz, q):
    """Append a new landmark to the state, in place: line L7.

    The landmark is new_mean = f(state[idx], z). gs is d f / d state[idx]
    and gz is d f / d z, and q is the covariance of z. The new rows of Sigma
    are gs Sigma[idx, :], and the new diagonal block is
    gs Sigma[idx, idx] gs^T + gz q gz^T.
    """
    n = len(mu)
    k = len(new_mean)
    cross = [[sum(gs[a][c] * sigma[idx[c]][col] for c in range(len(idx))) for col in range(n)] for a in range(k)]
    sii = [[sigma[r][c] for c in idx] for r in idx]
    block = rbm.add(rbm.mul(rbm.mul(gs, sii), rbm.transpose(gs)), rbm.mul(rbm.mul(gz, q), rbm.transpose(gz)))
    for r in range(n):
        sigma[r].extend(cross[a][r] for a in range(k))
    for a in range(k):
        sigma.append(cross[a] + block[a])
    mu.extend(new_mean)


def update(mu, sigma, idx, nu, h, q):
    """Apply one reading with innovation nu, in place: lines L9 to L11.

    h is the Jacobian of the reading with respect to state[idx]. The full
    Jacobian H is zero outside the columns idx, so Sigma H^T costs O(n) and
    the covariance update Sigma - K S K^T costs O(n^2).
    """
    n = len(mu)
    d = len(nu)
    k = len(idx)
    pht = [[sum(sigma[r][idx[c]] * h[a][c] for c in range(k)) for a in range(d)] for r in range(n)]
    s = [[sum(h[a][c] * pht[idx[c]][b] for c in range(k)) + q[a][b] for b in range(d)] for a in range(d)]
    sinv = rbm.inv(s)  # @line L9
    kg = [[sum(pht[r][a] * sinv[a][b] for a in range(d)) for b in range(d)] for r in range(n)]
    for r in range(n):
        mu[r] += sum(kg[r][b] * nu[b] for b in range(d))  # @line L10
    for r in range(n):
        kr = kg[r]
        row = sigma[r]
        for c in range(r, n):
            val = row[c] - sum(kr[a] * pht[c][a] for a in range(d))  # @line L11
            row[c] = val
            sigma[c][r] = val


# ---------------------------------------------------------------- planar EKF SLAM


def landmark_index(slot):
    """Return the index of the first coordinate of landmark slot in the state."""
    return RDIM + 2 * slot


def innovation(mu, sigma, slot, z, q):
    """Return (nu, idx, h, S) for the reading z of the landmark in the given slot."""
    j = landmark_index(slot)
    m = mu[j:j + 2]
    zhat = measure(mu, m)
    hx, hm = measure_jacobians(mu, m)
    h = [hx[0] + hm[0], hx[1] + hm[1]]
    idx = [0, 1, 2, j, j + 1]
    nu = [z[0] - zhat[0], robest.wrap_angle(z[1] - zhat[1])]
    s = [[sum(h[a][c] * sum(sigma[idx[c]][idx[e]] * h[b][e] for e in range(5)) for c in range(5)) + q[a][b] for b in range(2)] for a in range(2)]
    return nu, idx, h, s


def nearest(mu, sigma, z, q):
    """Return (slot, d2) of the landmark with the smallest nu^T S^(-1) nu, or (None, inf)."""
    best, best_d2 = None, math.inf
    for slot in range((len(mu) - RDIM) // 2):
        nu, _, _, s = innovation(mu, sigma, slot, z, q)
        d2 = robest.mahalanobis2(nu, [0.0, 0.0], s)
        if d2 < best_d2:
            best, best_d2 = slot, d2
    return best, best_d2


def ekf_slam(mu, sigma, ids, u, dt, zs, alphas, q, correspondences=None, gate=robest.CHI2[(2, 0.99)], new_gate=None):
    """One step of EKF SLAM, in place: lines L1 to L12.

    ids lists the landmark identifiers in the order of the state. With
    known correspondences, correspondences[i] is the identifier of the
    landmark of zs[i]. Otherwise each reading goes to the nearest landmark
    if its squared Mahalanobis distance is at most gate. If the distance is
    above new_gate (by default equal to gate), the reading starts a new
    landmark with the next free integer identifier; between the two
    thresholds the reading is dropped. Return the list of the identifiers
    used, with None for a dropped reading.
    """
    if new_gate is None:
        new_gate = gate
    g, vj = motion_jacobians(mu, u, dt)  # @line L1
    rx = rbm.mul(rbm.mul(vj, control_noise(u, alphas)), rbm.transpose(vj))
    predict(mu, sigma, RDIM, motion(mu, u, dt), g, rx)
    used = []
    for i, z in enumerate(zs):  # @line L5
        if correspondences is not None:
            lid = correspondences[i]
            slot = ids.index(lid) if lid in ids else None
        else:
            slot, d2 = nearest(mu, sigma, z, q)  # @line L6
            if gate < d2 <= new_gate:
                used.append(None)
                continue
            if d2 > new_gate:
                slot = None
            lid = ids[slot] if slot is not None else len(ids)
        if slot is None:
            gx, gz = inverse_jacobians(mu, z)
            augment(mu, sigma, [0, 1, 2], inverse_measure(mu, z), gx, gz, q)  # @line L7
            ids.append(lid)
            used.append(lid)
            continue
        nu, idx, h, _ = innovation(mu, sigma, slot, z, q)  # @line L8
        update(mu, sigma, idx, nu, h, q)
        mu[2] = robest.wrap_angle(mu[2])
        used.append(lid)
    return used  # @line L12
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_ekf_slam.py 287 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ekf-slam/. The authors are listed in prov/P959WA.jsonl.

import math
import random

import pytest

import rbm
import robest
from ekf_slam import (
    augment,
    ekf_slam,
    inverse_jacobians,
    inverse_measure,
    measure,
    measure_jacobians,
    motion,
    motion_jacobians,
    predict,
    update,
)

ALPHAS = (0.01, 0.005, 0.005, 0.01)
Q = [[0.1 ** 2, 0.0], [0.0, 0.03 ** 2]]
LANDMARKS = [[4.0, 0.0], [4.0, 4.0], [0.0, 4.0], [-3.0, 2.0], [-2.0, -3.0], [2.0, -3.0]]


def mat_close(a, b, tol):
    return all(abs(x - y) <= tol for ra, rb in zip(a, b) for x, y in zip(ra, rb))


def copy(mu, sigma):
    return list(mu), [list(row) for row in sigma]


# ---------------------------------------------------------------- Jacobians


@pytest.mark.parametrize("x,u", [([1.0, 2.0, 0.3], (1.0, 0.4)), ([0.0, 0.0, -2.0], (0.5, -1.2)), ([2.0, -1.0, 1.0], (0.8, 0.0))])
def test_motion_jacobians_against_finite_differences(x, u):
    g, v = motion_jacobians(x, u, 0.5)
    assert mat_close(g, rbm.num_jacobian(lambda y: motion(y, u, 0.5), x), 1e-6)
    if u[1] != 0.0:
        assert mat_close(v, rbm.num_jacobian(lambda c: motion(x, c, 0.5), list(u)), 1e-6)


@pytest.mark.parametrize("x,m", [([0.0, 0.0, 0.0], [3.0, 1.0]), ([1.0, -2.0, 2.5], [-1.0, 0.5]), ([0.5, 0.5, -1.0], [0.5, 3.0])])
def test_measurement_jacobians_against_finite_differences(x, m):
    hx, hm = measure_jacobians(x, m)
    assert mat_close(hx, rbm.num_jacobian(lambda y: measure(y, m), x), 1e-6)
    assert mat_close(hm, rbm.num_jacobian(lambda y: measure(x, y), m), 1e-6)


@pytest.mark.parametrize("x,z", [([0.0, 0.0, 0.0], [3.0, 0.4]), ([1.0, -2.0, 2.5], [1.5, -2.0])])
def test_inverse_model_and_its_jacobians(x, z):
    m = inverse_measure(x, z)
    back = measure(x, m)
    assert abs(back[0] - z[0]) < 1e-12 and abs(robest.wrap_angle(back[1] - z[1])) < 1e-12
    gx, gz = inverse_jacobians(x, z)
    assert mat_close(gx, rbm.num_jacobian(lambda y: inverse_measure(y, z), x), 1e-6)
    assert mat_close(gz, rbm.num_jacobian(lambda y: inverse_measure(x, y), z), 1e-6)


# ---------------------------------------------------------------- core steps


def random_belief(rng, n):
    a = [[rng.uniform(-1.0, 1.0) for _ in range(n)] for _ in range(n)]
    s = rbm.add(rbm.mul(a, rbm.transpose(a)), rbm.scale(rbm.eye(n), 0.5))
    return [rng.uniform(-3.0, 3.0) for _ in range(n)], s


def test_prediction_leaves_the_map_block_unchanged():
    rng = random.Random(1)
    mu, sigma = random_belief(rng, 9)
    mu[2] = 0.4
    before = copy(mu, sigma)
    g, vj = motion_jacobians(mu, (1.0, 0.3), 1.0)
    rx = rbm.mul(rbm.mul(vj, [[0.02, 0.0], [0.0, 0.01]]), rbm.transpose(vj))
    predict(mu, sigma, 3, motion(mu, (1.0, 0.3), 1.0), g, rx)
    assert mu[3:] == before[0][3:]
    assert all(sigma[r][c] == before[1][r][c] for r in range(3, 9) for c in range(3, 9))
    want_xm = rbm.mul(g, [row[3:] for row in before[1][:3]])
    assert mat_close([row[3:] for row in sigma[:3]], want_xm, 1e-12)
    assert mat_close(sigma, rbm.transpose(sigma), 0.0)


def test_sparse_update_equals_the_dense_kalman_update():
    rng = random.Random(2)
    mu, sigma = random_belief(rng, 11)
    idx = [0, 1, 2, 7, 8]
    h = [[rng.uniform(-1, 1) for _ in range(5)] for _ in range(2)]
    nu = [0.3, -0.2]
    full_h = [[0.0] * 11 for _ in range(2)]
    for a in range(2):
        for c, j in enumerate(idx):
            full_h[a][j] = h[a][c]
    s = rbm.add(rbm.mul(rbm.mul(full_h, sigma), rbm.transpose(full_h)), Q)
    k = rbm.mul(rbm.mul(sigma, rbm.transpose(full_h)), rbm.inv(s))
    want_mu = rbm.add(mu, rbm.matvec(k, nu))
    want_sigma = rbm.mul(rbm.sub(rbm.eye(11), rbm.mul(k, full_h)), sigma)
    update(mu, sigma, idx, nu, h, Q)
    assert all(abs(a - b) < 1e-12 for a, b in zip(mu, want_mu))
    assert mat_close(sigma, want_sigma, 1e-12)


def test_augment_matches_the_joint_gaussian_of_the_inverse_model():
    mu = [1.0, 2.0, 0.5]
    sigma = [[0.04, 0.01, 0.0], [0.01, 0.05, 0.002], [0.0, 0.002, 0.01]]
    z = [2.0, 0.3]
    augment(mu, sigma, [0, 1, 2], inverse_measure(mu, z), *inverse_jacobians(mu, z), Q)
    gx, gz = inverse_jacobians(mu[:3], z)
    full = [row + [0.0, 0.0] for row in [[0.04, 0.01, 0.0], [0.01, 0.05, 0.002], [0.0, 0.002, 0.01]]]
    full += [[0.0] * 3 + [Q[0][0], 0.0], [0.0] * 3 + [0.0, Q[1][1]]]
    j = [gx[0] + gz[0], gx[1] + gz[1]]
    a = [[1.0 if i == c else 0.0 for c in range(5)] for i in range(3)] + j
    want = rbm.mul(rbm.mul(a, full), rbm.transpose(a))
    assert mat_close(sigma, want, 1e-15)


# ---------------------------------------------------------------- linear SLAM


def linear_run(rng, steps, landmarks, p0, rw, rq, stationary=False):
    """Simulate z = m_j - x + noise and x' = x + u + noise; return the data."""
    x = [0.0, 0.0]
    data = []
    for _ in range(steps):
        u = [0.0, 0.0] if stationary else [rng.uniform(-0.5, 1.0), rng.uniform(-0.5, 1.0)]
        x = rbm.add(rbm.add(x, u), robest.gauss_sample(rng, [0.0, 0.0], rw)) if not stationary else x
        zs = [(j, rbm.add(rbm.sub(m, x), robest.gauss_sample(rng, [0.0, 0.0], rq))) for j, m in enumerate(landmarks)]
        data.append((u, zs))
    return data


def linear_filter(data, p0, rw, rq, record=None):
    """EKF SLAM with the generic core on the linear translation model."""
    mu, sigma, ids = [0.0, 0.0], [list(r) for r in p0], []
    for u, zs in data:
        predict(mu, sigma, 2, rbm.add(mu[:2], u), rbm.eye(2), rw)
        for j, z in zs:
            if j not in ids:
                augment(mu, sigma, [0, 1], rbm.add(mu[:2], z), rbm.eye(2), rbm.eye(2), rq)
                ids.append(j)
                continue
            k = 2 + 2 * ids.index(j)
            nu = rbm.sub(z, rbm.sub(mu[k:k + 2], mu[:2]))
            update(mu, sigma, [0, 1, k, k + 1], nu, [[-1.0, 0.0, 1.0, 0.0], [0.0, -1.0, 0.0, 1.0]], rq)
        if record is not None:
            record.append(copy(mu, sigma))
    return mu, sigma, ids


def batch_solution(data, p0, rw, rq, nl):
    """Weighted least squares over all poses and landmarks (the full SLAM posterior)."""
    t = len(data)
    n = 2 * (t + 1) + 2 * nl
    lam = rbm.zeros(n, n)
    eta = [0.0] * n

    def add_factor(cols, a, b, info):
        # factor a y[cols] = b with information info
        at_i = rbm.mul(rbm.transpose(a), info)
        blk = rbm.mul(at_i, a)
        vec = rbm.matvec(at_i, b)
        for r, cr in enumerate(cols):
            eta[cr] += vec[r]
            for c, cc in enumerate(cols):
                lam[cr][cc] += blk[r][c]

    i2 = rbm.eye(2)
    add_factor([0, 1], i2, [0.0, 0.0], rbm.inv(p0))
    wi, qi = rbm.inv(rw), rbm.inv(rq)
    for k, (u, zs) in enumerate(data):
        a, b = 2 * k, 2 * k + 2
        add_factor([a, a + 1, b, b + 1], [[-1.0, 0.0, 1.0, 0.0], [0.0, -1.0, 0.0, 1.0]], u, wi)
        for j, z in zs:
            m = 2 * (t + 1) + 2 * j
            add_factor([b, b + 1, m, m + 1], [[-1.0, 0.0, 1.0, 0.0], [0.0, -1.0, 0.0, 1.0]], z, qi)
    return rbm.solve(lam, eta), rbm.inv(lam)


def test_linear_ekf_slam_equals_batch_least_squares():
    rng = random.Random(3)
    p0, rw, rq = [[0.02, 0.0], [0.0, 0.03]], [[0.01, 0.002], [0.002, 0.02]], [[0.05, 0.0], [0.0, 0.04]]
    landmarks = [[3.0, 1.0], [-1.0, 4.0], [2.0, -2.0]]
    data = linear_run(rng, 6, landmarks, p0, rw, rq)
    mu, sigma, ids = linear_filter(data, p0, rw, rq)
    y, cov = batch_solution(data, p0, rw, rq, len(landmarks))
    t = len(data)
    cols = [2 * t, 2 * t + 1] + [2 * (t + 1) + 2 * j + c for j in ids for c in range(2)]
    assert all(abs(mu[i] - y[c]) < 1e-9 for i, c in enumerate(cols))
    assert all(abs(sigma[i][k] - cov[c][d]) < 1e-9 for i, c in enumerate(cols) for k, d in enumerate(cols))


def test_map_determinants_never_increase_in_the_linear_case():
    rng = random.Random(4)
    p0, rw, rq = [[0.1, 0.0], [0.0, 0.1]], [[0.02, 0.0], [0.0, 0.02]], [[0.05, 0.01], [0.01, 0.05]]
    data = linear_run(rng, 25, [[3.0, 1.0], [-1.0, 4.0], [2.0, -2.0]], p0, rw, rq)
    rec = []
    linear_filter(data, p0, rw, rq, rec)
    for sub in ([2, 3], [4, 5], [2, 3, 4, 5], [2, 3, 4, 5, 6, 7], [3, 6]):
        dets = [rbm.det([[s[r][c] for c in sub] for r in sub]) for _, s in rec]
        assert all(b <= a * (1.0 + 1e-12) for a, b in zip(dets, dets[1:]))


def test_landmark_covariance_stays_above_the_initial_robot_covariance():
    rng = random.Random(5)
    p0, rw, rq = [[0.1, 0.03], [0.03, 0.2]], [[0.02, 0.0], [0.0, 0.01]], [[0.05, 0.0], [0.0, 0.05]]
    data = linear_run(rng, 40, [[3.0, 1.0], [-1.0, 4.0]], p0, rw, rq)
    rec = []
    linear_filter(data, p0, rw, rq, rec)
    for _, s in rec:
        for k in (2, 4):
            d = [[s[k][k] - p0[0][0], s[k][k + 1] - p0[0][1]], [s[k + 1][k] - p0[1][0], s[k + 1][k + 1] - p0[1][1]]]
            assert d[0][0] >= -1e-12 and d[1][1] >= -1e-12 and rbm.det(d) >= -1e-12


def test_landmarks_become_fully_correlated():
    rng = random.Random(6)
    p0, rq = [[0.1, 0.0], [0.0, 0.1]], [[0.05, 0.0], [0.0, 0.05]]
    data = linear_run(rng, 50, [[3.0, 1.0], [-1.0, 4.0]], p0, rbm.zeros(2, 2), rq, stationary=True)
    rec = []
    linear_filter(data, p0, rbm.zeros(2, 2), rq, rec)
    for k, (_, s) in enumerate(rec, start=1):
        var_diff = s[2][2] + s[4][4] - 2.0 * s[2][4]
        assert var_diff <= 2.0 * rq[0][0] / k + 1e-12
    s = rec[-1][1]
    assert s[2][4] / math.sqrt(s[2][2] * s[4][4]) > 0.98


# ---------------------------------------------------------------- planar SLAM


def planar_run(rng, steps, correspondences=True, new_gate=None):
    x = [0.0, 0.0, 0.0]
    mu, sigma, ids = [0.0, 0.0, 0.0], rbm.zeros(3, 3), []
    nees = []
    for t in range(steps):
        u = (1.0, 0.35)
        m = robest.gauss_sample(rng, [0.0, 0.0], [[ALPHAS[0] + ALPHAS[1] * u[1] ** 2, 0.0], [0.0, ALPHAS[2] + ALPHAS[3] * u[1] ** 2]])
        x = motion(x, (u[0] + m[0], u[1] + m[1]), 1.0)
        zs, cs = [], []
        for j, lm in enumerate(LANDMARKS):
            z = measure(x, lm)
            if z[0] < 5.0:
                zs.append([z[0] + rng.gauss(0.0, 0.1), robest.wrap_angle(z[1] + rng.gauss(0.0, 0.03))])
                cs.append(j)
        ekf_slam(mu, sigma, ids, u, 1.0, zs, ALPHAS, Q, cs if correspondences else None, new_gate=new_gate)
        if t == 0:
            continue  # the pose covariance has rank 2 after the first control
        e = [x[0] - mu[0], x[1] - mu[1], robest.wrap_angle(x[2] - mu[2])]
        nees.append(robest.mahalanobis2(e, [0.0, 0.0, 0.0], [row[:3] for row in sigma[:3]]))
    return mu, sigma, ids, nees


def test_planar_run_with_known_correspondences_is_close_and_consistent():
    rng = random.Random(7)
    all_nees, map_nees = [], []
    for _ in range(10):
        mu, sigma, ids, nees = planar_run(rng, 25)
        all_nees.extend(nees)
        assert sorted(ids) == list(range(len(LANDMARKS)))
        for slot, j in enumerate(ids):
            k = 3 + 2 * slot
            map_nees.append(robest.mahalanobis2(mu[k:k + 2], LANDMARKS[j], [row[k:k + 2] for row in sigma[k:k + 2]]))
    assert 1.5 < sum(all_nees) / len(all_nees) < 6.0  # measured 2.59; 3 for a consistent filter
    assert 1.0 < sum(map_nees) / len(map_nees) < 4.0  # measured 2.13; 2 for a consistent filter


def test_unknown_correspondences_find_each_landmark_once():
    rng = random.Random(8)
    mu, sigma, ids, _ = planar_run(rng, 25, correspondences=False, new_gate=100.0)
    found = []
    for slot in range(len(ids)):
        k = 3 + 2 * slot
        d = [math.hypot(mu[k] - lm[0], mu[k + 1] - lm[1]) for lm in LANDMARKS]
        j = min(range(len(LANDMARKS)), key=lambda i: d[i])
        assert d[j] < 1.5 and sorted(d)[1] > 2.0  # the map as a whole may drift; the match is clear
        found.append(j)
    assert sorted(found) == list(range(len(LANDMARKS)))
    # the shape of the map is right: pairwise distances agree within 0.2 m
    est = [mu[3 + 2 * s:5 + 2 * s] for s in range(len(ids))]
    for a in range(len(est)):
        for b in range(a):
            assert abs(math.dist(est[a], est[b]) - math.dist(LANDMARKS[found[a]], LANDMARKS[found[b]])) < 0.2

History

Smith and Cheeseman (1986) gave a calculus for uncertain spatial relations, with means and covariances that compound along chains of frames. Smith, Self and Cheeseman (1990) put the robot and all objects into one state vector, the stochastic map, and showed that the estimates of the objects become correlated through the robot. This is EKF SLAM. Leonard and Durrant-Whyte used the same filter with sonar on real robots in the early 1990s, and the problem got the name SLAM in the mid 1990s. Dissanayake et al. (2001) proved the convergence of the map covariance in the linear case and ran the filter outdoors with millimeter wave radar. Julier and Uhlmann (2001) gave a counterexample to its consistency in the nonlinear case, and Huang and Dissanayake (2007) analyzed it. Thrun, Burgard and Fox (2005) present EKF SLAM in Chapter 10 of Probabilistic Robotics, and Durrant-Whyte and Bailey (2006) in their tutorial.

References

  1. Sebastian Thrun, Wolfram Burgard and Dieter Fox, Probabilistic Robotics, MIT Press, 2005, Chapter 10, Section 10.2 (EKF SLAM with known correspondences) and Section 10.3 (EKF SLAM with unknown correspondences)
  2. Randall C. Smith and Peter Cheeseman, On the representation and estimation of spatial uncertainty, International Journal of Robotics Research 5(4), 1986, pages 56 to 68, the representation of uncertain relations between frames by a mean and a covariance, and their compounding
  3. Randall Smith, Matthew Self and Peter Cheeseman, Estimating uncertain spatial relationships in robotics, in Ingemar J. Cox and Gordon T. Wilfong (eds.), Autonomous Robot Vehicles, Springer, 1990, the stochastic map, one state vector and one covariance for the robot and all objects, with the addition of new objects
  4. M. W. M. Gamini Dissanayake, Paul Newman, Steven Clark, Hugh F. Durrant-Whyte and M. Csorba, A solution to the simultaneous localization and map building (SLAM) problem, IEEE Transactions on Robotics and Automation 17(3), 2001, pages 229 to 241, Section III (the convergence of the map covariance in the linear case) and the experiments with millimeter wave radar
  5. Simon J. Julier and Jeffrey K. Uhlmann, A counter example to the theory of simultaneous localization and map building, Proceedings of the IEEE International Conference on Robotics and Automation, 2001, the inconsistency of the nonlinear EKF SLAM for a stationary robot
  6. Shoudong Huang and Gamini Dissanayake, Convergence and consistency analysis for extended Kalman filter based SLAM, IEEE Transactions on Robotics 23(5), 2007, pages 1036 to 1049, the analysis of the nonlinear planar EKF SLAM with range and bearing readings, and the role of the Jacobians evaluated at different estimates
  7. Hugh Durrant-Whyte and Tim Bailey, Simultaneous localization and mapping, part I, IEEE Robotics and Automation Magazine 13(2), 2006, from page 99, the EKF SLAM formulation and the history of the problem

Where this leads

About this page

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

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