Algorithm Search⌘K

Algorithmcore

MIT rule

Also called gradient adaptation rule.

Adjusts a controller parameter along the negative gradient of the squared model following error, the first model reference adaptation law.

Time
O(N (n^2 + d)) worst
Space
O(n + d) extra
Where
N = the number of integration steps; d = the number of adapted parameters; n = the order of the plant and of the model
Properties
deterministicnot exactonlineiterative
Origin
H. Philip Whitaker, Joseph Yamron, Allen Kezer, 1958

The MIT rule is the first adaptation law of model reference adaptive control: it changes each adjustable controller parameter θ\theta at a rate proportional to −e ∂e/∂θ-e\,\partial e/\partial\theta, where e=y−yme = y - y_m is the error between the plant output and the output of a reference model. It is gradient descent in continuous time on the instantaneous cost e2/2e^2/2, with the gradient computed from approximate sensitivity signals. The rule is simple and often works for small adaptation gains, but it has no stability guarantee: for a large gain or a large command signal the parameters can oscillate with growing amplitude (Parks 1966). The Lyapunov design on the MRAC page replaced it for this reason.

In plain words

You have a controller with a knob, and a model that shows how the controlled system should respond. You run the real system and the model side by side and watch the difference between their outputs. The rule turns the knob a little in the direction that makes the squared difference smaller. To know that direction, it needs to know how the output would change if the knob moved; it estimates this with a filter driven by the signals it can measure. The speed of the turning is set by a gain. A small gain gives slow, smooth learning. A large gain, or a large command signal, makes the knob overshoot, and the knob and the output can then swing with larger and larger amplitude. Nothing in the rule itself prevents this.

The problem

The plant has a known structure and unknown constant parameters. A controller with adjustable parameters θ∈Rd\theta \in \mathbb{R}^d acts on the plant. A reference model, a BIBO stable transfer function Gm(s)G_m(s), gives the wanted response ym=Gmucy_m = G_m u_c to the command signal uc(t)u_c(t). The aim is to find θ\theta so that e(t)=y(t)−ym(t)e(t) = y(t) - y_m(t) goes to zero. For each fixed θ\theta the closed loop gives an output y(t,θ)y(t, \theta), and the cost is J(θ)=e2/2J(\theta) = e^2/2.

Two standard cases are used on this page.

  • Feedforward gain. The plant is k G(s)k\,G(s) with GG known and BIBO stable and the gain k>0k > 0 unknown. The model is k0G(s)k_0 G(s). The controller is u=θucu = \theta u_c, and the ideal value is θ∗=k0/k\theta^* = k_0/k.
  • First order plant. The plant is y˙=−ay+bu\dot y = -a y + b u with b>0b > 0, the model is y˙m=−amym+bmuc\dot y_m = -a_m y_m + b_m u_c with am>0a_m > 0, and the controller is u=θ1uc−θ2yu = \theta_1 u_c - \theta_2 y. The closed loop is y˙=−(a+bθ2)y+bθ1uc\dot y = -(a + b\theta_2) y + b\theta_1 u_c, so the ideal values are θ1∗=bm/b\theta_1^* = b_m/b and θ2∗=(am−a)/b\theta_2^* = (a_m - a)/b.

The algorithm

For a slowly changing θ\theta, the gradient of JJ is e ∂e/∂θ=e ∂y/∂θe\,\partial e/\partial\theta = e\,\partial y/\partial\theta. The MIT rule sets

θ˙=−γ ψ e,\dot\theta = -\gamma\, \psi\, e,

where γ>0\gamma > 0 is the adaptation gain and ψ\psi is a signal that approximates the sensitivity derivative ∂e/∂θ\partial e/\partial\theta. Known positive constants in ψ\psi are absorbed into γ\gamma; this needs the sign of the plant gain.

  • Feedforward gain: y=kG(p) θucy = k G(p)\,\theta u_c for a constant θ\theta, where p=d/dtp = d/dt. So ∂e/∂θ=kGuc=(k/k0) ym\partial e/\partial\theta = k G u_c = (k/k_0)\, y_m, and with k/k0>0k/k_0 > 0 absorbed, θ˙=−γ yme\dot\theta = -\gamma\, y_m e. Here the sensitivity is exact and needs no filter.
  • First order plant: the exact sensitivities are ∂e/∂θ1=bp+a+bθ2uc\partial e/\partial\theta_1 = \frac{b}{p + a + b\theta_2} u_c and ∂e/∂θ2=−bp+a+bθ2y\partial e/\partial\theta_2 = -\frac{b}{p + a + b\theta_2} y. They contain the unknown plant. Near the ideal parameters p+a+bθ2=p+amp + a + b\theta_2 = p + a_m, so the rule uses the model pole: θ˙1=−γ(amp+amuc)e\dot\theta_1 = -\gamma \big(\frac{a_m}{p + a_m} u_c\big) e and θ˙2=γ(amp+amy)e\dot\theta_2 = \gamma \big(\frac{a_m}{p + a_m} y\big) e, with b/am>0b/a_m > 0 absorbed into γ\gamma.

The plant, the model, the sensitivity filters and θ\theta form one system of differential equations. The implementation integrates it with the classical fourth order Runge-Kutta method and a fixed step dtdt.

  1. MIT-RULE(γ, θ₀, dt, N) ▷ γ > 0, N steps of length dt
  2. 1θ ← θ₀; set the plant, model and filter states
  3. 2for i ← 0 to N - 1 do
  4. 3r ← u_c(t) ▷ the command signal at t = i dt
  5. 4e ← y - y_m ▷ model following error
  6. 5ψ ← sensitivity filter outputs ▷ ψ ≈ ∂e/∂θ
  7. 6u ← controller output with the current θ
  8. 7θ' ← -γ ψ e ▷ negative gradient of e²/2
  9. 8advance plant, model, filters and θ by one RK4 step of length dt
  10. 9return θ

Lines L3 to L7 are the right-hand side of the differential equation; RK4 evaluates them four times per step in line L8.

Example

Feedforward gain. Take G(s)=1/(s2+s+1)G(s) = 1/(s^2 + s + 1), the plant gain k=1k = 1, the model gain k0=2k_0 = 2 and a constant command uc=u0=1u_c = u_0 = 1. Start with θ(0)=1\theta(0) = 1, the plant at rest at y=θ(0)u0=1y = \theta(0) u_0 = 1 and the model at rest at ym=2y_m = 2. The ideal value is θ∗=2\theta^* = 2. With RK4 and dt=0.02dt = 0.02 s:

γ\gamma θ(10)\theta(10) θ(20)\theta(20) θ(30)\theta(30) θ(60)\theta(60)
0.25 2.0486 1.9996 1.9986 2.0000
1 -3.35 -37.25 -209.3 about 2×1042 \times 10^4

The section Correctness shows why. With ymy_m at rest, θ\theta obeys exactly the linear equation θ...+θ¨+θ˙+2γu02θ=4γu02\dddot\theta + \ddot\theta + \dot\theta + 2\gamma u_0^2 \theta = 4\gamma u_0^2. For γ=0.25\gamma = 0.25 the characteristic polynomial is s3+s2+s+0.5s^3 + s^2 + s + 0.5, with roots −0.6478-0.6478 and −0.1761±0.8607j-0.1761 \pm 0.8607j, so θ→2\theta \to 2. For γ=1\gamma = 1 it is s3+s2+s+2s^3 + s^2 + s + 2, with roots −1.3532-1.3532 and 0.1766±1.2028j0.1766 \pm 1.2028j, so θ\theta oscillates with growing amplitude at about 1.21.2 rad/s. By the Routh-Hurwitz criterion the limit is γu02<1/2\gamma u_0^2 < 1/2. The gain γ=0.25\gamma = 0.25 with the larger command u0=2u_0 = 2 gives γu02=1\gamma u_0^2 = 1, and the loop is again unstable: the amplitude of the command matters as much as the gain.

First order plant. Take a=1a = 1, b=0.5b = 0.5 and am=bm=2a_m = b_m = 2, so θ1∗=4\theta_1^* = 4 and θ2∗=2\theta_2^* = 2. The command is a square wave of amplitude 1 and period 20 s, and θ(0)=(0,0)\theta(0) = (0, 0). With dt=0.01dt = 0.01 s, at t=100t = 100 s:

γ\gamma θ1(100)\theta_1(100) θ2(100)\theta_2(100)
1 3.248 1.248
2 3.680 1.680
5 3.974 1.974

The error ee is below 0.03 at the end of each run, but the parameters are still far from their ideal values for γ=1\gamma = 1. In every run θ1−θ2≈2\theta_1 - \theta_2 \approx 2 after the first seconds. While the command is constant, the output only fixes the static gain bθ1/(a+bθ2)=bm/am=1b\theta_1/(a + b\theta_2) = b_m/a_m = 1, which is the line θ1−θ2=2\theta_1 - \theta_2 = 2. Only the short transients after each switch of the square wave carry information along the line. This is a weak form of persistent excitation.

Correctness

The MIT rule is a heuristic, and the proof in proofs/correctness.md shows what it does and does not give. It proves three facts. First, with θ\theta frozen, −γ ψ e-\gamma\,\psi\,e is exactly −γ-\gamma times the gradient of e2/2e^2/2 when ψ\psi is the exact sensitivity, so the rule is gradient descent on the instantaneous squared error. Second, the ideal parameter is an equilibrium of the adaptive loop: there e→0e \to 0 and θ˙→0\dot\theta \to 0. Third, for the feedforward gain with G(s)=1/(s2+a1s+a2)G(s) = 1/(s^2 + a_1 s + a_2) and a constant command, the parameter obeys a linear third order equation, and the adaptive loop converges if and only if γkk0u02<a1a22\gamma k k_0 u_0^2 < a_1 a_2^2 (a theorem, proved there with Routh-Hurwitz). The last fact shows that no gain γ>0\gamma > 0 is safe for all command amplitudes. There is no general convergence theorem for the MIT rule; the design with a stability proof is the Lyapunov rule of MRAC (Parks 1966).

Proof: The MIT rule is a gradient step on the squared error, and its stability depends on the gain and the command amplitudefull

Notation is that of the page. The error is e=y−yme = y - y_m, the adaptation gain is γ>0\gamma > 0, and p=d/dtp = d/dt.

Claim 1 (gradient). Fix θ\theta and let y(t,θ)y(t, \theta) be the plant output for this constant θ\theta. Then ∂(e2/2)/∂θ=e ∂y/∂θ\partial (e^2/2)/\partial\theta = e\,\partial y/\partial\theta, because ymy_m does not depend on θ\theta. So the law θ˙=−γ (∂e/∂θ) e\dot\theta = -\gamma\,(\partial e/\partial\theta)\, e (line L7 with the exact sensitivity in line L5) is θ˙=−γ∇θ(e2/2)\dot\theta = -\gamma \nabla_\theta (e^2/2), the continuous-time gradient flow of the instantaneous cost. If ψ=c ∂e/∂θ\psi = c\,\partial e/\partial\theta with a known constant c>0c > 0, then −γψe=−(γc)∇θ(e2/2)-\gamma\psi e = -(\gamma c)\nabla_\theta(e^2/2), which is the same flow with the gain γc\gamma c.

For the feedforward gain, a constant θ\theta gives y=kG(p)(θuc)=θ kGucy = k G(p)(\theta u_c) = \theta\, k G u_c, so ∂e/∂θ=kGuc=(k/k0)ym\partial e/\partial\theta = k G u_c = (k/k_0) y_m with c=k/k0>0c = k/k_0 > 0. The law θ˙=−γyme\dot\theta = -\gamma y_m e is therefore the gradient flow with gain γk/k0\gamma k / k_0. For the first order plant, a constant θ\theta gives y=bθ1p+a+bθ2ucy = \frac{b\theta_1}{p + a + b\theta_2} u_c. Differentiation gives ∂y/∂θ1=bp+a+bθ2uc\partial y/\partial\theta_1 = \frac{b}{p + a + b\theta_2} u_c and ∂y/∂θ2=−b2θ1(p+a+bθ2)2uc=−bp+a+bθ2y\partial y/\partial\theta_2 = -\frac{b^2\theta_1}{(p + a + b\theta_2)^2} u_c = -\frac{b}{p + a + b\theta_2} y. At θ=θ∗\theta = \theta^* the denominator is p+amp + a_m, and bp+am=bam⋅amp+am\frac{b}{p + a_m} = \frac{b}{a_m}\cdot\frac{a_m}{p + a_m} with b/am>0b/a_m > 0. So the filters of the page are the exact sensitivities at θ∗\theta^*, up to the positive constant b/amb/a_m.

The claim needs θ\theta constant. When θ\theta changes, G(p)(θuc)≠θ G(p)ucG(p)(\theta u_c) \ne \theta\,G(p)u_c, and the flow is only an approximation of the gradient flow. That is why Claim 1 gives no stability.

Claim 2 (equilibrium). At θ=θ∗\theta = \theta^* the closed loop transfer function from ucu_c to yy equals that of the model: kGθ∗=k0Gk G \theta^* = k_0 G for the feedforward gain, and bθ1∗p+a+bθ2∗=bmp+am\frac{b\theta_1^*}{p + a + b\theta_2^*} = \frac{b_m}{p + a_m} for the first order plant. So ee is the difference of the free responses of two systems with the same poles in the open left half plane, and e(t)→0e(t) \to 0 exponentially. Then ψe→0\psi e \to 0 for every bounded command, because ψ\psi is the output of a BIBO stable filter of bounded signals. So θ∗\theta^* with e=0e = 0 is an equilibrium of the adaptive loop when the plant and the model start from matching states.

Claim 3 (exact stability limit). Let G(s)=1/(s2+a1s+a2)G(s) = 1/(s^2 + a_1 s + a_2) with a1,a2>0a_1, a_2 > 0, let k,k0>0k, k_0 > 0, let the command be the constant u0≠0u_0 \ne 0, and let the model be at rest, ym(t)=ym0=k0u0/a2y_m(t) = y_{m0} = k_0 u_0 / a_2 for all t≥0t \ge 0. Then θ(t)→k0/k\theta(t) \to k_0/k for all initial states if and only if γkk0u02<a1a22\gamma k k_0 u_0^2 < a_1 a_2^2.

Proof. The plant equation is y¨+a1y˙+a2y=ku0 θ(t)\ddot y + a_1 \dot y + a_2 y = k u_0\, \theta(t), and the law is θ˙=−γym0(y−ym0)\dot\theta = -\gamma y_{m0}(y - y_{m0}). Differentiate the law twice: θ¨=−γym0y˙\ddot\theta = -\gamma y_{m0} \dot y and θ...=−γym0y¨\dddot\theta = -\gamma y_{m0} \ddot y. Then

θ...+a1θ¨+a2θ˙=−γym0(y¨+a1y˙+a2y−a2ym0)=−γym0(ku0θ−a2ym0).\dddot\theta + a_1\ddot\theta + a_2\dot\theta = -\gamma y_{m0}(\ddot y + a_1 \dot y + a_2 y - a_2 y_{m0}) = -\gamma y_{m0}(k u_0\theta - a_2 y_{m0}).

With ym0=k0u0/a2y_{m0} = k_0 u_0/a_2 this is

θ...+a1θ¨+a2θ˙+γkk0u02a2 θ=γk02u02a2.\dddot\theta + a_1\ddot\theta + a_2\dot\theta + \frac{\gamma k k_0 u_0^2}{a_2}\,\theta = \frac{\gamma k_0^2 u_0^2}{a_2}.

This is a linear equation with constant coefficients. Its constant solution is θ=k0/k\theta = k_0/k. The map from the state (y,y˙,θ)(y, \dot y, \theta) to (θ,θ˙,θ¨)(\theta, \dot\theta, \ddot\theta) is linear and invertible (its determinant is γ2ym02≠0\gamma^2 y_{m0}^2 \ne 0), so every solution of the adaptive loop goes to the constant solution if and only if the polynomial s3+a1s2+a2s+cs^3 + a_1 s^2 + a_2 s + c with c=γkk0u02/a2>0c = \gamma k k_0 u_0^2 / a_2 > 0 is Hurwitz. By the Routh-Hurwitz criterion for a cubic with positive coefficients, this holds if and only if a1a2>ca_1 a_2 > c, that is, γkk0u02<a1a22\gamma k k_0 u_0^2 < a_1 a_2^2. If a1a2<ca_1 a_2 < c, the first column of the Routh array has two sign changes, so two roots are in the open right half plane and θ\theta grows without bound for almost every initial state. □\square

For the example of the page, a1=a2=k=1a_1 = a_2 = k = 1 and k0=2k_0 = 2, so the condition is γu02<1/2\gamma u_0^2 < 1/2. The test file checks the formula against the Routh verdict on random data, and checks the simulated θ\theta against a separate integration of the third order equation.

Consequence. For every γ>0\gamma > 0 there is a command amplitude u0u_0 with γkk0u02>a1a22\gamma k k_0 u_0^2 > a_1 a_2^2, so no fixed gain makes the adaptive loop of the MIT rule converge for all constant commands. This is the reason for the Lyapunov design of model reference adaptive control.

Complexity

The cost is that of a fixed step simulation, in the real-RAM model. Each RK4 step evaluates the right-hand side four times. One evaluation costs O(n2)O(n^2) for the plant and the model in state space with dense matrices of order nn, and O(d)O(d) for dd parameters with first order sensitivity filters. So NN steps cost O(N(n2+d))O(N(n^2 + d)) operations, and the memory is O(n+d)O(n + d) besides the output samples. In a real controller the rule runs once per sampling period, so the cost per sample is O(n2+d)O(n^2 + d).

Properties

  • No stability guarantee. Theorem in the example class above: the loop is asymptotically stable for γkk0u02<a1a22\gamma k k_0 u_0^2 < a_1 a_2^2 and unstable above. In general the rule can make the closed loop unstable for large γ\gamma or a large command (Parks 1966; Åström and Wittenmark, Section 5.3).
  • Scale dependence. The update is proportional to ψe\psi e, which is quadratic in the signal level. A normalized version θ˙=−γ ψe/(α+ψTψ)\dot\theta = -\gamma\,\psi e/(\alpha + \psi^T\psi) with α>0\alpha > 0 removes this dependence (Åström and Wittenmark, Chapter 5).
  • Sign of the gain. The rule needs the sign of the plant gain, because it absorbs k/k0k/k_0 or b/amb/a_m into γ\gamma. With the wrong sign it pushes θ\theta away from θ∗\theta^*.
  • Parameter convergence. e→0e \to 0 does not imply θ→θ∗\theta \to \theta^*. The parameters converge only if the command excites the loop enough; the first order example shows the drift along a line.
  • Approximate sensitivities. The sensitivity filters use the model in place of the unknown plant. Far from θ∗\theta^* they can have the wrong phase, and then the update is not a descent direction.

Variants and improvements

  • Normalized MIT rule. Divide by α+ψTψ\alpha + \psi^T\psi, as above. This bounds the update for large signals but still gives no proof of stability.
  • Lyapunov redesign. Parks (1966) chose the adaptation law so that a Lyapunov function of the error and the parameter error decreases. For the first order plant this gives θ˙1=−γuce\dot\theta_1 = -\gamma u_c e and θ˙2=γye\dot\theta_2 = \gamma y e, the same form without the sensitivity filters, with bounded signals and e→0e \to 0 for every bounded command. See MRAC.
  • Sign-sign and sign-error versions. Use the signs of ψ\psi and ee, or of ee only. They are cheap to build, and they are also gradient-like heuristics with no general guarantee.
  • Discrete time. The update θk+1=θk−γh ψkek\theta_{k+1} = \theta_k - \gamma h\,\psi_k e_k with sampling period hh is the same rule as the LMS algorithm when ee is linear in θ\theta.
  • Extremum seeking. When the gradient cannot be computed from a model, extremum seeking control estimates it with a dither signal.

When to use it

Use the MIT rule to explain the idea of gradient adaptation, or in a loop where the adaptation is slow compared with the closed loop dynamics and the command amplitude is bounded and known. Then the gain can be chosen by the averaging analysis of Åström and Wittenmark (Section 5.3), as a rule of thumb. For a design that must keep all signals bounded for all bounded commands, use the Lyapunov based MRAC or a self-tuning regulator.

Pitfalls

  • Large gain or large command. The stability limit depends on γu02\gamma u_0^2, not on γ\gamma alone. A gain that is tuned for small commands can be unstable for large ones.
  • Wrong sign of the gain. The rule then moves θ\theta the wrong way.
  • Exact sensitivities assumed. The derivation treats θ\theta as a constant. When θ\theta changes fast, ψ\psi is not the gradient, and the rule is no longer a descent method.
  • Unmodeled dynamics. Even the Lyapunov version can drift and lose stability under unmodeled dynamics and disturbances; see Rohrs counterexample.
  • Error definition. This page uses e=y−yme = y - y_m. With e=ym−ye = y_m - y every sign in the update changes.

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.

ctlsim.pyI0RawGitHub
# 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()
mit_rule.py 129 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mit-rule/. The authors are listed in prov/B6VAKD.jsonl.

"""The MIT rule for model reference adaptation.

The model following error is e = y - y_m. The MIT rule moves each
controller parameter along the negative gradient of e^2 / 2:

    theta' = -gamma psi e,   psi an approximation of de/dtheta.

Two classic cases are here.

1. Adaptation of a feedforward gain. The plant is k G(s) with k > 0
   unknown, the model is k0 G(s), and u = theta u_c. Then
   de/dtheta = k G u_c = (k / k0) y_m, and the constant k / k0 > 0 goes
   into gamma, so theta' = -gamma y_m e.

2. A first order plant y' = -a y + b u with b > 0, the model
   y_m' = -a_m y_m + b_m u_c and u = theta_1 u_c - theta_2 y. The exact
   sensitivities need the unknown plant. With the plant pole replaced by
   the model pole, psi_1 = a_m / (p + a_m) u_c and
   psi_2 = -a_m / (p + a_m) y, so theta_1' = -gamma psi_1 e and
   theta_2' = +gamma (a_m / (p + a_m) y) e.

Every simulation uses the classical RK4 method with a fixed step dt from
ctlsim. The time t1 must be an integer multiple of dt.
"""

from ctlsim import rk4_step

__all__ = [
    "mit_feedforward_gain", "mit_first_order", "feedforward_theta_poly",
    "cubic_is_hurwitz",
]


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 mit_feedforward_gain(A, b, c, k, k0, gamma, uc, t1, dt, theta0=0.0, x0=None, xm0=None, every=1):
    """Simulate the MIT rule for the feedforward gain of the plant k G(s).

    G(s) = c (sI - A)^(-1) b is given in state space (A a list of rows,
    b and c flat lists). uc(t) is the command signal. Returns the lists
    (ts, thetas, errors), sampled every `every` steps.
    """
    n = len(A)
    x0 = [0.0] * n if x0 is None else list(x0)
    xm0 = [0.0] * n if xm0 is None else list(xm0)
    s = x0 + xm0 + [float(theta0)]  # @line L1

    def f(t, z, _u):
        x, xm, th = z[:n], z[n:2 * n], z[2 * n]
        r = uc(t)  # @line L3
        y = sum(ci * xi for ci, xi in zip(c, x))
        ym = sum(ci * xi for ci, xi in zip(c, xm))
        e = y - ym  # @line L4
        psi = ym  # @line L5
        u = th * r  # @line L6
        dx = [sum(a * xi for a, xi in zip(row, x)) + bi * k * u for row, bi in zip(A, b)]
        dxm = [sum(a * xi for a, xi in zip(row, xm)) + bi * k0 * r for row, bi in zip(A, b)]
        return dx + dxm + [-gamma * psi * e]  # @line L7

    N = _steps(t1, dt)
    ts, thetas, errors = [0.0], [s[2 * n]], [_err(s, c, n)]
    for i in range(N):  # @line L2
        s = rk4_step(f, i * dt, s, None, dt)  # @line L8
        if (i + 1) % every == 0:
            ts.append((i + 1) * dt)
            thetas.append(s[2 * n])
            errors.append(_err(s, c, n))
    return ts, thetas, errors  # @line L9


def _err(s, c, n):
    y = sum(ci * xi for ci, xi in zip(c, s[:n]))
    ym = sum(ci * xi for ci, xi in zip(c, s[n:2 * n]))
    return y - ym


def mit_first_order(a, b, am, bm, gamma, uc, t1, dt, theta0=(0.0, 0.0), every=1):
    """Simulate the MIT rule with two parameters on y' = -a y + b u.

    The controller is u = theta_1 u_c - theta_2 y. The ideal values are
    theta_1 = b_m / b and theta_2 = (a_m - a) / b. Returns
    (ts, theta1s, theta2s, errors), sampled every `every` steps.
    """
    s = [0.0, 0.0, 0.0, 0.0, float(theta0[0]), float(theta0[1])]  # @line L1
    # state: y, y_m, filtered u_c, filtered y, theta_1, theta_2

    def f(t, z, _u):
        y, ym, p1, p2, th1, th2 = z
        r = uc(t)  # @line L3
        e = y - ym  # @line L4
        psi1, psi2 = p1, -p2  # @line L5
        u = th1 * r - th2 * y  # @line L6
        dth1 = -gamma * psi1 * e  # @line L7
        dth2 = -gamma * psi2 * e
        return [-a * y + b * u, -am * ym + bm * r, -am * p1 + am * r, -am * p2 + am * y, dth1, dth2]

    N = _steps(t1, dt)
    ts, th1s, th2s, errs = [0.0], [s[4]], [s[5]], [0.0]
    for i in range(N):  # @line L2
        s = rk4_step(f, i * dt, s, None, dt)  # @line L8
        if (i + 1) % every == 0:
            ts.append((i + 1) * dt)
            th1s.append(s[4])
            th2s.append(s[5])
            errs.append(s[0] - s[1])
    return ts, th1s, th2s, errs  # @line L9


def feedforward_theta_poly(a1, a2, k, k0, gamma, u0):
    """Characteristic polynomial of theta for G(s) = 1 / (s^2 + a1 s + a2).

    With a constant command u_c = u0 and the model output at rest at
    y_m = k0 u0 / a2, the MIT rule gives the linear equation
    theta''' + a1 theta'' + a2 theta' + (gamma k k0 u0^2 / a2) theta = const.
    """
    return [1, a1, a2, gamma * k * k0 * u0 * u0 / a2]


def cubic_is_hurwitz(p):
    """Routh test for s^3 + p1 s^2 + p2 s + p3 (p[0] > 0)."""
    p0, p1, p2, p3 = p
    return p0 > 0 and p1 > 0 and p3 > 0 and p1 * p2 > p0 * p3
test_mit_rule.py 94 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mit-rule/. The authors are listed in prov/B6VAKD.jsonl.

"""Tests for the MIT rule. RK4 with a fixed step; tolerances are stated."""

import random
import unittest

from ctlsim import rk4_step
from mit_rule import (
    cubic_is_hurwitz, feedforward_theta_poly, mit_feedforward_gain, mit_first_order,
)

# G(s) = 1 / (s^2 + s + 1), plant gain k = 1, model gain k0 = 2.
A = [[0.0, 1.0], [-1.0, -1.0]]
B = [0.0, 1.0]
C = [1.0, 0.0]


def run_ff(gamma, u0, t1, dt=0.02, theta0=1.0):
    # plant and model start at rest for their gains, so y_m is constant
    return mit_feedforward_gain(
        A, B, C, 1.0, 2.0, gamma, lambda t: u0, t1, dt, theta0=theta0,
        x0=[theta0 * u0, 0.0], xm0=[2.0 * u0, 0.0], every=50)


class TestFeedforward(unittest.TestCase):
    def test_converges_for_small_gain(self):
        # gamma u0^2 = 0.25 < 1/2: theta -> k0 / k = 2
        _, th, err = run_ff(0.25, 1.0, 60.0)
        self.assertLess(abs(th[-1] - 2.0), 1e-3)
        self.assertLess(abs(err[-1]), 1e-3)

    def test_diverges_for_large_gain_or_amplitude(self):
        # gamma u0^2 = 1 > 1/2 in both runs: the same gain with a larger
        # command amplitude is unstable too
        for gamma, u0 in ((1.0, 1.0), (0.25, 2.0)):
            _, th, _ = run_ff(gamma, u0, 40.0)
            self.assertGreater(max(abs(v - 2.0) for v in th), 50.0)

    def test_routh_verdict_matches_simulation(self):
        for gamma, stable in ((0.3, True), (0.8, False)):
            p = feedforward_theta_poly(1.0, 1.0, 1.0, 2.0, gamma, 1.0)
            self.assertEqual(cubic_is_hurwitz(p), stable)
            _, th, _ = run_ff(gamma, 1.0, 80.0)
            early = max(abs(v - 2.0) for v in th[:10])
            late = max(abs(v - 2.0) for v in th[-10:])
            self.assertEqual(late < early, stable)

    def test_against_linear_theta_equation(self):
        # reference method: integrate the third order equation of theta
        gamma, u0, theta0 = 0.2, 1.0, 1.0
        p = feedforward_theta_poly(1.0, 1.0, 1.0, 2.0, gamma, u0)
        ym0, e0 = 2.0 * u0, (theta0 - 2.0) * u0
        z = [theta0, -gamma * ym0 * e0, 0.0]

        def g(t, w, _u):
            return [w[1], w[2], -p[1] * w[2] - p[2] * w[1] - p[3] * (w[0] - 2.0)]

        dt = 0.02
        for i in range(1000):
            z = rk4_step(g, i * dt, z, None, dt)
        _, th, _ = run_ff(gamma, u0, 20.0, dt=dt, theta0=theta0)
        self.assertLess(abs(th[-1] - z[0]), 1e-6)

    def test_routh_threshold_formula(self):
        rng = random.Random(7)
        for _ in range(50):
            a1, a2 = rng.uniform(0.2, 3), rng.uniform(0.2, 3)
            k, k0, u0 = rng.uniform(0.2, 3), rng.uniform(0.2, 3), rng.uniform(0.2, 3)
            limit = a1 * a2 * a2 / (k * k0 * u0 * u0)
            for gamma in (0.9 * limit, 1.1 * limit):
                p = feedforward_theta_poly(a1, a2, k, k0, gamma, u0)
                self.assertEqual(cubic_is_hurwitz(p), gamma < limit)


class TestFirstOrder(unittest.TestCase):
    def test_two_parameters_converge(self):
        # y' = -y + 0.5 u, model 2 / (s + 2), square wave command of period 20 s
        def sq(t):
            return 1.0 if (t % 20.0) < 10.0 else -1.0
        # gamma = 5: the ideal values are theta_1 = 4 and theta_2 = 2
        _, th1, th2, err = mit_first_order(1.0, 0.5, 2.0, 2.0, 5.0, sq, 100.0, 0.01, every=100)
        self.assertLess(abs(th1[-1] - 4.0), 0.05)
        self.assertLess(abs(th2[-1] - 2.0), 0.05)
        self.assertLess(max(abs(v) for v in err[-10:]), 0.01)

    def test_dt_must_divide_t1(self):
        with self.assertRaises(AssertionError):
            mit_first_order(1.0, 0.5, 2.0, 2.0, 1.0, lambda t: 1.0, 1.0, 0.3)


if __name__ == "__main__":
    unittest.main()

History

Whitaker, Yamron and Kezer (1958) at the MIT Instrumentation Laboratory proposed the model reference adaptive system for the flight control of aircraft, with the gains adjusted along the gradient of the squared error. The rule had no stability proof. Parks (1966) showed that it can be unstable and redesigned the law with Lyapunov theory, which gave model reference adaptive systems with bounded signals and an error that goes to zero for every bounded command. Ioannou and Sun (Section 1.3) give a short history of this period.

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: Section 5.2 (the MIT rule, the feedforward gain and first order examples) and Section 5.3 (the choice of the adaptation gain and the instability for large gains)
  2. P. C. Parks, Liapunov redesign of model reference adaptive control systems, IEEE Transactions on Automatic Control 11(3), 1966, pages 362 to 367 (the instability of the MIT rule and the Lyapunov redesign of the adaptive law)
  3. H. P. Whitaker, J. Yamron and A. Kezer, Design of model-reference adaptive control systems for aircraft, Report R-164, Instrumentation Laboratory, MIT, 1958, the whole report (the model reference scheme and the gradient adjustment of the gains)
  4. Petros A. Ioannou and Jing Sun, Robust Adaptive Control, Prentice Hall 1996 (Dover reprint 2012), Section 1.3, A brief history (the MIT rule and the instability results of the 1960s)

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