Algorithmcore
Random shortcut path smoothing
Also called path shortcutting.
Shortens a planned path by picking two random points on it and replacing the part between them by a straight segment if it is free.
- Solves
- Trajectory generation
- Time
- Θ(N (n + N + k)) worst
- Space
- Θ(n + N) extra
- Where
- N = the number of iterations; k = the number of obstacles; n = the number of vertices of the input path
- Model
- Real RAM
- Properties
- randomizednot exactofflinerandomized
- Evidence
- Proof sketchCode in 1 languages
Random shortcut path smoothing takes a collision-free path, usually the jagged output of a sampling-based motion planner such as a rapidly-exploring random tree or a probabilistic roadmap, and makes it shorter. In each iteration it picks two random points on the current path. If the straight segment between them is free of obstacles, it replaces the part of the path between the two points by that segment. The path stays free, keeps its end points, and never gets longer; these are theorems. How close it gets to the shortest path is not guaranteed: in practice a few hundred iterations remove most of the detours, and the measurements below show this on one scene. The method is a heuristic, very simple to implement, and uses only the collision checker that the planner already has. It is the most common post-processing step for sampling-based planners.
In plain words
A planner that finds paths by random search finds paths that wander: they zigzag and take detours, because the search was random. To clean such a path, pick two places on it at random. If you can walk straight from one to the other without hitting anything, do that, and drop the part of the path in between. Repeat many times. Each successful straight cut makes the path shorter, and a failed try changes nothing. After a few hundred tries the path is mostly straight lines that touch the corners of obstacles. It may still be the long way around an obstacle, because the method only cuts corners of the path it has.
The problem
Input: a free polyline path from a start to a goal, a test for whether a straight segment is free, a number of iterations, and a random number generator. Output: a free polyline from to that is as short as possible. The code works in the plane with axis-aligned rectangular obstacles, whose open interiors are forbidden; a robot uses its own collision checker on the segment in configuration space instead.
The algorithm
SHORTCUT(P, obstacles, N, rng)- 1
repeat N times - 2
compute the cumulative lengths of the segments of P - 3
draw s1, s2 uniform in [0, length(P)] and sort them - 4
a ← the point at arc length s1, on segment i; b ← the point at arc length s2, on segment j if i = j then continue ▷ same segment, nothing to gain- 5
if the segment ab is free then - 6
P ← (x0, ..., xi, a, b, x(j+1), ..., xn) - 7
return P
Line L3 picks the two points uniformly along the path, which is the choice that the measurements on this page use. Line L4 finds them by searching the cumulative lengths. Line L5 is the only call to the collision checker. In the code it is an exact slab test against each rectangle. Line L6 splices the shortcut into the path: the vertices strictly between and disappear, and and become vertices.
Example
The scene has one wall, the rectangle , and the path goes around it the long way: , of length 28. The shortest path goes over the top corners of the wall, , of length . With seed 1 the code measured:
| iterations | length | vertices |
|---|---|---|
| 0 | 28 | 4 |
| 10 | 26.367 | 6 |
| 30 | 22.202 | 11 |
| 100 | 20.481 | 12 |
| 300 | 20.304 | 15 |
| 1000 | 19.938 | 17 |
After 300 iterations the path is about 2.1 percent longer than the optimum; after 1000, about 0.25 percent. The number of vertices grows, since each shortcut adds two points and often removes only one. In a scene with no obstacles, a zigzag path from to shrank to length after 200 iterations (seed 3): the last detours near the two end points shrink slowly, because a shortcut must start inside them. These are measurements on one scene each, not bounds.
Correctness
Theorem: after any number of iterations, for every sequence of random choices, the result is a free path with the same end points as the input and a length at most the input length, with at most vertices. The proof shows that the slab test is exact, that the new segment is free by the test, that the two partial segments next to it are parts of old free segments, and that the new segment is at most as long as the part it replaces, by the triangle inequality. No claim is made about optimality: if the path goes around a wall on the far side and no free segment joins two of its points past the near side, the method can never switch to the other side.
Proof: Random shortcutting keeps the path free, keeps its end points, and never makes it longerfull
We use the notation of the page. A path is a polyline in the plane, and it is free if no segment meets the open interior of an obstacle rectangle. The input path is free. The claims below are invariants of the loop of lines L1 to L6; they say nothing about how close the result is to a shortest path, because the method is a heuristic. The proof is in exact arithmetic.
The segment test
Lemma 1. segment_free(p, q) returns false exactly when the segment from to meets the open interior of some rectangle .
Proof. Write the segment as for . For one axis with , the coordinate lies in the open interval of the rectangle exactly for in the open interval between and of the code. For an axis with , it lies there for all or for no ; the code handles the second case by the flag. Let be the maximum of and the lower ends, and the minimum of and the upper ends. If , every strictly between them is in and in every open interval, so the segment meets the interior. Conversely, if some in is in every open interval, then . Equality on both sides would need (the open lower ends are below ) and , which is impossible. So .
The invariants
Consider one pass of the loop. Line L3 picks arc lengths , and line L4 finds the points on segment and on segment of the current path. If nothing changes. Otherwise , and line L6 replaces the path by
Lemma 2. If is free, so is .
Proof. The segments with or are segments of . The segment is part of the segment of , and the segment is part of , so they meet no interior. The segment passed the test of line L5, so by Lemma 1 it meets no interior either.
Lemma 3. has the same end points as , and its length is at most the length of .
Proof. The point is on segment and on segment , so and stay at the ends. The part of between arc lengths and is a polyline from to of length . By the triangle inequality its length is at least , the length of the new segment, and the rest of the path does not change.
Lemma 4. has at most one more vertex than .
Proof. The vertices , at least one of them because , are removed, and the two vertices and are added.
Theorem 1. After any number of iterations and for every sequence of random choices, line L7 returns a free path with the same end points as the input, a length that is at most the input length, and at most vertices after iterations.
Proof. Induction on the iterations with Lemmas 2, 3 and 4.
What is not claimed
The length can stay well above the shortest path length forever. Every new segment joins two points of the current path. If the input goes around a wall by its far end, and no free straight segment joins two points of the path past the near end, then the path stays around the far end, however long it runs. Even in free space, detours near the two end points shrink slowly, because a shortcut must start inside them. The page reports measured lengths, not guarantees.
Complexity
In the real RAM, one iteration costs for the cumulative lengths, where is the current number of vertices, and for the segment test against obstacles. The path gains at most one vertex per iteration, so , and iterations cost in the worst case. With a real collision checker, the segment test dominates; it is usually a sequence of checks at a fine resolution along the segment, and its cost depends on the scene.
Properties
- Anytime. Every intermediate path is free and no longer than the one before (a theorem), so the method can stop at any time.
- Local. It only cuts corners of the current path. It cannot change the homotopy class: a path that goes around the wrong side of an obstacle stays there.
- Randomized. The result depends on the seed. Fixed seeds give the same result, which the tests check.
- Corners touch obstacles. The result tends to touch obstacle corners, with no clearance. Many systems add a margin to the obstacles for this reason.
- Geometric only. The result is a path, not a trajectory; it has corners where the velocity must drop to zero, unless a time scaling with blends is added.
Variants and improvements
- Vertex shortcuts. Try to join two random vertices of the path instead of two random points; this is simpler but leaves more corners. Geraerts and Overmars compare several such variants and report the trade-offs between length, clearance and time.
- Partial shortcuts. Shortcut only some of the coordinates of a configuration, which helps for arms with many joints where a full shortcut is rarely free (Geraerts and Overmars).
- Trajectory shortcuts. Hauser and Ng-Thow-Hing replace the straight segment by the time-optimal motion between the two states under velocity and acceleration bounds, the same profiles as in online trajectory generation, so the result is a trajectory with no stops.
- Deterministic shortcuts. A greedy pass that joins each vertex to the farthest visible vertex gives a similar result without randomness.
- Optimization. Elastic bands and CHOMP improve a path by gradient steps on a cost that includes clearance and smoothness.
- Exact shortest path. In the plane with polygonal obstacles, the visibility graph gives the exact Euclidean shortest path, which the tests use as the reference.
When to use it
Use random shortcutting after any sampling-based planner, as the default first post-processing step. It needs only the collision checker, and it never makes the path longer. As a rule of thumb, a few hundred iterations cost little compared with the planning itself. Follow it with a time scaling, such as a trapezoidal profile per segment with blends, or use the trajectory version of Hauser and Ng-Thow-Hing. Use an optimizer instead if clearance or smoothness matter more than length.
Pitfalls
- Collision checking by sampling. A segment test that checks discrete points can miss thin obstacles. Use a resolution that matches the smallest obstacle, or an exact test.
- Growing vertex count. Each shortcut adds vertices. Remove collinear vertices and merge very short segments from time to time.
- No clearance. The shortest path grazes obstacles. A robot that tracks it with any error collides. Inflate the obstacles first.
- Stopping too early. Most of the gain comes in the first few dozen iterations, but long detours near the end points need many more. Check the length, not just the iteration count.
- Same segment. If both points fall on one segment, the shortcut is the segment itself; skip it, as the code does, or the path gains useless vertices.
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/random-shortcut-path-smoothing/. The authors are listed in prov/N97VRM.jsonl.
"""Random shortcut smoothing of a 2D polyline among axis-aligned rectangles.
shortcut(path, obstacles, iterations, rng) repeats: pick two random points
on the path (by arc length), and if the straight segment between them is
free, replace the part of the path between them with that segment. The
path stays collision-free and its length never grows. This is a heuristic:
the result is usually much shorter, but it is not a shortest path.
An obstacle is (xmin, ymin, xmax, ymax). A segment collides when it meets the
open interior of a rectangle, so a path may touch rectangle borders.
"""
import math
def segment_free(p, q, obstacles):
"""True when the segment pq meets the open interior of no rectangle (slab test)."""
for x0, y0, x1, y1 in obstacles:
lo, hi = 0.0, 1.0
blocked = True
for a, d, mn, mx in ((p[0], q[0] - p[0], x0, x1), (p[1], q[1] - p[1], y0, y1)):
if d == 0:
if not (mn < a < mx):
blocked = False
break
else:
t0, t1 = (mn - a) / d, (mx - a) / d
if t0 > t1:
t0, t1 = t1, t0
lo, hi = max(lo, t0), min(hi, t1)
if blocked and lo < hi:
return False
return True
def path_free(path, obstacles):
return all(segment_free(path[i], path[i + 1], obstacles) for i in range(len(path) - 1))
def path_length(path):
return sum(math.dist(path[i], path[i + 1]) for i in range(len(path) - 1))
def _point_at(path, cum, s):
"""Index i of the segment that holds arc length s, and the point at s."""
i = 0
while i < len(path) - 2 and cum[i + 1] < s:
i += 1
seg = cum[i + 1] - cum[i]
u = 0.0 if seg == 0 else (s - cum[i]) / seg
p, q = path[i], path[i + 1]
return i, (p[0] + u * (q[0] - p[0]), p[1] + u * (q[1] - p[1]))
def shortcut(path, obstacles, iterations, rng):
"""Return a shorter free path with the same end points. rng is a random.Random."""
path = [tuple(p) for p in path]
for _ in range(iterations): # @line L1
cum = [0.0]
for i in range(len(path) - 1): # @line L2
cum.append(cum[-1] + math.dist(path[i], path[i + 1]))
if cum[-1] == 0:
break
s1, s2 = sorted((rng.uniform(0, cum[-1]), rng.uniform(0, cum[-1]))) # @line L3
i, a = _point_at(path, cum, s1) # @line L4
j, b = _point_at(path, cum, s2)
if i == j:
continue # both points on one segment: nothing to gain
if segment_free(a, b, obstacles): # @line L5
path = path[: i + 1] + [a, b] + path[j + 1:] # @line L6
return path # @line L7
test_random_shortcut_path_smoothing.py 106 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/random-shortcut-path-smoothing/. The authors are listed in prov/N97VRM.jsonl.
"""Tests: the path stays free, the length never grows, and it never beats the true shortest path."""
import heapq
import math
import random
from random_shortcut_path_smoothing import path_free, path_length, segment_free, shortcut
def shortest_length(start, goal, obstacles):
"""Exact shortest path length by Dijkstra on the visibility graph of the rectangle corners."""
nodes = [start, goal]
for x0, y0, x1, y1 in obstacles:
nodes += [(x0, y0), (x0, y1), (x1, y0), (x1, y1)]
dist = [math.inf] * len(nodes)
dist[0] = 0.0
heap = [(0.0, 0)]
while heap:
d, u = heapq.heappop(heap)
if d > dist[u]:
continue
if u == 1:
return d
for v in range(len(nodes)):
if v != u and segment_free(nodes[u], nodes[v], obstacles):
nd = d + math.dist(nodes[u], nodes[v])
if nd < dist[v]:
dist[v] = nd
heapq.heappush(heap, (nd, v))
return math.inf
def staircase(start, goal, rng, n):
"""A free but wasteful path: a random walk of waypoints, kept only where free."""
return [start] + [(rng.uniform(0, 10), rng.uniform(0, 10)) for _ in range(n)] + [goal]
def test_segment_test():
box = [(2, 2, 4, 4)]
assert not segment_free((0, 3), (6, 3), box)
assert segment_free((0, 2), (6, 2), box) # along the border
assert segment_free((0, 0), (2, 2), box) # ends at a corner
assert not segment_free((2, 2), (4, 4), box) # the diagonal crosses the interior
assert segment_free((5, 0), (5, 9), box)
assert not segment_free((3, 3), (3, 3), box) # a point inside
def test_one_wall():
walls = [(4, -9, 6, 8)]
path = [(0, 0), (0, 9), (10, 9), (10, 0)]
assert path_free(path, walls)
out = shortcut(path, walls, 300, random.Random(1))
assert out[0] == (0, 0) and out[-1] == (10, 0)
assert path_free(out, walls)
best = shortest_length((0, 0), (10, 0), walls)
assert abs(best - (2 * math.hypot(4, 8) + 2)) < 1e-12
assert best - 1e-9 <= path_length(out) <= path_length(path)
# Measured with this seed: 28 drops to about 20.30 after 300 tries, 2.1 percent above the optimum.
assert path_length(out) <= 1.03 * best
def test_random_scenes():
rng = random.Random(2)
for _ in range(12):
obstacles = []
for _ in range(4):
x, y = rng.uniform(1, 8), rng.uniform(1, 8)
obstacles.append((x, y, x + rng.uniform(0.5, 2), y + rng.uniform(0.5, 2)))
start, goal = (0.0, 0.0), (10.0, 10.0)
# Build a free path by sampling random free waypoint chains.
path = None
for _ in range(200):
cand = staircase(start, goal, rng, 6)
if path_free(cand, obstacles):
path = cand
break
if path is None:
continue
lengths = [path_length(path)]
cur = path
for _ in range(10):
before = len(cur)
nxt = shortcut(cur, obstacles, 5, rng)
assert len(nxt) <= before + 5 # at most one new vertex per iteration
assert path_free(nxt, obstacles)
assert nxt[0] == start and nxt[-1] == goal
lengths.append(path_length(nxt))
cur = nxt
assert all(b <= a + 1e-9 for a, b in zip(lengths, lengths[1:]))
assert lengths[-1] >= shortest_length(start, goal, obstacles) - 1e-9
def test_free_line_collapses():
rng = random.Random(3)
path = [(0, 0), (1, 5), (2, -3), (3, 4), (4, 0)]
out = shortcut(path, [], 200, rng)
# Close to the straight line, but small detours near the ends shrink slowly.
assert 4 <= path_length(out) < 4.02
def test_same_seed_same_result():
walls = [(4, -9, 6, 8)]
path = [(0, 0), (0, 9), (10, 9), (10, 0)]
assert shortcut(path, walls, 50, random.Random(9)) == shortcut(path, walls, 50, random.Random(9))
History
Shortcutting a path by joining points that can see each other is an old idea, used since the early sampling-based planners as their post-processing step. Geraerts and Overmars (2007) studied and compared shortcut heuristics systematically, including random shortcuts between points that are not vertices and partial shortcuts, together with methods that increase clearance. Hauser and Ng-Thow-Hing (2010) made the shortcuts dynamically feasible by using time-optimal bounded-acceleration trajectories. Lynch and Park (2017) discuss this kind of post-processing in their section on smoothing.
References
- Roland Geraerts and Mark H. Overmars, Creating high-quality paths for motion planning, The International Journal of Robotics Research 26(8), 2007, 845-863, the whole paper (shortcut heuristics, including random shortcuts between points on the path, compared on test scenes)
- Kris Hauser and Victor Ng-Thow-Hing, Fast smoothing of manipulator trajectories using optimal bounded-acceleration shortcuts, IEEE International Conference on Robotics and Automation, 2010, 2493-2498, the whole paper (shortcuts made of time-optimal trajectories under velocity and acceleration bounds)
- Kevin M. Lynch and Frank C. Park, Modern Robotics, Mechanics, Planning, and Control, Cambridge University Press, 2017, Section 10.8 (smoothing)
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 N97VRM Edit this page History Report an error Markdown