Algorithm Search⌘K

Algorithmcore

Smith predictor

Also called Smith dead-time compensator.

Takes the dead time out of the loop by feeding back a delay-free model output, so the controller can be tuned as if there were no delay.

Time
O(k n^2) worst
Space
O(n + d) extra
Where
d = the delay of the model in samples; k = the number of samples; n = the order of the model
Properties
deterministicexactonlineiterative
Origin
Otto J. M. Smith, 1957

The Smith predictor is a controller structure for a plant with a dead time, P(s)=P0(s)e−θsP(s) = P_0(s) e^{-\theta s}. It runs a model of the plant next to it. The model gives two outputs: the output without the delay, y^0\hat y_0, and the same output delayed by θ\theta, y^d\hat y_d. The primary controller, often a PID controller, gets the signal y+y^0−y^dy + \hat y_0 - \hat y_d. If the model is exact, y=y^dy = \hat y_d, so the controller sees the output that the plant would have without the delay. The controller can then be tuned for P0P_0 alone, and the closed loop answers a set-point change as the delay-free loop does, only θ\theta later.

In plain words

Some plants answer late. A valve opens, and the flow far down the pipe changes only seconds later. A normal controller sees no effect, pushes harder, and overshoots. The Smith predictor keeps a copy of the plant in the computer. The copy has two outputs: what the plant will do without the wait, and what it will do with the wait. The controller looks at the first output, so it sees the effect of its action at once and does not overshoot. The real measurement still counts. The difference between the real output and the copy with the wait shows the effects that the copy does not know, such as a load or a model error, and this difference is added in. The result is good only if the copy is close to the plant, the delay most of all.

The problem

Input. A plant P=P0e−θsP = P_0 e^{-\theta s} with one input and one output, a model Pm=P0me−θmsP_m = P_{0m} e^{-\theta_m s} of it, and a primary controller CC designed for P0mP_{0m}. For the sampled form, the sampling period hh, a model x^k+1=Amx^k+Bmuk\hat x_{k+1} = A_m \hat x_k + B_m u_k, y^k=Cmx^k\hat y_k = C_m \hat x_k of order nn from a zero-order hold discretization, and the model delay d=θm/hd = \theta_m/h in whole samples.

Output. At each sample, the control signal uku_k from the set point rkr_k and the measurement yky_k.

The aim. With an exact model the loop from rr to yy is T0(s)e−θsT_0(s) e^{-\theta s}, where T0=CP0/(1+CP0)T_0 = C P_0/(1 + C P_0) is the complementary sensitivity of the delay-free loop. So the delay is outside the loop: it does not enter the characteristic equation, and it does not limit the gain of CC. A load vv at the input of P0P_0 gives y=P0(1−T0e−θs)vy = P_0 (1 - T_0 e^{-\theta s}) v. The load still acts for the time θ\theta before the controller can answer it, and no controller can avoid that.

The algorithm

  1. SMITH-STEP(r, y)
  2. 1y_f ← yhat0 + (y - yhat_d) // yhat0 = C_m xhat; yhat_d = oldest value in the delay line
  3. 2e ← r - y_f
  4. 3u ← primary controller step with the error e
  5. 4xhat ← A_m xhat + B_m u
  6. 5push yhat0 into the delay line and drop its oldest value
  7. 6return u

The delay line holds the last dd values of y^0\hat y_0, so its oldest value is y^0\hat y_0 from dd samples ago, which is the model output with the delay. The state of the controller is x^\hat x, the delay line and the state of the primary controller. In the code the primary controller is a sampled PI controller, u=Ke+Iu = K e + I, then I←I+(Kh/Ti)eI \leftarrow I + (K h/T_i) e. Any controller with a step method can take its place.

The order of the operations in L1 matters for exact arithmetic. With an exact model, yy and y^d\hat y_d are the same number, so y−y^dy - \hat y_d is exactly 0 and yf=y^0y_f = \hat y_0.

Example

The plant. Take P0=1/(s+1)P_0 = 1/(s + 1), a delay θ=2\theta = 2 s, h=0.1h = 0.1 s, so d=20d = 20 samples. The delay is twice the time constant. Choose the PI controller K=2K = 2, Ti=1T_i = 1 s. Then TiT_i cancels the plant pole, CP0=2/sC P_0 = 2/s and T0=2/(s+2)T_0 = 2/(s + 2), a first order loop with the time constant 0.5 s.

Set-point step. All numbers are measurements on the sampled loop; the 2 percent band defines the settling time.

controller overshoot settling time
PI K=2K = 2, Ti=1T_i = 1 s, no delay in the plant 0.0021 1.7 s
Smith predictor with the same PI 0.0021 3.7 s
the same PI with the delay, no predictor output grows, peak 326 by 20 s -
Ziegler-Nichols PI, K=0.684K = 0.684, Ti=4.575T_i = 4.575 s 0 32.0 s
PI K=0.5K = 0.5, Ti=2T_i = 2 s 0 12.7 s
PI K=0.4K = 0.4, Ti=1.5T_i = 1.5 s 0.012 6.2 s

The Smith loop gives the delay-free response shifted by exactly 2 s; the difference between the two records is 0 in floating point. Without the predictor the same PI makes the loop diverge. The Ziegler-Nichols PI comes from the ultimate point Ku=1.5198K_u = 1.5198, Tu=5.4901T_u = 5.4901 s of this plant, and is slow. A PI tuned by hand for the delay does better, but it still settles more slowly than the Smith loop.

Load step. A unit load at the input of P0P_0 gives the peak 0.8775 and the integral of yy equal to 2.500 with the Smith loop. The Ziegler-Nichols PI gives the peak 0.883 and the integral 6.69. The peaks are close, because for the first 2 s no controller can act on the load. The Smith loop removes the load faster afterwards.

Model errors. The plant stays as above and the model changes. The settling times are for the set-point step.

model error overshoot settling time
model delay 2.2 s 0.031 8.8 s
model delay 1.8 s 0.158 6.7 s
model delay 3.0 s output grows, peak 833 by 150 s -
model gain 1.2 0 6.9 s
model gain 0.8 0.224 7.8 s
model time constant 1.5 s 0.188 11.3 s

A delay error of 10 percent doubles or triples the settling time. In this example the loop converges for every model delay from 0.8 s to 2.7 s, and it diverges for model delays of 0.6 s or less and from 2.9 s to 4.0 s, the largest value tried (measurement). The small gain bound of the Correctness section guarantees convergence of the continuous loop for delay errors below 0.7387 s.

A plant with a pole in the right half-plane. For P0=1/(s−1)P_0 = 1/(s - 1), θ=0.5\theta = 0.5 s, h=0.05h = 0.05 s and the PI K=3K = 3, Ti=1T_i = 1 s, the set-point step has the overshoot 0.507 and settles in 4.65 s. A load of 0.01 makes yy grow by the factor ee every second. The predictor does not work for such a plant.

Correctness

The proofs are in the correctness proof.

  • Exact model (theorem). With Pm=PP_m = P, the set-point response is T0e−θsT_0 e^{-\theta s} and the load response is P0(1−T0e−θs)P_0 (1 - T_0 e^{-\theta s}). For the sampled loop, yky_k equals the output of the delay-free loop at sample k−dk - d, exactly.
  • Internal stability (theorem). If P0P_0 is BIBO stable and the model is exact, the Smith loop is internally stable if and only if the delay-free loop of CC and P0P_0 is. The proof uses the internal model control form of the loop.
  • Poles in the right half-plane (theorem). If P0P_0 has a pole pp with Re⁡p≥0\operatorname{Re} p \ge 0 and e−θp≠1e^{-\theta p} \ne 1, the load response keeps that pole for every CC, so the loop is not internally stable.
  • Robust stability (theorem). With P=Pm(1+Δ)P = P_m (1 + \Delta) and both BIBO stable, the loop is internally stable if ∣T0m(jω)∣ ∣Δ(jω)∣<1|T_{0m}(j\omega)|\, |\Delta(j\omega)| < 1 for all ω\omega. For a delay error δ\delta the factor is ∣e−jωδ−1∣|e^{-j\omega\delta} - 1|, which reaches 2. The condition is sufficient, not necessary.
  • Integral action (theorem). With a PI controller the steady-state error to a set-point step is zero, and the integral of yy after a unit load step is Ti/K+P0(0) θT_i/K + P_0(0)\,\theta.
Proof: With an exact model the Smith predictor gives the delay-free loop followed by the delayfull

Notation is that of the page. The plant is P(s)=P0(s)e−θsP(s) = P_0(s) e^{-\theta s} with one input and one output, where P0P_0 is a proper rational transfer function. The model is Pm(s)=P0m(s)e−θmsP_m(s) = P_{0m}(s) e^{-\theta_m s}. The primary controller is C(s)C(s). The controller sees

yf=y+(P0m−Pm)u,e=r−yf,u=Ce.y_f = y + (P_{0m} - P_m) u, \qquad e = r - y_f, \qquad u = C e.

A load vv acts at the input of P0P_0, after the delay, as in the code, so y=Pu+P0vy = P u + P_0 v. The delay-free loop is the loop of CC and P0P_0, with L0=CP0L_0 = C P_0, S0=1/(1+L0)S_0 = 1/(1 + L_0) and T0=L0/(1+L0)T_0 = L_0/(1 + L_0). A transfer function is BIBO stable when it is proper and all its poles have negative real part; e−θse^{-\theta s} is BIBO stable. The loop is internally stable when every transfer function from the outside signals rr, vv and a measurement noise nn to the signals inside the loop, the model output included, is BIBO stable.

The claims are of two kinds. Claims 1 to 5 are theorems. Claim 6 is about the cost. The numbers on the page that are not covered here are measurements.

Claim 1: the closed loop with an exact model

Let Pm=PP_m = P. Then

yr=CP01+CP0e−θs=T0(s)e−θs,yv=P0(1−T0e−θs).\frac{y}{r} = \frac{C P_0}{1 + C P_0} e^{-\theta s} = T_0(s) e^{-\theta s}, \qquad \frac{y}{v} = P_0 \left(1 - T_0 e^{-\theta s}\right).

So the delay leaves the characteristic equation, and the set-point response is that of the delay-free loop, delayed by θ\theta.

Proof. From u=C(r−y−(P0−P)u)u = C(r - y - (P_0 - P) u),

u=K(r−y),K=C1+CP0−CP.u = K (r - y), \qquad K = \frac{C}{1 + C P_0 - C P}.

Then 1+PK=(1+CP0)/(1+CP0−CP)1 + P K = (1 + C P_0)/(1 + C P_0 - C P), so y/r=PK/(1+PK)=CP/(1+CP0)=T0e−θsy/r = P K/(1 + P K) = C P/(1 + C P_0) = T_0 e^{-\theta s}. For the load, y=P0v/(1+PK)=P0v(1+CP0−CP)/(1+CP0)=P0v(1−T0e−θs)y = P_0 v/(1 + P K) = P_0 v (1 + C P_0 - C P)/(1 + C P_0) = P_0 v (1 - T_0 e^{-\theta s}). A load at the plant input, before the delay, only adds the factor e−θse^{-\theta s}. □\square

The sampled loop. The code works on the sampled system. With the sampling period hh, a zero-order hold and θ=dh\theta = d h, the plant is xk+1=Adxk+Bduk−dx_{k+1} = A_d x_k + B_d u_{k-d}, yk=Cxky_k = C x_k, from x0=0x_0 = 0 and with uj=0u_j = 0 for j<0j < 0. The model with dm=dd_m = d and the same matrices has the state x^k\hat x_k with x^k+1=Adx^k+Bduk\hat x_{k+1} = A_d \hat x_k + B_d u_k, x^0=0\hat x_0 = 0.

With an exact model, yk=yk−d0y_k = y^0_{k-d} for k≥dk \ge d and yk=0y_k = 0 for k<dk < d, where y0y^0 is the output of the sampled delay-free loop of the same controller from rest.

Proof. Set x^j=0\hat x_j = 0 for j≤0j \le 0. By induction on kk, xk=x^k−dx_k = \hat x_{k-d}: it holds for k≤dk \le d, where both sides are 0, and xk+1=Adxk+Bduk−d=Adx^k−d+Bduk−d=x^k+1−dx_{k+1} = A_d x_k + B_d u_{k-d} = A_d \hat x_{k-d} + B_d u_{k-d} = \hat x_{k+1-d}. So yk=Cx^k−dy_k = C \hat x_{k-d}, which is the oldest value y^k−d\hat y_{k-d} in the delay line of the model. Line L1 then gives yf=y^k+(yk−y^k−d)=y^ky_f = \hat y_k + (y_k - \hat y_{k-d}) = \hat y_k. So the controller sees Cx^kC \hat x_k, and the pair (model, controller) runs exactly as the delay-free loop with the plant state x^\hat x. Thus x^k=xk0\hat x_k = x^0_k, uk=uk0u_k = u^0_k and yk=Cxk−d0=yk−d0y_k = C x^0_{k-d} = y^0_{k-d}. □\square

In the code the plant and the model compute yky_k and y^k−d\hat y_{k-d} by the same floating point operations on the same numbers, so yk−y^k−dy_k - \hat y_{k-d} is exactly 0 and the equality holds in floating point too. The tests compare with ==.

Claim 2: a plant with a pole in the right half-plane

Let Pm=PP_m = P, and let P0P_0 have a pole pp with Re⁡p≥0\operatorname{Re} p \ge 0 where CC has no zero. Let θ>0\theta > 0 and e−θp≠1e^{-\theta p} \ne 1, which holds for every real p>0p > 0. Then y/vy/v has the pole pp, so the loop is not internally stable, for every choice of CC.

Proof. At s=ps = p the loop gain L0=CP0L_0 = C P_0 is infinite, so T0(p)=1T_0(p) = 1. The factor 1−T0e−θs1 - T_0 e^{-\theta s} in Claim 1 is analytic near pp and has the value 1−e−θp≠01 - e^{-\theta p} \ne 0 there, so it does not cancel the pole of P0P_0. Thus y/v=P0(1−T0e−θs)y/v = P_0 (1 - T_0 e^{-\theta s}) has the pole pp. □\square

For P0=1/(s−1)P_0 = 1/(s - 1) and a load step of size ww, the term of yy from this pole is w(1−e−θ)etw (1 - e^{-\theta}) e^{t}, so yy grows by the factor ee each second. The set-point response T0e−θsT_0 e^{-\theta s} still converges. The growing mode is in the plant and in the model, and the two copies cancel in y−y^dy - \hat y_d. A load excites the copy in the plant only, so nothing cancels it.

A pole at the origin. For p=0p = 0 the factor 1−T0e−θs1 - T_0 e^{-\theta s} is 0 at s=0s = 0 and cancels the pole, so Claim 2 does not apply. But let P0=P1/sP_0 = P_1/s with P1(0)≠0P_1(0) \ne 0, and let the loop converge. The loop gain CP0C P_0 has at least one integrator, so near 0 either T0=c/(s+c)+O(s2)T_0 = c/(s + c) + O(s^2) with c>0c > 0, which gives T0′(0)=−1/cT_0'(0) = -1/c, or T0=1+O(s2)T_0 = 1 + O(s^2) when CP0C P_0 has two or more integrators, which gives T0′(0)=0T_0'(0) = 0. In both cases T0′(0)≤0T_0'(0) \le 0, and a load step of size ww gives, by the final value theorem,

lim⁡t→∞y(t)=wlim⁡s→0P1(s)s(1−T0e−θs)=wP1(0)(θ−T0′(0))≠0.\lim_{t \to \infty} y(t) = w \lim_{s \to 0} \frac{P_1(s)}{s} (1 - T_0 e^{-\theta s}) = w P_1(0) \left(\theta - T_0'(0)\right) \ne 0.

So a constant load leaves a constant error, even when CC has an integrator.

Claim 3: internal stability with an exact model

Let Pm=PP_m = P, and let P0P_0 be BIBO stable. Then the Smith predictor loop is internally stable if and only if the delay-free loop of CC and P0P_0 is internally stable.

Proof. Write Q=C/(1+CP0)=CS0Q = C/(1 + C P_0) = C S_0. With an exact model the signal y−Pmuy - P_m u that the predictor feeds back equals P0v+nP_0 v + n, and the controller is u=Q(r−(y+n−Pmu))u = Q (r - (y + n - P_m u)); to check this, solve u=C(r−y−n−(P0−Pm)u)u = C(r - y - n - (P_0 - P_m) u) for uu and compare. So

u=Qr−QP0v−Qn,y=PQr+P0(1−PQ)v−PQn,u = Q r - Q P_0 v - Q n, \qquad y = P Q r + P_0 (1 - P Q) v - P Q n,

and the model output is P0muP_{0m} u and PmuP_m u. If QQ is BIBO stable, every one of these is a product of BIBO stable factors, so the loop is internally stable. If the loop is internally stable, then u/r=Qu/r = Q is BIBO stable. So the Smith loop is internally stable if and only if QQ is BIBO stable.

For the delay-free loop, internal stability means that S0S_0, P0S0P_0 S_0, CS0C S_0 and T0T_0 are BIBO stable. If so, Q=CS0Q = C S_0 is BIBO stable. Conversely, if QQ is BIBO stable, then T0=P0QT_0 = P_0 Q, S0=1−P0QS_0 = 1 - P_0 Q, P0S0=P0(1−P0Q)P_0 S_0 = P_0 (1 - P_0 Q) and CS0=QC S_0 = Q are all BIBO stable. □\square

This is the internal model control structure with the parameter Q=C/(1+CP0)Q = C/(1 + C P_0). The proof also shows why the plant must be BIBO stable: for a plant with a pole in the right half-plane, P0(1−PQ)P_0 (1 - P Q) keeps the pole, as in Claim 2.

Claim 4: robust stability against model errors

Let PP and PmP_m be BIBO stable, and let the delay-free loop with the model be internally stable, so that Q=C/(1+CP0m)Q = C/(1 + C P_{0m}) is BIBO stable. Write P=Pm(1+Δ)P = P_m (1 + \Delta). If

∣T0m(jω)∣∣Δ(jω)∣<1for all ω,T0m=CP0m1+CP0m,\left| T_{0m}(j\omega) \right| \left| \Delta(j\omega) \right| < 1 \quad \text{for all } \omega, \qquad T_{0m} = \frac{C P_{0m}}{1 + C P_{0m}},

then the loop with the plant PP is internally stable. For a delay error only, P=Pme−δsP = P_m e^{-\delta s}, the condition is ∣T0m(jω)∣ ∣e−jωδ−1∣<1|T_{0m}(j\omega)|\, |e^{-j\omega\delta} - 1| < 1.

Proof. With the model error, the predictor feeds back y−Pmu=(P−Pm)u+P0v+ny - P_m u = (P - P_m) u + P_0 v + n, and u=Q(r−(P−Pm)u−P0v−n)u = Q (r - (P - P_m) u - P_0 v - n). So the loop is the feedback of QQ and P−Pm=PmΔP - P_m = P_m \Delta, both BIBO stable. On the imaginary axis ∣Q(P−Pm)∣=∣QP0m∣ ∣e−jωθm∣ ∣Δ∣=∣T0m∣ ∣Δ∣<1|Q (P - P_m)| = |Q P_{0m}|\, |e^{-j\omega\theta_m}|\, |\Delta| = |T_{0m}|\, |\Delta| < 1. By the small gain theorem, 1/(1+Q(P−Pm))1/(1 + Q (P - P_m)) is BIBO stable, and the other closed loop transfer functions are products of it with BIBO stable factors. □\square

The condition is sufficient only. For T0m=2/(s+2)T_{0m} = 2/(s + 2) and a delay error δ\delta, the left side has its maximum below 1 for ∣δ∣<0.7387|\delta| < 0.7387 s, and the maximum is 0.3573 for ∣δ∣=0.2|\delta| = 0.2 s. For a gain error, Δ=g−1\Delta = g - 1 is a constant, and since ∣T0m∣≤1|T_{0m}| \le 1 for this T0mT_{0m}, every gain ratio 0<g<20 < g < 2 is covered. Since ∣e−jωδ−1∣|e^{-j\omega\delta} - 1| reaches 2 at high frequency, a delay error of any size needs ∣T0m∣<1/2|T_{0m}| < 1/2 there. That is the reason to keep the bandwidth of the delay-free loop moderate when the delay is not well known.

Claim 5: integral action and the load response

Let Pm=PP_m = P, let P0P_0 be BIBO stable with P0(0)≠0P_0(0) \ne 0, let the loop be internally stable, and let CC have a simple pole at 0 with the residue K/TiK/T_i, as the PI controller K(1+1/(Tis))K (1 + 1/(T_i s)) has. Then a set-point step gives zero steady-state error, and for a unit load step at the plant input

∫0∞y(t) dt=TiK+P0(0) θ.\int_0^\infty y(t)\, dt = \frac{T_i}{K} + P_0(0)\, \theta.

Proof. Near s=0s = 0, L0=CP0≈c/sL_0 = C P_0 \approx c/s with c=KP0(0)/Tic = K P_0(0)/T_i, so T0(0)=1T_0(0) = 1 and the final value theorem gives y→T0(0)=1y \to T_0(0) = 1 for a unit set-point step. For the load, Y(s)=G(s)/sY(s) = G(s)/s with G=P0(1−T0e−θs)G = P_0 (1 - T_0 e^{-\theta s}). Since G(0)=P0(0)(1−1)=0G(0) = P_0(0)(1 - 1) = 0 and YY is analytic at 00, the integral of yy is Y(0)=G′(0)Y(0) = G'(0). The derivative is

G′(0)=P0(0)(θ−T0′(0)),G'(0) = P_0(0) \left( \theta - T_0'(0) \right),

and T0=c/(s+c)+O(s2)T_0 = c/(s + c) + O(s^2) near 0 gives T0′(0)=−1/cT_0'(0) = -1/c. So G′(0)=P0(0)θ+P0(0)Ti/(KP0(0))G'(0) = P_0(0)\theta + P_0(0) T_i/(K P_0(0)). □\square

The same loop without the delay has the integral Ti/KT_i/K. So the predictor cannot remove the term P0(0)θP_0(0)\theta: the controller sees the load only after the delay. With PI control and no predictor the integral is Ti/KT_i/K as well, but K/TiK/T_i must then be small enough for the loop with the delay, which makes Ti/KT_i/K large.

The same result holds for the sampled loop with the PI law of the code: the sum h∑kykh \sum_k y_k equals Ti/K+P0(0) dhT_i/K + P_0(0)\, d h, because the sampled integrator (Kh/Ti)/(z−1)(K h/T_i)/(z - 1) gives c=KP0(0)h/Tic = K P_0(0) h/T_i in the variable z−1z - 1. The tests check 2.52.5 for P0=1/(s+1)P_0 = 1/(s + 1), θ=2\theta = 2 s, K=2K = 2, Ti=1T_i = 1 s and 6.56.5 for the plant gain 3.

Claim 6: the cost

One controller step costs O(n2)O(n^2) time and the controller keeps O(n+dm)O(n + d_m) numbers, where nn is the order of the model and dmd_m the delay of the model in samples. A run of kk samples costs O(kn2)O(k n^2) time.

Proof. Lines L1 to L3 and L6 cost O(1)O(1), plus the cost of the primary controller, which is O(1)O(1) for a PI controller. Line L4 multiplies an n×nn \times n matrix by a vector, O(n2)O(n^2), and computing y^\hat y costs O(n)O(n). Line L5 appends to and removes from a queue of length dmd_m, O(1)O(1). The state is the model state, nn numbers, and the delay line, dmd_m numbers. The simulated plant has the same cost per step. □\square

Complexity

One controller step costs O(n2)O(n^2) time for the model update and O(1)O(1) for the delay line and a PI controller. A run of kk samples costs O(kn2)O(k n^2). The controller keeps O(n+d)O(n + d) numbers, the model state and the delay line. A long delay at a short sampling period needs a long delay line, but the cost per sample does not grow with it.

Properties

  • The delay leaves the loop. With an exact model the characteristic equation is that of the delay-free loop, so the controller can have a high gain even when the delay is long.
  • Model based. The structure needs a model of P0P_0 and of the delay. The quality of control depends on the model, the delay most of all.
  • Load response. The predictor does not shorten the time that a load acts before the controller answers. It helps after that time.
  • Plants with all poles in the left half-plane only. The basic predictor does not suit a plant with an integrator, where a constant load leaves a constant error, or a plant with a pole in the right half-plane, where the loop is not internally stable. Both are theorems in the proof.
  • Linear time-invariant. The structure adds no nonlinearity. Actuator limits need the same care as in any loop with integral action.

Variants and improvements

  • Internal model control. The Smith predictor with the controller CC is the internal model control structure with Q=C/(1+CP0)Q = C/(1 + C P_0). Designing QQ directly gives the same structure with a different tuning.
  • Filtered predictors. A filter on the correction y−y^dy - \hat y_d reduces the effect of noise and model errors and can make the scheme work for a plant with an integrator. Several variants of this kind exist for integrating plants and for plants with a pole in the right half-plane.
  • Model predictive control. Model predictive control and dynamic matrix control also predict the output over the delay with a model, and they add constraints and several inputs.
  • Disturbance observer. A disturbance observer uses a similar comparison of plant and model to estimate the load.

When to use it

Use the Smith predictor when the delay is long compared with the main time constant of the plant, the plant has all its poles in the left half-plane, and the delay is known well, for example from the length and speed of a conveyor or a pipe. When the delay is short compared with the time constant, a PID controller does about as well and needs no model. When the delay changes with the operating point, the model delay must follow it, or the loop must be tuned for the worst case.

Pitfalls

  • Delay errors. A wrong model delay hurts more than a wrong gain. In the example, a model delay 10 percent too short gives 16 percent overshoot. Keep the bandwidth of the delay-free loop moderate when the delay is uncertain.
  • Tuning for the delay-free model only. A controller tuned very fast for P0P_0 has ∣T0∣|T_0| near 1 at high frequency, and the robust stability condition then fails for small delay errors.
  • Integrating and other plants with poles outside the open left half-plane. The basic structure cannot remove a constant load on a plant with an integrator, and it cannot be internally stable for a plant with a pole in the right half-plane. Use a modified predictor.
  • Load response expectations. The set-point response looks like the delay-free one, but a load still acts for the full delay before any correction arrives.
  • Sampling and the delay. The sampled model holds the delay in whole samples. A delay that is not a whole number of samples needs a fractional delay in the model, or the error counts as a delay error.

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.

ctlmat.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the control pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Small dense linear algebra and polynomial routines for the control pages.

Conventions:
- A matrix is a list of rows. Entries are int, float, Fraction or complex.
- A vector is a flat list of scalars. matvec, dot, solve (with a vector
  right side), vec and unvec use flat lists.
- A polynomial is a list of coefficients, highest power first, so
  [1, 3, 2] is s^2 + 3 s + 2.
- Routines that divide (solve, inv, det, charpoly) compute in Fraction when
  every entry is an int or a Fraction, so the result is exact. With float or
  complex entries they compute in floating point.
- transpose does not conjugate complex entries.

Floating point tolerances:
- expm: scaling and squaring with a Taylor series; the scaled matrix has
  infinity norm at most 1/2 and the series stops when a term is below
  2^-60 times the sum. For matrices that are not far from normal the relative
  error is near 1e-14.
- polyroots: Durand-Kerner iteration, then a Newton polish. Simple roots of a
  well conditioned polynomial come out with a relative error near 1e-12 (the
  tests ask for 1e-9). A root of multiplicity k is ill conditioned: its error
  grows like 1e-16^(1/k), about 1e-8 for a double root and 1e-3 for a
  fourfold root. For real coefficients the output is closed under
  conjugation.
- is_pos_def with float entries: the matrix must be symmetric within
  1e-12 times its largest entry, and the Cholesky pivots of A - margin I must
  be positive.

This file holds no algorithm of a control page.
"""

import cmath
import math
from fractions import Fraction

__all__ = [
    "zeros", "eye", "add", "sub", "scale", "mul", "transpose", "matvec",
    "dot", "norm2", "block", "kron", "vec", "unvec", "solve", "inv", "det",
    "trace", "charpoly", "polyval", "polyadd", "polymul", "polyder",
    "polyroots", "expm", "mat_power", "is_symmetric", "is_pos_def",
]


def _is_exact(v):
    return isinstance(v, (int, Fraction))


def _all_exact(*mats):
    for m in mats:
        for row in m:
            if isinstance(row, list):
                for v in row:
                    if not _is_exact(v):
                        return False
            elif not _is_exact(row):
                return False
    return True


def _to_fraction(a):
    return [[Fraction(v) for v in row] for row in a]


def _shape(a):
    return len(a), (len(a[0]) if a else 0)


def zeros(n, m=None):
    """Return the n by m zero matrix (n by n if m is None), with int entries."""
    if m is None:
        m = n
    return [[0] * m for _ in range(n)]


def eye(n):
    """Return the n by n identity matrix, with int entries."""
    return [[1 if i == j else 0 for j in range(n)] for i in range(n)]


def add(a, b):
    """Return a + b."""
    if _shape(a) != _shape(b):
        raise ValueError("add: shapes differ")
    return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]


def sub(a, b):
    """Return a - b."""
    if _shape(a) != _shape(b):
        raise ValueError("sub: shapes differ")
    return [[x - y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]


def scale(c, a):
    """Return the scalar c times the matrix a."""
    return [[c * x for x in row] for row in a]


def mul(a, b):
    """Return the matrix product a b."""
    n, k = _shape(a)
    k2, m = _shape(b)
    if k != k2:
        raise ValueError("mul: inner dimensions differ")
    bt = list(zip(*b)) if b else []
    out = []
    for row in a:
        out_row = []
        for col in bt:
            s = 0
            for x, y in zip(row, col):
                s += x * y
            out_row.append(s)
        out.append(out_row)
    return out


def transpose(a):
    """Return the transpose of a (no complex conjugation)."""
    return [list(col) for col in zip(*a)]


def matvec(a, x):
    """Return the vector a x, for a flat list x."""
    if a and len(a[0]) != len(x):
        raise ValueError("matvec: dimensions differ")
    out = []
    for row in a:
        s = 0
        for v, w in zip(row, x):
            s += v * w
        out.append(s)
    return out


def dot(x, y):
    """Return sum of x_i y_i (no complex conjugation)."""
    if len(x) != len(y):
        raise ValueError("dot: lengths differ")
    s = 0
    for v, w in zip(x, y):
        s += v * w
    return s


def _sym_eigvals(s):
    """Eigenvalues of a real symmetric float matrix by cyclic Jacobi."""
    n = len(s)
    a = [list(map(float, row)) for row in s]
    for _ in range(100):
        off = sum(a[i][j] ** 2 for i in range(n) for j in range(n) if i != j)
        diag = sum(a[i][i] ** 2 for i in range(n))
        if off <= 1e-30 * max(diag, 1e-300):
            break
        for p in range(n - 1):
            for q in range(p + 1, n):
                if a[p][q] == 0.0:
                    continue
                theta = (a[q][q] - a[p][p]) / (2.0 * a[p][q])
                t = math.copysign(1.0, theta) / (abs(theta) + math.sqrt(theta * theta + 1.0))
                c = 1.0 / math.sqrt(t * t + 1.0)
                sn = t * c
                for k in range(n):
                    akp, akq = a[k][p], a[k][q]
                    a[k][p] = c * akp - sn * akq
                    a[k][q] = sn * akp + c * akq
                for k in range(n):
                    apk, aqk = a[p][k], a[q][k]
                    a[p][k] = c * apk - sn * aqk
                    a[q][k] = sn * apk + c * aqk
    return [a[i][i] for i in range(n)]


def norm2(x):
    """Return the 2-norm.

    For a flat vector this is the Euclidean norm. For a matrix it is the
    induced 2-norm (the largest singular value), computed from the
    eigenvalues of M^T M by the Jacobi method, where M is a real matrix with
    the same singular values. The result is a float.
    """
    if not x:
        return 0.0
    if not isinstance(x[0], list):
        return math.sqrt(sum(abs(complex(v)) ** 2 for v in x))
    if any(isinstance(v, complex) for row in x for v in row):
        re = [[complex(v).real for v in row] for row in x]
        im = [[complex(v).imag for v in row] for row in x]
        m = block([[re, scale(-1, im)], [im, re]])
    else:
        m = [[float(v) for v in row] for row in x]
    g = mul(transpose(m), m)
    lam = max(_sym_eigvals(g))
    return math.sqrt(max(lam, 0.0))


def block(rows):
    """Build a matrix from a list of rows of blocks.

    A block is a matrix, or the int 0 for a zero block whose size is taken
    from the other blocks in its block row and block column.
    """
    heights = []
    for r in rows:
        h = None
        for b in r:
            if isinstance(b, list):
                h = len(b)
                break
        if h is None:
            raise ValueError("block: a block row has no matrix block")
        heights.append(h)
    ncols = len(rows[0])
    widths = []
    for j in range(ncols):
        w = None
        for r in rows:
            if isinstance(r[j], list):
                w = len(r[j][0]) if r[j] else 0
                break
        if w is None:
            raise ValueError("block: a block column has no matrix block")
        widths.append(w)
    out = []
    for r, h in zip(rows, heights):
        if len(r) != ncols:
            raise ValueError("block: block rows have different lengths")
        for i in range(h):
            line = []
            for b, w in zip(r, widths):
                if isinstance(b, list):
                    if len(b) != h or (b and len(b[0]) != w):
                        raise ValueError("block: block sizes do not match")
                    line.extend(b[i])
                elif b == 0:
                    line.extend([0] * w)
                else:
                    raise ValueError("block: a scalar block must be 0")
            out.append(line)
    return out


def kron(a, b):
    """Return the Kronecker product of a and b."""
    n, m = _shape(a)
    p, q = _shape(b)
    return [[a[i // p][j // q] * b[i % p][j % q] for j in range(m * q)] for i in range(n * p)]


def vec(a):
    """Stack the columns of a into one flat list."""
    n, m = _shape(a)
    return [a[i][j] for j in range(m) for i in range(n)]


def unvec(v, n, m=None):
    """Inverse of vec: return the n by m matrix whose stacked columns are v."""
    if m is None:
        m = len(v) // n
    if n * m != len(v):
        raise ValueError("unvec: length does not match the shape")
    return [[v[j * n + i] for j in range(m)] for i in range(n)]


def solve(a, b):
    """Solve a x = b by Gaussian elimination with partial pivoting.

    b is a flat vector or a matrix; the result has the same form. With int
    and Fraction entries the result is exact (Fraction). Raises ValueError
    if a is singular (an exactly zero pivot).
    """
    n, m = _shape(a)
    if n != m:
        raise ValueError("solve: matrix is not square")
    is_vec = not (b and isinstance(b[0], list))
    rhs = [[v] for v in b] if is_vec else [list(row) for row in b]
    if len(rhs) != n:
        raise ValueError("solve: right side has the wrong length")
    if _all_exact(a, rhs):
        aa = _to_fraction(a)
        rhs = _to_fraction(rhs)
    else:
        aa = [list(row) for row in a]
    k = len(rhs[0]) if rhs else 0
    for c in range(n):
        p = max(range(c, n), key=lambda r: abs(aa[r][c]))
        if aa[p][c] == 0:
            raise ValueError("solve: matrix is singular")
        if p != c:
            aa[c], aa[p] = aa[p], aa[c]
            rhs[c], rhs[p] = rhs[p], rhs[c]
        piv = aa[c][c]
        for r in range(c + 1, n):
            f = aa[r][c] / piv
            if f == 0:
                continue
            row_r, row_c = aa[r], aa[c]
            for j in range(c, n):
                row_r[j] -= f * row_c[j]
            rr, rc = rhs[r], rhs[c]
            for j in range(k):
                rr[j] -= f * rc[j]
    x = [[0] * k for _ in range(n)]
    for c in range(n - 1, -1, -1):
        for j in range(k):
            s = rhs[c][j]
            for t in range(c + 1, n):
                s -= aa[c][t] * x[t][j]
            x[c][j] = s / aa[c][c]
    return [row[0] for row in x] if is_vec else x


def inv(a):
    """Return the inverse of a (exact with int and Fraction entries)."""
    return solve(a, eye(len(a)))


def det(a):
    """Return the determinant of a by elimination with partial pivoting.

    With int and Fraction entries the result is an exact Fraction.
    """
    n, m = _shape(a)
    if n != m:
        raise ValueError("det: matrix is not square")
    aa = _to_fraction(a) if _all_exact(a) else [list(row) for row in a]
    d = Fraction(1) if _all_exact(a) else 1.0
    for c in range(n):
        p = max(range(c, n), key=lambda r: abs(aa[r][c]))
        if aa[p][c] == 0:
            return d * 0
        if p != c:
            aa[c], aa[p] = aa[p], aa[c]
            d = -d
        piv = aa[c][c]
        d *= piv
        for r in range(c + 1, n):
            f = aa[r][c] / piv
            if f == 0:
                continue
            for j in range(c, n):
                aa[r][j] -= f * aa[c][j]
    return d


def trace(a):
    """Return the sum of the diagonal entries of a."""
    s = 0
    for i in range(len(a)):
        s += a[i][i]
    return s


def charpoly(a):
    """Return [1, a_1, ..., a_n] with det(s I - A) = s^n + a_1 s^(n-1) + ... + a_n.

    Uses the Faddeev-LeVerrier recursion M_k = A M_(k-1) + a_(k-1) I,
    a_k = -trace(A M_k) / k. Exact with int and Fraction entries.
    """
    n, m = _shape(a)
    if n != m:
        raise ValueError("charpoly: matrix is not square")
    aa = _to_fraction(a) if _all_exact(a) else [list(row) for row in a]
    coeffs = [1]
    mk = zeros(n)
    for k in range(1, n + 1):
        mk = mul(aa, mk)
        c = coeffs[-1]
        for i in range(n):
            mk[i][i] += c
        am = mul(aa, mk)
        coeffs.append(-trace(am) / k)
    return coeffs


def polyval(p, x):
    """Evaluate the polynomial p at x by Horner's rule."""
    s = 0
    for c in p:
        s = s * x + c
    return s


def _strip(p):
    i = 0
    while i < len(p) - 1 and p[i] == 0:
        i += 1
    return list(p[i:]) if p else [0]


def polyadd(p, q):
    """Return p + q, with exactly zero leading coefficients removed."""
    n = max(len(p), len(q))
    pp = [0] * (n - len(p)) + list(p)
    qq = [0] * (n - len(q)) + list(q)
    return _strip([x + y for x, y in zip(pp, qq)])


def polymul(p, q):
    """Return the product p q."""
    if not p or not q:
        return [0]
    out = [0] * (len(p) + len(q) - 1)
    for i, x in enumerate(p):
        for j, y in enumerate(q):
            out[i + j] += x * y
    return _strip(out)


def polyder(p):
    """Return the derivative of p."""
    n = len(p) - 1
    if n <= 0:
        return [0]
    return _strip([c * (n - i) for i, c in enumerate(p[:-1])])


def polyroots(p, tol=1e-15, maxiter=1000):
    """Return the complex roots of p, sorted by real part, then imaginary part.

    Durand-Kerner (Weierstrass) iteration from points on a circle, stopped
    when every relative correction is below tol, then a Newton polish of
    each root. For real coefficients the roots are made exactly real or
    exact conjugate pairs. See the module notes for the accuracy.
    """
    c = [complex(v) for v in p]
    while c and c[0] == 0:
        c.pop(0)
    if not c:
        raise ValueError("polyroots: zero polynomial")
    real_coeffs = all(v.imag == 0 for v in c)
    origin = 0
    while len(c) > 1 and c[-1] == 0:
        c.pop()
        origin += 1
    n = len(c) - 1
    a = [v / c[0] for v in c]
    if n == 0:
        z = []
    elif n == 1:
        z = [-a[1]]
    else:
        r = 2.0 * max(abs(a[k]) ** (1.0 / k) for k in range(1, n + 1))
        if r == 0:
            r = 1.0
        z = [r * cmath.exp(1j * (2 * math.pi * k / n + 0.4)) for k in range(n)]
        for _ in range(maxiter):
            worst = 0.0
            for i in range(n):
                den = 1.0 + 0j
                for j in range(n):
                    if j != i:
                        den *= z[i] - z[j]
                if den == 0:
                    z[i] += 1e-8 * (1 + abs(z[i])) * cmath.exp(1j * (i + 1))
                    worst = 1.0
                    continue
                d = polyval(a, z[i]) / den
                z[i] -= d
                worst = max(worst, abs(d) / (1.0 + abs(z[i])))
            if worst < tol:
                break
        dp = polyder(a)
        for i in range(n):
            zi = z[i]
            fz = abs(polyval(a, zi))
            for _ in range(5):
                der = polyval(dp, zi)
                if der == 0 or fz == 0:
                    break
                step = polyval(a, zi) / der
                if abs(step) > 1e-6 * (1.0 + abs(zi)):
                    break
                znew = zi - step
                fnew = abs(polyval(a, znew))
                if fnew >= fz:
                    break
                zi, fz = znew, fnew
            z[i] = zi
    z = z + [0j] * origin
    if real_coeffs:
        thr = 1e-9
        upper = [v for v in z if v.imag > thr * (1 + abs(v))]
        lower = [v for v in z if v.imag < -thr * (1 + abs(v))]
        reals = [complex(v.real, 0.0) for v in z if abs(v.imag) <= thr * (1 + abs(v))]
        # A cluster of close roots can leave more roots above the real axis
        # than below it (or the other way). The extra roots nearest to the
        # axis are then taken as real, so the output is closed under
        # conjugation.
        if len(upper) < len(lower):
            upper, lower = [v.conjugate() for v in lower], [v.conjugate() for v in upper]
        upper.sort(key=lambda v: v.imag)
        extra = len(upper) - len(lower)
        reals += [complex(v.real, 0.0) for v in upper[:extra]]
        upper = upper[extra:]
        out = list(reals)
        rest = list(lower)
        for u in upper:
            w = min(rest, key=lambda v: abs(v - u.conjugate()))
            rest.remove(w)
            re = (u.real + w.real) / 2
            im = (u.imag - w.imag) / 2
            out.append(complex(re, im))
            out.append(complex(re, -im))
        z = out
    return sorted(z, key=lambda v: (v.real, v.imag))


def _norm_inf(a):
    return max((sum(abs(v) for v in row) for row in a), default=0.0)


def expm(a):
    """Return e^A in floating point by scaling and squaring with a Taylor series.

    A is scaled by 2^-s so that its infinity norm is at most 1/2, the Taylor
    series of the scaled matrix is summed until a term is below 2^-60 of the
    sum, and the result is squared s times. Entries of the result are float
    (complex if A has complex entries).
    """
    n, m = _shape(a)
    if n != m:
        raise ValueError("expm: matrix is not square")
    cplx = any(isinstance(v, complex) for row in a for v in row)
    conv = complex if cplx else float
    x = [[conv(v) for v in row] for row in a]
    nrm = _norm_inf(x)
    s = 0
    while nrm > 0.5:
        nrm /= 2.0
        s += 1
    x = scale(conv(2.0 ** -s), x)
    e = [[conv(1.0 if i == j else 0.0) for j in range(n)] for i in range(n)]
    term = [row[:] for row in e]
    for k in range(1, 60):
        term = scale(1.0 / k, mul(term, x))
        e = add(e, term)
        tn = _norm_inf(term)
        if tn == 0.0 or tn <= 2.0 ** -60 * _norm_inf(e):
            break
    for _ in range(s):
        e = mul(e, e)
    return e


def mat_power(a, k):
    """Return A^k for an int k by repeated squaring (A^0 = I; k < 0 uses inv)."""
    n, m = _shape(a)
    if n != m:
        raise ValueError("mat_power: matrix is not square")
    if k < 0:
        a = inv(a)
        k = -k
    result = eye(n)
    base = [list(row) for row in a]
    while k:
        if k & 1:
            result = mul(result, base)
        k >>= 1
        if k:
            base = mul(base, base)
    return result


def is_symmetric(a, tol=0):
    """Return True if a is square and |a_ij - a_ji| <= tol for all i, j."""
    n, m = _shape(a)
    if n != m:
        return False
    return all(abs(a[i][j] - a[j][i]) <= tol for i in range(n) for j in range(i + 1, n))


def is_pos_def(a, margin=0):
    """Return True if a is symmetric and a - margin I is positive definite.

    With int and Fraction entries (and an exact margin) the test is exact:
    every leading principal minor of a - margin I must be positive
    (Sylvester's criterion), computed in Fraction. With float entries the
    matrix must be symmetric within 1e-12 times its largest entry, and the
    Cholesky factorization of a - margin I must have positive pivots.
    Complex entries are not accepted.
    """
    n, m = _shape(a)
    if n != m:
        return False
    if any(isinstance(v, complex) for row in a for v in row):
        raise ValueError("is_pos_def: complex entries are not accepted")
    if _all_exact(a) and _is_exact(margin):
        b = [[Fraction(a[i][j]) - (Fraction(margin) if i == j else 0) for j in range(n)] for i in range(n)]
        if not is_symmetric(b):
            return False
        return all(det([row[:k] for row in b[:k]]) > 0 for k in range(1, n + 1))
    b = [[float(a[i][j]) - (float(margin) if i == j else 0.0) for j in range(n)] for i in range(n)]
    big = max((abs(float(v)) for row in a for v in row), default=0.0)
    if not is_symmetric(b, 1e-12 * max(big, 1e-300)):
        return False
    low = [[0.0] * n for _ in range(n)]
    for j in range(n):
        d = b[j][j] - sum(low[j][k] ** 2 for k in range(j))
        if not d > 0.0:
            return False
        low[j][j] = math.sqrt(d)
        for i in range(j + 1, n):
            low[i][j] = (b[i][j] - sum(low[i][k] * low[j][k] for k in range(j))) / low[j][j]
    return True


def _self_test():
    a = [[0, 1], [-2, -3]]
    assert charpoly(a) == [1, 3, 2]
    assert det(a) == 2
    assert mul(inv(a), a) == eye(2)
    assert solve(a, [1, 0]) == [Fraction(-3, 2), Fraction(1)]
    r = polyroots([1, 3, 2])
    assert abs(r[0] + 2) < 1e-12 and abs(r[1] + 1) < 1e-12
    t = 0.7
    e = expm([[0.0, t], [-t, 0.0]])
    want = [[math.cos(t), math.sin(t)], [-math.sin(t), math.cos(t)]]
    assert max(abs(e[i][j] - want[i][j]) for i in range(2) for j in range(2)) < 1e-14
    assert is_pos_def([[Fraction(5, 4), Fraction(1, 4)], [Fraction(1, 4), Fraction(1, 4)]])
    assert not is_pos_def([[1, 2], [2, 1]])
    assert abs(norm2([[3.0, 0.0], [0.0, -4.0]]) - 4.0) < 1e-12
    return True


if __name__ == "__main__":
    _self_test()
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()
smith_predictor.py 128 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/smith-predictor/. The authors are listed in prov/R7T7GR.jsonl.

"""The Smith predictor (Smith, 1957) as a sampled controller.

The plant is P(s) = P0(s) e^(-theta s), with P0 = C (sI - A)^(-1) B. With the
sampling period h and a zero-order hold, P0 becomes x_(k+1) = Ad x_k + Bd u_k,
y_k = C x_k (exact for a held input), and the delay theta = d h becomes d
samples. The predictor runs a model (Am, Bm, Cm, dm) of the plant. At each
sample the controller sees

    y_f = y + (yhat0 - yhat_d),

where yhat0 is the output of the model without delay and yhat_d the output
of the model with its delay dm. With an exact model y = yhat_d, and the
controller sees the delay-free output yhat0.

The primary controller is a PI controller with the forward difference
integral: v = K e + I, then I = I + (K h / Ti) e.

All classes work in floating point. The order of the operations in
step() makes y_f equal yhat0 exactly when y equals yhat_d.
"""

import math
from collections import deque

from ctlmat import expm, matvec

__all__ = ["zoh", "PI", "SmithPredictor", "DelayedPlant", "run_loop"]


def zoh(A, B, h):
    """Return (Ad, Bd) of x' = A x + B u with u held over steps of length h.

    Uses the exponential of [[A, B], [0, 0]] h (one input)."""
    n = len(A)
    big = [[h * v for v in list(A[i]) + [B[i][0]]] for i in range(n)] + [[0.0] * (n + 1)]
    E = expm(big)
    return [row[:n] for row in E[:n]], [[E[i][n]] for i in range(n)]


class PI:
    """Sampled PI controller v = K e + I, I += K h/Ti e (Ti = None: P only)."""

    def __init__(self, K, Ti, h):
        self.K, self.bi, self.I = K, (0.0 if Ti is None else K * h / Ti), 0.0

    def step(self, e):
        v = self.K * e + self.I
        self.I += self.bi * e
        return v


class DelayedPlant:
    """x_(k+1) = Ad x_k + Bd (u_(k-d) + w_k), y_k = C x_k, from rest.

    w is a load disturbance at the plant input."""

    def __init__(self, Ad, Bd, C, d):
        self.Ad, self.Bd, self.C = Ad, Bd, C
        self.x = [0.0] * len(Ad)
        self.line = deque([0.0] * d)

    def output(self):
        return matvec([self.C], self.x)[0]

    def advance(self, u, w=0.0):
        self.line.append(u)
        ua = self.line.popleft() + w
        self.x = [sum(a * xi for a, xi in zip(row, self.x)) + b[0] * ua
                  for row, b in zip(self.Ad, self.Bd)]


class SmithPredictor:
    """The Smith predictor around a primary controller with a step(e) method."""

    def __init__(self, Am, Bm, Cm, dm, controller):
        self.Am, self.Bm, self.Cm = Am, Bm, Cm
        self.xm = [0.0] * len(Am)
        self.line = deque([0.0] * dm)     # past model outputs yhat0
        self.ctl = controller
        self.dm = dm

    def step(self, r, y):
        """Return u_k from the set point r_k and the measurement y_k."""
        yhat0 = matvec([self.Cm], self.xm)[0]
        yhat_d = self.line[0] if self.dm else yhat0
        yf = yhat0 + (y - yhat_d)  # @line L1
        e = r - yf  # @line L2
        u = self.ctl.step(e)  # @line L3
        self.xm = [sum(a * xi for a, xi in zip(row, self.xm)) + b[0] * u  # @line L4
                   for row, b in zip(self.Am, self.Bm)]
        if self.dm:
            self.line.append(yhat0)  # @line L5
            self.line.popleft()
        return u  # @line L6


def run_loop(plant, controller, n, r=1.0, w=None):
    """Run n samples. controller is a SmithPredictor or a plain controller
    with step(e). w(k) is the load at the plant input. Returns (ys, us)."""
    ys, us = [], []
    for k in range(n):
        y = plant.output()
        if isinstance(controller, SmithPredictor):
            u = controller.step(r, y)
        else:
            u = controller.step(r - y)
        plant.advance(u, 0.0 if w is None else w(k))
        ys.append(y)
        us.append(u)
    return ys, us


def _self_test():
    h = 0.1
    Ad, Bd = zoh([[-1.0]], [[1.0]], h)
    assert abs(Ad[0][0] - math.exp(-h)) < 1e-15
    plant = DelayedPlant(Ad, Bd, [1.0], 20)
    sp = SmithPredictor(Ad, Bd, [1.0], 20, PI(2.0, 1.0, h))
    ys, _ = run_loop(plant, sp, 400)
    assert abs(ys[-1] - 1) < 1e-6
    return True


if __name__ == "__main__":
    _self_test()
test_smith_predictor.py 131 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/smith-predictor/. The authors are listed in prov/R7T7GR.jsonl.

import math
import random

from ctlsim import lti, simulate
from smith_predictor import PI, DelayedPlant, SmithPredictor, run_loop, zoh

# Example: P0 = 1/(s + 1), theta = 2 s, h = 0.1 s (20 samples of delay),
# PI with K = 2 and Ti = 1, so that C P0 = 2/s and T0 = 2/(s + 2).
H = 0.1
AD, BD = zoh([[-1.0]], [[1.0]], H)
D = 20


def smith(Am=AD, Bm=BD, dm=D, K=2.0, Ti=1.0, h=H):
    return SmithPredictor(Am, Bm, [1.0], dm, PI(K, Ti, h))


def settling(ys, h, r=1.0, band=0.02):
    for k in range(len(ys) - 1, -1, -1):
        if abs(ys[k] - r) > band * abs(r):
            return (k + 1) * h
    return 0.0


def test_zoh_matches_simulation():
    A = [[0.0, 1.0], [-2.0, -3.0]]
    B = [[0.0], [1.0]]
    Ad, Bd = zoh(A, B, 0.5)
    _, xs, _ = simulate(lti(A, B), [1.0, -1.0], 0.0, 0.5, 0.005, control=lambda t, x: 0.7, hold=0.5)
    want = [sum(a * v for a, v in zip(row, [1.0, -1.0])) + b[0] * 0.7 for row, b in zip(Ad, Bd)]
    assert max(abs(p - q) for p, q in zip(xs[-1], want)) < 1e-10
    ad, bd = zoh([[-1.0]], [[1.0]], H)
    assert abs(ad[0][0] - math.exp(-H)) < 1e-15 and abs(bd[0][0] - (1 - math.exp(-H))) < 1e-15


def test_exact_model_gives_shifted_delay_free_response():
    free, ufree = run_loop(DelayedPlant(AD, BD, [1.0], 0), PI(2.0, 1.0, H), 300)
    ys, us = run_loop(DelayedPlant(AD, BD, [1.0], D), smith(), 300 + D)
    assert ys[:D] == [0.0] * D
    assert ys[D:] == free          # exact, not only close
    assert us[:300] == ufree


def test_shift_holds_for_random_plants():
    rng = random.Random(21)
    for _ in range(5):
        p1, p2 = rng.uniform(0.2, 3.0), rng.uniform(0.2, 3.0)
        A = [[0.0, 1.0], [-p1 * p2, -(p1 + p2)]]
        B = [[0.0], [p1 * p2]]
        C = [1.0, 0.0]
        h, d = 0.05, rng.randint(1, 40)
        K, Ti, r = rng.uniform(0.2, 3.0), rng.uniform(0.5, 5.0), rng.uniform(-2.0, 2.0)
        Ad, Bd = zoh(A, B, h)
        free, _ = run_loop(DelayedPlant(Ad, Bd, C, 0), PI(K, Ti, h), 200, r=r)
        sp = SmithPredictor(Ad, Bd, C, d, PI(K, Ti, h))
        ys, _ = run_loop(DelayedPlant(Ad, Bd, C, d), sp, 200 + d, r=r)
        assert ys[d:] == free


def test_settling_time_grows_by_the_delay_only():
    free, _ = run_loop(DelayedPlant(AD, BD, [1.0], 0), PI(2.0, 1.0, H), 400)
    ys, _ = run_loop(DelayedPlant(AD, BD, [1.0], D), smith(), 400)
    assert abs(settling(ys, H) - settling(free, H) - D * H) < 1e-9
    # Measured: overshoot 0.0021, settling time 3.7 s.
    assert max(ys) - 1 < 0.003 and abs(settling(ys, H) - 3.7) < 1e-9


def test_same_pi_without_predictor_diverges():
    ys, _ = run_loop(DelayedPlant(AD, BD, [1.0], D), PI(2.0, 1.0, H), 200)
    assert max(abs(y) for y in ys) > 100


def test_load_response_integral():
    # Continuous value: the integral of y for a unit load step is
    # theta - T0'(0) = 2 + 1/2 = 2.5. Measured on the sampled loop: 2.5.
    ys, _ = run_loop(DelayedPlant(AD, BD, [1.0], D), smith(), 1000, r=0.0, w=lambda k: 1.0)
    assert min(ys) > -1e-12
    assert abs(sum(ys) * H - 2.5) < 1e-6
    assert abs(ys[-1]) < 1e-9
    # General PI value Ti/K + P0(0) theta, here with the plant gain 3: 6.5.
    A3, B3 = zoh([[-1.0]], [[3.0]], H)
    sp = SmithPredictor(A3, B3, [1.0], D, PI(2.0, 1.0, H))
    ys, _ = run_loop(DelayedPlant(A3, B3, [1.0], D), sp, 1500, r=0.0, w=lambda k: 1.0)
    assert abs(sum(ys) * H - 6.5) < 1e-6


def test_model_mismatch():
    # Integral action removes the steady-state error whenever the loop
    # converges. Measured: delay errors of 10 percent converge, a model
    # delay of 3 s for a plant delay of 2 s does not.
    cases = [(22, 1.0, 1.0), (18, 1.0, 1.0), (20, 1.2, 1.0), (20, 0.8, 1.0), (20, 1.0, 1.5)]
    for dm, g, T in cases:
        Am, Bm = zoh([[-1.0 / T]], [[g / T]], H)
        ys, _ = run_loop(DelayedPlant(AD, BD, [1.0], D), smith(Am, Bm, dm), 1500)
        assert abs(ys[-1] - 1) < 1e-6
    ys, _ = run_loop(DelayedPlant(AD, BD, [1.0], D), smith(dm=30), 1500)
    assert max(abs(y) for y in ys) > 100


def small_gain_bound(delta, w_max=200.0, grid=20000):
    # max over w of |T0(jw)| |e^(-j w delta) - 1| with T0 = 2/(s + 2).
    best = 0.0
    for i in range(1, grid + 1):
        w = w_max * i / grid
        best = max(best, 2 / abs(2 + 1j * w) * abs(complex(math.cos(w * delta), -math.sin(w * delta)) - 1))
    return best


def test_small_gain_bound_for_delay_errors():
    # Measured: 0.3573 for |delta| = 0.2 s and 1.1990 for |delta| = 1 s. The
    # bound reaches 1 at |delta| = 0.7387 s.
    assert small_gain_bound(0.2) < 0.5
    assert small_gain_bound(-0.2) < 0.5
    assert small_gain_bound(0.73) < 1 < small_gain_bound(0.75)
    assert small_gain_bound(1.0) > 1


def test_unstable_plant_is_not_internally_stable():
    # P0 = 1/(s - 1), theta = 0.5 s, h = 0.05 s. The set-point response
    # converges, but a load step makes y grow like e^t.
    h, d = 0.05, 10
    Au, Bu = zoh([[1.0]], [[1.0]], h)
    sp = lambda: SmithPredictor(Au, Bu, [1.0], d, PI(3.0, 1.0, h))
    ys, _ = run_loop(DelayedPlant(Au, Bu, [1.0], d), sp(), 400)
    assert abs(ys[-1] - 1) < 1e-6
    ys, _ = run_loop(DelayedPlant(Au, Bu, [1.0], d), sp(), 400, r=0.0, w=lambda k: 0.01)
    assert ys[-1] > 1e5
    assert abs(ys[-1] / ys[-21] - math.e) < 1e-6

History

Otto J. M. Smith published the predictor in 1957 in Chemical Engineering Progress, in a short paper on the control of loops with dead time. A delay is hard to build with analog hardware, but in a digital controller it is only a queue of samples, so the predictor became easy to implement. In 1982 Garcia and Morari showed that the Smith predictor is a special case of internal model control, which gave a frame for its robustness analysis. Åström and Hägglund treat it in Sections 8.2 and 8.3 of their 2006 book on PID control.

References

  1. O. J. M. Smith, Closer control of loops with dead time, Chemical Engineering Progress 53(5), 217-219, 1957, the whole paper (the predictor structure)
  2. Karl Johan Åström and Tore Hägglund, Advanced PID Control, ISA, 2006, Sections 8.2 and 8.3 (the Smith predictor and its properties)
  3. Carlos E. Garcia and Manfred Morari, Internal model control. 1. A unifying review and some new results, Industrial and Engineering Chemistry Process Design and Development 21(2) (1982) 308-323, the whole paper (the internal model control structure, which contains the Smith predictor)

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