Algorithm Search⌘K

Algorithmintro

Ziegler-Nichols tuning

Also called Ziegler-Nichols method, ultimate gain method.

Sets PID gains by rules from the ultimate gain and period found at the edge of oscillation, or from a step response.

Time
O(g n + k) worst
Space
O(g) extra
Where
g = the number of frequency grid points; k = the number of samples of the step response; n = the degree of the plant
Properties
deterministicnot exactofflineiterative
Origin
John G. Ziegler, Nathaniel B. Nichols, 1942

Ziegler-Nichols tuning sets the three parameters of a PID controller from two numbers that one simple experiment gives. In the ultimate cycle method a P controller is put on the plant and its gain is raised until the loop oscillates with a constant amplitude. The gain at that point is the ultimate gain KuK_u and the period of the oscillation is the ultimate period TuT_u. In the step response method the plant gets a step input in open loop, and a tangent at the steepest point of the response gives a slope and an apparent delay. A table then gives KK, TiT_i and TdT_d. The rules are rules of thumb that aim at a decay ratio of one quarter. This page computes the ultimate point from a model, fits the tangent to a sampled response and applies both tables.

In plain words

Turn up the gain of a simple controller until the loop starts to swing with a steady size. Note that gain and the time of one swing. These two numbers tell how much gain the plant takes and how fast it is. The rules then say: use a bit more than half that gain, and set the integral and derivative times to fixed parts of the swing time. The other method kicks the plant once and draws a straight line along the steepest part of the response. Where that line starts tells the delay, and how steep it is tells the gain. Both methods are fast and need no model. The loop they give is often too lively, so people treat the result as a first try and then adjust it.

The problem

Input for the ultimate cycle method. A plant P(s)=n(s)d(s)e−θsP(s) = \frac{n(s)}{d(s)} e^{-\theta s} with real polynomials, deg⁡n<deg⁡d\deg n < \deg d, a delay θ≥0\theta \ge 0 and a positive gain at low frequency. On a real plant the input is the experiment itself.

Input for the step response method. Samples y0,…,yk−1y_0, \dots, y_{k-1} of the response to an input step of size Δu\Delta u at t=0t = 0, from rest, with a uniform time step Δt\Delta t.

Output. The parameters of the ideal PID form C(s)=K(1+1/(Tis)+Tds)C(s) = K (1 + 1/(T_i s) + T_d s), or of its P or PI part.

The ultimate point. It is the smallest ωu>0\omega_u > 0 with arg⁡P(jωu)=−180\arg P(j\omega_u) = -180 degrees, and

Ku=1∣P(jωu)∣,Tu=2πωu.K_u = \frac{1}{|P(j\omega_u)|}, \qquad T_u = \frac{2\pi}{\omega_u}.

At K=KuK = K_u the closed loop with a P controller has the poles ±jωu\pm j\omega_u, so it oscillates with the period TuT_u. So KuK_u is the gain margin of the plant under unit proportional feedback. A plant whose phase stays above −180-180 degrees, such as 1/(s+1)21/(s + 1)^2, has no finite ultimate gain, and the method does not apply.

The tables. For the ultimate cycle method:

controller KK TiT_i TdT_d
P 0.5Ku0.5 K_u
PI 0.45Ku0.45 K_u Tu/1.2T_u/1.2
PID 0.6Ku0.6 K_u Tu/2T_u/2 Tu/8T_u/8

For the step response method, with the largest slope RR per unit input, the apparent delay LL and a=RLa = R L:

controller KK TiT_i TdT_d
P 1/a1/a
PI 0.9/a0.9/a L/0.3L/0.3
PID 1.2/a1.2/a 2L2 L L/2L/2

Ziegler and Nichols gave the PI integral time as a reset rate of 0.3/L0.3/L repeats per minute, which is Ti=3.33LT_i = 3.33 L. Many books round it to 3L3 L. The two tables agree on the PID times if Tu=4LT_u = 4 L.

The algorithm

  1. ZN-ULTIMATE(n, d, theta, rule)
  2. 1phi_i ← continuous phase of P(j w_i) on a log grid w_0 < w_1 < ... < w_g
  3. 2i ← the first index with phi_i ≤ -pi; if there is none then fail
  4. 3w_u ← bisection of phi(w) = -pi on [w_(i-1), w_i]
  5. 4K_u ← 1/|P(j w_u)|; T_u ← 2 pi / w_u
  6. 5return (K, T_i, T_d) from the ultimate cycle table
  7. ZN-STEP(t, y, du, rule)
  8. 6j ← the sample with the largest slope R = (y_(j+1) - y_(j-1)) / (2 dt du)
  9. 7L ← t_j - (y_j - y_0) / (R du); a ← R L
  10. 8return (K, T_i, T_d) from the step response table

Line L1 starts the phase at −90-90 degrees per net pole at the origin. It unwraps the phase of the rational part from one grid point to the next and adds −ωθ-\omega\theta for the delay. The grid has 4000 points from 10−610^{-6} to 10310^3 rad/s. Line L3 halves the bracket until it is 10−1510^{-15} of its upper end. Line L6 uses central differences, so the first and the last sample cannot be the steepest point. If the steepest point is at the end of the record, the record is too short and the code stops with an error.

Example

A third order lag. Take P(s)=1/(s+1)3P(s) = 1/(s + 1)^3. Its phase is −3arctan⁡ω-3 \arctan \omega, which is −180-180 degrees at ωu=tan⁡60°=3\omega_u = \tan 60° = \sqrt 3. Its gain there is (1+3)−3/2=1/8(1 + 3)^{-3/2} = 1/8. So Ku=8K_u = 8 and Tu=2π/3=3.62760T_u = 2\pi/\sqrt 3 = 3.62760 s. Indeed (s+1)3+8=(s+3)(s2+3)(s + 1)^3 + 8 = (s + 3)(s^2 + 3), with the roots ±j3\pm j\sqrt 3. The code gives Ku=8K_u = 8 and ωu=3\omega_u = \sqrt 3 to 15 digits.

The unit step response is y(t)=1−e−t(1+t+t2/2)y(t) = 1 - e^{-t}(1 + t + t^2/2), with the slope y′(t)=t2e−t/2y'(t) = t^2 e^{-t}/2. The slope is largest at t=2t = 2. So R=2e−2=0.270671R = 2 e^{-2} = 0.270671, L=(9−e2)/2=0.805472L = (9 - e^2)/2 = 0.805472 s and a=9e−2−1=0.218018a = 9 e^{-2} - 1 = 0.218018. From a response sampled with Δt=0.01\Delta t = 0.01 s the code gives L=0.805462L = 0.805462 s. Here 4L=3.224 L = 3.22 s, a little shorter than TuT_u.

The loops. The table shows the four tunings and the closed loops that they give. The derivative has the filter constant N=20N = 20, all terms act on the error, and the loop is simulated with the classical Runge-Kutta method of order 4 and the step 0.01 s up to t=80t = 80 s. The decay ratio is the second peak above the final value divided by the first. The load response is the response of yy to a unit step at the plant input.

tuning KK TiT_i (s) TdT_d (s) set-point overshoot set-point decay ratio load peak load decay ratio
ultimate PI 3.6 3.0230 0.561 0.578 0.299 0.409
ultimate PID 4.8 1.8138 0.4534 0.523 0.138 0.188 0.097
step PI 4.1281 2.6849 0.684 0.755 0.276 0.525
step PID 5.5041 1.6109 0.4027 0.645 0.254 0.174 0.188

These are measurements of this simulation. All four loops are asymptotically stable, and the overshoot of the set-point response is above 50 percent in every case. The PI tunings decay slowly. The ultimate P controller, K=4K = 4, gives the final value 4/5=0.84/5 = 0.8, so the steady-state error is 0.2, and its decay ratio is 0.39. The PID controller page shows that the ultimate PID tuning has a phase margin of about 30 degrees and the peak sensitivity Ms=2.13M_s = 2.13.

Delays. For P(s)=e−θs/(s+1)P(s) = e^{-\theta s}/(s + 1), the ultimate frequency solves arctan⁡ωu+ωuθ=π\arctan \omega_u + \omega_u \theta = \pi, and Ku=1+ωu2K_u = \sqrt{1 + \omega_u^2}. With θ=1\theta = 1 s the code gives ωu=2.02876\omega_u = 2.02876 rad/s, Tu=3.09706T_u = 3.09706 s and Ku=2.26183K_u = 2.26183. With θ=0.1\theta = 0.1 s it gives ωu=16.3199\omega_u = 16.3199 rad/s and Ku=16.3506K_u = 16.3506. The ultimate gain grows as the delay gets shorter, and for θ→0\theta \to 0 a first order lag has no finite ultimate gain.

Correctness

The proofs are in the correctness proof.

  • The ultimate point (theorem). At K=KuK = K_u the closed loop with a P controller has the poles ±jωu\pm j\omega_u. Conversely, a closed-loop pole on the imaginary axis can only occur at a frequency where the phase is −180-180 degrees, with K=1/∣P∣K = 1/|P| there.
  • Below the ultimate gain (theorem). If the plant has no poles in the open right half plane, at most one integrator, and a gain ∣P(jω)∣|P(j\omega)| that falls strictly with ω\omega, then every gain 0<K<Ku0 < K < K_u gives an asymptotically stable closed loop. The proof uses the Nyquist stability criterion.
  • Above the ultimate gain (measurement). For random products of 3 to 5 real lags, the tests find a closed-loop pole in the right half plane at K=1.1KuK = 1.1 K_u.
  • The search (theorem). If the grid is fine enough that the phase moves less than 180 degrees between neighbours and crosses −180-180 degrees only once inside each grid interval, lines L1 to L3 converge to ωu\omega_u.
  • The tangent fit (theorem). At the inflection point the time t−(y−y0)/y′t - (y - y_0)/y' has a zero derivative. So the fit has an error of order Δt2\Delta t^2.
  • The tables (rule of thumb). Ziegler and Nichols chose the factors from many tests, to get a decay ratio near one quarter on typical process plants. They do not follow from a theorem. The example shows that the decay ratio can be far from one quarter.
Proof: The ultimate point search and the tangent fit compute what the Ziegler-Nichols rules needfull

Notation is that of the page. The plant is P(s)=n(s)d(s)e−θsP(s) = \frac{n(s)}{d(s)} e^{-\theta s} with real polynomials nn and dd, deg⁡n<deg⁡d\deg n < \deg d, and a delay θ≥0\theta \ge 0. The P controller is a gain K>0K > 0, so the loop transfer function is L=KPL = K P and the closed-loop poles are the roots of d(s)+Kn(s)e−θs=0d(s) + K n(s) e^{-\theta s} = 0. The ultimate frequency ωu\omega_u is the smallest ω>0\omega > 0 where the continuous phase of P(jω)P(j\omega) is −π-\pi. Then Ku=1/∣P(jωu)∣K_u = 1/|P(j\omega_u)| and Tu=2π/ωuT_u = 2\pi/\omega_u.

The rules themselves (lines L5 and L8) are rules of thumb. Nothing below proves that they give a good loop. The claims prove that lines L1 to L4 and L6 to L7 compute the quantities that the rules take as input.

Claim 1: at K=KuK = K_u the closed loop has the poles ±jωu\pm j\omega_u

If arg⁡P(jωu)=−π\arg P(j\omega_u) = -\pi (modulo 2π2\pi) and Ku=1/∣P(jωu)∣K_u = 1/|P(j\omega_u)|, then s=jωus = j\omega_u and s=−jωus = -j\omega_u are roots of d(s)+Kun(s)e−θsd(s) + K_u n(s) e^{-\theta s}. Conversely, if jωj\omega with ω>0\omega > 0 is a root for some K>0K > 0, then arg⁡P(jω)=−π\arg P(j\omega) = -\pi modulo 2π2\pi and K=1/∣P(jω)∣K = 1/|P(j\omega)|.

Proof. By the assumptions P(jωu)=∣P(jωu)∣e−jπ=−1/KuP(j\omega_u) = |P(j\omega_u)| e^{-j\pi} = -1/K_u. So 1+KuP(jωu)=01 + K_u P(j\omega_u) = 0. Multiply by d(jωu)d(j\omega_u), which is not 0 because P(jωu)P(j\omega_u) is finite: d(jωu)+Kun(jωu)e−jωuθ=0d(j\omega_u) + K_u n(j\omega_u) e^{-j\omega_u \theta} = 0. The coefficients are real, so the conjugate −jωu-j\omega_u is a root too. For the converse, a root jωj\omega with d(jω)≠0d(j\omega) \ne 0 gives KP(jω)=−1K P(j\omega) = -1, so P(jω)P(j\omega) is a negative real number with modulus 1/K1/K. If d(jω)=0d(j\omega) = 0, the equation gives n(jω)=0n(j\omega) = 0 too, and PP has a common factor that cancels; remove it first. □\square

So the gain KuK_u puts a pair of closed-loop poles on the imaginary axis, and the loop then oscillates with the period TuT_u. This is the experiment that Ziegler and Nichols did by hand.

Claim 2: for 0<K<Ku0 < K < K_u the closed loop is asymptotically stable, under a monotone gain

Assume that PP has no poles in the open right half plane, that its only possible pole on the imaginary axis is a simple pole at the origin, that the low-frequency gain is positive, and that ∣P(jω)∣|P(j\omega)| is strictly decreasing for ω>0\omega > 0. Then the closed loop with the gain KK is asymptotically stable for every 0<K<Ku0 < K < K_u.

Proof. Take 0<K<Ku0 < K < K_u. By the Nyquist stability criterion, for an open loop with no poles in the open right half plane, the closed loop is asymptotically stable if the Nyquist curve of KPK P does not pass through or encircle −1-1. (With a delay the criterion still holds, because PP is analytic in the right half plane away from the origin and tends to 0 as ∣s∣→∞|s| \to \infty there.) For a pole at the origin the Nyquist contour goes around it on a small half circle s=εejϕs = \varepsilon e^{j\phi}, ϕ\phi from −π/2-\pi/2 to π/2\pi/2. There KP(s)K P(s) is close to (Kc/ε)e−jϕ(K c/\varepsilon) e^{-j\phi} with c>0c > 0, a large arc through the positive real axis, which does not meet the ray (−∞,−1](-\infty, -1]. On the imaginary axis the curve can meet the negative real axis only at a frequency where arg⁡P(jω)=−π\arg P(j\omega) = -\pi modulo 2π2\pi. Every such ω>0\omega > 0 satisfies ω≥ωu\omega \ge \omega_u, because ωu\omega_u is the smallest one, and the same holds for −ω-\omega by symmetry. By the monotone gain, K∣P(jω)∣≤K∣P(jωu)∣=K/Ku<1K |P(j\omega)| \le K |P(j\omega_u)| = K/K_u < 1. So the curve meets the negative real axis only to the right of −1-1. A closed curve that does not meet the ray (−∞,−1](-\infty, -1] has the winding number 0 about −1-1. □\square

A product of at least one real lag 1/(s+p)1/(s + p) with p>0p > 0, perhaps with one integrator 1/s1/s, an all-pass factor (1−s/z)/(1+s/z)(1 - s/z)/(1 + s/z) and a delay, has a strictly decreasing ∣P(jω)∣|P(j\omega)|. So the claim holds for the plants that the method was made for. For a plant with a resonance the gain is not monotone and the claim can fail. The tests show for random products of 3 to 5 real lags that the closed loop has a root in the right half plane at K=1.1KuK = 1.1 K_u. That part is a measurement, not a theorem of this page.

Claim 3: lines L1 to L3 find ωu\omega_u

Assume that between neighbours of the log grid the phase of the rational part changes by less than π\pi, and that the continuous phase φ(ω)\varphi(\omega) does not go below −π-\pi and back between two neighbours. Then the scan finds the first interval [ωi−1,ωi][\omega_{i-1}, \omega_i] that contains ωu\omega_u, and the bisection converges to ωu\omega_u.

Proof. As ω→0+\omega \to 0^+, P(jω)P(j\omega) is close to c(jω)−mc (j\omega)^{-m}, with c=n0/d0c = n_0/d_0 the ratio of the lowest nonzero coefficients and mm the number of net poles at the origin. For c>0c > 0 the phase starts at −mπ/2-m\pi/2; for c<0c < 0 the code stops with an error, because the controller then needs the reverse action. The phase of the rational part is known modulo 2π2\pi at each grid point. Line L1 adds the wrapped difference wrap⁡(arg⁡i−arg⁡i−1)∈(−π,π]\operatorname{wrap}(\arg_i - \arg_{i-1}) \in (-\pi, \pi] to the running phase. Under the first assumption this wrapped difference is the true change of the continuous phase, so by induction φi\varphi_i is the continuous phase at ωi\omega_i. The delay adds −ωθ-\omega\theta exactly. Line L2 takes the first ii with φi≤−π\varphi_i \le -\pi. Then φi−1>−π≥φi\varphi_{i-1} > -\pi \ge \varphi_i. Under the second assumption no crossing lies below ωi−1\omega_{i-1}, so ωu∈(ωi−1,ωi]\omega_u \in (\omega_{i-1}, \omega_i]. On this interval the function g(ω)=φ(ω)+πg(\omega) = \varphi(\omega) + \pi is continuous, because the rational part has no pole on the imaginary axis away from the origin (a pole there would give an infinite gain). The code computes gg from the phase at ωi−1\omega_{i-1} plus a wrapped difference, which is right by the first assumption. Line L3 keeps g(a)>0≥g(b)g(a) > 0 \ge g(b), and each step halves b−ab - a, so aa and bb converge to a zero of gg in the bracket. A zero of gg in the bracket is ωu\omega_u when φ\varphi is decreasing there; this holds for the plants of Claim 2, where each lag and the delay decrease the phase. □\square

With 4000 grid points from 10−610^{-6} to 10310^3 rad/s, neighbours differ by the factor 109/4000=1.005210^{9/4000} = 1.0052. A real lag changes its phase by at most 0.00260.0026 rad over such a step, and a delay θ\theta by 0.0052 ωθ0.0052\, \omega \theta. The assumptions hold with a large margin unless the delay is long compared with 103/ωu10^3/\omega_u or the plant has lightly damped poles.

Claim 4: the tangent fit has an error of order Δt2\Delta t^2

Let yy be four times continuously differentiable with a single inflection point t∗t^*, where y′(t∗)=R>0y'(t^*) = R > 0 is the largest slope and y′′(t∗)=0y''(t^*) = 0, y′′′(t∗)<0y'''(t^*) < 0. Sample yy with the step Δt\Delta t. Then lines L6 and L7 give RR and the apparent delay L=t∗−(y(t∗)−y(0))/RL = t^* - (y(t^*) - y(0))/R with errors O(Δt2)O(\Delta t^2).

Proof. The central difference Dj=(yj+1−yj−1)/(2Δt)D_j = (y_{j+1} - y_{j-1})/(2\Delta t) equals y′(tj)+O(Δt2)y'(t_j) + O(\Delta t^2). Line L6 takes the jj with the largest DjD_j. Near t∗t^*, y′(t)=R+12y′′′(t∗)(t−t∗)2+O(∣t−t∗∣3)y'(t) = R + \frac12 y'''(t^*) (t - t^*)^2 + O(|t - t^*|^3), so the chosen tjt_j satisfies ∣tj−t∗∣≤Δt/2+O(Δt2)|t_j - t^*| \le \Delta t/2 + O(\Delta t^2), and Dj=R+O(Δt2)D_j = R + O(\Delta t^2). For line L7 let ℓ(t)=t−(y(t)−y(0))/y′(t)\ell(t) = t - (y(t) - y(0))/y'(t), the time where the tangent at tt crosses y(0)y(0). Its derivative is

ℓ′(t)=1−y′(t)2−(y(t)−y(0))y′′(t)y′(t)2=(y(t)−y(0))y′′(t)y′(t)2,\ell'(t) = 1 - \frac{y'(t)^2 - (y(t) - y(0)) y''(t)}{y'(t)^2} = \frac{(y(t) - y(0)) y''(t)}{y'(t)^2},

which is 0 at t∗t^*. So ℓ(tj)=ℓ(t∗)+O(Δt2)\ell(t_j) = \ell(t^*) + O(\Delta t^2). Line L7 computes ℓ(tj)\ell(t_j) with DjD_j in place of y′(tj)y'(t_j), which adds a further O(Δt2)O(\Delta t^2). □\square

For P(s)=1/(s+1)3P(s) = 1/(s + 1)^3 and a unit step, y(t)=1−e−t(1+t+t2/2)y(t) = 1 - e^{-t}(1 + t + t^2/2) and y′(t)=12t2e−ty'(t) = \frac12 t^2 e^{-t}. The slope is largest at t∗=2t^* = 2, so R=2e−2=0.270671R = 2 e^{-2} = 0.270671. With y(2)=1−5e−2y(2) = 1 - 5 e^{-2} the apparent delay is L=2−(e2−5)/2=(9−e2)/2=0.805472L = 2 - (e^2 - 5)/2 = (9 - e^2)/2 = 0.805472, and a=RL=9e−2−1=0.218018a = R L = 9 e^{-2} - 1 = 0.218018. With Δt=0.01\Delta t = 0.01 the code gives L=0.805462L = 0.805462, an error of 10−510^{-5}, as the claim predicts.

Claim 5: the cost

The ultimate point search costs O(g n)O(g\, n) operations for gg grid points and a plant of degree nn, plus O(n)O(n) per bisection step. The tangent fit costs O(k)O(k) for kk samples.

Proof. Each grid point needs two Horner evaluations of degree at most nn and a fixed number of other operations. The bisection stops after at most 200 steps, and in practice after about 50, when b−a≤10−15bb - a \le 10^{-15} b. Line L6 visits each sample once and line L7 is a fixed number of operations. □\square

Complexity

The search evaluates the plant at gg grid points. Each evaluation is two Horner evaluations of degree at most nn, so the search costs O(gn)O(g n) time. The bisection adds about 50 steps of O(n)O(n) each. The tangent fit visits each of the kk samples once, so it costs O(k)O(k). The phase list takes O(g)O(g) space. The cost that counts on a real plant is the time of the experiment: the ultimate cycle method needs several periods TuT_u at each trial gain, and the step response method needs one response that reaches the steepest point.

Properties

  • Two numbers. Each method reduces the plant to two numbers, KuK_u and TuT_u, or aa and LL. Plants with the same two numbers get the same controller.
  • Scale. The controller gain scales as 1/Ku1/K_u or 1/a1/a, and the times scale with TuT_u or LL. So a change of the units of time or of the plant gain gives the same loop in the new units.
  • Fixed ratio. Both PID rules give Ti=4TdT_i = 4 T_d, so the PID has a double real zero and it has a series form with equal times.
  • Aggressive. The target decay ratio of one quarter gives a damping ratio near 0.2 for a dominant pair of poles. This is a fast but lightly damped loop, with poor robustness for many plants.

Variants and improvements

  • Relay feedback. Relay autotuning finds the ultimate point with a relay in place of a P controller at the edge of oscillation. The loop then oscillates with a controlled amplitude, which is safer on a real plant.
  • Smaller factors. Many later tables keep the form of the ultimate cycle rule and use a smaller gain factor than 0.6, to get less overshoot at the cost of a slower load response.
  • AMIGO rules. Åström and Hägglund fitted rules to a large test batch of plants under a constraint on the peak sensitivity MsM_s. These rules use a first order model with a delay in place of the two numbers aa and LL, and they give much better robustness.
  • Model based rules. Internal model control gives PI and PID settings from a first order model with a delay, with one tuning knob, the closed-loop time constant. Skogestad's SIMC rules are of this kind.
  • Set-point weighting. A set-point weight b<1b < 1 in the proportional term cuts the overshoot to set-point steps without a change of the load response. See two-degree-of-freedom control.

When to use it

Use the ultimate cycle method when the plant can be run safely at the edge of oscillation for a few periods, and when a quick first tuning is good enough. Use the step response method when the plant can be run in open loop, its response is slow and has an S shape, and the noise is small enough that a tangent can be drawn. Use either set of factors as a start, and then reduce the gain or add a set-point weight if the overshoot is too large. Do not use the method on plants with a negative low-frequency gain without the reverse action, or on plants with lightly damped modes, where the two numbers do not describe the plant.

Pitfalls

  • Large overshoot. The quarter decay target gives overshoots of 50 percent and more to set-point steps, as the example shows. Treat the result as a first try.
  • Running at the limit. The ultimate cycle experiment brings the loop to the edge of a growing oscillation. A change of the plant during the test can make the oscillation grow. Use a relay in place of the high gain where this is a risk.
  • Integral times in the PI rule. The step response PI rule is Ti=L/0.3=3.33LT_i = L/0.3 = 3.33 L in the paper and 3L3 L in many books. State which one you use.
  • Forms. The rules are for the ideal (standard) form. A controller in the series or parallel form needs a conversion; see PID controller.
  • Long delays. The two numbers aa and LL do not tell a plant with a long delay from a plant with a long lag, and Åström and Hägglund (2004) show that the step response rules work poorly when the delay is long compared with the time constant. A Smith predictor or a model based rule works better there.
  • Noise and the tangent. The steepest slope of a noisy record is an estimate of a derivative, which amplifies noise. Filter the record or fit a model first.

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()
ziegler_nichols_tuning.py 182 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ziegler-nichols-tuning/. The authors are listed in prov/7QVRVJ.jsonl.

"""Ziegler-Nichols tuning, by the ultimate cycle method and by the step
response method.

The plant is P(s) = num(s)/den(s) e^(-s delay), with polynomials highest
power first. The ultimate point is the smallest omega_u > 0 where the phase
of P(j omega) is -180 degrees; then K_u = 1/|P(j omega_u)| and
T_u = 2 pi/omega_u. The phase is made continuous in omega: it starts at
-90 degrees per net pole at the origin, and the phase of the rational
part is unwrapped along a log grid of frequencies (the grid must be fine
enough that the phase moves less than 180 degrees between neighbours).
The delay adds -omega delay exactly.

The rules return (K, Ti, Td) of the ideal form K (1 + 1/(Ti s) + Td s), with
Ti = None for no integral action and Td = 0 for no derivative action.
They are the rules of Ziegler and Nichols (1942). They are rules of thumb,
not optimal settings.
"""

import cmath
import math

from ctlmat import polyval

__all__ = [
    "phase", "phase_scan", "ultimate_point", "ultimate_cycle_rule", "tangent_fit",
    "step_response_rule",
]

ULTIMATE_RULES = {
    "P": (0.5, None, None),
    "PI": (0.45, 1 / 1.2, None),
    "PID": (0.6, 1 / 2, 1 / 8),
}


def _wrap(x):
    """Return x - 2 pi k in (-pi, pi]."""
    return math.remainder(x, 2 * math.pi)


def _rational_arg(num, den, w):
    return cmath.phase(polyval(num, 1j * w) / polyval(den, 1j * w))


def _low_frequency_phase(num, den):
    """Phase of P(j w) as w -> 0+: -90 degrees per net pole at the origin.

    Raises ValueError for a negative low-frequency gain, where the
    controller needs the reverse action.
    """
    def lowest(p):
        k = 0
        while p[len(p) - 1 - k] == 0:
            k += 1
        return p[len(p) - 1 - k], k

    cn, kn = lowest(num)
    cd, kd = lowest(den)
    # P(j w) is close to (cn/cd) (j w)^(-k), with phase arg(cn/cd) - k pi/2.
    if cn / cd < 0:
        raise ValueError("negative low-frequency gain: use the reverse action")
    return -(kd - kn) * math.pi / 2


def phase_scan(num, den, delay, ws):
    """Continuous phase of P(j w) at the increasing frequencies ws > 0.

    The phase of the rational part is unwrapped from one point to the
    next, which is right when it changes by less than 180 degrees between
    neighbours. The delay adds -w delay exactly.
    """
    ph0 = _low_frequency_phase(num, den)
    prev_arg = None
    total = None
    out = []
    for w in ws:
        a = _rational_arg(num, den, w)
        if total is None:
            total = ph0 + _wrap(a - ph0)
        else:
            total += _wrap(a - prev_arg)
        prev_arg = a
        out.append(total - w * delay)
    return out


def phase(num, den, delay, w, grid=2000):
    """Continuous phase of P(j w) in radians, for w > 0."""
    lo = min(1e-6, w)
    ws = [lo * (w / lo) ** (i / grid) for i in range(grid + 1)]
    return phase_scan(num, den, delay, ws)[-1]


def ultimate_point(num, den, delay=0.0, w_max=1e3, grid=4000):
    """Return (K_u, T_u, w_u) by a scan on a log grid and bisection.

    Raises ValueError if the phase does not reach -180 degrees below w_max.
    Then no finite ultimate gain exists, as for 1/(s + 1)^2.
    """
    lo = 1e-6
    ws = [lo * (w_max / lo) ** (i / grid) for i in range(grid + 1)]
    phs = phase_scan(num, den, delay, ws)  # @line L1
    if phs[0] <= -math.pi:
        raise ValueError("the phase is at or below -180 degrees at low frequency")
    for i in range(1, grid + 1):  # @line L2
        if phs[i] <= -math.pi:
            a, b, base, base_arg = ws[i - 1], ws[i], phs[i - 1] + ws[i - 1] * delay, _rational_arg(num, den, ws[i - 1])
            break
    else:
        raise ValueError("no phase crossover below w_max")

    def g(w):
        return base + _wrap(_rational_arg(num, den, w) - base_arg) - w * delay + math.pi

    for _ in range(200):  # @line L3
        mid = (a + b) / 2
        if g(mid) > 0:
            a = mid
        else:
            b = mid
        if b - a <= 1e-15 * b:
            break
    wu = (a + b) / 2
    ku = abs(polyval(den, 1j * wu) / polyval(num, 1j * wu))  # @line L4
    return ku, 2 * math.pi / wu, wu


def ultimate_cycle_rule(ku, tu, kind="PID"):
    """Ziegler-Nichols ultimate cycle rule: (K, Ti, Td)."""
    kf, tif, tdf = ULTIMATE_RULES[kind]  # @line L5
    return kf * ku, None if tif is None else tif * tu, 0 if tdf is None else tdf * tu


def tangent_fit(ts, ys, du=1.0):
    """Fit the tangent at the steepest point of a step response.

    ts, ys: samples of the response to an input step of size du at t = 0,
    from rest, with a uniform time step. Returns (R, L, a): R the largest
    slope per unit input (central differences), L the time where the
    tangent crosses y = y(0) (the apparent delay), and a = R L.
    """
    n = len(ts)
    if n < 5:
        raise ValueError("too few samples")
    dt = ts[1] - ts[0]
    best = max(range(1, n - 1), key=lambda k: ys[k + 1] - ys[k - 1])  # @line L6
    if best == n - 2:
        raise ValueError("the steepest point is at the end of the record")
    slope = (ys[best + 1] - ys[best - 1]) / (2 * dt)
    if slope <= 0:
        raise ValueError("the response does not rise")
    L = ts[best] - (ys[best] - ys[0]) / slope  # @line L7
    R = slope / du
    return R, L, R * L


def step_response_rule(a, L, kind="PID"):
    """Ziegler-Nichols step response rule (1942) from a = R L and L.

    P: K = 1/a. PI: K = 0.9/a, Ti = L/0.3. PID: K = 1.2/a, Ti = 2 L,
    Td = L/2. Many books round the PI integral time to 3 L.
    """
    if kind == "P":  # @line L8
        return 1 / a, None, 0
    if kind == "PI":
        return 0.9 / a, L / 0.3, 0
    if kind == "PID":
        return 1.2 / a, 2 * L, L / 2
    raise ValueError("kind must be P, PI or PID")


def _self_test():
    ku, tu, wu = ultimate_point([1.0], [1.0, 3.0, 3.0, 1.0])
    assert abs(ku - 8) < 1e-9 and abs(wu - math.sqrt(3)) < 1e-9
    return True


if __name__ == "__main__":
    _self_test()
test_ziegler_nichols_tuning.py 157 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ziegler-nichols-tuning/. The authors are listed in prov/7QVRVJ.jsonl.

import math
import random

import pytest

from ctlmat import polyadd, polymul, polyroots, polyval
from ctlsim import simulate
from ziegler_nichols_tuning import (phase, step_response_rule, tangent_fit,
                                    ultimate_cycle_rule, ultimate_point)

TU3 = 2 * math.pi / math.sqrt(3)   # ultimate period of 1/(s + 1)^3


def test_ultimate_point_third_order_lag():
    # (s + 1)^3 + 8 = (s + 3)(s^2 + 3): K_u = 8, w_u = sqrt(3).
    ku, tu, wu = ultimate_point([1.0], [1.0, 3.0, 3.0, 1.0])
    assert abs(ku - 8) < 1e-9
    assert abs(wu - math.sqrt(3)) < 1e-9
    assert abs(tu - TU3) < 1e-9


def test_ultimate_point_with_integrator():
    # s (s + 1)(s + 2) + 6 = (s + 3)(s^2 + 2): K_u = 6, w_u = sqrt(2).
    ku, tu, wu = ultimate_point([1.0], [1.0, 3.0, 2.0, 0.0])
    assert abs(ku - 6) < 1e-9
    assert abs(wu - math.sqrt(2)) < 1e-9


def test_ultimate_point_right_half_plane_zero():
    # (s + 1)^3 + 2 (1 - s) = (s + 3)(s^2 + 1): K_u = 2, w_u = 1.
    ku, tu, wu = ultimate_point([-1.0, 1.0], [1.0, 3.0, 3.0, 1.0])
    assert abs(ku - 2) < 1e-9
    assert abs(wu - 1) < 1e-9


@pytest.mark.parametrize("seed", [1, 2, 3])
def test_first_order_plus_delay(seed):
    # P = e^(-theta s)/(s + 1): atan(w) + w theta = pi and K_u = sqrt(1 + w^2).
    rng = random.Random(seed)
    for _ in range(5):
        theta = rng.uniform(0.05, 5.0)
        ku, tu, wu = ultimate_point([1.0], [1.0, 1.0], delay=theta)
        assert abs(math.atan(wu) + wu * theta - math.pi) < 1e-10
        assert abs(ku - math.sqrt(1 + wu * wu)) < 1e-9 * ku


def test_phase_is_continuous():
    # The phase of 1/(s + 1)^3 is -3 atan(w), below -180 degrees for w > sqrt(3).
    for w in (0.1, 1.0, 1.7, 2.0, 10.0, 100.0):
        assert abs(phase([1.0], [1.0, 3.0, 3.0, 1.0], 0.0, w) + 3 * math.atan(w)) < 1e-12
    # A delay adds -w theta: 1/(s + 1) with theta = 2 at w = 3.
    assert abs(phase([1.0], [1.0, 1.0], 2.0, 3.0) + math.atan(3.0) + 6.0) < 1e-12


@pytest.mark.parametrize("seed", [11, 12, 13, 14])
def test_closed_loop_poles_cross_the_axis_at_ku(seed):
    # For a product of real lags, den + K num has roots +-j w_u at K = K_u,
    # all roots in the open left half plane for K < K_u and some root in
    # the right half plane for K > K_u.
    rng = random.Random(seed)
    n = rng.randint(3, 5)
    den = [1.0]
    for _ in range(n):
        den = polymul(den, [1.0, rng.uniform(0.3, 3.0)])
    num = [rng.uniform(0.5, 2.0)]
    ku, tu, wu = ultimate_point(num, den)
    closed = lambda k: polyadd(den, [k * c for c in num])
    p = closed(ku)
    assert abs(polyval(p, 1j * wu)) < 1e-9 * max(abs(c) for c in p)
    assert max(z.real for z in polyroots(closed(0.9 * ku))) < 0
    assert max(z.real for z in polyroots(closed(1.1 * ku))) > 0


def test_no_ultimate_point():
    # The phase of 1/(s + 1)^2 stays above -180 degrees.
    with pytest.raises(ValueError):
        ultimate_point([1.0], [1.0, 2.0, 1.0])
    # A negative gain needs the reverse action.
    with pytest.raises(ValueError):
        ultimate_point([-1.0], [1.0, 3.0, 3.0, 1.0])


def test_ultimate_cycle_rules():
    assert ultimate_cycle_rule(8.0, TU3, "P") == (4.0, None, 0)
    k, ti, td = ultimate_cycle_rule(8.0, TU3, "PI")
    assert abs(k - 3.6) < 1e-12 and abs(ti - TU3 / 1.2) < 1e-12 and td == 0
    k, ti, td = ultimate_cycle_rule(8.0, TU3, "PID")
    assert abs(k - 4.8) < 1e-12 and abs(ti - 1.813799) < 1e-6 and abs(td - 0.453450) < 1e-6


def lag3_step(t1=12.0, dt=0.01):
    ts, xs, _ = simulate(lambda t, x, u: [-x[0] + 1.0, -x[1] + x[0], -x[2] + x[1]],
                         [0.0, 0.0, 0.0], 0.0, t1, dt)
    assert len(ts) == round(t1 / dt) + 1
    return ts, [x[2] for x in xs]


def test_tangent_fit_closed_form():
    # y = 1 - e^(-t)(1 + t + t^2/2), y' = t^2 e^(-t)/2, steepest at t = 2.
    ts, ys = lag3_step()
    R, L, a = tangent_fit(ts, ys)
    assert abs(R - 2 * math.exp(-2)) < 1e-4
    assert abs(L - (9 - math.e ** 2) / 2) < 1e-4
    assert abs(a - (9 * math.exp(-2) - 1)) < 1e-4


def test_tangent_fit_input_size_and_errors():
    ts, ys = lag3_step()
    R1, L1, _ = tangent_fit(ts, ys)
    R2, L2, _ = tangent_fit(ts, [2.5 * y for y in ys], du=2.5)
    assert abs(R1 - R2) < 1e-12 and abs(L1 - L2) < 1e-12
    with pytest.raises(ValueError):
        tangent_fit(ts, [-y for y in ys])
    with pytest.raises(ValueError):
        tangent_fit(ts[:3], ys[:3])


def test_step_response_rules():
    a, L = 0.25, 0.8
    assert step_response_rule(a, L, "P") == (4.0, None, 0)
    k, ti, td = step_response_rule(a, L, "PI")
    assert abs(k - 3.6) < 1e-12 and abs(ti - L / 0.3) < 1e-12 and td == 0
    assert step_response_rule(a, L, "PID") == (4.8, 1.6, 0.4)
    with pytest.raises(ValueError):
        step_response_rule(a, L, "PD")


def pid_loop(K, Ti, Td, N=20.0, r=1.0, load=0.0, t1=60.0, dt=0.01):
    # 1/(s + 1)^3 with K (r - y) + (K/Ti) int(r - y) - K Td s/(1 + s Td/N) y.
    def f(t, x, _):
        y = x[2]
        D = -K * N * (y - x[4]) if Td > 0 else 0.0
        u = K * (r - y) + x[3] + D + load
        dxf = N / Td * (y - x[4]) if Td > 0 else 0.0
        return [-x[0] + u, -x[1] + x[0], -x[2] + x[1], K / Ti * (r - y), dxf]

    ts, xs, _ = simulate(f, [0.0] * 5, 0.0, t1, dt)
    return [x[2] for x in xs]


def maxima(ys, ref):
    return [ys[k] - ref for k in range(1, len(ys) - 1)
            if ys[k] > ref and ys[k] >= ys[k - 1] and ys[k] > ys[k + 1]]


def test_ziegler_nichols_pid_loop():
    ku, tu, _ = ultimate_point([1.0], [1.0, 3.0, 3.0, 1.0])
    K, Ti, Td = ultimate_cycle_rule(ku, tu, "PID")
    ys = pid_loop(K, Ti, Td)
    assert abs(ys[-1] - 1) < 1e-6
    pk = maxima(ys, 1.0)
    # Measurements of this run: overshoot 0.523, decay ratio 0.138.
    assert 0.45 < pk[0] < 0.60
    assert pk[1] / pk[0] < 0.25

History

John G. Ziegler and Nathaniel B. Nichols worked at the Taylor Instrument Companies in Rochester, New York. In 1942 they published "Optimum settings for automatic controllers" in the Transactions of the ASME. They measured the ultimate sensitivity and the ultimate period of a loop, and the reaction rate and the lag of a plant from its response curve, and gave the settings in a short table. They chose the settings so that an oscillation decays to a quarter of its amplitude in each period. The rules spread through the process industry and are still the best known tuning rules. Åström and Hägglund revisited the step response method in 2004 and showed that its robustness is often poor; they proposed the AMIGO rules in its place.

References

  1. J. G. Ziegler and N. B. Nichols, Optimum settings for automatic controllers, Transactions of the ASME 64(8) (1942) 759-768, the summary table of the settings on p. 765 and the quarter amplitude decay on p. 764
  2. Karl Johan Åström and Tore Hägglund, Revisiting the Ziegler-Nichols step response method for PID control, Journal of Process Control 14(6) (2004) 635-650, the whole paper (the analysis of the step response method and the AMIGO rules)
  3. Karl Johan Åström and Tore Hägglund, Advanced PID Control, ISA, 2006, Section 6.2, Ziegler-Nichols and related methods, and Chapter 7, the AMIGO rules

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