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
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 , where is the trial number, is the tracking error over the trial, and and are filters or matrices. Because the correction is computed between trials, 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 , , with one input, one output and the first Markov parameter (relative degree one). Each trial starts at the same state and has samples with the sampling period . The input gives the outputs . With the vectors of trial , the lifted model is
where is the response to . is lower triangular Toeplitz. Given a reference , find inputs with as , without knowing exactly.
The algorithm
Choose the learning matrix and the filter (often ). Common choices of :
- P-type (Arimoto): , that is in terms of the unlifted signals.
- Plant inversion: for a model of the plant.
- Norm-optimal: with a weight . It minimizes .
ILC(trial, y_d, u₀, L, Q, J) ▷ J updates- 1
u ← u₀ - 2
for j ← 0 to J do - 3
y ← run one trial with input u ▷ same initial state each trial - 4
e ← y_d - y ▷ the error over the whole trial - 5
u ← Q (u + L e) ▷ between trials - 6
return u and the errors of all trials
With , the error obeys exactly, because and are the same in every trial.
Example
Take with , so for . The trial has samples, the reference is for , and , so . With the P-type law:
| behavior of | ||||
|---|---|---|---|---|
| 0.9 | 1 | 7.0487 | 9 | grows to 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; 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 is lower triangular with the diagonal , so its spectral radius is . Only the last one converges monotonically in the 2-norm. The first case is nilpotent: is strictly lower triangular, so 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 . These are measurements of the stated runs.
The norm-optimal law with removes the transient growth. For , and is for to 3. For , and .
Correctness
The proof in proofs/correctness.md shows four facts (theorems). First, with and the same initial state, , so . Second, for every if and only if the spectral radius ; for the P-type law this is , a condition that does not depend on . Third, if , then , so the decay is monotonic; for a sufficient condition is , where is the transfer function of the plant advanced by one sample (for 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 , whose 2-norm is , where is the smallest singular value of .
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 starts at , the input holds , and the output holds .
Claim 1 (lifted model). , where for , for (indices from 0), and .
Proof. By induction on , . So , which is row of .
The function run_trial computes the recursion and lifted_matrix builds ; the tests check exactly in Fraction arithmetic.
Claim 2 (error recursion). With , , so .
Proof. Line L5 gives . By Claim 1, .
Claim 3 (asymptotic convergence). for every if and only if . For , .
Proof. For a square matrix , if and only if (by the Jordan form: a Jordan block of the eigenvalue has entries , which go to zero if and only if ). Since can be any vector (choose ), for every if and only if . For , is lower triangular with every diagonal entry , and the eigenvalues of a triangular matrix are its diagonal entries.
In particular, if then is strictly lower triangular, so and for every . The tests check this exactly for , . If , the first entry of is and grows; the tests check the factor for .
Claim 4 (monotonic convergence). If , then for every . For and with all eigenvalues inside the unit circle, with .
Proof. The first part follows from Claim 2 and the definition of the induced norm. For the second, let , so is the by lower triangular Toeplitz matrix with entries , and because . For , extend by zeros to a sequence on ; then is the restriction to of the convolution . By Parseval, , where . A restriction does not increase the norm, so .
For the example , which is real at and with the values and . For and , ranges over a circle through and , so the maximum is and the decay is monotonic. For and the value at is , and the bound gives nothing; the example shows the growth.
Claim 5 (norm-optimal law). If is invertible and , then gives and , where is the smallest singular value of . So the decay is monotonic for every invertible .
Proof. , so . Then and . This matrix is symmetric with the eigenvalues ; the largest is at . is lower triangular with diagonal , so it is invertible and .
The law minimizes over the change : the gradient vanishes at , and the cost is strictly convex.
Plant inversion. gives , so for every ; the tests check this exactly. If the true plant is and , then , and Claim 4 gives monotonic decay when .
Complexity
In the real-RAM model, one trial costs to simulate with a dense of order , and one update with a dense costs . So trials cost , and storing takes . The P-type law needs only per update. The norm-optimal matrix costs 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: for all if and only if .
- Monotonic convergence. Theorem: 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 with a model and an output multiplicative error , the law gives , so it converges monotonically in the 2-norm if .
- Q-filter trade-off. With a filter , the input obeys , so it converges if (theorem). A low pass makes this hold under high frequency model errors and noise, but the limit error is in general not zero; the bias is set by (rule of thumb: put the bandwidth of 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 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 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. alone allows the error to grow by a large factor before it decays; in practice this damages the plant. Check or the frequency condition.
- Non-repeating initial state. A different 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 trial after trial; use a Q-filter or a learning gain that decreases with .
- Relative degree. With the first output does not depend on the first input; shift the error by the relative degree, otherwise is singular.
- Error sign. This page uses . With the sign of 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.
# 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
- 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)
- 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)
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 0W0JD2 Edit this page History Report an error Markdown