Algorithm Search⌘K

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.

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
Properties
randomizednot exactofflinerandomized

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 P=(x0,…,xn)P = (x_0, \dots, x_n) from a start to a goal, a test for whether a straight segment is free, a number NN of iterations, and a random number generator. Output: a free polyline from x0x_0 to xnx_n that is as short as possible. The code works in the plane with kk 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

  1. SHORTCUT(P, obstacles, N, rng)
  2. 1repeat N times
  3. 2compute the cumulative lengths of the segments of P
  4. 3draw s1, s2 uniform in [0, length(P)] and sort them
  5. 4a ← the point at arc length s1, on segment i; b ← the point at arc length s2, on segment j
  6. if i = j then continue ▷ same segment, nothing to gain
  7. 5if the segment ab is free then
  8. 6P ← (x0, ..., xi, a, b, x(j+1), ..., xn)
  9. 7return 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 aa and bb disappear, and aa and bb become vertices.

Example

The scene has one wall, the rectangle [4,6]×[−9,8][4, 6] \times [-9, 8], and the path goes around it the long way: (0,0)→(0,9)→(10,9)→(10,0)(0, 0) \to (0, 9) \to (10, 9) \to (10, 0), of length 28. The shortest path goes over the top corners of the wall, (0,0)→(4,8)→(6,8)→(10,0)(0, 0) \to (4, 8) \to (6, 8) \to (10, 0), of length 280+2≈19.8892\sqrt{80} + 2 \approx 19.889. 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 (0,0)(0, 0) to (4,0)(4, 0) shrank to length 4.01064.0106 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 n+1+Nn + 1 + N 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 P=(x0,x1,…,xn)P = (x_0, x_1, \dots, x_n) in the plane, and it is free if no segment xkxk+1x_k x_{k+1} 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 pp to qq meets the open interior of some rectangle (x0,x1)×(y0,y1)(x_0, x_1) \times (y_0, y_1).

Proof. Write the segment as p+t(q−p)p + t(q - p) for t∈[0,1]t \in [0, 1]. For one axis with d≠0d \ne 0, the coordinate lies in the open interval of the rectangle exactly for tt in the open interval between t0t_0 and t1t_1 of the code. For an axis with d=0d = 0, it lies there for all tt or for no tt; the code handles the second case by the flag. Let ℓ\ell be the maximum of 00 and the lower ends, and uu the minimum of 11 and the upper ends. If ℓ<u\ell < u, every tt strictly between them is in [0,1][0, 1] and in every open interval, so the segment meets the interior. Conversely, if some t∗t^* in [0,1][0, 1] is in every open interval, then ℓ≤t∗≤u\ell \le t^* \le u. Equality on both sides would need ℓ=t∗=0\ell = t^* = 0 (the open lower ends are below t∗t^*) and u=t∗=1u = t^* = 1, which is impossible. So ℓ<u\ell < u. □\square

The invariants

Consider one pass of the loop. Line L3 picks arc lengths s1≤s2s_1 \le s_2, and line L4 finds the points aa on segment ii and bb on segment jj of the current path. If i=ji = j nothing changes. Otherwise i<ji < j, and line L6 replaces the path by

P′=(x0,…,xi,a,b,xj+1,…,xn).P' = (x_0, \dots, x_i, a, b, x_{j+1}, \dots, x_n).

Lemma 2. If PP is free, so is P′P'.

Proof. The segments xkxk+1x_k x_{k+1} with k<ik < i or k>jk > j are segments of PP. The segment xiax_i a is part of the segment xixi+1x_i x_{i+1} of PP, and the segment bxj+1b x_{j+1} is part of xjxj+1x_j x_{j+1}, so they meet no interior. The segment abab passed the test of line L5, so by Lemma 1 it meets no interior either. □\square

Lemma 3. P′P' has the same end points as PP, and its length is at most the length of PP.

Proof. The point aa is on segment i≥0i \ge 0 and bb on segment j≤n−1j \le n - 1, so x0x_0 and xnx_n stay at the ends. The part of PP between arc lengths s1s_1 and s2s_2 is a polyline from aa to bb of length s2−s1s_2 - s_1. By the triangle inequality its length is at least ∣a−b∣|a - b|, the length of the new segment, and the rest of the path does not change. □\square

Lemma 4. P′P' has at most one more vertex than PP.

Proof. The vertices xi+1,…,xjx_{i+1}, \dots, x_j, at least one of them because j>ij > i, are removed, and the two vertices aa and bb are added. □\square

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 n+1+Nn + 1 + N vertices after NN iterations.

Proof. Induction on the iterations with Lemmas 2, 3 and 4. □\square

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 Θ(n′)\Theta(n') for the cumulative lengths, where n′n' is the current number of vertices, and Θ(k)\Theta(k) for the segment test against kk obstacles. The path gains at most one vertex per iteration, so n′≤n+Nn' \le n + N, and NN iterations cost Θ(N(n+N+k))\Theta(N(n + N + k)) 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.

random_shortcut_path_smoothing.pyI0RawGitHub
# 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

  1. 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)
  2. 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)
  3. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • History with a source
  • a scene preset for the example