Algorithmcore
Markov localization
Also called Fox-Burgard-Thrun Markov localization.
Localization by a Bayes filter over all poses of the robot in a known map, under the Markov assumption. It can start with no knowledge of the pose.
- Time
- O(T g^2) worstO(g b + g D) per_step
- Space
- O(g) extra
- Where
- D = the cost of one evaluation of the measurement model; T = the number of time steps; b = the number of poses that one control can reach from a pose; g = the number of poses
- Model
- Real RAM
- Properties
- deterministicexactonlinerecursive
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Dieter Fox, Wolfram Burgard, Sebastian Thrun, 1999
Markov localization estimates the pose of a robot in a known map by running the Bayes filter over all poses. The state is the pose , the map is fixed, and the belief is a distribution over every pose the robot could have. Because the belief can have any shape, Markov localization handles global localization, where the robot starts with no idea of its pose, as well as tracking. The name comes from the Markov assumption that makes the filter exact: the current pose and the map explain each new reading. This page gives the algorithm on a finite set of poses, where it is exact, and shows a robot in a small maze that keeps four hypotheses until one turn decides between them.
In plain words
The robot has a map but does not know where on it it is. It gives every place and every direction a score, and all scores add up to one. At the start all scores are equal. When the robot drives, each score moves to the places the robot could reach. When the robot measures, for example the distance to the wall in front of it, places where the map predicts that distance keep their score, and the others lose most of it. In a building with many similar corridors, several places keep a high score for a while. A later measurement that only one of them can explain removes the others.
The problem
The input is a map , a set of poses (cells of a grid over , or the places of a topological map), a motion model , a measurement model and an initial belief. At each time the robot receives a control and a reading . The output is the posterior
for every . This is mobile robot localization with a belief that can have many peaks. For tracking, the initial belief is concentrated near a known pose; for global localization, it is uniform over the free space.
The map in the motion model expresses that the robot cannot drive through walls. Thrun et al. (Section 7.2) write both models with , and the algorithm is the Bayes filter with as a fixed extra argument.
The algorithm
MARKOV-LOCALIZATION(bel, u_t, z_t, m) ▷ bel(x) = bel(x_{t-1})- 1
bel_bar(x) ← 0 for all poses x - 2
for each pose x_{t-1} with bel(x_{t-1}) > 0 do - 3
for each pose x_t with p(x_t | u_t, x_{t-1}, m) > 0 do - 4
bel_bar(x_t) ← bel_bar(x_t) + p(x_t | u_t, x_{t-1}, m) bel(x_{t-1}) - 5
bel'(x) ← p(z_t | x, m) bel_bar(x) for all poses x - 6
η ← 1 / Σ_x bel'(x) - 7
return η bel'
Lines L1 to L4 compute the prediction . They loop over the source pose and push its probability to the poses it can reach, instead of looping over the target pose. The result is the same sum, but each pose has only a few successors, so the loop skips the zero terms. Lines L5 to L7 are the correction by Bayes' rule.
The code uses a grid map with four headings. A control is "F" (move one cell ahead), "L" or "R" (turn by 90 degrees). "F" succeeds with probability , and the robot stays where it is otherwise or when a wall is ahead. The sensor measures the number of free cells ahead of the robot. The reading has probability , where puts on and on each of and . This is a small version of the beam range finder model: a narrow peak at the expected range, plus a uniform term for random readings. The weights are chosen by hand here; on a real robot they are fitted to data.
Example
The map has 14 free cells, so there are poses. Rows and columns start at 0 in the top left corner, and the headings are N, E, S, W.
########
#......#
#.#.##.#
#...#..#
########
The parameters are , and . The robot starts at row 3, column 1, facing east, and does not know it. The prior is uniform. In this run, every move succeeds and every reading is the true range. The table gives, after each step, the number of poses with a belief above and the largest belief. The belief is computed in exact fractions.
| step | control | true pose | reading | poses above 0.05 | largest belief |
|---|---|---|---|---|---|
| 1 | none | (3, 1, E) | 2 | 10 | 0.0636 |
| 2 | F | (3, 2, E) | 1 | 10 | 0.0778 |
| 3 | F | (3, 3, E) | 0 | 10 | 0.0876 |
| 4 | L | (3, 3, N) | 2 | 4 | 0.2249 |
| 5 | F | (2, 3, N) | 1 | 4 | 0.2138 |
| 6 | F | (1, 3, N) | 0 | 4 | 0.2158 |
| 7 | R | (1, 3, E) | 3 | 1 | 0.9075 |
After step 1, ten poses see two free cells ahead and share most of the probability. Three steps later, four hypotheses remain: (1, 1, S), (1, 3, W), (3, 1, E) and (3, 3, N). For each of them, the robot saw ranges 2, 1, 0, then turned left and saw 2. They move in step and keep almost the same weight; after step 6, the true pose is in fact not the most likely one (0.2129 against 0.2158). The right turn at step 7 decides: only the true pose sees three free cells ahead. A filter with one Gaussian would have had to commit to one hypothesis at step 4 and would be wrong with probability about 3/4.
The test of the code checks this run, and checks the belief against a brute force sum over all paths of poses that the motion model allows.
Correctness
Markov localization is the Bayes filter with the map as a fixed argument, so the proof of the Bayes filter applies: under the Markov assumption, the output is exactly on a finite set of poses. Lines L1 to L4 compute the same sum as line L2 of the Bayes filter, term by term in another order. The full proof is in the correctness proof.
On a grid over continuous poses, the result is exact for the model on the grid cells, and an approximation of the continuous posterior; see the histogram filter.
Proof: Markov localization computes p(x_t | z_1:t, u_1:t, m)full
Setting. The set of poses is finite. The map is fixed and known. The data at time are a control and a reading , and . All probabilities below are conditioned on ; we write only where the models use it.
Assumptions.
- (M1) .
- (M2) .
- (C) : the control depends only on past data and on randomness that is independent of the pose.
- (P) for each reading that occurs.
Claim. If for all , then MARKOV-LOCALIZATION returns for all . By induction from , this holds at every time step.
Proof. Write .
Prediction. Line L1 sets every entry of to zero. Lines L2 to L4 add the term to the entry , once for each pair with and , and for no other pair. A pair with or has a zero term. So when line L4 has run for all pairs,
By the law of total probability and the product rule,
Summing (M1) over shows that the first factor is . By (C) and the hypothesis of the claim, the second factor is . So .
Correction. By Bayes' rule with the data held fixed,
Summing (M2) over shows that the first factor of the numerator is . The second factor is . So the numerator is of line L5. The denominator is by the law of total probability, and it is positive by (P). Lines L6 and L7 divide by it. So the output is .
Remarks. The proof does not use the order of the loops in lines L2 and L3, only that every nonzero term is added exactly once. If the motion model gives zero probability to the true move (a kidnapping), the claim still holds for the model, but the model is wrong, and the posterior can be zero at the true pose. If the readings of the beams of one scan are not independent given the pose, (M2) is false, and the output is not the posterior.
Complexity
Let be the number of poses and the largest number of poses that one control can reach from a pose. The costs are in the real RAM model.
- Prediction. Lines L2 to L4 cost . In the code . A pose grid with a fine resolution and a long time step has a large ; in the worst case the prediction costs .
- Correction. Line L5 evaluates the measurement model once per pose. If one evaluation costs , for example a ray cast through the map, the correction costs . The expected ranges depend only on the pose and the map, so they can be computed once and stored, which makes the number of beams.
- Memory. for the belief, plus times the number of beams if the expected ranges are stored.
The number of poses is the problem. A m building at 10 cm and 2 degree resolution has million poses. Fox, Burgard and Thrun (1999) update only the poses whose belief is above a threshold; this selective update is a heuristic.
Properties
- Exact on a finite set of poses. With exact arithmetic the output equals the posterior; the test uses fractions.
- Global. A uniform prior gives global localization with no special case.
- Multimodal. The belief keeps all hypotheses that fit the data, with the right weights, as in the example.
- Symmetry is not resolved. If the map looks the same from two poses for every reading, for example in a room with a rotation symmetry, their beliefs stay equal for ever. This is a property of the data, and no filter can do better.
- Deterministic. The same input gives the same belief, unlike Monte Carlo localization.
Variants and improvements
- Grid Markov localization. The poses are cells of a 3D grid; this is the histogram filter applied to pose estimation (Thrun et al., Section 8.2).
- Topological Markov localization. The poses are places of a topological map, or places with a few headings. This is how the method started (Simmons and Koenig 1995, Nourbakhsh, Powers and Birchfield 1995), and the state space is small.
- EKF localization. A Gaussian belief instead of a table; it is much cheaper but cannot localize globally. See EKF localization.
- Monte Carlo localization. Samples instead of a grid; see Monte Carlo localization.
- Dynamic environments. Fox, Burgard and Thrun (1999) add filters that drop readings that are shorter than expected and that people probably caused. The filtered readings break the strict Markov assumption less, but the filter itself is a heuristic.
- Active localization. The robot chooses controls that reduce the expected entropy of the belief. This is a POMDP problem in general. Fox, Burgard and Thrun also studied an active version that picks the next action by a greedy one-step rule, which is a heuristic.
When to use it
Use Markov localization when the robot may not know its pose, the set of poses is small enough to hold in memory (a topological map, or a 2D map with a coarse grid), and a deterministic answer is useful. For a large map at fine resolution, use Monte Carlo localization; for tracking with a good initial pose and identified landmarks, use EKF localization.
Pitfalls
- Readings that are not independent. The filter assumes that the readings of the beams of one scan are independent given the pose. They are not: one person in front of the robot shortens many beams at once. The filter then becomes too sure, too fast, and can remove the true pose. Using a subset of beams, or a sensor model with a wider peak, is a common rule of thumb.
- A map that is wrong. Doors that are open in the map and closed in reality, or furniture that moved, give readings that the model says are almost impossible. Keep the random term above zero, so that the true pose never gets probability zero.
- Probability zero. If the motion model forbids a move that happened (for example, the robot was pushed), the true pose can get probability zero and never come back. This is the kidnapped robot problem. Add a small probability of a random jump, which is a heuristic.
- Heading resolution. With coarse heading cells, a long range reading moves far from where the model expects when the heading is a little wrong. The sensor model must be wide enough for the cell size.
- Cost of the sensor model. A ray cast per beam per pose per step is too slow for large grids. Precompute the expected ranges, or use the likelihood field model, which needs no ray cast.
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/markov-localization/. The authors are listed in prov/599C1C.jsonl.
"""Markov localization on a grid map with four headings.
The map m is a list of strings: '#' is a wall and '.' is free.
A pose is (r, c, h): the row r, the column c of a free cell, and the heading
h in 0, 1, 2, 3 for north, east, south and west. Row 0 is the top row.
Motion model p(x_t | u_t, x_(t-1), m), for the controls:
'F' move one cell ahead with probability p_move; the robot stays where
it is with probability 1 - p_move, and also when the cell ahead is a wall;
'L', 'R' turn by 90 degrees to the left or to the right (no error).
Measurement model p(z_t | x_t, m): the robot measures the number d of free
cells ahead of it before the first wall. The reading z in 0..z_max is
(1 - w_rand) * K(z | d) + w_rand / (z_max + 1),
where K puts 3/5 on d and 1/5 on d - 1 and d + 1, clamped to 0..z_max.
The arithmetic is generic: with fractions.Fraction parameters the belief is
exact. A belief is a dict from pose to probability.
"""
from fractions import Fraction
DIRS = [(-1, 0), (0, 1), (1, 0), (0, -1)] # north, east, south, west
def free_cells(m):
return [(r, c) for r, row in enumerate(m) for c, ch in enumerate(row) if ch == "."]
def poses(m):
"""Return all poses of the map, in a fixed order."""
return [(r, c, h) for (r, c) in free_cells(m) for h in range(4)]
def is_free(m, r, c):
return 0 <= r < len(m) and 0 <= c < len(m[r]) and m[r][c] == "."
def motion_model(m, x_prev, u, p_move):
"""Return the list of (x_t, probability) with a positive probability."""
r, c, h = x_prev
if u == "L":
return [((r, c, (h + 3) % 4), 1)]
if u == "R":
return [((r, c, (h + 1) % 4), 1)]
if u != "F":
raise ValueError("unknown control")
dr, dc = DIRS[h]
if not is_free(m, r + dr, c + dc):
return [(x_prev, 1)]
return [((r + dr, c + dc, h), p_move), (x_prev, 1 - p_move)]
def expected_range(m, x):
"""Return the number of free cells ahead of the pose x before a wall."""
r, c, h = x
dr, dc = DIRS[h]
d = 0
while is_free(m, r + dr * (d + 1), c + dc * (d + 1)):
d += 1
return d
def measurement_model(z, d, z_max, w_rand):
"""Return p(z | d) for a reading z in 0..z_max and a true range d."""
if not 0 <= z <= z_max:
return 0 * w_rand
hit = 0 * w_rand
for dz, w in ((-1, Fraction(1, 5)), (0, Fraction(3, 5)), (1, Fraction(1, 5))):
if min(max(d + dz, 0), z_max) == z:
hit += w
return (1 - w_rand) * hit + w_rand / (z_max + 1)
def markov_localization(bel, u, z, m, p_move, z_max, w_rand):
"""Return bel(x_t) from bel(x_(t-1)), the control u and the reading z.
u = None skips the prediction and z = None skips the correction.
"""
if u is None:
bel_bar = dict(bel)
else:
bel_bar = {x: 0 * p_move for x in bel} # @line L1
for x_prev, b in bel.items(): # @line L2
if b == 0:
continue
for x, pr in motion_model(m, x_prev, u, p_move): # @line L3
bel_bar[x] += pr * b # @line L4
if z is None:
return bel_bar
q = {x: measurement_model(z, expected_range(m, x), z_max, w_rand) * b for x, b in bel_bar.items()} # @line L5
total = sum(q.values())
if total == 0:
raise ValueError("the reading has probability zero under the predicted belief")
eta = 1 / total # @line L6
return {x: eta * v for x, v in q.items()} # @line L7
def uniform_belief(m, one=Fraction(1)):
ps = poses(m)
return {x: one / len(ps) for x in ps}
test_markov_localization.py 148 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/markov-localization/. The authors are listed in prov/599C1C.jsonl.
import random
from fractions import Fraction as F
import pytest
from markov_localization import (
DIRS,
expected_range,
is_free,
markov_localization,
measurement_model,
motion_model,
poses,
uniform_belief,
)
MAP = [
"########",
"#......#",
"#.#.##.#",
"#...#..#",
"########",
]
P_MOVE, Z_MAX, W_RAND = F(4, 5), 6, F(1, 10)
def true_step(m, x, u):
r, c, h = x
if u == "L":
return (r, c, (h + 3) % 4)
if u == "R":
return (r, c, (h + 1) % 4)
if u == "F":
dr, dc = DIRS[h]
if is_free(m, r + dr, c + dc):
return (r + dr, c + dc, h)
return x
def test_models_are_distributions():
for x in poses(MAP):
for u in "FLR":
assert sum(p for _, p in motion_model(MAP, x, u, P_MOVE)) == 1
for d in range(Z_MAX + 1):
assert sum(measurement_model(z, d, Z_MAX, W_RAND) for z in range(Z_MAX + 1)) == 1
def brute_force_posterior(m, prior, controls, readings):
"""Sum the joint probability of every path of poses that the motion model allows."""
paths = [((x,), p) for x, p in prior.items() if p > 0]
for u, z in zip(controls, readings):
new = []
for path, w in paths:
succ = [(path[-1], 1)] if u is None else motion_model(m, path[-1], u, P_MOVE)
for x, pr in succ:
lik = 1 if z is None else measurement_model(z, expected_range(m, x), Z_MAX, W_RAND)
if pr * lik > 0:
new.append((path + (x,), w * pr * lik))
paths = new
post = {x: F(0) for x in prior}
for path, w in paths:
post[path[-1]] += w
total = sum(post.values())
return {x: v / total for x, v in post.items()}
def test_exact_against_sum_over_paths():
controls = [None, "F", "F", "L", "F"]
x, readings = (3, 1, 1), []
for u in controls:
x = true_step(MAP, x, u)
readings.append(expected_range(MAP, x))
readings[2] = None # one step without a reading
bel = uniform_belief(MAP)
for u, z in zip(controls, readings):
bel = markov_localization(bel, u, z, MAP, P_MOVE, Z_MAX, W_RAND)
assert sum(bel.values()) == 1
assert bel == brute_force_posterior(MAP, uniform_belief(MAP), controls, readings)
def test_page_example_global_localization():
bel = uniform_belief(MAP)
x = (3, 1, 1)
counts = []
for u in [None, "F", "F", "L", "F", "F", "R"]:
x = true_step(MAP, x, u)
bel = markov_localization(bel, u, expected_range(MAP, x), MAP, P_MOVE, Z_MAX, W_RAND)
counts.append(sum(1 for v in bel.values() if v > F(1, 20)))
assert counts == [10, 10, 10, 4, 4, 4, 1]
assert x == (1, 3, 1)
assert max(bel, key=bel.get) == x
assert abs(float(bel[x]) - 0.9075) < 1e-4
def test_symmetric_map_keeps_two_modes():
sym = [
"#####",
"#...#",
"#.#.#",
"#...#",
"#####",
]
bel = uniform_belief(sym)
x = (1, 1, 1)
for u in [None, "F", "R", "F", "F"]:
x = true_step(sym, x, u)
bel = markov_localization(bel, u, expected_range(sym, x), sym, P_MOVE, 3, W_RAND)
# The ring is the same after a rotation by 90 degrees, which maps the pose
# (r, c, h) to (c, 4 - r, h + 1). No reading can tell the four images of
# the true pose apart, so they keep the same belief.
images = [x]
for _ in range(3):
r, c, h = images[-1]
images.append((c, 4 - r, (h + 1) % 4))
assert len(set(images)) == 4
assert all(bel[y] == bel[x] for y in images)
assert bel[x] == max(bel.values())
assert bel[x] < F(1, 4)
def test_random_runs_converge_and_stay_normalized():
rng = random.Random(3)
one = 1.0
for _ in range(3):
x = rng.choice(poses(MAP))
bel = uniform_belief(MAP, one)
for _ in range(25):
u = rng.choice("FFFLR")
if u == "F":
y = true_step(MAP, x, "F")
x = y if rng.random() < 0.8 else x
else:
x = true_step(MAP, x, u)
d = expected_range(MAP, x)
r = rng.random()
z = d if r < 0.6 else min(max(d + rng.choice((-1, 1)), 0), Z_MAX) if r < 0.9 else rng.randint(0, Z_MAX)
bel = markov_localization(bel, u, z, MAP, 0.8, Z_MAX, 0.1)
assert abs(sum(bel.values()) - 1.0) < 1e-9
assert bel[x] > 0.0
def test_impossible_reading_raises():
bel = {(1, 1, 1): F(1)}
with pytest.raises(ValueError):
markov_localization(bel, None, 3, MAP, P_MOVE, Z_MAX, F(0))
History
Markov localization grew out of work in the mid 1990s that applied hidden Markov models and POMDPs to robot navigation on topological maps: Simmons and Koenig (1995) and Nourbakhsh, Powers and Birchfield (1995) kept a probability for each place of a graph of the office. Burgard, Fox, Hennig and Schmidt (1996) used a fine grid over the full pose and localized the robot globally. Fox, Burgard and Thrun (1999) gave the general method under the name Markov localization, with the selective update and the filters for people around the robot. Thrun, Burgard and Fox (2005) present it in Chapter 7 as the basis of all localization filters in the book.
References
- Sebastian Thrun, Wolfram Burgard and Dieter Fox, Probabilistic Robotics, MIT Press, 2005, Chapter 7, Sections 7.1 to 7.3 (the taxonomy of localization problems, the Markov localization algorithm and its illustration), and Chapter 8, Section 8.2 (grid localization)
- Dieter Fox, Wolfram Burgard and Sebastian Thrun, Markov localization for mobile robots in dynamic environments, Journal of Artificial Intelligence Research 11, 1999, pages 391 to 427, the Bayes filter over a grid of poses, the selective update, and the entropy and distance filters for readings caused by people
- 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, global localization with a grid over x, y and theta (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 599C1C Edit this page History Report an error Markdown