Algorithmresearch
Hamilton-Jacobi reachability
Also called HJ reachability, level set reachability.
Computes backward reachable sets of nonlinear systems with inputs and disturbances as the sublevel set of the viscosity solution of an HJ PDE.
- Time
- O(K n k^n) worst
- Space
- O(k^n) extra
- Where
- K = the number of time steps; k = the number of grid nodes per axis; n = the state dimension
- Model
- Real RAM
- Properties
- deterministicnot exactoffline
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Ian M. Mitchell, Alexandre M. Bayen, Claire J. Tomlin, 2005
Hamilton-Jacobi reachability computes the set of states from which a control input can drive a nonlinear system into a target set within a time , whatever a bounded disturbance does. This is the backward reachable tube. The method writes the target as , solves a Hamilton-Jacobi equation for a value function on a grid, and reads the tube as . Mitchell, Bayen and Tomlin (2005) proved that this sublevel set is the reachable set of the dynamic game when is the viscosity solution. The equation is a Hamilton-Jacobi-Bellman equation with an extra . It handles nonlinear dynamics, sets that are not convex, and two players. The price is a grid, so the cost is exponential in the state dimension. It is one method for the reachable set computation problem.
In plain words
Put a number on every point of the state space: negative inside the target, positive outside, and roughly the distance to the edge of the target. Now let time run backward. At each point, ask how fast the best input can push the state toward lower numbers, when the disturbance pushes the other way. Lower the number at that point by this speed. A point whose number drops to zero or below can reach the target in the time you have.
A point that reached the target once stays counted, so numbers only go down. The computer does this on a grid of points, with a small time step. It is easy and works for curved, nonlinear systems, but the grid has an enormous number of points when the state has more than four or five components.
The problem
The system is with , and compact, and bounded and Lipschitz in . The target is , for a Lipschitz function , often a signed distance. The control tries to reach the target and the disturbance tries to prevent it. The backward reachable tube of horizon is the set of initial states from which the control can reach the target at some time in , for every behavior of the disturbance, when the disturbance may react to the current input (a nonanticipative strategy). In time to go , the value function solves
and the tube is (Mitchell, Bayen and Tomlin 2005). Without the , the zero sublevel set is the set of states that are in the target exactly at time . The input to the program is a grid, , the function , bounds on the grid, and . The output is on the grid.
The algorithm
The scheme is the first order Lax-Friedrichs scheme (see Lax-Friedrichs scheme and Osher and Shu 1991), with and the backward and forward differences of along axis .
HJ-REACH(grid, g, G, alpha, T)- 1
for each node x_j do V_j ← g(x_j) - 2
K ← ceil(T * sum_i alpha_i / dx_i); dtau ← T / K - 3
for k ← 1 to K do - 4
for each node j do - 5
p-_i ← (V_j - V_{j - e_i}) / dx_i; p+_i ← (V_{j + e_i} - V_j) / dx_i for each axis i - 6
Ghat_j ← G(x_j, (p+ + p-) / 2) - sum_i alpha_i (p+_i - p-_i) / 2 - 7
for each node j do V_j ← V_j - dtau * max(0, Ghat_j) - 8
return V
Line L2 chooses the time step by the CFL condition . Line L6 is the numerical Hamiltonian: at the central difference, plus a diffusion term that makes the scheme monotone. Line L7 is a forward Euler step of . At the edge of the grid, the program fills the missing neighbor by linear extrapolation. For the common control-affine case with box or ball sets and , has a closed form. For example, with , gives .
Example
Take with , and the target , with . Here , so and . The open loop is unstable, and the input can stop the drift only where . The best input is , and from the solution is . It reaches at time if , so the exact tube is , which is for . The program runs on with .
| nodes | steps | computed edge of the tube | error | |
|---|---|---|---|---|
| 101 | 0.04 | 38 | 0.474709 | 0.040 |
| 201 | 0.02 | 75 | 0.498601 | 0.016 |
| 401 | 0.01 | 150 | 0.509698 | 0.005 |
The edge is the zero of the linear interpolant of . Here the error falls faster than , the rate that the theory guarantees. The computed set is inside the true tube on these grids, because the diffusion term rounds the kink of at its minimum. For with , and , the exact tube at is , and the program finds the edge at to rounding error, because stays linear on each side. With a stronger disturbance (, ) the tube is the target itself, and does not change. For in the plane with and a disk target of radius , the tube at is the disk of radius . On a 41 by 41 grid the program puts its edge at radius on the axes and on the diagonal. The tests check all these cases.
Correctness
Under the CFL condition and , the update of line L7 is monotone: a larger at a node or at a neighbor never gives a smaller new value. It commutes with adding a constant, so it does not increase the maximum difference of two solutions. It is consistent with the equation to first order. Crandall and Lions (1984) proved that monotone consistent schemes for converge to the viscosity solution, with an error of order . Mitchell, Bayen and Tomlin (2005) proved that the zero sublevel set of this viscosity solution is the backward reachable tube. Lygeros (2004) gives the same kind of characterization through an optimal control problem whose cost is the minimum of along the solution. The scheme also never raises , so the computed set grows with , like the true tube. The proof of the scheme properties, and the exact statements that it quotes, are in the correctness proof. The theorems give convergence, not a guaranteed inner or outer bound on a fixed grid.
Proof: The Lax-Friedrichs scheme for the reachability equation is monotone, stable and consistentpartial
Setting. The system is with and compact, and bounded and Lipschitz in . The target is with Lipschitz. In time to go the value function solves
Write , so that . The grid has steps on the axes . Lines L5 to L7 compute, at each node ,
with the one-sided differences of along axis . Assume (or, if is only Lipschitz in , that ), and the CFL condition of line L2.
This file proves the properties of the scheme at nodes away from the edge of the grid. The convergence to the viscosity solution and the meaning of its zero sublevel set are theorems of the literature, quoted at the end; this is why the status is partial.
Lemma 1 (monotone). At an inner node, is a nondecreasing function of and of each neighbor value .
Proof. Write as a function of the values. The point has entries , which do not depend on , and . Raise by . The first term of changes by at most by the Lipschitz bound, and the second term drops by exactly . So does not increase. The same holds for . Since is nondecreasing, does not decrease. Now raise by . Only the second term of changes, and it rises by . As is 1-Lipschitz, changes by at least by the CFL condition.
Lemma 2 (stable). The update commutes with adding a constant: if , then . With Lemma 1, this gives for any two grid functions, at inner nodes whose neighbors are inner nodes or obey the same bound.
Proof. The differences do not change when a constant is added, so does not change. For the bound, let . Then , and Lemma 1 with the first part gives .
Lemma 3 (consistent). If is the restriction of a smooth function , then , so the update is a consistent first order scheme for .
Proof. is the central difference, equal to , and is Lipschitz in . , so the second term is .
Lemma 4 (the tube grows). at every node, so the computed set never shrinks as grows.
Proof. .
Termination. Line L2 sets steps of length , which meets the CFL condition. Each step visits each of the nodes once and does work plus one evaluation of . So the program stops after operations and evaluations.
Results quoted from the literature.
- Crandall and Lions (1984) prove that a monotone and consistent scheme of the form for converges to the viscosity solution, with an error of order in the maximum norm when the initial data are Lipschitz and is fixed. Lemmas 1 to 3 are the hypotheses of this kind of result. The implementation also covers Hamiltonians that depend on ; the tests check such a case against its exact solution.
- Mitchell, Bayen and Tomlin (2005) prove that the zero sublevel set of the viscosity solution of , , is the backward reachable tube of horizon : the states from which the target can be reached within time , when the other player may react to the current input (a nonanticipative strategy). They state it with the roles of the players swapped; swapping the roles swaps and in .
At the edge of the grid. The missing neighbor is filled by linear extrapolation, which makes there. This update is not monotone. An inner node at distance nodes from the edge does not depend on the edge values during the first steps, because each step looks one node to each side. So Lemmas 1 and 2 hold for the nodes that are more than nodes from the edge. A test of the implementation checks the order of two solutions only at these nodes, and it fails near the edge for rough initial data.
What is not proved. The computed set is an approximation. It is not proved to contain, or to be contained in, the true tube on a given grid. In the tests, it lies inside the true tube or on its boundary.
Complexity
The model is the real RAM, with one evaluation of counted as operations.
- A grid with nodes per axis has nodes, and each step costs : this is the curse of dimensionality.
- Line L2 gives steps, and grows linearly with for a fixed domain.
- The total is time and memory for one copy of .
As a rule of thumb from the literature (see Bansal et al. 2017), direct grid methods are practical up to about four or five state dimensions. This is a statement about current hardware, not a theorem.
Properties
- Nonlinear and two-player. It needs only , so nonlinear dynamics, nonconvex targets and a disturbance that plays against the control are all allowed.
- Approximate. The result converges to the true tube as the grid is refined. On a fixed grid it is not a guaranteed over-approximation or under-approximation, unlike zonotope reachability.
- Gives a controller. Where is differentiable, is the input that reaches the target. The safety controller of the complement set uses the same gradient, as a control barrier function does.
- Monotone in time. The computed tube only grows with , like the true one.
- Exponential in . The grid limits the method to a few dimensions.
Variants and improvements
- Higher order schemes. Osher and Shu (1991) gave ENO schemes for HJ equations; with a total variation diminishing Runge-Kutta step in time they are the default in level set toolboxes. They are more accurate on smooth parts, but they are not monotone.
- Local Lax-Friedrichs. Use a bound at each node instead of one for the whole grid. It adds less diffusion. In the example, instead of .
- Reach-avoid and avoid sets. Swap the roles of the players to get the set of states that the disturbance can force into an unsafe set. Its complement is a safe set, and its limit as is the largest control invariant set inside the safe region. Combining a target and an obstacle gives reach-avoid sets.
- Minimum time. For time-invariant dynamics, the first time at which a state enters the tube is the minimum time to reach the target. For speeds that depend only on the position, it solves an eikonal equation, and the fast marching method computes it in one sweep.
- Fewer dimensions. Decomposition of the system, sampling of states, and neural approximations of trade guarantees for size; Bansal et al. (2017) survey them.
When to use it
Use it for systems with two to four state dimensions where the nonlinearity or the game matters: collision avoidance between two vehicles in relative coordinates, a pendulum with input limits, an aircraft that must stay in an envelope. Use zonotope reachability or other set propagation for linear systems in many dimensions. Use a barrier certificate search when you only need a proof of safety, not the exact set.
Pitfalls
- No min with zero (line L7). Without , the program computes the set of states that are in the target exactly at time . A state that passes through the target and leaves again is then missed.
- Too large a time step (line L2). If , the scheme is not monotone and can blow up. must bound on the whole grid, including the large near the edge.
- The edge of the grid. Linear extrapolation is not monotone, and with rough data the values near the edge can be wrong by much more than the grid error. The errors move inward one node per step. Put the edge far from the set of interest, by more than nodes if the data are rough.
- Order of min and max. lets the disturbance react to the input. gives the control the advantage. They agree when separates into a part with and a part with ; otherwise pick the one that matches the information of the real system.
- Reading a grid result as a proof. The computed set is an approximation. For a safety proof, add a margin of the size of the grid error, or verify the result with another method.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/hamilton-jacobi-reachability/. The authors are listed in prov/CFEBTN.jsonl.
"""Backward reachable tubes by a Lax-Friedrichs scheme on a grid.
The system is x' = f(x, u, d). The control u wants to reach the target set
{x : g(x) <= 0} and the disturbance d tries to prevent this. The value
V(x, tau) solves, in time to go tau >= 0,
dV/dtau = min(0, H(x, grad V)), V(x, 0) = g(x),
H(x, p) = min over u of max over d of p . f(x, u, d).
The backward reachable tube of horizon T is {x : V(x, T) <= 0} (Mitchell,
Bayen and Tomlin 2005). With G = -H the equation reads
dV/dtau = -max(0, G(x, grad V)), and the scheme is
V_new = V - dtau * max(0, G(x, pbar) - sum_i alpha_i (p+_i - p-_i) / 2),
with pbar = (p+ + p-) / 2 and one-sided differences p- and p+. It is
monotone if alpha_i >= max |dG/dp_i| on the grid and
dtau * sum_i alpha_i / dx_i <= 1.
A grid is a list of (lo, hi, k) per axis: k equally spaced nodes from lo to
hi. V is a flat list in row-major order (the last axis runs fastest). At
the edge of the grid the missing neighbor is filled by linear extrapolation,
so the one-sided difference there equals the inner one.
Cost: K = ceil(T sum_i alpha_i / dx_i) time steps, each O(n) work per
node, so O(K n M) for M = k_1 ... k_n nodes. M grows like k^n: this is the
curse of dimensionality of the method.
"""
import math
__all__ = ["grid_points", "hj_reach", "zero_crossings_1d"]
def grid_points(grid):
"""Return (points, strides, steps): the nodes in row-major order."""
axes = [[lo + (hi - lo) * j / (k - 1) for j in range(k)] for lo, hi, k in grid]
steps = [(hi - lo) / (k - 1) for lo, hi, k in grid]
sizes = [k for _, _, k in grid]
strides = [1] * len(grid)
for i in range(len(grid) - 2, -1, -1):
strides[i] = strides[i + 1] * sizes[i + 1]
points = [[]]
for ax in axes:
points = [p + [v] for p in points for v in ax]
return points, strides, steps
def hj_reach(grid, g, G, alpha, T, cfl=1.0):
"""Return (points, V, K): V(x, T) on the grid and the number K of time steps.
g(x) is the target function, G(x, p) = -H(x, p), alpha a list with
alpha_i >= max |dG/dp_i| on the grid, T >= 0 the horizon. cfl <= 1.
"""
if not 0 < cfl <= 1:
raise ValueError("hj_reach: cfl must be in (0, 1]")
points, strides, steps = grid_points(grid)
sizes = [k for _, _, k in grid]
if min(sizes) < 2:
raise ValueError("hj_reach: each axis needs at least 2 nodes")
n = len(grid)
v = [float(g(x)) for x in points] # @line L1
rate = sum(a / h for a, h in zip(alpha, steps))
big_k = 0 if T == 0 else max(1, math.ceil(T * rate / cfl - 1e-12)) # @line L2
dtau = T / big_k if big_k else 0.0
m = len(points)
index = [[(j // strides[i]) % sizes[i] for i in range(n)] for j in range(m)]
for _ in range(big_k): # @line L3
gh = [0.0] * m
for j in range(m): # @line L4
pm = [0.0] * n
pp = [0.0] * n
for i in range(n):
s, h, pos, k = strides[i], steps[i], index[j][i], sizes[i]
if pos == 0:
pp[i] = (v[j + s] - v[j]) / h
pm[i] = pp[i]
elif pos == k - 1:
pm[i] = (v[j] - v[j - s]) / h
pp[i] = pm[i]
else:
pm[i] = (v[j] - v[j - s]) / h # @line L5
pp[i] = (v[j + s] - v[j]) / h
pbar = [(a + b) / 2 for a, b in zip(pm, pp)]
gh[j] = G(points[j], pbar) - sum(alpha[i] * (pp[i] - pm[i]) / 2 for i in range(n)) # @line L6
v = [vj - dtau * max(0.0, gj) for vj, gj in zip(v, gh)] # @line L7
return points, v, big_k # @line L8
def zero_crossings_1d(xs, v):
"""Return the points where the piecewise linear interpolant of v changes sign."""
out = []
for a, b, va, vb in zip(xs, xs[1:], v, v[1:]):
if (va <= 0) != (vb <= 0):
out.append(a + (b - a) * va / (va - vb))
return out
test_hamilton_jacobi_reachability.py 106 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/hamilton-jacobi-reachability/. The authors are listed in prov/CFEBTN.jsonl.
import math
import random
from hamilton_jacobi_reachability import grid_points, hj_reach, zero_crossings_1d
def run_1d(k, g, G, alpha, T, lo=-2.0, hi=2.0):
pts, v, steps = hj_reach([(lo, hi, k)], g, G, [alpha], T)
return [p[0] for p in pts], v, steps
def test_grid_layout():
pts, strides, steps = grid_points([(0.0, 1.0, 3), (-1.0, 1.0, 5)])
assert len(pts) == 15 and strides == [5, 1]
assert pts[0] == [0.0, -1.0] and pts[1] == [0.0, -0.5] and pts[5] == [0.5, -1.0]
assert steps == [0.5, 0.5]
def test_input_against_disturbance_1d():
"""x' = u + d, |u| <= 1, |d| <= 0.5: the tube is |x| <= r0 + 0.5 T."""
a, b, r0, T = 1.0, 0.5, 0.5, 1.0
for k in (41, 81):
xs, v, steps = run_1d(k, lambda x: abs(x[0]) - r0, lambda x, p: (a - b) * abs(p[0]), a - b, T)
assert steps == math.ceil(T * (a - b) / (4.0 / (k - 1)))
cross = zero_crossings_1d(xs, v)
assert len(cross) == 2
assert abs(cross[0] + r0 + (a - b) * T) < 1e-9
assert abs(cross[1] - r0 - (a - b) * T) < 1e-9
def test_stronger_disturbance_keeps_target():
"""With |d| <= 1 > |u| <= 0.5 the control cannot make progress: the tube is the target."""
a, b, r0 = 0.5, 1.0, 0.5
xs, v, _ = run_1d(81, lambda x: abs(x[0]) - r0, lambda x, p: (a - b) * abs(p[0]), b - a, 1.0)
for x, val in zip(xs, v):
assert abs(val - (abs(x) - r0)) < 1e-12
def test_unstable_scalar_system():
"""x' = x + u, |u| <= 1, target |x| <= r0: the tube is |x| <= 1 - (1 - r0) e^(-T)."""
r0, T = 0.2, 0.5
exact = 1 - (1 - r0) * math.exp(-T)
errors = []
for k in (101, 201, 401):
xs, v, _ = run_1d(k, lambda x: abs(x[0]) - r0, lambda x, p: abs(p[0]) - p[0] * x[0], 3.0, T)
cross = zero_crossings_1d(xs, v)
assert len(cross) == 2 and abs(cross[0] + cross[1]) < 1e-9
errors.append(abs(cross[1] - exact))
assert errors[0] > errors[1] > errors[2]
assert errors[2] < 0.01
def test_disk_in_the_plane():
"""x' = u with ||u||_2 <= 1 and a disk target of radius r0: a disk of radius r0 + T."""
r0, T, k = 0.5, 0.5, 41
pts, v, steps = hj_reach([(-2.0, 2.0, k), (-2.0, 2.0, k)], lambda x: math.hypot(x[0], x[1]) - r0,
lambda x, p: math.hypot(p[0], p[1]), [1.0, 1.0], T)
assert steps == 10
xs = [-2.0 + 4.0 * j / (k - 1) for j in range(k)]
mid = k // 2
row = [v[mid * k + j] for j in range(k)]
col = [v[j * k + mid] for j in range(k)]
diag = [v[j * k + j] for j in range(k)]
radius = r0 + T
for line, scale in ((row, 1.0), (col, 1.0), (diag, math.sqrt(2))):
cross = zero_crossings_1d([scale * x for x in xs], line)
assert len(cross) == 2
assert abs(abs(cross[0]) - radius) < 0.1 and abs(cross[1] - radius) < 0.1
# Nodes far inside or far outside the exact disk are classified right.
for x, val in zip(pts, v):
d = math.hypot(x[0], x[1])
if d < radius - 0.15:
assert val <= 0
if d > radius + 0.15:
assert val > 0
def test_tube_grows_and_comparison():
"""The scheme never raises V (the tube only grows) and keeps the order of initial data.
The extrapolated edge values are not monotone, so the order is checked
only at nodes that the edge cannot reach in K steps (one node per step).
"""
rng = random.Random(11)
G = lambda x, p: abs(p[0]) - p[0] * x[0]
xs, v1, _ = run_1d(81, lambda x: abs(x[0]) - 0.2, G, 3.0, 0.3)
xs, v2, _ = run_1d(81, lambda x: abs(x[0]) - 0.2, G, 3.0, 0.6)
assert all(b <= a + 1e-12 for a, b in zip(v1, v2))
for _ in range(5):
bumps = [rng.uniform(0, 0.3) for _ in range(81)]
lower = lambda x: abs(x[0]) - 0.3
upper = lambda x, bumps=bumps: abs(x[0]) - 0.3 + bumps[round((x[0] + 2) * 20)]
_, va, steps = run_1d(81, lower, G, 3.0, 0.4)
_, vb, _ = run_1d(81, upper, G, 3.0, 0.4)
assert steps == 24
inner = range(steps + 1, 81 - steps - 1)
assert all(va[j] <= vb[j] + 1e-12 for j in inner)
def test_zero_horizon_returns_target():
xs, v, steps = run_1d(11, lambda x: x[0] ** 2 - 1, lambda x, p: abs(p[0]), 1.0, 0.0)
assert steps == 0
assert v == [x * x - 1 for x in xs]
History
Isaacs studied pursuit and evasion games through partial differential equations in the 1950s and 1960s. Crandall and Lions defined viscosity solutions in 1983, and in 1984 they proved the convergence of monotone schemes for HJ equations. Osher and Shu (1991) gave the ENO schemes used in level set methods. Lygeros (2004) linked reachable sets to minimum cost optimal control. Mitchell, Bayen and Tomlin (2005) gave the time-dependent HJ formulation for games and the level set computation used here. Bansal, Chen, Herbert and Tomlin (2017) surveyed the method and later work.
References
- I. M. Mitchell, A. M. Bayen and C. J. Tomlin, A time-dependent Hamilton-Jacobi formulation of reachable sets for continuous dynamic games, IEEE Transactions on Automatic Control 50(7), 2005, pages 947 to 957, the theorem that the zero sublevel set of the viscosity solution is the backward reachable set, and the numerical method
- J. Lygeros, On reachability and minimum cost optimal control, Automatica 40(6), 2004, pages 917 to 927, reachable sets as level sets of the value function of an optimal control problem
- M. G. Crandall and P.-L. Lions, Two approximations of solutions of Hamilton-Jacobi equations, Mathematics of Computation 43(167), 1984, pages 1 to 19, convergence of monotone schemes and the error bound of order the square root of the grid step
- S. Osher and C.-W. Shu, High-order essentially nonoscillatory schemes for Hamilton-Jacobi equations, SIAM Journal on Numerical Analysis 28(4), 1991, pages 907 to 922, the Lax-Friedrichs numerical Hamiltonian and higher order ENO schemes
- S. Bansal, M. Chen, S. Herbert and C. J. Tomlin, Hamilton-Jacobi reachability: A brief overview and recent advances, IEEE Conference on Decision and Control, 2017, pages 2242 to 2253, the overview of the formulation, its variants and the methods against the curse of dimensionality
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag CFEBTN Edit this page History Report an error Markdown