Algorithmadvanced
H-infinity loop shaping
Also called Glover-McFarlane loop shaping, normalized coprime factor robust stabilization.
Shapes the open loop with weights and then robustly stabilizes the shaped plant against normalized coprime factor uncertainty.
- Time
- O(c n^3 + n^2 (m + p)) total
- Space
- O(n^2 + n (m + p)) extra
- Where
- c = the number of Newton steps of one matrix sign function; m = the number of plant inputs; n = the number of states of the shaped plant; p = the number of plant outputs
- Model
- Real RAM
- Properties
- deterministicnot exactnot iterativeiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Duncan McFarlane, Keith Glover, 1992
H-infinity loop shaping, also called Glover-McFarlane loop shaping, is a design method for linear multivariable feedback in two steps. First the designer picks weights and so that the shaped plant has a good open loop shape: high gain at low frequency, low gain at high frequency and a moderate slope near crossover, as in classical loop shaping. Then a robust controller stabilizes with the largest possible margin against perturbations of a normalized coprime factorization of . The final controller is . The second step is a special H-infinity control problem whose optimal level has a closed form from two Riccati equations, so no search on is needed.
In plain words
Classical loop shaping tells you what the loop gain should look like, but it does not tell you how to make the loop stable with good margins for a plant with many inputs and outputs. This method lets you shape the gain first, with simple weights, and then adds a controller that fixes stability and robustness near crossover. The robust step is cheap: two Riccati equations give the best margin in closed form. If the best margin is very small, the shape you asked for is not compatible with the plant, and you change the weights. If the margin is good, the robust step changes the shaped loop only a little.
The problem
Let be a strictly proper shaped plant with inputs, outputs and states, with stabilizable and detectable. A normalized left coprime factorization has and stable and on the imaginary axis. The perturbed plants are
with and stable. The controller is connected in negative feedback, . By the small gain theorem, stabilizes every such if and only if it stabilizes internally and
The stability margin of the loop is . The robust step asks for a controller with close to the largest value .
Theorem (Glover and McFarlane 1989; Skogestad and Postlethwaite 2005, section 9.4). Let be the stabilizing solution of the filter Riccati equation and that of the control Riccati equation:
Then the smallest achievable value of over all internally stabilizing controllers is
where is the spectral radius and is the Hankel norm. For every a controller with is with
Skogestad and Postlethwaite (2005) write this controller for positive feedback, , with . This page uses negative feedback, so the sign of is changed once here and in the code.
The algorithm
LOOP-SHAPING-DESIGN(G, W1, W2, f)- 1
Gs ← W2 G W1 ▷ shaped plant (A, B, C, 0) - 2
Z ← stabilizing solution of A Z + Z A^T - Z C^T C Z + B B^T = 0 - 3
X ← stabilizing solution of A^T X + X A - X B B^T X + C^T C = 0 - 4
γmin ← sqrt(1 + ρ(X Z)) - 5
γ ← f · γmin ▷ f > 1, often 1.1 - 6
L ← (1 - γ^2) I + X Z - 7
B_K ← γ^2 (L^T)^-1 Z C^T - 8
Ks ← (A - B B^T X + B_K C, B_K, -B^T X, 0) - 9
return γmin, γ, K = W1 Ks W2
The two Riccati equations are solved as on the two-Riccati synthesis page: the code takes the matrix sign function of the Hamiltonian matrix by a scaled Newton iteration, reads off the stable invariant subspace, and accepts the solution only if the residual is small and the closed loop matrix is Hurwitz. The designer then checks : a value above about 4 ( below 0.25) means the weights ask for a loop that this plant cannot give with good robustness. This is a rule of thumb from design practice (Skogestad and Postlethwaite 2005, section 9.4), not a theorem.
Example
Take , so and . Both Riccati equations reduce to , so and
With , and . Then , , and . The controller for is
The loop gives the closed loop polynomial , so the loop is internally stable. A frequency sweep of the map in the definition of gives a peak of , reached as , so . This is above and below , as the theorem says.
For this plant the static gain already reaches : the map is , which has rank one and largest singular value at every frequency. As , becomes singular and the central controller degenerates; this is why the procedure backs off.
For the equations give , and . With the integral weight the shaped plant has , and the final controller has three states, an integrator, and gives an internally stable loop with the plant.
Correctness
The theorem above is cited; its proof combines three facts (Glover and McFarlane 1989; Zhou, Doyle and Glover 1996, chapter 18). First, the small gain theorem reduces robust stabilization against to the bound on . Second, for a normalized coprime factorization this bound is a two-block problem that reduces to a Nehari problem, whose optimum is given by the Hankel norm of . Third, the state-space formulas for the normalized factors turn that Hankel norm into the gramians of a realization with the matrices and , which gives .
The code is correct if it computes the stabilizing and , and then applies the formulas. The Riccati step is the one proved on the two-Riccati synthesis page. The proof file proofs/correctness.md checks the scalar cases in closed form, shows that the series connection gives , and explains why the sign change gives the same loop as the positive feedback formulas of the source. The tests check against a separate Hankel norm computation from two Lyapunov equations, and they check that no stabilizing static or first-order controller from a random sample has a margin above .
Proof: The loop shaping code computes gamma_min and a controller that meets the levelfull
Notation is that of the page. The theorem of Glover and McFarlane (1989) is cited, not proved here: for the stabilizing solutions and of the two Riccati equations, is the smallest achievable value of , and for every the central controller of the source reaches with an internally stable loop. What we prove is that the code computes the objects in that theorem and wires the result correctly.
Claim 1: the Riccati step returns the stabilizing solutions
Line L3 returns the unique symmetric with and Hurwitz. Line L2 returns the unique symmetric with and Hurwitz.
Proof. The routine riccati(a, r, q) is the same as on the two-Riccati synthesis page, where Claims 3 and 4 of its proof show that it returns the stabilizing solution of , or nothing. Line L3 calls it with , , , which is the control equation, and the routine checks that is Hurwitz. Line L2 calls it with , , . Then , and the routine checks that is Hurwitz, which holds if and only if its transpose is Hurwitz. Stabilizability of and detectability of give existence and (the stabilizing Riccati solution theorem).
Line L4 then evaluates the formula of the theorem. has the same eigenvalues as , so its eigenvalues are real and nonnegative and is its largest eigenvalue.
Claim 2: the sign change gives the same loop and the same margin
Let be the controller of the source for positive feedback . The code returns for . The two loops are the same, and equals the robustness level of the source for .
Proof. The transfer matrix of is , so and the two loops have the same equations. The source states the level for as . Put :
The left factor is a constant orthogonal matrix, so it does not change the largest singular value. Next, , and the normalized factors satisfy on the imaginary axis. For any matrix and any with , , so and have the same largest singular value. With and , the norm in the source equals the norm of at every frequency. Swapping the two block columns does not change the singular values, which gives as defined on the page.
Claim 3: the final loop has the same closed loop matrix as the shaped loop
Let = series(series(W1, G), W2) and = series(series(W2, Ks), W1). Then the closed loop state matrix of with is equal, up to a permutation of the states, to the closed loop state matrix of with . So the first loop is internally stable if and only if the second is.
Proof. series(s1, s2) builds the state with , , and output . This is the realization of whose state is the union of the two states, and the empty-state cases in the code are the same formulas with one part removed. So is the chain and is the chain , each with the states of its parts. Both closed loops are the ring with the same four realizations. The closed loop equations list the same state equations in a different order, so the closed loop matrices are equal up to a permutation of the states.
The level is a property of the shaped loop , not of . The page and the tests state it only for the shaped loop.
Claim 4: closed forms for first-order shaped plants
For , that is and , and . For , . For , and .
Proof. Both equations become . The roots are , and only for the plus sign, so that is the stabilizing root. Then . For , . For , and , so . Finally and , so .
Claim 5: for 1/s the unity gain is optimal
For and , .
Proof. The loop with unity negative feedback has the pole , so it is internally stable. At with , and the map is . This has rank one, so its largest singular value is for every . By Claim 4 this equals .
The test checks this value with the code's frequency sweep, which tests the sweep and the definition of against a value known in closed form.
What the tests check
- The values of Claim 4, and the Riccati residuals, positive semidefiniteness and Hurwitz checks of Claim 1 on four plants, one of them open loop unstable and two with a pole at 0.
- against an independent route: , with the Hankel norm from the controllability and observability gramians of the realization , each from a Kronecker form Lyapunov solve.
- For each plant and times : the closed loop is Hurwitz and the swept margin is between and .
- Brute force: random static and first-order controllers for two plants. Every one that stabilizes has a swept margin at most . The sweep uses a coarse grid, which can only miss the peak and so overstate the margin; the check is therefore on the safe side.
- A full design with : the final controller contains the integrator and the loop with the plant is Hurwitz.
Complexity
Let be the number of states of the shaped plant, which is the plant order plus the weight orders. The method needs two Riccati equations of size and one eigenvalue problem for . With Newton steps per matrix sign function, each step , the time is and the extra space is . There is no bisection on , unlike general H-infinity synthesis, because has a closed form. The final controller has states plus the states of and , before any reduction.
Properties
- always, so .
- The margin is the same quantity that the nu-gap metric theory uses: if , then stabilizes every plant whose -gap from is at most (Vinnicombe 1993).
- The robust step changes the loop only where it must: McFarlane and Glover (1992) give bounds, in terms of , on the change of the loop gain at frequencies where the shaped loop gain is large or small. The bounds are theorems; how close the final loop stays to the shaped loop is a measurement on each design.
- bounds the four closed loop maps , , and at once, because each one is a block of the block map in the definition. So also limits the peaks of the sensitivity and complementary sensitivity of the shaped loop.
- Like all H-infinity central controllers, is observer based and has the order of the shaped plant.
Variants and improvements
- Nonzero D. If the shaped plant has , the Riccati equations get extra terms with and (Skogestad and Postlethwaite 2005, section 9.4). This code needs .
- Observer form. The controller can be written in observer form, which makes gain scheduling and anti-windup easier (Skogestad and Postlethwaite 2005, section 9.4).
- Two degrees of freedom. A reference model can be added to the robust step to improve tracking, as in Skogestad and Postlethwaite (2005, section 9.4).
- Discrete time. The same procedure works with discrete Riccati equations.
- Weight choice by optimization. Some methods tune the weights to meet given margins; the second step stays the same.
When to use it
Use it for multivariable plants when you can say what the loop gain should look like, and you want a robust controller without building a weighted generalized plant as in mixed sensitivity design. It is a good first design because it needs only the two weights and one number, , tells you if they are reasonable. It is less direct when the specifications are about particular closed loop maps, or when there is structured uncertainty; then use mixed sensitivity or D-K iteration.
Pitfalls
- Bad weights. If is large, the robust step changes the loop a lot near crossover and the final loop is not the one you shaped. Fix the weights; do not accept the result.
- Unscaled plants. The robustness measure mixes all inputs and outputs, so scale the plant to sensible units before you shape it.
- Sign conventions. Formulas from books on this method are often for positive feedback. A controller with the wrong sign makes the loop unstable even though the numbers look right.
- Integrators. A pure integrator in gives a shaped plant with a pole at 0. The Riccati equations still work, but a frequency sweep at fails; sweep over positive frequencies.
- Controller order. The controller has as many states as the shaped plant. Use model order reduction and check the margin again after the reduction.
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()
h_infinity_loop_shaping.py 189 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/h-infinity-loop-shaping/. The authors are listed in prov/5JS87D.jsonl.
"""H-infinity loop shaping (McFarlane and Glover 1992).
A system is a tuple (A, B, C, D) of lists of rows. The shaped plant
Gs = W2 G W1 must have D = 0 here, as in the simplest form of the
formulas. The robust stabilization step follows Glover and McFarlane
(1989) in the form of Skogestad and Postlethwaite (2005, section 9.4):
GCARE A Z + Z A^T - Z C^T C Z + B B^T = 0
GFARE A^T X + X A - X B B^T X + C^T C = 0
gamma_min = sqrt(1 + rho(X Z)), eps_max = 1 / gamma_min
The central controller of that book is for positive feedback, u = Ks y.
The function controller() returns it in the negative feedback form of
this site, u = -C y (so C = -Ks), with the loop L = G C.
"""
import math
from ctlmat import (
add, block, charpoly, det, eye, inv, mul, norm2, polyroots, scale, solve,
sub, transpose, zeros,
)
__all__ = [
"riccati", "is_hurwitz", "gamma_min", "controller", "series",
"feedback_a", "margin_at", "stability_margin", "loop_shaping_design",
]
def _flo(a):
return [[float(v) for v in row] for row in a]
def _big(a):
return max((abs(v) for row in a for v in row), default=0.0)
def _sign(h, tol=1e-13, maxiter=100):
n = len(h)
z = _flo(h)
for _ in range(maxiter):
d = abs(det(z))
if not d > 0.0 or not math.isfinite(d):
return None
mu = d ** (-1.0 / n)
zi = inv(z)
znew = [[0.5 * (mu * z[i][j] + zi[i][j] / mu) for j in range(n)] for i in range(n)]
diff = _big(sub(znew, z))
z = znew
if diff <= tol * max(1.0, _big(z)):
break
if _big(sub(mul(z, z), eye(n))) > 1e-8:
return None
return z
def is_hurwitz(m, tol=1e-9):
"""Return True if every eigenvalue of m has real part below -tol."""
return max(r.real for r in polyroots(charpoly(_flo(m)))) < -tol
def riccati(a, r, q):
"""Stabilizing X of A^T X + X A + X R X + Q = 0 (A + R X Hurwitz), or None.
The stable invariant subspace of [[A, R], [-Q, -A^T]] is the kernel of
sign(H) + I, and it is the range of [I; X].
"""
n = len(a)
a, r, q = _flo(a), _flo(r), _flo(q)
h = block([[a, r], [scale(-1.0, q), scale(-1.0, transpose(a))]])
w = _sign(h)
if w is None:
return None
wp = add(w, eye(2 * n))
lhs = [row[n:] for row in wp]
rhs = [[-v for v in row[:n]] for row in wp]
lt = transpose(lhs)
try:
x = solve(mul(lt, lhs), mul(lt, rhs))
except ValueError:
return None
x = [[0.5 * (x[i][j] + x[j][i]) for j in range(n)] for i in range(n)]
res = add(add(mul(transpose(a), x), mul(x, a)), add(mul(mul(x, r), x), q))
size = 1.0 + _big(mul(transpose(a), x)) + _big(mul(mul(x, r), x)) + _big(q)
if _big(res) > 1e-8 * size or not is_hurwitz(add(a, mul(r, x))):
return None
return x
def _rho(m):
return max(abs(v) for v in polyroots(charpoly(_flo(m))))
def gamma_min(gs):
"""Return (gamma_min, X, Z) for the shaped plant gs = (A, B, C, 0)."""
a, b, c, d = (_flo(m) for m in gs)
if _big(d) != 0.0:
raise ValueError("this implementation needs D = 0")
z = riccati(transpose(a), scale(-1.0, mul(transpose(c), c)), mul(b, transpose(b))) # @line L2
x = riccati(a, scale(-1.0, mul(b, transpose(b))), mul(transpose(c), c)) # @line L3
if x is None or z is None:
raise ValueError("the shaped plant must be stabilizable and detectable")
return math.sqrt(1.0 + _rho(mul(x, z))), x, z # @line L4
def controller(gs, gamma):
"""Return the central controller (A_K, B_K, C_K, D_K) for u = -C y.
gamma must be larger than gamma_min. Then the loop of gs and C is
internally stable and ||[C; I] (I + gs C)^-1 [I, gs]||_inf <= gamma.
"""
gmin, x, z = gamma_min(gs)
if not gamma > gmin:
raise ValueError("gamma must exceed gamma_min")
a, b, c, _ = (_flo(m) for m in gs)
n = len(a)
g2 = gamma * gamma
l = add(scale(1.0 - g2, eye(n)), mul(x, z)) # @line L6
lti = inv(transpose(l))
bk = scale(g2, mul(mul(lti, z), transpose(c))) # @line L7
ak = add(sub(a, mul(mul(b, transpose(b)), x)), mul(bk, c))
ck = mul(transpose(b), x)
# Positive feedback Ks = (ak, bk, ck, 0); negative feedback C = -Ks.
return ak, bk, scale(-1.0, ck), zeros(len(ck), len(c)) # @line L8
def series(s1, s2):
"""Return s2 s1: the input goes through s1 first, then through s2."""
a1, b1, c1, d1 = (_flo(m) for m in s1)
a2, b2, c2, d2 = (_flo(m) for m in s2)
if not a1:
a = a2
b = mul(b2, d1)
c = c2
return a, b, c, mul(d2, d1)
if not a2:
return a1, b1, mul(d2, c1), mul(d2, d1)
a = block([[a1, zeros(len(a1), len(a2))], [mul(b2, c1), a2]])
b = block([[b1], [mul(b2, d1)]])
c = block([[mul(d2, c1), c2]])
return a, b, c, mul(d2, d1)
def feedback_a(g, k):
"""State matrix of the negative feedback loop u = -K y around G (D_G = 0)."""
ag, bg, cg, dg = (_flo(m) for m in g)
ak, bk, ck, dk = (_flo(m) for m in k)
if _big(dg) != 0.0:
raise ValueError("the plant must be strictly proper")
return block([[sub(ag, mul(mul(bg, dk), cg)), scale(-1.0, mul(bg, ck))],
[mul(bk, cg), ak]]) if ak else sub(ag, mul(mul(bg, dk), cg))
def _resp(sys, s):
a, b, c, d = sys
n = len(a)
if n == 0:
return [[complex(v) for v in row] for row in d]
m = [[(s if i == j else 0.0) - a[i][j] for j in range(n)] for i in range(n)]
return add(mul(c, solve(m, [[complex(v) for v in row] for row in b])), d)
def margin_at(g, k, w):
"""Largest singular value of [K; I] (I + G K)^-1 [I, G] at s = j w."""
gs = _resp(tuple(_flo(m) for m in g), 1j * w)
ks = _resp(tuple(_flo(m) for m in k), 1j * w)
p = len(gs)
sinv = inv(add(eye(p), mul(gs, ks)))
left = block([[ks], [eye(p)]])
right = block([[eye(p), gs]])
return norm2(mul(mul(left, sinv), right))
def stability_margin(g, k, freqs):
"""b(G, K) = 1 / max over freqs of margin_at; the loop must be stable."""
return 1.0 / max(margin_at(g, k, w) for w in freqs)
def loop_shaping_design(g, w1, w2, factor=1.1):
"""McFarlane-Glover design. Return (gamma_min, gamma, K) with K = W1 Ks W2."""
gs = series(series(w1, g), w2) # @line L1
gmin = gamma_min(gs)[0]
gamma = factor * gmin # @line L5
ks = controller(gs, gamma)
k = series(series(w2, ks), w1) # @line L9
return gmin, gamma, k
test_h_infinity_loop_shaping.py 143 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/h-infinity-loop-shaping/. The authors are listed in prov/5JS87D.jsonl.
import math
import random
import ctlmat as cm
from h_infinity_loop_shaping import (
controller,
feedback_a,
gamma_min,
is_hurwitz,
loop_shaping_design,
series,
stability_margin,
)
INTEGRATOR = ([[0]], [[1]], [[1]], [[0]]) # 1 / s
LAG = ([[-1]], [[1]], [[1]], [[0]]) # 1 / (s + 1)
MOTOR = ([[0, 1], [0, -1]], [[0], [1]], [[2, 0]], [[0]]) # 2 / (s (s + 1))
UNSTABLE = ([[1, 1], [0, -2]], [[0], [1]], [[1, 0]], [[0]]) # 1 / ((s - 1) (s + 2))
PLANTS = (INTEGRATOR, LAG, MOTOR, UNSTABLE)
FREQS = [10 ** (e / 40) for e in range(-160, 161)]
def static(k):
return ([], [], [], [[k]])
def lyap(a, q):
# Solve A P + P A^T + Q = 0 by the Kronecker form (I x A + A x I) vec P = -vec Q.
n = len(a)
big = cm.add(cm.kron(cm.eye(n), a), cm.kron(a, cm.eye(n)))
return cm.unvec(cm.solve(big, [-v for v in cm.vec(q)]), n)
def test_ctlmat_self_test():
assert cm._self_test()
def test_integrator_values():
g, x, z = gamma_min(INTEGRATOR)
assert abs(x[0][0] - 1) < 1e-12 and abs(z[0][0] - 1) < 1e-12
assert abs(g - math.sqrt(2)) < 1e-12
def test_first_order_lag_values():
g, x, z = gamma_min(LAG)
r = math.sqrt(2) - 1
assert abs(x[0][0] - r) < 1e-12 and abs(z[0][0] - r) < 1e-12
assert abs(g - math.sqrt(4 - 2 * math.sqrt(2))) < 1e-12
assert abs(1 / g - math.cos(math.pi / 8)) < 1e-12
def test_riccati_residuals():
for gs in PLANTS:
a, b, c, _ = (cm.scale(1.0, m) for m in gs)
_, x, z = gamma_min(gs)
bb = cm.mul(b, cm.transpose(b))
cc = cm.mul(cm.transpose(c), c)
rx = cm.add(cm.sub(cm.add(cm.mul(cm.transpose(a), x), cm.mul(x, a)), cm.mul(cm.mul(x, bb), x)), cc)
rz = cm.add(cm.sub(cm.add(cm.mul(a, z), cm.mul(z, cm.transpose(a))), cm.mul(cm.mul(z, cc), z)), bb)
assert max(abs(v) for row in rx + rz for v in row) < 1e-9
assert cm.is_pos_def(x, -1e-12) and cm.is_pos_def(z, -1e-12)
assert is_hurwitz(cm.sub(a, cm.mul(bb, x)))
assert is_hurwitz(cm.sub(a, cm.mul(z, cc)))
def test_gamma_min_matches_the_hankel_norm():
# Reference: eps_max^2 = 1 - ||[N M]||_H^2 for the normalized left
# coprime factors [N M] = (A - Z C^T C, [B, -Z C^T], C, [0, I]),
# with the Hankel norm from two Lyapunov equations.
for gs in PLANTS:
a, b, c, _ = (cm.scale(1.0, m) for m in gs)
g, _, z = gamma_min(gs)
ah = cm.sub(a, cm.mul(cm.mul(z, cm.transpose(c)), c))
bh = cm.block([[b, cm.scale(-1.0, cm.mul(z, cm.transpose(c)))]])
p = lyap(ah, cm.mul(bh, cm.transpose(bh)))
q = lyap(cm.transpose(ah), cm.mul(cm.transpose(c), c))
hankel2 = max(abs(v) for v in cm.polyroots(cm.charpoly(cm.mul(p, q))))
assert abs((1 - hankel2) - 1 / g ** 2) < 1e-9
def test_central_controller_reaches_the_level():
for gs in PLANTS:
g0 = gamma_min(gs)[0]
for f in (1.05, 1.1, 1.5):
k = controller(gs, f * g0)
assert is_hurwitz(feedback_a(gs, k))
b = stability_margin(gs, k, FREQS)
assert b >= 1 / (f * g0) - 1e-9
assert b <= 1 / g0 + 1e-9
def test_static_gain_for_the_integrator_is_optimal():
# For G = 1/s and C = 1, b(G, C) = 1/sqrt(2) = eps_max.
b = stability_margin(INTEGRATOR, static(1.0), FREQS)
assert abs(b - 1 / math.sqrt(2)) < 1e-9
def test_no_random_controller_beats_eps_max():
# A coarse grid can only miss the peak, which makes the computed
# margin larger, so the check below is on the safe side.
coarse = [10 ** (e / 10) for e in range(-30, 31)] + [0.0]
rng = random.Random(11)
for gs in (LAG, UNSTABLE):
eps = 1 / gamma_min(gs)[0]
found = 0
for _ in range(60):
if rng.random() < 0.5:
k = static(rng.uniform(-1, 6))
else:
pole = rng.uniform(0.1, 10)
k = ([[-pole]], [[1.0]], [[rng.uniform(-5, 20)]], [[rng.uniform(-1, 5)]])
if not is_hurwitz(feedback_a(gs, k)):
continue
found += 1
assert stability_margin(gs, k, coarse) <= eps + 1e-9
assert found > 15
def test_series_connection():
w1 = ([[0]], [[1]], [[2]], [[1]]) # (s + 2) / s
gs = series(w1, LAG) # (s + 2) / (s (s + 1))
a, b, c, d = gs
s = 0.7j
m = [[s - a[i][j] if i == j else -a[i][j] for j in range(2)] for i in range(2)]
val = cm.mul(c, cm.solve(m, [[complex(v) for v in row] for row in b]))[0][0] + d[0][0]
assert abs(val - (s + 2) / (s * (s + 1))) < 1e-12
def test_full_design_with_an_integral_weight():
w1 = ([[0]], [[1]], [[2]], [[1]]) # W1 = (s + 2) / s
w2 = static(1.0)
gmin, gamma, k = loop_shaping_design(LAG, w1, w2, 1.1)
assert abs(gamma - 1.1 * gmin) < 1e-12
assert is_hurwitz(feedback_a(LAG, k))
# The weight puts an integrator in K: K has an eigenvalue at 0.
assert min(abs(r) for r in cm.polyroots(cm.charpoly(k[0]))) < 1e-9
gs = series(w1, LAG)
ks = controller(gs, gamma)
assert stability_margin(gs, ks, FREQS) >= 1 / gamma - 1e-9
History
Glover and McFarlane (1989) solved the robust stabilization problem for normalized coprime factor perturbations and found that the optimal level has a closed form, unlike general H-infinity problems. McFarlane and Glover (1992) built the loop shaping design procedure on it, with weights that carry the performance goals and a robust step that needs no tuning. Vinnicombe (1993) linked the stability margin to the -gap metric, which gave the margin a clear meaning in terms of plant uncertainty.
References
- Keith Glover and Duncan McFarlane, Robust stabilization of normalized coprime factor plant descriptions with H-infinity-bounded uncertainty, IEEE Transactions on Automatic Control 34(8), 821-830, 1989, the closed form of the largest stability margin and the controllers that reach it
- Duncan McFarlane and Keith Glover, A loop-shaping design procedure using H-infinity synthesis, IEEE Transactions on Automatic Control 37(6), 759-769, 1992, the design procedure with pre and post weights and the bounds on how much the robust controller changes the shaped loop
- Sigurd Skogestad and Ian Postlethwaite, Multivariable Feedback Control, Analysis and Design, second edition, Wiley, 2005, Section 9.4, H-infinity loop-shaping design (the two Riccati equations, gamma_min and the central controller for positive feedback)
- Kemin Zhou, John C. Doyle and Keith Glover, Robust and Optimal Control, Prentice Hall, 1996, Chapter 18, H-infinity Loop Shaping
- Glenn Vinnicombe, Frequency domain uncertainty and the graph topology, IEEE Transactions on Automatic Control 38(9), 1371-1383, 1993, the nu-gap metric and the robust stability result in terms of b(G, K)
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 5JS87D Edit this page History Report an error Markdown