AI Wiki中文/EN

Rapidly-exploring random trees: grow toward random points

快速探索随机树

How an RRT plans a collision-free path by growing a tree toward random samples, why the Voronoi bias makes it explore quickly, what probabilistic completeness does and does not promise, and how RRT* repairs path quality by choosing parents and rewiring, shown on a synthetic S-shaped corridor.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Grow a tree toward random points

A rapidly-exploring random tree (RRT) is a method for finding a collision-free path for a robot. It grows a tree of reachable positions outward from the start. At each step it picks a random point, finds the tree node nearest to it, and takes a short step from that node toward the point. Basic construction

Picture a small robot in a room where three walls form an S-shaped corridor. The robot has no map of the free space. It can only ask a collision checker, a program that answers “does this position, or this straight move, hit a wall?” The tree starts at the robot and creeps around the walls. When a branch reaches the goal, following the branch back to the start gives a path. In our synthetic version of this room, the first path the RRT found was on average 1.449 times as long as the shortest possible path.

The key is which node gets to grow. A node at the edge of the tree is the nearest node for a large patch of empty space, so random points select it often. The tree is therefore pulled outward into unexplored space, which is where the name “rapidly exploring” comes from. Voronoi explanation Pulling, not pushing

Steven LaValle introduced the RRT in a 1998 technical report. He designed it for robots with many joints and for robots whose motion is constrained, such as a car that cannot slide sideways. An RRT never has to join two given states exactly. It only has to move a little toward a random point, which even a car can do. Abstract and motivation

The basic RRT finds a path with probability approaching one, if a path exists and it runs long enough. It does not promise a short path. A 2011 variant called RRT* adds two repair steps. For robots without dynamics, and with a large enough search radius, its best path approaches the shortest one as the tree grows. To plan many different paths in one fixed environment, the related method is probabilistic roadmaps. Contributions

The loop, the bias, the guarantees, and RRT*

This section states the planning problem, gives the basic loop, explains why it explores quickly, separates three kinds of guarantee, and then describes RRT*.

The planning problem

A configuration is a complete description of where the robot is, for example the position of a point robot or the angle of every joint of an arm. The set of all configurations is the configuration space, introduced in robotics overview. When velocities matter too, planners search a state space, which also contains speeds. LaValle’s 1998 report treats both as a bounded space XX. The planner must find a continuous path from a start xinitx_{\text{init}} to a goal state or goal region. Problem setting, p. 2

The obstacles are not stored as shapes. The planner can only test whether a given state lies inside the obstacle region. Every tree vertex and every edge must lie in the free space XfreeX_{\text{free}}, the part of XX outside the obstacles. Problem setting, p. 2

Motion follows a state transition equation x˙=f(x,u)\dot x=f(x,u), where uu is the control input. A new state comes from integrating this equation over a short time Δt\Delta t, with Euler’s method or, preferably, a higher-order method such as Runge–Kutta. A robot is holonomic if it can move in any direction. In that case f(x,u)=uf(x,u)=u with ∥u∥≤1\lVert u\rVert\le 1. A nonholonomic robot, such as a car, cannot. State transition, p. 2

LaValle and Kuffner list six ingredients for an RRT planner. They are the state space, the start and goal, a collision detector, and the set of inputs. The other two are an incremental simulator, which applies an input for a short time, and a metric, a function that measures distance between states. Six components, p. 2

The basic loop

The tree starts with one vertex, the start. Then the same step repeats. GENERATE_RRT, p. 2 Fig. 1

  1. Draw a random state xrandx_{\text{rand}}, usually uniformly over the space.
  2. Find the tree vertex xnearx_{\text{near}} nearest to it under the metric.
  3. Choose the input that moves xnearx_{\text{near}} closest to xrandx_{\text{rand}} without collision, and simulate it to get xnewx_{\text{new}}.
  4. If the move is collision-free, add xnewx_{\text{new}} and an edge from xnearx_{\text{near}}, storing the input.

LaValle and Kuffner call one such step EXTEND. It has three outcomes: Reached (the new vertex reaches the sample), Advanced (a vertex is added short of the sample), and Trapped (no collision-free new state exists). EXTEND, pp. 4–5

For a holonomic robot moving in straight lines, Karaman and Frazzoli write step 3 as a function called Steer. Steer, p. 11

xnew=Steer⁡(xnear,xrand)=arg⁡min⁡z: ∥z−xnear∥≤η∥z−xrand∥x_{\text{new}}=\operatorname{Steer}(x_{\text{near}},x_{\text{rand}})=\arg\min_{z:\ \lVert z-x_{\text{near}}\rVert\le\eta}\lVert z-x_{\text{rand}}\rVert

In words: among the points zz within distance η\eta of the nearest vertex, take the one closest to the sample. So the tree moves straight toward xrandx_{\text{rand}} by at most a step size η\eta, and reaches it exactly if it is closer than η\eta.

Why it explores quickly: the Voronoi bias

The Voronoi cell of a vertex is the region of space closer to that vertex than to any other vertex. A uniform random sample falls in some vertex’s cell, and that vertex is the one extended. So each vertex is chosen with probability proportional to the size of its cell. LaValle and Kuffner state this in words; the formula below is our own transcription, for uniform sampling and the nearest-vertex rule. Voronoi bias, pp. 4–5

Pr⁡(v is extended)=μ(Vor⁡(v))μ(X)\Pr(v\ \text{is extended})=\frac{\mu(\operatorname{Vor}(v))}{\mu(X)}

In words: the chance that vertex vv grows next equals the area (in general, the volume μ\mu) of its Voronoi cell Vor⁡(v)\operatorname{Vor}(v), divided by the area of the whole space XX. Vertices on the frontier face open space, so their cells are large and they grow most.

A naive random tree behaves differently. If you pick a random vertex and move it in a random direction, every vertex is equally likely to grow. Most vertices sit near the root, so the tree keeps growing where it already is. LaValle’s 1998 report makes this comparison, and Part 2 of our example repeats it. Naive random tree, p. 3 LaValle and Kuffner describe the RRT as pulling the tree toward samples, unlike planners that push a tree away from its existing vertices. Pull versus push, p. 4

In the long run the vertices spread like the samples. LaValle and Kuffner prove that the vertex distribution converges in probability to the sampling distribution (their Theorem 4). LaValle’s 1998 report had already argued that the vertices become uniform regardless of the root, and checked this with chi-square tests. Theorem 4, p. 6 Uniformity, pp. 3–4

Three different promises

Planners can promise three quite different things. Keep them apart.

A complete planner finds a path whenever one exists and reports failure otherwise. Sampling-based planners such as the RRT are not complete. With random samples they are probabilistically complete: if a path exists, the probability of finding one tends to one as the number of samples grows. LaValle stresses that the speed of this convergence is the most useful information, but it is usually very hard to establish. Completeness notions, pp. 185–186

For a holonomic robot, LaValle and Kuffner prove probabilistic completeness. The free space must be bounded, open and connected, though it may be nonconvex. The distance from any free point to the nearest vertex then goes to zero in probability (Lemmas 1–2, Theorem 3). Theorem 3, p. 5 Karaman and Frazzoli restate the result with a failure probability that decays exponentially in the number of samples. They attribute it to LaValle and Kuffner (2001). Theorem 16, p. 17

For nonholonomic robots the proof in LaValle and Kuffner needs restrictive conditions. The input set must be finite and Δt\Delta t constant. EXTEND must pick inputs at random. Vertices must be at least some ϵ\epsilon apart. The goal must be reachable by some finite sequence of inputs (Theorem 5). Theorem 5, p. 6

The third promise is asymptotic optimality: as the number of samples goes to infinity, the cost of the best path found converges to the optimal cost, with probability one. Probabilistic completeness says nothing about this. Both of LaValle’s early papers say that bounds on convergence rate and path quality remained open. Open questions, pp. 3–4 Rate of convergence, p. 6

What they did report were measurements. In LaValle’s 1998 experiments in convex 2-D regions, tree paths to the root averaged 1.3 to 2.0 times the optimal length. LaValle and Kuffner report a ratio of tree distance to straight-line distance consistently between 1.3 and 1.7 in a square region. These are observations from experiments, not bounds. Path ratio, p. 3 Path ratio, p. 7

Why the basic RRT is not asymptotically optimal

Karaman and Frazzoli prove that the RRT is not asymptotically optimal (their Theorem 33). The cost of its best path converges to a random limit. With probability one that limit is strictly above the optimum. They note that this explains why restarting the RRT many times helps. Theorem 33, p. 28

The reason is visible in the loop. Each new vertex is joined to its nearest vertex, and edges are never changed. Once the branch that reaches the goal has formed, new vertices elsewhere cannot straighten it.

RRT*: choose a parent, then rewire

RRT* keeps the RRT’s way of creating vertices but chooses edges more carefully. It needs the cost-to-come of each vertex, the length of the tree path from the start to that vertex. RRT*, Algorithm 6

Cost⁡(v)=Cost⁡(Parent⁡(v))+∥v−Parent⁡(v)∥,Cost⁡(xinit)=0\operatorname{Cost}(v)=\operatorname{Cost}(\operatorname{Parent}(v))+\lVert v-\operatorname{Parent}(v)\rVert,\qquad \operatorname{Cost}(x_{\text{init}})=0

In words: the cost of reaching a vertex is the cost of reaching its parent plus the length of the edge between them, and the start costs nothing.

When RRT* adds xnewx_{\text{new}}, it looks at all vertices within a radius rr. Two steps follow. RRT*, pp. 15–16

  • Choose parent. Among nearby vertices that can be joined to xnewx_{\text{new}} without collision, pick the one that gives xnewx_{\text{new}} the lowest cost-to-come. The nearest vertex is only the default.
  • Rewire. For each nearby vertex, check whether going through xnewx_{\text{new}} would be cheaper than its current path. If so, make xnewx_{\text{new}} its new parent.

For the same sequence of samples, RRT and RRT* build the same set of vertices. They differ only in their edges. Same vertices, pp. 14–15 Karaman and Frazzoli state that RRT* costs at most a constant factor more computation than RRT. Complexity, p. 1 and p. 4

The radius shrinks as the tree grows. In Karaman and Frazzoli’s arXiv version, it is given as follows. Algorithm 6 and Theorem 38, pp. 15–16 and 29

r(∣V∣)=min⁡{γRRT∗(log⁡∣V∣∣V∣)1/d, η},γRRT∗>(2(1+1/d))1/d(μ(Xfree)ζd)1/dr(|V|)=\min\left\{\gamma_{\mathrm{RRT}^*}\left(\frac{\log|V|}{|V|}\right)^{1/d},\ \eta\right\},\qquad \gamma_{\mathrm{RRT}^*}>\bigl(2(1+1/d)\bigr)^{1/d}\left(\frac{\mu(X_{\text{free}})}{\zeta_d}\right)^{1/d}

In words: ∣V∣|V| is the number of vertices, dd the dimension of the space, μ(Xfree)\mu(X_{\text{free}}) the volume of free space and ζd\zeta_d the volume of a unit ball (ζ2=π\zeta_2=\pi). The radius shrinks as the tree grows, but slowly enough that each new vertex still has about log⁡∣V∣\log|V| neighbours, and it never exceeds the step size η\eta. If the constant γRRT∗\gamma_{\mathrm{RRT}^*} is above the stated threshold, RRT* is asymptotically optimal.

A companion result (Theorem 39) covers a version that uses the kk nearest vertices instead of a radius. In the arXiv version it is asymptotically optimal if kRRT∗>2d+1e(1+1/d)k_{\mathrm{RRT}^*}>2^{d+1}e(1+1/d). Theorem 39, p. 29 The radius constant for the roadmap method PRM* in the same paper is different, 2(1+1/d)1/d(μ(Xfree)/ζd)1/d2(1+1/d)^{1/d}(\mu(X_{\text{free}})/\zeta_d)^{1/d}; do not mix the two. PRM*, pp. 13–14

These results have conditions. Karaman and Frazzoli prove them for path planning without differential constraints, in a bounded region of dd-dimensional space with d≥2d\ge 2 and straight-line connections. Robots with dynamics are left to other work. Problem formulation, pp. 4–6

Practical variants

Goal bias. Instead of always sampling uniformly, return the goal itself with a small probability. LaValle and Kuffner found that a bias such as 0.05 usually converges much faster. Too much bias makes the planner act like a potential-field planner, one that always heads downhill toward the goal, and it gets stuck in local minima behind obstacles. RRT-GoalBias, p. 7 LaValle’s book gives 1/100 as an example probability, with the same warning. Goal bias, p. 235

CONNECT. CONNECT repeats EXTEND toward the same sample until the sample is reached or the tree is trapped. LaValle and Kuffner found CONNECT best for holonomic problems and EXTEND best for nonholonomic ones, because CONNECT trusts the metric more. CONNECT, pp. 7–8

Two trees. A bidirectional RRT grows one tree from the start and one from the goal and tries to grow them into each other. LaValle and Kuffner found this much more efficient than one tree when it applies. Their most successful holonomic version extended one tree and ran CONNECT on the other. Bidirectional, p. 8 The catch is that under differential constraints the two trajectories must meet exactly. That needs steering or shooting methods, while one tree reaching a goal region does not. Joining trees, pp. 8–9 LaValle’s book recommends always extending the smaller tree. This helps in “bug trap” problems, where one tree has trouble escaping a pocket. Balanced search, p. 236

Many trees. Start a new tree at every sample and merge trees whenever they connect, and you get the probabilistic roadmap. PRM as a limit, p. 9 More than two trees, p. 237

The book’s version. In LaValle’s book an RRT is the random case of a rapidly exploring dense tree (RDT). The book joins each sample to the nearest point anywhere on the tree, not just the nearest vertex, and drops the step size. It notes that the step-size version is easier to implement. RDTs, pp. 229–231, footnote 14

The metric. The ideal metric would be the true cost-to-go, such as the shortest-path length. Computing it is as hard as solving the planning problem, so planners use simple metrics. Metric problem, p. 3 Finding the nearest vertex quickly is its own problem, often solved with a Kd-tree; see approximate nearest-neighbour search. Nearest points, p. 235

An S-shaped corridor, by simulation

This section runs RRT and RRT* on a small synthetic world and compares them with the exact shortest path. The program is original, uses only numpy, and has fixed seeds. All numbers are properties of this toy world and these seeds, not general performance figures.

The robot is a point in the square [0,10]2[0,10]^2. Three closed rectangular walls, (2,0)(2,0)–(3,7)(3,7), (5,3)(5,3)–(6,10)(6,10) and (7,0)(7,0)–(8,6)(8,6), form an S-shaped corridor. The start is (1,1)(1,1) and the goal is a disc of radius 0.5 around (9,1)(9,1). Edges are checked exactly against the rectangles (Liang–Barsky clipping). Real planners usually check points along an edge instead. The exact shortest path comes from a visibility graph, the graph of straight lines between rectangle corners that do not cross a wall, searched with Dijkstra’s algorithm (see uniform-cost search).

“Iterations” counts samples drawn. “Vertices” counts the start plus accepted extensions; a sample whose new point or edge collides is discarded.

import heapq
import numpy as np

# Synthetic 2-D world: point robot in the square [0, 10] x [0, 10].
# Obstacles are closed axis-aligned rectangles (xmin, ymin, xmax, ymax).
RECTS = np.array([
    [2.0, 0.0, 3.0, 7.0],   # wall rising from the bottom
    [5.0, 3.0, 6.0, 10.0],  # wall hanging from the top
    [7.0, 0.0, 8.0, 6.0],   # wall rising from the bottom
])
LO, HI = 0.0, 10.0
START = np.array([1.0, 1.0])
GOAL = np.array([9.0, 1.0])
GOAL_RADIUS = 0.5


def point_free(p):
    x, y = p
    inside = (RECTS[:, 0] <= x) & (x <= RECTS[:, 2]) & (RECTS[:, 1] <= y) & (y <= RECTS[:, 3])
    return not inside.any()


def segments_free(a, b):
    # Exact test: does segment a[i] -> b[i] avoid every closed rectangle?
    # Liang-Barsky clipping against all rectangles at once. a, b: (m, 2).
    a = np.atleast_2d(a)[:, None, :]
    d = np.atleast_2d(b)[:, None, :] - a
    lo = RECTS[None, :, :2]
    hi = RECTS[None, :, 2:]
    t0 = np.zeros((a.shape[0], RECTS.shape[0]))
    t1 = np.ones_like(t0)
    hit = np.ones(t0.shape, dtype=bool)
    for k in range(2):
        dk = d[..., k]
        ak = a[..., k]
        par = np.abs(dk) < 1e-15
        outside = par & ((ak < lo[..., k]) | (ak > hi[..., k]))
        hit &= ~outside
        with np.errstate(divide="ignore", invalid="ignore"):
            ta = (lo[..., k] - ak) / dk
            tb = (hi[..., k] - ak) / dk
        tmin = np.where(par, -np.inf, np.minimum(ta, tb))
        tmax = np.where(par, np.inf, np.maximum(ta, tb))
        t0 = np.maximum(t0, tmin)
        t1 = np.minimum(t1, tmax)
    hit &= t0 <= t1
    return ~hit.any(axis=1)


def seg_free(a, b):
    return bool(segments_free(a[None], b[None])[0])


def steer(x_near, x_rand, eta):
    d = x_rand - x_near
    n = np.hypot(d[0], d[1])
    return x_rand.copy() if n <= eta else x_near + d * (eta / n)


def visibility_optimum():
    # Shortest collision-free path for a point robot among rectangles:
    # Dijkstra on the visibility graph of start, goal and rectangle corners
    # (corners pushed 1e-6 outward so grazing edges count as free).
    e = 1e-6
    nodes = [START, GOAL]
    for x0, y0, x1, y1 in RECTS:
        for c in ([x0 - e, y0 - e], [x1 + e, y0 - e], [x0 - e, y1 + e], [x1 + e, y1 + e]):
            c = np.array(c)
            if LO <= c[0] <= HI and LO <= c[1] <= HI and point_free(c):
                nodes.append(c)
    P = np.array(nodes)
    m = len(P)
    I, J = np.triu_indices(m, 1)
    ok = segments_free(P[I], P[J])
    adj = [[] for _ in range(m)]
    for i, j, f in zip(I, J, ok):
        if f:
            w = float(np.hypot(*(P[i] - P[j])))
            adj[i].append((j, w))
            adj[j].append((i, w))
    dist = [np.inf] * m
    dist[0] = 0.0
    pq = [(0.0, 0)]
    while pq:
        dcur, u = heapq.heappop(pq)
        if dcur > dist[u]:
            continue
        for v, w in adj[u]:
            if dcur + w < dist[v]:
                dist[v] = dcur + w
                heapq.heappush(pq, (dist[v], v))
    return dist[1]


def sample(rng, goal_bias):
    if rng.random() < goal_bias:
        return GOAL.copy()
    return rng.uniform(LO, HI, size=2)


def rrt_first_solution(seed, eta=0.5, goal_bias=0.05, max_iter=20000):
    # Basic RRT (nearest vertex, steer by at most eta, keep the edge if free).
    # Stops at the first vertex inside the goal disc.
    rng = np.random.default_rng(seed)
    V = np.empty((max_iter + 1, 2))
    parent = np.empty(max_iter + 1, dtype=int)
    cost = np.empty(max_iter + 1)
    V[0], parent[0], cost[0] = START, -1, 0.0
    n = 1
    for it in range(1, max_iter + 1):
        x_rand = sample(rng, goal_bias)
        i_near = int(np.argmin(((V[:n] - x_rand) ** 2).sum(axis=1)))
        x_new = steer(V[i_near], x_rand, eta)
        if point_free(x_new) and seg_free(V[i_near], x_new):
            V[n], parent[n] = x_new, i_near
            cost[n] = cost[i_near] + np.hypot(*(x_new - V[i_near]))
            n += 1
            if np.hypot(*(x_new - GOAL)) <= GOAL_RADIUS:
                return it, n, cost[n - 1]
    return None, n, np.inf


def rrt_and_rrtstar(seed, n_iter, checkpoints, eta=1.0, goal_bias=0.05, gamma=None):
    # Runs RRT and RRT* on the same sample sequence and reports, at each
    # checkpoint, the best cost-to-come among vertices in the goal disc.
    rng = np.random.default_rng(seed)
    cap = n_iter + 1
    V = np.empty((cap, 2))
    par_rrt = np.empty(cap, dtype=int)
    c_rrt = np.empty(cap)
    par_star = np.empty(cap, dtype=int)
    c_star = np.empty(cap)
    children = [[] for _ in range(cap)]
    V[0] = START
    par_rrt[0] = par_star[0] = -1
    c_rrt[0] = c_star[0] = 0.0
    n = 1
    rewires = 0
    out = {}
    for it in range(1, n_iter + 1):
        x_rand = sample(rng, goal_bias)
        d2 = ((V[:n] - x_rand) ** 2).sum(axis=1)
        i_near = int(np.argmin(d2))
        x_new = steer(V[i_near], x_rand, eta)
        if point_free(x_new) and seg_free(V[i_near], x_new):
            # RRT: parent is the nearest vertex.
            par_rrt[n] = i_near
            c_rrt[n] = c_rrt[i_near] + np.hypot(*(x_new - V[i_near]))
            # RRT*: choose the cheapest parent in the shrinking ball, then rewire.
            r = min(gamma * np.sqrt(np.log(n) / n), eta) if n > 1 else eta
            dn = np.sqrt(((V[:n] - x_new) ** 2).sum(axis=1))
            near = np.nonzero(dn <= r)[0]
            if near.size:
                free = segments_free(V[near], np.repeat(x_new[None], near.size, 0))
                near, dnear = near[free], dn[near[free]]
            else:
                dnear = dn[near]
            best, cbest = i_near, c_star[i_near] + dn[i_near]
            if near.size:
                k = int(np.argmin(c_star[near] + dnear))
                if c_star[near[k]] + dnear[k] < cbest:
                    best, cbest = int(near[k]), float(c_star[near[k]] + dnear[k])
            V[n] = x_new
            par_star[n], c_star[n] = best, cbest
            children[best].append(n)
            for j, dj in zip(near, dnear):
                if cbest + dj < c_star[j] - 1e-12:
                    children[par_star[j]].remove(j)
                    par_star[j] = n
                    children[n].append(j)
                    delta = c_star[j] - (cbest + dj)
                    stack = [j]
                    while stack:  # propagate the cost drop to all descendants
                        u = stack.pop()
                        c_star[u] -= delta
                        stack.extend(children[u])
                    rewires += 1
            n += 1
        if it in checkpoints:
            in_goal = np.hypot(V[:n, 0] - GOAL[0], V[:n, 1] - GOAL[1]) <= GOAL_RADIUS
            b_rrt = c_rrt[:n][in_goal].min() if in_goal.any() else np.inf
            b_star = c_star[:n][in_goal].min() if in_goal.any() else np.inf
            out[it] = (n, b_rrt, b_star, rewires, r if n > 1 else eta)
    # Consistency check: stored RRT* costs equal costs recomputed along parents.
    err = 0.0
    for v in range(1, n):
        p = par_star[v]
        err = max(err, abs(c_star[v] - c_star[p] - np.hypot(*(V[v] - V[p]))))
    return out, err


def coverage_demo(K=500, seed=0):
    # LaValle (1998) style setting: empty square [0,100]^2, step 1, root (50,50).
    # RRT versus a naive random tree (random vertex, random direction).
    lo, hi, step, root = 0.0, 100.0, 1.0, np.array([50.0, 50.0])
    g = np.linspace(0.5, 99.5, 100)
    G = np.stack(np.meshgrid(g, g), -1).reshape(-1, 2)
    res = {}
    for name in ("rrt", "naive"):
        rng = np.random.default_rng(seed)
        V = np.empty((K, 2))
        V[0] = root
        for n in range(1, K):
            if name == "rrt":
                x = rng.uniform(lo, hi, size=2)
                i = int(np.argmin(((V[:n] - x) ** 2).sum(axis=1)))
                d = x - V[i]
                new = V[i] + d / np.hypot(*d) * step
            else:
                i = int(rng.integers(n))
                th = rng.uniform(0, 2 * np.pi)
                new = V[i] + step * np.array([np.cos(th), np.sin(th)])
            V[n] = np.clip(new, lo, hi)
        far = float(np.hypot(*(V - root).T).max())
        covered = 0
        for chunk in np.array_split(G, 10):
            dmin = np.sqrt(((chunk[:, None, :] - V[None]) ** 2).sum(-1)).min(1)
            covered += int((dmin <= 5.0).sum())
        res[name] = (far, covered / len(G))
    return res


opt = visibility_optimum()
free_area = (HI - LO) ** 2 - float(((RECTS[:, 2] - RECTS[:, 0]) * (RECTS[:, 3] - RECTS[:, 1])).sum())
d = 2
gamma_star = (2 * (1 + 1 / d)) ** (1 / d) * (free_area / np.pi) ** (1 / d)
print("World: [0,10]^2, 3 rectangles, start (1,1), goal disc r=0.5 at (9,1)")
print(f"free area = {free_area:.1f}, optimal path length (visibility graph) = {opt:.4f}")
print(f"optimal length to goal-disc boundary = {opt - GOAL_RADIUS:.4f}")
print()
print("[1] Basic RRT, eta=0.5, goal bias 0.05, stop at first vertex in goal disc")
it0, n0, c0 = rrt_first_solution(0)
print(f"seed 0: iterations={it0}, vertices={n0}, path length={c0:.4f}, ratio to optimum={c0 / (opt - GOAL_RADIUS):.3f}")
stats = []
for s in range(20):
    it, n, c = rrt_first_solution(s)
    stats.append((it, n, c / (opt - GOAL_RADIUS)))
st = np.array(stats, dtype=float)
print(f"20 seeds: solved {int(np.isfinite(st[:, 2]).sum())}/20, median iterations={np.median(st[:, 0]):.0f}, "
      f"min/max iterations={st[:, 0].min():.0f}/{st[:, 0].max():.0f}")
print(f"20 seeds: path/optimum ratio mean={st[:, 2].mean():.3f}, min={st[:, 2].min():.3f}, max={st[:, 2].max():.3f}")
print()
print("[2] Voronoi bias: empty [0,100]^2, step 1, root (50,50), 500 vertices")
cov = coverage_demo()
for name in ("rrt", "naive"):
    far, frac = cov[name]
    print(f"{name:5s}: farthest vertex from root={far:.2f}, grid points within 5 of a vertex={frac:.3f}")
print()
gamma = 1.1 * gamma_star
print(f"[3] RRT vs RRT* on the same samples, eta=1.0, gamma*={gamma_star:.4f}, gamma={gamma:.4f}")
cps = (1000, 2000, 3000, 4000)
out, err = rrt_and_rrtstar(1, 4000, cps, gamma=gamma)
def fmt(c):
    return "no path yet" if not np.isfinite(c) else f"{c:.4f} ({c / (opt - GOAL_RADIUS):.3f}x)"


for k in cps:
    n, br, bs, rw, r = out[k]
    print(f"iter {k:4d}: vertices={n:4d}, radius={r:.4f}, best RRT={fmt(br)}, best RRT*={fmt(bs)}, rewires so far={rw}")
print(f"RRT* stored costs match costs recomputed along parent links (max error < 1e-9): {err < 1e-9}")
print()
print("[4] Five seeds, 2000 iterations: best cost / optimum")
rows = []
for s in range(2, 7):
    o, _ = rrt_and_rrtstar(s, 2000, (2000,), gamma=gamma)
    _, br, bs, _, _ = o[2000]
    rows.append((br / (opt - GOAL_RADIUS), bs / (opt - GOAL_RADIUS)))
    print(f"seed {s}: RRT {rows[-1][0]:.3f}, RRT* {rows[-1][1]:.3f}")
rows = np.array(rows)
print(f"mean: RRT {rows[:, 0].mean():.3f}, RRT* {rows[:, 1].mean():.3f}")

The program prints:

World: [0,10]^2, 3 rectangles, start (1,1), goal disc r=0.5 at (9,1)
free area = 80.0, optimal path length (visibility graph) = 21.8162
optimal length to goal-disc boundary = 21.3162

[1] Basic RRT, eta=0.5, goal bias 0.05, stop at first vertex in goal disc
seed 0: iterations=899, vertices=542, path length=27.8689, ratio to optimum=1.307
20 seeds: solved 20/20, median iterations=1171, min/max iterations=711/1718
20 seeds: path/optimum ratio mean=1.449, min=1.295, max=1.585

[2] Voronoi bias: empty [0,100]^2, step 1, root (50,50), 500 vertices
rrt  : farthest vertex from root=48.28, grid points within 5 of a vertex=0.379
naive: farthest vertex from root=6.19, grid points within 5 of a vertex=0.028

[3] RRT vs RRT* on the same samples, eta=1.0, gamma*=8.7404, gamma=9.6144
iter 1000: vertices= 451, radius=1.0000, best RRT=no path yet, best RRT*=no path yet, rewires so far=366
iter 2000: vertices=1219, radius=0.7343, best RRT=33.3145 (1.563x), best RRT*=23.7576 (1.115x), rewires so far=1150
iter 3000: vertices=2041, radius=0.5876, best RRT=33.3145 (1.563x), best RRT*=23.1021 (1.084x), rewires so far=1777
iter 4000: vertices=2858, radius=0.5074, best RRT=33.3145 (1.563x), best RRT*=22.3850 (1.050x), rewires so far=2422
RRT* stored costs match costs recomputed along parent links (max error < 1e-9): True

[4] Five seeds, 2000 iterations: best cost / optimum
seed 2: RRT 1.726, RRT* 1.070
seed 3: RRT 1.455, RRT* 1.077
seed 4: RRT 1.459, RRT* 1.056
seed 5: RRT 1.499, RRT* 1.065
seed 6: RRT 1.577, RRT* 1.046
mean: RRT 1.543, RRT* 1.063

The world. The free area is 100−(7+7+6)=80100-(7+7+6)=80. The shortest path to the goal centre has length 21.8162 (exercise 2 checks this by hand). Stopping at the edge of the goal disc saves 0.5, giving 21.3162. All ratios below divide by 21.3162.

Part 1: basic RRT. All 20 seeds reached the goal disc; seed 0 needed 899 iterations and found a path 1.307 times the optimum. The mean ratio, 1.449, falls inside the 1.3–2.0 range LaValle observed, but our world is not convex and this proves nothing general.

Part 2: Voronoi bias. This repeats the setting of LaValle’s 1998 comparison in spirit: an empty square, step 1, 500 vertices grown from the centre. With the same number of vertices, the RRT reaches 48.28 from the root and covers 37.9% of the test grid; the naive tree reaches 6.19 and covers 2.8%.

Part 3: RRT versus RRT on the same samples.* For this world the arXiv threshold is γ∗=8.7404\gamma^*=8.7404, and we use γ=1.1γ∗\gamma=1.1\gamma^* (our choice). Both trees first reach the goal between 1000 and 2000 iterations. From then on RRT’s best path stays at 33.3145 (1.563 times optimal), while RRT*‘s shrinks from 1.115 to 1.050 times optimal by 4000 iterations. The final check line confirms that the stored RRT* costs equal the costs recomputed along parent links.

The printed radius is the one used for the last accepted vertex. It uses the vertex count before that insertion, as the code computes r before adding the vertex. At the 2000-iteration checkpoint that count is 1218: 9.6144×ln⁡1218/1218=9.6144×7.1050/1218=9.6144×0.07638=0.73439.6144\times\sqrt{\ln 1218/1218}=9.6144\times\sqrt{7.1050/1218}=9.6144\times0.07638=0.7343. At 1000 iterations the formula gives more than 1, so the cap η=1\eta=1 applies.

Part 4: five more seeds. At 2000 iterations RRT* is shorter on every seed, with the same vertices: mean ratio 1.063 against 1.543 for RRT.

Part 3 shows the theory at small scale: RRT’s goal branch is frozen while RRT*‘s keeps shortening. It is one run, not a proof of convergence.

Where the guarantees stop

This section lists what an RRT does not promise and where it struggles.

No path quality from the basic RRT. Probabilistic completeness is about finding some path. The basic RRT’s best cost converges to a value above the optimum (Theorem 33). Theorem 33, p. 28 The 1.3–2.0 and 1.3–1.7 ratios are experimental observations, not bounds. Path ratio, p. 3 Path ratio, p. 7

Failure proves nothing. A sampling-based planner that fails after any finite budget has not shown that no path exists. Completeness notions, pp. 185–186 Narrow passages need many samples, and the convergence rate is generally unknown. A planner that can certify “no path” must be complete, which usually means a combinatorial method.

The metric problem. The nearest vertex under a simple metric may be a poor place to grow from, especially for cars and other constrained robots. The true cost-to-go would be ideal but is as hard to compute as the plan itself. Metric problem, p. 3

Guarantees with dynamics are narrow. For nonholonomic robots, LaValle and Kuffner’s completeness proof needs the restrictive conditions listed above. Theorem 5, p. 6 Karaman and Frazzoli’s optimality results for RRT* assume no differential constraints. Problem formulation, pp. 4–6 They do not, by themselves, show that RRT* is asymptotically optimal for a car or a robot with dynamics.

Goal bias can trap. Strong goal bias keeps pushing the vertex nearest the goal into the same wall, where it is Trapped again and again. RRT-GoalBias, p. 7

Edge checking. Real planners check an edge at points spaced Δq\Delta q apart. Too small a spacing wastes collision checks. Too large a spacing can jump through a thin obstacle. Checking a segment, p. 216 Our example avoids this with an exact rectangle test, which real robots rarely have.

Single query versus many. An RRT does no precomputation, while a roadmap does. LaValle and Kuffner say that direct speed comparisons are therefore not straightforward, and examples favouring either method are easy to build. Comparison, p. 9

The example is a toy. A point robot, three rectangles, chosen step sizes and seeds. Asymptotic optimality is a limit statement, and our 1.050 at 4000 iterations is a single run.

Exercises

These exercises cover the Voronoi bias, two hand calculations, a counterexample about guarantees, and method choice.

  1. Why does an RRT spread out quickly while a naive random tree (pick a random vertex, move in a random direction) stays near the root? Use the example’s numbers.

    Answer: In an RRT the vertex that grows is the nearest vertex to a uniform sample. So each vertex grows with probability proportional to the area of its Voronoi cell. Frontier vertices have large cells and grow most, which pulls the tree outward. The naive tree grows every vertex equally often, and most vertices are near the root, so it keeps growing where it already is. In Part 2, after 500 vertices the RRT’s farthest vertex is 48.28 from the root and 37.9% of test points are within 5 of the tree. The naive tree reaches 6.19 and covers 2.8%.

  2. (a) In the example world the shortest path from (1,1)(1,1) to (9,1)(9,1) bends around the corners (2,7)(2,7), (3,7)(3,7), (5,3)(5,3), (6,3)(6,3), (7,6)(7,6) and (8,6)(8,6). Compute its length and compare with 21.8162. (b) Compute γ∗\gamma^* for RRT* in this world (d=2d=2, free area 80) and compare with 8.7404.

    Answer: (a) The segments are (1,1)→(2,7)(1,1)\to(2,7): 1+36=6.0828\sqrt{1+36}=6.0828; (2,7)→(3,7)(2,7)\to(3,7): 1; (3,7)→(5,3)(3,7)\to(5,3): 4+16=4.4721\sqrt{4+16}=4.4721; (5,3)→(6,3)(5,3)\to(6,3): 1; (6,3)→(7,6)(6,3)\to(7,6): 1+9=3.1623\sqrt{1+9}=3.1623; (7,6)→(8,6)(7,6)\to(8,6): 1; (8,6)→(9,1)(8,6)\to(9,1): 1+25=5.0990\sqrt{1+25}=5.0990. The sum is 21.8162. Stopping at the goal disc saves 0.5 along the last straight segment, giving 21.3162. (b) γ∗=(2(1+1/2))1/2(80/π)1/2=3×25.465=1.7321×5.0463=8.7404\gamma^*=(2(1+1/2))^{1/2}(80/\pi)^{1/2}=\sqrt3\times\sqrt{25.465}=1.7321\times5.0463=8.7404.

  3. A teammate says: “RRT is probabilistically complete, so if we run it long enough the path will become the shortest one. And if it fails after 10 000 iterations, there is no path.” Give a counterexample to each half.

    Answer: First half: probabilistic completeness is about finding a path, not about its length. Karaman and Frazzoli prove that RRT is not asymptotically optimal: its best cost converges to a random value above the optimum with probability one. In Part 3 RRT’s best path stays at 33.3145 (1.563 times optimal) from 2000 to 4000 iterations, while RRT* improves to 1.050. Second half: probabilistic completeness is not completeness. Failure after a finite budget does not prove that no path exists, and a narrow passage can need very many samples. Only a complete planner can certify that no path exists.

  4. Which planner would you choose, and why? (a) A car-like robot with dynamics must reach a goal region once, in a new environment. (b) A 7-joint arm in a fixed work cell must answer thousands of start–goal queries. (c) A point robot on a small 2-D grid map, where the shortest path at grid resolution is wanted. (d) A mobile robot that should return a first path quickly and keep improving it while time remains.

    Answer: (a) A single RRT using EXTEND, sampling in state space and applying inputs through the simulator. It never needs to steer exactly between two given states, which is what RRTs were designed for. (b) A probabilistic roadmap (probabilistic roadmaps): the precomputation pays off over many queries in a fixed cell. (c) Grid search with A*, which is optimal at the grid’s resolution and cheap in 2-D. Karaman and Frazzoli note both this resolution limit and that grid size grows exponentially with dimension. (d) RRT*, which keeps improving its path and is asymptotically optimal under the radius condition for robots without dynamics. Another option is a basic RRT followed by local smoothing with trajectory optimisation.

  5. Why can too much goal bias hurt? What values do the sources use?

    Answer: With strong bias, many samples are the goal itself. The tree keeps extending the vertex nearest the goal straight toward it. If a wall is in the way, that vertex is Trapped again and again, like a potential-field planner stuck in a local minimum. Small biases keep most samples exploring: LaValle and Kuffner use 0.05, and LaValle’s book gives 1/100 as an example. Our example uses 0.05.

History and further reading

This section summarises the original papers we read and suggests where to go next.

LaValle’s report “Rapidly-exploring random trees: A new tool for path planning” was Technical Report TR 98-11 of the Computer Science Department at Iowa State University, dated October 1998. The number and date come from the bibliography of LaValle’s book, because the PDF’s header did not survive text extraction. The four-page report presents the RRT for nonholonomic and high-dimensional problems and says it had been applied to problems with up to twelve degrees of freedom. Abstract, p. 1 Bibliography entry 103 It is a technical report, not a journal or conference paper. It already expected that RRTs “might be faster” than a basic roadmap planner for holonomic problems, while admitting that a conclusive comparison was difficult. Comparison with PRM, p. 3

LaValle and Kuffner’s “Rapidly-exploring random trees: Progress and prospects” appeared as a chapter in the 2001 book Algorithmic and Computational Robotics: New Directions, edited by Donald, Lynch and Rus. It adds the EXTEND and CONNECT functions, goal bias, the bidirectional versions and the probabilistic-completeness theorems used above. Sections 3–5 Bibliography entry 108 The chapter names its two-tree variants RRT-ExtExt, RRT-ExtCon and RRT-ConCon, after which function each tree uses.

Karaman and Frazzoli’s “Sampling-based algorithms for optimal motion planning” was posted on arXiv in May 2011 and published in the International Journal of Robotics Research the same year. It proved that RRT is not asymptotically optimal and introduced RRT* together with PRM* and the rapidly-exploring random graph (RRG). The constants quoted in this article are from the arXiv version. Abstract and contributions, pp. 1–5

For a textbook treatment, Chapter 5 of LaValle’s Planning Algorithms places RRTs within rapidly exploring dense trees and roadmaps. Section 5.5 For the two-tree idea on graphs, see bidirectional search. For the joint spaces in which arms are planned, see robot kinematics and inverse kinematics. For one source of the map a collision checker uses, see occupancy maps. Arm motions in grasping and manipulation tasks are a common use of RRTs.

Make a prediction, then check

In the example, RRT and RRT* use the same random sample sequence. From iteration 2000 to 4000, RRT's best path stays at 33.3145 (1.563 times the optimum) while RRT* falls from 1.115 to 1.050 times. Which explanation is correct?

Choose one answer

Learning objectives

  • Write the basic RRT loop (sample, nearest vertex, step-limited steering, collision check, add edge), explain with the Voronoi bias why it reaches into unexplored space quickly, and state what goal bias, CONNECT and bidirectional search each do and risk.
  • Distinguish probabilistic completeness, completeness and asymptotic optimality; explain why RRT is not asymptotically optimal, how RRT* improves paths by choosing parents, rewiring and a connection radius that shrinks with the vertex count, and which conditions that guarantee depends on.

Prerequisites & connections

Explore related knowledge →

References

  1. Rapidly-exploring random trees: A new tool for path planning — scoped
    Steven M. LaValle · 1998
  2. Rapidly-exploring random trees: Progress and prospects — scoped
    Steven M. LaValle; James J. Kuffner · 2001
  3. Sampling-based algorithms for optimal motion planning (arXiv v1) — scoped
    Sertac Karaman; Emilio Frazzoli · 2011
  4. Planning Algorithms, Chapter 5: Sampling-Based Motion Planning — scoped
    Steven M. LaValle · 2006

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Claude · 2026-12-03 · Independent AI check (Claude subagent, not the author; not a human or expert review). Research was done by a separate research subagent (facts.md) and the prose by a writer subagent. Gemini app style-only edits had been applied to the English opening (intuition) section before this check; each logged edit was compared with its old text and none changed a fact, hedge or attribution. The Chinese opening had no Gemini pass, so the checker did its own D012 readability pass on it. Ran example.py with the pinned interpreter (numpy 1.26.4): output identical to example.stdout.txt, and the python block in en.mdx and zh.mdx is byte-identical to example.py. Re-derived the visibility-graph optimum 21.8162/21.3162, gamma* = 8.7404, the printed radius 0.7343 at 1218 vertices and the cap at 1000 iterations, and checked every number quoted in the prose against the output. Re-opened the sources myself: Karaman-Frazzoli arXiv:1105.1186v1 via pdftotext (Steer p. 11, PRM*/RRG constants pp. 13-14, RRT* text and Algorithm 6 pp. 15-16, Theorems 15-16 p. 17, Theorem 33 p. 28, Theorems 38-39 p. 29, abstract p. 1, section 1.3 and problem scope p. 4); LaValle's Planning Algorithms ch. 5 via pdftotext (RDT swath and footnote 14 pp. 229-230, goal bias 1/100 and balanced bidirectional search pp. 235-236, sampling-based roadmaps pp. 237-238 and 246); LaValle 1998 TR (4 pages) and LaValle-Kuffner 2001 (PDF pp. 1-9) by OCR, spot-checking twelve DOF, naive tree and random walk bias, the 1.3-2.0 ratio in 2-D convex spaces, chi-square uniformity, 'might be faster', the six components, pull versus push, Reached/Trapped, Theorems 3-5, the 1.3-1.7 ratio, goal bias 0.05, RRT-ExtCon and the PRM limiting case. Compared zh and en section by section, checked display-equation parity, citation IDs, MDX safety, links (only published topics are linked; probabilistic-roadmaps, grasping and manipulation stay inline code) and data.json catalogue IDs and quiz answer. Not checked: the IJRR journal version of Karaman-Frazzoli, their proofs and complexity section, and LaValle-Kuffner pp. 10-19.

  • example.py run with the pinned interpreter (numpy 1.26.4) matches example.stdout.txt; the zh and en code blocks are byte-identical to example.py.
  • Hand-checked the optimum 21.8162, gamma* = 8.7404, radius 0.7343 and the ratios; all match the output.
  • Re-opened Karaman-Frazzoli arXiv v1: Steer is on p. 11, Algorithm 6 on pp. 15-16, Theorem 33 on p. 28, and Theorem 38 (radius constant) and Theorem 39 (k-nearest constant) on p. 29.
  • Checked LaValle's chapter 5: the RDT joins each sample to the nearest point of the tree's swath and footnote 14 drops the step size; goal bias 1/100 and balanced bidirectional search are on pp. 235-236.
  • Spot-checked the claims cited to LaValle 1998 and LaValle-Kuffner 2001 by OCR; all are supported.
  • zh and en compared section by section: same claims, numbers, exercises, answers and caveats; equations, citation IDs and links match, and the MDX is safe.

Source locations checked:

  • Rapidly-exploring random trees: A new tool for path planning — scoped · Lav98c.pdf, 4 PDF pages, Type-3 fonts so pdftotext fails; rendered at 200 dpi and OCR'd with tesseract; all 4 pages read in full. p. 1: abstract (nonholonomic constraints incl. dynamics, high DOF, up to twelve DOF), §1 motivation (PRM connection problem can be as hard as a nonlinear controller). p. 2: §2 problem setting (metric space X, implicit X_obs, X_free), state transition equation, Euler/Runge-Kutta, holonomic f = u, GENERATE_RRT pseudocode and explanation. p. 3: §3 seven properties, square [0,100]^2 with Δt = 1 and root (50,50), naive random tree bias, Voronoi explanation, 1.3–2.0 path ratio, chi-square uniformity, uniform-convergence argument, metric problem, comparison with PRM (single nearest neighbour, minimal edges, 'difficult to make a conclusive experimental comparison'). p. 4: §4 examples, §5 research issues (multiple RRTs, goal bias warning, convergence-rate bounds open), references. Report number TR 98-11 and date Oct. 1998 not visible in the OCR text; taken from Planning Algorithms bibliography entry [103]. Figures not inspected beyond captions.
  • Rapidly-exploring random trees: Progress and prospects — scoped · LavKuf01.pdf, 19 PDF pages, OCR as above. Read in full PDF pp. 1–9: abstract; §1 introduction (differential constraints, dynamic-programming contrast, PRM connection problem, p. 3); §2 six-component formulation, holonomic/nonholonomic/kinodynamic cases (pp. 2–4); §3 BUILD_RRT and EXTEND with Reached/Advanced/Trapped, pull-vs-push, Voronoi-area selection probability (pp. 4–5); §4 Lemmas 1–2, Theorem 3 (p. 5), Theorems 4–5 and conditions, open rate of convergence, convex-hull branches, 1.3–1.7 ratio (pp. 6–7); §5 RRT-GoalBias (0.05), GoalZoom, step size, CONNECT (p. 7–8), bidirectional RRT_BIDIRECTIONAL, ExtExt/ExtCon/ConCon, many trees and PRM as the limiting case (pp. 8–9); start of §6 (single- vs multiple-query comparison, p. 9). Skimmed only the first lines of pp. 10–16 (experiments, conclusions, references). Venue (A K Peters 2001, pp. 293–308) taken from Planning Algorithms bibliography [108]; not printed in the PDF. Not read: experiment details, figures.
  • Sampling-based algorithms for optimal motion planning (arXiv v1) — scoped · arXiv:1105.1186v1 PDF via pdftotext, arXiv PDF page numbers. Read pp. 1–6 (abstract; §1.1 PRM/RRT background; §1.2 optimal planning and grid A* resolution limit, p. 4; §1.3 contributions; Table 1, p. 5; §2.1 problem formulation, p. 6); pp. 11–17 (§3.1 Steer with η and Near; §3.2 Algorithms 1–3 PRM, sPRM, RRT with k-nearest/bounded-degree/variable-radius variants, p. 12; §3.3 PRM* (radius and k rules), RRG, RRT* Algorithms 4–6, pp. 13–16; §4.1 robust feasibility, Definition 14, Theorems 15–16, p. 17); pp. 28–29 (Theorem 33 non-optimality of RRT and the restart remark; Theorems 34–39 including Theorem 38's γ_RRT* condition; opening of §4.3). Not read: §2.2 beyond the k-nearest percolation theorem on p. 9, §4.2.1 other proofs, §4.3 complexity analysis, §5 experiments, §6, appendices. Journal version (IJRR 30(7), 2011) not opened; the Theorem 38 constant is quoted from v1 only.
  • Planning Algorithms, Chapter 5: Sampling-Based Motion Planning — scoped · ch5.pdf (printed pp. 185–248) via pdftotext. Read: chapter opening pp. 185–186 (complete / resolution complete / probabilistically complete, rate of convergence); §5.3.4 opening pp. 215–216 (path-segment checking with step Δq); §5.5 pp. 229–237: RDT definition, footnote 14 (step size dropped), Figs. 5.16–5.21 exploration algorithm and stopping configuration, §5.5.2 opening and Kd-tree paragraph (p. 235), §5.5.3 single-tree goal bias 1/100 (p. 235), balanced bidirectional RDT Fig. 5.24 (p. 236), more than two trees and the PRM limit (p. 237); Further Reading pp. 245–246; bibliography entries [103], [105]–[108]. Not read: §5.1–§5.2, §5.3.1–5.3.3, most of §5.4, §5.5.2 approximate methods in detail, Chapter 14.

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.