Algorithmcore
Self-tuning regulator
Also called STR.
Estimates the plant online by recursive least squares and redesigns the controller from the estimate at each sample.
- Time
- O(N d^2) worst
- Space
- O(d^2) extra
- Where
- N = the number of samples; d = the number of estimated parameters
- Model
- Real RAM
- Properties
- deterministicnot exactonlineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Karl Johan Åström, Björn Wittenmark, 1973
A self-tuning regulator (STR) is an adaptive controller that repeats two steps at every sample: it updates an estimate of a plant model from the latest input and output, and it computes the controller from the estimate as if the estimate were exact (certainty equivalence). The estimator is usually the RLS algorithm; the RLS page covers the estimator alone, and this page covers the closed loop that wraps a control design around it, where the data are generated by the controller that the estimate defines. This page treats the direct minimum variance self-tuner of Åström and Wittenmark (1973). Its main result is the self-tuning property: if the estimates converge, the limit controller gives the minimum output variance, even though the least squares estimates of a plant with coloured noise are biased.
In plain words
The regulator keeps a simple model of the plant and keeps improving it. At each sample it measures the output, checks how wrong the model's last prediction was, and corrects the model a little. Then it computes the input that, by the corrected model, would bring the next output as close to zero as possible, and it applies that input. The model is never assumed to be exact; the regulator just acts as if it were, and fixes the model again at the next sample. For the noise regulation problem on this page, this simple loop finds the best possible controller, even though the model it uses is too simple to describe the noise.
The problem
The plant is an ARMAX model with a delay of one sample,
where is white noise with variance , the polynomial has all zeros inside the unit circle, and has all zeros inside the unit circle (the plant is minimum phase). The coefficients are unknown. The aim is to minimize the output variance . The controller that does this, when the plant is known, is the minimum variance controller: it makes the one step ahead prediction equal to zero, so that is the prediction error , and the minimum variance is .
The algorithm
The direct self-tuner does not estimate , and . It estimates the parameters of the controller directly, from the model
where is a fixed guess of with the correct sign, and . The control sets the predicted output of this model to zero.
STR-MV(β₀, θ₀, p₀, λ, N) ▷ λ ∈ (0, 1] is the forgetting factor- 1
θ̂ ← θ₀; P ← p₀ I - 2
for t ← 0 to N - 1 do - 3
measure y_t - 4
z ← y_t - β₀ u_{t-1} ▷ the regression target - 5
K ← P φ_{t-1} / (λ + φ_{t-1}ᵀ P φ_{t-1}) - 6
θ̂ ← θ̂ + K (z - φ_{t-1}ᵀ θ̂) - 7
P ← (P - K φ_{t-1}ᵀ P) / λ - 8
u_t ← -φ_tᵀ θ̂ / β₀ ▷ certainty equivalence: predicted y_{t+1} = 0 - 9
return θ̂
Lines L4 to L7 are one step of recursive least squares. Line L8 is the control design; for this problem it is one division. In an indirect self-tuner, line L8 is replaced by a full design from an estimated plant model, for example the polynomial equation of adaptive pole placement.
Example
Take the first order plant with , so , and . The open loop has the pole and the variance . The prediction is . Under the minimum variance law , so the law is , and then exactly.
The self-tuner uses , , so it estimates one number in , and it applies . The ideal value of is . The start is , , and ; the variance is taken over . These are measurements for one noise sequence (seed 0).
| at | output variance | |
|---|---|---|
| 0.25 | 2.803 | 1.014 |
| 0.5 | 2.780 | 1.014 |
| 1 | 2.620 | 1.031 |
| 2 | 2.104 | 1.171 |
With and the seeds 0 to 7, at is between 2.62 and 2.785, the output variance is between 0.97 and 1.04, and the lag one autocorrelation of is at most 0.13 in absolute value. The variance is flat near the optimum: the gain 2.62 gives the closed loop pole and the variance , only 1 percent above the minimum. The open loop variance measured on one sequence of 3500 samples is 12.3.
Correctness
The proof in proofs/correctness.md shows two facts. First, the parameter of the minimum variance controller is a fixed point of the least squares estimator in closed loop: when the regulator uses , the output is , the residual is , and this is uncorrelated with , so the normal equations hold at . Second (the self-tuning property, a theorem of Åström and Wittenmark), if converges and the closed loop signals are bounded in mean square, the limit makes the sample correlations for and for zero; when and are large enough, this forces the minimum variance controller. Convergence itself is a separate and harder theorem: Ljung (1977) proved convergence with probability one under a positive real condition on , with the method of an associated differential equation.
Proof: The minimum variance self-tuner has the self-tuning propertyfull
Notation is that of the page. The regressor is , the target is , and the control is (line L8), where is the estimate after the update with . We take .
Claim 1 (the residual is the output). Line L8 gives . So
In closed loop, the prediction error of the model at the current estimate is the next output.
Claim 2 (normal equations of RLS). Line L5 to L7 with are the recursive form of and (a standard identity, proved on the page RLS algorithm with the Sherman-Morrison formula; the tests check it exactly in rational arithmetic). By Claim 1, . Substitute and subtract :
Claim 3 (self-tuning property). Assume and for all . Then . In terms of sample correlations, for , and for , whenever these limits exist.
Proof. Divide the identity of Claim 2 by . The first term is because is bounded. For the second term, let and choose with for . For , the terms with satisfy , so their sum divided by is at most . The terms with are a fixed finite sum, which divided by goes to . So the of the norm is at most for every , which proves the limit. The components of are for and for , which give the stated correlations.
Claim 4 (the example limit is the minimum variance law). For the plant with and , a constant gain gives with . For this is a stationary ARMA(1,1) process, and its correlations are and . Since , if and only if , that is . Then , so up to a term that goes to zero, and the variance is , the minimum: every causal law gives , whose variance is at least because is independent of the data up to . With , , this is , the value of the page. So by Claim 3, if the estimate converges and the loop is bounded in mean square, the limit gain is .
Remark. Claims 3 and 4 assume convergence; they do not prove it. Ljung (1977) proved convergence with probability one under a positive real condition on (a theorem not reproduced here). The tests measure convergence on fixed noise sequences.
Complexity
With parameters, one RLS step costs operations in the real-RAM model and the control law costs . So samples cost , and the memory is the matrix , . An indirect self-tuner adds the cost of the design, for example solving a polynomial equation of size by Gaussian elimination in at each sample.
Properties
- Self-tuning property. Theorem (Åström and Wittenmark 1973): if the estimates converge, the limit controller is the minimum variance controller, for a model with enough parameters. The bias of least squares under coloured noise does not matter, because the controller, not the plant, is estimated.
- Convergence. Theorem (Ljung 1977): convergence with probability one holds under a positive real condition on the noise polynomial . Without it, the estimates can fail to converge.
- Choice of . Only the sign of must be correct for the fixed point, but the speed of convergence depends on the ratio . The table shows faster convergence for near or below (measurement).
- Not a dual controller. The regulator ignores the uncertainty of the estimate when it chooses the input. It does not add probing signals, so the estimates can stop learning when the loop is quiet.
- Minimum phase plants only. The minimum variance law cancels the zeros of . An unstable zero gives an unbounded input. Indirect self-tuners with pole placement avoid this.
Variants and improvements
- Indirect self-tuners. Estimate and by RLS and solve a design problem at each sample, for example adaptive pole placement or a linear quadratic design. This allows non-minimum phase plants.
- Generalized minimum variance. Add a penalty on the input to the cost, which limits the control effort and can handle some non-minimum phase plants (Clarke and Gawthrop).
- Forgetting. A forgetting factor tracks slowly changing parameters. Without excitation, then grows without bound (estimator windup); constant trace or directional forgetting limits this.
- Predictive self-tuners. Generalized predictive control and model predictive control with an online model use a cost over a longer horizon.
- Model reference adaptive control. MRAC is the continuous-time, direct counterpart with a Lyapunov design in place of least squares.
When to use it
Use a self-tuning regulator for a sampled process with slowly varying dynamics and a noise disturbance, where a model of fixed structure is acceptable, for example a process control loop whose gain drifts with the production rate. Use the minimum variance form only for minimum phase plants with a known delay. For a plant with a known operating schedule, gain scheduling is often simpler, and for a one-time tuning, relay autotuning of a PID controller is the usual industrial choice.
Pitfalls
- Wrong delay. The law assumes a delay of one sample. With a longer delay, the one step predictor is wrong and the loop can go unstable; use the step predictor.
- Wrong sign of . The fixed point then has the wrong sign of the gain.
- Estimator windup. With forgetting and a quiet loop, grows, and a later disturbance gives a large jump of the estimate.
- Bursting. Without excitation the estimates can drift slowly until the closed loop becomes unstable, then the burst of data corrects them, and the cycle repeats.
- Non-minimum phase zeros. Sampling a continuous plant of relative degree at least 3 with a short sampling period creates zeros outside the unit circle (a theorem of Åström, Hagander and Sternby, 1984); the minimum variance law then gives an unbounded input.
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
# Part of https://algorithm.tamnd.com/self-tuning-regulator/. The authors are listed in prov/KY0VB7.jsonl.
"""The direct minimum variance self-tuning regulator of Astrom and Wittenmark.
Plant (ARMAX, delay one sample):
y_t = -a_1 y_(t-1) - ... - a_n y_(t-n) + b_1 u_(t-1) + ... + b_m u_(t-m)
+ e_t + c_1 e_(t-1) + ... + c_k e_(t-k),
with white noise e_t. The regulator estimates by recursive least squares
the predictor model
y_(t+1) - beta0 u_t = s_0 y_t + ... + s_ns y_(t-ns) + r_1 u_(t-1) + ... + r_nr u_(t-nr),
with beta0 fixed (a guess of b_1), and applies the control that makes the
predicted output zero (certainty equivalence):
u_t = -(s_0 y_t + ... + r_nr u_(t-nr)) / beta0.
rls_update works with float or Fraction entries; with Fraction it is exact.
"""
import random
__all__ = ["rls_update", "str_minimum_variance", "mv_gain_first_order"]
def rls_update(theta, P, phi, z, lam=1):
"""One recursive least squares step with forgetting factor lam.
theta: estimate (list), P: covariance (list of rows), phi: regressor,
z: new measurement. Returns (theta, P) for the data up to z.
"""
n = len(theta)
Pphi = [sum(P[i][j] * phi[j] for j in range(n)) for i in range(n)]
den = lam + sum(phi[i] * Pphi[i] for i in range(n))
K = [v / den for v in Pphi] # @line L5
eps = z - sum(phi[i] * theta[i] for i in range(n))
theta = [theta[i] + K[i] * eps for i in range(n)] # @line L6
P = [[(P[i][j] - K[i] * Pphi[j]) / lam for j in range(n)] for i in range(n)] # @line L7
return theta, P
def str_minimum_variance(a, b, c, beta0, N, seed, ns=0, nr=0, sigma=1.0, p0=100.0, lam=1.0,
theta0=None, adapt=True):
"""Run the self-tuning regulator for N samples on the ARMAX plant.
a, b, c are the coefficient lists [a_1..a_n], [b_1..b_m], [c_1..c_k].
The noise e_t is Gaussian with standard deviation sigma from
random.Random(seed). The estimate starts at theta0 (zeros if None).
With adapt=False the estimate stays at theta0, which gives a fixed
controller. Returns (thetas, ys, us, es): the estimate after each
sample, the outputs, the inputs and the noise.
"""
rng = random.Random(seed)
d = ns + 1 + nr
theta = [0.0] * d if theta0 is None else [float(v) for v in theta0] # @line L1
P = [[p0 if i == j else 0.0 for j in range(d)] for i in range(d)]
hist = max(len(a), len(b), len(c), ns + 1, nr + 1) + 1
ys, us, es = [0.0] * hist, [0.0] * hist, [0.0] * hist
thetas = []
phi_prev = None
for _ in range(N): # @line L2
e = rng.gauss(0.0, sigma)
y = (-sum(ai * ys[-1 - i] for i, ai in enumerate(a))
+ sum(bi * us[-1 - i] for i, bi in enumerate(b))
+ e + sum(ci * es[-1 - i] for i, ci in enumerate(c))) # @line L3
ys.append(y)
es.append(e)
if phi_prev is not None and adapt:
z = y - beta0 * us[-1] # @line L4
theta, P = rls_update(theta, P, phi_prev, z, lam)
phi = [ys[-1 - i] for i in range(ns + 1)] + [us[-1 - i] for i in range(nr)]
u = -sum(t * p for t, p in zip(theta, phi)) / beta0 # @line L8
us.append(u)
phi_prev = phi
thetas.append(list(theta))
return thetas, ys[hist:], us[hist:], es[hist:] # @line L9
def mv_gain_first_order(a, b, c):
"""Minimum variance gain for y_(t+1) = -a y_t + b u_t + e_(t+1) + c e_t.
u_t = g y_t with g = (a - c) / b makes y_t = e_t.
"""
return (a - c) / b
test_self_tuning_regulator.py 79 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/self-tuning-regulator/. The authors are listed in prov/KY0VB7.jsonl.
"""Tests for the minimum variance self-tuning regulator."""
import random
import unittest
from fractions import Fraction
from self_tuning_regulator import mv_gain_first_order, rls_update, str_minimum_variance
# y_(t+1) = 0.9 y_t + 0.5 u_t + e_(t+1) + 0.5 e_t; minimum variance law u = -2.8 y
PLANT = ([-0.9], [0.5], [0.5])
def stats(ys, skip=0):
y = ys[skip:]
n = len(y)
r0 = sum(v * v for v in y) / n
r1 = sum(y[i] * y[i + 1] for i in range(n - 1)) / n
return r0, r1 / r0
class TestRLS(unittest.TestCase):
def test_exact_against_weighted_least_squares(self):
# reference: theta = (lam^t P0^-1 + sum lam^(t-i) phi phi^T)^-1 sum lam^(t-i) phi z
rng = random.Random(1)
for lam in (Fraction(1), Fraction(9, 10)):
p0 = Fraction(100)
theta = [Fraction(0), Fraction(0)]
P = [[p0, Fraction(0)], [Fraction(0), p0]]
data = []
for t in range(1, 13):
phi = [Fraction(rng.randint(-5, 5)), Fraction(rng.randint(-5, 5))]
z = Fraction(rng.randint(-9, 9), rng.randint(1, 4))
data.append((phi, z))
theta, P = rls_update(theta, P, phi, z, lam)
M = [[lam ** t / p0 if i == j else Fraction(0) for j in range(2)] for i in range(2)]
v = [Fraction(0), Fraction(0)]
for i, (ph, zz) in enumerate(data, start=1):
w = lam ** (t - i)
for r in range(2):
v[r] += w * ph[r] * zz
for c in range(2):
M[r][c] += w * ph[r] * ph[c]
det = M[0][0] * M[1][1] - M[0][1] * M[1][0]
want = [(v[0] * M[1][1] - M[0][1] * v[1]) / det,
(M[0][0] * v[1] - M[1][0] * v[0]) / det]
self.assertEqual(theta, want)
class TestMinimumVariance(unittest.TestCase):
def test_true_gain_gives_white_output(self):
# reference: with the minimum variance gain the output equals the noise
g = mv_gain_first_order(-0.9, 0.5, 0.5)
self.assertAlmostEqual(g, -2.8, places=12)
_, ys, _, es = str_minimum_variance(*PLANT, 1.0, 2000, 5, theta0=[-g], adapt=False)
self.assertLess(max(abs(y - e) for y, e in zip(ys, es)), 1e-9)
def test_self_tuner_reaches_minimum_variance(self):
for seed in (0, 1):
th, ys, _, es = str_minimum_variance(*PLANT, 1.0, 5000, seed)
self.assertLess(abs(th[-1][0] - 2.8), 0.25)
r0, rho1 = stats(ys, 1000)
e0 = sum(e * e for e in es[1000:]) / len(es[1000:])
self.assertLess(abs(r0 - e0), 0.1)
self.assertLess(abs(rho1), 0.15)
def test_much_better_than_open_loop(self):
# open loop variance (1 + c^2 + 2 a c) / (1 - a^2) = 2.15 / 0.19 = 11.3
_, y_ol, _, _ = str_minimum_variance(*PLANT, 1.0, 4000, 2, adapt=False)
_, y_str, _, _ = str_minimum_variance(*PLANT, 1.0, 4000, 2)
v_ol, v_str = stats(y_ol, 500)[0], stats(y_str, 500)[0]
self.assertGreater(v_ol, 8.0)
self.assertLess(v_str, 1.2)
if __name__ == "__main__":
unittest.main()
History
Kalman (1958) built a self-optimizing controller that combined least squares estimation of a plant model with a control design, an early form of the idea. Åström and Wittenmark (1973) proposed the self-tuning regulator with least squares estimation and minimum variance control and proved the self-tuning property. Ljung (1977) proved convergence with an ordinary differential equation that describes the average behaviour of the estimates. Clarke and Gawthrop added a penalty on the control signal, and many industrial self-tuners followed in the late 1970s and the 1980s.
References
- Karl Johan Åström and Björn Wittenmark, Adaptive Control, second edition, Addison-Wesley 1995 (Dover reprint 2008), Chapter 3, Deterministic self-tuning regulators, and Chapter 4, Stochastic and predictive self-tuning regulators (the direct minimum variance self-tuner)
- K. J. Åström and B. Wittenmark, On self tuning regulators, Automatica 9(2), 1973, pages 185 to 199 (the algorithm and the self-tuning property)
- R. E. Kalman, Design of a self-optimizing control system, Transactions of the ASME 80, 1958, the whole paper (least squares estimation combined with a control design)
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 KY0VB7 Edit this page History Report an error Markdown