Algorithmcore
Model reference adaptive control
Also called MRAC, Lyapunov-based MRAC.
Adjusts the controller so that the plant output follows a reference model, with an adaptation law chosen to make a Lyapunov function decrease.
- Time
- O(n^6 + N n^2) worst
- Space
- O(n^4) extra
- Where
- N = the number of integration steps; n = the order of the plant
- Model
- Real RAM
- Properties
- deterministicnot exactonlineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- P. C. Parks, 1966
Model reference adaptive control (MRAC) is a direct adaptive controller: it adjusts the gains of a controller online so that the plant follows a reference model with a Hurwitz state matrix, with the adaptation law chosen so that a Lyapunov function of the tracking error and the gain error never increases. This page treats the state feedback form for a linear plant with unknown constant matrices. The result is a theorem: all signals stay bounded and the error goes to zero for every bounded reference, and the gains converge to their ideal values when the reference is persistently exciting. The Slotine-Li adaptive controller of robotics uses the same Lyapunov construction for the nonlinear dynamics of a robot arm, with the regressor of the arm in place of the state.
In plain words
You choose a model that shows how the controlled system should behave. The real system and the model get the same command, and the controller compares their states. A controller with adjustable gains acts on the real system. When the real system lags or overshoots the model, the gains move in the direction that removes the difference. The rule for this movement is not a guess: it is chosen so that a measure of the total error, made from the tracking error and the gain error, can only fall. So the gains and the states cannot run away, and the tracking error dies out. The gains themselves reach the correct values only if the command is rich enough, for example a sum of sine waves.
The problem
The plant is with the state measured, a single input , and , unknown. The reference model is , where is a Hurwitz matrix and is a bounded, piecewise continuous reference. The controller is with adjustable and . The structural assumptions are these.
- Matching. There are constant and with and . Then the controller with and makes the closed loop equal to the model.
- Known sign. The sign of is known. This is the sign of the high frequency gain of the plant.
The aim is to choose and from measured signals so that the tracking error goes to zero and all signals stay bounded.
The algorithm
With and , the matching conditions give the error equation
Choose a symmetric positive definite and solve the Lyapunov equation for . With , the adaptive laws are
The plant, the model and the gains form one system of differential equations. The implementation integrates it with the classical fourth order Runge-Kutta method and a fixed step .
MRAC(A_m, b_m, Q, γ, sgn, k₀, l₀, dt, N) ▷ A_m Hurwitz, Q ≻ 0, γ > 0- 1
solve A_mᵀ P + P A_m = -Q for P - 2
k ← k₀; l ← l₀; set the states x and x_m - 3
for i ← 0 to N - 1 do - 4
r ← r(t) ▷ the reference at t = i dt - 5
e ← x - x_m ▷ tracking error - 6
u ← kᵀ x + l r - 7
x' ← A x + b u; x_m' ← A_m x_m + b_m r - 8
k' ← -γ sgn x (b_mᵀ P e); l' ← -γ sgn r (b_mᵀ P e) - 9
advance x, x_m, k and l by one RK4 step of length dt - 10
return k, l
Line L1 runs once. Lines L4 to L8 are the right-hand side of the differential equation, and RK4 evaluates them four times per step in line L9. The plant matrices and in line L7 stand for the real plant; the controller uses only the measured .
Example
Scalar plant. The plant has a pole at . The model is , so and . With the Lyapunov equation gives , and the laws are and . All states and gains start at zero, and s.
| Reference | |||||
|---|---|---|---|---|---|
| 1 | -1.4731 | 0.9438 | -1.4997 | 0.9996 | |
| 5 | -1.5248 | 1.0466 | -1.5000 | 1.0000 | |
| 1 | 1 | -1.0756 | 0.5879 | -1.0818 | 0.5818 |
| 1 | 5 | -1.2382 | 0.7363 | -1.2372 | 0.7372 |
With the constant reference the error goes to zero in all runs, but the gains stop at a wrong point. The point is on the line , which is the set of gains with the correct static gain . A constant reference fixes only this one number. The sine excites one frequency, which fixes two numbers, and the gains converge to .
Second order plant. The plant , is unstable. The model has and , so and . With the exact solution is . The reference is , , and the gains start at zero. For , and , and decreases at every sample. The gains are , , , , and at . Three gains need two frequencies; one sine would not be enough.
Correctness
Take . Along solutions,
because the laws make the last two terms cancel. So , and are bounded, and is square integrable. Since is bounded, and are bounded, and Barbalat's lemma gives . If in addition the regressor is persistently exciting, the gain errors go to zero exponentially. The full proof is in proofs/correctness.md; the tests check that never increases and that equals the integral of .
Proof: The Lyapunov adaptive laws keep all signals bounded and drive the tracking error to zerofull
Notation is that of the page. The plant is , the model is with Hurwitz, and is bounded and piecewise continuous. There are , with and . The error is , , , , and solves . The laws are and with .
Claim 0 (P exists). Because is Hurwitz, converges, is symmetric positive definite, and is the unique solution of the Lyapunov equation. This is the standard theorem on the Lyapunov equation. The Kronecker form solved in line L1 has the matrix , whose eigenvalues are the sums of eigenvalues of . They all have negative real part, so the matrix is invertible and line L1 returns this .
Claim 1 (error equation). With ,
By matching, and , so . Since , this is .
Claim 2 (V does not increase). Let . Since , are constant, and . With , which equals because is symmetric,
The laws give , so the last term is , which cancels the middle term. Hence .
Claim 3 (bounded signals). By Claim 2, for all in the interval of existence. So gives , and . The model state is bounded because is Hurwitz and is bounded. So , and are bounded, and then is bounded. The right-hand side of the closed loop is locally Lipschitz in the state, and a bounded solution cannot escape in finite time, so the solution exists for all and is bounded.
Claim 4 (the error goes to zero). Integrate from to : . So . By Claim 1 and Claim 3, is bounded, so is uniformly continuous, and so is (a product of bounded, uniformly continuous functions). Its integral over is finite, so by Barbalat's lemma , and because .
Remark (parameter convergence). The proof above gives no convergence of and . If the regressor of the model is persistently exciting, that is, for some and all , then the equilibrium is exponentially attractive (Ioannou and Sun, Chapter 4 and Section 6.2, theorem). Without excitation the gains can stop at any point with along the limit trajectory. For the scalar example of the page with , this set is the line ; the tests check both cases.
Numerical check. The tests compute along the RK4 solution and check that equals the Simpson integral of within , which is Claim 2 in integral form.
Complexity
In the real-RAM model, the Lyapunov equation in line L1 is a linear system of unknowns. The implementation solves it in Kronecker form by Gaussian elimination, which costs operations and memory once; a Bartels-Stewart solver would cost . Each evaluation of the right-hand side costs for the plant and the model and for the laws, so RK4 steps cost . In a real controller the plant is the physical system, and the work per sample is for the model and for the laws.
Properties
- Bounded signals and zero error. Theorem: under matching and the known sign, every solution is bounded and for every bounded piecewise continuous and every .
- No parameter convergence without excitation. Theorem: the gains converge to exponentially if the regressor is persistently exciting; otherwise they can stop at any point that gives zero error, as the constant reference shows.
- Direct. The law adapts the controller gains, not a plant model. Compare the indirect self-tuning regulator.
- No robustness margin. The proof needs the exact matching structure. With a bounded disturbance the gains can drift without bound, and with unmodeled dynamics the loop can lose stability (Rohrs counterexample).
- Transient. bounds the tracking error by , but grows with the initial gain error divided by , so the bound says little about the size of the transient for small , and a large gives oscillatory control signals.
Variants and improvements
- Robust modifications. Sigma modification, parameter projection, the -modification and a dead zone keep the gains bounded under disturbances and unmodeled dynamics, at the cost of a residual error.
- Output feedback MRAC. When only the output is measured, the controller uses filters of the input and output. For a model of relative degree one with a strictly positive real transfer function, the same Lyapunov argument works through the Kalman-Yakubovich-Popov lemma. Higher relative degree needs an augmented error or adaptive backstepping.
- L1 adaptive control. Adds a low-pass filter on the control signal and uses a high adaptation gain, to separate the speed of adaptation from robustness.
- Nonlinear plants. When the uncertainty is linear in the unknown parameters, the same design applies with a regressor in place of ; the Slotine-Li adaptive controller is the robot arm case.
- The MIT rule. The older gradient law of the MIT rule has the same form for the first order plant but needs sensitivity filters, and it has no stability proof.
When to use it
Use MRAC when the plant structure is known, the parameters are constant or slowly varying, the full state is measured and the matching condition holds, for example a flight control loop with unknown aerodynamic coefficients. Add a robust modification in every real application, because measurement noise and unmodeled dynamics break the proof. When the plant changes in a known way with an operating point, gain scheduling is often simpler.
Pitfalls
- Wrong sign of . The laws then push the gains away from , and the loop can go unstable.
- No matching. If has no solution, the error does not go to zero and the gains can drift.
- Parameter drift. A small constant disturbance and a reference that is not persistently exciting can make grow slowly without bound, until the loop goes unstable.
- High adaptation gain. The proof holds for every , but a large gives a stiff system and high frequency control signals that excite unmodeled dynamics.
- Error sign. This page uses . With the opposite sign every law changes sign.
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()
model_reference_adaptive_control.py 92 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/model-reference-adaptive-control/. The authors are listed in prov/V7E58W.jsonl.
"""Lyapunov based model reference adaptive control with full state feedback.
Plant: x' = A x + b u (A, b unknown, single input)
Model: x_m' = A_m x_m + b_m r (A_m Hurwitz, chosen by the designer)
Control: u = k^T x + l r
Matching condition: there are k*, l* with A + b k*^T = A_m and b l* = b_m.
The sign of l* must be known. With e = x - x_m, P the solution of
A_m^T P + P A_m = -Q (Q symmetric positive definite) and gamma > 0, the
adaptive laws
k' = -gamma sgn(l*) x (b_m^T P e)
l' = -gamma sgn(l*) r (b_m^T P e)
make V = e^T P e + (|k - k*|^2 + (l - l*)^2) / (gamma |l*|)
satisfy V' = -e^T Q e <= 0.
The simulation uses the classical RK4 method with a fixed step dt from
ctlsim. The time t1 must be an integer multiple of dt.
"""
from ctlmat import eye, kron, solve, transpose, unvec, vec
from ctlsim import rk4_step
__all__ = ["lyapunov_p", "mrac", "lyapunov_v"]
def _steps(t1, dt):
n = round(t1 / dt)
assert abs(n * dt - t1) <= 1e-9 * max(1.0, abs(t1)), "dt must divide t1"
return n
def lyapunov_p(Am, Q):
"""Solve A_m^T P + P A_m = -Q by the Kronecker form (exact for Fraction input)."""
n = len(Am)
At = transpose(Am)
# vec(At P) = (I kron At) vec(P), vec(P Am) = (Am^T kron I) vec(P)
I = eye(n)
K = [[x + y for x, y in zip(r1, r2)] for r1, r2 in zip(kron(I, At), kron(At, I))]
p = solve(K, [-v for v in vec(Q)])
return unvec(p, n, n)
def mrac(A, b, Am, bm, Q, gamma, sign_l, r, t1, dt, k0=None, l0=0.0, x0=None, xm0=None, every=1):
"""Simulate Lyapunov MRAC. r(t) is the reference signal.
Returns (ts, xs, xms, ks, ls) sampled every `every` steps.
"""
n = len(A)
P = [[float(v) for v in row] for row in lyapunov_p(Am, Q)] # @line L1
Pbm = [sum(P[j][i] * bm[j] for j in range(n)) for i in range(n)] # (b_m^T P) as a row
k = [0.0] * n if k0 is None else [float(v) for v in k0]
x = [0.0] * n if x0 is None else [float(v) for v in x0]
xm = [0.0] * n if xm0 is None else [float(v) for v in xm0]
s = x + xm + k + [float(l0)] # @line L2
def f(t, z, _u):
x, xm, k, l = z[:n], z[n:2 * n], z[2 * n:3 * n], z[3 * n]
rt = r(t) # @line L4
e = [xi - mi for xi, mi in zip(x, xm)] # @line L5
u = sum(ki * xi for ki, xi in zip(k, x)) + l * rt # @line L6
dx = [sum(a * xi for a, xi in zip(row, x)) + bi * u for row, bi in zip(A, b)] # @line L7
dxm = [sum(a * xi for a, xi in zip(row, xm)) + bi * rt for row, bi in zip(Am, bm)]
s_e = sum(p * ei for p, ei in zip(Pbm, e))
dk = [-gamma * sign_l * xi * s_e for xi in x] # @line L8
dl = -gamma * sign_l * rt * s_e
return dx + dxm + dk + [dl]
N = _steps(t1, dt)
ts, xs, xms, ks, ls = [0.0], [s[:n]], [s[n:2 * n]], [s[2 * n:3 * n]], [s[3 * n]]
for i in range(N): # @line L3
s = rk4_step(f, i * dt, s, None, dt) # @line L9
if (i + 1) % every == 0:
ts.append((i + 1) * dt)
xs.append(s[:n])
xms.append(s[n:2 * n])
ks.append(s[2 * n:3 * n])
ls.append(s[3 * n])
return ts, xs, xms, ks, ls # @line L10
def lyapunov_v(P, gamma, l_star, k_star, x, xm, k, l):
"""V = e^T P e + (|k - k*|^2 + (l - l*)^2) / (gamma |l*|)."""
n = len(x)
e = [x[i] - xm[i] for i in range(n)]
epe = sum(e[i] * P[i][j] * e[j] for i in range(n) for j in range(n))
dk = sum((k[i] - k_star[i]) ** 2 for i in range(n))
return epe + (dk + (l - l_star) ** 2) / (gamma * abs(l_star))
test_model_reference_adaptive_control.py 108 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/model-reference-adaptive-control/. The authors are listed in prov/V7E58W.jsonl.
"""Tests for Lyapunov MRAC. RK4 with a fixed step; tolerances are stated."""
import math
import random
import unittest
from fractions import Fraction
from ctlmat import add, is_pos_def, mul, polymul, transpose
from model_reference_adaptive_control import lyapunov_p, lyapunov_v, mrac
# second order plant x1' = x2, x2' = x1 - x2 + u (unstable, a pole at 0.618)
A2 = [[0.0, 1.0], [1.0, -1.0]]
B2 = [0.0, 1.0]
AM2 = [[0.0, 1.0], [-4.0, -2.0]]
BM2 = [0.0, 4.0]
K2, L2 = [-5.0, -1.0], 4.0 # A + b k*^T = A_m, b l* = b_m
Q2 = [[1, 0], [0, 1]]
def two_sines(t):
return math.sin(t) + math.sin(3.0 * t)
def run2(gamma, t1=60.0, every=10):
return mrac(A2, B2, AM2, BM2, Q2, gamma, 1, two_sines, t1, 0.01, x0=[1.0, 0.0], every=every)
def run1(gamma, r, t1=60.0):
# y' = y + 2 u, model y_m' = -2 y_m + 2 r: k* = -1.5, l* = 1
return mrac([[1.0]], [2.0], [[-2.0]], [2.0], [[4]], gamma, 1, r, t1, 0.01, every=100)
class TestLyapunovEquation(unittest.TestCase):
def test_exact_solution(self):
P = lyapunov_p([[0, 1], [-4, -2]], Q2)
self.assertEqual(P, [[Fraction(3, 2), Fraction(1, 8)], [Fraction(1, 8), Fraction(5, 16)]])
self.assertTrue(is_pos_def(P))
def test_random_hurwitz_residual_is_zero(self):
rng = random.Random(3)
for n in (1, 2, 3, 4):
# companion matrix of a polynomial with roots -1 .. -9
p = [1]
for _ in range(n):
p = polymul(p, [1, rng.randint(1, 9)])
Am = [[1 if j == i + 1 else 0 for j in range(n)] for i in range(n - 1)]
Am.append([-c for c in reversed(p[1:])])
Q = [[rng.randint(1, 3) if i == j else 0 for j in range(n)] for i in range(n)]
P = lyapunov_p(Am, Q)
res = add(add(mul(transpose(Am), P), mul(P, Am)), Q)
self.assertTrue(all(v == 0 for row in res for v in row))
self.assertTrue(is_pos_def(P))
class TestLyapunovFunction(unittest.TestCase):
def test_v_does_not_increase(self):
P = [[float(v) for v in row] for row in lyapunov_p(AM2, Q2)]
_, xs, xms, ks, ls = run2(1.0)
V = [lyapunov_v(P, 1.0, L2, K2, x, m, k, l) for x, m, k, l in zip(xs, xms, ks, ls)]
self.assertAlmostEqual(V[0], 12.0, places=12)
for v0, v1 in zip(V, V[1:]):
self.assertLessEqual(v1, v0 + 1e-10)
def test_v_drop_equals_integral(self):
# reference: V(0) - V(T) = integral of e^T Q e (Simpson rule)
P = [[float(v) for v in row] for row in lyapunov_p(AM2, Q2)]
_, xs, xms, ks, ls = run2(5.0, t1=10.0, every=1)
V = [lyapunov_v(P, 5.0, L2, K2, x, m, k, l) for x, m, k, l in zip(xs, xms, ks, ls)]
q = [(x[0] - m[0]) ** 2 + (x[1] - m[1]) ** 2 for x, m in zip(xs, xms)]
h = 0.01
integral = h / 3 * (q[0] + q[-1] + 4 * sum(q[1:-1:2]) + 2 * sum(q[2:-1:2]))
self.assertLess(abs((V[0] - V[-1]) - integral), 1e-6)
class TestConvergence(unittest.TestCase):
def test_rich_reference_gives_parameter_convergence(self):
_, xs, xms, ks, ls = run2(5.0)
self.assertLess(max(abs(a - b) for a, b in zip(ks[-1], K2)), 1e-3)
self.assertLess(abs(ls[-1] - L2), 1e-3)
self.assertLess(max(abs(x[0] - m[0]) for x, m in zip(xs[-100:], xms[-100:])), 1e-4)
def test_sine_vs_constant_reference(self):
_, _, _, ks, ls = run1(5.0, math.sin)
self.assertLess(abs(ks[-1][0] + 1.5), 1e-3)
self.assertLess(abs(ls[-1] - 1.0), 1e-3)
_, xs, xms, ks, ls = run1(5.0, lambda t: 1.0)
self.assertLess(abs(xs[-1][0] - xms[-1][0]), 1e-6)
# the parameters stop on the line l + k = -0.5, away from (k*, l*)
self.assertLess(abs(ks[-1][0] + ls[-1] + 0.5), 1e-3)
self.assertGreater(abs(ks[-1][0] + 1.5), 0.2)
def test_ideal_gains_give_model_error_decay(self):
# reference: with gamma = 0 and the ideal gains, e(t) = e(0) exp(-2 t)
ts, xs, xms, _, _ = mrac([[1.0]], [2.0], [[-2.0]], [2.0], [[4]], 0.0, 1, math.sin,
3.0, 0.01, k0=[-1.5], l0=1.0, x0=[1.0], every=50)
for t, x, m in zip(ts, xs, xms):
self.assertLess(abs((x[0] - m[0]) - math.exp(-2.0 * t)), 1e-8)
def test_dt_must_divide_t1(self):
with self.assertRaises(AssertionError):
run1(1.0, math.sin, t1=1.005)
if __name__ == "__main__":
unittest.main()
History
Whitaker, Yamron and Kezer (1958) proposed the model reference scheme with the MIT rule, which has no stability guarantee. Parks (1966) redesigned the law from a Lyapunov function and gave the first model reference adaptive systems with a stability proof (bounded signals and an error that goes to zero) for plants whose state is measured. Around 1980 several groups, among them Morse, Narendra, Lin and Valavani, proved global stability for output feedback MRAC of linear plants of any relative degree. Rohrs and co-authors showed in 1985 that these schemes can lose stability under small unmodeled dynamics, which started the work on robust adaptive control (Ioannou and Sun, Section 1.3 and Chapter 8).
References
- Karl Johan Åström and Björn Wittenmark, Adaptive Control, second edition, Addison-Wesley 1995 (Dover reprint 2008), Chapter 5, Model-reference adaptive systems: the sections on Lyapunov theory and on the design of model reference adaptive systems with Lyapunov theory
- Petros A. Ioannou and Jing Sun, Robust Adaptive Control, Prentice Hall 1996 (Dover reprint 2012), Chapter 6, Model reference adaptive control: Section 6.2 (simple direct MRAC schemes, with the scalar and the full state examples)
- P. C. Parks, Liapunov redesign of model reference adaptive control systems, IEEE Transactions on Automatic Control 11(3), 1966, pages 362 to 367
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 V7E58W Edit this page History Report an error Markdown