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
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 and the period of the oscillation is the ultimate period . 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 , and . 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 with real polynomials, , a delay and a positive gain at low frequency. On a real plant the input is the experiment itself.
Input for the step response method. Samples of the response to an input step of size at , from rest, with a uniform time step .
Output. The parameters of the ideal PID form , or of its P or PI part.
The ultimate point. It is the smallest with degrees, and
At the closed loop with a P controller has the poles , so it oscillates with the period . So is the gain margin of the plant under unit proportional feedback. A plant whose phase stays above degrees, such as , has no finite ultimate gain, and the method does not apply.
The tables. For the ultimate cycle method:
| controller | |||
|---|---|---|---|
| P | |||
| PI | |||
| PID |
For the step response method, with the largest slope per unit input, the apparent delay and :
| controller | |||
|---|---|---|---|
| P | |||
| PI | |||
| PID |
Ziegler and Nichols gave the PI integral time as a reset rate of repeats per minute, which is . Many books round it to . The two tables agree on the PID times if .
The algorithm
ZN-ULTIMATE(n, d, theta, rule)- 1
phi_i ← continuous phase of P(j w_i) on a log grid w_0 < w_1 < ... < w_g - 2
i ← the first index with phi_i ≤ -pi; if there is none then fail - 3
w_u ← bisection of phi(w) = -pi on [w_(i-1), w_i] - 4
K_u ← 1/|P(j w_u)|; T_u ← 2 pi / w_u - 5
return (K, T_i, T_d) from the ultimate cycle table ZN-STEP(t, y, du, rule)- 6
j ← the sample with the largest slope R = (y_(j+1) - y_(j-1)) / (2 dt du) - 7
L ← t_j - (y_j - y_0) / (R du); a ← R L - 8
return (K, T_i, T_d) from the step response table
Line L1 starts the phase at degrees per net pole at the origin. It unwraps the phase of the rational part from one grid point to the next and adds for the delay. The grid has 4000 points from to rad/s. Line L3 halves the bracket until it is 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 . Its phase is , which is degrees at . Its gain there is . So and s. Indeed , with the roots . The code gives and to 15 digits.
The unit step response is , with the slope . The slope is largest at . So , s and . From a response sampled with s the code gives s. Here s, a little shorter than .
The loops. The table shows the four tunings and the closed loops that they give. The derivative has the filter constant , 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 s. The decay ratio is the second peak above the final value divided by the first. The load response is the response of to a unit step at the plant input.
| tuning | (s) | (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, , gives the final value , 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 .
Delays. For , the ultimate frequency solves , and . With s the code gives rad/s, s and . With s it gives rad/s and . The ultimate gain grows as the delay gets shorter, and for a first order lag has no finite ultimate gain.
Correctness
The proofs are in the correctness proof.
- The ultimate point (theorem). At the closed loop with a P controller has the poles . Conversely, a closed-loop pole on the imaginary axis can only occur at a frequency where the phase is degrees, with 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 that falls strictly with , then every gain 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 .
- The search (theorem). If the grid is fine enough that the phase moves less than 180 degrees between neighbours and crosses degrees only once inside each grid interval, lines L1 to L3 converge to .
- The tangent fit (theorem). At the inflection point the time has a zero derivative. So the fit has an error of order .
- 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 with real polynomials and , , and a delay . The P controller is a gain , so the loop transfer function is and the closed-loop poles are the roots of . The ultimate frequency is the smallest where the continuous phase of is . Then and .
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 the closed loop has the poles
If (modulo ) and , then and are roots of . Conversely, if with is a root for some , then modulo and .
Proof. By the assumptions . So . Multiply by , which is not 0 because is finite: . The coefficients are real, so the conjugate is a root too. For the converse, a root with gives , so is a negative real number with modulus . If , the equation gives too, and has a common factor that cancels; remove it first.
So the gain puts a pair of closed-loop poles on the imaginary axis, and the loop then oscillates with the period . This is the experiment that Ziegler and Nichols did by hand.
Claim 2: for the closed loop is asymptotically stable, under a monotone gain
Assume that 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 is strictly decreasing for . Then the closed loop with the gain is asymptotically stable for every .
Proof. Take . 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 does not pass through or encircle . (With a delay the criterion still holds, because is analytic in the right half plane away from the origin and tends to 0 as there.) For a pole at the origin the Nyquist contour goes around it on a small half circle , from to . There is close to with , a large arc through the positive real axis, which does not meet the ray . On the imaginary axis the curve can meet the negative real axis only at a frequency where modulo . Every such satisfies , because is the smallest one, and the same holds for by symmetry. By the monotone gain, . So the curve meets the negative real axis only to the right of . A closed curve that does not meet the ray has the winding number 0 about .
A product of at least one real lag with , perhaps with one integrator , an all-pass factor and a delay, has a strictly decreasing . 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 . That part is a measurement, not a theorem of this page.
Claim 3: lines L1 to L3 find
Assume that between neighbours of the log grid the phase of the rational part changes by less than , and that the continuous phase does not go below and back between two neighbours. Then the scan finds the first interval that contains , and the bisection converges to .
Proof. As , is close to , with the ratio of the lowest nonzero coefficients and the number of net poles at the origin. For the phase starts at ; for the code stops with an error, because the controller then needs the reverse action. The phase of the rational part is known modulo at each grid point. Line L1 adds the wrapped difference to the running phase. Under the first assumption this wrapped difference is the true change of the continuous phase, so by induction is the continuous phase at . The delay adds exactly. Line L2 takes the first with . Then . Under the second assumption no crossing lies below , so . On this interval the function 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 from the phase at plus a wrapped difference, which is right by the first assumption. Line L3 keeps , and each step halves , so and converge to a zero of in the bracket. A zero of in the bracket is when is decreasing there; this holds for the plants of Claim 2, where each lag and the delay decrease the phase.
With 4000 grid points from to rad/s, neighbours differ by the factor . A real lag changes its phase by at most rad over such a step, and a delay by . The assumptions hold with a large margin unless the delay is long compared with or the plant has lightly damped poles.
Claim 4: the tangent fit has an error of order
Let be four times continuously differentiable with a single inflection point , where is the largest slope and , . Sample with the step . Then lines L6 and L7 give and the apparent delay with errors .
Proof. The central difference equals . Line L6 takes the with the largest . Near , , so the chosen satisfies , and . For line L7 let , the time where the tangent at crosses . Its derivative is
which is 0 at . So . Line L7 computes with in place of , which adds a further .
For and a unit step, and . The slope is largest at , so . With the apparent delay is , and . With the code gives , an error of , as the claim predicts.
Claim 5: the cost
The ultimate point search costs operations for grid points and a plant of degree , plus per bisection step. The tangent fit costs for samples.
Proof. Each grid point needs two Horner evaluations of degree at most and a fixed number of other operations. The bisection stops after at most 200 steps, and in practice after about 50, when . Line L6 visits each sample once and line L7 is a fixed number of operations.
Complexity
The search evaluates the plant at grid points. Each evaluation is two Horner evaluations of degree at most , so the search costs time. The bisection adds about 50 steps of each. The tangent fit visits each of the samples once, so it costs . The phase list takes space. The cost that counts on a real plant is the time of the experiment: the ultimate cycle method needs several periods 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, and , or and . Plants with the same two numbers get the same controller.
- Scale. The controller gain scales as or , and the times scale with or . 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 , 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 . These rules use a first order model with a delay in place of the two numbers and , 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 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 in the paper and 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 and 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.
# 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
- 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
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 7QVRVJ Edit this page History Report an error Markdown