Data structurecore
Topological map
Also called place graph.
A graph whose vertices are distinct places and whose edges are the paths between them, labeled with the actions that follow them, without a global metric frame.
- Time
- O(1) expected add_edge · stepO(1) add_placeO(V + k V) expected localizeO((V + E) log V) route
- Space
- O(V + E) total
- Where
- E = the number of edges; V = the number of places; k = the number of steps of a localization query
- Model
- Word RAM
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Benjamin Kuipers, Yung Tai Byun, 1991
A topological map stores the environment of a robot as a graph. A vertex is a place that the robot can recognize, such as a junction of corridors or a door, and an edge is a path that the robot can follow from one place to the next. An edge has a label for the action that follows it, for example "go east along the corridor", and can have a length. There is no global coordinate frame: the map says what is connected to what and how to get there, not where things are. This makes the map small and robust to errors of odometry, and it suits planning routes and talking about places. It is weak when two places look the same, which is the problem of perceptual aliasing. This page describes the structure, the operations to build it, to plan a route and to localize by a sequence of actions and observations, and their costs. Kuipers and Byun (1991) made this the central level of a robot map, and the occupancy grid map is its metric counterpart.
In plain words
Think of how you give directions in a building: "from the lift, go to the end of the corridor, turn left, and it is the second door". You do not use coordinates. A topological map is the same idea for a robot. It is a list of places that the robot can recognize, and for each place the ways out of it, each leading to another place. To plan a route, the robot finds a chain of ways out from where it is to where it wants to go. If it does not know where it is, it looks at the place, makes a move, looks again, and crosses out every place on the map that does not fit what it saw.
The abstract type
A topological map holds places and edges, with these operations:
add_place(σ): add a place with the signature , what the robot senses there, and return its id.add_edge(u, a, v, b, ℓ): join the places and with an edge of length . The action at leads to , and the action at leads back to .step(v, a): the place that the action leads to from , or none.route(s, t): a shortest route from to , as a list of places and a list of actions, or none if cannot be reached.localize(σ_0, [(a_1, σ_1), ..., (a_k, σ_k)]): the set of places where the robot can be after it sensed , took the action , sensed , and so on.
Representation
- An array
sigof signatures, indexed by the place id . - An array
outof dictionaries:out[v][a] = (w, ℓ)means that the action at leads to along an edge of length . This is an adjacency list keyed by the action.
Invariant (T). (1) For each place and each action , there is at most one entry out[v][a]. (2) Each edge appears twice, as out[u][a] = (v, ℓ) and out[v][b] = (u, ℓ). (3) All lengths are .
Part 1 says that actions are deterministic in the map: an action at a place has at most one outcome. A real robot may fail to follow an action; the map records the intended outcome.
Operations
ADD-PLACE(G, σ)- 1
v ← |V|; sig[v] ← σ; out[v] ← an empty dictionary; return v ADD-EDGE(G, u, a, v, b, ℓ) ▷ a leads from u to v, b from v to u- 2
if a is a key of out[u], or b is a key of out[v], or (u = v and a = b) then error - 3
out[u][a] ← (v, ℓ); out[v][b] ← (u, ℓ) ROUTE(G, s, t) ▷ Dijkstra on the lengths- 4
d[s] ← 0; Q ← a min-heap with (0, s) - 5
while Q is not empty do - 6
pop (δ, u) with the smallest δ; if δ > d[u] then continue; if u = t then stop - 7
for each action a with out[u][a] = (w, ℓ) do - 8
if δ + ℓ < d[w] then d[w] ← δ + ℓ; prev[w] ← (u, a); push (d[w], w) - 9
if t was reached, follow prev from t back to s and return d[t], the places and the actions LOCALIZE(G, σ_0, [(a_1, σ_1), ..., (a_k, σ_k)])- 10
C ← {v : sig[v] = σ_0} - 11
for i ← 1 to k do - 12
C ← {w : v ∈ C, out[v][a_i] = (w, ℓ) for some ℓ, sig[w] = σ_i} - 13
return C
ROUTE is Dijkstra's algorithm on the directed graph of the actions, with the lazy deletion of old heap entries. With unit lengths, breadth-first search gives the routes with the fewest edges. LOCALIZE keeps the set of places that agree with all observations so far; because actions are deterministic in the map, never grows.
Example
The map of one floor has seven places. The signature of a place is its kind: a corner, a T junction or a dead end. The actions are the compass directions, and each edge has its length in meters.
A (corner) -E 5- B (T) -E 4- C (corner)
|S 3 |S 3 |S 3
D (T) ----E 4---- E (T) -E 4- F (corner)
|S 2
G (dead end)
Route. From A to F, three routes reach F: A, B, C, F of length , A, B, E, F of length , and A, D, E, F of length . ROUTE returns the places A, D, E, F with the actions S, E, E and the length 11.
Localization. The robot wakes up at a T junction. LOCALIZE starts with .
| step | action | sensed | candidates |
|---|---|---|---|
| 0 | T | {B, D, E} | |
| 1 | E | corner | {C, F}: B leads east to C, a corner; D leads east to E, a T, which is out; E leads east to F, a corner |
| 2 | S | corner | {F}: C leads south to F, a corner; F has no way south |
After two moves the robot knows that it is at F, so it started at E. The reading "T" after the action N from a T junction would give , and "dead end" after N would give the empty set: the observations do not fit the map, which means a sensing error or a wrong map.
Aliasing. Four corners joined in a square, with the actions "left" and "right", cannot be told apart: every sequence of actions leaves all four places as candidates. Only a difference in signatures or in the structure of the graph lets the robot localize.
Correctness
ADD-PLACE and ADD-EDGE keep the invariant (T): line L2 refuses an edge that would give a second outcome to an action at a place, and line L3 writes both directions. ROUTE is Dijkstra's algorithm with nonnegative lengths, so it returns a shortest route. The correctness proof shows that LOCALIZE returns exactly the set of places such that some place with the signature leads by the actions through places with the signatures to . So the true place is always in the set when the robot senses and acts without error, and every place in the set agrees with the data. The tests compare ROUTE with the Floyd-Warshall distances and LOCALIZE with a search from every start place, on random maps.
Proof: The topological map keeps its invariant, ROUTE finds a shortest route, and LOCALIZE returns exactly the consistent placesfull
Setting. A map has the places , the signatures and the dictionaries . For a place and an action , write if , and if is not a key of . The invariant (T) is: (1) each pair has at most one entry; (2) every edge added by ADD-EDGE has its two entries; (3) every length is .
For the data and , a place is consistent if there are places with and, for , and .
Assumptions. Dictionary operations behave as maps from keys to values. Lengths are compared and added exactly.
Claim.
- ADD-PLACE and ADD-EDGE keep (T), or ADD-EDGE raises an error and leaves the map unchanged.
- ROUTE returns the length of a shortest directed path from to in the graph with an arc of length for each entry , together with a path of that length and its actions, or none if there is no path.
- LOCALIZE returns exactly the set of consistent places.
Proof.
Claim 1. ADD-PLACE appends a place with an empty dictionary, which adds no entry, so (T) still holds. ADD-EDGE first checks that both places exist and that , else it raises an error before any change. Line L2 raises an error if is already a key of , or of , or if and , in which case the two writes of line L3 would give one key two meanings. Otherwise is new at and is new at , and they are different keys if , so line L3 adds two new entries and changes none. Part 1 holds because each new key was absent, part 2 because both entries are written, and part 3 because .
Claim 2. The arcs of the graph are the entries of the dictionaries, and by (T) all lengths are . Lines L4 to L8 are Dijkstra's algorithm with a binary heap and lazy deletion: an entry with is out of date and skipped. For nonnegative lengths, Dijkstra's algorithm pops each place with equal to its shortest distance from , and then holds a shortest path tree of the places reached; the proof is on the page of Dijkstra's algorithm. Stopping when is popped does not change , which is final at that moment. If is never reached, no path exists, because every place reachable from is eventually pushed. Line L9 follows from ; each was set together with for , so the actions replay the path and its lengths add up to . The chain ends at . Say that a place is settled when it is popped with . Line L8 sets only while is being settled, and is settled later, after its last such update, so along the chain the settle times strictly decrease. (The place is settled when the loop stops.) Hence the chain has no cycle. It can only end at a place without , and is the only such place that was reached: and lengths are , so line L8 never sets , while every other place that was reached got its from line L8.
Claim 3. Let be the set after passes of line L12, and let be the set of places consistent with the first steps of the data. We show by induction on .
For , line L10 gives , which is by the definition with .
Assume . If , there is a chain as in the definition. Its first steps show , and with , so line L12 puts into . Conversely, if , line L12 found some with and . The chain for extended by shows . So , and LOCALIZE returns .
By part 1 of (T), has at most one value, so each place of gives at most one place of and .
Remark. If the robot senses and acts without error, its true place is consistent by the definition, so it is in the set that LOCALIZE returns.
Complexity
The model is the word RAM, with dictionary operations in expected time by hashing.
| operation | time |
|---|---|
| add_place | amortized |
| add_edge, step | expected |
| route | with a binary heap |
| localize | for line L10, then expected per step, so |
The space is . A topological map of a building has a few hundred places where an occupancy grid of the same building has millions of cells.
Variants
- Metric annotations. Store at each edge the relative pose between its ends, and at each place a small local map. This is the topological and metric hybrid of the spatial semantic hierarchy (Kuipers, 2000), and close to a pose graph.
- Voronoi graphs. Take the places as the meeting points of the Voronoi diagram of the free space, where the robot is equally far from three or more obstacles. The edges are the paths along the diagram. Choset and Nagatani (2001) built and localized in such maps.
- Probabilistic localization. Replace the set of candidates by a probability for each place, updated by a Bayes filter over the graph with error models for actions and signatures. This handles sensing errors that the set version cannot.
- Regions. Group places into rooms or zones, as a hierarchy, to plan in large buildings.
When to use it
Use a topological map for route planning over large spaces, for tasks given in terms of places ("go to the kitchen"), and when the metric error of odometry is too large for one consistent metric map. Use an occupancy grid map or a pose graph when the robot needs exact positions, for example to avoid obstacles or to align scans. Most systems use both: a topological map on top of local metric maps.
Pitfalls
- Perceptual aliasing. Two places with the same signature and the same neighborhood cannot be told apart. LOCALIZE then keeps both, and a mapping system that merges them builds a wrong map. Rich signatures and checks of loop closures reduce the risk.
- Errors of sensing. One wrong signature removes the true place from the set of LOCALIZE, and the set can become empty. Treat an empty set as a sign of an error, and use a probabilistic version if errors are common.
- Actions that fail. The map assumes that an action leads to its recorded place. A robot that misses a junction is somewhere else. Detect this with the signature of the place where it arrives.
- Two edges with one label. If two exits of a place have the same action label, the map is not deterministic and the operations above are wrong. Line L2 refuses such an edge.
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/topological-map/. The authors are listed in prov/KYBFGV.jsonl.
"""A topological map: places with signatures, joined by edges with action labels.
A place is an integer id with a signature, the value that the robot senses
there (for example the kind of junction). An edge joins two places. It has
a length and two action labels: the action that leads from the first place
to the second, and the action that leads back. At each place, an action
label leads to at most one place, so a route is a list of actions.
There is no global coordinate frame. The lengths are only used to rank
routes and must be >= 0.
"""
import heapq
import math
class TopologicalMap:
def __init__(self):
self.sig = [] # sig[v] is the signature of place v
self.out = [] # out[v][action] = (w, length)
def add_place(self, signature):
"""Add a place and return its id."""
v = len(self.sig) # @line L1
self.sig.append(signature)
self.out.append({})
return v
def add_edge(self, u, a, v, b, length):
"""Join u and v: action a leads from u to v, and action b from v to u."""
if not (0 <= u < len(self.sig) and 0 <= v < len(self.sig)):
raise ValueError("unknown place")
if length < 0:
raise ValueError("negative length")
if a in self.out[u] or b in self.out[v] or (u == v and a == b): # @line L2
raise ValueError("an action label is used twice at one place")
self.out[u][a] = (v, length) # @line L3
self.out[v][b] = (u, length)
def step(self, v, a):
"""Return the place that action a leads to from v, or None."""
e = self.out[v].get(a)
return None if e is None else e[0]
def route(self, s, t):
"""Return (length, places, actions) of a shortest route from s to t, or None.
This is Dijkstra's algorithm on the directed graph of the actions.
"""
dist = {s: 0} # @line L4
prev = {}
heap = [(0, s)]
while heap: # @line L5
d, u = heapq.heappop(heap) # @line L6
if d > dist[u]:
continue
if u == t:
break
for a, (v, length) in sorted(self.out[u].items(), key=lambda item: repr(item[0])): # @line L7
nd = d + length
if nd < dist.get(v, math.inf): # @line L8
dist[v] = nd
prev[v] = (u, a)
heapq.heappush(heap, (nd, v))
if t not in dist:
return None
places, actions = [t], [] # @line L9
while places[-1] != s:
u, a = prev[places[-1]]
places.append(u)
actions.append(a)
return dist[t], places[::-1], actions[::-1]
def localize(self, first, steps):
"""Return the set of places where the robot can be.
first is the signature sensed at the start, and steps is a list of
(action, signature) pairs: the robot took the action and then sensed
the signature. Perception and actions are assumed free of errors.
"""
cands = {v for v in range(len(self.sig)) if self.sig[v] == first} # @line L10
for a, z in steps: # @line L11
nxt = set()
for v in cands:
w = self.step(v, a)
if w is not None and self.sig[w] == z: # @line L12
nxt.add(w)
cands = nxt
return cands # @line L13
test_topological_map.py 165 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/topological-map/. The authors are listed in prov/KYBFGV.jsonl.
import math
import random
import pytest
from topological_map import TopologicalMap
OPP = {"N": "S", "S": "N", "E": "W", "W": "E"}
def floor_map():
"""The map of the page: a 2 by 3 block of corridors and one dead end.
A(corner) - B(T) - C(corner)
| | |
D(T) ----- E(T) - F(corner)
|
G(dead end)
"""
m = TopologicalMap()
ids = {}
for name, sig in [("A", "corner"), ("B", "T"), ("C", "corner"), ("D", "T"), ("E", "T"), ("F", "corner"), ("G", "end")]:
ids[name] = m.add_place(sig)
for u, a, v, length in [("A", "E", "B", 5), ("B", "E", "C", 4), ("A", "S", "D", 3), ("B", "S", "E", 3),
("C", "S", "F", 3), ("D", "E", "E", 4), ("E", "E", "F", 4), ("D", "S", "G", 2)]:
m.add_edge(ids[u], a, ids[v], OPP[a], length)
return m, ids
def test_route_on_the_page_map():
m, ids = floor_map()
length, places, actions = m.route(ids["A"], ids["F"])
assert length == 11
assert places == [ids["A"], ids["D"], ids["E"], ids["F"]]
assert actions == ["S", "E", "E"]
assert m.route(ids["G"], ids["G"]) == (0, [ids["G"]], [])
def test_localize_on_the_page_map():
m, ids = floor_map()
assert m.localize("T", []) == {ids["B"], ids["D"], ids["E"]}
assert m.localize("T", [("E", "corner")]) == {ids["C"], ids["F"]}
assert m.localize("T", [("E", "corner"), ("S", "corner")]) == {ids["F"]}
assert m.localize("T", [("W", "corner")]) == {ids["A"]} # from B, the only T with a corner to its west
assert m.localize("T", [("N", "T")]) == {ids["B"]} # from E
assert m.localize("T", [("N", "end")]) == set() # inconsistent with the map
def test_symmetric_ring_cannot_be_resolved():
# four corners in a square: every action sequence leaves all four candidates
m = TopologicalMap()
v = [m.add_place("corner") for _ in range(4)]
for k in range(4):
m.add_edge(v[k], "left", v[(k + 1) % 4], "right", 1)
rng = random.Random(0)
steps = [(rng.choice(["left", "right"]), "corner") for _ in range(20)]
assert m.localize("corner", steps) == set(v)
def random_map(rng, n, labels):
m = TopologicalMap()
for _ in range(n):
m.add_place(rng.randrange(3))
for _ in range(3 * n):
u, v = rng.randrange(n), rng.randrange(n)
a, b = rng.choice(labels), rng.choice(labels)
try:
m.add_edge(u, a, v, b, rng.randint(0, 9))
except ValueError:
pass
return m
def floyd_warshall(m):
n = len(m.sig)
d = [[math.inf] * n for _ in range(n)]
for u in range(n):
d[u][u] = 0
for v, length in m.out[u].values():
d[u][v] = min(d[u][v], length)
for k in range(n):
for i in range(n):
for j in range(n):
if d[i][k] + d[k][j] < d[i][j]:
d[i][j] = d[i][k] + d[k][j]
return d
def test_route_matches_floyd_warshall():
rng = random.Random(5)
for _ in range(20):
m = random_map(rng, 12, ["a", "b", "c", "d"])
d = floyd_warshall(m)
for s in range(12):
for t in range(12):
r = m.route(s, t)
if d[s][t] == math.inf:
assert r is None
continue
length, places, actions = r
assert length == d[s][t]
# the actions replay the route and add up to its length
v, total = s, 0
for a, w in zip(actions, places[1:]):
nxt, l = m.out[v][a]
assert nxt == w
v, total = w, total + l
assert v == t and total == length
def test_localize_matches_brute_force():
rng = random.Random(9)
labels = ["a", "b", "c"]
for _ in range(40):
m = random_map(rng, 10, labels)
start = rng.randrange(10)
v, steps = start, []
for _ in range(rng.randrange(6)):
a = rng.choice(labels)
w = m.step(v, a)
if w is None:
break
steps.append((a, m.sig[w]))
v = w
got = m.localize(m.sig[start], steps)
want = set()
for v0 in range(10):
if m.sig[v0] != m.sig[start]:
continue
v, ok = v0, True
for a, z in steps:
w = m.step(v, a)
if w is None or m.sig[w] != z:
ok = False
break
v = w
if ok:
want.add(v)
assert got == want
# the true place is always a candidate
true_v = start
for a, _ in steps:
true_v = m.step(true_v, a)
assert true_v in got
def test_errors():
m = TopologicalMap()
a = m.add_place("x")
b = m.add_place("y")
m.add_edge(a, "E", b, "W", 1)
with pytest.raises(ValueError):
m.add_edge(a, "E", b, "N", 1) # E is taken at a
with pytest.raises(ValueError):
m.add_edge(a, "N", 5, "S", 1)
with pytest.raises(ValueError):
m.add_edge(a, "N", b, "S", -1)
with pytest.raises(ValueError):
m.add_edge(a, "loop", a, "loop", 1)
assert m.route(b, a) == (1, [b, a], ["W"])
c = m.add_place("z")
assert m.route(a, c) is None
History
Kuipers and Byun (1991) proposed a map built on distinctive places and travel edges, learned by exploration, with metric information added only on top of the graph. Kuipers (2000) developed this into the spatial semantic hierarchy, with control, causal, topological and metric levels. Choset and Nagatani (2001) used the generalized Voronoi graph as a topological map for SLAM. Later systems combine topological graphs of places with local metric maps.
References
- Benjamin Kuipers and Yung-Tai Byun, A robot exploration and mapping strategy based on a semantic hierarchy of spatial representations, Robotics and Autonomous Systems 8(1-2), 1991, pages 47 to 63, the distinctive places, the travel edges between them, and the topological map as the level between control and metric maps
- Benjamin Kuipers, The spatial semantic hierarchy, Artificial Intelligence 119(1-2), 2000, pages 191 to 233, the control, causal, topological and metric levels, and the topological map of places, paths and regions
- Howie Choset and Keiji Nagatani, Topological simultaneous localization and mapping (SLAM): toward exact localization without explicit localization, IEEE Transactions on Robotics and Automation 17(2), 2001, pages 125 to 137, the generalized Voronoi graph as a topological map whose nodes are meeting points, and localization by matching the graph
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 | W4 complete |
|
Tag KYBFGV Edit this page History Report an error Markdown