Algorithm Search⌘K

Algorithmadvanced

GraphSLAM

Also called Thrun-Montemerlo GraphSLAM.

Full SLAM in information form. It links all poses and landmarks in a sparse matrix, removes the landmarks by Schur complements, solves for the path, recovers the map, and relinearizes.

Solves
Full SLAM
Time
O(I (m p^2 + p^3 + k)) totalO(p + k) linearizeO(m p^2) reduceO(p^3 + k) solve
Space
O(p + k) information_formO(p^2) reduced
Where
I = the number of iterations; k = the number of measurements; m = the number of landmarks; p = the number of poses
Properties
batchdeterministicnot exactlocal optimum
Origin
Sebastian Thrun, Michael Montemerlo, 2006

GraphSLAM solves the full SLAM problem in one batch. It turns every control and every measurement into a constraint between two variables, a pose and the next pose or a pose and a landmark. It linearizes these constraints and adds them into a sparse information matrix Ω\Omega and an information vector ξ\xi over all poses and all landmarks. It then removes the landmarks from this system by Schur complements, solves the smaller system for the path, and recovers each landmark from the path. It repeats these steps from the new estimate until the estimate stops changing. Each pass is one Gauss-Newton step on the full SLAM cost. Thrun and Montemerlo (2006) published it, and it is Chapter 11 of Probabilistic Robotics. A pose graph is the special case without landmarks, and square root SAM solves the same least squares problem by a factorization of the Jacobian instead of by elimination of the map.

In plain words

The robot drives and writes down two kinds of notes: how far it thinks it moved, and where it saw each landmark from where it stood. Each note ties two things together, like a spring. GraphSLAM puts all the springs in one big table. The table is mostly empty, because each note touches only two things. To make the problem smaller, it first removes the landmarks. Each removed landmark leaves springs between all the places it was seen from. Then it finds the path where all springs are least stretched, puts the landmarks back where the path says, and does it all again from there, because the springs were only straight lines near the old guess.

The problem

The input is the controls u1,…,uTu_1, \dots, u_T, the measurements ziz_i of landmark cic_i from pose xtix_{t_i} (the correspondences are known), the motion model xt=g(ut,xt−1)+εtx_t = g(u_t, x_{t-1}) + \varepsilon_t with εt∼N(0,R)\varepsilon_t \sim N(0, R), and the measurement model zi=h(xti,mci)+δiz_i = h(x_{t_i}, m_{c_i}) + \delta_i with δi∼N(0,Q)\delta_i \sim N(0, Q). The notation is that of Thrun, Burgard and Fox. The output is the path x0,…,xTx_0, \dots, x_T and the map m=(m1,…,mM)m = (m_1, \dots, m_M) that minimize the negative log posterior

J=x0⊤Ω0 x0+∑t(xt−g(ut,xt−1))⊤R−1(xt−g(ut,xt−1))+∑i(zi−h(xti,mci))⊤Q−1(zi−h(xti,mci)),J = x_0^\top \Omega_0\, x_0 + \sum_t \big(x_t - g(u_t, x_{t-1})\big)^\top R^{-1} \big(x_t - g(u_t, x_{t-1})\big) + \sum_i \big(z_i - h(x_{t_i}, m_{c_i})\big)^\top Q^{-1} \big(z_i - h(x_{t_i}, m_{c_i})\big),

with an anchor Ω0\Omega_0 that fixes x0x_0, because the measurements fix the path and the map only up to a rigid motion. On this page and in the code, the robot is planar, xt=(x,y,θ)x_t = (x, y, \theta), the control is a motion in the frame of xt−1x_{t-1}, the landmarks are points, and each measurement is a range and a bearing. Angle differences are wrapped to [−π,π)[-\pi, \pi).

The algorithm

INITIALIZE composes the controls from x0=0x_0 = 0 and puts each landmark where its first measurement says. The main loop runs LINEARIZE, REDUCE and SOLVE. In LINEARIZE, GtG_t and HiH_i are the Jacobians of gg and hh at the current estimate μ\mu, x^t=g(ut,μt−1)\hat x_t = g(u_t, \mu_{t-1}) and z^i=h(μti,μci)\hat z_i = h(\mu_{t_i}, \mu_{c_i}). τ(j)\tau(j) is the set of poses that measured landmark jj.

  1. INITIALIZE(u, z)
  2. 1μ_0 ← 0; μ_t ← g(u_t, μ_{t-1}) for t = 1 to T; put each landmark at its first measurement
  3. LINEARIZE(u, z, μ)
  4. 2Ω ← anchor on x_0; ξ ← 0
  5. 3for t ← 1 to T do
  6. 4add [-G_t I]ᵀ R⁻¹ [-G_t I] to Ω at (x_{t-1}, x_t); add [-G_t I]ᵀ R⁻¹ (x̂_t - G_t μ_{t-1}) to ξ
  7. 5for each measurement i do
  8. 6add H_iᵀ Q⁻¹ H_i to Ω at (x_{t_i}, m_{c_i}); add H_iᵀ Q⁻¹ (z_i - ẑ_i + H_i μ) to ξ
  9. REDUCE(Ω, ξ)
  10. 7Ω̃ ← Ω_{x,x}; ξ̃ ← ξ_x
  11. 8for each landmark j do
  12. 9ξ̃_{τ(j)} ← ξ̃_{τ(j)} - Ω_{τ(j),j} Ω_{j,j}⁻¹ ξ_j
  13. 10Ω̃_{τ(j),τ(j)} ← Ω̃_{τ(j),τ(j)} - Ω_{τ(j),j} Ω_{j,j}⁻¹ Ω_{j,τ(j)}
  14. SOLVE(Ω̃, ξ̃, Ω, ξ)
  15. 11Σ ← Ω̃⁻¹
  16. 12μ_x ← Σ ξ̃
  17. 13for each landmark j do
  18. 14μ_j ← Ω_{j,j}⁻¹ (ξ_j - Ω_{j,τ(j)} μ_{τ(j)})
  19. GRAPHSLAM(u, z)
  20. 15μ ← INITIALIZE(u, z)
  21. 16repeat
  22. 17Ω, ξ ← LINEARIZE(u, z, μ)
  23. 18Ω̃, ξ̃ ← REDUCE(Ω, ξ)
  24. 19μ, Σ ← SOLVE(Ω̃, ξ̃, Ω, ξ)
  25. 20until μ changes by less than a tolerance
  26. 21return μ, Σ

Line L4 is the information of the linearized motion residual xt−Gtxt−1−(x^t−Gtμt−1)x_t - G_t x_{t-1} - (\hat x_t - G_t \mu_{t-1}), and line L6 that of the linearized measurement residual. Lines L9 and L10 touch only the poses in τ(j)\tau(j), because Ωx,j\Omega_{x,j} is zero elsewhere. No factor links two landmarks, so the landmarks can be removed one at a time and in any order. Line L14 comes from the landmark row of Ωμ=ξ\Omega \mu = \xi.

In the code, the anchor is 10810^8 on the diagonal of x0x_0 instead of infinity, the inverse is a dense Gauss-Jordan inverse, and the predicted angle θ^t\hat\theta_t is moved by a multiple of 2π2\pi to lie near μt\mu_t, so that the linear system stays continuous across ±π\pm\pi.

Example

The robot drives 12 steps of 1 m with a turn of 30°30° after each step. This is a closed regular polygon of 12 sides, with the radius 1.931.93 m. Five landmarks lie around it, and the robot measures each landmark within 3.5 m. The control noise has the standard deviations 0.020.02 m and 0.010.01 rad, and the measurement noise 0.050.05 m in range and 0.020.02 rad in bearing. With the seed 4, there are 42 measurements and 13 poses, so Ω\Omega is 49×4949 \times 49.

dead reckoning (INITIALIZE) GraphSLAM
cost J/2J/2 276.67 38.00
error of the last position 0.239 m 0.036 m
error of the last heading -0.033 rad -0.013 rad
largest landmark error 0.099 m 0.065 m

The estimate converged in 8 passes. The largest change of a pose coordinate was 0.210.21 after the first pass, 5.2×10−35.2 \times 10^{-3} after the second, 4.2×10−44.2 \times 10^{-4} after the third, and 2.3×10−52.3 \times 10^{-5} after the fourth, which is the fast local convergence of Gauss-Newton on a problem with small residuals. The standard deviations of the last pose from Σ\Sigma are 0.0230.023 m, 0.0300.030 m and 0.0140.014 rad.

The example also shows the price of the reduction. Landmark 3 is seen from all 13 poses. The full Ω\Omega has 761 nonzero entries out of 2401, but after REDUCE, Ω~\tilde\Omega has 1521 nonzero entries out of 1521. One landmark seen from every pose makes the reduced matrix dense.

Correctness

The correctness proof shows three things. LINEARIZE builds the Ω\Omega and ξ\xi of the quadratic model of JJ at μ\mu, whose minimizer is Ω−1ξ\Omega^{-1}\xi. REDUCE and SOLVE return exactly Ω−1ξ\Omega^{-1}\xi, and Σ\Sigma is the pose block of Ω−1\Omega^{-1}, because Ω~\tilde\Omega is the Schur complement of the block diagonal landmark block. A fixed point of the loop is a point where the gradient of JJ is zero. With noise-free data, the true path and map are a fixed point with zero cost. The proof gives no global result: JJ is not convex in the headings, and Gauss-Newton converges only from a good start. The tests check the noise-free case to 10−910^{-9}, check REDUCE and SOLVE against a dense solve of the full system to 10−810^{-8}, and check that every partial derivative of JJ at the noisy solution is below 10−310^{-3}.

Proof: One GraphSLAM iteration is a Gauss-Newton step, and its fixed points are stationary points of the full SLAM costfull

Setting. The state is y=(x0,…,xT,m1,…,mM)y = (x_0, \dots, x_T, m_1, \dots, m_M). The cost is

J(y)=12x0⊤Ω0 x0+12∑t=1Trt⊤R−1rt+12∑isi⊤Q−1si,J(y) = \tfrac{1}{2} x_0^\top \Omega_0\, x_0 + \tfrac{1}{2} \sum_{t=1}^{T} r_t^\top R^{-1} r_t + \tfrac{1}{2} \sum_{i} s_i^\top Q^{-1} s_i,

with the motion residuals rt=xt−g(ut,xt−1)r_t = x_t - g(u_t, x_{t-1}) and the measurement residuals si=zi−h(xti,mji)s_i = z_i - h(x_{t_i}, m_{j_i}). RR and QQ are symmetric positive definite, and Ω0=αI\Omega_0 = \alpha I with α>0\alpha > 0 is the anchor. gg and hh are differentiable. The angle parts of the residuals are wrapped to [−π,π)[-\pi, \pi); near a point where no residual angle is at ±π\pm\pi, the wrap adds a constant multiple of 2π2\pi and does not change the derivatives.

Assumptions.

  • (A1) Every landmark has at least one measurement, and every block Ωjj\Omega_{jj} built by LINEARIZE is invertible. (A range and bearing measurement at a nonzero range has a 2×22 \times 2 landmark Jacobian with determinant −1/r-1/r, so one measurement is enough.)
  • (A2) The matrix Ω\Omega built by LINEARIZE is invertible.

Claim 1 (linearize). Let μ\mu be the current estimate. Replace each residual by its first order expansion at μ\mu: rt≈xt−Gtxt−1−(x^t−Gtμt−1)r_t \approx x_t - G_t x_{t-1} - (\hat x_t - G_t \mu_{t-1}) with x^t=g(ut,μt−1)\hat x_t = g(u_t, \mu_{t-1}) and Gt=∂g/∂xG_t = \partial g / \partial x, and si≈zi−z^i+Hiμ(i)−Hiy(i)s_i \approx z_i - \hat z_i + H_i \mu_{(i)} - H_i y_{(i)} with z^i=h(μ(i))\hat z_i = h(\mu_{(i)}) and Hi=∂h/∂(x,m)H_i = \partial h / \partial (x, m). The quadratic J~(y)\tilde J(y) that results is 12y⊤Ωy−ξ⊤y+c\tfrac{1}{2} y^\top \Omega y - \xi^\top y + c, with the Ω\Omega and ξ\xi of lines L2 to L6.

Proof. Each linearized residual is affine. Up to its sign, which does not change its square, it has the form Cy−bC y - b, where CC is zero outside the variables of one factor. Then 12(Cy−b)⊤W(Cy−b)=12y⊤C⊤WC y−(C⊤Wb)⊤y+c\tfrac{1}{2}(C y - b)^\top W (C y - b) = \tfrac{1}{2} y^\top C^\top W C\, y - (C^\top W b)^\top y + c. For a motion factor, C=[−Gt    I]C = [-G_t \;\; I] on (xt−1,xt)(x_{t-1}, x_t) and b=x^t−Gtμt−1b = \hat x_t - G_t \mu_{t-1}, so the terms are C⊤R−1CC^\top R^{-1} C and C⊤R−1bC^\top R^{-1} b, which line L4 and the line after it add. For a measurement factor, si≈−(Hiy(i)−bi)s_i \approx -(H_i y_{(i)} - b_i) with bi=zi−z^i+Hiμ(i)b_i = z_i - \hat z_i + H_i \mu_{(i)}, so C=HiC = H_i on (xti,mji)(x_{t_i}, m_{j_i}), and the terms are Hi⊤Q−1HiH_i^\top Q^{-1} H_i and Hi⊤Q−1biH_i^\top Q^{-1} b_i, which line L6 and the line after it add. The anchor gives αI\alpha I on x0x_0 and no term in ξ\xi, because its target is 00. Summing over the factors gives Ω\Omega and ξ\xi. □\square

Since Ω\Omega is invertible and J~\tilde J is a convex quadratic (a sum of squares), its unique minimizer is y∗=Ω−1ξy^* = \Omega^{-1} \xi.

Claim 2 (reduce and solve). Order y=(x,m)y = (x, m) with xx the poses. Lines L7 to L14 return exactly y∗=Ω−1ξy^* = \Omega^{-1} \xi, and the returned Σ\Sigma is the pose block of Ω−1\Omega^{-1}.

Proof. No factor joins two landmarks, so Ωmm\Omega_{mm} is block diagonal with the blocks Ωjj\Omega_{jj}. Hence Ωmm−1=diag(Ωjj−1)\Omega_{mm}^{-1} = \mathrm{diag}(\Omega_{jj}^{-1}), and

ΩxmΩmm−1Ωmx=∑jΩxjΩjj−1Ωjx,ΩxmΩmm−1ξm=∑jΩxjΩjj−1ξj.\Omega_{xm} \Omega_{mm}^{-1} \Omega_{mx} = \sum_j \Omega_{x j} \Omega_{jj}^{-1} \Omega_{j x}, \qquad \Omega_{xm} \Omega_{mm}^{-1} \xi_m = \sum_j \Omega_{x j} \Omega_{jj}^{-1} \xi_j.

The column block Ωxj\Omega_{xj} is zero outside the poses in τ(j)\tau(j), the poses that measured mjm_j, so each term changes only the rows and columns of τ(j)\tau(j). Lines L8 to L10 subtract exactly these terms, so Ω~=Ωxx−ΩxmΩmm−1Ωmx\tilde\Omega = \Omega_{xx} - \Omega_{xm}\Omega_{mm}^{-1}\Omega_{mx} and ξ~=ξx−ΩxmΩmm−1ξm\tilde\xi = \xi_x - \Omega_{xm}\Omega_{mm}^{-1}\xi_m. Write the system Ωy=ξ\Omega y = \xi in blocks:

Ωxxx+Ωxmm=ξx,Ωmxx+Ωmmm=ξm.\Omega_{xx} x + \Omega_{xm} m = \xi_x, \qquad \Omega_{mx} x + \Omega_{mm} m = \xi_m.

The second equation gives m=Ωmm−1(ξm−Ωmxx)m = \Omega_{mm}^{-1}(\xi_m - \Omega_{mx} x). Put it in the first: Ω~x=ξ~\tilde\Omega x = \tilde\xi. Ω~\tilde\Omega is the Schur complement of Ωmm\Omega_{mm} in Ω\Omega, and det⁡Ω=det⁡Ωmmdet⁡Ω~\det \Omega = \det \Omega_{mm} \det \tilde\Omega, so Ω~\tilde\Omega is invertible by (A1) and (A2). Lines L11 and L12 give x=Ω~−1ξ~x = \tilde\Omega^{-1} \tilde\xi, the pose part of y∗y^*. Since Ωmm\Omega_{mm} is block diagonal, the landmark equation splits into mj=Ωjj−1(ξj−Ωjτ(j)xτ(j))m_j = \Omega_{jj}^{-1} (\xi_j - \Omega_{j\tau(j)} x_{\tau(j)}), which is line L14. The block inverse formula gives (Ω−1)xx=Ω~−1(\Omega^{-1})_{xx} = \tilde\Omega^{-1}, which is Σ\Sigma. □\square

Claim 3 (the iteration). Lines L16 to L19 are Gauss-Newton on JJ. If the iteration reaches a fixed point μ=μ′\mu = \mu', then ∇J(μ)=0\nabla J(\mu) = 0.

Proof. By Claims 1 and 2, the new estimate minimizes the quadratic model J~\tilde J built at μ\mu. Write J~\tilde J in the step δ=y−μ\delta = y - \mu: each residual is e(μ)+Dδe(\mu) + D \delta, with e(μ)e(\mu) the residual at μ\mu and DD its Jacobian at μ\mu, and J~=12∑(e+Dδ)⊤W(e+Dδ)\tilde J = \tfrac{1}{2} \sum (e + D\delta)^\top W (e + D\delta). This is the Gauss-Newton model of JJ, so the step is the Gauss-Newton step. The gradient of J~\tilde J at δ=0\delta = 0 is ∑D⊤We\sum D^\top W e, which is ∇J(μ)\nabla J(\mu) by the chain rule. At a fixed point the minimizer of J~\tilde J is δ=0\delta = 0, so the gradient of J~\tilde J at δ=0\delta = 0 is zero, and so ∇J(μ)=0\nabla J(\mu) = 0. □\square

Exact data. If the controls and measurements have no noise, the true path and map y†y^\dagger (with x0=0x_0 = 0) make every residual zero, so J(y†)=0J(y^\dagger) = 0, the global minimum. At y†y^\dagger the gradient is zero, so y†y^\dagger is a fixed point. INITIALIZE composes the exact controls, so it starts at the true path; the landmark from the first measurement is exact as well. The first iteration then returns y†y^\dagger again. The test checks this to 10−910^{-9}.

What this does not show. Gauss-Newton converges only from a start close enough to a minimum, and the cost is not convex, so the fixed point can be a local minimum. The proof says nothing about the number of iterations. The anchor α\alpha is finite in the code, so x0x_0 is close to, not equal to, the initial guess.

Complexity

Let p=T+1p = T + 1 be the number of poses, mm the number of landmarks, kk the number of measurements, and II the number of passes.

  • LINEARIZE: O(p+k)O(p + k) work. Ω\Omega has O(p+k)O(p + k) nonzero blocks.
  • REDUCE: O(∑j∣τ(j)∣2)O(\sum_j |\tau(j)|^2), which is at most O(mp2)O(m p^2). It can fill Ω~\tilde\Omega completely, as in the example.
  • SOLVE: O(p3)O(p^3) for the dense inverse, plus O(k)O(k) to recover the landmarks.
  • Memory: O(p+k)O(p + k) for Ω\Omega in sparse form, and up to O(p2)O(p^2) for Ω~\tilde\Omega.

The code stores Ω\Omega as a dense matrix, so it uses O((p+m)2)O((p + m)^2) memory; this keeps it short and does not change the result. The number of passes II is not bounded by the analysis. In the example it was 8 to reach a change below 10−1010^{-10}, and 4 to reach 10−410^{-4}.

Properties

  • Batch. It uses all data at once and recomputes from the start. It is an offline method. For an online version, see iSAM and iSAM2.
  • A local optimum. Each pass is a Gauss-Newton step, so the result is a stationary point of JJ, and in general a local minimum. Bad initial headings can lead to a wrong one.
  • Exact elimination. Removing the landmarks loses nothing: the path and its covariance are the same as from the full system. This is unlike the sparse extended information filter, which drops links on purpose.
  • Known correspondences. The basic algorithm assumes that each measurement names its landmark. Thrun and Montemerlo add a test that merges two landmarks when the information form says that they are probably the same.

Variants and improvements

  • Without landmarks. If the measurements are relative poses, for example from scan matching, the problem is pose graph optimization, and REDUCE has nothing to do.
  • Factorization instead of elimination of the map. Square root SAM factors the whole Jacobian with a fill-reducing elimination ordering. Removing all landmarks first is one fixed ordering, and often not the best one.
  • Sparse solvers. Replace the dense inverse by a sparse Cholesky factorization or the conjugate gradient method when only μ\mu is needed and not all of Σ\Sigma.
  • Robust costs. Replace the squares by an M-estimator to limit the effect of wrong data associations.

When to use it

Use GraphSLAM for offline mapping with landmarks and known data association, when all data is available and the path is not too long for the reduced system. For long runs where a landmark is seen from many poses, or for online use, prefer square root SAM with a good ordering, or iSAM2. For laser data without landmarks, use a pose graph.

Pitfalls

  • Unwrapped angles. A predicted heading and the current heading can differ by 2π2\pi. If the difference is not wrapped, one factor pulls the robot through a full turn.
  • A missing anchor. Without the anchor, Ω\Omega is singular, because the whole solution can move and turn freely.
  • Dense reduction. The reduced matrix can be dense, as in the example. Do not assume that Ω~\tilde\Omega stays banded.
  • The sign in the landmark recovery. Derive it from the landmark row of Ωμ=ξ\Omega\mu = \xi: the term Ωj,τ(j)μτ(j)\Omega_{j,\tau(j)}\mu_{\tau(j)} is subtracted from ξj\xi_j.
  • Overconfident Σ\Sigma. Σ\Sigma comes from the linearization at the final estimate. It is too small when the linearization is poor or the noise models are too small.

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.

graphslam.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/graphslam/. The authors are listed in prov/DRMB6N.jsonl.

"""GraphSLAM of Thrun and Montemerlo, as in Probabilistic Robotics, Chapter 11.

A planar robot has the poses x_0, ..., x_T, each (x, y, theta) in meters and
radians, and the map has point landmarks m_j = (x, y). The correspondences
are known.

Motion: x_t = g(u_t, x_(t-1)) + noise with covariance Rm, where the control
u_t = (dx, dy, dtheta) is the motion in the frame of x_(t-1).
Measurement: z = (range, bearing) = h(x_t, m_j) + noise with covariance Qm.

The four steps follow the tables of the book:
  initialize  compose the controls to get the poses, and set each landmark
              from its first measurement
  linearize   build the information matrix Omega and the vector xi over all
              poses and landmarks
  reduce      remove the landmarks from Omega and xi by the Schur complement
  solve       solve the reduced system for the path, then recover the
              landmarks one by one
GraphSLAM repeats linearize, reduce and solve until the estimate stops
changing.

Angles inside the estimate are not wrapped, so that the linear system stays
continuous. Each angle difference that enters xi is wrapped to [-pi, pi).

Vectors are lists, matrices are lists of rows. The dense inverse of the
reduced matrix costs O(p^3) for p poses, which is the cost the book states
for this step.
"""

import math

ANCHOR = 1e8  # the information that pins x_0 at its initial mean (the book uses infinity)


def wrap(a):
    return (a + math.pi) % (2.0 * math.pi) - math.pi


def motion(x, u):
    """Return g(u, x): the pose x moved by u, given in the frame of x."""
    c, s = math.cos(x[2]), math.sin(x[2])
    return [x[0] + c * u[0] - s * u[1], x[1] + s * u[0] + c * u[1], x[2] + u[2]]


def motion_jacobian(x, u):
    """Return G = dg/dx at x."""
    c, s = math.cos(x[2]), math.sin(x[2])
    return [[1.0, 0.0, -s * u[0] - c * u[1]], [0.0, 1.0, c * u[0] - s * u[1]], [0.0, 0.0, 1.0]]


def measure(x, m):
    """Return h(x, m) = (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), wrap(math.atan2(dy, dx) - x[2])]


def measure_jacobian(x, m):
    """Return the 2 by 5 matrix dh/d(x, m)."""
    dx, dy = m[0] - x[0], m[1] - x[1]
    q = dx * dx + dy * dy
    r = math.sqrt(q)
    return [[-dx / r, -dy / r, 0.0, dx / r, dy / r], [dy / q, -dx / q, -1.0, -dy / q, dx / q]]


# ------------------------------------------------------------ small dense algebra


def inverse(a):
    """Return the inverse of a square matrix by Gauss-Jordan with partial pivoting."""
    n = len(a)
    m = [list(map(float, a[r])) + [1.0 if c == r else 0.0 for c in range(n)] for r in range(n)]
    for c in range(n):
        p = max(range(c, n), key=lambda r: abs(m[r][c]))
        if m[p][c] == 0.0:
            raise ValueError("singular matrix")
        m[c], m[p] = m[p], m[c]
        f = m[c][c]
        m[c] = [v / f for v in m[c]]
        for r in range(n):
            if r != c and m[r][c] != 0.0:
                f = m[r][c]
                m[r] = [v - f * w for v, w in zip(m[r], m[c])]
    return [row[n:] for row in m]


def matvec(a, x):
    return [sum(ai * xi for ai, xi in zip(row, x)) for row in a]


def _add_block(big, rows, cols, blk, sign=1.0):
    for a, r in enumerate(rows):
        for b, c in enumerate(cols):
            big[r][c] += sign * blk[a][b]


def _quad(jt_rows, w, j_cols):
    """Return J^T W J for J given by its columns (lists)."""
    return [[sum(ci[a] * w[a][b] * cj[b] for a in range(len(w)) for b in range(len(w))) for cj in j_cols] for ci in jt_rows]


# ------------------------------------------------------------------ the steps


class Problem:
    """Controls u[1..T], measurements (t, j, z), and the noise covariances."""

    def __init__(self, controls, measurements, n_landmarks, rm, qm):
        self.u = controls  # controls[t - 1] is u_t
        self.z = measurements
        self.m = n_landmarks
        self.T = len(controls)
        self.rinv = inverse(rm)
        self.qinv = inverse(qm)

    def pose_index(self, t):
        return list(range(3 * t, 3 * t + 3))

    def landmark_index(self, j):
        b = 3 * (self.T + 1) + 2 * j
        return [b, b + 1]

    def size(self):
        return 3 * (self.T + 1) + 2 * self.m


def initialize(pb):
    """Return the initial mean: poses by dead reckoning, landmarks from their first measurement."""
    mu = [[0.0, 0.0, 0.0]]  # @line L1
    for t in range(1, pb.T + 1):
        mu.append(motion(mu[-1], pb.u[t - 1]))
    lm = [None] * pb.m
    for t, j, z in pb.z:
        if lm[j] is None:
            x = mu[t]
            lm[j] = [x[0] + z[0] * math.cos(z[1] + x[2]), x[1] + z[0] * math.sin(z[1] + x[2])]
    if any(l is None for l in lm):
        raise ValueError("every landmark needs a measurement")
    return mu, lm


def linearize(pb, mu, lm):
    """Return (Omega, xi) of all poses and landmarks, linearized at (mu, lm)."""
    n = pb.size()
    om = [[0.0] * n for _ in range(n)]  # @line L2
    xi = [0.0] * n
    for k in range(3):
        om[k][k] += ANCHOR  # x_0 is pinned at its mean, which is 0
    for t in range(1, pb.T + 1):  # @line L3
        u, xp = pb.u[t - 1], mu[t - 1]
        xhat = motion(xp, u)
        xhat[2] = mu[t][2] + wrap(xhat[2] - mu[t][2])  # keep the angle near mu_t
        g = motion_jacobian(xp, u)
        # the residual is x_t - G x_(t-1) - (xhat - G mu_(t-1)); its matrix is [-G  I]
        cols = [[-g[a][c] for a in range(3)] for c in range(3)] + [[1.0 if a == c else 0.0 for a in range(3)] for c in range(3)]
        idx = pb.pose_index(t - 1) + pb.pose_index(t)
        _add_block(om, idx, idx, _quad(cols, pb.rinv, cols))  # @line L4
        rhs = [xhat[a] - sum(g[a][b] * xp[b] for b in range(3)) for a in range(3)]
        for r, col in zip(idx, cols):
            xi[r] += sum(col[a] * pb.rinv[a][b] * rhs[b] for a in range(3) for b in range(3))
    for t, j, z in pb.z:  # @line L5
        x, m = mu[t], lm[j]
        zhat = measure(x, m)
        hj = measure_jacobian(x, m)
        cols = [[hj[a][c] for a in range(2)] for c in range(5)]
        idx = pb.pose_index(t) + pb.landmark_index(j)
        _add_block(om, idx, idx, _quad(cols, pb.qinv, cols))  # @line L6
        state = list(x) + list(m)
        innov = [z[0] - zhat[0], wrap(z[1] - zhat[1])]
        rhs = [innov[a] + sum(hj[a][b] * state[b] for b in range(5)) for a in range(2)]
        for r, col in zip(idx, cols):
            xi[r] += sum(col[a] * pb.qinv[a][b] * rhs[b] for a in range(2) for b in range(2))
    return om, xi


def observers(pb):
    """Return tau: for each landmark, the sorted list of poses that measured it."""
    tau = [set() for _ in range(pb.m)]
    for t, j, _ in pb.z:
        tau[j].add(t)
    return [sorted(s) for s in tau]


def reduce(pb, om, xi):
    """Return (Omega~, xi~) over the poses only, by removing each landmark."""
    p = 3 * (pb.T + 1)
    omr = [row[:p] for row in om[:p]]  # @line L7
    xir = xi[:p]
    for j, ts in enumerate(observers(pb)):  # @line L8
        lj = pb.landmark_index(j)
        rows = [r for t in ts for r in pb.pose_index(t)]
        ojj_inv = inverse([[om[a][b] for b in lj] for a in lj])
        otj = [[om[r][c] for c in lj] for r in rows]  # Omega_(tau(j), j)
        k = [[sum(otj[a][c] * ojj_inv[c][d] for c in range(2)) for d in range(2)] for a in range(len(rows))]
        for a, r in enumerate(rows):
            xir[r] -= sum(k[a][d] * xi[lj[d]] for d in range(2))  # @line L9
            for b, s in enumerate(rows):
                omr[r][s] -= sum(k[a][d] * otj[b][d] for d in range(2))  # @line L10
    return omr, xir


def solve(pb, omr, xir, om, xi):
    """Return (poses, landmarks, Sigma of the path)."""
    sigma = inverse(omr)  # @line L11
    flat = matvec(sigma, xir)  # @line L12
    poses = [flat[3 * t:3 * t + 3] for t in range(pb.T + 1)]
    lms = []
    for j, ts in enumerate(observers(pb)):  # @line L13
        lj = pb.landmark_index(j)
        rows = [r for t in ts for r in pb.pose_index(t)]
        rhs = [xi[a] - sum(om[a][r] * flat[r] for r in rows) for a in lj]
        ojj_inv = inverse([[om[a][b] for b in lj] for a in lj])
        lms.append(matvec(ojj_inv, rhs))  # @line L14
    return poses, lms, sigma


def graphslam(pb, iterations=20, tol=1e-10):
    """Return (poses, landmarks, Sigma, number of iterations)."""
    mu, lm = initialize(pb)  # @line L15
    it = 0
    for it in range(1, iterations + 1):  # @line L16
        om, xi = linearize(pb, mu, lm)  # @line L17
        omr, xir = reduce(pb, om, xi)  # @line L18
        new_mu, new_lm, sigma = solve(pb, omr, xir, om, xi)  # @line L19
        step = max(abs(a - b) for p, q in zip(new_mu, mu) for a, b in zip(p, q))
        step = max([step] + [abs(a - b) for p, q in zip(new_lm, lm) for a, b in zip(p, q)])
        mu, lm = new_mu, new_lm
        if step < tol:  # @line L20
            break
    return mu, lm, sigma, it  # @line L21
test_graphslam.py 142 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/graphslam/. The authors are listed in prov/DRMB6N.jsonl.

import math
import random

import pytest

from graphslam import (
    ANCHOR,
    Problem,
    graphslam,
    initialize,
    inverse,
    linearize,
    matvec,
    measure,
    motion,
    reduce,
    solve,
    wrap,
)

RM = [[0.02 ** 2, 0.0, 0.0], [0.0, 0.02 ** 2, 0.0], [0.0, 0.0, 0.01 ** 2]]
QM = [[0.05 ** 2, 0.0], [0.0, 0.02 ** 2]]
LANDMARKS = [(2.0, 0.5), (3.5, 2.5), (1.5, 4.0), (-0.5, 2.5), (0.5, -1.0)]


def simulate(seed, steps=12, noise=True, max_range=3.5):
    """Drive a circle of radius about 2 m around (1.5, 1.5) and measure the landmarks in range."""
    rng = random.Random(seed)
    u_true = (1.0, 0.0, 2.0 * math.pi / steps)
    poses = [[0.0, 0.0, 0.0]]
    controls = []
    for _ in range(steps):
        poses.append(motion(poses[-1], u_true))
        if noise:
            controls.append([u_true[0] + rng.gauss(0, 0.02), u_true[1] + rng.gauss(0, 0.02), u_true[2] + rng.gauss(0, 0.01)])
        else:
            controls.append(list(u_true))
    meas = []
    for t, x in enumerate(poses):
        for j, m in enumerate(LANDMARKS):
            z = measure(x, m)
            if z[0] <= max_range:
                if noise:
                    z = [z[0] + rng.gauss(0, 0.05), wrap(z[1] + rng.gauss(0, 0.02))]
                meas.append((t, j, z))
    return Problem(controls, meas, len(LANDMARKS), RM, QM), poses


def cost(pb, mu, lm):
    """The negative log posterior up to a constant: the sum that GraphSLAM minimizes."""
    c = 0.5 * ANCHOR * sum(v * v for v in mu[0])
    for t in range(1, pb.T + 1):
        g = motion(mu[t - 1], pb.u[t - 1])
        d = [mu[t][0] - g[0], mu[t][1] - g[1], wrap(mu[t][2] - g[2])]
        c += 0.5 * sum(d[a] * pb.rinv[a][b] * d[b] for a in range(3) for b in range(3))
    for t, j, z in pb.z:
        h = measure(mu[t], lm[j])
        d = [z[0] - h[0], wrap(z[1] - h[1])]
        c += 0.5 * sum(d[a] * pb.qinv[a][b] * d[b] for a in range(2) for b in range(2))
    return c


def test_noise_free_data_gives_the_true_map_and_path():
    pb, poses = simulate(1, noise=False)
    mu, lm, _, it = graphslam(pb)
    assert it <= 3
    for p, q in zip(mu, poses):
        assert abs(p[0] - q[0]) < 1e-9 and abs(p[1] - q[1]) < 1e-9 and abs(wrap(p[2] - q[2])) < 1e-9
    for p, q in zip(lm, LANDMARKS):
        assert abs(p[0] - q[0]) < 1e-9 and abs(p[1] - q[1]) < 1e-9
    assert cost(pb, mu, lm) < 1e-12


def test_reduce_then_solve_equals_the_full_joint_solve():
    pb, _ = simulate(2)
    mu, lm = initialize(pb)
    om, xi = linearize(pb, mu, lm)
    omr, xir = reduce(pb, om, xi)
    poses, lms, sigma = solve(pb, omr, xir, om, xi)
    full = matvec(inverse(om), xi)
    flat = [v for p in poses for v in p] + [v for m in lms for v in m]
    assert max(abs(a - b) for a, b in zip(flat, full)) < 1e-8
    # Sigma of the path equals the pose block of the inverse of the full Omega.
    big = inverse(om)
    p = 3 * (pb.T + 1)
    assert max(abs(sigma[r][c] - big[r][c]) for r in range(p) for c in range(p)) < 1e-9


def test_reduced_matrix_couples_poses_that_saw_the_same_landmark():
    pb, _ = simulate(3)
    mu, lm = initialize(pb)
    om, xi = linearize(pb, mu, lm)
    omr, _ = reduce(pb, om, xi)
    seen = {}
    for t, j, _ in pb.z:
        seen.setdefault(j, set()).add(t)
    for a in range(pb.T + 1):
        for b in range(pb.T + 1):
            linked = abs(a - b) <= 1 or any(a in s and b in s for s in seen.values())
            block = max(abs(omr[3 * a + r][3 * b + c]) for r in range(3) for c in range(3))
            if not linked:
                assert block == 0.0


def test_noisy_solution_is_a_stationary_point_of_the_cost():
    pb, poses = simulate(4)
    mu, lm, _, it = graphslam(pb)
    assert it < 20
    flat = [v for p in mu for v in p] + [v for m in lm for v in m]

    def unflat(v):
        return [v[3 * t:3 * t + 3] for t in range(pb.T + 1)], [v[3 * (pb.T + 1) + 2 * j:3 * (pb.T + 1) + 2 * j + 2] for j in range(pb.m)]

    h = 1e-6
    for k in range(3, len(flat)):  # x_0 is pinned by the anchor
        vp, vm = list(flat), list(flat)
        vp[k] += h
        vm[k] -= h
        grad = (cost(pb, *unflat(vp)) - cost(pb, *unflat(vm))) / (2 * h)
        assert abs(grad) < 1e-3
    # The estimate is better than dead reckoning at the end of the loop.
    dr, _ = initialize(pb)
    end_err = math.hypot(mu[-1][0] - poses[-1][0], mu[-1][1] - poses[-1][1])
    dr_err = math.hypot(dr[-1][0] - poses[-1][0], dr[-1][1] - poses[-1][1])
    assert end_err < dr_err


def test_iteration_lowers_the_cost():
    pb, _ = simulate(5)
    mu0, lm0 = initialize(pb)
    mu, lm, _, _ = graphslam(pb)
    assert cost(pb, mu, lm) < cost(pb, mu0, lm0)


def test_unseen_landmark_is_an_error():
    pb, _ = simulate(6)
    pb.m += 1
    with pytest.raises(ValueError):
        initialize(pb)

History

Lu and Milios (1997) solved jointly for a network of poses linked by scan matches, which started the graph view of SLAM. Thrun and Montemerlo (2006) named GraphSLAM, extended it to landmarks with the information form and the elimination of the map, and used it to map urban structures. Probabilistic Robotics (2005) gives it as a complete chapter. Dellaert and Kaess (2006) gave the factorization view in square root SAM, and Grisetti, Kümmerle, Stachniss and Burgard (2010) wrote a tutorial on graph-based SLAM.

References

  1. Sebastian Thrun and Michael Montemerlo, The GraphSLAM algorithm with applications to large-scale mapping of urban structures, International Journal of Robotics Research 25(5-6), 2006, pages 403 to 429, the information form of the constraints, the elimination of the map variables, and the solution for the path
  2. Sebastian Thrun, Wolfram Burgard and Dieter Fox, Probabilistic Robotics, MIT Press, 2005, Chapter 11, The GraphSLAM Algorithm: the initialize, linearize, reduce and solve steps, and the notation of this page
  3. Feng Lu and Evangelos Milios, Globally consistent range scan alignment for environment mapping, Autonomous Robots 4(4), 1997, pages 333 to 349, the network of pose constraints solved jointly, the idea that GraphSLAM extends to landmarks
  4. Giorgio Grisetti, Rainer Kümmerle, Cyrill Stachniss and Wolfram Burgard, A tutorial on graph-based SLAM, IEEE Intelligent Transportation Systems Magazine 2(4), 2010, pages 31 to 43, the graph view of full SLAM and the Gauss-Newton solution of the linearized system

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.linearize
  • a full proof of time.reduce
  • a full proof of time.solve
  • a full proof of time.total
  • a full proof of space.information_form
  • a full proof of space.reduced
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