Algorithm Search⌘K

Algorithmcore

Reeds-Shepp path

Also called Reeds-Shepp curves.

Shortest path of a car that drives forward and backward with bounded curvature. Reeds and Shepp gave 48 candidate words; Sussmann and Tang reduced the sufficient family to 46.

Time
O(1) worst
Space
O(1) extra
Where
w = the number of candidate words, at most 48
Properties
deterministicexactofflinenot randomized
Origin
James A. Reeds, Lawrence A. Shepp, 1990

A Reeds-Shepp path is a shortest path between two poses of a car that can drive forward and backward and cannot turn tighter than a radius ρ\rho. A pose is (x,y,θ)(x, y, \theta), a position and a heading. Reeds and Shepp proved in 1990 that a shortest path always exists, has at most five pieces (arcs of radius ρ\rho and straight segments) and at most two cusps where the car changes gear, and has one of 48 words. Sussmann and Tang showed in 1991 that two of these words are never needed, so 46 suffice. The algorithm solves each word in closed form and keeps the shortest, in constant time. It is the analytic shot to the goal of hybrid A* and the steering function of many parking planners.

In plain words

You park a car in an empty lot. You may back up, and the steering wheel has a stop. The shortest way to the parking spot always uses at most five pieces: hard turns and straight runs, with at most two changes between forward and reverse. A U-turn on the spot, for example, is three short hard turns: forward left, back right, forward left.

There are only 48 patterns. Each one comes with a formula for the lengths of its pieces. You try all patterns and keep the shortest.

The problem

The model. The car is the unicycle model with a speed v∈{−1,+1}v \in \{-1, +1\} and a turn rate ∣ω∣≤1/ρ|\omega| \le 1/\rho, or the rear axle of the kinematic bicycle model with ρ=L/tan⁡δmax\rho = L/\tan\delta_{max}. The length of a path is the total distance, forward and backward, and a gear change costs nothing. There are no obstacles. The machine model is the real RAM.

Input. A start pose q0q_0 and a goal pose q1q_1, in meters and radians, and the minimum turning radius ρ>0\rho > 0 in meters.

Output. A word over {L,S,R}\{L, S, R\} and signed segment lengths, positive for forward and negative for backward, such that driving them from q0q_0 ends at q1q_1, and the sum of the absolute lengths is the least possible.

How it differs from close pages. The Dubins path is the same problem for a car that only drives forward. Every Dubins path is also a Reeds-Shepp path, so the Reeds-Shepp length is never longer, and it is often much shorter for goals behind the car. Kinodynamic planning adds obstacles and dynamics. A search such as A* on a lattice, or hybrid A*, handles the obstacles and calls this solver for heuristics and final connections.

The algorithm

Write the goal in the frame of the start and scale by 1/ρ1/\rho, so the start is (0,0,0)(0, 0, 0), the goal is (x,y,φ)(x, y, \varphi) and the radius is 1. Reeds and Shepp use three transformations of the goal that map solutions to solutions:

  • Time flip (x,y,φ)→(−x,y,−φ)(x, y, \varphi) \to (-x, y, -\varphi): drive every segment with the opposite sign. The word stays the same.
  • Reflection (x,y,φ)→(x,−y,−φ)(x, y, \varphi) \to (x, -y, -\varphi): swap L and R. The signs stay the same.
  • Backward (x,y,φ)→(xcos⁡φ+ysin⁡φ, xsin⁡φ−ycos⁡φ, φ)(x, y, \varphi) \to (x\cos\varphi + y\sin\varphi,\ x\sin\varphi - y\cos\varphi,\ \varphi): the same path read from the goal to the start, followed by a time flip. The order of the segments is reversed.

With these, nine base formulas of Section 8 of their paper give all 48 words. In the base words, ++ is forward and −- is backward.

In the family names, a bar ∣\mid marks a cusp, CuC_u marks two arcs of the same angle uu, and Cπ/2C_{\pi/2} an arc of angle π/2\pi/2.

Formula Base word Families Uses backward
8.1 L+S+L+L^+ S^+ L^+ CSCCSC no
8.2 L+S+R+L^+ S^+ R^+ CSCCSC no
8.3, 8.4 L+R−LL^+ R^- L C∣C∣CC \mid C \mid C, C∣CCC \mid CC, CC∣CCC \mid C yes
8.7 L+Ru+Lu−R−L^+ R^+_u L^-_u R^- CCu∣CuCCC_u \mid C_u C no
8.8 L+Ru−Lu−R+L^+ R^-_u L^-_u R^+ C∣CuCu∣CC \mid C_u C_u \mid C no
8.9 L+Rπ/2−S−L−L^+ R^-_{\pi/2} S^- L^- C∣Cπ/2SCC \mid C_{\pi/2} S C and, backward, CSCπ/2∣CC S C_{\pi/2} \mid C yes
8.10 L+Rπ/2−S−R−L^+ R^-_{\pi/2} S^- R^- C∣Cπ/2SCC \mid C_{\pi/2} S C and, backward, CSCπ/2∣CC S C_{\pi/2} \mid C yes
8.11 L+Rπ/2−S−Lπ/2−R+L^+ R^-_{\pi/2} S^- L^-_{\pi/2} R^+ C∣Cπ/2SCπ/2∣CC \mid C_{\pi/2} S C_{\pi/2} \mid C no
  1. REEDS-SHEPP(q0, q1, ρ)
  2. 1(x, y, φ) ← q1 in the frame of q0, with x and y divided by ρ
  3. 2best ← none
  4. 3(xb, yb) ← (x cos φ + y sin φ, x sin φ - y cos φ)
  5. 4for each base formula F and each goal g among (x, y, φ), (-x, y, -φ), (x, -y, -φ), (-x, -y, φ), and the same four for (xb, yb, φ) where F uses backward do
  6. 5if F(g) gives (t, u, v) within its ranges then build the signed lengths of the word; negate them for a time flip, swap L and R for a reflection, reverse their order for a backward goal
  7. 6ℓ ← ρ times the sum of the absolute lengths
  8. 7if best is none or ℓ < the length of best then best ← (word, ρ times the lengths)
  9. 8return best

Each base formula is a few lines of trigonometry. For example, 8.1 (L+S+L+L^+ S^+ L^+) puts the center of the left circle at the goal at (x−sin⁡φ,y+cos⁡φ)(x - \sin\varphi, y + \cos\varphi), takes (u,t)(u, t) as the polar coordinates of (x−sin⁡φ,y−1+cos⁡φ)(x - \sin\varphi, y - 1 + \cos\varphi), and sets v=φ−tv = \varphi - t; it accepts when t≥0t \ge 0 and v≥0v \ge 0 after wrapping to [−π,π)[-\pi, \pi). The tests "within its ranges" of line L5 keep only the sign pattern of the base word. The implementation follows the formulas as they appear in the ReedsSheppStateSpace class of the open source OMPL library, whose source marks misprints in formulas 8.3/8.4 and 8.11 of the paper and uses corrected forms.

Example

Let ρ=1\rho = 1 m and the start (0,0,0)(0, 0, 0), with all lengths in meters.

Parallel shift. The goal is (0,1,0)(0, 1, 0): the same heading, 1 m to the left. A forward-only car needs a loop, and the Dubins path is LSL with a quarter turn, 1 m straight and three quarters of a turn, of length 2π+1=7.28322\pi + 1 = 7.2832 m. The loop of lines L4 to L7 finds 8 candidates. The two shortest are:

Word Signed lengths (m) Length (m) Gear changes
R−L+R+L−R^- L^+ R^+ L^- −0.5054,0.8128,0.8128,−0.5054-0.5054, 0.8128, 0.8128, -0.5054 2.6362 2
R+L−R−L+R^+ L^- R^- L^+ 0.5054,−0.8128,−0.8128,0.50540.5054, -0.8128, -0.8128, 0.5054 2.6362 2

These are the two mirror images in time of the CC_u|C_uC family: back right a little, forward left and right by the same angle u=0.8128u = 0.8128 rad, and back left a little. The next family, LRLRL R L R with four arcs of 0.7227, is longer at 2.8909 m.

U-turn on the spot. The goal is (0,0,π)(0, 0, \pi). The answer is a C|C|C word of three arcs of π/3\pi/3 rad, for example forward left, backward right, forward left, with total length π=3.1416\pi = 3.1416 m. The Dubins path for the same goal is 7π/3=7.33047\pi/3 = 7.3304 m.

A goal in front. For the goal (3,4,π/2)(3, 4, \pi/2) the answer is the forward path L+S+L+L^+ S^+ L^+ with lengths 0.9828, 3.6056 and 0.5880, the same as the Dubins path, of length 5.1763 m. The best word with reverse, R+Lπ/2−S−Rπ/2−L+R^+ L^-_{\pi/2} S^- R^-_{\pi/2} L^+, has 7.2344 m.

Correctness

The proof shows that the three transformations map paths to paths, so each candidate of line L5 ends at the goal when its base formula does. It proves the base formula 8.1 in full as an example and relies on Section 8 of Reeds and Shepp for the others. The implementation checks the end pose of every candidate on 1500 random pairs of poses, within 10−910^{-9} m. The optimality comes from the theorem of Reeds and Shepp, which the page uses and does not prove: a shortest path exists and has one of the 48 words, with segment lengths in the ranges that the base formulas test.

Proof: The Reeds-Shepp algorithm returns a shortest path of a car that drives both waysfull

Line numbers refer to the pseudocode on the Reeds-Shepp path page. After line L1 the start is (0,0,0)(0, 0, 0), the goal is (x,y,φ)(x, y, \varphi) and the turning radius is 1; rigid motions and scaling map admissible paths to admissible paths and scale lengths by 1/ρ1/\rho. A path is a word over {L,S,R}\{L, S, R\} and signed lengths sis_i. On a segment of signed length ss the car moves with speed v=sign(s)v = \mathrm{sign}(s) for time ∣s∣|s|, with

x′=vcos⁡θ,y′=vsin⁡θ,θ′=vκ,x' = v\cos\theta,\quad y' = v\sin\theta,\quad \theta' = v\kappa,

where κ=+1\kappa = +1 on L, −1-1 on R and 00 on S. The length of the path is ∑i∣si∣\sum_i |s_i|.

Lemma 1 (time flip). If a path with word ww and lengths (si)(s_i) goes from (0,0,0)(0, 0, 0) to (x,y,φ)(x, y, \varphi), then the path with word ww and lengths (−si)(-s_i) goes from (0,0,0)(0, 0, 0) to (−x,y,−φ)(-x, y, -\varphi), and has the same length.

Proof. Let (x(τ),y(τ),θ(τ))(x(\tau), y(\tau), \theta(\tau)) be the first trajectory with speed v(τ)v(\tau) and curvature κ(τ)\kappa(\tau). Set x~=−x\tilde x = -x, y~=y\tilde y = y, θ~=−θ\tilde\theta = -\theta, v~=−v\tilde v = -v and κ~=κ\tilde\kappa = \kappa. Then x~′=−vcos⁡θ=v~cos⁡θ~\tilde x' = -v\cos\theta = \tilde v\cos\tilde\theta, y~′=vsin⁡θ=(−v~)(−sin⁡θ~)=v~sin⁡θ~\tilde y' = v\sin\theta = (-\tilde v)(-\sin\tilde\theta) = \tilde v\sin\tilde\theta and θ~′=−vκ=v~κ~\tilde\theta' = -v\kappa = \tilde v\tilde\kappa. So the new curve is a trajectory of the car with the same curvature on each segment, the same word, and the opposite signs. It starts at (0,0,0)(0, 0, 0) and ends at (−x,y,−φ)(-x, y, -\varphi). □\square

Lemma 2 (reflection). If a path with word ww and lengths (si)(s_i) goes from (0,0,0)(0, 0, 0) to (x,y,φ)(x, y, \varphi), then the path with L and R swapped in ww and the same lengths goes to (x,−y,−φ)(x, -y, -\varphi).

Proof. Set x~=x\tilde x = x, y~=−y\tilde y = -y, θ~=−θ\tilde\theta = -\theta, v~=v\tilde v = v, κ~=−κ\tilde\kappa = -\kappa. Then x~′=vcos⁡θ~\tilde x' = v\cos\tilde\theta, y~′=−vsin⁡θ=v~sin⁡θ~\tilde y' = -v\sin\theta = \tilde v\sin\tilde\theta and θ~′=−vκ=v~κ~\tilde\theta' = -v\kappa = \tilde v\tilde\kappa. □\square

Lemma 3 (backward). Let (xb,yb)=(xcos⁡φ+ysin⁡φ, xsin⁡φ−ycos⁡φ)(x_b, y_b) = (x\cos\varphi + y\sin\varphi,\ x\sin\varphi - y\cos\varphi). If a path with word ww and lengths (s1,…,sk)(s_1, \dots, s_k) goes from (0,0,0)(0, 0, 0) to (xb,yb,φ)(x_b, y_b, \varphi), then the path with the reversed word and lengths (sk,…,s1)(s_k, \dots, s_1) goes from (0,0,0)(0, 0, 0) to (x,y,φ)(x, y, \varphi).

Proof. Drive a path backward in time: run its segments in reverse order with negated lengths. This is a trajectory of the car, by the substitution τ→−τ\tau \to -\tau, v→−vv \to -v, which keeps κ\kappa. So if PP goes from AA to BB, its reversal goes from BB to AA with the reversed word and negated lengths. Now write the start (0,0,0)(0, 0, 0) in the frame of the goal (x,y,φ)(x, y, \varphi): it is (−xcos⁡φ−ysin⁡φ, xsin⁡φ−ycos⁡φ, −φ)(-x\cos\varphi - y\sin\varphi,\ x\sin\varphi - y\cos\varphi,\ -\varphi). The time flip of Lemma 1 maps this pose to (xb,yb,φ)(x_b, y_b, \varphi). So the given path, flipped in time by Lemma 1, goes from (0,0,0)(0, 0, 0) to the start seen from the goal, with negated lengths. Placed in the frame of the goal, it is a path from the goal to the start. Its reversal goes from the start to the goal, with the word reversed and the lengths negated twice, that is (sk,…,s1)(s_k, \dots, s_1). □\square

Line L5 applies exactly these maps: it negates the lengths for the goals (−x,y,−φ)(-x, y, -\varphi) and (−x,−y,φ)(-x, -y, \varphi), swaps L and R for (x,−y,−φ)(x, -y, -\varphi) and (−x,−y,φ)(-x, -y, \varphi), and reverses the order for the backward goals. The goal (−x,−y,φ)(-x, -y, \varphi) is the composition of Lemma 1 and Lemma 2, and the two maps commute. Each map is an involution, so the candidate built from a base solution for a transformed goal is a path to the original goal.

Lemma 4 (base formula 8.1). If L+S+L+L^+ S^+ L^+ is accepted with (t,u,v)(t, u, v), its path goes from (0,0,0)(0, 0, 0) to (x,y,φ)(x, y, \varphi).

Proof. By the motion on a left arc (see Lemma 1 of the Dubins path proof), the first arc of angle tt ends at (sin⁡t,1−cos⁡t)(\sin t, 1 - \cos t) with heading tt. The straight part of length uu ends at (sin⁡t+ucos⁡t, 1−cos⁡t+usin⁡t)(\sin t + u\cos t,\ 1 - \cos t + u\sin t). The last arc of angle vv ends at heading t+vt + v, and its position is the previous point plus (sin⁡(t+v)−sin⁡t, cos⁡t−cos⁡(t+v))(\sin(t + v) - \sin t,\ \cos t - \cos(t + v)). With v≡φ−tv \equiv \varphi - t, the heading is φ\varphi and the position is (ucos⁡t+sin⁡φ, 1+usin⁡t−cos⁡φ)(u\cos t + \sin\varphi,\ 1 + u\sin t - \cos\varphi). The formula takes (u,t)(u, t) as the polar coordinates of (x−sin⁡φ, y−1+cos⁡φ)(x - \sin\varphi,\ y - 1 + \cos\varphi), so ucos⁡t=x−sin⁡φu\cos t = x - \sin\varphi and usin⁡t=y−1+cos⁡φu\sin t = y - 1 + \cos\varphi, and the end point is (x,y)(x, y). □\square

The other base formulas (8.2, 8.3 and 8.4, 8.7, 8.8, 8.9, 8.10 and 8.11) come from the same kind of computation on the circles of the word: tangent lines for the words with S, and circles that touch at distance 2 for the words of arcs only. Reeds and Shepp derive them in Section 8 of their paper; the OMPL source corrects 8.3/8.4 and 8.11, and the implementation uses the corrected forms. We do not repeat the derivations. As a check of the code, the tests drive every accepted candidate on 1500 random pairs of poses and radii and find the end pose within 10−910^{-9} of the goal every time.

Theorem (Reeds and Shepp 1990). Between any two poses there is a shortest path of the car with speed ±1\pm 1 and curvature at most 1. Some shortest path has one of the 48 words of the theorem, with at most five segments and at most two cusps, and with segment parameters in the ranges of Section 8.

Sussmann and Tang (1991) and Boissonnat, Cérézo and Leblond (1994) gave proofs with the maximum principle. We use the theorem and do not reprove it.

Theorem (correctness). REEDS-SHEPP returns a path from q0q_0 to q1q_1 of the least length.

Proof. By Lemmas 1 to 4 and the derivations of Section 8, every candidate that line L5 builds is a path from q0q_0 to q1q_1, so the result is feasible and its length is at least the optimum. By the theorem of Reeds and Shepp, some shortest path P∗P^* has one of the 48 words with parameters in the stated ranges. Each of the 48 words is a base word of the table on the page, or the image of one under time flip, reflection and backward reading, and line L4 tries every one of these images. Within one word and its ranges, Section 8 solves the end-pose equations for the parameters, so the candidate of that word is P∗P^*, or a path of the same word with the same length. So line L7 sees a candidate of length at most ∣P∗∣|P^*| and keeps the least length, which therefore equals the optimum. Line L8 returns it. □\square

What the tests add. Beyond the end poses, the tests check on 4000 cases that no random path of up to five signed segments is shorter, including paths of the Reeds-Shepp shapes with arcs of exactly π/2\pi/2. They check that the length from q0q_0 to q1q_1 equals the length from q1q_1 to q0q_0, that every result has at most five segments and two gear changes, that each of the 18 base types (with reflections) is the answer somewhere, and the hand cases of the page: 4 m straight back, the U-turn on the spot of length π\pi, and the forward path of length 5.1763 m that equals the Dubins path.

Complexity

  • Time. At most 9 base formulas, each on 4 or 8 goals, so a fixed number of operations: O(1)O(1) in the real RAM. Measured: one call takes about 0.3 milliseconds in CPython on a loaded laptop, about 20 times a Dubins call.
  • Space. O(1)O(1).
  • Sampling. Points along the path for collision checks cost O(ℓ/Δs)O(\ell / \Delta s) for a length ℓ\ell and a spacing Δs\Delta s.

Properties

  • A metric. Unlike the Dubins length, the Reeds-Shepp length is symmetric: a path from q0q_0 to q1q_1, driven backward in time, is a path from q1q_1 to q0q_0 of the same length. It satisfies the triangle inequality, so it is a metric on the poses.
  • Continuous. The Reeds-Shepp car is small-time locally controllable, so the Reeds-Shepp distance is continuous in the poses (LaValle, Section 15.3.2). The best word can still jump, so the path is not continuous in the goal.
  • At most two cusps and five segments. Every word in the family has at most two gear changes.
  • Not unique. Mirror images in time often tie, as in the example.
  • Scale. Lengths scale with ρ\rho.

Variants and improvements

  • Dubins paths. Forward only; see Dubins path.
  • 46 words. Sussmann and Tang (1991) showed that two of the 48 words are never strictly needed, so 46 suffice. LaValle (Section 15.3.2) calls these 46 the Reeds-Shepp curves. The code does not remove the two extra words; testing them costs a little time and does not change the answer.
  • Gear change cost. Planners such as hybrid A* add a cost for reverse driving and for each gear change. The Reeds-Shepp path then is no longer optimal for that cost, and planners use it only as a candidate or a heuristic.
  • Continuous curvature. Clothoid pieces replace the curvature jumps for real steering; the result is longer.
  • Differential drive. For a robot that turns in place, the time-optimal paths are the Balkcom-Mason curves (LaValle, Section 15.3.3).

When to use it

Use it as the local path, the distance and the final shot to the goal for car-like robots that can reverse: parking, docking, forklifts. Use its length as an admissible heuristic in an empty map. If the robot must not reverse, use the Dubins path. Do not track the path as it is, because the curvature jumps and the car must stop at each cusp.

Pitfalls

  • Misprints in the paper. The OMPL source marks formulas 8.3/8.4 and 8.11 of the paper as misprinted. Use a corrected version, and test every candidate by driving it to the end.
  • Sign conventions. A backward left arc (L−L^-) turns the heading clockwise, because the heading rate is v/ρv/\rho with v<0v < 0. Code that changes the heading by the absolute length gets every backward arc wrong.
  • Rounding at zero segments. As for Dubins paths, square roots of quantities near 0 give lengths near 10−810^{-8} instead of 0, and the range tests need a small tolerance (here 10−1010^{-10}).
  • Wrapping. The range tests compare angles after wrapping to [−π,π)[-\pi, \pi). Wrapping to [0,2π)[0, 2\pi) changes which candidates pass.
  • Gear changes cost time. The shortest path can have two cusps where the car must stop. For a real car, a slightly longer path with fewer cusps can be faster.

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.

reeds_shepp_path.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/reeds-shepp-path/. The authors are listed in prov/FYPPAD.jsonl.

"""Shortest path of a car that drives forward and backward with a minimum turning radius rho.

Reeds and Shepp (1990) proved that a shortest path has at most five segments and
belongs to a family of 48 words (Sussmann and Tang 1991 reduced the sufficient family
to 46). Each segment is a left arc L, a right arc R or a straight segment S, driven
forward (+) or backward (-). The code follows the formulas of Reeds and Shepp, Section 8,
in the form of the OMPL ReedsSheppStateSpace: nine base formulas (8.1, 8.2, 8.3, 8.4,
8.7, 8.8, 8.9, 8.10, 8.11), each applied to the goal and to three transformed goals
(time flip, reflection, and both), and for some families also to the goal seen
backward. A segment length is signed: positive means forward and negative backward.
"""

import math

TWO_PI = 2.0 * math.pi
HALF_PI = 0.5 * math.pi
ZERO = 1e-10

# Segment kinds of the 18 base types, as in the OMPL table.
TYPES = (
    "LRL", "RLR", "LRLR", "RLRL", "LRSL", "RLSR", "LSRL", "RSLR", "LRSR",
    "RLSL", "RSRL", "LSLR", "LSR", "RSL", "LSL", "RSR", "LRSLR", "RLSRL",
)


def wrap(a):
    """Angle in [-pi, pi)."""
    return (a + math.pi) % TWO_PI - math.pi


def polar(x, y):
    return math.hypot(x, y), math.atan2(y, x)


def tau_omega(u, v, xi, eta, phi):
    delta = wrap(u - v)
    a = math.sin(u) - math.sin(delta)
    b = math.cos(u) - math.cos(delta) - 1.0
    t1 = math.atan2(eta * a - xi * b, xi * a + eta * b)
    t2 = 2.0 * (math.cos(delta) - math.cos(v) - math.cos(u)) + 3.0
    tau = wrap(t1 + math.pi) if t2 < 0.0 else wrap(t1)
    omega = wrap(tau - u + v - phi)
    return tau, omega


# Base formulas. Each returns (t, u, v) or None. The goal (x, y, phi) is in the start
# frame and scaled by 1 / rho.

def lp_sp_lp(x, y, phi):  # formula 8.1: L+ S+ L+
    u, t = polar(x - math.sin(phi), y - 1.0 + math.cos(phi))
    if t >= -ZERO:
        v = wrap(phi - t)
        if v >= -ZERO:
            return t, u, v
    return None


def lp_sp_rp(x, y, phi):  # formula 8.2: L+ S+ R+
    u1, t1 = polar(x + math.sin(phi), y - 1.0 - math.cos(phi))
    u1 = u1 * u1
    if u1 >= 4.0:
        u = math.sqrt(u1 - 4.0)
        theta = math.atan2(2.0, u)
        t = wrap(t1 + theta)
        v = wrap(t - phi)
        if t >= -ZERO and v >= -ZERO:
            return t, u, v
    return None


def lp_rm_l(x, y, phi):  # formulas 8.3 and 8.4: L+ R- L
    xi, eta = x - math.sin(phi), y - 1.0 + math.cos(phi)
    u1, theta = polar(xi, eta)
    if u1 <= 4.0:
        u = -2.0 * math.asin(0.25 * u1)
        t = wrap(theta + 0.5 * u + math.pi)
        v = wrap(phi - t + u)
        if t >= -ZERO and u <= ZERO:
            return t, u, v
    return None


def lp_rup_lum_rm(x, y, phi):  # formula 8.7: L+ R+ L- R-
    xi, eta = x + math.sin(phi), y - 1.0 - math.cos(phi)
    rho = 0.25 * (2.0 + math.hypot(xi, eta))
    if rho <= 1.0:
        u = math.acos(rho)
        t, v = tau_omega(u, -u, xi, eta, phi)
        if t >= -ZERO and v <= ZERO:
            return t, u, v
    return None


def lp_rum_lum_rp(x, y, phi):  # formula 8.8: L+ R- L- R+
    xi, eta = x + math.sin(phi), y - 1.0 - math.cos(phi)
    rho = (20.0 - xi * xi - eta * eta) / 16.0
    if 0.0 <= rho <= 1.0:
        u = -math.acos(rho)
        if u >= -HALF_PI:
            t, v = tau_omega(u, u, xi, eta, phi)
            if t >= -ZERO and v >= -ZERO:
                return t, u, v
    return None


def lp_rm_sm_lm(x, y, phi):  # formula 8.9: L+ R-(pi/2) S- L-
    xi, eta = x - math.sin(phi), y - 1.0 + math.cos(phi)
    rho, theta = polar(xi, eta)
    if rho >= 2.0:
        r = math.sqrt(rho * rho - 4.0)
        u = 2.0 - r
        t = wrap(theta + math.atan2(r, -2.0))
        v = wrap(phi - HALF_PI - t)
        if t >= -ZERO and u <= ZERO and v <= ZERO:
            return t, u, v
    return None


def lp_rm_sm_rm(x, y, phi):  # formula 8.10: L+ R-(pi/2) S- R-
    xi, eta = x + math.sin(phi), y - 1.0 - math.cos(phi)
    rho, theta = polar(-eta, xi)
    if rho >= 2.0:
        t = theta
        u = 2.0 - rho
        v = wrap(t + HALF_PI - phi)
        if t >= -ZERO and u <= ZERO and v <= ZERO:
            return t, u, v
    return None


def lp_rm_s_lm_rp(x, y, phi):  # formula 8.11: L+ R-(pi/2) S- L-(pi/2) R+
    xi, eta = x + math.sin(phi), y - 1.0 - math.cos(phi)
    rho, theta = polar(xi, eta)
    if rho >= 2.0:
        u = 4.0 - math.sqrt(rho * rho - 4.0)
        if u <= ZERO:
            t = wrap(math.atan2((4.0 - u) * xi - 2.0 * eta, -2.0 * xi + (u - 4.0) * eta))
            v = wrap(t - phi)
            if t >= -ZERO and v >= -ZERO:
                return t, u, v
    return None


def _four(f, x, y, phi):
    """The base formula on the goal and on its time flip, reflection, and both."""
    return (
        (f(x, y, phi), False, False),
        (f(-x, y, -phi), True, False),
        (f(x, -y, -phi), False, True),
        (f(-x, -y, phi), True, True),
    )


def _word(base, reflect):
    if not reflect:
        return base
    return base.translate(str.maketrans("LR", "RL"))


def candidates_unit(x, y, phi):
    """All candidate paths for radius 1, as (word, signed lengths)."""
    out = []

    def add(base, reflect, flip, lengths):  # @line L5
        s = -1.0 if flip else 1.0  # @line L5
        out.append((_word(base, reflect), tuple(s * a for a in lengths)))  # @line L5

    xb = x * math.cos(phi) + y * math.sin(phi)  # @line L3
    yb = x * math.sin(phi) - y * math.cos(phi)  # @line L3
    # CSC
    for r, flip, refl in _four(lp_sp_lp, x, y, phi):  # @line L4
        if r:
            add("LSL", refl, flip, r)
    for r, flip, refl in _four(lp_sp_rp, x, y, phi):  # @line L4
        if r:
            add("LSR", refl, flip, r)
    # CCC, forward and backward
    for r, flip, refl in _four(lp_rm_l, x, y, phi):  # @line L4
        if r:
            add("LRL", refl, flip, r)
    for r, flip, refl in _four(lp_rm_l, xb, yb, phi):  # @line L4
        if r:
            t, u, v = r
            add("LRL", refl, flip, (v, u, t))
    # CCCC
    for r, flip, refl in _four(lp_rup_lum_rm, x, y, phi):  # @line L4
        if r:
            t, u, v = r
            add("LRLR", refl, flip, (t, u, -u, v))
    for r, flip, refl in _four(lp_rum_lum_rp, x, y, phi):  # @line L4
        if r:
            t, u, v = r
            add("LRLR", refl, flip, (t, u, u, v))
    # CCSC, forward and backward
    for r, flip, refl in _four(lp_rm_sm_lm, x, y, phi):  # @line L4
        if r:
            t, u, v = r
            add("LRSL", refl, flip, (t, -HALF_PI, u, v))
    for r, flip, refl in _four(lp_rm_sm_rm, x, y, phi):  # @line L4
        if r:
            t, u, v = r
            add("LRSR", refl, flip, (t, -HALF_PI, u, v))
    for r, flip, refl in _four(lp_rm_sm_lm, xb, yb, phi):  # @line L4
        if r:
            t, u, v = r
            add("LSRL", refl, flip, (v, u, -HALF_PI, t))
    for r, flip, refl in _four(lp_rm_sm_rm, xb, yb, phi):  # @line L4
        if r:
            t, u, v = r
            add("RSRL", refl, flip, (v, u, -HALF_PI, t))
    # CCSCC
    for r, flip, refl in _four(lp_rm_s_lm_rp, x, y, phi):  # @line L4
        if r:
            t, u, v = r
            add("LRSLR", refl, flip, (t, -HALF_PI, u, -HALF_PI, v))
    return out


def reeds_shepp_candidates(q0, q1, rho):
    """All candidates as (length, word, signed segment lengths in meters)."""
    dx, dy = q1[0] - q0[0], q1[1] - q0[1]  # @line L1
    c, s = math.cos(q0[2]), math.sin(q0[2])  # @line L1
    x, y = (c * dx + s * dy) / rho, (-s * dx + c * dy) / rho  # @line L1
    phi = wrap(q1[2] - q0[2])  # @line L1
    out = []
    for word, lengths in candidates_unit(x, y, phi):  # @line L4
        seg = tuple(rho * a for a in lengths)  # @line L6
        out.append((sum(abs(a) for a in seg), word, seg))  # @line L6
    return out


def reeds_shepp_path(q0, q1, rho):
    """Shortest Reeds-Shepp path: (length, word, signed segment lengths in meters)."""
    best = None  # @line L2
    for cand in reeds_shepp_candidates(q0, q1, rho):
        if best is None or cand[0] < best[0]:  # @line L7
            best = cand  # @line L7
    return best  # @line L8


def step(q, kind, s, rho):
    """Exact pose after a signed arc length s (negative is backward) on one segment."""
    x, y, th = q
    if kind == "S":
        return x + s * math.cos(th), y + s * math.sin(th), th
    if kind == "L":
        nth = th + s / rho
        return x + rho * (math.sin(nth) - math.sin(th)), y - rho * (math.cos(nth) - math.cos(th)), nth
    if kind == "R":
        nth = th - s / rho
        return x - rho * (math.sin(nth) - math.sin(th)), y + rho * (math.cos(nth) - math.cos(th)), nth
    raise ValueError(kind)


def endpoint(q0, word, lengths, rho):
    q = q0
    for kind, s in zip(word, lengths):
        q = step(q, kind, s, rho)
    return q[0], q[1], wrap(q[2])


def gear_changes(lengths):
    """Number of switches between forward and backward along the path."""
    signs = [1 if a > 0 else -1 for a in lengths if abs(a) > 1e-12]
    return sum(1 for a, b in zip(signs, signs[1:]) if a != b)
test_reeds_shepp_path.py 127 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/reeds-shepp-path/. The authors are listed in prov/FYPPAD.jsonl.

import math
import random

from reeds_shepp_path import (
    TYPES,
    endpoint,
    gear_changes,
    reeds_shepp_candidates,
    reeds_shepp_path,
    wrap,
)

HALF_PI = 0.5 * math.pi


def pose_error(a, b):
    return max(abs(a[0] - b[0]), abs(a[1] - b[1]), abs(wrap(a[2] - b[2])))


def random_pose(rng, size=5.0):
    return (rng.uniform(-size, size), rng.uniform(-size, size), rng.uniform(-math.pi, math.pi))


def test_every_candidate_ends_at_the_goal():
    rng = random.Random(21)
    for _ in range(1500):
        q0, q1 = random_pose(rng), random_pose(rng)
        rho = rng.uniform(0.3, 2.0)
        cands = reeds_shepp_candidates(q0, q1, rho)
        assert cands
        for length, word, seg in cands:
            assert len(word) == len(seg)
            assert abs(length - sum(abs(a) for a in seg)) < 1e-12
            assert pose_error(endpoint(q0, word, seg, rho), q1) < 1e-9


def random_signed_path(rng, rho):
    """A random path of the car: a random word of up to five segments with random signs,
    or a word of the Reeds-Shepp shape with arcs of exactly pi / 2 where the shape has them."""
    if rng.random() < 0.5:
        word = "".join(rng.choice("LSR") for _ in range(rng.randint(1, 5)))
        seg = [rng.choice((-1.0, 1.0)) * (rng.uniform(0.0, 4.0) if k == "S" else rho * rng.uniform(0.0, math.pi)) for k in word]
        return word, seg
    word = rng.choice(TYPES)
    seg = []
    for i, k in enumerate(word):
        sign = rng.choice((-1.0, 1.0))
        fixed = "S" in word and k != "S" and (word[i - 1:i] == "S" or word[i + 1:i + 2] == "S") and len(word) >= 4
        if k == "S":
            seg.append(sign * rng.uniform(0.0, 4.0))
        elif fixed and rng.random() < 0.7:
            seg.append(sign * rho * HALF_PI)
        else:
            seg.append(sign * rho * rng.uniform(0.0, math.pi))
    return word, seg


def test_no_random_path_is_shorter():
    rng = random.Random(22)
    for _ in range(4000):
        rho = rng.uniform(0.5, 1.5)
        q0 = random_pose(rng)
        word, seg = random_signed_path(rng, rho)
        q1 = endpoint(q0, word, seg, rho)
        # 1e-7: a segment of length 0 can come out near 1e-8 from a square root.
        assert reeds_shepp_path(q0, q1, rho)[0] <= sum(abs(a) for a in seg) + 1e-7


def test_no_forward_path_is_shorter():
    # A forward path is also a Reeds-Shepp path, so the result is never longer.
    rng = random.Random(23)
    for _ in range(1500):
        q0 = random_pose(rng)
        word = "".join(rng.choice("LSR") for _ in range(rng.randint(1, 3)))
        seg = [rng.uniform(0.0, 3.0) for _ in word]
        q1 = endpoint(q0, word, seg, 1.0)
        assert reeds_shepp_path(q0, q1, 1.0)[0] <= sum(seg) + 1e-7


def test_reversal_symmetry():
    # Driving a path backward in time is a valid path from the goal to the start.
    rng = random.Random(24)
    for _ in range(800):
        q0, q1 = random_pose(rng), random_pose(rng)
        a = reeds_shepp_path(q0, q1, 1.0)[0]
        b = reeds_shepp_path(q1, q0, 1.0)[0]
        assert abs(a - b) < 1e-9


def test_every_base_type_is_optimal_somewhere():
    rng = random.Random(25)
    seen = set()
    for _ in range(4000):
        q0, q1 = random_pose(rng, 3.0), random_pose(rng, 3.0)
        seen.add(reeds_shepp_path(q0, q1, 1.0)[1])
    assert seen == set(TYPES)


def test_hand_cases():
    # Straight back by 4 m.
    length, word, seg = reeds_shepp_path((0.0, 0.0, 0.0), (-4.0, 0.0, 0.0), 1.0)
    assert abs(length - 4.0) < 1e-12 and word[seg.index(min(seg))] == "S"
    # U-turn on the spot with radius 1 m: three arcs of pi / 3 with two gear changes.
    length, word, seg = reeds_shepp_path((0.0, 0.0, 0.0), (0.0, 0.0, math.pi), 1.0)
    assert abs(length - math.pi) < 1e-9 and word in ("LRL", "RLR") and gear_changes(seg) == 2
    # A goal that a forward path reaches best: the same as the Dubins path (5.1763 m).
    length, word, seg = reeds_shepp_path((0.0, 0.0, 0.0), (3.0, 4.0, math.pi / 2.0), 1.0)
    assert word == "LSL" and abs(length - (math.atan2(3.0, 2.0) + math.sqrt(13.0) + math.pi / 2.0 - math.atan2(3.0, 2.0))) < 1e-9
    # Parallel shift by 1 m to the left: four arcs, shorter than 2.64 m.
    length, word, seg = reeds_shepp_path((0.0, 0.0, 0.0), (0.0, 1.0, 0.0), 1.0)
    assert len(word) == 4 and abs(length - 2.6362) < 1e-4
    # Scaling.
    a = reeds_shepp_path((0.0, 0.0, 0.3), (2.0, 1.0, -1.0), 1.0)[0]
    b = reeds_shepp_path((0.0, 0.0, 0.3), (6.0, 3.0, -1.0), 3.0)[0]
    assert abs(3.0 * a - b) < 1e-9


def test_at_most_five_segments_and_two_gear_changes():
    rng = random.Random(26)
    for _ in range(1500):
        q0, q1 = random_pose(rng), random_pose(rng)
        length, word, seg = reeds_shepp_path(q0, q1, 1.0)
        assert len(word) <= 5
        assert gear_changes(seg) <= 2

History

Reeds and Shepp (1990) extended the result of Dubins to a car that may reverse, with a long geometric proof and the closed forms of Section 8. Sussmann and Tang (1991) and Boissonnat, Cérézo and Leblond (1994) reproved it with the Pontryagin maximum principle, and Sussmann and Tang removed two words. Dolgov, Thrun, Montemerlo and Diebel used Reeds-Shepp paths as the analytic expansion of hybrid A* in the DARPA Urban Challenge of 2007.

References

  1. James A. Reeds and Lawrence A. Shepp, Optimal paths for a car that goes both forwards and backwards, Pacific Journal of Mathematics 145(2), 1990, pages 367 to 393 (the theorem with the 48 words, and Section 8 with the formulas 8.1 to 8.11 for the segment lengths)
  2. Shortest paths for the Reeds-Shepp car, a worked out example of the use of geometric techniques in nonlinear optimal control, the whole report (a proof with the maximum principle, and the reduction of the sufficient family from 48 to 46 words)
  3. Steven M. LaValle, Planning Algorithms, Cambridge University Press, 2006, Section 15.3.2 (Reeds-Shepp curves, the nine base words with cusps and the 46 curves that occur) and Section 15.4 (the Reeds-Shepp car is small-time locally controllable)
  4. Jean-Daniel Boissonnat, André Cérézo and Juliette Leblond, Shortest paths of bounded curvature in the plane, Journal of Intelligent and Robotic Systems 11, 1994, pages 5 to 20 (a proof of the results of Dubins and of Reeds and Shepp with the Pontryagin minimum principle)

Where this leads

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
  • a scene preset for the example