Algorithm Search⌘K

Algorithmcore

Monte Carlo localization

Also called particle filter localization.

Represents the pose belief by particles that the motion model moves and the sensor model weights, then resamples them. Augmented MCL adds random poses to recover.

Time
O(T N D) totalO(N D) per_step
Space
O(N) extra
Where
D = the cost of one evaluation of the measurement model; N = the number of particles; T = the number of time steps
Properties
randomizednot exactonlinerandomizedrecursive
Origin
Frank Dellaert, Dieter Fox, Wolfram Burgard, Sebastian Thrun, 1999

Monte Carlo localization (MCL) is the particle filter applied to mobile robot localization. The belief over the pose is a set of NN particles, each a pose hypothesis. At each step every particle is moved by a draw from the motion model, weighted by the likelihood of the reading under the sensor model, and the set is resampled in proportion to the weights. The particles collect where the readings agree with the map, so the belief can have one peak, many peaks or none. This makes MCL usable for global localization, which a Gaussian filter cannot do, at a cost that grows with NN and not with the size of the map. Augmented MCL adds random particles when the weights drop, a heuristic that lets the robot recover from a kidnapping.

In plain words

The robot keeps many guesses of where it is. When it drives, each guess drives too, with a little random error, because the real wheels also slip. When it takes a reading, each guess gets a score: how well would the reading match the map if the robot were there? Then the robot makes a new set of guesses by copying good guesses many times and dropping bad ones. After a few steps the guesses gather around the true pose. If all scores suddenly become bad, the robot may have been moved, so it adds some guesses at random places.

The problem

The input is a map mm, a motion model p(xt∣ut,xt−1,m)p(x_t \mid u_t, x_{t-1}, m) that can be sampled, a measurement model p(zt∣xt,m)p(z_t \mid x_t, m) that can be evaluated, an initial set of particles, and the controls and readings ut,ztu_t, z_t for t=1,2,…t = 1, 2, \dots. The output at each step is a set Xt={xt[1],…,xt[N]}\mathcal{X}_t = \{x_t^{[1]}, \dots, x_t^{[N]}\} whose empirical distribution approximates the posterior p(xt∣z1:t,u1:t,m)p(x_t \mid z_{1:t}, u_{1:t}, m) of the Bayes filter. For global localization, the initial particles are uniform over the free space. For tracking, they are drawn around the known start pose.

Typical models are the odometry motion model or the velocity motion model for utu_t, and the beam model or the likelihood field for a range scan ztz_t. Their noise parameters are fitted to data. A scan model usually treats the beams as independent given the pose, which is an approximation.

The algorithm

  1. MCL(X_{t-1}, u_t, z_t, m) ▷ N particles; w_slow, w_fast persist
  2. 1for k ← 1 to N do
  3. 2x̄^[k] ← sample of p(x_t | u_t, x_{t-1}^[k], m)
  4. 3w^[k] ← p(z_t | x̄^[k], m)
  5. 4w_avg ← (1/N) Σ_k w^[k]
  6. 5w_slow ← w_slow + α_slow (w_avg - w_slow); w_fast ← w_fast + α_fast (w_avg - w_fast) ▷ augmented only
  7. 6X_t ← N draws from {x̄^[k]} with probabilities w^[k] / Σ w, by the low variance sampler
  8. 7replace each particle of X_t by a random pose with probability max(0, 1 - w_fast / w_slow) ▷ augmented only
  9. 8return X_t

Plain MCL is lines L1 to L4, L6 and L8 (Thrun et al., Section 8.3). Line L2 is the proposal: the particles are drawn from the predicted belief. Line L3 is the importance weight, the ratio of the target (the posterior) to the proposal, up to a constant. Line L6 is the resampling step. The code uses the low variance sampler of Thrun et al. (Section 4.3), which is systematic sampling: one uniform r∈[0,1/N)r \in [0, 1/N), and the NN points r+i/Nr + i/N select the particles through the cumulative normalized weights. A particle with normalized weight w~\tilde w is copied ⌊Nw~⌋\lfloor N \tilde w \rfloor or ⌈Nw~⌉\lceil N \tilde w \rceil times.

Augmented MCL. Lines L5 and L7 follow Thrun et al. (Section 8.3.5), with 0≤αslow≪αfast0 \le \alpha_\text{slow} \ll \alpha_\text{fast}. The mean weight wavgw_\text{avg} estimates p(zt∣z1:t−1,u1:t,m)p(z_t \mid z_{1:t-1}, u_{1:t}, m), the probability of the reading under the current belief. When the short term average wfastw_\text{fast} falls below the long term average wsloww_\text{slow}, the readings fit the belief worse than they used to, and a fraction of the particles restarts at random poses. Thrun et al. draw each new particle either at random or from the weights. The code first resamples and then replaces, which gives the same probability per particle. This rule is a heuristic: it has no guarantee to find the true pose, and the rates are set by hand.

Example

One resampling step. A ring of 30 cells has a color in each cell. The sensor reads the right color with probability 0.850.85 and each of the 3 other colors with probability 0.050.05. After line L2, five particles are at cells 5, 10, 11, 14 and 21, whose colors are 0, 3, 3, 1 and 2. The reading is z=3z = 3.

particle cell color ww (L3) w~=w/1.85\tilde w = w / 1.85 cumulative copies
1 5 0 0.05 0.027 0.027 0
2 10 3 0.85 0.459 0.486 2
3 11 3 0.85 0.459 0.946 3
4 14 1 0.05 0.027 0.973 0
5 21 2 0.05 0.027 1.000 0

With r=0.1r = 0.1, the points are 0.1,0.3,0.5,0.7,0.90.1, 0.3, 0.5, 0.7, 0.9. The first two fall in the interval (0.027,0.486](0.027, 0.486] of particle 2 and the other three in (0.486,0.946](0.486, 0.946] of particle 3, so Xt={10,10,11,11,11}\mathcal{X}_t = \{10, 10, 11, 11, 11\}. The expected copies are 5×0.459=2.305 \times 0.459 = 2.30 for each of particles 2 and 3; the sampler gives 2 or 3. The mean weight is wavg=0.37w_\text{avg} = 0.37.

Against the exact filter. On the same ring, with the motion of 1 cell ahead with probability 0.80.8 and of 0 or 2 cells with probability 0.10.1 each, the test runs MCL with N=3000N = 3000 particles from a uniform start and the exact histogram filter side by side. Over 8 steps, the total variation distance between the particle histogram and the exact belief stays below 0.080.08, while the exact belief concentrates to more than 0.80.8 on one cell. This is a measurement for one seed.

Kidnapping. With N=300N = 300, the robot is moved 13 cells ahead after step 20. With αslow=0.05\alpha_\text{slow} = 0.05 and αfast=0.5\alpha_\text{fast} = 0.5, the injection probability rises to about 0.30.3 to 0.40.4 in the steps just after the kidnapping, and the most frequent cell of augmented MCL is the true cell in 21 of steps 41 to 70. Plain MCL has no particle near the new pose and gets the true cell in none of those steps. This is a measurement for one seed; for other seeds, plain MCL sometimes recovers by chance through its motion noise.

Correctness

MCL does not compute the posterior exactly; it approximates it with random particles. The correctness proof shows the parts that are exact. Given the particles Xt−1\mathcal{X}_{t-1}, the weighted particles of lines L1 to L3 are an unbiased importance sample of the Bayes update of the empirical belief: E[1N∑kw[k]f(xˉ[k])]=1N∑k∫f(x) p(zt∣x,m) p(x∣ut,xt−1[k],m) dxE[\tfrac{1}{N} \sum_k w^{[k]} f(\bar x^{[k]})] = \tfrac{1}{N} \sum_k \int f(x)\, p(z_t \mid x, m)\, p(x \mid u_t, x_{t-1}^{[k]}, m)\, dx for each bounded ff. The low variance sampler copies each particle Nw~N \tilde w times on average, and ⌊Nw~⌋\lfloor N \tilde w \rfloor or ⌈Nw~⌉\lceil N \tilde w \rceil times always. If the particles Xt−1\mathcal{X}_{t-1} are independent draws of the prior belief, the ratio ∑kw[k]f(xˉ[k])/∑kw[k]\sum_k w^{[k]} f(\bar x^{[k]}) / \sum_k w^{[k]} converges almost surely to the posterior mean of ff as N→∞N \to \infty.

Over many steps, the resampled particles are no longer independent. That the error over a fixed number of steps still goes to 0 as N→∞N \to \infty is a theorem of the theory of sequential Monte Carlo under conditions such as bounded likelihoods; the proof here does not cover it. For a fixed NN, nothing guarantees that a particle lies near the true pose.

Proof: One step of MCL is an unbiased importance sample of the Bayes update, and its resampling is unbiasedfull

Setting. One step of plain MCL takes particles xt−1[1],…,xt−1[N]x_{t-1}^{[1]}, \dots, x_{t-1}^{[N]}, a control u=utu = u_t and a reading z=ztz = z_t. Write π(x∣x′)\pi(x \mid x') for the density of the motion model p(xt=x∣u,xt−1=x′,m)p(x_t = x \mid u, x_{t-1} = x', m) and ℓ(x)=p(z∣xt=x,m)\ell(x) = p(z \mid x_t = x, m) for the measurement model. Line L2 draws xˉ[k]∼π(⋅∣xt−1[k])\bar x^{[k]} \sim \pi(\cdot \mid x_{t-1}^{[k]}), independently for each kk. Line L3 sets w[k]=ℓ(xˉ[k])w^{[k]} = \ell(\bar x^{[k]}). Line L6 resamples with the low variance sampler: with W=∑kw[k]W = \sum_k w^{[k]}, w~k=w[k]/W\tilde w_k = w^{[k]} / W, C0=0C_0 = 0 and Ck=w~1+⋯+w~kC_k = \tilde w_1 + \dots + \tilde w_k, it draws rr uniform in [0,1/N)[0, 1/N), and for i=0,…,N−1i = 0, \dots, N-1 it outputs the particle kk with Ck−1<r+i/N≤CkC_{k-1} < r + i/N \le C_k.

Assumptions.

  • (A1) ℓ\ell is measurable, 0≤ℓ≤L0 \le \ell \le L for a constant LL.
  • (A2) W>0W > 0. (If W=0W = 0, plain MCL stops with an error.)
  • (A3) For Claim 3 only: the xt−1[k]x_{t-1}^{[k]} are independent draws of a density bb (the prior belief), and η=∫ℓ(x) bˉ(x) dx>0\eta = \int \ell(x)\, \bar b(x)\, dx > 0, where bˉ(x)=∫π(x∣x′) b(x′) dx′\bar b(x) = \int \pi(x \mid x')\, b(x')\, dx' is the predicted belief.

The arithmetic is exact; rounding is not part of the claims.

Claim.

  1. For each bounded measurable ff, given the particles xt−1[⋅]x_{t-1}^{[\cdot]},
E[1N∑kw[k]f(xˉ[k])]=1N∑k∫f(x) ℓ(x) π(x∣xt−1[k]) dx.E\Big[\frac{1}{N} \sum_k w^{[k]} f(\bar x^{[k]})\Big] = \frac{1}{N} \sum_k \int f(x)\, \ell(x)\, \pi(x \mid x_{t-1}^{[k]})\, dx.

The right side is ∫f ℓ bˉN\int f\, \ell\, \bar b_N, the unnormalized Bayes update of the empirical belief bNb_N that puts mass 1/N1/N on each xt−1[k]x_{t-1}^{[k]}, after its prediction bˉN(x)=1N∑kπ(x∣xt−1[k])\bar b_N(x) = \frac{1}{N} \sum_k \pi(x \mid x_{t-1}^{[k]}). 2. Given the weighted particles, the low variance sampler outputs particle kk exactly nkn_k times with nk∈{⌊Nw~k⌋,⌈Nw~k⌉}n_k \in \{\lfloor N \tilde w_k \rfloor, \lceil N \tilde w_k \rceil\}, and E[nk]=Nw~kE[n_k] = N \tilde w_k. So for each ff, E[1N∑knkf(xˉ[k])]=∑kw~kf(xˉ[k])E[\frac{1}{N} \sum_k n_k f(\bar x^{[k]})] = \sum_k \tilde w_k f(\bar x^{[k]}). 3. Under (A3), as N→∞N \to \infty,

∑kw[k]f(xˉ[k])∑kw[k]→∫f(x) ℓ(x) bˉ(x) dxη=E[f(xt)∣z1:t,u1:t,m]\frac{\sum_k w^{[k]} f(\bar x^{[k]})}{\sum_k w^{[k]}} \to \frac{\int f(x)\, \ell(x)\, \bar b(x)\, dx}{\eta} = E[f(x_t) \mid z_{1:t}, u_{1:t}, m]

almost surely, where the right side is the posterior of the Bayes filter with prior bb.

Proof.

Claim 1. Fix kk. Given xt−1[k]x_{t-1}^{[k]}, the draw xˉ[k]\bar x^{[k]} has the density π(⋅∣xt−1[k])\pi(\cdot \mid x_{t-1}^{[k]}). The function fℓf \ell is bounded by (A1), so its expectation exists and is E[w[k]f(xˉ[k])]=E[ℓ(xˉ[k])f(xˉ[k])]=∫f(x) ℓ(x) π(x∣xt−1[k]) dxE[w^{[k]} f(\bar x^{[k]})] = E[\ell(\bar x^{[k]}) f(\bar x^{[k]})] = \int f(x)\, \ell(x)\, \pi(x \mid x_{t-1}^{[k]})\, dx. Sum over kk, divide by NN and use the linearity of the expectation. The last sentence of the claim is the definition of bˉN\bar b_N and the update step of the Bayes filter before normalization.

Claim 2. By (A2) the w~k\tilde w_k are defined, are ≥0\ge 0 and sum to 1, so the half-open intervals Ik=(Ck−1,Ck]I_k = (C_{k-1}, C_k] for k=1,…,Nk = 1, \dots, N are disjoint and cover (0,1](0, 1]. The points ui=r+i/Nu_i = r + i/N, i=0,…,N−1i = 0, \dots, N-1, lie in [0,1)[0, 1). The point ui=0u_i = 0 occurs only if r=0r = 0, an event of probability 0; the code then gives it to the first particle with Ck≥0C_k \ge 0, which does not change the claims below for r>0r > 0. So, almost surely, each point lies in exactly one IkI_k, and nkn_k is the number of points in IkI_k.

Let r>0r > 0. The points of the infinite progression r+i/Nr + i/N, i∈Zi \in \mathbb{Z}, that lie in (0,1](0, 1] are exactly u0,…,uN−1u_0, \dots, u_{N-1}, because u−1=r−1/N<0u_{-1} = r - 1/N < 0 and uN=r+1>1u_N = r + 1 > 1. So nkn_k is the number of points of the infinite progression in Ik=(a,a+w~k]I_k = (a, a + \tilde w_k] with a=Ck−1a = C_{k-1}. The condition a<r+i/N≤a+w~ka < r + i/N \le a + \tilde w_k is y<i≤y+Nw~ky < i \le y + N \tilde w_k with y=N(a−r)y = N(a - r), so

nk=⌊y+Nw~k⌋−⌊y⌋.n_k = \lfloor y + N \tilde w_k \rfloor - \lfloor y \rfloor.

For real yy and s≥0s \ge 0, ⌊y+s⌋−⌊y⌋\lfloor y + s \rfloor - \lfloor y \rfloor is ⌊s⌋\lfloor s \rfloor or ⌊s⌋+1\lfloor s \rfloor + 1, and it equals ss if ss is an integer. So nk∈{⌊Nw~k⌋,⌈Nw~k⌉}n_k \in \{\lfloor N \tilde w_k \rfloor, \lceil N \tilde w_k \rceil\}.

For the mean, rr is uniform in [0,1/N)[0, 1/N). The point uiu_i is uniform in [i/N,(i+1)/N)[i/N, (i+1)/N), with the density NN there. So P(ui∈Ik)=N⋅∣Ik∩[i/N,(i+1)/N)∣P(u_i \in I_k) = N \cdot |I_k \cap [i/N, (i+1)/N)|, and

E[nk]=∑i=0N−1N⋅∣Ik∩[i/N,(i+1)/N)∣=N⋅∣Ik∩[0,1)∣=Nw~k.E[n_k] = \sum_{i=0}^{N-1} N \cdot |I_k \cap [i/N, (i+1)/N)| = N \cdot |I_k \cap [0, 1)| = N \tilde w_k.

The last statement of the claim follows by linearity: E[1N∑knkf(xˉ[k])]=1N∑kNw~kf(xˉ[k])E[\frac{1}{N} \sum_k n_k f(\bar x^{[k]})] = \frac{1}{N} \sum_k N \tilde w_k f(\bar x^{[k]}).

Claim 3. Under (A3), the pairs (xt−1[k],xˉ[k])(x_{t-1}^{[k]}, \bar x^{[k]}) are independent and identically distributed, and each xˉ[k]\bar x^{[k]} has the density bˉ\bar b. The variables w[k]f(xˉ[k])w^{[k]} f(\bar x^{[k]}) and w[k]w^{[k]} are bounded by (A1), so by the strong law of large numbers

1N∑kw[k]f(xˉ[k])→∫f ℓ bˉand1N∑kw[k]→∫ℓ bˉ=η\frac{1}{N} \sum_k w^{[k]} f(\bar x^{[k]}) \to \int f\, \ell\, \bar b \quad \text{and} \quad \frac{1}{N} \sum_k w^{[k]} \to \int \ell\, \bar b = \eta

almost surely. Since η>0\eta > 0, the ratio converges almost surely to ∫f ℓ bˉ/η\int f\, \ell\, \bar b / \eta. By the Bayes filter, the posterior density is ℓ(x) bˉ(x)/η\ell(x)\, \bar b(x) / \eta, so this limit is the posterior mean of ff. ■\blacksquare

What this does not show. After a resampling step the particles are not independent, so Claim 3 does not apply to step t+1t + 1 directly. Convergence over many steps is a theorem of the theory of sequential Monte Carlo, under conditions such as bounded likelihoods, and is not proved here. Augmented MCL changes the particle set on purpose, so its particles do not approximate the Bayes posterior; Claims 1 and 2 hold for its lines L1 to L6.

Complexity

One step evaluates the motion sampler and the measurement model once per particle and resamples in one pass.

  • Time: O(ND)O(N D) per step, where DD is the cost of the measurement model. For the beam model with BB beams ray cast in a grid, DD is O(B)O(B) times the cost of a ray cast; the likelihood field makes each beam O(1)O(1) after a precomputed distance transform.
  • Space: O(N)O(N) for the particles, plus the map.

The number of particles that is enough depends on the problem. Global localization in a large building needs far more particles than tracking. KLD-sampling adapts NN at each step.

Properties

  • Multimodal. The particles can represent any distribution, so MCL handles global localization and symmetric maps.
  • Any models. The motion model must only be sampled and the measurement model must only be evaluated, up to a constant factor. Neither needs to be linear or Gaussian.
  • Randomized. Two runs with the same data give different particle sets. Tests need fixed seeds.
  • Resampling adds variance. It removes particles of low weight, so it keeps the set useful, but it also loses diversity. Many implementations resample only when the effective sample size (∑w)2/∑w2(\sum w)^2 / \sum w^2 falls below a threshold.
  • Particle deprivation. For a fixed NN, there is a positive probability that no particle lies near the true pose, and plain MCL cannot recover from this. Augmented MCL and Mixture-MCL reduce this risk; they do not remove it.

Variants and improvements

  • Augmented MCL (Thrun et al., Section 8.3.5): random particles when wfast<wsloww_\text{fast} < w_\text{slow}, as above. A simpler form adds a fixed small fraction of random particles at each step.
  • Mixture-MCL (Thrun, Fox, Burgard and Dellaert, 2001): a part of the particles is drawn from the sensor model, that is, at poses that fit the reading, and weighted by the motion model. This works better when the sensor is accurate, where plain MCL gives most particles a weight near 0.
  • KLD-sampling (Fox, 2003): choose NN at each step from the number of grid bins that the particles occupy. See KLD-sampling.
  • Rao-Blackwellized filters: when a part of the state can be estimated in closed form given the rest, sample only the rest. FastSLAM uses this for the map. See the Rao-Blackwellized particle filter.
  • Smoother sensor models: with a very accurate sensor, the weights are almost all 0. A common rule of thumb is to inflate the sensor noise, or to raise the likelihood to a power below 1, so that the particles can follow it. This is a heuristic.

When to use it

Use MCL when the initial pose is unknown, when the map has repeated structure, when the robot may be kidnapped, or when the models are far from linear and Gaussian, for example a laser scan in a grid map. It is the usual choice for indoor robots with a laser scanner. Use EKF localization when the pose is known well, the map has distinct landmarks and the computation budget is small. Use Markov localization on a grid when the state space is small enough to enumerate and an exact belief is needed.

Pitfalls

  • Too few particles. The filter can converge to a wrong pose in a symmetric map, or lose the true pose in a large one. Check with many seeds, not one.
  • An overconfident sensor model. If p(z∣x)p(z \mid x) is too sharp, few particles get a weight above 0 and the set collapses to a few poses. Independent beams make the likelihood of a scan far too sharp; inflate the noise or use fewer beams.
  • All weights 0. If no particle explains the reading, line L6 cannot normalize. The code raises an error in plain MCL; augmented MCL keeps the moved particles and lets line L7 act.
  • Resampling with no motion. If the robot does not move, the particles do not spread, and repeated resampling with the same reading makes the set too narrow. Skip the update when the robot is still, as many systems do.
  • Angles. Average headings with atan2⁡\operatorname{atan2} of the mean sine and cosine, not with the arithmetic mean.
  • Rounding of weights. Products of many beam likelihoods underflow. Compute log weights and subtract the largest before taking the exponential.

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.

monte_carlo_localization.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/monte-carlo-localization/. The authors are listed in prov/GRKHHG.jsonl.

"""Monte Carlo localization (MCL) and augmented MCL.

The notation follows Thrun, Burgard and Fox (2005), Sections 8.3 and 8.3.5.
The belief is a list of N particles, each a pose. 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
  sample_pose(rng)           one pose drawn uniformly from the free space

A pose can be any value that these callables accept. rng is a random.Random.
"""

import robest


class Recovery:
    """The state of the random particle injection of augmented MCL.

    w_slow and w_fast are averages of the mean weight with the rates
    a_slow < a_fast. When the short term average falls below the long term
    average, a fraction max(0, 1 - w_fast / w_slow) of the new particles
    are random poses. This is a heuristic: it has no guarantee to find the
    true pose, and a_slow and a_fast are set by hand.
    """

    def __init__(self, a_slow, a_fast, sample_pose):
        if not 0.0 <= a_slow < a_fast <= 1.0:
            raise ValueError("need 0 <= a_slow < a_fast <= 1")
        self.a_slow = a_slow
        self.a_fast = a_fast
        self.sample_pose = sample_pose
        self.w_slow = 0.0
        self.w_fast = 0.0

    def observe(self, w_avg):
        """Update both averages with the mean weight of one step."""
        self.w_slow += self.a_slow * (w_avg - self.w_slow)
        self.w_fast += self.a_fast * (w_avg - self.w_fast)

    def p_random(self):
        """Return the probability to replace a new particle by a random pose."""
        if self.w_slow <= 0.0:
            return 0.0
        return max(0.0, 1.0 - self.w_fast / self.w_slow)


def mcl(particles, u, z, sample_motion, likelihood, rng, recovery=None):
    """One step of MCL, or of augmented MCL if recovery is a Recovery.

    Return (the new particles, the mean weight w_avg). Plain MCL raises
    ValueError if every weight is 0, because then no particle explains z.
    Augmented MCL then keeps the moved particles and lets the injection act.
    """
    n = len(particles)
    if n == 0:
        raise ValueError("no particles")
    moved, weights = [], []
    for x in particles:  # @line L1
        xm = sample_motion(rng, x, u)  # @line L2
        moved.append(xm)
        weights.append(likelihood(z, xm))  # @line L3
    w_avg = sum(weights) / n  # @line L4
    if recovery is not None:
        recovery.observe(w_avg)  # @line L5
    if w_avg <= 0.0:
        if recovery is None:
            raise ValueError("every particle has weight 0")
        weights = [1.0] * n
    new = [moved[i] for i in robest.low_variance_resample(rng, weights)]  # @line L6
    if recovery is not None:
        p = recovery.p_random()
        for k in range(n):  # @line L7
            if rng.random() < p:
                new[k] = recovery.sample_pose(rng)
    return new, w_avg  # @line L8
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_monte_carlo_localization.py 167 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/monte-carlo-localization/. The authors are listed in prov/GRKHHG.jsonl.

import math
import random

import pytest

import robest
from monte_carlo_localization import Recovery, mcl

# A ring of 30 cells. Each cell has a color in {0, 1, 2, 3}. The sensor reads
# the right color with probability 0.85, and each other color with 0.05.
# A control moves the robot 1 cell ahead with probability 0.8, 0 cells
# with 0.1 and 2 cells with 0.1.
C = 30
_R = random.Random(3)
COLORS = [_R.randrange(4) for _ in range(C)]
P_RIGHT = 0.85
MOVE = {0: 0.1, 1: 0.8, 2: 0.1}


def ring_likelihood(z, x):
    return P_RIGHT if COLORS[x] == z else (1.0 - P_RIGHT) / 3.0


def ring_motion(rng, x, u):
    r = rng.random()
    s = 0 if r < 0.1 else (1 if r < 0.9 else 2)
    return (x + u * s) % C


def ring_sense(rng, x):
    if rng.random() < P_RIGHT:
        return COLORS[x]
    return rng.choice([c for c in range(4) if c != COLORS[x]])


def histogram_step(bel, u, z):
    """The exact Bayes filter on the ring, for comparison."""
    pred = [0.0] * C
    for x in range(C):
        for s, p in MOVE.items():
            pred[(x + u * s) % C] += bel[x] * p
    post = [pred[x] * ring_likelihood(z, x) for x in range(C)]
    total = sum(post)
    return [p / total for p in post]


def counts(particles):
    c = [0] * C
    for x in particles:
        c[x] += 1
    return c


def test_mcl_approximates_the_exact_filter():
    rng = random.Random(0)
    n = 3000
    truth = 0
    bel = [1.0 / C] * C
    particles = [rng.randrange(C) for _ in range(n)]
    for _ in range(8):
        truth = ring_motion(rng, truth, 1)
        z = ring_sense(rng, truth)
        bel = histogram_step(bel, 1, z)
        particles, _ = mcl(particles, 1, z, ring_motion, ring_likelihood, rng)
        emp = [c / n for c in counts(particles)]
        tv = 0.5 * sum(abs(a - b) for a, b in zip(bel, emp))
        assert tv < 0.1
    assert max(bel) > 0.8  # the colors make the pose unique after 8 steps


def run_kidnapping(seed, recovery, n=300, steps=70, kidnap_at=20, jump=13):
    rng = random.Random(seed)
    truth = 0
    particles = [rng.randrange(C) for _ in range(n)]
    right = []
    p_random = []
    for t in range(steps):
        if t == kidnap_at:
            truth = (truth + jump) % C
        truth = ring_motion(rng, truth, 1)
        z = ring_sense(rng, truth)
        particles, _ = mcl(particles, 1, z, ring_motion, ring_likelihood, rng, recovery)
        c = counts(particles)
        right.append(max(range(C), key=lambda i: c[i]) == truth)
        if recovery is not None:
            p_random.append(recovery.p_random())
    return right, p_random


def test_augmented_mcl_recovers_from_a_kidnapping_and_plain_mcl_does_not():
    rec = Recovery(0.05, 0.5, lambda rng: rng.randrange(C))
    aug, p_random = run_kidnapping(0, rec)
    plain, _ = run_kidnapping(0, None)
    assert sum(aug[10:20]) >= 7 and sum(plain[10:20]) >= 7  # both track before the kidnapping
    assert sum(aug[40:]) >= 15  # of 30 steps
    assert sum(plain[40:]) <= 3
    assert max(p_random[20:25]) > 0.3  # the drop of the weights starts the injection
    # while it tracks, one wrong color can give a short burst, but few random particles on average
    assert sum(p_random[12:20]) / 8 < 0.05


def test_recovery_probability():
    rec = Recovery(0.1, 0.5, None)
    assert rec.p_random() == 0.0
    rec.observe(0.8)
    assert rec.w_slow == pytest.approx(0.08) and rec.w_fast == pytest.approx(0.4)
    assert rec.p_random() == 0.0  # w_fast > w_slow
    for _ in range(200):
        rec.observe(0.8)
    rec.observe(0.2)
    w_slow = 0.8 - 0.1 * 0.6
    w_fast = 0.8 - 0.5 * 0.6
    assert rec.p_random() == pytest.approx(1.0 - w_fast / w_slow, abs=1e-9)
    with pytest.raises(ValueError):
        Recovery(0.5, 0.1, None)


def test_plain_mcl_rejects_all_zero_weights():
    rng = random.Random(1)
    with pytest.raises(ValueError):
        mcl([0, 1, 2], 1, 0, ring_motion, lambda z, x: 0.0, rng)
    rec = Recovery(0.1, 0.5, lambda r: 99)
    rec.w_slow = rec.w_fast = 0.5
    new, w_avg = mcl([0, 1, 2], 1, 0, ring_motion, lambda z, x: 0.0, rng, rec)
    assert w_avg == 0.0 and len(new) == 3


# Global localization in a 10 m by 10 m room with 4 range beacons.
BEACONS = [(0.0, 0.0), (10.0, 0.0), (0.0, 10.0), (10.0, 10.0)]
SIGMA_R = 0.3


def plane_motion(rng, x, u):
    rot, trans = u
    th = robest.wrap_angle(x[2] + rot + rng.gauss(0.0, 0.05 + 0.05 * abs(rot)))
    d = trans + rng.gauss(0.0, 0.05 + 0.1 * abs(trans))
    return (x[0] + d * math.cos(th), x[1] + d * math.sin(th), th)


def plane_likelihood(z, x):
    p = 1.0
    for r, (bx, by) in zip(z, BEACONS):
        e = r - math.hypot(bx - x[0], by - x[1])
        p *= math.exp(-0.5 * e * e / (SIGMA_R * SIGMA_R))
    return p


def test_global_localization_with_range_beacons():
    rng = random.Random(7)
    n = 3000
    particles = [(rng.uniform(0, 10), rng.uniform(0, 10), rng.uniform(-math.pi, math.pi)) for _ in range(n)]
    truth = (2.0, 3.0, 0.0)
    controls = [(0.0, 1.0)] * 5 + [(math.pi / 2, 1.0)] + [(0.0, 1.0)] * 4
    for u in controls:
        rot, trans = u
        th = truth[2] + rot
        truth = (truth[0] + trans * math.cos(th), truth[1] + trans * math.sin(th), th)
        z = [math.hypot(bx - truth[0], by - truth[1]) + rng.gauss(0.0, SIGMA_R) for bx, by in BEACONS]
        particles, _ = mcl(particles, u, z, plane_motion, plane_likelihood, rng)
    mx = sum(p[0] for p in particles) / n
    my = sum(p[1] for p in particles) / n
    mth = math.atan2(sum(math.sin(p[2]) for p in particles), sum(math.cos(p[2]) for p in particles))
    assert math.hypot(mx - truth[0], my - truth[1]) < 0.4
    assert abs(robest.wrap_angle(mth - truth[2])) < 0.2

History

The particle filter came from the bootstrap filter of Gordon, Salmond and Smith (1993) and from related sampling methods in statistics and computer vision. Dellaert, Fox, Burgard and Thrun (1999) used it for mobile robot localization and called it Monte Carlo localization; it replaced the grids of Markov localization by a set of samples that follows the belief. Thrun, Fox, Burgard and Dellaert (2001) showed that plain MCL can fail with accurate sensors and proposed Mixture-MCL. Fox (2003) made the number of particles adaptive with KLD-sampling. Thrun, Burgard and Fox (2005) present MCL and augmented MCL in Chapter 8.

References

  1. Sebastian Thrun, Wolfram Burgard and Dieter Fox, Probabilistic Robotics, MIT Press, 2005, Chapter 4, Section 4.3 (the particle filter and the low variance sampler), and Chapter 8, Section 8.3 (Monte Carlo localization, its properties and random particle MCL in Section 8.3.5)
  2. Frank Dellaert, Dieter Fox, Wolfram Burgard and Sebastian Thrun, Monte Carlo localization for mobile robots, Proceedings of the IEEE International Conference on Robotics and Automation (ICRA), 1999, the sample-based representation of the pose belief and its update by the motion and sensor models
  3. Sebastian Thrun, Dieter Fox, Wolfram Burgard and Frank Dellaert, Robust Monte Carlo localization for mobile robots, Artificial Intelligence 128(1-2), 2001, pages 99 to 141, the failure of MCL with accurate sensors and small sample sets, and Mixture-MCL, which also samples poses from the sensor model

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.per_step
  • a full proof of time.total
  • 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