Algorithm Search⌘K

Algorithmadvanced

Reference governor

Also called command governor.

An add-on that changes the reference of a closed loop with a Schur state matrix as little as needed so that constraints on the future response are never violated.

Time
O(N (n + m)) worst
Space
O(N (n + m)) extra
Where
N = the number of rows of the admissible set, at most q (t + 1) + q for q rows of the constraint and the index t at which the offline loop stops; m = the number of references; n = the number of states
Properties
deterministicexactonlineiterative
Origin
Elmer G. Gilbert, Ilya Kolmanovsky, Kok Tin Tan, 1995

A reference governor is an add-on to a control loop that already works well when no limit is active. It sits between the user and the loop and passes on a modified reference vkv_k instead of the requested reference rkr_k. At each step it moves vkv_k from its last value toward rkr_k by the largest fraction κk∈[0,1]\kappa_k \in [0, 1] for which the future response, with vv held constant from now on, meets all constraints. The test uses a set of states and references computed offline by linear programs. The governor keeps the constraints for all time, and it reaches a constant reference that is strictly admissible in finitely many steps. The online work is one ratio per row of that set.

In plain words

A good controller can still overshoot. If the operator asks for a big change at once, a valve can hit its limit or a temperature can go too high. The reference governor watches each request and asks one question: if I pass this request on and keep it fixed, will every future value stay within the limits? If yes, it passes the request on. If no, it passes on only part of the change, as much as is safe. The answer to the question comes from a list of simple linear checks prepared ahead of time. As the loop settles, more of the change becomes safe, and the full request goes through.

The problem

Input: a discrete-time closed loop xk+1=Axk+Bvkx_{k+1} = A x_k + B v_k, yk=Cxk+Dvky_k = C x_k + D v_k with AA Schur, a constraint Hyk≤hH y_k \le h with h>0h > 0 that describes a bounded set, a margin ε∈(0,1)\varepsilon \in (0, 1), an initial pair (x0,v−1)(x_0, v_{-1}), and a reference sequence r0,r1,…r_0, r_1, \dots. The steady state gain is G0=C(I−A)−1B+DG_0 = C (I - A)^{-1} B + D. Assume that (C,A)(C, A) is observable and G0G_0 has full column rank.

Output: a sequence vk=vk−1+κk(rk−vk−1)v_k = v_{k-1} + \kappa_k (r_k - v_{k-1}) with κk∈[0,1]\kappa_k \in [0, 1] as large as possible, such that Hyk≤hH y_k \le h for all kk.

The admissible set. With vv held constant from the state xx, the output at time tt is yt(x,v)=CAtx+(CStB+D)vy_t(x, v) = C A^t x + (C S_t B + D) v, with St=I+A+⋯+At−1S_t = I + A + \dots + A^{t-1}. Let

O={(x,v):Hyt(x,v)≤h for all t≥0, HG0v≤(1−ε)h}.O = \{(x, v) : H y_t(x, v) \le h \text{ for all } t \ge 0, \ H G_0 v \le (1 - \varepsilon) h\}.

Without the margin, the set is in general not finitely determined, because the pair (x,v)(x, v) has the dynamics diag(A,I)\mathrm{diag}(A, I) with eigenvalues 1. The margin ε\varepsilon costs a little of the steady state range and makes OO a polyhedron with finitely many rows (maximal positively invariant set).

The algorithm

  1. REFERENCE-GOVERNOR(A, B, C, D, H, h, ε, x₀, v₋₁, r₀, r₁, ...)
  2. 1O ← {(x, v) : H G₀ v ≤ (1 - ε) h}, G₀ = C (I - A)⁻¹ B + D ▷ steady state rows
  3. 2for t = 0, 1, 2, ... do ▷ offline part
  4. 3R_t ← rows of H (C Aᵗ x + (C Sₜ B + D) v) ≤ h
  5. 4if every row of R_t is redundant in O (one LP per row) then stop
  6. 5O ← O ∩ R_t
  7. 6for k = 0, 1, 2, ... do ▷ online part
  8. 7κ ← largest value in [0, 1] with (x_k, v_{k-1} + κ (r_k - v_{k-1})) ∈ O
  9. 8v_k ← v_{k-1} + κ (r_k - v_{k-1}); apply v_k; x_{k+1} ← A x_k + B v_k

Lines L1 to L5 build OO once, as in the algorithm of Gilbert and Tan (1991). Line L4 checks a row aTz≤ba^T z \le b by solving max⁡{aTz:z∈O}\max\{a^T z : z \in O\}; the row is redundant when the maximum is at most bb. The code solves each LP by the simplex method on its dual, with Bland's rule. When all rows of one time step are redundant, the rows of all later steps are redundant too, so the loop stops.

Line L7 is cheap. Each row axTx+avTv≤ba_x^T x + a_v^T v \le b becomes κα≤β\kappa \alpha \le \beta with α=avT(rk−vk−1)\alpha = a_v^T (r_k - v_{k-1}) and β=b−axTxk−avTvk−1\beta = b - a_x^T x_k - a_v^T v_{k-1}. Rows with α≤0\alpha \le 0 do not limit κ\kappa, and the others give κ≤β/α\kappa \le \beta / \alpha. So κ\kappa is the minimum of 1 and these ratios. Since (xk,vk−1)(x_k, v_{k-1}) is in OO, β≥0\beta \ge 0, and κ=0\kappa = 0 is always allowed.

Example

Take the closed loop

A=[01−121],B=[01],C=[120],D=0.A = \begin{bmatrix} 0 & 1 \\ -\tfrac12 & 1 \end{bmatrix}, \quad B = \begin{bmatrix} 0 \\ 1 \end{bmatrix}, \quad C = \begin{bmatrix} \tfrac12 & 0 \end{bmatrix}, \quad D = 0.

The eigenvalues of AA are 12±12j\tfrac12 \pm \tfrac12 j, of modulus 0.7070.707, so AA is Schur, and G0=1G_0 = 1. The response to a unit step of vv from rest is y=0,0,0.5,1,1.25,1.25,1.125,1,0.9375,…y = 0, 0, 0.5, 1, 1.25, 1.25, 1.125, 1, 0.9375, \dots, with a peak of 1.25.

Let the constraint be ∣y∣≤1.1|y| \le 1.1 and ε=0.05\varepsilon = 0.05, so the steady state rows are ∣v∣≤1.045|v| \le 1.045. In exact rational arithmetic, the offline loop adds the rows of t=0,…,6t = 0, \dots, 6 and finds all rows of t=7t = 7 redundant, so OO has 16 rows. For example, the row of t=4t = 4 is −18x1+54v≤1.1-\tfrac18 x_1 + \tfrac54 v \le 1.1, which from rest is the peak 1.25 v≤1.11.25\, v \le 1.1.

Start at rest with v−1=0v_{-1} = 0 and request r=1r = 1. The governor gives:

kk 0 1 2 3 4 5 6 7 8
κk\kappa_k 0.88 0 0 0 1 1 1 1 1
vkv_k 0.88 0.88 0.88 0.88 1 1 1 1 1
yky_k 0 0 0.44 0.88 1.1 1.1 1.05 1 0.975

At k=0k = 0 the row of t=4t = 4 limits the step to v=1.1/1.25=0.88v = 1.1 / 1.25 = 0.88. At k=4k = 4 the full reference is safe, and vv jumps to 1. The output touches the limit 1.1 at k=4k = 4 and k=5k = 5 and never passes it, and then settles at 1. Without the governor the output would reach 1.25.

If the request is r=1.2r = 1.2, which is beyond the steady state range, vv stops at 1.0451.045, the largest admissible steady state value, and the output stays within ±1.1\pm 1.1.

Correctness

The proof is in proofs/correctness.md. One step with vv held maps (x,v)(x, v) to (Ax+Bv,v)(A x + B v, v), and the output at time tt from the new state is the output at time t+1t + 1 from the old one. Hence the set OtO_t of the rows up to time tt satisfies Ot=O0∩M−1(Ot−1)O_t = O_0 \cap M^{-1}(O_{t-1}), and once Ot=Ot−1O_t = O_{t-1}, the set stays the same for all later tt. Observability and the bounded constraint make On−1O_{n-1} bounded. Since AA is Schur, yty_t approaches G0vG_0 v, which is at least εh\varepsilon h inside the limits, so all rows beyond some time are redundant, and the offline loop stops. OO is invariant when vv is held, so κ=0\kappa = 0 is always feasible and (xk,vk)∈O(x_k, v_k) \in O for all kk, which gives Hyk≤hH y_k \le h. For a constant reference rr with HG0r≤(1−ε)hH G_0 r \le (1 - \varepsilon) h, the margin gives every state near a steady state a uniform amount of room, so vkv_k reaches rr after finitely many steps.

Proof: The admissible set is finitely determined and invariant, so the governed loop meets the constraints for all time and reaches a constant admissible reference in finite timefull

Setting. The closed loop is xk+1=Axk+Bvkx_{k+1} = A x_k + B v_k, yk=Cxk+Dvky_k = C x_k + D v_k, with x∈Rnx \in \mathbb{R}^n, v∈Rmv \in \mathbb{R}^m and AA Schur. The constraint is Hy≤hH y \le h with h>0h > 0 componentwise, and Y={y:Hy≤h}Y = \{y : H y \le h\} is bounded. Fix ε∈(0,1)\varepsilon \in (0, 1). Let St=I+A+⋯+At−1S_t = I + A + \dots + A^{t-1} (S0=0S_0 = 0), let G0=C(I−A)−1B+DG_0 = C (I - A)^{-1} B + D be the steady state gain, and assume that (C,A)(C, A) is observable and G0G_0 has full column rank. If vv is held constant from the state xx, the output at time tt is

yt(x,v)=CAtx+(CStB+D)v.(1)y_t(x, v) = C A^t x + (C S_t B + D) v. \tag{1}

Write z=(x,v)z = (x, v) and Mz=(Ax+Bv,v)M z = (A x + B v, v) for one step with vv held. Then yt(Mz)=yt+1(z)y_t(M z) = y_{t+1}(z), because At(Ax+Bv)+StBv=At+1x+St+1BvA^t (A x + B v) + S_t B v = A^{t+1} x + S_{t+1} B v.

Define the sets S={z:HG0v≤(1−ε)h}\mathcal{S} = \{z : H G_0 v \le (1 - \varepsilon) h\}, Rt={z:Hyt(z)≤h}R_t = \{z : H y_t(z) \le h\}, O−1=SO_{-1} = \mathcal{S} and Ot=Ot−1∩RtO_t = O_{t-1} \cap R_t, and

O=S∩⋂t≥0Rt.O = \mathcal{S} \cap \bigcap_{t \ge 0} R_t.

Part 1: the LP

lp_max solves max⁡ cTz\max\, c^T z subject to Gz≤gG z \le g with g≥0g \ge 0. The point z=0z = 0 is feasible. By LP duality, the primal is bounded if and only if the dual min⁡ gTλ\min\, g^T \lambda subject to GTλ=cG^T \lambda = c, λ≥0\lambda \ge 0 is feasible, and then both optima are equal. Phase 1 minimizes the sum of the artificial variables; its value is 0 exactly when the dual is feasible, and the code then returns None otherwise. After the artificial variables are pivoted out of the basis (an equation whose row has no nonzero entry outside the artificial columns is a linear combination of the others and is dropped), phase 2 starts from a feasible basis. Bland's rule makes both phases end after finitely many pivots (Bland 1977). Phase 2 cannot be unbounded, since every dual feasible λ\lambda has gTλ≥cT0=0g^T \lambda \ge c^T 0 = 0 by weak duality. So the returned value is the primal maximum. With rational data and tol = 0 all operations are exact.

Part 2: the stopping test is correct

Lemma 1. For every t≥0t \ge 0, Ot=S∩R0∩M−1(Ot−1)O_t = \mathcal{S} \cap R_0 \cap M^{-1}(O_{t-1}).

Proof. z∈M−1(Rs)  ⟺  Hys(Mz)≤h  ⟺  Hys+1(z)≤h  ⟺  z∈Rs+1z \in M^{-1}(R_{s}) \iff H y_s(M z) \le h \iff H y_{s+1}(z) \le h \iff z \in R_{s+1}. Also M−1(S)=SM^{-1}(\mathcal{S}) = \mathcal{S} because MM does not change vv. So M−1(Ot−1)=S∩R1∩⋯∩RtM^{-1}(O_{t-1}) = \mathcal{S} \cap R_1 \cap \dots \cap R_t, and intersecting with S∩R0\mathcal{S} \cap R_0 gives OtO_t. □\square

Lemma 2. If Ot=Ot−1O_t = O_{t-1} for some t≥0t \ge 0, then O=Ot−1O = O_{t-1}.

Proof. By Lemma 1, Ot+1=S∩R0∩M−1(Ot)=S∩R0∩M−1(Ot−1)=OtO_{t+1} = \mathcal{S} \cap R_0 \cap M^{-1}(O_t) = \mathcal{S} \cap R_0 \cap M^{-1}(O_{t-1}) = O_t. By induction Os=Ot−1O_s = O_{t-1} for all s≥t−1s \ge t - 1, so O=⋂sOs=Ot−1O = \bigcap_s O_s = O_{t-1}. □\square

Lines L4 and L5 test whether every row of RtR_t is redundant in the current set, by one LP per row: the row aTz≤ba^T z \le b is redundant in {Gz≤g}\{G z \le g\} if and only if max⁡{aTz:Gz≤g}≤b\max\{a^T z : G z \le g\} \le b. The code adds to the set only the rows that are not redundant; this does not change the set. If all rows of RtR_t are redundant, then Ot=Ot−1O_t = O_{t-1}, and by Lemma 2 the rows found so far define OO.

Part 3: the loop stops

Lemma 3. There is a finite t∗t^* such that Ot∗−1=Ot∗O_{t^* - 1} = O_{t^*}.

Proof. First, On−1O_{n-1} is bounded. On S\mathcal{S}, HG0v≤(1−ε)hH G_0 v \le (1 - \varepsilon) h, so G0v∈YG_0 v \in Y, which is bounded, and vv is bounded because G0G_0 has full column rank. On R0∩⋯∩Rn−1R_0 \cap \dots \cap R_{n-1}, the vector Ox\mathcal{O} x, where O\mathcal{O} stacks C,CA,…,CAn−1C, C A, \dots, C A^{n-1}, equals the stacked outputs minus terms linear in vv; the outputs lie in YY and vv is bounded, and O\mathcal{O} has full column rank by observability, so xx is bounded. Let ρ\rho bound ∣x−(I−A)−1Bv∣|x - (I - A)^{-1} B v| on On−1O_{n-1}.

Next, with xs(v)=(I−A)−1Bvx_s(v) = (I - A)^{-1} B v, (1) gives yt(z)=G0v+CAt(x−xs(v))y_t(z) = G_0 v + C A^t (x - x_s(v)). Since AA is Schur, ∥CAt∥→0\|C A^t\| \to 0, so there is t1t_1 such that ∥Hi∥ ∥CAt∥ ρ≤εhi\|H_i\|\, \|C A^t\|\, \rho \le \varepsilon h_i for all rows ii and all t≥t1t \ge t_1. For z∈On−1z \in O_{n-1} and t≥t1t \ge t_1,

Hiyt(z)≤HiG0v+∥Hi∥ ∥CAt∥ ρ≤(1−ε)hi+εhi=hi.H_i y_t(z) \le H_i G_0 v + \|H_i\|\, \|C A^t\|\, \rho \le (1 - \varepsilon) h_i + \varepsilon h_i = h_i.

So every row of RtR_t is redundant in On−1⊇Ot−1O_{n-1} \supseteq O_{t-1} for t≥max⁡(n,t1)t \ge \max(n, t_1), and the loop stops at the latest at that tt. □\square

Part 4: the online step

Lemma 4. If (x,vprev)∈O(x, v_{\rm prev}) \in O, governor_step returns the largest κ∈[0,1]\kappa \in [0, 1] with (x,vprev+κ(r−vprev))∈O(x, v_{\rm prev} + \kappa (r - v_{\rm prev})) \in O.

Proof. Let d=r−vprevd = r - v_{\rm prev}. A row axTx+avTv≤ba_x^T x + a_v^T v \le b at v=vprev+κdv = v_{\rm prev} + \kappa d reads κα≤β\kappa \alpha \le \beta with α=avTd\alpha = a_v^T d and β=b−axTx−avTvprev≥0\beta = b - a_x^T x - a_v^T v_{\rm prev} \ge 0. If α≤0\alpha \le 0 the row holds for all κ≥0\kappa \ge 0. If α>0\alpha > 0 it holds exactly for κ≤β/α\kappa \le \beta/\alpha. So the set of feasible κ∈[0,1]\kappa \in [0, 1] is [0,min⁡(1,min⁡α>0β/α)][0, \min(1, \min_{\alpha > 0} \beta/\alpha)], which is what line L7 computes. □\square

Theorem. Let (x0,v−1)∈O(x_0, v_{-1}) \in O. Then for all k≥0k \ge 0:

  1. the step is defined, κk∈[0,1]\kappa_k \in [0, 1], and (xk,vk)∈O(x_k, v_k) \in O;
  2. Hyk≤hH y_k \le h;
  3. if rk=rr_k = r for all k≥k0k \ge k_0 and HG0r≤(1−ε)hH G_0 r \le (1 - \varepsilon) h, then vk=rv_k = r for all kk after some finite time.

Proof. (1) and (2). OO is invariant under MM: if z∈Oz \in O, then z∈Otz \in O_t for all tt, and by Lemma 1 Mz∈Ot−1M z \in O_{t-1} for all tt, so Mz∈OM z \in O. Suppose (xk,vk−1)∈O(x_k, v_{k-1}) \in O. By Lemma 4, κk\kappa_k exists and (xk,vk)∈O⊆R0(x_k, v_k) \in O \subseteq R_0, so Hyk=H(Cxk+Dvk)≤hH y_k = H (C x_k + D v_k) \le h. Then (xk+1,vk)=M(xk,vk)∈O(x_{k+1}, v_k) = M (x_k, v_k) \in O. Induction on kk gives (1) and (2).

(3). For k≥k0k \ge k_0 the values vkv_k lie on the segment from vk0−1v_{k_0 - 1} to rr and move toward rr: r−vk=(1−κk)(r−vk−1)r - v_k = (1 - \kappa_k)(r - v_{k-1}). So ∣r−vk∣|r - v_k| is nonincreasing and vk→vˉv_k \to \bar v for some vˉ\bar v on the segment. Suppose that vk≠rv_k \ne r for all kk. The rows of S\mathcal{S} never limit κ\kappa: they are linear in vv alone and hold at vk−1v_{k-1} and at rr, so they hold on the segment between. Since S\mathcal{S} is convex and contains vk0−1v_{k_0 - 1} and rr, it contains vˉ\bar v and every v′v' between vˉ\bar v and rr. Because vk→vˉv_k \to \bar v and AA is Schur, xk→xs(vˉ)x_k \to x_s(\bar v). For a row of RtR_t at (xk,v′)(x_k, v'),

Hiyt(xk,v′)=HiG0v′+HiCAt(xk−xs(v′))≤(1−ε)hi+c(∣xk−xs(vˉ)∣+∣v′−vˉ∣)H_i y_t(x_k, v') = H_i G_0 v' + H_i C A^t (x_k - x_s(v')) \le (1 - \varepsilon) h_i + c \left(|x_k - x_s(\bar v)| + |v' - \bar v|\right)

with c=max⁡i∥Hi∥sup⁡t∥CAt∥max⁡(1,∥(I−A)−1B∥)c = \max_i \|H_i\| \sup_t \|C A^t\| \max(1, \|(I - A)^{-1} B\|), which is finite since AA is Schur. Choose δ>0\delta > 0 with 2cδ≤εmin⁡ihi2 c \delta \le \varepsilon \min_i h_i. For kk large, ∣xk−xs(vˉ)∣≤δ|x_k - x_s(\bar v)| \le \delta and ∣vk−1−vˉ∣≤δ/2|v_{k-1} - \bar v| \le \delta / 2; then every v′v' on the segment with ∣v′−vk−1∣≤δ/2|v' - v_{k-1}| \le \delta / 2 is admissible at xkx_k, so either vk=rv_k = r or ∣vk−vk−1∣≥δ/2|v_k - v_{k-1}| \ge \delta / 2. The second case cannot happen infinitely often for a convergent sequence, so vk=rv_k = r for some kk, against the assumption. Once vk=rv_k = r, the direction is d=0d = 0 and vv stays at rr. □\square

Part 5: what the code computes

  • Line L1 forms G0G_0 by solving (I−A)X=B(I - A) X = B and adds the rows of S\mathcal{S}, which is O−1O_{-1}.
  • Lines L2 and L3 keep AtA^t and StBS_t B with the recursions At+1=AAtA^{t+1} = A A^t and St+1B=B+AStBS_{t+1} B = B + A S_t B, and form the rows of RtR_t from (1).
  • Lines L4 and L5 are the test of Part 2. The returned t∗t^* is the first tt with Ot=Ot−1O_t = O_{t-1}, so the rows of S\mathcal{S} and of R0,…,Rt∗−1R_0, \dots, R_{t^* - 1} define OO.
  • Lines L6 to L8 are the step of Lemma 4 and the plant update. With floating point data, β\beta can be slightly negative from rounding; the code then sets κ=0\kappa = 0, which keeps the old vv and is the choice that the theorem allows.

Complexity

The online step costs O(N(n+m))O(N (n + m)) for the NN rows of OO: one inner product and one ratio per row. The offline part runs t∗+1t^* + 1 rounds with qq LPs each, where qq is the number of rows of HH; each LP has n+mn + m variables and at most NN rows. The proof bounds t∗t^* by the first tt with ∥CAt∥\|C A^t\| below a constant times ε\varepsilon, which is of the order of log⁡(1/ε)/log⁡(1/ρ(A))\log(1/\varepsilon) / \log(1/\rho(A)) for the spectral radius ρ(A)\rho(A); so t∗t^* grows when ρ(A)\rho(A) is close to 1 or ε\varepsilon is small. Memory is O(N(n+m))O(N (n + m)).

Properties

  • Constraint satisfaction for all time, for every reference sequence, if the loop starts in OO, for example at rest at an admissible steady state.
  • Recursive feasibility. κ=0\kappa = 0 is always allowed, so the governor never fails.
  • Finite-time convergence to a constant reference rr with HG0r≤(1−ε)hH G_0 r \le (1 - \varepsilon) h. For a constant reference outside this range, vv stops on the boundary of the admissible range.
  • No change to the loop. If the reference is far from the limits, κ=1\kappa = 1 and the loop behaves as designed. The governor does not alter the stability or the robustness of the inner loop, since it only filters its reference.
  • Monotone in one direction. For a constant reference, vkv_k moves along a segment toward rr and never back.

Variants and improvements

  • Command governor. Choose vkv_k freely in the admissible set, closest to rkr_k in a quadratic norm, instead of on the segment. This needs a small QP per step instead of the ratio test.
  • Extended command governor. Add a few free future corrections of vv, which enlarges the admissible set at the cost of a larger QP.
  • Disturbances. With a bounded additive disturbance, tighten each row by the worst case effect of the disturbance up to time tt, as in tube MPC.
  • Nonlinear plants. Bemporad (1998) checks admissibility by simulating the nonlinear response with vv held, instead of a precomputed set.
  • Explicit form. Since κ\kappa is a minimum of ratios, the map from (x,vk−1,r)(x, v_{k-1}, r) to vkv_k is piecewise rational and can be stored, but the online ratio test is already cheap.

When to use it

Use a reference governor when a linear loop is already tuned for small signals, and the only problem is that large reference changes violate limits on the state or the input. It is much simpler than MPC: the online step has no optimization, and it leaves the inner loop unchanged, so existing controllers and certifications stay valid. Use MPC instead when the limits are active most of the time, when performance near the limits matters, or when the plant is open-loop unstable without a stabilizing inner loop. For an integrator in the loop that winds up during saturation, anti-windup is the simpler fix.

Pitfalls

  • Forgetting the margin. With ε=0\varepsilon = 0 the admissible set has infinitely many rows in general, and the offline loop does not stop.
  • Starting outside the set. The guarantees need (x0,v−1)∈O(x_0, v_{-1}) \in O. A loop that starts far from a steady state may need v−1v_{-1} chosen to match the state, or a check before switching on.
  • A slow loop. If AA has eigenvalues near the unit circle, t∗t^* and the number of rows grow large. Remove redundant rows, or use a larger ε\varepsilon.
  • Model errors. The guarantee is only for the model. Unmodeled dynamics or disturbances can push the output over the limit; add a disturbance tightening, or keep a margin in hh.
  • Rounding. With floating point, a row can be violated by a rounding error, and β\beta can come out slightly negative. Clip κ\kappa to 0 in that case, as the code does.

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.

reference_governor.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/reference-governor/. The authors are listed in prov/JN3QT7.jsonl.

"""Scalar reference governor for a discrete-time closed loop.

The closed loop is x_(k+1) = A x_k + B v_k, y_k = C x_k + D v_k, with A Schur
and the constraint H y_k <= h (h > 0). The governor replaces the reference r_k
by v_k = v_(k-1) + kappa_k (r_k - v_(k-1)) with the largest kappa_k in [0, 1]
such that (x_k, v_k) lies in the set O of states and constant inputs whose
future outputs meet the constraint and whose steady state output meets it with
the margin eps.

Matrices are lists of rows and vectors are flat lists. With int or Fraction
data and tol = 0 every step is exact rational arithmetic.
"""

__all__ = ["lp_max", "build_admissible_set", "governor_step", "run", "admissible"]


def _mul(a, b):
    return [[sum(a[i][k] * b[k][j] for k in range(len(b))) for j in range(len(b[0]))] for i in range(len(a))]


def _add(a, b):
    return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]


def _eye(n):
    return [[1 if i == j else 0 for j in range(n)] for i in range(n)]


def _solve(a, b):
    """Solve a X = b by Gaussian elimination with partial pivoting."""
    n = len(a)
    M = [list(a[i]) + list(b[i]) for i in range(n)]
    for c in range(n):
        p = max(range(c, n), key=lambda r: abs(M[r][c]))
        if M[p][c] == 0:
            raise ValueError("singular matrix")
        M[c], M[p] = M[p], M[c]
        for r in range(n):
            if r != c and M[r][c] != 0:
                f = M[r][c] / M[c][c]
                M[r] = [x - f * y for x, y in zip(M[r], M[c])]
    return [[v / M[i][i] for v in M[i][n:]] for i in range(n)]


def _pivot(T, r, c):
    p = T[r][c]
    T[r] = [v / p for v in T[r]]
    for i in range(len(T)):
        if i != r and T[i][c] != 0:
            f = T[i][c]
            T[i] = [x - f * y for x, y in zip(T[i], T[r])]


def _simplex(T, basis, cost, tol):
    """Minimize cost . lam on the tableau T, which is in canonical form for basis.

    Bland's rule (smallest index enters, smallest basic index leaves on ties)
    prevents cycling. Returns False if the objective is unbounded below.
    """
    ncol = len(T[0]) - 1
    while True:
        enter = None
        for j in range(ncol):
            if j in basis:
                continue
            rj = cost[j] - sum(cost[basis[i]] * T[i][j] for i in range(len(T)))
            if rj < -tol:
                enter = j
                break
        if enter is None:
            return True
        leave, best = None, None
        for i in range(len(T)):
            if T[i][enter] > tol:
                ratio = T[i][-1] / T[i][enter]
                if best is None or ratio < best - tol or (abs(ratio - best) <= tol and basis[i] < basis[leave]):
                    leave, best = i, ratio
        if leave is None:
            return False
        _pivot(T, leave, enter)
        basis[leave] = enter


def lp_max(c, G, g, tol=1e-10):
    """Return max c . z subject to G z <= g, z free, or None if unbounded.

    Needs g >= 0, so that z = 0 is feasible. Solves the dual LP
    min g . lam subject to G^T lam = c, lam >= 0 by the two-phase simplex method;
    by strong duality its value is the primal maximum.
    """
    d, N = len(c), len(G)
    T = []
    for i in range(d):
        row = [G[j][i] for j in range(N)] + [0] * d + [c[i]]
        if c[i] < 0:
            row = [-v for v in row]
        row[N + i] = 1
        T.append(row)
    basis = [N + i for i in range(d)]
    _simplex(T, basis, [0] * N + [1] * d, tol)  # phase 1 is bounded below by 0
    if sum(T[i][-1] for i in range(d) if basis[i] >= N) > tol * max(1, d):
        return None  # the dual is infeasible, so the primal is unbounded
    keep = []
    for i in range(d):
        if basis[i] >= N:
            j = next((j for j in range(N) if abs(T[i][j]) > tol), None)
            if j is None:
                continue  # redundant equation
            _pivot(T, i, j)
            basis[i] = j
        keep.append(i)
    T = [T[i][:N] + [T[i][-1]] for i in keep]
    basis = [basis[i] for i in keep]
    if not _simplex(T, basis, list(g), tol):
        raise ValueError("the primal LP is infeasible")
    return sum(g[basis[i]] * T[i][-1] for i in range(len(T)))


def build_admissible_set(A, B, C, D, H, h, eps, tol=1e-10, t_max=1000):
    """Return (rows, t_star): the rows (a, b) of a . (x, v) <= b that define O.

    O is the set of (x, v) with H y_t <= h for all t >= 0 when v is held
    constant from the state x, and H G0 v <= (1 - eps) h for the steady state
    gain G0 = C (I - A)^(-1) B + D. t_star is the first t whose rows were all
    redundant, so the rows of the times 0, ..., t_star - 1 define O.
    """
    n, m = len(A), len(B[0])
    if D is None:
        D = [[0] * m for _ in C]
    nH = len(H)
    G0 = _add(_mul(C, _solve(_add(_eye(n), [[-a for a in row] for row in A]), B)), D)  # @line L1
    HG0 = _mul(H, G0)
    rows = [([0] * n + HG0[i], (1 - eps) * h[i]) for i in range(nH)]
    Apow = _eye(n)
    SB = [[0] * m for _ in range(n)]  # S_t B with S_t = I + A + ... + A^(t-1)
    for t in range(t_max + 1):  # @line L2
        Hx = _mul(H, _mul(C, Apow))  # @line L3
        Hv = _mul(H, _add(_mul(C, SB), D))
        G = [a for a, _ in rows]
        g = [b for _, b in rows]
        new = []
        for i in range(nH):
            a = Hx[i] + Hv[i]
            val = lp_max(a, G, g, tol)  # @line L4
            if val is None or val > h[i] + tol:
                new.append((a, h[i]))
        if not new:
            return rows, t  # @line L4
        rows = rows + new  # @line L5
        SB = _add(B, _mul(A, SB))
        Apow = _mul(A, Apow)
    raise RuntimeError("O was not determined within t_max steps")


def admissible(rows, x, v, tol=0):
    """True if (x, v) satisfies every row."""
    z = list(x) + list(v)
    return all(sum(ai * zi for ai, zi in zip(a, z)) <= b + tol for a, b in rows)


def governor_step(rows, x, v_prev, r):
    """Return (v, kappa) with the largest kappa in [0, 1] such that (x, v) is in O."""
    n = len(x)
    d = [ri - vi for ri, vi in zip(r, v_prev)]
    kappa = 1  # @line L7
    for a, b in rows:
        beta = b - sum(ai * xi for ai, xi in zip(a[:n], x)) - sum(ai * vi for ai, vi in zip(a[n:], v_prev))
        alpha = sum(ai * di for ai, di in zip(a[n:], d))
        if alpha > 0 and beta < kappa * alpha:
            kappa = beta / alpha
    if kappa < 0:  # only rounding can make beta negative
        kappa = 0
    v = [vi + kappa * di for vi, di in zip(v_prev, d)]  # @line L8
    return v, kappa


def run(A, B, C, D, rows, x0, v_prev, refs):
    """Apply the governor to the references refs. Returns (xs, vs, ys, kappas)."""
    m = len(B[0])
    if D is None:
        D = [[0] * m for _ in C]
    x = list(x0)
    v = list(v_prev)
    xs, vs, ys, ks = [list(x)], [], [], []
    for r in refs:  # @line L6
        v, kappa = governor_step(rows, x, v, r)
        y = [sum(c * xi for c, xi in zip(Cr, x)) + sum(dd * vi for dd, vi in zip(Dr, v)) for Cr, Dr in zip(C, D)]
        x = [sum(a * xi for a, xi in zip(Ar, x)) + sum(b * vi for b, vi in zip(Br, v)) for Ar, Br in zip(A, B)]  # @line L8
        xs.append(x)
        vs.append(v)
        ys.append(y)
        ks.append(kappa)
    return xs, vs, ys, ks
test_reference_governor.py 150 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/reference-governor/. The authors are listed in prov/JN3QT7.jsonl.

import itertools
import random
from fractions import Fraction as F

from reference_governor import _solve, admissible, build_admissible_set, governor_step, lp_max, run

# The example of the page: y = x1 / 2 follows v with the step response 0, 0, 0.5, 1, 1.25, 1.25, 1.125, ...
A = [[0, 1], [F(-1, 2), 1]]
B = [[0], [1]]
C = [[F(1, 2), 0]]
H = [[1], [-1]]
h = [F(11, 10), F(11, 10)]
EPS = F(1, 20)


def outputs(Am, Bm, Cm, x, v, steps):
    ys = []
    for _ in range(steps):
        ys.append(sum(c * xi for c, xi in zip(Cm[0], x)))
        x = [sum(a * xi for a, xi in zip(row, x)) + Bm[i][0] * v for i, row in enumerate(Am)]
    return ys


def random_schur(rng, n):
    while True:
        M = [[rng.uniform(-1, 1) for _ in range(n)] for _ in range(n)]
        # Gershgorin: spectral radius below max row sum of |entries|; scale it to 0.8.
        s = max(sum(abs(v) for v in row) for row in M)
        M = [[0.8 * v / s for v in row] for row in M]
        b = [[rng.uniform(-1, 1)] for _ in range(n)]
        c = [[rng.uniform(-1, 1) for _ in range(n)]]
        # Steady state gain away from 0 so that references matter.
        I_A = [[(1 if i == j else 0) - M[i][j] for j in range(n)] for i in range(n)]
        g0 = sum(c[0][i] * _solve(I_A, b)[i][0] for i in range(n))
        if abs(g0) > 0.3:
            return M, b, c, g0


def test_lp_against_vertex_enumeration():
    rng = random.Random(4)
    for _ in range(40):
        k = rng.randint(3, 7)
        G = [[rng.uniform(-1, 1), rng.uniform(-1, 1)] for _ in range(k)]
        g = [rng.uniform(0.1, 1.0) for _ in range(k)]
        c = [rng.uniform(-1, 1), rng.uniform(-1, 1)]
        best = None
        for i, j in itertools.combinations(range(k), 2):
            det = G[i][0] * G[j][1] - G[i][1] * G[j][0]
            if abs(det) < 1e-9:
                continue
            z = [(g[i] * G[j][1] - G[i][1] * g[j]) / det, (G[i][0] * g[j] - g[i] * G[j][0]) / det]
            if all(G[r][0] * z[0] + G[r][1] * z[1] <= g[r] + 1e-9 for r in range(k)):
                val = c[0] * z[0] + c[1] * z[1]
                best = val if best is None else max(best, val)
        val = lp_max(c, G, g)
        # In the plane, the cone {d : G d <= 0} is spanned by directions along the lines G_i d = 0.
        dirs = [[s * G[i][1], -s * G[i][0]] for i in range(k) for s in (1, -1)] + [c]
        ray = any(all(G[r][0] * d[0] + G[r][1] * d[1] <= 1e-12 for r in range(k)) and c[0] * d[0] + c[1] * d[1] > 1e-12
                  for d in dirs)
        if val is None:
            assert ray
        else:
            assert not ray and best is not None and abs(val - best) < 1e-8


def test_lp_unbounded_and_exact():
    assert lp_max([1, 0], [[0, 1], [0, -1]], [1, 1]) is None
    assert lp_max([F(1), F(1)], [[1, 0], [0, 1], [-1, 0], [0, -1]], [F(1, 3), F(2, 7), 1, 1], tol=0) == F(13, 21)


def test_example_set_is_exact_and_small():
    rows, ts = build_admissible_set(A, B, C, None, H, h, EPS, tol=0)
    assert ts == 7 and len(rows) == 16
    # The row of t = 4 is the peak 1.25 v of the step response.
    assert ([F(-1, 8), 0, F(5, 4)], F(11, 10)) in rows


def test_membership_matches_simulation():
    rows, ts = build_admissible_set(A, B, C, None, H, h, EPS, tol=0)
    rng = random.Random(9)
    inside = outside = 0
    for _ in range(300):
        x = [F(rng.randint(-24, 24), 10), F(rng.randint(-24, 24), 10)]
        v = F(rng.randint(-12, 12), 10)
        ss_ok = abs(v) <= (1 - EPS) * h[0]
        ys = outputs(A, B, C, x, v, 60)
        ok = ss_ok and all(abs(y) <= h[0] for y in ys)
        assert admissible(rows, x, [v]) == ok
        # A violation, if any, happens before t_star.
        if ss_ok and not ok:
            assert any(abs(y) > h[0] for y in ys[:ts])
        inside += ok
        outside += not ok
    assert inside > 20 and outside > 20


def test_example_closed_loop():
    rows, _ = build_admissible_set(A, B, C, None, H, h, EPS, tol=0)
    xs, vs, ys, ks = run(A, B, C, None, rows, [0, 0], [0], [[1]] * 30)
    assert vs[0] == [F(22, 25)] and vs[3] == [F(22, 25)] and vs[4] == [1]
    assert max(y[0] for y in ys) == F(11, 10)
    assert all(vs[k][0] <= vs[k + 1][0] for k in range(29))
    assert abs(ys[-1][0] - 1) < 1e-3
    # Without the governor the output peaks at 1.25.
    assert max(outputs(A, B, C, [0, 0], 1, 12)) == F(5, 4)


def test_inadmissible_reference_stops_at_the_margin():
    Af = [[0.0, 1.0], [-0.5, 1.0]]
    rows, _ = build_admissible_set(Af, [[0.0], [1.0]], [[0.5, 0.0]], None, H, [1.1, 1.1], 0.05)
    xs, vs, ys, ks = run(Af, [[0.0], [1.0]], [[0.5, 0.0]], None, rows, [0.0, 0.0], [0.0], [[1.2]] * 40)
    assert max(abs(y[0]) for y in ys) <= 1.1 + 1e-12
    assert abs(vs[-1][0] - 1.045) < 1e-9


def test_random_loops_and_references():
    rng = random.Random(21)
    for _ in range(6):
        n = rng.choice([2, 3])
        M, b, c, g0 = random_schur(rng, n)
        hh = [1.0, 1.0]
        rows, ts = build_admissible_set(M, b, c, None, H, hh, 0.1)
        x = [0.0] * n
        v = [0.0]
        for k in range(60):
            if k % 15 == 0:
                r = [rng.uniform(-2.0, 2.0) / g0]
            assert admissible(rows, x, v, 1e-9)
            v, kappa = governor_step(rows, x, v, r)
            assert 0 <= kappa <= 1
            assert admissible(rows, x, v, 1e-9)
            y = sum(ci * xi for ci, xi in zip(c[0], x))
            assert abs(y) <= 1.0 + 1e-9
            x = [sum(a * xi for a, xi in zip(row, x)) + b[i][0] * v[0] for i, row in enumerate(M)]


def test_set_is_invariant_with_constant_v():
    rows, _ = build_admissible_set(A, B, C, None, H, h, EPS, tol=0)
    rng = random.Random(5)
    for _ in range(200):
        x = [F(rng.randint(-20, 20), 10), F(rng.randint(-20, 20), 10)]
        v = F(rng.randint(-10, 10), 10)
        if admissible(rows, x, [v]):
            x1 = [x[1], -x[0] / 2 + x[1] + v]
            assert admissible(rows, x1, [v])
            # kappa = 0 is always allowed, so the governor never gets stuck.
            assert governor_step(rows, x1, [v], [F(-3)])[1] >= 0

History

Gilbert and Tan (1991) defined the maximal output admissible set of a linear system, showed when it is finitely determined, and computed it by linear programs. Gilbert, Kolmanovsky and Tan (1995) applied it to the state together with a constant reference to build the discrete-time reference governor with one scalar per step and proved constraint satisfaction and finite-time convergence. Bemporad (1998) extended the idea to nonlinear systems. Later work added command governors with a free choice of vv, robust versions for disturbances, and many applications in automotive and aerospace control, which Garone, Di Cairano and Kolmanovsky (2017) survey.

References

  1. Elmer G. Gilbert, Ilya Kolmanovsky and Kok Tin Tan, Discrete-time reference governors and the nonlinear control of systems with state and control constraints, International Journal of Robust and Nonlinear Control 5(5), 487-504, 1995, the discrete-time reference governor for linear systems and the proofs of its properties
  2. Elmer G. Gilbert and Kok Tin Tan, Linear systems with state and control constraints, the theory and application of maximal output admissible sets, IEEE Transactions on Automatic Control 36(9), 1008-1020, 1991, the maximal output admissible set, its finite determination, and its computation by linear programs
  3. Alberto Bemporad, Reference governor for constrained nonlinear systems, IEEE Transactions on Automatic Control 43(3), 415-419, 1998, the reference governor for nonlinear systems, based on prediction of the future response
  4. Emanuele Garone, Stefano Di Cairano and Ilya Kolmanovsky, Reference and command governors for systems with constraints, a survey on theory and applications, Automatica 75, 306-328, 2017, the survey of scalar reference governors, command governors and their applications

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