Algorithmintro
PID controller
Also called proportional-integral-derivative controller, three-term controller.
Sets the control to a weighted sum of the error, its integral and its filtered derivative, the most used controller in industry.
- Time
- O(k) worst
- Space
- O(1) extra
- Where
- k = the number of samples
- Model
- Real RAM
- Properties
- deterministicnot exactonlineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Nicolas Minorsky, 1922
A PID controller computes the control signal from the control error , the difference between the set point and the measured output . It adds three terms: one proportional to the error, one proportional to the integral of the error, and one proportional to the derivative of the error. The integral term removes the steady-state error for constant set points and loads. The derivative term adds phase lead and damping. A controller that is used on a real plant also needs a filter on the derivative, separate weights on the set point, limits on the output and a protection against integrator windup. This page gives the sampled algorithm with all of these parts, as computers run it, and proves its main properties.
In plain words
Think of a driver who keeps a car at a set speed. The driver presses the pedal more when the car is slow. That is the proportional part. If the car stays a little slow for a long time, for example on a long hill, the driver presses a little more each second until the error is gone. That is the integral part. If the speed starts to fall quickly, the driver reacts before the error becomes large. That is the derivative part. A PID controller does the same with three numbers that set how strong each part is. A computer reads the output at fixed times, updates the three parts and sends a new command each time.
The problem
Input. At each sampling instant , with the sampling period in seconds: the set point and the measured output . The parameters are:
- the gain , the integral time and the derivative time , in seconds;
- the filter constant , usually 5 to 20, so that the derivative filter has the time constant ;
- the set-point weights and , usually in ;
- the output limits and the tracking time for anti-windup.
Output. The control signal , held constant over by a zero-order hold.
The continuous controller. The algorithm approximates
With and this is the ideal (or standard) form applied to . Two other forms are common. The parallel form is , with , and . The series (or interacting) form is . Every series form has an ideal form. An ideal form has a series form with real parameters if and only if , because only then are the zeros of real. Old pneumatic controllers and many industrial products use the series form, so the same numbers mean different controllers in different products.
The algorithm
The integral is approximated by the forward difference and the filtered derivative by the backward difference, as Åström and Hägglund recommend. The output limits act on , and the difference is fed back into the integral with the gain . This is the back-calculation form of anti-windup.
PID-STEP(r, y) ▷ state: I, D, e_old; I = D = 0 at start- 1
once: b_i ← K h / T_i; a_r ← h / T_t; a_d ← T_d / (T_d + N h); b_d ← K T_d N / (T_d + N h) - 2
e ← r - y; e_d ← c r - y; if this is the first call then e_old ← e_d - 3
P ← K (b r - y) - 4
D ← a_d D + b_d (e_d - e_old) - 5
v ← P + I + D - 6
u ← min(max(v, u_min), u_max) - 7
I ← I + b_i e + a_r (u - v) - 8
e_old ← e_d - 9
return u
Line L1 runs once, when the parameters are set. With no integral action, set ; with no tracking, set . Line L2 starts the derivative at rest, so the first sample causes no jump in . Line L4 is the backward difference of ; its pole is in for every . Line L7 runs after line L9 sends in a real controller, because the integral update is not needed for the current output. This keeps the time from the reading of to the output of short.
Example
Plant and tuning. Take the plant , with time in seconds. Its ultimate gain is and its ultimate period is s. The classic Ziegler-Nichols PID rule gives , s and s. Take and s. Line L1 gives
| coefficient | formula | value |
|---|---|---|
| 0.132319 | ||
| 0.475589 | ||
| 22.8283 |
At the first sample and , so , , and . Then becomes .
Set-point weights. The plant is simulated with the classical Runge-Kutta method of order 4 and the step s, which divides . For a unit step in at , with no limits and :
| overshoot | peak time (s) | 2 percent settling time (s) | largest | |
|---|---|---|---|---|
| 1 | 0.5503 | 2.61 | 9.72 | 5.27 |
| 0.5 | 0.1826 | 3.00 | 7.90 | 3.17 |
| 0 | 0.0377 | 3.96 | 8.16 | 2.13 |
These numbers are measurements of this simulation. In all three runs is within of 1 at s, as Claim 3 of the proof says. A load step of at the plant input at s gives the same change of for each , to , as Claim 2 says. The weight trades the speed of the set-point response for its overshoot, without any change to the loop.
Robustness of this tuning. With the ideal derivative the loop has the gain crossover at 1.37545 rad/s, a phase margin of 30.62 degrees and the peak sensitivity . With the crossover moves to 1.40479 rad/s, the phase margin to 29.43 degrees and to 2.24. Both are on the aggressive side of the usual design range of from 1.2 to 2, which is a rule of thumb.
Limits. With and no tracking (), the overshoot is 0.569. With tracking and s, the overshoot is 0.162. The anti-windup page explains the difference.
Sampling period. Compare the sampled controller with the continuous controller on the same plant, over s. The largest difference of at the sampling instants is 0.0487 for , 0.0237 for and 0.0117 for . The error halves when halves, as expected for a first order difference scheme. With the overshoot grows to 0.654 and with to 0.914, because the hold adds a delay of about to the loop.
Correctness
The proofs are in the correctness proof.
- Difference approximations (proved). Line L7 is the forward Euler step of , and line L4 is the backward Euler step of the derivative filter. The filter pole is in for every , so the discrete filter is asymptotically stable (Schur) for every sampling period. The forward difference would need .
- Set-point weights (proved). Without limits, and change only the response to . The loop transfer function and the responses to load disturbances and noise do not depend on them. With a step in causes no derivative kick.
- Zero steady-state error (proved). If the closed loop converges for a constant and the output is not held at a limit, then converges to . The claim needs integral action. It does not say that the loop converges; that depends on the plant and the tuning.
- Back-calculation (proved). While the output is held at a limit with a constant error , and , the integral converges geometrically and tends to . Without tracking the integral grows without bound.
- Forms (proved). The series form converts to the ideal form, and an ideal form has a real series form if and only if .
- Convergence as (measured). The tests show the first order convergence of the sampled loop to the continuous loop on the example plant. The proof proves only that each update is a first order Euler step.
Proof: The sampled PID update has the stated filter, steady state and anti-windup propertiesfull
Notation is that of the page. The sampling period is , the samples are and , the error is and the derivative error is . The parameters are , (or no integral action), , and (or no tracking). Lines L1 to L9 compute
with and . Here clips to ; with no limits, .
Claim 1: the terms are Euler approximations of the continuous terms
The integral update is the forward Euler step of . The derivative update is the backward Euler step of . The filter pole is in for every , so the derivative filter is a Schur (asymptotically stable) first order filter for every sampling period.
Proof. The forward Euler step of is , which is line L7 when . For the filter, replace and at by the backward differences and :
Multiply by . This gives , which is line L4. For , and the value is in , and for it is 0. The homogeneous recursion then decays like .
The forward Euler step of the filter would give the pole , which is outside the unit disc when . This is why the backward difference is used.
Closed form on a ramp. If and , then for , so with . Since , induction gives . The continuous filter gives , and tends to as with . The test checks the discrete formula exactly in Fraction.
Claim 2: set-point weights change only the response to the set point
Without limits, is a linear function of the past and present and , and the part that acts on does not depend on or . So the loop transfer function, the response to a load disturbance and the response to measurement noise do not depend on and .
Proof. Without limits , so the recursions are linear. Write each signal as the sum of the part caused by and the part caused by . The coefficient of in is , in the update of it is (through ), and in the update of it is . None of these contains or . The parameters and multiply only . So the controller is with independent of and . The loop is closed through only, and every transfer function from a signal that enters the loop (a load disturbance or noise) to or contains only and the plant. By linearity, the response to and a load is the sum of the two separate responses, and only the first one changes with and .
With the derivative acts on only, so a step in causes no impulse in . With a step of size in adds to at that sample.
Claim 3: zero steady-state error with integral action
Let be finite and constant. If the closed loop converges, so that , and , and if (the output is not held at a limit, or there are no limits), then .
Proof. From line L7, . The left side tends to 0. The second term tends to . So , and , so .
The claim does not say that the loop converges. That depends on the plant and the tuning, and it is the subject of the stability analysis of the loop, for example with the Nyquist stability criterion.
Claim 4: back-calculation keeps the integral bounded under saturation
Let the output be at the limit for , with and constant. If , then converges geometrically with ratio , and converges to
Without tracking (), grows by at each sample, without bound if .
Proof. With and , line L7 reads . This is an affine recursion with the factor , and exactly when . Its fixed point satisfies , so . With the recursion is .
So with tracking, stays within of the limit, and comes back below the limit as soon as changes sign, up to this offset. Without tracking, comes back only after the sum of the errors has undone the growth of . This is the integrator windup effect.
Claim 5: the forms convert into each other
The series form equals the ideal form with
An ideal form has a series form with real if and only if . Then, with , one series form is , and . The parallel form has , and .
Proof. Expand the series form: . Match the constant, the and the terms with . The constant gives . The term gives , so . The term gives , so .
The ideal form is . The series form has the real zeros and . So a series form exists only if the numerator has real roots, that is , or . Conversely, if , the given and are real and positive, , , so , and . The parallel form follows by expanding the ideal form.
The series form is unique up to swapping the roles of and (with the gain changed to match); the formula returns the one with .
Cost
Line L1 runs once. Lines L3 to L8 use a fixed number of operations (at most 10 multiplications and 10 additions) and keep three numbers of state (, and ). So samples cost time and space.
Complexity
One call does a fixed number of operations: at most 10 multiplications, 10 additions and 2 comparisons, and line L1 adds 6 operations once. The state is three numbers, , and . So samples cost time and extra space. This fixed cost per sample is one reason that PID control runs on the smallest processors. A closed-loop simulation costs the number of integration steps times the cost of one step of the plant model.
Properties
- Online. Each output uses only the present and past samples.
- Not exact. The algorithm is exact for its own difference equations, but it approximates the continuous controller with an error of order .
- Linear inside the limits. Without saturation, the controller is a linear time-invariant discrete system of order 2 (one integrator state and one filter state).
- Proper. The filter makes the derivative part proper. Its gain at high frequency is in place of infinity.
- Fixed structure. Only two zeros and a pole at the origin can be placed. Plants with large delays, many oscillatory modes or strong coupling need other structures.
Variants and improvements
- PI and PD. With the controller is PI, the most common case in process control. Without integral action it is PD, used where the plant has an integrator, as in positioning.
- Velocity form. Compute the change and add it to the previous output. The integral is then implicit, and windup protection only needs a limit on the integrated output. This form is common in programmable controllers.
- Second order filter. Filter the measurement with before the controller, in place of the filter on the derivative only. This gives a roll-off of the whole controller at high frequency.
- Gain scheduling. Change , and with an operating variable. See gain scheduling.
- Tuning. The parameters come from rules such as Ziegler-Nichols tuning, from an experiment with relay autotuning, from internal model control, or from loop shaping.
- Other discretizations. The Tustin approximation of the whole controller is also used; see controller discretization.
- Structures. PID controllers are the building blocks of cascade control, feedforward control and the Smith predictor.
When to use it
Use a PID controller for a single loop where the plant has dominant dynamics of first or second order, perhaps with a short delay, and where the aim is to hold the output at a set point against loads. Most flow, pressure, level, temperature and speed loops are of this kind. Use PI when the measurement is noisy or the plant is close to first order. Add the derivative when the plant has two lags of similar size or when the loop must be fast. Use another design when the delay is long compared with the time constants, when several loops interact strongly (see relative gain array), or when constraints must be handled in a planned way, as in model predictive control.
Pitfalls
- Unfiltered derivative. The ideal derivative amplifies measurement noise without limit. Always filter it, and choose so that the noise in is acceptable.
- Derivative kick. With a step in the set point gives an impulse in . Use unless the set point is smooth.
- Windup. If the actuator saturates and nothing stops the integral, the integral grows during the saturation, and the overshoot afterwards can be large. Use tracking or conditional integration.
- Forms differ. The same three numbers give different controllers in the ideal, series and parallel forms. Convert the parameters before moving a tuning to another product.
- Sign of the action. If the plant gain is negative, the controller must use the reverse action. A wrong sign gives positive feedback.
- Bumpless transfer. When the operator moves from manual to automatic, set the integral so that equals the present manual output. Otherwise the output jumps.
- Sampling. The hold adds a delay of about , which reduces the phase margin by about radians at the crossover frequency . Take many samples per closed-loop rise time, and check the margins of the sampled loop. The example shows how the overshoot grows with .
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()
pid_controller.py 148 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/pid-controller/. The authors are listed in prov/M0FN5Q.jsonl.
"""A sampled PID controller with a derivative filter, set-point weights,
output limits and anti-windup by back-calculation.
The continuous controller, in the ideal (standard) form, is
U(s) = K (b R - Y) + K/(T_i s) (R - Y) + K T_d s/(1 + s T_d/N) (c R - Y).
The sampled version follows Astrom and Hagglund (2006), Section 13.3:
- the integral term uses the forward difference;
- the filtered derivative uses the backward difference, which gives a
filter pole a_d = T_d/(T_d + N h) in [0, 1) for every h > 0;
- the integral state also takes a correction (h/T_t)(u - v), where v is
the computed output and u the output after the limits.
The class works in exact arithmetic when every parameter and signal is an
int or a Fraction and there are no limits (or the limits are exact).
Use Ti = None for no integral action and Td = 0 for no derivative action,
and Tt = None for no anti-windup.
"""
import cmath
import math
__all__ = [
"PID", "ideal_to_parallel", "parallel_to_ideal", "series_to_ideal",
"ideal_to_series", "pid_frequency_response",
]
class PID:
"""Sampled PID controller (pseudocode lines L1 to L9)."""
def __init__(self, K, Ti=None, Td=0, N=10, h=1, b=1, c=0,
Tt=None, umin=None, umax=None):
if h <= 0:
raise ValueError("the sampling period h must be positive")
if Ti is not None and Ti <= 0:
raise ValueError("Ti must be positive or None")
if Td < 0 or N <= 0:
raise ValueError("Td must be at least 0 and N positive")
if Tt is not None and Tt <= 0:
raise ValueError("Tt must be positive or None")
if umin is not None and umax is not None and umin > umax:
raise ValueError("umin is above umax")
self.K, self.b, self.c = K, b, c
self.umin, self.umax = umin, umax
self.bi = 0 if Ti is None else K * h / Ti # @line L1
self.ar = 0 if Tt is None else h / Tt
if Td == 0:
self.ad, self.bd = 0, 0
else:
self.ad = Td / (Td + N * h)
self.bd = K * Td * N / (Td + N * h)
self.I = 0
self.D = 0
self.ed_old = None
def _limit(self, v):
if self.umax is not None and v > self.umax:
return self.umax
if self.umin is not None and v < self.umin:
return self.umin
return v
def step(self, r, y, uff=0):
"""Return the output u for the set point r and the measurement y.
uff is an optional feedforward term added before the limits.
At the first call the derivative has no past value, so it starts
at 0 (no derivative kick at start up).
"""
ed = self.c * r - y # @line L2
if self.ed_old is None:
self.ed_old = ed
P = self.K * (self.b * r - y) # @line L3
self.D = self.ad * self.D + self.bd * (ed - self.ed_old) # @line L4
v = P + self.I + self.D + uff # @line L5
u = self._limit(v) # @line L6
self.I = self.I + self.bi * (r - y) + self.ar * (u - v) # @line L7
self.ed_old = ed # @line L8
return u # @line L9
def reset(self, I=0, D=0):
"""Set the integral and derivative states (for bumpless transfer)."""
self.I, self.D, self.ed_old = I, D, None
def ideal_to_parallel(K, Ti, Td):
"""Return (kp, ki, kd) with kp + ki/s + kd s = K (1 + 1/(Ti s) + Td s)."""
return K, K / Ti, K * Td
def parallel_to_ideal(kp, ki, kd):
"""Inverse of ideal_to_parallel; needs kp > 0 and ki > 0."""
if kp <= 0 or ki <= 0:
raise ValueError("the ideal form needs kp > 0 and ki > 0")
return kp, kp / ki, kd / kp
def series_to_ideal(Ks, Tis, Tds):
"""Return (K, Ti, Td) with K (1 + 1/(Ti s) + Td s) equal to
Ks (1 + 1/(Tis s)) (1 + Tds s)."""
return Ks * (Tis + Tds) / Tis, Tis + Tds, Tis * Tds / (Tis + Tds)
def ideal_to_series(K, Ti, Td):
"""Return the series form of an ideal PID.
It exists if and only if Ti >= 4 Td, because the zeros of the ideal
form are real only then. The result is in floating point (a square
root).
"""
if Ti < 4 * Td:
raise ValueError("no series form: the zeros are complex (Ti < 4 Td)")
q = math.sqrt(1 - 4 * Td / Ti)
return K * (1 + q) / 2, Ti * (1 + q) / 2, Ti * (1 - q) / 2
def pid_frequency_response(K, Ti, Td, N, omega, b=1, c=1):
"""Return C(j omega) of the continuous controller from e = r - y.
N = None gives the ideal derivative K Td s. b and c weight the set
point; C is the transfer function from the error when b = c = 1.
"""
s = 1j * omega
ci = 0 if Ti is None else 1 / (Ti * s)
if Td == 0:
cd = 0
elif N is None:
cd = Td * s
else:
cd = Td * s / (1 + s * Td / N)
return complex(K * (1 + ci + cd))
def _self_test():
k, ti, td = ideal_to_series(*series_to_ideal(2.0, 4.0, 1.0))
assert abs(k - 2.0) < 1e-12 and abs(ti - 4.0) < 1e-12 and abs(td - 1.0) < 1e-12
c = pid_frequency_response(1.0, 1.0, 0.0, None, 1.0)
assert abs(c - (1 - 1j)) < 1e-15 and abs(cmath.phase(c) + math.pi / 4) < 1e-15
return True
if __name__ == "__main__":
_self_test()
test_pid_controller.py 183 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/pid-controller/. The authors are listed in prov/M0FN5Q.jsonl.
import cmath
import math
import random
from fractions import Fraction as Fr
import pytest
from ctlmat import polyval
from ctlsim import simulate
from pid_controller import (PID, ideal_to_parallel, ideal_to_series,
parallel_to_ideal, pid_frequency_response,
series_to_ideal)
# Plant P(s) = 1/(s + 1)^3 as a chain of three first order lags, y = x3.
# Simulation: RK4 with dt = 0.01 s, zero-order hold over h. Tolerances are
# given at each assert.
TU = 2 * math.pi / math.sqrt(3) # ultimate period of 1/(s + 1)^3
ZN = dict(K=4.8, Ti=TU / 2, Td=TU / 8, N=10)
def plant(t, x, u):
return [-x[0] + u, -x[1] + x[0], -x[2] + x[1]]
def run(pid, t1, h, dt=0.01, r=lambda t: 1.0, load=lambda t: 0.0):
n = round(t1 / dt)
assert abs(n * dt - t1) < 1e-9 and abs(round(h / dt) * dt - h) < 1e-12
def ctl(t, x):
return pid.step(r(t), x[2]) + load(t)
ts, xs, us = simulate(plant, [0.0, 0.0, 0.0], 0.0, t1, dt, control=ctl, hold=h)
assert len(ts) == n + 1
return ts, [x[2] for x in xs], us
def test_integral_and_proportional_terms_are_exact():
K, Ti, h = Fr(3, 2), Fr(5, 2), Fr(1, 10)
pid = PID(K, Ti=Ti, Td=0, h=h, b=Fr(1, 2))
r, y = Fr(2), Fr(1, 3)
for k in range(25):
u = pid.step(r, y)
assert u == K * (Fr(1, 2) * r - y) + k * K * h / Ti * (r - y)
def test_derivative_filter_is_exact_on_a_ramp():
# y_k = k h, r = 0: D_k = -K Td (1 - a_d^k) with a_d = Td/(Td + N h).
K, Td, N, h = Fr(2), Fr(1, 2), Fr(5), Fr(1, 20)
pid = PID(K, Ti=None, Td=Td, N=N, h=h, b=0)
ad = Td / (Td + N * h)
for k in range(30):
u = pid.step(0, k * h)
assert u == -K * k * h - K * Td * (1 - ad ** k)
assert ad == Fr(2, 3)
def test_no_derivative_kick_with_c_zero():
pid0 = PID(1.0, Ti=None, Td=1.0, N=10, h=0.1, c=0)
pid1 = PID(1.0, Ti=None, Td=1.0, N=10, h=0.1, c=1)
for p in (pid0, pid1):
p.step(0.0, 0.0)
u0, u1 = pid0.step(1.0, 0.0), pid1.step(1.0, 0.0)
assert u0 == 1.0
# c = 1: the kick is bd = K Td N/(Td + N h) = 5 on top of K r = 1
assert abs(u1 - 6.0) < 1e-12
def test_closed_loop_step_has_zero_steady_state_error():
ts, ys, us = run(PID(h=0.05, b=1, **ZN), t1=60.0, h=0.05)
assert abs(ys[-1] - 1.0) < 1e-8
over = max(ys) - 1.0
assert 0.50 < over < 0.60 # measured 0.5503 with h = 0.05, N = 10
assert abs(us[-1] - 1.0) < 1e-7 # P(0) = 1, so u tends to r
def test_set_point_weight_changes_only_the_set_point_response():
load = lambda t: -0.5 if t >= 30.0 else 0.0
ys_by_b = {}
for b in (0.0, 0.5, 1.0):
_, y_load, _ = run(PID(h=0.05, b=b, **ZN), t1=60.0, h=0.05, load=load)
_, y_free, _ = run(PID(h=0.05, b=b, **ZN), t1=60.0, h=0.05)
ys_by_b[b] = (y_load, y_free)
base = [a - f for a, f in zip(*ys_by_b[1.0])]
for b in (0.0, 0.5):
diff = [a - f for a, f in zip(*ys_by_b[b])]
assert max(abs(p - q) for p, q in zip(diff, base)) < 1e-12
over = {b: max(ys_by_b[b][1]) - 1.0 for b in ys_by_b}
assert over[0.0] < over[0.5] < over[1.0]
assert over[0.0] < 0.05 # measured 0.0377
def continuous_pid_error(h, t1=20.0, dt=0.005):
"""Max |y_h(t_k) - y(t_k)| over the sampling instants, against the
continuous PID (states x1, x2, x3, I, xf), both with RK4 and step dt."""
K, Ti, Td, N = ZN["K"], ZN["Ti"], ZN["Td"], ZN["N"]
def f(t, x, _):
y = x[2]
e = 1.0 - y
u = K * (1.0 - y) + x[3] - K * N * (y - x[4])
return [-x[0] + u, -x[1] + x[0], -x[2] + x[1], K / Ti * e, N / Td * (y - x[4])]
_, xs, _ = simulate(f, [0.0] * 5, 0.0, t1, dt)
pid = PID(h=h, b=1, **ZN)
_, xs_h, _ = simulate(plant, [0.0] * 3, 0.0, t1, dt,
control=lambda t, x: pid.step(1.0, x[2]), hold=h)
r = round(h / dt)
return max(abs(xs[k][2] - xs_h[k][2]) for k in range(0, len(xs), r))
def test_sampled_pid_converges_to_the_continuous_pid():
errs = [continuous_pid_error(h) for h in (0.08, 0.04, 0.02)]
# first order in h: each halving should cut the error by about 2
assert errs[1] < 0.65 * errs[0] and errs[2] < 0.65 * errs[1]
assert errs[2] < 0.05
def test_back_calculation_reduces_overshoot_under_saturation():
lim = dict(umin=-2.0, umax=2.0)
_, y_sat, u_sat = run(PID(h=0.05, b=1, **ZN, **lim), t1=40.0, h=0.05)
tt = math.sqrt(ZN["Ti"] * ZN["Td"])
_, y_aw, u_aw = run(PID(h=0.05, b=1, Tt=tt, **ZN, **lim), t1=40.0, h=0.05)
assert max(u_sat) == 2.0 and max(u_aw) == 2.0
assert min(u_sat) >= -2.0 and min(u_aw) >= -2.0
assert max(y_sat) - 1.0 > 0.5 # measured 0.569
assert max(y_aw) - 1.0 < 0.2 # measured 0.162
assert abs(y_aw[-1] - 1.0) < 1e-6
def test_back_calculation_fixed_point_under_saturation():
# With e and u held, I converges to the value where
# K h e / Ti + (h / Tt)(u - v) = 0, that is v = umax + Tt K e / Ti.
K, Ti, Tt, h = 2.0, 4.0, 0.5, 0.01
pid = PID(K, Ti=Ti, Td=0, h=h, Tt=Tt, umax=1.0)
for _ in range(3000):
u = pid.step(3.0, 0.0)
v = K * 3.0 + pid.I
assert u == 1.0
assert abs(v - (1.0 + Tt * K * 3.0 / Ti)) < 1e-9
def test_form_conversions():
rng = random.Random(7)
for _ in range(200):
Ks = Fr(rng.randint(1, 50), rng.randint(1, 9))
Tis = Fr(rng.randint(1, 50), rng.randint(1, 9))
Tds = Fr(rng.randint(1, 50), rng.randint(1, 9))
K, Ti, Td = series_to_ideal(Ks, Tis, Tds)
assert Ti >= 4 * Td
assert parallel_to_ideal(*ideal_to_parallel(K, Ti, Td)) == (K, Ti, Td)
k2, ti2, td2 = ideal_to_series(K, Ti, Td)
# the series form is unique up to swapping Tis and Tds with
# the matching gain; ideal_to_series returns Tis >= Tds
hi, lo = max(Tis, Tds), min(Tis, Tds)
assert abs(ti2 - hi) < 1e-9 * hi and abs(td2 - lo) < 1e-9 * hi
s = 0.3j + 0.1
c_ser = complex(Ks) * (1 + 1 / (complex(Tis) * s)) * (1 + complex(Tds) * s)
c_id = complex(K) * (1 + 1 / (complex(Ti) * s) + complex(Td) * s)
assert abs(c_ser - c_id) < 1e-9 * abs(c_id)
with pytest.raises(ValueError):
ideal_to_series(1.0, 1.0, 0.3)
def test_margins_of_the_ziegler_nichols_loop():
# Ideal derivative: phase margin 30.62 degrees at 1.37545 rad/s.
def loop(w, N):
p = 1 / polyval([1, 3, 3, 1], 1j * w)
return p * pid_frequency_response(ZN["K"], ZN["Ti"], ZN["Td"], N, w)
for N, w_want, pm_want in ((None, 1.37545, 30.619), (10, 1.40479, 29.428)):
lo, hi = 0.5, 3.0
for _ in range(80):
mid = (lo + hi) / 2
if abs(loop(mid, N)) > 1:
lo = mid
else:
hi = mid
pm = 180 + math.degrees(cmath.phase(loop(lo, N)))
assert abs(lo - w_want) < 1e-5 and abs(pm - pm_want) < 1e-3
History
Nicolas Minorsky studied the automatic steering of ships and published in 1922 an analysis that recommended a steering law with proportional, integral and derivative terms. Pneumatic process controllers with proportional and reset (integral) action came into use in the 1930s, and the derivative action was added under the name pre-act. Ziegler and Nichols used these terms in 1942, when they gave the first tuning rules. Electronic analog controllers and then computer controllers replaced most of the pneumatic ones. The computer made it easy to add the filter, the set-point weights, anti-windup and automatic tuning. Åström and Hägglund describe this development and the modern form of the algorithm.
References
- Nicolas Minorsky, Directional stability of automatically steered bodies, Journal of the American Society of Naval Engineers 34(2) (1922) 280-309, the whole paper (the steering law with proportional, integral and derivative terms)
- Karl Johan Åström and Tore Hägglund, Advanced PID Control, ISA, 2006, Chapter 3, PID Control (Sections 3.2 to 3.5, the forms, the derivative filter, set-point weighting and windup) and Section 13.3, Computer implementations
- Karl Johan Åström and Richard M. Murray, Feedback Systems, second edition, Princeton University Press, 2021, Chapter 11, PID Control (the sections on integral windup and on implementation)
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| 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 M0FN5Q Edit this page History Report an error Markdown