"""Numerical check for the Lyapunov result (Math.SE 2922967).
For Hurwitz A put c = 1/(-2 tr A), and let P(X) solve A P + P A^T = -X.
Claim: ||P(X)||_2 >= c for every density matrix X, and the minimum over X equals c.
 (1) random X:  ||P(X)|| / c >= 1
 (2) random Y:  lambda_min(Q(Y)) / c <= 1, where A^T Q + Q A = -Y
 (3) a saddle-point iteration drives ||P(X)|| / c down to 1."""
import numpy as np
rng = np.random.default_rng(3)

def lyap(A, X):                      # solve A P + P A^T = -X
    n = len(A); I = np.eye(n)
    return np.linalg.solve(np.kron(A, I) + np.kron(I, A), -X.reshape(-1)).reshape(n, n)
def sym(M): return (M + M.T) / 2
def norm2(P): return np.linalg.eigvalsh(sym(P))[-1]
def density(n):
    B = rng.normal(size=(n, rng.integers(1, n + 1))); X = B @ B.T; return X / np.trace(X)
def expm_density(H):
    w, V = np.linalg.eigh(sym(H)); w = np.exp(w - w.max()); M = (V * w) @ V.T
    return M / np.trace(M)

def minimise(A, c, iters=4000):
    n = len(A); eta = 1.0 / c; SQ = np.zeros((n, n)); SP = np.zeros((n, n)); Xavg = np.zeros((n, n))
    for t in range(1, iters + 1):
        X = expm_density(-eta * SQ / np.sqrt(t)); Y = expm_density(eta * SP / np.sqrt(t))
        SQ += sym(lyap(A.T, Y)); SP += sym(lyap(A, X)); Xavg += X
    return norm2(lyap(A, Xavg / iters)) / c

lo_primal = 9.0; hi_dual = 0.0; gaps = []; trials = 0
for n in (2, 3, 4, 6, 8):
    for _ in range(30):
        A = rng.normal(size=(n, n)) * rng.uniform(.3, 3)
        A = A - (max(np.linalg.eigvals(A).real) + rng.uniform(.05, 2)) * np.eye(n)   # Hurwitz
        c = 1 / (-2 * np.trace(A)); trials += 1
        for _ in range(40):
            lo_primal = min(lo_primal, norm2(lyap(A, density(n))) / c)
            hi_dual = max(hi_dual, np.linalg.eigvalsh(sym(lyap(A.T, density(n))))[0] / c)
        gaps.append(minimise(A, c) - 1)
print(f'{trials} random Hurwitz matrices, n = 2..8')
print(f'(1) smallest ||P(X)|| / c over random X : {lo_primal:.6f}   (claim: >= 1)')
print(f'(2) largest lambda_min(Q(Y)) / c        : {hi_dual:.6f}   (claim: <= 1)')
print(f'(3) after optimisation, ||P(X)|| / c - 1: median {np.median(gaps):.1e}, worst {max(gaps):.1e}   (claim: tends to 0)')
