Algorithmresearch
Control barrier function quadratic program
Also called CBF-QP, safety filter.
Changes a nominal control as little as possible, by a quadratic program at each state, so that a control barrier function condition holds.
- Time
- O(m log m) worst
- Space
- O(m) extra
- Where
- m = the number of inputs
- Model
- Real RAM
- Properties
- deterministicexactonlineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Aaron D. Ames, Jessy W. Grizzle, Paulo Tabuada, Xiangru Xu, 2014
The control barrier function quadratic program (CBF-QP) takes the input that a nominal controller wants and returns the closest input that satisfies the condition of a control barrier function . For and the safe set , the condition is , which is linear in . So at each state the filter solves a small quadratic program, and if the program is feasible along the way and the closed loop is Lipschitz, the state never leaves . The nominal controller handles the task and the filter only acts near the boundary of . A control barrier function is the function; this page is the controller built on it; a barrier certificate is the different object that proves safety of a system without an input.
In plain words
A driver steers toward a goal. A guard sits next to the driver and watches one safety score, which is positive while the car is safe and zero at the edge of danger. Close to the edge, the score may only fall slowly, and the closer the car is to the edge, the slower it may fall. Each moment, the guard looks at what the driver wants and asks whether that keeps the score falling slowly enough. If yes, the guard does nothing. If no, the guard makes the smallest change to the driver's command that keeps the rule. The smallest change is easy to find because the rule is a straight line in the space of commands. When the command is limited, the guard may find no allowed command at all, and then the guard has no answer.
The problem
Input. At the current state : the nominal input , the row , the number with , and optional limits (each bound may be absent). Here is continuously differentiable and is an extended class K function: continuous, strictly increasing, with ; the common choice is with .
Output. The solution of
or a report that the constraints are infeasible. The feasible set is convex and the cost is strictly convex, so the solution is unique when it exists.
Used as feedback, makes along the closed loop. With , locally Lipschitz (see the Lipschitz condition) and a locally Lipschitz , the solutions are unique by the Picard-Lindelöf theorem, and the comparison lemma gives for all when . So is forward invariant (a positively invariant set of the closed loop).
The algorithm
CBF-QP(u_nom, a, b, ℓ, r)- 1
u ← clip(u_nom) - 2
if a·u + b ≥ 0 then return u - 3
if Σ_j max_{ℓ_j ≤ v ≤ r_j} a_j v + b < 0 then return INFEASIBLE - 4
Λ ← sorted values λ > 0 with u_nom,j + λ a_j ∈ {ℓ_j, r_j} - 5
binary search Λ for the piece [λ_-, λ_+] where ψ(λ_-) < 0 ≤ ψ(λ_+), ψ(λ) = a·clip(u_nom + λa) + b; λ ← root of ψ on that piece - 6
return clip(u_nom + λ a)
Line L1 respects the limits first, and line L2 returns that input if it already satisfies the barrier condition. This is the usual case far from the boundary, where the filter does nothing. Line L3 checks whether any allowed input can satisfy the condition. For a fixed multiplier , the Lagrangian is separable, and its minimizer over the box is . The function is continuous, nondecreasing and linear between the points of line L4, where a coordinate reaches a bound. Line L5 finds the multiplier with , which makes the barrier constraint active, and line L6 returns the input. These are the KKT conditions of the program, and the proof checks optimality directly.
Without input limits, lines L4 and L5 reduce to one formula:
The filter adds the smallest multiple of , the direction that increases fastest per unit of input.
Example
A point robot in the plane has with . A round obstacle of radius 1 sits at , so . Use and the nominal controller , which drives the robot in a straight line to the goal through the obstacle. Here and , so and .
At : , , , and , so the filter acts. With no limits, , and . Check: , so the constraint is active.
A 4th order Runge-Kutta simulation with step and the filter evaluated inside the right side gives:
| filter active | ||||||
|---|---|---|---|---|---|---|
| 0 | 0 | 0.2 | 3.04 | 0.77228 | 0.12277 | yes |
| 1 | 0.62007 | 0.46277 | 1.11835 | 0.56645 | 0.48076 | yes |
| 2 | 1.68245 | 1.14481 | 0.41142 | 1.90340 | 0.34827 | yes |
| 3 | 3.14916 | 0.57364 | 0.64965 | 0.85084 | -0.57364 | no |
| 4 | 3.68700 | 0.21103 | 1.89049 | 0.31300 | -0.21103 | no |
| 8 | 3.99427 | 0.00387 | 2.97712 | 0.00573 | -0.00387 | no |
| 12 | 3.99989 | 0.00007 | 2.99958 | 0.00011 | -0.00007 | no |
The smallest value of is , at , and the filter changes the input for the last time at (measurements). After that, the nominal controller runs alone and the robot reaches the goal.
Correctness
The full proof is in proofs/correctness.md. Its main steps:
- Inner problem. For , minimizes the Lagrangian over the box, because the Lagrangian is a sum of one-dimensional quadratics.
- Shape of psi. Each term is nondecreasing in , whatever the sign of , and it is linear between the points where the coordinate meets a bound. So the binary search of line L5 is valid, and the root on one linear piece is found exactly.
- Optimality. If , is feasible and , then for every feasible , . Strict convexity gives uniqueness.
- Infeasibility. Line L3 computes the supremum of over the box, which decides feasibility. If the supremum is infinite, the last piece of has a positive slope, so a root exists.
- Safety. Along the closed loop, . By the comparison lemma (Khalil 2002, Section 3.4), stays above the solution of , , which never becomes negative. For , gives .
The tests compare the algorithm in exact Fraction arithmetic with a brute force solver that tries every active set, on 600 random instances with to , random boxes with missing bounds and some , and check the KKT conditions. They also check the closed form without limits, that integer data give exact fractions, the infeasible example below, the closed loop , , against within , the obstacle run above ( throughout and arrival at the goal), and the sampled-data failure in the pitfalls.
Proof: The CBF-QP algorithm returns the unique minimizer or correctly reports infeasibility, and the filtered closed loop keeps the safe set forward invariantfull
At a fixed state, the problem is
where , , and is a box in which a bound may be absent ( or ), with . The factor does not change the minimizer. Write for the projection onto , which clamps each coordinate to . For put
Termination
Lines L1 to L3 and L6 are loops over the coordinates. Line L4 makes at most breakpoints. The binary search of line L5 halves the interval of indices at each step, so it ends after at most steps. So the algorithm ends.
Lemma 1: the inner minimization
For each , minimizes over .
Proof. , where the constant does not depend on . The sum is separable, and the minimizer of over an interval is clamped to the interval.
Lemma 2: the shape of psi
is continuous and nondecreasing on . It is linear between consecutive points of , the set of line L4. After the largest point of (after 0 if is empty), its slope is .
Proof. . Terms with are zero. If , the argument increases with , the clamp is continuous and nondecreasing, and the term is times it, so it is nondecreasing. If , the argument decreases, the clamp of it is nonincreasing, and the factor makes the term nondecreasing. The clamp is linear (slope 1 or 0) between the values of where the argument crosses or , and these values are in when they are positive. So each term is linear between points of , with slope when the coordinate is strictly inside its interval and 0 when it is clamped. After the last point of , a coordinate with has passed every finite bound that it can cross. If is finite it is clamped at ; otherwise it is free. The case is the same with . This gives .
Lemma 3: the feasibility test
The problem is feasible if and only if , where . if and only if some has or some has ; otherwise , and the supremum is attained.
Proof. The supremum of a separable linear function over a box is the sum of the suprema over the intervals. If is finite it is attained at the point described, so a feasible point exists if and only if . If , some point of has . Line L3 computes exactly this test.
Theorem 1: the QP step
If the problem is infeasible, the algorithm returns INFEASIBLE. Otherwise it returns the unique minimizer and a multiplier with and .
Proof. Sufficiency of the conditions. Suppose , is feasible and . For every feasible ,
using and , then Lemma 1. So is a minimizer. The objective is strictly convex and the feasible set is convex, so the minimizer is unique.
Line L2. If , then satisfies the conditions, and the answer is .
Line L3. If the test fails, the problem is infeasible by Lemma 3, and the answer is correct. From now on and the problem is feasible.
Lines L4 and L5. Let be the sorted points of . By Lemma 2 the values are nondecreasing in , so the predicate is false and then true, and the binary search returns the first index with a true value, or if there is none. Put .
- If the index is at most , then . is linear on , so the linear interpolation of line L5 gives the root in this interval exactly.
- If no point has , then (or if ). If were finite, then at every coordinate with would sit at the bound that attains , so , a contradiction. So , and the slope of Lemma 2 is positive. Then is the root.
In both cases and , so is feasible, and the conditions hold. Line L6 returns . Every operation is a field operation, so the result is exact with rational data.
Theorem 2: forward invariance of the safe set
Let with , locally Lipschitz on an open set . Let be continuously differentiable, let be closed in , and let be locally Lipschitz, strictly increasing, with . Suppose that for every the QP with , and the box is feasible, and that its solution makes locally Lipschitz on . Then every solution with stays in on its whole interval of existence.
Proof. The closed loop has unique solutions (Picard-Lindelöf). Let be a solution with on , and let be the supremum of the times with . On , put . By the chain rule and the constraint of the QP,
Let be the solution of , . It is unique because is locally Lipschitz. The constant is a solution, so a solution with cannot cross zero, and . By the comparison lemma (Khalil 2002, Lemma 3.4, applied to , which satisfies ), on . So for .
If , then because is closed and is continuous, so . is open, so stays in a little longer after , which contradicts the choice of . So , and for all .
For the comparison is explicit: , so .
Remark: when the closed loop is Lipschitz
Without the box, Theorem 1 gives the closed form . If , and are locally Lipschitz in and on , then is locally Lipschitz, because sums, products, the maximum of two Lipschitz functions and the quotient by a function that stays away from zero on compact sets are locally Lipschitz. So the hypothesis of Theorem 2 holds in this case. The theorem says nothing about a controller that holds between sampling times; then holds only at the sampling instants.
Complexity
With inputs, lines L1 to L3 take time. Line L4 sorts at most breakpoints in . The binary search of line L5 evaluates at points, each. In total time and extra space. Without limits it is . Forming and costs one gradient of and one evaluation of and , which usually dominates. With several barrier constraints, or with a Lyapunov constraint added, the program is a general convex QP and needs a QP solver.
Properties
- Minimally invasive. When satisfies the condition, the filter returns it unchanged. Far from the boundary of the nominal controller acts alone.
- Pointwise. The program uses only the current state. It does not predict, so it cannot plan around a future conflict; the condition limits only how fast may fall.
- Unique. The solution is unique when the program is feasible.
- Lipschitz in the simple case. Without limits and with , the closed form is locally Lipschitz when , , and are, so the closed loop has unique solutions and the safety theorem applies.
- Exact. With rational data, every step is a field operation, and the result is exact.
Variants and improvements
- CLF-CBF QP. Add a control Lyapunov function constraint with a penalized slack , so that stability gives way to safety when they conflict (Ames, Xu, Grizzle and Tabuada 2017).
- Several barriers. Each barrier adds one linear constraint. The program is then a general QP, and the constraints can be jointly infeasible even when each one alone is feasible.
- High order barriers. When , the input does not appear in . Exponential or high order CBFs put the condition on a higher derivative of (see the control barrier function page).
- Sampled data and robustness. Margins added to , or conditions that bound over the whole sampling interval, keep safety for held inputs and model errors.
- Closed form without optimization. For one constraint, a smooth formula in the style of Sontag's universal formula also gives a safe feedback (Wieland and Allgöwer 2007).
- Predictive filters. A reference governor or a predictive filter based on model predictive control looks ahead and can handle input limits that the pointwise program cannot.
When to use it
Use it when a nominal controller already does the task, perhaps a learned or hand-tuned one, and you need a guarantee that the state stays in a set described by one or a few smooth inequalities. It suits robots that avoid obstacles, vehicles that keep a distance, and systems with state limits. It needs a function that really is a control barrier function with the input limits you have; without that, the program can become infeasible. When the input limits are tight or the safe set is complex, use a method that computes a control invariant set directly, such as Hamilton-Jacobi reachability, or a predictive method.
Pitfalls
- Held inputs at line L6. The safety theorem assumes the input is updated continuously. For , , and , holding the input for time gives near the boundary (a calculation for this example). With and the factor is , and the simulation reaches , an unsafe state (measurement). With , or with and , stays nonnegative (measurement). Here is the condition; in general, add a margin.
- Infeasible program at line L3. For with , and , the condition is , which some satisfies only when . For the state is safe but no allowed input keeps the condition, so is not a control barrier function with these limits. Choose so that the condition is feasible with the real limits, for example here.
- Undesired equilibria at line L6. When points straight into the obstacle, the filter can cancel it exactly. In the example, from the robot moves along the axis and stops in front of the obstacle: at it is at with (measurement). The filter keeps safety but not the task.
- The choice of alpha at line L2. A large lets the state come close to the boundary, and a small makes the filter act early. In the example, , and give smallest values of of about , and , and arrival within of the goal at , and (measurements).
- Zero gradient at line L5. If , the input does not affect , and the program is feasible only if . A position limit on a system with force input has this problem. Use a high order barrier.
- Floating point at line L2. With floats, can be for an input that is safe in exact arithmetic, and the solver then makes a tiny change. This is harmless, but tests that compare inputs must allow a tolerance.
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/cbf-safety-filter/. The authors are listed in prov/3VWCBR.jsonl.
"""Control barrier function quadratic program (CBF-QP) with one barrier
constraint and optional box limits on the input.
At a state x of x' = f(x) + g(x) u with a control barrier function h and an
extended class K function alpha, put a = L_g h(x) (a row of m numbers) and
b = L_f h(x) + alpha(h(x)). The filter solves
minimize |u - u_nom|^2 subject to a . u + b >= 0, lo <= u <= hi.
For fixed lambda >= 0, the Lagrangian is minimized over the box by
u(lambda) = clip(u_nom + lambda a). psi(lambda) = a . u(lambda) + b is
continuous, nondecreasing and piecewise linear, so the multiplier is 0 if
clip(u_nom) is feasible and otherwise the smallest root of psi, found by a
binary search over the sorted breakpoints and a linear solve on one piece.
With Fraction inputs the result is exact.
Precondition: u_nom and a are lists of m numbers; lo and hi are None or
lists of m entries, each a number or None (no bound), with lo_j <= hi_j.
Cost: O(m log m) time for the sort and O(log m) evaluations of psi, each
O(m); O(m) extra space.
"""
from fractions import Fraction
__all__ = ["clip", "cbf_qp", "cbf_filter", "INFEASIBLE"]
INFEASIBLE = None
def _div(p, q):
# int / int would give a float; keep exact values exact.
if isinstance(p, int) and isinstance(q, int):
return Fraction(p, q)
return p / q
def _bounds(lo, hi, m):
lo = [None] * m if lo is None else list(lo)
hi = [None] * m if hi is None else list(hi)
return lo, hi
def clip(v, lo, hi):
"""Clamp each v_j to [lo_j, hi_j]; None means no bound."""
out = []
for vj, l, h in zip(v, lo, hi):
if l is not None and vj < l:
vj = l
if h is not None and vj > h:
vj = h
out.append(vj)
return out
def _dot(a, b):
return sum((x * y for x, y in zip(a, b)), 0)
def cbf_qp(u_nom, a, b, lo=None, hi=None):
"""Return (u, lam): the solution of the CBF-QP and the multiplier of the
barrier constraint, or (INFEASIBLE, None) if no u in the box satisfies
a . u + b >= 0."""
m = len(u_nom)
lo, hi = _bounds(lo, hi, m)
def u_of(lam):
return clip([u + lam * aj for u, aj in zip(u_nom, a)], lo, hi)
def psi(lam):
return _dot(a, u_of(lam)) + b
u = clip(u_nom, lo, hi) # @line L1
if _dot(a, u) + b >= 0: # @line L2
return u, 0 # @line L2
best, unbounded = b, False # @line L3
for aj, l, h in zip(a, lo, hi): # @line L3
if aj > 0:
if h is None:
unbounded = True
else:
best += aj * h
elif aj < 0:
if l is None:
unbounded = True
else:
best += aj * l
if not unbounded and best < 0: # @line L3
return INFEASIBLE, None # @line L3
bps = set() # @line L4
for uj, aj, l, h in zip(u_nom, a, lo, hi): # @line L4
if aj != 0:
for bound in (l, h):
if bound is not None:
lam = _div(bound - uj, aj)
if lam > 0:
bps.add(lam)
bps = sorted(bps) # @line L4
# Find the first breakpoint with psi >= 0; psi(0) < 0 here.
lo_i, hi_i = 0, len(bps) # @line L5
while lo_i < hi_i: # @line L5
mid = (lo_i + hi_i) // 2
if psi(bps[mid]) >= 0:
hi_i = mid
else:
lo_i = mid + 1
left = bps[lo_i - 1] if lo_i > 0 else 0 # @line L5
p_left = psi(left) # @line L5
if lo_i < len(bps): # @line L5
right = bps[lo_i]
p_right = psi(right)
lam = left + _div((0 - p_left) * (right - left), p_right - p_left)
else:
# Past the last breakpoint, a coordinate moves only if it has no
# bound in the direction of a_j, so psi has slope sum a_j^2 over
# those coordinates. L3 ensures that this slope is positive.
slope = 0
for aj, l, h in zip(a, lo, hi):
if (aj > 0 and h is None) or (aj < 0 and l is None):
slope += aj * aj
lam = left + _div(0 - p_left, slope)
return u_of(lam), lam # @line L6
def cbf_filter(f, g, h, grad_h, alpha, u_nom, lo=None, hi=None):
"""Return control(t, x) that applies the CBF-QP to u_nom(t, x).
f(x) is a list of n numbers, g(x) a list of n rows of m numbers, h(x) a
number, grad_h(x) a list of n numbers and alpha a function of one number.
The control returns a list of m numbers, or INFEASIBLE.
"""
def control(t, x):
dh = grad_h(x)
G = g(x)
m = len(G[0])
a = [sum(dh[i] * G[i][j] for i in range(len(dh))) for j in range(m)]
b = _dot(dh, f(x)) + alpha(h(x))
return cbf_qp(list(u_nom(t, x)), a, b, lo, hi)[0]
return control
ctlsim.py 120 lines
# SPDX-License-Identifier: MIT
# Shared helper of the control pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Fixed step simulation for the control pages.
Conventions:
- A continuous-time system is a function f(t, x, u) that returns x' as a
flat list. x is a flat list. u is whatever the control returns (a flat
list, a scalar, or None when there is no control).
- A discrete-time system is a function F(k, x, u) that returns x_(k+1).
- The integrator is the classical 4th order Runge-Kutta method with a fixed
step dt. The input is held constant over each step.
- Time t_k = t0 + k dt is computed by multiplication, not by summation.
- The number of steps round((t1 - t0) / dt) and the hold ratio
round(hold / dt) must match the real ratios within 1e-9 (relative), or
ValueError is raised.
This file holds no controller or observer of a control page.
"""
__all__ = ["rk4_step", "simulate", "simulate_discrete", "lti"]
def _axpy(a, x, y):
return [yi + a * xi for xi, yi in zip(x, y)]
def rk4_step(f, t, x, u, dt):
"""Return x(t + dt) after one RK4 step of x' = f(t, x, u), u held constant."""
k1 = f(t, x, u)
k2 = f(t + dt / 2, _axpy(dt / 2, k1, x), u)
k3 = f(t + dt / 2, _axpy(dt / 2, k2, x), u)
k4 = f(t + dt, _axpy(dt, k3, x), u)
return [xi + dt / 6 * (a + 2 * b + 2 * c + d) for xi, a, b, c, d in zip(x, k1, k2, k3, k4)]
def _ratio(num, den, what):
r = round(num / den)
if abs(r * den - num) > 1e-9 * max(abs(num), abs(den)):
raise ValueError(what + " is not an integer multiple of dt")
return r
def simulate(f, x0, t0, t1, dt, control=None, hold=None):
"""Simulate x' = f(t, x, u) from x(t0) = x0 to t1 with RK4 and step dt.
control(t, x) gives the input. It is called at each sampling instant
t0 + j hold, and its value is held (zero-order hold) until the next
instant. hold must be an integer multiple of dt; hold = None means
hold = dt. With control = None the input is None.
Returns (ts, xs, us): ts has N + 1 times, xs the N + 1 states, and us the
N inputs, where us[k] acts on [ts[k], ts[k + 1]].
"""
if dt <= 0:
raise ValueError("dt must be positive")
n_steps = _ratio(t1 - t0, dt, "t1 - t0")
if n_steps < 0:
raise ValueError("t1 is before t0")
r = 1 if hold is None else _ratio(hold, dt, "hold")
if r < 1:
raise ValueError("hold must be at least dt")
x = list(x0)
ts = [t0]
xs = [list(x)]
us = []
u = None
for k in range(n_steps):
t = t0 + k * dt
if control is not None and k % r == 0:
u = control(t, list(x))
x = rk4_step(f, t, x, u, dt)
ts.append(t0 + (k + 1) * dt)
xs.append(x)
us.append(u)
return ts, xs, us
def simulate_discrete(F, x0, N, control=None):
"""Run x_(k+1) = F(k, x_k, u_k) for k = 0, ..., N - 1.
u_k = control(k, x_k), or None if control is None. Returns (xs, us) with
N + 1 states and N inputs. Exact if F and control are exact.
"""
x = list(x0)
xs = [list(x)]
us = []
for k in range(N):
u = control(k, list(x)) if control is not None else None
x = list(F(k, x, u))
xs.append(x)
us.append(u)
return xs, us
def lti(A, B=None):
"""Return f(t, x, u) = A x + B u for the system x' = A x + B u.
u may be a flat list, a scalar (one input) or None (zero input). B may
be None for a system with no input.
"""
def f(t, x, u):
dx = [sum(a * xi for a, xi in zip(row, x)) for row in A]
if B is None or u is None:
return dx
uu = u if isinstance(u, (list, tuple)) else [u]
return [d + sum(b * ui for b, ui in zip(row, uu)) for d, row in zip(dx, B)]
return f
def _self_test():
import math
f = lti([[-1.0]])
_, xs, _ = simulate(f, [1.0], 0.0, 1.0, 0.01)
assert abs(xs[-1][0] - math.exp(-1.0)) < 1e-9
return True
if __name__ == "__main__":
_self_test()
test_cbf_safety_filter.py 169 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/cbf-safety-filter/. The authors are listed in prov/3VWCBR.jsonl.
"""Tests for cbf_safety_filter.py. Standard library only, fixed seeds."""
import itertools
import math
import random
import unittest
from fractions import Fraction as Fr
from cbf_safety_filter import INFEASIBLE, cbf_filter, cbf_qp, clip
from ctlsim import simulate
def dot(a, b):
return sum((x * y for x, y in zip(a, b)), 0)
def brute_force(u_nom, a, b, lo, hi):
"""Solve the QP by trying every active set. Exact with Fractions.
Each coordinate is at its lower bound, at its upper bound or free, and
the barrier constraint is active or not. For each choice the stationary
point is unique; the answer is the feasible one with the least cost.
"""
m = len(u_nom)
best = None
states = []
for j in range(m):
s = ["free"]
if lo[j] is not None:
s.append("lo")
if hi[j] is not None:
s.append("hi")
states.append(s)
for choice in itertools.product(*states):
fixed = {}
for j, s in enumerate(choice):
if s == "lo":
fixed[j] = lo[j]
elif s == "hi":
fixed[j] = hi[j]
free = [j for j in range(m) if j not in fixed]
cands = []
u = [fixed.get(j, u_nom[j]) for j in range(m)]
cands.append(u)
nf = sum((a[j] * a[j] for j in free), 0)
if nf != 0:
lam = -(dot(a, u) + b) / Fr(nf)
cands.append([u[j] + lam * a[j] if j in free else u[j] for j in range(m)])
for u in cands:
ok = dot(a, u) + b >= 0 and all(
(lo[j] is None or u[j] >= lo[j]) and (hi[j] is None or u[j] <= hi[j])
for j in range(m))
if ok:
cost = sum(((x - y) ** 2 for x, y in zip(u, u_nom)), 0)
if best is None or cost < best[0]:
best = (cost, u)
return None if best is None else best[1]
def random_instance(rng, m):
def r():
return Fr(rng.randint(-8, 8), rng.randint(1, 3))
u_nom = [r() for _ in range(m)]
a = [r() if rng.random() < 0.85 else Fr(0) for _ in range(m)]
b = r()
lo, hi = [], []
for _ in range(m):
x, y = sorted([r(), r()])
lo.append(x if rng.random() < 0.7 else None)
hi.append(y if rng.random() < 0.7 else None)
return u_nom, a, b, lo, hi
class TestQP(unittest.TestCase):
def test_against_brute_force(self):
rng = random.Random(3)
n_inf = n_act = 0
for m in (1, 2, 3, 4):
for _ in range(150):
u_nom, a, b, lo, hi = random_instance(rng, m)
u, lam = cbf_qp(u_nom, a, b, lo, hi)
ref = brute_force(u_nom, a, b, lo, hi)
self.assertEqual(u, ref)
if u is INFEASIBLE:
n_inf += 1
continue
# KKT: lam >= 0, u = clip(u_nom + lam a), complementary slackness.
self.assertGreaterEqual(lam, 0)
self.assertEqual(u, clip([x + lam * y for x, y in zip(u_nom, a)], lo, hi))
self.assertEqual(lam * (dot(a, u) + b), 0)
if lam > 0:
n_act += 1
self.assertGreater(n_inf, 10)
self.assertGreater(n_act, 100)
def test_no_box_closed_form(self):
rng = random.Random(4)
for _ in range(50):
m = rng.randint(1, 4)
u_nom = [Fr(rng.randint(-9, 9), 2) for _ in range(m)]
a = [Fr(rng.randint(1, 9), rng.randint(1, 3)) * rng.choice((-1, 1)) for _ in range(m)]
b = Fr(rng.randint(-20, 20), 3)
u, _ = cbf_qp(u_nom, a, b)
psi = dot(a, u_nom) + b
want = list(u_nom) if psi >= 0 else [x - psi * y / dot(a, a) for x, y in zip(u_nom, a)]
self.assertEqual(u, want)
def test_integer_inputs_stay_exact(self):
u, lam = cbf_qp([1, 1], [-1, -2], 0)
# psi(0) = -3 and |a|^2 = 5, so lam = 3/5 and u = (1, 1) + lam a.
self.assertEqual(u, [Fr(2, 5), Fr(-1, 5)])
self.assertEqual(lam, Fr(3, 5))
self.assertIsInstance(u[0], Fr)
def test_infeasible_example(self):
# x' = x + u, |u| <= 1, h = 2 - x, alpha(h) = h: a = -1, b = 2 - 2x.
def solve(x):
return cbf_qp([Fr(0)], [Fr(-1)], 2 - 2 * x, [Fr(-1)], [Fr(1)])[0]
self.assertEqual(solve(Fr(3, 2)), [-1])
self.assertIs(solve(Fr(8, 5)), INFEASIBLE)
self.assertEqual(solve(Fr(1)), [0])
class TestClosedLoop(unittest.TestCase):
def test_one_dimension(self):
# x' = u, h = 1 - x, alpha(h) = h, u_nom = 1: the filter gives
# u = 1 - x, so x(t) = 1 - e^(-t). RK4, dt = 0.01.
ctl = cbf_filter(lambda x: [0.0], lambda x: [[1.0]], lambda x: 1 - x[0],
lambda x: [-1.0], lambda s: s, lambda t, x: [1.0])
ts, xs, _ = simulate(lambda t, x, u: ctl(t, x), [0.0], 0.0, 5.0, 0.01)
err = max(abs(x[0] - (1 - math.exp(-t))) for t, x in zip(ts, xs))
self.assertLess(err, 1e-8)
def test_obstacle(self):
# Single integrator in the plane, disk of radius 1 at (2, 0),
# h = |x - (2, 0)|^2 - 1, alpha(h) = h, u_nom = (4, 0) - x.
h = lambda x: (x[0] - 2) ** 2 + x[1] ** 2 - 1 # noqa: E731
ctl = cbf_filter(lambda x: [0.0, 0.0], lambda x: [[1.0, 0.0], [0.0, 1.0]], h,
lambda x: [2 * (x[0] - 2), 2 * x[1]], lambda s: s,
lambda t, x: [4 - x[0], -x[1]])
ts, xs, _ = simulate(lambda t, x, u: ctl(t, x), [0.0, 0.2], 0.0, 12.0, 0.01)
hs = [h(x) for x in xs]
self.assertGreater(min(hs), 0.25)
self.assertLess(min(hs), 0.2501)
self.assertLess(math.hypot(xs[-1][0] - 4, xs[-1][1]), 1e-3)
k = round(2.0 / 0.01)
self.assertAlmostEqual(xs[k][0], 1.68245, places=4)
self.assertAlmostEqual(xs[k][1], 1.14481, places=4)
def test_sampled_data_violation(self):
# With the input held for 0.15 and alpha(h) = 10 h, near the boundary
# 1 - x_(k+1) = -0.5 (1 - x_k), so h changes sign (the pitfall).
def run(gamma, hold):
ctl = cbf_filter(lambda x: [0.0], lambda x: [[1.0]], lambda x: 1 - x[0],
lambda x: [-1.0], lambda s: gamma * s, lambda t, x: [1.0])
self.assertEqual(round(hold / 0.01) * 0.01, hold)
_, xs, _ = simulate(lambda t, x, u: [u[0]], [0.0], 0.0, 3.0, 0.01,
control=ctl, hold=hold)
return min(1 - x[0] for x in xs)
self.assertAlmostEqual(run(10.0, 0.15), -0.05, places=9)
self.assertGreaterEqual(run(10.0, 0.05), 0.0)
self.assertGreater(run(1.0, 0.15), 0.0)
if __name__ == "__main__":
unittest.main()
History
Barrier functions for control systems with inputs appear in Wieland and Allgöwer (2007), who called them control barrier functions and gave a universal formula for a safe feedback. Ames, Grizzle and Tabuada (2014) put a barrier condition and a control Lyapunov function condition into one quadratic program, for adaptive cruise control. Ames, Xu, Grizzle and Tabuada (2017) gave the theory, with reciprocal and zeroing control barrier functions, forward invariance and conditions for a Lipschitz solution. The survey of Ames and others (2019) collected the extensions to high relative degree, several constraints and applications in robotics.
References
- Aaron D. Ames, Xiangru Xu, Jessy W. Grizzle and Paulo Tabuada, Control barrier function based quadratic programs for safety critical systems, IEEE Transactions on Automatic Control 62(8), 3861-3876, 2017, zeroing control barrier functions, forward invariance of the safe set, and the quadratic program that combines CBF and CLF constraints
- Aaron D. Ames, Samuel Coogan, Magnus Egerstedt, Gennaro Notomista, Koushil Sreenath and Paulo Tabuada, Control barrier functions: theory and applications, European Control Conference, 3420-3431, 2019, survey of CBF based quadratic programs, with the explicit solution for one constraint and no input limits
- Control barrier function based quadratic programs with application to adaptive cruise control, the first CBF based quadratic program
- Constructive safety using control barrier functions, control barrier functions and a universal formula for safe feedback
- Hassan K. Khalil, Nonlinear Systems, third edition, Prentice Hall, 2002, Section 3.4, the comparison principle (Lemma 3.4)
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 3VWCBR Edit this page History Report an error Markdown