Algorithmcore
Histogram filter
Also called discrete Bayes filter, grid localization.
A Bayes filter over a fixed grid of cells that split a continuous state space. It can hold any belief shape, at a cost that grows with the number of cells.
- Solves
- Filtering
- Time
- O(T g^2) worstO(T g b) banded
- Space
- O(g) extra
- Where
- T = the number of time steps; b = the number of cells that one motion step can reach from a cell; g = the number of cells
- Model
- Real RAM
- Properties
- deterministicnot exactonlinerecursive
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Richard S. Bucy, Kenneth D. Senne, 1971
The histogram filter is the Bayes filter run on a fixed partition of a continuous state space into cells. It keeps one probability per cell, so it can hold a belief of any shape: one peak, several peaks, or almost no information. It is exact for the discrete model that the partition defines, and an approximation of the continuous model, with an error that depends on the cell size. For a robot pose in a known map it is grid Markov localization. One step costs time, or when a motion step can reach only cells, and memory.
In plain words
Cut the world into small boxes of equal size and give each box a number: the chance that the robot is in that box. When the robot moves, each box hands its number to the boxes that the robot can reach from it, more to the box where the move should end and less to its neighbors. When the robot measures something, each box multiplies its number by how well the measurement fits a robot at the middle of the box. Then all numbers are divided by their total, so they add up to one again. Smaller boxes give a more exact answer but take more work.
The problem
The state is continuous, for example the position of a robot on a line or its pose in a map. The model is the one of the Bayes filter: a motion model , a measurement model and a prior. The exact Bayes filter needs integrals over the state space, which have no closed form for most nonlinear models.
The histogram filter replaces the state space by cells that cover it and do not overlap. Let be a representative point of cell , usually its center. The belief is the list of the probabilities of the cells. Two approximations turn the model into a model on the cells (Thrun et al., Section 4.1):
- the transition is the probability that the motion model, started at , ends in cell ; on a line with Gaussian noise it is a difference of two values of the normal distribution function;
- the likelihood of cell is , the density at the representative point.
The output is the posterior of the cells under this discrete model.
The algorithm
HISTOGRAM-FILTER(p, u_t, z_t) ▷ p_i = P(x_{t-1} in cell i)- 1
for k = 1 to g do - 2
p̄_k ← Σ_{i=1}^{g} P(k | u_t, i) p_i ▷ prediction - 3
q_k ← p(z_t | x_t = c_k) p̄_k for k = 1, ..., g ▷ correction - 4
η ← 1 / Σ_k q_k - 5
return the list with entries η q_k
The lines are those of the Bayes filter, with sums over cells. The work is in building the model on the cells. The code below handles a state on an interval cut into cells of width , a motion with , and any measurement density. The transition from cell to cell is , where and are the edges of cell and is the standard normal distribution function. The outer edges are and : the mass that leaves the interval goes to the end cells, as if the robot stops at a wall. So each column of the transition matrix sums to one.
For a robot pose, the cells form a 3D grid over , and , and the transition comes from the odometry motion model or the velocity motion model. Thrun et al. (Section 8.2) call this grid localization.
Example
A beacon on a line. The state space is m, cut into cells of 1 m with centers . A beacon stands at . The sensor gives the distance to the beacon, but not the side: with . The likelihood of cell is ; the constant factor cancels in L4. The prior is uniform. The robot is at .
Step 1 has no motion, and the sensor reads . Cells 2, 3, 6 and 7 are at distance or from the beacon, so their likelihood is . Cells 1, 4, 5 and 8 get .
Step 2 moves the robot by m with m, to , and the sensor reads . From the center of a cell, the move puts of the mass in the cell one to the right, in each of its two neighbors and two cells further out on each side.
| cell | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
|---|---|---|---|---|---|---|---|---|---|---|
| 0.0000 | 0.0045 | 0.2455 | 0.2455 | 0.0045 | 0.0045 | 0.2455 | 0.2455 | 0.0045 | 0.0000 | |
| 0.0000 | 0.0010 | 0.0420 | 0.2069 | 0.2069 | 0.0431 | 0.0431 | 0.2069 | 0.2069 | 0.0431 | |
| 0.0000 | 0.0000 | 0.0004 | 0.2560 | 0.5697 | 0.1185 | 0.0533 | 0.0021 | 0.0000 | 0.0000 |
After step 1 the belief has two equal peaks, one on each side of the beacon. No Gaussian can hold this. The move shifts both peaks to the right. The left peak is now at about 1 m from the beacon, which fits ; the right peak is at about 3 m, which does not. After step 2, cells 0 to 4 hold of the mass, cell 4 (which contains the true position 4.2) is the most likely cell, and the mean is m.
Against the Kalman filter. On a linear Gaussian model the exact posterior is known from the Kalman filter. The test of the code uses , the prior , six moves of with and six measurements from a simulation with seed 7. The Kalman filter gives the mean and the variance . The histogram filter, with the mass of each cell spread uniformly over the cell, gives:
| cells | width | mean | variance |
|---|---|---|---|
| 10 | 4 | 5.9779 | 1.4212 |
| 40 | 1 | 5.3532 | 0.5260 |
| 160 | 0.25 | 5.4125 | 0.4007 |
| 640 | 0.0625 | 5.4165 | 0.3930 |
These are measurements on one data set, not a bound. The error falls quickly with here because the posterior is smooth and much wider than a cell at .
Correctness
The histogram filter is the Bayes filter of the discrete model whose states are the cells, whose transition is and whose measurement probability is . Each column of the transition sums to one, so this is a valid model, and the proof of the Bayes filter applies line by line: the output is the exact posterior of the cells under the discrete model. The proof, with the condition that makes the end cells correct, is in the correctness proof.
The output is not the posterior of the continuous model. The two differ because the motion from cell is computed from only, and because the likelihood is read at only. Both errors go to zero for smooth models as , but the rate depends on the model, and a measurement model narrower than a cell can be badly wrong (see Pitfalls). Kramer and Sorenson (1988) analyze how such errors can grow over time.
Proof: The histogram filter computes the posterior of the cell modelfull
Setting. A continuous state space is split into cells that do not overlap and cover . Cell has a representative point . The cell model is the hidden Markov model whose state is a cell, with
- the prior ,
- the transition , the probability that the continuous motion model started at ends in ,
- the measurement probability .
The data at time are .
Assumptions.
- (T) For every control and every cell , and .
- (M) The cell model satisfies the Markov assumption, and each control is chosen from the past data and from randomness independent of the state (assumptions M1, M2 and C of the proof of the Bayes filter).
- (P) Each measurement that occurs has positive probability under the predicted belief, so line L4 does not divide by zero.
Claim. If the input for all , then the output of HISTOGRAM-FILTER is for all . By induction over , the filter computes the posterior of the cell model at every time step.
Proof. First, the cell model is a valid model. The prior is a distribution by assumption. By (T), each column of the transition is a distribution over the cells, so is a stochastic matrix. For the code on an interval with Gaussian noise, with , where , and is the left edge of cell for . The edges increase, and increases, so each term is nonnegative. The sum over telescopes to . So (T) holds, and the end cells receive exactly the mass of the motion model that falls outside .
Second, the cell model is a finite state Bayes filter model, with state , motion model and measurement model . Lines L1 and L2 compute
which is line L2 of the Bayes filter for this model. Line L3 computes , which is line L3 of the Bayes filter. Lines L4 and L5 divide by , which is positive by (P). This is lines L4 and L5 of the Bayes filter. By the correctness of the Bayes filter on a finite state space under (M), the output is .
What the claim does not say. The claim is about the cell model. The posterior of the continuous model, integrated over cell , is in general a different number, because the cell model starts the motion from and not from the true distribution of the state inside cell , and because it reads the likelihood at only. The tests of the code measure this difference on a linear Gaussian model, against the Kalman filter, and show that it falls as the cells get smaller.
Complexity
Let be the number of cells. The costs are in the real RAM model.
- Prediction. Line L2 costs per cell, so per step. If one motion step can reach only cells from any cell, the sum has nonzero terms, and the cost is . For a pose grid with a short time step, is small.
- Shift-invariant motion. On a uniform grid, if the motion is the same everywhere (a shift plus noise that does not depend on the position), line L2 is a convolution, and the fast Fourier transform computes it in . Walls break the shift invariance near the edges.
- Correction. Lines L3 to L5 cost plus evaluations of the measurement model. For a laser scan with many beams, these evaluations dominate.
- Memory. for the belief. The transition matrix need not be stored; the code stores it only for the tests.
- Dimension. A grid with cells per axis in dimensions has cells. For a planar pose with 15 cm cells over a m map and 5 degree steps in , . This is why grids are used up to three dimensions and rarely above.
Properties
- Any shape. The belief can have many peaks, long tails and flat parts. This is what global localization needs.
- Deterministic. The same input gives the same output. A particle filter with the same number of cells gives a random answer.
- Fixed resolution. The cells do not move to where the probability is. Most cells hold almost no probability once the robot knows where it is, but they still cost time.
- Mass is kept. The prediction keeps the total probability at one, because the columns of the transition sum to one.
- Exact on finite models. When the state space is finite, as a set of doors, rooms or the places of a topological map, there is no discretization error, and the filter is the exact Bayes filter. In this case it is the forward algorithm with normalization at each step.
Variants and improvements
- Static and dynamic decomposition. Thrun et al. (Section 4.1) describe grids with cells of different sizes, density trees and grids whose cells depend on the current belief. They save time, but the model on the cells must then be built for each layout.
- Selective update. Fox, Burgard and Thrun (1999) update only the cells whose probability is above a threshold. This is a heuristic: a cell below the threshold can hold the true pose.
- Precomputed sensor model. For a fixed map, the expected range of each beam from each cell can be computed once with ray casting and stored. This trades memory for time.
- Point-mass filter. Bucy and Senne (1971) put the mass on grid points instead of cells. The equations are the same with taken as the density at times the cell volume.
- Particle filter. It puts its samples where the probability is, instead of on a fixed grid; for localization it is Monte Carlo localization.
When to use it
Use a histogram filter when the state has at most three dimensions, the belief can have several peaks, and a deterministic result matters, for example to localize a robot in a small map, to track a target on a road graph or to estimate a discrete mode. Use the Kalman filter or the EKF when the belief has one peak, and a particle filter when the space is large and most of it has almost no probability.
Pitfalls
- A sensor sharper than a cell. If the measurement density is much narrower than a cell, the value at the center can be close to zero even when the cell contains states that fit the measurement well. The filter then removes the true cell. Thrun et al. (Section 8.2) discuss this effect for coarse grids. A common fix is to widen the sensor model to the cell size; this is a rule of thumb, and it makes the filter less certain than the model.
- A motion smaller than a cell. If the robot moves less than a cell per step and the transition is computed from the center only, the belief can stay in the same cell for ever, or jump by a whole cell. Spread the mass over the cells that the motion from the whole cell reaches, or keep the odometry between updates and apply it once it is larger than a cell.
- Edges. Decide what happens to mass that leaves the grid. The code puts it in the end cells, which models a wall. Dropping it and normalizing later makes the belief move away from the edge without evidence.
- Underflow and zero cells. A cell with probability zero never comes back. Add a small floor to the sensor model, or normalize in log space for many sharp measurements.
- Angles. On a pose grid, the axis wraps around: the cell before is the cell before . Treat it as a ring, not as an interval with walls.
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.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/histogram-filter/. The authors are listed in prov/JZ7RY4.jsonl.
"""The histogram filter on a line (Thrun, Burgard and Fox 2005, Section 4.1).
A continuous state x in [a, b) is split into g cells of equal width h.
Cell k is [a + k h, a + (k + 1) h) and its center is c_k = a + (k + 1/2) h.
The belief is a list p of g probabilities, one per cell.
The motion model is x_t = x_(t-1) + u_t + noise, with noise N(0, sigma^2).
The probability to go from cell i to cell k is the mass of N(c_i + u, sigma^2)
on cell k. Mass that leaves [a, b) goes to the first or the last cell, as if
the robot stops at a wall. The measurement model is any density p(z | x),
read at the cell centers.
"""
import math
def _phi(x):
"""Return the standard normal distribution function at x."""
return 0.5 * math.erfc(-x / math.sqrt(2.0))
def centers(a, b, g):
"""Return the g cell centers of [a, b)."""
h = (b - a) / g
return [a + (k + 0.5) * h for k in range(g)]
def gaussian_transition(a, b, g, u, sigma):
"""Return T with T[k][i] = P(cell k at time t | cell i at time t - 1, u).
Each column of T sums to 1. sigma must be positive.
"""
if sigma <= 0.0:
raise ValueError("sigma must be positive")
h = (b - a) / g
c = centers(a, b, g)
t = [[0.0] * g for _ in range(g)]
for i in range(g):
m = c[i] + u
# cdf[k] = P(x < left edge of cell k); the outer edges are -inf and +inf
cdf = [0.0] + [_phi((a + k * h - m) / sigma) for k in range(1, g)] + [1.0]
for k in range(g):
t[k][i] = cdf[k + 1] - cdf[k]
return t
def histogram_filter(p, trans, likelihood):
"""Return the belief after one motion and one measurement.
p is the belief over the g cells, trans is a g by g matrix with
trans[k][i] = P(k | u_t, i), or None for no motion, and likelihood is a
list with likelihood[k] = p(z_t | x = c_k), or None for no measurement.
"""
g = len(p)
if trans is None:
p_bar = list(p)
else:
p_bar = []
for k in range(g): # @line L1
p_bar.append(sum(trans[k][i] * p[i] for i in range(g))) # @line L2
if likelihood is None:
return p_bar
q = [likelihood[k] * p_bar[k] for k in range(g)] # @line L3
total = sum(q)
if total <= 0:
raise ValueError("the measurement has probability zero under the predicted belief")
eta = 1 / total # @line L4 (stays exact for fractions.Fraction inputs)
return [eta * x for x in q] # @line L5
def mean_var(a, b, p):
"""Return the mean and the variance of the belief p on [a, b).
The mass of each cell is spread uniformly over the cell, so the variance
includes the term h^2 / 12 of a uniform distribution on one cell.
"""
g = len(p)
h = (b - a) / g
c = centers(a, b, g)
mean = sum(pk * ck for pk, ck in zip(p, c))
var = sum(pk * (ck - mean) ** 2 for pk, ck in zip(p, c)) + h * h / 12.0
return mean, var
def gaussian_prior(a, b, g, mu, sigma):
"""Return the mass of N(mu, sigma^2) on each cell, with the tails in the end cells."""
h = (b - a) / g
cdf = [0.0] + [_phi((a + k * h - mu) / sigma) for k in range(1, g)] + [1.0]
return [cdf[k + 1] - cdf[k] for k in range(g)]
test_histogram_filter.py 110 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/histogram-filter/. The authors are listed in prov/JZ7RY4.jsonl.
import itertools
import math
import random
from fractions import Fraction as F
import pytest
from histogram_filter import centers, gaussian_prior, gaussian_transition, histogram_filter, mean_var
def kalman_1d(mu, var, u, q, z, r):
"""The scalar Kalman filter for x_t = x_(t-1) + u + N(0, q), z = x + N(0, r)."""
mu, var = mu + u, var + q
k = var / (var + r)
return mu + k * (z - mu), (1.0 - k) * var
def run_histogram(g, steps, a=-20.0, b=20.0):
p = gaussian_prior(a, b, g, 0.0, 2.0)
c = centers(a, b, g)
trans = gaussian_transition(a, b, g, 1.0, 0.5)
for z in steps:
lik = [math.exp(-0.5 * (z - ck) ** 2) for ck in c]
p = histogram_filter(p, trans, lik)
return mean_var(a, b, p)
def run_kalman(steps):
mu, var = 0.0, 4.0
for z in steps:
mu, var = kalman_1d(mu, var, 1.0, 0.25, z, 1.0)
return mu, var
def test_matches_kalman_filter_and_converges_with_finer_grid():
rng = random.Random(7)
x, steps = rng.gauss(0.0, 2.0), []
for _ in range(6):
x += 1.0 + rng.gauss(0.0, 0.5)
steps.append(x + rng.gauss(0.0, 1.0))
mu, var = run_kalman(steps)
errs = []
for g in (40, 160, 640):
m, v = run_histogram(g, steps)
errs.append(abs(m - mu) + abs(v - var))
assert errs[0] > errs[1] > errs[2]
assert errs[2] < 1e-3
def test_transition_columns_sum_to_one_and_mass_is_kept():
trans = gaussian_transition(0.0, 10.0, 25, 3.7, 0.8)
for i in range(25):
assert abs(sum(trans[k][i] for k in range(25)) - 1.0) < 1e-12
# a move far to the right puts all the mass in the last cell
trans = gaussian_transition(0.0, 10.0, 25, 100.0, 0.5)
assert all(abs(trans[24][i] - 1.0) < 1e-12 for i in range(25))
p = histogram_filter([1.0 / 25] * 25, trans, None)
assert abs(sum(p) - 1.0) < 1e-12
def test_exact_against_sum_over_paths():
# A small discrete model in exact arithmetic: 4 cells, a move that goes
# 0, 1 or 2 cells to the right and stops at the last cell.
g = 4
def step(i, s):
return min(i + s, g - 1)
moves = {0: F(1, 10), 1: F(7, 10), 2: F(1, 5)}
trans = [[sum((pr for s, pr in moves.items() if step(i, s) == k), F(0)) for i in range(g)] for k in range(g)]
liks = [[F(1, 2), F(1, 4), F(1, 8), F(1, 8)], [F(1, 10), F(3, 5), F(1, 5), F(1, 10)], [F(1), F(1, 3), F(1, 3), F(1, 9)]]
prior = [F(2, 5), F(3, 10), F(1, 5), F(1, 10)]
p = prior
for lik in liks:
p = histogram_filter(p, trans, lik)
joint = [F(0)] * g
for path in itertools.product(range(g), repeat=len(liks) + 1):
w = prior[path[0]]
for t, lik in enumerate(liks):
w *= trans[path[t + 1]][path[t]] * lik[path[t + 1]]
joint[path[-1]] += w
total = sum(joint)
assert p == [j / total for j in joint]
def test_bimodal_measurement_and_its_resolution():
a, b, g = 0.0, 10.0, 10
c = centers(a, b, g)
def lik(z):
return [math.exp(-0.5 * ((z - abs(ck - 5.0)) / 0.5) ** 2) for ck in c]
p1 = histogram_filter([0.1] * g, None, lik(2.0))
assert abs(sum(p1) - 1.0) < 1e-12
# two equal peaks, at cells 2 and 3 and at cells 6 and 7
assert abs(p1[2] - p1[7]) < 1e-12 and abs(p1[3] - p1[6]) < 1e-12
assert abs(p1[2] - 0.2455) < 1e-4
p2 = histogram_filter(p1, gaussian_transition(a, b, g, 1.0, 0.5), lik(0.8))
assert abs(sum(p2[:5]) - 0.8261) < 1e-4
assert max(range(g), key=lambda k: p2[k]) == 4
def test_zero_likelihood_everywhere_raises():
with pytest.raises(ValueError):
histogram_filter([0.5, 0.5, 0.0], None, [0.0, 0.0, 1.0])
with pytest.raises(ValueError):
gaussian_transition(0.0, 1.0, 4, 0.0, 0.0)
History
Bucy and Senne (1971) computed the Bayes recursion of a nonlinear filter on a grid of points, so that the accuracy is set by the program and not by a linearization. Kramer and Sorenson (1988) used densities that are constant on cells and studied the growth of the error. In robotics, Burgard, Fox, Hennig and Schmidt (1996) used position probability grids over the three pose coordinates for global localization, and Fox, Burgard and Thrun (1999) built Markov localization on such grids. Thrun, Burgard and Fox (2005) present the method as the histogram filter, and its use for robot pose as grid localization.
References
- Sebastian Thrun, Wolfram Burgard and Dieter Fox, Probabilistic Robotics, MIT Press, 2005, Chapter 4, Section 4.1 (the discrete Bayes filter and the histogram filter with its decomposition of a continuous space), and Chapter 8, Section 8.2 (grid localization)
- Richard S. Bucy and Kenneth D. Senne, Digital synthesis of non-linear filters, Automatica 7(3), 1971, pages 287 to 298, the Bayes recursion of a nonlinear filter evaluated on a grid, with the convolution of the prediction done numerically
- Stuart C. Kramer and Harold W. Sorenson, Recursive Bayesian estimation using piece-wise constant approximations, Automatica 24(6), 1988, pages 789 to 801, the density held as a piecewise constant function on cells, and the analysis of how its error can grow
- Wolfram Burgard, Dieter Fox, Daniel Hennig and Timo Schmidt, Estimating the absolute position of a mobile robot using position probability grids, Proceedings of the Thirteenth National Conference on Artificial Intelligence (AAAI-96), 1996, a grid over the three pose coordinates of a robot, updated by the Bayes filter (general locator)
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag JZ7RY4 Edit this page History Report an error Markdown