Algorithm Search⌘K

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
Properties
deterministicnot exactonlinenot randomized
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 ψ\psi, the angle between the path and the car, and the cross-track error ee, the signed distance from the center of the front axle to the closest point of the path. It steers with δ=ψ+arctan⁡(ke/u)\delta = \psi + \arctan(ke/u), where uu is the speed of the front wheels and kk 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: xf′=ucos⁡(θ+δ)x_f' = u\cos(\theta + \delta), yf′=usin⁡(θ+δ)y_f' = u\sin(\theta + \delta), θ′=(u/L)sin⁡δ\theta' = (u/L)\sin\delta, with wheelbase LL, speed u>0u > 0 of the front wheels, and steering angle ∣δ∣≤δmax|\delta| \le \delta_{max}. 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 (xf,yf,θ)(x_f, y_f, \theta) of the front axle, the speed uu, the gain k>0k > 0 in 1/s and the steering limit δmax\delta_{max}.

Output. A steering angle δ\delta 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

  1. STANLEY(path, (xf, yf, θ), u, k, δmax)
  2. 1(i, s) ← the point of the path closest to (xf, yf), searching from the last index onward
  3. 2e ← signed distance from (xf, yf) to that point, positive when the path is to the left of the front axle
  4. 3ψ ← wrap(heading of segment i - θ)
  5. 4δ ← ψ + arctan(k e / u)
  6. 5δ ← clamp(δ, -δmax, δmax)
  7. 6apply δ for one control period
  8. 7the vehicle moves; repeat from L1 at the next period

With this sign convention, a positive δ\delta is a left turn and reduces a positive ee. Line L4 uses the two-argument arctangent of (ke,u)(ke, u) in the code. Thrun et al. write the law with the cross-track error x(t)x(t) and the speed u(t)u(t), as δ(t)=ψ(t)+arctan⁡(k x(t)/u(t))\delta(t) = \psi(t) + \arctan(k\,x(t)/u(t)). The implementation integrates the model with the classical Runge-Kutta method, either with δ\delta held for a step, like a digital controller, or with δ\delta recomputed in each stage, which integrates the continuous closed loop of the proof.

Example

Let L=2.85L = 2.85 m, k=1k = 1 1/s and u=5u = 5 m/s; the wheelbase and the gain are the values in Thrun et al. (2006). The path is the xx axis, and the front axle starts at (0,1)(0, 1) with heading 0, so it is 1 m to the left of the path. Line L2 gives e=−1e = -1 m and line L3 gives ψ=0\psi = 0. Line L4 gives δ=arctan⁡(−1/5)=−0.1974\delta = \arctan(-1/5) = -0.1974 rad, a right turn of 11.3 degrees.

From then on, the proof shows that e˙=−ke/1+(ke/u)2\dot e = -ke/\sqrt{1 + (ke/u)^2}, whatever the heading, as long as the steering does not saturate. With s=ke/us = ke/u, the time to go from e0e_0 to ee is (F(s0)−F(s))/k(F(s_0) - F(s))/k with F(s)=1+s2+ln⁡(∣s∣/(1+1+s2))F(s) = \sqrt{1 + s^2} + \ln(|s|/(1 + \sqrt{1 + s^2})). The table gives the time to reach 1 cm for k=1k = 1:

uu (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 e−kte^{-kt} 4.605 6.908

For a small ke/uke/u, the error decays like e−kte^{-kt} 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, u=5u = 5 m/s and e0=10e_0 = 10 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 u>0u > 0, and no saturation of line L5. Lemma 1 shows that on a straight path the law gives e˙=−ke/1+(ke/u)2\dot e = -ke/\sqrt{1 + (ke/u)^2} for every heading. Theorem 1 solves this equation: the error keeps its sign, decreases strictly to zero from every start, and decays like e−kte^{-kt} once it is small. Theorem 2 shows that the heading also converges and that the path is locally exponentially stable, with the eigenvalues −k-k and −u/L-u/L. Theorem 3 shows that a circle of radius R>LR > L is an equilibrium, with δ=arcsin⁡(L/R)\delta = \arcsin(L/R). 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 uu in the direction θ+δ\theta + \delta, and the rear wheels roll along θ\theta, so

xf′=ucos⁡(θ+δ),yf′=usin⁡(θ+δ),θ′=uLsin⁡δ.x_f' = u\cos(\theta + \delta),\quad y_f' = u\sin(\theta + \delta),\quad \theta' = \frac{u}{L}\sin\delta.

Hypotheses. H1: the model above holds (no tire slip, no actuator delay, the steering is updated continuously). H2: the speed u>0u > 0 is constant. H3: the steering does not saturate, ∣ψ+arctan⁡(ke/u)∣<δmax≤π/2|\psi + \arctan(ke/u)| < \delta_{max} \le \pi/2, so line L5 does not clip. The gain k>0k > 0 is in 1/s. The path is the xx axis, except in Theorem 3. Then the closest point of the path to the front axle is (xf,0)(x_f, 0), the cross-track error of line L2 is e=−yfe = -y_f (positive when the front axle is to the right of the path), and the heading error of line L3 is ψ=−θ\psi = -\theta.

Lemma 1 (the error equation). Under H1 to H3, on the straight path,

e˙=−ke1+(ke/u)2,\dot e = -\frac{k e}{\sqrt{1 + (k e/u)^2}},

for every heading θ\theta.

Proof. Line L4 gives δ=ψ+arctan⁡(ke/u)=−θ+arctan⁡(ke/u)\delta = \psi + \arctan(ke/u) = -\theta + \arctan(ke/u), so θ+δ=arctan⁡(ke/u)\theta + \delta = \arctan(ke/u). Then e˙=−y˙f=−usin⁡(arctan⁡(ke/u))\dot e = -\dot y_f = -u\sin(\arctan(ke/u)). With sin⁡(arctan⁡z)=z/1+z2\sin(\arctan z) = z/\sqrt{1 + z^2}, this is −u (ke/u)/1+(ke/u)2-u\,(ke/u)/\sqrt{1 + (ke/u)^2}. □\square

The heading drops out: the law turns the front wheels to point at the path at the angle arctan⁡(ke/u)\arctan(ke/u), 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 10−910^{-9}.

Theorem 1 (the cross-track error). Under H1 to H3 on the straight path, e(t)e(t) keeps its sign, ∣e(t)∣|e(t)| decreases strictly to 0, and with s=ke/us = ke/u and

F(s)=1+s2+ln⁡∣s∣1+1+s2,F(s) = \sqrt{1 + s^2} + \ln\frac{|s|}{1 + \sqrt{1 + s^2}},

the solution satisfies F(s(t))=F(s(0))−ktF(s(t)) = F(s(0)) - kt. Moreover ∣e(t)∣≤∣e(0)∣exp⁡ ⁣(−kt/1+s(0)2)|e(t)| \le |e(0)|\exp\!\big(-kt/\sqrt{1 + s(0)^2}\big), and ∣e(t)∣|e(t)| decays like e−kte^{-kt} as s→0s \to 0.

Proof. By Lemma 1, s˙=−ks/1+s2\dot s = -ks/\sqrt{1 + s^2}. The right side is Lipschitz, and s=0s = 0 is an equilibrium, so a solution that starts at s0≠0s_0 \ne 0 never reaches 0 in finite time and keeps its sign; ∣s∣|s| decreases strictly because ss˙<0s\dot s < 0. For s>0s > 0, separate the variables: 1+s2s ds=−k dt\frac{\sqrt{1 + s^2}}{s}\,ds = -k\,dt. The derivative of FF is s1+s2+1s−s1+s2 (1+1+s2)\frac{s}{\sqrt{1+s^2}} + \frac{1}{s} - \frac{s}{\sqrt{1+s^2}\,(1 + \sqrt{1+s^2})}. With r=1+s2r = \sqrt{1 + s^2}, the first and third terms sum to s1+r\frac{s}{1 + r}, and 1s+s1+r=1+r+s2s(1+r)=r(1+r)s(1+r)=rs\frac1s + \frac{s}{1+r} = \frac{1 + r + s^2}{s(1 + r)} = \frac{r(1 + r)}{s(1+r)} = \frac{r}{s}. So F′=1+s2/sF' = \sqrt{1 + s^2}/s and F(s(t))−F(s0)=−ktF(s(t)) - F(s_0) = -kt. For s<0s < 0 the equation is odd in ss, and FF depends on ∣s∣|s|. Since ∣s(t)∣≤∣s0∣|s(t)| \le |s_0|, 1+s2≤1+s02\sqrt{1 + s^2} \le \sqrt{1 + s_0^2}, so ddt∣e∣≤−k∣e∣/1+s02\frac{d}{dt}|e| \le -k|e|/\sqrt{1 + s_0^2}, which gives the exponential bound. As s→0s \to 0, F(s)=ln⁡∣s∣+1−ln⁡2+O(s2)F(s) = \ln|s| + 1 - \ln 2 + O(s^2), so ∣s(t)∣=∣s0∣ eF(s0)−1+ln⁡2−kt(1+o(1))|s(t)| = |s_0|\,e^{F(s_0) - 1 + \ln 2 - kt}(1 + o(1)), which decays like e−kte^{-kt}. □\square

So the error converges for every initial error, at an exponential rate that depends on how large ∣ke0/u∣|ke_0/u| is. For a large error, e˙≈−u sign(e)\dot e \approx -u\,\mathrm{sign}(e): 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 e0=−2e_0 = -2 m, θ0=0.3\theta_0 = 0.3 rad with k=1k = 1 1/s and u=5u = 5 m/s and finds ktkt equal to F(s0)−F(s(t))F(s_0) - F(s(t)) within 10−810^{-8} s at every step of 10 ms.

Theorem 2 (the heading and local exponential stability). Under H1 to H3 on the straight path, θ(t)→0\theta(t) \to 0. The state (e,θ)=(0,0)(e, \theta) = (0, 0) is locally exponentially stable, with the eigenvalues −k-k and −u/L-u/L of the linearization.

Proof. Let φ(t)=arctan⁡s(t)\varphi(t) = \arctan s(t), so δ=−(θ+φ)\delta = -(\theta + \varphi) and θ˙=−(u/L)sin⁡(θ+φ)\dot\theta = -(u/L)\sin(\theta + \varphi), with ∣θ+φ∣=∣δ∣<π/2|\theta + \varphi| = |\delta| < \pi/2 by H3. By Theorem 1, ∣φ(t)∣|\varphi(t)| decreases to 0. Fix ϵ>0\epsilon > 0 and a time TT with ∣φ(t)∣<ϵ/2|\varphi(t)| < \epsilon/2 for t≥Tt \ge T. When ∣θ∣≥ϵ|\theta| \ge \epsilon and t≥Tt \ge T, θ+φ\theta + \varphi has the sign of θ\theta and ∣θ+φ∣≥ϵ/2|\theta + \varphi| \ge \epsilon/2, so ddt∣θ∣≤−(u/L)sin⁡(ϵ/2)<0\frac{d}{dt}|\theta| \le -(u/L)\sin(\epsilon/2) < 0. So ∣θ∣|\theta| falls below ϵ\epsilon in finite time and does not leave the interval [−ϵ,ϵ][-\epsilon, \epsilon] after that. As ϵ\epsilon is arbitrary, θ→0\theta \to 0. For the second claim, linearize at the origin: s˙=−ks\dot s = -ks and θ˙=−(u/L)(θ+s)\dot\theta = -(u/L)(\theta + s). The matrix is triangular with eigenvalues −k-k and −u/L-u/L, both negative, so by the Jacobian linearization principle the origin of the nonlinear loop is locally exponentially stable. □\square

Theorem 3 (a circle is an equilibrium). Let the path be a circle of radius R>LR > L, traversed counterclockwise. If the front axle is on the circle and the heading lags the tangent of the circle by arcsin⁡(L/R)\arcsin(L/R), then the law returns δ=arcsin⁡(L/R)\delta = \arcsin(L/R), and the vehicle keeps that relation for all time.

Proof. The front axle is on the path, so e=0e = 0, ψ=arcsin⁡(L/R)\psi = \arcsin(L/R), and line L4 gives δ=ψ\delta = \psi. The front wheels then point along the tangent, so the front axle moves along the circle with speed uu, and the tangent turns at the rate u/Ru/R. The heading turns at θ˙=(u/L)sin⁡δ=u/R\dot\theta = (u/L)\sin\delta = u/R, the same rate, so ψ\psi stays constant and ee stays 0. □\square

The rear axle runs on the circle of radius R2−L2\sqrt{R^2 - L^2} 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 10−410^{-4} m of the circle; the steering stays within 4⋅10−44 \cdot 10^{-4} rad of arcsin⁡(L/R)=0.1430\arcsin(L/R) = 0.1430 rad, a deviation that comes from the turn of 3.1⋅10−43.1 \cdot 10^{-4} 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 10−610^{-6} m. At low speed, ke/uke/u 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 O(n)O(n) for a path of nn vertices in the worst case, and O(1)O(1) with a search window of a few segments near the last index, which the implementation offers. The law itself is O(1)O(1). Measured: one call takes about 1.5 microseconds in CPython on a laptop for a path of two points.
  • Space. O(1)O(1) 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 kk in time, not in distance, so the car covers about u/ku/k m per e-fold of the error. At high speed the correction stretches over a long distance.
  • Low speed. As u→0u \to 0, the term arctan⁡(ke/u)\arctan(ke/u) goes to ±π/2\pm\pi/2 for any nonzero error, and the law becomes very sensitive to noise in ee. 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 arcsin⁡(L/R)\arcsin(L/R), and the rear axle runs inside the path, on the circle of radius R2−L2\sqrt{R^2 - L^2}.

Variants and improvements

  • Softening constant. Use arctan⁡(ke/(ks+u))\arctan(ke/(k_s + u)) with a small ks>0k_s > 0, 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 kk 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 ee, ψ\psi and δ\delta must agree; with this page's convention, a positive ee means that the path is to the left and a positive δ\delta turns left.
  • Angle wrapping. The heading error must be wrapped to [−π,π)[-\pi, \pi), or a path heading near ±π\pm\pi makes the car turn the long way.
  • Noisy cross-track error at low speed. Without the softening constant, a few centimeters of noise in ee at u≈0u \approx 0 give a full steering swing.
  • Polyline headings. The heading of a polyline jumps at each vertex, and so does ψ\psi, 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.

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

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

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