Algorithm Search⌘K

Algorithmadvanced

Rao-Blackwellized particle filter

Also called RBPF, marginalized particle filter.

A particle filter that samples only some state variables and computes the rest in closed form for each particle, for example by a Kalman filter. This lowers the variance for a given particle count.

Time
O(N K c) step
Space
O(N b) extra
Where
K = the number of values of the sampled part per step; N = the number of particles; b = the size of one closed form belief; c = the cost of one closed form update
Properties
randomizednot exactonlinerecursive
Origin
Arnaud Doucet, Nando de Freitas, Kevin Murphy, Stuart Russell, 2000

A Rao-Blackwellized particle filter (RBPF) estimates the hidden state of a system that changes over time, from noisy observations, when the state has two parts: one part that is hard to handle in closed form, and one part that becomes easy once the first part is known. A plain particle filter represents the whole state by random samples. The RBPF samples only the hard part. Each particle then carries an exact distribution of the easy part given its sample, usually a Kalman filter. This removes the sampling noise of the easy part, so the same accuracy needs fewer particles. In robotics, the sampled part is the robot path and the exact part is the map: FastSLAM uses one small Kalman filter per landmark, and grid-based RBPF SLAM uses one occupancy grid per particle. This page describes the general method.

In plain words

Some problems are easy once you know one thing. If you knew the exact path of a robot, building its map would be simple bookkeeping. If you knew when a machine switched between its modes, its state would follow a simple linear law. The filter guesses the hard thing many times, with a different guess in each particle, and solves the easy part exactly for each guess. Guesses that explain the observations well get more weight, and bad guesses are dropped and replaced by copies of good ones. Because only the hard part is guessed, fewer guesses are needed than when the filter guesses everything.

The problem

The state at time tt is (rt,xt)(r_t, x_t). The filter must estimate p(r1:t,xt∣z1:t)p(r_{1:t}, x_t \mid z_{1:t}), or expectations under it, from the observations z1,…,ztz_1, \dots, z_t, one step at a time. The model must have this property: given the history r1:tr_{1:t}, the distribution p(xt∣r1:t,z1:t)p(x_t \mid r_{1:t}, z_{1:t}) and the predictive density p(zt∣r1:t,z1:t−1)p(z_t \mid r_{1:t}, z_{1:t-1}) can be computed in closed form, step by step. The common case is a model that is linear and Gaussian in xtx_t given r1:tr_{1:t}, as in a switching linear system or a hidden Markov model whose output is a linear system. The code on this page uses a scalar switching system: a mode sts_t follows a Markov chain, and xt=astxt−1+bst+wtx_t = a_{s_t} x_{t-1} + b_{s_t} + w_t, zt=cxt+vtz_t = c x_t + v_t with Gaussian noise.

The algorithm

  1. RBPF(particles {(r^i, α^i, w^i)} for i = 1..N, z_t)
  2. 1for i ← 1 to N do
  3. 2draw r_t^i ~ π(r_t | r^i_{1:t-1}, z_t)
  4. 3predict α^i in closed form given r^i_{1:t} ▷ for example a Kalman prediction
  5. 4w^i ← w^i · p(z_t | r^i_{1:t}, z_{1:t-1}) p(r_t^i | r_{t-1}^i) / π(r_t^i | r^i_{1:t-1}, z_t)
  6. 5update α^i with z_t in closed form ▷ for example a Kalman update
  7. 6normalize the weights w^i to sum 1
  8. 7if N_eff = 1 / Σ (w^i)² < N_T then resample the particles and set each w^i to 1/N
  9. 8return the particles; E[f(x_t) | z_{1:t}] ≈ Σ w^i E[f(x_t) | r^i_{1:t}, z_{1:t}]

αi\alpha^i holds the closed form belief of xtx_t for particle ii: a mean and a covariance in the linear Gaussian case. The density p(zt∣r1:ti,z1:t−1)p(z_t \mid r^i_{1:t}, z_{1:t-1}) of line L4 is a by-product of the Kalman filter: the Gaussian density of the innovation.

The proposal of line L2. The simplest choice is the prior π=p(rt∣rt−1)\pi = p(r_t \mid r_{t-1}); then line L4 multiplies the weight by the predictive density of ztz_t. When the sampled part has few values, the code can also draw rtr_t from p(rt∣r1:t−1i,z1:t)p(r_t \mid r^i_{1:t-1}, z_{1:t}), which looks at the new reading. Then the weight factor is the sum of the predictive densities over all values, weighted by the transition probabilities, and it does not depend on the drawn value. This needs the prediction of line L3 for every value, which is why the code computes it before the draw.

Line L7. Resampling every step adds noise; resampling never lets the weights degenerate. The code resamples with the low variance sampler when the effective sample size drops below N/2N/2, as Grisetti et al. do for grid maps.

Example

A cart on a line is stopped (mode 0) or moves by 1 per step (mode 1), and it keeps its mode with probability 0.9. The position noise has variance q=0.01q = 0.01, the reading is zt=xt+vtz_t = x_t + v_t with variance r=0.25r = 0.25, and at time 0 the cart is stopped at x0∼N(0,0.01)x_0 \sim N(0, 0.01). The first reading is z1=0.9z_1 = 0.9.

One particle at time 0 predicts for mode 0 the position N(0,0.02)N(0, 0.02) and the reading N(0,0.27)N(0, 0.27), and for mode 1 the position N(1,0.02)N(1, 0.02) and the reading N(1,0.27)N(1, 0.27). The weight of each mode is the transition probability times the density of the reading:

  • mode 0: 0.9⋅exp⁡(−0.92/0.54)/2π⋅0.27=0.9⋅0.2231/1.3025=0.15420.9 \cdot \exp(-0.9^2 / 0.54) / \sqrt{2 \pi \cdot 0.27} = 0.9 \cdot 0.2231 / 1.3025 = 0.1542;
  • mode 1: 0.1⋅exp⁡(−0.12/0.54)/2π⋅0.27=0.1⋅0.9817/1.3025=0.07540.1 \cdot \exp(-0.1^2 / 0.54) / \sqrt{2 \pi \cdot 0.27} = 0.1 \cdot 0.9817 / 1.3025 = 0.0754.

So P(s1=0∣z1)=0.1542/0.2296=0.672P(s_1 = 0 \mid z_1) = 0.1542 / 0.2296 = 0.672. The Kalman gain is 0.02/0.27=0.07410.02 / 0.27 = 0.0741 for both modes, so the mean of x1x_1 is 0+0.0741⋅0.9=0.0670 + 0.0741 \cdot 0.9 = 0.067 in mode 0 and 1+0.0741⋅(0.9−1)=0.9931 + 0.0741 \cdot (0.9 - 1) = 0.993 in mode 1, both with variance 0.01850.0185. The exact posterior mean is 0.672⋅0.067+0.328⋅0.993=0.3710.672 \cdot 0.067 + 0.328 \cdot 0.993 = 0.371. The particles that draw mode 0 or mode 1 carry these two Kalman filters exactly; only the share of each mode is a Monte Carlo estimate.

After the readings 2.12.1 and 2.02.0, the exact posterior, a mixture of 232^3 Kalman filters, gives P(moving)=0.640P(\text{moving}) = 0.640 and a mean position of 2.4762.476: the jump from 0.9 to 2.1 says that the cart moved, and the small step to 2.0 says that it may have stopped. The test file checks these numbers and shows that the RBPF approaches them as NN grows.

Correctness

Given the sampled history, the rest of the model is a linear Gaussian state space model, so the Kalman filter of lines L3 and L5 gives the exact conditional of xtx_t. The weights of line L4 are the importance weights of the history under the target p(r1:t∣z1:t)p(r_{1:t} \mid z_{1:t}), for any proposal that is positive where the target is. So line L8 is an importance sampling estimate of the exact sum over all histories, and it converges to it as NN grows. The correctness proof gives the details and the Rao-Blackwell argument for the variance. The tests compare the filter with an exact enumeration of all 2t2^t mode histories, check that one mode reduces it to a Kalman filter, and check that the average of the likelihood estimate matches p(z1:t)p(z_{1:t}).

Proof: The RBPF is importance sampling on the sampled variables with exact conditionalsfull

Setting. The state splits into rtr_t, the part the filter samples, and xtx_t, the part it computes in closed form. In the code, rt=str_t = s_t is a mode of a Markov chain with p(st∣st−1)p(s_t \mid s_{t-1}), and given the modes the model is linear and Gaussian: xt=astxt−1+bst+wtx_t = a_{s_t} x_{t-1} + b_{s_t} + w_t and zt=cxt+vtz_t = c x_t + v_t with Gaussian noise. Particle ii holds a history s1:tis^i_{1:t} (the code keeps only stis^i_t, which is all that the next step needs), the mean and the variance of xtx_t given that history and z1:tz_{1:t}, and a weight wiw^i.

Claim. (1) For each particle, lines L3 and L5 give the exact conditional p(xt∣s1:ti,z1:t)p(x_t \mid s^i_{1:t}, z_{1:t}). (2) Lines L2, L4 and L6 are sequential importance sampling for the target p(s1:t∣z1:t)p(s_{1:t} \mid z_{1:t}), with either proposal. (3) So the estimate of line L8 is a self-normalized importance sampling estimate of E[f(xt)∣z1:t]E[f(x_t) \mid z_{1:t}] with the integrand E[f(xt)∣s1:t,z1:t]E[f(x_t) \mid s_{1:t}, z_{1:t}]. (4) For a perfect sampler, this integrand has a variance no larger than that of f(xt)f(x_t), which is the Rao-Blackwell argument.

The factorization

By the chain rule,

p(s1:t,xt∣z1:t)=p(xt∣s1:t,z1:t) p(s1:t∣z1:t).p(s_{1:t}, x_t \mid z_{1:t}) = p(x_t \mid s_{1:t}, z_{1:t}) \, p(s_{1:t} \mid z_{1:t}).

So it is enough to sample histories from the second factor and to compute the first one for each history.

(1) The conditional of xtx_t is a Kalman filter

Fix a history s1:ts_{1:t}. Then xt=astxt−1+bst+wtx_t = a_{s_t} x_{t-1} + b_{s_t} + w_t and zt=cxt+vtz_t = c x_t + v_t form a linear Gaussian state space model with known, time varying coefficients. For such a model, the Kalman filter gives p(xt∣s1:t,z1:t)p(x_t \mid s_{1:t}, z_{1:t}) exactly, by induction over tt: if p(xt−1∣s1:t−1,z1:t−1)=N(m,P)p(x_{t-1} \mid s_{1:t-1}, z_{1:t-1}) = N(m, P), the prediction is N(am+b,a2P+q)N(a m + b, a^2 P + q), and Bayes' rule with the Gaussian reading gives the update of line L5. The mode sts_t enters only through aa, bb and qq, and xt−1x_{t-1} does not depend on sts_t given s1:t−1s_{1:t-1}, so line L3 uses the right prior. The same recursion gives the predictive density of the reading,

p(zt∣s1:t,z1:t−1)=N(zt;  cmˉ,  c2Pˉ+r),p(z_t \mid s_{1:t}, z_{1:t-1}) = N\big(z_t; \; c \bar m, \; c^2 \bar P + r\big),

with the predicted moments mˉ\bar m and Pˉ\bar P of line L3.

(2) The weights

By Bayes' rule and the Markov property of the modes,

p(s1:t∣z1:t)∝p(s1:t−1∣z1:t−1)  p(st∣st−1)  p(zt∣s1:t,z1:t−1).p(s_{1:t} \mid z_{1:t}) \propto p(s_{1:t-1} \mid z_{1:t-1}) \; p(s_t \mid s_{t-1}) \; p(z_t \mid s_{1:t}, z_{1:t-1}).

Suppose that the weighted particles at time t−1t-1 represent p(s1:t−1∣z1:t−1)p(s_{1:t-1} \mid z_{1:t-1}): for each ii, wt−1iw^i_{t-1} is proportional to the target over the proposal density of s1:t−1is^i_{1:t-1}. Line L2 extends each history with st∼π(st∣s1:t−1i,zt)s_t \sim \pi(s_t \mid s^i_{1:t-1}, z_t). The importance weight of the extended history is then

wti∝wt−1i p(sti∣st−1i) p(zt∣s1:ti,z1:t−1)π(sti∣s1:t−1i,zt).w^i_t \propto w^i_{t-1} \, \frac{p(s^i_t \mid s^i_{t-1}) \, p(z_t \mid s^i_{1:t}, z_{1:t-1})}{\pi(s^i_t \mid s^i_{1:t-1}, z_t)}.
  • Prior proposal. π=p(st∣st−1)\pi = p(s_t \mid s_{t-1}), so the factor is the predictive density p(zt∣s1:ti,z1:t−1)p(z_t \mid s^i_{1:t}, z_{1:t-1}). The code computes it as probs[s] / trans[s_prev][s].
  • Optimal proposal. π(st)=p(st∣st−1i) p(zt∣s1:t−1i,st,z1:t−1)/Zi\pi(s_t) = p(s_t \mid s^i_{t-1}) \, p(z_t \mid s^i_{1:t-1}, s_t, z_{1:t-1}) / Z^i with Zi=∑sp(s∣st−1i) p(zt∣s1:t−1i,s,z1:t−1)Z^i = \sum_{s} p(s \mid s^i_{t-1}) \, p(z_t \mid s^i_{1:t-1}, s, z_{1:t-1}). Then the factor is ZiZ^i, which does not depend on the drawn stis^i_t. Because the factor is fixed once the past is fixed, the draw of stis^i_t adds no variance to the weight; this is why the proposal is called optimal. It needs the predictive density of every mode, which the code computes anyway.

Line L6 normalizes, which does not change the ratios. Line L7 resamples with the low variance sampler when the effective sample size (∑w)2/∑w2(\sum w)^2 / \sum w^2 falls below N/2N/2. Resampling draws NN histories with probabilities proportional to the weights and gives each the weight 1/N1/N, so the expected number of copies of each history is proportional to its weight, and the resampled set represents the same distribution.

(3) The estimate

Line L8 returns ∑iw~i E[xt∣s1:ti,z1:t]\sum_i \tilde w^i \, E[x_t \mid s^i_{1:t}, z_{1:t}] with the normalized weights w~i\tilde w^i, and ∑iw~i[sti=k]\sum_i \tilde w^i [s^i_t = k] for the mode probabilities. By the factorization,

E[f(xt)∣z1:t]=∑s1:tp(s1:t∣z1:t) E[f(xt)∣s1:t,z1:t],E[f(x_t) \mid z_{1:t}] = \sum_{s_{1:t}} p(s_{1:t} \mid z_{1:t}) \, E[f(x_t) \mid s_{1:t}, z_{1:t}],

so line L8 is the self-normalized importance sampling estimate of this sum. For a fixed tt and N→∞N \to \infty, such estimates converge to the sum; with resampling, this is the standard convergence of sequential Monte Carlo, which we use and do not prove here. The exact sum has KtK^t terms, each a Kalman filter; exact_posterior in the code computes it, and the tests compare the filter with it.

(4) Why it needs fewer particles

Let g(s1:t)=E[f(xt)∣s1:t,z1:t]g(s_{1:t}) = E[f(x_t) \mid s_{1:t}, z_{1:t}]. By the law of total variance under the posterior,

Var[f(xt)]=Var[g(s1:t)]+E[Var[f(xt)∣s1:t]]≥Var[g(s1:t)].\mathrm{Var}[f(x_t)] = \mathrm{Var}[g(s_{1:t})] + E\big[\mathrm{Var}[f(x_t) \mid s_{1:t}]\big] \ge \mathrm{Var}[g(s_{1:t})].

So with NN independent draws from the posterior, the average of gg has a variance no larger than the average of ff over draws of (s1:t,xt)(s_{1:t}, x_t). This is the Rao-Blackwell theorem applied to the estimator. For the full filter with resampling, the gain is not covered by these statements, so the code measures it: on the example of the page, with 100 particles over 20 seeds, the mean squared error of the RBPF is below that of a particle filter that samples xtx_t too.

Complexity

  • Time per step: O(NKc)O(N K c), where cc is the cost of one closed form step and KK the number of values that the proposal looks at. For the prior proposal, K=1K = 1. For a Kalman filter on dd variables, c=O(d3)c = O(d^3), or less with structure, as in FastSLAM, where each landmark has its own small filter.
  • Resampling: O(N)O(N) with the low variance sampler, plus the cost of copying the closed form beliefs. FastSLAM shares the unchanged parts in a tree so that a copy costs O(log⁡m)O(\log m) for mm landmarks.
  • Memory: NN closed form beliefs.

Properties

  • Exact in the closed form part. The only Monte Carlo error is in the sampled part. If the sampled part has one value, the RBPF is the Kalman filter, with no sampling error at all.
  • Lower variance (theorem for perfect sampling, measurement for the full filter). For draws from the posterior, the law of total variance gives Var[E[f∣r]]≤Var[f]\mathrm{Var}[E[f \mid r]] \le \mathrm{Var}[f], which is the Rao-Blackwell theorem. On the example with 8 steps, over 20 seeds, the mean squared error of the posterior mean is 5.3⋅10−45.3 \cdot 10^{-4} for the RBPF and 2.2⋅10−32.2 \cdot 10^{-3} for a plain particle filter at 100 particles, and 4.8⋅10−54.8 \cdot 10^{-5} against 2.9⋅10−42.9 \cdot 10^{-4} at 1000 particles.
  • Unbiased likelihood. The product of the normalizers of line L6 over the steps is an estimate of p(z1:t)p(z_{1:t}) whose average over runs is the exact value. The tests check this on 300 runs.
  • Degeneracy of the past. Resampling makes the particles share their early history. The estimate of the current state is fine, but the samples of old values of rr have little diversity. In SLAM this is the loss of the diversity of the path, which matters at a loop closure.

Variants and improvements

  • The optimal proposal. Drawing rtr_t given ztz_t as well, as the code does for a few modes, keeps more particles in useful places. Grid-based RBPF SLAM approximates it by scan matching, and FastSLAM 2.0 does the same with the landmark readings.
  • Adaptive resampling. Resampling only when the effective sample size is low, as in line L7, reduces the loss of diversity.
  • FastSLAM. The sampled part is the robot path, and given the path the landmarks are independent, so each particle has one small EKF per landmark instead of one large filter.
  • Mixture Kalman filters and the marginalized particle filter. The same idea under other names in signal processing, often for models with a nonlinear part and a linear Gaussian part, where the nonlinear part is sampled.

When to use it

Use an RBPF when the state has a part that is hard, because it is discrete, multimodal or strongly nonlinear, and a part that is linear and Gaussian, or otherwise tractable, given the first. Switching linear systems, fault detection, target tracking with an unknown maneuver mode and SLAM are the typical cases. If the whole state is tractable, use the exact filter. If no part is tractable, use a plain particle filter. If the tractable part is large and its closed form step is expensive, compare the cost per particle with that of more particles in a plain filter.

Pitfalls

  • The wrong conditional. The closed form part must be exact given the full sampled history, not only given the current value of rr. A particle must keep its own filter state, which carries the history.
  • Sharing filters after resampling. Copies of a particle must not share a mutable filter state. Copy it, or share it only in a persistent structure, as FastSLAM does.
  • A peaked likelihood. With a precise sensor and the prior proposal, almost all weights are near zero. Use a proposal that looks at ztz_t.
  • Underflow. Multiply weights in the log domain when the likelihoods are small, and normalize at each step.
  • Too few particles for the history. The closed form part cannot fix a wrong sampled history. If the right history has no particle, the estimate is wrong with a small reported variance.

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.

rao_blackwellized_particle_filter.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/rao-blackwellized-particle-filter/. The authors are listed in prov/E6NP93.jsonl.

"""A Rao-Blackwellized particle filter for a switching linear model.

The model is a jump Markov linear system with a scalar state:

  s_t        a mode in {0, ..., K-1}, a Markov chain with P(s_t = j | s_(t-1) = i) = trans[i][j]
  x_t        = a[s_t] x_(t-1) + b[s_t] + w_t,   w_t ~ N(0, q[s_t])
  z_t        = c x_t + v_t,                     v_t ~ N(0, r)

Given the mode history, the model is linear and Gaussian, so a Kalman
filter gives p(x_t | s_(1:t), z_(1:t)) exactly. The filter samples only
the modes, and each particle carries the mean and the variance of its
Kalman filter. This is the setting of Doucet, de Freitas, Murphy and
Russell (2000).

  rbpf_step(model, particles, z, rng, proposal)   one step, lines L1 to L8
  estimate(particles)                              the mixture mean of x_t and P(s_t = k)
  exact_posterior(model, zs)                       enumeration of all K^t mode histories
  bootstrap_pf_step(model, particles, z, rng)      a plain particle filter over (s, x), to compare

A particle is a list [s, mean, var, weight].
"""

import math

import robest


class Model:
    """The parameters of the switching linear model, with the prior of x_0 and s_0."""

    def __init__(self, trans, a, b, q, c, r, x0_mean, x0_var, s0_prob):
        self.trans = trans
        self.a = a
        self.b = b
        self.q = q
        self.c = c
        self.r = r
        self.x0_mean = x0_mean
        self.x0_var = x0_var
        self.s0_prob = s0_prob
        self.k = len(a)


def kalman_predict(model, s, mean, var):
    """Return the Kalman prediction of x_t given the mode s."""
    return model.a[s] * mean + model.b[s], model.a[s] ** 2 * var + model.q[s]


def predictive(model, s, mean, var):
    """Return the predicted moments and the likelihood mean and variance of z_t, given s."""
    pm, pv = kalman_predict(model, s, mean, var)
    return pm, pv, model.c * pm, model.c ** 2 * pv + model.r


def kalman_update(model, pm, pv, z):
    """Return the Kalman update of N(pm, pv) with the reading z."""
    sv = model.c ** 2 * pv + model.r
    gain = pv * model.c / sv
    return pm + gain * (z - model.c * pm), (1.0 - gain * model.c) * pv


def initial_particles(model, n, rng):
    """N particles with the modes drawn from s0_prob and the prior of x_0 in each."""
    out = []
    for _ in range(n):
        s = draw(rng, model.s0_prob)
        out.append([s, model.x0_mean, model.x0_var, 1.0 / n])
    return out


def draw(rng, probs):
    """Draw an index with the given probabilities."""
    u = rng.random() * sum(probs)
    acc = 0.0
    for i, p in enumerate(probs):
        acc += p
        if u < acc:
            return i
    return len(probs) - 1


def effective_size(particles):
    total = sum(p[3] for p in particles)
    return total * total / sum(p[3] * p[3] for p in particles)


def rbpf_step(model, particles, z, rng, proposal="optimal", resample_ratio=0.5):
    """One step of the RBPF, in place. Return the log of the step's likelihood estimate.

    proposal="prior" draws s_t from the Markov chain and weights by the
    predictive likelihood of z_t. proposal="optimal" draws s_t from
    p(s_t | s_(t-1), x-belief, z_t), whose weight does not depend on the
    draw. Resampling happens when the effective sample size falls below
    resample_ratio times N.
    """
    n = len(particles)
    total_before = sum(p[3] for p in particles)
    for p in particles:  # @line L1
        s_prev, mean, var, w = p
        probs, moments = [], []
        for s in range(model.k):
            pm, pv, zm, zv = predictive(model, s, mean, var)
            moments.append((pm, pv))
            probs.append(model.trans[s_prev][s] * robest.gauss_pdf(z, zm, zv))
        if proposal == "optimal":
            s = draw(rng, probs)  # @line L2
            factor = sum(probs)
        else:
            s = draw(rng, model.trans[s_prev])
            factor = probs[s] / model.trans[s_prev][s]
        pm, pv = moments[s]  # @line L3
        p[3] = w * factor  # @line L4
        p[0] = s
        p[1], p[2] = kalman_update(model, pm, pv, z)  # @line L5
    total = sum(p[3] for p in particles)
    if total <= 0.0:
        raise ValueError("all weights are zero")
    for p in particles:
        p[3] /= total  # @line L6
    if effective_size(particles) < resample_ratio * n:  # @line L7
        idx = robest.low_variance_resample(rng, [p[3] for p in particles])
        new = [[particles[i][0], particles[i][1], particles[i][2], 1.0 / n] for i in idx]
        particles[:] = new
    return math.log(total / total_before)


def estimate(particles):
    """Return E[x_t | z_(1:t)] and the list P(s_t = k | z_(1:t)) from the particles: line L8."""
    total = sum(p[3] for p in particles)
    mean = sum(p[3] * p[1] for p in particles) / total  # @line L8
    k = 1 + max(p[0] for p in particles)
    probs = [0.0] * k
    for p in particles:
        probs[p[0]] += p[3] / total
    return mean, probs


def rbpf(model, zs, n, rng, proposal="optimal"):
    """Run the RBPF over the readings zs. Return the list of (mean, mode probabilities) per step."""
    particles = initial_particles(model, n, rng)
    out = []
    for z in zs:
        rbpf_step(model, particles, z, rng, proposal)
        mean, probs = estimate(particles)
        probs = probs + [0.0] * (model.k - len(probs))
        out.append((mean, probs))
    return out


def exact_posterior(model, zs):
    """Enumerate all mode histories with a Kalman filter each. Cost O(K^(t+1)).

    Return the exact E[x_t | z_(1:t)], P(s_t = k | z_(1:t)) and p(z_(1:t)).
    """
    hyps = [(s, model.s0_prob[s], model.x0_mean, model.x0_var) for s in range(model.k) if model.s0_prob[s] > 0.0]
    lik = 1.0
    for z in zs:
        new = []
        for s_prev, w, mean, var in hyps:
            for s in range(model.k):
                if model.trans[s_prev][s] == 0.0:
                    continue
                pm, pv, zm, zv = predictive(model, s, mean, var)
                m, v = kalman_update(model, pm, pv, z)
                new.append((s, w * model.trans[s_prev][s] * robest.gauss_pdf(z, zm, zv), m, v))
        total = sum(h[1] for h in new)
        lik *= total
        hyps = [(s, w / total, m, v) for s, w, m, v in new]
    mean = sum(w * m for _, w, m, _ in hyps)
    probs = [0.0] * model.k
    for s, w, _, _ in hyps:
        probs[s] += w
    return mean, probs, lik


def bootstrap_pf_step(model, particles, z, rng):
    """One step of a plain particle filter that samples both s_t and x_t.

    A particle is [s, x, weight]. It resamples at every step.
    """
    n = len(particles)
    for p in particles:
        s = draw(rng, model.trans[p[0]])
        x = model.a[s] * p[1] + model.b[s] + math.sqrt(model.q[s]) * rng.gauss(0.0, 1.0)
        p[0], p[1] = s, x
        p[2] *= robest.gauss_pdf(z, model.c * x, model.r)
    total = sum(p[2] for p in particles)
    mean = sum(p[2] * p[1] for p in particles) / total
    idx = robest.low_variance_resample(rng, [p[2] for p in particles])
    particles[:] = [[particles[i][0], particles[i][1], 1.0 / n] for i in idx]
    return mean


def bootstrap_pf(model, zs, n, rng):
    """Run the plain particle filter; return the list of the estimates of E[x_t | z_(1:t)]."""
    particles = []
    for _ in range(n):
        s = draw(rng, model.s0_prob)
        particles.append([s, model.x0_mean + math.sqrt(model.x0_var) * rng.gauss(0.0, 1.0), 1.0 / n])
    return [bootstrap_pf_step(model, particles, z, rng) for z in zs]


def simulate(model, steps, rng):
    """Draw a mode path, a state path and readings from the model."""
    s = draw(rng, model.s0_prob)
    x = model.x0_mean + math.sqrt(model.x0_var) * rng.gauss(0.0, 1.0)
    modes, xs, zs = [], [], []
    for _ in range(steps):
        s = draw(rng, model.trans[s])
        x = model.a[s] * x + model.b[s] + math.sqrt(model.q[s]) * rng.gauss(0.0, 1.0)
        modes.append(s)
        xs.append(x)
        zs.append(model.c * x + math.sqrt(model.r) * rng.gauss(0.0, 1.0))
    return modes, xs, zs
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_rao_blackwellized_particle_filter.py 116 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/rao-blackwellized-particle-filter/. The authors are listed in prov/E6NP93.jsonl.

import math
import random

from rao_blackwellized_particle_filter import (
    Model,
    bootstrap_pf,
    effective_size,
    estimate,
    exact_posterior,
    initial_particles,
    kalman_predict,
    kalman_update,
    rbpf,
    rbpf_step,
    simulate,
)


def cart():
    """The example of the page: a cart that is stopped (mode 0) or moves 1 per step (mode 1)."""
    return Model([[0.9, 0.1], [0.1, 0.9]], [1.0, 1.0], [0.0, 1.0], [0.01, 0.01], 1.0, 0.25, 0.0, 0.01, [1.0, 0.0])


def test_example_of_the_page():
    m = cart()
    mean, probs, lik = exact_posterior(m, [0.9])
    assert abs(probs[0] - 0.6717) < 1e-4
    assert abs(mean - 0.3707) < 1e-4
    mean, probs, _ = exact_posterior(m, [0.9, 2.1, 2.0])
    assert abs(probs[1] - 0.6402) < 1e-4
    assert abs(mean - 2.4763) < 1e-4
    # one particle step by hand: both modes give the variance 0.02 (1 - 0.02 / 0.27)
    p = [[0, 0.0, 0.01, 1.0]]
    rbpf_step(m, p, 0.9, random.Random(0))
    assert abs(p[0][2] - 0.02 * (1.0 - 0.02 / 0.27)) < 1e-12
    want = 0.9 * 0.02 / 0.27 if p[0][0] == 0 else 1.0 - 0.1 * 0.02 / 0.27
    assert abs(p[0][1] - want) < 1e-12


def test_one_mode_is_the_kalman_filter():
    m = Model([[1.0]], [0.95], [0.3], [0.04], 2.0, 0.5, 1.0, 1.0, [1.0])
    rng = random.Random(4)
    _, xs, zs = simulate(m, 10, rng)
    particles = initial_particles(m, 5, rng)
    mean, var, loglik = 1.0, 1.0, 0.0
    for z in zs:
        pm, pv = kalman_predict(m, 0, mean, var)
        sv = m.c ** 2 * pv + m.r
        step_ll = -0.5 * math.log(2.0 * math.pi * sv) - 0.5 * (z - m.c * pm) ** 2 / sv
        loglik += step_ll
        mean, var = kalman_update(m, pm, pv, z)
        assert abs(rbpf_step(m, particles, z, rng) - step_ll) < 1e-12
        est, probs = estimate(particles)
        assert abs(est - mean) < 1e-12
        assert probs == [1.0]
        for p in particles:
            assert abs(p[2] - var) < 1e-15
    _, _, lik = exact_posterior(m, zs)
    assert abs(math.log(lik) - loglik) < 1e-9


def test_converges_to_the_exact_posterior():
    m = cart()
    _, _, zs = simulate(m, 8, random.Random(1))
    mean, probs, _ = exact_posterior(m, zs)
    for proposal in ("optimal", "prior"):
        est, est_probs = rbpf(m, zs, 2000, random.Random(2), proposal)[-1]
        assert abs(est - mean) < 0.03
        assert abs(est_probs[1] - probs[1]) < 0.03


def test_the_optimal_proposal_weight_does_not_depend_on_the_draw():
    m = cart()
    a = [[0, 0.0, 0.01, 0.5], [1, 1.0, 0.02, 0.5]]
    b = [list(p) for p in a]
    rbpf_step(m, a, 0.9, random.Random(1), resample_ratio=0.0)
    rbpf_step(m, b, 0.9, random.Random(7), resample_ratio=0.0)
    assert [p[3] for p in a] == [p[3] for p in b]
    assert abs(sum(p[3] for p in a) - 1.0) < 1e-12


def test_the_likelihood_estimate_is_unbiased():
    """The product of the step likelihoods averages to p(z_(1:t)) over many runs."""
    m = cart()
    _, _, zs = simulate(m, 5, random.Random(3))
    _, _, lik = exact_posterior(m, zs)
    total, runs = 0.0, 300
    for seed in range(runs):
        rng = random.Random(100 + seed)
        particles = initial_particles(m, 8, rng)
        total += math.exp(sum(rbpf_step(m, particles, z, rng, "prior") for z in zs))
    assert abs(total / runs / lik - 1.0) < 0.1


def test_resampling_keeps_the_size_and_resets_the_weights():
    m = cart()
    particles = initial_particles(m, 50, random.Random(5))
    rbpf_step(m, particles, 5.0, random.Random(6), "prior", resample_ratio=1.01)
    assert len(particles) == 50
    assert all(p[3] == 1.0 / 50 for p in particles)
    assert abs(effective_size(particles) - 50.0) < 1e-9


def test_fewer_particles_than_a_plain_particle_filter():
    """A measurement: at the same N, the RBPF error is smaller than the error of a filter that samples x too."""
    m = cart()
    _, _, zs = simulate(m, 8, random.Random(1))
    mean, _, _ = exact_posterior(m, zs)
    err_rb, err_pf = 0.0, 0.0
    for seed in range(20):
        err_rb += (rbpf(m, zs, 100, random.Random(seed))[-1][0] - mean) ** 2
        err_pf += (bootstrap_pf(m, zs, 100, random.Random(seed))[-1] - mean) ** 2
    assert err_rb < err_pf

History

The idea of replacing a sampled variable by its conditional expectation comes from the Rao-Blackwell theorem of statistics. In particle filtering, it appeared in several forms around 1999 and 2000. Murphy (1999) used it to learn a grid map with a particle filter over the robot path, and Doucet, de Freitas, Murphy and Russell (2000) described Rao-Blackwellized particle filtering for dynamic Bayesian networks at UAI 2000. In SLAM, Montemerlo, Thrun, Koller and Wegbreit (2002) built FastSLAM on it, and Grisetti, Stachniss and Burgard (2007) built a grid-based version with an improved proposal and adaptive resampling. Thrun, Burgard and Fox present it as the basis of FastSLAM in Chapter 13 of Probabilistic Robotics (2005).

References

  1. Arnaud Doucet, Nando de Freitas, Kevin Murphy and Stuart Russell, Rao-Blackwellised particle filtering for dynamic Bayesian networks, Proceedings of the 16th Conference on Uncertainty in Artificial Intelligence (UAI), 2000, pages 176 to 183, the RBPF algorithm, the choice of the proposal and the examples
  2. Kevin Murphy, Bayesian map learning in dynamic environments, Advances in Neural Information Processing Systems 12 (NIPS), 1999, the use of Rao-Blackwellization to learn a grid map with a particle filter over the robot path
  3. Sebastian Thrun, Wolfram Burgard and Dieter Fox, Probabilistic Robotics, MIT Press, 2005, Chapter 13 (FastSLAM, a Rao-Blackwellized particle filter for SLAM)

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.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