Algorithm Search⌘K

Algorithmadvanced

Iterative learning control

Also called ILC.

Improves the input of a system that repeats a task, by learning from the error of the last trial so the error falls from trial to trial.

Time
O(J (N n^2 + N^2)) worst
Space
O(N^2) extra
Where
J = the number of trials; N = the number of samples per trial; n = the order of the plant
Properties
deterministicexactofflineiterative
Origin
Suguru Arimoto, Sadao Kawamura, Fumio Miyazaki, 1984

Iterative learning control (ILC) is a method for a system that does the same task again and again from the same initial state: after each trial it corrects the whole input signal with the error signal of that trial, so that the error falls from trial to trial. The update is uj+1=Q(uj+Lej)u_{j+1} = Q(u_j + L e_j), where jj is the trial number, ej=yd−yje_j = y_d - y_j is the tracking error over the trial, and LL and QQ are filters or matrices. Because the correction is computed between trials, LL can use the error at later times of the trial, which a causal feedback controller cannot do. ILC learns a feedforward input for one fixed reference; a feedback loop is usually still present to reject disturbances that do not repeat.

In plain words

Think of a robot arm that draws the same curve every few seconds. On the first try, the arm misses the curve a little. After the try, you look at the whole record of the miss: at each moment, how far off and in which direction. For the next try, you change the push at each moment a little, in the direction that removes the miss. You can use what happened just after each moment, because the try is already over. After many tries the arm follows the curve almost exactly. The method only works if every try starts the same way and the task is the same. If the push is changed too much at once, the miss can grow very large before it shrinks.

The problem

The plant is x(k+1)=Ax(k)+Bu(k)x(k+1) = Ax(k) + Bu(k), y(k)=Cx(k)y(k) = Cx(k), with one input, one output and the first Markov parameter CB≠0CB \ne 0 (relative degree one). Each trial starts at the same state x(0)=x0x(0) = x_0 and has NN samples with the sampling period hh. The input u(0),…,u(N−1)u(0), \dots, u(N-1) gives the outputs y(1),…,y(N)y(1), \dots, y(N). With the vectors uj,yj∈RNu_j, y_j \in \mathbb{R}^N of trial jj, the lifted model is

yj=Puj+d,P=(CB0⋯0CABCB⋯0⋮⋱CAN−1B⋯CABCB),y_j = P u_j + d,\qquad P = \begin{pmatrix} CB & 0 & \cdots & 0\\ CAB & CB & \cdots & 0\\ \vdots & & \ddots & \\ CA^{N-1}B & \cdots & CAB & CB\end{pmatrix},

where dd is the response to x0x_0. PP is lower triangular Toeplitz. Given a reference yd∈RNy_d \in \mathbb{R}^N, find inputs uju_j with ej=yd−yj→0e_j = y_d - y_j \to 0 as j→∞j \to \infty, without knowing PP exactly.

The algorithm

Choose the learning matrix LL and the filter QQ (often Q=IQ = I). Common choices of LL:

  • P-type (Arimoto): L=γIL = \gamma I, that is uj+1(k)=uj(k)+γej(k+1)u_{j+1}(k) = u_j(k) + \gamma e_j(k + 1) in terms of the unlifted signals.
  • Plant inversion: L=P^−1L = \hat P^{-1} for a model P^\hat P of the plant.
  • Norm-optimal: L=(PTP+wI)−1PTL = (P^TP + wI)^{-1}P^T with a weight w>0w > 0. It minimizes ∥ej+1∥2+w∥uj+1−uj∥2\|e_{j+1}\|^2 + w\|u_{j+1} - u_j\|^2.
  1. ILC(trial, y_d, u₀, L, Q, J) ▷ J updates
  2. 1u ← u₀
  3. 2for j ← 0 to J do
  4. 3y ← run one trial with input u ▷ same initial state each trial
  5. 4e ← y_d - y ▷ the error over the whole trial
  6. 5u ← Q (u + L e) ▷ between trials
  7. 6return u and the errors of all trials

With Q=IQ = I, the error obeys ej+1=(I−PL) eje_{j+1} = (I - PL)\,e_j exactly, because dd and ydy_d are the same in every trial.

Example

Take y(k+1)=a y(k)+u(k)y(k+1) = a\,y(k) + u(k) with y(0)=0y(0) = 0, so Pik=ai−kP_{ik} = a^{i-k} for i≥ki \ge k. The trial has N=30N = 30 samples, the reference is yd(k)=sin⁡(πk/30)y_d(k) = \sin(\pi k/30) for k=1,…,30k = 1, \dots, 30, and u0=0u_0 = 0, so ∥e0∥2=3.873\|e_0\|_2 = 3.873. With the P-type law:

aa γ\gamma ∥I−γP∥2\|I - \gamma P\|_2 max⁡ω∣1−γPˉ(eiω)∣\max_\omega \lvert 1 - \gamma \bar P(e^{\mathrm{i}\omega})\rvert behavior of ∥ej∥2\|e_j\|_2
0.9 1 7.0487 9 grows to 1.1×1061.1 \times 10^6 at trial 14, zero after trial 30 in exact arithmetic
0.9 0.5 3.1213 4 grows to 54.14 at trial 4, then decays; 7.0×10−47.0 \times 10^{-4} at trial 30
0.5 0.5 0.6666 2/3 decreases in every trial; 0.379 after one trial

All three cases converge, because I−γPI - \gamma P is lower triangular with the diagonal 1−γ1 - \gamma, so its spectral radius is ∣1−γ∣<1|1 - \gamma| < 1. Only the last one converges monotonically in the 2-norm. The first case is nilpotent: I−PI - P is strictly lower triangular, so (I−P)30=0(I - P)^{30} = 0 and the error is exactly zero after 30 updates (the tests check this in Fraction arithmetic), but on the way it grows by a factor of about 3×1053 \times 10^5. These are measurements of the stated runs.

The norm-optimal law with a=0.9a = 0.9 removes the transient growth. For w=1w = 1, ∥I−PL∥2=0.7826\|I - PL\|_2 = 0.7826 and ∥ej∥2\|e_j\|_2 is 3.873,0.0948,0.0194,0.00993.873, 0.0948, 0.0194, 0.0099 for j=0j = 0 to 3. For w=0.1w = 0.1, ∥I−PL∥2=0.2647\|I - PL\|_2 = 0.2647 and ∥e1∥2=0.0115\|e_1\|_2 = 0.0115.

Correctness

The proof in proofs/correctness.md shows four facts (theorems). First, with Q=IQ = I and the same initial state, ej+1=(I−PL)eje_{j+1} = (I - PL)e_j, so ej=(I−PL)je0e_j = (I - PL)^je_0. Second, ej→0e_j \to 0 for every e0e_0 if and only if the spectral radius ρ(I−PL)<1\rho(I - PL) < 1; for the P-type law this is ∣1−γCB∣<1|1 - \gamma CB| < 1, a condition that does not depend on AA. Third, if ∥I−PL∥2<1\|I - PL\|_2 < 1, then ∥ej+1∥2≤∥I−PL∥2 ∥ej∥2\|e_{j+1}\|_2 \le \|I - PL\|_2\,\|e_j\|_2, so the decay is monotonic; for L=γIL = \gamma I a sufficient condition is max⁡ω∣1−γPˉ(eiω)∣<1\max_\omega|1 - \gamma \bar P(e^{\mathrm{i}\omega})| < 1, where Pˉ(z)=∑k≥0CAkB z−k=z C(zI−A)−1B\bar P(z) = \sum_{k \ge 0} CA^kB\,z^{-k} = z\,C(zI - A)^{-1}B is the transfer function of the plant advanced by one sample (for AA with all eigenvalues inside the unit circle), because a finite section of a Toeplitz operator has a norm at most the peak of its symbol. Fourth, the norm-optimal law gives I−PL=w(PPT+wI)−1I - PL = w(PP^T + wI)^{-1}, whose 2-norm is w/(σmin⁡2+w)<1w/(\sigma_{\min}^2 + w) < 1, where σmin⁡>0\sigma_{\min} > 0 is the smallest singular value of PP.

Proof: The ILC error obeys a fixed linear recursion over the trials, and its convergence is set by the spectral radius and the norm of I - PLfull

Notation is that of the page. Trial jj starts at x(0)=x0x(0) = x_0, the input uj∈RNu_j \in \mathbb{R}^N holds u(0),…,u(N−1)u(0), \dots, u(N-1), and the output yj∈RNy_j \in \mathbb{R}^N holds y(1),…,y(N)y(1), \dots, y(N).

Claim 1 (lifted model). yj=Puj+dy_j = Pu_j + d, where Pik=CAi−kBP_{ik} = CA^{i-k}B for i≥ki \ge k, Pik=0P_{ik} = 0 for i<ki < k (indices from 0), and di=CAi+1x0d_i = CA^{i+1}x_0.

Proof. By induction on kk, x(k)=Akx0+∑m=0k−1Ak−1−mBu(m)x(k) = A^kx_0 + \sum_{m=0}^{k-1}A^{k-1-m}Bu(m). So y(i+1)=Cx(i+1)=CAi+1x0+∑m=0iCAi−mBu(m)y(i+1) = Cx(i+1) = CA^{i+1}x_0 + \sum_{m=0}^{i}CA^{i-m}Bu(m), which is row ii of Puj+dPu_j + d. □\square

The function run_trial computes the recursion and lifted_matrix builds PP; the tests check yj=Puj+dy_j = Pu_j + d exactly in Fraction arithmetic.

Claim 2 (error recursion). With Q=IQ = I, ej+1=(I−PL)eje_{j+1} = (I - PL)e_j, so ej=(I−PL)je0e_j = (I - PL)^je_0.

Proof. Line L5 gives uj+1=uj+Leju_{j+1} = u_j + Le_j. By Claim 1, ej+1=yd−Puj+1−d=(yd−Puj−d)−PLej=ej−PLeje_{j+1} = y_d - Pu_{j+1} - d = (y_d - Pu_j - d) - PLe_j = e_j - PLe_j. □\square

Claim 3 (asymptotic convergence). ej→0e_j \to 0 for every e0e_0 if and only if ρ(I−PL)<1\rho(I - PL) < 1. For L=γIL = \gamma I, ρ(I−γP)=∣1−γCB∣\rho(I - \gamma P) = |1 - \gamma CB|.

Proof. For a square matrix MM, Mj→0M^j \to 0 if and only if ρ(M)<1\rho(M) < 1 (by the Jordan form: a Jordan block of the eigenvalue λ\lambda has entries (jm)λj−m\binom{j}{m}\lambda^{j-m}, which go to zero if and only if ∣λ∣<1|\lambda| < 1). Since e0=yd−Pu0−de_0 = y_d - Pu_0 - d can be any vector (choose ydy_d), ej=Mje0→0e_j = M^je_0 \to 0 for every e0e_0 if and only if Mj→0M^j \to 0. For L=γIL = \gamma I, I−γPI - \gamma P is lower triangular with every diagonal entry 1−γCB1 - \gamma CB, and the eigenvalues of a triangular matrix are its diagonal entries. □\square

In particular, if γCB=1\gamma CB = 1 then I−γPI - \gamma P is strictly lower triangular, so (I−γP)N=0(I - \gamma P)^N = 0 and eN=0e_N = 0 for every e0e_0. The tests check this exactly for a=9/10a = 9/10, N=30N = 30. If ∣1−γCB∣>1|1 - \gamma CB| > 1, the first entry of eje_j is (1−γCB)je0(0)(1 - \gamma CB)^je_0(0) and grows; the tests check the factor −3/2-3/2 for γ=5/2\gamma = 5/2.

Claim 4 (monotonic convergence). If ∥I−PL∥2=q<1\|I - PL\|_2 = q < 1, then ∥ej+1∥2≤q∥ej∥2\|e_{j+1}\|_2 \le q\|e_j\|_2 for every jj. For L=γIL = \gamma I and AA with all eigenvalues inside the unit circle, ∥I−γP∥2≤max⁡ω∣1−γPˉ(eiω)∣\|I - \gamma P\|_2 \le \max_\omega|1 - \gamma\bar P(e^{\mathrm{i}\omega})| with Pˉ(z)=∑k≥0CAkBz−k\bar P(z) = \sum_{k\ge 0}CA^kBz^{-k}.

Proof. The first part follows from Claim 2 and the definition of the induced norm. For the second, let ck=[k=0]−γCAkBc_k = [k = 0] - \gamma CA^kB, so I−γPI - \gamma P is the NN by NN lower triangular Toeplitz matrix TNT_N with entries ci−kc_{i-k}, and ∑k∣ck∣<∞\sum_k|c_k| < \infty because ρ(A)<1\rho(A) < 1. For v∈RNv \in \mathbb{R}^N, extend vv by zeros to a sequence on Z\mathbb{Z}; then TNvT_Nv is the restriction to {0,…,N−1}\{0, \dots, N-1\} of the convolution c∗vc * v. By Parseval, ∥c∗v∥22=12π∫−ππ∣c^(ω)∣2∣v^(ω)∣2 dω≤max⁡ω∣c^(ω)∣2 ∥v∥22\|c * v\|_2^2 = \frac{1}{2\pi}\int_{-\pi}^{\pi}|\hat c(\omega)|^2|\hat v(\omega)|^2\,d\omega \le \max_\omega|\hat c(\omega)|^2\,\|v\|_2^2, where c^(ω)=∑kcke−ikω=1−γPˉ(eiω)\hat c(\omega) = \sum_kc_ke^{-\mathrm{i}k\omega} = 1 - \gamma\bar P(e^{\mathrm{i}\omega}). A restriction does not increase the norm, so ∥TNv∥2≤max⁡ω∣c^(ω)∣ ∥v∥2\|T_Nv\|_2 \le \max_\omega|\hat c(\omega)|\,\|v\|_2. □\square

For the example Pˉ(z)=1/(1−az−1)\bar P(z) = 1/(1 - az^{-1}), which is real at ω=0\omega = 0 and ω=π\omega = \pi with the values 1/(1−a)1/(1 - a) and 1/(1+a)1/(1 + a). For a=1/2a = 1/2 and γ=1/2\gamma = 1/2, 1−γPˉ1 - \gamma\bar P ranges over a circle through 00 and 2/32/3, so the maximum is 2/32/3 and the decay is monotonic. For a=0.9a = 0.9 and γ=1\gamma = 1 the value at ω=0\omega = 0 is 1−10=−91 - 10 = -9, and the bound gives nothing; the example shows the growth.

Claim 5 (norm-optimal law). If PP is invertible and w>0w > 0, then L=(PTP+wI)−1PTL = (P^TP + wI)^{-1}P^T gives I−PL=w(PPT+wI)−1I - PL = w(PP^T + wI)^{-1} and ∥I−PL∥2=w/(σmin⁡2+w)<1\|I - PL\|_2 = w/(\sigma_{\min}^2 + w) < 1, where σmin⁡\sigma_{\min} is the smallest singular value of PP. So the decay is monotonic for every invertible PP.

Proof. PT(PPT+wI)=(PTP+wI)PTP^T(PP^T + wI) = (P^TP + wI)P^T, so (PTP+wI)−1PT=PT(PPT+wI)−1(P^TP + wI)^{-1}P^T = P^T(PP^T + wI)^{-1}. Then PL=PPT(PPT+wI)−1PL = PP^T(PP^T + wI)^{-1} and I−PL=(PPT+wI−PPT)(PPT+wI)−1=w(PPT+wI)−1I - PL = (PP^T + wI - PP^T)(PP^T + wI)^{-1} = w(PP^T + wI)^{-1}. This matrix is symmetric with the eigenvalues w/(σi2+w)w/(\sigma_i^2 + w); the largest is at σmin⁡\sigma_{\min}. PP is lower triangular with diagonal CB≠0CB \ne 0, so it is invertible and σmin⁡>0\sigma_{\min} > 0. □\square

The law minimizes ∥ej−Pδ∥22+w∥δ∥22\|e_j - P\delta\|_2^2 + w\|\delta\|_2^2 over the change δ=uj+1−uj\delta = u_{j+1} - u_j: the gradient −2PT(ej−Pδ)+2wδ-2P^T(e_j - P\delta) + 2w\delta vanishes at δ=(PTP+wI)−1PTej=Lej\delta = (P^TP + wI)^{-1}P^Te_j = Le_j, and the cost is strictly convex.

Plant inversion. L=P−1L = P^{-1} gives I−PL=0I - PL = 0, so e1=0e_1 = 0 for every e0e_0; the tests check this exactly. If the true plant is (I+Δ)P^(I + \Delta)\hat P and L=P^−1L = \hat P^{-1}, then I−PL=−ΔI - PL = -\Delta, and Claim 4 gives monotonic decay when ∥Δ∥2<1\|\Delta\|_2 < 1.

Complexity

In the real-RAM model, one trial costs O(Nn2)O(Nn^2) to simulate with a dense AA of order nn, and one update with a dense LL costs O(N2)O(N^2). So JJ trials cost O(J(Nn2+N2))O(J(Nn^2 + N^2)), and storing LL takes O(N2)O(N^2). The P-type law needs only O(N)O(N) per update. The norm-optimal matrix costs O(N3)O(N^3) once. With int or Fraction data the implementation is exact, so the property exact is true; the entries grow in size with the number of trials.

Properties

  • Asymptotic convergence. Theorem: ej→0e_j \to 0 for all e0e_0 if and only if ρ(I−PL)<1\rho(I - PL) < 1.
  • Monotonic convergence. Theorem: ∥I−PL∥2<1\|I - PL\|_2 < 1 gives a decay in every trial with that factor. Without it, the error can grow by many orders of magnitude before it decays, as in the example.
  • Robustness. Theorem: if the true plant is P=(I+Δ)P^P = (I + \Delta)\hat P with a model P^\hat P and an output multiplicative error Δ\Delta, the law L=P^−1L = \hat P^{-1} gives I−PL=−ΔI - PL = -\Delta, so it converges monotonically in the 2-norm if ∥Δ∥2<1\|\Delta\|_2 < 1.
  • Q-filter trade-off. With a filter QQ, the input obeys uj+1=Q(I−LP)uj+QL(yd−d)u_{j+1} = Q(I - LP)u_j + QL(y_d - d), so it converges if ρ(Q(I−LP))<1\rho(Q(I - LP)) < 1 (theorem). A low pass QQ makes this hold under high frequency model errors and noise, but the limit error is in general not zero; the bias is set by QQ (rule of thumb: put the bandwidth of QQ where the model is still good).
  • Repetition needed. The error recursion holds only when the initial state, the reference and the disturbances are the same in every trial. A disturbance that changes from trial to trial is not learned.

Variants and improvements

  • PD-type and phase lead laws. Use LL with a time shift of several samples or a derivative; this compensates the phase lag of the plant.
  • Q-filtered ILC. Use a zero phase low pass QQ to stop the learning at frequencies where the model is poor (Bristow, Tharayil and Alleyne 2006).
  • Norm-optimal ILC. Amann, Owens and Rogers (1996) minimize a quadratic cost in each trial; the decay is monotonic in the 2-norm. It is close to LQR over the trial.
  • Repetitive control. For a periodic task with no reset between periods, the learning runs continuously; its design rests on the internal model principle.
  • Nonlinear and adaptive ILC. For nonlinear plants with a Lipschitz condition, contraction mapping arguments give similar results.

When to use it

Use ILC when a system repeats the same motion from the same initial state, for example robot manipulators, wafer stages, printers, machine tools, and batch processes in chemistry. It suits cases where feedback alone cannot reach the required accuracy because of delays and phase lag, but the error repeats. If the task changes in every run, use a feedback design or model predictive control. If a good model is available, plant inversion or a norm-optimal law learns in a few trials; with no model, a small P-type gain with a Q-filter is a safer start.

Pitfalls

  • Transient growth. ρ(I−PL)<1\rho(I - PL) < 1 alone allows the error to grow by a large factor before it decays; in practice this damages the plant. Check ∥I−PL∥2<1\|I - PL\|_2 < 1 or the frequency condition.
  • Non-repeating initial state. A different x0x_0 in each trial adds an error term that learning cannot remove.
  • Noise. The law adds the measured error to the input, so the noise accumulates in uu trial after trial; use a Q-filter or a learning gain that decreases with jj.
  • Relative degree. With CB=0CB = 0 the first output does not depend on the first input; shift the error by the relative degree, otherwise PP is singular.
  • Error sign. This page uses e=yd−ye = y_d - y. With e=y−yde = y - y_d the sign of LL 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.

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()
iterative_learning_control.py 82 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/iterative-learning-control/. The authors are listed in prov/0W0JD2.jsonl.

"""Iterative learning control for a discrete-time plant that repeats a task.

The plant is x(k+1) = A x(k) + B u(k), y(k) = C x(k), with a single input
and a single output and C B != 0 (relative degree one). Each trial starts
from the same state x0 and lasts N samples: the input u(0), ..., u(N-1)
gives the outputs y(1), ..., y(N). In lifted form y = P u + d, where P is
the N by N lower triangular Toeplitz matrix of the Markov parameters
P[i][j] = C A^(i-j) B and d is the free response from x0.

The learning law is u_(j+1) = Q (u_j + L e_j) with e_j = y_d - y_j. For
Q = I the error obeys e_(j+1) = (I - P L) e_j exactly.

With int or Fraction data every routine is exact (Fraction arithmetic).
"""

from ctlmat import eye, matvec, mul, solve, sub, transpose, add, scale

__all__ = ["run_trial", "lifted_matrix", "ilc", "p_type", "plant_inverse", "norm_optimal", "error_map"]


def run_trial(A, B, C, x0, u):
    """Simulate one trial and return y(1), ..., y(N) for the inputs u(0..N-1)."""
    x = list(x0)
    ys = []
    for uk in u:
        x = [s + b * uk for s, b in zip(matvec(A, x), B)]
        ys.append(sum(c * v for c, v in zip(C, x)))
    return ys


def lifted_matrix(A, B, C, N):
    """Return the lifted plant P with P[i][j] = C A^(i-j) B for i >= j."""
    h = []
    v = list(B)
    for _ in range(N):
        h.append(sum(c * w for c, w in zip(C, v)))
        v = matvec(A, v)
    return [[h[i - j] if i >= j else 0 for j in range(N)] for i in range(N)]


def p_type(gamma, N):
    """The P-type (Arimoto) learning matrix L = gamma I."""
    return scale(gamma, eye(N))


def plant_inverse(P):
    """The inverse learning matrix L = P^(-1); one trial removes the error."""
    return solve(P, eye(len(P)))


def norm_optimal(P, w):
    """The norm-optimal learning matrix L = (P^T P + w I)^(-1) P^T, w > 0."""
    Pt = transpose(P)
    return solve(add(mul(Pt, P), scale(w, eye(len(P)))), Pt)


def ilc(trial, yd, u0, L, trials, Q=None):
    """Run the learning loop for a number of trials.

    trial(u) runs the plant once and returns the outputs. Returns (us, es):
    the inputs and errors of trials 0, ..., trials (one more than the number
    of updates).
    """
    u = list(u0)  # @line L1
    us, es = [], []
    for _ in range(trials + 1):  # @line L2
        y = trial(u)  # @line L3
        e = [r - v for r, v in zip(yd, y)]  # @line L4
        us.append(u)
        es.append(e)
        u = [a + b for a, b in zip(u, matvec(L, e))]  # @line L5
        if Q is not None:
            u = matvec(Q, u)
    return us, es  # @line L6


def error_map(P, L):
    """Return I - P L, the matrix that maps e_j to e_(j+1) when Q = I."""
    return sub(eye(len(P)), mul(P, L))
test_iterative_learning_control.py 124 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/iterative-learning-control/. The authors are listed in prov/0W0JD2.jsonl.

"""Tests for iterative learning control. Exact (Fraction) where the algorithm is exact."""

import math
import random
import unittest
from fractions import Fraction

from ctlmat import mat_power, matvec, norm2
from iterative_learning_control import (error_map, ilc, lifted_matrix, norm_optimal, p_type,
                                        plant_inverse, run_trial)


def random_plant(rng, n):
    while True:
        A = [[Fraction(rng.randint(-5, 5), 10) for _ in range(n)] for _ in range(n)]
        B = [Fraction(rng.randint(-3, 3)) for _ in range(n)]
        C = [Fraction(rng.randint(-3, 3)) for _ in range(n)]
        if sum(c * b for c, b in zip(C, B)) != 0:
            x0 = [Fraction(rng.randint(-2, 2)) for _ in range(n)]
            return A, B, C, x0


def first_order(a, N):
    A, B, C = [[a]], [1], [1]
    return lifted_matrix(A, B, C, N), (lambda u: run_trial(A, B, C, [0 * a], u))


SINE = [math.sin(math.pi * (k + 1) / 30) for k in range(30)]


class TestLiftedModel(unittest.TestCase):
    def test_lifted_matrix_matches_simulation(self):
        # reference: the trial simulation; y = P u + d with d the free response
        rng = random.Random(3)
        for n in (1, 2, 3):
            A, B, C, x0 = random_plant(rng, n)
            N = 8
            P = lifted_matrix(A, B, C, N)
            d = run_trial(A, B, C, x0, [0] * N)
            for _ in range(3):
                u = [Fraction(rng.randint(-4, 4)) for _ in range(N)]
                y = run_trial(A, B, C, x0, u)
                self.assertEqual(y, [p + q for p, q in zip(matvec(P, u), d)])

    def test_error_recursion_is_exact(self):
        # e_j = (I - P L)^j e_0, checked against matrix powers
        rng = random.Random(4)
        A, B, C, x0 = random_plant(rng, 3)
        N = 6
        P = lifted_matrix(A, B, C, N)
        L = [[Fraction(rng.randint(-2, 2), 4) for _ in range(N)] for _ in range(N)]
        yd = [Fraction(rng.randint(-5, 5)) for _ in range(N)]
        _, es = ilc(lambda u: run_trial(A, B, C, x0, u), yd, [0] * N, L, 5)
        M = error_map(P, L)
        for j, e in enumerate(es):
            self.assertEqual(e, matvec(mat_power(M, j), es[0]))


class TestLearningLaws(unittest.TestCase):
    def test_plant_inverse_one_trial(self):
        rng = random.Random(5)
        A, B, C, x0 = random_plant(rng, 2)
        N = 6
        P = lifted_matrix(A, B, C, N)
        yd = [Fraction(rng.randint(-5, 5)) for _ in range(N)]
        _, es = ilc(lambda u: run_trial(A, B, C, x0, u), yd, [0] * N, plant_inverse(P), 2)
        self.assertNotEqual(es[0], [0] * N)
        self.assertEqual(es[1], [0] * N)
        self.assertEqual(es[2], [0] * N)

    def test_p_type_nilpotent_exact(self):
        # gamma = 1 and C B = 1: I - P is strictly lower triangular, so e_N = 0 exactly
        N = 30
        P, trial = first_order(Fraction(9, 10), N)
        yd = [Fraction(k + 1, N) for k in range(N)]
        _, es = ilc(trial, yd, [0] * N, p_type(1, N), N)
        self.assertNotEqual(es[N - 1], [0] * N)
        self.assertEqual(es[N], [0] * N)

    def test_p_type_transient_growth(self):
        # a = 0.9, gamma = 1: converges in theory, but the error first grows by about 3e5
        N = 30
        P, trial = first_order(0.9, N)
        _, es = ilc(trial, SINE, [0.0] * N, p_type(1.0, N), N)
        ns = [norm2(e) for e in es]
        self.assertGreater(max(ns), 1e6)
        self.assertEqual(max(range(N + 1), key=lambda j: ns[j]), 14)
        self.assertLess(ns[-1], 1e-6)

    def test_p_type_monotone_when_norm_below_one(self):
        N = 30
        P, trial = first_order(0.5, N)
        rho = norm2(error_map(P, p_type(0.5, N)))
        self.assertLess(rho, 2.0 / 3.0)
        _, es = ilc(trial, SINE, [0.0] * N, p_type(0.5, N), 20)
        for j in range(20):
            self.assertLessEqual(norm2(es[j + 1]), rho * norm2(es[j]) + 1e-12)

    def test_first_error_entry_factor(self):
        # the first entry of e is multiplied by 1 - gamma C B in every trial
        N = 6
        P, trial = first_order(Fraction(1, 2), N)
        yd = [Fraction(1)] * N
        _, es = ilc(trial, yd, [0] * N, p_type(Fraction(5, 2), N), 8)
        for j, e in enumerate(es):
            self.assertEqual(e[0], Fraction(-3, 2) ** j)

    def test_norm_optimal_monotone(self):
        N = 30
        P, trial = first_order(0.9, N)
        for w in (0.1, 1.0):
            L = norm_optimal(P, w)
            rho = norm2(error_map(P, L))
            self.assertLess(rho, 1.0)
            _, es = ilc(trial, SINE, [0.0] * N, L, 10)
            for j in range(10):
                self.assertLessEqual(norm2(es[j + 1]), rho * norm2(es[j]) + 1e-12)


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

History

Uchiyama (1978) published in Japanese a method that corrects the input of a robot from the error of the last motion. Arimoto, Kawamura and Miyazaki (1984) gave the update in its standard form, proved its convergence, and introduced the name learning control for robots; their paper is the usual start of the field. Amann, Owens and Rogers (1996) introduced the norm-optimal law with monotonic convergence. Longman (2000) explained the large transient growth of simple laws in practice and gave the frequency domain condition. Bristow, Tharayil and Alleyne (2006) wrote the standard survey.

References

  1. Suguru Arimoto, Sadao Kawamura and Fumio Miyazaki, Bettering operation of robots by learning, Journal of Robotic Systems 1(2), 1984, pages 123 to 140 (the learning update from the error of the last trial and its convergence)
  2. Douglas A. Bristow, Marina Tharayil and Andrew G. Alleyne, A survey of iterative learning control, IEEE Control Systems Magazine 26(3), 2006, pages 96 to 114 (the lifted system, asymptotic and monotonic convergence, the P-type, plant inversion and norm-optimal designs, the Q-filter)
  3. Notker Amann, David H. Owens and Eric Rogers, Iterative learning control for discrete-time systems with exponential rate of convergence, IEE Proceedings, Control Theory and Applications 143(2), 1996, pages 217 to 224 (the norm-optimal learning law)
  4. Richard W. Longman, Iterative learning control and repetitive control for engineering practice, International Journal of Control 73(10), 2000, pages 930 to 954 (the large transient growth of simple learning laws and the frequency domain condition for monotonic decay)

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