Algorithm Search⌘K

Algorithmintro

PID controller

Also called proportional-integral-derivative controller, three-term controller.

Sets the control to a weighted sum of the error, its integral and its filtered derivative, the most used controller in industry.

Time
O(k) worst
Space
O(1) extra
Where
k = the number of samples
Properties
deterministicnot exactonlineiterative
Origin
Nicolas Minorsky, 1922

A PID controller computes the control signal from the control error e=r−ye = r - y, the difference between the set point rr and the measured output yy. It adds three terms: one proportional to the error, one proportional to the integral of the error, and one proportional to the derivative of the error. The integral term removes the steady-state error for constant set points and loads. The derivative term adds phase lead and damping. A controller that is used on a real plant also needs a filter on the derivative, separate weights on the set point, limits on the output and a protection against integrator windup. This page gives the sampled algorithm with all of these parts, as computers run it, and proves its main properties.

In plain words

Think of a driver who keeps a car at a set speed. The driver presses the pedal more when the car is slow. That is the proportional part. If the car stays a little slow for a long time, for example on a long hill, the driver presses a little more each second until the error is gone. That is the integral part. If the speed starts to fall quickly, the driver reacts before the error becomes large. That is the derivative part. A PID controller does the same with three numbers that set how strong each part is. A computer reads the output at fixed times, updates the three parts and sends a new command each time.

The problem

Input. At each sampling instant tk=kht_k = k h, with the sampling period h>0h > 0 in seconds: the set point rkr_k and the measured output yky_k. The parameters are:

  • the gain K>0K > 0, the integral time Ti>0T_i > 0 and the derivative time Td≥0T_d \ge 0, in seconds;
  • the filter constant N>0N > 0, usually 5 to 20, so that the derivative filter has the time constant Td/NT_d/N;
  • the set-point weights bb and cc, usually in [0,1][0, 1];
  • the output limits umin⁡≤umax⁡u_{\min} \le u_{\max} and the tracking time Tt>0T_t > 0 for anti-windup.

Output. The control signal uku_k, held constant over [tk,tk+1)[t_k, t_{k+1}) by a zero-order hold.

The continuous controller. The algorithm approximates

U(s)=K(bR(s)−Y(s))+KTis(R(s)−Y(s))+KTds1+sTd/N(cR(s)−Y(s)).U(s) = K \left( b R(s) - Y(s) \right) + \frac{K}{T_i s} \left( R(s) - Y(s) \right) + \frac{K T_d s}{1 + s T_d/N} \left( c R(s) - Y(s) \right).

With b=c=1b = c = 1 and N→∞N \to \infty this is the ideal (or standard) form C(s)=K(1+1/(Tis)+Tds)C(s) = K (1 + 1/(T_i s) + T_d s) applied to E(s)E(s). Two other forms are common. The parallel form is C(s)=kp+ki/s+kdsC(s) = k_p + k_i/s + k_d s, with kp=Kk_p = K, ki=K/Tik_i = K/T_i and kd=KTdk_d = K T_d. The series (or interacting) form is C(s)=K′(1+1/(Ti′s))(1+Td′s)C(s) = K' (1 + 1/(T_i' s))(1 + T_d' s). Every series form has an ideal form. An ideal form has a series form with real parameters if and only if Ti≥4TdT_i \ge 4 T_d, because only then are the zeros of CC real. Old pneumatic controllers and many industrial products use the series form, so the same numbers mean different controllers in different products.

The algorithm

The integral is approximated by the forward difference and the filtered derivative by the backward difference, as Åström and Hägglund recommend. The output limits act on vv, and the difference u−vu - v is fed back into the integral with the gain h/Tth/T_t. This is the back-calculation form of anti-windup.

  1. PID-STEP(r, y) ▷ state: I, D, e_old; I = D = 0 at start
  2. 1once: b_i ← K h / T_i; a_r ← h / T_t; a_d ← T_d / (T_d + N h); b_d ← K T_d N / (T_d + N h)
  3. 2e ← r - y; e_d ← c r - y; if this is the first call then e_old ← e_d
  4. 3P ← K (b r - y)
  5. 4D ← a_d D + b_d (e_d - e_old)
  6. 5v ← P + I + D
  7. 6u ← min(max(v, u_min), u_max)
  8. 7I ← I + b_i e + a_r (u - v)
  9. 8e_old ← e_d
  10. 9return u

Line L1 runs once, when the parameters are set. With no integral action, set bi=0b_i = 0; with no tracking, set ar=0a_r = 0. Line L2 starts the derivative at rest, so the first sample causes no jump in DD. Line L4 is the backward difference of (Td/N)D′+D=KTd (ed)′(T_d/N) D' + D = K T_d\, (e^d)'; its pole ada_d is in [0,1)[0, 1) for every h>0h > 0. Line L7 runs after line L9 sends uu in a real controller, because the integral update is not needed for the current output. This keeps the time from the reading of yy to the output of uu short.

Example

Plant and tuning. Take the plant P(s)=1/(s+1)3P(s) = 1/(s + 1)^3, with time in seconds. Its ultimate gain is Ku=8K_u = 8 and its ultimate period is Tu=2π/3=3.62760T_u = 2\pi/\sqrt 3 = 3.62760 s. The classic Ziegler-Nichols PID rule gives K=0.6Ku=4.8K = 0.6 K_u = 4.8, Ti=Tu/2=1.81380T_i = T_u/2 = 1.81380 s and Td=Tu/8=0.45345T_d = T_u/8 = 0.45345 s. Take N=10N = 10 and h=0.05h = 0.05 s. Line L1 gives

coefficient formula value
bib_i Kh/TiK h/T_i 0.132319
ada_d Td/(Td+Nh)T_d/(T_d + N h) 0.475589
bdb_d KTdN/(Td+Nh)K T_d N/(T_d + N h) 22.8283

At the first sample y0=0y_0 = 0 and r=1r = 1, so P=4.8P = 4.8, D=0D = 0, I=0I = 0 and u0=4.8u_0 = 4.8. Then II becomes 0.1323190.132319.

Set-point weights. The plant is simulated with the classical Runge-Kutta method of order 4 and the step dt=0.01dt = 0.01 s, which divides hh. For a unit step in rr at t=0t = 0, with no limits and c=0c = 0:

bb overshoot peak time (s) 2 percent settling time (s) largest uu
1 0.5503 2.61 9.72 5.27
0.5 0.1826 3.00 7.90 3.17
0 0.0377 3.96 8.16 2.13

These numbers are measurements of this simulation. In all three runs yy is within 2⋅10−102 \cdot 10^{-10} of 1 at t=60t = 60 s, as Claim 3 of the proof says. A load step of −0.5-0.5 at the plant input at t=30t = 30 s gives the same change of yy for each bb, to 10−1210^{-12}, as Claim 2 says. The weight bb trades the speed of the set-point response for its overshoot, without any change to the loop.

Robustness of this tuning. With the ideal derivative the loop L=PCL = P C has the gain crossover at 1.37545 rad/s, a phase margin of 30.62 degrees and the peak sensitivity Ms=max⁡ω∣S(jω)∣=2.13M_s = \max_\omega |S(j\omega)| = 2.13. With N=10N = 10 the crossover moves to 1.40479 rad/s, the phase margin to 29.43 degrees and MsM_s to 2.24. Both are on the aggressive side of the usual design range of MsM_s from 1.2 to 2, which is a rule of thumb.

Limits. With ∣u∣≤2|u| \le 2 and no tracking (ar=0a_r = 0), the overshoot is 0.569. With tracking and Tt=TiTd=0.907T_t = \sqrt{T_i T_d} = 0.907 s, the overshoot is 0.162. The anti-windup page explains the difference.

Sampling period. Compare the sampled controller with the continuous controller on the same plant, over 0≤t≤200 \le t \le 20 s. The largest difference of yy at the sampling instants is 0.0487 for h=0.08h = 0.08, 0.0237 for h=0.04h = 0.04 and 0.0117 for h=0.02h = 0.02. The error halves when hh halves, as expected for a first order difference scheme. With h=0.2h = 0.2 the overshoot grows to 0.654 and with h=0.5h = 0.5 to 0.914, because the hold adds a delay of about h/2h/2 to the loop.

Correctness

The proofs are in the correctness proof.

  • Difference approximations (proved). Line L7 is the forward Euler step of I′=(K/Ti)eI' = (K/T_i) e, and line L4 is the backward Euler step of the derivative filter. The filter pole ad=Td/(Td+Nh)a_d = T_d/(T_d + N h) is in [0,1)[0, 1) for every h>0h > 0, so the discrete filter is asymptotically stable (Schur) for every sampling period. The forward difference would need h<2Td/Nh < 2 T_d/N.
  • Set-point weights (proved). Without limits, bb and cc change only the response to rr. The loop transfer function and the responses to load disturbances and noise do not depend on them. With c=0c = 0 a step in rr causes no derivative kick.
  • Zero steady-state error (proved). If the closed loop converges for a constant rr and the output is not held at a limit, then yy converges to rr. The claim needs integral action. It does not say that the loop converges; that depends on the plant and the tuning.
  • Back-calculation (proved). While the output is held at a limit with a constant error ee, and 0<h/Tt<20 < h/T_t < 2, the integral converges geometrically and vv tends to umax⁡+(Tt/Ti)Keu_{\max} + (T_t/T_i) K e. Without tracking the integral grows without bound.
  • Forms (proved). The series form converts to the ideal form, and an ideal form has a real series form if and only if Ti≥4TdT_i \ge 4 T_d.
  • Convergence as h→0h \to 0 (measured). The tests show the first order convergence of the sampled loop to the continuous loop on the example plant. The proof proves only that each update is a first order Euler step.
Proof: The sampled PID update has the stated filter, steady state and anti-windup propertiesfull

Notation is that of the page. The sampling period is h>0h > 0, the samples are rkr_k and yky_k, the error is ek=rk−yke_k = r_k - y_k and the derivative error is ekd=c rk−yke^d_k = c\, r_k - y_k. The parameters are K>0K > 0, Ti>0T_i > 0 (or no integral action), Td≥0T_d \ge 0, N>0N > 0 and Tt>0T_t > 0 (or no tracking). Lines L1 to L9 compute

bi=KhTi,ar=hTt,ad=TdTd+Nh,bd=KTdNTd+Nh,b_i = \frac{K h}{T_i}, \quad a_r = \frac{h}{T_t}, \quad a_d = \frac{T_d}{T_d + N h}, \quad b_d = \frac{K T_d N}{T_d + N h},
Pk=K(b rk−yk),Dk=adDk−1+bd(ekd−ek−1d),vk=Pk+Ik+Dk,uk=sat⁡(vk),P_k = K (b\, r_k - y_k), \quad D_k = a_d D_{k-1} + b_d (e^d_k - e^d_{k-1}), \quad v_k = P_k + I_k + D_k, \quad u_k = \operatorname{sat}(v_k),
Ik+1=Ik+biek+ar(uk−vk),I_{k+1} = I_k + b_i e_k + a_r (u_k - v_k),

with I0=D−1=0I_0 = D_{-1} = 0 and e−1d=e0de^d_{-1} = e^d_0. Here sat⁡\operatorname{sat} clips to [umin⁡,umax⁡][u_{\min}, u_{\max}]; with no limits, uk=vku_k = v_k.

Claim 1: the terms are Euler approximations of the continuous terms

The integral update is the forward Euler step of I′=(K/Ti)eI' = (K/T_i) e. The derivative update is the backward Euler step of (Td/N)D′+D=KTd (ed)′(T_d/N) D' + D = K T_d\, (e^d)'. The filter pole ada_d is in [0,1)[0, 1) for every h>0h > 0, so the derivative filter is a Schur (asymptotically stable) first order filter for every sampling period.

Proof. The forward Euler step of I′=(K/Ti)eI' = (K/T_i) e is Ik+1=Ik+h(K/Ti)ek=Ik+biekI_{k+1} = I_k + h (K/T_i) e_k = I_k + b_i e_k, which is line L7 when uk=vku_k = v_k. For the filter, replace D′D' and (ed)′(e^d)' at tkt_k by the backward differences (Dk−Dk−1)/h(D_k - D_{k-1})/h and (ekd−ek−1d)/h(e^d_k - e^d_{k-1})/h:

TdNh(Dk−Dk−1)+Dk=KTdh(ekd−ek−1d).\frac{T_d}{N h}(D_k - D_{k-1}) + D_k = \frac{K T_d}{h} (e^d_k - e^d_{k-1}).

Multiply by Nh/(Td+Nh)N h/(T_d + N h). This gives Dk=adDk−1+bd(ekd−ek−1d)D_k = a_d D_{k-1} + b_d (e^d_k - e^d_{k-1}), which is line L4. For Td>0T_d > 0, N>0N > 0 and h>0h > 0 the value ad=Td/(Td+Nh)a_d = T_d/(T_d + N h) is in (0,1)(0, 1), and for Td=0T_d = 0 it is 0. The homogeneous recursion Dk=adDk−1D_k = a_d D_{k-1} then decays like adka_d^k. □\square

The forward Euler step of the filter would give the pole 1−Nh/Td1 - N h/T_d, which is outside the unit disc when h>2Td/Nh > 2 T_d/N. This is why the backward difference is used.

Closed form on a ramp. If c=0c = 0 and yk=khy_k = k h, then ekd−ek−1d=−he^d_k - e^d_{k-1} = -h for k≥1k \ge 1, so Dk=adDk−1−bdhD_k = a_d D_{k-1} - b_d h with D0=0D_0 = 0. Since bdh/(1−ad)=KTdb_d h/(1 - a_d) = K T_d, induction gives Dk=−KTd(1−adk)D_k = -K T_d (1 - a_d^k). The continuous filter gives −KTd(1−e−Nt/Td)-K T_d (1 - e^{-N t/T_d}), and adka_d^k tends to e−Nt/Tde^{-N t/T_d} as h→0h \to 0 with kh=tk h = t. The test checks the discrete formula exactly in Fraction.

Claim 2: set-point weights change only the response to the set point

Without limits, uku_k is a linear function of the past and present rr and yy, and the part that acts on yy does not depend on bb or cc. So the loop transfer function, the response to a load disturbance and the response to measurement noise do not depend on bb and cc.

Proof. Without limits uk=vku_k = v_k, so the recursions are linear. Write each signal as the sum of the part caused by rr and the part caused by yy. The coefficient of yy in PkP_k is −K-K, in the update of DkD_k it is −bd-b_d (through ede^d), and in the update of Ik+1I_{k+1} it is −bi-b_i. None of these contains bb or cc. The parameters bb and cc multiply only rr. So the controller is U=CrR−CyYU = C_r R - C_y Y with CyC_y independent of bb and cc. The loop is closed through CyC_y only, and every transfer function from a signal that enters the loop (a load disturbance or noise) to yy or uu contains only CyC_y and the plant. By linearity, the response to rr and a load is the sum of the two separate responses, and only the first one changes with bb and cc. □\square

With c=0c = 0 the derivative acts on −y-y only, so a step in rr causes no impulse in DD. With c=1c = 1 a step of size Δ\Delta in rr adds bdΔb_d \Delta to uu at that sample.

Claim 3: zero steady-state error with integral action

Let TiT_i be finite and rk=rr_k = r constant. If the closed loop converges, so that yk→y∞y_k \to y_\infty, Ik→I∞I_k \to I_\infty and uk→u∞u_k \to u_\infty, and if u∞=v∞u_\infty = v_\infty (the output is not held at a limit, or there are no limits), then y∞=ry_\infty = r.

Proof. From line L7, Ik+1−Ik=biek+ar(uk−vk)I_{k+1} - I_k = b_i e_k + a_r (u_k - v_k). The left side tends to 0. The second term tends to ar(u∞−v∞)=0a_r (u_\infty - v_\infty) = 0. So bi(r−y∞)=0b_i (r - y_\infty) = 0, and bi=Kh/Ti≠0b_i = K h/T_i \ne 0, so y∞=ry_\infty = r. □\square

The claim does not say that the loop converges. That depends on the plant and the tuning, and it is the subject of the stability analysis of the loop, for example with the Nyquist stability criterion.

Claim 4: back-calculation keeps the integral bounded under saturation

Let the output be at the limit umax⁡u_{\max} for k≥k0k \ge k_0, with ek=ee_k = e and Pk+Dk=qP_k + D_k = q constant. If 0<h/Tt<20 < h/T_t < 2, then IkI_k converges geometrically with ratio 1−h/Tt1 - h/T_t, and vkv_k converges to

v∞=umax⁡+TtTiKe.v_\infty = u_{\max} + \frac{T_t}{T_i} K e.

Without tracking (ar=0a_r = 0), IkI_k grows by bieb_i e at each sample, without bound if e≠0e \ne 0.

Proof. With uk=umax⁡u_k = u_{\max} and vk=q+Ikv_k = q + I_k, line L7 reads Ik+1=(1−ar)Ik+bie+ar(umax⁡−q)I_{k+1} = (1 - a_r) I_k + b_i e + a_r (u_{\max} - q). This is an affine recursion with the factor 1−ar1 - a_r, and ∣1−ar∣<1|1 - a_r| < 1 exactly when 0<ar<20 < a_r < 2. Its fixed point satisfies arI∞=bie+ar(umax⁡−q)a_r I_\infty = b_i e + a_r (u_{\max} - q), so v∞=q+I∞=umax⁡+(bi/ar)e=umax⁡+(Tt/Ti)Kev_\infty = q + I_\infty = u_{\max} + (b_i/a_r) e = u_{\max} + (T_t/T_i) K e. With ar=0a_r = 0 the recursion is Ik+1=Ik+bieI_{k+1} = I_k + b_i e. □\square

So with tracking, vv stays within (Tt/Ti)K∣e∣(T_t/T_i) K |e| of the limit, and vv comes back below the limit as soon as ee changes sign, up to this offset. Without tracking, vv comes back only after the sum of the errors has undone the growth of II. This is the integrator windup effect.

Claim 5: the forms convert into each other

The series form K′(1+1/(Ti′s))(1+Td′s)K' (1 + 1/(T_i' s)) (1 + T_d' s) equals the ideal form K(1+1/(Tis)+Tds)K (1 + 1/(T_i s) + T_d s) with

K=K′Ti′+Td′Ti′,Ti=Ti′+Td′,Td=Ti′Td′Ti′+Td′.K = K' \frac{T_i' + T_d'}{T_i'}, \quad T_i = T_i' + T_d', \quad T_d = \frac{T_i' T_d'}{T_i' + T_d'}.

An ideal form has a series form with real Ti′,Td′>0T_i', T_d' > 0 if and only if Ti≥4TdT_i \ge 4 T_d. Then, with q=1−4Td/Tiq = \sqrt{1 - 4 T_d/T_i}, one series form is K′=K(1+q)/2K' = K (1 + q)/2, Ti′=Ti(1+q)/2T_i' = T_i (1 + q)/2 and Td′=Ti(1−q)/2T_d' = T_i (1 - q)/2. The parallel form kp+ki/s+kdsk_p + k_i/s + k_d s has kp=Kk_p = K, ki=K/Tik_i = K/T_i and kd=KTdk_d = K T_d.

Proof. Expand the series form: K′(1+1/(Ti′s))(1+Td′s)=K′(1+Td′/Ti′)+K′/(Ti′s)+K′Td′sK' (1 + 1/(T_i' s))(1 + T_d' s) = K' (1 + T_d'/T_i') + K'/(T_i' s) + K' T_d' s. Match the constant, the 1/s1/s and the ss terms with K+K/(Tis)+KTdsK + K/(T_i s) + K T_d s. The constant gives K=K′(Ti′+Td′)/Ti′K = K'(T_i' + T_d')/T_i'. The 1/s1/s term gives K/Ti=K′/Ti′K/T_i = K'/T_i', so Ti=Ti′K/K′=Ti′+Td′T_i = T_i' K/K' = T_i' + T_d'. The ss term gives KTd=K′Td′K T_d = K' T_d', so Td=Td′K′/K=Ti′Td′/(Ti′+Td′)T_d = T_d' K'/K = T_i' T_d'/(T_i' + T_d').

The ideal form is K(TiTds2+Tis+1)/(Tis)K (T_i T_d s^2 + T_i s + 1)/(T_i s). The series form has the real zeros −1/Ti′-1/T_i' and −1/Td′-1/T_d'. So a series form exists only if the numerator TiTds2+Tis+1T_i T_d s^2 + T_i s + 1 has real roots, that is Ti2−4TiTd≥0T_i^2 - 4 T_i T_d \ge 0, or Ti≥4TdT_i \ge 4 T_d. Conversely, if Ti≥4TdT_i \ge 4 T_d, the given Ti′T_i' and Td′T_d' are real and positive, Ti′+Td′=TiT_i' + T_d' = T_i, Ti′Td′=Ti2(1−q2)/4=TiTdT_i' T_d' = T_i^2 (1 - q^2)/4 = T_i T_d, so Ti′Td′/(Ti′+Td′)=TdT_i' T_d'/(T_i' + T_d') = T_d, and K′(Ti′+Td′)/Ti′=K(1+q)/2⋅2/(1+q)=KK'(T_i' + T_d')/T_i' = K (1 + q)/2 \cdot 2/(1 + q) = K. The parallel form follows by expanding the ideal form. □\square

The series form is unique up to swapping the roles of Ti′T_i' and Td′T_d' (with the gain changed to match); the formula returns the one with Ti′≥Td′T_i' \ge T_d'.

Cost

Line L1 runs once. Lines L3 to L8 use a fixed number of operations (at most 10 multiplications and 10 additions) and keep three numbers of state (II, DD and ek−1de^d_{k-1}). So kk samples cost O(k)O(k) time and O(1)O(1) space.

Complexity

One call does a fixed number of operations: at most 10 multiplications, 10 additions and 2 comparisons, and line L1 adds 6 operations once. The state is three numbers, II, DD and eolde_{\text{old}}. So kk samples cost O(k)O(k) time and O(1)O(1) extra space. This fixed cost per sample is one reason that PID control runs on the smallest processors. A closed-loop simulation costs the number of integration steps times the cost of one step of the plant model.

Properties

  • Online. Each output uses only the present and past samples.
  • Not exact. The algorithm is exact for its own difference equations, but it approximates the continuous controller with an error of order hh.
  • Linear inside the limits. Without saturation, the controller is a linear time-invariant discrete system of order 2 (one integrator state and one filter state).
  • Proper. The filter makes the derivative part proper. Its gain at high frequency is KNK N in place of infinity.
  • Fixed structure. Only two zeros and a pole at the origin can be placed. Plants with large delays, many oscillatory modes or strong coupling need other structures.

Variants and improvements

  • PI and PD. With Td=0T_d = 0 the controller is PI, the most common case in process control. Without integral action it is PD, used where the plant has an integrator, as in positioning.
  • Velocity form. Compute the change Δuk=uk−uk−1\Delta u_k = u_k - u_{k-1} and add it to the previous output. The integral is then implicit, and windup protection only needs a limit on the integrated output. This form is common in programmable controllers.
  • Second order filter. Filter the measurement with 1/(1+sTf)21/(1 + s T_f)^2 before the controller, in place of the filter on the derivative only. This gives a roll-off of the whole controller at high frequency.
  • Gain scheduling. Change KK, TiT_i and TdT_d with an operating variable. See gain scheduling.
  • Tuning. The parameters come from rules such as Ziegler-Nichols tuning, from an experiment with relay autotuning, from internal model control, or from loop shaping.
  • Other discretizations. The Tustin approximation of the whole controller is also used; see controller discretization.
  • Structures. PID controllers are the building blocks of cascade control, feedforward control and the Smith predictor.

When to use it

Use a PID controller for a single loop where the plant has dominant dynamics of first or second order, perhaps with a short delay, and where the aim is to hold the output at a set point against loads. Most flow, pressure, level, temperature and speed loops are of this kind. Use PI when the measurement is noisy or the plant is close to first order. Add the derivative when the plant has two lags of similar size or when the loop must be fast. Use another design when the delay is long compared with the time constants, when several loops interact strongly (see relative gain array), or when constraints must be handled in a planned way, as in model predictive control.

Pitfalls

  • Unfiltered derivative. The ideal derivative amplifies measurement noise without limit. Always filter it, and choose NN so that the noise in uu is acceptable.
  • Derivative kick. With c=1c = 1 a step in the set point gives an impulse in uu. Use c=0c = 0 unless the set point is smooth.
  • Windup. If the actuator saturates and nothing stops the integral, the integral grows during the saturation, and the overshoot afterwards can be large. Use tracking or conditional integration.
  • Forms differ. The same three numbers give different controllers in the ideal, series and parallel forms. Convert the parameters before moving a tuning to another product.
  • Sign of the action. If the plant gain is negative, the controller must use the reverse action. A wrong sign gives positive feedback.
  • Bumpless transfer. When the operator moves from manual to automatic, set the integral so that vv equals the present manual output. Otherwise the output jumps.
  • Sampling. The hold adds a delay of about h/2h/2, which reduces the phase margin by about ωch/2\omega_c h/2 radians at the crossover frequency ωc\omega_c. Take many samples per closed-loop rise time, and check the margins of the sampled loop. The example shows how the overshoot grows with hh.

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()
pid_controller.py 148 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/pid-controller/. The authors are listed in prov/M0FN5Q.jsonl.

"""A sampled PID controller with a derivative filter, set-point weights,
output limits and anti-windup by back-calculation.

The continuous controller, in the ideal (standard) form, is

    U(s) = K (b R - Y) + K/(T_i s) (R - Y) + K T_d s/(1 + s T_d/N) (c R - Y).

The sampled version follows Astrom and Hagglund (2006), Section 13.3:
- the integral term uses the forward difference;
- the filtered derivative uses the backward difference, which gives a
  filter pole a_d = T_d/(T_d + N h) in [0, 1) for every h > 0;
- the integral state also takes a correction (h/T_t)(u - v), where v is
  the computed output and u the output after the limits.

The class works in exact arithmetic when every parameter and signal is an
int or a Fraction and there are no limits (or the limits are exact).
Use Ti = None for no integral action and Td = 0 for no derivative action,
and Tt = None for no anti-windup.
"""

import cmath
import math

__all__ = [
    "PID", "ideal_to_parallel", "parallel_to_ideal", "series_to_ideal",
    "ideal_to_series", "pid_frequency_response",
]


class PID:
    """Sampled PID controller (pseudocode lines L1 to L9)."""

    def __init__(self, K, Ti=None, Td=0, N=10, h=1, b=1, c=0,
                 Tt=None, umin=None, umax=None):
        if h <= 0:
            raise ValueError("the sampling period h must be positive")
        if Ti is not None and Ti <= 0:
            raise ValueError("Ti must be positive or None")
        if Td < 0 or N <= 0:
            raise ValueError("Td must be at least 0 and N positive")
        if Tt is not None and Tt <= 0:
            raise ValueError("Tt must be positive or None")
        if umin is not None and umax is not None and umin > umax:
            raise ValueError("umin is above umax")
        self.K, self.b, self.c = K, b, c
        self.umin, self.umax = umin, umax
        self.bi = 0 if Ti is None else K * h / Ti  # @line L1
        self.ar = 0 if Tt is None else h / Tt
        if Td == 0:
            self.ad, self.bd = 0, 0
        else:
            self.ad = Td / (Td + N * h)
            self.bd = K * Td * N / (Td + N * h)
        self.I = 0
        self.D = 0
        self.ed_old = None

    def _limit(self, v):
        if self.umax is not None and v > self.umax:
            return self.umax
        if self.umin is not None and v < self.umin:
            return self.umin
        return v

    def step(self, r, y, uff=0):
        """Return the output u for the set point r and the measurement y.

        uff is an optional feedforward term added before the limits.
        At the first call the derivative has no past value, so it starts
        at 0 (no derivative kick at start up).
        """
        ed = self.c * r - y  # @line L2
        if self.ed_old is None:
            self.ed_old = ed
        P = self.K * (self.b * r - y)  # @line L3
        self.D = self.ad * self.D + self.bd * (ed - self.ed_old)  # @line L4
        v = P + self.I + self.D + uff  # @line L5
        u = self._limit(v)  # @line L6
        self.I = self.I + self.bi * (r - y) + self.ar * (u - v)  # @line L7
        self.ed_old = ed  # @line L8
        return u  # @line L9

    def reset(self, I=0, D=0):
        """Set the integral and derivative states (for bumpless transfer)."""
        self.I, self.D, self.ed_old = I, D, None


def ideal_to_parallel(K, Ti, Td):
    """Return (kp, ki, kd) with kp + ki/s + kd s = K (1 + 1/(Ti s) + Td s)."""
    return K, K / Ti, K * Td


def parallel_to_ideal(kp, ki, kd):
    """Inverse of ideal_to_parallel; needs kp > 0 and ki > 0."""
    if kp <= 0 or ki <= 0:
        raise ValueError("the ideal form needs kp > 0 and ki > 0")
    return kp, kp / ki, kd / kp


def series_to_ideal(Ks, Tis, Tds):
    """Return (K, Ti, Td) with K (1 + 1/(Ti s) + Td s) equal to
    Ks (1 + 1/(Tis s)) (1 + Tds s)."""
    return Ks * (Tis + Tds) / Tis, Tis + Tds, Tis * Tds / (Tis + Tds)


def ideal_to_series(K, Ti, Td):
    """Return the series form of an ideal PID.

    It exists if and only if Ti >= 4 Td, because the zeros of the ideal
    form are real only then. The result is in floating point (a square
    root).
    """
    if Ti < 4 * Td:
        raise ValueError("no series form: the zeros are complex (Ti < 4 Td)")
    q = math.sqrt(1 - 4 * Td / Ti)
    return K * (1 + q) / 2, Ti * (1 + q) / 2, Ti * (1 - q) / 2


def pid_frequency_response(K, Ti, Td, N, omega, b=1, c=1):
    """Return C(j omega) of the continuous controller from e = r - y.

    N = None gives the ideal derivative K Td s. b and c weight the set
    point; C is the transfer function from the error when b = c = 1.
    """
    s = 1j * omega
    ci = 0 if Ti is None else 1 / (Ti * s)
    if Td == 0:
        cd = 0
    elif N is None:
        cd = Td * s
    else:
        cd = Td * s / (1 + s * Td / N)
    return complex(K * (1 + ci + cd))


def _self_test():
    k, ti, td = ideal_to_series(*series_to_ideal(2.0, 4.0, 1.0))
    assert abs(k - 2.0) < 1e-12 and abs(ti - 4.0) < 1e-12 and abs(td - 1.0) < 1e-12
    c = pid_frequency_response(1.0, 1.0, 0.0, None, 1.0)
    assert abs(c - (1 - 1j)) < 1e-15 and abs(cmath.phase(c) + math.pi / 4) < 1e-15
    return True


if __name__ == "__main__":
    _self_test()
test_pid_controller.py 183 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/pid-controller/. The authors are listed in prov/M0FN5Q.jsonl.

import cmath
import math
import random
from fractions import Fraction as Fr

import pytest

from ctlmat import polyval
from ctlsim import simulate
from pid_controller import (PID, ideal_to_parallel, ideal_to_series,
                            parallel_to_ideal, pid_frequency_response,
                            series_to_ideal)

# Plant P(s) = 1/(s + 1)^3 as a chain of three first order lags, y = x3.
# Simulation: RK4 with dt = 0.01 s, zero-order hold over h. Tolerances are
# given at each assert.

TU = 2 * math.pi / math.sqrt(3)   # ultimate period of 1/(s + 1)^3
ZN = dict(K=4.8, Ti=TU / 2, Td=TU / 8, N=10)


def plant(t, x, u):
    return [-x[0] + u, -x[1] + x[0], -x[2] + x[1]]


def run(pid, t1, h, dt=0.01, r=lambda t: 1.0, load=lambda t: 0.0):
    n = round(t1 / dt)
    assert abs(n * dt - t1) < 1e-9 and abs(round(h / dt) * dt - h) < 1e-12

    def ctl(t, x):
        return pid.step(r(t), x[2]) + load(t)

    ts, xs, us = simulate(plant, [0.0, 0.0, 0.0], 0.0, t1, dt, control=ctl, hold=h)
    assert len(ts) == n + 1
    return ts, [x[2] for x in xs], us


def test_integral_and_proportional_terms_are_exact():
    K, Ti, h = Fr(3, 2), Fr(5, 2), Fr(1, 10)
    pid = PID(K, Ti=Ti, Td=0, h=h, b=Fr(1, 2))
    r, y = Fr(2), Fr(1, 3)
    for k in range(25):
        u = pid.step(r, y)
        assert u == K * (Fr(1, 2) * r - y) + k * K * h / Ti * (r - y)


def test_derivative_filter_is_exact_on_a_ramp():
    # y_k = k h, r = 0: D_k = -K Td (1 - a_d^k) with a_d = Td/(Td + N h).
    K, Td, N, h = Fr(2), Fr(1, 2), Fr(5), Fr(1, 20)
    pid = PID(K, Ti=None, Td=Td, N=N, h=h, b=0)
    ad = Td / (Td + N * h)
    for k in range(30):
        u = pid.step(0, k * h)
        assert u == -K * k * h - K * Td * (1 - ad ** k)
    assert ad == Fr(2, 3)


def test_no_derivative_kick_with_c_zero():
    pid0 = PID(1.0, Ti=None, Td=1.0, N=10, h=0.1, c=0)
    pid1 = PID(1.0, Ti=None, Td=1.0, N=10, h=0.1, c=1)
    for p in (pid0, pid1):
        p.step(0.0, 0.0)
    u0, u1 = pid0.step(1.0, 0.0), pid1.step(1.0, 0.0)
    assert u0 == 1.0
    # c = 1: the kick is bd = K Td N/(Td + N h) = 5 on top of K r = 1
    assert abs(u1 - 6.0) < 1e-12


def test_closed_loop_step_has_zero_steady_state_error():
    ts, ys, us = run(PID(h=0.05, b=1, **ZN), t1=60.0, h=0.05)
    assert abs(ys[-1] - 1.0) < 1e-8
    over = max(ys) - 1.0
    assert 0.50 < over < 0.60          # measured 0.5503 with h = 0.05, N = 10
    assert abs(us[-1] - 1.0) < 1e-7    # P(0) = 1, so u tends to r


def test_set_point_weight_changes_only_the_set_point_response():
    load = lambda t: -0.5 if t >= 30.0 else 0.0
    ys_by_b = {}
    for b in (0.0, 0.5, 1.0):
        _, y_load, _ = run(PID(h=0.05, b=b, **ZN), t1=60.0, h=0.05, load=load)
        _, y_free, _ = run(PID(h=0.05, b=b, **ZN), t1=60.0, h=0.05)
        ys_by_b[b] = (y_load, y_free)
    base = [a - f for a, f in zip(*ys_by_b[1.0])]
    for b in (0.0, 0.5):
        diff = [a - f for a, f in zip(*ys_by_b[b])]
        assert max(abs(p - q) for p, q in zip(diff, base)) < 1e-12
    over = {b: max(ys_by_b[b][1]) - 1.0 for b in ys_by_b}
    assert over[0.0] < over[0.5] < over[1.0]
    assert over[0.0] < 0.05            # measured 0.0377


def continuous_pid_error(h, t1=20.0, dt=0.005):
    """Max |y_h(t_k) - y(t_k)| over the sampling instants, against the
    continuous PID (states x1, x2, x3, I, xf), both with RK4 and step dt."""
    K, Ti, Td, N = ZN["K"], ZN["Ti"], ZN["Td"], ZN["N"]

    def f(t, x, _):
        y = x[2]
        e = 1.0 - y
        u = K * (1.0 - y) + x[3] - K * N * (y - x[4])
        return [-x[0] + u, -x[1] + x[0], -x[2] + x[1], K / Ti * e, N / Td * (y - x[4])]

    _, xs, _ = simulate(f, [0.0] * 5, 0.0, t1, dt)
    pid = PID(h=h, b=1, **ZN)
    _, xs_h, _ = simulate(plant, [0.0] * 3, 0.0, t1, dt,
                          control=lambda t, x: pid.step(1.0, x[2]), hold=h)
    r = round(h / dt)
    return max(abs(xs[k][2] - xs_h[k][2]) for k in range(0, len(xs), r))


def test_sampled_pid_converges_to_the_continuous_pid():
    errs = [continuous_pid_error(h) for h in (0.08, 0.04, 0.02)]
    # first order in h: each halving should cut the error by about 2
    assert errs[1] < 0.65 * errs[0] and errs[2] < 0.65 * errs[1]
    assert errs[2] < 0.05


def test_back_calculation_reduces_overshoot_under_saturation():
    lim = dict(umin=-2.0, umax=2.0)
    _, y_sat, u_sat = run(PID(h=0.05, b=1, **ZN, **lim), t1=40.0, h=0.05)
    tt = math.sqrt(ZN["Ti"] * ZN["Td"])
    _, y_aw, u_aw = run(PID(h=0.05, b=1, Tt=tt, **ZN, **lim), t1=40.0, h=0.05)
    assert max(u_sat) == 2.0 and max(u_aw) == 2.0
    assert min(u_sat) >= -2.0 and min(u_aw) >= -2.0
    assert max(y_sat) - 1.0 > 0.5      # measured 0.569
    assert max(y_aw) - 1.0 < 0.2       # measured 0.162
    assert abs(y_aw[-1] - 1.0) < 1e-6


def test_back_calculation_fixed_point_under_saturation():
    # With e and u held, I converges to the value where
    # K h e / Ti + (h / Tt)(u - v) = 0, that is v = umax + Tt K e / Ti.
    K, Ti, Tt, h = 2.0, 4.0, 0.5, 0.01
    pid = PID(K, Ti=Ti, Td=0, h=h, Tt=Tt, umax=1.0)
    for _ in range(3000):
        u = pid.step(3.0, 0.0)
        v = K * 3.0 + pid.I
    assert u == 1.0
    assert abs(v - (1.0 + Tt * K * 3.0 / Ti)) < 1e-9


def test_form_conversions():
    rng = random.Random(7)
    for _ in range(200):
        Ks = Fr(rng.randint(1, 50), rng.randint(1, 9))
        Tis = Fr(rng.randint(1, 50), rng.randint(1, 9))
        Tds = Fr(rng.randint(1, 50), rng.randint(1, 9))
        K, Ti, Td = series_to_ideal(Ks, Tis, Tds)
        assert Ti >= 4 * Td
        assert parallel_to_ideal(*ideal_to_parallel(K, Ti, Td)) == (K, Ti, Td)
        k2, ti2, td2 = ideal_to_series(K, Ti, Td)
        # the series form is unique up to swapping Tis and Tds with
        # the matching gain; ideal_to_series returns Tis >= Tds
        hi, lo = max(Tis, Tds), min(Tis, Tds)
        assert abs(ti2 - hi) < 1e-9 * hi and abs(td2 - lo) < 1e-9 * hi
        s = 0.3j + 0.1
        c_ser = complex(Ks) * (1 + 1 / (complex(Tis) * s)) * (1 + complex(Tds) * s)
        c_id = complex(K) * (1 + 1 / (complex(Ti) * s) + complex(Td) * s)
        assert abs(c_ser - c_id) < 1e-9 * abs(c_id)
    with pytest.raises(ValueError):
        ideal_to_series(1.0, 1.0, 0.3)


def test_margins_of_the_ziegler_nichols_loop():
    # Ideal derivative: phase margin 30.62 degrees at 1.37545 rad/s.
    def loop(w, N):
        p = 1 / polyval([1, 3, 3, 1], 1j * w)
        return p * pid_frequency_response(ZN["K"], ZN["Ti"], ZN["Td"], N, w)

    for N, w_want, pm_want in ((None, 1.37545, 30.619), (10, 1.40479, 29.428)):
        lo, hi = 0.5, 3.0
        for _ in range(80):
            mid = (lo + hi) / 2
            if abs(loop(mid, N)) > 1:
                lo = mid
            else:
                hi = mid
        pm = 180 + math.degrees(cmath.phase(loop(lo, N)))
        assert abs(lo - w_want) < 1e-5 and abs(pm - pm_want) < 1e-3

History

Nicolas Minorsky studied the automatic steering of ships and published in 1922 an analysis that recommended a steering law with proportional, integral and derivative terms. Pneumatic process controllers with proportional and reset (integral) action came into use in the 1930s, and the derivative action was added under the name pre-act. Ziegler and Nichols used these terms in 1942, when they gave the first tuning rules. Electronic analog controllers and then computer controllers replaced most of the pneumatic ones. The computer made it easy to add the filter, the set-point weights, anti-windup and automatic tuning. Åström and Hägglund describe this development and the modern form of the algorithm.

References

  1. Nicolas Minorsky, Directional stability of automatically steered bodies, Journal of the American Society of Naval Engineers 34(2) (1922) 280-309, the whole paper (the steering law with proportional, integral and derivative terms)
  2. Karl Johan Åström and Tore Hägglund, Advanced PID Control, ISA, 2006, Chapter 3, PID Control (Sections 3.2 to 3.5, the forms, the derivative filter, set-point weighting and windup) and Section 13.3, Computer implementations
  3. Karl Johan Åström and Richard M. Murray, Feedback Systems, second edition, Princeton University Press, 2021, Chapter 11, PID Control (the sections on integral windup and on implementation)

Where this leads

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