Algorithm Search⌘K

Algorithmcore

EKF localization

Also called extended Kalman filter localization.

Tracks the pose of a robot in a map of point landmarks with an extended Kalman filter. Fast, but it needs a good initial pose and correct data association.

Time
O(T k) known_correspondencesO(T k m) unknown_correspondences
Space
O(1) extra
Where
T = the number of time steps; k = the number of readings in one step; m = the number of landmarks of the map
Properties
deterministicnot exactonlinerecursive
Origin
John J. Leonard, Hugh F. Durrant Whyte, 1991

EKF localization tracks the pose (x,y,θ)(x, y, \theta) of a mobile robot in a known map with an extended Kalman filter. The belief is one Gaussian with mean μt\mu_t and covariance Σt\Sigma_t. A prediction moves it with the velocity motion model, linearized at the mean, and each range and bearing reading of a landmark corrects it, with the landmark measurement model linearized in the same way. One step costs a few small matrix products, so it is the cheapest of the localization filters. In exchange it has two needs: the robot must know its pose to within the range where the linearization holds, and each reading must be matched to the right landmark. This page gives the algorithm of Thrun, Burgard and Fox (Section 7.4), the maximum likelihood association with a chi-square gate, a step with real numbers and a consistency test.

In plain words

The robot keeps one best guess of its pose and a measure of how unsure it is, as an ellipse around the guess. When it drives, it moves the guess by the commanded motion and makes the ellipse larger, because the wheels slip. When it sees a known landmark, it compares where the landmark appears with where the guess says it should appear. The difference moves the guess, more if the guess was unsure and less if the sensor is noisy, and the ellipse gets smaller. If a reading is too far from every landmark, the robot ignores it.

The problem

The input is a map of mm point landmarks mj=(mj,x,mj,y)m_j = (m_{j,x}, m_{j,y}), a Gaussian prior N(μ0,Σ0)N(\mu_0, \Sigma_0) on the pose, 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). The output is a Gaussian approximation N(μt,Σt)N(\mu_t, \Sigma_t) of p(xt∣z1:t,u1:t,m)p(x_t \mid z_{1:t}, u_{1:t}, m). This is the tracking case of mobile robot localization.

Motion model. With θ=μt−1,θ\theta = \mu_{t-1,\theta}, the noise-free motion is

g(ut,xt−1)=xt−1+(−vωsin⁡θ+vωsin⁡(θ+ωΔt)vωcos⁡θ−vωcos⁡(θ+ωΔt)ωΔt)g(u_t, x_{t-1}) = x_{t-1} + \begin{pmatrix} -\tfrac{v}{\omega} \sin\theta + \tfrac{v}{\omega} \sin(\theta + \omega \Delta t) \\ \tfrac{v}{\omega} \cos\theta - \tfrac{v}{\omega} \cos(\theta + \omega \Delta t) \\ \omega \Delta t \end{pmatrix}

for ω≠0\omega \ne 0, and a straight line (vΔtcos⁡θ,vΔtsin⁡θ,0)(v \Delta t \cos\theta, v \Delta t \sin\theta, 0) for ω=0\omega = 0. The control noise has the covariance 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). The αi\alpha_i are fitted to the robot; they are not derived. The final rotation term of the full velocity model is left out, as in Thrun et al.

Measurement model. With q=(mj,x−x)2+(mj,y−y)2q = (m_{j,x} - x)^2 + (m_{j,y} - y)^2, a landmark jj is seen at

h(xt,j)=(qatan2⁡(mj,y−y,mj,x−x)−θ)h(x_t, j) = \begin{pmatrix} \sqrt{q} \\ \operatorname{atan2}(m_{j,y} - y, m_{j,x} - x) - \theta \end{pmatrix}

plus noise N(0,Qt)N(0, Q_t) with Qt=diag(σr2,σϕ2)Q_t = \mathrm{diag}(\sigma_r^2, \sigma_\phi^2). Readings are independent given the pose. The bearing and the heading wrap to [−π,π)[-\pi, \pi).

Correspondences. The index ctic_t^i of the landmark of reading ii is either given (known correspondences) or must be estimated.

The algorithm

  1. EKF-LOCALIZATION(μ, Σ, u_t, z_t, m) ▷ u_t = (v, ω), θ = μ_θ
  2. 1G_t ← ∂g/∂x at (u_t, μ); V_t ← ∂g/∂u at (u_t, μ)
  3. 2M_t ← diag(α1 v² + α2 ω², α3 v² + α4 ω²)
  4. 3μ̄ ← g(u_t, μ)
  5. 4Σ̄ ← G_t Σ G_tᵀ + V_t M_t V_tᵀ
  6. 5for each reading z^i = (r^i, φ^i) in z_t do
  7. 6j ← c^i if known, else the most likely landmark that passes the gate (or skip z^i)
  8. 7ẑ ← h(μ̄, j)
  9. 8H ← ∂h/∂x at μ̄ = [[-Δx/√q, -Δy/√q, 0], [Δy/q, -Δx/q, -1]]
  10. 9S ← H Σ̄ Hᵀ + Q_t
  11. 10K ← Σ̄ Hᵀ S⁻¹
  12. 11μ̄ ← μ̄ + K wrap(z^i - ẑ)
  13. 12Σ̄ ← (I - K H) Σ̄
  14. 13return μ̄, Σ̄

Here Δx=mj,x−μˉx\Delta x = m_{j,x} - \bar\mu_x and Δy=mj,y−μˉy\Delta y = m_{j,y} - \bar\mu_y. For ω≠0\omega \ne 0 the Jacobians are

Gt=(10vω(cos⁡(θ+ωΔt)−cos⁡θ)01vω(sin⁡(θ+ωΔt)−sin⁡θ)001),G_t = \begin{pmatrix} 1 & 0 & \tfrac{v}{\omega}(\cos(\theta + \omega\Delta t) - \cos\theta) \\ 0 & 1 & \tfrac{v}{\omega}(\sin(\theta + \omega\Delta t) - \sin\theta) \\ 0 & 0 & 1 \end{pmatrix},

and VtV_t has the columns ∂g/∂v\partial g / \partial v and ∂g/∂ω\partial g / \partial \omega, given in full in the code. For ω→0\omega \to 0 the code takes the limits, for example ∂gx/∂ω→−vΔt2sin⁡θ/2\partial g_x / \partial \omega \to -v \Delta t^2 \sin\theta / 2. Lines L1 to L4 are the prediction of the EKF. Lines L5 to L12 apply the readings one after the other. Because the readings are independent given the pose, this gives the same result as one update with the stacked readings, up to the relinearization at the new mean after each reading.

Line L6, unknown correspondences. For each landmark jj, compute the innovation νj=zi−h(μˉ,j)\nu_j = z^i - h(\bar\mu, j) and its covariance SjS_j. Thrun et al. (Section 7.5) choose the jj with the largest likelihood det⁡(2πSj)−1/2exp⁡(−12νj⊤Sj−1νj)\det(2\pi S_j)^{-1/2} \exp(-\tfrac{1}{2} \nu_j^\top S_j^{-1} \nu_j). The code also applies the validation gate of Leonard and Durrant-Whyte: jj is a candidate only if νj⊤Sj−1νj≤9.210\nu_j^\top S_j^{-1} \nu_j \le 9.210, the 0.990.99 quantile of the chi-square distribution with 2 degrees of freedom. A reading with no candidate is dropped. If the innovation were exactly Gaussian, a correct reading would fail the gate with probability 0.010.01; the level is a choice of the user.

Example

One step. The prior is μ0=(0,0,0)\mu_0 = (0, 0, 0) and Σ0=diag(0.01,0.01,0.0025)\Sigma_0 = \mathrm{diag}(0.01, 0.01, 0.0025), so standard deviations of 10 cm, 10 cm and 0.05 rad. The control is v=1v = 1 m/s and ω=0.5\omega = 0.5 rad/s for Δt=1\Delta t = 1 s, with α=(0.01,0.005,0.005,0.01)\alpha = (0.01, 0.005, 0.005, 0.01), so M=diag(0.01125,0.0075)M = \mathrm{diag}(0.01125, 0.0075).

  • L1: G=(10−0.2448010.9589001)G = \begin{pmatrix} 1 & 0 & -0.2448 \\ 0 & 1 & 0.9589 \\ 0 & 0 & 1 \end{pmatrix} and V=(0.9589−0.16250.24480.469201)V = \begin{pmatrix} 0.9589 & -0.1625 \\ 0.2448 & 0.4692 \\ 0 & 1 \end{pmatrix}.
  • L3: μˉ=(2sin⁡0.5, 2−2cos⁡0.5, 0.5)=(0.9589,0.2448,0.5)\bar\mu = (2 \sin 0.5,\ 2 - 2 \cos 0.5,\ 0.5) = (0.9589, 0.2448, 0.5).
  • L4: the standard deviations grow to (0.144,0.121,0.100)(0.144, 0.121, 0.100), and Σˉ\bar\Sigma gets a correlation between yy and θ\theta (Σˉyθ=0.0059\bar\Sigma_{y\theta} = 0.0059): a heading error moves the robot sideways.

The true pose is (1.0,0.2,0.45)(1.0, 0.2, 0.45). A landmark at (5,0)(5, 0) is read at z=(4.00,−0.500)z = (4.00, -0.500), with σr=0.1\sigma_r = 0.1 m and σϕ=0.03\sigma_\phi = 0.03 rad.

  • L7: z^=(4.0486,−0.5605)\hat z = (4.0486, -0.5605), so the innovation is ν=(−0.0486,0.0605)\nu = (-0.0486, 0.0605).
  • L8: H=(−0.99820.06050−0.0149−0.2466−1)H = \begin{pmatrix} -0.9982 & 0.0605 & 0 \\ -0.0149 & -0.2466 & -1 \end{pmatrix}.
  • L9: S=(0.0305−0.0017−0.00170.0147)S = \begin{pmatrix} 0.0305 & -0.0017 \\ -0.0017 & 0.0147 \end{pmatrix}, and ν⊤S−1ν=0.306\nu^\top S^{-1} \nu = 0.306, far inside the gate.
  • L11 and L12: μ=(0.9916,0.2078,0.4517)\mu = (0.9916, 0.2078, 0.4517), and the standard deviations shrink to (0.083,0.091,0.033)(0.083, 0.091, 0.033).

One bearing reading fixes the heading well, because the bearing depends on θ\theta directly. The position along the line of sight to the landmark improves through the range, and the position across it only through the correlation with θ\theta.

Consistency. A filter is consistent if its covariance matches its real error. The test runs 50 simulations of 20 steps with four landmarks and the noise of the model, and computes the normalized estimation error squared e⊤Σ−1ee^\top \Sigma^{-1} e with e=xt−μte = x_t - \mu_t. For a consistent filter its mean is 3, the dimension of the pose. The measured mean over the 1000 steps is 3.043.04. This is a measurement for these noise levels; with larger heading noise or few landmarks, the linearization error makes the EKF overconfident, and the mean grows above 3.

Correctness

For a linear motion model and a linear measurement model with Gaussian noise, the algorithm is the Kalman filter, and its output is the exact posterior. For the nonlinear models here, the EKF replaces gg and hh by their first order Taylor expansions at the current mean, so the output is an approximation with no general error bound. The correctness proof shows what is exact: the prediction is the exact moment propagation of the linearized model, each update is the exact Bayes update of the linearized measurement, and the update in lines L10 to L12 equals the information form Σ−1←Σˉ−1+H⊤Q−1H\Sigma^{-1} \leftarrow \bar\Sigma^{-1} + H^\top Q^{-1} H. The tests check the Jacobians against central differences, the update against the information form, and the consistency by the NEES test.

Proof: EKF localization is the exact Bayes filter of the linearized modelsfull

Setting. The state is the pose x∈R3x \in \mathbb{R}^3. One step of EKF localization takes the belief N(μ,Σ)N(\mu, \Sigma), a control uu and readings z1,…,zkz^1, \dots, z^k with known landmarks j1,…,jkj_1, \dots, j_k (line L6 with known correspondences). Let G=∂g/∂xG = \partial g / \partial x and V=∂g/∂uV = \partial g / \partial u at (u,μ)(u, \mu), and let MM be the covariance of the control noise. The linearized motion model is

xt=g(u,μ)+G(xt−1−μ)+Vε,ε∼N(0,M).x_t = g(u, \mu) + G (x_{t-1} - \mu) + V \varepsilon, \qquad \varepsilon \sim N(0, M).

For a reading of landmark jj with the current mean μˉ\bar\mu and H=∂h/∂xH = \partial h / \partial x at μˉ\bar\mu, the linearized measurement model is

z=h(μˉ,j)+H(xt−μˉ)+δ,δ∼N(0,Q).z = h(\bar\mu, j) + H (x_t - \bar\mu) + \delta, \qquad \delta \sim N(0, Q).

The noises ε\varepsilon and δ\delta of each reading are independent of each other and of the state.

Assumptions.

  • (A1) Σ\Sigma, QQ and MM are symmetric; Σ\Sigma and QQ are positive definite.
  • (A2) The bearing innovation is wrapped so that it represents the angle difference in [−π,π)[-\pi, \pi). In the linearized model angles are real numbers, so this assumption only says which real number the code uses.

Claim.

  1. If xt−1∼N(μ,Σ)x_{t-1} \sim N(\mu, \Sigma), then under the linearized motion model xt∼N(μˉ,Σˉ)x_t \sim N(\bar\mu, \bar\Sigma) with μˉ\bar\mu and Σˉ\bar\Sigma of lines L3 and L4.
  2. If xt∼N(μˉ,Σˉ)x_t \sim N(\bar\mu, \bar\Sigma), then under the linearized measurement model the posterior p(xt∣z)p(x_t \mid z) is N(μ′,Σ′)N(\mu', \Sigma') with μ′\mu' and Σ′\Sigma' of lines L7 to L12. Also Σ′−1=Σˉ−1+H⊤Q−1H\Sigma'^{-1} = \bar\Sigma^{-1} + H^\top Q^{-1} H and μ′=μˉ+Σ′H⊤Q−1ν\mu' = \bar\mu + \Sigma' H^\top Q^{-1} \nu, where ν=z−h(μˉ,j)\nu = z - h(\bar\mu, j).
  3. So one step of EKF localization is the exact Bayes filter for the models that are linearized at the current mean, with the measurements of one step applied one after the other. For the nonlinear models, the result is an approximation; this proof gives no bound on its error.

Proof.

Part 1. The map (xt−1,ε)↦g(u,μ)+G(xt−1−μ)+Vε(x_{t-1}, \varepsilon) \mapsto g(u, \mu) + G (x_{t-1} - \mu) + V \varepsilon is affine, and (xt−1,ε)(x_{t-1}, \varepsilon) is jointly Gaussian because the two parts are independent and Gaussian. An affine image of a Gaussian vector is Gaussian. Its mean is g(u,μ)+G⋅0+V⋅0=g(u,μ)g(u, \mu) + G \cdot 0 + V \cdot 0 = g(u, \mu), which is line L3. Because xt−1−μx_{t-1} - \mu and ε\varepsilon are independent with zero mean, the covariance is GΣG⊤+VMV⊤G \Sigma G^\top + V M V^\top, which is line L4.

Part 2. Write e=xt−μˉe = x_t - \bar\mu, so e∼N(0,Σˉ)e \sim N(0, \bar\Sigma) and ν=He+δ\nu = H e + \delta. The pair (e,ν)(e, \nu) is an affine image of the independent Gaussians (e,δ)(e, \delta), so it is jointly Gaussian with

Cov⁡(ν)=HΣˉH⊤+Q=S,Cov⁡(e,ν)=ΣˉH⊤.\operatorname{Cov}(\nu) = H \bar\Sigma H^\top + Q = S, \qquad \operatorname{Cov}(e, \nu) = \bar\Sigma H^\top.

SS is positive definite because QQ is (A1), so S−1S^{-1} exists. The conditional distribution of one block of a jointly Gaussian vector given the other block is Gaussian with

E[e∣ν]=ΣˉH⊤S−1ν=Kν,Cov⁡(e∣ν)=Σˉ−ΣˉH⊤S−1HΣˉ=(I−KH)Σˉ.E[e \mid \nu] = \bar\Sigma H^\top S^{-1} \nu = K \nu, \qquad \operatorname{Cov}(e \mid \nu) = \bar\Sigma - \bar\Sigma H^\top S^{-1} H \bar\Sigma = (I - K H) \bar\Sigma.

With KK from line L10, this gives μ′=μˉ+Kν\mu' = \bar\mu + K \nu (line L11) and Σ′=(I−KH)Σˉ\Sigma' = (I - K H) \bar\Sigma (line L12). Lines L7, L8 and L9 compute h(μˉ,j)h(\bar\mu, j), HH and SS, and ν\nu is the wrapped difference by (A2).

For the information form, let P=Σˉ−1+H⊤Q−1HP = \bar\Sigma^{-1} + H^\top Q^{-1} H. Then

Σ′P=ΣˉP−ΣˉH⊤S−1HΣˉP.\Sigma' P = \bar\Sigma P - \bar\Sigma H^\top S^{-1} H \bar\Sigma P.

Here ΣˉP=I+ΣˉH⊤Q−1H\bar\Sigma P = I + \bar\Sigma H^\top Q^{-1} H and HΣˉP=H+HΣˉH⊤Q−1H=(Q+HΣˉH⊤)Q−1H=SQ−1HH \bar\Sigma P = H + H \bar\Sigma H^\top Q^{-1} H = (Q + H \bar\Sigma H^\top) Q^{-1} H = S Q^{-1} H. So

Σ′P=I+ΣˉH⊤Q−1H−ΣˉH⊤S−1SQ−1H=I,\Sigma' P = I + \bar\Sigma H^\top Q^{-1} H - \bar\Sigma H^\top S^{-1} S Q^{-1} H = I,

and Σ′−1=P\Sigma'^{-1} = P. For the mean, Σ′H⊤Q−1=(I−KH)ΣˉH⊤Q−1\Sigma' H^\top Q^{-1} = (I - K H) \bar\Sigma H^\top Q^{-1}. Since KS=ΣˉH⊤K S = \bar\Sigma H^\top,

ΣˉH⊤Q−1−KHΣˉH⊤Q−1=K(S−HΣˉH⊤)Q−1=KQQ−1=K.\bar\Sigma H^\top Q^{-1} - K H \bar\Sigma H^\top Q^{-1} = K (S - H \bar\Sigma H^\top) Q^{-1} = K Q Q^{-1} = K.

So Σ′H⊤Q−1=K\Sigma' H^\top Q^{-1} = K and μ′=μˉ+Σ′H⊤Q−1ν\mu' = \bar\mu + \Sigma' H^\top Q^{-1} \nu. The test test_update_equals_information_form checks this identity in floating point.

Part 3. By Part 1, the prediction of lines L1 to L4 is the exact prediction step of the Bayes filter for the linearized motion model. By Part 2, each pass through lines L7 to L12 is the exact Bayes update for one linearized reading. The readings of one step are independent given the pose, so the posterior after all of them is the product of their likelihoods with the prior, and the Bayes update with several independent readings equals the updates with each reading in turn. The algorithm relinearizes hh at the new mean before each reading, so it applies the exact update for a model that changes with the order; for linear hh the model does not change and the result is independent of the order. In all cases the step equals the Bayes filter of the linearized models, and the error relative to the nonlinear models comes only from the linearization. ■\blacksquare

Complexity

Let kk be the number of readings in one step and mm the number of landmarks. The state has 3 dimensions and a reading 2, so each matrix operation costs O(1)O(1) in the real RAM model.

  • Prediction: O(1)O(1).
  • Update with known correspondences: O(1)O(1) per reading, so O(k)O(k) per step.
  • Association by maximum likelihood: O(m)O(m) per reading, so O(km)O(k m) per step. A spatial index over the landmarks, for example a k-d tree with the gate as the search radius, reduces the number of candidates.
  • Memory: O(1)O(1) for the belief, plus the map.

This is the main advantage over grid and particle methods, whose cost grows with the number of poses or particles.

Properties

  • Unimodal. The belief has one peak. It cannot represent two hypotheses, so it cannot do global localization or recover from a kidnapping.
  • Local. The linearization holds only near the mean. If the pose error is large compared with the distance to the landmarks, or the heading error is large, the update can move the mean the wrong way.
  • Deterministic and fast. The same data give the same result, at a cost independent of the size of the map when correspondences are known.
  • The order of the readings matters a little. Each update relinearizes at the new mean, so a different order gives slightly different results. With linear models the order does not matter.

Variants and improvements

  • Unknown correspondences. Maximum likelihood association with a gate, as above (Thrun et al., Section 7.5). Joint association of all readings of a step, for example with joint compatibility branch and bound, avoids two readings taking the same landmark. See data association in SLAM.
  • Multi-hypothesis tracking. Keep a mixture of Gaussians, one per association history, and prune the unlikely ones (Thrun et al., Section 7.6). It handles a few ambiguous hypotheses at a cost that grows with their number.
  • UKF localization. The unscented Kalman filter propagates sigma points through gg and hh instead of Jacobians (Thrun et al., Section 7.7). It needs no derivatives and handles stronger nonlinearity, at a small constant factor more.
  • Iterated EKF. Repeat lines L7 to L11 with HH evaluated at the updated mean, a Gauss-Newton step on the measurement. This reduces the linearization error of sharp readings.
  • Joseph form. Replace line L12 by (I−KH)Σˉ(I−KH)⊤+KQK⊤(I - K H) \bar\Sigma (I - K H)^\top + K Q K^\top, which keeps Σ\Sigma symmetric and positive definite under rounding. The code instead symmetrizes Σ\Sigma after each update.
  • EKF SLAM. If the landmarks are unknown, put them in the state; see EKF SLAM.

When to use it

Use EKF localization to track a robot whose initial pose is known well, in a map of distinct landmarks, for example reflectors or fiducial markers, when computation is limited. Use Markov localization or Monte Carlo localization when the initial pose is unknown, when the map has repeated structure that makes association ambiguous, or when the sensor gives raw scans instead of landmarks.

Pitfalls

  • Angles. Wrap the bearing innovation z−z^z - \hat z to [−π,π)[-\pi, \pi) before line L11, and wrap μθ\mu_\theta after it. Without this, a reading near ±π\pm\pi gives an innovation near 2π2\pi and a huge wrong correction. The code has a test for this case.
  • A wrong association. One reading matched to the wrong landmark moves the mean by a full innovation and shrinks the covariance, so the filter becomes sure of a wrong pose. Later correct readings then fail the gate. The gate reduces the risk but does not remove it: in a map with landmarks close together, two landmarks can pass the gate for one reading.
  • Overconfidence. Neglected correlations, such as several readings of the same object or a noise model that is too small, make Σ\Sigma too small. The NEES test above detects this in simulation. Inflating QQ or MM is a common rule of thumb.
  • ω\omega near zero. The arc formulas divide by ω\omega. Use the straight-line limits below a small threshold, for gg and for both Jacobians.
  • A landmark at the robot. HH divides by qq and q\sqrt q. Skip readings of landmarks that are very close.

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_localization.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ekf-localization/. The authors are listed in prov/EVPG4E.jsonl.

"""EKF localization with the velocity motion model and range-bearing landmarks.

The notation follows Thrun, Burgard and Fox (2005), Section 7.4.
The state is the planar pose mu = [x, y, theta]; Sigma is its 3x3 covariance.
A control is u = (v, omega), held for dt seconds. The noise of the control has
the covariance M = diag(a1 v^2 + a2 omega^2, a3 v^2 + a4 omega^2).
A landmark is a point (m_x, m_y) of the map. A measurement of a landmark is
z = (r, phi), the range and the bearing relative to the heading, with the
noise covariance Q = diag(sigma_r^2, sigma_phi^2). Angles wrap to [-pi, pi).
"""

import math

import rbm
import robest

STRAIGHT = 1e-9  # below this |omega|, the robot moves on a straight line


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


def motion_jacobians(mu, u, dt):
    """Return G = d motion / d mu and V = d motion / d u at (mu, u)."""
    _, _, th = mu
    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 * c0 + v / w * c1], [0.0, 1.0, -v / w * s0 + v / w * s1], [0.0, 0.0, 1.0]]
    vj = [
        [(-s0 + s1) / 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 measure(mu, landmark):
    """Return the expected (range, bearing) of a landmark from the pose mu."""
    dx, dy = landmark[0] - mu[0], landmark[1] - mu[1]
    return [math.hypot(dx, dy), robest.wrap_angle(math.atan2(dy, dx) - mu[2])]


def measure_jacobian(mu, landmark):
    """Return H = d measure / d mu (2x3)."""
    dx, dy = landmark[0] - mu[0], landmark[1] - mu[1]
    q = dx * dx + dy * dy
    sq = math.sqrt(q)
    return [[-dx / sq, -dy / sq, 0.0], [dy / q, -dx / q, -1.0]]


def predict(mu, sigma, u, dt, alphas):
    """The prediction of EKF localization: lines L1 to L5."""
    v, w = u
    a1, a2, a3, a4 = alphas
    g, vj = motion_jacobians(mu, u, dt)  # @line L1
    m = [[a1 * v * v + a2 * w * w, 0.0], [0.0, a3 * v * v + a4 * w * w]]  # @line L2
    mu_bar = motion(mu, u, dt)  # @line L3
    sigma_bar = rbm.add(rbm.mul(rbm.mul(g, sigma), rbm.transpose(g)), rbm.mul(rbm.mul(vj, m), rbm.transpose(vj)))  # @line L4
    return mu_bar, sigma_bar


def innovation(mu, sigma, z, landmark, q):
    """Return (nu, H, S): the innovation z - h(mu), its Jacobian and its covariance."""
    zhat = measure(mu, landmark)  # @line L7
    h = measure_jacobian(mu, landmark)  # @line L8
    s = rbm.add(rbm.mul(rbm.mul(h, sigma), rbm.transpose(h)), q)  # @line L9
    nu = [z[0] - zhat[0], robest.wrap_angle(z[1] - zhat[1])]
    return nu, h, s


def update(mu, sigma, z, landmark, q):
    """The correction with one measurement of a known landmark: lines L7 to L12."""
    nu, h, s = innovation(mu, sigma, z, landmark, q)
    k = rbm.mul(rbm.mul(sigma, rbm.transpose(h)), rbm.inv(s))  # @line L10
    dmu = rbm.matvec(k, nu)
    mu = [mu[0] + dmu[0], mu[1] + dmu[1], robest.wrap_angle(mu[2] + dmu[2])]  # @line L11
    sigma = rbm.mul(rbm.sub(rbm.eye(3), rbm.mul(k, h)), sigma)  # @line L12
    sigma = [[(sigma[i][j] + sigma[j][i]) / 2.0 for j in range(3)] for i in range(3)]
    return mu, sigma


def associate(mu, sigma, z, landmarks, q, gate):
    """Return the index of the most likely landmark for z, or None if it fails the gate.

    The likelihood of landmark j is N(nu_j; 0, S_j). A landmark is a candidate
    only if nu_j^T S_j^(-1) nu_j <= gate (for example 9.210, the 0.99 quantile
    of the chi-square distribution with 2 degrees of freedom).
    """
    best, best_ll = None, -math.inf
    for j, lm in enumerate(landmarks):
        nu, _, s = innovation(mu, sigma, z, lm, q)
        d2 = robest.mahalanobis2(nu, [0.0, 0.0], s)
        if d2 > gate:
            continue
        ll = -0.5 * d2 - 0.5 * math.log(rbm.det(s))
        if ll > best_ll:
            best, best_ll = j, ll
    return best


def ekf_localization(mu, sigma, u, dt, zs, landmarks, alphas, q, correspondences=None, gate=robest.CHI2[(2, 0.99)]):
    """One step of EKF localization: lines L1 to L13.

    zs is a list of (range, bearing) readings. If correspondences is given,
    correspondences[i] is the index of the landmark of zs[i] (the case of
    known correspondences in Thrun et al., Section 7.4). Otherwise each reading is associated by maximum
    likelihood with a chi-square gate, and a reading that fails the gate is
    ignored. Return (mu, Sigma, the list of the used landmark indices).
    """
    mu, sigma = predict(mu, sigma, u, dt, alphas)
    used = []
    for i, z in enumerate(zs):  # @line L5
        j = correspondences[i] if correspondences is not None else associate(mu, sigma, z, landmarks, q, gate)  # @line L6
        if j is None:
            used.append(None)
            continue
        mu, sigma = update(mu, sigma, z, landmarks[j], q)
        used.append(j)
    return mu, sigma, used  # @line L13
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_localization.py 173 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ekf-localization/. The authors are listed in prov/EVPG4E.jsonl.

import math
import random

import pytest

import rbm
import robest
from ekf_localization import (
    associate,
    ekf_localization,
    measure,
    measure_jacobian,
    motion,
    motion_jacobians,
    predict,
    update,
)

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


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


def mat_close(a, b, tol):
    return all(close(ra, rb, tol) for ra, rb in zip(a, b))


@pytest.mark.parametrize("mu,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(mu, u):
    g, v = motion_jacobians(mu, u, DT)
    gn = rbm.num_jacobian(lambda x: motion(x, u, DT), mu)
    if abs(u[1]) > 0.0:
        vn = rbm.num_jacobian(lambda w: motion(mu, w, DT), list(u))
    else:
        # at omega = 0 the derivative in omega is the limit of the arc formula
        eps = 1e-5
        vn = rbm.num_jacobian(lambda w: motion(mu, [w[0], w[1] + eps], DT), list(u))
    assert mat_close(g, gn, 1e-6)
    assert mat_close(v, vn, 1e-4)


def test_measure_jacobian_against_finite_differences():
    mu = [1.0, -0.5, 0.7]
    for lm in LANDMARKS:
        h = measure_jacobian(mu, lm)
        hn = rbm.num_jacobian(lambda x: measure(x, lm), mu)
        assert mat_close(h, hn, 1e-6)


def test_noise_free_motion_follows_the_arc():
    # v = 1 and omega = 0.5 give a circle of radius 2 with the period 4 pi
    mu = [0.0, 0.0, 0.0]
    for _ in range(25):
        mu = motion(mu, (1.0, 0.5), 4.0 * math.pi / 25.0)
    assert close(mu, [0.0, 0.0, 0.0], 1e-9)
    mu = motion([0.0, 0.0, 0.0], (1.0, 0.5), math.pi)  # a quarter of the circle
    assert close(mu, [2.0, 2.0, math.pi / 2.0], 1e-12)
    mu = motion([0.0, 0.0, 0.0], (1.0, 0.5), 2.0 * math.pi)  # half of it
    assert close(mu, [0.0, 4.0, -math.pi], 1e-12)


def test_update_equals_information_form():
    mu = [0.5, 0.2, 0.1]
    sigma = [[0.2, 0.05, 0.01], [0.05, 0.3, -0.02], [0.01, -0.02, 0.1]]
    z = [4.8, -0.1]
    lm = LANDMARKS[0]
    mu1, s1 = update(mu, sigma, z, lm, Q)
    h = measure_jacobian(mu, lm)
    info = rbm.add(rbm.inv(sigma), rbm.mul(rbm.mul(rbm.transpose(h), rbm.inv(Q)), h))
    s2 = rbm.inv(info)
    zhat = measure(mu, lm)
    nu = [z[0] - zhat[0], robest.wrap_angle(z[1] - zhat[1])]
    dmu = rbm.matvec(rbm.mul(rbm.mul(s2, rbm.transpose(h)), rbm.inv(Q)), nu)
    assert mat_close(s1, s2, 1e-12)
    assert close(mu1, [mu[i] + dmu[i] for i in range(3)], 1e-12)


def test_bearing_innovation_wraps():
    mu = [0.0, 0.0, math.pi - 0.01]
    lm = [-10.0, 0.0]  # straight behind the x axis, bearing 0.01 from the heading
    sigma = [[0.01, 0.0, 0.0], [0.0, 0.01, 0.0], [0.0, 0.0, 0.01]]
    z = [10.0, -0.01 + 2.0 * math.pi]  # the same angle as -0.01, written beyond pi
    mu1, _ = update(mu, sigma, z, lm, Q)
    # the innovation is -0.02, so theta moves by a small amount and not by 2 pi
    assert abs(robest.wrap_angle(mu1[2] - mu[2])) < 0.02


def simulate(rng, steps, x0):
    x, us, zss = list(x0), [], []
    for t in range(steps):
        u = (1.0, 0.3 if (t // 10) % 2 == 0 else -0.3)
        v, w = u
        a1, a2, a3, a4 = ALPHAS
        vt = v + rng.gauss(0.0, math.sqrt(a1 * v * v + a2 * w * w))
        wt = w + rng.gauss(0.0, math.sqrt(a3 * v * v + a4 * w * w))
        x = motion(x, (vt, wt), DT)
        zs = []
        for lm in LANDMARKS:
            r, phi = measure(x, lm)
            zs.append([r + rng.gauss(0.0, 0.1), robest.wrap_angle(phi + rng.gauss(0.0, 0.03))])
        us.append(u)
        zss.append(zs)
        yield x, u, zs


def test_consistency_by_nees():
    rng = random.Random(11)
    runs, steps, total = 50, 20, 0.0
    sigma0 = [[0.01, 0.0, 0.0], [0.0, 0.01, 0.0], [0.0, 0.0, 0.0025]]
    for _ in range(runs):
        x0 = [0.0, 0.0, 0.0]
        mu = robest.gauss_sample(rng, x0, sigma0)
        sigma = sigma0
        for x, u, zs in simulate(rng, steps, x0):
            mu, sigma, _ = ekf_localization(mu, sigma, u, DT, zs, LANDMARKS, ALPHAS, Q, correspondences=[0, 1, 2, 3])
            e = [x[0] - mu[0], x[1] - mu[1], robest.wrap_angle(x[2] - mu[2])]
            total += robest.mahalanobis2(e, [0.0, 0.0, 0.0], sigma)
    # The average NEES of a consistent filter is 3. The bounds are the 0.025
    # and 0.975 quantiles of chi-square(3000) / 1000, about 2.85 and 3.15;
    # the steps of one run are correlated, so the test allows [2.5, 3.5].
    avg = total / (runs * steps)
    assert 2.5 < avg < 3.5


def test_unknown_correspondences_match_known_ones():
    rng = random.Random(5)
    sigma0 = [[0.01, 0.0, 0.0], [0.0, 0.01, 0.0], [0.0, 0.0, 0.0025]]
    mu_k, s_k = [0.0, 0.0, 0.0], sigma0
    mu_u, s_u = [0.0, 0.0, 0.0], sigma0
    mu_g, s_g, rejected = [0.0, 0.0, 0.0], sigma0, 0
    for x, u, zs in simulate(rng, 30, [0.0, 0.0, 0.0]):
        order = [2, 0, 3, 1]
        zs = [zs[j] for j in order]
        mu_k, s_k, _ = ekf_localization(mu_k, s_k, u, DT, zs, LANDMARKS, ALPHAS, Q, correspondences=order)
        # maximum likelihood association with no gate
        mu_u, s_u, used = ekf_localization(mu_u, s_u, u, DT, zs, LANDMARKS, ALPHAS, Q, gate=math.inf)
        assert used == order
        # with the 0.99 gate, about 1 in 100 correct readings is dropped
        mu_g, s_g, used = ekf_localization(mu_g, s_g, u, DT, zs, LANDMARKS, ALPHAS, Q)
        assert all(j is None or j == o for j, o in zip(used, order))
        rejected += used.count(None)
    assert close(mu_k, mu_u, 1e-12)
    assert math.hypot(mu_k[0] - x[0], mu_k[1] - x[1]) < 0.2
    assert rejected <= 6  # of 120 readings


def test_gate_rejects_an_outlier():
    mu = [0.0, 0.0, 0.0]
    sigma = [[0.01, 0.0, 0.0], [0.0, 0.01, 0.0], [0.0, 0.0, 0.0025]]
    good = measure(mu, LANDMARKS[1])
    assert associate(mu, sigma, good, LANDMARKS, Q, robest.CHI2[(2, 0.99)]) == 1
    outlier = [good[0] + 2.0, good[1]]
    mu2, sigma2, used = ekf_localization(mu, sigma, (0.0, 0.0), DT, [outlier], LANDMARKS, ALPHAS, Q)
    assert used == [None]
    assert close(mu2, mu, 1e-12) and mat_close(sigma2, sigma, 1e-12)


def test_prediction_grows_and_update_shrinks_the_covariance():
    mu = [0.0, 0.0, 0.0]
    sigma = [[0.01, 0.0, 0.0], [0.0, 0.01, 0.0], [0.0, 0.0, 0.0025]]
    mu_bar, sigma_bar = predict(mu, sigma, (1.0, 0.3), DT, ALPHAS)
    assert rbm.det(sigma_bar) > rbm.det(sigma)
    mu1, sigma1 = update(mu_bar, sigma_bar, measure(mu_bar, LANDMARKS[0]), LANDMARKS[0], Q)
    assert rbm.det(sigma1) < rbm.det(sigma_bar)
    assert close(mu1, mu_bar, 1e-12)  # a reading equal to its prediction leaves mu unchanged

History

In the second half of the 1980s, robotics researchers started to write the uncertain geometry of robot poses and features in terms of means and covariances. Leonard and Durrant-Whyte (1991) built the first widely cited EKF localization system: a robot with sonar sensors tracked its pose by matching returns to geometric beacons of a map, with a validation gate on the innovation. Thrun, Burgard and Fox (2005) present EKF localization in Chapter 7 next to Markov localization, with maximum likelihood correspondences, multi-hypothesis tracking and the UKF variant.

References

  1. Sebastian Thrun, Wolfram Burgard and Dieter Fox, Probabilistic Robotics, MIT Press, 2005, Chapter 7, Section 7.4 (EKF localization with known correspondences, its derivation and its physical implementation), Section 7.5 (estimating correspondences by maximum likelihood), Section 7.6 (multi-hypothesis tracking) and Section 7.7 (UKF localization)
  2. John J. Leonard and Hugh F. Durrant-Whyte, Mobile robot localization by tracking geometric beacons, IEEE Transactions on Robotics and Automation 7(3), 1991, pages 376 to 382, the extended Kalman filter that matches sonar features to beacons of an a priori map, with the validation gate on the innovation

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.known_correspondences
  • a full proof of time.unknown_correspondences
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • at least three sources
  • a scene preset for the example