Algorithm Search⌘K

Algorithmadvanced

Hybrid A*

Also called hybrid-state A*.

A* over grid cells that stores a continuous pose in each cell and expands by car motions, with Reeds-Shepp shots to the goal.

Time
O(B (log B + s)) worst
Space
O(B) extra
Where
B = the number of bins, nx ny ntheta; s = the number of collision samples on one primitive
Properties
deterministicnot exactofflinenot randomized
Origin
Dmitri Dolgov, Sebastian Thrun, Michael Montemerlo, James Diebel, 2008

Hybrid A* is a path planner for a car among obstacles. It runs A* over a grid of bins in (x,y,θ)(x, y, \theta), but each bin stores one continuous pose, not the center of the bin. A node expands by driving short arcs of the car, left, straight or right at full steering, forward and backward, from its exact pose. So every path it returns can be driven, while the grid keeps the search finite. Reverse motion and changes of direction cost extra. The heuristic is the larger of two lower bounds: the length of a car path without obstacles, and the length of a grid path with obstacles but without the car's turning limit. Every few expansions the search tries an exact Reeds-Shepp path to the goal and stops when it is free. The method is a heuristic: it is neither complete nor optimal for the continuous problem, but it finds good paths in parking lots in a fraction of a second.

In plain words

Lay a grid over the map. A plain grid search would jump from the center of one square to the center of the next, and a car cannot drive that path. Hybrid A* instead keeps the real position of the car in each square. From there it tries six short drives: hard left, straight and hard right, forward or backward. Where a drive ends, it records the exact spot, in whatever square that is.

If two drives end in the same square, it keeps only the cheaper one. This keeps the search small, but it can throw away the one way that would have worked. Every now and then it also tries to reach the goal in one go with the shortest car path, and stops if that path is clear.

The problem

The model. The car is the kinematic bicycle model at the rear axle, with minimum turning radius ρ\rho, which may drive forward and backward. The map is an occupancy grid with cells of side rr. The search uses bins of r×rr \times r meters and Δθ=2π/nθ\Delta\theta = 2\pi/n_\theta radians, so a bounded map has finitely many bins. Bins are integers and costs are floating point numbers; the model is the word RAM at that resolution.

Input. The grid, a start pose and a goal pose, the radius ρ\rho, the length ℓ\ell of a primitive, the reverse factor cr≥1c_r \ge 1, the switch penalty cs≥0c_s \ge 0, and a goal tolerance.

Output. A list of arcs of curvature in {−1/ρ,0,1/ρ}\{-1/\rho, 0, 1/\rho\} with signed lengths, followed by an exact shot to the goal, or a pose in the goal region. Or failure.

How it differs from close pages. Plain A* on a grid of cells returns paths with corners that a car cannot follow. State lattice planning also searches with motion primitives, but its primitives join lattice points exactly, so states never drift off the grid and the search is resolution complete on the lattice; hybrid A* gives that up for primitives from any pose. Kinodynamic planning is the general problem, and sampling planners such as RRT* solve it with asymptotic optimality, at a higher cost. The Dubins path and the Reeds-Shepp path solve the problem without obstacles, in constant time.

The algorithm

  1. HYBRID-A*(map, start, goal, ρ, ℓ)
  2. 1store start in bin key(start) with g = 0; push it with f = h(start)
  3. 2h(q) = max(0, |q - goal| - εp), or its max with the grid distance from q to the goal
  4. 3key(q) = (floor(x / r), floor(y / r), floor(θ / Δθ))
  5. 4while the open list is not empty: pop the bin b with the least f
  6. 5if b is closed then continue; close b; q ← the pose stored in b
  7. 6if q is in the goal region then return the chain of primitives to q
  8. 7every N expansions: if the shot from q to the goal is free then return the chain + the shot
  9. 8for each κ in {-1/ρ, 0, 1/ρ} and each direction d in {+1, -1} do
  10. 9q' ← drive the arc (κ, d ℓ) from q; skip it if it hits an obstacle
  11. 10b' ← key(q'); skip it if b' is closed
  12. 11g' ← g(q) + ℓ (times cr if d < 0) (plus cs if d differs from the last direction)
  13. 12if b' is empty or g' < g(b') then store q' in b' with g', parent b; push b' with f = g' + h(q')
  14. 13return failure

Line L9 integrates the arc exactly, so the stored pose is where the car really is; only the bin is discrete. The shot of line L7 is a Reeds-Shepp path in Dolgov et al.; the implementation uses a Dubins path, which is forward only but simpler, and is still a drivable path. Dolgov et al. try the shot every NN expansions and more often near the goal. In the second heuristic of line L2, they precompute the car path length without obstacles as a lookup table, and they compute the grid distance with obstacles by dynamic programming over the 2D grid; the implementation uses the Euclidean distance in place of the first and an 8-connected Dijkstra for the second. After the search, Dolgov et al. smooth the path with the conjugate gradient method, trading length, curvature and clearance; the implementation does not smooth.

Example

A corridor 20 m long and 3 m wide, with cells of 1 m and 72 heading bins of 5 degrees. The car has ρ=2\rho = 2 m and primitives of ℓ=1.5\ell = 1.5 m, with cr=2c_r = 2 and cs=1c_s = 1. It starts at (3,1.5)(3, 1.5) facing +x+x and must end at (12,1.5)(12, 1.5) facing −x-x. A U-turn needs a corridor at least 2ρ=42\rho = 4 m wide, so a forward-only search fails: it closes all reachable bins and returns failure in 2 ms.

Measured, with reverse motion and a shot every 5 expansions: the search expands 360 bins in about 10 ms and returns 13 pieces with a length of 18.71 m, of which 3.0 m are in reverse, and 2 changes of direction, a three-point turn. Its cost is 18.71+3.0+2=23.7118.71 + 3.0 + 2 = 23.71. With a shot at every expansion it expands 307 bins and returns a cheaper path, cost 22.39, with 1.5 m in reverse. Without any shot and with a goal tolerance of 0.5 m and 0.1 rad, it expands 2014 bins and returns a path of cost 53.5 with 10 changes of direction. The goal region is small, and pruned bins make it hard to land in it with primitives alone. The grid heuristic does not change the result in this corridor, because the Euclidean distance is already close to the grid distance.

These numbers show two things. The shot is what makes the method practical, and the result depends on when the shot is tried, so the method is not optimal.

Correctness

The proof shows four things. Soundness: every returned path is a chain of car arcs with curvature at most 1/ρ1/\rho that passed the collision test, and it ends in the goal region or exactly at the goal. Termination: each bin is expanded at most once, so the search stops after at most B=nxnynθB = n_x n_y n_\theta expansions. The Euclidean heuristic is consistent. Relative optimality: without shots, with the Euclidean heuristic, with cs=0c_s = 0, and with bins fine enough that no two reachable poses share a bin, the search is A* on the graph of primitive sequences and returns the cheapest sequence. With coarse bins, neither this optimality nor completeness holds, and the collision test is only as good as its sampling.

Proof: Hybrid A* returns drivable paths, terminates, and is optimal relative to its primitives when the bins separate the statesfull

Line numbers refer to the pseudocode on the hybrid A* page. Hybrid A* is not complete and not optimal for the continuous problem; Dolgov et al. (2010) say so, and the page gives measured cases. What can be proved is narrower: every path it returns is a path of the car, it always stops, and, when its bins are fine enough, it finds the best sequence of its own motion primitives. The page calls this optimality relative to the discretization.

Setting. A pose is q=(x,y,θ)q = (x, y, \theta). A primitive is a pair (κ,d)(\kappa, d) with κ∈{−1/ρ,0,1/ρ}\kappa \in \{-1/\rho, 0, 1/\rho\} and d∈{+1,−1}d \in \{+1, -1\} (only +1+1 when reverse motion is off); it drives the arc of curvature κ\kappa and signed length d ℓd\,\ell from qq. Its cost is ℓ\ell for d=+1d = +1 and crℓc_r\ell for d=−1d = -1, with cr≥1c_r \ge 1, plus cs≥0c_s \ge 0 when dd differs from the direction of the previous primitive. The key of line L3 maps a pose to a bin (⌊x/r⌋,⌊y/r⌋,⌊θ/Δθ⌋)(\lfloor x/r\rfloor, \lfloor y/r\rfloor, \lfloor \theta/\Delta\theta\rfloor). The goal region is G={q:∣qxy−gxy∣≤ϵp, ∣θ−gθ∣≤ϵθ}G = \{q : |q_{xy} - g_{xy}| \le \epsilon_p,\ |\theta - g_\theta| \le \epsilon_\theta\}.

Lemma 1 (soundness). If the search returns a path, the path starts at the start pose, consists of arcs of curvature at most 1/ρ1/\rho in absolute value, passes the collision test of line L9 on every piece, and ends in GG, or exactly at the goal pose when it ends with a shot. The returned cost equals the cost of the path.

Proof. Line L12 stores in each node the parent bin and the primitive that led to it, and the pose of the node is the exact end pose of that primitive from the pose of the parent (the function move integrates the arc in closed form). By induction on the order in which nodes are stored, following the parents from any stored node gives a chain of primitives from the start pose to the pose of the node, and the stored gg is the sum of their costs, by line L11. A node is stored only after line L9 tests its primitive, so every primitive of the chain passed the test. A node replaced in its bin by line L12 is no longer reachable from the bin, but the chain of the node that replaced it has the same property. Line L6 returns the chain of a node whose pose is in GG. Line L7 returns the chain followed by a Dubins path, which consists of arcs of curvature ±1/ρ\pm 1/\rho and lines, ends exactly at the goal pose (Lemma 2 of the Dubins path proof), and passes the same test; its cost adds its length and one switch penalty if the chain ended in reverse. □\square

The collision test samples the arc at spacing at most r/4r/4. It is exact for the samples, not for the whole arc: an arc can clip the corner of a blocked cell between two samples. This is a limit of the test, and real implementations dilate the obstacles by a margin for this reason.

Lemma 2 (termination). On a map of nx×nyn_x \times n_y cells, the loop of lines L4 to L12 runs at most B=nxnynθB = n_x n_y n_\theta expansions (times (rmap/r)2(r_{map}/r)^2 if the bins are finer than the cells), and then returns.

Proof. A pose that line L9 accepts is in a free cell, so its bin is one of the BB bins of the map. Line L5 closes a bin when it expands its node, and a closed bin is never expanded again: line L10 skips closed bins, and line L4 skips heap entries of closed bins. So the number of expansions is at most BB, each pushes at most six entries, and the heap empties after finitely many pops. Line L13 then returns that no path was found. □\square

Lemma 3 (the heuristic is consistent). Let h(q)=max⁡(0,∣qxy−gxy∣−ϵp)h(q) = \max(0, |q_{xy} - g_{xy}| - \epsilon_p). Then h≤h \le the cost to reach GG from qq, and h(q)≤c(q,q′)+h(q′)h(q) \le c(q, q') + h(q') for every primitive from qq to q′q'.

Proof. A primitive of arc length ℓ\ell moves the position by at most ℓ\ell, and its cost is at least ℓ\ell. The function q↦∣qxy−gxy∣q \mapsto |q_{xy} - g_{xy}| is 1-Lipschitz in the position, and so is hh, so h(q)−h(q′)≤∣qxy−qxy′∣≤ℓ≤c(q,q′)h(q) - h(q') \le |q_{xy} - q'_{xy}| \le \ell \le c(q, q'). At a pose of GG, h=0h = 0. Summing along any path to GG gives admissibility. □\square

The grid heuristic of the option use_grid_heuristic is the distance on the 8-connected grid of free cells, minus a margin of two cell diagonals. It is not admissible in general, because the 8-connected distance can exceed the Euclidean shortest path by up to about 8%, and Dolgov et al. accept this.

Theorem (optimality relative to the primitives). Run the search without shots, with the Euclidean heuristic and cs=0c_s = 0. Let QQ be the set of poses reachable from the start by sequences of primitives of cost at most C∗C^*, where C∗C^* is the least cost of a sequence that ends in GG and passes the collision test. If the key of line L3 is injective on QQ, the search returns a path of cost C∗C^*.

Proof. With cs=0c_s = 0, the cost of a primitive depends only on its own pose and direction, not on the previous one, so the cost-to-go from a pose does not depend on how the pose was reached. When the key is injective on QQ, two different poses of QQ never share a bin, so line L12 never replaces a pose of QQ by a different pose; it only lowers the gg of the same pose. Then lines L4 to L12 are A* on the graph whose vertices are the poses of QQ and whose edges are the free primitives, with the consistent heuristic of Lemma 3. Poses outside QQ have g>C∗g > C^*, so f>C∗f > C^*, and they are never expanded before a goal pose of cost C∗C^*. If a pose outside QQ shares a bin with a pose pp of QQ, its gg exceeds C∗≥g∗(p)C^* \ge g^*(p), so line L12 replaces it by pp when pp is reached with its least cost, and the bin is not closed before that, because its ff is above C∗C^* until then. A* with a consistent heuristic closes each vertex with its least cost and returns the first goal vertex it expands, which has the least cost C∗C^*; see A* search and consistent heuristic. □\square

The theorem needs injectivity, and that is the point of the method: with coarse bins, line L12 keeps only one pose per bin, and the dropped pose may be the only one that reaches the goal cheaply, or at all. Then the result costs more than C∗C^*, or the search fails while a path exists. The test test_cost_is_at_least_the_best_primitive_sequence checks both sides on 12 random goals: with bins of 1 mm and 10510^5 headings, the result equals the least cost found by a uniform-cost search over exact poses, to 10−910^{-9}; with 1 m bins and 36 headings, the result is never cheaper. With a positive switch penalty, the bin would also have to keep the direction of motion for the theorem to hold.

What is not proved. Completeness and optimality for the continuous problem are false in general. A shot found earlier can be worse than a shot found later, which the page shows by measurement. The grid heuristic is only approximately admissible, so even the relative optimality needs the Euclidean heuristic.

Complexity

  • Time. At most BB expansions, each with six primitives, each checked at ss samples, and heap operations of O(log⁡B)O(\log B): O(B(log⁡B+s))O(B(\log B + s)), plus the cost of the shots. The grid heuristic adds a Dijkstra of O(nxnylog⁡(nxny))O(n_x n_y \log(n_x n_y)) once per goal. Dolgov et al. use a grid of 160 m by 160 m with 0.5 m cells and 5 degree heading bins, and report replanning times of about 50 to 300 ms on the vehicle (measurement in the paper).
  • Space. O(B)O(B) for the bins and the open list.
  • Measured. In the tests, random 20 m by 20 m maps with 15% of the cells blocked need from 5 to about 16,000 expansions; CPython does about 20,000 expansions per second on a laptop.

Properties

  • Not complete. A pose dropped by line L12 can be the only one that leads to the goal, so the search can fail when a path exists. Finer bins reduce this; they never remove it.
  • Not optimal. Relative to its primitives, it is optimal only when the bins separate the reachable poses. Against the continuous problem, the primitives with fixed curvature and length miss shorter paths, and the shot found first need not be the best.
  • Drivable paths. Unlike grid A*, every path is a path of the car, with the curvature bound and with exact poses.
  • Asymmetric costs. Reverse motion and gear changes cost more, which gives the natural parking behavior.
  • Heading continuity. The path is C1C^1 but its curvature jumps between 00 and ±1/ρ\pm 1/\rho; the smoothing step of the paper reduces this.

Variants and improvements

  • More primitives. More steering values, or several lengths, give smoother paths at a higher branching factor.
  • Heuristic tables. The nonholonomic heuristic without obstacles depends only on the relative pose, so a table computed once serves all queries.
  • Footprint checks. Real implementations test the car's rectangle against the obstacle map, often with a precomputed distance transform or a set of discs.
  • Smoothing. Dolgov et al. smooth the result with a cost on length, curvature and a Voronoi field for clearance, then interpolate.
  • State lattice. State lattice planning keeps the poses on a lattice and gets resolution completeness with respect to it.

When to use it

Use it for cars and car-like robots in unstructured spaces where reverse motion matters: parking lots, loading docks, U-turns in narrow streets, and open fields. It needs a map that fits in memory as a grid and a goal pose. For structured roads, a lattice or a sampling planner along the lane is more common. If you need guarantees of completeness or optimality, use a state lattice with resolution completeness on the lattice, or an asymptotically optimal sampling planner such as RRT*.

Pitfalls

  • Primitive length vs bin size. If a primitive is shorter than a bin, its end often falls in the bin of its start, which is closed, and the search stalls. Make ℓ\ell at least the diagonal of a bin, or allow successors in the same bin with a better cost.
  • The heading of the bin. The heading must be reduced modulo 2π2\pi before binning, or −π-\pi and π\pi fall in different bins.
  • Inadmissible grid heuristic. The 8-connected grid distance can overestimate the true shortest distance, so the search can return a worse path than it could. Dolgov et al. accept this.
  • Collision checks between samples. A sampled check can miss a thin obstacle between two samples; dilate the obstacles by the sample spacing.
  • Shot frequency. Shots are cheap to compute but cost a collision check each. Too rare, and the search wastes expansions near the goal; too frequent, and the checks dominate.
  • Goal tolerance. Without shots, a tight goal tolerance makes the goal very hard to hit with fixed primitives.

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.

hybrid_a_star.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/hybrid-a-star/. The authors are listed in prov/C6X95N.jsonl.

"""Hybrid A* (Dolgov, Thrun, Montemerlo and Diebel, 2008 and 2010).

A* search over the cells of a grid of (x, y, heading). Each cell keeps one continuous pose,
the best one found so far. A node expands by short arcs of a car with curvature -1/rho, 0
or +1/rho, forward and, if allowed, backward. The cost is the arc length, times a factor for
reverse motion, plus a penalty for each change of direction. The heuristic is the Euclidean
distance, and optionally the maximum of it and an 8-connected grid distance that knows the
obstacles. Every few expansions the search tries an analytic shot to the goal. Dolgov et al.
use a Reeds-Shepp path for the shot; this file uses a Dubins path (forward only), which is
shorter to write and is still a feasible path of the car.

The robot is a point. The map is a set of blocked square cells of side res; a motion is
free when its samples, spaced at most res / 4 apart, lie in free cells inside the map.
"""

import heapq
import math

TWO_PI = 2.0 * math.pi
EPS = 1e-10


def wrap(a):
    return (a + math.pi) % TWO_PI - math.pi


# ----- the map -----

class Grid:
    def __init__(self, width, height, res, blocked=()):
        self.nx, self.ny, self.res = width, height, res
        self.blocked = set(blocked)

    def cell(self, x, y):
        return int(math.floor(x / self.res)), int(math.floor(y / self.res))

    def free(self, x, y):
        i, j = self.cell(x, y)
        return 0 <= i < self.nx and 0 <= j < self.ny and (i, j) not in self.blocked


# ----- motion of the car -----

def move(q, kappa, s):
    """Exact pose after signed arc length s with curvature kappa (s < 0 drives backward)."""
    x, y, th = q
    if abs(kappa) < 1e-15:
        return x + s * math.cos(th), y + s * math.sin(th), th
    nth = th + kappa * s
    return x + (math.sin(nth) - math.sin(th)) / kappa, y - (math.cos(nth) - math.cos(th)) / kappa, nth


def motion_free(grid, q, kappa, s):
    n = max(1, int(math.ceil(abs(s) / (grid.res / 4.0))))
    for k in range(1, n + 1):
        p = move(q, kappa, s * k / n)
        if not grid.free(p[0], p[1]):
            return False
    return True


def path_free(grid, q, segments):
    for kappa, s in segments:
        if not motion_free(grid, q, kappa, s):
            return False
        q = move(q, kappa, s)
    return True


def endpoint(q, segments):
    for kappa, s in segments:
        q = move(q, kappa, s)
    return q


# ----- Dubins shot (forward, shortest of the six words) -----

def _mod(a):
    a = a % TWO_PI
    return 0.0 if a > TWO_PI - EPS else a


def _dubins_words(d, a, b):
    sa, sb, ca, cb = math.sin(a), math.sin(b), math.cos(a), math.cos(b)
    cab = math.cos(a - b)
    out = []
    p2 = 2 + d * d - 2 * cab + 2 * d * (sa - sb)  # LSL
    if p2 >= -EPS:
        vx, vy = d + sa - sb, cb - ca
        g = math.atan2(vy, vx) if math.hypot(vx, vy) > EPS else a
        out.append(("LSL", _mod(g - a), math.sqrt(max(p2, 0.0)), _mod(b - g)))
    p2 = 2 + d * d - 2 * cab + 2 * d * (sb - sa)  # RSR
    if p2 >= -EPS:
        vx, vy = d - sa + sb, ca - cb
        g = math.atan2(vy, vx) if math.hypot(vx, vy) > EPS else a
        out.append(("RSR", _mod(a - g), math.sqrt(max(p2, 0.0)), _mod(g - b)))
    p2 = -2 + d * d + 2 * cab + 2 * d * (sa + sb)  # LSR
    if p2 >= -EPS:
        p = math.sqrt(max(p2, 0.0))
        g = math.atan2(-ca - cb, d + sa + sb) - math.atan2(-2.0, p)
        out.append(("LSR", _mod(g - a), p, _mod(g - b)))
    p2 = -2 + d * d + 2 * cab - 2 * d * (sa + sb)  # RSL
    if p2 >= -EPS:
        p = math.sqrt(max(p2, 0.0))
        g = math.atan2(ca + cb, d - sa - sb) - math.atan2(2.0, p)
        out.append(("RSL", _mod(a - g), p, _mod(b - g)))
    c = (6 - d * d + 2 * cab + 2 * d * (sa - sb)) / 8  # RLR
    if abs(c) <= 1:
        p = TWO_PI - math.acos(c)
        t = _mod(a - math.atan2(ca - cb, d - sa + sb) + p / 2)
        out.append(("RLR", t, p, _mod(a - b - t + p)))
    c = (6 - d * d + 2 * cab + 2 * d * (sb - sa)) / 8  # LRL
    if abs(c) <= 1:
        p = TWO_PI - math.acos(c)
        t = _mod(-a - math.atan2(ca - cb, d + sa - sb) + p / 2)
        out.append(("LRL", t, p, _mod(b - a - t + p)))
    return out


def dubins_segments(q0, q1, rho):
    """Shortest Dubins path from q0 to q1 as a list of (curvature, arc length)."""
    dx, dy = q1[0] - q0[0], q1[1] - q0[1]
    d = math.hypot(dx, dy) / rho
    phi = math.atan2(dy, dx)
    best = None
    for word, t, p, q in _dubins_words(d, _mod(q0[2] - phi), _mod(q1[2] - phi)):
        if best is None or t + p + q < best[0]:
            best = (t + p + q, word, (t, p, q))
    _, word, lens = best
    kap = {"L": 1.0 / rho, "R": -1.0 / rho, "S": 0.0}
    return [(kap[w], rho * a) for w, a in zip(word, lens) if a > 0.0]


# ----- heuristics -----

def grid_distance(grid, goal_xy):
    """8-connected Dijkstra over free cells from the goal cell, in meters (Dolgov's second
    heuristic, the holonomic distance with obstacles)."""
    start = grid.cell(*goal_xy)
    dist = {start: 0.0}
    heap = [(0.0, start)]
    diag = math.sqrt(2.0) * grid.res
    while heap:
        d, (i, j) = heapq.heappop(heap)
        if d > dist[(i, j)]:
            continue
        for di in (-1, 0, 1):
            for dj in (-1, 0, 1):
                if di == 0 and dj == 0:
                    continue
                c = (i + di, j + dj)
                if not (0 <= c[0] < grid.nx and 0 <= c[1] < grid.ny) or c in grid.blocked:
                    continue
                nd = d + (diag if di and dj else grid.res)
                if nd < dist.get(c, math.inf):
                    dist[c] = nd
                    heapq.heappush(heap, (nd, c))
    return dist


# ----- the search -----

def hybrid_a_star(grid, start, goal, rho, step, n_heading=72, reverse=True,
                  reverse_cost=2.0, switch_cost=1.0, pos_tol=0.5, ang_tol=0.1,
                  shot_every=0, use_grid_heuristic=False, bin_res=None, max_expansions=200000):
    """Returns (cost, segments, expansions) or None. segments is a list of
    (curvature, signed arc length) from the start pose."""
    bin_res = grid.res if bin_res is None else bin_res
    dth = TWO_PI / n_heading

    def key(q):  # @line L3
        return (int(math.floor(q[0] / bin_res)), int(math.floor(q[1] / bin_res)),
                int(math.floor((q[2] % TWO_PI) / dth)) % n_heading)

    h2d = grid_distance(grid, goal[:2]) if use_grid_heuristic else None

    def h(q):  # @line L2
        e = max(0.0, math.hypot(q[0] - goal[0], q[1] - goal[1]) - pos_tol)
        if h2d is not None:
            e = max(e, h2d.get(grid.cell(q[0], q[1]), math.inf) - 2.0 * math.sqrt(2.0) * grid.res - pos_tol)
        return e

    def at_goal(q):
        return math.hypot(q[0] - goal[0], q[1] - goal[1]) <= pos_tol and abs(wrap(q[2] - goal[2])) <= ang_tol

    moves = [(k, d) for d in ((1.0, -1.0) if reverse else (1.0,)) for k in (-1.0 / rho, 0.0, 1.0 / rho)]
    k0 = key(start)
    # node: key -> (g, pose, parent key, (kappa, s), direction)
    nodes = {k0: (0.0, tuple(start), None, None, 0.0)}  # @line L1
    heap = [(h(start), 0, k0)]  # @line L1
    closed = set()
    counter = 1
    expansions = 0

    def chain(k):
        segs = []
        while nodes[k][2] is not None:
            segs.append(nodes[k][3])
            k = nodes[k][2]
        return segs[::-1]

    while heap:  # @line L4
        f, _, k = heapq.heappop(heap)  # @line L4
        if k in closed:
            continue
        g, q, _, _, direction = nodes[k]
        if f > g + h(q) + 1e-12:  # an outdated entry
            continue
        closed.add(k)  # @line L5
        expansions += 1
        if at_goal(q):  # @line L6
            return g, chain(k), expansions  # @line L6
        if shot_every and expansions % shot_every == 0:  # @line L7
            shot = dubins_segments(q, goal, rho)  # @line L7
            if path_free(grid, q, shot):  # @line L7
                cost = g + sum(abs(s) for _, s in shot) + (switch_cost if direction < 0 else 0.0)
                return cost, chain(k) + shot, expansions  # @line L7
        if expansions >= max_expansions:
            return None
        for kappa, d in moves:  # @line L8
            if not motion_free(grid, q, kappa, d * step):  # @line L9
                continue
            q2 = move(q, kappa, d * step)  # @line L9
            k2 = key(q2)  # @line L10
            if k2 in closed:  # @line L10
                continue
            g2 = g + step * (reverse_cost if d < 0 else 1.0)  # @line L11
            if direction != 0.0 and d != direction:  # @line L11
                g2 += switch_cost  # @line L11
            if k2 not in nodes or g2 < nodes[k2][0]:  # @line L12
                nodes[k2] = (g2, q2, k, (kappa, d * step), d)  # @line L12
                heapq.heappush(heap, (g2 + h(q2), counter, k2))  # @line L12
                counter += 1
    return None  # @line L13


def path_cost(segments, reverse_cost=2.0, switch_cost=1.0):
    """The cost of a list of (curvature, signed length) as the search counts it."""
    cost, prev = 0.0, 0.0
    for _, s in segments:
        d = 1.0 if s > 0 else -1.0
        cost += abs(s) * (reverse_cost if d < 0 else 1.0)
        if prev != 0.0 and d != prev:
            cost += switch_cost
        prev = d
    return cost
test_hybrid_a_star.py 151 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/hybrid-a-star/. The authors are listed in prov/C6X95N.jsonl.

import heapq
import math
import random

from hybrid_a_star import (
    Grid,
    dubins_segments,
    endpoint,
    hybrid_a_star,
    move,
    path_cost,
    path_free,
    wrap,
)

RHO, STEP = 2.0, 1.5


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_map(rng, n=20, density=0.15):
    blocked = {(i, j) for i in range(n) for j in range(n) if rng.random() < density}
    return Grid(n, n, 1.0, blocked)


def random_free_pose(rng, grid):
    while True:
        x, y = rng.uniform(0, grid.nx), rng.uniform(0, grid.ny)
        if grid.free(x, y):
            return x, y, rng.uniform(-math.pi, math.pi)


def best_sequence_cost(start, goal, moves, bound, pos_tol, ang_tol, reverse_cost, switch_cost):
    """Uniform-cost search over exact poses and the last direction: the least cost of any
    sequence of the motion primitives that ends in the goal region (empty map)."""
    def at_goal(q):
        return math.hypot(q[0] - goal[0], q[1] - goal[1]) <= pos_tol and abs(wrap(q[2] - goal[2])) <= ang_tol

    def key(q, d):
        return round(q[0], 9), round(q[1], 9), round(q[2] % (2 * math.pi), 9), d

    heap = [(0.0, 0, tuple(start), 0.0)]
    seen = {}
    c = 1
    while heap:
        g, _, q, d = heapq.heappop(heap)
        if at_goal(q):
            return g
        k = key(q, d)
        if k in seen:
            continue
        seen[k] = g
        for kappa, dd in moves:
            g2 = g + STEP * (reverse_cost if dd < 0 else 1.0) + (switch_cost if d and dd != d else 0.0)
            if g2 <= bound + 1e-9:
                heapq.heappush(heap, (g2, c, move(q, kappa, dd * STEP), dd))
                c += 1
    return math.inf


def test_dubins_shot_ends_at_the_goal():
    rng = random.Random(1)
    for _ in range(2000):
        q0 = (rng.uniform(-9, 9), rng.uniform(-9, 9), rng.uniform(-math.pi, math.pi))
        q1 = (rng.uniform(-9, 9), rng.uniform(-9, 9), rng.uniform(-math.pi, math.pi))
        segs = dubins_segments(q0, q1, RHO)
        assert all(abs(k) <= 1.0 / RHO + 1e-15 and s > 0 for k, s in segs)
        assert pose_error(endpoint(q0, segs), q1) < 1e-9


def test_paths_are_free_and_drivable():
    rng = random.Random(2)
    found = 0
    for trial in range(20):
        grid = random_map(rng)
        start, goal = random_free_pose(rng, grid), random_free_pose(rng, grid)
        res = hybrid_a_star(grid, start, goal, RHO, STEP, shot_every=5, use_grid_heuristic=True, max_expansions=4000)
        if res is None:
            continue
        found += 1
        cost, segs, _ = res
        assert path_free(grid, start, segs)
        assert all(abs(k) <= 1.0 / RHO + 1e-15 for k, _ in segs)
        assert abs(path_cost(segs) - cost) < 1e-9
        end = endpoint(start, segs)
        assert math.hypot(end[0] - goal[0], end[1] - goal[1]) <= 0.5 + 1e-9
        assert abs(wrap(end[2] - goal[2])) <= 0.1 + 1e-9
    assert found >= 12


def test_cost_is_at_least_the_best_primitive_sequence():
    # Without the shot, the result is a sequence of primitives, so it cannot beat the best one.
    # With fine bins nothing is pruned that matters, and the two are equal.
    rng = random.Random(3)
    grid = Grid(40, 40, 1.0)
    moves = [(k, d) for d in (1.0, -1.0) for k in (-1.0 / RHO, 0.0, 1.0 / RHO)]
    gaps = []
    for _ in range(12):
        start = (20.0, 20.0, rng.uniform(-math.pi, math.pi))
        seq = [rng.choice(moves) for _ in range(rng.randint(2, 4))]
        goal = endpoint(start, [(k, d * STEP) for k, d in seq])
        bound = path_cost([(k, d * STEP) for k, d in seq], 2.0, 0.0)
        opt = best_sequence_cost(start, goal, moves, bound, 0.3, 0.05, 2.0, 0.0)
        assert opt <= bound + 1e-9
        fine = hybrid_a_star(grid, start, goal, RHO, STEP, n_heading=100000, bin_res=1e-3,
                             switch_cost=0.0, pos_tol=0.3, ang_tol=0.05)
        assert abs(fine[0] - opt) < 1e-9
        coarse = hybrid_a_star(grid, start, goal, RHO, STEP, n_heading=36, switch_cost=0.0,
                               pos_tol=0.3, ang_tol=0.05)
        if coarse is not None:
            assert coarse[0] >= opt - 1e-9
            gaps.append(coarse[0] - opt)
    assert gaps


def test_forward_path_is_not_shorter_than_dubins():
    # With reverse motion off, any path is a forward path of curvature at most 1 / rho, so its
    # length is at least the Dubins length between its end poses.
    rng = random.Random(4)
    for _ in range(10):
        grid = random_map(rng, density=0.08)
        start, goal = random_free_pose(rng, grid), random_free_pose(rng, grid)
        res = hybrid_a_star(grid, start, goal, RHO, STEP, reverse=False, shot_every=3,
                            use_grid_heuristic=True, max_expansions=3000)
        if res is None:
            continue
        cost, segs, _ = res
        length = sum(abs(s) for _, s in segs)
        dub = sum(s for _, s in dubins_segments(start, endpoint(start, segs), RHO))
        assert length >= dub - 1e-7


def test_shot_on_an_empty_map_is_the_dubins_path():
    grid = Grid(30, 30, 1.0)
    start, goal = (5.0, 5.0, 0.0), (20.0, 22.0, 1.0)
    cost, segs, expansions = hybrid_a_star(grid, start, goal, RHO, STEP, shot_every=1)
    assert expansions == 1
    assert pose_error(endpoint(start, segs), goal) < 1e-9
    assert abs(cost - sum(s for _, s in dubins_segments(start, goal, RHO))) < 1e-12


def test_walled_off_goal_returns_none():
    # The search runs out of cells and returns None.
    blocked = {(6, j) for j in range(12)}
    grid = Grid(12, 12, 1.0, blocked)
    assert hybrid_a_star(grid, (2.0, 6.0, 0.0), (10.0, 6.0, 0.0), RHO, STEP, n_heading=36, shot_every=4) is None

History

The Stanford Racing Team built Junior for the DARPA Urban Challenge of 2007, a race of autonomous cars in a town with traffic, parking and blocked roads. Junior used hybrid A* to plan in parking lots and for U-turns, and was second in the race. Dolgov, Thrun, Montemerlo and Diebel described the planner at an AAAI workshop in 2008, and in a longer paper in the International Journal of Robotics Research in 2010, with the two heuristics, the analytic Reeds-Shepp expansion and the smoothing. Hybrid A* became the standard parking planner of many open-source autonomous driving stacks.

References

  1. Dmitri Dolgov, Sebastian Thrun, Michael Montemerlo and James Diebel, Path planning for autonomous vehicles in unknown semi-structured environments, The International Journal of Robotics Research 29(5), 2010, pages 485 to 501 (the hybrid-state search, the two heuristics, the analytic Reeds-Shepp expansion, the penalties for reverse and for switching, and the smoothing with conjugate gradient)
  2. Practical search techniques in path planning for autonomous driving, pages 32 to 37 (the first description of the method)
  3. Steven M. LaValle, Planning Algorithms, Cambridge University Press, 2006, Section 14.2 (reachability graphs, motion primitives and resolution completeness under differential constraints)

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