Algorithm Search⌘K

Algorithmcore

Dynamic window approach

Also called DWA.

Searches the velocities reachable in the next step, keeps the safe ones, and picks the best by heading, clearance and speed.

Time
O(c k) worst
Space
O(c) extra
Where
c = the number of candidate velocity pairs; k = the number of obstacles
Properties
deterministicnot exactonlinenot randomized
Origin
Dieter Fox, Wolfram Burgard, Sebastian Thrun, 1997

The dynamic window approach (DWA) is a local collision avoidance method for a mobile robot with limited accelerations. At each control cycle it looks at the pairs of forward speed vv and turn rate ω\omega that the motors can reach before the next cycle (the dynamic window). It keeps the pairs on which the robot can still stop before it hits an obstacle (the admissible pairs). From those, it picks the pair with the best weighted sum of three scores: heading to the goal, clearance and speed. The robot holds that pair for one cycle, and the search starts again. Because each pair is held for a full cycle, the robot of the unicycle model moves on a circular arc, and the safety test is a test of circles against obstacles. DWA is a reactive method: it plans only one cycle ahead, so it can stop in front of an obstacle and never reach the goal.

In plain words

A driver on a dark road cannot turn the wheel instantly, and cannot stop instantly either. So at each moment the driver thinks only about the moves that the car can really make in the next second. Of those moves, the driver drops every one that would leave no room to stop before something in the way. Then the driver picks, among the safe moves, one that points at the destination, stays away from things and keeps a good speed.

DWA does the same, many times each second. It never commits to a long plan. This makes it fast and lets it react to new obstacles, but it can also get stuck in front of an obstacle that lies straight between the robot and the goal.

The problem

Input. The pose (x,y,θ)(x, y, \theta) and the current velocity (v0,ω0)(v_0, \omega_0) of a round robot with radius RR; the speed limits v∈[0,vmax⁡]v \in [0, v_{\max}] and ∣ω∣≤ωmax⁡|\omega| \le \omega_{\max}; the accelerations ava_v and aωa_\omega; the cycle Δt\Delta t; the goal point; and a set of obstacles. Here the obstacles are discs, and the robot radius is added to each of them, so the robot is a point in the configuration space of positions. Arithmetic, square roots and trigonometric functions cost one step each, as in the real RAM.

Output. A velocity (v,ω)(v, \omega) for the next cycle that the accelerations can reach, and that is admissible: if the robot holds it for one cycle and then brakes on the same arc, it stops before it touches an obstacle. Among such pairs, the output should score high on the objective. There is no guarantee that the robot reaches the goal.

How it differs from close pages. The vector field histogram and potential fields first choose a direction and then a steering command, so they do not respect the accelerations. Velocity obstacles also search in velocity space, but for moving obstacles and a holonomic robot. Pure pursuit follows a given path and does not look at obstacles. Model predictive control optimizes a sequence of commands over a horizon; DWA is the special case of one held command, chosen by enumeration.

The algorithm

  1. DWA(pose, (v0, ω0), goal, obstacles)
  2. 1window ← [v0 - a_v Δt, v0 + a_v Δt] × [ω0 - a_ω Δt, ω0 + a_ω Δt], clipped to the speed limits
  3. 2for each (v, ω) in a grid over the window, and the braking pair of (v0, ω0)
  4. 3dist ← the arc length to the first obstacle on the arc of (v, ω)
  5. 4if stop(v, ω) > dist then skip this pair
  6. 5h ← π - |angle to the goal at the stopping point|; c ← min(dist, D); s ← v
  7. 6divide h, c and s by their maxima over the kept pairs
  8. 7(v*, ω*) ← the kept pair with the largest α h + β c + γ s
  9. 8hold (v*, ω*) for Δt, then start again at L1 with the new pose and velocity

Line L1 is the dynamic window of Fox, Burgard and Thrun (eq. 15). Line L3 intersects the arc of (v,ω)(v, \omega) with each inflated disc. The arc is a circle of radius v/∣ω∣v/|\omega|, or a straight line when ω=0\omega = 0; a pair with v=0v = 0 turns the round robot in place and is always safe.

Line L4 is the safety test. The function stop(v,ω)(v, \omega) is the arc length that the robot covers if it holds (v,ω)(v, \omega) for one cycle and then brakes on the same arc: both speeds drop by the same fraction each cycle, so the ratio ω/v\omega/v and the arc stay the same. With n=max⁡(1,⌈max⁡(v/(avΔt),∣ω∣/(aωΔt))⌉)n = \max(1, \lceil\max(v/(a_v\Delta t), |\omega|/(a_\omega\Delta t))\rceil) braking cycles, the speeds are v,v(n−1)/n,…,v/nv, v(n-1)/n, \dots, v/n, and

stop⁡(v,ω)=Δt v n+12.\operatorname{stop}(v, \omega) = \Delta t\,v\,\frac{n + 1}{2}.

The paper states the test as v≤2 dist(v,ω) v˙bv \le \sqrt{2\,\mathrm{dist}(v, \omega)\,\dot v_b} and ω≤2 dist(v,ω) ω˙b\omega \le \sqrt{2\,\mathrm{dist}(v, \omega)\,\dot\omega_b} (eq. 14), the stopping distance with braking from the start. The code uses the discrete form because the command is held for a full cycle before braking can start; the Example shows the difference.

Line L2 adds the braking pair (v0,ω0)(n−1)/n(v_0, \omega_0)(n-1)/n of the current velocity to the grid. It is always admissible (Lemma 2 of the proof), so line L7 always has a pair to pick. Line L5 measures the heading at the point where the robot would stop on the arc, as the paper does, so that a fast turn gets credit for the angle it will really turn. The clearance cc is capped at DD (3 m in the code), because a far obstacle should not matter. The weights of the paper are α=2\alpha = 2 and β=γ=0.2\beta = \gamma = 0.2, with a cycle of 0.25 s.

Example

The robot has R=0.3R = 0.3 m, vmax⁡=0.95v_{\max} = 0.95 m/s, ωmax⁡=1\omega_{\max} = 1 rad/s, av=0.5a_v = 0.5 m/s², aω=60a_\omega = 60 deg/s² and Δt=0.25\Delta t = 0.25 s. It is at the origin, faces the goal at (6,0)(6, 0), and drives straight at v0=0.75v_0 = 0.75 m/s. A disc of radius 0.3 m is at (1.4,0)(1.4, 0). With the robot radius added, it is a disc of radius 0.6, so the free distance straight ahead is 0.8 m.

The window is v∈[0.625,0.875]v \in [0.625, 0.875] m/s and ∣ω∣≤0.262|\omega| \le 0.262 rad/s. On the straight line:

vv (m/s) braking cycles nn stop(v,0)(v, 0) (m) admissible (dist = 0.8 m)
0.625 5 0.469 yes
0.75 6 0.656 yes
0.80 7 0.800 yes (equal)
0.875 7 0.875 no

The turning arcs in the window miss the disc by little, so their free distance is between 0.80 and 0.84 m, and v=0.875v = 0.875 is not admissible on any of them. The chosen pair is (0.8,0)(0.8, 0): it points straight at the goal and is the fastest admissible pair. In the next cycles the robot slows down, turns past the disc and reaches the goal after 40 cycles (10 s, measured).

The continuous test of eq. 14 gives v≤2⋅0.8⋅0.5=0.894v \le \sqrt{2 \cdot 0.8 \cdot 0.5} = 0.894 m/s and accepts v=0.875v = 0.875. But a robot that holds 0.875 m/s for 0.25 s covers 0.219 m, and braking from 0.875 m/s at 0.5 m/s² then needs 0.766 m, which is 0.985 m in total. The discrete test is the one that matches a controller that changes the command only once per cycle.

Correctness

DWA is a heuristic for reaching the goal and has no guarantee of it: in the test test_a_disc_on_the_line_is_a_local_minimum, a disc straight between the robot and the goal stops the robot for good, because every pair that turns away loses more heading score than it gains in clearance. Safety, however, is a theorem. The proof shows that if the obstacles are static and known, the motion model is exact, and the robot starts at rest, then every cycle has an admissible pair, and the robot never overlaps an obstacle. The key fact is that the braking pair on the current arc is always admissible: its stopping distance is exactly v0Δtv_0\Delta t shorter than that of the previous command, and the robot has just moved v0Δtv_0\Delta t along the same arc. The tests check the exact arc distance against dense sampling, the stopping distance against the braking sequence, and safety and the acceleration limits along every simulated run.

Proof: The dynamic window approach never collides and always has an admissible commandfull

Line numbers refer to the pseudocode on the dynamic window approach page. The claim is about safety only; reaching the goal is not guaranteed. The assumptions are: the obstacles are static discs that are known exactly; the robot is a disc of radius RR whose motion follows the unicycle model exactly, with each command held for one cycle Δt\Delta t; and the robot starts at rest in a free pose. The robot overlaps an obstacle of radius rr when the distance between the centers is less than r+Rr + R; touching is not overlap.

Notation. For a pair (v,ω)(v, \omega) with v>0v > 0, let m(v,ω)=max⁡(v/(avΔt),∣ω∣/(aωΔt))m(v, \omega) = \max(v/(a_v\Delta t), |\omega|/(a_\omega\Delta t)) and n(v,ω)=max⁡(1,⌈m(v,ω)⌉)n(v, \omega) = \max(1, \lceil m(v, \omega)\rceil). The braking sequence of (v,ω)(v, \omega) is (v,ω) (n−j)/n(v, \omega)\,(n - j)/n for j=0,1,…,nj = 0, 1, \dots, n. Each pair is held for one cycle. Let stop⁡(v,ω)=Δt∑j=0n−1v(n−j)/n=Δt v(n+1)/2\operatorname{stop}(v, \omega) = \Delta t \sum_{j=0}^{n-1} v(n - j)/n = \Delta t\,v(n + 1)/2, and stop⁡(0,ω)=0\operatorname{stop}(0, \omega) = 0. The braking pair b(v,ω)b(v, \omega) is the pair with j=1j = 1, that is (v,ω)(n−1)/n(v, \omega)(n - 1)/n; for v=0v = 0 it is (0,ω′)(0, \omega') where ω′\omega' moves ω\omega toward 0 by at most aωΔta_\omega\Delta t. For a pose pp, dist⁡(p,v,ω)\operatorname{dist}(p, v, \omega) is the arc length along the path of (v,ω)(v, \omega) from pp to the first point where the robot touches an obstacle, or ∞\infty; for v=0v = 0 it is ∞\infty. A pair is admissible at pp when stop⁡(v,ω)≤dist⁡(p,v,ω)\operatorname{stop}(v, \omega) \le \operatorname{dist}(p, v, \omega), which is the test of line L4.

Lemma 1 (the braking sequence is feasible and stays on the arc). Consecutive pairs of the braking sequence differ by v/n≤avΔtv/n \le a_v\Delta t and ∣ω∣/n≤aωΔt|\omega|/n \le a_\omega\Delta t, and every pair of the sequence with a nonzero speed has the same ratio ω/v\omega/v. The robot covers exactly stop⁡(v,ω)\operatorname{stop}(v, \omega) along the path of (v,ω)(v, \omega) and then stands still.

Proof. Since n≥m(v,ω)n \ge m(v, \omega), we have v/n≤avΔtv/n \le a_v\Delta t and ∣ω∣/n≤aωΔt|\omega|/n \le a_\omega\Delta t. Every pair is a positive multiple of (v,ω)(v, \omega) until the last one, so the ratio, and with it the radius v/∣ω∣v/|\omega| and the direction of the turn, do not change. A unicycle that holds a pair with this ratio moves along the same circle (or the same line for ω=0\omega = 0), and the arc length of one cycle is the speed times Δt\Delta t. Adding the arc lengths gives stop⁡(v,ω)\operatorname{stop}(v, \omega). □\square

Lemma 2 (the braking pair is admissible after one cycle). Let (v,ω)(v, \omega) with v>0v > 0 be admissible at pp, and let p′p' be the pose after the robot holds (v,ω)(v, \omega) for Δt\Delta t. Then b=b(v,ω)b = b(v, \omega) is in the dynamic window of (v,ω)(v, \omega), and bb is admissible at p′p'.

Proof. By Lemma 1, bb differs from (v,ω)(v, \omega) by at most avΔta_v\Delta t and aωΔta_\omega\Delta t, and its components are no larger in absolute value, so it is inside the speed limits and the window of line L1.

First the stopping distance. If n=1n = 1, then b=(0,0)b = (0, 0) and stop⁡(b)=0=stop⁡(v,ω)−vΔt\operatorname{stop}(b) = 0 = \operatorname{stop}(v, \omega) - v\Delta t. If n≥2n \ge 2, then m=m(v,ω)m = m(v, \omega) satisfies n−1<m≤nn - 1 < m \le n, and m(b)=m(n−1)/nm(b) = m(n - 1)/n. So m(b)≤n−1m(b) \le n - 1, and m(b)>(n−1)2/n≥n−2m(b) > (n - 1)^2/n \ge n - 2, because (n−1)2=n(n−2)+1(n - 1)^2 = n(n - 2) + 1. Hence n(b)=n−1n(b) = n - 1 and

stop⁡(b)=Δt v(n−1)n⋅n2=Δt v n−12=stop⁡(v,ω)−vΔt.\operatorname{stop}(b) = \Delta t\,\frac{v(n - 1)}{n}\cdot\frac{n}{2} = \Delta t\,v\,\frac{n - 1}{2} = \operatorname{stop}(v, \omega) - v\Delta t.

Now the free distance. The path of bb from p′p' is the continuation of the path of (v,ω)(v, \omega) from pp, since the circle and the direction are the same and p′p' lies on it at arc length vΔtv\Delta t from pp. Let d=dist⁡(p,v,ω)d = \operatorname{dist}(p, v, \omega). Admissibility gives d≥stop⁡(v,ω)≥vΔtd \ge \operatorname{stop}(v, \omega) \ge v\Delta t. Suppose the robot touched an obstacle at arc length u<d−vΔtu < d - v\Delta t from p′p'. That point lies at arc length u+vΔt<du + v\Delta t < d from pp along the same path (if the path is a circle and u+vΔtu + v\Delta t exceeds its length, the same point also lies at a smaller arc length). This contradicts the choice of dd as the first contact. So dist⁡(p′,b)≥d−vΔt\operatorname{dist}(p', b) \ge d - v\Delta t. Together,

stop⁡(b)=stop⁡(v,ω)−vΔt≤d−vΔt≤dist⁡(p′,b).□\operatorname{stop}(b) = \operatorname{stop}(v, \omega) - v\Delta t \le d - v\Delta t \le \operatorname{dist}(p', b). \qquad\square

Lemma 3 (one admissible cycle is safe). If (v,ω)(v, \omega) is admissible at a free pose pp, then the robot does not overlap an obstacle while it holds (v,ω)(v, \omega) for Δt\Delta t.

Proof. If v=0v = 0, the round robot turns in place and its center does not move. Otherwise it covers the arc length vΔt≤Δt v(n+1)/2=stop⁡(v,ω)≤dist⁡(p,v,ω)v\Delta t \le \Delta t\,v(n + 1)/2 = \operatorname{stop}(v, \omega) \le \operatorname{dist}(p, v, \omega), because n≥1n \ge 1. Before the arc length dist⁡(p,v,ω)\operatorname{dist}(p, v, \omega), the center stays out of every inflated disc, since pp is free and the first entry into a disc happens at a point of its boundary. □\square

Theorem (safety). Under the assumptions above, at every cycle line L4 keeps at least one pair, and the robot never overlaps an obstacle.

Proof. We show by induction on the cycle tt that the pose ptp_t is free and the current velocity (vt,ωt)(v_t, \omega_t) is admissible at pt−1p_{t-1}, where for t=0t = 0 the velocity is (0,0)(0, 0), which is admissible everywhere.

At cycle tt, line L2 includes the braking pair b(vt,ωt)b(v_t, \omega_t). If vt>0v_t > 0, Lemma 2 applied to the admissible command (vt,ωt)(v_t, \omega_t) at pt−1p_{t-1} shows that bb is admissible at ptp_t. If vt=0v_t = 0, then bb has speed 0 and dist⁡=∞\operatorname{dist} = \infty, so it is admissible. Hence line L4 keeps bb, and line L7 returns some admissible pair (vt+1,ωt+1)(v_{t+1}, \omega_{t+1}) in the window. By Lemma 3, the robot moves from ptp_t to pt+1p_{t+1} without overlap, so pt+1p_{t+1} is free. This completes the induction. □\square

Remarks. The theorem does not depend on the weights, on the grid of line L2, or on the cap DD of the clearance, which enters only the score. It needs the braking pair in the candidate set: a grid alone may contain no admissible pair after a coarse sampling. It fails when an obstacle appears inside the stopping distance, when obstacles move, or when the real robot does not follow the commanded arc; then a margin on the robot radius and a brake reflex are needed. The tests check the parts on random data: test_arc_distance_matches_dense_sampling compares the exact arc distance with a walk in steps of 2 mm, test_stopping_distance_and_braking_stay_on_the_arc checks Lemma 1 and the equation stop⁡(b)=stop⁡(v,ω)−vΔt\operatorname{stop}(b) = \operatorname{stop}(v, \omega) - v\Delta t, and the run tests check Lemma 3 and the acceleration limits at every cycle.

Complexity

  • Time. Each of the cc candidate pairs is tested against each of the kk obstacles in O(1)O(1), so a cycle costs O(ck)O(ck). Measured: with an 11×2111 \times 21 grid plus the braking pair (232 pairs) and 14 discs, one cycle takes about 1.7 ms in this pure Python code. With an occupancy grid instead of discs, the cost of line L3 depends on the number of cells near the arc.
  • Space. O(c)O(c) for the scores of the kept pairs, needed for the normalization of line L6.

Properties

  • Safe by construction. Under the assumptions of the proof, the robot never enters an obstacle and always has an admissible command. The test test_brakes_in_front_of_a_wall puts a wall across the path; the robot stops in front of it.
  • Respects the accelerations. Every command is inside the window, so the motors can follow it.
  • Not complete. It can stop in a local minimum, or circle, and never reach a goal that a global planner would reach.
  • Sensitive to the weights. Measured on 10 random fields of 14 discs with the goal 10 m away and 300 cycles: the weights (2,0.2,0.2)(2, 0.2, 0.2) reached the goal in 1 field, and the weights (1,1,0.3)(1, 1, 0.3) reached it in 9 fields. No run collided. These numbers describe this code, with its clearance cap and normalization, not the robot of the paper.
  • Online. Each cycle uses only the current pose, velocity and obstacles.

Variants and improvements

  • Global dynamic window. Brock and Khatib replaced the heading term with a navigation function computed over a map, which removes most local minima.
  • Trajectory rollout. Planners in the ROS navigation stack simulate each candidate pair over a horizon of a few seconds and score the rollout against a global path and a cost map.
  • Curvature-velocity method. Simmons chose (v,ω)(v, \omega) by a similar weighted objective with constraints from the obstacles, published a year earlier.
  • Holonomic and car-like robots. The window gets a third dimension for sideways speed, or the curvature replaces ω\omega for a car-like robot.
  • Moving obstacles. Predicting each obstacle along its own velocity, as in velocity obstacles, replaces the static distance of line L3.

When to use it

Use DWA as the local planner of a mobile robot with real acceleration limits, under a global planner that gives it a nearby goal or a path to follow. It is cheap, easy to tune and safe with respect to the obstacles it sees. Do not use it alone in a cluttered space with dead ends, for a fast car-like robot that needs plans of many seconds, or among many moving people, where a predictive method does better.

Pitfalls

  • Local minima. A wall or a U-shaped obstacle between the robot and the goal can stop the robot for good. Give DWA a global path, or replace the heading term with a navigation function.
  • The stopping test. Eq. 14 assumes braking starts at once. If the command is held for a cycle first, the test must include that cycle, as in the Example.
  • Coarse grids. A grid that is too coarse can miss a narrow gap, and the braking pair must stay in the candidate set, or the robot can find no admissible pair after a sudden obstacle.
  • The robot shape. Inflating obstacles by a radius is exact only for a round robot. For other shapes, check the swept area of the arc.
  • Unnormalized scores. Without line L6, the term with the largest units dominates, and the weights lose their meaning.

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.

dynamic_window_approach.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dynamic-window-approach/. The authors are listed in prov/0PW0PJ.jsonl.

"""The dynamic window approach (Fox, Burgard and Thrun 1997) for a round robot.

The robot is a unicycle: x' = v cos(theta), y' = v sin(theta), theta' = w. Velocities are
held for one control interval dt, so each command moves the robot on a circular arc (or
a straight segment). Obstacles are discs; the robot radius is added to their radius.

At each interval the method searches the velocities that the accelerations can reach
within dt (the dynamic window), keeps the admissible ones (the robot can still stop on
the same arc before it reaches an obstacle), and picks the one that maximizes a weighted
sum of heading to the goal, clearance and speed.

Admissible here means: the stopping distance s(v, w) of the discrete braking sequence on
the arc of (v, w) is at most the free arc length dist(v, w). The braking pair on the
current arc is always a candidate, so an admissible pair always exists when the start
velocity is admissible (Theorem 1 of the proof).
"""

import math

INF = float("inf")
TWO_PI = 2.0 * math.pi


class Robot:
    """Limits of the robot. Speeds in m/s and rad/s, accelerations in m/s^2 and rad/s^2."""

    def __init__(self, radius=0.3, v_max=0.95, w_max=1.0, a_v=0.5, a_w=math.radians(60.0), dt=0.25):
        self.radius, self.v_max, self.w_max = radius, v_max, w_max
        self.a_v, self.a_w, self.dt = a_v, a_w, dt


def move(pose, v, w, t):
    """Exact unicycle motion for time t with constant (v, w)."""
    x, y, th = pose
    if abs(w) < 1e-12:
        return (x + v * t * math.cos(th), y + v * t * math.sin(th), th)
    r = v / w
    th2 = th + w * t
    return (x + r * (math.sin(th2) - math.sin(th)), y - r * (math.cos(th2) - math.cos(th)), th2)


def arc_distance(pose, v, w, obstacles, inflate):
    """Arc length from pose along the path of (v, w) until the robot touches an obstacle.

    obstacles is a list of (ox, oy, r); the robot touches it when its center is within
    r + inflate. Returns INF if the path never touches one (or if v = 0: the round robot
    turns in place). The start pose must be free.
    """
    if v <= 0.0:
        return INF
    x, y, th = pose
    best = INF
    if abs(w) < 1e-9:
        c, s = math.cos(th), math.sin(th)
        for ox, oy, r in obstacles:
            rho = r + inflate
            dx, dy = ox - x, oy - y
            along = dx * c + dy * s
            perp2 = (dx * dx + dy * dy) - along * along
            if perp2 >= rho * rho or along < 0.0:
                continue
            t = along - math.sqrt(rho * rho - perp2)
            best = min(best, max(t, 0.0))
        return best
    rad = v / abs(w)
    sgn = 1.0 if w > 0 else -1.0
    cx, cy = x - sgn * rad * math.sin(th), y + sgn * rad * math.cos(th)
    phi0 = math.atan2(y - cy, x - cx)
    for ox, oy, r in obstacles:
        rho = r + inflate
        dx, dy = ox - cx, oy - cy
        d = math.hypot(dx, dy)
        if d > rad + rho or d < rad - rho or d == 0.0:
            continue
        cosa = (rad * rad + d * d - rho * rho) / (2.0 * rad * d)
        a = math.acos(max(-1.0, min(1.0, cosa)))
        base = math.atan2(dy, dx)
        for phi in (base - a, base + a):
            delta = ((phi - phi0) * sgn) % TWO_PI
            best = min(best, rad * delta)
    return best


def stopping_distance(v, w, robot):
    """Arc length covered by holding (v, w) for one interval and then braking on the same arc.

    Braking keeps the ratio w / v (the same arc), so both speeds drop by the same fraction
    per interval; the fraction is set by the tighter of the two deceleration limits.
    """
    if v <= 0.0:
        return 0.0
    n = braking_intervals(v, w, robot)
    # Speeds v, v (n-1)/n, ..., v/n, each for dt: dt v (n + 1) / 2.
    return robot.dt * v * (n + 1) / 2.0


def braking_intervals(v, w, robot):
    """The number n of intervals after the first one that braking on the arc needs."""
    steps = max(v / (robot.a_v * robot.dt), abs(w) / (robot.a_w * robot.dt))
    return max(1, math.ceil(steps - 1e-12))


def brake_pair(v, w, robot):
    """The next velocity of the braking sequence on the current arc."""
    if v <= 0.0:
        step = robot.a_w * robot.dt
        return 0.0, (0.0 if abs(w) <= step else w - math.copysign(step, w))
    n = braking_intervals(v, w, robot)
    f = (n - 1) / n
    return v * f, w * f


def heading_score(pose, goal):
    """pi minus the absolute angle between the heading and the direction to the goal."""
    ang = math.atan2(goal[1] - pose[1], goal[0] - pose[0]) - pose[2]
    ang = (ang + math.pi) % TWO_PI - math.pi
    return math.pi - abs(ang)


def dwa_step(pose, vel, goal, obstacles, robot, alpha=2.0, beta=0.2, gamma=0.2, nv=11, nw=21, dist_cap=3.0):
    """Choose the velocity for the next interval. Returns (v, w)."""
    v0, w0 = vel
    dt = robot.dt
    vlo, vhi = max(0.0, v0 - robot.a_v * dt), min(robot.v_max, v0 + robot.a_v * dt)  # @line L1
    wlo, whi = max(-robot.w_max, w0 - robot.a_w * dt), min(robot.w_max, w0 + robot.a_w * dt)  # @line L1
    cands = [brake_pair(v0, w0, robot)]  # @line L2
    for i in range(nv):
        for j in range(nw):
            v = vlo + (vhi - vlo) * i / (nv - 1)
            w = wlo + (whi - wlo) * j / (nw - 1)
            cands.append((v, w))
    rows = []
    for v, w in cands:  # @line L2
        dist = arc_distance(pose, v, w, obstacles, robot.radius)  # @line L3
        s = stopping_distance(v, w, robot)
        if s > dist + 1e-9:  # @line L4
            continue
        t_stop = s / v if v > 0 else 0.0
        ahead = move(pose, v, w, t_stop if v > 0 else dt)
        rows.append((v, w, heading_score(ahead, goal), min(dist, dist_cap), v))  # @line L5
    if not rows:
        raise RuntimeError("no admissible velocity; the start velocity was not admissible")
    mh = max(r[2] for r in rows) or 1.0  # @line L6
    md = max(r[3] for r in rows) or 1.0
    ms = max(r[4] for r in rows) or 1.0
    best = max(rows, key=lambda r: alpha * r[2] / mh + beta * r[3] / md + gamma * r[4] / ms)  # @line L7
    return best[0], best[1]


def run(start, goal, obstacles, robot, max_steps=400, tol=0.2, record=None, **kw):
    """Simulate until the robot is within tol of the goal. Returns (pose, steps, reached)."""
    pose, vel = start, (0.0, 0.0)
    for k in range(max_steps):
        if math.hypot(goal[0] - pose[0], goal[1] - pose[1]) < tol:
            return pose, k, True
        v, w = dwa_step(pose, vel, goal, obstacles, robot, **kw)
        if record is not None:
            record(pose, vel, (v, w))
        pose = move(pose, v, w, robot.dt)  # @line L8
        vel = (v, w)
    return pose, max_steps, False
test_dynamic_window_approach.py 139 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dynamic-window-approach/. The authors are listed in prov/0PW0PJ.jsonl.

import math
import random

from dynamic_window_approach import (
    INF,
    Robot,
    arc_distance,
    brake_pair,
    move,
    run,
    stopping_distance,
)


def sampled_distance(pose, v, w, obstacles, inflate, step, limit):
    """Walk along the path in small steps; return the first arc length inside an obstacle."""
    s = 0.0
    while s < limit:
        p = move(pose, v, w, s / v)
        if any(math.hypot(p[0] - ox, p[1] - oy) < r + inflate for ox, oy, r in obstacles):
            return s
        s += step
        if abs(w) > 1e-9 and s > 2 * math.pi * v / abs(w) + step:
            break
    return INF


def test_arc_distance_matches_dense_sampling():
    rng = random.Random(11)
    checked = 0
    limit = 6.0
    for _ in range(80):
        obs = [(rng.uniform(-3, 3), rng.uniform(-3, 3), rng.uniform(0.05, 0.4)) for _ in range(4)]
        pose = (0.0, 0.0, rng.uniform(-math.pi, math.pi))
        if any(math.hypot(ox, oy) <= r + 0.3 for ox, oy, r in obs):
            continue
        v = rng.uniform(0.1, 1.0)
        w = rng.choice([0.0, rng.uniform(-1.5, 1.5)])
        d = arc_distance(pose, v, w, obs, 0.3)
        ds = sampled_distance(pose, v, w, obs, 0.3, 2e-3, limit)
        if ds == INF:
            # The sampled walk found nothing: the exact distance is beyond the walk.
            assert d > limit - 1e-6 or abs(w) > 1e-9 and d > 2 * math.pi * v / abs(w) - 1e-6
            continue
        assert d <= ds + 1e-9 and ds - d < 2.5e-3
        checked += 1
    assert checked > 15


def test_stopping_distance_and_braking_stay_on_the_arc():
    rob = Robot()
    rng = random.Random(12)
    for _ in range(200):
        v = rng.uniform(0.0, rob.v_max)
        w = rng.uniform(-rob.w_max, rob.w_max)
        s = stopping_distance(v, w, rob)
        # Follow the braking sequence; each change respects the accelerations and keeps w / v.
        total, cv, cw = 0.0, v, w
        for _ in range(100):
            total += cv * rob.dt
            nv, nw = brake_pair(cv, cw, rob)
            assert cv - nv <= rob.a_v * rob.dt + 1e-12
            assert abs(cw - nw) <= rob.a_w * rob.dt + 1e-12
            if nv > 1e-12:
                assert abs(nw / nv - w / v) < 1e-9
            cv, cw = nv, nw
            if cv <= 1e-12:
                break
        assert abs(total - s) < 1e-9
        # The stopping distance shrinks by exactly v dt after one interval on the arc.
        bv, bw = brake_pair(v, w, rob)
        assert abs(stopping_distance(bv, bw, rob) - (s - v * rob.dt)) < 1e-9


def check_no_collision(obs, rob, log):
    for pose, vel, cmd in log:
        v, w = cmd
        if v > 0:
            free = arc_distance(pose, v, w, obs, rob.radius)
            assert v * rob.dt <= free + 1e-9
        assert vel[0] - rob.a_v * rob.dt - 1e-12 <= v <= vel[0] + rob.a_v * rob.dt + 1e-12
        assert abs(w - vel[1]) <= rob.a_w * rob.dt + 1e-12
        for ox, oy, r in obs:
            assert math.hypot(pose[0] - ox, pose[1] - oy) >= r + rob.radius - 1e-9


def test_random_fields_are_safe_and_reached():
    rob = Robot()
    rng = random.Random(13)
    for _ in range(4):
        obs = []
        while len(obs) < 14:
            o = (rng.uniform(1, 9), rng.uniform(-3, 3), rng.uniform(0.1, 0.5))
            if math.hypot(o[0], o[1]) > o[2] + 1.0 and math.hypot(o[0] - 10, o[1]) > o[2] + 1.0:
                obs.append(o)
        log = []
        _, steps, reached = run((0.0, 0.0, rng.uniform(-1, 1)), (10.0, 0.0), obs, rob, max_steps=300,
                                record=lambda p, vl, c: log.append((p, vl, c)),
                                nv=6, nw=11, alpha=1.0, beta=1.0, gamma=0.3)
        check_no_collision(obs, rob, log)
        assert reached and steps < 200


def test_brakes_in_front_of_a_wall():
    # A wall of discs across the path and the goal behind it: the robot must stop, not touch.
    rob = Robot()
    wall = [(3.0, y / 10.0, 0.06) for y in range(-60, 61)]
    log = []
    pose, _, reached = run((0.0, 0.0, 0.0), (6.0, 0.0), wall, rob, max_steps=120,
                           record=lambda p, vl, c: log.append((p, vl, c)), nv=6, nw=11)
    assert not reached
    check_no_collision(wall, rob, log)
    assert pose[0] < 3.0 - 0.36 + 1e-9


def test_passes_a_disc_beside_the_line():
    rob = Robot()
    obs = [(3.0, 0.6, 0.5)]
    log = []
    _, steps, reached = run((0.0, 0.0, 0.0), (6.0, 0.0), obs, rob, max_steps=200,
                            record=lambda p, vl, c: log.append((p, vl, c)))
    assert reached
    check_no_collision(obs, rob, log)
    assert steps < 60


def test_a_disc_on_the_line_is_a_local_minimum():
    # The heading term keeps the robot pointed at the goal; it stops in front of the disc.
    rob = Robot()
    obs = [(3.0, 0.0, 0.5)]
    log = []
    pose, _, reached = run((0.0, 0.0, 0.0), (6.0, 0.0), obs, rob, max_steps=200,
                           record=lambda p, vl, c: log.append((p, vl, c)), nv=6, nw=11)
    assert not reached
    check_no_collision(obs, rob, log)
    assert pose[0] < 3.0

History

Fox, Burgard and Thrun published the dynamic window approach in 1997. Their robot had a synchro drive and sonar sensors, used a cycle of 0.25 s, accelerations of 50 cm/s² and 60 deg/s², and reached speeds up to 95 cm/s. Simmons had proposed the curvature-velocity method, which also searches over (v,ω)(v, \omega), in 1996. Brock and Khatib added a navigation function in 1999 to escape local minima. Later local planners in the ROS navigation stack used the same search over sampled velocities.

References

  1. The dynamic window approach to collision avoidance, Section 4 (the search space, eq. 14 for the admissible velocities, eq. 15 for the dynamic window, and the objective function)

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
  • at least three sources
  • a scene preset for the example