Algorithm Search⌘K

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 x(t+1)=Aσ(t)x(t)x(t+1) = A_{\sigma(t)} x(t), where a switching signal σ\sigma 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 1/21/2 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 M={A1,…,Am}\mathcal{M} = \{A_1, \dots, A_m\} be a finite set of real n×nn \times n matrices, and let Σk\Sigma_k be the set of the mkm^k products Aik⋯Ai1A_{i_k} \cdots A_{i_1} of length kk. For any matrix norm induced by a vector norm, the joint spectral radius is

ρ(M)=lim⁡k→∞max⁡P∈Σk∥P∥1/k.\rho(\mathcal{M}) = \lim_{k \to \infty} \max_{P \in \Sigma_k} \|P\|^{1/k}.

The limit exists and equals the infimum over kk, because the sequence log⁡max⁡P∈Σk∥P∥\log \max_{P \in \Sigma_k} \|P\| 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 kk.

Basic facts, for every k≥1k \ge 1:

max⁡P∈Σkρ(P)1/k  ≤  ρ(M)  ≤  max⁡P∈Σk∥P∥1/k.\max_{P \in \Sigma_k} \rho(P)^{1/k} \;\le\; \rho(\mathcal{M}) \;\le\; \max_{P \in \Sigma_k} \|P\|^{1/k}.
  • max⁡iρ(Ai)≤ρ(M)≤max⁡i∥Ai∥\max_i \rho(A_i) \le \rho(\mathcal{M}) \le \max_i \|A_i\| (the case k=1k = 1).
  • ρ(cM)=∣c∣ ρ(M)\rho(c\mathcal{M}) = |c|\,\rho(\mathcal{M}), and ρ(T−1MT)=ρ(M)\rho(T^{-1} \mathcal{M} T) = \rho(\mathcal{M}) for an invertible TT.
  • Rota and Strang: ρ(M)=inf⁡∥⋅∥max⁡i∥Ai∥\rho(\mathcal{M}) = \inf_{\|\cdot\|} \max_i \|A_i\|, the infimum over all induced norms. A norm that reaches the infimum is called an extremal norm.
  • Stability. ρ(M)<1\rho(\mathcal{M}) < 1 if and only if the system x(t+1)=Aσ(t)x(t)x(t+1) = A_{\sigma(t)} x(t) is globally uniformly exponentially stable (GUES) under arbitrary switching. If ρ(M)=1\rho(\mathcal{M}) = 1, 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 ρ(M)\rho(\mathcal{M}). It lists the products of each length and keeps the best bounds:

  1. JSR-BOUNDS(M, K) ▷ M = {A_1, ..., A_m}, all n by n
  2. 1lo ← 0; hi ← ∞; prods ← [I]
  3. 2for k ← 1 to K do
  4. 3prods ← [A P : P in prods, A in M] ▷ all m^k products of length k
  5. 4lo ← max(lo, max over P in prods of ρ(P)^(1/k))
  6. 5hi ← min(hi, max over P in prods of ‖P‖^(1/k))
  7. 6return (lo, hi)

The proof that lo≤ρ(M)≤hilo \le \rho(\mathcal{M}) \le hi, and of the stability statement, is in proofs/correctness.md of this page. The cost is O(mKn3)O(m^K n^3), exponential in KK, 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

A1=[1101],A2=[1011].A_1 = \begin{bmatrix} 1 & 1 \\ 0 & 1 \end{bmatrix}, \qquad A_2 = \begin{bmatrix} 1 & 0 \\ 1 & 1 \end{bmatrix}.

Each matrix has spectral radius 1, and each has 2-norm φ=(1+5)/2≈1.618034\varphi = (1 + \sqrt 5)/2 \approx 1.618034. The product A1A2=[2111]A_1 A_2 = \begin{bmatrix} 2 & 1 \\ 1 & 1 \end{bmatrix} has spectral radius φ2\varphi^2. So the lower bound at k=2k = 2 meets the upper bound at k=1k = 1, and ρ(M)=φ\rho(\mathcal{M}) = \varphi. The bounds of each length alone, with the 2-norm, are:

kk products max⁡ρ(P)1/k\max \rho(P)^{1/k} max⁡∥P∥21/k\max \lVert P \rVert_2^{1/k}
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 A1A2A_1 A_2 an exact number of times. The algorithm keeps the best value found so far.

Two Schur matrices that switch to instability. Take

A1=[0.5200.5],A2=[0.5020.5].A_1 = \begin{bmatrix} 0.5 & 2 \\ 0 & 0.5 \end{bmatrix}, \qquad A_2 = \begin{bmatrix} 0.5 & 0 \\ 2 & 0.5 \end{bmatrix}.

Each has spectral radius 0.50.5, so each system x(t+1)=Aix(t)x(t+1) = A_i x(t) alone goes to zero. But A2A1A_2 A_1 has spectral radius 2.25+5≈4.4862.25 + \sqrt 5 \approx 4.486, so ρ(M)≥4.486≈2.118\rho(\mathcal{M}) \ge \sqrt{4.486} \approx 2.118. Each AiA_i also has 2-norm 2.25+5\sqrt{2.25 + \sqrt 5}, so the bounds meet and ρ(M)=2.25+5=0.5+φ≈2.118\rho(\mathcal{M}) = \sqrt{2.25 + \sqrt 5} = 0.5 + \varphi \approx 2.118. Alternating the two matrices makes ∥x(t)∥\|x(t)\| grow like 2.118t2.118^t.

A set with a gap. For A1=[0.60.500.6]A_1 = \begin{bmatrix} 0.6 & 0.5 \\ 0 & 0.6 \end{bmatrix} and A2=[0.60−0.50.6]A_2 = \begin{bmatrix} 0.6 & 0 \\ -0.5 & 0.6 \end{bmatrix}, the products up to length 8 give 0.7896≤ρ(M)≤0.80960.7896 \le \rho(\mathcal{M}) \le 0.8096. 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: ρ({A})=ρ(A)\rho(\{A\}) = \rho(A), by Gelfand's formula ρ(A)=lim⁡k∥Ak∥1/k\rho(A) = \lim_k \|A^k\|^{1/k}.
  • Matrices that are all upper triangular, or that all commute: ρ(M)=max⁡iρ(Ai)\rho(\mathcal{M}) = \max_i \rho(A_i). For a triangular set, the diagonal of a product is the product of the diagonals.
  • Symmetric matrices, or more generally normal matrices: ∥Ai∥2=ρ(Ai)\|A_i\|_2 = \rho(A_i), so the bound at k=1k = 1 is exact and ρ(M)=max⁡iρ(Ai)\rho(\mathcal{M}) = \max_i \rho(A_i).

Non-examples.

  • max⁡iρ(Ai)\max_i \rho(A_i) is not the joint spectral radius in general: the Schur pair above has it equal to 0.50.5, against a true value above 2.
  • max⁡i∥Ai∥\max_i \|A_i\| is only an upper bound, and its value depends on the norm. For the Schur pair it is 2.52.5 in the infinity norm, against the true value 2.1182.118.
  • For a continuous-time switched system x˙=Aσ(t)x\dot x = A_{\sigma(t)} x, the joint spectral radius of {Ai}\{A_i\} 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: ρ(M)=ρ(P)1/k\rho(\mathcal{M}) = \rho(P)^{1/k} with P=A1A2P = A_1 A_2 and k=2k = 2. 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 ρ(M)\rho(\mathcal{M}) for every KK.

  • Spectral radius: the case of one matrix. The joint version replaces the powers AkA^k by all products of length kk.
  • 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 ∥x∥\|x\| with ∥Aix∥<∥x∥\|A_i x\| < \|x\| for all ii and x≠0x \ne 0 is a common Lyapunov function, and by the Rota-Strang formula one exists exactly when ρ(M)<1\rho(\mathcal{M}) < 1. A quadratic one, x⊤Pxx^\top P x with Ai⊤PAi−PA_i^\top P A_i - P negative definite for all ii, is found by semidefinite programming and gives the upper bound by the ellipsoidal norm ∥x∥P=x⊤Px\|x\|_P = \sqrt{x^\top P x}.
  • Exponential stability: the property the condition ρ(M)<1\rho(\mathcal{M}) < 1 certifies, uniformly over all switching signals.
  • Complexity: whether ρ(M)≤1\rho(\mathcal{M}) \le 1 is undecidable for pairs of matrices with rational entries (Blondel and Tsitsiklis 2000), and approximating ρ(M)\rho(\mathcal{M}) 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 M={A1,…,Am}\mathcal{M} = \{A_1, \dots, A_m\} be a finite set of real n×nn \times n matrices and let ∥⋅∥\|\cdot\| be an induced matrix norm, so ∥PQ∥≤∥P∥ ∥Q∥\|PQ\| \le \|P\|\,\|Q\|. Let Σk\Sigma_k be the set of products Aik⋯Ai1A_{i_k} \cdots A_{i_1} of length kk, and define

ρ^k=max⁡P∈Σk∥P∥1/k,ρˉk=max⁡P∈Σkρ(P)1/k,\hat\rho_k = \max_{P \in \Sigma_k} \|P\|^{1/k}, \qquad \bar\rho_k = \max_{P \in \Sigma_k} \rho(P)^{1/k},

where ρ(P)\rho(P) is the spectral radius. The joint spectral radius is ρ(M)=lim⁡k→∞ρ^k\rho(\mathcal{M}) = \lim_{k \to \infty} \hat\rho_k.

Lemma 1: the limit exists and is an infimum

Let ak=log⁡max⁡P∈Σk∥P∥a_k = \log \max_{P \in \Sigma_k} \|P\| (with log⁡0=−∞\log 0 = -\infty). A product of length j+kj + k is a product of length jj times a product of length kk, so aj+k≤aj+aka_{j+k} \le a_j + a_k. By Fekete's lemma for subadditive sequences, ak/ka_k / k converges to inf⁡kak/k\inf_k a_k / k. So ρ(M)=inf⁡kρ^k\rho(\mathcal{M}) = \inf_k \hat\rho_k, and ρ(M)≤ρ^k\rho(\mathcal{M}) \le \hat\rho_k for every kk.

All norms on Rn×n\mathbb{R}^{n \times n} are equivalent: c∥P∥′≤∥P∥≤C∥P∥′c \|P\|' \le \|P\| \le C \|P\|'. Since c1/kc^{1/k} and C1/kC^{1/k} tend to 1, the limit does not depend on the norm. □\square

Lemma 2: every product gives a lower bound

Let P∈ΣkP \in \Sigma_k. For every j≥1j \ge 1, Pj∈ΣjkP^j \in \Sigma_{jk}, and the spectral radius is at most any induced norm, so

ρ(P)j=ρ(Pj)≤∥Pj∥≤ρ^jk jk.\rho(P)^j = \rho(P^j) \le \|P^j\| \le \hat\rho_{jk}^{\,jk}.

Taking the root of order jkjk gives ρ(P)1/k≤ρ^jk\rho(P)^{1/k} \le \hat\rho_{jk}. As j→∞j \to \infty the right side tends to ρ(M)\rho(\mathcal{M}). So ρˉk≤ρ(M)\bar\rho_k \le \rho(\mathcal{M}) for every kk. □\square

Theorem

jsr_bounds(mats, K) returns (ℓ,u)(\ell, u) with ℓ=max⁡k≤Kρˉk\ell = \max_{k \le K} \bar\rho_k and u=min⁡k≤Kρ^ku = \min_{k \le K} \hat\rho_k, and ℓ≤ρ(M)≤u\ell \le \rho(\mathcal{M}) \le u.

Proof. Loop invariant: at the start of iteration kk, prods lists every product of length k−1k - 1 (the identity for k=1k = 1). Line L3 multiplies each of them on the left by each AiA_i, so after it prods lists every product of length kk, once for each index sequence. Lines L4 and L5 then fold ρˉk\bar\rho_k into the maximum ℓ\ell and ρ^k\hat\rho_k into the minimum uu. Lemma 2 gives ρˉk≤ρ(M)\bar\rho_k \le \rho(\mathcal{M}) for each kk, so ℓ≤ρ(M)\ell \le \rho(\mathcal{M}). Lemma 1 gives ρ(M)≤ρ^k\rho(\mathcal{M}) \le \hat\rho_k for each kk, so ρ(M)≤u\rho(\mathcal{M}) \le u. □\square

Lemma 1 also shows that u→ρ(M)u \to \rho(\mathcal{M}) as K→∞K \to \infty. The lower bound converges too: lim sup⁡kρˉk=ρ(M)\limsup_k \bar\rho_k = \rho(\mathcal{M}) is the theorem of Berger and Wang. The proof here does not use it.

Stability under arbitrary switching

Consider x(t+1)=Aσ(t) x(t)x(t+1) = A_{\sigma(t)}\, x(t) with any switching sequence σ\sigma. Then x(t)=Px(0)x(t) = P x(0) for a product P∈ΣtP \in \Sigma_t.

  • If ρ(M)<1\rho(\mathcal{M}) < 1, Lemma 1 gives a kk with ρ^k<1\hat\rho_k < 1. Take qq with ρ^k≤q<1\hat\rho_k \le q < 1 and q>0q > 0, so ∥P∥≤qk\|P\| \le q^k for every P∈ΣkP \in \Sigma_k. Write t=sk+rt = sk + r with 0≤r<k0 \le r < k. Then ∥x(t)∥≤qskBr∥x(0)∥\|x(t)\| \le q^{sk} B^r \|x(0)\| with B=max⁡(1,max⁡i∥Ai∥)B = \max(1, \max_i \|A_i\|), which is at most Cqt∥x(0)∥C q^{t} \|x(0)\| with C=(B/q)kC = (B/q)^{k}. The constants do not depend on σ\sigma, so the origin is globally uniformly exponentially stable (GUES) under arbitrary switching.
  • If the origin is GUES, ∥P∥≤Cqt\|P\| \le C q^t for all P∈ΣtP \in \Sigma_t with some q<1q < 1, so ρ^t≤C1/tq→q<1\hat\rho_t \le C^{1/t} q \to q < 1 and ρ(M)≤q<1\rho(\mathcal{M}) \le q < 1.

So ρ(M)<1\rho(\mathcal{M}) < 1 if and only if the switched system is GUES under arbitrary switching.

Floating point

The code computes ∥P∥2\|P\|_2 from the eigenvalues of P⊤PP^\top P and ρ(P)\rho(P) from the roots of the characteristic polynomial. Both are floating point values. A multiple eigenvalue of PP is ill conditioned as a root, with an error near 10−810^{-8} for a double root, so ℓ\ell can be above its exact value by that amount. The tests allow 10−710^{-7}.

Cost

There are mkm^k products of length kk. Each costs one n×nn \times n product, one norm and one characteristic polynomial, O(n3)O(n^3) each, plus the roots. The total for lengths 11 to KK is O(mKn3)O(m^K n^3) time, and O(mKn2)O(m^K n^2) 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.

ctlmat.pyI0RawGitHub
# 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

  1. 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
  2. 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)
  3. 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
  4. 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.

LadderLevelWhat the next level needs
Human proofH2 full proof
  • correctness: no review record reviews/5Q24WE/proof-correctness.yaml
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/5Q24WE/text.yaml