Algorithm Search⌘K

Algorithmintro

Process reaction curve method

Also called FOPDT model fitting, step response model fitting.

Fits a first-order plus dead time model to the open-loop step response from its gain, its delay and its time constant.

Time
O(n) worst
Space
O(n) extra
Where
n = the number of samples
Properties
deterministicnot exactofflineiterative
Origin
John G. Ziegler, Nathaniel B. Nichols, 1942

The process reaction curve method fits the first-order plus dead time (FOPDT) model

G(s)=K e−LsTs+1G(s) = \frac{K\, e^{-L s}}{T s + 1}

to the recorded response of a process to one step of its input, taken in open loop. The gain KK is the final change of the output divided by the size of the step. The dead time LL and the time constant TT come from the shape of the curve: either from the tangent at its steepest point, the classical reading of Ziegler and Nichols in 1942, or from the two times at which the normalized output reaches 28.3 and 63.2 percent of its final change. The work is one pass over the nn samples, O(n)O(n). The two-point formulas return LL and TT exactly for a true FOPDT response, and for any other S-shaped response they return an approximation. The three numbers KK, LL and TT are the input of many rules of thumb for tuning PID controllers.

In plain words

Put the process in a steady state, change its input by one fixed step, and record how the output moves until it settles again. Many processes answer in the same way: for a while nothing happens, then the output rises along an S-shaped curve and levels off. Three numbers describe that curve well enough to tune a controller. The gain says how far the output moved for each unit of input. The dead time says how long the process waited before it began to move. The time constant says how long the rise took. You can read them with a ruler from a printed curve, or compute them from the samples in one pass.

The problem

Input. Sample times t0<t1<⋯<tn−1t_0 < t_1 < \cdots < t_{n-1}, the output samples y0,…,yn−1y_0, \ldots, y_{n-1}, and the step size Δu≠0\Delta u \ne 0. The step is applied at t0t_0, the process is at rest at y0y_0 before it, and the output has settled at yn−1≠y0y_{n-1} \ne y_0.

Output. KK, LL and TT of the FOPDT model, with LL measured from t0t_0. Its unit step response is 0 for t<Lt < L and K(1−e−(t−L)/T)K\big(1 - e^{-(t - L)/T}\big) for t≥Lt \ge L.

The algorithm

  1. FOPDT-FIT(t, y, Δu, ⟨method⟩)
  2. 1K ← (y_(n-1) - y_0) / Δu
  3. 2z_i ← (y_i - y_0) / (y_(n-1) - y_0) for every i
  4. 3if ⟨method⟩ = two-point then
  5. 4t28, t63 ← the first times, after t_0, at which z reaches 1 - e^(-1/3) and 1 - e^(-1), by linear interpolation between samples
  6. 5T ← 1.5 · (t63 - t28)
  7. 6L ← t63 - T
  8. 7else: (s, tm, zm) ← the slope and the midpoint of the steepest chord (z_(i+1) - z_i) / (t_(i+1) - t_i)
  9. 8L ← tm - zm / s
  10. 9T ← 1 / s
  11. 10return (K, L, T)

Line L2 scales the curve so that it goes from 0 to 1; the levels of L4 are then 1−e−1/3≈0.28351 - e^{-1/3} \approx 0.2835 and 1−e−1≈0.63211 - e^{-1} \approx 0.6321. For an FOPDT curve these levels are reached at L+T/3L + T/3 and L+TL + T, so their distance is 2T/32T/3, which gives L5 and L6. Lines L7 to L9 are the tangent method on sampled data: the steepest chord stands for the tangent at the inflection point, and the line through the chord midpoint with slope ss crosses z=0z = 0 at LL and z=1z = 1 at L+1/sL + 1/s.

Example

Take the process 1/(s+1)31/(s+1)^3, three equal first-order lags in series, a unit step and samples every 0.50.5 s. Its step response is y(t)=1−e−t(1+t+t2/2)y(t) = 1 - e^{-t}(1 + t + t^2/2), so K=1K = 1 and z=yz = y.

tt 0.50.5 1.01.0 1.51.5 2.02.0 2.52.5 3.03.0 3.53.5
y(t)y(t) 0.01440.0144 0.08030.0803 0.19120.1912 0.32330.3233 0.45620.4562 0.57680.5768 0.67920.6792
slope of the chord ending at tt 0.02880.0288 0.13180.1318 0.22170.2217 0.26430.2643 0.26570.2657 0.24120.2412 0.20470.2047

Two-point. L4 interpolates t28=1.8492t_{28} = 1.8492 between 1.51.5 and 2.02.0, and t63=3.2702t_{63} = 3.2702 between 3.03.0 and 3.53.5. L5 gives T=1.5⋅1.4210=2.1315T = 1.5 \cdot 1.4210 = 2.1315 and L6 gives L=3.2702−2.1315=1.1387L = 3.2702 - 2.1315 = 1.1387.

Tangent. The steepest chord is the one from 2.02.0 to 2.52.5, with s=0.2657s = 0.2657 and midpoint (2.25,0.3898)(2.25, 0.3898). L8 gives L=2.25−0.3898/0.2657=0.7832L = 2.25 - 0.3898/0.2657 = 0.7832 and L9 gives T=3.7633T = 3.7633.

Fine sampling (computation). The exact curve has its inflection point at t=2t = 2 with slope 2e−22e^{-2}, so the true tangent gives L=(9−e2)/2=0.8055L = (9 - e^2)/2 = 0.8055 and T=e2/2=3.6945T = e^2/2 = 3.6945, and the exact crossing times give L=1.1496L = 1.1496 and T=2.1087T = 2.1087. With samples every 0.010.01 s the algorithm returned (0.80546,3.69456)(0.80546, 3.69456) and (1.14959,2.10867)(1.14959, 2.10867).

The two models are different approximations of the same curve. At ω=0.5\omega = 0.5 rad/s the true gain is 0.71550.7155 and the true phase −1.3909-1.3909 rad; the tangent model gives 0.47610.4761 and −1.4774-1.4774, the two-point model 0.68820.6882 and −1.3866-1.3866 (computation). The tangent model has the larger time constant and the smaller delay, so it underestimates the gain at middle frequencies.

Correctness

Claim. Suppose the samples come from an FOPDT response, yi=y0+KΔu(1−e−(ti−t0−L)/T)y_i = y_0 + K \Delta u \big(1 - e^{-(t_i - t_0 - L)/T}\big) for ti≥t0+Lt_i \ge t_0 + L and yi=y0y_i = y_0 before, except that the last sample holds the settled value y0+KΔuy_0 + K \Delta u, and that the record is long enough (made precise in the proof). Then L1 returns KK exactly. If the crossing times of L4 are read from the continuous curve, the two-point method returns LL and TT exactly; with linear interpolation and sample spacing h≤T/3h \le T/3, each crossing time is off by at most h2eh/T/(8T)h^2 e^{h/T}/(8T). If t0+Lt_0 + L is a sample time and the spacing near it is hh, the tangent method returns LL exactly and TT as h/(1−e−h/T)=T+h/2+O(h2)h/(1 - e^{-h/T}) = T + h/2 + O(h^2).

Key invariant. After L2, z(t)=1−e−(t−t0−L)/Tz(t) = 1 - e^{-(t - t_0 - L)/T} for t≥t0+Lt \ge t_0 + L. This is concave, so the chords to the right of t0+Lt_0 + L get flatter, and the steepest chord is the first one after the dead time.

The two-point formula follows from z(L+T/3)=1−e−1/3z(L + T/3) = 1 - e^{-1/3} and z(L+T)=1−e−1z(L + T) = 1 - e^{-1}. The tangent result follows because the line through the first chord after the dead time meets z=0z = 0 exactly at its left end. The full proof is below.

Proof: The FOPDT fit recovers K, L and T from a first-order plus dead time responsefull

We work in exact real arithmetic, with exe^x and ln⁡\ln as exact operations. Measure time from the step, so t0=0t_0 = 0, and let K≠0K \ne 0, L≥0L \ge 0 and T>0T > 0. Let

ϕ(t)=0 for t<L,ϕ(t)=1−e−(t−L)/T for t≥L,\phi(t) = 0 \text{ for } t < L, \qquad \phi(t) = 1 - e^{-(t - L)/T} \text{ for } t \ge L,

the normalized step response of the FOPDT model.

Hypotheses. The samples are yi=y0+KΔu ϕ(ti)y_i = y_0 + K \Delta u\, \phi(t_i) for 0≤i≤n−20 \le i \le n-2 and yn−1=y0+KΔuy_{n-1} = y_0 + K \Delta u. The record is long enough in this sense: tn−2≥L+Tt_{n-2} \ge L + T, and the last chord of zz, from tn−2t_{n-2} to tn−1t_{n-1}, is not steeper than any chord of zz that lies in [L,tn−2][L, t_{n-2}]. (The second condition holds when the last interval is not much shorter than the others, since 1−ϕ(tn−2)≤e−11 - \phi(t_{n-2}) \le e^{-1} is small.)

Lemma 1 (gain and normalization). L1 returns KK, and after L2, zi=ϕ(ti)z_i = \phi(t_i) for i≤n−2i \le n - 2 and zn−1=1z_{n-1} = 1.

Proof. yn−1−y0=KΔuy_{n-1} - y_0 = K \Delta u, which is nonzero, so L1 gives KΔu/Δu=KK \Delta u / \Delta u = K, and L2 gives zi=KΔu ϕ(ti)/(KΔu)=ϕ(ti)z_i = K \Delta u\, \phi(t_i) / (K \Delta u) = \phi(t_i). □\square

Note that the sign of KK and of Δu\Delta u plays no role after L2: zz always rises from 0 to 1.

Lemma 2 (the two levels). For 0<c<10 < c < 1, the first time at which ϕ\phi reaches cc is L−Tln⁡(1−c)L - T \ln(1 - c). In particular ϕ\phi reaches 1−e−1/31 - e^{-1/3} at L+T/3L + T/3 and 1−e−11 - e^{-1} at L+TL + T.

Proof. ϕ=0<c\phi = 0 < c before LL, and on [L,∞)[L, \infty) it is continuous and strictly increasing, so the first time is the unique solution of 1−e−(t−L)/T=c1 - e^{-(t - L)/T} = c, which is t=L−Tln⁡(1−c)t = L - T \ln(1 - c). For c=1−e−1/3c = 1 - e^{-1/3} this is L+T/3L + T/3, and for c=1−e−1c = 1 - e^{-1} it is L+TL + T. □\square

Theorem 1 (two-point, exact crossings). If L4 returns the exact first crossing times of ϕ\phi, then L5 and L6 return TT and LL.

Proof. By Lemma 2, t63−t28=(L+T)−(L+T/3)=2T/3t_{63} - t_{28} = (L + T) - (L + T/3) = 2T/3, so L5 gives 1.5⋅2T/3=T1.5 \cdot 2T/3 = T, and L6 gives (L+T)−T=L(L + T) - T = L. □\square

Theorem 2 (two-point, linear interpolation). Let every sample interval have length at most h≤T/3h \le T/3. Then each of the times returned by L4 differs from the exact crossing time by at most h2eh/T8T\frac{h^2 e^{h/T}}{8 T}.

Proof. Fix a level c∈{1−e−1/3,1−e−1}c \in \{1 - e^{-1/3}, 1 - e^{-1}\} and let t∗=L−Tln⁡(1−c)t^* = L - T \ln(1 - c), so t∗≥L+T/3t^* \ge L + T/3 by Lemma 2. Since tn−2≥L+T≥t∗t_{n-2} \ge L + T \ge t^* and ϕ\phi is nondecreasing, the scan of L4 stops at the first i≤n−2i \le n - 2 with zi≥cz_i \ge c; then zi−1<c≤ziz_{i-1} < c \le z_i and so ti−1<t∗≤tit_{i-1} < t^* \le t_i. Hence ti−1≥t∗−h≥Lt_{i-1} \ge t^* - h \ge L, and ϕ\phi is smooth on [ti−1,ti][t_{i-1}, t_i] with

ϕ′(t)=1Te−(t−L)/T≥1Te−(ti−L)/T,∣ϕ′′(t)∣=1T2e−(t−L)/T≤1T2e−(ti−1−L)/T.\phi'(t) = \tfrac{1}{T} e^{-(t - L)/T} \ge \tfrac{1}{T} e^{-(t_i - L)/T}, \qquad \lvert \phi''(t) \rvert = \tfrac{1}{T^2} e^{-(t - L)/T} \le \tfrac{1}{T^2} e^{-(t_{i-1} - L)/T}.

Let ℓ\ell be the line through (ti−1,zi−1)(t_{i-1}, z_{i-1}) and (ti,zi)(t_i, z_i), and t^\hat t the time with ℓ(t^)=c\ell(\hat t) = c, which L4 returns; t^∈(ti−1,ti]\hat t \in (t_{i-1}, t_i]. The error of linear interpolation is ∣ϕ(t)−ℓ(t)∣≤(ti−ti−1)28max⁡∣ϕ′′∣≤h28max⁡∣ϕ′′∣\lvert \phi(t) - \ell(t) \rvert \le \frac{(t_i - t_{i-1})^2}{8} \max \lvert \phi'' \rvert \le \frac{h^2}{8} \max \lvert \phi'' \rvert on the interval. So ∣ϕ(t^)−ϕ(t∗)∣=∣ϕ(t^)−ℓ(t^)∣≤h28max⁡∣ϕ′′∣\lvert \phi(\hat t) - \phi(t^*) \rvert = \lvert \phi(\hat t) - \ell(\hat t) \rvert \le \frac{h^2}{8} \max \lvert \phi'' \rvert. By the mean value theorem, ∣ϕ(t^)−ϕ(t∗)∣≥min⁡ϕ′⋅∣t^−t∗∣\lvert \phi(\hat t) - \phi(t^*) \rvert \ge \min \phi' \cdot \lvert \hat t - t^* \rvert, both extremes taken over [ti−1,ti][t_{i-1}, t_i]. Therefore

∣t^−t∗∣≤h28⋅max⁡∣ϕ′′∣min⁡ϕ′≤h28⋅1Te(ti−ti−1)/T≤h2eh/T8T.□\lvert \hat t - t^* \rvert \le \frac{h^2}{8} \cdot \frac{\max \lvert \phi'' \rvert}{\min \phi'} \le \frac{h^2}{8} \cdot \frac{1}{T} e^{(t_i - t_{i-1})/T} \le \frac{h^2 e^{h/T}}{8 T}. \qquad \square

Theorem 3 (tangent). Suppose LL is a sample time tmt_m with m≤n−3m \le n - 3, and let h=tm+1−tmh = t_{m+1} - t_m. Then L7 selects the chord from tmt_m to tm+1t_{m+1}, L8 returns LL exactly, and L9 returns h1−e−h/T\frac{h}{1 - e^{-h/T}}, which lies in (T,T+h](T, T + h] and equals T+h/2+O(h2)T + h/2 + O(h^2) as h→0h \to 0.

Proof. For i<mi < m, zi=zi+1=0z_i = z_{i+1} = 0, so those chords have slope 0. The chord from tmt_m to tm+1t_{m+1} has slope sm=(1−e−h/T)/h>0s_m = (1 - e^{-h/T})/h > 0. On [L,∞)[L, \infty), ϕ\phi is strictly concave, so the slopes of consecutive chords between samples in [L,tn−2][L, t_{n-2}] strictly decrease from left to right. By the hypothesis on the last chord, no chord is steeper than sms_m, and every chord after it in [L,tn−2][L, t_{n-2}] is strictly less steep. L7 keeps the first chord of largest slope, so it selects the chord at mm, with midpoint tˉ=L+h/2\bar t = L + h/2 and zˉ=(0+ϕ(L+h))/2=hsm/2\bar z = (0 + \phi(L + h))/2 = h s_m / 2. L8 gives L+h/2−(hsm/2)/sm=LL + h/2 - (h s_m/2)/s_m = L, and L9 gives 1/sm=h/(1−e−h/T)1/s_m = h/(1 - e^{-h/T}).

For the bounds, put x=h/T>0x = h/T > 0; then 1/sm=T⋅x/(1−e−x)1/s_m = T \cdot x/(1 - e^{-x}). Since e−x>1−xe^{-x} > 1 - x, 1−e−x<x1 - e^{-x} < x and the ratio is greater than 1. Since ex≥1+xe^{x} \ge 1 + x, e−x≤1/(1+x)e^{-x} \le 1/(1 + x), so 1−e−x≥x/(1+x)1 - e^{-x} \ge x/(1 + x) and the ratio is at most 1+x1 + x. Multiplying by TT gives T<1/sm≤T+hT < 1/s_m \le T + h. Finally, x/(1−e−x)x/(1 - e^{-x}) is analytic at x=0x = 0 with the expansion 1+x/2+x2/12+⋯1 + x/2 + x^2/12 + \cdots, so 1/sm=T+h/2+O(h2)1/s_m = T + h/2 + O(h^2). □\square

Corollary. Under the hypotheses, the algorithm returns KK exactly by both methods; the two-point method returns LL and TT exactly with exact crossings, and within O(h2)O(h^2) with interpolated crossings, since L5 and L6 are linear in t28t_{28} and t63t_{63}; and the tangent method returns LL exactly and TT within hh, with error h/2+O(h2)h/2 + O(h^2), when the dead time is a sample time. ■\blacksquare

Complexity

Line L1 is O(1)O(1), line L2 is O(n)O(n), the two scans of L4 and the scan of L7 are O(n)O(n) each, and the rest is O(1)O(1). The total is O(n)O(n) arithmetic operations in the real RAM, plus two evaluations of exe^x for the levels, with O(n)O(n) extra space for the normalized curve; computing ziz_i on the fly lowers this to O(1)O(1).

Properties

  • Exact for FOPDT data (theorem). As stated in the claim, for the two-point method with exact crossings and for the tangent method with the dead time on the sample grid.
  • Not exact for other curves. A process of higher order has no exact FOPDT model, and the two methods give different models, as in the example. The two-point model matches the curve at two points by design; the tangent model matches the steepest slope.
  • Noise sensitivity (measurement). With Gaussian noise of standard deviation 0.010.01 added to the 0.010.01 s samples of the example, the tangent method gave L=8.55L = 8.55 and T=0.19T = 0.19, because the steepest chord between two noisy samples is set by the noise. The two-point method gave L=1.034L = 1.034 and T=2.170T = 2.170.
  • Gain error from an unsettled record. If the record stops at time tet_e before the output has settled, L1 returns K(1−e−(te−t0−L)/T)K\big(1 - e^{-(t_e - t_0 - L)/T}\big) for FOPDT data, and the levels of L4 shift with it.
  • Open loop only. The method needs the process to be BIBO stable and to settle; an integrating or unstable process has no final value.

Variants and improvements

  • Other pairs of levels. Several published two-point rules use other pairs of levels, such as 35.3 and 85.3 percent; any two levels z1,z2z_1, z_2 give T=(t2−t1)/ln⁡((1−z1)/(1−z2))T = (t_2 - t_1)/\ln\big((1 - z_1)/(1 - z_2)\big).
  • Area method. Compute the area between the final value and the curve, which equals K(L+T)K (L + T) for an FOPDT model, and a second area to separate LL from TT. Integrals average the noise, so this is much less sensitive than the tangent method.
  • Least squares fit. Fit KK, LL and TT to all samples by nonlinear least squares, an output error fit with a step input and a delay.
  • Second-order plus dead time. Fit two time constants and a delay when the curve is clearly more sluggish than one lag.
  • Integrating processes. Fit Ke−Ls/sK e^{-L s}/s from the slope of the final ramp and its intercept with the time axis.
  • Closed-loop alternatives. The relay autotuning test identifies one point of the frequency response with the loop closed.

When to use it

Use it to get a first model of a stable, well-damped process that can be run in open loop for one step test, as for many temperature, level and flow loops in the process industry, and to tune a PID controller from that model. Prefer the two-point or area method to the tangent method on measured data. Use a parametric fit or a frequency method when the process oscillates, when the dead time must be known accurately, or when the model will be used for more than tuning.

The tuning rules that start from KK, LL and TT are not part of the fit; they are rules of thumb.

  • Ziegler and Nichols. For a PID controller, Kp=1.2 T/(KL)K_p = 1.2\, T/(K L), Ti=2LT_i = 2L and Td=0.5LT_d = 0.5 L (Ziegler and Nichols 1942); see Ziegler-Nichols tuning. On the tangent model of the example this gives Kp=5.5041K_p = 5.5041, Ti=1.6109T_i = 1.6109 and Td=0.4027T_d = 0.4027; on the two-point model, Kp=2.2011K_p = 2.2011, Ti=2.2992T_i = 2.2992 and Td=0.5748T_d = 0.5748. The rule aims at a quarter amplitude decay, which is often too aggressive.
  • Cohen and Coon. Settings derived for the same model, with more attention to processes where LL is large compared with TT (Cohen and Coon 1953).
  • SIMC. For a PI controller with a desired closed-loop time constant τc\tau_c, Kp=T/(K(τc+L))K_p = T/\big(K (\tau_c + L)\big) and Ti=min⁡(T,4(τc+L))T_i = \min\big(T, 4(\tau_c + L)\big), with τc=L\tau_c = L as a default (Skogestad 2003). The internal model control view gives rules of the same kind.

Pitfalls

  • Normalizing by an unsettled value. Stopping the record early makes yn−1y_{n-1} in L1 and L2 too small, so KK is too small and every level of L4 is reached too early. Record until the output has settled, and use the settled value in L1 and L2.
  • The tangent on raw noisy samples. The steepest chord of L7 on noisy data is a noise spike. Filter the samples or fit a smooth curve before L7, or use the two-point lines L4 to L6.
  • Measuring LL from the wrong origin. L4 and L8 must measure time from the moment t0t_0 of the step. Measuring it from the start of the record adds the idle time before the step to LL.
  • A step that is too small or too large. A small step drowns in noise and a large one drives the process out of its linear range. Choose Δu\Delta u in L1 so that the output change is several times the noise level, and check that a step of the opposite sign gives a similar KK.
  • Disturbances during the test. A load change during the recording is read as part of the response. Repeat the test, and in L1 and L2 use only records where the output starts from a steady value.

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.

ctlsim.pyI0RawGitHub
# 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()
process_reaction_curve.py 84 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/process-reaction-curve/. The authors are listed in prov/QACT9Z.jsonl.

"""Fit a first order plus dead time (FOPDT) model to a recorded step response.

The model is G(s) = K e^(-L s) / (T s + 1). Its unit step response is 0
for t < L and K (1 - e^(-(t - L) / T)) for t >= L.

Input: sample times t[0] < t[1] < ... (the step of size du is applied at
t[0]) and the output samples y[i], from rest at y[0] until the response has
settled at y[-1]. The normalized response is z = (y - y[0]) / (y[-1] - y[0]).

Two methods:
- "tangent": the line of largest slope through the curve (the tangent at the
  inflection point). It meets z = 0 at t = L and z = 1 at t = L + T. The
  slope is taken from the chords of the samples, so the result is exact for
  a sampled FOPDT response whose dead time is a sample time, and close to
  the tangent of a smooth curve when the sampling is fine.
- "two-point": the times t28 and t63 where z reaches 1 - e^(-1/3) (about
  28.3 percent) and 1 - e^(-1) (about 63.2 percent), by linear
  interpolation. Then T = 1.5 (t63 - t28) and L = t63 - T. These are the
  exact values for a FOPDT response.

Precondition: at least 3 samples, strictly increasing times, du != 0, and
y[-1] != y[0]. z should rise monotonically; with noise the result is
sensitive, see the page.

Cost: O(n) for n samples, in the real RAM.
"""

import math
from typing import Sequence, Tuple

P28 = 1.0 - math.exp(-1.0 / 3.0)
P63 = 1.0 - math.exp(-1.0)


def _crossing(t: Sequence, z: Sequence, level: float) -> float:
    """First time where z reaches level, by linear interpolation."""
    for i in range(1, len(z)):
        if z[i] >= level:
            if z[i] == z[i - 1]:
                return t[i]
            return t[i - 1] + (level - z[i - 1]) * (t[i] - t[i - 1]) / (z[i] - z[i - 1])
    raise ValueError("the response never reaches the level")


def fit_fopdt(t: Sequence, y: Sequence, du: float,
              method: str = "two-point") -> Tuple[float, float, float]:
    """Return (K, L, T) of the FOPDT model fitted to the step response."""
    if len(t) != len(y) or len(t) < 3:
        raise ValueError("need at least 3 samples of t and y")
    if any(t[i] >= t[i + 1] for i in range(len(t) - 1)):
        raise ValueError("times must be strictly increasing")
    if du == 0 or y[-1] == y[0]:
        raise ValueError("need a nonzero step and a nonzero change of the output")
    k = (y[-1] - y[0]) / du  # @line L1
    z = [(v - y[0]) / (y[-1] - y[0]) for v in y]  # @line L2
    if method == "two-point":  # @line L3
        t28 = _crossing(t, z, P28) - t[0]  # @line L4
        t63 = _crossing(t, z, P63) - t[0]
        tau = 1.5 * (t63 - t28)  # @line L5
        dead = t63 - tau  # @line L6
    elif method == "tangent":
        best = None
        for i in range(len(z) - 1):  # @line L7
            s = (z[i + 1] - z[i]) / (t[i + 1] - t[i])
            if best is None or s > best[0]:
                best = (s, 0.5 * (t[i] + t[i + 1]) - t[0], 0.5 * (z[i] + z[i + 1]))
        s, tm, zm = best
        if s <= 0:
            raise ValueError("the normalized response does not rise")
        dead = tm - zm / s  # @line L8
        tau = 1.0 / s  # @line L9
    else:
        raise ValueError("method must be 'two-point' or 'tangent'")
    return k, dead, tau  # @line L10


def fopdt_step(k: float, dead: float, tau: float, t: float) -> float:
    """Unit step response of K e^(-L s) / (T s + 1) at time t."""
    if t < dead:
        return 0.0
    return k * (1.0 - math.exp(-(t - dead) / tau))
test_process_reaction_curve.py 81 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/process-reaction-curve/. The authors are listed in prov/QACT9Z.jsonl.

import math
import random

from ctlsim import lti, simulate
from process_reaction_curve import fit_fopdt, fopdt_step


def _third_order(dt, t_end):
    # 1/(s+1)^3 as three first order lags in series, unit step at t = 0.
    a = [[-1.0, 0.0, 0.0], [1.0, -1.0, 0.0], [0.0, 1.0, -1.0]]
    b = [[1.0], [0.0], [0.0]]
    ts, xs, _ = simulate(lti(a, b), [0.0, 0.0, 0.0], 0.0, t_end, dt, control=lambda t, x: 1.0)
    return ts, [x[2] for x in xs]


def test_worked_example_third_order_lag():
    ts, y = _third_order(0.01, 20.0)
    k, dead, tau = fit_fopdt(ts, y, 1.0, "tangent")
    assert abs(k - 1.0) < 1e-5
    assert abs(dead - 0.805472) < 1e-3 and abs(tau - 3.694528) < 1e-3
    k, dead, tau = fit_fopdt(ts, y, 1.0, "two-point")
    assert abs(dead - 1.149590) < 1e-3 and abs(tau - 2.108662) < 1e-3


def test_coarse_table_of_the_page():
    ts = [0.5 * i for i in range(41)]
    y = [1 - math.exp(-t) * (1 + t + t * t / 2) for t in ts]
    _, dead, tau = fit_fopdt(ts, y, 1.0, "two-point")
    assert abs(dead - 1.1387) < 1e-4 and abs(tau - 2.1315) < 1e-4
    _, dead, tau = fit_fopdt(ts, y, 1.0, "tangent")
    assert abs(dead - 0.7832) < 1e-4 and abs(tau - 3.7633) < 1e-4


def test_random_fopdt_responses_are_recovered():
    # Oracle: the closed form FOPDT step response. The dead time is a sample
    # time, so the chord tangent gives L exactly and T = h / (1 - e^(-h/T)).
    rng = random.Random(42)
    for _ in range(500):
        k = rng.choice((-1, 1)) * rng.uniform(0.2, 5.0)
        tau = rng.uniform(0.5, 5.0)
        h = tau / 20
        dead = h * rng.randint(0, 40)
        du = rng.choice((-1, 1)) * rng.uniform(0.5, 2.0)
        y0 = rng.uniform(-3, 3)
        ts = [h * i for i in range(int((dead + 16 * tau) / h) + 1)]
        y = [y0 + du * fopdt_step(k, dead, tau, t) for t in ts]
        k2, l2, t2 = fit_fopdt(ts, y, du, "two-point")
        assert abs(k2 - k) < 1e-5 * abs(k)
        assert abs(l2 - dead) < 0.01 * tau and abs(t2 - tau) < 0.01 * tau
        k3, l3, t3 = fit_fopdt(ts, y, du, "tangent")
        assert abs(l3 - dead) < 1e-9 * (1 + dead)
        assert abs(t3 - h / (1 - math.exp(-h / tau))) < 1e-5 * tau


def test_negative_gain_and_offset():
    ts = [0.1 * i for i in range(301)]
    y = [2 + 0.5 * fopdt_step(-6, 1.0, 2.0, t) for t in ts]
    k, dead, tau = fit_fopdt(ts, y, 0.5, "two-point")
    assert abs(k + 6) < 1e-4 and abs(dead - 1.0) < 0.01 and abs(tau - 2.0) < 0.01


def test_no_dead_time():
    ts = [0.05 * i for i in range(400)]
    y = [fopdt_step(1.0, 0.0, 1.0, t) for t in ts]
    _, dead, _ = fit_fopdt(ts, y, 1.0, "tangent")
    assert abs(dead) < 1e-12


def test_bad_arguments():
    ts = [0.0, 1.0, 2.0, 3.0]
    y = [0.0, 0.5, 0.9, 1.0]
    for args in ((ts, y, 0.0), (ts, [0.0] * 4, 1.0), (ts[:2], y[:2], 1.0),
                 ([0.0, 2.0, 1.0, 3.0], y, 1.0), (ts, y, 1.0, "other")):
        try:
            fit_fopdt(*args)
        except ValueError:
            continue
        raise AssertionError("expected ValueError for %r" % (args,))

History

Ziegler and Nichols in 1942 proposed to record the reaction curve of a process after a step of the controller output, to draw the tangent at its steepest point, and to read from it an apparent dead time and a reaction rate; their controller settings were given in terms of these two numbers. Cohen and Coon in 1953 derived settings from the first-order plus dead time model that the curve suggests. Two-point readings based on fixed percentages of the final change, and area methods, came later to make the reading less dependent on drawing a tangent. Skogestad's rules of 2003 are a modern set of tuning formulas built on the same three numbers.

References

  1. John G. Ziegler and Nathaniel B. Nichols, Optimum settings for automatic controllers, Transactions of the ASME 64, 759-768, 1942, the reaction curve method, the apparent dead time and the reaction rate read from the tangent at the steepest point, and the controller settings derived from them
  2. G. H. Cohen and G. A. Coon, Theoretical consideration of retarded control, Transactions of the ASME 75, 827-834, 1953, controller settings for a first-order process with dead time identified from the reaction curve
  3. Karl Johan Åström and Tore Hägglund, Advanced PID Control, ISA, 2006, the chapter on process models (step response methods, the tangent and area methods, and first-order plus dead time models)
  4. Sigurd Skogestad, Simple analytic rules for model reduction and PID controller tuning, Journal of Process Control 13(4), 291-309, 2003, the first-order plus dead time model and the SIMC tuning rules

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