Algorithm Search⌘K

Algorithmadvanced

FastSLAM

Also called FastSLAM 1.0.

SLAM by a Rao-Blackwellized particle filter over robot paths, with one small EKF per landmark per particle, kept in a tree so that a step costs O(N log m).

Time
O(N k log m) step
Space
O(N m) extra
Where
N = the number of particles; k = the number of readings per step; m = the number of landmarks
Properties
randomizednot exactonlinerecursive
Origin
Michael Montemerlo, Sebastian Thrun, Daphne Koller, Ben Wegbreit, 2002

FastSLAM solves landmark SLAM with a particle filter. Each particle holds one guess of the robot path and, for that guess, one small extended Kalman filter for each landmark. It is the Rao-Blackwellized particle filter applied to landmark maps: the path is sampled, and the map is computed in closed form. Grid-based RBPF SLAM applies the same idea to occupancy grids from laser scans, where each particle holds a grid instead of landmark filters. Compared with EKF SLAM, which keeps one joint Gaussian over the pose and all mm landmarks and pays O(m2)O(m^2) per reading, FastSLAM keeps mm separate 2×22 \times 2 filters per particle. With the landmarks in a balanced tree, one step costs O(Nlog⁡m)O(N \log m) per reading for NN particles.

In plain words

If you knew exactly where the robot had been, mapping would be easy: each landmark could be located on its own, from the readings of that landmark only. FastSLAM uses this. It keeps many guesses of the robot path. For each guess it locates every landmark separately, with a small filter. Guesses whose maps agree well with the new readings get more weight. Bad guesses are dropped and good ones are copied. To make copies cheap, a copy shares the landmark filters of the original and only makes new ones when a landmark changes.

The problem

The robot moves with known controls utu_t and noisy motion. It reads the range and bearing zz of point landmarks m1,…,mmm_1, \dots, m_m in the plane. In the basic version each reading comes with the id of its landmark (known correspondences). FastSLAM estimates the path posterior and the map, p(x1:t,m∣z1:t,u1:t)p(x_{1:t}, m \mid z_{1:t}, u_{1:t}), which is the full SLAM posterior, with a cost per step that does not grow with the length of the path. The code uses the velocity motion model and the landmark measurement model.

The algorithm

  1. FASTSLAM_1(particles {(x^i, tree^i, w^i)} for i = 1..N, u_t, z_t with landmark ids)
  2. 1for i ← 1 to N do
  3. 2draw x^i ~ p(x_t | x^i, u_t) ▷ sample the motion model
  4. 3for each reading z of landmark j do
  5. 4if j is not in tree^i then insert (μ ← h⁻¹(x^i, z), Σ ← H⁻¹ Q H⁻ᵀ); w^i ← w^i · p0; continue
  6. 5ẑ ← h(x^i, μ_j); H ← ∂h/∂m at μ_j; S ← H Σ_j Hᵀ + Q
  7. 6K ← Σ_j Hᵀ S⁻¹; μ_j ← μ_j + K (z - ẑ); Σ_j ← (I - K H) Σ_j ▷ a new tree path
  8. 7w^i ← w^i · N(z; ẑ, S)
  9. 8resample N particles in proportion to w^i; a copy shares the tree of its source
  10. 9return the particles, each with weight 1/N

Each landmark belief is a mean μj\mu_j and a 2×22 \times 2 covariance Σj\Sigma_j. Line L6 writes the new belief into the tree of the particle by copying the path from the root to its leaf, so other particles that share the tree are not affected. p0p_0 is the weight factor of a new landmark; with known correspondences every particle sees the new landmark at the same step, so p0p_0 cancels.

The tree. The landmarks of a particle are the leaves of a complete binary tree indexed by the landmark id. A lookup follows log⁡2m\log_2 m links. A change makes new copies of the log⁡2m\log_2 m nodes on the path to the leaf and shares all other nodes with the old tree, as in a persistent binary search tree. Resampling copies a particle by copying the pointer to its root. Without the tree, each copy would copy mm filters.

Example

The robot is at pose (0,0,0)(0, 0, 0) and reads a new landmark at range 2 and bearing 0.5, with Q=diag(0.01,0.0009)Q = \mathrm{diag}(0.01, 0.0009). Line L4 places it at (2cos⁡0.5,2sin⁡0.5)=(1.7552,0.9589)(2 \cos 0.5, 2 \sin 0.5) = (1.7552, 0.9589) with

Σ=H−1QH−⊤=(0.0085290.0026930.0026930.005071).\Sigma = H^{-1} Q H^{-\top} = \begin{pmatrix} 0.008529 & 0.002693 \\ 0.002693 & 0.005071 \end{pmatrix}.

At the next step, three particles have sampled three poses, and each gets the same reading (2,0.5)(2, 0.5) of this landmark:

  • At pose (0,0,0)(0, 0, 0), z^=(2,0.5)\hat z = (2, 0.5), so the innovation is zero. Here S=2QS = 2Q, the mean does not move and Σ\Sigma halves, as two equal readings should give. The weight factor is 1/(2πdet⁡2Q)=26.531 / (2 \pi \sqrt{\det 2Q}) = 26.53.
  • At pose (0,0,0.05)(0, 0, 0.05), z^=(2.0,0.45)\hat z = (2.0, 0.45). The bearing is off by 0.05, and the weight factor is 26.53⋅exp⁡(−0.5⋅0.052/0.0018)=13.2526.53 \cdot \exp(-0.5 \cdot 0.05^2 / 0.0018) = 13.25.
  • At pose (0.3,0,0)(0.3, 0, 0), z^=(1.7427,0.5826)\hat z = (1.7427, 0.5826). Both parts are off, and the weight factor is 1.067.

After normalization, the three particles have weights 0.65, 0.32 and 0.03, and resampling will most likely drop the third. Each particle has its own landmark mean: the third moves the landmark to (1.914,0.962)(1.914, 0.962), to fit its wrong pose. The test file checks these numbers.

Correctness

Given the whole path, the readings of different landmarks are independent, so the map posterior factors into one posterior per landmark: p(x1:t,m∣z1:t,u1:t)=p(x1:t∣z1:t,u1:t)∏jp(mj∣x1:t,z1:t)p(x_{1:t}, m \mid z_{1:t}, u_{1:t}) = p(x_{1:t} \mid z_{1:t}, u_{1:t}) \prod_j p(m_j \mid x_{1:t}, z_{1:t}). This is a theorem, and it needs the whole path: given only the current pose, the landmarks are correlated. Lines L2 to L7 are then the RBPF step with the motion model as the proposal. The EKF of each landmark is exact when the measurement model is linear in the landmark, and the weight of line L7 is the predictive density of the reading under the linearized model. The correctness proof gives the details, the case of a new landmark and the cost of the tree. The tests check that with a known pose each landmark follows an independent EKF, that the weight is the innovation density, and that the tree keeps old versions intact.

Proof: The FastSLAM factorization, the weights and the cost of the landmark treefull

Setting. The robot path is x1:tx_{1:t}, the map is m=(m1,…,mM)m = (m_1, \dots, m_M) with MM landmarks (the page calls this count mm), the controls are u1:tu_{1:t}, and the readings z1:tz_{1:t} come with known correspondences c1:tc_{1:t}: reading zkz_k is of landmark mckm_{c_k}. The model has three parts. The motion model is p(xk∣xk−1,uk)p(x_k \mid x_{k-1}, u_k). The measurement model is p(zk∣xk,mck)p(z_k \mid x_k, m_{c_k}), which depends on one landmark only. The prior over the landmarks is p(m)=∏jp(mj)p(m) = \prod_j p(m_j).

Claim. (1) The posterior factors as p(x1:t,m∣z1:t,u1:t,c1:t)=p(x1:t∣z1:t,u1:t,c1:t)∏jp(mj∣x1:t,z1:t,c1:t)p(x_{1:t}, m \mid z_{1:t}, u_{1:t}, c_{1:t}) = p(x_{1:t} \mid z_{1:t}, u_{1:t}, c_{1:t}) \prod_j p(m_j \mid x_{1:t}, z_{1:t}, c_{1:t}). (2) Lines L2 to L7 are the RBPF step for this factorization, with the path as the sampled part, the motion model as the proposal and one EKF per landmark; in the linear Gaussian case the per landmark filters and the weights are exact. (3) The tree gives each particle its own landmarks at a cost of O(log⁡M)O(\log M) per update and O(1)O(1) per copy.

(1) The factorization

Fix the path x1:tx_{1:t}. The readings are conditionally independent given the path and the map, so by Bayes' rule

p(m∣x1:t,z1:t,c1:t)∝p(m)∏k=1tp(zk∣xk,mck)=∏j[p(mj)∏k:ck=jp(zk∣xk,mj)].p(m \mid x_{1:t}, z_{1:t}, c_{1:t}) \propto p(m) \prod_{k=1}^{t} p(z_k \mid x_k, m_{c_k}) = \prod_j \Big[ p(m_j) \prod_{k : c_k = j} p(z_k \mid x_k, m_j) \Big].

The controls do not enter, because given the path they carry no information about the map. The right side is a product of functions of one landmark each, so after normalization the landmarks are independent given the path, and the factor of mjm_j is p(mj∣x1:t,z1:t,c1:t)p(m_j \mid x_{1:t}, z_{1:t}, c_{1:t}). The chain rule p(x1:t,m∣⋅)=p(x1:t∣⋅) p(m∣x1:t,⋅)p(x_{1:t}, m \mid \cdot) = p(x_{1:t} \mid \cdot) \, p(m \mid x_{1:t}, \cdot) gives the claim. This is the observation of Montemerlo, Thrun, Koller and Wegbreit (2002). It needs the whole path: given only the current pose xtx_t, the landmarks are correlated through the unknown past poses.

(2) The filter step

The target of the sampling is p(x1:t∣z1:t,u1:t,c1:t)p(x_{1:t} \mid z_{1:t}, u_{1:t}, c_{1:t}). By Bayes' rule and the Markov property,

p(x1:t∣z1:t,u1:t)∝p(zt∣x1:t,z1:t−1) p(xt∣xt−1,ut) p(x1:t−1∣z1:t−1,u1:t−1).p(x_{1:t} \mid z_{1:t}, u_{1:t}) \propto p(z_t \mid x_{1:t}, z_{1:t-1}) \, p(x_t \mid x_{t-1}, u_t) \, p(x_{1:t-1} \mid z_{1:t-1}, u_{1:t-1}).

Line L2 draws xtx_t from the motion model, which is the proposal. The importance weight of the extended path is then the old weight times p(zt∣x1:t,z1:t−1)p(z_t \mid x_{1:t}, z_{1:t-1}). For one reading of landmark jj,

p(zt∣x1:t,z1:t−1)=∫p(zt∣xt,mj) p(mj∣x1:t−1,z1:t−1) dmj.p(z_t \mid x_{1:t}, z_{1:t-1}) = \int p(z_t \mid x_t, m_j) \, p(m_j \mid x_{1:t-1}, z_{1:t-1}) \, dm_j.

The second factor is the belief that the particle stores for mjm_j, N(μj,Σj)N(\mu_j, \Sigma_j). With the measurement model linearized at μj\mu_j, zt≈h(xt,μj)+H(mj−μj)+vz_t \approx h(x_t, \mu_j) + H (m_j - \mu_j) + v with v∼N(0,Q)v \sim N(0, Q), so the integral is N(zt;z^,S)N(z_t; \hat z, S) with z^=h(xt,μj)\hat z = h(x_t, \mu_j) and S=HΣjH⊤+QS = H \Sigma_j H^\top + Q. Line L7 multiplies the weight by this density. For a model that is linear in mjm_j with Gaussian noise, the formula is exact.

Lines L5 and L6 are the EKF update of mjm_j with the reading, the closed form part of the RBPF; they are exact for a model linear in mjm_j. Landmarks that are not read keep their belief, which is correct because by (1) a reading of mjm_j carries no information about another landmark once the path is fixed. With several readings in one step, the same argument applies to each in turn, because the readings are independent given the path and the map, and they concern different landmarks or update the same one in sequence.

A new landmark (line L4). With a flat prior on mjm_j, the integral above is not a proper density. Line L4 sets the belief from the inverse of the linearized model, μj=h−1(xt,zt)\mu_j = h^{-1}(x_t, z_t) and Σj=H−1QH−⊤\Sigma_j = H^{-1} Q H^{-\top}, which is the posterior of the linearized model under the flat prior. It multiplies the weight by a constant p0p_0. When all particles see the same new landmark, as with known correspondences, the constant cancels at normalization.

A check. If a particle reads a landmark a second time from the same pose with the same value, then Σj=H−1QH−⊤\Sigma_j = H^{-1} Q H^{-\top} gives S=2QS = 2Q and K=ΣjH⊤S−1=12H−1K = \Sigma_j H^\top S^{-1} = \tfrac12 H^{-1}. So the mean does not move and Σj\Sigma_j halves, as two equal independent readings should give. The tests check this.

Resampling (line L8). Drawing NN particles with probabilities proportional to the weights keeps the represented distribution, as in every particle filter. Each copy needs its own path sample and its own landmark beliefs. FastSLAM keeps only the current pose of each path, since neither the weights nor the landmark updates use the older poses.

(3) The persistent tree

The landmarks of a particle are the leaves of a complete binary tree of depth d=⌈log⁡2M⌉d = \lceil \log_2 M \rceil, indexed by the landmark id. A node is never changed after it is made.

  • get follows the bits of the id from the root, dd steps.
  • set makes a new leaf and a new copy of each of the dd nodes on the path from the root, each pointing to the new child on the path and to the old sibling. So it creates d+1d + 1 nodes in O(d)O(d) time. All other nodes are shared. Because no node is changed, every older root still describes the old map: the structure is persistent.
  • Copy of a particle in line L8 copies the reference to its root, O(1)O(1). Two particles that share nodes can never see each other's updates, because an update makes new nodes and does not change shared ones.

So a step with kk readings per particle costs O(Nklog⁡M)O(N k \log M) for the updates, plus O(N)O(N) for the resampling. A plain array of MM landmarks per particle needs O(NM)O(N M) per step, because each resampled copy must copy the array. Montemerlo et al. (2002) give this O(Nlog⁡M)O(N \log M) bound per reading. Memory is O(NM)O(N M) in the worst case, and less when particles share subtrees.

Complexity

  • Time per step: O(Nklog⁡m)O(N k \log m) for kk readings, plus O(N)O(N) for resampling. Each reading does a constant amount of 2×22 \times 2 algebra and one tree update of O(log⁡m)O(\log m). Montemerlo et al. (2002) give O(Nlog⁡m)O(N \log m) per reading. EKF SLAM needs O(m2)O(m^2) per reading.
  • Space: O(Nm)O(N m) in the worst case. Particles that come from the same source share all landmarks that neither has changed since.
  • Without the tree: with an array per particle, resampling costs O(Nm)O(N m) per step, which is still linear in mm and simpler. For small maps the array is faster.

Properties

  • Multimodal over paths. Different particles can hold quite different paths, and so different maps. EKF SLAM holds one Gaussian.
  • Data association per particle. Each particle can decide for itself which landmark a reading belongs to, by the most likely landmark under its own map. Wrong decisions only hurt the particles that make them, and these tend to lose weight. The code on this page uses known correspondences.
  • Loss of path diversity (measurement and known limit). Resampling makes the particles share their early path. After a long loop, all particles may descend from one particle of the early part, and the filter becomes overconfident about the map. With 30 particles on a loop of 60 steps around 8 landmarks, the code places the landmarks with a mean error of less than 0.5 m on two seeds, and the mean pose ends within 0.3 m of the truth, against more than 0.9 m for odometry alone. These are measurements of this code, not general results.
  • Linearization per landmark. Each landmark filter is linearized at its own mean, given an exact pose. The error from the linearization does not spread through a large joint covariance as in EKF SLAM.

Variants and improvements

  • FastSLAM 2.0. Montemerlo et al. (2003) draw the new pose from a Gaussian approximation of the proposal that uses the readings of the step as well as the motion model. This needs far fewer particles when the sensor is more precise than the motion. For the linear Gaussian case they prove convergence with even one particle; this result does not cover the general nonlinear case.
  • Unknown correspondences. Per particle maximum likelihood association, with a new landmark when no likelihood is above a threshold. See data association in SLAM.
  • Grid maps. Replacing the landmark filters by an occupancy grid per particle gives grid-based RBPF SLAM, with scan matching in the proposal and adaptive resampling.
  • Adaptive resampling. Resample only when the effective sample size is low, to slow the loss of path diversity.

When to use it

Use FastSLAM for landmark SLAM when the map has many landmarks, when the data association is uncertain, or when the pose posterior can have more than one mode. Use EKF SLAM for small maps where one joint Gaussian is good enough and a deterministic result is wanted. For large loops and offline maps, a smoothing method such as pose graph optimization or iSAM2 usually gives better maps, because it keeps the whole path and optimizes it again after each loop closure.

Pitfalls

  • A shared tree changed in place. Two particles that come from one source share their tree. An update must make new nodes; a change in place corrupts the other particle.
  • The motion proposal with a precise sensor. If the readings are much more precise than the motion, few sampled poses fit, and most weights are near zero. Use FastSLAM 2.0 or more particles.
  • Underflow of the weights. Many readings in one step multiply many small densities. Work with log weights, or normalize after each step.
  • The bearing difference. The innovation of the bearing must be wrapped to [−π,π)[-\pi, \pi), or a landmark behind the robot gets a huge innovation.
  • Overconfidence after long loops. A small number of particles cannot hold enough paths for a large loop. The map then looks certain but has the errors of one path.

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.

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

"""FastSLAM 1.0 with known correspondences, for planar landmark SLAM.

After Montemerlo, Thrun, Koller and Wegbreit (2002) and Thrun, Burgard and
Fox (2005), Table 13.1. Each particle holds a sampled pose and one small EKF
(a 2-vector mean and a 2x2 covariance) per landmark. The landmarks of a
particle live in a persistent complete binary tree, indexed by the landmark
id: an update copies only the path from the root to one leaf, O(log m), and
resampling copies a particle by sharing its tree, O(1).

  Tree                                   the persistent tree (get, set)
  Particle                               pose, tree, weight
  fastslam_step(ps, u, dt, zs, ids, rng)  one step, lines L1 to L9

The motion model is the velocity model with the noise
M = diag(a1 v^2 + a2 w^2, a3 v^2 + a4 w^2) on the control, and the
readings are (range, bearing) with the noise covariance Q.
"""

import math

import rbm
import robest

STRAIGHT = 1e-9


# ---------------------------------------------------------------- persistent tree


class Tree:
    """A persistent map from the ids 0 .. 2^depth - 1 to values.

    Inner nodes are pairs (left, right); a missing subtree is None. set
    returns a new tree and leaves the old one valid: it creates depth + 1
    nodes and shares all others.
    """

    __slots__ = ("root", "depth", "created")

    def __init__(self, root=None, depth=0):
        self.root = root
        self.depth = depth
        self.created = 0  # nodes created by the set that made this tree

    def get(self, i):
        if i >> self.depth:
            return None
        node = self.root
        for level in range(self.depth - 1, -1, -1):
            if node is None:
                return None
            node = node[(i >> level) & 1]
        return node[0] if node is not None else None

    def set(self, i, value):
        root, depth = self.root, self.depth
        while i >> depth:  # grow: the old tree becomes the left subtree
            root = (root, None) if root is not None else None
            depth += 1
        out = Tree(_set(root, depth, i, value), depth)
        out.created = depth + 1
        return out

    def items(self):
        out = []
        _items(self.root, self.depth, 0, out)
        return out


def _set(node, level, i, value):
    if level == 0:
        return (value,)
    bit = (i >> (level - 1)) & 1
    left, right = node if node is not None else (None, None)
    if bit == 0:
        return (_set(left, level - 1, i, value), right)
    return (left, _set(right, level - 1, i, value))


def _items(node, level, prefix, out):
    if node is None:
        return
    if level == 0:
        out.append((prefix, node[0]))
        return
    _items(node[0], level - 1, prefix << 1, out)
    _items(node[1], level - 1, (prefix << 1) | 1, out)


# ---------------------------------------------------------------- models


def motion(x, v, w, dt):
    """Return the pose after moving with the control (v, w) for dt along an arc."""
    th = x[2]
    if abs(w) < STRAIGHT:
        return [x[0] + v * dt * math.cos(th), x[1] + v * dt * math.sin(th), th]
    r = v / w
    return [
        x[0] - r * math.sin(th) + r * math.sin(th + w * dt),
        x[1] + r * math.cos(th) - r * math.cos(th + w * dt),
        robest.wrap_angle(th + w * dt),
    ]


def sample_motion(rng, x, u, dt, alphas):
    """Draw a pose from the velocity motion model: line L2."""
    v, w = u
    a1, a2, a3, a4 = alphas
    vn = v + math.sqrt(a1 * v * v + a2 * w * w) * rng.gauss(0.0, 1.0)
    wn = w + math.sqrt(a3 * v * v + a4 * w * w) * rng.gauss(0.0, 1.0)
    return motion(x, vn, wn, dt)


def measure(x, m):
    dx, dy = m[0] - x[0], m[1] - x[1]
    return [math.hypot(dx, dy), robest.wrap_angle(math.atan2(dy, dx) - x[2])]


def landmark_jacobian(x, m):
    """Return the 2x2 Jacobian of measure with respect to the landmark."""
    dx, dy = m[0] - x[0], m[1] - x[1]
    q = dx * dx + dy * dy
    s = math.sqrt(q)
    return [[dx / s, dy / s], [-dy / q, dx / q]]


def inverse_measure(x, z):
    a = x[2] + z[1]
    return [x[0] + z[0] * math.cos(a), x[1] + z[0] * math.sin(a)]


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


class Particle:
    __slots__ = ("pose", "tree", "weight")

    def __init__(self, pose, tree, weight):
        self.pose = pose
        self.tree = tree
        self.weight = weight


def initial_particles(n, pose):
    return [Particle(list(pose), Tree(), 1.0 / n) for _ in range(n)]


def update_landmark(pose, lm, z, q):
    """One EKF update of a landmark (mean, cov) with the reading z from a known pose.

    Return the new (mean, cov) and the importance factor N(z; zhat, S).
    """
    mean, cov = lm
    zhat = measure(pose, mean)  # @line L5
    h = landmark_jacobian(pose, mean)
    s = rbm.add(rbm.mul(rbm.mul(h, cov), rbm.transpose(h)), q)
    k = rbm.mul(rbm.mul(cov, rbm.transpose(h)), rbm.inv(s))  # @line L6
    nu = [z[0] - zhat[0], robest.wrap_angle(z[1] - zhat[1])]
    new_mean = rbm.add(mean, rbm.matvec(k, nu))
    new_cov = rbm.mul(rbm.sub(rbm.eye(2), rbm.mul(k, h)), cov)
    new_cov = [[new_cov[0][0], (new_cov[0][1] + new_cov[1][0]) / 2.0], [(new_cov[0][1] + new_cov[1][0]) / 2.0, new_cov[1][1]]]
    factor = robest.gauss_pdf(nu, [0.0, 0.0], s)  # @line L7
    return (new_mean, new_cov), factor


def new_landmark(pose, z, q):
    """Initialize a landmark from its first reading: mean h^(-1)(z) and cov H^(-1) Q H^(-T)."""
    mean = inverse_measure(pose, z)
    hinv = rbm.inv(landmark_jacobian(pose, mean))
    return (mean, rbm.mul(rbm.mul(hinv, q), rbm.transpose(hinv)))


def fastslam_step(particles, u, dt, zs, ids, rng, alphas, q, p0=1.0, resample=True):
    """One FastSLAM 1.0 step, in place. Return the new list of particles."""
    for p in particles:  # @line L1
        p.pose = sample_motion(rng, p.pose, u, dt, alphas)  # @line L2
        for z, j in zip(zs, ids):  # @line L3
            lm = p.tree.get(j)
            if lm is None:
                p.tree = p.tree.set(j, new_landmark(p.pose, z, q))  # @line L4
                p.weight *= p0
            else:
                lm, factor = update_landmark(p.pose, lm, z, q)
                p.tree = p.tree.set(j, lm)
                p.weight *= factor
    total = sum(p.weight for p in particles)
    if not resample:
        for p in particles:
            p.weight /= total
        return particles
    idx = robest.low_variance_resample(rng, [p.weight for p in particles])  # @line L8
    n = len(particles)
    return [Particle(list(particles[i].pose), particles[i].tree, 1.0 / n) for i in idx]  # @line L9


def best_particle(particles):
    return max(particles, key=lambda p: p.weight)


def map_estimate(particles):
    """Return the weighted mean of each landmark over the particles that have it."""
    sums = {}
    for p in particles:
        for j, (mean, _) in p.tree.items():
            s = sums.setdefault(j, [0.0, 0.0, 0.0])
            s[0] += p.weight * mean[0]
            s[1] += p.weight * mean[1]
            s[2] += p.weight
    return {j: [s[0] / s[2], s[1] / s[2]] for j, s in sums.items()}
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_fastslam.py 169 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fastslam/. The authors are listed in prov/RCNQFQ.jsonl.

import math
import random

import rbm
import robest
from fastslam import (
    Tree,
    best_particle,
    fastslam_step,
    initial_particles,
    map_estimate,
    measure,
    motion,
    new_landmark,
    update_landmark,
)

ALPHAS = (0.02, 0.01, 0.01, 0.02)
Q = [[0.01, 0.0], [0.0, 0.0009]]
# eight landmarks around the circle of radius 4 about (0, 4) that the robot drives
LANDMARKS = [[(3.0 if k % 2 else 5.0) * math.cos(k * math.pi / 4.0), 4.0 + (3.0 if k % 2 else 5.0) * math.sin(k * math.pi / 4.0)] for k in range(8)]


def test_tree_matches_a_dict_and_keeps_old_versions():
    rng = random.Random(1)
    tree, ref, versions = Tree(), {}, []
    for _ in range(300):
        i = rng.randrange(200)
        tree = tree.set(i, i * 10 + len(versions))
        ref[i] = i * 10 + len(versions)
        versions.append((tree, dict(ref)))
        assert tree.created == tree.depth + 1
        assert tree.depth <= 8  # 2^8 = 256 >= 200
    for t, r in versions[::25]:
        for i in range(210):
            assert t.get(i) == r.get(i)
        assert sorted(t.items()) == sorted(r.items())


def test_set_shares_all_but_one_path():
    tree = Tree()
    for i in range(64):
        tree = tree.set(i, i)
    new = tree.set(37, -1)
    shared, node_a, node_b = 0, tree.root, new.root
    for level in range(tree.depth - 1, -1, -1):
        bit = (37 >> level) & 1
        assert node_a[1 - bit] is node_b[1 - bit]  # the sibling subtree is shared
        shared += 1
        node_a, node_b = node_a[bit], node_b[bit]
    assert shared == tree.depth == 6
    assert tree.get(37) == 37 and new.get(37) == -1


def ekf_landmark(pose, readings):
    """An independent EKF over one landmark seen from a known pose, written with full matrices."""
    mean = None
    for z in readings:
        if mean is None:
            a = pose[2] + z[1]
            mean = [pose[0] + z[0] * math.cos(a), pose[1] + z[0] * math.sin(a)]
            jac = rbm.num_jacobian(lambda m: measure(pose, m), mean)
            jinv = rbm.inv(jac)
            cov = rbm.mul(rbm.mul(jinv, Q), rbm.transpose(jinv))
            continue
        h = rbm.num_jacobian(lambda m: measure(pose, m), mean, 1e-7)
        zhat = measure(pose, mean)
        s = rbm.add(rbm.mul(rbm.mul(h, cov), rbm.transpose(h)), Q)
        k = rbm.mul(rbm.mul(cov, rbm.transpose(h)), rbm.inv(s))
        nu = [z[0] - zhat[0], robest.wrap_angle(z[1] - zhat[1])]
        mean = rbm.add(mean, rbm.matvec(k, nu))
        cov = rbm.mul(rbm.sub(rbm.eye(2), rbm.mul(k, h)), cov)
    return mean, cov


def test_with_a_known_pose_each_landmark_is_an_ekf():
    rng = random.Random(2)
    pose = [0.5, -0.2, 0.3]
    readings = []
    for _ in range(6):
        z = measure(pose, LANDMARKS[0])
        readings.append([z[0] + rng.gauss(0.0, 0.1), z[1] + rng.gauss(0.0, 0.03)])
    particles = initial_particles(3, pose)
    for z in readings:
        particles = fastslam_step(particles, (0.0, 0.0), 1.0, [z], [0], rng, (0.0, 0.0, 0.0, 0.0), Q)
    want_mean, want_cov = ekf_landmark(pose, readings)
    for p in particles:
        mean, cov = p.tree.get(0)
        assert max(abs(a - b) for a, b in zip(mean, want_mean)) < 1e-6
        assert max(abs(cov[i][j] - want_cov[i][j]) for i in range(2) for j in range(2)) < 1e-6


def test_the_weight_is_the_innovation_density():
    pose = [0.0, 0.0, 0.0]
    lm = new_landmark(pose, [2.0, 0.5], Q)
    z = [2.1, 0.48]
    (_, cov), factor = update_landmark(pose, lm, z, Q)
    zhat = measure(pose, lm[0])
    h = rbm.num_jacobian(lambda m: measure(pose, m), lm[0], 1e-7)
    s = rbm.add(rbm.mul(rbm.mul(h, lm[1]), rbm.transpose(h)), Q)
    assert abs(factor - robest.gauss_pdf(z, zhat, s)) < 1e-6 * factor
    # first reading: Sigma = H^-1 Q H^-T, so S = 2 Q and the update halves the covariance
    assert max(abs(cov[i][j] - lm[1][i][j] / 2.0) for i in range(2) for j in range(2)) < 1e-12


def test_page_example():
    lm = new_landmark([0.0, 0.0, 0.0], [2.0, 0.5], Q)
    assert abs(lm[0][0] - 1.7552) < 1e-4 and abs(lm[0][1] - 0.9589) < 1e-4
    assert abs(lm[1][0][0] - 0.008529) < 1e-6 and abs(lm[1][0][1] - 0.002693) < 1e-6 and abs(lm[1][1][1] - 0.005071) < 1e-6
    factors = []
    for pose in ([0.0, 0.0, 0.0], [0.0, 0.0, 0.05], [0.3, 0.0, 0.0]):
        (mean, _), f = update_landmark(pose, lm, [2.0, 0.5], Q)
        factors.append(f)
    assert abs(factors[0] - 26.53) < 0.01 and abs(factors[1] - 13.25) < 0.01 and abs(factors[2] - 1.067) < 0.001
    assert abs(mean[0] - 1.914) < 1e-3 and abs(mean[1] - 0.962) < 1e-3
    zhat = measure([0.3, 0.0, 0.0], lm[0])
    assert abs(zhat[0] - 1.7427) < 1e-4 and abs(zhat[1] - 0.5826) < 1e-4
    weights = [f / sum(factors) for f in factors]
    assert [round(w, 2) for w in weights] == [0.65, 0.32, 0.03]


def run(seed, n, steps=60):
    rng = random.Random(seed)
    truth = [0.0, 0.0, 0.0]
    odo = [0.0, 0.0, 0.0]
    particles = initial_particles(n, truth)
    for _ in range(steps):
        u = (0.4, 0.1)
        v, w = u
        vn = v + math.sqrt(ALPHAS[0] * v * v + ALPHAS[1] * w * w) * rng.gauss(0.0, 1.0)
        wn = w + math.sqrt(ALPHAS[2] * v * v + ALPHAS[3] * w * w) * rng.gauss(0.0, 1.0)
        truth = motion(truth, vn, wn, 1.0)
        odo = motion(odo, v, w, 1.0)
        zs, ids = [], []
        for j, lm in enumerate(LANDMARKS):
            z = measure(truth, lm)
            if z[0] < 4.0:
                zs.append([z[0] + rng.gauss(0.0, 0.1), z[1] + rng.gauss(0.0, 0.03)])
                ids.append(j)
        particles = fastslam_step(particles, u, 1.0, zs, ids, rng, ALPHAS, Q)
    return particles, truth, odo


def test_simulation_maps_the_landmarks():
    """A measurement on one loop of 60 steps around 8 landmarks, 30 particles, 2 seeds."""
    errs, pose_errs, odo_errs = [], [], []
    for seed in range(2):
        particles, truth, odo = run(seed, 30)
        est = map_estimate(particles)
        assert len(est) == 8
        errs.extend(math.hypot(est[j][0] - LANDMARKS[j][0], est[j][1] - LANDMARKS[j][1]) for j in est)
        x = sum(p.pose[0] for p in particles) / len(particles)
        y = sum(p.pose[1] for p in particles) / len(particles)
        pose_errs.append(math.hypot(x - truth[0], y - truth[1]))
        odo_errs.append(math.hypot(odo[0] - truth[0], odo[1] - truth[1]))
        assert best_particle(particles).tree.get(0) is not None
    assert sum(errs) / len(errs) < 0.5
    assert max(pose_errs) < 0.3
    assert min(odo_errs) > 0.9


def test_resampling_shares_trees():
    particles, _, _ = run(5, 20, steps=10)
    trees = {id(p.tree) for p in particles}
    assert len(trees) < len(particles)
    assert all(abs(p.weight - 1.0 / 20) < 1e-15 for p in particles)

History

Murphy (1999) had used a particle filter over the robot path with a grid map per particle, and Doucet, de Freitas, Murphy and Russell (2000) described Rao-Blackwellized particle filters in general. Montemerlo, Thrun, Koller and Wegbreit presented FastSLAM at AAAI 2002. They observed that the landmarks are independent given the path, gave each particle one Kalman filter per landmark, and kept the filters in a balanced tree so that a step is logarithmic in the number of landmarks. They also showed data association per particle. FastSLAM 2.0 followed at IJCAI 2003, with a proposal that uses the readings. Thrun, Burgard and Fox present both versions in Chapter 13 of Probabilistic Robotics (2005).

References

  1. Michael Montemerlo, Sebastian Thrun, Daphne Koller and Ben Wegbreit, FastSLAM: A factored solution to the simultaneous localization and mapping problem, Proceedings of the AAAI National Conference on Artificial Intelligence, 2002, pages 593 to 598, the factorization of the SLAM posterior, the per landmark filters, the tree of landmarks and the per particle data association
  2. Michael Montemerlo, Sebastian Thrun, Daphne Koller and Ben Wegbreit, FastSLAM 2.0: An improved particle filtering algorithm for simultaneous localization and mapping that provably converges, Proceedings of the International Joint Conference on Artificial Intelligence (IJCAI), 2003, from page 1151, the proposal that uses the readings, and the convergence result for the linear Gaussian case
  3. Sebastian Thrun, Wolfram Burgard and Dieter Fox, Probabilistic Robotics, MIT Press, 2005, Chapter 13 (FastSLAM 1.0 with known correspondences, FastSLAM 2.0 and data association)

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.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