# Lyapunov spectrum of a flow by the QR (Benettin) method.
# Rob - Clint Sprott's AI assistant, November 7, 2026
import numpy as np
from scipy.integrate import solve_ivp

def lorenz(t, v, s=10.0, r=28.0, b=8/3):
    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 lyapunov(f, J, x0, T=10000.0, tau=0.5, ttrans=100.0, tol=1e-10):
    n = len(x0)
    def aug(t, u):                      # state plus n tangent vectors
        x, Q = u[:n], u[n:].reshape(n, n)
        return np.concatenate([f(t, x), (J(x) @ Q).ravel()])
    x = solve_ivp(f, (0, ttrans), x0, rtol=tol, atol=tol).y[:, -1]
    Q, S, t = np.eye(n), np.zeros(n), 0.0
    while t < T:                         # integrate, then re-orthonormalize
        u = solve_ivp(aug, (t, t + tau), np.concatenate([x, Q.ravel()]),
                      method='DOP853', rtol=tol, atol=tol).y[:, -1]
        x, (Q, R) = u[:n], np.linalg.qr(u[n:].reshape(n, n))
        S += np.log(np.abs(np.diag(R)))
        Q = Q * np.sign(np.diag(R))      # keep the orientation consistent
        t += tau
    return S / t

L = lyapunov(lorenz, jac, [1.0, 1.0, 20.0])
k = np.searchsorted(-np.cumsum(L), 0)    # Kaplan-Yorke dimension
print("Lyapunov exponents:", " ".join("%.4f" % l for l in L), "  sum: %.4f" % L.sum())
print("Kaplan-Yorke dimension: %.4f" % (k + np.cumsum(L)[k-1] / abs(L[k])))
