Algorithm Search⌘K

Algorithmadvanced

Grid-based Rao-Blackwellized SLAM

Also called improved proposal grid SLAM, Grisetti RBPF SLAM.

Grisetti's particle filter that builds one occupancy grid per particle, with scan matching in the proposal and adaptive resampling.

Time
O(N G) resamplingO(N B (S + K + L)) step
Space
O(N G) extra
Where
B = the number of beams per scan; G = the number of cells of a grid; K = the number of points of the proposal; L = the number of cells along one beam; N = the number of particles; S = the number of score evaluations of the scan matcher
Properties
randomizednot exactonlinerecursive
Origin
Giorgio Grisetti, Cyrill Stachniss, Wolfram Burgard, 2007

Grid-based Rao-Blackwellized SLAM builds an occupancy grid map from laser scans and odometry with a particle filter in which each particle holds one robot path and one full grid built along that path. It is the Rao-Blackwellized particle filter applied to grid maps, as FastSLAM is for landmark maps. Its contribution is in how it moves the particles: in the version of Grisetti, Stachniss and Burgard (2007), each particle matches the new scan against its own map and draws its new pose near the match, not from the odometry alone, and the filter resamples only when the weights have become uneven. With these two changes, the filter needs far fewer particles than a grid particle filter that moves its particles by odometry alone. The open source implementation GMapping, from the same group, made the method a common tool for 2D laser SLAM.

In plain words

A robot with a laser scanner drives through a building. The filter keeps a few guesses of where the robot has been, and each guess draws its own map. When a new scan arrives, each guess first checks where the scan fits best on its own map, and then picks its new position close to that fit. Guesses whose maps match the scan well get more weight. When a few guesses hold almost all the weight, the filter copies the good ones and drops the bad ones, but it waits until then, because each copy step also throws away variety. The best guess gives the map.

The problem

The input is a stream of odometry steps utu_t, which give the relative motion with noise, and laser scans ztz_t, each a list of ranges at known angles. The output is a grid map of the area, with each cell occupied or free, and the robot path. This is the SLAM problem with a dense map. A dense grid has thousands of cells, so one joint Gaussian over the pose and the map, as in EKF SLAM, is out of the question. Given the path, the map is easy: it is occupancy grid mapping with known poses. That is what makes a Rao-Blackwellized filter fit.

The algorithm

  1. GRID_RBPF(particles {(x^i, m^i, w^i)} for i = 1..N, u_t, z_t)
  2. 1for i ← 1 to N do
  3. 2x' ← x^i ⊕ u_t ▷ the odometry guess
  4. 3x̂ ← scan match of z_t in m^i, by hill climbing from x'
  5. 4if the match fails then draw x^i ~ p(x | x^i, u_t); w^i ← w^i · p(z_t | m^i, x^i); go to L7
  6. 5draw x_1..x_K in a box around x̂; τ_j ← p(z_t | m^i, x_j) · p(x_j | x^i, u_t)
  7. 6μ, Σ ← the mean and covariance of the x_j weighted by τ_j; draw x^i ~ N(μ, Σ); w^i ← w^i · Σ_j τ_j
  8. 7update the grid m^i with z_t at x^i ▷ log-odds update
  9. 8normalize the weights; if N_eff = 1 / Σ (w^i)² ≥ N/2 then return the particles
  10. 9resample N particles in proportion to w^i, each with its own copy of the grid and weight 1/N

The proposal. The best draw for a particle is from p(xt∣mi,xt−1i,zt,ut)p(x_t \mid m^i, x^i_{t-1}, z_t, u_t), the motion model times the scan likelihood, normalized. Its weight factor is then p(zt∣mi,xt−1i,ut)p(z_t \mid m^i, x^i_{t-1}, u_t), the same whatever pose is drawn. A laser scan is far more precise than odometry, so this density is a narrow peak near the pose where the scan fits the map. Line L3 finds the peak, and lines L5 and L6 approximate the density by a Gaussian fitted to KK scored points around it. The sum of the scores in line L6 estimates the weight factor.

The scan likelihood. The code scores each beam endpoint by its distance dd to the nearest occupied cell nearby, as exp⁡(−d2/2σ2)\exp(-d^2 / 2 \sigma^2), a simple form of the likelihood field model. Any scan matcher that returns a good local fit can take its place.

Adaptive resampling. Line L8 resamples only when the effective sample size NeffN_\text{eff} falls below N/2N/2, the threshold of Grisetti et al. Between resampling steps the weights carry the information, and no particle is lost.

Example

The proposal. Take one coordinate only. The scan matcher returns x^=1.00\hat x = 1.00 m. Three points 0.950.95, 1.001.00 and 1.051.05 get the scores τ=1,2,1\tau = 1, 2, 1. The weighted mean is (0.95+2⋅1.00+1.05)/4=1.00(0.95 + 2 \cdot 1.00 + 1.05) / 4 = 1.00, and the weighted variance is (0.052+0+0.052)/4=0.00125(0.05^2 + 0 + 0.05^2) / 4 = 0.00125, a standard deviation of 3.5 cm. The particle draws its new position from N(1.00,0.00125)N(1.00, 0.00125), and its weight is multiplied by the sum of the scores, 4, times the volume of the box over KK.

Resampling. Four particles end a step with the normalized weights 0.5,0.3,0.1,0.10.5, 0.3, 0.1, 0.1. Then Neff=1/(0.25+0.09+0.01+0.01)=2.78≥2N_\text{eff} = 1 / (0.25 + 0.09 + 0.01 + 0.01) = 2.78 \ge 2, and the filter keeps them as they are. After the next step the weights are 0.7,0.1,0.1,0.10.7, 0.1, 0.1, 0.1, so Neff=1/0.52=1.92<2N_\text{eff} = 1 / 0.52 = 1.92 < 2, and the filter resamples. The test file checks both examples.

A run. The code drives a robot with 16 beams around a box in a room of 6 m by 4 m, on a grid of 10 cm cells. The robot turns 0.015 rad per step more than the odometry says. After 25 steps, over 6 seeds, odometry alone ends on average more than 0.48 m from the true position. These are measurements of this code:

proposal particles mean final position error
scan matching (lines L3 to L6) 5 0.05 m
motion model only 5 0.13 m
motion model only 30 0.06 m

Of the cells that the best particle marks occupied, 96% are within one cell of a true wall, against about 60% for the map built along the odometry path. In this small Python code, 5 particles with scan matching took about as much time as 30 particles without it. The gain in memory is clearer: 5 grids instead of 30.

Correctness

Given the path, the map is the occupancy grid of that path, so the filter only needs to sample paths; this is the Rao-Blackwellized factorization. For the proposal p(xt∣m,xt−1,zt,ut)p(x_t \mid m, x_{t-1}, z_t, u_t), the importance weight factor is p(zt∣m,xt−1,ut)p(z_t \mid m, x_{t-1}, u_t), by Bayes' rule. Lines L5 and L6 approximate both: the sum of the scores times the volume over KK is an unbiased estimate of the integral over the box, and the Gaussian is a moment fit. The fallback of line L4 is a plain particle filter step whose weight has the same expected value. The correctness proof gives the derivation, the limits of the approximation, and why the scan matcher stops. Note that the grid update itself treats the cells as independent, so even with exact sampling the map is an approximation.

Proof: Why the improved proposal and its weight are right, and what is approximatedfull

Setting. Particle ii holds a pose xt−1ix^i_{t-1}, a grid map mt−1im^i_{t-1} built from its own path and the scans so far, and a weight wt−1iw^i_{t-1}. The motion model is p(xt∣xt−1,ut)p(x_t \mid x_{t-1}, u_t) and the scan model is p(zt∣m,xt)p(z_t \mid m, x_t). The target of the filter is the path posterior p(x1:t∣z1:t,u1:t)p(x_{1:t} \mid z_{1:t}, u_{1:t}). Given a path, the map is the result of occupancy grid mapping on that path, p(m∣x1:t,z1:t)p(m \mid x_{1:t}, z_{1:t}).

Claims. (1) The method is a Rao-Blackwellized particle filter over paths. (2) If line L6 draws from p(xt∣mt−1i,xt−1i,zt,ut)p(x_t \mid m^i_{t-1}, x^i_{t-1}, z_t, u_t), then the correct weight factor is p(zt∣mt−1i,xt−1i,ut)p(z_t \mid m^i_{t-1}, x^i_{t-1}, u_t), which does not depend on the drawn pose. (3) Lines L5 and L6 approximate this draw by a Gaussian and this factor by a Monte Carlo sum, and line L4 falls back to the motion model, whose weight estimates the same factor. (4) Resampling and the copies of the grids keep the represented distribution. (5) The scan matcher of line L3 stops and never lowers the score.

(1) The factorization

By the chain rule, p(x1:t,m∣z1:t,u1:t)=p(m∣x1:t,z1:t) p(x1:t∣z1:t,u1:t)p(x_{1:t}, m \mid z_{1:t}, u_{1:t}) = p(m \mid x_{1:t}, z_{1:t}) \, p(x_{1:t} \mid z_{1:t}, u_{1:t}). The controls drop from the first factor because, given the path, they carry no information about the map. So it is enough to sample paths and to compute, for each path, the map posterior. Line L7 does this incrementally for each particle, with the log-odds update. The grid update is itself an approximation: it treats the cells as independent and uses an inverse sensor model. So, unlike the landmark filters of FastSLAM in the linear Gaussian case, the "closed form" part here is not exact. This is a known property of occupancy grids, not of the particle filter.

(2) The optimal proposal and its weight

Write m=mt−1im = m^i_{t-1}, x′=xt−1ix' = x^i_{t-1} and q(xt)=p(xt∣m,x′,zt,ut)q(x_t) = p(x_t \mid m, x', z_t, u_t). By Bayes' rule,

q(xt)=p(zt∣m,xt) p(xt∣x′,ut)p(zt∣m,x′,ut),p(zt∣m,x′,ut)=∫p(zt∣m,x) p(x∣x′,ut) dx.q(x_t) = \frac{p(z_t \mid m, x_t) \, p(x_t \mid x', u_t)}{p(z_t \mid m, x', u_t)}, \qquad p(z_t \mid m, x', u_t) = \int p(z_t \mid m, x) \, p(x \mid x', u_t) \, dx.

The scan model needs only the map built from the earlier scans, because the map is a function of the path so far and the scans so far. The path target changes from step t−1t-1 to step tt by the factor p(zt∣m,xt) p(xt∣x′,ut)/p(zt∣z1:t−1,u1:t)p(z_t \mid m, x_t) \, p(x_t \mid x', u_t) / p(z_t \mid z_{1:t-1}, u_{1:t}), where the denominator is the same for all particles. The importance weight is the target over the proposal, so the weight factor of a particle that draws xtx_t from qq is

p(zt∣m,xt) p(xt∣x′,ut)q(xt)=p(zt∣m,x′,ut),\frac{p(z_t \mid m, x_t) \, p(x_t \mid x', u_t)}{q(x_t)} = p(z_t \mid m, x', u_t),

up to the common constant. It does not depend on xtx_t. This is the proposal that Grisetti, Stachniss and Burgard (2007) approximate.

(3) The approximation of lines L4 to L6

The scan model of a laser is very peaked, so qq is concentrated near the poses where the scan fits the map. Line L3 finds such a pose x^\hat x by scan matching. Line L5 draws KK points xjx_j uniformly in a box BB of volume VV around x^\hat x and computes τj=p(zt∣m,xj) p(xj∣x′,ut)\tau_j = p(z_t \mid m, x_j) \, p(x_j \mid x', u_t).

  • The weight. VK∑jτj\frac{V}{K} \sum_j \tau_j is a Monte Carlo estimate of ∫Bp(zt∣m,x) p(x∣x′,ut) dx\int_B p(z_t \mid m, x) \, p(x \mid x', u_t) \, dx: each term has the expected value 1V∫Bτ(x) dx\frac{1}{V} \int_B \tau(x) \, dx, so the estimate is unbiased for the integral over BB. The integral over BB is below the integral of claim (2) by the mass outside BB, which is small when qq is concentrated in BB. The tests compare the estimate with K=3000K = 3000 against a midpoint rule over the same box. In the code the scan model drops a factor that is the same for every pose and every particle, so it cancels at normalization.
  • The draw. Line L6 fits a Gaussian to the points with the weights τj/∑kτk\tau_j / \sum_k \tau_k: the weighted mean and the weighted covariance, with a small floor on the diagonal. If qq is Gaussian and KK is large, the fit tends to the moments of qq restricted to BB. If qq has several modes or is cut by the box, the draw is from a different density than the weight assumes, and the weights are then only approximate. This is a known error of the method, not a bug of the code.
  • The fallback. If the scan matcher fails, line L4 draws xtx_t from the motion model and multiplies the weight by p(zt∣m,xt)p(z_t \mid m, x_t). The expected value of this factor over the draw is ∫p(zt∣m,x) p(x∣x′,ut) dx\int p(z_t \mid m, x) \, p(x \mid x', u_t) \, dx, the same integral as above. So both branches estimate the same weight factor, and particles that took different branches can be compared.

(4) Resampling

Lines L8 and L9 compute Neff=1/∑i(w~i)2N_\text{eff} = 1 / \sum_i (\tilde w^i)^2 from the normalized weights and resample only when it is below N/2N/2. Resampling draws NN particles with probabilities w~i\tilde w^i, which keeps the represented distribution in expectation, and sets all weights to 1/N1/N. If it does not resample, the particles and their weights are left as they are, which is also correct. Each copy gets its own copy of the grid. The tests check that a change to one copy does not change another; if two copies shared one mutable grid, the next update of line L7 would write the scan of one path into the map of the other.

(5) The scan matcher

The matcher accepts a move only when it raises the score, so the score never goes down and the result is at least as good as the odometry guess. It stops: at each step size the candidate poses lie on a lattice, a pose whose score is above the score of the start must have at least one beam endpoint near an occupied cell of the finite grid, so such poses lie in a bounded region with finitely many lattice points, and a strictly increasing sequence cannot repeat a point. The result is a local maximum at the smallest step size, not always the global one: the tests show a start 6 cm from the truth from which it stops 5 cm off.

Complexity

  • Time per step: O(NB(S+K+L))O(N B (S + K + L)). Each score evaluation looks at BB beam endpoints, the matcher makes SS evaluations and the proposal KK more, and the grid update walks about LL cells per beam.
  • Resampling: O(NG)O(N G) for copying grids of GG cells. Adaptive resampling makes this rarer. Real implementations share unchanged parts of the maps between particles, for example in a tree of map patches, to avoid the full copy.
  • Memory: O(NG)O(N G), one grid per particle. This, more than time, limits the number of particles for large areas.

Properties

  • Few particles (measurement). The improved proposal puts the particles where the scan fits, so most of them keep a useful weight. Grisetti et al. report maps of real data sets built with far fewer particles than earlier grid-based filters needed; the table above shows the same effect on a small scale.
  • Multimodal over paths. Each particle has its own path and map. When the robot closes a loop, the particles whose maps fit the old part survive, which corrects the whole map at once.
  • Loss of path diversity. Each resampling step reduces the number of distinct path histories. Adaptive resampling slows this, but after many steps without a loop closure, the particles may share all of their old path, and a later loop closure cannot be fixed.
  • Not exact. The Gaussian fit, the box, the scan matcher and the independent cells of the grid are all approximations.

Variants and improvements

  • Plain grid FastSLAM. The motion model as the proposal and one grid per particle, as in the grid-based FastSLAM of Probabilistic Robotics. It needs far more particles with a precise laser.
  • Selective resampling only. Keeping the motion model proposal but resampling by NeffN_\text{eff} already helps.
  • Shared maps. Representing the grid of each particle as differences from the grids of its ancestors saves memory and copy time.
  • Graph-based SLAM. For large areas, graph-based methods such as pose graph optimization, with correlative scan matching for the constraints, have mostly replaced particle filters, because they can optimize the whole path again after a loop closure.

When to use it

Use it for 2D laser SLAM in indoor areas of moderate size, when odometry is available and an online grid map is wanted. It handles ambiguous loop closures better than a single-hypothesis method, because the particles keep several paths. For large areas, long trajectories or 3D data, a graph-based method is usually better. For landmark maps, use FastSLAM. For localization in a known map, use Monte Carlo localization.

Pitfalls

  • Copies that share one grid. A copied particle must own its grid, or share it only through a structure that never changes shared parts.
  • A peaked likelihood with the motion model. With a precise laser and the motion model as the proposal, almost all particles get a near zero weight. This is the problem the improved proposal solves.
  • A scan matcher stuck in a local maximum. Hill climbing can stop near, not at, the right pose, and then the Gaussian is centered there. Start from the odometry guess, and fall back to the motion model when too few beams match.
  • Too few particles for a large loop. Particles cannot hold many paths. If no particle has a path that closes the loop correctly, the map gets a double wall.
  • Units of the weights. The weights of the two branches of lines L4 and L6 must estimate the same quantity, with the same constants, or the branch decides which particles survive.

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.

grid_based_rbpf_slam.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/grid-based-rbpf-slam/. The authors are listed in prov/X1GN8F.jsonl.

"""Grid-based Rao-Blackwellized SLAM with an improved proposal, kept small.

After Grisetti, Stachniss and Burgard (2007). Each particle holds a pose, a
log-odds occupancy grid and a log weight. One step does, for each particle:
scan matching of the new scan in the grid of the particle, starting from the
odometry guess; K points around the match, each scored by the scan
likelihood times the motion density; a Gaussian fitted to these points, from
which the new pose is drawn; the weight times the sum of the scores; and the
update of the grid. Resampling happens only when N_eff < N/2.

This is a teaching version on a small planar grid. It has none of the speed
tricks of a real implementation (no shared map tree, no lookup tables, no
multi-resolution matching) and its scan likelihood is a simple endpoint model.

  Params                                     grid size, sensor and noise settings
  grid_rbpf_step(particles, u, ranges, rng, p)   one step, lines L1 to L9
  scan_match, scan_loglik, integrate_scan    the parts of the step
  World                                      a simulated room for the tests
"""

import math

import robest

LOG_2PI = math.log(2.0 * math.pi)


class Params:
    def __init__(
        self,
        width=60,
        height=40,
        res=0.1,
        beams=16,
        max_range=5.0,
        l_occ=0.9,
        l_free=-0.4,
        l_max=6.0,
        sigma_hit=0.1,
        search=1,
        motion_sd=(0.03, 0.02, 0.03),
        k_points=8,
        delta=(0.05, 0.05, 0.03),
        min_match=0.5,
        match_step=(0.1, 0.1, 0.05),
        match_levels=3,
    ):
        self.width, self.height, self.res = width, height, res
        self.angles = [2.0 * math.pi * k / beams for k in range(beams)]
        self.max_range = max_range
        self.l_occ, self.l_free, self.l_max = l_occ, l_free, l_max
        self.sigma_hit = sigma_hit
        self.search = search
        self.motion_sd = motion_sd
        self.k_points = k_points
        self.delta = delta
        self.min_match = min_match
        self.match_step = match_step
        self.match_levels = match_levels


# ---------------------------------------------------------------- poses and motion


def compose(x, d):
    """Return x (+) d: the pose d, given in the frame of x, in the world frame."""
    c, s = math.cos(x[2]), math.sin(x[2])
    return [x[0] + c * d[0] - s * d[1], x[1] + s * d[0] + c * d[1], robest.wrap_angle(x[2] + d[2])]


def relative(a, b):
    """Return a^(-1) (+) b: the pose b in the frame of a."""
    c, s = math.cos(a[2]), math.sin(a[2])
    dx, dy = b[0] - a[0], b[1] - a[1]
    return [c * dx + s * dy, -s * dx + c * dy, robest.wrap_angle(b[2] - a[2])]


def motion_logpdf(prev, x, u, sd):
    """Log density of x given prev and the odometry step u (in the frame of prev)."""
    d = relative(prev, x)
    e = [d[0] - u[0], d[1] - u[1], robest.wrap_angle(d[2] - u[2])]
    return sum(-0.5 * (e[i] / sd[i]) ** 2 - math.log(sd[i]) - 0.5 * LOG_2PI for i in range(3))


def sample_motion(rng, prev, u, sd):
    return compose(prev, [u[i] + sd[i] * rng.gauss(0.0, 1.0) for i in range(3)])


# ---------------------------------------------------------------- the grid


def new_grid(p):
    return [0.0] * (p.width * p.height)


def ray_cells(c0, c1):
    """Return the cells from c0 up to c1, c1 excluded, by Bresenham's line algorithm."""
    x0, y0 = c0
    x1, y1 = c1
    dx, dy = abs(x1 - x0), -abs(y1 - y0)
    sx = 1 if x0 < x1 else -1
    sy = 1 if y0 < y1 else -1
    err = dx + dy
    out = []
    while (x0, y0) != (x1, y1):
        out.append((x0, y0))
        e2 = 2 * err
        if e2 >= dy:
            err += dy
            x0 += sx
        if e2 <= dx:
            err += dx
            y0 += sy
    return out


def integrate_scan(grid, p, pose, ranges):
    """Add the scan to the log-odds grid: free cells along each beam, occupied at a hit."""
    res, w, h = p.res, p.width, p.height
    c0 = (int(pose[0] // res), int(pose[1] // res))
    for a, r in zip(p.angles, ranges):
        hit = r < p.max_range
        r = min(r, p.max_range)
        ex = pose[0] + r * math.cos(pose[2] + a)
        ey = pose[1] + r * math.sin(pose[2] + a)
        c1 = (int(ex // res), int(ey // res))
        for cx, cy in ray_cells(c0, c1):
            if 0 <= cx < w and 0 <= cy < h:
                i = cy * w + cx
                grid[i] = max(-p.l_max, grid[i] + p.l_free)
        if hit and 0 <= c1[0] < w and 0 <= c1[1] < h:
            i = c1[1] * w + c1[0]
            grid[i] = min(p.l_max, grid[i] + p.l_occ)


def scan_loglik(grid, p, pose, ranges):
    """Return (log likelihood, matched beams) of the scan at pose, by an endpoint model.

    Each hit endpoint scores -d^2 / (2 sigma^2), where d is the distance to the
    center of the nearest occupied cell within `search` cells, or a cap if
    there is none. Constants that are the same for every pose are dropped.
    """
    res, w, h, s = p.res, p.width, p.height, p.search
    cap2 = ((s + 0.5) * res) ** 2
    inv = 0.5 / (p.sigma_hit * p.sigma_hit)
    x, y, th = pose
    total, matched = 0.0, 0
    for a, r in zip(p.angles, ranges):
        if r >= p.max_range:
            continue
        ex = x + r * math.cos(th + a)
        ey = y + r * math.sin(th + a)
        cx, cy = int(ex // res), int(ey // res)
        best = cap2
        for yy in range(cy - s, cy + s + 1):
            if not 0 <= yy < h:
                continue
            row = yy * w
            ddy = (yy + 0.5) * res - ey
            for xx in range(cx - s, cx + s + 1):
                if 0 <= xx < w and grid[row + xx] > 0.0:
                    ddx = (xx + 0.5) * res - ex
                    d2 = ddx * ddx + ddy * ddy
                    if d2 < best:
                        best = d2
        if best < cap2:
            matched += 1
        total -= best * inv
    return total, matched


def scan_match(grid, p, start, ranges):
    """Hill climbing on scan_loglik from start, halving the steps match_levels times."""
    best = list(start)
    score = scan_loglik(grid, p, best, ranges)[0]
    step = list(p.match_step)
    for _ in range(p.match_levels):
        improved = True
        while improved:
            improved = False
            for k in range(3):
                for sign in (1.0, -1.0):
                    cand = list(best)
                    cand[k] += sign * step[k]
                    cand[2] = robest.wrap_angle(cand[2])
                    s = scan_loglik(grid, p, cand, ranges)[0]
                    if s > score:
                        best, score, improved = cand, s, True
        step = [v / 2.0 for v in step]
    return best, score


def log_sum_exp(values):
    top = max(values)
    return top + math.log(sum(math.exp(v - top) for v in values))


def gaussian_from_points(points, logw, center):
    """Fit a Gaussian to weighted poses: return (mean, cov, log of the sum of weights).

    The angle is averaged as an offset from center, so the poses must lie
    near it. A floor of 1e-8 on the diagonal keeps the covariance positive.
    """
    log_eta = log_sum_exp(logw)
    wts = [math.exp(v - log_eta) for v in logw]
    offs = [[q[0] - center[0], q[1] - center[1], robest.wrap_angle(q[2] - center[2])] for q in points]
    m = [sum(wt * o[i] for wt, o in zip(wts, offs)) for i in range(3)]
    cov = [[sum(wt * (o[i] - m[i]) * (o[j] - m[j]) for wt, o in zip(wts, offs)) for j in range(3)] for i in range(3)]
    for i in range(3):
        cov[i][i] += 1e-8
    mean = [center[0] + m[0], center[1] + m[1], robest.wrap_angle(center[2] + m[2])]
    return mean, cov, log_eta


def improved_proposal(rng, grid, p, prev, u, ranges):
    """Draw the new pose of one particle. Return (pose, log weight factor)."""
    guess = compose(prev, u)  # @line L2
    best, _ = scan_match(grid, p, guess, ranges)  # @line L3
    hits = sum(1 for r in ranges if r < p.max_range)
    if scan_loglik(grid, p, best, ranges)[1] < p.min_match * hits:  # @line L4
        x = sample_motion(rng, prev, u, p.motion_sd)
        return x, scan_loglik(grid, p, x, ranges)[0]
    points, logt = [], []
    for _ in range(p.k_points):  # @line L5
        q = [best[i] + (2.0 * rng.random() - 1.0) * p.delta[i] for i in range(3)]
        q[2] = robest.wrap_angle(q[2])
        points.append(q)
        logt.append(scan_loglik(grid, p, q, ranges)[0] + motion_logpdf(prev, q, u, p.motion_sd))
    mean, cov, log_eta = gaussian_from_points(points, logt, best)
    volume = 8.0 * p.delta[0] * p.delta[1] * p.delta[2]
    x = robest.gauss_sample(rng, mean, cov)  # @line L6
    x[2] = robest.wrap_angle(x[2])
    return x, log_eta + math.log(volume / p.k_points)


# ---------------------------------------------------------------- the filter


class Particle:
    __slots__ = ("pose", "grid", "logw")

    def __init__(self, pose, grid, logw):
        self.pose, self.grid, self.logw = pose, grid, logw


def initial_particles(n, pose, ranges, p):
    """n particles at a known start pose, each with the first scan in its grid."""
    out = []
    for _ in range(n):
        g = new_grid(p)
        integrate_scan(g, p, pose, ranges)
        out.append(Particle(list(pose), g, -math.log(n)))
    return out


def n_eff(logws):
    """Return 1 / sum(w^2) of the normalized weights."""
    top = log_sum_exp(logws)
    return 1.0 / sum(math.exp(2.0 * (v - top)) for v in logws)


def prior_proposal(rng, grid, p, prev, u, ranges):
    """The plain proposal, for comparison: draw from the motion model, weight by the scan."""
    x = sample_motion(rng, prev, u, p.motion_sd)
    return x, scan_loglik(grid, p, x, ranges)[0]


def grid_rbpf_step(particles, u, ranges, rng, p, improved=True):
    """One step with the odometry step u and a scan. Return (particles, resampled)."""
    propose = improved_proposal if improved else prior_proposal
    for q in particles:  # @line L1
        q.pose, factor = propose(rng, q.grid, p, q.pose, u, ranges)
        q.logw += factor
        integrate_scan(q.grid, p, q.pose, ranges)  # @line L7
    top = log_sum_exp([q.logw for q in particles])
    for q in particles:
        q.logw -= top
    n = len(particles)
    if n_eff([q.logw for q in particles]) >= n / 2.0:  # @line L8
        return particles, False
    idx = robest.low_variance_resample(rng, [math.exp(q.logw) for q in particles])
    return [Particle(list(particles[i].pose), list(particles[i].grid), -math.log(n)) for i in idx], True  # @line L9


def best_particle(particles):
    return max(particles, key=lambda q: q.logw)


# ---------------------------------------------------------------- a simulated room


class World:
    """A rectangular room with walls on the border cells and one box inside."""

    def __init__(self, p, box=(26, 16, 34, 24)):
        self.p = p
        self.occ = [False] * (p.width * p.height)
        for cy in range(p.height):
            for cx in range(p.width):
                border = cx in (0, p.width - 1) or cy in (0, p.height - 1)
                inside = box[0] <= cx < box[2] and box[1] <= cy < box[3]
                if border or inside:
                    self.occ[cy * p.width + cx] = True

    def occupied(self, cx, cy):
        p = self.p
        return not (0 <= cx < p.width and 0 <= cy < p.height) or self.occ[cy * p.width + cx]

    def scan(self, pose, rng=None, sd=0.0):
        """Ray cast each beam in steps of a quarter cell; add N(0, sd^2) noise to hits."""
        p = self.p
        step = p.res / 4.0
        out = []
        for a in p.angles:
            c, s = math.cos(pose[2] + a), math.sin(pose[2] + a)
            r = 0.0
            while r < p.max_range:
                if self.occupied(int((pose[0] + r * c) // p.res), int((pose[1] + r * s) // p.res)):
                    break
                r += step
            if r < p.max_range and rng is not None:
                r = max(0.0, r + sd * rng.gauss(0.0, 1.0))
            out.append(min(r, p.max_range))
        return out
rbm.py 482 lines
# SPDX-License-Identifier: MIT
# Shared helper of the robotics pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small linear algebra, rotations, poses and quaternions for the robotics pages.

Conventions (Lynch and Park, Modern Robotics, 2017):
- A matrix is a list of rows. A vector is a flat list.
- hat3(w) is the skew-symmetric matrix [w], so that [w] x = w x x.
- A twist or screw is a 6-vector (omega, v), angular part first.
  hat6(V) is the 4x4 matrix [[[omega], v], [0, 0]].
- A pose T is the 4x4 matrix [[R, p], [0, 1]].
- so3_exp and so3_log use exponential coordinates w = omega_hat * theta,
  with theta = |w| in [0, pi] for so3_log.
- se3_exp and se3_log use 6-vectors (w, v) = S * theta.
- Quaternions are Hamilton, scalar first: q = (w, x, y, z), with i j = k.
- Angles are in radians.

The helper holds no algorithm of a robotics page except the four maps
so3_exp, so3_log, se3_exp and se3_log. The pages so3-logarithm-map and
se3-exponential-map hold their own complete versions with comments.
"""

import math

# Below this angle, the coefficient functions of the exponential and the
# logarithm are evaluated by their Taylor series. The first omitted term
# of each series is of order theta^6 and is below 3e-16 for theta < 1e-2;
# it also multiplies [w] or [w]^2, which are small. Above the threshold,
# the closed forms such as (1 - cos(theta)) / theta^2 lose at most about
# 1e-16 / theta^2 to cancellation, which [w] or [w]^2 brings to 1e-14.
SERIES_THETA = 1e-2

# Above pi - NEAR_PI, so3_log takes the axis from the symmetric part of R
# (which is (R + I) / 2 at theta = pi) and not from the skew part.
NEAR_PI = 1e-2

# A pivot whose magnitude is at most PIVOT_TOL times the largest entry of
# the matrix makes solve, inv and pinv_right raise ValueError.
PIVOT_TOL = 1e-12


# ---------------------------------------------------------------- matrices


def zeros(n, m):
    """Return the n by m zero matrix."""
    return [[0.0] * m for _ in range(n)]


def eye(n):
    """Return the n by n identity matrix."""
    return [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]


def _is_matrix(a):
    return len(a) > 0 and isinstance(a[0], list)


def add(a, b):
    """Return a + b for two vectors or two matrices of the same shape."""
    if _is_matrix(a):
        return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
    return [x + y for x, y in zip(a, b)]


def sub(a, b):
    """Return a - b for two vectors or two matrices of the same shape."""
    if _is_matrix(a):
        return [[x - y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
    return [x - y for x, y in zip(a, b)]


def scale(a, s):
    """Return s * a for a vector or a matrix a and a number s."""
    if _is_matrix(a):
        return [[s * x for x in row] for row in a]
    return [s * x for x in a]


def transpose(a):
    """Return the transpose of the matrix a."""
    return [list(col) for col in zip(*a)]


def mul(a, b):
    """Return the matrix product a b."""
    bt = transpose(b)
    return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]


def matvec(a, x):
    """Return the product of the matrix a and the vector x."""
    return [sum(p * q for p, q in zip(row, x)) for row in a]


def dot(x, y):
    """Return the dot product of two vectors."""
    return sum(p * q for p, q in zip(x, y))


def norm(x):
    """Return the Euclidean norm of a vector."""
    return math.sqrt(dot(x, x))


def cross(a, b):
    """Return the cross product a x b of two 3-vectors."""
    return [
        a[1] * b[2] - a[2] * b[1],
        a[2] * b[0] - a[0] * b[2],
        a[0] * b[1] - a[1] * b[0],
    ]


def _max_abs(a):
    return max((abs(x) for row in a for x in row), default=0.0)


def solve(a, b):
    """Solve a x = b by Gaussian elimination with partial pivoting.

    a is a square matrix. b is a vector or a matrix with one column per
    right-hand side; the result has the same shape as b. Raise ValueError
    if a pivot is at most PIVOT_TOL times the largest entry of a.
    """
    n = len(a)
    vec = not _is_matrix(b)
    rhs = [[x] for x in b] if vec else [list(row) for row in b]
    m = [list(map(float, row)) + list(map(float, r)) for row, r in zip(a, rhs)]
    k = len(rhs[0]) if rhs else 0
    tol = PIVOT_TOL * _max_abs(a)
    for c in range(n):
        piv = max(range(c, n), key=lambda r: abs(m[r][c]))
        if abs(m[piv][c]) <= tol or m[piv][c] == 0.0:
            raise ValueError("matrix is singular to working precision")
        m[c], m[piv] = m[piv], m[c]
        for r in range(c + 1, n):
            f = m[r][c] / m[c][c]
            if f != 0.0:
                row_r, row_c = m[r], m[c]
                for j in range(c, n + k):
                    row_r[j] -= f * row_c[j]
    x = [[0.0] * k for _ in range(n)]
    for r in range(n - 1, -1, -1):
        for j in range(k):
            s = m[r][n + j] - sum(m[r][i] * x[i][j] for i in range(r + 1, n))
            x[r][j] = s / m[r][r]
    return [row[0] for row in x] if vec else x


def inv(a):
    """Return the inverse of the square matrix a (see solve for errors)."""
    return solve(a, eye(len(a)))


def det(a):
    """Return the determinant of the square matrix a by elimination."""
    n = len(a)
    m = [list(map(float, row)) for row in a]
    d = 1.0
    for c in range(n):
        piv = max(range(c, n), key=lambda r: abs(m[r][c]))
        if m[piv][c] == 0.0:
            return 0.0
        if piv != c:
            m[c], m[piv] = m[piv], m[c]
            d = -d
        d *= m[c][c]
        for r in range(c + 1, n):
            f = m[r][c] / m[c][c]
            for j in range(c, n):
                m[r][j] -= f * m[c][j]
    return d


def cholesky(a):
    """Return the lower triangular L with a = L L^T.

    a must be symmetric positive definite. Raise ValueError if a diagonal
    entry of the factor is not positive.
    """
    n = len(a)
    low = zeros(n, n)
    for i in range(n):
        for j in range(i + 1):
            s = a[i][j] - sum(low[i][k] * low[j][k] for k in range(j))
            if i == j:
                if s <= 0.0:
                    raise ValueError("matrix is not positive definite")
                low[i][i] = math.sqrt(s)
            else:
                low[i][j] = s / low[j][j]
    return low


def pinv_right(j):
    """Return the right pseudoinverse J^T (J J^T)^(-1) of a J with full row rank."""
    jt = transpose(j)
    return mul(jt, inv(mul(j, jt)))


# ---------------------------------------------------------------- hat and vee


def hat3(w):
    """Return the 3x3 skew-symmetric matrix [w] of a 3-vector w."""
    return [
        [0.0, -w[2], w[1]],
        [w[2], 0.0, -w[0]],
        [-w[1], w[0], 0.0],
    ]


def vee3(m):
    """Return the 3-vector w of a skew-symmetric matrix m = [w]."""
    return [m[2][1], m[0][2], m[1][0]]


def hat6(v):
    """Return the 4x4 matrix [V] = [[[omega], v], [0, 0]] of V = (omega, v)."""
    w = hat3(v[:3])
    return [
        [w[0][0], w[0][1], w[0][2], v[3]],
        [w[1][0], w[1][1], w[1][2], v[4]],
        [w[2][0], w[2][1], w[2][2], v[5]],
        [0.0, 0.0, 0.0, 0.0],
    ]


def vee6(m):
    """Return the 6-vector (omega, v) of a 4x4 matrix [V]."""
    return [m[2][1], m[0][2], m[1][0], m[0][3], m[1][3], m[2][3]]


# ---------------------------------------------------------------- rotations


def rot_x(a):
    """Return the rotation by a radians about the x axis."""
    c, s = math.cos(a), math.sin(a)
    return [[1.0, 0.0, 0.0], [0.0, c, -s], [0.0, s, c]]


def rot_y(a):
    """Return the rotation by a radians about the y axis."""
    c, s = math.cos(a), math.sin(a)
    return [[c, 0.0, s], [0.0, 1.0, 0.0], [-s, 0.0, c]]


def rot_z(a):
    """Return the rotation by a radians about the z axis."""
    c, s = math.cos(a), math.sin(a)
    return [[c, -s, 0.0], [s, c, 0.0], [0.0, 0.0, 1.0]]


def rpy(roll, pitch, yaw):
    """Return R = Rz(yaw) Ry(pitch) Rx(roll)."""
    return mul(rot_z(yaw), mul(rot_y(pitch), rot_x(roll)))


def so3_exp(w):
    """Return exp([w]) for exponential coordinates w = omega_hat * theta.

    Rodrigues' formula in the form I + A [w] + B [w]^2 with
    A = sin(theta) / theta and B = (1 - cos(theta)) / theta^2.
    """
    t = norm(w)
    if t < SERIES_THETA:
        t2 = t * t
        a = 1.0 - t2 / 6.0 + t2 * t2 / 120.0
        b = 0.5 - t2 / 24.0 + t2 * t2 / 720.0
    else:
        a = math.sin(t) / t
        b = (1.0 - math.cos(t)) / (t * t)
    k = hat3(w)
    k2 = mul(k, k)
    return [[(1.0 if i == j else 0.0) + a * k[i][j] + b * k2[i][j] for j in range(3)] for i in range(3)]


def so3_log(r):
    """Return w = omega_hat * theta with exp([w]) = r and theta in [0, pi].

    theta = atan2(|s|, c), where c = (trace(r) - 1) / 2 = cos(theta) and
    s = vee(r - r^T) / 2 = sin(theta) omega_hat. For theta below
    SERIES_THETA, w = s (1 + theta^2 / 6 + 7 theta^4 / 360). For theta
    above pi - NEAR_PI, the axis comes from the symmetric part
    ((r + r^T) / 2 - c I) / (1 - c) = omega_hat omega_hat^T, and its sign
    from s. At theta = pi both signs are valid; the sign is then chosen so
    that the largest component of the axis is positive.
    """
    c = (r[0][0] + r[1][1] + r[2][2] - 1.0) / 2.0
    c = max(-1.0, min(1.0, c))
    s = [(r[2][1] - r[1][2]) / 2.0, (r[0][2] - r[2][0]) / 2.0, (r[1][0] - r[0][1]) / 2.0]
    sn = norm(s)
    t = math.atan2(sn, c)
    if t < SERIES_THETA:
        t2 = t * t
        f = 1.0 + t2 / 6.0 + 7.0 * t2 * t2 / 360.0
        return [f * x for x in s]
    if t <= math.pi - NEAR_PI:
        return [t / sn * x for x in s]
    b = [[(r[i][j] + r[j][i]) / 2.0 - (c if i == j else 0.0) for j in range(3)] for i in range(3)]
    # b = (1 - c) omega_hat omega_hat^T. Its column k with the largest
    # diagonal entry is (1 - c) omega_k omega_hat, with omega_k^2 >= 1/3.
    k = max(range(3), key=lambda i: b[i][i])
    col = [b[i][k] for i in range(3)]
    axis = [x / norm(col) for x in col]
    if dot(axis, s) < 0.0 or (dot(axis, s) == 0.0 and axis[k] < 0.0):
        axis = [-x for x in axis]
    return [t * x for x in axis]


# ---------------------------------------------------------------- poses


def make_T(r, p):
    """Return the 4x4 pose [[r, p], [0, 1]]."""
    return [
        [r[0][0], r[0][1], r[0][2], p[0]],
        [r[1][0], r[1][1], r[1][2], p[1]],
        [r[2][0], r[2][1], r[2][2], p[2]],
        [0.0, 0.0, 0.0, 1.0],
    ]


def _rp(t):
    return [row[:3] for row in t[:3]], [t[0][3], t[1][3], t[2][3]]


def T_inv(t):
    """Return the inverse [[R^T, -R^T p], [0, 1]] of a pose t."""
    r, p = _rp(t)
    rt = transpose(r)
    return make_T(rt, [-x for x in matvec(rt, p)])


def T_apply(t, x):
    """Return R x + p, the image of the point x under the pose t."""
    r, p = _rp(t)
    return add(matvec(r, x), p)


def se3_exp(xi):
    """Return exp([xi]) for a 6-vector xi = (w, v) = S * theta.

    The rotation is so3_exp(w). The translation is G v with
    G = I + B [w] + C [w]^2, B = (1 - cos(theta)) / theta^2 and
    C = (theta - sin(theta)) / theta^3, theta = |w|. For w = 0 this is a
    translation by v.
    """
    w, v = xi[:3], xi[3:]
    t = norm(w)
    if t < SERIES_THETA:
        t2 = t * t
        b = 0.5 - t2 / 24.0 + t2 * t2 / 720.0
        c = 1.0 / 6.0 - t2 / 120.0 + t2 * t2 / 5040.0
    else:
        b = (1.0 - math.cos(t)) / (t * t)
        c = (t - math.sin(t)) / (t * t * t)
    k = hat3(w)
    k2 = mul(k, k)
    g = [[(1.0 if i == j else 0.0) + b * k[i][j] + c * k2[i][j] for j in range(3)] for i in range(3)]
    return make_T(so3_exp(w), matvec(g, v))


def se3_log(t):
    """Return the 6-vector xi = (w, v) with se3_exp(xi) = t and |w| in [0, pi].

    w = so3_log(R) and v = G^(-1) p with
    G^(-1) = I - [w] / 2 + D [w]^2, D = (1 - (theta / 2) cot(theta / 2)) / theta^2.
    """
    r, p = _rp(t)
    w = so3_log(r)
    th = norm(w)
    if th < SERIES_THETA:
        t2 = th * th
        d = 1.0 / 12.0 + t2 / 720.0 + t2 * t2 / 30240.0
    else:
        half = th / 2.0
        d = (1.0 - half * math.cos(half) / math.sin(half)) / (th * th)
    k = hat3(w)
    k2 = mul(k, k)
    gi = [[(1.0 if i == j else 0.0) - 0.5 * k[i][j] + d * k2[i][j] for j in range(3)] for i in range(3)]
    return w + matvec(gi, p)


def adjoint(t):
    """Return the 6x6 adjoint [[R, 0], [[p] R, R]] of a pose t."""
    r, p = _rp(t)
    pr = mul(hat3(p), r)
    out = zeros(6, 6)
    for i in range(3):
        for j in range(3):
            out[i][j] = r[i][j]
            out[i + 3][j + 3] = r[i][j]
            out[i + 3][j] = pr[i][j]
    return out


# ---------------------------------------------------------------- quaternions


def quat_mul(q, r):
    """Return the Hamilton product q r of quaternions (w, x, y, z)."""
    a1, b1, c1, d1 = q
    a2, b2, c2, d2 = r
    return [
        a1 * a2 - b1 * b2 - c1 * c2 - d1 * d2,
        a1 * b2 + b1 * a2 + c1 * d2 - d1 * c2,
        a1 * c2 - b1 * d2 + c1 * a2 + d1 * b2,
        a1 * d2 + b1 * c2 - c1 * b2 + d1 * a2,
    ]


def quat_conj(q):
    """Return the conjugate (w, -x, -y, -z)."""
    return [q[0], -q[1], -q[2], -q[3]]


def quat_to_rot(q):
    """Return the rotation matrix of the quaternion q, so that (0, R v) = q (0, v) q*.

    q need not be of unit length; the result is the rotation of q / |q|.
    """
    w, x, y, z = q
    n = w * w + x * x + y * y + z * z
    s = 2.0 / n
    return [
        [1.0 - s * (y * y + z * z), s * (x * y - w * z), s * (x * z + w * y)],
        [s * (x * y + w * z), 1.0 - s * (x * x + z * z), s * (y * z - w * x)],
        [s * (x * z - w * y), s * (y * z + w * x), 1.0 - s * (x * x + y * y)],
    ]


def quat_from_axis_angle(axis, angle):
    """Return (cos(angle / 2), sin(angle / 2) axis / |axis|).

    A zero axis is allowed only with angle 0 (the identity); otherwise
    raise ValueError.
    """
    n = norm(axis)
    if n == 0.0:
        if angle == 0.0:
            return [1.0, 0.0, 0.0, 0.0]
        raise ValueError("zero axis with a nonzero angle")
    s = math.sin(angle / 2.0) / n
    return [math.cos(angle / 2.0), s * axis[0], s * axis[1], s * axis[2]]


# ---------------------------------------------------------------- derivatives


def num_jacobian(f, x, h=1e-6):
    """Return the Jacobian of f at x by central differences with step h.

    f maps a list of n numbers to a list of m numbers; the result is m by n.
    """
    cols = []
    for i in range(len(x)):
        xp = list(x)
        xm = list(x)
        xp[i] += h
        xm[i] -= h
        fp, fm = f(xp), f(xm)
        cols.append([(a - b) / (2.0 * h) for a, b in zip(fp, fm)])
    return transpose(cols)


# ---------------------------------------------------------------- self-test


def self_test():
    """Check the area check values; return True or raise AssertionError."""
    r = so3_exp([2.0 * math.pi / 3.0 / math.sqrt(3.0)] * 3)
    want = [[0.0, 0.0, 1.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]
    assert max(abs(r[i][j] - want[i][j]) for i in range(3) for j in range(3)) < 1e-12
    w = so3_log(want)
    assert abs(norm(w) - 2.0943951) < 1e-7
    assert max(abs(x - 2.0 * math.pi / 3.0 / math.sqrt(3.0)) for x in w) < 1e-12
    t = se3_exp([0.0, 0.0, math.pi / 2.0, math.pi / 2.0, 0.0, 0.0])
    want_t = make_T(rot_z(math.pi / 2.0), [1.0, 1.0, 0.0])
    assert max(abs(t[i][j] - want_t[i][j]) for i in range(4) for j in range(4)) < 1e-12
    return True
robest.py 149 lines
# SPDX-License-Identifier: MIT
# Shared helper of the robotics pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Small estimation helpers for the localization and SLAM pages.

Vectors are lists of floats and matrices are lists of rows, as in rbm.py.
The notation follows Thrun, Burgard and Fox, Probabilistic Robotics (2005).

  wrap_angle(a)                       a wrapped to [-pi, pi)
  gauss_sample(rng, mean, cov)        one draw of N(mean, cov), by a Cholesky factor
  gauss_pdf(x, mean, cov)             the density of N(mean, cov) at x
  mahalanobis2(x, mean, cov)          (x - mean)^T cov^(-1) (x - mean)
  low_variance_resample(rng, w)       indices of a systematic (low variance) resample
  logodds(p), prob_from_logodds(l)    l = log(p / (1 - p)) and its inverse
  CHI2[(dof, level)]                  chi-square quantiles for gates, dof 1 to 3

gauss_pdf and mahalanobis2 also take plain numbers: then cov is a variance.
This module holds no filter, no SLAM back end and no planner.
"""

import math

import rbm

CHI2 = {
    (1, 0.95): 3.841,
    (1, 0.99): 6.635,
    (2, 0.95): 5.991,
    (2, 0.99): 9.210,
    (3, 0.95): 7.815,
    (3, 0.99): 11.345,
}

_TWO_PI = 2.0 * math.pi


def wrap_angle(a):
    """Return a + 2 pi k in [-pi, pi), with ((a + pi) mod 2 pi) - pi.

    An angle that is already in [-pi, pi) comes back unchanged, so that
    small angles keep all their digits.
    """
    if -math.pi <= a < math.pi:
        return float(a)
    w = math.fmod(a + math.pi, _TWO_PI)
    if w < 0.0:
        w += _TWO_PI
    w -= math.pi
    if w >= math.pi:  # rounding can give exactly pi
        w -= _TWO_PI
    return w


def _as_vector(x):
    if isinstance(x, (int, float)):
        return [float(x)], True
    return [float(v) for v in x], False


def _as_matrix(cov, scalar):
    if scalar:
        if isinstance(cov, (int, float)):
            return [[float(cov)]]
        return [[float(cov[0][0])]]
    return [[float(v) for v in row] for row in cov]


def gauss_sample(rng, mean, cov):
    """Draw x = mean + L z, with cov = L L^T and z standard normal.

    rng is a random.Random. cov must be symmetric positive definite.
    A number for mean (with a variance for cov) gives a number.
    """
    mu, scalar = _as_vector(mean)
    if scalar:
        var = float(cov) if isinstance(cov, (int, float)) else float(cov[0][0])
        if var < 0.0:
            raise ValueError("negative variance")
        return mu[0] + math.sqrt(var) * rng.gauss(0.0, 1.0)
    L = rbm.cholesky(_as_matrix(cov, False))
    z = [rng.gauss(0.0, 1.0) for _ in mu]
    return [mu[i] + sum(L[i][j] * z[j] for j in range(i + 1)) for i in range(len(mu))]


def mahalanobis2(x, mean, cov):
    """Return the squared Mahalanobis distance (x - mean)^T cov^(-1) (x - mean)."""
    xv, scalar = _as_vector(x)
    mv, _ = _as_vector(mean)
    if len(xv) != len(mv):
        raise ValueError("x and mean differ in size")
    d = [a - b for a, b in zip(xv, mv)]
    S = _as_matrix(cov, scalar)
    if len(d) == 1:
        return d[0] * d[0] / S[0][0]
    y = rbm.solve(S, d)
    return sum(a * b for a, b in zip(d, y))


def gauss_pdf(x, mean, cov):
    """Return the density of N(mean, cov) at x."""
    xv, scalar = _as_vector(x)
    S = _as_matrix(cov, scalar)
    k = len(xv)
    det = S[0][0] if k == 1 else rbm.det(S)
    if det <= 0.0:
        raise ValueError("covariance is not positive definite")
    m2 = mahalanobis2(xv, mean if not scalar else [mean], S)
    return math.exp(-0.5 * m2) / math.sqrt((_TWO_PI ** k) * det)


def low_variance_resample(rng, weights):
    """Return len(weights) indices drawn by the low variance sampler.

    This is systematic resampling (Thrun et al. 2005, Table 4.4): one
    uniform offset r in [0, 1/N), and the N points r + m / N select the
    indices through the cumulative weights. The weights need not sum to 1.
    """
    n = len(weights)
    if n == 0:
        return []
    total = float(sum(weights))
    if total <= 0.0 or any(w < 0.0 for w in weights):
        raise ValueError("weights must be nonnegative with a positive sum")
    r = rng.random() / n
    c = weights[0] / total
    i = 0
    out = []
    for m in range(n):
        u = r + m / n
        while u > c and i < n - 1:
            i += 1
            c += weights[i] / total
        out.append(i)
    return out


def logodds(p):
    """Return log(p / (1 - p)) for p in (0, 1)."""
    if not 0.0 < p < 1.0:
        raise ValueError("p must be in (0, 1)")
    return math.log(p / (1.0 - p))


def prob_from_logodds(l):
    """Return p = 1 - 1 / (1 + exp(l)), the inverse of logodds, without overflow."""
    if l >= 0.0:
        return 1.0 / (1.0 + math.exp(-l))
    e = math.exp(l)
    return e / (1.0 + e)
test_grid_based_rbpf_slam.py 173 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/grid-based-rbpf-slam/. The authors are listed in prov/X1GN8F.jsonl.

import math
import random

from grid_based_rbpf_slam import (
    Params,
    Particle,
    World,
    best_particle,
    compose,
    gaussian_from_points,
    grid_rbpf_step,
    improved_proposal,
    initial_particles,
    integrate_scan,
    log_sum_exp,
    motion_logpdf,
    n_eff,
    new_grid,
    ray_cells,
    relative,
    sample_motion,
    scan_loglik,
    scan_match,
)

P = Params()
WORLD = World(P)
U = [0.2, 0.0, 0.2 / 1.2]  # the odometry step: a circle of radius 1.2 m around the box


def test_ray_cells_and_one_beam():
    cells = ray_cells((0, 0), (5, 2))
    assert cells == [(0, 0), (1, 0), (2, 1), (3, 1), (4, 2)]
    p = Params(beams=1)
    grid = new_grid(p)
    integrate_scan(grid, p, [1.05, 1.05, 0.0], [0.5])
    assert grid[10 * p.width + 15] == p.l_occ  # the hit cell (15, 10)
    assert all(grid[10 * p.width + cx] == p.l_free for cx in range(10, 15))
    assert sum(1 for v in grid if v != 0.0) == 6


def test_compose_relative_and_motion_density():
    a, b = [1.0, 2.0, 0.7], [0.3, -0.1, 0.2]
    c = compose(a, b)
    assert max(abs(x - y) for x, y in zip(relative(a, c), b)) < 1e-12
    sd = P.motion_sd
    peak = sum(-math.log(s) - 0.5 * math.log(2.0 * math.pi) for s in sd)
    assert abs(motion_logpdf(a, compose(a, U), U, sd) - peak) < 1e-12
    rng = random.Random(3)
    draws = [relative(a, sample_motion(rng, a, U, sd)) for _ in range(3000)]
    for i in range(3):
        m = sum(d[i] for d in draws) / len(draws)
        v = sum((d[i] - m) ** 2 for d in draws) / len(draws)
        assert abs(m - U[i]) < 4.0 * sd[i] / math.sqrt(len(draws))
        assert abs(math.sqrt(v) / sd[i] - 1.0) < 0.06


def known_map(poses):
    grid = new_grid(P)
    for pose in poses:
        integrate_scan(grid, P, pose, WORLD.scan(pose))
    return grid


def test_scan_match_recovers_a_perturbed_pose():
    grid = [P.l_occ if occ else P.l_free for occ in WORLD.occ]  # the true map
    truth = [3.3, 0.9, 0.2]
    ranges = WORLD.scan(truth)
    for start in ([3.38, 0.84, 0.24], [3.24, 0.95, 0.17], [3.2, 1.0, 0.25]):
        found, score = scan_match(grid, P, start, ranges)
        assert math.hypot(found[0] - truth[0], found[1] - truth[1]) < 0.03
        assert abs(found[2] - truth[2]) < 0.02
        assert score >= scan_loglik(grid, P, start, ranges)[0]
        assert scan_loglik(grid, P, found, ranges)[1] == len(ranges)
    # hill climbing can stop at a local maximum: from this start it stops 5 cm off
    found, _ = scan_match(grid, P, [3.35, 0.86, 0.23], ranges)
    assert 0.03 < math.hypot(found[0] - truth[0], found[1] - truth[1]) < 0.1


def test_gaussian_from_points_page_example():
    pts = [[0.95, 0.0, 0.0], [1.0, 0.0, 0.0], [1.05, 0.0, 0.0]]
    mean, cov, log_eta = gaussian_from_points(pts, [0.0, math.log(2.0), 0.0], [1.0, 0.0, 0.0])
    assert abs(mean[0] - 1.0) < 1e-12 and abs(mean[1]) < 1e-12
    assert abs(cov[0][0] - (0.00125 + 1e-8)) < 1e-12 and abs(cov[1][1] - 1e-8) < 1e-15
    assert abs(log_eta - math.log(4.0)) < 1e-12


def test_the_weight_factor_estimates_the_integral_over_the_box():
    """With many points, the factor of line L6 matches a midpoint rule over the same box."""
    grid = known_map([[3.0, 0.8, 0.0], [4.2, 2.0, 1.57]])
    prev = [3.0, 0.8, 0.0]
    ranges = WORLD.scan(compose(prev, [0.21, 0.01, 0.18]))
    best, _ = scan_match(grid, P, compose(prev, U), ranges)
    p = Params(k_points=3000)
    _, log_factor = improved_proposal(random.Random(4), grid, p, prev, U, ranges)
    n = 14
    logs = []
    for i in range(n):
        for j in range(n):
            for k in range(n):
                q = [best[0] + P.delta[0] * (2.0 * (i + 0.5) / n - 1.0), best[1] + P.delta[1] * (2.0 * (j + 0.5) / n - 1.0), best[2] + P.delta[2] * (2.0 * (k + 0.5) / n - 1.0)]
                logs.append(scan_loglik(grid, P, q, ranges)[0] + motion_logpdf(prev, q, U, P.motion_sd))
    volume = 8.0 * P.delta[0] * P.delta[1] * P.delta[2]
    exact = log_sum_exp(logs) + math.log(volume / n**3)
    assert abs(log_factor - exact) < 0.05


def test_adaptive_resampling():
    rng = random.Random(5)
    grids = [new_grid(P) for _ in range(4)]
    even = [Particle([0.0, 0.0, 0.0], g, math.log(w)) for g, w in zip(grids, [0.5, 0.3, 0.1, 0.1])]
    assert abs(n_eff([q.logw for q in even]) - 1.0 / 0.36) < 1e-9
    # N_eff = 2.78 >= N/2 = 2: no resampling. With the weights 0.7, 0.1, 0.1, 0.1, N_eff = 1.92 < 2.
    skew = [Particle([0.0, 0.0, 0.0], g, math.log(w)) for g, w in zip(grids, [0.7, 0.1, 0.1, 0.1])]
    assert abs(n_eff([q.logw for q in skew]) - 1.0 / 0.52) < 1e-9
    zero = [10.0] * len(P.angles)
    kept, resampled = grid_rbpf_step(even, [0.0, 0.0, 0.0], zero, rng, P, improved=False)
    assert not resampled and kept is even
    out, resampled = grid_rbpf_step(skew, [0.0, 0.0, 0.0], zero, rng, P, improved=False)
    assert resampled and len(out) == 4
    assert all(abs(q.logw + math.log(4.0)) < 1e-12 for q in out)
    assert len({id(q.grid) for q in out}) == 4  # every copy owns its grid
    out[0].grid[0] = 99.0
    assert all(q.grid[0] != 99.0 for q in out[1:])


def run(seed, n, improved, steps=25, slip=0.015):
    """A loop around the box. The robot turns 0.015 rad per step more than the odometry says."""
    rng = random.Random(seed)
    truth = [3.0, 0.8, 0.0]
    odo = list(truth)
    ranges = WORLD.scan(truth, rng, 0.02)
    particles = initial_particles(n, truth, ranges, P)
    odo_grid = new_grid(P)
    integrate_scan(odo_grid, P, odo, ranges)
    for _ in range(steps):
        step = [U[0] + 0.02 * rng.gauss(0.0, 1.0), 0.01 * rng.gauss(0.0, 1.0), U[2] + slip + 0.01 * rng.gauss(0.0, 1.0)]
        truth = compose(truth, step)
        odo = compose(odo, U)
        ranges = WORLD.scan(truth, rng, 0.02)
        particles, _ = grid_rbpf_step(particles, U, ranges, rng, P, improved)
        integrate_scan(odo_grid, P, odo, ranges)
    w = [math.exp(q.logw) for q in particles]
    x = sum(wi * q.pose[0] for wi, q in zip(w, particles)) / sum(w)
    y = sum(wi * q.pose[1] for wi, q in zip(w, particles)) / sum(w)
    err = math.hypot(x - truth[0], y - truth[1])
    return err, math.hypot(odo[0] - truth[0], odo[1] - truth[1]), particles, odo_grid


def map_agreement(grid):
    """The share of occupied cells of the grid that are within one cell of a true wall."""
    occ = [i for i, v in enumerate(grid) if v > 0.0]
    good = sum(1 for i in occ if any(WORLD.occupied(i % P.width + dx, i // P.width + dy) for dx in (-1, 0, 1) for dy in (-1, 0, 1)))
    return good / len(occ)


def test_simulation_with_the_improved_proposal():
    """A measurement: 5 particles, 25 steps, 2 seeds."""
    for seed in range(2):
        err, odo_err, particles, odo_grid = run(seed, 5, True)
        assert err < 0.15
        assert odo_err > 0.4
        assert map_agreement(best_particle(particles).grid) > 0.9
        assert map_agreement(odo_grid) < 0.75


def test_the_motion_proposal_does_worse_with_5_particles():
    """A measurement: the same runs with the motion model as the proposal, 6 seeds."""
    errs = [run(seed, 5, False)[0] for seed in range(6)]
    assert sum(errs) / len(errs) > 0.1

History

Murphy (1999) used a Rao-Blackwellized particle filter to learn grid maps. FastSLAM (2002) used the same factorization for landmark maps, and FastSLAM 2.0 (2003) added a proposal that uses the readings. Grisetti, Stachniss and Burgard combined these ideas for grid maps: their 2007 paper in the IEEE Transactions on Robotics computes the proposal from a scan match and a set of sampled points, and resamples only when the effective sample size is below N/2N/2. Their implementation, released as GMapping, became one of the most used SLAM programs for 2D lasers.

References

  1. Giorgio Grisetti, Cyrill Stachniss and Wolfram Burgard, Improved techniques for grid mapping with Rao-Blackwellized particle filters, IEEE Transactions on Robotics 23(1), 2007, pages 34 to 46, the improved proposal from scan matching, the computation of the weights and the adaptive resampling
  2. Kevin Murphy, Bayesian map learning in dynamic environments, Advances in Neural Information Processing Systems 12 (NIPS), 1999, the use of a Rao-Blackwellized particle filter to learn a grid map
  3. Sebastian Thrun, Wolfram Burgard and Dieter Fox, Probabilistic Robotics, MIT Press, 2005, Chapter 13 (FastSLAM, including its grid-based version)

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