Algorithm Search⌘K

Algorithmadvanced

KLD-sampling

Also called adaptive particle filter.

A particle filter that draws particles until their number reaches a bound from the count of occupied bins. The bound limits the KL error of the histogram only asymptotically.

Time
O(N + n log N + n D) per_step
Space
O(N + n + k) extra
Where
D = the cost of one evaluation of the measurement model; N = the number of particles of the previous step; epsilon = the error bound; k = the number of occupied bins; n = the number of particles drawn in one step
Properties
adaptiverandomizednot exactonlinerandomized
Origin
Dieter Fox, 2003

KLD-sampling is a variant of Monte Carlo localization that chooses the number of particles at each step. It draws the new particles one at a time and puts each in a bin of a fixed grid over the pose space. It stops when the number of particles nn reaches a bound that grows with the number kk of bins that hold at least one particle. When the belief is spread out, as at the start of global localization, many bins are occupied and the filter uses many particles. When the belief is concentrated, few bins are occupied and the filter uses few. Fox (2003) derived the bound from the distribution of the Kullback-Leibler divergence between a sample histogram and the true distribution: with n=χk−1,1−δ2/(2ε)n = \chi^2_{k-1, 1-\delta} / (2\varepsilon) samples, the divergence is at most ε\varepsilon with probability about 1−δ1 - \delta. This holds only asymptotically, and only for the histogram of independent samples of a fixed distribution.

In plain words

A robot that does not know where it is needs many guesses, because the guesses must cover the whole building. Once it knows where it is, a few guesses near the right place are enough. KLD-sampling counts how many different areas the guesses fall in while it makes them. Each new area means that more guesses are needed. It stops when it has enough guesses for the number of areas it has seen. So the robot spends its computation where it helps, and runs fast when it is sure of its pose.

The problem

The setting is Monte Carlo localization: a map, a motion model that can be sampled, a measurement model that can be evaluated, and a weighted particle set {(xt−1[i],wt−1[i])}\{(x_{t-1}^{[i]}, w_{t-1}^{[i]})\} for the previous belief. In addition, there is a grid of bins over the pose space, an error bound ε>0\varepsilon > 0 and a probability δ∈(0,1)\delta \in (0, 1). The output is a weighted particle set for the new belief, with a number of particles that depends on the belief.

The goal behind the bound is this. Let a distribution pp over kk bins be sampled nn times independently, and let p^\hat p be the histogram of the samples. Choose nn so that P(K(p^,p)≤ε)≈1−δP(K(\hat p, p) \le \varepsilon) \approx 1 - \delta, where K(p^,p)=∑jp^jlog⁡(p^j/pj)K(\hat p, p) = \sum_j \hat p_j \log(\hat p_j / p_j).

The algorithm

The bound. By the likelihood ratio test theory (Wilks' theorem), 2nK(p^,p)2 n K(\hat p, p) converges in distribution to the chi-square distribution with k−1k - 1 degrees of freedom as n→∞n \to \infty. So the probability that K(p^,p)≤εK(\hat p, p) \le \varepsilon is about 1−δ1 - \delta for

n=12εχk−1,1−δ2n = \frac{1}{2\varepsilon} \chi^2_{k-1, 1-\delta}

(Fox, equation (13)), where χk−1,1−δ2\chi^2_{k-1, 1-\delta} is the 1−δ1 - \delta quantile. The Wilson-Hilferty approximation of the quantile gives

n≈k−12ε(1−29(k−1)+29(k−1) z1−δ)3n \approx \frac{k-1}{2\varepsilon} \left(1 - \frac{2}{9(k-1)} + \sqrt{\frac{2}{9(k-1)}}\, z_{1-\delta}\right)^3

(Fox, equation (14)), where z1−δz_{1-\delta} is the 1−δ1 - \delta quantile of the standard normal distribution. For large kk, nn is about (k−1)/(2ε)(k-1)/(2\varepsilon): linear in the number of occupied bins.

The sampler. kk is not known in advance. KLD-sampling counts the bins that the new particles occupy and updates the bound after each new bin.

  1. KLD-MCL(X_{t-1}, u_t, z_t, m, ε, δ, n_min, n_max)
  2. 1X_t ← ∅; n ← 0; k ← 0; n_χ ← 0; all bins empty
  3. 2repeat
  4. 3draw an index i with probability w_{t-1}^[i] / Σ w_{t-1}
  5. 4x ← sample of p(x_t | u_t, x_{t-1}^[i], m)
  6. 5w ← p(z_t | x, m); add (x, w) to X_t
  7. 6if the bin of x is empty then
  8. 7mark it nonempty; k ← k + 1
  9. 8if k > 1 then n_χ ← (k-1)/(2ε) · (1 - 2/(9(k-1)) + √(2/(9(k-1))) z_{1-δ})³
  10. 9n ← n + 1
  11. 10until (n ≥ n_χ and n ≥ n_min) or n ≥ n_max
  12. 11return X_t

Unlike the MCL of Thrun et al., which moves and then resamples a set of fixed size, KLD-sampling draws each new particle independently from the previous weighted set (line L3), so the number of draws can be chosen while sampling. The new set stays weighted. Fox uses a lower limit nminn_\text{min} (typically 10). The code adds nmaxn_\text{max} so that the loop always ends.

The loop condition. The listing of the algorithm in Fox (2003), Table 2, prints the loop condition as "while (n<nχn < n_\chi and n<nχminn < n_{\chi\text{min}})". With nχ=0n_\chi = 0 at the start, this would stop after one particle. The text and the version of Thrun et al. (Section 8.3.7) mean that the loop continues while either bound is not reached, which is line L10 here.

Example

The bound for ε=0.05\varepsilon = 0.05. The table gives ⌈n⌉\lceil n \rceil by the Wilson-Hilferty form, and in brackets by the exact chi-square quantile where they differ.

kk δ=0.01\delta = 0.01 δ=0.05\delta = 0.05 δ=0.01\delta = 0.01, ε=0.1\varepsilon = 0.1
2 66 (67) 38 33
3 93 60 47
5 134 (133) 95 67
10 217 170 109
20 363 (362) 302 182
50 750 664 375
100 1347 1233 674
1000 11060 10737 5530

The Wilson-Hilferty form is worst for k=2k = 2, with 1 degree of freedom, where it is up to 2.5 percent low for δ=0.05\delta = 0.05 and δ=0.1\delta = 0.1. For k≥5k \ge 5 it is within 0.5 percent of the exact value in the tests.

Coverage. The test draws n=147n = 147 samples, the bound for k=10k = 10, ε=0.05\varepsilon = 0.05 and δ=0.1\delta = 0.1, from a fixed distribution over 10 bins, 1500 times. The divergence of the histogram is at most 0.050.05 in 89.1 percent of the trials, against the asymptotic 9090 percent. This is a measurement for one distribution and one seed.

Localization on a ring. A robot moves 1 m per step on a ring of 30 m with a color in each 1 m cell, and the bins are 0.5 m long, 60 bins in all. The start is 5000 particles spread over the ring. With ε=0.05\varepsilon = 0.05 and δ=0.01\delta = 0.01, the numbers of particles in the first 10 steps are 872, 836, 688, 444, 444, 263, 248, 169, 134 and 114, and in the last 7 of 25 steps they are 93 or 114, which is the bound for 3 or 4 bins. The first step occupies all 60 bins, and the bound for k=60k = 60 is 872. This is a measurement for one seed.

Correctness

The correctness proof shows three things. The loop ends after at most nmaxn_\text{max} draws. When it ends before nmaxn_\text{max}, n≥max⁡(nmin,nχ(k))n \ge \max(n_\text{min}, n_\chi(k)) for the number kk of occupied bins. And, for nn independent samples of a fixed distribution with kk bins of positive mass and nn set by equation (13), P(K(p^,p)≤ε)→1−δP(K(\hat p, p) \le \varepsilon) \to 1 - \delta as ε→0\varepsilon \to 0.

Each of these is a theorem with its assumptions. The use of the bound for a particle filter is a heuristic, for these reasons.

  • The bound is asymptotic. For small nn the true probability can differ from 1−δ1 - \delta.
  • It is about the histogram of the samples, not about the continuous belief, and the grid size sets what it measures.
  • The particles are drawn from the predicted belief and weighted afterwards, so the histogram that the bound controls is that of the proposal, not that of the posterior.
  • kk is counted from the samples themselves, and it grows while they are drawn.
  • A bound on the error of one step does not bound the error over many steps. Fox (2003) states that the approach is not guaranteed not to diverge.
Proof: KLD-sampling stops at its bound, and the bound gives the coverage 1 - delta asymptoticallyfull

Setting. One call of KLD-MCL with ε>0\varepsilon > 0, δ∈(0,1)\delta \in (0, 1) and integers 1≤nmin≤nmax1 \le n_\text{min} \le n_\text{max}. After nn draws, knk_n is the number of occupied bins and nχ(k)n_\chi(k) is the value of line L8, with nχ(k)=0n_\chi(k) = 0 for k≤1k \le 1. For Part 3, p=(p1,…,pk)p = (p_1, \dots, p_k) is a distribution over k≥2k \ge 2 bins with all pj>0p_j > 0, X1,X2,…X_1, X_2, \dots are independent draws of pp, NjN_j is the number of the first nn draws in bin jj, p^j=Nj/n\hat p_j = N_j / n and Kn=∑jp^jlog⁡(p^j/pj)K_n = \sum_j \hat p_j \log(\hat p_j / p_j), with 0log⁡0=00 \log 0 = 0. Let q=χk−1,1−δ2q = \chi^2_{k-1, 1-\delta} and n(ε)=⌈q/(2ε)⌉n(\varepsilon) = \lceil q / (2\varepsilon) \rceil.

Assumptions.

  • (A1) The previous weights are ≥0\ge 0 with a positive sum, so line L3 is defined.
  • (A2) For Part 3 only: the draws are independent and identically distributed with the distribution pp over the bins. This is an assumption about the samples, not something that the particle filter guarantees.

Claim.

  1. The loop ends after at most nmaxn_\text{max} iterations.
  2. If it ends with n<nmaxn < n_\text{max} draws, then n≥nminn \ge n_\text{min}, n≥nχ(kn)n \ge n_\chi(k_n), and the loop did not end after any earlier draw n′<nn' < n, that is, n′<nminn' < n_\text{min} or n′<nχ(kn′)n' < n_\chi(k_{n'}).
  3. Under (A2), 2nKn2 n K_n converges in distribution to the chi-square distribution with k−1k - 1 degrees of freedom as n→∞n \to \infty, and P(Kn(ε)≤ε)→1−δP(K_{n(\varepsilon)} \le \varepsilon) \to 1 - \delta as ε→0\varepsilon \to 0.

Proof.

Claim 1. Each iteration increases nn by 1 (line L9), starting from 0. The test of line L10 is true when n≥nmaxn \ge n_\text{max}, so the loop ends at the latest after iteration nmaxn_\text{max}.

Claim 2. The loop tests line L10 after each draw, with the current values of nn and nχn_\chi. Line L8 sets nχn_\chi to nχ(k)n_\chi(k) each time kk grows past 1, and nχn_\chi stays 0=nχ(k)0 = n_\chi(k) while k≤1k \le 1, so at each test nχ=nχ(kn)n_\chi = n_\chi(k_n). The loop ends at draw nn for the first nn where (n≥nχ(kn)(n \ge n_\chi(k_n) and n≥nmin)n \ge n_\text{min}) or n≥nmaxn \ge n_\text{max}. If n<nmaxn < n_\text{max}, the first part holds; the condition was false at each earlier n′n', which gives the last statement.

Claim 3. Let dj=p^j−pjd_j = \hat p_j - p_j, so ∑jdj=0\sum_j d_j = 0.

Step 1: Pearson's statistic. The vector Yn=n (p^−p)Y_n = \sqrt{n}\,(\hat p - p) is a normalized sum of nn independent copies of eX−pe_{X} - p, where eXe_X is the unit vector of the bin of XX. Its mean is 0 and its covariance is Σ=diag(p)−pp⊤\Sigma = \mathrm{diag}(p) - p p^\top. By the multivariate central limit theorem, Yn→Y∼N(0,Σ)Y_n \to Y \sim N(0, \Sigma) in distribution. Pearson's statistic is Xn2=∑jndj2/pj=Yn⊤DYnX_n^2 = \sum_j n d_j^2 / p_j = Y_n^\top D Y_n with D=diag(1/p)D = \mathrm{diag}(1/p). The map y↦y⊤Dyy \mapsto y^\top D y is continuous, so Xn2→Y⊤DYX_n^2 \to Y^\top D Y in distribution. The vector YY has the same distribution as D−1/2(I−ss⊤)GD^{-1/2} (I - s s^\top) G with s=(p1,…,pk)s = (\sqrt{p_1}, \dots, \sqrt{p_k}) and G∼N(0,I)G \sim N(0, I): indeed D−1/2(I−ss⊤)(I−ss⊤)D−1/2=D−1/2(I−ss⊤)D−1/2=diag(p)−pp⊤D^{-1/2}(I - s s^\top)(I - s s^\top)D^{-1/2} = D^{-1/2}(I - s s^\top) D^{-1/2} = \mathrm{diag}(p) - p p^\top, because s⊤s=1s^\top s = 1 makes I−ss⊤I - s s^\top a projection and D−1/2s=pD^{-1/2} s = p. Then Y⊤DY=G⊤(I−ss⊤)GY^\top D Y = G^\top (I - s s^\top) G, the squared length of the projection of a standard normal vector onto a subspace of dimension k−1k - 1. This has the chi-square distribution with k−1k - 1 degrees of freedom.

Step 2: 2nKn−Xn2→02 n K_n - X_n^2 \to 0 in probability. For ∣t∣≤1/2|t| \le 1/2, Taylor's theorem gives (1+t)log⁡(1+t)=t+t2/2+r(t)(1 + t)\log(1 + t) = t + t^2/2 + r(t) with ∣r(t)∣≤∣t∣3|r(t)| \le |t|^3. (The third derivative of (1+t)log⁡(1+t)(1+t)\log(1+t) is −1/(1+t)2-1/(1+t)^2, of absolute value at most 4 on ∣t∣≤1/2|t| \le 1/2, so ∣r(t)∣≤4∣t∣3/6≤∣t∣3|r(t)| \le 4 |t|^3 / 6 \le |t|^3.) With tj=dj/pjt_j = d_j / p_j,

Kn=∑jpj(1+tj)log⁡(1+tj)=∑jdj+∑jdj22pj+∑jpjr(tj)=Xn22n+∑jpjr(tj)K_n = \sum_j p_j (1 + t_j) \log(1 + t_j) = \sum_j d_j + \sum_j \frac{d_j^2}{2 p_j} + \sum_j p_j r(t_j) = \frac{X_n^2}{2n} + \sum_j p_j r(t_j)

on the event En={max⁡j∣tj∣≤1/2}E_n = \{\max_j |t_j| \le 1/2\}. On EnE_n, ∣2nKn−Xn2∣≤2n∑jpj∣tj∣3=2∑j∣Yn,j∣3/(n pj2)|2 n K_n - X_n^2| \le 2 n \sum_j p_j |t_j|^3 = 2 \sum_j |Y_{n,j}|^3 / (\sqrt{n}\, p_j^2). Since YnY_n converges in distribution, it is bounded in probability, so this tends to 0 in probability. By the law of large numbers p^→p\hat p \to p almost surely, so P(En)→1P(E_n) \to 1. Hence 2nKn−Xn2→02 n K_n - X_n^2 \to 0 in probability, and by Slutsky's theorem 2nKn→χk−122 n K_n \to \chi^2_{k-1} in distribution.

Step 3: the coverage. Let FnF_n be the distribution function of 2nKn2 n K_n and FF that of χk−12\chi^2_{k-1}. FF is continuous, so by Pólya's theorem sup⁡x∣Fn(x)−F(x)∣→0\sup_x |F_n(x) - F(x)| \to 0. As ε→0\varepsilon \to 0, n=n(ε)→∞n = n(\varepsilon) \to \infty, and xε=2n(ε) εx_\varepsilon = 2 n(\varepsilon)\, \varepsilon lies in [q,q+2ε)[q, q + 2\varepsilon), so xε→qx_\varepsilon \to q. Then

∣P(Kn≤ε)−(1−δ)∣=∣Fn(xε)−F(q)∣≤sup⁡x∣Fn(x)−F(x)∣+∣F(xε)−F(q)∣→0,|P(K_n \le \varepsilon) - (1 - \delta)| = |F_n(x_\varepsilon) - F(q)| \le \sup_x |F_n(x) - F(x)| + |F(x_\varepsilon) - F(q)| \to 0,

since F(q)=1−δF(q) = 1 - \delta by the definition of qq and FF is continuous. ■\blacksquare

What this does not show. Claim 3 is a limit; it gives no error bound for a fixed nn. The code uses the Wilson-Hilferty approximation of qq, which the tests compare with the exact quantile. In the particle filter, the samples are drawn from the predicted belief and weighted afterwards, the number of bins kk is counted from the samples, and the errors of successive steps add up, so the claim does not bound the error of the filter. That use is a heuristic.

Complexity

Let NN be the size of the previous set and nn the number of new particles.

  • Building the cumulative weights: O(N)O(N).
  • Each draw in line L3 by binary search: O(log⁡N)O(\log N). Each motion sample: O(1)O(1). Each weight: O(D)O(D).
  • Each bin test: O(1)O(1) expected time with a hash set.
  • Total per step: O(N+nlog⁡N+nD)O(N + n \log N + n D). Space: O(N+n+k)O(N + n + k).

The point is that nn adapts: it is about (k−1)/(2ε)(k-1)/(2\varepsilon) for large kk, and max⁡(nmin,nχ(k))\max(n_\text{min}, n_\chi(k)) in general. During tracking, kk is small and nn can be one or two orders of magnitude below the nn needed for global localization.

Properties

  • Adaptive. The number of particles follows the spread of the belief, as measured by the number of occupied bins.
  • Two parameters with meaning. ε\varepsilon and δ\delta replace the number of particles, which is hard to choose. The grid size is a third parameter, and it matters as much.
  • No guarantee to find the pose. Like plain MCL, it can lose the true pose. When the belief is concentrated at a wrong pose, kk is small and so is nn, which makes recovery harder. Random particles, as in augmented MCL, help.
  • Monotone bound. nχ(k)n_\chi(k) increases with kk and with 1/ε1/\varepsilon, and nχ(k)n_\chi(k) for 2ε2\varepsilon is half of that for ε\varepsilon.

Variants and improvements

  • Exact quantile. Compute χk−1,1−δ2\chi^2_{k-1, 1-\delta} exactly, for example by bisection on the regularized incomplete gamma function, as the test does. For k≥5k \ge 5 the gain is under 0.5 percent.
  • Bins by tree. Instead of a fixed grid, count leaves of a kd-tree or of a multi-resolution grid to adapt the bin size.
  • Adaptive resampling. Combine KLD-sampling with resampling only when the effective sample size is low.
  • Random particles. Add a few random poses at each step, as in augmented MCL, so that a wrong concentrated belief can still recover.

When to use it

Use KLD-sampling in Monte Carlo localization when the robot has phases with very different uncertainty, such as a global start and long tracking, and computation is limited. The gain is large when the map is large compared with the bin size. When the belief always stays concentrated, a fixed small number of particles is as good and simpler.

Pitfalls

  • Bins too large. With large bins, a tracked belief occupies one or two bins, nn drops to nminn_\text{min}, and the filter can lose the true pose. With bins too small, kk grows with nn and the loop can run to nmaxn_\text{max}.
  • Heading bins. The grid must include the heading. A 2D position grid alone hides spread in the heading.
  • The printed loop condition. Copying the "and" of Table 2 in Fox (2003) gives a sampler that stops after one particle. Use "or" for the continue condition, or "and" for the stop condition as in line L10.
  • Reading the bound as a guarantee. The probability 1−δ1 - \delta is asymptotic and about the histogram of the proposal. It does not mean that the filter keeps the error of the belief below ε\varepsilon.
  • No upper limit. Without nmaxn_\text{max}, a belief spread over a very large map can make the loop draw more particles than fit in memory.

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.

kld_sampling.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/kld-sampling/. The authors are listed in prov/ZKY15F.jsonl.

"""KLD-sampling: Monte Carlo localization with an adaptive number of particles.

The notation follows Fox (2003) and Thrun, Burgard and Fox (2005), Section 8.3.7.
A belief is a list of (pose, weight) pairs; the weights need not sum to 1.
The models are callables:

  sample_motion(rng, x, u)   one draw of x_t from p(x_t | u_t, x_{t-1} = x, m)
  likelihood(z, x)           p(z_t | x_t = x, m), a number >= 0
  bin_of(x)                  a hashable key of the grid bin that holds x

rng is a random.Random.
"""

import bisect
import math
from statistics import NormalDist


def kld_bound(k, epsilon, delta):
    """Return the number of samples of the KLD bound for k occupied bins.

    n = chi^2_{k-1, 1-delta} / (2 epsilon), with the quantile of the
    chi-square distribution approximated by Wilson and Hilferty:
    n = (k-1) / (2 epsilon) * (1 - 2/(9(k-1)) + sqrt(2/(9(k-1))) z_{1-delta})^3.
    For k <= 1 the bound is 0. The value is a real number; the sampler
    stops at the first integer count that reaches it.
    """
    if not (epsilon > 0.0 and 0.0 < delta < 1.0):
        raise ValueError("need epsilon > 0 and 0 < delta < 1")
    if k <= 1:
        return 0.0
    z = NormalDist().inv_cdf(1.0 - delta)
    a = 2.0 / (9.0 * (k - 1))
    return (k - 1) / (2.0 * epsilon) * (1.0 - a + math.sqrt(a) * z) ** 3


def kld_mcl(belief, u, z, sample_motion, likelihood, bin_of, rng, epsilon=0.05, delta=0.01, n_min=10, n_max=100000):
    """One step of KLD-sampling MCL.

    Draw particles from the previous weighted belief one at a time, move
    them, weight them and count the occupied bins, until the number of
    particles reaches both the KLD bound for the current number of bins
    and n_min, or reaches n_max. Return the new list of (pose, weight).
    """
    if not belief:
        raise ValueError("empty belief")
    if not 1 <= n_min <= n_max:
        raise ValueError("need 1 <= n_min <= n_max")
    cum, total = [], 0.0
    for _, w in belief:
        if w < 0.0:
            raise ValueError("negative weight")
        total += w
        cum.append(total)
    if total <= 0.0:
        raise ValueError("every particle has weight 0")
    new, bins = [], set()  # @line L1
    n, n_chi, k = 0, 0.0, 0
    while True:  # @line L2
        i = bisect.bisect_right(cum, rng.random() * total)  # @line L3
        i = min(i, len(belief) - 1)
        x = sample_motion(rng, belief[i][0], u)  # @line L4
        new.append((x, likelihood(z, x)))  # @line L5
        b = bin_of(x)
        if b not in bins:  # @line L6
            bins.add(b)  # @line L7
            k += 1
            if k > 1:
                n_chi = kld_bound(k, epsilon, delta)  # @line L8
        n += 1  # @line L9
        if (n >= n_chi and n >= n_min) or n >= n_max:  # @line L10
            return new  # @line L11
test_kld_sampling.py 151 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/kld-sampling/. The authors are listed in prov/ZKY15F.jsonl.

import bisect
import math
import random

import pytest

from kld_sampling import kld_bound, kld_mcl


def gamma_p(a, x):
    """The regularized lower incomplete gamma function P(a, x), by its series."""
    if x <= 0.0:
        return 0.0
    term = 1.0 / a
    s = term
    n = 0
    while abs(term) > 1e-17 * abs(s):
        n += 1
        term *= x / (a + n)
        s += term
    return s * math.exp(-x + a * math.log(x) - math.lgamma(a))


def chi2_quantile(dof, p):
    """The p quantile of the chi-square distribution, by bisection on its CDF."""
    lo, hi = 0.0, dof + 20.0 * math.sqrt(dof) + 50.0
    for _ in range(60):
        mid = (lo + hi) / 2.0
        if gamma_p(dof / 2.0, mid / 2.0) < p:
            lo = mid
        else:
            hi = mid
    return (lo + hi) / 2.0


def test_chi2_quantile_helper_matches_known_values():
    assert chi2_quantile(1, 0.99) == pytest.approx(6.635, abs=1e-3)
    assert chi2_quantile(2, 0.99) == pytest.approx(9.210, abs=1e-3)
    assert chi2_quantile(3, 0.95) == pytest.approx(7.815, abs=1e-3)


def test_wilson_hilferty_is_close_to_the_exact_bound():
    eps = 0.05
    for delta in (0.01, 0.05, 0.1):
        for k in list(range(2, 12)) + [20, 50, 100, 300, 1000]:
            exact = chi2_quantile(k - 1, 1.0 - delta) / (2.0 * eps)
            # the approximation is worst for 1 degree of freedom
            rel = 0.03 if k == 2 else (0.015 if k <= 4 else 0.005)
            assert kld_bound(k, eps, delta) == pytest.approx(exact, rel=rel)


def test_bound_grows_with_k_and_shrinks_with_epsilon():
    values = [kld_bound(k, 0.05, 0.01) for k in range(1, 200)]
    assert values[0] == 0.0
    assert all(a < b for a, b in zip(values, values[1:]))
    assert kld_bound(20, 0.1, 0.01) == pytest.approx(kld_bound(20, 0.05, 0.01) / 2.0)
    # for large k, the bound is about (k - 1) / (2 epsilon)
    assert kld_bound(5001, 0.05, 0.01) / (5000 / 0.1) == pytest.approx(1.0, abs=0.05)
    with pytest.raises(ValueError):
        kld_bound(5, 0.0, 0.01)


def kl(p_hat, p):
    return sum(a * math.log(a / b) for a, b in zip(p_hat, p) if a > 0.0)


def test_bound_gives_the_coverage_asymptotically():
    # Draw n = the bound samples from a fixed distribution over k bins.
    # The KL divergence from the histogram to the true distribution is at
    # most epsilon in about 1 - delta of the trials (a large-n result).
    rng = random.Random(4)
    p = [0.05, 0.05, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.2]
    k, eps, delta = len(p), 0.05, 0.1
    n = math.ceil(kld_bound(k, eps, delta))
    cum = [sum(p[: i + 1]) for i in range(k)]
    trials, good = 1500, 0
    for _ in range(trials):
        c = [0] * k
        for _ in range(n):
            c[min(bisect.bisect_left(cum, rng.random()), k - 1)] += 1
        if kl([v / n for v in c], p) <= eps:
            good += 1
    assert 0.86 <= good / trials <= 0.94


# A ring of 30 m with a color in each 1 m cell; the bins are the cells.
C = 30
_R = random.Random(3)
COLORS = [_R.randrange(4) for _ in range(C)]


def color(x):
    return COLORS[int(x) % C]


def likelihood(z, x):
    return 0.85 if color(x) == z else 0.05


def motion(rng, x, u):
    return (x + u + rng.gauss(0.0, 0.1)) % C


def sense(rng, x):
    if rng.random() < 0.85:
        return color(x)
    return rng.choice([c for c in range(4) if c != color(x)])


def bin_of(x):
    return int(x * 2.0)  # bins of 0.5 m


def test_particles_shrink_when_the_belief_concentrates():
    rng = random.Random(2)
    belief = [(rng.uniform(0, C), 1.0) for _ in range(5000)]
    truth = 0.3
    sizes = []
    for _ in range(25):
        truth = motion(rng, truth, 1.0)
        belief = kld_mcl(belief, 1.0, sense(rng, truth), motion, likelihood, bin_of, rng)
        sizes.append(len(belief))
    assert sizes[0] > 800  # the global phase occupies all 60 bins: the bound is 872
    assert max(sizes[-5:]) < 200  # tracking occupies a few bins
    mean = sum(x * w for x, w in belief) / sum(w for _, w in belief)
    assert abs(mean - truth) < 0.5


def test_n_min_and_n_max():
    rng = random.Random(0)
    belief = [(5.2, 1.0)]
    # a still robot with no noise keeps one bin, so n_min particles are drawn
    out = kld_mcl(belief, 0.0, 0, lambda r, x, u: x, likelihood, bin_of, rng, n_min=10)
    assert len(out) == 10
    belief = [(rng.uniform(0, C), 1.0) for _ in range(100)]
    out = kld_mcl(belief, 0.0, 0, lambda r, x, u: r.uniform(0, 1000), likelihood, lambda x: int(x), rng, n_max=500)
    assert len(out) == 500
    with pytest.raises(ValueError):
        kld_mcl([(0.0, 0.0)], 0.0, 0, motion, likelihood, bin_of, rng)


def test_the_count_stops_at_the_bound():
    # The samples fill 20 bins in turn, so k reaches 20 after 20 samples and
    # the sampler stops at the first count that reaches the bound for k = 20.
    rng = random.Random(1)
    counter = iter(range(10 ** 6))
    out = kld_mcl([(0.0, 1.0)], 0.0, 0, lambda r, x, u: next(counter), lambda z, x: 1.0, lambda x: x % 20, rng, epsilon=0.05, delta=0.05)
    assert len(out) == math.ceil(kld_bound(20, 0.05, 0.05))

History

Fox presented KLD-sampling at a conference in 2001 and in a journal article in 2003, with experiments in Monte Carlo localization where, in his measurements, the adaptive filter needed far fewer particles than a filter of fixed size for the same accuracy. Thrun, Burgard and Fox (2005) include it in Chapter 8 as a standard part of MCL. Its form of the bound, a chi-square quantile in the number of occupied bins, comes from the classical asymptotic theory of the likelihood ratio and of Pearson's chi-square statistic.

References

  1. Dieter Fox, Adapting the sample size in particle filters through KLD-sampling, The International Journal of Robotics Research 22(12), 2003, pages 985 to 1003, the bound of equation (13), the Wilson-Hilferty form of equation (14), the KLD-sampling algorithm of Table 2 and the localization experiments
  2. Sebastian Thrun, Wolfram Burgard and Dieter Fox, Probabilistic Robotics, MIT Press, 2005, Chapter 8, Section 8.3.7 (KLD-sampling)

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.per_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
  • at least three sources
  • a scene preset for the example