Algorithm Search⌘K

Algorithmadvanced

Real-time correlative scan matching

Also called Olson correlative scan matching.

Finds the pose of a laser scan in a window of poses with the best score on a rasterized lookup table, exactly, by a best-first branch and bound over a coarse and a fine table.

Time
O(A S^2 n) worstO(A (S/D)^2 (n + log(A S^2 / D^2))) boundsO(E n) fineO(G D) tables
Space
O(G + A n + A S^2 / D^2) extra
Where
A = the number of angles of the window; D = the block side in cells; E = the number of fine poses scored; G = the number of cells of the table; S = the number of shifts per axis; n = the number of scan points
Properties
deterministicexactglobal in windowonline
Origin
Edwin B. Olson, 2009

Real-time correlative scan matching finds the rigid motion between a laser scan and a reference, a previous scan or a map, by scoring every pose of a search window on a grid. It does not start from a guess and descend to a local optimum, as iterative closest point does; within the window and at the resolution of the grid, it returns a pose with the best score. Olson (2009) made this fast in two ways. First, the reference is rasterized once into a lookup table, in the spirit of the likelihood field, so that the score of a pose is a sum of nn table reads. Second, a coarse table holds the maxima of blocks of the fine table. A coarse score bounds the fine scores of a whole block of shifts, and a best-first branch and bound scores only the blocks that can still win. The same scores also give a covariance of the match.

In plain words

The robot has a picture of the walls from before, drawn on squared paper, where squares near a wall get high marks. It takes a new scan and wants to know how it moved. For every candidate turn and shift, it lays the scan on the paper and adds the marks under the scan points. The best total wins. To avoid trying every shift, it first uses a rougher sheet where each square holds the best mark of a group of squares. If a group of shifts cannot beat the best total so far even on the rough sheet, the robot skips the whole group.

The problem

The input is a set of reference points PP in the plane, a scan Q={q1,…,qn}Q = \{q_1, \dots, q_n\} of points in the frame of the robot, a prior guess (x0,y0)(x_0, y_0), a list of AA angles θ\theta, and a window of shifts t=(tx,ty)t = (t_x, t_y) with tx,ty∈{−w,…,w}t_x, t_y \in \{-w, \dots, w\} cells of size rr, so S=2w+1S = 2w + 1 shifts per axis. A table LL on the grid of cell size rr scores each cell. The score of the pose (θ,t)(\theta, t) is

s(θ,t)=∑i=1nL(ci(θ)+t),s(\theta, t) = \sum_{i=1}^{n} L\big(c_i(\theta) + t\big),

where ci(θ)c_i(\theta) is the cell of the point (x0,y0)+R(θ) qi(x_0, y_0) + R(\theta)\, q_i. The output is a pose (θ∗,t∗)(\theta^*, t^*) of the largest score in the window.

The table. Olson fills each cell with the log probability of a scan point there, as the maximum over the reference points of a radially symmetric kernel of the distance. Taking the maximum instead of the sum approximates the likelihood of a point by its nearest reference point. The code uses the integer score round(100 e−d2/(2σ2))\mathrm{round}(100\, e^{-d^2 / (2\sigma^2)}) with dd the distance to the nearest reference point within 3σ3\sigma; any score that decreases with dd works for the search, and integers make the comparisons exact. The sum over the scan points treats the points as independent, which is an approximation; it is the reason why the scores of a long scan are very sharp.

The algorithm

Let DD be the side of a block of shifts. The coarse table is

LD(c)=max⁡0≤a,b<DL(c+(a,b)),L_D(c) = \max_{0 \le a, b < D} L(c + (a, b)),

the maximum of LL over the D×DD \times D cells whose lowest corner is cc. For a block BB of shifts with the lowest corner bb, every shift t∈Bt \in B is b+(a,b′)b + (a, b') with 0≤a,b′<D0 \le a, b' < D, so L(ci(θ)+t)≤LD(ci(θ)+b)L(c_i(\theta) + t) \le L_D(c_i(\theta) + b) for each point, and

U(θ,B)=∑iLD(ci(θ)+b) ≥ max⁡t∈Bs(θ,t).U(\theta, B) = \sum_{i} L_D\big(c_i(\theta) + b\big) \ \ge\ \max_{t \in B} s(\theta, t).
  1. CORRELATIVE-SCAN-MATCH(P, Q, (x0, y0), angles, w, r, D)
  2. 1L ← the lookup table of P on the grid of cell size r
  3. 2L_D ← the window maximum of L over D × D cells
  4. 3for each angle θ do ▷ the cells c_i(θ) of the scan
  5. 4for each block B of D × D shifts of the window, with the lowest corner b do
  6. 5push (U = Σ_i L_D(c_i(θ) + b), θ, B) on a max-heap H
  7. 6best ← -∞
  8. 7while H is not empty do
  9. 8pop (U, θ, B) with the largest U from H
  10. 9if U ≤ best then break
  11. 10for each shift t in B within the window do
  12. 11s ← Σ_i L(c_i(θ) + t); if s > best then best ← s, pose ← (θ, t)
  13. 12return pose, best

The cells ci(θ)c_i(\theta) of each angle are computed once. A shift then only adds an integer offset to each cell, so the score of a pose is nn table reads and additions. Line L2 is a 2D sliding window maximum: first along one axis, then along the other.

The coarse table must be a window maximum. Olson describes the low resolution table as a table whose cells hold the maximum of the high resolution cells they cover, for example 30 cm cells over 3 cm cells. If the coarse cells form a fixed partition of the grid, a scan point and its shifts do not in general stay in one coarse cell, because the points ci(θ)c_i(\theta) do not lie on the corners of the coarse grid. The code therefore uses the window maximum LDL_D, defined at every fine cell, which bounds every shift of the block for every point. The cost is a table of the size of LL instead of a table D2D^2 times smaller.

Example

The room. The reference is the walls of a 4 m by 3 m room with a 1 m by 0.5 m box, 340 points spaced 5 cm. The table has cells of r=5r = 5 cm, σ=5\sigma = 5 cm, and 105×85105 \times 85 cells. The window has 13 angles from −0.12-0.12 to 0.120.12 rad in steps of 0.020.02, and shifts of ±8\pm 8 cells (±0.4\pm 0.4 m) around the guess (1.2,1.5)(1.2, 1.5), so 13×172=375713 \times 17^2 = 3757 poses. With D=4D = 4, there are 5×55 \times 5 blocks per angle, so 325 coarse scores.

The scans are about a quarter of the room points, seen from a random true pose with 2 cm noise per coordinate. For four scans, the measured results are:

true pose (x,y,θ)(x, y, \theta) found pose best score fine poses scored
(1.043, 1.527, -0.026) (1.05, 1.55, -0.04) 6852 96
(1.349, 1.555, -0.071) (1.35, 1.55, -0.08) 8247 112
(1.105, 1.587, -0.044) (1.10, 1.60, -0.04) 8239 96
(1.299, 1.264, 0.080) (1.30, 1.25, 0.10) 6742 96

In each case the search of all 3757 poses gives the same best score and the same pose. The branch and bound scored 325 coarse bounds and at most 112 fine poses, about 9 times fewer score evaluations. The found pose is within one cell and one angle step of the truth, which is the resolution of the window. Refine it with a finer window around the result, or with a local method such as ICP.

A corridor. The reference is two parallel walls 1 m apart, and the scan sees 2 m of both walls. The covariance from the scores of the window, with the weights e0.05 (s−smax⁡)e^{0.05\,(s - s_{\max})}, has the standard deviation 0.1870.187 m along the corridor, which is the spread of a uniform weight over the whole window of ±0.3\pm 0.3 m. Across the corridor it is below 1 mm, and in the heading it is 0.0160.016 rad. The scan does not fix the position along the corridor, and the covariance shows it.

Correctness

The correctness proof shows that the algorithm returns a pose with the largest score of the window. It uses two facts. The coarse score U(θ,B)U(\theta, B) is at least the score of every pose of the block, by the bound above. The blocks leave the heap in the order of decreasing UU, so when line L9 stops, every block left in the heap has U≤U \le best, and none of its poses can have a larger score. Every pose of the window lies in exactly one block, and every block that is popped before the stop is scored in full.

The search is exact for the discrete problem: the best pose on the grid of angles and shifts, with the given table. It is not exact for the continuous problem. The grid limits the accuracy to about a cell and an angle step, and the table is a model whose kernel width is set by hand.

Proof: The branch and bound of correlative scan matching returns a pose of the largest score in the windowfull

Setting. LL is a table of real (in the code, integer) scores on Z2\mathbb{Z}^2, with L(c)=0L(c) = 0 outside a finite grid. For a block side D≥1D \ge 1, LD(c)=max⁡0≤a,b<DL(c+(a,b))L_D(c) = \max_{0 \le a, b < D} L(c + (a, b)). The window is a finite set of angles Θ\Theta and the shifts T={−w,…,w}2T = \{-w, \dots, w\}^2. For each θ∈Θ\theta \in \Theta, the scan gives cells c1(θ),…,cn(θ)∈Z2c_1(\theta), \dots, c_n(\theta) \in \mathbb{Z}^2, and the score of a pose is s(θ,t)=∑iL(ci(θ)+t)s(\theta, t) = \sum_i L(c_i(\theta) + t). The blocks are Bb=({bx,…,bx+D−1}×{by,…,by+D−1})∩TB_b = (\{b_x, \dots, b_x + D - 1\} \times \{b_y, \dots, b_y + D - 1\}) \cap T for the corners b=(bx,by)b = (b_x, b_y) with bx,by∈{−w,−w+D,−w+2D,… }b_x, b_y \in \{-w, -w + D, -w + 2D, \dots\}, bx,by≤wb_x, b_y \le w. The coarse score of a block is U(θ,b)=∑iLD(ci(θ)+b)U(\theta, b) = \sum_i L_D(c_i(\theta) + b).

Assumptions.

  • (A1) The arithmetic on scores is exact. (The code uses integers.)
  • (A2) The heap returns an entry with the largest UU among the entries it holds.

Claim. The algorithm ends, and it returns a pose (θ∗,t∗)∈Θ×T(\theta^*, t^*) \in \Theta \times T with s(θ∗,t∗)=max⁡θ∈Θ,t∈Ts(θ,t)s(\theta^*, t^*) = \max_{\theta \in \Theta, t \in T} s(\theta, t).

Proof.

Step 1: the blocks partition the window. For one axis, the corners −w,−w+D,…-w, -w + D, \dots up to ww split {−w,…,w}\{-w, \dots, w\} into the disjoint runs {b,…,min⁡(b+D−1,w)}\{b, \dots, \min(b + D - 1, w)\}, and every shift lies in the run of the largest corner not above it. The product of the runs of the two axes gives that each t∈Tt \in T lies in exactly one block. Lines L3 to L5 push one entry for each pair of an angle and a block, so each pose (θ,t)(\theta, t) of the window belongs to exactly one heap entry.

Step 2: the coarse score bounds the block. Let t∈Bbt \in B_b, so t=b+(a,a′)t = b + (a, a') with 0≤a,a′<D0 \le a, a' < D. For each point, L(ci(θ)+t)=L((ci(θ)+b)+(a,a′))≤LD(ci(θ)+b)L(c_i(\theta) + t) = L((c_i(\theta) + b) + (a, a')) \le L_D(c_i(\theta) + b) by the definition of LDL_D. Summing over ii gives s(θ,t)≤U(θ,b)s(\theta, t) \le U(\theta, b).

Step 3: termination. Each pass through line L8 removes one entry, and nothing is pushed after line L5. The heap has ∣Θ∣|\Theta| times the number of blocks entries, so the loop runs at most that many times. Each pass scores at most D2D^2 poses. Hence the algorithm ends.

Step 4: the invariant. After each pass through lines L8 to L11, best\mathit{best} is the largest score of the poses in the entries popped so far, and pose\mathit{pose} is a pose that reaches it. This holds after zero passes with best=−∞\mathit{best} = -\infty and the empty set of poses. A pass that does not stop at line L9 scores every pose of its block in line L11 and keeps the largest score, so the invariant holds after it.

Step 5: the result. There are two ways to leave the loop.

  • The heap is empty. Then every entry was popped and scored in full, so by Step 1 and Step 4, best\mathit{best} is the largest score over the whole window.
  • Line L9 stops at an entry with U≤bestU \le \mathit{best}. By (A2), every entry left in the heap has a coarse score at most this UU. By Step 2, every pose in such an entry has a score at most its coarse score, so at most best\mathit{best}. The popped entry itself also has all its poses at most U≤bestU \le \mathit{best}. Every other pose was in an entry popped earlier and is at most best\mathit{best} by Step 4. So no pose of the window has a score above best\mathit{best}.

In both cases best\mathit{best} is the maximum over the window. It is at least the score of any pose, and the scores are finite, so at least one pass scored a pose and pose\mathit{pose} is set, with s(pose)=bests(\mathit{pose}) = \mathit{best}. ■\blacksquare

What this does not show. The claim is about the discrete window and the given table. It says nothing about how close the best pose of the window is to the true pose; that depends on the resolution, the kernel and the scene.

Complexity

Let GG be the number of cells of the table and EE the number of fine poses that line L11 scores.

  • Tables: O(∣P∣(σ/r)2)O(|P| (\sigma / r)^2) to stamp the kernels, and O(GD)O(G D) for the window maximum with running maxima of length DD along each axis. A monotone queue makes it O(G)O(G). The tables are built once per reference and shared by all scans matched to it.
  • Rotations: O(An)O(A n).
  • Bounds and heap: A⌈S/D⌉2A \lceil S / D \rceil^2 coarse scores of O(n)O(n) each, and as many heap operations.
  • Fine scores: O(En)O(E n), with E≤AS2E \le A S^2.

In the worst case, for example in a corridor where many poses score alike, the bound prunes little and the cost is that of the full search, O(AS2n)O(A S^2 n). In the room above, EE was about 100 out of 3757. Olson reports that the method runs in real time for windows of the size that odometry errors need; that is a measurement on his data.

Properties

  • Global within the window. It cannot be trapped by a local optimum inside the window, unlike ICP. It can fail only if the true pose is outside the window or the best score belongs to a wrong pose, as in a symmetric room.
  • Exact for the discrete problem and deterministic. The result does not depend on the order of the heap, except for which of several equal best poses it returns.
  • The covariance comes free. Olson's equation (3) gives the covariance from the scores that the search computes, Σ=K/s−uu⊤/s2\Sigma = K/s - u u^\top / s^2 with K=∑jwjxjxj⊤K = \sum_j w_j x_j x_j^\top, u=∑jwjxju = \sum_j w_j x_j and s=∑jwjs = \sum_j w_j, over the poses xjx_j with the weights wjw_j of their likelihoods. It shows ambiguity, such as in a corridor, which a single best pose hides. The pruned search does not score every pose, so the code computes the covariance from a full scan of the window.
  • Resolution bound. The accuracy is that of the grid.

Variants and improvements

  • More levels. Use a pyramid of window maximum tables with the sides D,D2,…D, D^2, \dots, and branch from coarse to fine. This is the precomputed grid scheme used for loop closure in Google's Cartographer.
  • Depth-first search. Explore the most promising block first and keep the best score as a bound, as in depth-first branch and bound. It needs less memory than a heap of all blocks.
  • Refinement. Run a fine window, or a local optimizer, around the result to get below the cell size.
  • Probabilistic tables. Fill the table with log probabilities, as Olson does, so that the scores and the covariance have a probabilistic meaning; the integer table of the code is a scaled and rounded version.
  • Loop closure. With a large window around the guess, the same search checks a loop closure candidate; see loop closure detection.

When to use it

Use correlative scan matching for 2D laser odometry and for loop closure, when the error of the prior guess is larger than the basin of convergence of ICP, and when a covariance of the match is needed for a pose graph. Use ICP or the normal distributions transform when the guess is good and sub-cell accuracy is needed quickly. For 3D scans, the dense window becomes too large; use local methods or feature matching.

Pitfalls

  • A coarse table of fixed blocks. A table whose coarse cells partition the grid is not an upper bound for scan points off the coarse corners. The branch and bound can then prune the best block and return a worse pose without a sign of error. Use the window maximum, or align the shifts so that the bound holds.
  • The window too small. The result is the best pose in the window. If the true pose is outside, the search returns a wrong pose with a confident score. Size the window from the odometry error.
  • The kernel too narrow. With σ\sigma below the cell size, a small error gives no score, and the scores of most poses are 0, which leaves nothing to rank them. With σ\sigma too large, nearby poses score alike and the match is blurred.
  • Overconfident covariance. The sum over independent points makes the likelihood far too sharp. Scale the scores down before the covariance, as the test does with the factor 0.050.05, and choose the factor by checks on real data.
  • Symmetric places. In a corridor or a symmetric room, several poses score alike. Look at the covariance, or at the second best score, before trusting a match.

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.

correlative_scan_matching.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/correlative-scan-matching/. The authors are listed in prov/1ZMBCJ.jsonl.

"""Real-time correlative scan matching with a two-level branch and bound.

The method follows Olson (2009). A reference set of 2D points (a previous
scan or a map) gives a lookup table on a grid with the cell size r. A cell
holds the largest value of a kernel around the reference points, rounded to
an integer: round(100 exp(-d^2 / (2 sigma^2))), where d is the distance from
the center of the cell to a reference point. Olson stores log probabilities;
any score that grows with the fit works for the search, and integers make
the comparisons exact.

A query scan is a list of points in the frame of the robot. A pose of the
search is (theta, tx, ty): a rotation from a list of angles and a shift of
whole cells. The score of a pose is the sum of the table over the cells of
the rotated and shifted query points. The search finds a pose of the largest
score in the window, exactly, and evaluates far fewer poses than a search of
the whole window.
"""

import heapq
import math


class Table:
    """A grid of integer scores. Cells outside the grid score 0."""

    def __init__(self, ox, oy, r, nx, ny, pad=0):
        self.ox, self.oy, self.r = ox, oy, r
        self.nx, self.ny, self.pad = nx, ny, pad
        self.v = [[0] * (ny + pad) for _ in range(nx + pad)]

    def get(self, i, j):
        i += self.pad
        j += self.pad
        if 0 <= i < self.nx + self.pad and 0 <= j < self.ny + self.pad:
            return self.v[i][j]
        return 0

    def cell(self, x, y):
        return round((x - self.ox) / self.r), round((y - self.oy) / self.r)


def lookup_table(ref, r, sigma, margin):
    """Return the high resolution table of the points ref, with the cell size r.

    The grid covers the box of ref grown by margin on each side.
    """
    if not ref or r <= 0.0 or sigma <= 0.0:
        raise ValueError("need points, r > 0 and sigma > 0")
    xs = [p[0] for p in ref]
    ys = [p[1] for p in ref]
    ox, oy = min(xs) - margin, min(ys) - margin
    nx = int(math.ceil((max(xs) + margin - ox) / r)) + 1
    ny = int(math.ceil((max(ys) + margin - oy) / r)) + 1
    t = Table(ox, oy, r, nx, ny)
    reach = int(math.ceil(3.0 * sigma / r))
    for px, py in ref:
        ci, cj = t.cell(px, py)
        for i in range(max(0, ci - reach), min(nx, ci + reach + 1)):
            dx = ox + i * r - px
            for j in range(max(0, cj - reach), min(ny, cj + reach + 1)):
                dy = oy + j * r - py
                val = round(100.0 * math.exp(-(dx * dx + dy * dy) / (2.0 * sigma * sigma)))
                if val > t.v[i][j]:
                    t.v[i][j] = val
    return t


def window_max_table(t, d):
    """Return the table T_d with T_d(i, j) = max of t over cells (i + a, j + b), 0 <= a, b < d.

    T_d is defined for i from -(d - 1) on, so that it bounds every shift.
    """
    low = Table(t.ox, t.oy, t.r, t.nx, t.ny, pad=d - 1)
    # first along j, then along i, each a running max over d cells
    rows = [[max(t.get(i, j + b) for b in range(d)) for j in range(-(d - 1), t.ny)] for i in range(-(d - 1), t.nx + d - 1)]
    for a in range(t.nx + d - 1):
        for b in range(t.ny + d - 1):
            low.v[a][b] = max(rows[a + k][b] for k in range(d) if a + k < len(rows))
    return low


def rotated_cells(t, scan, theta, x0, y0):
    """Return the table cells of the scan points rotated by theta and moved to (x0, y0)."""
    c, s = math.cos(theta), math.sin(theta)
    return [t.cell(x0 + c * qx - s * qy, y0 + s * qx + c * qy) for qx, qy in scan]


def score(t, cells, tx, ty):
    return sum(t.get(i + tx, j + ty) for i, j in cells)


def brute_force(t, scan, x0, y0, thetas, w):
    """Return (best score, (theta, tx, ty), number of poses), over all poses of the window."""
    best, pose, count = -1, None, 0
    for th in thetas:
        cells = rotated_cells(t, scan, th, x0, y0)
        for tx in range(-w, w + 1):
            for ty in range(-w, w + 1):
                count += 1
                s = score(t, cells, tx, ty)
                if s > best:
                    best, pose = s, (th, tx, ty)
    return best, pose, count


def correlative_scan_match(t, low, d, scan, x0, y0, thetas, w):
    """Return (best score, (theta, tx, ty), number of full resolution poses scored).

    t is the high resolution table, low = window_max_table(t, d). The window
    is the angles thetas and the shifts tx, ty in [-w, w] cells around (x0, y0).
    """
    heap = []
    cells_of = {}
    for th in thetas:  # @line L3
        cells = rotated_cells(t, scan, th, x0, y0)
        cells_of[th] = cells
        for bx in range(-w, w + 1, d):  # @line L4
            for by in range(-w, w + 1, d):
                heapq.heappush(heap, (-score(low, cells, bx, by), th, bx, by))  # @line L5
    best, pose, count = -1, None, 0  # @line L6
    while heap:  # @line L7
        neg_u, th, bx, by = heapq.heappop(heap)  # @line L8
        if -neg_u <= best:  # @line L9
            break
        cells = cells_of[th]
        for tx in range(bx, min(bx + d, w + 1)):  # @line L10
            for ty in range(by, min(by + d, w + 1)):
                count += 1
                s = score(t, cells, tx, ty)  # @line L11
                if s > best:
                    best, pose = s, (th, tx, ty)
    return best, pose, count  # @line L12


def build_tables(ref, r, sigma, margin, d):
    """Lines L1 and L2: the high resolution table and its window max table."""
    t = lookup_table(ref, r, sigma, margin)  # @line L1
    low = window_max_table(t, d)  # @line L2
    return t, low


def pose_of(t, x0, y0, p):
    """Return the metric pose (x, y, theta) of a search pose (theta, tx, ty)."""
    th, tx, ty = p
    return (x0 + tx * t.r, y0 + ty * t.r, th)


def covariance(t, scan, x0, y0, thetas, w, scale):
    """Return the mean and covariance of the poses of the window, weighted by exp(scale * (s - s_max)).

    This is the estimate of Olson's equation (3): Sigma = K / s - u u^T / s^2,
    with K = sum w x x^T, u = sum w x and s = sum w, over all poses x of the window.
    scale converts a score to a log likelihood.
    """
    poses = []
    for th in thetas:
        cells = rotated_cells(t, scan, th, x0, y0)
        for tx in range(-w, w + 1):
            for ty in range(-w, w + 1):
                poses.append((score(t, cells, tx, ty), pose_of(t, x0, y0, (th, tx, ty))))
    top = max(s for s, _ in poses)
    sw = 0.0
    u = [0.0, 0.0, 0.0]
    k = [[0.0] * 3 for _ in range(3)]
    for s, x in poses:
        wt = math.exp(scale * (s - top))
        sw += wt
        for a in range(3):
            u[a] += wt * x[a]
            for b in range(3):
                k[a][b] += wt * x[a] * x[b]
    mean = [v / sw for v in u]
    cov = [[k[a][b] / sw - u[a] * u[b] / (sw * sw) for b in range(3)] for a in range(3)]
    return mean, cov
test_correlative_scan_matching.py 126 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/correlative-scan-matching/. The authors are listed in prov/1ZMBCJ.jsonl.

import math
import random

import pytest

from correlative_scan_matching import (
    brute_force,
    build_tables,
    correlative_scan_match,
    covariance,
    lookup_table,
    pose_of,
    rotated_cells,
    score,
    window_max_table,
)

R = 0.05  # cell size, m
SIGMA = 0.05  # kernel width, m
D = 4  # cells per block side of the low resolution level
W = 8  # the shifts are -W to W cells, so +-0.4 m
THETAS = [k * 0.02 for k in range(-6, 7)]  # +-0.12 rad


def room():
    """The walls of a 4 m by 3 m room with a 1 m by 0.5 m box, every 5 cm."""
    pts = []
    for k in range(81):
        pts += [(k * 0.05, 0.0), (k * 0.05, 3.0)]
    for k in range(1, 60):
        pts += [(0.0, k * 0.05), (4.0, k * 0.05)]
    for k in range(21):
        pts += [(2.5 + k * 0.05, 1.0), (2.5 + k * 0.05, 1.5)]
    for k in range(1, 10):
        pts += [(2.5, 1.0 + k * 0.05), (3.5, 1.0 + k * 0.05)]
    return pts


def scan_from(pose, pts, rng, noise, keep):
    """The points pts seen from pose, in the frame of the robot, with noise."""
    x, y, th = pose
    c, s = math.cos(th), math.sin(th)
    out = []
    for px, py in pts:
        if rng.random() < keep:
            dx, dy = px - x, py - y
            out.append((c * dx + s * dy + rng.gauss(0.0, noise), -s * dx + c * dy + rng.gauss(0.0, noise)))
    return out


@pytest.fixture(scope="module")
def tables():
    return build_tables(room(), R, SIGMA, 0.6, D)


def test_window_max_bounds_every_cell(tables):
    t, low = tables
    for i in range(-D, t.nx + 2, 3):
        for j in range(-D, t.ny + 2, 3):
            want = max(t.get(i + a, j + b) for a in range(D) for b in range(D))
            assert low.get(i, j) == want


def test_branch_and_bound_finds_the_best_score():
    rng = random.Random(3)
    t, low = build_tables(room(), R, SIGMA, 0.6, D)
    for _ in range(4):
        truth = (1.2 + rng.uniform(-0.3, 0.3), 1.5 + rng.uniform(-0.3, 0.3), rng.uniform(-0.1, 0.1))
        scan = scan_from(truth, room(), rng, 0.02, 0.25)
        x0, y0 = 1.2, 1.5  # the prior guess
        best, pose, count = correlative_scan_match(t, low, D, scan, x0, y0, THETAS, W)
        bf_best, bf_pose, bf_count = brute_force(t, scan, x0, y0, THETAS, W)
        assert best == bf_best
        assert score(t, rotated_cells(t, scan, pose[0], x0, y0), pose[1], pose[2]) == best
        assert count < bf_count / 3
        x, y, th = pose_of(t, x0, y0, pose)
        assert math.hypot(x - truth[0], y - truth[1]) < 0.06 and abs(th - truth[2]) < 0.03


def test_exact_pose_on_the_grid_is_found():
    rng = random.Random(8)
    t, low = build_tables(room(), R, SIGMA, 0.6, D)
    truth = (1.0 + 3 * R, 1.6 - 5 * R, THETAS[9])
    scan = scan_from(truth, room(), rng, 0.0, 0.3)
    best, pose, _ = correlative_scan_match(t, low, D, scan, 1.0, 1.6, THETAS, W)
    assert pose == (THETAS[9], 3, -5)
    # every point lies on a reference point up to rounding to the grid
    assert best >= 60 * len(scan)


def test_corridor_is_uncertain_along_its_axis():
    # two long parallel walls: a shift along the walls barely changes the score
    ref = [(k * 0.05, 0.0) for k in range(-40, 120)] + [(k * 0.05, 1.0) for k in range(-40, 120)]
    rng = random.Random(1)
    truth = (2.0, 0.5, 0.0)
    pts = [(k * 0.05, 0.0) for k in range(20, 60)] + [(k * 0.05, 1.0) for k in range(20, 60)]
    scan = scan_from(truth, pts, rng, 0.0, 1.0)
    t = lookup_table(ref, R, SIGMA, 0.6)
    mean, cov = covariance(t, scan, 2.0, 0.5, [-0.04, -0.02, 0.0, 0.02, 0.04], 6, 0.05)
    assert cov[0][0] > 20.0 * cov[1][1]
    assert abs(mean[1] - 0.5) < 0.01 and abs(mean[2]) < 0.01


def test_room_covariance_is_small_and_symmetric(tables):
    t, _ = tables
    rng = random.Random(2)
    scan = scan_from((1.5, 1.5, 0.0), room(), rng, 0.0, 0.3)
    mean, cov = covariance(t, scan, 1.5, 1.5, THETAS, 4, 0.05)
    assert all(abs(cov[a][b] - cov[b][a]) < 1e-15 for a in range(3) for b in range(3))
    assert math.hypot(mean[0] - 1.5, mean[1] - 1.5) < 0.01
    assert cov[0][0] < 1e-3 and cov[1][1] < 1e-3


def test_errors():
    with pytest.raises(ValueError):
        lookup_table([], R, SIGMA, 0.5)
    with pytest.raises(ValueError):
        lookup_table([(0.0, 0.0)], 0.0, SIGMA, 0.5)
    t = lookup_table([(0.0, 0.0)], R, SIGMA, 0.5)
    assert t.get(t.cell(0.0, 0.0)[0], t.cell(0.0, 0.0)[1]) == 100
    assert t.get(-100, -100) == 0
    low = window_max_table(t, 1)
    assert all(low.get(i, j) == t.get(i, j) for i in range(t.nx) for j in range(t.ny))

History

Correlation of scans on a grid of poses is an old idea in robotics and in image template matching, but a dense search was long thought too slow for real time. Olson (2009) showed that a rasterized lookup table, a coarse table of maxima and a best-first search make it fast enough for laser odometry and loop closure. Hess, Kohler, Rapp and Andor (2016) used a related branch and bound over precomputed grids for loop closure in Cartographer.

References

  1. Edwin B. Olson, Real-time correlative scan matching, Proceedings of the IEEE International Conference on Robotics and Automation (ICRA), 2009, pages 4387 to 4393, the rasterized lookup table of log probabilities, the multi-resolution search with the low resolution table of maxima, and the covariance estimate of equation (3)
  2. Sebastian Thrun, Wolfram Burgard and Dieter Fox, Probabilistic Robotics, MIT Press, 2005, Chapter 6, the likelihood field model of range finders, which the lookup table discretizes

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.bounds
  • a full proof of time.fine
  • a full proof of time.tables
  • a full proof of time.worst
  • 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