# Lyapunov spectrum by the QR method, with each exponent's precision estimated
# by batch means.  Rob - Clint Sprott's AI assistant, November 7, 2026
import numpy as np
from scipy.integrate import solve_ivp

def f(t, v, s=10.0, r=28.0, b=8/3):      # Lorenz system
    x, y, z = v
    return [s*(y - x), r*x - y - x*z, x*y - b*z]

def jac(v, s=10.0, r=28.0, b=8/3):
    x, y, z = v
    return np.array([[-s, s, 0], [r - z, -1, -x], [y, x, -b]])

def fmt(x, e):                           # e.g. 0.9063 +- 0.0021 -> 0.906(2)
    d = -int(np.floor(np.log10(e))); u = round(e * 10.0**d)
    if u == 10: d, u = d - 1, 1
    return "%.*f(%d)" % (d, x, u) if d > 0 else "%.0f(%d)" % (x, u * 10**-d)

def spectrum(x0, T=10000.0, tau=0.5, blocks=40, ttrans=100.0, tol=1e-10):
    n = len(x0)
    aug = lambda t, u: np.concatenate([f(t, u[:n]), (jac(u[:n]) @ u[n:].reshape(n, n)).ravel()])
    x = solve_ivp(f, (0, ttrans), x0, rtol=tol, atol=tol).y[:, -1]
    Q, logs = np.eye(n), []
    for i in range(int(T / tau)):         # integrate tau, then re-orthonormalize
        u = solve_ivp(aug, (0, tau), np.concatenate([x, Q.ravel()]),
                      method='DOP853', rtol=tol, atol=tol).y[:, -1]
        Q, R = np.linalg.qr(u[n:].reshape(n, n)); x = u[:n]
        logs.append(np.log(np.abs(np.diag(R)))); Q = Q * np.sign(np.diag(R))
    L = np.array(logs).reshape(blocks, -1, n).sum(1) / (T / blocks)   # block averages
    return L.mean(0), L.std(0, ddof=1) / np.sqrt(blocks), L

lam, err, L = spectrum([1.0, 1.0, 20.0])
for i in range(len(lam)): print("lambda%d = %s" % (i + 1, fmt(lam[i], err[i])))
print("sum      = %.6f  (should equal the divergence, %.6f)" % (lam.sum(), -(10 + 1 + 8/3)))
D = 2 + L[:, 0] / np.abs(L[:, 2])        # Kaplan-Yorke dimension of each block
print("D_KY     = %s" % fmt(D.mean(), D.std(ddof=1) / np.sqrt(len(D))))
