Algorithmcore
Vector field histogram
Also called VFH.
Builds a polar histogram of obstacle density around the robot from a grid and steers through the valley closest to the goal.
- Time
- O(w^2 + n l) worst
- Space
- O(n) extra
- Where
- l = the half-width of the smoothing window in sectors; n = the number of sectors; w = the width of the active window in cells
- Model
- Real RAM
- Properties
- deterministicnot exactonlinenot randomized
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Johann Borenstein, Yoram Koren, 1991
The vector field histogram (VFH) is a local obstacle avoidance method for a mobile robot with range sensors. It keeps a grid of certainty values around the robot, in the style of an occupancy grid. At each cycle it reduces the cells near the robot to a polar histogram: for each angular sector, a number that grows with the certainty and the closeness of the cells in that direction. It smooths the histogram, marks the sectors below a threshold as free, and steers into the run of free sectors (a valley) that is closest to the direction of the goal. A second rule lowers the speed when an obstacle lies ahead or the robot turns fast. VFH followed the potential field method and its weakness: summing all obstacle forces into one vector hides a gap between two obstacles, while a histogram keeps it.
In plain words
Picture the robot in the middle of a clock face. For each hour mark, it asks: how much obstacle is in that direction, and how close? It draws a bar for each direction. Tall bars mean "blocked", short bars mean "open".
Then it looks for a run of open directions, like a gap between two tall bars. It picks the gap that is nearest to the direction of the goal. If the gap is narrow, the robot drives through its middle. If the gap is wide, the robot drives along its edge, at a safe angle from the obstacle beside it. When the bars straight ahead are tall, or when it has to turn hard, it slows down.
The problem
Input. A histogram grid: a certainty value for each square cell (here 10 cm wide); the position of the robot; its heading; the direction to the target; and the parameters below. Arithmetic, square roots and arc tangents cost one step each, as in the real RAM.
Output. A steering direction inside a free sector, or "stop" if no sector is free, and a speed.
How it differs from close pages. A potential field sums forces into one vector and can be pushed back from a gap that is wide enough to pass. The dynamic window approach searches over velocities and respects the accelerations of the robot, with a stopping test; VFH chooses a direction first and has no such test. Bug algorithms follow obstacle boundaries with a guarantee of reaching the goal in the plane, but need exact contact sensing. Velocity obstacles handle moving obstacles.
The algorithm
With sectors of width , a window of cells, and positive constants and with , where is the distance from the robot to the farthest cell of the window:
VFH(grid c, position p, heading, target direction)- 1
h[0..n-1] ← 0 - 2
for each cell (i, j) of the w × w window around p: β ← direction from p to the cell; d ← distance; h[⌊β/α⌋] += c_ij² (a - b d) - 3
h′[k] ← Σ_{|j| ≤ l} (l + 1 - |j|) h[k + j] / (l + 1)² (indices mod n) - 4
free[k] ← h′[k] < τ - 5
if no sector is free then return stop; k_t ← the sector of the target; if all are free then return k_t - 6
V ← the valley (maximal run of free sectors) that contains k_t, or else has a border nearest to k_t - 7
if V has more than s_max sectors then θ ← the sector of V nearest to k_t that is at least s_max/2 inside both borders, else θ ← the middle of V - 8
v ← V_max (1 - min(h′[current], h_m)/h_m) (1 - |Ω|/Ω_max) + V_min
Line L2 is eqs. 1 to 4 of Borenstein and Koren. The square of the certainty favors cells that many readings confirm; the term is 0 at the farthest cell of the window and grows linearly for closer cells. Line L3 smooths the histogram, because the grid makes it ragged: in the Example below, one sector between two obstacle cells gets nothing. The paper's eq. 5 lists a triangular window with the middle weight and divides by ; that does not match the sum of its weights, so the code divides by the sum of the weights, which only rescales the threshold .
Line L7 is the steering rule of Section 4.2. When the target lies outside the valley, let be the free sector nearest to it and ; the robot steers at , that is, sectors from the obstacle. In a narrow valley, is the other border and the robot steers through the middle. The paper describes the rule for a target direction that is blocked. For a target inside a wide valley, the code steers straight at the target when it is at least sectors inside both borders, and otherwise at the nearest sector that is; this agrees with the paper's rule at the borders. Line L8 is eqs. 8 to 10, where is the smoothed density in the current direction of travel and is the turn rate. The code returns the center of the chosen sector, so is quantized to .
The paper uses a window of cells of 10 cm, so , , , deg/s and cm/s.
Example
The robot is at the center of cell . Five cells with certainty 3 form a short wall 1 m ahead, at cells to . With per meter, m. The middle cell is at 1 m, so it adds to sector 0. The other cells lie at and , so they go to sectors 1, 2, 70 and 69. Sector 71 gets nothing.
After smoothing, sector 0 has 6.90, sectors 1 and 71 have 6.58, and the values fall off on both sides to 0.31 at sectors 7 and 64. The target is straight ahead, at 0°.
| Threshold | Blocked sectors | Nearest free border | Steering direction |
|---|---|---|---|
| 5 | 69 to 2 | sector 3 | sector 12, 62.5° |
| 2 | 67 to 4 | sector 5 | sector 14, 72.5° |
| 1 | 66 to 5 | sector 6 | sector 15, 77.5° |
The valley on the other side of the wall is wide, so the robot steers sectors beyond the near border: it turns left and leaves the wall on its right. A higher threshold makes the blocked range narrower, so the robot turns less.
Correctness
VFH is a heuristic, with no guarantee of collision avoidance or of reaching the goal. The steering rule itself has a simple guarantee, which the proof shows: when some sector is free, the returned direction lies in a free sector, and when the target sector is free with at least free sectors on each side, the robot steers straight at it. The proof also shows that line L2 assigns each cell to exactly one sector, so the histogram sums all the magnitudes, and that rotating the grid by a multiple of about the robot shifts the histogram by the same number of sectors. The tests check these facts on random grids and random histograms, the smoothing against its definition, and hand cases of the steering rule.
A collision can still happen: the threshold may hide an obstacle until the robot is close, the grid may be wrong, and the robot does not turn instantly. Measured in this code, with a point robot that turns at most 120 deg/s, a cycle of 0.16 s and a top speed of 0.6 m/s, through a gap of 1.2 m in a wall with a thin pole on the way: thresholds 2, 5, 10 and 20 reached the target in 80, 61, 64 and 57 cycles; threshold 1 blocked the gap and never reached it; threshold 40 reached it but passed 5.7 cm from the center of a wall cell.
Proof: The histogram sums every cell once and the steering rule always picks a free sectorfull
Line numbers refer to the pseudocode on the vector field histogram page. VFH is a heuristic: nothing below says that the robot avoids every obstacle or reaches the goal. What can be proved is that the two data reductions do what they claim. The proof uses exact arithmetic; the code adds degrees before it divides by , so that a direction that is a multiple of up to roundoff goes to the upper sector, as it does in exact arithmetic.
Sectors are numbered and taken modulo . Sector holds the directions with , for . A valley is a maximal run of free sectors with .
Lemma 1 (the histogram). After line L2, , where the sum on the right is over the cells of the window other than the cell at the robot's position, and .
Proof. Each such cell has , so its direction is defined, and is exactly one integer in . So line L2 adds to exactly one sector.
Lemma 2 (rotation). Let the robot be at the center of its cell, let divide , and rotate the grid by about the robot: the cell at offset from the robot's cell moves to offset . Then the new histogram satisfies for every .
Proof. The rotation maps the square window onto itself and keeps each distance , so each moves to its image cell unchanged. The direction of the image is modulo , and , so its sector is modulo . By Lemma 1, each sector of the new histogram receives exactly the magnitudes that sector received before.
Theorem (steering). Assume at least one smoothed value is below . Then the direction returned by lines L5 to L7 is the center of a free sector. If, moreover, the target sector and the sectors for are free, then the direction is the center of .
Proof. If every sector is free, line L5 returns the center of , which is free. Otherwise there is a free sector and a blocked one, so there is at least one valley, and line L6 chooses a valley with first sector and length . Write the result of line L7 as with a real number ; the code returns the center of sector . It suffices to show , because then and the sector belongs to .
If , then , which is in . If , then , so the bounds and satisfy . Line L7 clamps into : if the target is inside , is its offset clamped to that interval; if it is outside, is or . In both cases . This proves the first claim.
For the second claim, let . If all sectors are free, the result is by line L5. Otherwise, the sectors are free and lie in one valley , which contains ; line L6 picks it, since its distance to is 0 and a valley that does not contain has a positive distance. The offset of in satisfies and , so , the valley is wide, and the clamp of line L7 leaves unchanged. The result is the center of .
The speed. Line L8 gives , because and when . The code clips to .
The tests. test_histogram_matches_brute_force_and_rotates_with_the_grid checks Lemmas 1 and 2 on 20 random grids. test_steering_always_picks_a_free_sector checks the theorem on 500 random histograms. test_steering_hand_cases and test_smoothing_is_a_triangular_average check the rules on small cases worked by hand, and test_speed_rule checks line L8.
Complexity
- Time. Line L2 visits cells, line L3 costs , and lines L4 to L7 scan the sectors a constant number of times, so one cycle costs . With the paper's values, that is 1089 cells and 792 products. Measured: one cycle takes about 2 to 5 ms in this pure Python code.
- Space. for the two histograms, besides the grid.
Properties
- Keeps gaps visible. Unlike one summed force vector, the histogram shows each gap between obstacles, so the robot can pass a door.
- Insensitive threshold. Borenstein and Koren report that raising or lowering the threshold by a factor of 3 or 4 changes only the width of the valleys. The table of the Example shows the same effect.
- Smooth steering. The averaging over many cells and the smoothing make the steering direction change only a little from one cycle to the next.
- No dynamics. The method does not model the accelerations or the shape of the robot; the speed rule and make up for that only in part.
- Local. It can be trapped by a U-shaped obstacle, or swing between two valleys of the same quality.
Variants and improvements
- VFH+. Ulrich and Borenstein enlarged obstacle cells by the robot radius, used a binary histogram with hysteresis, and masked the sectors that the robot cannot reach with its turning radius.
- VFH*. Ulrich and Borenstein looked ahead with an A*-style search over several steps of VFH+ to avoid dead ends.
- Virtual force field (VFF). The earlier method of the same authors: the same grid, with each cell pushing the robot by a force and the target pulling it.
- Adaptive threshold. The paper suggests a high-level planner that raises the threshold, and lowers the speed, to pass a narrow door.
When to use it
Use VFH as a reactive layer on a robot with noisy range sensors, such as sonars, that must move without stopping among unknown obstacles. Its histogram grid is cheap to update from each reading. Pair it with a global planner for long routes. When the accelerations or the shape of the robot matter, the dynamic window approach or VFH+ is a better fit.
Pitfalls
- The threshold. Far too high, and the robot sees an obstacle only when it is close and may hit it; far too low, and narrow passages disappear.
- The ragged histogram. Without smoothing, single empty sectors between obstacle cells look like gaps the robot can pass.
- The sector of 360°. Indices are circular. A valley can wrap around sector 0, and the nearest border must be found in both directions.
- The window corner. With , cells in the corners of the square window add almost nothing, while cells at the same distance in other directions are not even in the window. A circular window is more uniform, at a small cost.
- The speed formula. As written, eq. 10 adds to the result, so the speed can reach .
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/vector-field-histogram/. The authors are listed in prov/Z398RM.jsonl.
"""The vector field histogram (Borenstein and Koren 1991).
The world is a histogram grid: a dict from a cell (i, j) to a certainty value c >= 0.
Cell (i, j) covers [i*cell, (i+1)*cell) x [j*cell, (j+1)*cell). The robot sits at a
point (x, y). Angles are in degrees, counterclockwise from the +x axis, in [0, 360).
One step:
1. polar_histogram: each cell of the ws x ws window around the robot adds
c^2 (a - b d) to the sector of its direction (eqs. 1 to 4 of the paper);
2. smooth: a triangular moving average over 2l + 1 sectors (eq. 5);
3. steer: threshold the smoothed histogram, pick the valley of free sectors
closest to the target, and steer into it (Section 4.2);
4. speed: slow down for obstacles ahead and for sharp turns (eqs. 8 to 10).
"""
import math
def polar_histogram(grid, x, y, ws=33, n=72, cell=0.1, b=1.0):
"""The polar obstacle density h[0..n-1] of the window around (x, y).
a is chosen with a - b d_max = 0, where d_max = sqrt(2) (ws - 1) / 2 cells, so the
farthest cell of the window adds 0. Cells farther than d_max add nothing.
"""
alpha = 360.0 / n
half = (ws - 1) // 2
i0, j0 = math.floor(x / cell), math.floor(y / cell)
d_max = math.sqrt(2.0) * half * cell
a = b * d_max
h = [0.0] * n # @line L1
for i in range(i0 - half, i0 + half + 1):
for j in range(j0 - half, j0 + half + 1):
c = grid.get((i, j), 0.0)
if c <= 0.0:
continue
dx, dy = (i + 0.5) * cell - x, (j + 0.5) * cell - y # @line L2
d = math.hypot(dx, dy)
if d == 0.0:
continue
beta = math.degrees(math.atan2(dy, dx)) % 360.0
k = int((beta + 1e-9) / alpha) % n
h[k] += c * c * max(0.0, a - b * d) # @line L2
return h
def smooth(h, l=5):
"""Triangular average: weight l + 1 - |j| on sector k + j for |j| <= l, divided by the weight sum."""
n = len(h)
total = float((l + 1) * (l + 1))
return [sum((l + 1 - abs(j)) * h[(k + j) % n] for j in range(-l, l + 1)) / total for k in range(n)] # @line L3
def circ(a, b, n):
"""Steps from sector a to sector b going counterclockwise."""
return (b - a) % n
def valleys(free):
"""Maximal runs of free sectors as (start, length), start being the clockwise end."""
n = len(free)
if all(free):
return [(0, n)]
out = []
for k in range(n):
if free[k] and not free[(k - 1) % n]:
m = 0
while free[(k + m) % n]:
m += 1
out.append((k, m))
return out
def steer(hs, target_deg, threshold, s_max=18):
"""The steering direction in degrees, or None if every sector is above the threshold."""
n = len(hs)
alpha = 360.0 / n
free = [v < threshold for v in hs] # @line L4
kt = int((target_deg % 360.0) / alpha) % n
if not any(free): # @line L5
return None
if all(free):
return (kt + 0.5) * alpha
best = None
for start, length in valleys(free): # @line L6
off = circ(start, kt, n)
if off < length:
gap = 0
else:
gap = min(circ(kt, start, n), off - (length - 1))
if best is None or gap < best[0]:
best = (gap, start, length)
_, start, length = best
if length > s_max: # @line L7
lo, hi = s_max / 2.0, length - 1 - s_max / 2.0
off = circ(start, kt, n)
if off >= length:
# The target is outside: k_n is the nearer border, k_f = k_n +- s_max.
off = lo if circ(kt, start, n) <= off - (length - 1) else hi
theta = start + min(hi, max(lo, off))
else:
theta = start + (length - 1) / 2.0 # @line L7
return ((theta + 0.5) * alpha) % 360.0
def speed(h_c, omega, v_max, h_m, omega_max, v_min):
"""Eqs. 8 to 10: slow down for density h_c ahead and for the turn rate omega."""
v1 = v_max * (1.0 - min(h_c, h_m) / h_m) # @line L8
return v1 * (1.0 - min(abs(omega), omega_max) / omega_max) + v_min # @line L8
def angle_diff(a, b):
"""The signed difference a - b of two angles in degrees, in (-180, 180]."""
d = (a - b) % 360.0
return d - 360.0 if d > 180.0 else d
def run(grid, start, heading, target, threshold, steps=400, dt=0.16, v_max=0.6, omega_max=120.0,
v_min=0.04, h_m=None, ws=33, cell=0.1, l=5, s_max=18, tol=0.2, record=None):
"""Simulate a point robot that turns at most omega_max deg/s and moves at the VFH speed.
Returns (x, y, heading, steps, reached).
"""
x, y = start
if h_m is None:
h_m = threshold
n = 72
alpha = 360.0 / n
for k in range(steps):
if math.hypot(target[0] - x, target[1] - y) < tol:
return x, y, heading, k, True
hs = smooth(polar_histogram(grid, x, y, ws, n, cell), l)
tdeg = math.degrees(math.atan2(target[1] - y, target[0] - x))
theta = steer(hs, tdeg, threshold, s_max)
if theta is None:
return x, y, heading, k, False
turn = max(-omega_max * dt, min(omega_max * dt, angle_diff(theta, heading)))
heading = (heading + turn) % 360.0
h_c = hs[int(heading / alpha) % n]
v = speed(h_c, turn / dt, v_max, h_m, omega_max, v_min)
x += v * dt * math.cos(math.radians(heading))
y += v * dt * math.sin(math.radians(heading))
if record is not None:
record(x, y, heading, theta, v)
return x, y, heading, steps, False
test_vector_field_histogram.py 118 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/vector-field-histogram/. The authors are listed in prov/Z398RM.jsonl.
import math
import random
from vector_field_histogram import polar_histogram, run, smooth, speed, steer, valleys
A = math.sqrt(2.0) * 16 * 0.1 # a for b = 1, ws = 33, cells of 10 cm
def test_single_cells_land_in_their_sectors():
x, y = 0.05, 0.05 # the center of cell (0, 0)
for cell, sector, dist in (((10, 0), 0, 1.0), ((0, 10), 18, 1.0), ((-7, -7), 45, math.sqrt(98) * 0.1),
((3, 1), 3, math.sqrt(10) * 0.1), ((-5, 2), 31, math.sqrt(29) * 0.1)):
h = polar_histogram({cell: 2.0}, x, y)
assert [k for k in range(72) if h[k] != 0.0] == [sector]
assert abs(h[sector] - 4.0 * (A - dist)) < 1e-12
def test_histogram_matches_brute_force_and_rotates_with_the_grid():
rng = random.Random(21)
x, y = 0.05, 0.05
for _ in range(20):
grid = {(rng.randint(-20, 20), rng.randint(-20, 20)): float(rng.randint(1, 15)) for _ in range(60)}
grid.pop((0, 0), None)
h = polar_histogram(grid, x, y)
# Brute force: every cell of the window contributes c^2 max(0, a - d) once.
total = sum(c * c * max(0.0, A - math.hypot(i * 0.1, j * 0.1))
for (i, j), c in grid.items() if abs(i) <= 16 and abs(j) <= 16)
assert abs(sum(h) - total) < 1e-9 * (1.0 + total)
# Rotating the grid by 90 degrees about the robot shifts the histogram by 18 sectors.
rot = {(-j, i): c for (i, j), c in grid.items()}
hr = polar_histogram(rot, x, y)
for k in range(72):
assert abs(hr[(k + 18) % 72] - h[k]) < 1e-9 * (1.0 + h[k])
def test_smoothing_is_a_triangular_average():
assert all(abs(v - 3.0) < 1e-12 for v in smooth([3.0] * 72))
h = [0.0] * 72
h[2] = 36.0
hs = smooth(h, 5)
for k in range(72):
j = min((k - 2) % 72, (2 - k) % 72)
assert abs(hs[k] - (6 - j if j <= 5 else 0)) < 1e-12
def blocked(sectors):
hs = [0.0] * 72
for k in sectors:
hs[k % 72] = 10.0
return hs
def test_steering_hand_cases():
free = [0.0] * 72
assert steer(free, 37.0, 1.0) == 37.5
assert steer([5.0] * 72, 37.0, 1.0) is None
# Sectors 0..9 blocked, target at 0 degrees: the near border is sector 71, so
# k_n = 71, k_f = 71 - 18 = 53 and theta is sector 62.
assert steer(blocked(range(10)), 0.0, 1.0) == 312.5
# Target inside the wide valley but close to its border: keep s_max / 2 sectors away.
assert steer(blocked(range(10)), 62.0, 1.0) == 97.5
# Target well inside the wide valley: go straight to it.
assert steer(blocked(range(10)), 182.0, 1.0) == 182.5
# A narrow valley of sectors 20..25: steer to its middle.
assert steer(blocked([k for k in range(72) if not 20 <= k <= 25]), 300.0, 1.0) == 115.0
def test_steering_always_picks_a_free_sector():
rng = random.Random(22)
for _ in range(500):
hs = [rng.choice([0.0, 0.0, 0.0, 5.0]) for _ in range(72)]
target = rng.uniform(0.0, 360.0)
theta = steer(hs, target, 1.0)
if all(v >= 1.0 for v in hs):
assert theta is None
continue
k = int(theta / 5.0) % 72
assert hs[k] < 1.0
kt = int(target / 5.0)
# A free target with at least 9 free sectors on each side is steered to directly.
if all(hs[(kt + j) % 72] < 1.0 for j in range(-9, 10)):
assert theta == (kt + 0.5) * 5.0
def test_valleys_are_maximal_runs():
free = [False] * 72
for k in list(range(70, 72)) + list(range(0, 3)) + list(range(10, 14)):
free[k] = True
assert sorted(valleys(free)) == [(10, 4), (70, 5)]
assert valleys([True] * 72) == [(0, 72)]
def test_speed_rule():
assert speed(0.0, 0.0, 0.6, 10.0, 120.0, 0.04) == 0.6 + 0.04
assert speed(25.0, 0.0, 0.6, 10.0, 120.0, 0.04) == 0.04
assert speed(0.0, -120.0, 0.6, 10.0, 120.0, 0.04) == 0.04
assert abs(speed(5.0, 60.0, 0.6, 10.0, 120.0, 0.04) - (0.15 + 0.04)) < 1e-12
def scene():
# A wall along x = 3 m with a gap of 1.2 m between y = 1.4 and y = 2.6, and a pole.
g = {(30, j): 5.0 for j in range(-10, 50) if not 1.4 <= (j + 0.5) * 0.1 <= 2.6}
g[(15, 12)] = 5.0
return g
def test_passes_the_gap_and_keeps_away_from_obstacles():
g = scene()
for threshold in (5.0, 20.0):
path = []
_, _, _, steps, reached = run(g, (0.5, 0.5), 0.0, (5.0, 2.0), threshold, steps=200,
record=lambda *p: path.append(p))
assert reached and steps < 100
clear = min(math.hypot((i + 0.5) * 0.1 - p[0], (j + 0.5) * 0.1 - p[1]) for p in path for (i, j) in g)
assert clear > 0.15
History
Borenstein and Koren built the virtual force field method in the late 1980s for fast robots with ultrasonic sensors, on a histogram grid that increments one cell per reading. They found that summing all forces into one vector loses the shape of the obstacles, so the robot could not pass narrow openings. The vector field histogram, published in 1991, kept the intermediate polar histogram to solve that. Ulrich and Borenstein extended it to VFH+ in 1998 and to VFH* in 2000.
References
- The vector field histogram, fast obstacle avoidance for mobile robots, Section 4 (eqs. 1 to 5 for the polar histogram and its smoothing, Section 4.2 for valleys and steering, Section 4.3 for the threshold, Section 4.4 and eqs. 8 to 10 for the speed)
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 Z398RM Edit this page History Report an error Markdown