Algorithm Search⌘K

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
Properties
deterministicnot exactonlineiterative
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 x˙=Ax+bu\dot x = A x + b u with the state x∈Rnx \in \mathbb{R}^n measured, a single input uu, and AA, bb unknown. The reference model is x˙m=Amxm+bmr\dot x_m = A_m x_m + b_m r, where AmA_m is a Hurwitz matrix and r(t)r(t) is a bounded, piecewise continuous reference. The controller is u=kTx+l ru = k^T x + l\,r with adjustable k∈Rnk \in \mathbb{R}^n and l∈Rl \in \mathbb{R}. The structural assumptions are these.

  • Matching. There are constant k∗k^* and l∗l^* with A+b k∗T=AmA + b\,k^{*T} = A_m and b l∗=bmb\,l^* = b_m. Then the controller with k=k∗k = k^* and l=l∗l = l^* makes the closed loop equal to the model.
  • Known sign. The sign of l∗l^* is known. This is the sign of the high frequency gain of the plant.

The aim is to choose k˙\dot k and l˙\dot l from measured signals so that the tracking error e=x−xme = x - x_m goes to zero and all signals stay bounded.

The algorithm

With k~=k−k∗\tilde k = k - k^* and l~=l−l∗\tilde l = l - l^*, the matching conditions give the error equation

e˙=Ame+bml∗(k~Tx+l~ r).\dot e = A_m e + \frac{b_m}{l^*}\big(\tilde k^T x + \tilde l\, r\big).

Choose a symmetric positive definite QQ and solve the Lyapunov equation AmTP+PAm=−QA_m^T P + P A_m = -Q for PP. With γ>0\gamma > 0, the adaptive laws are

k˙=−γ sgn(l∗) x bmTPe,l˙=−γ sgn(l∗) r bmTPe.\dot k = -\gamma\,\mathrm{sgn}(l^*)\, x\, b_m^T P e, \qquad \dot l = -\gamma\,\mathrm{sgn}(l^*)\, r\, b_m^T P e.

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 dtdt.

  1. MRAC(A_m, b_m, Q, γ, sgn, k₀, l₀, dt, N) ▷ A_m Hurwitz, Q ≻ 0, γ > 0
  2. 1solve A_mᵀ P + P A_m = -Q for P
  3. 2k ← k₀; l ← l₀; set the states x and x_m
  4. 3for i ← 0 to N - 1 do
  5. 4r ← r(t) ▷ the reference at t = i dt
  6. 5e ← x - x_m ▷ tracking error
  7. 6u ← kᵀ x + l r
  8. 7x' ← A x + b u; x_m' ← A_m x_m + b_m r
  9. 8k' ← -γ sgn x (b_mᵀ P e); l' ← -γ sgn r (b_mᵀ P e)
  10. 9advance x, x_m, k and l by one RK4 step of length dt
  11. 10return 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 AA and bb in line L7 stand for the real plant; the controller uses only the measured xx.

Example

Scalar plant. The plant y˙=y+2u\dot y = y + 2u has a pole at +1+1. The model is y˙m=−2ym+2r\dot y_m = -2 y_m + 2 r, so k∗=−(1+2)/2=−1.5k^* = -(1 + 2)/2 = -1.5 and l∗=1l^* = 1. With Q=4Q = 4 the Lyapunov equation gives P=1P = 1, and the laws are k˙=−2γ ye\dot k = -2\gamma\, y e and l˙=−2γ re\dot l = -2\gamma\, r e. All states and gains start at zero, and dt=0.01dt = 0.01 s.

Reference γ\gamma k(10)k(10) l(10)l(10) k(60)k(60) l(60)l(60)
sin⁡t\sin t 1 -1.4731 0.9438 -1.4997 0.9996
sin⁡t\sin t 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 k+l=−0.5k + l = -0.5, which is the set of gains with the correct static gain 2l/(−(1+2k))=12l/(-(1 + 2k)) = 1. A constant reference fixes only this one number. The sine excites one frequency, which fixes two numbers, and the gains converge to (k∗,l∗)(k^*, l^*).

Second order plant. The plant x˙1=x2\dot x_1 = x_2, x˙2=x1−x2+u\dot x_2 = x_1 - x_2 + u is unstable. The model has Am=[0,1;−4,−2]A_m = [0, 1; -4, -2] and bm=(0,4)b_m = (0, 4), so k∗=(−5,−1)k^* = (-5, -1) and l∗=4l^* = 4. With Q=IQ = I the exact solution is P=[3/2,1/8;1/8,5/16]P = [3/2, 1/8; 1/8, 5/16]. The reference is r=sin⁡t+sin⁡3tr = \sin t + \sin 3t, x(0)=(1,0)x(0) = (1, 0), and the gains start at zero. For γ=1\gamma = 1, V(0)=12V(0) = 12 and V(60)=3.4×10−9V(60) = 3.4 \times 10^{-9}, and VV decreases at every sample. The gains are k(10)=(−4.522,−0.747)k(10) = (-4.522, -0.747), l(10)=3.697l(10) = 3.697, k(30)=(−4.987,−1.000)k(30) = (-4.987, -1.000), l(30)=3.993l(30) = 3.993, and (k,l)=(−5.000,−1.000,4.000)(k, l) = (-5.000, -1.000, 4.000) at t=60t = 60. Three gains need two frequencies; one sine would not be enough.

Correctness

Take V=eTPe+(k~Tk~+l~2)/(γ∣l∗∣)V = e^T P e + (\tilde k^T \tilde k + \tilde l^2)/(\gamma |l^*|). Along solutions,

V˙=−eTQe+2l∗eTPbm(k~Tx+l~r)+2γ∣l∗∣(k~Tk˙+l~l˙)=−eTQe≤0,\dot V = -e^T Q e + \frac{2}{l^*} e^T P b_m(\tilde k^T x + \tilde l r) + \frac{2}{\gamma |l^*|}(\tilde k^T \dot k + \tilde l \dot l) = -e^T Q e \le 0,

because the laws make the last two terms cancel. So ee, kk and ll are bounded, and ee is square integrable. Since xmx_m is bounded, x=e+xmx = e + x_m and e˙\dot e are bounded, and Barbalat's lemma gives e(t)→0e(t) \to 0. If in addition the regressor (xm,r)(x_m, r) is persistently exciting, the gain errors go to zero exponentially. The full proof is in proofs/correctness.md; the tests check that VV never increases and that V(0)−V(T)V(0) - V(T) equals the integral of eTQee^T Q e.

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 x˙=Ax+bu\dot x = A x + b u, the model is x˙m=Amxm+bmr\dot x_m = A_m x_m + b_m r with AmA_m Hurwitz, and rr is bounded and piecewise continuous. There are k∗k^*, l∗≠0l^* \ne 0 with A+bk∗T=AmA + b k^{*T} = A_m and bl∗=bmb l^* = b_m. The error is e=x−xme = x - x_m, k~=k−k∗\tilde k = k - k^*, l~=l−l∗\tilde l = l - l^*, Q=QT≻0Q = Q^T \succ 0, and PP solves AmTP+PAm=−QA_m^T P + P A_m = -Q. The laws are k˙=−γ sgn(l∗) x bmTPe\dot k = -\gamma\,\mathrm{sgn}(l^*)\,x\,b_m^T P e and l˙=−γ sgn(l∗) r bmTPe\dot l = -\gamma\,\mathrm{sgn}(l^*)\,r\,b_m^T P e with γ>0\gamma > 0.

Claim 0 (P exists). Because AmA_m is Hurwitz, P=∫0∞eAmTtQeAmt dtP = \int_0^\infty e^{A_m^T t} Q e^{A_m t}\,dt 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 I⊗AmT+AmT⊗II \otimes A_m^T + A_m^T \otimes I, whose eigenvalues are the sums λi+λj\lambda_i + \lambda_j of eigenvalues of AmA_m. They all have negative real part, so the matrix is invertible and line L1 returns this PP.

Claim 1 (error equation). With u=kTx+lru = k^T x + l r,

e˙=Ax+b(kTx+lr)−Amxm−bmr=(A+bk∗T)x+bk~Tx+bl∗r+bl~r−Amxm−bmr.\dot e = A x + b(k^T x + l r) - A_m x_m - b_m r = (A + b k^{*T}) x + b \tilde k^T x + b l^* r + b \tilde l r - A_m x_m - b_m r.

By matching, A+bk∗T=AmA + b k^{*T} = A_m and bl∗=bmb l^* = b_m, so e˙=Ame+b(k~Tx+l~r)\dot e = A_m e + b(\tilde k^T x + \tilde l r). Since b=bm/l∗b = b_m / l^*, this is e˙=Ame+1l∗bm(k~Tx+l~r)\dot e = A_m e + \frac{1}{l^*} b_m (\tilde k^T x + \tilde l r).

Claim 2 (V does not increase). Let V=eTPe+(k~Tk~+l~2)/(γ∣l∗∣)V = e^T P e + (\tilde k^T\tilde k + \tilde l^2)/(\gamma |l^*|). Since k∗k^*, l∗l^* are constant, k~˙=k˙\dot{\tilde k} = \dot k and l~˙=l˙\dot{\tilde l} = \dot l. With s=bmTPes = b_m^T P e, which equals eTPbme^T P b_m because PP is symmetric,

V˙=eT(AmTP+PAm)e+2l∗s (k~Tx+l~r)+2γ∣l∗∣(k~Tk˙+l~l˙).\dot V = e^T(A_m^T P + P A_m) e + \frac{2}{l^*} s\,(\tilde k^T x + \tilde l r) + \frac{2}{\gamma|l^*|}\big(\tilde k^T \dot k + \tilde l \dot l\big).

The laws give k~Tk˙+l~l˙=−γ sgn(l∗) s (k~Tx+l~r)\tilde k^T \dot k + \tilde l \dot l = -\gamma\,\mathrm{sgn}(l^*)\, s\,(\tilde k^T x + \tilde l r), so the last term is −2 sgn(l∗)∣l∗∣s(k~Tx+l~r)=−2l∗s(k~Tx+l~r)-\frac{2\,\mathrm{sgn}(l^*)}{|l^*|} s (\tilde k^T x + \tilde l r) = -\frac{2}{l^*} s (\tilde k^T x + \tilde l r), which cancels the middle term. Hence V˙=−eTQe≤−λmin⁡(Q) ∣e∣2\dot V = -e^T Q e \le -\lambda_{\min}(Q)\,|e|^2.

Claim 3 (bounded signals). By Claim 2, V(t)≤V(0)V(t) \le V(0) for all tt in the interval of existence. So eTPe≤V(0)e^T P e \le V(0) gives ∣e∣2≤V(0)/λmin⁡(P)|e|^2 \le V(0)/\lambda_{\min}(P), and ∣k~∣2+l~2≤γ∣l∗∣V(0)|\tilde k|^2 + \tilde l^2 \le \gamma |l^*| V(0). The model state xmx_m is bounded because AmA_m is Hurwitz and rr is bounded. So x=e+xmx = e + x_m, kk and ll are bounded, and then uu 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 t≥0t \ge 0 and is bounded.

Claim 4 (the error goes to zero). Integrate V˙=−eTQe\dot V = -e^T Q e from 00 to TT: ∫0TeTQe dt=V(0)−V(T)≤V(0)\int_0^T e^T Q e\,dt = V(0) - V(T) \le V(0). So e∈L2e \in L_2. By Claim 1 and Claim 3, e˙\dot e is bounded, so ee is uniformly continuous, and so is eTQee^T Q e (a product of bounded, uniformly continuous functions). Its integral over [0,∞)[0, \infty) is finite, so by Barbalat's lemma eTQe→0e^T Q e \to 0, and e(t)→0e(t) \to 0 because Q≻0Q \succ 0. □\square

Remark (parameter convergence). The proof above gives no convergence of k~\tilde k and l~\tilde l. If the regressor w=(xm,r)w = (x_m, r) of the model is persistently exciting, that is, ∫tt+T0wwTdτ⪰α0T0I\int_t^{t + T_0} w w^T d\tau \succeq \alpha_0 T_0 I for some α0,T0>0\alpha_0, T_0 > 0 and all tt, then the equilibrium (e,k~,l~)=0(e, \tilde k, \tilde l) = 0 is exponentially attractive (Ioannou and Sun, Chapter 4 and Section 6.2, theorem). Without excitation the gains can stop at any point with k~Tx+l~r≡0\tilde k^T x + \tilde l r \equiv 0 along the limit trajectory. For the scalar example of the page with r=1r = 1, this set is the line k+l=−0.5k + l = -0.5; the tests check both cases.

Numerical check. The tests compute VV along the RK4 solution and check that V(0)−V(T)V(0) - V(T) equals the Simpson integral of eTQee^T Q e within 10−610^{-6}, which is Claim 2 in integral form.

Complexity

In the real-RAM model, the Lyapunov equation in line L1 is a linear system of n2n^2 unknowns. The implementation solves it in Kronecker form by Gaussian elimination, which costs O(n6)O(n^6) operations and O(n4)O(n^4) memory once; a Bartels-Stewart solver would cost O(n3)O(n^3). Each evaluation of the right-hand side costs O(n2)O(n^2) for the plant and the model and O(n)O(n) for the laws, so NN RK4 steps cost O(Nn2)O(N n^2). In a real controller the plant is the physical system, and the work per sample is O(n2)O(n^2) for the model and O(n)O(n) for the laws.

Properties

  • Bounded signals and zero error. Theorem: under matching and the known sign, every solution is bounded and e(t)→0e(t) \to 0 for every bounded piecewise continuous rr and every γ>0\gamma > 0.
  • No parameter convergence without excitation. Theorem: the gains converge to (k∗,l∗)(k^*, l^*) 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. VV bounds the tracking error by eTPe≤V(0)e^T P e \le V(0), but V(0)V(0) grows with the initial gain error divided by γ\gamma, so the bound says little about the size of the transient for small γ\gamma, and a large γ\gamma gives oscillatory control signals.

Variants and improvements

  • Robust modifications. Sigma modification, parameter projection, the ee-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 xx; 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 l∗l^*. The laws then push the gains away from k∗k^*, and the loop can go unstable.
  • No matching. If A+bkT=AmA + b k^T = A_m 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 kk grow slowly without bound, until the loop goes unstable.
  • High adaptation gain. The proof holds for every γ>0\gamma > 0, but a large γ\gamma gives a stiff system and high frequency control signals that excite unmodeled dynamics.
  • Error sign. This page uses e=x−xme = x - x_m. 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.

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()
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

  1. 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
  2. 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)
  3. 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.

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