Algorithmadvanced
H-infinity norm computation by bisection
Also called Boyd-Balakrishnan-Bruinsma-Steinbuch algorithm, Hamiltonian bisection for the H-infinity norm.
Decides whether the H-infinity norm of a system with A Hurwitz is at least gamma from the imaginary eigenvalues of a Hamiltonian matrix, then bisects on gamma or raises gamma by the level set method.
- Time
- O((n + m + p)^3 log(n / e)) worst
- Space
- O((n + m + p)^2) extra
- Where
- e = the relative accuracy (epsilon on the page); m = the number of inputs; n = the state dimension; p = the number of outputs
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Stephen Boyd, Venkataramanan Balakrishnan, Pierre Kabamba, N. A. Bruinsma, Maarten Steinbuch, 1989
H-infinity norm computation finds the H-infinity norm of a linear system with a Hurwitz state matrix, the peak over all frequencies of the largest singular value of its transfer matrix, to a chosen relative accuracy. It does not search over frequency. Instead it answers the question "is the norm at least gamma?" exactly, by checking whether a Hamiltonian matrix built from the state-space data has an eigenvalue on the imaginary axis. Boyd, Balakrishnan and Kabamba (1989) used this test inside a bisection on gamma, and Bruinsma and Steinbuch (1990) used the frequencies of the imaginary eigenvalues to raise gamma at each step, which converges quadratically.
In plain words
A system whose free motion dies out amplifies some input signals more than others, and the amount depends on how fast the input oscillates. The H-infinity norm is the largest amplification over all inputs and all speeds. You could test many speeds one by one, but you can miss a narrow peak between two test points. This method asks a different question: is there any speed at which the amplification reaches a given level? A small matrix built from the system answers this question with certainty, and it also tells you at which speeds the amplification crosses that level. Bisection then halves the range of possible levels until it is small enough. The faster variant uses the crossing speeds: the peak lies between two crossings, so it tests the middle of each such gap and moves the level up to the best value found.
The problem
Input. Real matrices , , and of the system , , with Hurwitz, and a relative accuracy . The realization need not be minimal.
Output. Numbers with
where is the transfer function and , with the largest singular value. The level set method also returns a frequency (possibly ) with .
The test. For that is not a singular value of , let and
If has no imaginary eigenvalue, then is a singular value of exactly when is an eigenvalue of . With Hurwitz and it follows that if and only if has an imaginary eigenvalue. The characteristic polynomial of is even, with , so the imaginary eigenvalues are the real roots of .
The algorithm
IMAGINARY-FREQUENCIES(A, B, C, D, γ)- 1
M ← [[D, -γ I_p], [-γ I_m, D^T]]; H ← [[A, 0], [0, -A^T]] + [[B, 0], [0, -C^T]] M^(-1) [[-C, 0], [0, -B^T]] - 2
r ← the polynomial of degree n with det(sI - H) = r(s²) - 3
return the sorted list of ω = √(-t) for the real roots t ≤ 0 of r HINF-BISECTION(A, B, C, D, ε)- 4
check that A is Hurwitz; d ← σ_max(D) - 5
σ_1 ≥ ... ≥ σ_n ← the Hankel singular values, the square roots of the eigenvalues of W_c W_o - 6
lo ← max(d, σ_1); hi ← d + 2 (σ_1 + ... + σ_n) - 7
while hi - lo > 2ε lo - 8
γ ← (lo + hi) / 2 - 9
if IMAGINARY-FREQUENCIES(A, B, C, D, γ) is not empty then lo ← γ else hi ← γ - 10
return (lo, hi) HINF-LEVEL-SET(A, B, C, D, ε)- 11
check that A is Hurwitz; lb ← the largest of σ_max(D), σ_max(G(0)) and σ_max(G(j|λ|)) for the eigenvalues λ of A - 12
loop - 13
γ ← (1 + 2ε) lb; F ← IMAGINARY-FREQUENCIES(A, B, C, D, γ) - 14
if F is empty then return (lb, γ) - 15
ω_1 < ... < ω_k ← F together with -F; best ← max(lb, max over i < k of σ_max(G(j (ω_i + ω_(i+1)) / 2))) - 16
if best ≤ γ then return (best, γ) else lb ← best
Lines L1 to L3 are the test. Line L1 needs invertible, which holds for every ; both callers only use such levels. Line L2 drops the odd coefficients of the characteristic polynomial, which are zero in exact arithmetic. Line L3 turns each real root of into a frequency at which some singular value of equals . These crossings belong to any singular value, not only the largest one.
Lines L5 and L6 give the start interval. Here and are the controllability gramian and the observability gramian, from and . The norm is at least (its limit at infinity) and at least the largest Hankel singular value, and at most by the balanced truncation error bound with nothing kept. Lines L7 to L9 keep the norm in and halve the interval at each pass.
Line L11 starts the level set method from values of at three kinds of points: infinity, zero, and the moduli of the poles, where lightly damped peaks sit. Bruinsma and Steinbuch use a similar rule with one pole frequency. Each pass of lines L12 to L16 tests the level just above the current lower bound. If the test fails, the norm is below and the interval is the answer. If it passes, the frequencies where some singular value equals cut the axis into pieces. On every piece where both ends are crossings, so the midpoint of two consecutive crossings falls inside, and line L15 finds a value above . Line L15 uses negative frequencies too, so that a peak at , between and , is found.
The implementation forms , computes its characteristic polynomial with the Faddeev-LeVerrier algorithm, and finds the roots of with the Durand-Kerner method of the shared helper module. A root counts as real when and as nonpositive when . This is fine for the small of the tests (); a production code computes the eigenvalues of with a structure preserving variant of the QR algorithm.
Example
A lightly damped mode. Take , with damping ratio and natural frequency 1 rad/s, as , , and . The exact norm is , reached at rad/s. Here
The sum of the roots of is , so its real roots are negative whenever they exist, and they exist exactly when , that is . This matches the exact norm, as the test promises. The same follows from with .
The gramians are and , and the Hankel singular values are and . Line L6 gives and . The first passes of the bisection are:
| pass | γ | frequencies of line L3 (rad/s) | update |
|---|---|---|---|
| 1 | 6.40617 | none | hi ← 6.40617 |
| 2 | 4.58432 | 0.94374, 1.03409 | lo ← 4.58432 |
| 3 | 5.49525 | none | hi ← 5.49525 |
| 4 | 5.03978 | none | hi ← 5.03978 |
| 5 | 4.81205 | 0.95923, 1.01975 | lo ← 4.81205 |
| 6 | 4.92592 | 0.96946, 1.01003 | lo ← 4.92592 |
| 7 | 4.98285 | 0.97673, 1.00299 | lo ← 4.98285 |
| 8 | 5.01132 | 0.98244, 0.99741 | lo ← 5.01132 |
With the bisection stops after 27 passes with . The two crossing frequencies close in on the peak frequency from both sides as rises.
The level set method starts from , because both poles have modulus 1, against and .
| pass | γ | frequencies | midpoints | new lower bound |
|---|---|---|---|---|
| 1 | 5.0000001 | 0.979796, 1.000000 | 0, ±0.989898 | 5.02518842 at 0.989898 |
| 2 | 5.0251885 | 0.989902, 0.989997 | 0, ±0.989949 | 5.0251890763 at 0.989949 |
| 3 | 5.0251892 | none | stop |
It returns , and the lower end equals the exact norm to all printed digits. The error of the lower bound drops from (relative) after pass 1 to below after pass 2: the quadratic convergence of Boyd and Balakrishnan.
A realization that is not minimal. With , , and , the modes at and are not controllable, and . The Hankel singular values are , and , and both methods return the norm , reached at .
A peak at infinity. For , written as , , , , the gain rises from at toward 1 and never reaches it. The norm is . No level above 1 gives an imaginary eigenvalue, so the bisection shrinks to , and the level set method stops at once with .
Correctness
The proofs are in the correctness proof. They hold in exact arithmetic.
- Hamiltonian test (proved). If has no imaginary eigenvalue and is not a singular value of , then is a singular value of if and only if is an eigenvalue of . The proof turns a pair of singular vectors into an eigenvector with , and back.
- Even polynomial (proved). is symmetric for , so is similar to and is a polynomial in .
- Level test (proved). For Hurwitz and : if and only if has an imaginary eigenvalue. The proof uses the continuity of , its limit at infinity, and the intermediate value theorem.
- Bisection (proved). The interval always holds the norm, and the loop runs at most times, because the start interval has width at most .
- Level set (proved). The lower bound is always a value of , so it never exceeds the norm. A pass that does not stop raises it by a factor larger than , so the method stops. At a stop the norm is at most .
Proof: The Hamiltonian bisection and the level set iteration return an interval that holds the H-infinity normfull
Let with , , and , and let . The two procedures on the page assume that is Hurwitz, so has no pole in the closed right half plane and the norm is finite. All statements below hold in exact arithmetic. The last section says what changes in floating point.
For that is not a singular value of , the matrix
is invertible (a vector in its kernel has and , so it is zero unless is a singular value of ). Define
For this is .
Lemma 1 (singular values and imaginary eigenvalues)
Assume that has no eigenvalue on the imaginary axis and that is not a singular value of . Then for every real , is a singular value of if and only if is an eigenvalue of .
Proof. Write for the conjugate transpose. Since is real, .
() Let be a singular value of . Then there are vectors and , not both zero, with and . Put and . Both inverses exist because has no imaginary eigenvalue. Then
and the two singular value equations read and , that is
Solve this for and put it into the two differential equations. The result is . The vector is not zero: if and , the last display gives , so , which is false. So is an eigenvalue of .
() Let with . Define . The two block rows of the eigenvalue equation say and , so and . If then , which is false. The definition of gives and , that is and . If , the first equation gives ; so , and . So is a singular value of .
Lemma 2 (the characteristic polynomial is even)
Under the hypotheses of Lemma 1, for a real polynomial of degree . Hence is an eigenvalue of if and only if is a root of , and the imaginary eigenvalues of are exactly the numbers for the real roots of .
Proof. Let . We show that is symmetric. First, is symmetric. Next, write and . A direct product gives with the permutation , so . Now and
which is symmetric. The inverse of a symmetric matrix is symmetric, so is symmetric, and so is . Then gives , so . Thus is similar to , and with ,
A polynomial of even degree with has only even powers, so with . The coefficients are real because is real. The equivalence for follows from .
Lemma 3 (the level test)
Let be Hurwitz and . Then if and only if has an eigenvalue on the imaginary axis.
Proof. The function is continuous on , because has no pole on the imaginary axis and singular values depend continuously on the matrix. As , , so .
If : there is with for , so the supremum of is its maximum on , reached at some with . On the continuous function goes from a value at least to a value below , so for some . Then is a singular value of , and Lemma 1 gives the eigenvalue . (Every singular value of is at most , so Lemma 1 applies.)
If has an eigenvalue : Lemma 1 says that is a singular value of , so .
Lemma 4 (the start interval of the bisection)
Let be Hurwitz, and the solutions of and , and the square roots of the eigenvalues of (the Hankel singular values). Then
Proof. The first lower bound is the limit of at infinity. The second is the classical fact that the Hankel norm is the norm of the Hankel operator of , which maps past inputs to future outputs; this operator is a compression of the input-output map of on , whose induced norm is (Glover 1984, also Zhou, Doyle and Glover 1996, the chapter on Hankel norm approximation). The upper bound is the error bound of balanced truncation, , applied with , where , together with the triangle inequality (see the balanced truncation error bound; Enns 1984 and Glover 1984). A non-minimal realization only adds zero values to the list, because the nonzero eigenvalues of are those of a minimal realization.
Theorem 1 (bisection)
Let be Hurwitz and . HINF-BISECTION stops, and it returns with and . If , the loop runs at most times.
Proof. Invariant: and . It holds after line L6 by Lemma 4 (line L6 also sets to at least , which does not break the invariant, because then the norm equals ). In line L8, , because the loop runs only while . So Lemma 3 applies to : if line L9 finds an imaginary eigenvalue, then and the new keeps the invariant; if not, and the new keeps it.
Termination and count. If , then and all , so and the loop does not run; in this case . Otherwise each pass halves , and never decreases. The start width is , since and . After passes the width is at most , which is at most once . At exit the loop condition is false, so .
Theorem 2 (level set iteration)
Let be Hurwitz, , and let the start value of line L11 be positive. HINF-LEVEL-SET stops after at most passes of the loop, and it returns with for the value held at the start of the last pass, so . Here , or with .
Proof. Invariant: is a value of (or the limit ), so . Line L11 sets this way, and line L15 replaces it only by a larger value of at a midpoint.
The level is valid. Since and , the level is larger than , so Lemma 3 applies.
Exit at line L14. If has no imaginary eigenvalue, Lemma 3 gives .
Exit at line L16. Suppose has imaginary eigenvalues but every midpoint value is at most . We show that . Assume instead . The set is open, not empty, and bounded (because ). Let be one of its components. Then and are finite, and by continuity. By Lemma 1, and are eigenvalues of , so and are in the sorted list of line L15, which holds the frequencies of line L13 with both signs (the eigenvalues of the real matrix come in conjugate pairs, and ). Let ; then , and the midpoint lies in . Its value is larger than , which is false. So , and the returned is at least the old , so .
Progress. If the loop does not exit, line L16 found a midpoint value larger than , so the new is larger than times the old one. Since always, after such passes , which bounds .
The count in Theorem 2 is a worst case that grows like . Boyd and Balakrishnan (1990) proved much more: the lower bounds of the level set iteration converge quadratically to the norm. That result rests on the regularity of near a peak and is not reproved here.
Floating point
The implementation forms in floating point, computes with the Faddeev-LeVerrier recursion, keeps the even coefficients as , and finds the roots of with the Durand-Kerner method of the shared helper. A root counts as real when , and as nonpositive when . When is far from in relative terms, every root of is either clearly real and negative or clearly not, and the decision is the exact one. Near two real roots of merge into a double root, which the root finder computes with an error near ; the tolerance then accepts the pair as real, and a decision can be wrong only when is within about (relative) of the norm. Since the methods are stopped with in practice, such an error moves the returned interval by much less than its width. The tests compare the floating point decision with an exact count of the nonpositive roots of in rational arithmetic (a Sturm sequence) on random systems.
Complexity
The model is the real RAM, with the state dimension, the number of inputs, the number of outputs and the relative accuracy. Dense factorizations count as flops for a matrix, and the eigenvalues of a matrix count as , as is usual for the QR algorithm.
- One test (lines L1 to L3). Solving with costs , the products cost , and the eigenvalues cost . The implementation instead spends on the Faddeev-LeVerrier recursion and on Durand-Kerner iterations.
- Start of the bisection (lines L4 to L6). Two Lyapunov equations and the eigenvalues of cost with the Bartels-Stewart method (see the Lyapunov equation). The implementation solves the Kronecker system instead, in , which is fine for .
- Bisection. At most tests, so in all. The convergence is linear: one bit of accuracy per pass.
- Level set, per pass. One test, plus at most evaluations of at midpoints, because has at most roots. Each evaluation costs and a singular value computation . After a one time reduction of to Hessenberg form, each evaluation of costs .
- Level set, number of passes. The proved bound is , which is poor. The convergence result of Boyd and Balakrishnan (1990) is local and quadratic. In the tests of this page the level set method used 0 to 3 passes (a measurement, not a bound).
- Space. for the matrices.
Properties
- Certified interval. In exact arithmetic the output interval holds the norm. A frequency sweep only gives a lower bound, and it can miss a narrow peak by any amount.
- Independent of the realization. Uncontrollable or unobservable modes do not change , and they do not change the answer; they add eigenvalues of that are never on the imaginary axis when is Hurwitz.
- Peak frequency. The level set method returns a frequency at which the lower bound is reached. The bisection returns only the interval, but the crossings of its last successful test bracket a frequency near the peak.
- Not exact. The norm is in general an algebraic number with no closed form, so every method returns an interval.
- Deterministic. The same input gives the same output.
Variants and improvements
- Level set iteration. Lines L11 to L16, from Bruinsma and Steinbuch (1990) and Boyd and Balakrishnan (1990). It is the method used in practice, because it needs few passes.
- Discrete time. For with Schur, the frequencies are points on the unit circle. The Hamiltonian matrix becomes a symplectic matrix or pencil, and the test looks for its eigenvalues of modulus 1. A bilinear transform to continuous time is another way.
- Structure preserving eigenvalue solvers. A general eigenvalue solver can move a true imaginary eigenvalue of off the axis by rounding. Solvers that keep the Hamiltonian structure keep the eigenvalues in pairs , so a simple imaginary eigenvalue stays on the axis.
- Descriptor systems and large systems. The test extends to through a generalized eigenvalue problem with the QZ algorithm. For large sparse systems, only the eigenvalues near the imaginary axis are needed, and Krylov methods are used.
- Related levels. The same idea tests other quantities: the distance of a Hurwitz matrix to the set of unstable matrices (with ), and the bounded real lemma gives the Riccati and LMI forms of the same question "is the norm below gamma?".
When to use it
Use it whenever you need the H-infinity norm of a system with a state-space model: to check a robustness margin with the small-gain theorem, to report the peak of a sensitivity function, to check the result of an H-infinity synthesis, or as the inner test of a gamma iteration. For one lightly damped mode a sweep near the resonance gives a good lower bound, but only the Hamiltonian test certifies the upper bound. For the H2 norm no iteration is needed; one Lyapunov equation gives it.
Pitfalls
- A must be Hurwitz. If has an imaginary eigenvalue the norm is infinite or the test of Lemma 1 fails, and if has an eigenvalue in the right half plane the supremum over is the norm, not the H-infinity norm. Check first, as lines L4 and L11 do.
- Levels at or below the norm of D. At the matrix is singular, and below it the test is not valid. The start values keep every level above .
- Tangency is ill-conditioned. At two imaginary eigenvalues merge, and near this level they split by about the square root of the unit roundoff. A tolerance on the real part is needed; too small a tolerance turns a correct "yes" into "no" near the norm, and too large a tolerance turns a "no" into "yes". The implementation works on , where a crossing at is a simple root and stays well conditioned.
- Crossings of other singular values. For a system with several inputs and outputs, a frequency in line L3 can be a crossing of a smaller singular value. The bisection does not care, but a level set code that only uses pairs of crossings as intervals must use consecutive crossings, as line L15 does, and not assume that they alternate between rising and falling.
- Scaling. Badly scaled , , give a badly scaled . Balance the realization first.
- Sweeps are lower bounds. A grid of frequencies can miss a peak of width about by a large factor. Use a sweep only to check, never to bound the norm from 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()
h_infinity_norm_computation.py 170 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/h-infinity-norm-computation/. The authors are listed in prov/KBHPWA.jsonl.
"""H-infinity norm of a stable state-space system by Hamiltonian tests.
The system is x' = A x + B u, y = C x + D u with A Hurwitz (n by n), B
(n by m), C (p by n) and D (p by m). Matrices are lists of rows. The
transfer matrix is G(s) = C (s I - A)^(-1) B + D, and the H-infinity norm is
the supremum over real w of the largest singular value of G(j w).
The test behind both methods (pseudocode lines L1 to L3): for gamma larger
than the largest singular value of D, gamma is a singular value of G(j w)
if and only if j w is an eigenvalue of the Hamiltonian matrix
H = [[A, 0], [0, -A^T]] + [[B, 0], [0, -C^T]] M^(-1) [[-C, 0], [0, -B^T]],
M = [[D, -gamma I_p], [-gamma I_m, D^T]].
The characteristic polynomial of H is even, det(s I - H) = r(s^2), so the
imaginary eigenvalues j w are the real roots t = -w^2 <= 0 of r.
- hinf_norm_bisection: the bisection of Boyd, Balakrishnan and Kabamba
(1989), lines L4 to L10.
- hinf_norm_level_set: the level set iteration of Bruinsma and Steinbuch
(1990) and Boyd and Balakrishnan (1990), lines L11 to L16.
Both return an interval [lo, hi] that holds the norm, with
hi - lo <= 2 eps lo. Floating point tolerances: the characteristic
polynomial comes from ctlmat.charpoly and its roots from ctlmat.polyroots.
A root t of r is taken as real if |Im t| <= IMAG_TOL (1 + |t|), and as
nonpositive if Re t <= SIGN_TOL (1 + |t|). A double root of r (a tangent
of the singular value curve to the level gamma) is computed with an error
near 1e-8, so a decision can be wrong only when gamma is within about
1e-12 (relative) of the norm.
"""
import math
from ctlmat import (add, block, charpoly, eye, kron, mul, norm2, polyroots,
scale, solve, transpose, unvec, vec, zeros)
IMAG_TOL = 1e-6
SIGN_TOL = 1e-10
MAX_ITER = 500
def eigenvalues(a):
"""Eigenvalues of a small square matrix, as roots of its characteristic polynomial."""
return polyroots(charpoly([[float(v) for v in row] for row in a]))
def is_hurwitz(a):
"""True if every eigenvalue of a has a negative real part."""
return all(lam.real < 0 for lam in eigenvalues(a))
def freq_response(A, B, C, D, w):
"""Return G(j w) = C (j w I - A)^(-1) B + D as a complex matrix."""
n = len(A)
jwa = [[(1j * w if i == j else 0) - A[i][j] for j in range(n)] for i in range(n)]
x = solve(jwa, [[complex(v) for v in row] for row in B])
g = mul(C, x)
return [[g[i][j] + D[i][j] for j in range(len(D[0]))] for i in range(len(D))]
def sigma_max(A, B, C, D, w):
"""Largest singular value of G(j w)."""
return norm2(freq_response(A, B, C, D, w))
def hamiltonian(A, B, C, D, gamma):
"""The Hamiltonian matrix H_gamma (exact when the data and gamma are int or Fraction)."""
n, m, p = len(A), len(B[0]), len(C)
big_m = block([[D, scale(-gamma, eye(p))], [scale(-gamma, eye(m)), transpose(D)]])
right = block([[scale(-1, C), zeros(p, n)], [zeros(m, n), scale(-1, transpose(B))]])
left = block([[B, zeros(n, p)], [zeros(n, m), scale(-1, transpose(C))]])
h0 = block([[A, zeros(n)], [zeros(n), scale(-1, transpose(A))]])
return add(h0, mul(left, solve(big_m, right)))
def even_polynomial(h):
"""The coefficients of r with det(s I - h) = r(s^2), highest power first."""
c = charpoly(h)
return [c[k] for k in range(0, len(c), 2)]
def imaginary_frequencies(A, B, C, D, gamma):
"""The w >= 0 such that j w is an eigenvalue of H_gamma, sorted."""
h = hamiltonian(A, B, C, D, gamma) # @line L1
r = even_polynomial([[float(v) for v in row] for row in h]) # @line L2
out = []
for t in polyroots(r): # @line L3
if abs(t.imag) <= IMAG_TOL * (1 + abs(t)) and t.real <= SIGN_TOL * (1 + abs(t)):
out.append(math.sqrt(max(0.0, -t.real)))
return sorted(out)
def gramians(A, B, C):
"""Controllability and observability gramians of a Hurwitz A.
A W_c + W_c A^T + B B^T = 0 and A^T W_o + W_o A + C^T C = 0, solved
through the Kronecker form (I kron A + A kron I) vec(W) = -vec(B B^T).
"""
n = len(A)
at = transpose(A)
k_c = add(kron(eye(n), A), kron(A, eye(n)))
k_o = add(kron(eye(n), at), kron(at, eye(n)))
wc = unvec(solve(k_c, [-v for v in vec(mul(B, transpose(B)))]), n)
wo = unvec(solve(k_o, [-v for v in vec(mul(transpose(C), C))]), n)
return wc, wo
def hankel_singular_values(A, B, C):
"""Square roots of the eigenvalues of W_c W_o, largest first."""
wc, wo = gramians(A, B, C)
lam = eigenvalues(mul(wc, wo))
return sorted((math.sqrt(max(v.real, 0.0)) for v in lam), reverse=True)
def hinf_norm_bisection(A, B, C, D, eps=1e-8):
"""Bisection on gamma. Returns (lo, hi, iterations) with lo <= norm <= hi."""
if not is_hurwitz(A): # @line L4
raise ValueError("A is not Hurwitz")
d = norm2(D)
hsv = hankel_singular_values(A, B, C) # @line L5
lo = max(d, hsv[0]) # @line L6
hi = max(lo, d + 2 * sum(hsv))
iterations = 0
while hi - lo > 2 * eps * lo: # @line L7
gamma = (lo + hi) / 2 # @line L8
if imaginary_frequencies(A, B, C, D, gamma): # @line L9
lo = gamma
else:
hi = gamma
iterations += 1
return lo, hi, iterations # @line L10
def hinf_norm_level_set(A, B, C, D, eps=1e-8):
"""Level set iteration. Returns (lo, hi, w, iterations).
lo is the largest singular value of G(j w) at the returned w (w is
math.inf when lo comes from D), and lo <= norm <= hi.
"""
if not is_hurwitz(A): # @line L11
raise ValueError("A is not Hurwitz")
lb, w_lb = norm2(D), math.inf
for w in [0.0] + [abs(lam) for lam in eigenvalues(A)]:
s = sigma_max(A, B, C, D, w)
if s > lb:
lb, w_lb = s, w
if lb == 0:
raise ValueError("G is zero at 0, at infinity and at the pole moduli; use the bisection")
iterations = 0
while iterations < MAX_ITER: # @line L12
gamma = (1 + 2 * eps) * lb # @line L13
freqs = imaginary_frequencies(A, B, C, D, gamma)
if not freqs: # @line L14
return lb, gamma, w_lb, iterations
iterations += 1
ws = sorted([-w for w in freqs] + freqs) # @line L15
best, w_best = lb, w_lb
for a, b in zip(ws, ws[1:]):
mid = abs((a + b) / 2)
s = sigma_max(A, B, C, D, mid)
if s > best:
best, w_best = s, mid
if best <= gamma: # @line L16
return best, gamma, w_best, iterations
lb, w_lb = best, w_best
raise RuntimeError("level set iteration did not stop")
test_h_infinity_norm_computation.py 237 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/h-infinity-norm-computation/. The authors are listed in prov/KBHPWA.jsonl.
import math
import random
from fractions import Fraction
import pytest
from ctlmat import charpoly, mul, polyder, polyroots, transpose
from h_infinity_norm_computation import (even_polynomial, freq_response, hamiltonian,
hankel_singular_values, hinf_norm_bisection,
hinf_norm_level_set, imaginary_frequencies,
sigma_max)
# Tolerances: both methods run with eps = 1e-8, so the returned interval has
# relative width at most 2e-8; values are compared with a relative
# tolerance of 1e-7. The frequency sweep is a lower bound of the norm; it
# must not exceed the upper end of the interval by more than 1e-9
# (relative), and on these systems it comes within 1e-6 of the lower end.
EPS = 1e-8
F = Fraction
FIRST_ORDER = ([[-1]], [[1]], [[1]], [[0]]) # 1 / (s + 1)
LIGHT = ([[0, 1], [-1, F(-1, 5)]], [[0], [1]], [[1, 0]], [[0]]) # 1 / (s^2 + 0.2 s + 1)
NON_MINIMAL = ([[-4, -8, 12], [0, -8, 0], [0, 0, -16]], [[1], [0], [0]], [[1, 1, 1]], [[0]])
PEAK_AT_ZERO = ([[-1]], [[1]], [[1]], [[1]]) # (s + 2) / (s + 1)
PEAK_AT_INFINITY = ([[-2]], [[1]], [[-1]], [[1]]) # (s + 1) / (s + 2)
LIGHT_NORM = 1 / (0.2 * math.sqrt(1 - 0.01)) # 1 / (2 zeta sqrt(1 - zeta^2))
def close(x, y, tol=1e-7):
return abs(x - y) <= tol * max(1.0, abs(y))
def random_system(rng):
"""A random rational system with n <= 3, m, p <= 2 and A Hurwitz (max Re < -0.1)."""
while True:
n, m, p = rng.randint(1, 3), rng.randint(1, 2), rng.randint(1, 2)
a = [[F(rng.randint(-6, 6), 4) for _ in range(n)] for _ in range(n)]
for i in range(n):
a[i][i] = F(-rng.randint(2, 12), 4)
if max(r.real for r in polyroots(charpoly(a))) >= -0.1:
continue
b = [[F(rng.randint(-4, 4), 4) for _ in range(m)] for _ in range(n)]
c = [[F(rng.randint(-4, 4), 4) for _ in range(n)] for _ in range(p)]
d = [[F(rng.randint(-2, 2), 4) for _ in range(m)] for _ in range(p)]
if all(v == 0 for row in b for v in row) or all(v == 0 for row in c for v in row):
continue
return a, b, c, d
def sweep(sys, points=1201):
"""A lower bound of the norm: a log grid from 1e-3 to 1e3, the value at 0
and at infinity (sigma_max(D)), and a golden section refinement around the
best grid point."""
a, b, c, d = sys
grid = [10 ** (-3 + 6 * k / (points - 1)) for k in range(points)]
vals = [sigma_max(a, b, c, d, w) for w in grid]
k = max(range(points), key=lambda i: vals[i])
best = max(vals[k], sigma_max(a, b, c, d, 0.0), sigma_max(a, b, c, d, 1e9))
lo, hi = grid[max(k - 1, 0)], grid[min(k + 1, points - 1)]
g = (math.sqrt(5) - 1) / 2
x1, x2 = hi - g * (hi - lo), lo + g * (hi - lo)
f1, f2 = sigma_max(a, b, c, d, x1), sigma_max(a, b, c, d, x2)
for _ in range(80):
if f1 > f2:
hi, x2, f2 = x2, x1, f1
x1 = hi - g * (hi - lo)
f1 = sigma_max(a, b, c, d, x1)
else:
lo, x1, f1 = x1, x2, f2
x2 = lo + g * (hi - lo)
f2 = sigma_max(a, b, c, d, x2)
return max(best, f1, f2)
def singular_values(g):
"""Singular values of a complex matrix with at most 2 columns, from G^H G."""
gh = [[v.conjugate() for v in row] for row in transpose(g)]
q = mul(gh, g)
if len(q) == 1:
return [math.sqrt(max(q[0][0].real, 0.0))]
a, d, b = q[0][0].real, q[1][1].real, q[0][1]
mid, rad = (a + d) / 2, math.sqrt(((a - d) / 2) ** 2 + abs(b) ** 2)
return [math.sqrt(max(mid + rad, 0.0)), math.sqrt(max(mid - rad, 0.0))]
def sturm_count_nonpositive(r):
"""Number of distinct real roots of the Fraction polynomial r in (-inf, 0]."""
seq = [r, polyder(r)]
while len(seq[-1]) > 1 or seq[-1][0] != 0:
num, den = list(seq[-2]), seq[-1]
if len(den) == 1 and den[0] == 0:
break
while len(num) >= len(den) and any(v != 0 for v in num):
f = num[0] / den[0]
for i in range(len(den)):
num[i] -= f * den[i]
num.pop(0)
while len(num) > 1 and num[0] == 0:
num.pop(0)
if not num or all(v == 0 for v in num):
break
seq.append([-v for v in num])
def changes(signs):
s = [v for v in signs if v != 0]
return sum(1 for x, y in zip(s, s[1:]) if (x > 0) != (y > 0))
at_minus_inf = [p[0] * (-1) ** (len(p) - 1) for p in seq]
at_zero = [p[-1] for p in seq]
return changes(at_minus_inf) - changes(at_zero)
def test_check_value_first_order():
lo, hi, _ = hinf_norm_bisection(*FIRST_ORDER, eps=EPS)
assert lo <= 1.0 <= hi and hi - lo <= 2 * EPS * lo
lo, hi, w, _ = hinf_norm_level_set(*FIRST_ORDER, eps=EPS)
assert close(lo, 1.0) and w == 0.0
def test_check_value_light_damping():
lo, hi, _ = hinf_norm_bisection(*LIGHT, eps=EPS)
assert close(lo, LIGHT_NORM) and close(hi, LIGHT_NORM)
assert close(LIGHT_NORM, 5.02519, 1e-6)
lo, hi, w, _ = hinf_norm_level_set(*LIGHT, eps=EPS)
assert close(lo, LIGHT_NORM) and close(w, math.sqrt(0.98), 1e-6)
def test_even_polynomial_exact():
# r(t) = t^2 + 1.96 t + 1 - 1/gamma^2, in exact arithmetic.
for gamma in (F(1), F(5), F(11, 2)):
r = even_polynomial(hamiltonian(*LIGHT, gamma))
assert r == [1, F(49, 25), 1 - 1 / gamma ** 2]
def test_level_crossings_light_damping():
a, b, c, d = LIGHT
assert close(imaginary_frequencies(a, b, c, d, 1.0)[-1], 1.4, 1e-9)
w = imaginary_frequencies(a, b, c, d, 5.0)
assert len(w) == 2 and close(w[0], math.sqrt(0.96), 1e-9) and close(w[1], 1.0, 1e-9)
assert imaginary_frequencies(a, b, c, d, 5.03) == []
def test_non_minimal_realization():
# G = 1/(s + 4): the modes at -8 and -16 cancel.
for lo, hi in (hinf_norm_bisection(*NON_MINIMAL, eps=EPS)[:2],
hinf_norm_level_set(*NON_MINIMAL, eps=EPS)[:2]):
assert close(lo, 0.25) and close(hi, 0.25)
def test_feedthrough():
lo, hi, _ = hinf_norm_bisection(*PEAK_AT_ZERO, eps=EPS)
assert close(lo, 2.0) and close(hi, 2.0)
lo, hi, w, _ = hinf_norm_level_set(*PEAK_AT_ZERO, eps=EPS)
assert close(lo, 2.0) and w == 0.0
lo, hi, _ = hinf_norm_bisection(*PEAK_AT_INFINITY, eps=EPS)
assert close(lo, 1.0) and close(hi, 1.0)
lo, hi, w, _ = hinf_norm_level_set(*PEAK_AT_INFINITY, eps=EPS)
assert close(lo, 1.0) and w == math.inf
def test_not_hurwitz():
with pytest.raises(ValueError):
hinf_norm_bisection([[1]], [[1]], [[1]], [[0]])
with pytest.raises(ValueError):
hinf_norm_level_set([[0, 1], [-1, 0]], [[0], [1]], [[1, 0]], [[0]])
def test_random_systems():
rng = random.Random(20240611)
for _ in range(12):
sys = random_system(rng)
a, b, c, d = sys
n = len(a)
lo1, hi1, it = hinf_norm_bisection(*sys, eps=EPS)
lo2, hi2, w2, _ = hinf_norm_level_set(*sys, eps=EPS)
# The difference of two close floats carries a relative error near 1e-8.
assert hi1 - lo1 <= 2 * EPS * lo1 * (1 + 1e-6)
assert hi2 - lo2 <= 2 * EPS * lo2 * (1 + 1e-6)
# The two intervals hold the same number.
assert max(lo1, lo2) <= min(hi1, hi2) * (1 + 1e-9)
# The proved bound on the number of bisection steps.
assert it <= math.ceil(math.log2(n / EPS))
# The start interval of the bisection holds the norm.
hsv = hankel_singular_values(a, b, c)
sd = sigma_max(a, b, c, d, 1e12)
assert max(sd, hsv[0]) <= hi1 * (1 + 1e-9)
assert lo1 <= (sd + 2 * sum(hsv)) * (1 + 1e-9)
# The level set lower bound is a value of sigma_max.
if w2 != math.inf:
assert close(sigma_max(a, b, c, d, w2), lo2, 1e-12)
# A dense sweep never beats the upper bound, and it finds the peak.
s = sweep(sys)
assert s <= hi1 * (1 + 1e-9)
assert s >= lo1 * (1 - 1e-6)
def test_decision_against_exact_sturm_count():
rng = random.Random(7)
checked = 0
for _ in range(10):
sys = random_system(rng)
a, b, c, d = sys
lo, hi, _ = hinf_norm_bisection(*sys, eps=EPS)
sd = max(singular_values([[complex(v) for v in row] for row in d]))
for factor in (F(1, 2), F(4, 5), F(19, 20), F(21, 20), F(5, 4), F(2)):
gamma = F(lo).limit_denominator(10 ** 6) * factor
if gamma <= sd * 1.001:
continue
exact = even_polynomial(hamiltonian(a, b, c, d, gamma))
has_exact = sturm_count_nonpositive(exact) > 0
assert has_exact == (factor < 1)
assert bool(imaginary_frequencies(a, b, c, d, float(gamma))) == has_exact
checked += 1
assert checked >= 20
def test_frequencies_are_singular_values():
rng = random.Random(11)
for _ in range(10):
sys = random_system(rng)
a, b, c, d = sys
lo, _, _ = hinf_norm_bisection(*sys, eps=EPS)
sd = max(singular_values([[complex(v) for v in row] for row in d]))
gamma = 0.8 * lo
if gamma <= sd * 1.001:
continue
ws = imaginary_frequencies(a, b, c, d, gamma)
assert ws
for w in ws:
g = freq_response(a, b, c, d, w)
sv = singular_values(g) if len(g[0]) <= 2 else None
assert min(abs(s - gamma) for s in sv) <= 1e-6 * gamma
History
Before 1989 the H-infinity norm was found by sweeping the frequency or by a gamma iteration on a Riccati equation. Boyd, Balakrishnan and Kabamba (1989) showed that the question "is the norm at least gamma?" has an exact answer from the imaginary eigenvalues of a Hamiltonian matrix, and they used it in a bisection with the Hankel singular value bounds as the start interval. They also noted that the test applies to related problems, such as the distance to instability. In 1990 Bruinsma and Steinbuch used the crossing frequencies to raise the level, and Boyd and Balakrishnan proved that this level set iteration converges quadratically, from a regularity result on the largest singular value near a peak. The level set method is now the standard way to compute the norm.
References
- Stephen Boyd, Venkataramanan Balakrishnan and Pierre Kabamba, A bisection method for computing the H-infinity norm of a transfer matrix and related problems, Mathematics of Control, Signals, and Systems 2(3) (1989) 207-219, the whole paper (the Hamiltonian test for a level gamma and the bisection on gamma)
- N. A. Bruinsma and M. Steinbuch, A fast algorithm to compute the H-infinity-norm of a transfer function matrix, Systems and Control Letters 14(4), 287-293, 1990, the whole paper (the level set iteration with midpoints of the imaginary eigenvalues, and its start value)
- Stephen Boyd and Venkataramanan Balakrishnan, A regularity result for the singular values of a transfer matrix and a quadratically convergent algorithm for computing its L-infinity-norm, Systems and Control Letters 15(1), 1-7, 1990, the whole paper (the regularity of the largest singular value and the quadratic convergence of the level set iteration)
- Kemin Zhou, John C. Doyle and Keith Glover, Robust and Optimal Control, Prentice Hall, 1996, Chapter 4, Performance Specifications (the computation of the H2 and H-infinity norms), and Chapter 8, Hankel Norm Approximation (the bounds by the Hankel singular values)
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 KBHPWA Edit this page History Report an error Markdown