Algorithm Search⌘K

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
Properties
deterministicexactonlineiterative
Origin
Aaron D. Ames, Jessy W. Grizzle, Paulo Tabuada, Xiangru Xu, 2014

The control barrier function quadratic program (CBF-QP) takes the input unomu_{\text{nom}} that a nominal controller wants and returns the closest input that satisfies the condition of a control barrier function hh. For x˙=f(x)+g(x)u\dot x = f(x) + g(x) u and the safe set C={x:h(x)≥0}C = \{x : h(x) \ge 0\}, the condition is Lfh(x)+Lgh(x) u+α(h(x))≥0L_f h(x) + L_g h(x)\, u + \alpha(h(x)) \ge 0, which is linear in uu. 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 CC. The nominal controller handles the task and the filter only acts near the boundary of CC. 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 xx: the nominal input unom∈Rmu_{\text{nom}} \in \mathbb{R}^m, the row a=Lgh(x)=∇h(x)Tg(x)a = L_g h(x) = \nabla h(x)^T g(x), the number b=Lfh(x)+α(h(x))b = L_f h(x) + \alpha(h(x)) with Lfh=∇hTfL_f h = \nabla h^T f, and optional limits ℓj≤uj≤rj\ell_j \le u_j \le r_j (each bound may be absent). Here hh is continuously differentiable and α\alpha is an extended class K function: continuous, strictly increasing, with α(0)=0\alpha(0) = 0; the common choice is α(s)=γs\alpha(s) = \gamma s with γ>0\gamma > 0.

Output. The solution of

min⁡u ∣u−unom∣2subject toa⋅u+b≥0,ℓ≤u≤r,\min_u \ |u - u_{\text{nom}}|^2 \quad \text{subject to} \quad a \cdot u + b \ge 0, \quad \ell \le u \le r,

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, u=k(x)u = k(x) makes h˙≥−α(h)\dot h \ge -\alpha(h) along the closed loop. With ff, gg locally Lipschitz (see the Lipschitz condition) and a locally Lipschitz kk, the solutions are unique by the Picard-Lindelöf theorem, and the comparison lemma gives h(x(t))≥0h(x(t)) \ge 0 for all t≥0t \ge 0 when h(x(0))≥0h(x(0)) \ge 0. So CC is forward invariant (a positively invariant set of the closed loop).

The algorithm

  1. CBF-QP(u_nom, a, b, ℓ, r)
  2. 1u ← clip(u_nom)
  3. 2if a·u + b ≥ 0 then return u
  4. 3if Σ_j max_{ℓ_j ≤ v ≤ r_j} a_j v + b < 0 then return INFEASIBLE
  5. 4Λ ← sorted values λ > 0 with u_nom,j + λ a_j ∈ {ℓ_j, r_j}
  6. 5binary search Λ for the piece [λ_-, λ_+] where ψ(λ_-) < 0 ≤ ψ(λ_+), ψ(λ) = a·clip(u_nom + λa) + b; λ ← root of ψ on that piece
  7. 6return 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 λ≥0\lambda \ge 0, the Lagrangian ∣u−unom∣2/2−λ(a⋅u+b)|u - u_{\text{nom}}|^2 / 2 - \lambda (a \cdot u + b) is separable, and its minimizer over the box is clip⁡(unom+λa)\operatorname{clip}(u_{\text{nom}} + \lambda a). The function ψ\psi is continuous, nondecreasing and linear between the points of line L4, where a coordinate reaches a bound. Line L5 finds the multiplier with ψ(λ)=0\psi(\lambda) = 0, 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:

u=unom+max⁡(0,−(a⋅unom+b))∣a∣2 aT(a≠0).u = u_{\text{nom}} + \frac{\max\bigl(0, -(a \cdot u_{\text{nom}} + b)\bigr)}{|a|^2}\, a^T \qquad (a \neq 0).

The filter adds the smallest multiple of a=Lgha = L_g h, the direction that increases hh fastest per unit of input.

Example

A point robot in the plane has x˙=u\dot x = u with x,u∈R2x, u \in \mathbb{R}^2. A round obstacle of radius 1 sits at (2,0)(2, 0), so h(x)=(x1−2)2+x22−1h(x) = (x_1 - 2)^2 + x_2^2 - 1. Use α(s)=s\alpha(s) = s and the nominal controller unom=(4,0)−xu_{\text{nom}} = (4, 0) - x, which drives the robot in a straight line to the goal (4,0)(4, 0) through the obstacle. Here f=0f = 0 and g=Ig = I, so a=∇h(x)T=(2(x1−2),2x2)a = \nabla h(x)^T = (2(x_1 - 2), 2 x_2) and b=h(x)b = h(x).

At x(0)=(0,0.2)x(0) = (0, 0.2): h=4+0.04−1=3.04h = 4 + 0.04 - 1 = 3.04, a=(−4,0.4)a = (-4, 0.4), unom=(4,−0.2)u_{\text{nom}} = (4, -0.2), and a⋅unom+b=−16−0.08+3.04=−13.04<0a \cdot u_{\text{nom}} + b = -16 - 0.08 + 3.04 = -13.04 < 0, so the filter acts. With no limits, ∣a∣2=16.16|a|^2 = 16.16, λ=13.04/16.16=0.80693\lambda = 13.04 / 16.16 = 0.80693 and u=(4,−0.2)+0.80693 (−4,0.4)=(0.77228,0.12277)u = (4, -0.2) + 0.80693\, (-4, 0.4) = (0.77228, 0.12277). Check: a⋅u+b=−3.08911+0.04911+3.04=0a \cdot u + b = -3.08911 + 0.04911 + 3.04 = 0, so the constraint is active.

A 4th order Runge-Kutta simulation with step 0.010.01 and the filter evaluated inside the right side gives:

tt x1x_1 x2x_2 hh u1u_1 u2u_2 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 hh is 0.250030.25003, at t=2.52t = 2.52, and the filter changes the input for the last time at t=2.47t = 2.47 (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 λ≥0\lambda \ge 0, clip⁡(unom+λa)\operatorname{clip}(u_{\text{nom}} + \lambda a) minimizes the Lagrangian over the box, because the Lagrangian is a sum of one-dimensional quadratics.
  • Shape of psi. Each term ajclip⁡j(unom,j+λaj)a_j \operatorname{clip}_j(u_{\text{nom}, j} + \lambda a_j) is nondecreasing in λ\lambda, whatever the sign of aja_j, 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 λ≥0\lambda \ge 0, u(λ)u(\lambda) is feasible and λψ(λ)=0\lambda \psi(\lambda) = 0, then for every feasible vv, 12∣v−unom∣2≥L(v,λ)≥L(u(λ),λ)=12∣u(λ)−unom∣2\frac12 |v - u_{\text{nom}}|^2 \ge L(v, \lambda) \ge L(u(\lambda), \lambda) = \frac12 |u(\lambda) - u_{\text{nom}}|^2. Strict convexity gives uniqueness.
  • Infeasibility. Line L3 computes the supremum of a⋅ua \cdot u over the box, which decides feasibility. If the supremum is infinite, the last piece of ψ\psi has a positive slope, so a root exists.
  • Safety. Along the closed loop, h˙=a⋅k(x)+b−α(h)≥−α(h)\dot h = a \cdot k(x) + b - \alpha(h) \ge -\alpha(h). By the comparison lemma (Khalil 2002, Section 3.4), h(x(t))h(x(t)) stays above the solution of y˙=−α(y)\dot y = -\alpha(y), y(0)=h(x(0))≥0y(0) = h(x(0)) \ge 0, which never becomes negative. For α(s)=γs\alpha(s) = \gamma s, ddt(eγth)≥0\frac{d}{dt}(e^{\gamma t} h) \ge 0 gives h(x(t))≥e−γth(x(0))h(x(t)) \ge e^{-\gamma t} h(x(0)).

The tests compare the algorithm in exact Fraction arithmetic with a brute force solver that tries every active set, on 600 random instances with m=1m = 1 to 44, random boxes with missing bounds and some aj=0a_j = 0, 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 x˙=u\dot x = u, h=1−xh = 1 - x, unom=1u_{\text{nom}} = 1 against x(t)=1−e−tx(t) = 1 - e^{-t} within 10−810^{-8}, the obstacle run above (h≥0.25h \ge 0.25 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

min⁡u∈B 12∣u−unom∣2subject toa⋅u+b≥0,\min_{u \in B} \ \tfrac12 |u - u_{\text{nom}}|^2 \quad \text{subject to} \quad a \cdot u + b \ge 0,

where a∈Rma \in \mathbb{R}^m, b∈Rb \in \mathbb{R}, and B=∏j[ℓj,rj]B = \prod_j [\ell_j, r_j] is a box in which a bound may be absent (ℓj=−∞\ell_j = -\infty or rj=+∞r_j = +\infty), with ℓj≤rj\ell_j \le r_j. The factor 12\frac12 does not change the minimizer. Write clip⁡\operatorname{clip} for the projection onto BB, which clamps each coordinate to [ℓj,rj][\ell_j, r_j]. For λ≥0\lambda \ge 0 put

u(λ)=clip⁡(unom+λa),ψ(λ)=a⋅u(λ)+b.u(\lambda) = \operatorname{clip}(u_{\text{nom}} + \lambda a), \qquad \psi(\lambda) = a \cdot u(\lambda) + b.

Termination

Lines L1 to L3 and L6 are loops over the mm coordinates. Line L4 makes at most 2m2m breakpoints. The binary search of line L5 halves the interval [lo,hi)[lo, hi) of indices at each step, so it ends after at most ⌈log⁡2(2m+1)⌉\lceil \log_2(2m + 1) \rceil steps. So the algorithm ends.

Lemma 1: the inner minimization

For each λ≥0\lambda \ge 0, u(λ)u(\lambda) minimizes L(u,λ)=12∣u−unom∣2−λ(a⋅u+b)L(u, \lambda) = \frac12 |u - u_{\text{nom}}|^2 - \lambda (a \cdot u + b) over BB.

Proof. L(u,λ)=∑j(12(uj−unom,j)2−λajuj)−λb=∑j12(uj−(unom,j+λaj))2+constL(u, \lambda) = \sum_j \bigl(\frac12 (u_j - u_{\text{nom}, j})^2 - \lambda a_j u_j\bigr) - \lambda b = \sum_j \frac12 \bigl(u_j - (u_{\text{nom}, j} + \lambda a_j)\bigr)^2 + \text{const}, where the constant does not depend on uu. The sum is separable, and the minimizer of 12(uj−c)2\frac12 (u_j - c)^2 over an interval is cc clamped to the interval. □\square

Lemma 2: the shape of psi

ψ\psi is continuous and nondecreasing on [0,∞)[0, \infty). It is linear between consecutive points of Λ={λ>0:λ=(ℓj−unom,j)/aj or λ=(rj−unom,j)/aj, aj≠0}\Lambda = \{ \lambda > 0 : \lambda = (\ell_j - u_{\text{nom}, j}) / a_j \text{ or } \lambda = (r_j - u_{\text{nom}, j}) / a_j, \ a_j \neq 0 \}, the set of line L4. After the largest point of Λ\Lambda (after 0 if Λ\Lambda is empty), its slope is s=∑{aj2:aj>0,rj=∞ or aj<0,ℓj=−∞}s = \sum \{ a_j^2 : a_j > 0, r_j = \infty \text{ or } a_j < 0, \ell_j = -\infty \}.

Proof. ψ(λ)−b=∑jaj clamp⁡j(unom,j+λaj)\psi(\lambda) - b = \sum_j a_j\, \operatorname{clamp}_j(u_{\text{nom}, j} + \lambda a_j). Terms with aj=0a_j = 0 are zero. If aj>0a_j > 0, the argument increases with λ\lambda, the clamp is continuous and nondecreasing, and the term is aja_j times it, so it is nondecreasing. If aj<0a_j < 0, the argument decreases, the clamp of it is nonincreasing, and the factor aj<0a_j < 0 makes the term nondecreasing. The clamp is linear (slope 1 or 0) between the values of λ\lambda where the argument crosses ℓj\ell_j or rjr_j, and these values are in Λ\Lambda when they are positive. So each term is linear between points of Λ\Lambda, with slope aj2a_j^2 when the coordinate is strictly inside its interval and 0 when it is clamped. After the last point of Λ\Lambda, a coordinate with aj>0a_j > 0 has passed every finite bound that it can cross. If rjr_j is finite it is clamped at rjr_j; otherwise it is free. The case aj<0a_j < 0 is the same with ℓj\ell_j. This gives ss. □\square

Lemma 3: the feasibility test

The problem is feasible if and only if M+b≥0M + b \ge 0, where M=sup⁡u∈Ba⋅u=∑jsup⁡uj∈[ℓj,rj]ajujM = \sup_{u \in B} a \cdot u = \sum_j \sup_{u_j \in [\ell_j, r_j]} a_j u_j. M=∞M = \infty if and only if some aj>0a_j > 0 has rj=∞r_j = \infty or some aj<0a_j < 0 has ℓj=−∞\ell_j = -\infty; otherwise M=∑aj>0ajrj+∑aj<0ajℓjM = \sum_{a_j > 0} a_j r_j + \sum_{a_j < 0} a_j \ell_j, 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 MM is finite it is attained at the point described, so a feasible point exists if and only if M+b≥0M + b \ge 0. If M=∞M = \infty, some point of BB has a⋅u+b≥0a \cdot u + b \ge 0. Line L3 computes exactly this test. □\square

Theorem 1: the QP step

If the problem is infeasible, the algorithm returns INFEASIBLE. Otherwise it returns the unique minimizer u∗u^* and a multiplier λ∗≥0\lambda^* \ge 0 with u∗=u(λ∗)u^* = u(\lambda^*) and λ∗ψ(λ∗)=0\lambda^* \psi(\lambda^*) = 0.

Proof. Sufficiency of the conditions. Suppose λ≥0\lambda \ge 0, u(λ)u(\lambda) is feasible and λψ(λ)=0\lambda \psi(\lambda) = 0. For every feasible vv,

12∣v−unom∣2≥12∣v−unom∣2−λ(a⋅v+b)=L(v,λ)≥L(u(λ),λ)=12∣u(λ)−unom∣2−λψ(λ)=12∣u(λ)−unom∣2,\tfrac12 |v - u_{\text{nom}}|^2 \ge \tfrac12 |v - u_{\text{nom}}|^2 - \lambda (a \cdot v + b) = L(v, \lambda) \ge L(u(\lambda), \lambda) = \tfrac12 |u(\lambda) - u_{\text{nom}}|^2 - \lambda \psi(\lambda) = \tfrac12 |u(\lambda) - u_{\text{nom}}|^2,

using λ≥0\lambda \ge 0 and a⋅v+b≥0a \cdot v + b \ge 0, then Lemma 1. So u(λ)u(\lambda) is a minimizer. The objective is strictly convex and the feasible set is convex, so the minimizer is unique.

Line L2. If ψ(0)≥0\psi(0) \ge 0, then λ=0\lambda = 0 satisfies the conditions, and the answer is u(0)=clip⁡(unom)u(0) = \operatorname{clip}(u_{\text{nom}}).

Line L3. If the test fails, the problem is infeasible by Lemma 3, and the answer is correct. From now on ψ(0)<0\psi(0) < 0 and the problem is feasible.

Lines L4 and L5. Let λ1<⋯<λK\lambda_1 < \dots < \lambda_K be the sorted points of Λ\Lambda. By Lemma 2 the values ψ(λk)\psi(\lambda_k) are nondecreasing in kk, so the predicate ψ(λk)≥0\psi(\lambda_k) \ge 0 is false and then true, and the binary search returns the first index with a true value, or K+1K + 1 if there is none. Put λ0=0\lambda_0 = 0.

  • If the index kk is at most KK, then ψ(λk−1)<0≤ψ(λk)\psi(\lambda_{k-1}) < 0 \le \psi(\lambda_k). ψ\psi is linear on [λk−1,λk][\lambda_{k-1}, \lambda_k], so the linear interpolation of line L5 gives the root λ∗\lambda^* in this interval exactly.
  • If no point has ψ≥0\psi \ge 0, then ψ(λK)<0\psi(\lambda_K) < 0 (or ψ(0)<0\psi(0) < 0 if K=0K = 0). If MM were finite, then at λ≥λK\lambda \ge \lambda_K every coordinate with aj≠0a_j \neq 0 would sit at the bound that attains MM, so ψ(λK)=M+b≥0\psi(\lambda_K) = M + b \ge 0, a contradiction. So M=∞M = \infty, and the slope ss of Lemma 2 is positive. Then λ∗=λK+(−ψ(λK))/s\lambda^* = \lambda_K + (-\psi(\lambda_K)) / s is the root.

In both cases λ∗>0\lambda^* > 0 and ψ(λ∗)=0\psi(\lambda^*) = 0, so u(λ∗)u(\lambda^*) is feasible, and the conditions hold. Line L6 returns u(λ∗)u(\lambda^*). Every operation is a field operation, so the result is exact with rational data. □\square

Theorem 2: forward invariance of the safe set

Let x′=f(x)+g(x)ux' = f(x) + g(x) u with ff, gg locally Lipschitz on an open set DD. Let h:D→Rh : D \to \mathbb{R} be continuously differentiable, let C={x∈D:h(x)≥0}C = \{x \in D : h(x) \ge 0\} be closed in Rn\mathbb{R}^n, and let α:R→R\alpha : \mathbb{R} \to \mathbb{R} be locally Lipschitz, strictly increasing, with α(0)=0\alpha(0) = 0. Suppose that for every x∈Dx \in D the QP with a=∇h(x)Tg(x)a = \nabla h(x)^T g(x), b=∇h(x)Tf(x)+α(h(x))b = \nabla h(x)^T f(x) + \alpha(h(x)) and the box BB is feasible, and that its solution k(x)k(x) makes F(x)=f(x)+g(x)k(x)F(x) = f(x) + g(x) k(x) locally Lipschitz on DD. Then every solution with x(0)∈Cx(0) \in C stays in CC on its whole interval of existence.

Proof. The closed loop has unique solutions (Picard-Lindelöf). Let xx be a solution with x(0)∈Cx(0) \in C on [0,tf)[0, t_f), and let TT be the supremum of the times t<tft < t_f with x([0,t])⊂Dx([0, t]) \subset D. On [0,T)[0, T), put η(t)=h(x(t))\eta(t) = h(x(t)). By the chain rule and the constraint of the QP,

η˙=∇h(x)T(f(x)+g(x)k(x))=a⋅k(x)+b−α(η)≥−α(η).\dot\eta = \nabla h(x)^T \bigl(f(x) + g(x) k(x)\bigr) = a \cdot k(x) + b - \alpha(\eta) \ge -\alpha(\eta).

Let yy be the solution of y˙=−α(y)\dot y = -\alpha(y), y(0)=η(0)≥0y(0) = \eta(0) \ge 0. It is unique because α\alpha is locally Lipschitz. The constant 00 is a solution, so a solution with y(0)≥0y(0) \ge 0 cannot cross zero, and y(t)≥0y(t) \ge 0. By the comparison lemma (Khalil 2002, Lemma 3.4, applied to v=−ηv = -\eta, which satisfies v˙≤α(−v)\dot v \le \alpha(-v)), η(t)≥y(t)≥0\eta(t) \ge y(t) \ge 0 on [0,T)[0, T). So x(t)∈Cx(t) \in C for t<Tt < T.

If T<tfT < t_f, then x(T)∈Cx(T) \in C because CC is closed and xx is continuous, so x(T)∈Dx(T) \in D. DD is open, so xx stays in DD a little longer after TT, which contradicts the choice of TT. So T=tfT = t_f, and x(t)∈Cx(t) \in C for all t∈[0,tf)t \in [0, t_f).

For α(s)=γs\alpha(s) = \gamma s the comparison is explicit: ddt(eγtη)=eγt(η˙+γη)≥0\frac{d}{dt}(e^{\gamma t} \eta) = e^{\gamma t} (\dot\eta + \gamma \eta) \ge 0, so η(t)≥e−γtη(0)≥0\eta(t) \ge e^{-\gamma t} \eta(0) \ge 0. □\square

Remark: when the closed loop is Lipschitz

Without the box, Theorem 1 gives the closed form k(x)=unom+max⁡(0,−ψ(0)) a/∣a∣2k(x) = u_{\text{nom}} + \max(0, -\psi(0))\, a / |a|^2. If unomu_{\text{nom}}, aa and bb are locally Lipschitz in xx and a(x)≠0a(x) \neq 0 on DD, then kk 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 k(x(tk))k(x(t_k)) between sampling times; then η˙≥−α(η)\dot\eta \ge -\alpha(\eta) holds only at the sampling instants. ■\blacksquare

Complexity

With mm inputs, lines L1 to L3 take O(m)O(m) time. Line L4 sorts at most 2m2m breakpoints in O(mlog⁡m)O(m \log m). The binary search of line L5 evaluates ψ\psi at O(log⁡m)O(\log m) points, O(m)O(m) each. In total O(mlog⁡m)O(m \log m) time and O(m)O(m) extra space. Without limits it is O(m)O(m). Forming aa and bb costs one gradient of hh and one evaluation of ff and gg, 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 clip⁡(unom)\operatorname{clip}(u_{\text{nom}}) satisfies the condition, the filter returns it unchanged. Far from the boundary of CC 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 hh may fall.
  • Unique. The solution is unique when the program is feasible.
  • Lipschitz in the simple case. Without limits and with Lgh≠0L_g h \neq 0, the closed form is locally Lipschitz when unomu_{\text{nom}}, ff, gg and ∇h\nabla h 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 V˙≤−cV+δ\dot V \le -c V + \delta with a penalized slack δ\delta, 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 Lgh=0L_g h = 0, the input does not appear in h˙\dot h. Exponential or high order CBFs put the condition on a higher derivative of hh (see the control barrier function page).
  • Sampled data and robustness. Margins added to bb, or conditions that bound hh 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 hh 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 x˙=u\dot x = u, h=1−xh = 1 - x, unom=1u_{\text{nom}} = 1 and α(s)=γs\alpha(s) = \gamma s, holding the input for time TT gives 1−xk+1=(1−γT)(1−xk)1 - x_{k+1} = (1 - \gamma T)(1 - x_k) near the boundary (a calculation for this example). With γ=10\gamma = 10 and T=0.15T = 0.15 the factor is −0.5-0.5, and the simulation reaches h=−0.05h = -0.05, an unsafe state (measurement). With T=0.05T = 0.05, or with γ=1\gamma = 1 and T=0.15T = 0.15, hh stays nonnegative (measurement). Here γT<1\gamma T < 1 is the condition; in general, add a margin.
  • Infeasible program at line L3. For x˙=x+u\dot x = x + u with ∣u∣≤1|u| \le 1, h=2−xh = 2 - x and α(s)=s\alpha(s) = s, the condition is −u+2−2x≥0-u + 2 - 2x \ge 0, which some ∣u∣≤1|u| \le 1 satisfies only when x≤1.5x \le 1.5. For 1.5<x≤21.5 < x \le 2 the state is safe but no allowed input keeps the condition, so hh is not a control barrier function with these limits. Choose hh so that the condition is feasible with the real limits, for example h=0.5−xh = 0.5 - x here.
  • Undesired equilibria at line L6. When unomu_{\text{nom}} points straight into the obstacle, the filter can cancel it exactly. In the example, from x(0)=(0,0)x(0) = (0, 0) the robot moves along the axis and stops in front of the obstacle: at t=12t = 12 it is at (0.99999,0)(0.99999, 0) with h=0.00002h = 0.00002 (measurement). The filter keeps safety but not the task.
  • The choice of alpha at line L2. A large γ\gamma lets the state come close to the boundary, and a small γ\gamma makes the filter act early. In the example, γ=0.2\gamma = 0.2, 11 and 55 give smallest values of hh of about 1.4951.495, 0.2500.250 and 0.00020.0002, and arrival within 0.10.1 of the goal at t=6.11t = 6.11, 5.335.33 and 4.794.79 (measurements).
  • Zero gradient at line L5. If Lgh(x)=0L_g h(x) = 0, the input does not affect h˙\dot h, and the program is feasible only if b≥0b \ge 0. A position limit on a system with force input has this problem. Use a high order barrier.
  • Floating point at line L2. With floats, a⋅u+ba \cdot u + b can be −10−16-10^{-16} 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.

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

  1. 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
  2. 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
  3. Control barrier function based quadratic programs with application to adaptive cruise control, the first CBF based quadratic program
  4. Constructive safety using control barrier functions, control barrier functions and a universal formula for safe feedback
  5. 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.

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