Algorithm Search⌘K

Data structurecore

Pose graph

Also called pose constraint graph.

A graph whose vertices are robot poses and whose edges are measured relative poses with information matrices, from odometry, scan matching and loop closures.

Time
O(1) add_edge · add_vertex · residualO(p + E) assemble · initializeO(d) neighbors
Space
O(p + E) total
Where
E = the number of edges; d = the number of edges at one vertex; p = the number of poses
Origin
Feng Lu, Evangelos Milios, 1997

A pose graph stores the result of the front end of a SLAM system in a form that a back end can optimize. Each vertex is a robot pose XiX_i in SE(2)SE(2) or SE(3)SE(3). Each edge (i,j,Zij,Ωij)(i, j, Z_{ij}, \Omega_{ij}) says that a sensor measured the pose of jj in the frame of ii as ZijZ_{ij}, with the information matrix Ωij\Omega_{ij}, the inverse of the covariance of the measurement. Edges between consecutive poses come from odometry. Edges between poses far apart in time come from scan matching or loop closure detection. The graph holds no landmarks; they were used to make the edges and are then dropped. The structure supports adding vertices and edges, computing the error of each edge, building a first guess from a spanning tree, and assembling the sparse linear system that pose graph optimization solves. It is a special case of a factor graph, with one factor per edge and one prior factor that fixes the gauge.

In plain words

Think of the places where the robot stood as pins on a board, and each measurement as a rubber band between two pins. A band has a natural length and a stiffness. Bands between neighbors in time come from the wheel counts. Bands between distant pins come from the robot seeing the same place again. The pose graph is the list of pins and bands. It can say how much each band is stretched, give a first layout by following one chain of bands from a start pin, and write down the equations that an optimizer needs to relax all the bands at once.

The abstract type

A pose graph holds:

  • a set of vertices, each with an identifier and a pose XiX_i;
  • a list of edges, each with two distinct vertex identifiers ii and jj, a measured relative pose ZijZ_{ij}, and an information matrix Ωij\Omega_{ij} (symmetric positive semidefinite, 3×33 \times 3 in the plane).

The operations are ADD-VERTEX, ADD-EDGE, NEIGHBORS, RESIDUAL, COST, INITIALIZE and ASSEMBLE. The error of an edge is

eij=Log(Zij−1Xi−1Xj),e_{ij} = \mathrm{Log}\big(Z_{ij}^{-1} X_i^{-1} X_j\big),

the vector in the Lie algebra that takes the measured pose of jj to the predicted one. It is zero when the poses agree with the measurement. The cost is F=∑eij⊤ΩijeijF = \sum e_{ij}^\top \Omega_{ij} e_{ij}. Derivatives use the right perturbation Xexp⁡(δ)X \exp(\delta), so δ\delta is expressed in the frame of the pose. The code is planar: a pose is (x,y,θ)(x, y, \theta), and Log\mathrm{Log} returns (ρx,ρy,θ)(\rho_x, \rho_y, \theta) with θ∈[−π,π)\theta \in [-\pi, \pi), where (ρx,ρy)=V(θ)−1(x,y)(\rho_x, \rho_y) = V(\theta)^{-1}(x, y) and V(θ)=1θ[sin⁡θ−(1−cos⁡θ)1−cos⁡θsin⁡θ]V(\theta) = \frac{1}{\theta}\begin{bmatrix} \sin\theta & -(1 - \cos\theta) \\ 1 - \cos\theta & \sin\theta \end{bmatrix}.

Representation

The vertices are a hash map from the identifier to the pose. The edges are an array, and each vertex has an adjacency list of the indices of its edges. An edge is stored once, with its direction. Reading an edge from jj to ii uses Zij−1Z_{ij}^{-1} with the covariance AdZΩ−1AdZ⊤\mathrm{Ad}_{Z} \Omega^{-1} \mathrm{Ad}_{Z}^\top under the right perturbation, but the code never needs to reverse an edge, because the residual is always written from the first end. The linear system is a map from a pair of vertices to a 3×33 \times 3 block, so a block exists only where an edge exists.

Operations

  1. ADD-VERTEX(G, i, X)
  2. 1G.X[i] ← X; G.adj[i] ← empty list
  3. ADD-EDGE(G, i, j, Z, Ω)
  4. 2append (i, j, Z, Ω) to G.E; let k be its index
  5. 3append k to G.adj[i] and to G.adj[j]
  6. RESIDUAL(G, k)
  7. 4return Log(Z⁻¹ X_i⁻¹ X_j) for the edge k = (i, j, Z, Ω)
  8. INITIALIZE(G, r)
  9. 5seen ← {r}; Q ← a queue that holds r
  10. 6while Q is not empty do
  11. 7i ← pop the front of Q
  12. 8for each edge k in G.adj[i] do
  13. 9j ← the other end of k
  14. 10if j is not in seen then
  15. 11X_j ← X_i Z if k goes from i to j, else X_i Z⁻¹
  16. 12add j to seen; push j on Q
  17. ASSEMBLE(G)
  18. 13H ← an empty map of 3 × 3 blocks; g ← an empty map of 3-vectors
  19. 14for each edge k = (i, j, Z, Ω) do
  20. 15e ← RESIDUAL(G, k); A ← ∂e/∂δ_i; B ← ∂e/∂δ_j
  21. 16H_ii += AᵀΩA; H_ij += AᵀΩB; H_ji += BᵀΩA; H_jj += BᵀΩB
  22. 17g_i += AᵀΩe; g_j += BᵀΩe
  23. 18return H, g

NEIGHBORS(GG, ii) reads the other end of each edge in G.adj[i]G.\mathit{adj}[i]. COST sums e⊤Ωee^\top \Omega e over the edges.

INITIALIZE is a breadth-first search that composes the measurements along a spanning tree from the root rr. It is the usual first guess for an optimizer: it gives a zero error on every tree edge, and all of the error of each loop sits on the edges outside the tree.

ASSEMBLE builds the Gauss-Newton system H δ=−gH\,\delta = -g of the cost. The code computes AA and BB by central differences with the step 10−610^{-6} on the right perturbation. In the plane, closed forms exist: with E=Z−1Xi−1XjE = Z^{-1} X_i^{-1} X_j, the Jacobian of Log(E)\mathrm{Log}(E) is Jr−1(e)J_r^{-1}(e), and ∂e/∂δj=Jr−1(e)\partial e / \partial \delta_j = J_r^{-1}(e) and ∂e/∂δi=−Jr−1(e) AdXj−1Xi\partial e / \partial \delta_i = -J_r^{-1}(e)\,\mathrm{Ad}_{X_j^{-1} X_i}. Many codes replace Jr−1(e)J_r^{-1}(e) by the identity, which is close when the errors are small. The module does not solve the system; a solver such as square root SAM, iSAM2 or a dense Cholesky does that.

Example

The square. Four poses on a square of side 2 m, driven counterclockwise: (0,0,0)(0, 0, 0), (2,0,π/2)(2, 0, \pi/2), (2,2,π)(2, 2, \pi), (0,2,−π/2)(0, 2, -\pi/2). The edges are 0→10 \to 1, 1→21 \to 2, 2→32 \to 3 and the loop closure 3→03 \to 0, each with the true relative pose (2,0,π/2)(2, 0, \pi/2) and Ω=diag(100,100,400)\Omega = \mathrm{diag}(100, 100, 400), which means standard deviations of 0.1 m and 0.05 rad. With these exact measurements, INITIALIZE from vertex 0 reproduces the four poses, and the cost is 0.

With noise. Add noise of standard deviation 0.05 to each component of each measurement (seed 7). The measurements become

edge ZZ
0→10 \to 1 (1.9872, 0.0256, 1.5595)
1→21 \to 2 (1.9842, -0.0465, 1.5601)
2→32 \to 3 (2.0556, 0.0212, 1.6226)
3→03 \to 0 (2.0124, 0.0197, 1.5801)

The search from vertex 0 first takes the edges 0→10 \to 1 and 3→03 \to 0, then 1→21 \to 2. The edge 3→03 \to 0 is read backward, so X3=X0Z30−1=(−0.0011,2.0125,−1.5801)X_3 = X_0 Z_{30}^{-1} = (-0.0011, 2.0125, -1.5801). The tree edges have zero error, and the edge 2→32 \to 3 carries the whole loop error, e=(0.0206,−0.0019,−0.0391)e = (0.0206, -0.0019, -0.0391), with F=0.6554F = 0.6554. ASSEMBLE returns 12 blocks: the 4 diagonal blocks and 2 for each of the 4 edges; the blocks (0,2)(0, 2) and (1,3)(1, 3) are absent. Eight Gauss-Newton steps on this system with X0X_0 fixed lower FF to 0.26000.2600 and spread the error over all four edges, whose costs become 0.031, 0.051, 0.111 and 0.067.

Correctness

The correctness proof shows that INITIALIZE reaches exactly the connected component of the root, keeps the root pose, gives a zero error on every edge of the search tree, and leaves the other components alone. With consistent measurements, it recovers the true poses up to the root pose. It also shows that ASSEMBLE returns the sums ∑J⊤ΩJ\sum J^\top \Omega J and ∑J⊤Ωe\sum J^\top \Omega e with a block only where an edge exists, and that 2g2g is the gradient of FF under the right perturbation. The tests check these facts, and check that Gauss-Newton with the assembled system drives the gradient below 10−710^{-7}.

Proof: Spanning tree initialization of a pose graph satisfies every tree edge, and the assembled system has the sparsity of the graphfull

Setting. A pose graph has vertices VV with poses Xi∈SE(2)X_i \in SE(2) and edges k=(i,j,Zk,Ωk)k = (i, j, Z_k, \Omega_k) with i≠ji \ne j, Zk∈SE(2)Z_k \in SE(2) and Ωk\Omega_k symmetric positive semidefinite. The residual of an edge is ek=Log(Zk−1Xi−1Xj)e_k = \mathrm{Log}(Z_k^{-1} X_i^{-1} X_j), and the cost is F=∑kek⊤ΩkekF = \sum_k e_k^\top \Omega_k e_k. Log\mathrm{Log} maps SE(2)SE(2) onto the set of (ρx,ρy,θ)(\rho_x, \rho_y, \theta) with θ∈[−π,π)\theta \in [-\pi, \pi), and it is the inverse of Exp\mathrm{Exp} on that set.

Assumptions.

  • (A1) Exact arithmetic for the group operations.
  • (A2) For the claim on the gradient, every residual angle lies in the open interval (−π,π)(-\pi, \pi), so that Log\mathrm{Log} is smooth at the current poses.

Claim 1 (initialization). Let CC be the connected component of the root rr. INITIALIZE(GG, rr) returns the set CC, keeps XrX_r, and gives every edge of a spanning tree of CC the residual 00. It does not change the poses outside CC.

Proof. Lines L5 to L12 are a breadth-first search from rr over the edge lists. A vertex enters the set seen\mathit{seen} only when an edge from a vertex already in seen\mathit{seen} reaches it, so every vertex in seen\mathit{seen} is in CC. Conversely, let v∈Cv \in C with the path r=v0,v1,…,vℓ=vr = v_0, v_1, \dots, v_\ell = v. By induction on ss, every vsv_s enters seen\mathit{seen}: v0v_0 is there at the start; when vsv_{s} is popped at line L7, which happens because every vertex in seen\mathit{seen} is pushed once, the loop of line L8 visits the edge to vs+1v_{s+1} and adds vs+1v_{s+1} if it is not already there. So seen=C\mathit{seen} = C. Only line L11 writes a pose, and only for a vertex not in seen\mathit{seen} and reached from CC, so poses outside CC do not change and XrX_r is never written.

For each j≠rj \ne r in CC, let k(j)k(j) be the edge through which jj entered seen\mathit{seen}. These ∣C∣−1|C| - 1 edges join each vertex to one that entered before it, so they form a spanning tree of CC. Each pose is written once, at the moment of entry, and the pose XiX_i of the other end is already final then. If k(j)k(j) goes from ii to jj, line L11 sets Xj=XiZX_j = X_i Z, so Z−1Xi−1Xj=IZ^{-1} X_i^{-1} X_j = I and e=Log(I)=0e = \mathrm{Log}(I) = 0. If it goes from jj to ii, line L11 sets Xj=XiZ−1X_j = X_i Z^{-1}, and then the residual of this edge, with jj as its first end, is Log(Z−1Xj−1Xi)=Log(Z−1ZXi−1Xi)=0\mathrm{Log}(Z^{-1} X_j^{-1} X_i) = \mathrm{Log}(Z^{-1} Z X_i^{-1} X_i) = 0. □\square

Corollary. If all measurements are consistent, that is, there are poses X†X^\dagger with Zk=(Xi†)−1Xj†Z_k = (X_i^\dagger)^{-1} X_j^\dagger for every edge, and Xr=Xr†X_r = X_r^\dagger, then after INITIALIZE every pose of CC equals X†X^\dagger and every residual in CC is 00. Indeed, by Claim 1 and induction along the tree, Xj=XiZk=Xi†(Xi†)−1Xj†=Xj†X_j = X_i Z_k = X_i^\dagger (X_i^\dagger)^{-1} X_j^\dagger = X_j^\dagger for each tree edge (and the same for the reversed case). Then every edge of CC, in the tree or not, has Zk−1Xi−1Xj=IZ_k^{-1} X_i^{-1} X_j = I.

Claim 2 (assembly). ASSEMBLE returns Huv=∑kJk,u⊤ΩkJk,vH_{uv} = \sum_k J_{k,u}^\top \Omega_k J_{k,v} and gu=∑kJk,u⊤Ωkekg_u = \sum_k J_{k,u}^\top \Omega_k e_k, where Jk,uJ_{k,u} is the Jacobian of eke_k with respect to the right perturbation Xuexp⁡(δu)X_u \exp(\delta_u) at δu=0\delta_u = 0, and Jk,u=0J_{k,u} = 0 if uu is not an end of kk. A block HuvH_{uv} with u≠vu \ne v is present only if an edge joins uu and vv. Under (A2), 2gu2 g_u is the gradient of F(Xuexp⁡(δu))F(X_u \exp(\delta_u)) at δu=0\delta_u = 0.

Proof. The residual eke_k depends only on XiX_i and XjX_j, so Jk,u=0J_{k,u} = 0 unless u∈{i,j}u \in \{i, j\}. Lines L14 to L17 add, for each edge, the four products Jk,u⊤ΩkJk,vJ_{k,u}^\top \Omega_k J_{k,v} with u,v∈{i,j}u, v \in \{i, j\} and the two products Jk,u⊤ΩkekJ_{k,u}^\top \Omega_k e_k. These are exactly the nonzero terms of the sums, and no block (u,v)(u, v) is created by any other edge than one with the ends uu and vv. For the gradient, ∂F/∂δu=∑k2Jk,u⊤Ωkek\partial F / \partial \delta_u = \sum_k 2 J_{k,u}^\top \Omega_k e_k because Ωk\Omega_k is symmetric, and this is 2gu2 g_u. □\square

In the code the Jacobians are central differences with the step 10−610^{-6}, so JJ has an error of order 10−1210^{-12} times the third derivative. The test compares 2g2g with central differences of FF and finds agreement within 10−510^{-5}.

What this does not show. The spanning tree initialization satisfies the tree edges and puts all of the error of each loop on its non-tree edges. With noise, this can be a poor start for an optimizer, and the claims say nothing about the minimum of FF; that is the problem of pose graph optimization.

Complexity

Let pp be the number of poses, EE the number of edges and dd the number of edges at a vertex.

  • ADD-VERTEX and ADD-EDGE: O(1)O(1) expected, with hash maps for the vertices.
  • NEIGHBORS: O(d)O(d).
  • RESIDUAL: O(1)O(1) in the plane and in 3D.
  • INITIALIZE: O(p+E)O(p + E), as for breadth-first search.
  • ASSEMBLE: O(p+E)O(p + E), and the system has at most p+2Ep + 2E nonzero blocks.
  • Memory: O(p+E)O(p + E).

A typical SLAM pose graph has EE a small multiple of pp: one odometry edge per pose, plus loop closures. Solving the system is not part of the structure, and its cost depends on the fill-in of the factorization; see elimination ordering.

Variants

  • 3D pose graphs. The poses are in SE(3)SE(3), the errors have 6 components, and the blocks are 6×66 \times 6.
  • Pose and landmark graphs. Add landmark vertices and pose to landmark edges; the result is the graph of GraphSLAM and square root SAM.
  • Robust edges. Give loop closure edges a robust kernel, or a switch variable as in switchable constraints, so that a wrong loop closure does not bend the map.
  • Other error forms. Some codes use the plain difference of the coordinates with a wrapped angle, Zij⊖(Xi−1Xj)Z_{ij} \ominus (X_i^{-1} X_j), instead of Log\mathrm{Log}. The two agree to first order for small errors.
  • Hierarchical graphs. Group the poses into submaps and keep a coarse graph of submaps for speed.

When to use it

Use a pose graph when a front end, such as scan matching or visual odometry, already turns the raw data into relative poses. It is the standard back end for 2D and 3D laser SLAM and for visual SLAM with keyframes, as in ORB-SLAM. When landmarks must stay in the estimate, for example to reuse them for localization, use a factor graph with landmarks instead.

Pitfalls

  • Wrong direction of an edge. ZijZ_{ij} is the pose of jj in the frame of ii. Storing ZjiZ_{ji} in its place gives a wrong error that no optimizer can repair.
  • Unwrapped angles. The angle part of the error must be wrapped to [−π,π)[-\pi, \pi), and so must the difference of two angle errors in a finite difference.
  • The gauge. The cost does not change if all poses move by the same rigid motion. Fix one pose, or add a prior, before solving.
  • Overconfident edges. An information matrix that is too large on a wrong loop closure lets that edge win against all the odometry. Check loop closures before adding them.
  • Initialization by a long tree path. On large loops, the spanning tree guess can be far from the optimum, because it stacks all the drift on the closing edges.

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.

pose_graph.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/pose-graph/. The authors are listed in prov/4A941D.jsonl.

"""A planar pose graph: poses on SE(2) as vertices, relative pose measurements as edges.

A pose is a tuple (x, y, theta) in meters and radians. It stands for the
transform T = [[R(theta), (x, y)], [0, 1]]. An edge (i, j, Z, Omega) says
that the pose of j seen from i was measured as Z, with the 3 by 3
information matrix Omega (the inverse of the covariance).

The residual of an edge is e = Log(Z^-1 X_i^-1 X_j) in the coordinates
(rho_x, rho_y, theta) of the Lie algebra se(2). Jacobians use the right
perturbation X exp(delta), by central differences with the step H.

The module holds the structure and its operations: add a vertex, add an
edge, list the edges at a vertex, compute residuals and the cost, set
initial poses from a spanning tree, and assemble the sparse Gauss-Newton
system in 3 by 3 blocks. It does not solve the system.
"""

import math
from collections import deque

H = 1e-6  # the step of the central differences, in the units of delta


def wrap(a):
    """Return the angle a wrapped to [-pi, pi)."""
    return (a + math.pi) % (2.0 * math.pi) - math.pi


def compose(a, b):
    """Return the pose a b (b expressed in the frame of a)."""
    c, s = math.cos(a[2]), math.sin(a[2])
    return (a[0] + c * b[0] - s * b[1], a[1] + s * b[0] + c * b[1], wrap(a[2] + b[2]))


def inverse(a):
    """Return the pose a^-1."""
    c, s = math.cos(a[2]), math.sin(a[2])
    return (-c * a[0] - s * a[1], s * a[0] - c * a[1], wrap(-a[2]))


def _v_coeffs(t):
    """Return (A, B) with V(t) = [[A, -B], [B, A]], A = sin t / t, B = (1 - cos t) / t."""
    if abs(t) < 1e-6:
        return 1.0 - t * t / 6.0, t / 2.0 - t ** 3 / 24.0
    return math.sin(t) / t, (1.0 - math.cos(t)) / t


def exp_se2(v):
    """Return the pose exp(v) for v = (rho_x, rho_y, theta)."""
    a, b = _v_coeffs(v[2])
    return (a * v[0] - b * v[1], b * v[0] + a * v[1], wrap(v[2]))


def log_se2(p):
    """Return v = (rho_x, rho_y, theta) with exp(v) = p and theta in [-pi, pi)."""
    t = wrap(p[2])
    a, b = _v_coeffs(t)
    d = a * a + b * b
    return ((a * p[0] + b * p[1]) / d, (-b * p[0] + a * p[1]) / d, t)


class PoseGraph:
    """Vertices hold poses; edges hold relative pose measurements."""

    def __init__(self):
        self.X = {}  # vertex id -> pose
        self.adj = {}  # vertex id -> list of edge indices
        self.E = []  # list of (i, j, Z, Omega)

    def add_vertex(self, i, pose=(0.0, 0.0, 0.0)):
        if i in self.X:
            raise ValueError("vertex exists")
        self.X[i] = tuple(pose)  # @line L1
        self.adj[i] = []

    def add_edge(self, i, j, z, omega):
        if i not in self.X or j not in self.X or i == j:
            raise ValueError("an edge needs two distinct vertices")
        k = len(self.E)
        self.E.append((i, j, tuple(z), [list(r) for r in omega]))  # @line L2
        self.adj[i].append(k)  # @line L3
        self.adj[j].append(k)
        return k

    def neighbors(self, i):
        """Return the vertices that share an edge with i."""
        out = []
        for k in self.adj[i]:
            a, b = self.E[k][0], self.E[k][1]
            out.append(b if a == i else a)
        return out

    def residual(self, k, xi=None, xj=None):
        """Return e = Log(Z^-1 X_i^-1 X_j) of edge k, optionally at other poses."""
        i, j, z, _ = self.E[k]
        xi = self.X[i] if xi is None else xi
        xj = self.X[j] if xj is None else xj
        return log_se2(compose(inverse(z), compose(inverse(xi), xj)))  # @line L4

    def edge_cost(self, k):
        e = self.residual(k)
        om = self.E[k][3]
        return sum(e[a] * om[a][b] * e[b] for a in range(3) for b in range(3))

    def cost(self):
        """Return the sum over the edges of e^T Omega e."""
        return sum(self.edge_cost(k) for k in range(len(self.E)))

    def initialize(self, root):
        """Set every pose reachable from root by composing edges along a BFS tree.

        The root keeps its pose. Return the set of vertices that were reached.
        """
        seen = {root}  # @line L5
        q = deque([root])
        while q:  # @line L6
            i = q.popleft()  # @line L7
            for k in self.adj[i]:  # @line L8
                a, b, z, _ = self.E[k]
                j = b if a == i else a  # @line L9
                if j not in seen:  # @line L10
                    if a == i:
                        self.X[j] = compose(self.X[i], z)  # @line L11
                    else:
                        self.X[j] = compose(self.X[i], inverse(z))
                    seen.add(j)  # @line L12
                    q.append(j)
        return seen

    def jacobians(self, k):
        """Return (A, B), the 3 by 3 derivatives of the residual of edge k
        with respect to the right perturbations of X_i and X_j."""
        i, j, _, _ = self.E[k]
        xi, xj = self.X[i], self.X[j]
        a = [[0.0] * 3 for _ in range(3)]
        b = [[0.0] * 3 for _ in range(3)]
        for c in range(3):
            d = [0.0, 0.0, 0.0]
            d[c] = H
            dm = [0.0, 0.0, 0.0]
            dm[c] = -H
            ep = self.residual(k, compose(xi, exp_se2(d)), xj)
            em = self.residual(k, compose(xi, exp_se2(dm)), xj)
            fp = self.residual(k, xi, compose(xj, exp_se2(d)))
            fm = self.residual(k, xi, compose(xj, exp_se2(dm)))
            for r in range(3):
                a[r][c] = _diff(ep[r], em[r], r) / (2 * H)
                b[r][c] = _diff(fp[r], fm[r], r) / (2 * H)
        return a, b

    def assemble(self):
        """Return (Hb, g): the Gauss-Newton blocks H_uv = sum J_u^T Omega J_v
        and g_u = sum J_u^T Omega e, as dicts keyed by vertex pairs and vertices.

        A block H_uv with u != v exists only if an edge joins u and v.
        """
        hb, g = {}, {}  # @line L13
        for k, (i, j, _, om) in enumerate(self.E):  # @line L14
            e = self.residual(k)  # @line L15
            a, b = self.jacobians(k)
            for u, ju in ((i, a), (j, b)):
                ou = _mtm(ju, om)  # J_u^T Omega
                for v, jv in ((i, a), (j, b)):
                    blk = hb.setdefault((u, v), [[0.0] * 3 for _ in range(3)])
                    m = _mm(ou, jv)
                    for r in range(3):  # @line L16
                        for c in range(3):
                            blk[r][c] += m[r][c]
                gv = g.setdefault(u, [0.0, 0.0, 0.0])
                for r in range(3):  # @line L17
                    gv[r] += sum(ou[r][c] * e[c] for c in range(3))
        return hb, g  # @line L18


def _diff(p, m, r):
    """Difference of two residual components; the angle is wrapped."""
    return wrap(p - m) if r == 2 else p - m


def _mtm(j, om):
    """Return J^T Omega."""
    return [[sum(j[k][r] * om[k][c] for k in range(3)) for c in range(3)] for r in range(3)]


def _mm(a, b):
    return [[sum(a[r][k] * b[k][c] for k in range(3)) for c in range(3)] for r in range(3)]
test_pose_graph.py 172 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/pose-graph/. The authors are listed in prov/4A941D.jsonl.

import math
import random

import pytest

from pose_graph import PoseGraph, compose, exp_se2, inverse, log_se2, wrap

# A square of side 2 m driven counterclockwise: four poses, then back to the start.
TRUE = [(0.0, 0.0, 0.0), (2.0, 0.0, math.pi / 2), (2.0, 2.0, -math.pi), (0.0, 2.0, -math.pi / 2)]
OM = [[100.0, 0.0, 0.0], [0.0, 100.0, 0.0], [0.0, 0.0, 400.0]]  # 0.1 m and 0.05 rad


def between(a, b):
    return compose(inverse(a), b)


def square(noise=0.0, seed=1, reverse_loop=False):
    rng = random.Random(seed)
    g = PoseGraph()
    for i in range(4):
        g.add_vertex(i)
    pairs = [(0, 1), (1, 2), (2, 3), (0, 3) if reverse_loop else (3, 0)]
    for i, j in pairs:
        z = between(TRUE[i], TRUE[j])
        z = (z[0] + rng.gauss(0, noise), z[1] + rng.gauss(0, noise), wrap(z[2] + rng.gauss(0, noise)))
        g.add_edge(i, j, z, OM)
    return g


def dense_solve(a, b):
    """Gaussian elimination with partial pivoting (reference solver of the test)."""
    n = len(a)
    m = [list(a[r]) + [b[r]] for r in range(n)]
    for c in range(n):
        p = max(range(c, n), key=lambda r: abs(m[r][c]))
        m[c], m[p] = m[p], m[c]
        for r in range(c + 1, n):
            f = m[r][c] / m[c][c]
            for k in range(c, n + 1):
                m[r][k] -= f * m[c][k]
    x = [0.0] * n
    for r in range(n - 1, -1, -1):
        x[r] = (m[r][n] - sum(m[r][k] * x[k] for k in range(r + 1, n))) / m[r][r]
    return x


def test_exp_log_round_trip():
    rng = random.Random(3)
    for _ in range(200):
        v = (rng.uniform(-3, 3), rng.uniform(-3, 3), rng.uniform(-3.1, 3.1))
        w = log_se2(exp_se2(v))
        assert all(abs(p - q) < 1e-12 for p, q in zip(v, w))
    for t in (0.0, 1e-9, 1e-7, -1e-7):
        w = log_se2(exp_se2((1.0, -2.0, t)))
        assert abs(w[0] - 1.0) < 1e-12 and abs(w[1] + 2.0) < 1e-12


def test_consistent_graph_has_zero_residual():
    for rev in (False, True):
        g = square(reverse_loop=rev)
        for i in range(4):
            g.X[i] = TRUE[i]
        assert g.cost() < 1e-24
        assert sorted(g.neighbors(0)) == [1, 3]


def test_spanning_tree_initialization_recovers_true_poses():
    for rev in (False, True):
        g = square(reverse_loop=rev)
        assert g.initialize(0) == {0, 1, 2, 3}
        for i in range(4):
            assert all(abs(wrap(p - q)) < 1e-12 for p, q in zip(g.X[i], TRUE[i]))
        assert g.cost() < 1e-20


def test_initialization_leaves_other_components_alone():
    g = square()
    g.add_vertex(9, (5.0, 5.0, 1.0))
    assert 9 not in g.initialize(0)
    assert g.X[9] == (5.0, 5.0, 1.0)


def test_noisy_loop_closure_error():
    g = square(noise=0.05, seed=7)
    g.initialize(0)
    # BFS from 0 reaches 1 and 3 by edges 0 and 3, then 2 by edge 1.
    # Edge 2 (from 2 to 3) is the only edge outside the tree.
    for k in (0, 1, 3):
        assert all(abs(c) < 1e-12 for c in g.residual(k))
    assert g.edge_cost(2) > 0.0
    assert abs(g.cost() - g.edge_cost(2)) < 1e-12


def test_block_pattern_matches_edges():
    g = square()
    g.add_vertex(4)
    g.add_edge(3, 4, (1.0, 0.0, 0.0), OM)
    g.initialize(0)
    hb, _ = g.assemble()
    off = {(u, v) for (u, v) in hb if u != v}
    want = set()
    for i, j, _, _ in g.E:
        want |= {(i, j), (j, i)}
    assert off == want
    assert {(u, u) for u in range(5)} <= set(hb)


def test_gradient_matches_numerical_gradient_of_cost():
    g = square(noise=0.1, seed=2)
    g.initialize(0)
    g.X[2] = compose(g.X[2], (0.1, -0.2, 0.15))
    _, grad = g.assemble()
    base = dict(g.X)
    for u in range(4):
        for c in range(3):
            d = [0.0, 0.0, 0.0]
            d[c] = 1e-5
            g.X[u] = compose(base[u], exp_se2(d))
            fp = g.cost()
            d[c] = -1e-5
            g.X[u] = compose(base[u], exp_se2(d))
            fm = g.cost()
            g.X[u] = base[u]
            assert abs((fp - fm) / 2e-5 - 2.0 * grad[u][c]) < 1e-5


def gauss_newton_with_dense_solve(g, anchor, iters):
    ids = [i for i in sorted(g.X) if i != anchor]
    pos = {v: 3 * n for n, v in enumerate(ids)}
    for _ in range(iters):
        hb, grad = g.assemble()
        n = 3 * len(ids)
        a = [[0.0] * n for _ in range(n)]
        b = [0.0] * n
        for (u, v), blk in hb.items():
            if u in pos and v in pos:
                for r in range(3):
                    for c in range(3):
                        a[pos[u] + r][pos[v] + c] = blk[r][c]
        for u, gv in grad.items():
            if u in pos:
                for r in range(3):
                    b[pos[u] + r] = -gv[r]
        dx = dense_solve(a, b)
        for u in ids:
            g.X[u] = compose(g.X[u], exp_se2(dx[pos[u]:pos[u] + 3]))
    return g


def test_assembled_system_drives_gradient_to_zero():
    g = square(noise=0.05, seed=7)
    g.add_vertex(4)
    g.add_edge(1, 4, (1.0, 0.5, 0.2), OM)
    g.add_edge(2, 4, between(TRUE[2], compose(TRUE[1], (1.05, 0.45, 0.25))), OM)
    g.initialize(0)
    c0 = g.cost()
    gauss_newton_with_dense_solve(g, 0, 8)
    _, grad = g.assemble()
    assert g.cost() < c0
    assert max(abs(x) for u, gv in grad.items() if u != 0 for x in gv) < 1e-7


def test_errors():
    g = PoseGraph()
    g.add_vertex(0)
    with pytest.raises(ValueError):
        g.add_vertex(0)
    with pytest.raises(ValueError):
        g.add_edge(0, 1, (0, 0, 0), OM)

History

Lu and Milios (1997) aligned laser scans by keeping all scan poses and the relative poses between them, and solving for all poses at once. This is the first pose graph. Gutmann and Konolige (1999) built such graphs incrementally with loop closures. Olson, Leonard and Teller (2006) and Grisetti and colleagues made the optimization fast on large graphs, and Grisetti, Kümmerle, Stachniss and Burgard (2010) wrote a tutorial on graph-based SLAM. Libraries such as g2o and GTSAM store the pose graph as a factor graph.

References

  1. 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 poses linked by relative pose constraints from scan matching and odometry
  2. 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 of poses and constraints, the error of an edge with its information matrix, and the sparse structure of the linear system
  3. Frank Dellaert and Michael Kaess, Factor graphs for robot perception, Foundations and Trends in Robotics 6(1-2), 2017, pose graphs as factor graphs with between factors, and the retraction on the pose manifold

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.add_edge
  • a full proof of time.add_vertex
  • a full proof of time.assemble
  • a full proof of time.initialize
  • a full proof of time.neighbors
  • a full proof of time.residual
  • a full proof of space.total
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)
WritingW4 complete
  • a review of the text: no review record reviews/4A941D/text.yaml