Algorithm Search⌘K

Algorithmcore

Relay feedback autotuning

Also called Astrom-Hagglund relay autotuning, relay tuning.

Puts a relay in the loop to make a limit cycle, reads the ultimate gain and period from it, and tunes a PID from them.

Time
O(k n^2) worst
Space
O(k) extra
Where
k = the number of simulation steps or samples; n = the order of the plant
Properties
deterministicnot exactonlineiterative
Origin
Karl Johan Åström, Tore Hägglund, 1984

Relay feedback autotuning finds the ultimate point of a plant with a short experiment in closed loop. A relay, a switch with the two outputs +d+d and −d-d, replaces the controller. For most process plants the loop then settles into a limit cycle. Its period is close to the ultimate period TuT_u, and its amplitude aa gives the estimate 4d/(πa)4 d/(\pi a) of the ultimate gain KuK_u. A rule such as the Ziegler-Nichols ultimate cycle rule then gives the settings of a PID controller. Unlike the original Ziegler-Nichols experiment, the loop is never brought close to a growing oscillation, and the size of the oscillation is set by dd.

In plain words

Put a simple switch in place of the controller. When the output is below the target, the switch pushes up with full force. When the output is above the target, it pushes down. The output then swings up and down at a steady rate. The time of one swing tells how fast the plant is. The size of the swing, compared with the size of the push, tells how much gain the plant has at that rate. These two numbers are almost the same as the two numbers that the Ziegler-Nichols method needs. So a controller can run the test by itself, compute its settings and switch back to normal control, all in a few swings. The person who starts the test only chooses how hard the switch pushes.

The problem

Input. A plant that can run in closed loop with a relay. For a simulation, a linear model x′=Ax+Bu(t−θ)x' = A x + B u(t - \theta), y=Cxy = C x of order nn with a delay θ≥0\theta \ge 0. The relay amplitude d>0d > 0, an optional hysteresis ε≥0\varepsilon \ge 0, the step Δt\Delta t and the length of the experiment.

Output. The period TT and the amplitude aa of the limit cycle, the estimates K^u=4d/(πa)\hat K_u = 4 d/(\pi a) and T^u=T\hat T_u = T, and the controller settings from a tuning rule.

The relay. With the error e=r−ye = r - y, the relay gives u=+du = +d when e>εe > \varepsilon, u=−du = -d when e<−εe < -\varepsilon, and keeps its last value in between.

Why it works. Assume that yy is close to a sine of amplitude aa. The relay output is a square wave in phase with ee, and the first harmonic of a square wave of amplitude dd has the amplitude 4d/π4 d/\pi. A plant that passes this first harmonic and damps the higher ones gives the loop condition

P(jω)=−πa4d.P(j\omega) = -\frac{\pi a}{4 d}.

So the cycle runs at a frequency where the phase of PP is −180-180 degrees, and 1/∣P(jω)∣=4d/(πa)1/|P(j\omega)| = 4 d/(\pi a). This is the describing function method. It is an approximation, because yy is not a pure sine. With hysteresis the relay switches later, and the same argument gives the point where the phase of PP is −180+arcsin⁡(ε/a)-180 + \arcsin(\varepsilon/a) degrees.

The algorithm

  1. RELAY-AUTOTUNE(plant, d, eps, rule)
  2. 1u ← +d
  3. 2at each step: e ← r - y; if e > eps then u ← +d; if e < -eps then u ← -d
  4. 3apply u to the plant for one step and record y
  5. 4when the run ends: find the upward crossings of r by y, by linear interpolation
  6. 5T ← the mean time between crossings over the last m periods
  7. 6a ← half the peak-to-peak value of y over the same periods
  8. 7K ← 4 d / (pi a)
  9. 8return rule(K, T)

Lines L2 and L3 repeat until the cycle has settled. The code runs a fixed time and uses the last m=3m = 3 full periods; a real autotuner stops when two periods in a row agree within a tolerance. A real relay acts at the sampling instants only, and so does the simulated one, which adds up to one sample of delay to each switch. The simulation uses the classical Runge-Kutta method with the step Δt\Delta t, and the delay is a queue of whole steps.

The code also computes the exact symmetric limit cycle for a plant with no delay and no hysteresis. With Φ=eAτ\Phi = e^{A\tau} and Γ=∫0τeAs ds B\Gamma = \int_0^\tau e^{As}\, ds\, B, the state at a switch is x0=−(I+Φ)−1Γdx_0 = -(I + \Phi)^{-1} \Gamma d, and the half period τ\tau solves Cx0(τ)=0C x_0(\tau) = 0. A grid scan and bisection give τ\tau. This shows how large the error of the describing function is, apart from the effects of sampling.

Example

A third order lag. Take P(s)=1/(s+1)3P(s) = 1/(s + 1)^3 and d=1d = 1. The true ultimate point is Ku=8K_u = 8 and Tu=2π/3=3.62760T_u = 2\pi/\sqrt 3 = 3.62760 s.

quantity exact cycle simulation, Δt=0.005\Delta t = 0.005 s true value
period TT (s) 3.67975 3.69000 Tu=3.62760T_u = 3.62760
amplitude aa 0.163061 0.164096
4d/(πa)4 d/(\pi a) 7.8083 7.7591 Ku=8K_u = 8

The exact cycle has a period 1.4 percent longer than TuT_u and a gain estimate 2.4 percent below KuK_u. That is the error of the describing function for this plant. The simulation adds about 2Δt2 \Delta t to the period, because each switch waits for the next step. The ultimate cycle PID rule gives K=4.6555K = 4.6555, Ti=1.8450T_i = 1.8450 s and Td=0.46125T_d = 0.46125 s, close to the values 4.8, 1.8138 s and 0.4534 s from the true ultimate point. With a derivative filter N=20N = 20 the loop has an overshoot of 0.504 to a set-point step. These numbers are measurements.

A plant with an integrator. For P(s)=1/(s(s+1)(s+2))P(s) = 1/(s(s + 1)(s + 2)), with Ku=6K_u = 6 and Tu=4.44288T_u = 4.44288 s, the exact cycle has T=4.55107T = 4.55107 s and 4d/(πa)=5.78654 d/(\pi a) = 5.7865. The errors are 2.4 and 3.6 percent.

A first order lag with a delay. For P(s)=e−θs/(s+1)P(s) = e^{-\theta s}/(s + 1) the cycle has a closed form: the half period is θ+ln⁡(2−e−θ)\theta + \ln(2 - e^{-\theta}) and the amplitude is d(1−e−θ)d(1 - e^{-\theta}). The output has corners, so the describing function is less accurate here.

θ\theta (s) cycle period (s) true TuT_u (s) 4d/(πa)4 d/(\pi a) true KuK_u
0.5 1.6636 1.7106 3.2359 3.8069
1 2.9798 3.0971 2.0142 2.2618
2 5.2462 5.4901 1.4725 1.5198

The gain estimate is 15 percent low for θ=0.5\theta = 0.5 s and 3 percent low for θ=2\theta = 2 s. A low estimate gives a lower controller gain, which errs on the safe side.

Hysteresis. With ε=0.05\varepsilon = 0.05 on the third order lag the cycle slows to T=4.33T = 4.33 s with a=0.23283a = 0.23283. The estimate is the point with the gain 5.46865.4686 at the phase −167.60-167.60 degrees. At ω=2π/T\omega = 2\pi/T the plant has 1/∣P∣=5.47301/|P| = 5.4730 and the phase −166.28-166.28 degrees. So the hysteresis moves the point found away from the ultimate point, as the formula says.

Correctness

The proofs are in the correctness proof.

  • Scaling (theorem). Without hysteresis, the period of the cycle does not depend on dd and its amplitude is proportional to dd. So dd sets the size of the test without a change of the result.
  • The exact cycle (theorem). For a plant with no delay, a symmetric cycle with the half period τ\tau has the switching state x0=−(I+Φ)−1Γdx_0 = -(I + \Phi)^{-1} \Gamma d with Cx0=0C x_0 = 0, and such an x0x_0 gives a cycle if yy keeps its sign over the half period. For a first order lag with a delay the cycle has a closed form.
  • The estimate (approximation). If yy is a sine, harmonic balance gives P(jω)=−(πa/(4d))ejarcsin⁡(ε/a)P(j\omega) = -(\pi a/(4 d)) e^{j \arcsin(\varepsilon/a)}. Because yy is not a sine, 4d/(πa)4 d/(\pi a) is an estimate of KuK_u, not its value. The errors in the example are measurements.
  • The analysis of the record (theorem). Linear interpolation of the crossings and the largest samples give the period and the amplitude of a sampled smooth cycle with an error of order Δt2\Delta t^2.
  • Convergence to the cycle (measurement). The page does not prove that the loop converges to the cycle. In the simulations it does within a few periods for every plant above.
Proof: The relay experiment gives a describing function estimate of the ultimate point, and the exact cycle can be computedfull

Notation is that of the page. The plant is x′=Ax+Bu(t−θ)x' = A x + B u(t - \theta), y=Cxy = C x, with one input and one output, transfer function P(s)=C(sI−A)−1Be−θsP(s) = C (sI - A)^{-1} B e^{-\theta s} and a delay θ≥0\theta \ge 0. The set point is r=0r = 0, so the error is e=−ye = -y. The relay gives u=+du = +d when e>εe > \varepsilon, u=−du = -d when e<−εe < -\varepsilon, and keeps its last value in between, with d>0d > 0 and the hysteresis ε≥0\varepsilon \ge 0.

The claims are of three kinds. Claims 1 and 2 are exact statements about the loop. Claim 3 is the describing function approximation, which is not exact; the page gives measured errors. Claim 4 is about the analysis of a sampled record.

Claim 1: the cycle scales with the relay amplitude

Let ε=0\varepsilon = 0 and c>0c > 0. If (x(t),u(t))(x(t), u(t)) is a solution of the loop with the relay amplitude dd, then (c x(t),c u(t))(c\, x(t), c\, u(t)) is a solution with the amplitude c dc\, d. So the period of a limit cycle does not depend on dd, and its amplitude is proportional to dd. With ε>0\varepsilon > 0 the same holds when ε\varepsilon is scaled by cc too.

Proof. The plant equation is linear, so c xc\, x solves it with the input c uc\, u. The relay with no hysteresis uses only the sign of e=−Cxe = -C x, and the sign of −C(c x)-C (c\, x) is that of −Cx-C x. So the relay with amplitude c dc\, d gives exactly c uc\, u. With hysteresis the thresholds ±ε\pm \varepsilon must scale with xx, which needs the hysteresis c εc\, \varepsilon. □\square

Claim 2: the symmetric cycle without delay and hysteresis

Let θ=0\theta = 0 and ε=0\varepsilon = 0. For τ>0\tau > 0 let Φ=eAτ\Phi = e^{A\tau} and Γ=∫0τeAs ds B\Gamma = \int_0^\tau e^{As}\, ds\, B, and assume that I+ΦI + \Phi is invertible. The loop has a symmetric periodic solution with the period 2τ2\tau, in which yy crosses 0 downward at t=0t = 0 and u=+du = +d on (0,τ)(0, \tau), if and only if

x0=−(I+Φ)−1ΓdsatisfiesCx0=0,x_0 = -(I + \Phi)^{-1} \Gamma d \quad \text{satisfies} \quad C x_0 = 0,

y(t)<0y(t) < 0 on (0,τ)(0, \tau) for the solution from x0x_0 with u=+du = +d, and C(Ax0−Bd)<0C(A x_0 - B d) < 0, so that yy indeed falls through 0 just before t=0t = 0.

Proof. Assume such a solution. On (0,τ)(0, \tau) the input is the constant +d+d, so x(τ)=Φx0+Γdx(\tau) = \Phi x_0 + \Gamma d. Symmetry means that the second half of the period is the first half with all signs changed, so x(τ)=−x0x(\tau) = -x_0. Then (I+Φ)x0=−Γd(I + \Phi) x_0 = -\Gamma d, which gives the formula. The switch at t=0t = 0 needs y(0)=Cx0=0y(0) = C x_0 = 0, and the input stays at +d+d only if e=−y>0e = -y > 0, that is y<0y < 0, on (0,τ)(0, \tau). Just before t=0t = 0 the input was −d-d, so y′(0−)=C(Ax0−Bd)y'(0^-) = C(A x_0 - B d), and a downward crossing needs this to be negative.

Conversely, let x0x_0 satisfy the conditions. From x0x_0 with u=+du = +d, yy stays below 0 on (0,τ)(0, \tau), so the relay keeps u=+du = +d, and x(τ)=Φx0+Γd=−x0x(\tau) = \Phi x_0 + \Gamma d = -x_0. Now y(τ)=−Cx0=0y(\tau) = -C x_0 = 0 and yy rises through 0, so the relay switches to −d-d. By the symmetry of the equations under (x,u)→(−x,−u)(x, u) \to (-x, -u), the next half period is the first one with signs changed, and the state returns to x0x_0 at 2τ2\tau. □\square

The code finds the first sign change of τ↦Cx0(τ)\tau \mapsto C x_0(\tau) on a grid and refines it by bisection. It computes Φ\Phi and Γ\Gamma together, as the upper blocks of the exponential of the matrix [AB00]τ\left[\begin{smallmatrix} A & B \\ 0 & 0 \end{smallmatrix}\right] \tau. The tests check the conditions on the solution afterwards. The cycle may still be one of several, and the claim says nothing about whether nearby solutions converge to it; the simulation shows that they do for the example plants.

A closed form with a delay. For P(s)=e−θs/(s+1)P(s) = e^{-\theta s}/(s + 1) and ε=0\varepsilon = 0, take y(t0)=0y(t_0) = 0 with yy falling, so the relay switches to +d+d at t0t_0. For the time θ\theta the plant still gets −d-d, so y(t0+θ)=−d(1−e−θ)y(t_0 + \theta) = -d(1 - e^{-\theta}). Then yy rises toward +d+d:

y(t)=d−d(2−e−θ)e−(t−t0−θ),y(t) = d - d (2 - e^{-\theta}) e^{-(t - t_0 - \theta)},

which is 0 after the further time ln⁡(2−e−θ)\ln(2 - e^{-\theta}). So the half period is τ=θ+ln⁡(2−e−θ)\tau = \theta + \ln(2 - e^{-\theta}) and the amplitude is a=d(1−e−θ)a = d(1 - e^{-\theta}). The tests compare the simulation with these values.

Claim 3: the describing function estimate

Assume that yy is close to a sine, y(t)=−asin⁡ωty(t) = -a \sin \omega t. Keep only the first harmonic of the relay output. Then P(jω)=−πa4dejarcsin⁡(ε/a)P(j\omega) = -\frac{\pi a}{4 d} e^{j \arcsin(\varepsilon/a)}. With ε=0\varepsilon = 0 this is the point where the phase of PP is −180-180 degrees, so ω\omega estimates ωu\omega_u and 4d/(πa)4 d/(\pi a) estimates KuK_u.

Proof. With no hysteresis, e=asin⁡ωte = a \sin \omega t and the relay output is a square wave of amplitude dd in phase with ee. Its Fourier series is 4dπ∑k oddsin⁡kωtk\frac{4 d}{\pi} \sum_{k \text{ odd}} \frac{\sin k\omega t}{k}, so the first harmonic is 4dπsin⁡ωt\frac{4 d}{\pi} \sin \omega t. With hysteresis the relay switches when ee passes +ε+\varepsilon upward and −ε-\varepsilon downward. This delays the square wave by arcsin⁡(ε/a)/ω\arcsin(\varepsilon/a)/\omega, so the first harmonic is 4dπsin⁡(ωt−ψ)\frac{4 d}{\pi} \sin(\omega t - \psi) with ψ=arcsin⁡(ε/a)\psi = \arcsin(\varepsilon/a). Harmonic balance asks that the plant maps this first harmonic to the assumed yy: in phasor form, P(jω)4dπe−jψ=−aP(j\omega) \frac{4 d}{\pi} e^{-j\psi} = -a. Solve for P(jω)P(j\omega). □\square

The assumption is not exact: yy also contains the odd harmonics of the square wave, filtered by PP. The estimate is good when ∣P(3jω)∣|P(3 j\omega)| is small compared with ∣P(jω)∣|P(j\omega)|, which holds for plants with several lags. It is worse for plants close to a first order lag with a delay, whose output has corners. The page gives the measured errors.

Claim 4: the analysis of the record has an error of order Δt2\Delta t^2 for a fixed cycle

Let the record be samples, with the step Δt\Delta t, of a periodic function yy that is twice continuously differentiable near its upward crossings of 0 and near its extrema, with y′≠0y' \ne 0 at the crossings. Then the period and the amplitude from lines L4 to L6 have errors O(Δt2)O(\Delta t^2).

Proof. Near a crossing tct_c, linear interpolation between the samples around it has the error O(Δt2max⁡∣y′′∣)O(\Delta t^2 \max |y''|) in yy, so the interpolated crossing time has the error O(Δt2/∣y′(tc)∣)O(\Delta t^2 / |y'(t_c)|). The period is a difference of two such times divided by the number of periods. At an extremum tet_e, y′(te)=0y'(t_e) = 0, so the nearest sample tjt_j with ∣tj−te∣≤Δt/2|t_j - t_e| \le \Delta t/2 has ∣y(tj)−y(te)∣≤18Δt2max⁡∣y′′∣|y(t_j) - y(t_e)| \le \frac18 \Delta t^2 \max|y''|. □\square

The claim is about the analysis of a given record. The sampled relay itself acts on yy at the steps only, so each switch comes up to one step late. This changes the loop: in the tests the period of the simulated loop is longer than the exact period by about 2Δt2 \Delta t. That is a measurement.

Claim 5: the cost

A record of kk steps of a plant of order nn costs O(kn2)O(k n^2) time, and its analysis costs O(k)O(k).

Proof. One step of the classical Runge-Kutta method evaluates Ax+BuA x + B u four times, each O(n2)O(n^2), and the relay and the delay line cost O(1)O(1) per step (the delay line is a queue). The analysis visits each sample a fixed number of times. □\square

Complexity

Each simulation step evaluates Ax+BuA x + B u four times, which costs O(n2)O(n^2), so an experiment of kk steps costs O(kn2)O(k n^2) time. The analysis visits each sample once, O(k)O(k). The record takes O(k)O(k) space; a real autotuner keeps only the last crossing times and extreme values, O(1)O(1). The exact cycle costs one matrix exponential of order n+1n + 1 per trial value of τ\tau, O(n3)O(n^3) each. On a real plant the cost is the time of the experiment, usually 2 to 4 periods after the start.

Properties

  • Closed loop all the time. The plant output stays near the set point, within ±a\pm a, during the test.
  • Amplitude set by dd. The size of the oscillation is proportional to dd, so the operator can keep the test inside the allowed range.
  • No prior model. The method needs only the sign of the plant gain and a rough size for dd.
  • One frequency. The test gives one point of the frequency response. Two plants with the same point get the same controller.
  • Noise. A relay with no hysteresis switches on noise near the crossings. Hysteresis stops this, at the cost of a different point of the Nyquist curve.

Variants and improvements

  • Hysteresis. A hysteresis wider than the noise band makes the switching clean. The point found has the phase −180+arcsin⁡(ε/a)-180 + \arcsin(\varepsilon/a) degrees.
  • Bias. A relay with unequal levels, or an extra constant input, also gives the static gain of the plant from the mean values of uu and yy. With the static gain and the ultimate point, a first order model with a delay can be fitted.
  • Other points. A relay in series with an integrator adds −90-90 degrees to the loop, so it finds the point where the phase of the plant is −90-90 degrees. A relay with hysteresis or with a known delay finds other points of the third quadrant. With several points, rules with a phase or gain margin target can be used, as in the 1984 paper.
  • Other rules. The ultimate cycle rule is the classic choice, but the rules with a given phase margin, or the AMIGO rules of Åström and Hägglund, give a better damped loop.
  • Gain scheduling and adaptation. An autotuner can run the test at several operating points and store the settings in a table. See gain scheduling. Continuous adaptation is a different method; see self-tuning regulator.

When to use it

Use relay autotuning to set the first PID settings of a process loop, or to retune a loop whose plant has drifted, when a short oscillation of a known small size is acceptable. It suits plants with a phase that falls below −180-180 degrees, which covers lags of order two or more and plants with a delay. It does not suit plants that do not oscillate under relay feedback, such as a first order lag with no delay, plants with lightly damped modes, where the cycle can lock onto the wrong frequency, or plants where any oscillation is unsafe.

Pitfalls

  • The estimate is not exact. The describing function underestimates KuK_u by a few percent on lag plants and by 10 percent or more on plants close to a first order lag with a delay. The tuning rule should allow for this.
  • Noise and switching. Without hysteresis, noise near the set point makes the relay chatter. Choose ε\varepsilon larger than the noise band.
  • Load changes during the test. A load step during the test makes the cycle unsymmetric. Use the time between crossings of the same direction, and check that the half periods agree.
  • Sign of the plant gain. For a plant with a negative gain the relay must act in reverse. A wrong sign drives the output away.
  • Sampling. A sampled relay switches up to one sample late, which adds phase lag and lengthens the period. In the example the period grows by about 2Δt2 \Delta t. Sample many times per period.
  • Start-up. The first periods differ from the later ones, because the plant starts from rest. Use the later periods only.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

ctlmat.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the control pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Small dense linear algebra and polynomial routines for the control pages.

Conventions:
- A matrix is a list of rows. Entries are int, float, Fraction or complex.
- A vector is a flat list of scalars. matvec, dot, solve (with a vector
  right side), vec and unvec use flat lists.
- A polynomial is a list of coefficients, highest power first, so
  [1, 3, 2] is s^2 + 3 s + 2.
- Routines that divide (solve, inv, det, charpoly) compute in Fraction when
  every entry is an int or a Fraction, so the result is exact. With float or
  complex entries they compute in floating point.
- transpose does not conjugate complex entries.

Floating point tolerances:
- expm: scaling and squaring with a Taylor series; the scaled matrix has
  infinity norm at most 1/2 and the series stops when a term is below
  2^-60 times the sum. For matrices that are not far from normal the relative
  error is near 1e-14.
- polyroots: Durand-Kerner iteration, then a Newton polish. Simple roots of a
  well conditioned polynomial come out with a relative error near 1e-12 (the
  tests ask for 1e-9). A root of multiplicity k is ill conditioned: its error
  grows like 1e-16^(1/k), about 1e-8 for a double root and 1e-3 for a
  fourfold root. For real coefficients the output is closed under
  conjugation.
- is_pos_def with float entries: the matrix must be symmetric within
  1e-12 times its largest entry, and the Cholesky pivots of A - margin I must
  be positive.

This file holds no algorithm of a control page.
"""

import cmath
import math
from fractions import Fraction

__all__ = [
    "zeros", "eye", "add", "sub", "scale", "mul", "transpose", "matvec",
    "dot", "norm2", "block", "kron", "vec", "unvec", "solve", "inv", "det",
    "trace", "charpoly", "polyval", "polyadd", "polymul", "polyder",
    "polyroots", "expm", "mat_power", "is_symmetric", "is_pos_def",
]


def _is_exact(v):
    return isinstance(v, (int, Fraction))


def _all_exact(*mats):
    for m in mats:
        for row in m:
            if isinstance(row, list):
                for v in row:
                    if not _is_exact(v):
                        return False
            elif not _is_exact(row):
                return False
    return True


def _to_fraction(a):
    return [[Fraction(v) for v in row] for row in a]


def _shape(a):
    return len(a), (len(a[0]) if a else 0)


def zeros(n, m=None):
    """Return the n by m zero matrix (n by n if m is None), with int entries."""
    if m is None:
        m = n
    return [[0] * m for _ in range(n)]


def eye(n):
    """Return the n by n identity matrix, with int entries."""
    return [[1 if i == j else 0 for j in range(n)] for i in range(n)]


def add(a, b):
    """Return a + b."""
    if _shape(a) != _shape(b):
        raise ValueError("add: shapes differ")
    return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]


def sub(a, b):
    """Return a - b."""
    if _shape(a) != _shape(b):
        raise ValueError("sub: shapes differ")
    return [[x - y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]


def scale(c, a):
    """Return the scalar c times the matrix a."""
    return [[c * x for x in row] for row in a]


def mul(a, b):
    """Return the matrix product a b."""
    n, k = _shape(a)
    k2, m = _shape(b)
    if k != k2:
        raise ValueError("mul: inner dimensions differ")
    bt = list(zip(*b)) if b else []
    out = []
    for row in a:
        out_row = []
        for col in bt:
            s = 0
            for x, y in zip(row, col):
                s += x * y
            out_row.append(s)
        out.append(out_row)
    return out


def transpose(a):
    """Return the transpose of a (no complex conjugation)."""
    return [list(col) for col in zip(*a)]


def matvec(a, x):
    """Return the vector a x, for a flat list x."""
    if a and len(a[0]) != len(x):
        raise ValueError("matvec: dimensions differ")
    out = []
    for row in a:
        s = 0
        for v, w in zip(row, x):
            s += v * w
        out.append(s)
    return out


def dot(x, y):
    """Return sum of x_i y_i (no complex conjugation)."""
    if len(x) != len(y):
        raise ValueError("dot: lengths differ")
    s = 0
    for v, w in zip(x, y):
        s += v * w
    return s


def _sym_eigvals(s):
    """Eigenvalues of a real symmetric float matrix by cyclic Jacobi."""
    n = len(s)
    a = [list(map(float, row)) for row in s]
    for _ in range(100):
        off = sum(a[i][j] ** 2 for i in range(n) for j in range(n) if i != j)
        diag = sum(a[i][i] ** 2 for i in range(n))
        if off <= 1e-30 * max(diag, 1e-300):
            break
        for p in range(n - 1):
            for q in range(p + 1, n):
                if a[p][q] == 0.0:
                    continue
                theta = (a[q][q] - a[p][p]) / (2.0 * a[p][q])
                t = math.copysign(1.0, theta) / (abs(theta) + math.sqrt(theta * theta + 1.0))
                c = 1.0 / math.sqrt(t * t + 1.0)
                sn = t * c
                for k in range(n):
                    akp, akq = a[k][p], a[k][q]
                    a[k][p] = c * akp - sn * akq
                    a[k][q] = sn * akp + c * akq
                for k in range(n):
                    apk, aqk = a[p][k], a[q][k]
                    a[p][k] = c * apk - sn * aqk
                    a[q][k] = sn * apk + c * aqk
    return [a[i][i] for i in range(n)]


def norm2(x):
    """Return the 2-norm.

    For a flat vector this is the Euclidean norm. For a matrix it is the
    induced 2-norm (the largest singular value), computed from the
    eigenvalues of M^T M by the Jacobi method, where M is a real matrix with
    the same singular values. The result is a float.
    """
    if not x:
        return 0.0
    if not isinstance(x[0], list):
        return math.sqrt(sum(abs(complex(v)) ** 2 for v in x))
    if any(isinstance(v, complex) for row in x for v in row):
        re = [[complex(v).real for v in row] for row in x]
        im = [[complex(v).imag for v in row] for row in x]
        m = block([[re, scale(-1, im)], [im, re]])
    else:
        m = [[float(v) for v in row] for row in x]
    g = mul(transpose(m), m)
    lam = max(_sym_eigvals(g))
    return math.sqrt(max(lam, 0.0))


def block(rows):
    """Build a matrix from a list of rows of blocks.

    A block is a matrix, or the int 0 for a zero block whose size is taken
    from the other blocks in its block row and block column.
    """
    heights = []
    for r in rows:
        h = None
        for b in r:
            if isinstance(b, list):
                h = len(b)
                break
        if h is None:
            raise ValueError("block: a block row has no matrix block")
        heights.append(h)
    ncols = len(rows[0])
    widths = []
    for j in range(ncols):
        w = None
        for r in rows:
            if isinstance(r[j], list):
                w = len(r[j][0]) if r[j] else 0
                break
        if w is None:
            raise ValueError("block: a block column has no matrix block")
        widths.append(w)
    out = []
    for r, h in zip(rows, heights):
        if len(r) != ncols:
            raise ValueError("block: block rows have different lengths")
        for i in range(h):
            line = []
            for b, w in zip(r, widths):
                if isinstance(b, list):
                    if len(b) != h or (b and len(b[0]) != w):
                        raise ValueError("block: block sizes do not match")
                    line.extend(b[i])
                elif b == 0:
                    line.extend([0] * w)
                else:
                    raise ValueError("block: a scalar block must be 0")
            out.append(line)
    return out


def kron(a, b):
    """Return the Kronecker product of a and b."""
    n, m = _shape(a)
    p, q = _shape(b)
    return [[a[i // p][j // q] * b[i % p][j % q] for j in range(m * q)] for i in range(n * p)]


def vec(a):
    """Stack the columns of a into one flat list."""
    n, m = _shape(a)
    return [a[i][j] for j in range(m) for i in range(n)]


def unvec(v, n, m=None):
    """Inverse of vec: return the n by m matrix whose stacked columns are v."""
    if m is None:
        m = len(v) // n
    if n * m != len(v):
        raise ValueError("unvec: length does not match the shape")
    return [[v[j * n + i] for j in range(m)] for i in range(n)]


def solve(a, b):
    """Solve a x = b by Gaussian elimination with partial pivoting.

    b is a flat vector or a matrix; the result has the same form. With int
    and Fraction entries the result is exact (Fraction). Raises ValueError
    if a is singular (an exactly zero pivot).
    """
    n, m = _shape(a)
    if n != m:
        raise ValueError("solve: matrix is not square")
    is_vec = not (b and isinstance(b[0], list))
    rhs = [[v] for v in b] if is_vec else [list(row) for row in b]
    if len(rhs) != n:
        raise ValueError("solve: right side has the wrong length")
    if _all_exact(a, rhs):
        aa = _to_fraction(a)
        rhs = _to_fraction(rhs)
    else:
        aa = [list(row) for row in a]
    k = len(rhs[0]) if rhs else 0
    for c in range(n):
        p = max(range(c, n), key=lambda r: abs(aa[r][c]))
        if aa[p][c] == 0:
            raise ValueError("solve: matrix is singular")
        if p != c:
            aa[c], aa[p] = aa[p], aa[c]
            rhs[c], rhs[p] = rhs[p], rhs[c]
        piv = aa[c][c]
        for r in range(c + 1, n):
            f = aa[r][c] / piv
            if f == 0:
                continue
            row_r, row_c = aa[r], aa[c]
            for j in range(c, n):
                row_r[j] -= f * row_c[j]
            rr, rc = rhs[r], rhs[c]
            for j in range(k):
                rr[j] -= f * rc[j]
    x = [[0] * k for _ in range(n)]
    for c in range(n - 1, -1, -1):
        for j in range(k):
            s = rhs[c][j]
            for t in range(c + 1, n):
                s -= aa[c][t] * x[t][j]
            x[c][j] = s / aa[c][c]
    return [row[0] for row in x] if is_vec else x


def inv(a):
    """Return the inverse of a (exact with int and Fraction entries)."""
    return solve(a, eye(len(a)))


def det(a):
    """Return the determinant of a by elimination with partial pivoting.

    With int and Fraction entries the result is an exact Fraction.
    """
    n, m = _shape(a)
    if n != m:
        raise ValueError("det: matrix is not square")
    aa = _to_fraction(a) if _all_exact(a) else [list(row) for row in a]
    d = Fraction(1) if _all_exact(a) else 1.0
    for c in range(n):
        p = max(range(c, n), key=lambda r: abs(aa[r][c]))
        if aa[p][c] == 0:
            return d * 0
        if p != c:
            aa[c], aa[p] = aa[p], aa[c]
            d = -d
        piv = aa[c][c]
        d *= piv
        for r in range(c + 1, n):
            f = aa[r][c] / piv
            if f == 0:
                continue
            for j in range(c, n):
                aa[r][j] -= f * aa[c][j]
    return d


def trace(a):
    """Return the sum of the diagonal entries of a."""
    s = 0
    for i in range(len(a)):
        s += a[i][i]
    return s


def charpoly(a):
    """Return [1, a_1, ..., a_n] with det(s I - A) = s^n + a_1 s^(n-1) + ... + a_n.

    Uses the Faddeev-LeVerrier recursion M_k = A M_(k-1) + a_(k-1) I,
    a_k = -trace(A M_k) / k. Exact with int and Fraction entries.
    """
    n, m = _shape(a)
    if n != m:
        raise ValueError("charpoly: matrix is not square")
    aa = _to_fraction(a) if _all_exact(a) else [list(row) for row in a]
    coeffs = [1]
    mk = zeros(n)
    for k in range(1, n + 1):
        mk = mul(aa, mk)
        c = coeffs[-1]
        for i in range(n):
            mk[i][i] += c
        am = mul(aa, mk)
        coeffs.append(-trace(am) / k)
    return coeffs


def polyval(p, x):
    """Evaluate the polynomial p at x by Horner's rule."""
    s = 0
    for c in p:
        s = s * x + c
    return s


def _strip(p):
    i = 0
    while i < len(p) - 1 and p[i] == 0:
        i += 1
    return list(p[i:]) if p else [0]


def polyadd(p, q):
    """Return p + q, with exactly zero leading coefficients removed."""
    n = max(len(p), len(q))
    pp = [0] * (n - len(p)) + list(p)
    qq = [0] * (n - len(q)) + list(q)
    return _strip([x + y for x, y in zip(pp, qq)])


def polymul(p, q):
    """Return the product p q."""
    if not p or not q:
        return [0]
    out = [0] * (len(p) + len(q) - 1)
    for i, x in enumerate(p):
        for j, y in enumerate(q):
            out[i + j] += x * y
    return _strip(out)


def polyder(p):
    """Return the derivative of p."""
    n = len(p) - 1
    if n <= 0:
        return [0]
    return _strip([c * (n - i) for i, c in enumerate(p[:-1])])


def polyroots(p, tol=1e-15, maxiter=1000):
    """Return the complex roots of p, sorted by real part, then imaginary part.

    Durand-Kerner (Weierstrass) iteration from points on a circle, stopped
    when every relative correction is below tol, then a Newton polish of
    each root. For real coefficients the roots are made exactly real or
    exact conjugate pairs. See the module notes for the accuracy.
    """
    c = [complex(v) for v in p]
    while c and c[0] == 0:
        c.pop(0)
    if not c:
        raise ValueError("polyroots: zero polynomial")
    real_coeffs = all(v.imag == 0 for v in c)
    origin = 0
    while len(c) > 1 and c[-1] == 0:
        c.pop()
        origin += 1
    n = len(c) - 1
    a = [v / c[0] for v in c]
    if n == 0:
        z = []
    elif n == 1:
        z = [-a[1]]
    else:
        r = 2.0 * max(abs(a[k]) ** (1.0 / k) for k in range(1, n + 1))
        if r == 0:
            r = 1.0
        z = [r * cmath.exp(1j * (2 * math.pi * k / n + 0.4)) for k in range(n)]
        for _ in range(maxiter):
            worst = 0.0
            for i in range(n):
                den = 1.0 + 0j
                for j in range(n):
                    if j != i:
                        den *= z[i] - z[j]
                if den == 0:
                    z[i] += 1e-8 * (1 + abs(z[i])) * cmath.exp(1j * (i + 1))
                    worst = 1.0
                    continue
                d = polyval(a, z[i]) / den
                z[i] -= d
                worst = max(worst, abs(d) / (1.0 + abs(z[i])))
            if worst < tol:
                break
        dp = polyder(a)
        for i in range(n):
            zi = z[i]
            fz = abs(polyval(a, zi))
            for _ in range(5):
                der = polyval(dp, zi)
                if der == 0 or fz == 0:
                    break
                step = polyval(a, zi) / der
                if abs(step) > 1e-6 * (1.0 + abs(zi)):
                    break
                znew = zi - step
                fnew = abs(polyval(a, znew))
                if fnew >= fz:
                    break
                zi, fz = znew, fnew
            z[i] = zi
    z = z + [0j] * origin
    if real_coeffs:
        thr = 1e-9
        upper = [v for v in z if v.imag > thr * (1 + abs(v))]
        lower = [v for v in z if v.imag < -thr * (1 + abs(v))]
        reals = [complex(v.real, 0.0) for v in z if abs(v.imag) <= thr * (1 + abs(v))]
        # A cluster of close roots can leave more roots above the real axis
        # than below it (or the other way). The extra roots nearest to the
        # axis are then taken as real, so the output is closed under
        # conjugation.
        if len(upper) < len(lower):
            upper, lower = [v.conjugate() for v in lower], [v.conjugate() for v in upper]
        upper.sort(key=lambda v: v.imag)
        extra = len(upper) - len(lower)
        reals += [complex(v.real, 0.0) for v in upper[:extra]]
        upper = upper[extra:]
        out = list(reals)
        rest = list(lower)
        for u in upper:
            w = min(rest, key=lambda v: abs(v - u.conjugate()))
            rest.remove(w)
            re = (u.real + w.real) / 2
            im = (u.imag - w.imag) / 2
            out.append(complex(re, im))
            out.append(complex(re, -im))
        z = out
    return sorted(z, key=lambda v: (v.real, v.imag))


def _norm_inf(a):
    return max((sum(abs(v) for v in row) for row in a), default=0.0)


def expm(a):
    """Return e^A in floating point by scaling and squaring with a Taylor series.

    A is scaled by 2^-s so that its infinity norm is at most 1/2, the Taylor
    series of the scaled matrix is summed until a term is below 2^-60 of the
    sum, and the result is squared s times. Entries of the result are float
    (complex if A has complex entries).
    """
    n, m = _shape(a)
    if n != m:
        raise ValueError("expm: matrix is not square")
    cplx = any(isinstance(v, complex) for row in a for v in row)
    conv = complex if cplx else float
    x = [[conv(v) for v in row] for row in a]
    nrm = _norm_inf(x)
    s = 0
    while nrm > 0.5:
        nrm /= 2.0
        s += 1
    x = scale(conv(2.0 ** -s), x)
    e = [[conv(1.0 if i == j else 0.0) for j in range(n)] for i in range(n)]
    term = [row[:] for row in e]
    for k in range(1, 60):
        term = scale(1.0 / k, mul(term, x))
        e = add(e, term)
        tn = _norm_inf(term)
        if tn == 0.0 or tn <= 2.0 ** -60 * _norm_inf(e):
            break
    for _ in range(s):
        e = mul(e, e)
    return e


def mat_power(a, k):
    """Return A^k for an int k by repeated squaring (A^0 = I; k < 0 uses inv)."""
    n, m = _shape(a)
    if n != m:
        raise ValueError("mat_power: matrix is not square")
    if k < 0:
        a = inv(a)
        k = -k
    result = eye(n)
    base = [list(row) for row in a]
    while k:
        if k & 1:
            result = mul(result, base)
        k >>= 1
        if k:
            base = mul(base, base)
    return result


def is_symmetric(a, tol=0):
    """Return True if a is square and |a_ij - a_ji| <= tol for all i, j."""
    n, m = _shape(a)
    if n != m:
        return False
    return all(abs(a[i][j] - a[j][i]) <= tol for i in range(n) for j in range(i + 1, n))


def is_pos_def(a, margin=0):
    """Return True if a is symmetric and a - margin I is positive definite.

    With int and Fraction entries (and an exact margin) the test is exact:
    every leading principal minor of a - margin I must be positive
    (Sylvester's criterion), computed in Fraction. With float entries the
    matrix must be symmetric within 1e-12 times its largest entry, and the
    Cholesky factorization of a - margin I must have positive pivots.
    Complex entries are not accepted.
    """
    n, m = _shape(a)
    if n != m:
        return False
    if any(isinstance(v, complex) for row in a for v in row):
        raise ValueError("is_pos_def: complex entries are not accepted")
    if _all_exact(a) and _is_exact(margin):
        b = [[Fraction(a[i][j]) - (Fraction(margin) if i == j else 0) for j in range(n)] for i in range(n)]
        if not is_symmetric(b):
            return False
        return all(det([row[:k] for row in b[:k]]) > 0 for k in range(1, n + 1))
    b = [[float(a[i][j]) - (float(margin) if i == j else 0.0) for j in range(n)] for i in range(n)]
    big = max((abs(float(v)) for row in a for v in row), default=0.0)
    if not is_symmetric(b, 1e-12 * max(big, 1e-300)):
        return False
    low = [[0.0] * n for _ in range(n)]
    for j in range(n):
        d = b[j][j] - sum(low[j][k] ** 2 for k in range(j))
        if not d > 0.0:
            return False
        low[j][j] = math.sqrt(d)
        for i in range(j + 1, n):
            low[i][j] = (b[i][j] - sum(low[i][k] * low[j][k] for k in range(j))) / low[j][j]
    return True


def _self_test():
    a = [[0, 1], [-2, -3]]
    assert charpoly(a) == [1, 3, 2]
    assert det(a) == 2
    assert mul(inv(a), a) == eye(2)
    assert solve(a, [1, 0]) == [Fraction(-3, 2), Fraction(1)]
    r = polyroots([1, 3, 2])
    assert abs(r[0] + 2) < 1e-12 and abs(r[1] + 1) < 1e-12
    t = 0.7
    e = expm([[0.0, t], [-t, 0.0]])
    want = [[math.cos(t), math.sin(t)], [-math.sin(t), math.cos(t)]]
    assert max(abs(e[i][j] - want[i][j]) for i in range(2) for j in range(2)) < 1e-14
    assert is_pos_def([[Fraction(5, 4), Fraction(1, 4)], [Fraction(1, 4), Fraction(1, 4)]])
    assert not is_pos_def([[1, 2], [2, 1]])
    assert abs(norm2([[3.0, 0.0], [0.0, -4.0]]) - 4.0) < 1e-12
    return True


if __name__ == "__main__":
    _self_test()
ctlsim.py 120 lines
# SPDX-License-Identifier: MIT
# Shared helper of the control pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Fixed step simulation for the control pages.

Conventions:
- A continuous-time system is a function f(t, x, u) that returns x' as a
  flat list. x is a flat list. u is whatever the control returns (a flat
  list, a scalar, or None when there is no control).
- A discrete-time system is a function F(k, x, u) that returns x_(k+1).
- The integrator is the classical 4th order Runge-Kutta method with a fixed
  step dt. The input is held constant over each step.
- Time t_k = t0 + k dt is computed by multiplication, not by summation.
- The number of steps round((t1 - t0) / dt) and the hold ratio
  round(hold / dt) must match the real ratios within 1e-9 (relative), or
  ValueError is raised.

This file holds no controller or observer of a control page.
"""

__all__ = ["rk4_step", "simulate", "simulate_discrete", "lti"]


def _axpy(a, x, y):
    return [yi + a * xi for xi, yi in zip(x, y)]


def rk4_step(f, t, x, u, dt):
    """Return x(t + dt) after one RK4 step of x' = f(t, x, u), u held constant."""
    k1 = f(t, x, u)
    k2 = f(t + dt / 2, _axpy(dt / 2, k1, x), u)
    k3 = f(t + dt / 2, _axpy(dt / 2, k2, x), u)
    k4 = f(t + dt, _axpy(dt, k3, x), u)
    return [xi + dt / 6 * (a + 2 * b + 2 * c + d) for xi, a, b, c, d in zip(x, k1, k2, k3, k4)]


def _ratio(num, den, what):
    r = round(num / den)
    if abs(r * den - num) > 1e-9 * max(abs(num), abs(den)):
        raise ValueError(what + " is not an integer multiple of dt")
    return r


def simulate(f, x0, t0, t1, dt, control=None, hold=None):
    """Simulate x' = f(t, x, u) from x(t0) = x0 to t1 with RK4 and step dt.

    control(t, x) gives the input. It is called at each sampling instant
    t0 + j hold, and its value is held (zero-order hold) until the next
    instant. hold must be an integer multiple of dt; hold = None means
    hold = dt. With control = None the input is None.

    Returns (ts, xs, us): ts has N + 1 times, xs the N + 1 states, and us the
    N inputs, where us[k] acts on [ts[k], ts[k + 1]].
    """
    if dt <= 0:
        raise ValueError("dt must be positive")
    n_steps = _ratio(t1 - t0, dt, "t1 - t0")
    if n_steps < 0:
        raise ValueError("t1 is before t0")
    r = 1 if hold is None else _ratio(hold, dt, "hold")
    if r < 1:
        raise ValueError("hold must be at least dt")
    x = list(x0)
    ts = [t0]
    xs = [list(x)]
    us = []
    u = None
    for k in range(n_steps):
        t = t0 + k * dt
        if control is not None and k % r == 0:
            u = control(t, list(x))
        x = rk4_step(f, t, x, u, dt)
        ts.append(t0 + (k + 1) * dt)
        xs.append(x)
        us.append(u)
    return ts, xs, us


def simulate_discrete(F, x0, N, control=None):
    """Run x_(k+1) = F(k, x_k, u_k) for k = 0, ..., N - 1.

    u_k = control(k, x_k), or None if control is None. Returns (xs, us) with
    N + 1 states and N inputs. Exact if F and control are exact.
    """
    x = list(x0)
    xs = [list(x)]
    us = []
    for k in range(N):
        u = control(k, list(x)) if control is not None else None
        x = list(F(k, x, u))
        xs.append(x)
        us.append(u)
    return xs, us


def lti(A, B=None):
    """Return f(t, x, u) = A x + B u for the system x' = A x + B u.

    u may be a flat list, a scalar (one input) or None (zero input). B may
    be None for a system with no input.
    """
    def f(t, x, u):
        dx = [sum(a * xi for a, xi in zip(row, x)) for row in A]
        if B is None or u is None:
            return dx
        uu = u if isinstance(u, (list, tuple)) else [u]
        return [d + sum(b * ui for b, ui in zip(row, uu)) for d, row in zip(dx, B)]
    return f


def _self_test():
    import math
    f = lti([[-1.0]])
    _, xs, _ = simulate(f, [1.0], 0.0, 1.0, 0.01)
    assert abs(xs[-1][0] - math.exp(-1.0)) < 1e-9
    return True


if __name__ == "__main__":
    _self_test()
relay_autotuning.py 201 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/relay-autotuning/. The authors are listed in prov/WBZ78H.jsonl.

"""Relay feedback autotuning (Astrom and Hagglund, 1984).

A relay with the output levels +d and -d (and an optional hysteresis eps)
closes the loop around the plant x' = A x + B u(t - delay), y = C x. The loop
settles into a limit cycle. From its period T and its amplitude a, the
describing function of the relay gives the estimate of the ultimate point

    K = 4 d / (pi a),   T_u = T,

where the estimate lies at the phase -180 + asin(eps/a) degrees. A tuning
rule then turns K and T into PID settings.

The plant is simulated with the classical Runge-Kutta method (ctlsim) with
the step dt. The relay acts at every step, and the delay must be a whole
number of steps. Switching times and zero crossings are found by linear
interpolation between steps.

exact_relay_cycle computes the true symmetric limit cycle of a relay with
no hysteresis around a plant with no delay, from the matrix exponential.
"""

import math
from collections import deque

from ctlmat import expm, matvec, solve
from ctlsim import rk4_step, lti

__all__ = [
    "relay_experiment", "analyze_cycle", "relay_estimate", "exact_relay_cycle",
    "ultimate_cycle_rule", "relay_autotune",
]

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


def relay_experiment(A, B, C, d, t1, dt, eps=0.0, delay=0.0, r=0.0, x0=None):
    """Run the relay loop from x0 (rest by default) until t1.

    The relay output is u = +d when e = r - y > eps, u = -d when e < -eps,
    and keeps its last value in between. It starts at +d. Returns (ts, ys, us).
    """
    if d <= 0 or eps < 0:
        raise ValueError("need d > 0 and eps >= 0")
    n = round(t1 / dt)
    if abs(n * dt - t1) > 1e-9 * t1:
        raise ValueError("t1 is not a multiple of dt")
    m = round(delay / dt)
    if abs(m * dt - delay) > 1e-9 * max(delay, dt):
        raise ValueError("the delay is not a multiple of dt")
    f = lti(A, B)
    x = [0.0] * len(A) if x0 is None else list(x0)
    line = deque([0.0] * m)   # inputs on their way through the delay
    u = d  # @line L1
    ts, ys, us = [0.0], [matvec([C], x)[0]], []
    for k in range(n):
        e = r - ys[-1]  # @line L2
        if e > eps:
            u = d
        elif e < -eps:
            u = -d
        if m:
            line.append(u)
            ua = line.popleft()
        else:
            ua = u
        x = rk4_step(f, k * dt, x, [ua], dt)  # @line L3
        ts.append((k + 1) * dt)
        ys.append(matvec([C], x)[0])
        us.append(u)
    return ts, ys, us


def analyze_cycle(ts, ys, r=0.0, periods=3):
    """Return (T, a, center) of the last `periods` full periods of ys.

    T is the mean time between upward crossings of the level r, found by
    linear interpolation. a is half the peak-to-peak value over the same
    time, and center the mean of the largest and the smallest value.
    """
    up = []
    for k in range(1, len(ys)):  # @line L4
        if ys[k - 1] < r <= ys[k]:
            s = (r - ys[k - 1]) / (ys[k] - ys[k - 1])
            up.append(ts[k - 1] + s * (ts[k] - ts[k - 1]))
    if len(up) < periods + 2:
        raise ValueError("too few periods: run the experiment longer")
    t_a, t_b = up[-1 - periods], up[-1]
    T = (t_b - t_a) / periods  # @line L5
    window = [y for t, y in zip(ts, ys) if t_a <= t <= t_b]
    hi, lo = max(window), min(window)
    return T, (hi - lo) / 2, (hi + lo) / 2  # @line L6


def relay_estimate(d, a, eps=0.0):
    """Return (K, phase): the describing function estimate 4 d/(pi a) of the
    gain that puts the loop at the point found, and its phase in radians."""
    if a <= eps:
        raise ValueError("the amplitude must exceed the hysteresis")
    return 4 * d / (math.pi * a), -math.pi + math.asin(eps / a)  # @line L7


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


def relay_autotune(A, B, C, d, t1, dt, eps=0.0, delay=0.0, kind="PID", periods=3):
    """Run the experiment, analyze the last periods and apply the rule.

    Returns (K, Ti, Td, ku, tu, a)."""
    ts, ys, _ = relay_experiment(A, B, C, d, t1, dt, eps=eps, delay=delay)
    tu, a, _ = analyze_cycle(ts, ys, periods=periods)
    ku, _ = relay_estimate(d, a, eps)
    K, Ti, Td = ultimate_cycle_rule(ku, tu, kind)  # @line L8
    return K, Ti, Td, ku, tu, a


def _flow(A, B, tau):
    """Return (Phi, Gamma) = (e^(A tau), int_0^tau e^(A s) ds B)."""
    n, m = len(A), len(B[0])
    big = [list(A[i]) + list(B[i]) for i in range(n)] + [[0.0] * (n + m) for _ in range(m)]
    E = expm([[tau * v for v in row] for row in big])
    return [row[:n] for row in E[:n]], [row[n:] for row in E[:n]]


def _start_state(A, B, d, tau):
    Phi, Gam = _flow(A, B, tau)
    n = len(A)
    M = [[(1.0 if i == j else 0.0) + Phi[i][j] for j in range(n)] for i in range(n)]
    g = [-d * Gam[i][0] for i in range(n)]
    return solve(M, g)


def exact_relay_cycle(A, B, C, d, tau_max=50.0, grid=5000):
    """Return (T, a, x0) of the symmetric relay cycle, no hysteresis, no delay.

    At t = 0, y crosses 0 going down and the relay switches to +d. Over the
    half period tau, x(tau) = -x(0), so x0 = -(I + Phi)^(-1) Gamma d, and tau
    solves C x0(tau) = 0. The first sign change of C x0 on a grid is refined
    by bisection. a = -min y over the half period, from a fine grid and a
    parabola through the three smallest neighbours.
    """
    def h(tau):
        return matvec([C], _start_state(A, B, d, tau))[0]

    taus = [tau_max * (i + 1) / grid for i in range(grid)]
    prev = h(taus[0])
    lo = hi = None
    for t0, t1 in zip(taus, taus[1:]):
        cur = h(t1)
        if prev != 0 and (prev > 0) != (cur > 0):
            lo, hi = t0, t1
            break
        prev = cur
    if lo is None:
        raise ValueError("no relay cycle found below tau_max")
    s_lo = h(lo) > 0
    for _ in range(100):
        mid = (lo + hi) / 2
        if (h(mid) > 0) == s_lo:
            lo = mid
        else:
            hi = mid
        if hi - lo <= 1e-14 * hi:
            break
    tau = (lo + hi) / 2
    x0 = _start_state(A, B, d, tau)
    k = 2000
    step = tau / k
    Phi, Gam = _flow(A, B, step)
    x = list(x0)
    yv = [matvec([C], x)[0]]
    for _ in range(k):
        x = [sum(p * v for p, v in zip(row, x)) + g[0] * d for row, g in zip(Phi, Gam)]
        yv.append(matvec([C], x)[0])
    j = min(range(1, k), key=lambda i: yv[i])
    y0, y1, y2 = yv[j - 1], yv[j], yv[j + 1]
    den = y0 - 2 * y1 + y2
    ymin = y1 - (y0 - y2) ** 2 / (8 * den) if den > 0 else y1
    return 2 * tau, -ymin, x0


def _self_test():
    A = [[-1.0, 0.0, 0.0], [1.0, -1.0, 0.0], [0.0, 1.0, -1.0]]
    B = [[1.0], [0.0], [0.0]]
    C = [0.0, 0.0, 1.0]
    T, a, _ = exact_relay_cycle(A, B, C, 1.0)
    assert 3.0 < T < 4.0 and 0.1 < a < 0.2
    return True


if __name__ == "__main__":
    _self_test()
test_relay_autotuning.py 128 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/relay-autotuning/. The authors are listed in prov/WBZ78H.jsonl.

import cmath
import math
import random

import pytest

from ctlmat import matvec
from ctlsim import lti, simulate
from relay_autotuning import (analyze_cycle, exact_relay_cycle, relay_autotune,
                              relay_estimate, relay_experiment,
                              ultimate_cycle_rule)

# Plant 1/(s + 1)^3 as a chain of three lags, y = x3. K_u = 8 and
# T_u = 2 pi/sqrt(3) for this plant.
A3 = [[-1.0, 0.0, 0.0], [1.0, -1.0, 0.0], [0.0, 1.0, -1.0]]
B3 = [[1.0], [0.0], [0.0]]
C3 = [0.0, 0.0, 1.0]
TU3 = 2 * math.pi / math.sqrt(3)
DT = 0.005


def test_exact_cycle_is_a_cycle():
    T, a, x0 = exact_relay_cycle(A3, B3, C3, 1.0)
    assert abs(matvec([C3], x0)[0]) < 1e-12
    # From x0 with u = +d for T/2, y stays below 0 and returns to 0, and
    # the state reaches -x0 (the symmetric half of the cycle).
    ts, xs, _ = simulate(lti(A3, B3), x0, 0.0, T / 2, T / 2 / 4000, control=lambda t, x: 1.0)
    ys = [x[2] for x in xs]
    assert max(ys[1:-1]) < 0
    assert max(abs(u + v) for u, v in zip(xs[-1], x0)) < 1e-10
    assert abs(-min(ys) - a) < 1e-9


def test_exact_cycle_against_ultimate_point():
    # The describing function gives the period and the gain with a small
    # error for this plant: measured 1.4 percent and 2.4 percent.
    T, a, _ = exact_relay_cycle(A3, B3, C3, 1.0)
    ku = 4 / (math.pi * a)
    assert 0 < (T - TU3) / TU3 < 0.02
    assert 0 < (8 - ku) / 8 < 0.03


def test_simulated_cycle_matches_exact_cycle():
    T, a, _ = exact_relay_cycle(A3, B3, C3, 1.0)
    ts, ys, us = relay_experiment(A3, B3, C3, 1.0, 40.0, DT)
    assert len(ts) == round(40.0 / DT) + 1
    Tm, am, center = analyze_cycle(ts, ys)
    # The relay acts at the steps only, which delays each switch by at most
    # one step. Measured: the period is 2 dt longer.
    assert 0 < Tm - T < 3 * DT
    assert abs(am - a) / a < 0.01
    assert abs(center) < 1e-6


@pytest.mark.parametrize("theta", [0.5, 1.0, 2.0])
def test_first_order_plus_delay_closed_form(theta):
    # P = e^(-theta s)/(s + 1): the half period is theta + ln(2 - e^(-theta))
    # and the amplitude is d (1 - e^(-theta)).
    dt = 0.002
    d = 1.5
    ts, ys, _ = relay_experiment([[-1.0]], [[1.0]], [1.0], d, 12 * (theta + 1), dt, delay=theta)
    Tm, am, _ = analyze_cycle(ts, ys)
    T = 2 * (theta + math.log(2 - math.exp(-theta)))
    assert abs(Tm - T) < 3 * dt
    assert abs(am - d * (1 - math.exp(-theta))) < 2e-3 * d


def test_amplitude_scales_with_d():
    _, a1, _ = analyze_cycle(*relay_experiment(A3, B3, C3, 1.0, 40.0, DT)[:2])
    _, a2, _ = analyze_cycle(*relay_experiment(A3, B3, C3, 2.5, 40.0, DT)[:2])
    assert abs(a2 - 2.5 * a1) < 1e-9


def test_hysteresis_moves_the_point():
    # With hysteresis the estimate lies near the point where the phase of P
    # is -180 + asin(eps/a) degrees. Measured: 1.3 degrees and 0.1 percent
    # off for this plant.
    eps = 0.05
    ts, ys, _ = relay_experiment(A3, B3, C3, 1.0, 40.0, DT, eps=eps)
    Tm, am, _ = analyze_cycle(ts, ys)
    k, ph = relay_estimate(1.0, am, eps)
    w = 2 * math.pi / Tm
    P = 1 / (1j * w + 1) ** 3
    assert abs(cmath.phase(P) - ph) < 0.04
    assert abs(k * abs(P) - 1) < 0.02


def test_analyze_cycle_on_a_sine():
    rng = random.Random(5)
    for _ in range(3):
        T, a, c = rng.uniform(0.5, 3.0), rng.uniform(0.1, 2.0), rng.uniform(-1.0, 1.0)
        dt = T / 1000
        ts = [k * dt for k in range(10001)]
        ys = [c + a * math.sin(2 * math.pi * t / T + 0.3) for t in ts]
        Tm, am, cm = analyze_cycle(ts, ys, r=c)
        assert abs(Tm - T) < 1e-6 * T
        assert abs(am - a) < 1e-4 * a and abs(cm - c) < 1e-4 * a
    with pytest.raises(ValueError):
        analyze_cycle(ts[:1500], ys[:1500], r=c)


def test_relay_estimate_errors():
    assert relay_estimate(1.0, 4 / math.pi) == (1.0, -math.pi)
    with pytest.raises(ValueError):
        relay_estimate(1.0, 0.1, eps=0.2)
    with pytest.raises(ValueError):
        relay_experiment(A3, B3, C3, 0.0, 1.0, DT)


def test_autotune_and_closed_loop():
    K, Ti, Td, ku, tu, a = relay_autotune(A3, B3, C3, 1.0, 40.0, DT)
    assert (K, Ti, Td) == ultimate_cycle_rule(ku, tu, "PID")
    assert abs(K / 4.8 - 1) < 0.05 and abs(Ti / (TU3 / 2) - 1) < 0.03
    N = 20.0

    def f(t, x, _):
        y = x[2]
        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 * (1.0 - y), N / Td * (y - x[4])]

    ts, xs, _ = simulate(f, [0.0] * 5, 0.0, 60.0, 0.01)
    ys = [x[2] for x in xs]
    assert abs(ys[-1] - 1) < 1e-6
    # Measured overshoot of this loop: 0.504.
    assert 0.4 < max(ys) - 1 < 0.6

History

The use of relays to make oscillations is old: relay servos were common in the 1940s and 1950s, and their limit cycles were analysed with the describing function. Karl Johan Åström and Tore Hägglund, at Lund, proposed in 1984 to use a relay experiment to tune simple controllers automatically. Their paper in Automatica showed how the relay gives a point of the Nyquist curve and how to design a PID controller from it with specifications on the phase and gain margins. The method became the basis of automatic tuning in industrial PID controllers, and it is now a standard feature of process controllers.

References

  1. K. J. Åström and T. Hägglund, Automatic tuning of simple regulators with specifications on phase and amplitude margins, Automatica 20(5) (1984) 645-651, the whole paper (the relay experiment and the describing function analysis)
  2. Karl Johan Åström and Tore Hägglund, Advanced PID Control, ISA, 2006, Chapter 9, Automatic tuning and adaptation
  3. Karl Johan Åström and Richard M. Murray, Feedback Systems, second edition, Princeton University Press, 2021, Chapter 11, PID Control (the section on tuning with relay feedback)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example