Algorithm Search⌘K

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
Properties
deterministicnot exactoffline
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 x′=f(x,u,d)x' = f(x, u, d) into a target set within a time TT, whatever a bounded disturbance dd does. This is the backward reachable tube. The method writes the target as {x:g(x)≤0}\{x : g(x) \le 0\}, solves a Hamilton-Jacobi equation for a value function V(x,τ)V(x, \tau) on a grid, and reads the tube as {x:V(x,T)≤0}\{x : V(x, T) \le 0\}. Mitchell, Bayen and Tomlin (2005) proved that this sublevel set is the reachable set of the dynamic game when VV is the viscosity solution. The equation is a Hamilton-Jacobi-Bellman equation with an extra min⁡(0,⋅)\min(0, \cdot). 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 x′=f(x,u,d)x' = f(x, u, d) with x∈Rnx \in \mathbb{R}^n, u∈Uu \in U and d∈Dd \in D compact, and ff bounded and Lipschitz in xx. The target is {x:g(x)≤0}\{x : g(x) \le 0\}, for a Lipschitz function gg, often a signed distance. The control tries to reach the target and the disturbance tries to prevent it. The backward reachable tube of horizon TT is the set of initial states from which the control can reach the target at some time in [0,T][0, T], for every behavior of the disturbance, when the disturbance may react to the current input (a nonanticipative strategy). In time to go τ=T−t\tau = T - t, the value function solves

Vτ=min⁡(0,H(x,∇V)),V(x,0)=g(x),H(x,p)=min⁡u∈Umax⁡d∈D  p⋅f(x,u,d),V_\tau = \min\big(0, H(x, \nabla V)\big), \qquad V(x, 0) = g(x), \qquad H(x, p) = \min_{u \in U} \max_{d \in D} \; p \cdot f(x, u, d),

and the tube is {x:V(x,T)≤0}\{x : V(x, T) \le 0\} (Mitchell, Bayen and Tomlin 2005). Without the min⁡(0,⋅)\min(0, \cdot), the zero sublevel set is the set of states that are in the target exactly at time TT. The input to the program is a grid, gg, the function G=−HG = -H, bounds αi≥sup⁡∣∂G/∂pi∣\alpha_i \ge \sup |\partial G / \partial p_i| on the grid, and TT. The output is V(⋅,T)V(\cdot, T) on the grid.

The algorithm

The scheme is the first order Lax-Friedrichs scheme (see Lax-Friedrichs scheme and Osher and Shu 1991), with pi−p_i^- and pi+p_i^+ the backward and forward differences of VV along axis ii.

  1. HJ-REACH(grid, g, G, alpha, T)
  2. 1for each node x_j do V_j ← g(x_j)
  3. 2K ← ceil(T * sum_i alpha_i / dx_i); dtau ← T / K
  4. 3for k ← 1 to K do
  5. 4for each node j do
  6. 5p-_i ← (V_j - V_{j - e_i}) / dx_i; p+_i ← (V_{j + e_i} - V_j) / dx_i for each axis i
  7. 6Ghat_j ← G(x_j, (p+ + p-) / 2) - sum_i alpha_i (p+_i - p-_i) / 2
  8. 7for each node j do V_j ← V_j - dtau * max(0, Ghat_j)
  9. 8return V

Line L2 chooses the time step by the CFL condition Δτ∑iαi/Δxi≤1\Delta\tau \sum_i \alpha_i / \Delta x_i \le 1. Line L6 is the numerical Hamiltonian: GG at the central difference, plus a diffusion term αi(pi+−pi−)/2\alpha_i (p_i^+ - p_i^-)/2 that makes the scheme monotone. Line L7 is a forward Euler step of Vτ=−max⁡(0,G)V_\tau = -\max(0, G). At the edge of the grid, the program fills the missing neighbor by linear extrapolation. For the common control-affine case f=f0(x)+gu(x)u+gd(x)df = f_0(x) + g_u(x) u + g_d(x) d with box or ball sets UU and DD, HH has a closed form. For example, x′=u+dx' = u + d with ∣u∣≤a|u| \le a, ∣d∣≤b|d| \le b gives H(p)=−(a−b)∣p∣H(p) = -(a - b)|p|.

Example

Take x′=x+ux' = x + u with ∣u∣≤1|u| \le 1, and the target ∣x∣≤0.2|x| \le 0.2, with g(x)=∣x∣−0.2g(x) = |x| - 0.2. Here H(x,p)=px−∣p∣H(x, p) = px - |p|, so G(x,p)=∣p∣−pxG(x, p) = |p| - px and ∣∂G/∂p∣≤1+∣x∣|\partial G / \partial p| \le 1 + |x|. The open loop is unstable, and the input can stop the drift only where ∣x∣<1|x| < 1. The best input is u=−sign⁡(x)u = -\operatorname{sign}(x), and from x0∈(0,1)x_0 \in (0, 1) the solution is x(t)=1−(1−x0)etx(t) = 1 - (1 - x_0)e^t. It reaches 0.20.2 at time TT if x0=1−0.8e−Tx_0 = 1 - 0.8 e^{-T}, so the exact tube is ∣x∣≤1−0.8e−T|x| \le 1 - 0.8 e^{-T}, which is 0.5147750.514775 for T=0.5T = 0.5. The program runs on [−2,2][-2, 2] with α=3\alpha = 3.

nodes Δx\Delta x steps KK 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 VV. Here the error falls faster than Δx\sqrt{\Delta x}, 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 gg at its minimum. For x′=u+dx' = u + d with ∣u∣≤1|u| \le 1, ∣d∣≤0.5|d| \le 0.5 and g(x)=∣x∣−0.5g(x) = |x| - 0.5, the exact tube at T=1T = 1 is ∣x∣≤1|x| \le 1, and the program finds the edge at ±1\pm 1 to rounding error, because VV stays linear on each side. With a stronger disturbance (∣d∣≤1|d| \le 1, ∣u∣≤0.5|u| \le 0.5) the tube is the target itself, and VV does not change. For x′=ux' = u in the plane with ∥u∥2≤1\|u\|_2 \le 1 and a disk target of radius 0.50.5, the tube at T=0.5T = 0.5 is the disk of radius 11. On a 41 by 41 grid the program puts its edge at radius 0.9640.964 on the axes and 0.9620.962 on the diagonal. The tests check all these cases.

Correctness

Under the CFL condition and αi≥sup⁡∣∂G/∂pi∣\alpha_i \ge \sup |\partial G / \partial p_i|, the update of line L7 is monotone: a larger VV 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 ut+H(Du)=0u_t + H(Du) = 0 converge to the viscosity solution, with an error of order Δx\sqrt{\Delta x}. 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 gg along the solution. The scheme also never raises VV, so the computed set grows with τ\tau, 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 x′=f(x,u,d)x' = f(x, u, d) with u∈Uu \in U and d∈Dd \in D compact, and ff bounded and Lipschitz in xx. The target is {x:g(x)≤0}\{x : g(x) \le 0\} with gg Lipschitz. In time to go τ≥0\tau \ge 0 the value function solves

Vτ=min⁡(0,H(x,∇V)),V(x,0)=g(x),H(x,p)=min⁡u∈Umax⁡d∈Dp⋅f(x,u,d).V_\tau = \min(0, H(x, \nabla V)), \qquad V(x, 0) = g(x), \qquad H(x, p) = \min_{u \in U} \max_{d \in D} p \cdot f(x, u, d).

Write G=−HG = -H, so that Vτ=−max⁡(0,G(x,∇V))V_\tau = -\max(0, G(x, \nabla V)). The grid has steps Δxi\Delta x_i on the axes i=1,…,ni = 1, \ldots, n. Lines L5 to L7 compute, at each node jj,

Vjnew=Vj−Δτmax⁡(0,G^j),G^j=G(xj,p++p−2)−∑iαipi+−pi−2,V_j^{new} = V_j - \Delta\tau \max\Big(0, \hat G_j\Big), \qquad \hat G_j = G\Big(x_j, \frac{p^+ + p^-}{2}\Big) - \sum_i \alpha_i \frac{p_i^+ - p_i^-}{2},

with pi±p_i^\pm the one-sided differences of VV along axis ii. Assume αi≥sup⁡∣∂G/∂pi∣\alpha_i \ge \sup |\partial G / \partial p_i| (or, if GG is only Lipschitz in pp, that ∣G(x,p)−G(x,q)∣≤∑iαi∣pi−qi∣|G(x, p) - G(x, q)| \le \sum_i \alpha_i |p_i - q_i|), and the CFL condition Δτ∑iαi/Δxi≤1\Delta\tau \sum_i \alpha_i / \Delta x_i \le 1 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, VjnewV_j^{new} is a nondecreasing function of VjV_j and of each neighbor value Vj±eiV_{j \pm e_i}.

Proof. Write G^j\hat G_j as a function of the values. The point (p++p−)/2(p^+ + p^-)/2 has entries (Vj+ei−Vj−ei)/(2Δxi)(V_{j + e_i} - V_{j - e_i}) / (2 \Delta x_i), which do not depend on VjV_j, and pi+−pi−=(Vj+ei−2Vj+Vj−ei)/Δxip_i^+ - p_i^- = (V_{j + e_i} - 2V_j + V_{j - e_i}) / \Delta x_i. Raise Vj+eiV_{j + e_i} by ϵ>0\epsilon > 0. The first term of G^j\hat G_j changes by at most αiϵ/(2Δxi)\alpha_i \epsilon / (2\Delta x_i) by the Lipschitz bound, and the second term drops by exactly αiϵ/(2Δxi)\alpha_i \epsilon / (2\Delta x_i). So G^j\hat G_j does not increase. The same holds for Vj−eiV_{j - e_i}. Since max⁡(0,⋅)\max(0, \cdot) is nondecreasing, −Δτmax⁡(0,G^j)-\Delta\tau \max(0, \hat G_j) does not decrease. Now raise VjV_j by ϵ\epsilon. Only the second term of G^j\hat G_j changes, and it rises by ϵ∑iαi/Δxi\epsilon \sum_i \alpha_i / \Delta x_i. As max⁡(0,⋅)\max(0, \cdot) is 1-Lipschitz, VjnewV_j^{new} changes by at least ϵ−Δτϵ∑iαi/Δxi≥0\epsilon - \Delta\tau \epsilon \sum_i \alpha_i / \Delta x_i \ge 0 by the CFL condition. ■\blacksquare

Lemma 2 (stable). The update commutes with adding a constant: if W=V+cW = V + c, then Wnew=Vnew+cW^{new} = V^{new} + c. With Lemma 1, this gives max⁡j∣Vjnew−Wjnew∣≤max⁡j∣Vj−Wj∣\max_j |V_j^{new} - W_j^{new}| \le \max_j |V_j - W_j| for any two grid functions, at inner nodes whose neighbors are inner nodes or obey the same bound.

Proof. The differences p±p^\pm do not change when a constant is added, so G^j\hat G_j does not change. For the bound, let c=max⁡∣V−W∣c = \max |V - W|. Then W−c≤V≤W+cW - c \le V \le W + c, and Lemma 1 with the first part gives Wnew−c≤Vnew≤Wnew+cW^{new} - c \le V^{new} \le W^{new} + c. ■\blacksquare

Lemma 3 (consistent). If VV is the restriction of a smooth function ϕ\phi, then G^j=G(xj,∇ϕ(xj))+O(max⁡iΔxi)\hat G_j = G(x_j, \nabla\phi(x_j)) + O(\max_i \Delta x_i), so the update is a consistent first order scheme for Vτ=−max⁡(0,G(x,∇V))V_\tau = -\max(0, G(x, \nabla V)).

Proof. (p++p−)/2(p^+ + p^-)/2 is the central difference, equal to ∇ϕ(xj)+O(Δx2)\nabla \phi(x_j) + O(\Delta x^2), and GG is Lipschitz in pp. pi+−pi−=Δxi ∂iiϕ(xj)+O(Δxi2)p_i^+ - p_i^- = \Delta x_i \, \partial_{ii}\phi(x_j) + O(\Delta x_i^2), so the second term is O(Δx)O(\Delta x). ■\blacksquare

Lemma 4 (the tube grows). Vjnew≤VjV_j^{new} \le V_j at every node, so the computed set {V≤0}\{V \le 0\} never shrinks as τ\tau grows.

Proof. Δτmax⁡(0,G^j)≥0\Delta\tau \max(0, \hat G_j) \ge 0. ■\blacksquare

Termination. Line L2 sets K=⌈T∑iαi/Δxi⌉K = \lceil T \sum_i \alpha_i / \Delta x_i \rceil steps of length Δτ=T/K\Delta\tau = T / K, which meets the CFL condition. Each step visits each of the M=∏ikiM = \prod_i k_i nodes once and does O(n)O(n) work plus one evaluation of GG. So the program stops after O(KnM)O(K n M) operations and evaluations.

Results quoted from the literature.

  • Crandall and Lions (1984) prove that a monotone and consistent scheme of the form unew=u−Δt H^(p+,p−)u^{new} = u - \Delta t \, \hat H(p^+, p^-) for ut+H(Du)=0u_t + H(Du) = 0 converges to the viscosity solution, with an error of order Δx\sqrt{\Delta x} in the maximum norm when the initial data are Lipschitz and Δτ/Δx\Delta\tau / \Delta x is fixed. Lemmas 1 to 3 are the hypotheses of this kind of result. The implementation also covers Hamiltonians that depend on xx; 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 Vτ=min⁡(0,H(x,∇V))V_\tau = \min(0, H(x, \nabla V)), V(⋅,0)=gV(\cdot, 0) = g, is the backward reachable tube of horizon TT: the states from which the target can be reached within time TT, 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 min⁡\min and max⁡\max in HH.

At the edge of the grid. The missing neighbor is filled by linear extrapolation, which makes p+=p−p^+ = p^- there. This update is not monotone. An inner node at distance dd nodes from the edge does not depend on the edge values during the first dd steps, because each step looks one node to each side. So Lemmas 1 and 2 hold for the nodes that are more than KK 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 {Vj≤0}\{V_j \le 0\} 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 GG counted as O(n)O(n) operations.

  • A grid with kk nodes per axis has M=knM = k^n nodes, and each step costs O(nM)O(n M): this is the curse of dimensionality.
  • Line L2 gives K=⌈T∑iαi/Δxi⌉K = \lceil T \sum_i \alpha_i / \Delta x_i \rceil steps, and KK grows linearly with kk for a fixed domain.
  • The total is O(Knkn)O(K n k^n) time and O(kn)O(k^n) memory for one copy of VV.

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 HH, 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 VV is differentiable, u(x)=arg⁡min⁡umax⁡d∇V⋅f(x,u,d)u(x) = \arg\min_u \max_d \nabla V \cdot f(x, u, d) 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 τ\tau, like the true one.
  • Exponential in nn. 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 αi\alpha_i at each node instead of one for the whole grid. It adds less diffusion. In the example, α=1+∣x∣\alpha = 1 + |x| instead of 33.
  • 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 T→∞T \to \infty 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 VV 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 max⁡(0,⋅)\max(0, \cdot), the program computes the set of states that are in the target exactly at time TT. A state that passes through the target and leaves again is then missed.
  • Too large a time step (line L2). If Δτ∑iαi/Δxi>1\Delta\tau \sum_i \alpha_i / \Delta x_i > 1, the scheme is not monotone and can blow up. α\alpha must bound ∣∂G/∂p∣|\partial G / \partial p| on the whole grid, including the large ∣x∣|x| 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 KK nodes if the data are rough.
  • Order of min and max. min⁡umax⁡d\min_u \max_d lets the disturbance react to the input. max⁡dmin⁡u\max_d \min_u gives the control the advantage. They agree when ff separates into a part with uu and a part with dd; 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.

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

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

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of correctness
  • 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