Algorithmresearch
LMI-based H-infinity synthesis
Also called Gahinet-Apkarian synthesis.
Solves the H-infinity problem by linear matrix inequalities with no regularity assumptions, and builds the controller from their solution.
- Time
- O(k (n^2 (n + m + p)^3 + n^4 (n + m + p)^2)) totalO(n^2 (n + m + p)^3 + n^4 (n + m + p)^2) per-newton-step
- Space
- O(n^4 + n^2 (n + m + p)^2) extra
- Where
- k = the number of Newton steps of the barrier method; m = the number of inputs w and u together; n = the number of plant states; p = the number of outputs z and y together
- Model
- Real RAM
- Properties
- deterministicnot exactiterativeiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Pascal Gahinet, Pierre Apkarian, Tetsuya Iwasaki, Robert E. Skelton, 1994
LMI-based H-infinity synthesis, also called Gahinet-Apkarian synthesis, solves the H-infinity control problem as a semidefinite program. An output feedback controller of the same order as the plant with closed loop H-infinity norm below exists if and only if two symmetric matrices and satisfy three linear matrix inequalities. The inequalities are linear in , and together, so the smallest is the optimum of a convex program, with no bisection on . A second LMI then gives the controller. Unlike the two-Riccati method, the LMI method needs no rank or normalization assumptions on and and no condition on zeros on the imaginary axis. It also takes extra convex constraints, such as pole regions or bounds on other closed loop norms. The price is speed: the SDP has about variables, so it is much slower than solving two Riccati equations.
In plain words
The bounded real lemma says that a system has gain below if and only if a certain matrix inequality has a positive definite solution. For a closed loop, that inequality has products of the unknown controller and the unknown Lyapunov matrix, so it is not convex. Gahinet and Apkarian showed that you can remove the controller from the problem. What is left is three inequalities in two matrices, and they are linear. A convex solver finds the best and the two matrices. From them you build the closed loop Lyapunov matrix, and then the controller is the solution of one more linear inequality.
The problem
The generalized plant is
with , , , and . The only assumptions are that is stabilizable, is detectable and . A nonzero is removed by a change of the controller. As on the two-Riccati page the loop is closed by , the lower linear fractional transformation, with .
Let the columns of be a basis of the kernel of and those of a basis of the kernel of .
Theorem (Gahinet and Apkarian 1994; Iwasaki and Skelton 1994). There is an internally stabilizing controller of order with if and only if there are symmetric and with
If the third LMI holds with rank , a controller of order exists, so controllers of order above give nothing new. A controller of any order with norm below exists if and only if one of order does.
The algorithm
LMI-SYNTHESIS(A, B1, B2, C1, C2, D11, D12, D21, delta)- 1
N_R ← basis of ker [B2^T D12^T], N_S ← basis of ker [C2 D21] - 2
γ* ← min γ over R, S, γ subject to LMI_R < 0, LMI_S < 0, [R I; I S] > 0 - 3
γ ← (1 + delta) γ* - 4
(R, S) ← analytic center of the three LMIs with γ fixed - 5
N ← I - S R ▷ M = I - 6
X_cl ← [S N; N^T R S R - R] - 7
Ω ← a point with BRL(A_cl(Ω), B_cl(Ω), C_cl(Ω), D_cl(Ω), X_cl, γ) < 0 - 8
return γ*, K = (A_K, B_K, C_K, D_K) read from Ω = [A_K B_K; C_K D_K] BARRIER(c, G_1, ..., G_q, x) ▷ min c^T x subject to G_i(x) > 0- 9
x ← phase I: min s subject to G_i(x) + s I > 0, stop when s < 0 - 10
repeat x ← argmin of t c^T x - Σ log det G_i(x), by Newton steps from x - 11
t ← 8 t until (Σ sizes of the G_i) / t < eps
Line L2 is an SDP in the entries of , and . Its blocks have sizes , and when has full column rank and full row rank. The code also adds the scalar constraint , which keeps every SDP bounded.
Lines L5 and L6 build a closed loop Lyapunov matrix with and . With and , the matrix is . It is positive definite because the third LMI holds strictly at the analytic center.
Line L7. With the closed loop matrices
each of which is affine in , the bounded real LMI
is an LMI in alone. The code solves it with a bound on the Frobenius norm of , written as an LMI by a Schur complement, and takes its analytic center.
The SDP solver. The code uses the barrier method: Newton's method with a backtracking line search on , with the Cholesky factor of each to test feasibility and to get . Phase I starts from and a large slack . When stays positive and the gap bound shows that the minimum of is positive, the LMIs are infeasible. A production code uses a primal-dual interior point method instead.
Example
Take the scalar plant of the two-Riccati page with : , , . The kernel of is spanned by and . The first LMI becomes the inequality
By a Schur complement on the two entries next to the middle, it is equivalent to . The plant is its own dual, so the second LMI is . The third LMI needs , and .
At the first inequality is , that is , and satisfies all three LMIs. At it gives and the same for , so and the LMIs are infeasible. The boundary is at : , so , the same value as the two-Riccati method.
The barrier code returns (error ) with . At the analytic center is , and line L7 gives
The closed loop poles are and , and a frequency sweep gives the peak . This controller differs from the central controller of the two-Riccati method: the LMI method gives some controller that meets the level, not a particular one.
Correctness
The theorem is cited; the proof in Gahinet and Apkarian (1994) goes as follows. By the bounded real lemma, a controller meets the level if and only if some satisfies the closed loop LMI. That LMI has the form with , and fixed by . The elimination lemma (also called the projection lemma) says such an exists if and only if is negative definite on the kernels of and . Written out, these two conditions are the first two LMIs with and . The third LMI says exactly when such and come from one of size .
Given the theorem, the code is correct when each SDP is solved to its tolerance: line L2 finds within in the barrier gap, lines L4 to L6 give an with the right blocks, and by the elimination lemma the LMI of line L7 is feasible, so the barrier method finds an . The proof file proofs/correctness.md shows the block identities of , that the closed loop matrices are affine in as written, that the barrier step keeps every iterate strictly feasible, and the scalar reduction of the example.
Proof: The LMI synthesis code builds a valid closed loop Lyapunov matrix and controllerfull
Notation is that of the page. The theorem of Gahinet and Apkarian (1994) is cited: the controller exists if and only if the three LMIs hold, and for any with and for a solution with strict inequalities, the bounded real LMI in is feasible. We prove the parts that the code adds.
Claim 1: the reconstructed matrix has the right blocks
Let and be symmetric with . Put and with . Then , and .
Proof. The strict coupling LMI gives and, by a Schur complement, . Then . Also is invertible, and , so . Using :
So the Schur complement of in is . With this gives , and the block inverse formula gives . The (1,1) block is by construction.
The code symmetrizes before use, which changes nothing in exact arithmetic.
Claim 2: the closed loop matrices are affine in Omega
With , , , and :
Proof. With , and , substitute into the plant:
, , and .
These are the matrices on the page. Next, , and multiplying by on the right gives ; multiplying by gives . Also , so and . These match term by term.
So, for fixed and , the bounded real matrix is affine in , and the routine affine recovers it exactly from its values at and at the unit vectors.
Claim 3: every iterate of the barrier method is strictly feasible
If the starting point has for all , then every point that _center returns has for all . Phase I starts at a strictly feasible point of the augmented problem.
Proof. A step is accepted only when _objective is finite, and _objective returns a number only when the Cholesky factorization of every succeeds, that is, when every is positive definite. If no step is accepted, the old point is returned. For phase I, the loop doubles until for all and then doubles it once more, so . When phase I stops with , every .
Claim 4: the infeasibility test of phase I is sound
Let be the exact minimizer of and the sum of the block sizes. Then , where is the minimum of . So if , the LMIs have no solution.
Proof. This is the duality gap bound on the central path of the log-det barrier (Boyd and Vandenberghe 2004, chapter 11): the point is dual feasible, and the gap between and its dual value is . Since is at least the dual value, . If , no has all .
The code centers to a Newton decrement of , not exactly. The tests use the test with a clear margin: the level .
Claim 5: the scalar example reduces to scalar inequalities
For the plant of the example with any real , the three LMIs at level have a solution if and only if .
Proof. The kernel of has the orthonormal basis and in the coordinates . The middle matrix of the first LMI in the coordinates has the entries at , at , at , and on the rest of the diagonal. The projection gives
The last row and column only need . A Schur complement on the two other entries reduces the rest to , that is with . The plant is the same after the swaps , , , , so the second LMI is . The third LMI is , and .
If , then , that is , so is a solution. Conversely, let be a solution and . Then , and is convex, so . Divide by : . Since , this gives , so .
This agrees with the two-Riccati page, where the same plant has . At the boundary , so the solution is , which the test checks.
What the tests check
- The kernel bases are orthonormal and span the kernel, for random matrices with a fixed seed.
- The minimum of matches for with relative error below , with at the optimum.
- For a plant with two states, the minimum matches the value from the two-Riccati page within relative.
- At phase I reports infeasible; at the analytic center makes every LMI positive definite with a Cholesky margin.
- The blocks of and of its inverse (Claim 1).
- The controllers give a Hurwitz closed loop and a frequency sweep peak between and .
- A singular plant with , where the two-Riccati method does not apply. For any stabilizing controller the map from to equals at the unstable pole , so by the maximum modulus principle. The code returns a value in and a controller that meets its level.
Complexity
Let be the number of SDP variables and the largest block size. One Newton step forms for all variables in , the Hessian entries in , and solves the Newton system in . With this is per Newton step, in the real-RAM model.
The number of Newton steps is a separate result. For the barrier method on a bounded problem with a strictly feasible start, the self-concordance analysis bounds the Newton steps per centering by a constant plus a term in the change of , and the number of centerings by , where is the sum of block sizes (Boyd and Vandenberghe 2004, chapter 11). Short-step path following methods need Newton steps. These are polynomial bounds only under those assumptions: a fixed accuracy , strict feasibility and a bound on the feasible set. In exact terms the problem of deciding feasibility of an LMI is not known to be in polynomial time. As a measurement, the code needs 50 Newton steps (phase I included) to minimize for the scalar example and 293 for the test plant with two states, and 42 and 87 steps for the controller part.
The second SDP, line L7, has variables and one block of size , so its cost has the same order.
Properties
- No rank assumptions: the method handles singular problems where or loses rank, or where the plant has zeros on the imaginary axis. Then is often an infimum that no controller reaches, and the LMI solution grows without bound as .
- Convex in : the optimum is found directly, not by bisection.
- Extra constraints that are LMIs in and can be added, such as pole regions or an H2 bound on another channel (Scherer, Gahinet and Chilali 1997). With several objectives the common Lyapunov matrix makes the result conservative; that is a theorem about sufficiency, not an exact condition.
- The controller has order , or order if the coupling LMI holds with rank .
- The result depends on the solver: different SDP solutions give different valid controllers.
Variants and improvements
- Change of variables. Scherer, Gahinet and Chilali (1997) use a nonlinear change of the controller variables that makes the synthesis inequality linear in all unknowns at once. The controller then comes from a linear system, not from a second SDP.
- Explicit controller formulas. Gahinet (1996) gave closed formulas for a controller from and , which avoid the second SDP.
- Reduced order. Requiring rank gives a controller of order . The rank constraint is not convex, and the fixed-order problem is NP-hard in general (see the problem page).
- Parameter-dependent plants. The same projection idea gives gain-scheduled controllers for LPV systems (Apkarian, Gahinet and Becker 1995).
- Discrete time. The discrete bounded real lemma gives similar LMIs.
When to use it
Use it when the plant breaks the assumptions of the two-Riccati method, when you need extra convex constraints, or when the problem is a building block in a larger LMI design such as gain scheduling. For a plain H-infinity problem that meets the assumptions, the Riccati method is faster by a large factor and more accurate. Use a good SDP solver; the barrier code here is only for plants with a few states.
Pitfalls
- Strict versus non-strict. SDP solvers return points on the boundary of the feasible set. At the optimum, is singular and the reconstruction of fails, so back off from and re-center, as in lines L3 and L4.
- Ill conditioning. Near the optimum, or in singular problems, or can be huge, and the controller then has very fast poles. In the singular test problem of the code the optimum is 1 and the bound is active.
- Scaling. Scale the plant before solving. Interior point solvers lose accuracy when the entries of the LMIs span many orders of magnitude.
- Verification. Check the result: compute the closed loop poles and the H-infinity norm of the closed loop with a reliable norm computation. A small solver error can give a controller with a norm slightly above .
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()
lmi_h_infinity_synthesis.py 385 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lmi-h-infinity-synthesis/. The authors are listed in prov/HWW5GT.jsonl.
"""LMI-based H-infinity synthesis (Gahinet and Apkarian 1994).
The plant is a dict with keys A, B1, B2, C1, C2, D11, D12, D21 (D22 = 0):
x' = A x + B1 w + B2 u, z = C1 x + D11 w + D12 u, y = C2 x + D21 w.
The controller K = (A_K, B_K, C_K, D_K) is wired as u = K y, the lower
linear fractional transformation, as on the two-Riccati synthesis page.
The semidefinite programs are solved by a small log-barrier method with
Newton steps and a phase I. It is meant for plants with a few states;
a real code uses a primal-dual interior point solver.
"""
import math
from ctlmat import add, block, charpoly, eye, inv, mul, polyroots, scale, solve, sub, transpose, zeros
__all__ = [
"null_space", "chol", "sdp_feasible", "sdp_minimize", "sdp_center",
"gamma_lmis", "optimal_gamma", "reconstruct_x", "controller_lmi",
"closed_loop", "is_hurwitz", "lmi_synthesis",
]
def _flo(a):
return [[float(v) for v in row] for row in a]
# ---------------------------------------------------------------- algebra
def null_space(m, tol=1e-10):
"""Orthonormal basis of the kernel of m, as the columns of a matrix."""
m = _flo(m)
rows, cols = len(m), len(m[0])
a = [list(r) for r in m]
pivots = []
r = 0
big = max((abs(v) for row in a for v in row), default=0.0)
for c in range(cols):
if r == rows:
break
p = max(range(r, rows), key=lambda i: abs(a[i][c]))
if abs(a[p][c]) <= tol * max(big, 1.0):
continue
a[r], a[p] = a[p], a[r]
piv = a[r][c]
a[r] = [v / piv for v in a[r]]
for i in range(rows):
if i != r and a[i][c] != 0.0:
f = a[i][c]
a[i] = [a[i][j] - f * a[r][j] for j in range(cols)]
pivots.append(c)
r += 1
free = [c for c in range(cols) if c not in pivots]
vecs = []
for f in free:
v = [0.0] * cols
v[f] = 1.0
for i, c in enumerate(pivots):
v[c] = -a[i][f]
vecs.append(v)
basis = []
for v in vecs: # Gram-Schmidt, twice for accuracy
for _ in range(2):
for q in basis:
d = sum(x * y for x, y in zip(v, q))
v = [x - d * y for x, y in zip(v, q)]
n = math.sqrt(sum(x * x for x in v))
basis.append([x / n for x in v])
return [[basis[j][i] for j in range(len(basis))] for i in range(cols)]
def chol(a):
"""Lower Cholesky factor of a symmetric matrix, or None if not positive definite."""
n = len(a)
low = [[0.0] * n for _ in range(n)]
for j in range(n):
d = a[j][j] - sum(low[j][k] ** 2 for k in range(j))
if not d > 0.0:
return None
low[j][j] = math.sqrt(d)
for i in range(j + 1, n):
low[i][j] = (a[i][j] - sum(low[i][k] * low[j][k] for k in range(j))) / low[j][j]
return low
def is_hurwitz(m, tol=1e-9):
return max(r.real for r in polyroots(charpoly(_flo(m)))) < -tol
def _sym(a):
n = len(a)
return [[0.5 * (a[i][j] + a[j][i]) for j in range(n)] for i in range(n)]
# ------------------------------------------------------- log-barrier SDP
#
# An LMI is a pair (G0, [G1, ..., Gk]) and means G0 + sum x_j G_j > 0.
def affine(fun, k):
"""Turn an affine map x -> symmetric matrix into the pair (G0, [G_j])."""
g0 = _sym(_flo(fun([0.0] * k)))
gs = []
for j in range(k):
e = [0.0] * k
e[j] = 1.0
gs.append(_sym(sub(_flo(fun(e)), g0)))
return g0, gs
def _value(lmi, x):
g0, gs = lmi
n = len(g0)
out = [list(row) for row in g0]
for xj, gj in zip(x, gs):
if xj != 0.0:
for i in range(n):
oi, gi = out[i], gj[i]
for j in range(n):
oi[j] += xj * gi[j]
return out
def _objective(c, t, lmis, x):
f = t * sum(ci * xi for ci, xi in zip(c, x))
for lmi in lmis:
low = chol(_value(lmi, x))
if low is None:
return None
f -= 2.0 * sum(math.log(low[i][i]) for i in range(len(low)))
return f
def _center(c, t, lmis, x, stop=None, tol=1e-10, maxiter=80):
"""Newton's method with backtracking on t c^T x - sum log det G_i(x)."""
k = len(x)
for _ in range(maxiter):
g = [t * ci for ci in c]
h = [[0.0] * k for _ in range(k)]
for lmi in lmis:
gi = inv(_value(lmi, x))
a = [mul(gi, gj) for gj in lmi[1]]
size = len(gi)
for p in range(k):
ap = a[p]
g[p] -= sum(ap[i][i] for i in range(size))
for q in range(p, k):
aq = a[q]
s = sum(ap[i][j] * aq[j][i] for i in range(size) for j in range(size))
h[p][q] += s
if q != p:
h[q][p] += s
dx = solve(h, [-v for v in g])
slope = sum(a * b for a, b in zip(g, dx))
if -slope / 2.0 <= tol:
break
f0 = _objective(c, t, lmis, x)
step = 1.0
while True:
xn = [xi + step * di for xi, di in zip(x, dx)]
fn = _objective(c, t, lmis, xn)
if fn is not None and fn <= f0 + 0.25 * step * slope:
break
step *= 0.5
if step < 1e-14:
return x
x = xn
if stop is not None and stop(x):
return x
return x
def sdp_minimize(c, lmis, x, eps=1e-8, mu=8.0):
"""Minimize c^T x over the LMIs from a strictly feasible x (barrier method)."""
total = sum(len(lmi[0]) for lmi in lmis)
t = 1.0
while True:
x = _center(c, t, lmis, x) # @line L10
if total / t < eps: # @line L11
return x
t *= mu
def sdp_center(lmis, x):
"""Analytic center of the LMIs, from a strictly feasible x."""
return _center([0.0] * len(x), 1.0, lmis, x)
def sdp_feasible(lmis, x0, eps=1e-9):
"""Phase I: return a strictly feasible x, or None if min s > 0.
Solves min s subject to G_i(x) + s I > 0, starting at x0 with s large.
The LMIs must bound x, or min s may be unbounded; the callers add a
bound constraint.
"""
k = len(x0)
aug = [(g0, gs + [eye(len(g0))]) for g0, gs in lmis]
s = 1.0
while _objective([0.0] * (k + 1), 0.0, aug, list(x0) + [s]) is None:
s *= 2.0
s *= 2.0 # now G_i(x0) + s I >= (s / 2) I
c = [0.0] * k + [1.0]
done = (lambda z: z[-1] < 0.0)
total = sum(len(lmi[0]) for lmi in aug)
z = list(x0) + [s]
t = 1.0
while True: # @line L9
z = _center(c, t, aug, z, stop=done)
if z[-1] < 0.0:
return z[:-1]
# On the central path, min s >= s(t) - total / t.
if z[-1] - total / t > 0.0 or total / t < eps:
return None
t *= 8.0
# ------------------------------------------------------- the H-infinity LMIs
def _svec_size(n):
return n * (n + 1) // 2
def _smat(v, n):
m = [[0.0] * n for _ in range(n)]
idx = 0
for i in range(n):
for j in range(i, n):
m[i][j] = m[j][i] = v[idx]
idx += 1
return m
def _dims(p):
n = len(p["A"])
return n, len(p["B1"][0]), len(p["B2"][0]), len(p["C1"]), len(p["C2"])
def gamma_lmis(p, gamma=None, bound=1e3):
"""The three LMIs of Gahinet and Apkarian, plus a bound, as SDP data.
The variable is x = (svec R, svec S) and, if gamma is None, also gamma.
"""
a, b1, b2, c1, c2 = (_flo(p[k]) for k in ("A", "B1", "B2", "C1", "C2"))
d11, d12, d21 = (_flo(p[k]) for k in ("D11", "D12", "D21"))
n, m1, m2, p1, p2 = _dims(p)
q = _svec_size(n)
nr = null_space(block([[transpose(b2), transpose(d12)]])) # @line L1
ns = null_space(block([[c2, d21]]))
k = 2 * q + (1 if gamma is None else 0)
def split(x):
g = x[2 * q] if gamma is None else gamma
return _smat(x[:q], n), _smat(x[q:2 * q], n), g
def lmi_r(x):
r, _, g = split(x)
mid = block([[add(mul(a, r), mul(r, transpose(a))), mul(r, transpose(c1)), b1],
[mul(c1, r), scale(-g, eye(p1)), d11],
[transpose(b1), transpose(d11), scale(-g, eye(m1))]])
w = block([[nr, zeros(n + p1, m1)], [zeros(m1, len(nr[0])), eye(m1)]])
return scale(-1.0, mul(mul(transpose(w), mid), w))
def lmi_s(x):
_, s, g = split(x)
mid = block([[add(mul(transpose(a), s), mul(s, a)), mul(s, b1), transpose(c1)],
[mul(transpose(b1), s), scale(-g, eye(m1)), transpose(d11)],
[c1, d11, scale(-g, eye(p1))]])
w = block([[ns, zeros(n + m1, p1)], [zeros(p1, len(ns[0])), eye(p1)]])
return scale(-1.0, mul(mul(transpose(w), mid), w))
def coupling(x):
r, s, _ = split(x)
return block([[r, eye(n)], [eye(n), s]])
def box(x):
r, s, g = split(x)
tr = sum(r[i][i] + s[i][i] for i in range(n))
return [[bound - tr - (g if gamma is None else 0.0)]]
lmis = [affine(f, k) for f in (lmi_r, lmi_s, coupling, box)]
x0 = [0.0] * k
for i in range(n): # R = S = I as a start
x0[_svec_index(i, i, n)] = 1.0
x0[q + _svec_index(i, i, n)] = 1.0
if gamma is None:
x0[-1] = 1.0
return lmis, x0, split
def _svec_index(i, j, n):
i, j = min(i, j), max(i, j)
return i * n - i * (i - 1) // 2 + (j - i)
def optimal_gamma(p, eps=1e-8):
"""Return (gamma_opt, R, S) from min gamma subject to the three LMIs."""
lmis, x0, split = gamma_lmis(p)
x = sdp_feasible(lmis, x0)
if x is None:
raise ValueError("no stabilizing controller within the bound")
c = [0.0] * (len(x) - 1) + [1.0]
x = sdp_minimize(c, lmis, x, eps) # @line L2
r, s, g = split(x)
return g, r, s
def reconstruct_x(r, s):
"""X_cl > 0 with (X_cl)_11 = S and (X_cl^-1)_11 = R, taking M = I."""
n = len(r)
nn = sub(eye(n), mul(s, r)) # @line L5
w = _sym(sub(mul(mul(r, s), r), r))
return block([[s, nn], [transpose(nn), w]]) # @line L6
def _closed_loop_mats(p, omega):
a, b1, b2, c1, c2 = (_flo(p[k]) for k in ("A", "B1", "B2", "C1", "C2"))
d11, d12, d21 = (_flo(p[k]) for k in ("D11", "D12", "D21"))
n, m1, m2, p1, p2 = _dims(p)
ak = [row[:n] for row in omega[:n]]
bk = [row[n:] for row in omega[:n]]
ck = [row[:n] for row in omega[n:]]
dk = [row[n:] for row in omega[n:]]
acl = block([[add(a, mul(mul(b2, dk), c2)), mul(b2, ck)], [mul(bk, c2), ak]])
bcl = block([[add(b1, mul(mul(b2, dk), d21))], [mul(bk, d21)]])
ccl = block([[add(c1, mul(mul(d12, dk), c2)), mul(d12, ck)]])
dcl = add(d11, mul(mul(d12, dk), d21))
return acl, bcl, ccl, dcl
def closed_loop(p, k):
"""Closed loop (A, B, C, D) from w to z with u = K y."""
ak, bk, ck, dk = (_flo(m) for m in k)
omega = block([[ak, bk], [ck, dk]])
return _closed_loop_mats(p, omega)
def controller_lmi(p, xcl, gamma, bound=1e3):
"""Find Omega = [[A_K, B_K], [C_K, D_K]] with the bounded real LMI < 0."""
n, m1, m2, p1, p2 = _dims(p)
rows, cols = n + m2, n + p2
k = rows * cols
def unpack(x):
return [[x[i * cols + j] for j in range(cols)] for i in range(rows)]
def brl(x):
acl, bcl, ccl, dcl = _closed_loop_mats(p, unpack(x))
top = add(mul(transpose(acl), xcl), mul(xcl, acl))
mid = block([[top, mul(xcl, bcl), transpose(ccl)],
[mul(transpose(bcl), xcl), scale(-gamma, eye(m1)), transpose(dcl)],
[ccl, dcl, scale(-gamma, eye(p1))]])
return scale(-1.0, mid)
def frob(x):
return block([[scale(bound, eye(k)), [[v] for v in x]], [[list(x)], [[bound]]]])
lmis = [affine(brl, k), affine(frob, k)]
x = sdp_feasible(lmis, [0.0] * k) # @line L7
if x is None:
return None
x = sdp_center(lmis, x)
om = unpack(x)
return ([row[:n] for row in om[:n]], [row[n:] for row in om[:n]],
[row[:n] for row in om[n:]], [row[n:] for row in om[n:]])
def lmi_synthesis(p, backoff=1.05, gopt=None):
"""Return (gamma_opt, gamma, K, X_cl) with K built at gamma = backoff * gamma_opt.
A known gamma_opt can be passed in to skip the first SDP.
"""
if gopt is None:
gopt, _, _ = optimal_gamma(p)
gamma = backoff * gopt # @line L3
lmis, x0, split = gamma_lmis(p, gamma)
x = sdp_feasible(lmis, x0)
x = sdp_center(lmis, x) # @line L4
r, s, _ = split(x)
xcl = reconstruct_x(r, s)
k = controller_lmi(p, xcl, gamma)
return gopt, gamma, k, xcl # @line L8
test_lmi_h_infinity_synthesis.py 159 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lmi-h-infinity-synthesis/. The authors are listed in prov/HWW5GT.jsonl.
import math
import random
import ctlmat as cm
from lmi_h_infinity_synthesis import (
_value,
chol,
closed_loop,
controller_lmi,
gamma_lmis,
is_hurwitz,
lmi_synthesis,
null_space,
optimal_gamma,
reconstruct_x,
sdp_center,
sdp_feasible,
)
def scalar_plant(a):
# x' = a x + w1 + u, z = (x, u), y = x + w2
return {"A": [[a]], "B1": [[1, 0]], "B2": [[1]], "C1": [[1], [0]], "C2": [[1]],
"D11": [[0, 0], [0, 0]], "D12": [[0], [1]], "D21": [[0, 1]]}
SCALAR = {a: scalar_plant(a) for a in (-1, 0, 1, 2)}
PLANT2 = {"A": [[0, 1], [2, -1]], "B1": [[1, 0, 0], [0, 1, 0]], "B2": [[0], [1]],
"C1": [[1, 0], [0, 1], [0, 0]], "C2": [[1, 0]], "D11": [[0, 0, 0]] * 3,
"D12": [[0], [0], [1]], "D21": [[0, 0, 1]]}
# Reference: the two-Riccati synthesis page computes gamma_opt for PLANT2 by
# bisection on its three conditions (relative tolerance 1e-9).
PLANT2_GAMMA = 7.2145628072
# A singular problem: z = x has no control weight, so D12 = 0 and the
# two-Riccati method does not apply.
SINGULAR = {"A": [[1]], "B1": [[1, 0]], "B2": [[1]], "C1": [[1]], "C2": [[1]],
"D11": [[0, 0]], "D12": [[0]], "D21": [[0, 1]]}
FREQS = [10 ** (e / 40) for e in range(-160, 161)] + [0.0]
_CACHE = {}
def opt(p):
# The SDPs take a moment in pure Python, so each one runs once.
key = ("opt", id(p))
if key not in _CACHE:
_CACHE[key] = optimal_gamma(p)
return _CACHE[key]
def synth(p):
key = ("synth", id(p))
if key not in _CACHE:
_CACHE[key] = lmi_synthesis(p, gopt=opt(p)[0])
return _CACHE[key]
def peak(sys):
a, b, c, d = sys
n = len(a)
best = 0.0
for w in FREQS:
m = [[(1j * w if i == j else 0.0) - a[i][j] for j in range(n)] for i in range(n)]
g = cm.add(cm.mul(c, cm.solve(m, [[complex(v) for v in row] for row in b])), d)
best = max(best, cm.norm2(g))
return best
def min_pivot(m):
low = chol(m)
return 0.0 if low is None else min(low[i][i] for i in range(len(low))) ** 2
def test_ctlmat_self_test():
assert cm._self_test()
def test_null_space_is_an_orthonormal_kernel_basis():
rng = random.Random(3)
for rows, cols in ((1, 3), (2, 5), (3, 4)):
m = [[rng.uniform(-1, 1) for _ in range(cols)] for _ in range(rows)]
n = null_space(m)
k = len(n[0])
assert k == cols - rows
assert max(abs(v) for row in cm.mul(m, n) for v in row) < 1e-12
g = cm.mul(cm.transpose(n), n)
assert max(abs(g[i][j] - (i == j)) for i in range(k) for j in range(k)) < 1e-12
def test_scalar_optimum_matches_the_closed_form():
for a, p in SCALAR.items():
g, r, s = opt(p)
assert abs(g - (a + math.sqrt(a * a + 2))) < 1e-7 * g
# At the optimum the coupling constraint is active: R = S = 1.
assert abs(r[0][0] - 1) < 1e-6 and abs(s[0][0] - 1) < 1e-6
def test_two_state_optimum_matches_the_riccati_method():
g, _, _ = opt(PLANT2)
assert abs(g - PLANT2_GAMMA) < 1e-7 * PLANT2_GAMMA
def test_feasible_above_and_infeasible_below_the_optimum():
for p in (SCALAR[1], PLANT2):
g = opt(p)[0]
lmis, x0, _ = gamma_lmis(p, 0.99 * g)
assert sdp_feasible(lmis, x0) is None
lmis, x0, _ = gamma_lmis(p, 1.01 * g)
x = sdp_center(lmis, sdp_feasible(lmis, x0))
# A certificate: every LMI is positive definite with a clear margin.
assert all(min_pivot(_value(lmi, x)) > 1e-6 for lmi in lmis)
def test_reconstruction_of_the_closed_loop_lyapunov_matrix():
p = PLANT2
lmis, x0, split = gamma_lmis(p, 1.05 * opt(p)[0])
r, s, _ = split(sdp_center(lmis, sdp_feasible(lmis, x0)))
xcl = reconstruct_x(r, s)
n = len(r)
assert cm.is_pos_def(xcl)
xi = cm.inv(xcl)
big = 1 + max(abs(v) for row in r for v in row)
assert max(abs(xcl[i][j] - s[i][j]) for i in range(n) for j in range(n)) < 1e-12
assert max(abs(xi[i][j] - r[i][j]) for i in range(n) for j in range(n)) < 1e-8 * big
def test_controllers_meet_the_bound():
for p in (SCALAR[0], SCALAR[1], PLANT2):
gopt, g, k, xcl = synth(p)
cl = closed_loop(p, k)
assert is_hurwitz(cl[0])
pk = peak(cl)
assert gopt * (1 - 1e-4) <= pk < g
def test_controller_lmi_is_infeasible_below_the_level():
# With X_cl fixed, the bounded real LMI in Omega has no solution at a
# level below gamma_opt, since a solution would give a better controller.
p = SCALAR[1]
gopt, g, k, xcl = synth(p)
assert controller_lmi(p, xcl, 0.98 * gopt) is None
def test_singular_problem():
# For any stabilizing K, the map from w2 to z equals -1 at s = 1, the
# unstable pole, so gamma_opt >= 1 by the maximum modulus principle.
g, r, s = opt(SINGULAR)
assert 1.0 <= g < 1.01
gopt, gk, k, _ = synth(SINGULAR)
cl = closed_loop(SINGULAR, k)
assert is_hurwitz(cl[0])
assert 1.0 - 1e-6 <= peak(cl) < gk
History
The bounded real lemma and its LMI form were known from the 1970s, and LMIs for state feedback were in use by the late 1980s (Boyd, El Ghaoui, Feron and Balakrishnan 1994). In 1994, Gahinet and Apkarian and, independently, Iwasaki and Skelton reduced output feedback H-infinity synthesis to LMIs in two matrices. Packard (1994) and Apkarian, Gahinet and Becker (1995) used the same ideas for gain scheduling. Scherer, Gahinet and Chilali (1997) extended the approach to several objectives at once. Efficient interior point solvers for SDPs, from the work of Nesterov and Nemirovskii, made these results practical.
References
- Pascal Gahinet and Pierre Apkarian, A linear matrix inequality approach to H-infinity control, International Journal of Robust and Nonlinear Control 4(4), 421-448, 1994, the projected LMIs in R and S, the coupling LMI, and the construction of the controller from a solution
- Tetsuya Iwasaki and Robert E. Skelton, All controllers for the general H-infinity control problem, LMI existence conditions and state space formulas, Automatica 30(8), 1307-1317, 1994, the same existence conditions, derived independently, and the set of all controllers
- Carsten Scherer, Pascal Gahinet and Mahmoud Chilali, Multiobjective output-feedback control via LMI optimization, IEEE Transactions on Automatic Control 42(7), 896-911, 1997, the change of variables that makes synthesis LMIs linear with several objectives and pole region constraints
- Stephen Boyd, Laurent El Ghaoui, Eric Feron and Venkataramanan Balakrishnan, Linear Matrix Inequalities in System and Control Theory, SIAM, 1994, the bounded real lemma as an LMI, interior point methods for LMI problems, and state feedback synthesis by LMIs
- Pascal Gahinet, Explicit controller formulas for LMI-based H-infinity synthesis, Automatica 32(7), 1007-1014, 1996, closed formulas for a controller from a solution R, S of the synthesis LMIs
- Pierre Apkarian, Pascal Gahinet and Greg Becker, Self-scheduled H-infinity control of linear parameter-varying systems, a design example, Automatica 31(9), 1251-1261, 1995, the LMI synthesis conditions extended to gain-scheduled controllers for LPV plants
- Stephen Boyd and Lieven Vandenberghe, Convex Optimization, Cambridge University Press, 2004, Chapter 11, Interior-point methods (the barrier method, phase I and its complexity analysis)
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 HWW5GT Edit this page History Report an error Markdown