Algorithm Search⌘K

Algorithmcore

Generalized predictive control

Also called GPC.

An MPC on a CARIMA transfer function model that minimizes predicted output errors and input increments over a horizon.

Time
O(N (a + b)) worstO(N^2 (a + b) + N M^2 + M^3) offline
Space
O(N^2 + N (a + b) + N M) extra
Where
M = the control horizon Nu; N = the output horizon N2; a = the degree of A; b = the degree of B
Properties
deterministicexactonlineiterative
Origin
D. W. Clarke, C. Mohtadi, P. S. Tuffs, 1987

Generalized predictive control (GPC) is a model predictive control method for a plant given as a transfer function in the backward shift q−1q^{-1}. Its model is the CARIMA model (controlled autoregressive integrated moving average)

A(q−1) y(t)=B(q−1) u(t−1)+e(t)Δ,Δ=1−q−1,A(q^{-1})\, y(t) = B(q^{-1})\, u(t-1) + \frac{e(t)}{\Delta}, \qquad \Delta = 1 - q^{-1},

in which the disturbance is integrated white noise. From this model, the Diophantine identity 1=EjΔA+q−jFj1 = E_j \Delta A + q^{-j} F_j gives the optimal jj-step predictor of the output. GPC minimizes the squared predicted errors over the horizons N1N_1 to N2N_2 plus λ\lambda times the squared input increments over NuN_u moves, and applies the first increment. Without constraints the law is a fixed linear controller in RST form with integral action. Clarke, Mohtadi and Tuffs introduced it in 1987, from the line of work on self-tuning control.

In plain words

GPC is like dynamic matrix control, but its model is a short difference equation instead of a recorded step response. The model also says how the unknown disturbance behaves: it drifts like a random walk, so the controller must act on changes of the input, which gives integral action. From the model, a polynomial division gives the best guess of each future output, as a sum of a part from the past and a part from the future input changes. The controller picks the future input changes that bring the guesses close to the setpoint, with a penalty on large changes, and applies only the first one. Because the model has few numbers, it is easy to estimate online, which makes GPC a common choice for adaptive control.

The problem

Input: monic AA of degree aa and BB of degree bb (a dead time of τ\tau samples is written as τ\tau leading zeros in BB); the horizons 1≤N1≤N21 \le N_1 \le N_2; the control horizon NuN_u; the move weight λ≥0\lambda \ge 0; at each sampling instant tt, the measured output y(t)y(t) and the setpoint ww. Output: the input u(t)u(t).

The predictor. Write A~=ΔA\tilde A = \Delta A, which is monic of degree a+1a + 1. For each jj, long division of 1 by A~\tilde A to jj terms gives unique EjE_j of degree j−1j - 1 and FjF_j of degree aa with 1=EjA~+q−jFj1 = E_j \tilde A + q^{-j} F_j. With Gj=EjBG_j = E_j B,

y(t+j)=Gj Δu(t+j−1)+Fj y(t)+Ej e(t+j).y(t + j) = G_j\, \Delta u(t + j - 1) + F_j\, y(t) + E_j\, e(t + j).

The last term depends only on future noise, so y^(t+j∣t)=Gj Δu(t+j−1)+Fj y(t)\hat y(t + j \mid t) = G_j\, \Delta u(t + j - 1) + F_j\, y(t) is the minimum mean square error predictor.

The split. The first jj coefficients of GjG_j are g0,…,gj−1g_0, \dots, g_{j-1}, the step response of q−1B/Aq^{-1} B / A. So the predictions for j=N1,…,N2j = N_1, \dots, N_2 are y^=G ΔU+f\hat y = G\, \Delta U + f with Gjl=gj−1−lG_{j l} = g_{j - 1 - l} for l<min⁡(j,Nu)l < \min(j, N_u), and the free response fjf_j collects Fj y(t)F_j\, y(t) and the terms of GjG_j that multiply past increments.

The move. Minimize ∥w1−G ΔU−f∥2+λ∥ΔU∥2\|w \mathbf{1} - G\, \Delta U - f\|^2 + \lambda \|\Delta U\|^2 over the NuN_u increments ΔU\Delta U. The minimizer is ΔU∗=(GTG+λI)−1GT(w1−f)\Delta U^* = (G^T G + \lambda I)^{-1} G^T (w \mathbf{1} - f).

The algorithm

  1. GPC-SETUP(A, B, N1, N2, Nu, λ) ▷ offline
  2. 1Ã ← A (1 - q⁻¹)
  3. for j ← N1 to N2
  4. 2(E_j, F_j) ← long division of 1 by à to j terms ▷ 1 = E_j à + q⁻ʲ F_j
  5. 3G_j ← E_j B
  6. G ← the matrix with G_jl = g_(j-1-l), the step response coefficients
  7. 4K ← first row of (Gᵀ G + λ I)⁻¹ Gᵀ
  8. GPC-STEP(y(t), w) ▷ online, at each sampling instant
  9. 5f_j ← F_j y(t) + Σ_(i ≥ j) G_j,i Δu(t + j - 1 - i) for j = N1, …, N2
  10. 6Δu(t) ← K (w 1 - f)
  11. 7u(t) ← u(t - 1) + Δu(t); store y(t) and Δu(t); return u(t)

Line L2 is polynomial long division: EjE_j is the first jj terms of the power series 1/A~1 / \tilde A, and FjF_j is what is left, shifted by jj. Line L4 keeps only the first row, because only the first increment is applied. Line L5 needs the last a+1a + 1 outputs and the last bb increments. The implementation also returns the equivalent RST polynomials and the closed-loop polynomial, for analysis.

Example

The model is A=1−0.8 q−1A = 1 - 0.8\, q^{-1}, B=0.2 q−1B = 0.2\, q^{-1}, so y(t)=0.8 y(t−1)+0.2 u(t−2)y(t) = 0.8\, y(t-1) + 0.2\, u(t-2). This is the plant of the DMC example: gain 1 and one extra sample of delay. Then A~=1−1.8 q−1+0.8 q−2\tilde A = 1 - 1.8\, q^{-1} + 0.8\, q^{-2}.

The Diophantine polynomials (exact with rational arithmetic):

jj EjE_j FjF_j
1 11 95−45q−1\frac95 - \frac45 q^{-1}
2 1+95q−11 + \frac95 q^{-1} 6125−3625q−1\frac{61}{25} - \frac{36}{25} q^{-1}

Fj(1)=1F_j(1) = 1 in both rows, as it must be because A~(1)=0\tilde A(1) = 0. The step response coefficients are g=(0,0.2,0.36,0.488,0.5904,… )g = (0, 0.2, 0.36, 0.488, 0.5904, \dots), the DMC step response.

The gain. With N1=1N_1 = 1, N2=10N_2 = 10, Nu=2N_u = 2 and λ=0.1\lambda = 0.1, GG is the dynamic matrix of DMC with P=10P = 10, M=2M = 2, so KK is the same vector, with ∑jKj=1.8422\sum_j K_j = 1.8422.

The RST form. The law is R(q−1) Δu(t)=T w−S(q−1) y(t)R(q^{-1})\, \Delta u(t) = T\, w - S(q^{-1})\, y(t) with

R=1+0.8962 q−1,S=5.4268−3.5846 q−1,T=1.8422.R = 1 + 0.8962\, q^{-1}, \qquad S = 5.4268 - 3.5846\, q^{-1}, \qquad T = 1.8422.

S(1)=1.8422=TS(1) = 1.8422 = T, which gives unit steady-state gain. The closed-loop polynomial is Pc=A~R+q−1BS=1−0.9038 q−1+0.2723 q−2P_c = \tilde A R + q^{-1} B S = 1 - 0.9038\, q^{-1} + 0.2723\, q^{-2}. Its roots are 00 and 0.4519±0.2609 i0.4519 \pm 0.2609\, i, of modulus 0.52180.5218, inside the unit circle, so the loop with the exact model is Schur.

Setpoint and disturbance. For a unit setpoint step from rest, the outputs are 0,0.3684,0.7015,0.9021,0.9928,1.0202,…0, 0.3684, 0.7015, 0.9021, 0.9928, 1.0202, \dots, the same as with DMC. For a step of 0.3 added to the measured output from t=25t = 25 (measurement with the implementation), the two methods differ:

sample after the step 0 1 2 3 4 5 6
GPC 1.3 1.3 0.9744 0.8952 0.9122 0.9492 0.9780
DMC 1.2999 1.2999 1.1894 1.0896 1.0295 1.0025 0.9946

GPC treats the jump as noise that enters through 1/A~1/\tilde A, so it predicts that the output will keep rising and acts harder; for a pure output step this gives an undershoot. DMC assumes the jump stays constant, which is right for this disturbance. For a load that enters the difference equation, the CARIMA assumption is the right one. In the tests, GPC removes such a load with no offset, also when the plant is 1−0.85 q−11 - 0.85\, q^{-1} with B=0.12 q−1B = 0.12\, q^{-1} or 0.3 q−10.3\, q^{-1} instead of the model.

Other tunings (with the same model, λ=0\lambda = 0, Nu=1N_u = 1):

N1N_1 N2N_2 closed-loop pole TT
2 10 0.7101 1.4496
1 20 0.7664 1.1679
1 50 0.7896 1.0519
2 2 0 5

With Nu=1N_u = 1 and a long output horizon the pole moves toward the open-loop pole 0.8. With N1=N2=2N_1 = N_2 = 2, the delay plus one, all closed-loop poles are at 0: R=1+1.8 q−1R = 1 + 1.8\, q^{-1}, S=12.2−7.2 q−1S = 12.2 - 7.2\, q^{-1}, T=5T = 5, which is deadbeat control.

Correctness

The proofs are in proofs/correctness.md.

  1. The Diophantine identity has a unique solution with deg⁡Ej≤j−1\deg E_j \le j - 1 and deg⁡Fj≤a\deg F_j \le a, and Fj(1)=1F_j(1) = 1 (Lemma 1).
  2. The predictor is the minimum mean square error predictor of y(t+j)y(t + j) for the CARIMA model, and it is exact when the noise is zero after time tt (Lemma 2).
  3. The split into G ΔU+fG\, \Delta U + f holds because GjG_j agrees with B/A~B / \tilde A up to order j−1j - 1 (Lemma 3).
  4. The move is the unique least squares minimizer for λ>0\lambda > 0, or for λ=0\lambda = 0 when GG has full column rank (Lemma 4).
  5. RST form and zero offset (theorem). The law is R Δu=Tw−SyR\, \Delta u = T w - S y with S(1)=TS(1) = T. If the closed loop is Schur, a constant setpoint and a constant load give y→wy \to w, also under model error that keeps the loop Schur. The theorem says nothing about where the closed-loop poles are; they must be checked.
Proof: The Diophantine predictor of GPC is the optimal predictor of the CARIMA model, the move is the least-squares optimum, and the law is an RST controller with unit steady-state gainfull

Polynomials are in the backward shift q−1q^{-1}. The model is

A(q−1) y(t)=B(q−1) u(t−1)+e(t)Δ,Δ=1−q−1,A(q^{-1})\, y(t) = B(q^{-1})\, u(t-1) + \frac{e(t)}{\Delta}, \qquad \Delta = 1 - q^{-1},

with AA monic of degree nan_a, BB of degree nbn_b, and ee a zero-mean white noise. Write A~=ΔA\tilde A = \Delta A, which is monic of degree na+1n_a + 1, and Δu(t)=u(t)−u(t−1)\Delta u(t) = u(t) - u(t-1). Multiplying the model by Δ\Delta gives

A~ y(t)=B Δu(t−1)+e(t).(1)\tilde A\, y(t) = B\, \Delta u(t-1) + e(t). \tag{1}

Lemma 1: the Diophantine identity

For each j≥1j \ge 1 there are unique polynomials EjE_j of degree at most j−1j - 1 and FjF_j of degree at most nan_a with

1=EjA~+q−jFj.1 = E_j \tilde A + q^{-j} F_j.

EjE_j is the first jj terms of the power series 1/A~1 / \tilde A, and Fj(1)=1F_j(1) = 1.

Proof. Since A~\tilde A is monic, 1/A~1/\tilde A is a power series ∑i≥0ciq−i\sum_{i \ge 0} c_i q^{-i}. Let Ej=∑i<jciq−iE_j = \sum_{i < j} c_i q^{-i}. Then 1−EjA~=A~∑i≥jciq−i1 - E_j \tilde A = \tilde A \sum_{i \ge j} c_i q^{-i} has no terms of order below jj, and it is a polynomial of degree at most j−1+na+1=j+naj - 1 + n_a + 1 = j + n_a. So it equals q−jFjq^{-j} F_j with deg⁡Fj≤na\deg F_j \le n_a. Uniqueness: if EA~+q−jF=0E \tilde A + q^{-j} F = 0 with deg⁡E<j\deg E < j, then EA~E \tilde A has no terms of order below jj; as A~\tilde A has the constant term 1, the lowest nonzero term of EE would give a term of the same order in EA~E \tilde A, so E=0E = 0 and then F=0F = 0. Finally, A~(1)=0\tilde A(1) = 0 because of the factor Δ\Delta, so setting q−1=1q^{-1} = 1 gives Fj(1)=1F_j(1) = 1. □\square

The routine diophantine is this long division: it subtracts ciq−iA~c_i q^{-i} \tilde A from the remainder for i=0,…,j−1i = 0, \dots, j - 1 and reads FjF_j from what is left (line L2).

Lemma 2: the predictor

Let Gj=EjBG_j = E_j B (line L3). Then

y(t+j)=Gj Δu(t+j−1)+Fj y(t)+Ej e(t+j).y(t + j) = G_j\, \Delta u(t + j - 1) + F_j\, y(t) + E_j\, e(t + j).

The last term involves only e(t+1),…,e(t+j)e(t+1), \dots, e(t+j), which are independent of the data up to time tt. So y^(t+j∣t)=Gj Δu(t+j−1)+Fj y(t)\hat y(t + j \mid t) = G_j\, \Delta u(t + j - 1) + F_j\, y(t) is the minimum mean square error predictor of y(t+j)y(t + j) given the data up to tt and the future moves, and it is exact when ee is zero after time tt.

Proof. Multiply (1), written at time t+jt + j, by EjE_j and use EjA~=1−q−jFjE_j \tilde A = 1 - q^{-j} F_j:

y(t+j)−Fj y(t)=EjB Δu(t+j−1)+Ej e(t+j).y(t + j) - F_j\, y(t) = E_j B\, \Delta u(t + j - 1) + E_j\, e(t + j).

EjE_j has degree at most j−1j - 1, so Eje(t+j)E_j e(t+j) is a combination of e(t+1),…,e(t+j)e(t+1), \dots, e(t+j). Given the past, the best predictor in mean square is the conditional mean, which removes exactly this term. □\square

Lemma 3: the split into forced and free response

The first jj coefficients of GjG_j are g0,…,gj−1g_0, \dots, g_{j-1}, the first coefficients of the power series B/A~B / \tilde A, which do not depend on jj. Hence

y^(t+j∣t)=∑l=0j−1gj−1−l Δu(t+l)+fj,fj=Fj y(t)+∑i≥jGj,i Δu(t+j−1−i).\hat y(t + j \mid t) = \sum_{l=0}^{j-1} g_{j-1-l}\, \Delta u(t + l) + f_j, \qquad f_j = F_j\, y(t) + \sum_{i \ge j} G_{j,i}\, \Delta u(t + j - 1 - i).

Proof. Gj=EjBG_j = E_j B and EjE_j agrees with 1/A~1/\tilde A up to order j−1j - 1, so GjG_j agrees with B/A~B / \tilde A up to order j−1j - 1. The coefficient Gj,iG_{j,i} multiplies Δu(t+j−1−i)\Delta u(t + j - 1 - i). For i≤j−1i \le j - 1 this is a move at time t+lt + l with l=j−1−i≥0l = j - 1 - i \ge 0, a decision variable; for i≥ji \ge j it is a move before time tt, a known value. □\square

The coefficients gig_i are the step response of the plant model q−1B/Aq^{-1} B / A: the response of y(t+1+i)y(t + 1 + i) to a unit step of uu at time tt. The free response fjf_j is computed by the code from the stored outputs and moves (line L5). Collecting j=N1,…,N2j = N_1, \dots, N_2 gives y^=GΔU+f\hat y = G \Delta U + f, with Gj,l=gj−1−lG_{j, l} = g_{j-1-l} for l≤j−1l \le j - 1 and 0 otherwise.

Lemma 4: the move

For λ>0\lambda > 0, or for λ=0\lambda = 0 when GG has full column rank, the cost ∥w1−GΔU−f∥2+λ∥ΔU∥2\|w \mathbf{1} - G \Delta U - f\|^2 + \lambda \|\Delta U\|^2 has the unique minimizer ΔU∗=(GTG+λI)−1GT(w1−f)\Delta U^* = (G^T G + \lambda I)^{-1} G^T (w \mathbf{1} - f).

Proof. The Hessian 2(GTG+λI)2 (G^T G + \lambda I) is positive definite under either condition, so the cost is strictly convex, and the minimizer is the zero of its gradient. □\square

Line L4 stores the first row KK of (GTG+λI)−1GT(G^T G + \lambda I)^{-1} G^T, and line L6 computes Δu(t)=K(w1−f)\Delta u(t) = K (w \mathbf{1} - f), the first entry of ΔU∗\Delta U^*.

Theorem 1: the RST form and the steady-state gain

Write K=(kN1,…,kN2)K = (k_{N_1}, \dots, k_{N_2}). The control law of line L6 is

R(q−1) Δu(t)=T w−S(q−1) y(t),S=∑jkjFj,T=∑jkj,R=1+∑jkj∑i≥jGj,i q−(1+i−j).R(q^{-1})\, \Delta u(t) = T\, w - S(q^{-1})\, y(t), \qquad S = \sum_j k_j F_j, \qquad T = \sum_j k_j, \qquad R = 1 + \sum_j k_j \sum_{i \ge j} G_{j,i}\, q^{-(1 + i - j)}.

With the model as the plant, the closed loop satisfies Pc y(t)=q−1BT w(t)+R e(t)P_c\, y(t) = q^{-1} B T\, w(t) + R\, e(t) with Pc=A~R+q−1BSP_c = \tilde A R + q^{-1} B S. Moreover S(1)=TS(1) = T, so if PcP_c has all its roots (as a polynomial in z=qz = q) inside the unit circle, a constant setpoint gives y→wy \to w with no offset, also under a constant load disturbance and under model error that keeps the loop Schur.

Proof. Substitute the formula of fjf_j from Lemma 3 into Δu(t)=∑jkj(w−fj)\Delta u(t) = \sum_j k_j (w - f_j) and move the terms with past moves to the left. The move Δu(t+j−1−i)\Delta u(t + j - 1 - i) with i≥ji \ge j is q−(1+i−j)Δu(t)q^{-(1 + i - j)} \Delta u(t), which gives RR; the output terms give SS. For the closed loop, multiply (1) by RR and the control law by q−1Bq^{-1} B, and add: A~Ry=BRΔu(t−1)+Re\tilde A R y = B R \Delta u(t-1) + R e and BRΔu(t−1)=q−1B(Tw−Sy)B R \Delta u(t-1) = q^{-1} B (T w - S y), which gives Pcy=q−1BTw+ReP_c y = q^{-1} B T w + R e. By Lemma 1, S(1)=∑jkjFj(1)=∑jkj=TS(1) = \sum_j k_j F_j(1) = \sum_j k_j = T. At z=1z = 1, A~(1)=0\tilde A(1) = 0, so the steady-state gain from ww to yy is B(1)T/(B(1)S(1))=1B(1) T / (B(1) S(1)) = 1 when B(1)≠0B(1) \ne 0 and T≠0T \ne 0. A constant load vv added to the output equation enters as Δv\Delta v, which is 0 after one step, so it leaves no offset. For a plant Apy=Bpu(t−1)A_p y = B_p u(t-1) different from the model, the same law gives (ΔApR+q−1BpS)y=q−1BpTw(\Delta A_p R + q^{-1} B_p S) y = q^{-1} B_p T w; at z=1z = 1 the first term vanishes again because of Δ\Delta, so the gain is still Bp(1)T/(Bp(1)S(1))=1B_p(1) T / (B_p(1) S(1)) = 1 whenever this loop is Schur. □\square

The theorem says nothing about the location of the roots of PcP_c. GPC with arbitrary horizons can give an unstable loop; the horizons and λ\lambda must be chosen and the roots checked. Results that guarantee stability for special choices of the horizons are in the GPC literature and are not used here.

Complexity

Costs are in the real-RAM model, with N=N2N = N_2, M=NuM = N_u, a=deg⁡Aa = \deg A and b=deg⁡Bb = \deg B, for one input and one output.

  • Offline. Each long division to jj terms costs O(ja)O(j a), and Gj=EjBG_j = E_j B costs O(jb)O(j b), so O(N2(a+b))O(N^2 (a + b)) for all jj. The divisions can also be done recursively in O(a)O(a) per step of jj, which gives O(N(a+b))O(N (a + b)). The gain costs O(NM2+M3)O(N M^2 + M^3) with a Cholesky factorization.
  • Online, per sampling instant. The free response costs O(a+b)O(a + b) for each jj, so O(N(a+b))O(N (a + b)), and line L6 costs O(N)O(N). In RST form the law costs only O(a+b)O(a + b).
  • Space. O(N2)O(N^2) for the polynomials EjE_j, which can be dropped after setup, O(N(a+b))O(N (a + b)) for FjF_j and the tails of GjG_j, and O(NM)O(N M) for GG.

Properties

  • Linear time-invariant controller without constraints, of RST form with the factor Δ\Delta, so it has integral action.
  • No general stability guarantee. Theorem 1 of the proof file does not locate the poles. Some choices of the horizons and λ\lambda give an unstable loop; check the roots of PcP_c.
  • Handles integrating and unstable plants. The model is a transfer function, so AA may have roots on or outside the unit circle, which DMC with a finite step response cannot represent.
  • Same setpoint response as DMC when the step response of DMC is the step response of q−1B/Aq^{-1} B / A and the horizons match (N1=1N_1 = 1, N2=PN_2 = P, Nu=MN_u = M); the disturbance responses differ, as in the table.
  • Few parameters to estimate. The model has a+b+1a + b + 1 numbers, which a recursive estimator can update online; with such an estimator GPC is a self-tuning regulator.

Variants and improvements

  • The noise polynomial or TT filter. The CARIMA model can carry a noise polynomial, C(q−1) e(t)/ΔC(q^{-1})\, e(t) / \Delta, and in practice a designer filter TT often takes its place. It changes the predictor and the disturbance response; with an exact model it does not change the setpoint response.
  • Constrained GPC. With input or output limits, each step is a quadratic program, as in linear MPC.
  • Multivariable GPC. AA and BB become polynomial matrices; the Diophantine identity is solved with matrix polynomials.
  • Setpoint preview. A known future setpoint w(t+j)w(t + j) replaces w1w \mathbf{1} in line L6.
  • Stabilizing variants. Terminal equality constraints on the predicted outputs and increments can be added to get a stability guarantee, in the spirit of the MPC stability theorem.

When to use it

Use GPC for single-loop or small plants that are well described by a low-order transfer function, especially when the model is estimated online, as in adaptive control. It handles dead time by leading zeros in BB and integrating plants directly. For many inputs and outputs with constraints, a state-space linear MPC is usually simpler to set up and analyze.

Pitfalls

  • Rank loss with a dead time. If λ=0\lambda = 0 and the horizons do not cover the dead time, GG loses rank. In the example, N1=1N_1 = 1, N2=3N_2 = 3, Nu=3N_u = 3, λ=0\lambda = 0 gives a singular GTGG^T G. Choose N2≥Nu+τN_2 \ge N_u + \tau, or use λ>0\lambda > 0.
  • Instability for some tunings. GPC does not guarantee an asymptotically stable loop. Check the roots of PcP_c for the model, and test with model error.
  • Noise model mismatch. The default model assumes integrated noise through 1/A1 / A. For output steps or measurement noise this gives an aggressive response; use the TT filter.
  • Deadbeat tuning. N1=N2=τ+1N_1 = N_2 = \tau + 1, Nu=1N_u = 1, λ=0\lambda = 0 gives all poles at 0 but large inputs (T=5T = 5 in the example), and it is sensitive to model error.
  • Clipping the input. Clipping uu after line L7 without telling the controller the applied value gives windup. Store the applied increment, or solve the constrained problem.

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.

generalized_predictive_control.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/generalized-predictive-control/. The authors are listed in prov/J9ZFD5.jsonl.

"""Generalized predictive control (GPC) of Clarke, Mohtadi and Tuffs (1987).

Single input, single output. Polynomials are lists of coefficients in
increasing powers of the backward shift q^-1, so [1, -0.8] is 1 - 0.8 q^-1.
The plant model is the CARIMA model

    A(q^-1) y(t) = B(q^-1) u(t-1) + e(t) / Delta,   Delta = 1 - q^-1,

with A monic. A dead time of d samples is written as d leading zeros in B.
With At = Delta A, the Diophantine identity

    1 = E_j(q^-1) At(q^-1) + q^-j F_j(q^-1),   deg E_j = j - 1, deg F_j = deg A,

gives the j-step predictor yhat(t+j | t) = G_j du(t+j-1) + F_j y(t) with
G_j = E_j B. The first j coefficients of G_j are the step response
coefficients g_0, ..., g_(j-1) of B / A, so the predictions over j = N1..N2
are G du + f, where G holds the g_i and f (the free response) holds F_j y(t)
and the terms of G_j that multiply past moves. The control law minimizes

    sum_(j=N1)^N2 (w - yhat(t+j | t))^2 + lam sum_(i=0)^(Nu-1) du(t+i)^2,

which gives du = (G^T G + lam I)^-1 G^T (w - f); only the first move is used.

All arithmetic is generic: with int and Fraction data the Diophantine
polynomials and the RST polynomials are exact.
"""

__all__ = ["poly_mul", "diophantine", "GPC"]


def poly_mul(a, b):
    """Product of two polynomials in q^-1."""
    out = [0] * (len(a) + len(b) - 1)
    for i, x in enumerate(a):
        for j, y in enumerate(b):
            out[i + j] += x * y
    return out


def diophantine(At, j):
    """Return (E_j, F_j) with 1 = E_j At + q^-j F_j, for a monic At.

    E_j is the first j terms of the series 1 / At (long division); F_j is
    the remainder divided by q^-j.
    """
    if At[0] != 1:
        raise ValueError("At must be monic")
    rem = [1] + [0] * (j + len(At) - 1)
    E = []
    for i in range(j):
        e = rem[i]
        E.append(e)
        for k, a in enumerate(At):
            rem[i + k] -= e * a
    F = rem[j:j + len(At) - 1]
    return E, F


def _solve(a, b):
    n = len(a)
    m = [list(r) + [v] for r, v in zip(a, b)]
    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 [m[i][n] / m[i][i] for i in range(n)]


class GPC:
    """Unconstrained GPC with the horizons N1..N2, the control horizon Nu and the move weight lam."""

    def __init__(self, A, B, N1, N2, Nu, lam):
        if A[0] != 1:
            raise ValueError("A must be monic")
        self.A, self.B = list(A), list(B)
        self.N1, self.N2, self.Nu, self.lam = N1, N2, Nu, lam
        self.At = poly_mul(A, [1, -1])  # @line L1
        self.E, self.F, self.Gj = {}, {}, {}
        for j in range(N1, N2 + 1):
            self.E[j], self.F[j] = diophantine(self.At, j)  # @line L2
            self.Gj[j] = poly_mul(self.E[j], self.B)  # @line L3
        g = self.Gj[N2][:N2]  # step response coefficients g_0..g_(N2-1)
        self.g = g
        self.G = [[g[j - 1 - l] if j - 1 - l >= 0 else 0 for l in range(Nu)] for j in range(N1, N2 + 1)]
        ny = N2 - N1 + 1
        GtG = [[sum(self.G[i][a] * self.G[i][b] for i in range(ny)) + (lam if a == b else 0) for b in range(Nu)]
               for a in range(Nu)]
        cols = [_solve(GtG, [self.G[i][a] for a in range(Nu)]) for i in range(ny)]
        self.K = [cols[i][0] for i in range(ny)]  # @line L4
        self.ys = [0] * len(self.F[N1])  # y(t), y(t-1), ..., y(t-deg A)
        self.nb = max(1, len(B) - 1)
        self.dus = [0] * (self.nb + 1)  # du(t-1), du(t-2), ..., one extra for predict()
        self.u = 0

    def free_response(self):
        """f_j for j = N1..N2 from the stored outputs and past moves."""
        f = []
        for j in range(self.N1, self.N2 + 1):
            fj = sum(c * y for c, y in zip(self.F[j], self.ys))
            fj += sum(self.Gj[j][i] * self.dus[i - j] for i in range(j, len(self.Gj[j])))
            f.append(fj)
        return f

    def step(self, y, w):
        """Return u(t) for the measured y(t) and the constant setpoint w."""
        self.ys = [y] + self.ys[:-1]
        f = self.free_response()  # @line L5
        du = sum(k * (w - fj) for k, fj in zip(self.K, f))  # @line L6
        self.dus = [du] + self.dus[:-1]
        self.u += du  # @line L7
        return self.u

    def predict(self, du_future):
        """yhat(t+j | t), j = N1..N2, for the future moves du(t..t+Nu-1), after step() at time t."""
        saved = self.dus
        self.dus = self.dus[1:]  # the moves before du(t), which is a decision variable here
        f = self.free_response()
        self.dus = saved
        return [fj + sum(self.G[i][l] * du_future[l] for l in range(self.Nu)) for i, fj in enumerate(f)]

    def rst(self):
        """Return (R, S, T) with R(q^-1) du(t) = T w - S(q^-1) y(t), the same law as step()."""
        js = list(range(self.N1, self.N2 + 1))
        R = [1] + [0] * self.nb
        for k, j in zip(self.K, js):
            for i in range(j, len(self.Gj[j])):
                R[1 + i - j] += k * self.Gj[j][i]
        S = [0] * len(self.F[self.N1])
        for k, j in zip(self.K, js):
            for i, c in enumerate(self.F[j]):
                S[i] += k * c
        return R, S, sum(self.K)

    def closed_loop_polynomial(self):
        """Return At R + q^-1 B S, the closed-loop characteristic polynomial in q^-1."""
        R, S, _ = self.rst()
        p1 = poly_mul(self.At, R)
        p2 = [0] + poly_mul(self.B, S)
        n = max(len(p1), len(p2))
        return [(p1[i] if i < len(p1) else 0) + (p2[i] if i < len(p2) else 0) for i in range(n)]
test_generalized_predictive_control.py 154 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/generalized-predictive-control/. The authors are listed in prov/J9ZFD5.jsonl.

import random
from fractions import Fraction as Fr

import pytest

from generalized_predictive_control import GPC, diophantine, poly_mul

A_EX = [1, -0.8]
B_EX = [0, 0.2]  # y(t) = 0.8 y(t-1) + 0.2 u(t-2)


class Plant:
    """A(q^-1) y(t) = B(q^-1) u(t-1) + load(t), simulated directly."""

    def __init__(self, A, B):
        self.A, self.B = A, B
        self.y = [0.0] * len(A)  # y(t), y(t-1), ...
        self.u = [0.0] * (len(B) + 1)  # u(t), u(t-1), ...

    def output(self):
        return self.y[0]

    def advance(self, u, load=0.0):
        """Apply u(t) and return y(t+1)."""
        self.u = [u] + self.u[:-1]
        y = load - sum(a * yy for a, yy in zip(self.A[1:], self.y))
        y += sum(b * uu for b, uu in zip(self.B, self.u))  # B u(t) for y(t+1)
        self.y = [y] + self.y[:-1]
        return y


def run_gpc(ctrl, plant, ws, load=lambda t: 0.0):
    ys, us = [], []
    for t, w in enumerate(ws):
        u = ctrl.step(plant.output(), w)
        plant.advance(u, load(t + 1))
        ys.append(plant.output())
        us.append(u)
    return ys, us


def test_diophantine_identity_exact():
    rng = random.Random(41)
    for _ in range(10):
        A = [1] + [Fr(rng.randint(-9, 9), rng.randint(1, 9)) for _ in range(rng.randint(1, 3))]
        At = poly_mul(A, [1, -1])
        for j in range(1, 10):
            E, F = diophantine(At, j)
            assert len(E) == j and len(F) == len(A)
            lhs = poly_mul(E, At)
            for i, c in enumerate(F):
                lhs[j + i] += c
            assert lhs[0] == 1 and all(c == 0 for c in lhs[1:])
            assert sum(F) == 1  # F_j(1) = 1, because At(1) = 0


def test_example_diophantine_polynomials():
    At = poly_mul([1, Fr(-4, 5)], [1, -1])
    assert diophantine(At, 1) == ([1], [Fr(9, 5), Fr(-4, 5)])
    assert diophantine(At, 2) == ([1, Fr(9, 5)], [Fr(61, 25), Fr(-36, 25)])


def test_step_coefficients_of_the_example():
    ctrl = GPC(A_EX, B_EX, 1, 10, 2, 0.1)
    assert ctrl.g[0] == 0
    for i in range(1, 10):
        assert abs(ctrl.g[i] - (1 - 0.8 ** i)) < 1e-12


def test_prediction_is_exact_for_a_carima_plant():
    rng = random.Random(42)
    for _ in range(10):
        A = [1, rng.uniform(-1.2, 1.2), rng.uniform(-0.4, 0.4)]
        B = [0.0] * rng.randint(0, 2) + [rng.uniform(0.1, 1.0), rng.uniform(-0.5, 0.5)]
        N1, N2, Nu = 1, 8, 3
        ctrl2 = GPC(A, B, N1, N2, Nu, 0.5)
        plant2 = Plant(A, B)
        for t in range(12):  # random setpoints; a load step is an integrated disturbance
            ctrl2.step(plant2.output(), rng.uniform(-1, 1))
            plant2.advance(ctrl2.u, 0.7 if t >= 3 else 0.0)
        ctrl2.step(plant2.output(), 0.0)
        du0 = ctrl2.dus[0]
        future = [du0] + [rng.uniform(-1, 1) for _ in range(Nu - 1)]
        pred = ctrl2.predict(future)
        u = ctrl2.u
        ys = []
        for i in range(N2):
            if 0 < i < Nu:
                u += future[i]
            ys.append(plant2.advance(u, 0.7))
        for j in range(N1, N2 + 1):
            assert abs(pred[j - N1] - ys[j - 1]) < 1e-9


def test_rst_form_gives_the_same_inputs():
    rng = random.Random(43)
    ctrl = GPC(A_EX, B_EX, 1, 10, 2, 0.1)
    R, S, T = ctrl.rst()
    assert abs(sum(S) - T) < 1e-12  # S(1) = T: unit steady-state gain
    ws = [rng.uniform(-1, 1) for _ in range(30)]
    loads = [rng.uniform(-0.2, 0.2) for _ in range(31)]
    _, u_gpc = run_gpc(ctrl, Plant(A_EX, B_EX), ws, lambda t: loads[t])
    plant = Plant(A_EX, B_EX)
    ys, dus, u = [0.0] * len(S), [0.0] * (len(R) - 1), 0.0
    for t, w in enumerate(ws):
        ys = [plant.output()] + ys[:-1]
        du = T * w - sum(s * y for s, y in zip(S, ys)) - sum(r * d for r, d in zip(R[1:], dus))
        dus = [du] + dus[:-1]
        u += du
        assert abs(u - u_gpc[t]) < 1e-9
        plant.advance(u, loads[t + 1])


def test_closed_loop_polynomial_of_the_example():
    ctrl = GPC(A_EX, B_EX, 1, 10, 2, 0.1)
    pc = ctrl.closed_loop_polynomial()
    assert len(pc) == 4 and abs(pc[3]) < 1e-12
    # z^3 Pc = z (z^2 + p1 z + p2): a complex pair of modulus sqrt(p2)
    assert pc[1] ** 2 - 4 * pc[2] < 0
    assert abs(pc[2] ** 0.5 - 0.5218) < 5e-5
    # the simulated output satisfies Pc(q^-1) y(t) = q^-1 B T w for a constant w
    _, _, T = ctrl.rst()
    ys, _ = run_gpc(ctrl, Plant(A_EX, B_EX), [1.0] * 30)
    for t in range(5, 30):
        lhs = sum(p * ys[t - i] for i, p in enumerate(pc))
        assert abs(lhs - sum(B_EX) * T) < 1e-9


def test_example_closed_loop_and_offset():
    ctrl = GPC(A_EX, B_EX, 1, 10, 2, 0.1)
    assert abs(sum(ctrl.K) - 1.8422) < 5e-5
    ys, _ = run_gpc(ctrl, Plant(A_EX, B_EX), [1.0] * 60, lambda t: 0.3 if t >= 25 else 0.0)
    assert ys[0] == 0.0 and abs(ys[1] - 0.3684) < 5e-5 and abs(ys[2] - 0.7015) < 5e-5
    assert abs(ys[-1] - 1.0) < 1e-6


def test_no_offset_with_model_error():
    for b in (0.12, 0.3):
        ctrl = GPC(A_EX, B_EX, 1, 10, 2, 0.1)
        ys, _ = run_gpc(ctrl, Plant([1, -0.85], [0, b]), [1.0] * 150, lambda t: 0.2 if t >= 50 else 0.0)
        assert abs(ys[-1] - 1.0) < 1e-6


def test_one_step_horizon_after_the_delay_puts_all_poles_at_zero():
    ctrl = GPC([1, Fr(-4, 5)], [0, Fr(1, 5)], 2, 2, 1, 0)
    assert ctrl.closed_loop_polynomial() == [1, 0, 0, 0]


def test_input_checks():
    with pytest.raises(ValueError):
        GPC([2, -0.8], B_EX, 1, 5, 1, 0.1)

History

Clarke, Mohtadi and Tuffs published GPC in 1987 in two papers in Automatica: the basic algorithm and the extensions and interpretations. It came from self-tuning control, where the plant model is a transfer function estimated online. It used the same receding horizon idea as the industrial methods based on step and impulse responses, such as DMC. Qin and Badgwell (2003) place GPC in the history of MPC next to these industrial methods.

References

  1. D. W. Clarke, C. Mohtadi and P. S. Tuffs, Generalized predictive control, Part I. The basic algorithm, Automatica 23(2), 137-148, 1987, the CARIMA model, the Diophantine predictor, the cost with the horizons N1, N2, Nu and the move weight, and the receding horizon law
  2. D. W. Clarke, C. Mohtadi and P. S. Tuffs, Generalized predictive control, Part II. Extensions and interpretations, Automatica 23(2), 149-160, 1987, the extensions of the basic algorithm and its relation to other self-tuning and predictive controllers
  3. S. Joe Qin and Thomas A. Badgwell, A survey of industrial model predictive control technology, Control Engineering Practice 11(7), 733-764, 2003, the place of GPC and the adaptive control line of work in the history of MPC

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.offline
  • 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