"""Checks for the Library article "GUE eigenvalues as a determinantal point process".

Conventions of the chapter: one eigenvalue weight e^{-x^2}, orthonormal Hermite functions phi_j with
phi_0 = pi^{-1/4} e^{-x^2/2}, and K_N(x, y) = sum_{j<N} phi_j(x) phi_j(y). The GUE density is proportional
to exp(-tr H^2); the soft edge is x = sqrt(2N) + s / (sqrt(2) N^{1/6}).

1. Finite N. The probability that an interval J holds no eigenvalue is det(I - K_N) on J. It is computed
   by Gauss-Legendre quadrature of the Fredholm determinant and, independently, as det(I - G) for the
   N x N Gram matrix G_jk = int_J phi_j phi_k; then compared with sampled GUE matrices. Controls:
   independent points with the same one-point density, and sampled GOE matrices, disagree.
2. Bulk. Unfolded central gaps converge to the sine-kernel determinant E_2(0; s); the Wigner surmise
   misses it at the 10^-3 level and the Poisson law e^{-s} by much more. The number of levels in L mean
   spacings has variance approaching (log 2 pi L + gamma + 1)/pi^2 (Dyson-Mehta), checked on sampled
   matrices; independent levels would give L.
3. Edge. F_2(s) = det(I - K_Ai) on (s, inf) agrees with exp(-int_s^inf (x - s) q^2) for the Hastings-McLeod
   solution q of Painleve II, and its mean and variance reproduce the Tracy-Widom values. F_1 follows from
   F_1 = exp(-1/2 int_s^inf q) F_2^{1/2}. Sampled GUE and GOE largest eigenvalues follow F_2 and F_1
   respectively, and not each other. With the GUE centering sqrt(2N) the GOE mean approaches its limit
   slowly; centering the GOE at sqrt(2N - 1) removes most of that shift in these samples (an observation).
Run with Python 3, NumPy and SciPy:  python3 determinantal_core.py
"""
import numpy as np
from numpy.polynomial.legendre import leggauss
from scipy.integrate import solve_ivp
from scipy.special import airy

TW2_MEAN, TW2_VAR = -1.7710868074, 0.8131947928      # Tracy-Widom unitary, from the literature
TW1_MEAN, TW1_VAR = -1.2065335746, 1.6077810346      # Tracy-Widom orthogonal


def hermite_functions(x, n):
    """Rows phi_0 .. phi_{n-1} at the points x (normalized three-term recurrence)."""
    x = np.asarray(x, float)
    out = np.empty((n, x.size))
    prev, cur = np.zeros_like(x), np.pi ** -0.25 * np.exp(-x * x / 2)
    for j in range(n):
        out[j] = cur
        prev, cur = cur, np.sqrt(2 / (j + 1)) * x * cur - np.sqrt(j / (j + 1)) * prev
    return out


def nodes(a, b, m):
    t, w = leggauss(m)
    return 0.5 * (b - a) * t + 0.5 * (b + a), 0.5 * (b - a) * w


def fredholm(kernel, a, b, m=60):
    """det(I - K) on L^2(a, b) by Bornemann's Gauss-Legendre method."""
    x, w = nodes(a, b, m)
    sw = np.sqrt(w)
    return np.linalg.det(np.eye(m) - sw[:, None] * kernel(x[:, None], x[None, :]) * sw[None, :])


def gap_finite(n, a, b, m=80):
    phi = lambda x: hermite_functions(np.ravel(x), n)
    def K(x, y):
        X, Y = phi(x[:, 0]), phi(y[0, :])
        return X.T @ Y
    return fredholm(K, a, b, m)


def gap_gram(n, a, b, m=200):
    x, w = nodes(a, b, m)
    P = hermite_functions(x, n)
    G = (P * w) @ P.T
    return np.linalg.det(np.eye(n) - G)


def sine_kernel(x, y):
    d = x - y
    with np.errstate(invalid='ignore', divide='ignore'):
        return np.where(np.abs(d) < 1e-12, 1.0, np.sin(np.pi * d) / (np.pi * d))


def airy_kernel(x, y):
    ax, apx, _, _ = airy(x)
    ay, apy, _, _ = airy(y)
    d = x - y
    with np.errstate(invalid='ignore', divide='ignore'):
        off = (ax * apy - apx * ay) / d
    diag = apx ** 2 - x * ax ** 2
    return np.where(np.abs(d) < 1e-12, diag, off)


def sine_number_variance(L, m=600):
    """Variance of the number of sine-kernel points in an interval of L mean spacings."""
    u, w = nodes(0.0, L, m)
    k = np.where(u < 1e-12, 1.0, np.sin(np.pi * u) / (np.pi * u))
    return L - 2 * np.sum(w * (L - u) * k ** 2)


def finite_count_moments(n, a, b, m=120):
    """Mean and variance of the GUE eigenvalue count in (a, b) from K_N: int K(x,x) - int int K(x,y)^2."""
    x, w = nodes(a, b, m)
    P = hermite_functions(x, n)
    K = P.T @ P
    mean = np.sum(w * np.diag(K))
    return mean, mean - np.sum((w[:, None] * K * w[None, :]) * K)


def F2(s, m=60, length=14.0):
    return fredholm(airy_kernel, s, s + length, m)


def E2(s, m=40):
    """Sine-kernel probability of no level in an unfolded interval of length s."""
    return fredholm(sine_kernel, 0.0, s, m) if s > 0 else 1.0


def wigner_gap(s, m=200):
    """Gap probability implied by the beta = 2 Wigner surmise p(u) = (32/pi^2) u^2 exp(-4u^2/pi)."""
    u, w = nodes(s, s + 8.0, m)
    return np.sum(w * (u - s) * (32 / np.pi ** 2) * u ** 2 * np.exp(-4 * u ** 2 / np.pi))


def hastings_mcleod(s_min=-8.0, s0=8.0):
    """Dense solution of q'' = 2q^3 + sq started from Airy data at s0 and integrated backward."""
    a, ap, _, _ = airy(s0)
    rhs = lambda s, y: [y[1], 2 * y[0] ** 3 + s * y[0]]
    return solve_ivp(rhs, (s0, s_min), [a, ap], method='DOP853', rtol=1e-13, atol=1e-15, dense_output=True).sol


def tw_from_q(sol, s, s0=8.0, m=120):
    """F_2 and F_1 at s from the Painleve II solution; the tail beyond s0 uses q ~ Ai."""
    x, w = nodes(s, s0, m)
    q = sol(x)[0]
    tail_x, tail_w = nodes(s0, s0 + 10, 40)
    tq = airy(tail_x)[0]
    log_f2 = -(np.sum(w * (x - s) * q ** 2) + np.sum(tail_w * (tail_x - s) * tq ** 2))
    int_q = np.sum(w * q) + np.sum(tail_w * tq)
    return np.exp(log_f2), np.exp(-0.5 * int_q + 0.5 * log_f2)


def moments(cdf, lo=-12.0, hi=8.0, m=120):
    """Mean and variance of a distribution on the line from its distribution function."""
    xl, wl = nodes(lo, 0.0, m)
    xr, wr = nodes(0.0, hi, m)
    Fl, Fr = np.array([cdf(x) for x in xl]), np.array([cdf(x) for x in xr])
    mean = np.sum(wr * (1 - Fr)) - np.sum(wl * Fl)
    second = 2 * np.sum(wr * xr * (1 - Fr)) - 2 * np.sum(wl * xl * Fl)
    return mean, second - mean ** 2


def sample_gue(n, count, rng):
    A = rng.normal(0, np.sqrt(0.5), (count, n, n)) + 1j * rng.normal(0, np.sqrt(0.5), (count, n, n))
    return np.linalg.eigvalsh((A + np.conj(np.swapaxes(A, 1, 2))) / 2)


def sample_goe(n, count, rng):
    A = rng.normal(0, 1, (count, n, n))
    return np.linalg.eigvalsh((A + np.swapaxes(A, 1, 2)) / 2)


def edge(n):
    return np.sqrt(2 * n), 1 / (np.sqrt(2) * n ** (1 / 6))


def main():
    rng = np.random.default_rng(20261125)
    checks, controls = {}, {}

    # 1. Finite N: two exact evaluations and sampled matrices.
    n, samples = 8, 400000
    b, l = edge(n)
    intervals = {'bulk (-0.5, 0.5)': (-0.5, 0.5), 'edge (b - l, inf)': (b - l, b - l + 14 * l + 8)}
    eig = sample_gue(n, samples, rng)
    goe = sample_goe(n, samples, rng)
    worst_exact, worst_mc = 0.0, 0.0
    for name, (lo, hi) in intervals.items():
        quad, gram = gap_finite(n, lo, hi), gap_gram(n, lo, hi)
        empty = np.mean(~np.any((eig > lo) & (eig < hi), axis=1))
        se = np.sqrt(empty * (1 - empty) / samples)
        x, w = nodes(lo, hi, 200)
        mass = np.sum(w * np.sum(hermite_functions(x, n) ** 2, axis=0))
        indep = (1 - mass / n) ** n
        goe_empty = np.mean(~np.any((goe > lo) & (goe < hi), axis=1))
        worst_exact = max(worst_exact, abs(quad - gram))
        worst_mc = max(worst_mc, abs(empty - quad) / se)
        print(f'N = {n}, J = {name}: det(I - K_N) = {quad:.10f} (Gram {gram:.10f}); sampled GUE {empty:.5f} +- {se:.5f}; '
              f'independent points {indep:.5f}; sampled GOE {goe_empty:.5f}')
        controls[f'independent points with the same density miss the {name.split()[0]} gap'] = abs(indep - quad) > 10 * se
        controls[f'GOE matrices miss the GUE {name.split()[0]} gap'] = abs(goe_empty - quad) > 10 * se
    checks['quadrature and Gram determinants agree (1e-12)'] = worst_exact < 1e-12
    checks['sampled GUE gaps agree with det(I - K_N) within 3 standard errors'] = worst_mc < 3

    # 2. Bulk: finite-N central gaps against the sine kernel and the Wigner surmise.
    s = 1.0
    e_sine = E2(s)
    print(f'sine-kernel gap E_2(0; 1) = {e_sine:.10f}; Wigner surmise gives {wigner_gap(s):.10f}; Poisson exp(-1) = {np.exp(-1):.10f}')
    finite = {}
    for N in (8, 32, 128):
        spacing = np.pi / np.sqrt(2 * N)
        finite[N] = gap_finite(N, -s * spacing / 2, s * spacing / 2)
        print(f'  N = {N:3d}: central gap of unfolded length 1 = {finite[N]:.8f}, difference from the sine kernel {finite[N] - e_sine:+.2e}')
    checks['central finite-N gaps converge to the sine kernel'] = (abs(finite[128] - e_sine) < abs(finite[32] - e_sine) < abs(finite[8] - e_sine)
                                                                  and abs(finite[128] - e_sine) < 5e-4)
    surmise_gap = max(abs(E2(x) - wigner_gap(x)) for x in np.linspace(0.2, 2.0, 10))
    print(f'largest |E_2 - Wigner surmise| on 0.2 <= s <= 2: {surmise_gap:.2e}')
    controls['the Wigner surmise is not the sine-kernel law (difference above 1e-4, far above quadrature error)'] = surmise_gap > 1e-4
    controls['the Poisson law exp(-s) is far from it (difference above 0.1)'] = abs(np.exp(-1) - e_sine) > 0.1

    # Rigidity: the count in L mean spacings has variance ~ (log 2 pi L + gamma + 1) / pi^2, not L.
    asym = lambda L: (np.log(2 * np.pi * L) + np.euler_gamma + 1) / np.pi ** 2
    for L in (10, 100):
        print(f'sine-kernel number variance at L = {L}: {sine_number_variance(L):.7f}; Dyson-Mehta asymptotic {asym(L):.7f}')
    checks['sine-kernel number variance approaches the Dyson-Mehta law (1e-4 at L = 10, 1e-6 at L = 100)'] = (
        abs(sine_number_variance(10) - asym(10)) < 1e-4 and abs(sine_number_variance(100) - asym(100)) < 1e-6)
    n_var, width = 200, 10 * np.pi / np.sqrt(400)
    counts = np.concatenate([np.sum(np.abs(sample_gue(n_var, 250, rng)) < width / 2, axis=1) for _ in range(8)])
    exact_mean, exact_var = finite_count_moments(n_var, -width / 2, width / 2)
    var_se = counts.var() * np.sqrt(2 / len(counts))
    print(f'GUE N = {n_var}, central interval of 10 mean spacings: sampled count mean {counts.mean():.3f}, variance {counts.var():.4f} +- {var_se:.4f}; '
          f'from K_N {exact_mean:.4f} and {exact_var:.4f}; sine kernel {sine_number_variance(10):.4f}; independent levels 10')
    checks['sampled count variance agrees with the kernel within 3 standard errors'] = abs(counts.var() - exact_var) < 3 * var_se
    controls['independent levels would have a count variance more than ten times larger'] = 10 > 10 * exact_var

    # 3. Edge: Fredholm determinant against Painleve II, moments, and sampled matrices.
    sol = hastings_mcleod()
    worst_pii = 0.0
    for x in (-4.0, -2.0, 0.0, 2.0):
        f_det = F2(x)
        f_pii, f1 = tw_from_q(sol, x)
        worst_pii = max(worst_pii, abs(f_det - f_pii))
        print(f'  s = {x:+.1f}: F_2 = {f_det:.10f} (Painleve II {f_pii:.10f}), F_1 = {f1:.10f}')
    print(f'largest |Airy determinant - Painleve II formula| for F_2: {worst_pii:.1e}')
    checks['F_2 from the Airy determinant equals the Painleve II formula (5e-9)'] = worst_pii < 5e-9
    checks['F_2(0) and F_2(-2) match the chapter (0.969373, 0.413224)'] = abs(F2(0.0) - 0.969373) < 1e-6 and abs(F2(-2.0) - 0.413224) < 1e-6
    m2, v2 = moments(F2)
    m1, v1 = moments(lambda x: tw_from_q(sol, x)[1])
    print(f'Tracy-Widom unitary: mean {m2:.8f}, variance {v2:.8f}; orthogonal: mean {m1:.8f}, variance {v1:.8f}')
    checks['TW2 mean and variance reproduce the literature (1e-6)'] = abs(m2 - TW2_MEAN) < 1e-6 and abs(v2 - TW2_VAR) < 1e-6
    checks['TW1 mean and variance reproduce the literature (1e-6)'] = abs(m1 - TW1_MEAN) < 1e-6 and abs(v1 - TW1_VAR) < 1e-6

    n_big, count = 100, 20000
    b, l = edge(n_big)
    s_gue = (sample_gue(n_big, count, rng)[:, -1] - b) / l
    top_goe = sample_goe(n_big, count, rng)[:, -1]
    s_goe, s_goe_shifted = (top_goe - b) / l, (top_goe - np.sqrt(2 * n_big - 1)) / l
    for name, data in (('GUE', s_gue), ('GOE, centered at sqrt(2N)', s_goe), ('GOE, centered at sqrt(2N - 1)', s_goe_shifted)):
        print(f'{name}, N = {n_big}: scaled largest eigenvalue mean {data.mean():.4f} +- {np.sqrt(data.var() / count):.4f}, '
              f'variance {data.var():.4f} +- {data.var() * np.sqrt(2 / count):.4f}')
    grid = (-3.0, -2.0, -1.0, 0.0)
    F1 = lambda x: tw_from_q(sol, x)[1]
    ks_gue = max(abs(np.mean(s_gue <= x) - F2(x)) for x in grid)
    ks_goe = max(abs(np.mean(s_goe <= x) - F1(x)) for x in grid)
    ks_goe_shift = max(abs(np.mean(s_goe_shifted <= x) - F1(x)) for x in grid)
    ks_goe_vs_f2 = max(abs(np.mean(s_goe_shifted <= x) - F2(x)) for x in grid)
    print(f'largest distribution-function difference at s = -3, -2, -1, 0: GUE vs F_2 {ks_gue:.4f}; GOE vs F_1 {ks_goe:.4f} '
          f'(centered at sqrt(2N)) and {ks_goe_shift:.4f} (centered at sqrt(2N - 1)); GOE vs F_2 {ks_goe_vs_f2:.4f}')
    small = sample_goe(25, 20000, rng)[:, -1]
    b25, l25 = edge(25)
    shift_25 = np.mean((small - b25) / l25) - np.mean((small - np.sqrt(49)) / l25)
    print(f'GOE mean shift from the two centerings: {shift_25:.4f} at N = 25 and {np.mean(s_goe) - np.mean(s_goe_shifted):.4f} at N = 100 '
          f'(about N^(-1/3)/2: {0.5 * 25 ** (-1 / 3):.4f} and {0.5 * 100 ** (-1 / 3):.4f})')
    checks['sampled GUE largest eigenvalues follow F_2 (within 0.02 at N = 100)'] = ks_gue < 0.02
    checks['sampled GOE largest eigenvalues follow F_1 once centered at sqrt(2N - 1) (within 0.02)'] = ks_goe_shift < 0.02
    controls['GOE largest eigenvalues do not follow F_2 (difference above 0.1)'] = ks_goe_vs_f2 > 0.1

    for name, ok in checks.items():
        print(f"{'PASS' if ok else 'FAIL'}  {name}")
    for name, ok in controls.items():
        print(f"{'PASS' if ok else 'FAIL'}  control: {name}")
    if not all(checks.values()) or not all(controls.values()):
        raise SystemExit(1)
    print('Finite kernels, sampled matrices, the sine and Airy limits and both Tracy-Widom laws agree; controls fail.')


if __name__ == '__main__':
    main()
