Algorithmcore
Stanley controller
Also called Stanley steering control.
Steers by the heading error plus the arctangent of gain times cross-track error over speed at the front axle. Locally exponentially stable for the kinematic bicycle at positive speed.
- Time
- O(n) worst
- Space
- O(1) extra
- Where
- n = the number of vertices of the path polyline; the bounds are for one control step
- Model
- Real RAM
- Properties
- deterministicnot exactonlinenot randomized
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Sebastian Thrun, Michael Montemerlo, Gabriel M. Hoffmann, Claire J. Tomlin, 2006
The Stanley controller is a steering law for a car that follows a path. It looks at the front axle. It measures the heading error , the angle between the path and the car, and the cross-track error , the signed distance from the center of the front axle to the closest point of the path. It steers with , where is the speed of the front wheels and is a gain. The first term aligns the wheels with the path, and the second turns them toward the path, more strongly when the error is large or the car is slow. For the kinematic bicycle model at a constant positive speed and without saturation, the cross-track error on a straight path converges to zero for every start, and the path is locally exponentially stable. The law steered Stanley, the car that won the DARPA Grand Challenge of 2005.
In plain words
Look at the road at your front wheels, not far ahead. Two things are wrong: the car points in a slightly wrong direction, and the front wheels are a bit to the side of the line. Turn the wheels to fix the direction, and turn them a bit more toward the line. If you are far from the line, turn toward it hard. If you are close, turn toward it gently.
At high speed, the same distance from the line asks for a smaller correction, because the car covers ground fast. That is why the speed is in the formula.
The problem
The model. The car is the kinematic bicycle model with the reference point at the center of the front axle: , , , with wheelbase , speed of the front wheels, and steering angle . The speed comes from another loop. The path is a polyline in the plane. The machine model is the real RAM.
Input. The path, the pose of the front axle, the speed , the gain in 1/s and the steering limit .
Output. A steering angle in radians for the next control period.
How it differs from close pages. Pure pursuit uses the rear axle and a goal point at a lookahead distance, and ignores the heading of the path; it is smoother but cuts corners, and it has no proof of convergence for large errors. The Stanley law uses the closest point at the front axle and the path heading, so it reacts at once to errors, and it needs a positive speed. Model predictive control uses a dynamic model and a horizon. A PID controller on the cross-track error is the usual baseline, with three gains and no geometry.
The algorithm
STANLEY(path, (xf, yf, θ), u, k, δmax)- 1
(i, s) ← the point of the path closest to (xf, yf), searching from the last index onward - 2
e ← signed distance from (xf, yf) to that point, positive when the path is to the left of the front axle - 3
ψ ← wrap(heading of segment i - θ) - 4
δ ← ψ + arctan(k e / u) - 5
δ ← clamp(δ, -δmax, δmax) - 6
apply δ for one control period - 7
the vehicle moves; repeat from L1 at the next period
With this sign convention, a positive is a left turn and reduces a positive . Line L4 uses the two-argument arctangent of in the code. Thrun et al. write the law with the cross-track error and the speed , as . The implementation integrates the model with the classical Runge-Kutta method, either with held for a step, like a digital controller, or with recomputed in each stage, which integrates the continuous closed loop of the proof.
Example
Let m, 1/s and m/s; the wheelbase and the gain are the values in Thrun et al. (2006). The path is the axis, and the front axle starts at with heading 0, so it is 1 m to the left of the path. Line L2 gives m and line L3 gives . Line L4 gives rad, a right turn of 11.3 degrees.
From then on, the proof shows that , whatever the heading, as long as the steering does not saturate. With , the time to go from to is with . The table gives the time to reach 1 cm for :
| (m/s) | From 1 m (s) | From 10 m (s) |
|---|---|---|
| 1 | 4.831 | 14.248 |
| 5 | 4.615 | 7.663 |
| 20 | 4.606 | 6.968 |
| pure exponential | 4.605 | 6.908 |
For a small , the error decays like and the speed does not matter. For a large one, the front axle drives straight at the path, and the time is about the distance over the speed. Measured: with a steering limit of 24 degrees, m/s and m, the steering saturates for the first 0.79 s, and the error reaches 1 cm at 7.873 s instead of 7.663 s.
Correctness
The proof works under three hypotheses: the kinematic bicycle model at the front axle, a constant speed , and no saturation of line L5. Lemma 1 shows that on a straight path the law gives for every heading. Theorem 1 solves this equation: the error keeps its sign, decreases strictly to zero from every start, and decays like once it is small. Theorem 2 shows that the heading also converges and that the path is locally exponentially stable, with the eigenvalues and . Theorem 3 shows that a circle of radius is an equilibrium, with . The behavior under saturation, with dynamics or on general curved paths is not proved; Hoffmann et al. (2007) give an analysis for positive speed, and the tests measure convergence with a 24 degree limit.
Proof: The Stanley law drives the cross-track error to zero on a straight pathfull
Line numbers refer to the pseudocode on the Stanley controller page. The vehicle is the kinematic bicycle model with the reference point at the center of the front axle. The front wheels roll with speed in the direction , and the rear wheels roll along , so
Hypotheses. H1: the model above holds (no tire slip, no actuator delay, the steering is updated continuously). H2: the speed is constant. H3: the steering does not saturate, , so line L5 does not clip. The gain is in 1/s. The path is the axis, except in Theorem 3. Then the closest point of the path to the front axle is , the cross-track error of line L2 is (positive when the front axle is to the right of the path), and the heading error of line L3 is .
Lemma 1 (the error equation). Under H1 to H3, on the straight path,
for every heading .
Proof. Line L4 gives , so . Then . With , this is .
The heading drops out: the law turns the front wheels to point at the path at the angle , whatever the body does. This is equation (8) of Thrun et al. (2006). The test test_error_rate_is_independent_of_the_heading checks the lemma on 3000 random unsaturated states to .
Theorem 1 (the cross-track error). Under H1 to H3 on the straight path, keeps its sign, decreases strictly to 0, and with and
the solution satisfies . Moreover , and decays like as .
Proof. By Lemma 1, . The right side is Lipschitz, and is an equilibrium, so a solution that starts at never reaches 0 in finite time and keeps its sign; decreases strictly because . For , separate the variables: . The derivative of is . With , the first and third terms sum to , and . So and . For the equation is odd in , and depends on . Since , , so , which gives the exponential bound. As , , so , which decays like .
So the error converges for every initial error, at an exponential rate that depends on how large is. For a large error, : the front axle drives straight at the path at nearly full speed. The test test_continuous_loop_matches_the_implicit_solution integrates the continuous loop from m, rad with 1/s and m/s and finds equal to within s at every step of 10 ms.
Theorem 2 (the heading and local exponential stability). Under H1 to H3 on the straight path, . The state is locally exponentially stable, with the eigenvalues and of the linearization.
Proof. Let , so and , with by H3. By Theorem 1, decreases to 0. Fix and a time with for . When and , has the sign of and , so . So falls below in finite time and does not leave the interval after that. As is arbitrary, . For the second claim, linearize at the origin: and . The matrix is triangular with eigenvalues and , both negative, so by the Jacobian linearization principle the origin of the nonlinear loop is locally exponentially stable.
Theorem 3 (a circle is an equilibrium). Let the path be a circle of radius , traversed counterclockwise. If the front axle is on the circle and the heading lags the tangent of the circle by , then the law returns , and the vehicle keeps that relation for all time.
Proof. The front axle is on the path, so , , and line L4 gives . The front wheels then point along the tangent, so the front axle moves along the circle with speed , and the tangent turns at the rate . The heading turns at , the same rate, so stays constant and stays 0.
The rear axle runs on the circle of radius inside the path. The test test_circle_is_an_equilibrium drives 30 m on a polyline of 20000 chords around a circle of radius 20 m and finds the front axle within m of the circle; the steering stays within rad of rad, a deviation that comes from the turn of rad between chords.
What is not proved. Theorems 1 and 2 need H3. With a steering limit, the law can saturate, and the paper's monotone convergence claim covers only the unsaturated equation. The test test_converges_with_a_steering_limit is a measurement, not a proof: from 25 random starts with errors up to 10 m and 1 rad, a limit of 24 degrees, and a held steering of 10 ms, the loop reaches the path within m. At low speed, is large and the law reduces to steering at the path at a right angle, which is why the softening constant of the page exists. The page does not prove stability on curved paths other than the equilibrium of Theorem 3, nor with dynamics, slip or delay.
Complexity
- Time per step. Finding the closest point costs for a path of vertices in the worst case, and with a search window of a few segments near the last index, which the implementation offers. The law itself is . Measured: one call takes about 1.5 microseconds in CPython on a laptop for a path of two points.
- Space. beyond the path.
Properties
- Global on a straight path. Without saturation, the cross-track error converges from any start, monotonically, without overshoot. This is a theorem for the kinematic model, not a measurement.
- Speed scaling. For small errors, the decay rate is in time, not in distance, so the car covers about m per e-fold of the error. At high speed the correction stretches over a long distance.
- Low speed. As , the term goes to for any nonzero error, and the law becomes very sensitive to noise in . The softening constant below fixes this.
- Front axle reference. The law needs the pose of the front axle. A pose estimate at the rear axle or the center of mass must be moved to the front axle first.
- Curved paths. On a circle, the equilibrium heading lags the path by , and the rear axle runs inside the path, on the circle of radius .
Variants and improvements
- Softening constant. Use with a small , so the law stays bounded at low speed. Hoffmann et al. (2007) and Snider (2009) use this form; the implementation has it as the parameter
soft. - Damping terms. Hoffmann et al. add terms on the yaw rate and on the steering rate for a real car at speed, where the kinematic model no longer holds.
- Feedforward of the curvature. Add the steering angle that the curvature of the path needs, so that the heading error does not have to build up on curves.
- Reverse driving. In reverse, the rear axle leads. Apply the law at the rear axle with the speed and the heading reversed; the proof of the page does not cover this case.
When to use it
Use it for path tracking at low to moderate speed when the path has a heading at every point and the pose of the front axle is known well: autonomous cars, off-road vehicles, and course tracking in research and teaching. It needs a path that is smooth enough for the heading error to make sense, and a positive speed. The gain is a tuning parameter; it is not derived from the model, and in practice it is set by tests on the vehicle. For high speed, combine it with a dynamic model, or use model predictive control.
Pitfalls
- Wrong reference point. The analysis holds at the front axle. Using the rear axle with the same law changes the error equation and can oscillate.
- Sign conventions. The signs of , and must agree; with this page's convention, a positive means that the path is to the left and a positive turns left.
- Angle wrapping. The heading error must be wrapped to , or a path heading near makes the car turn the long way.
- Noisy cross-track error at low speed. Without the softening constant, a few centimeters of noise in at give a full steering swing.
- Polyline headings. The heading of a polyline jumps at each vertex, and so does , which gives a jump in the steering. Use dense points, or interpolate the heading.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/stanley-controller/. The authors are listed in prov/8QP9X9.jsonl.
"""Stanley steering law (Thrun et al. 2006, Hoffmann et al. 2007).
The vehicle is the kinematic bicycle model with its reference point at the center of the
front axle. The front wheels move with speed u > 0 in the direction theta + delta, and the
heading turns at theta' = u sin(delta) / L:
xf' = u cos(theta + delta), yf' = u sin(theta + delta), theta' = u sin(delta) / L.
The path is a polyline. At each step the controller finds the point of the path closest
to the front axle, the signed cross-track error e (positive when the front axle is to the
right of the path, so that a left turn reduces it) and the heading error psi = path
heading - theta. It steers with
delta = psi + atan(k e / (ks + u)),
clamped to [-max_steer, max_steer]. The gain k is in 1/s; ks >= 0 is an optional softening
speed in m/s (ks = 0 gives the law of the paper).
"""
import math
def wrap(a):
return (a + math.pi) % (2.0 * math.pi) - math.pi
def closest_on_path(path, p, start, window=None):
"""(segment index, parameter in [0, 1]) of the closest point of the path to p, over the
segments from index start onward, or over the next window segments if window is set."""
best = (math.inf, start, 0.0)
stop = len(path) - 1 if window is None else min(len(path) - 1, start + window)
for i in range(start, stop):
ax, ay = path[i]
bx, by = path[i + 1]
dx, dy = bx - ax, by - ay
den = dx * dx + dy * dy
u = 0.0 if den == 0.0 else max(0.0, min(1.0, ((p[0] - ax) * dx + (p[1] - ay) * dy) / den))
d2 = (ax + u * dx - p[0]) ** 2 + (ay + u * dy - p[1]) ** 2
if d2 < best[0]:
best = (d2, i, u)
return best[1], best[2]
class Stanley:
"""Stanley controller for a polyline path."""
def __init__(self, path, gain, wheelbase, max_steer=math.pi / 2.0, soft=0.0, window=None):
self.path = [tuple(p) for p in path]
self.k = gain
self.L = wheelbase
self.max_steer = max_steer
self.ks = soft
self.window = window
self.index = 0
self.error = 0.0
self.heading_error = 0.0
def errors(self, pose):
"""Cross-track error e (positive: path to the left) and heading error psi."""
x, y, th = pose
i, u = closest_on_path(self.path, (x, y), self.index, self.window) # @line L1
self.index = i
ax, ay = self.path[i]
bx, by = self.path[i + 1]
seg = math.atan2(by - ay, bx - ax) # @line L2
qx, qy = ax + u * (bx - ax), ay + u * (by - ay)
e = math.sin(seg) * (x - qx) - math.cos(seg) * (y - qy) # @line L2
psi = wrap(seg - th) # @line L3
return e, psi
def steer(self, pose, speed):
"""Steering angle for the front axle pose (x, y, theta) and the front wheel speed."""
e, psi = self.errors(pose)
self.error, self.heading_error = e, psi
delta = psi + math.atan2(self.k * e, self.ks + speed) # @line L4
return max(-self.max_steer, min(self.max_steer, delta)) # @line L5
def front_rhs(state, u, delta, wheelbase):
x, y, th = state
return u * math.cos(th + delta), u * math.sin(th + delta), u * math.sin(delta) / wheelbase
def _add(s, k, h):
return s[0] + h * k[0], s[1] + h * k[1], s[2] + h * k[2]
def _rk4(f, state, dt):
k1 = f(state)
k2 = f(_add(state, k1, dt / 2.0))
k3 = f(_add(state, k2, dt / 2.0))
k4 = f(_add(state, k3, dt))
return tuple(state[j] + dt / 6.0 * (k1[j] + 2.0 * k2[j] + 2.0 * k3[j] + k4[j]) for j in range(3))
def simulate(controller, pose, u, dt, steps, hold=True):
"""Closed loop with front wheel speed u. With hold=True the steering is computed once per
step and held for dt (a digital controller). With hold=False it is recomputed inside each
RK4 stage, which integrates the continuous closed loop."""
poses = [tuple(pose)]
steers = []
for _ in range(steps): # @line L6
if hold:
delta = controller.steer(pose, u) # @line L6
pose = _rk4(lambda s: front_rhs(s, u, delta, controller.L), pose, dt) # @line L7
else:
delta = controller.steer(pose, u)
pose = _rk4(lambda s: front_rhs(s, u, controller.steer(s, u), controller.L), pose, dt)
poses.append(pose)
steers.append(delta)
return poses, steers
def implicit_time(s0, s):
"""Time for the scaled error s = k e / u to go from s0 to s (same sign, |s| <= |s0|) under
e' = -k e / sqrt(1 + (k e / u)^2), multiplied by k. Uses
F(s) = sqrt(1 + s^2) + ln(s / (1 + sqrt(1 + s^2))) and k t = F(s0) - F(s)."""
def F(z):
z = abs(z)
r = math.sqrt(1.0 + z * z)
return r + math.log(z / (1.0 + r))
return F(s0) - F(s)
test_stanley_controller.py 87 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/stanley-controller/. The authors are listed in prov/8QP9X9.jsonl.
import math
import random
from stanley_controller import Stanley, front_rhs, implicit_time, simulate, wrap
L = 2.85 # the wheelbase of the vehicle in Thrun et al. (2006)
STRAIGHT = [(-100.0, 0.0), (5000.0, 0.0)]
def test_error_rate_is_independent_of_the_heading():
# On a straight path, without saturation, e' = -k e / sqrt(1 + (k e / u)^2) for any heading.
rng = random.Random(1)
checked = 0
for _ in range(3000):
k, u = rng.uniform(0.2, 5.0), rng.uniform(0.5, 20.0)
y, th = rng.uniform(-10, 10), rng.uniform(-1.2, 1.2)
st = Stanley(STRAIGHT, k, L)
delta = st.steer((0.0, y, th), u)
e = -y # positive when the front axle is to the right of the path
assert abs(st.error - e) < 1e-12 and abs(st.heading_error + th) < 1e-12
if abs(-th + math.atan(k * e / u)) >= st.max_steer:
continue # saturated: the formula does not hold
checked += 1
de = -front_rhs((0.0, y, th), u, delta, L)[1]
assert abs(de - (-k * e / math.sqrt(1.0 + (k * e / u) ** 2))) < 1e-9
assert checked > 2000
def test_continuous_loop_matches_the_implicit_solution():
# k t = F(s0) - F(s(t)) with s = k e / u, for the continuous closed loop.
k, u, dt = 1.0, 5.0, 0.01
st = Stanley(STRAIGHT, k, L)
poses, _ = simulate(st, (0.0, 2.0, 0.3), u, dt, 800, hold=False)
s0 = k * -2.0 / u
for n, p in enumerate(poses[1:], 1):
e = -p[1]
assert e < 0.0 # monotone: no overshoot
assert abs(implicit_time(s0, k * e / u) / k - n * dt) < 1e-8
def test_small_error_decays_like_exp_minus_kt():
# For |k e / u| small the solution is close to e0 exp(-k t).
k, u, e0 = 2.0, 10.0, 1e-3
st = Stanley(STRAIGHT, k, L)
poses, _ = simulate(st, (0.0, -e0, 0.0), u, 0.01, 300, hold=False)
for n, p in enumerate(poses):
assert abs(p[1] + e0 * math.exp(-k * n * 0.01)) < 1e-9
def test_circle_is_an_equilibrium():
# On a circle of radius R the front axle stays on the circle with delta = asin(L / R)
# and the vehicle heading behind the path heading by the same angle.
R, n = 20.0, 20000
path = [(R * math.sin(2 * math.pi * j / n), R - R * math.cos(2 * math.pi * j / n)) for j in range(n + 1)]
st = Stanley(path, 2.0, L, window=200)
poses, steers = simulate(st, (0.0, 0.0, -math.asin(L / R)), 3.0, 0.02, 500)
for (x, y, _), d in zip(poses, steers):
# The chords of the polyline turn by 2 pi / n = 3.1e-4 rad, which bounds the error.
assert abs(math.hypot(x, y - R) - R) < 1e-4
assert abs(d - math.asin(L / R)) < 4e-4
def test_converges_with_a_steering_limit():
# With the 24 degree limit of the paper, from errors up to 10 m and 1 rad.
rng = random.Random(4)
for _ in range(25):
y0, th0 = rng.uniform(-10, 10), rng.uniform(-1, 1)
st = Stanley(STRAIGHT, rng.uniform(0.5, 3.0), L, max_steer=math.radians(24))
poses, steers = simulate(st, (0.0, y0, th0), rng.uniform(2.0, 10.0), 0.01, 4000)
assert all(abs(d) <= math.radians(24) + 1e-15 for d in steers)
assert abs(poses[-1][1]) < 1e-6 and abs(wrap(poses[-1][2])) < 1e-6
def test_digital_controller_is_close_to_the_continuous_one():
k, u = 1.0, 5.0
a, _ = simulate(Stanley(STRAIGHT, k, L), (0.0, 2.0, 0.3), u, 0.01, 800, hold=False)
b, _ = simulate(Stanley(STRAIGHT, k, L), (0.0, 2.0, 0.3), u, 0.01, 800, hold=True)
assert max(abs(p[1] - q[1]) for p, q in zip(a, b)) < 0.02
def test_softening_constant():
# With ks > 0 the law is defined at u = 0 and gives the cross-track term atan(k e / ks).
st = Stanley(STRAIGHT, 1.0, L, soft=1.0)
assert abs(st.steer((0.0, 0.5, 0.0), 0.0) - math.atan(-0.5)) < 1e-15
History
The Stanford Racing Team, led by Sebastian Thrun, built Stanley for the DARPA Grand Challenge of 2005, a race of autonomous cars through the desert, and won it. The steering law was one part of the system. Thrun et al. (2006) described the whole car, and wrote the law and its error equation in the section on control. Hoffmann, Tomlin, Montemerlo and Thrun (2007) gave the analysis for positive speed and the extensions for a real car at speed. Snider's report of 2009 placed the law next to pure pursuit and other steering methods, and it became a standard method in teaching.
References
- Sebastian Thrun et al., Stanley, the robot that won the DARPA Grand Challenge, Journal of Field Robotics 23(9), 2006, pages 661 to 692; Section 9.2 (the steering law, equation (7), the error equation (8) and the exponential convergence for small errors, equation (9))
- Gabriel M. Hoffmann, Claire J. Tomlin, Michael Montemerlo and Sebastian Thrun, Autonomous automobile trajectory tracking for off-road driving, controller design, experimental validation and racing, American Control Conference, 2007, pages 2296 to 2301 (the analysis of the law for positive speed and the extensions of the law for a real vehicle)
- Automatic Steering Methods for Autonomous Automobile Path Tracking, Section 2.3 (the Stanley method, its geometry and its tuning, next to pure pursuit)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 8QP9X9 Edit this page History Report an error Markdown