Definitionadvanced
Joint spectral radius
Also called JSR.
The largest growth rate of long products of matrices from a set. It is below 1 if and only if the discrete-time switched linear system is GUES under arbitrary switching.
The joint spectral radius of a finite set of square matrices is the largest rate at which long products of matrices from the set can grow. For one matrix it is the ordinary spectral radius. For a set, it describes the discrete-time switched linear system , where a switching signal picks one matrix at each step: the joint spectral radius is below 1 if and only if every solution goes to zero at a uniform exponential rate, whatever the switching. This is a much stronger property than the stability of each matrix alone, since two matrices with spectral radius can give products that grow without bound. Gian-Carlo Rota and Gilbert Strang defined the quantity in 1960. It is easy to bound and hard to compute: deciding whether it is at most 1 is undecidable.
Definition
Let be a finite set of real matrices, and let be the set of the products of length . For any matrix norm induced by a vector norm, the joint spectral radius is
The limit exists and equals the infimum over , because the sequence is subadditive. It does not depend on the norm, because all norms on a finite-dimensional space are equivalent and the constants disappear under the root of order .
Basic facts, for every :
- (the case ).
- , and for an invertible .
- Rota and Strang: , the infimum over all induced norms. A norm that reaches the infimum is called an extremal norm.
- Stability. if and only if the system is globally uniformly exponentially stable (GUES) under arbitrary switching. If , the products can stay bounded or can grow slower than any exponential, depending on the set.
The two inequalities above give a direct algorithm for an interval that contains . It lists the products of each length and keeps the best bounds:
JSR-BOUNDS(M, K) ▷ M = {A_1, ..., A_m}, all n by n- 1
lo ← 0; hi ← ∞; prods ← [I] - 2
for k ← 1 to K do - 3
prods ← [A P : P in prods, A in M] ▷ all m^k products of length k - 4
lo ← max(lo, max over P in prods of ρ(P)^(1/k)) - 5
hi ← min(hi, max over P in prods of ‖P‖^(1/k)) - 6
return (lo, hi)
The proof that , and of the stability statement, is in proofs/correctness.md of this page. The cost is , exponential in , so the method only works for short products. The gap between the bounds can close slowly.
Examples and non-examples
A pair with a closed form. Take
Each matrix has spectral radius 1, and each has 2-norm . The product has spectral radius . So the lower bound at meets the upper bound at , and . The bounds of each length alone, with the 2-norm, are:
| products | |||
|---|---|---|---|
| 1 | 2 | 1 | 1.618034 |
| 2 | 4 | 1.618034 | 1.618034 |
| 3 | 8 | 1.551134 | 1.618034 |
| 4 | 16 | 1.618034 | 1.618034 |
| 5 | 32 | 1.581678 | 1.618034 |
The lower bound of a single length does not grow monotonically: the odd lengths cannot repeat an exact number of times. The algorithm keeps the best value found so far.
Two Schur matrices that switch to instability. Take
Each has spectral radius , so each system alone goes to zero. But has spectral radius , so . Each also has 2-norm , so the bounds meet and . Alternating the two matrices makes grow like .
A set with a gap. For and , the products up to length 8 give . The value is not known in closed form, but the upper bound is below 1, so the switched system is GUES.
Special cases.
- One matrix: , by Gelfand's formula .
- Matrices that are all upper triangular, or that all commute: . For a triangular set, the diagonal of a product is the product of the diagonals.
- Symmetric matrices, or more generally normal matrices: , so the bound at is exact and .
Non-examples.
- is not the joint spectral radius in general: the Schur pair above has it equal to , against a true value above 2.
- is only an upper bound, and its value depends on the norm. For the Schur pair it is in the infinity norm, against the true value .
- For a continuous-time switched system , the joint spectral radius of means nothing. The analog is the largest exponential growth rate of the solutions, and it is studied with Lyapunov functions instead.
The finiteness property. In the first example, the value is reached by one finite product: with and . The conjecture that every finite set has such a product was disproved by Bousch and Mairesse (2002), so the lower bounds of the algorithm can stay strictly below for every .
Related definitions
- Spectral radius: the case of one matrix. The joint version replaces the powers by all products of length .
- Switched system: the joint spectral radius is the exact stability test for the discrete-time linear case under arbitrary switching.
- Common Lyapunov function: a norm with for all and is a common Lyapunov function, and by the Rota-Strang formula one exists exactly when . A quadratic one, with negative definite for all , is found by semidefinite programming and gives the upper bound by the ellipsoidal norm .
- Exponential stability: the property the condition certifies, uniformly over all switching signals.
- Complexity: whether is undecidable for pairs of matrices with rational entries (Blondel and Tsitsiklis 2000), and approximating is NP-hard (Jungers 2009, Chapter 2). Practical methods find extremal norms from polytopes or sums of squares, and they work well on most sets of moderate size.
Proof: The products of length up to K give a lower and an upper bound on the joint spectral radiusfull
Let be a finite set of real matrices and let be an induced matrix norm, so . Let be the set of products of length , and define
where is the spectral radius. The joint spectral radius is .
Lemma 1: the limit exists and is an infimum
Let (with ). A product of length is a product of length times a product of length , so . By Fekete's lemma for subadditive sequences, converges to . So , and for every .
All norms on are equivalent: . Since and tend to 1, the limit does not depend on the norm.
Lemma 2: every product gives a lower bound
Let . For every , , and the spectral radius is at most any induced norm, so
Taking the root of order gives . As the right side tends to . So for every .
Theorem
jsr_bounds(mats, K) returns with and , and .
Proof. Loop invariant: at the start of iteration , prods lists every product of length (the identity for ). Line L3 multiplies each of them on the left by each , so after it prods lists every product of length , once for each index sequence. Lines L4 and L5 then fold into the maximum and into the minimum . Lemma 2 gives for each , so . Lemma 1 gives for each , so .
Lemma 1 also shows that as . The lower bound converges too: is the theorem of Berger and Wang. The proof here does not use it.
Stability under arbitrary switching
Consider with any switching sequence . Then for a product .
- If , Lemma 1 gives a with . Take with and , so for every . Write with . Then with , which is at most with . The constants do not depend on , so the origin is globally uniformly exponentially stable (GUES) under arbitrary switching.
- If the origin is GUES, for all with some , so and .
So if and only if the switched system is GUES under arbitrary switching.
Floating point
The code computes from the eigenvalues of and from the roots of the characteristic polynomial. Both are floating point values. A multiple eigenvalue of is ill conditioned as a root, with an error near for a double root, so can be above its exact value by that amount. The tests allow .
Cost
There are products of length . Each costs one product, one norm and one characteristic polynomial, each, plus the roots. The total for lengths to is time, and memory for the list of products of the last length.
Code
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()
joint_spectral_radius.py 60 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/joint-spectral-radius/. The authors are listed in prov/5Q24WE.jsonl.
"""Bounds on the joint spectral radius by brute force over products.
For a finite set M of n by n real matrices, the joint spectral radius is
rho(M) = lim_k max over products P of length k of ||P||^(1/k).
For every length k and every product P of length k,
rho(P)^(1/k) <= rho(M) <= max over products Q of length k of ||Q||^(1/k),
so the products of length 1, ..., K give an interval that contains rho(M).
The number of products of length k is |M|^k, so K must stay small.
The norm is the induced 2-norm (ctlmat.norm2). The spectral radius of a
product is the largest modulus of a root of its characteristic polynomial.
"""
import math
from ctlmat import charpoly, eye, mul, norm2, polyroots
__all__ = ["spectral_radius", "products", "jsr_bounds"]
def spectral_radius(a):
"""Return the largest modulus of an eigenvalue of the square matrix a."""
roots = polyroots(charpoly(a))
return max((abs(z) for z in roots), default=0.0)
def products(mats, k):
"""Return all products A_(i_k) ... A_(i_1) of length k, as a list."""
n = len(mats[0])
out = [eye(n)]
for _ in range(k):
out = [mul(a, p) for p in out for a in mats]
return out
def jsr_bounds(mats, kmax):
"""Return (lower, upper) with lower <= rho(mats) <= upper.
The bounds use the products of length 1 to kmax. lower is the largest
value of rho(P)^(1/k) and upper the smallest value of max ||P||^(1/k) found.
"""
if not mats or kmax < 1:
raise ValueError("need at least one matrix and kmax >= 1")
n = len(mats[0])
if any(len(a) != n or any(len(row) != n for row in a) for a in mats):
raise ValueError("all matrices must be n by n")
lo, hi = 0.0, math.inf # @line L1
prods = [eye(n)] # @line L1
for k in range(1, kmax + 1): # @line L2
prods = [mul(a, p) for p in prods for a in mats] # @line L3
lo = max(lo, max(spectral_radius(p) for p in prods) ** (1.0 / k)) # @line L4
hi = min(hi, max(norm2(p) for p in prods) ** (1.0 / k)) # @line L5
return lo, hi # @line L6
test_joint_spectral_radius.py 129 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/joint-spectral-radius/. The authors are listed in prov/5Q24WE.jsonl.
import math
import random
import pytest
from ctlmat import inv, matvec, mul, norm2
from joint_spectral_radius import jsr_bounds, products, spectral_radius
PHI = (1 + math.sqrt(5)) / 2
GOLDEN = [[[1, 1], [0, 1]], [[1, 0], [1, 1]]]
TOL = 1e-7 # polyroots is accurate to about 1e-8 for a double eigenvalue
def random_matrix(rng, n, scale=1.0):
return [[rng.uniform(-scale, scale) for _ in range(n)] for _ in range(n)]
def test_golden_pair():
lo, hi = jsr_bounds(GOLDEN, 1)
assert abs(lo - 1.0) < TOL and abs(hi - PHI) < TOL
lo, hi = jsr_bounds(GOLDEN, 2)
assert abs(lo - PHI) < TOL and abs(hi - PHI) < TOL
assert abs(spectral_radius(mul(GOLDEN[0], GOLDEN[1])) - PHI ** 2) < TOL
# odd lengths alone give smaller lower bounds
ps = products(GOLDEN, 3)
assert abs(max(spectral_radius(p) for p in ps) ** (1 / 3) - 1.551134) < 1e-6
def test_switching_between_schur_matrices_can_diverge():
a1 = [[0.5, 2.0], [0.0, 0.5]]
a2 = [[0.5, 0.0], [2.0, 0.5]]
assert spectral_radius(a1) < 1 and spectral_radius(a2) < 1
lo, hi = jsr_bounds([a1, a2], 2)
assert abs(lo - (0.5 + PHI)) < TOL
assert abs(hi - (0.5 + PHI)) < TOL
x = [1.0, 1.0]
for _ in range(20):
x = matvec(a2, matvec(a1, x))
assert norm2(x) > 1e6
def test_single_matrix_gives_its_spectral_radius():
rng = random.Random(11)
for _ in range(20):
a = random_matrix(rng, 3)
rho = spectral_radius(a)
lo, hi = jsr_bounds([a], 6)
assert lo == pytest.approx(rho, rel=1e-6, abs=TOL)
assert hi >= rho - TOL
def test_upper_triangular_sets():
# For upper triangular matrices the JSR is the largest modulus of a diagonal entry.
rng = random.Random(3)
for _ in range(30):
mats = []
for _ in range(rng.randint(1, 3)):
d1, d2, u = rng.uniform(-1, 1), rng.uniform(-1, 1), rng.uniform(-3, 3)
mats.append([[d1, u], [0.0, d2]])
rho = max(max(abs(m[0][0]), abs(m[1][1])) for m in mats)
lo, hi = jsr_bounds(mats, 4)
assert lo == pytest.approx(rho, abs=TOL)
assert hi >= rho - TOL
def test_bounds_sandwich_and_monotone():
rng = random.Random(7)
for _ in range(15):
n = rng.randint(2, 3)
mats = [random_matrix(rng, n) for _ in range(rng.randint(2, 3))]
prev_lo, prev_hi = 0.0, math.inf
for k in range(1, 5):
lo, hi = jsr_bounds(mats, k)
assert lo <= hi + TOL
assert lo >= prev_lo and hi <= prev_hi
prev_lo, prev_hi = lo, hi
# every product of every length lies inside the interval
for k in range(1, 6):
for p in products(mats, k):
assert spectral_radius(p) ** (1 / k) <= prev_hi + TOL
def test_similarity_and_scaling():
rng = random.Random(19)
for _ in range(10):
mats = [random_matrix(rng, 2) for _ in range(2)]
t = random_matrix(rng, 2)
t[0][0] += 3.0
t[1][1] += 3.0
ti = inv(t)
conj = [mul(ti, mul(a, t)) for a in mats]
lo1, _ = jsr_bounds(mats, 4)
lo2, _ = jsr_bounds(conj, 4)
assert lo1 == pytest.approx(lo2, rel=1e-6, abs=TOL)
c = rng.uniform(0.2, 3.0)
scaled = [[[c * v for v in row] for row in a] for a in mats]
lo3, hi3 = jsr_bounds(scaled, 3)
lo4, hi4 = jsr_bounds(mats, 3)
assert lo3 == pytest.approx(c * lo4, rel=1e-6, abs=TOL)
assert hi3 == pytest.approx(c * hi4, rel=1e-9)
def test_upper_bound_below_one_gives_decay_under_any_switching():
rng = random.Random(23)
mats = [[[0.6, 0.5], [0.0, 0.6]], [[0.6, 0.0], [-0.5, 0.6]]]
_, hi = jsr_bounds(mats, 5)
assert hi < 0.81
k = 5
assert max(norm2(p) for p in products(mats, k)) <= hi ** k + 1e-12
# ||P|| <= hi^k for every product of length k, so x decays at least like hi^k per block
for _ in range(50):
x = [rng.uniform(-1, 1), rng.uniform(-1, 1)]
x0 = norm2(x)
for _ in range(4):
for _ in range(k):
x = matvec(mats[rng.randrange(2)], x)
assert norm2(x) <= hi ** (4 * k) * x0 + 1e-12
def test_rejects_bad_input():
with pytest.raises(ValueError):
jsr_bounds([], 2)
with pytest.raises(ValueError):
jsr_bounds(GOLDEN, 0)
with pytest.raises(ValueError):
jsr_bounds([[[1, 0], [0, 1]], [[1]]], 2)
References
- Gian-Carlo Rota and Gilbert Strang, A note on the joint spectral radius, Indagationes Mathematicae 22, 379-381, 1960, the definition of the joint spectral radius and its characterization as an infimum over norms
- Raphaël Jungers, The Joint Spectral Radius, Theory and Applications, Lecture Notes in Control and Information Sciences 385, Springer, 2009, Chapter 1, Basics (definition and elementary properties); Chapter 2, Classical Results and Problems (extremal norms, complexity, computation, the finiteness property)
- Vincent D. Blondel and John N. Tsitsiklis, The boundedness of all products of a pair of matrices is undecidable, Systems and Control Letters 41(2), 135-140, 2000, the main theorem and its consequence that the question whether the joint spectral radius is at most 1 is undecidable
- Thierry Bousch and Jean Mairesse, Asymptotic height optimization for topical IFS, Tetris heaps, and the finiteness conjecture, Journal of the American Mathematical Society 15(1), 77-111, 2002, the counterexample to the finiteness conjecture
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 | H2 full proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag 5Q24WE Edit this page History Report an error Markdown