Algorithmadvanced
Balanced truncation
Also called Moore balanced truncation.
Reduces an asymptotically stable linear system by deleting the balanced states with small Hankel singular values, with a guaranteed H-infinity error bound.
- Solves
- Model order reduction
- Time
- O(n^3 + n^2 (m + p)) worst
- Space
- O(n^2) extra
- Where
- m = the number of inputs; n = the number of states; p = the number of outputs; r = the reduced order
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Bruce C. Moore, Lars Pernebo, Leonard M. Silverman, Dale F. Enns, Keith Glover, 1981
Balanced truncation makes a small model out of a large one. It applies to an asymptotically stable linear system, given by matrices , , , with internal states, and it returns a system with states whose response to every input is close to the original response. The method first measures, for each direction in the state space, how strongly the inputs drive it and how strongly the outputs show it. These two measures are matrices, the controllability Gramian and the observability Gramian. A change of coordinates, the balanced realization, makes them equal and diagonal. The diagonal entries, the Hankel singular values , rank the states, and the method keeps the first and deletes the rest. The result is guaranteed to be asymptotically stable, with Hurwitz, when , and its worst-case gain error over all frequencies, the H-infinity norm of , is at most twice the sum of the distinct deleted values (Enns 1984, Glover 1984). No model of order can do better than , so the method is within a factor of about of the best possible in the worst case, and usually much closer. Moore (1981) introduced it; it is the standard method of model order reduction for dense models with up to a few thousand states.
In plain words
A large model has many internal variables, but most of them matter little for what goes from the inputs to the outputs. Some are hard to move with the inputs. Others move but barely show in the outputs. A variable is worth keeping only if it is both easy to move and easy to see. The method first turns the model so that these two qualities are measured on the same scale for each internal direction. Then it sorts the directions by that common measure and throws away the weakest ones. The thrown-away measures also give a guarantee: the small model's error, for any input, is at most twice their sum.
The problem
Input: Hurwitz, , , and an order . Output: , , , , the Hankel singular values , and the bound
where and . The reduced model must be the truncation of a balanced realization of . If and , the cut would split a repeated value; the theorem then gives no guarantee, and the implementation refuses.
The algorithm
BALANCED-TRUNCATION(A, B, C, D, r)- 1
W_c, W_o ← solve A W_c + W_c Aᵀ + B Bᵀ = 0 and Aᵀ W_o + W_o A + Cᵀ C = 0 - 2
L_c, L_o ← factors with W_c = L_c L_cᵀ and W_o = L_o L_oᵀ - 3
U Σ Vᵀ ← SVD of L_oᵀ L_c ▷ σ_1 ≥ ... ≥ σ_n ≥ 0 - 4
if 0 < r < n and σ_r = σ_(r+1) then fail ▷ a gap is needed - 5
T_r ← L_c V_r Σ_r^(-1/2); W_r ← L_o U_r Σ_r^(-1/2) - 6
A_r ← W_rᵀ A T_r; B_r ← W_rᵀ B; C_r ← C T_r; D_r ← D - 7
bound ← 2 · (sum of the distinct values among σ_(r+1), ..., σ_n) - 8
return (A_r, B_r, C_r, D_r, σ, bound)
Line L1 solves the two Lyapunov equations for the Gramians. Libraries use the Bartels-Stewart method or Hammarling's method, which work on a Schur form of and cost . The implementation solves the Kronecker form directly, which costs and is used only for the small test systems. Line L2 takes square-root factors. Libraries take Cholesky factors, usually computed directly from the Lyapunov equation; the implementation uses from a symmetric eigendecomposition, which also works when a Gramian is singular. Line L3 is the square-root step of Laub, Heath, Paige and Ward (1987): the singular values of are the Hankel singular values. Line L4 checks the gap, with the tolerance in the code. Line L5 builds only the first columns of the balancing transformation and of , with and the first columns of and ; the full is never formed or inverted. Line L6 projects. Line L7 computes the bound, with values that agree within counted once.
Example
A chain of four first-order sections. , , , , so . Line L3 gives . The norm of is . The table lists, for each , the error measured on a frequency grid, the lower bound , the bound of line L7, the poles of and its gain at .
| (grid) | bound (L7) | poles of | |||
|---|---|---|---|---|---|
| 0 | 0.027988 | 0.041667 | 0.074791 | none | 0 |
| 1 | 0.0082179 | 0.014601 | 0.018816 | 0.055975 | |
| 2 | 0.0011269 | 0.0021479 | 0.0023804 | 0.039539 | |
| 3 | 0.0000632855 | 0.00012657 | 0.00012657 | , | 0.041793 |
Every error lies between and the bound, as the theorems require. For the error on the grid equals within , so the bound is attained (a measurement; the tests check it). The reduced poles are not a subset of the original poles : balanced truncation does not keep modes, it keeps directions. With the model has two states and a relative error of percent. The gain at is not kept: for it is instead of .
Two modes. For , the balanced realization page gives the balanced form; truncation to gives with error , again the bound, attained at .
Correctness
The full proof is in proofs/correctness.md. Its steps are theorems:
- The values are right. The singular values of are the square roots of the eigenvalues of , which has the same nonzero eigenvalues as .
- The projection is oblique and exact. From and follows .
- The reduced model is balanced. and . Multiplying the full Lyapunov equations by and , or by and , gives and .
- It is the truncation of a balanced realization. When the system is minimal, balances it, is its first columns and the first rows of , so is the leading block of the balanced realization.
- Stability and the bound. If , is Hurwitz (Pernebo and Silverman 1982) and the bound of line L7 holds (Enns 1984, Glover 1984). The proof is on the error bound page.
The tests check the Gramians by their Lyapunov residuals, the values against the square roots of the roots of on 500 random systems, the invariance under a change of coordinates, the balanced Gramians and the stability of , the error between and the bound on a grid, and the cases where the bound is attained.
Proof: The square root method returns a balanced reduced model with gramians diag(sigma_1, ..., sigma_r), and its error obeys the twice-the-tail boundfull
Let be Hurwitz, , and , with . The gramians are the unique solutions of
They are symmetric positive semidefinite, because and (see Lyapunov equation). The algorithm takes any square factors with and , and a singular value decomposition
with and orthogonal. For with , let and be the first columns of and , , and
Lemma 1: the sigma_i are the Hankel singular values
are the eigenvalues of , so the do not depend on the choice of factors.
Proof. . For square matrices and , and have the same characteristic polynomial. With and , , whose eigenvalues are .
Lemma 2: the two singular vector identities
and .
Proof. and . Take the first columns.
Lemma 3: the projection is oblique and exact on its range
, so is a projection and is the Petrov-Galerkin projection of onto along .
Proof. , by Lemma 2.
Lemma 4: the gramians act on the projection bases by Sigma_r
and .
Proof. . In the same way, . Both use Lemma 2.
Theorem 1: the reduced model is balanced
and .
Proof. Multiply the controllability equation on the left by and on the right by :
By Lemma 4, , and its transpose is . So the left side is . Multiply the observability equation on the left by and on the right by , and use and :
If is Hurwitz, the gramians of the reduced model are the unique solutions of these equations, so both are . The reduced model is then balanced, and its Hankel singular values are .
Theorem 2: the reduced model is the truncation of a balanced realization
Assume (the realization is minimal). Let . Then , the realization is balanced with both gramians equal to , and is its leading , and block.
Proof. Lemma 3 with gives , so this is the inverse. The new gramians are and . Lemma 4 with gives , where . So , and . The first columns of are and the first rows of are , so the leading blocks are , and .
Theorem 3: stability and the error bound
Assume and . Then is Hurwitz, and
where are the distinct values among .
Proof. By Theorem 2, is the truncation of a balanced realization of . The balanced truncation error bound theorem gives both claims for such a truncation; its proof is on that page. The lower bound holds for every model of order , not only for this one.
The checks in the implementation
The implementation raises ValueError when and , because then the hypothesis of Theorem 3 fails or cannot be decided in floating point. It also raises when , because does not exist. The function error_bound counts two computed values as one distinct value when they differ by at most . In exact arithmetic this is the bound of Theorem 3. In floating point, values that are equal in exact arithmetic come out with a small difference, and without the grouping the bound would count them twice and be up to twice too large.
For a realization that is not minimal (), Theorem 1 still holds, because its proof does not use . The tests check this case on a system with one uncontrollable state.
Complexity
With dense matrices, and counting floating-point operations:
- Line L1 costs by the Bartels-Stewart method; the Kronecker solve of the implementation costs time and space.
- Lines L2 and L3 cost , for the factorizations and the SVD.
- Lines L5 and L6 cost .
- Line L7 costs after the sort.
So the time is and the extra space is . The dense cost limits the method to about on one computer. For large sparse , low-rank factors and with few columns come from iterative Lyapunov solvers, and lines L3 to L6 then cost for factors with columns.
Rounding. In the floating-point model with unit roundoff , the SVD in line L3 is backward stable in the 2-norm: the computed values are the exact singular values of with , so each computed has absolute error relative to the computed factors (a theorem, see backward error analysis). The Lyapunov solvers give small residuals but are not backward stable in the Frobenius norm in general (Higham's analysis of the Sylvester equation). So values below about carry no information, and a cut there is not meaningful (a rule of thumb). Line L3 avoids forming , whose eigenvalues would lose the small values below instead.
Properties
- Asymptotic stability is kept, with Hurwitz, when (a theorem). Without the gap the truncated model can have poles on the imaginary axis.
- The error bound holds in the norm, with each distinct value counted once (a theorem). The error is also at least , as for every model of order (a theorem).
- The reduced model is balanced and minimal, with Hankel singular values (a theorem). So reducing further from gives the same result as reducing from .
- It does not depend on the realization. A change of coordinates of changes the Gramians by congruences and leaves the same, up to the sign freedom of the balanced realization (a theorem).
- High frequencies are matched. , and the error tends to zero as . The gain at is not matched in general.
- Not optimal. The result is not the best model of order in the , or Hankel norm. On the chain example, the iterative rational Krylov algorithm gives slightly smaller errors for (a measurement).
Variants and improvements
- Balanced singular perturbation approximation. Partition the balanced system and set instead of (see singular perturbation method). The result matches , keeps asymptotic stability and has the same error bound. Use it when the steady-state gain matters.
- Balancing-free square-root method. Replace and by orthonormal bases of the same column spaces, which gives a better conditioned projection with the same .
- Frequency-weighted balanced truncation (Enns 1984). Use the Gramians of the system with input and output weights. It is used for controller reduction. The general bound does not hold for it, and asymptotic stability can be lost unless the method is modified.
- Low-rank balanced truncation. For large sparse systems, compute low-rank Cholesky factors of the Gramians with alternating direction implicit or rational Krylov iterations, and apply lines L3 to L6 to them.
- Unstable systems. Split off the unstable part, which is kept, or use LQG balanced truncation, which uses Riccati equations and has a bound in a gap metric (see nu-gap metric).
- Discrete time. Replace the Lyapunov equations by Stein equations. The same bound holds for on the unit circle.
- Hankel-norm approximation (Glover 1984). Not a truncation, but built from the same Gramians. It reaches the best possible Hankel norm error (a theorem).
When to use it
Use balanced truncation when the model is linear, asymptotically stable and of moderate size, up to a few thousand states, and when a guaranteed error bound in the worst-case gain is wanted, for example to reduce a plant model before a robust control design, or to reduce a controller of high order. Look at the Hankel singular values first: a fast decay means a small accurate model exists, and the gap condition tells you where to cut. Use it with low-rank Gramians for large sparse models. Use the iterative rational Krylov algorithm instead when the model is very large and only solves with are affordable, or when the error matters more than the error. Use the singular perturbation variant when the gain at must be exact.
Pitfalls
- Line L4 skipped. If and the cut splits the pair, the bound and the stability proof fail. For the values are , and the implementation refuses . Choose at a gap.
- Line L1 on an unstable . The Lyapunov equation can still have a solution, but it is not a Gramian and need not be positive semidefinite; for it is . The implementation does not check that is Hurwitz; the caller must. Split off the unstable part first.
- Line L3 on the product. Computing with an eigenvalue routine works in exact arithmetic but squares the range of the values, and the small , the ones that decide the cut, lose their accuracy. Use the SVD of .
- Line L5 with the full inverse. Forming and then requires inverting a matrix with condition number up to . The formulas of line L5 avoid the inverse.
- Line L6 changes the gain at . matches at infinite frequency, not at zero frequency. A reduced plant used for steady-state design can have the wrong static gain, as for in the example. Use the singular perturbation variant.
- Line L7 with a loose tolerance. Values that are close but not equal are distinct, and each must be counted. Counting a cluster as one value gives a bound that is too small. The code merges only values within .
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
# Part of https://algorithm.tamnd.com/balanced-truncation/. The authors are listed in prov/F4R34P.jsonl.
"""Balanced truncation of a continuous-time LTI system (square root method).
For x' = A x + B u, y = C x + D u with A Hurwitz, the gramians solve
A W_c + W_c A^T + B B^T = 0, A^T W_o + W_o A + C^T C = 0.
With W_c = L_c L_c^T, W_o = L_o L_o^T and the SVD L_o^T L_c = U S V^T, the
Hankel singular values are the diagonal of S. The reduced model of order r is
T_r = L_c V_r S_r^(-1/2), W_r = L_o U_r S_r^(-1/2),
A_r = W_r^T A T_r, B_r = W_r^T B, C_r = C T_r, D_r = D.
W_r^T T_r = I, and the reduced model is balanced with gramians S_r. If
sigma_r > sigma_(r+1), A_r is Hurwitz and the H-infinity norm of the error is
at most 2 times the sum of the distinct values among sigma_(r+1), ..., sigma_n.
Everything is in float. The gramians are found by the Kronecker method
(O(n^6) work), which is fine for the small n of the tests and the page.
"""
import math
from ctlmat import eye, kron, mul, norm2, solve, sub, transpose, unvec, vec
__all__ = [
"lyap", "gramians", "sym_eig", "sqrt_factor", "svd", "hankel_singular_values",
"balanced_truncation", "error_bound", "freq_response", "hinf_on_grid",
]
def lyap(a, q):
"""Return X with A X + X A^T + Q = 0 (A Hurwitz), in float."""
n = len(a)
af = [[float(v) for v in row] for row in a]
big = [[x + y for x, y in zip(r1, r2)] for r1, r2 in zip(kron(eye(n), af), kron(af, eye(n)))]
x = unvec(solve(big, [-float(v) for v in vec(q)]), n, n)
return [[(x[i][j] + x[j][i]) / 2.0 for j in range(n)] for i in range(n)]
def gramians(a, b, c):
"""Return (W_c, W_o), the controllability and observability gramians."""
wc = lyap(a, mul(b, transpose(b)))
wo = lyap(transpose(a), mul(transpose(c), c))
return wc, wo
def sym_eig(s, sweeps=100):
"""Return (values, vectors) of a real symmetric matrix by cyclic Jacobi.
vectors is a matrix whose columns are orthonormal eigenvectors, so
s = vectors diag(values) vectors^T up to rounding.
"""
n = len(s)
a = [[float(v) for v in row] for row in s]
q = [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]
for _ in range(sweeps):
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 r in range(p + 1, n):
if a[p][r] == 0.0:
continue
theta = (a[r][r] - a[p][p]) / (2.0 * a[p][r])
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, akr = a[k][p], a[k][r]
a[k][p] = c * akp - sn * akr
a[k][r] = sn * akp + c * akr
for k in range(n):
apk, ark = a[p][k], a[r][k]
a[p][k] = c * apk - sn * ark
a[r][k] = sn * apk + c * ark
for k in range(n):
qkp, qkr = q[k][p], q[k][r]
q[k][p] = c * qkp - sn * qkr
q[k][r] = sn * qkp + c * qkr
return [a[i][i] for i in range(n)], q
def sqrt_factor(w):
"""Return L with W = L L^T for a symmetric positive semidefinite W.
L = Q diag(sqrt(max(lambda, 0))) from the eigendecomposition, so a
gramian that is singular to rounding error still gets a factor.
"""
vals, q = sym_eig(w)
n = len(w)
return [[q[i][j] * math.sqrt(max(vals[j], 0.0)) for j in range(n)] for i in range(n)]
def svd(m, sweeps=100):
"""Return (U, s, V) with M = U diag(s) V^T for a square M (one-sided Jacobi).
s is sorted in decreasing order. A column of U that belongs to a zero
singular value is set to zero.
"""
n = len(m)
g = [[float(m[i][j]) for j in range(n)] for i in range(n)]
v = [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]
for _ in range(sweeps):
rotated = False
for p in range(n - 1):
for r in range(p + 1, n):
alpha = sum(g[k][p] ** 2 for k in range(n))
beta = sum(g[k][r] ** 2 for k in range(n))
gamma = sum(g[k][p] * g[k][r] for k in range(n))
if abs(gamma) <= 1e-15 * math.sqrt(alpha * beta) or gamma == 0.0:
continue
rotated = True
zeta = (beta - alpha) / (2.0 * gamma)
t = math.copysign(1.0, zeta) / (abs(zeta) + math.sqrt(1.0 + zeta * zeta))
c = 1.0 / math.sqrt(1.0 + t * t)
sn = c * t
for k in range(n):
gp, gr = g[k][p], g[k][r]
g[k][p] = c * gp - sn * gr
g[k][r] = sn * gp + c * gr
vp, vr = v[k][p], v[k][r]
v[k][p] = c * vp - sn * vr
v[k][r] = sn * vp + c * vr
if not rotated:
break
s = [math.sqrt(sum(g[k][j] ** 2 for k in range(n))) for j in range(n)]
order = sorted(range(n), key=lambda j: -s[j])
s = [s[j] for j in order]
vv = [[v[i][j] for j in order] for i in range(n)]
u = [[(g[i][j] / s[jj]) if s[jj] > 0.0 else 0.0 for jj, j in enumerate(order)] for i in range(n)]
return u, s, vv
def hankel_singular_values(a, b, c):
"""Return the Hankel singular values sigma_1 >= ... >= sigma_n."""
wc, wo = gramians(a, b, c)
_, s, _ = svd(mul(transpose(sqrt_factor(wo)), sqrt_factor(wc)))
return s
def error_bound(sigma, r, rtol=1e-9):
"""Return 2 times the sum of the distinct values among sigma[r:].
Two values count as equal when they differ by at most rtol * sigma[0].
"""
tail = sigma[r:]
tol = rtol * (sigma[0] if sigma else 0.0)
distinct = []
for x in tail:
if not any(abs(x - y) <= tol for y in distinct):
distinct.append(x)
return 2.0 * sum(distinct)
def balanced_truncation(a, b, c, d, r, rtol=1e-9):
"""Return (A_r, B_r, C_r, D_r, sigma, bound) for the reduced order r.
sigma is the list of all Hankel singular values and bound is the
H-infinity error bound. Raises ValueError if 0 < r < n and
sigma_r - sigma_(r+1) <= rtol * sigma_1, because the cut then splits a
repeated value and the theorem gives no guarantee.
"""
n = len(a)
wc, wo = gramians(a, b, c) # @line L1
lc, lo = sqrt_factor(wc), sqrt_factor(wo) # @line L2
u, sigma, v = svd(mul(transpose(lo), lc)) # @line L3
if not 0 <= r <= n:
raise ValueError("r must be between 0 and n")
if 0 < r < n and sigma[r - 1] - sigma[r] <= rtol * sigma[0]: # @line L4
raise ValueError("sigma_r equals sigma_(r+1): choose another r")
if r > 0 and sigma[r - 1] <= 0.0:
raise ValueError("the system has fewer than r controllable and observable modes")
isq = [1.0 / math.sqrt(sigma[j]) for j in range(r)]
tr = [[sum(lc[i][k] * v[k][j] for k in range(n)) * isq[j] for j in range(r)] for i in range(n)] # @line L5
wr = [[sum(lo[i][k] * u[k][j] for k in range(n)) * isq[j] for j in range(r)] for i in range(n)]
wrt = transpose(wr) if r > 0 else []
ar = mul(mul(wrt, a), tr) if r > 0 else [] # @line L6
br = mul(wrt, b) if r > 0 else []
cr = mul(c, tr) if r > 0 else [[] for _ in c]
dr = [list(row) for row in d]
bound = error_bound(sigma, r, rtol) # @line L7
return ar, br, cr, dr, sigma, bound # @line L8
def freq_response(a, b, c, d, s):
"""Return G(s) = C (s I - A)^(-1) B + D as a complex matrix."""
n = len(a)
p = len(d)
m = len(d[0])
if n == 0:
return [[complex(d[i][j]) for j in range(m)] for i in range(p)]
si_a = sub([[complex(s) if i == j else 0j for j in range(n)] for i in range(n)], [[complex(v) for v in row] for row in a])
x = solve(si_a, [[complex(v) for v in row] for row in b])
g = mul([[complex(v) for v in row] for row in c], x)
return [[g[i][j] + d[i][j] for j in range(m)] for i in range(p)]
def hinf_on_grid(sys1, sys2, omegas):
"""Return the largest 2-norm of G1(j w) - G2(j w) over the grid (a lower estimate)."""
best = 0.0
for w in omegas:
g1 = freq_response(*sys1, 1j * w)
g2 = freq_response(*sys2, 1j * w)
e = [[x - y for x, y in zip(r1, r2)] for r1, r2 in zip(g1, g2)]
best = max(best, norm2(e))
return best
ctlmat.py 630 lines
# 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()
test_balanced_truncation.py 186 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/balanced-truncation/. The authors are listed in prov/F4R34P.jsonl.
import math
import random
import pytest
from balanced_truncation import (
balanced_truncation, error_bound, freq_response, gramians,
hankel_singular_values, hinf_on_grid, lyap, svd, sym_eig,
)
from ctlmat import charpoly, inv, mul, polyroots, transpose
GRID = [0.0] + [10 ** (k / 60.0) for k in range(-180, 181)]
def random_stable(rng, n, m, p):
r = [[rng.uniform(-1, 1) for _ in range(n)] for _ in range(n)]
rho = max(sum(abs(v) for v in row) for row in r)
a = [[r[i][j] - (rho + 0.3 if i == j else 0.0) for j in range(n)] for i in range(n)]
b = [[rng.uniform(-1, 1) for _ in range(m)] for _ in range(n)]
c = [[rng.uniform(-1, 1) for _ in range(n)] for _ in range(p)]
d = [[rng.uniform(-1, 1) for _ in range(m)] for _ in range(p)]
return a, b, c, d
def poles(a):
return polyroots(charpoly(a))
def maxdiff(x, y):
return max(abs(u - v) for r1, r2 in zip(x, y) for u, v in zip(r1, r2))
CHAIN = (
[[-1, 1, 0, 0], [0, -2, 1, 0], [0, 0, -3, 1], [0, 0, 0, -4]],
[[0], [0], [0], [1]],
[[1, 0, 0, 0]],
[[0]],
)
def test_first_order_system():
assert abs(hankel_singular_values([[-1]], [[1]], [[1]])[0] - 0.5) < 1e-14
# 1/(s + a) with b = c = 1 has sigma = 1/(2a)
assert abs(hankel_singular_values([[-4.0]], [[1.0]], [[1.0]])[0] - 0.125) < 1e-14
def test_lyap_residual_and_jacobi():
rng = random.Random(10)
a, b, c, _ = random_stable(rng, 5, 2, 2)
wc, wo = gramians(a, b, c)
bb = mul(b, transpose(b))
res = [[sum(a[i][k] * wc[k][j] + wc[i][k] * a[j][k] for k in range(5)) + bb[i][j] for j in range(5)] for i in range(5)]
assert maxdiff(res, [[0.0] * 5 for _ in range(5)]) < 1e-12
vals, q = sym_eig(wc)
rebuilt = [[sum(q[i][k] * vals[k] * q[j][k] for k in range(5)) for j in range(5)] for i in range(5)]
assert maxdiff(rebuilt, wc) < 1e-13
m = [[rng.uniform(-1, 1) for _ in range(4)] for _ in range(4)]
u, s, v = svd(m)
rebuilt = [[sum(u[i][k] * s[k] * v[j][k] for k in range(4)) for j in range(4)] for i in range(4)]
assert maxdiff(rebuilt, m) < 1e-13
assert all(x >= y for x, y in zip(s, s[1:]))
def test_hsv_against_eigenvalues_of_gramian_product():
a, b, c, _ = CHAIN
wc, wo = gramians(a, b, c)
lam = sorted((z.real for z in poles(mul(wc, wo))), reverse=True)
sig = hankel_singular_values(a, b, c)
for s, l in zip(sig, lam):
assert abs(s - math.sqrt(l)) < 1e-9 * sig[0]
def test_hsv_against_eigenvalues_on_500_random_systems():
# oracle: sqrt of the roots of det(s I - W_c W_o), with the gramians
# from the Kronecker solve and the roots from ctlmat.polyroots
rng = random.Random(15)
for _ in range(500):
n = rng.randint(1, 3)
a, b, c, _ = random_stable(rng, n, rng.randint(1, 2), rng.randint(1, 2))
wc, wo = gramians(a, b, c)
lam = sorted((max(z.real, 0.0) for z in poles(mul(wc, wo))), reverse=True)
sig = hankel_singular_values(a, b, c)
for s, l in zip(sig, lam):
assert abs(s - math.sqrt(l)) < 1e-6 * sig[0]
def test_hsv_invariant_under_similarity():
rng = random.Random(11)
for _ in range(5):
a, b, c, _ = random_stable(rng, 4, 1, 2)
t = [[rng.uniform(-1, 1) + (2.0 if i == j else 0.0) for j in range(4)] for i in range(4)]
ti = inv(t)
s1 = hankel_singular_values(a, b, c)
s2 = hankel_singular_values(mul(mul(ti, a), t), mul(ti, b), mul(c, t))
for x, y in zip(s1, s2):
assert abs(x - y) < 1e-9 * s1[0]
def test_reduced_model_is_balanced_and_stable():
rng = random.Random(12)
for trial in range(6):
a, b, c, d = random_stable(rng, 5, 2, 2)
for r in range(1, 5):
ar, br, cr, dr, sig, bound = balanced_truncation(a, b, c, d, r)
wc, wo = gramians(ar, br, cr)
want = [[sig[i] if i == j else 0.0 for j in range(r)] for i in range(r)]
assert maxdiff(wc, want) < 1e-9 * sig[0]
assert maxdiff(wo, want) < 1e-9 * sig[0]
assert all(z.real < 0 for z in poles(ar))
def test_error_between_lower_and_upper_bound():
rng = random.Random(13)
systems = [CHAIN] + [random_stable(rng, 4, 1, 1) for _ in range(3)] + [random_stable(rng, 4, 2, 2)]
for sys in systems:
n = len(sys[0])
for r in range(0, n):
red = balanced_truncation(*sys, r)
sig, bound = red[4], red[5]
err = hinf_on_grid(sys, red[:4], GRID)
assert err <= bound * (1 + 1e-9)
# sigma_(r+1) is a lower bound for every model of order r; the grid
# gives a lower estimate of the norm, so allow a small margin.
assert err >= 0.98 * sig[r]
def test_chain_example_of_the_page():
sig = hankel_singular_values(*CHAIN[:3])
want = [0.0279876, 0.00821788, 0.00112693, 0.0000632855]
for s, w in zip(sig, want):
assert abs(s - w) < 5e-6 * w
ar, br, cr, dr, _, bound = balanced_truncation(*CHAIN, 2)
assert abs(bound - 0.00238044) < 1e-8
err = hinf_on_grid(CHAIN, (ar, br, cr, dr), GRID)
assert abs(err - 0.00214790) < 1e-7
# dropping only the last state: the error equals 2 sigma_4 on this system
red3 = balanced_truncation(*CHAIN, 3)
assert abs(hinf_on_grid(CHAIN, red3[:4], GRID) - 2 * sig[3]) < 1e-12
def test_full_order_reproduces_g():
rng = random.Random(14)
a, b, c, d = random_stable(rng, 4, 2, 3)
ar, br, cr, dr, _, bound = balanced_truncation(a, b, c, d, 4)
assert bound == 0.0
for s in [0.3j, 1.0 + 2.0j, -0.2 + 5j, 10.0]:
assert maxdiff(freq_response(a, b, c, d, s), freq_response(ar, br, cr, dr, s)) < 1e-10
def test_repeated_values_counted_once_and_tight():
# diag(1/(s+1), 1/(s+3), 1/(s+3)) has sigma = 1/2, 1/6, 1/6
a = [[-1, 0, 0], [0, -3, 0], [0, 0, -3]]
b = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
c = b
d = [[0] * 3 for _ in range(3)]
ar, br, cr, dr, sig, bound = balanced_truncation(a, b, c, d, 1)
assert abs(sig[0] - 0.5) < 1e-14 and abs(sig[1] - 1 / 6) < 1e-14 and abs(sig[2] - 1 / 6) < 1e-14
assert abs(bound - 1 / 3) < 1e-12
assert abs(hinf_on_grid((a, b, c, d), (ar, br, cr, dr), GRID) - 1 / 3) < 1e-12
assert abs(error_bound(sig, 1, rtol=0.0) - 1 / 3) < 1e-12
with pytest.raises(ValueError):
balanced_truncation(a, b, c, d, 2)
def test_bound_is_attained_for_first_order():
# G = 1/(s+1), r = 0: G_r = 0 and the error is 1 = 2 sigma_1
ar, br, cr, dr, sig, bound = balanced_truncation([[-1]], [[1]], [[1]], [[0]], 0)
assert abs(bound - 1.0) < 1e-14
assert abs(hinf_on_grid(([[-1]], [[1]], [[1]], [[0]]), (ar, br, cr, dr), [0.0]) - 1.0) < 1e-14
def test_non_minimal_system():
# the second state is not controllable: sigma_2 = 0, order 1 is exact
a = [[-1.0, 0.0], [0.0, -2.0]]
b = [[1.0], [0.0]]
c = [[1.0, 1.0]]
d = [[0.0]]
sig = hankel_singular_values(a, b, c)
assert abs(sig[0] - 0.5) < 1e-12 and abs(sig[1]) < 1e-7
ar, br, cr, dr, _, bound = balanced_truncation(a, b, c, d, 1)
assert hinf_on_grid((a, b, c, d), (ar, br, cr, dr), GRID) < 1e-9
with pytest.raises(ValueError):
balanced_truncation(a, b, c, d, 2)
History
Moore (1981) introduced internally balanced realizations, by analogy with principal component analysis, and proposed to delete the weakly controllable and weakly observable states. Pernebo and Silverman (1982) proved that the truncated model is asymptotically stable and minimal. Enns (1984) proved the bound of twice the sum of the deleted values and proposed the frequency-weighted version, and Glover (1984), in his paper on optimal Hankel-norm approximation, proved the bound with each distinct value counted once. Laub, Heath, Paige and Ward (1987) gave the square-root computation from Cholesky factors and an SVD, which is the form used in numerical libraries.
References
- B. C. Moore, Principal component analysis in linear systems, controllability, observability, and model reduction, IEEE Transactions on Automatic Control 26(1), 17-32, 1981, the internally balanced realization and the reduced model obtained by deleting the weak states
- L. Pernebo and L. M. Silverman, Model reduction via balanced state space representations, IEEE Transactions on Automatic Control 27(2), 382-387, 1982, the stability and minimality of the truncated balanced model
- Dale F. Enns, Model reduction with balanced realizations, an error bound and a frequency weighted generalization, 23rd IEEE Conference on Decision and Control, 127-132, 1984, the bound of twice the sum of the deleted Hankel singular values and the frequency-weighted version
- Keith Glover, All optimal Hankel-norm approximations of linear multivariable systems and their L-infinity error bounds, International Journal of Control 39(6), 1115-1193, 1984, the L-infinity error bound for balanced truncation, with each distinct Hankel singular value counted once
- A. J. Laub, M. T. Heath, C. C. Paige and R. C. Ward, Computation of system balancing transformations and other applications of simultaneous diagonalization algorithms, IEEE Transactions on Automatic Control 32(2), 115-122, 1987, the balancing transformation from Cholesky factors of the Gramians and an SVD of their product
- Athanasios C. Antoulas, Approximation of Large-Scale Dynamical Systems, SIAM, 2005, Chapter 7, Balancing and balanced approximations
- Kemin Zhou, John C. Doyle and Keith Glover, Robust and Optimal Control, Prentice Hall, 1996, Chapter 7, Model Reduction by Balanced Truncation
Where this leads
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 F4R34P Edit this page History Report an error Markdown