"""Checks for the Library article "TASEP and the Tracy-Widom law".

Step-initial TASEP on Z: particle n starts at 1 - n (n = 1, 2, ...), jumps one site right at rate one when the target
is empty, and J(t) counts crossings of the bond 0 -> 1. With last-passage times T(k, n) of independent unit
exponentials, {J(t) >= n} = {T(n, n) <= t} (Rost's coupling). T(n, n) has the law of the largest eigenvalue of G*G
for an n x n matrix G of independent standard complex normals, E|g|^2 = 1 (Johansson, Proposition 1.4). With the
Laguerre functions phi_j(x) = L_j(x) e^{-x/2} this gives
    P(J(t) >= n) = det[ int_0^t phi_j(x) phi_k(x) dx ]_{j,k=0}^{n-1},
the nth leading principal minor of a single Gram matrix, a product of elimination pivots. Under
(t/4 - J(t)) / (2^{-4/3} t^{1/3}) the law tends to the GUE Tracy-Widom distribution F2 (Johansson, Theorem 1.6).

Checks:
  1. F2 = det(I - K_Airy) by Gauss-Legendre Nystrom: mean -1.7710868074 and variance 0.8131947928, unchanged to 1e-9
     when the step is halved and the nodes raised from 60 to 80, and equal to the eight-digit values quoted elsewhere;
  2. the Gram minors at t = 12 equal the Hankel determinants det[A_{j+k}(t)] / prod_k (k!)^2, with
     A_d(t) = int_0^t x^d e^{-x} dx in 40-digit arithmetic, for n = 1, ..., 8 (1e-12); n = 1, 2 are 1 - e^{-t} and
     A_0 A_2 - A_1^2; as t -> 0, P(J(t) >= n) / t^{n^2} tends to det[1/(j+k+1)] / prod_k (k!)^2 for n = 2, 3, 4;
  3. a direct Gillespie simulation of TASEP and sampled last-passage times both follow the exact law of J(12)
     (total variation below 0.02 for 20000 samples each);
  4. at n = 6 sampled last-passage times and largest eigenvalues of sampled complex Wishart matrices follow the
     exact distribution (one-sample Kolmogorov-Smirnov statistic below the 0.1% critical value 1.95/sqrt(20000));
  5. the exact Kolmogorov distance between (T(n,n) - 4n)/(2^{4/3} n^{1/3}) and F2 falls at each doubling of n from
     25 to 400 and is below 0.03 at n = 400; P(J(1000) >= 250) computed as a Gram minor on [0, 1000] and as
     det(I - K_250) on [1000, infinity) agrees to 1e-12;
  6. exact mean and variance of J(t) for t = 100, 200, ..., 1600: the scaled mean and variance approach -1.7711 and
     0.8132 at every doubling of t, and the log-log slope of the variance between t = 800 and 1600 lies in
     (0.64, 0.69); doubling the quadrature panels changes no probability by more than 1e-12.
Controls: without exclusion the particles are independent and Var J(t) = sum_n P(K >= n) P(K < n) with K Poisson(t),
which grows like sqrt(t/pi) with slope in (0.49, 0.51); last-passage times with Gaussian weights of mean and variance
one fail the n = 6 test (Kolmogorov-Smirnov statistic above three times its critical value).
Run with Python 3, NumPy, SciPy and mpmath:  python3 tasep_tracy_widom_check.py   (about 15 seconds)
"""
import random

import mpmath as mp
import numpy as np
from scipy.special import airy, gammainc, gammaln

TW_MEAN, TW_VAR = -1.7710868074, 0.8131947928      # computed by tw_moments below; quoted to eight digits elsewhere
rng = np.random.default_rng(20261125)
pyrng = random.Random(20261125)


def F2(s, m=60, length=16.0):
    """GUE Tracy-Widom distribution: Fredholm determinant of the Airy kernel on [s, s + length] (Nystrom)."""
    x, w = np.polynomial.legendre.leggauss(m)
    x, w = s + (x + 1) * length / 2, w * length / 2
    ai, aip, _, _ = airy(x)
    with np.errstate(divide='ignore', invalid='ignore'):
        K = (ai[:, None] * aip[None, :] - aip[:, None] * ai[None, :]) / (x[:, None] - x[None, :])
    K[np.diag_indices(m)] = aip ** 2 - x * ai ** 2
    sw = np.sqrt(w)
    return np.linalg.det(np.eye(m) - sw[:, None] * K * sw[None, :])


def tw_moments(lo=-9.0, hi=7.0, h=0.005, m=60):
    """Mean and variance of F2 from E g(S) = g(hi) - int_lo^hi g'(s) F2(s) ds by Simpson's rule."""
    s = np.arange(lo, hi + h / 2, h)
    F = np.array([F2(v, m) for v in s])
    wts = np.ones(len(s))
    wts[1:-1:2], wts[2:-1:2] = 4, 2
    mean = hi - h / 3 * np.sum(wts * F)
    second = hi ** 2 - h / 3 * np.sum(wts * 2 * s * F)
    return mean, second - mean ** 2, s, F


def laguerre_functions(n, x):
    """phi_j(x) = L_j(x) e^{-x/2}, j < n, by the three-term recurrence; a running scale avoids under- and overflow."""
    x = np.asarray(x, dtype=float)
    phi = np.empty((n, x.size))
    prev, cur, log_scale = np.zeros_like(x), np.ones_like(x), -x / 2
    phi[0] = np.exp(log_scale)
    for j in range(n - 1):
        prev, cur = cur, ((2 * j + 1 - x) * cur - j * prev) / (j + 1)
        big = np.abs(cur) > 1e100
        if big.any():
            scale = np.abs(cur[big])
            prev[big] /= scale
            cur[big] /= scale
            log_scale[big] += np.log(scale)
        phi[j + 1] = cur * np.exp(log_scale)
    return phi


def gram(n, edges, nodes=40):
    """int phi_j phi_k dx over the union of the panels [edges[i], edges[i+1]], composite Gauss-Legendre."""
    g, w = np.polynomial.legendre.leggauss(nodes)
    half, mid = np.diff(edges)[:, None] / 2, (edges[:-1, None] + edges[1:, None]) / 2
    x, wt = (mid + half * g).ravel(), (half * w).ravel()
    phi = laguerre_functions(n, x)
    return (phi * wt) @ phi.T


def leading_minors(G, floor=1e-30):
    """Leading principal minors of a symmetric positive definite G by elimination without pivoting; each pivot is a
    ratio of successive minors. Elimination stops once a minor falls below floor, where the remaining pivots would be
    dominated by rounding; the later minors are set to zero."""
    A = np.array(G, dtype=float)
    out = np.zeros(len(A))
    minor = 1.0
    for i in range(len(A)):
        if A[i, i] <= 0:
            raise ArithmeticError(f'pivot {i} is not positive while the minor is {minor:.1e}')
        minor *= A[i, i]
        out[i] = minor
        if minor < floor:
            break
        A[i + 1:, i + 1:] -= np.outer(A[i + 1:, i] / A[i, i], A[i, i + 1:])
    return out


def crossing_law(t, nmax, panels=None):
    """P(J(t) >= n) for n = 1..nmax: leading principal minors of the Gram matrix on [0, t]. The panels are graded
    quadratically, which spreads the oscillations of phi_j near x = 0 evenly over them."""
    panels = panels or max(16, int(3 * np.sqrt(nmax * t) / 10))
    edges = t * np.linspace(0.0, 1.0, panels + 1) ** 2
    return leading_minors(gram(nmax, edges))


def hankel_law(t, nmax, dps=40):
    """P(J(t) >= n) from det[A_{j+k}(t)] / prod_k (k!)^2 in multiprecision arithmetic."""
    mp.mp.dps = dps
    A = [mp.gammainc(d + 1, 0, t) for d in range(2 * nmax - 1)]
    out = []
    for n in range(1, nmax + 1):
        H = mp.matrix([[A[j + k] for k in range(n)] for j in range(n)])
        out.append(float(mp.det(H) / mp.fprod(mp.factorial(k) ** 2 for k in range(n))))
    return np.array(out)


def lue_cdf(n, s):
    """P(T(n, n) <= s) for an array s, from the Hankel form in double precision (adequate for small n)."""
    s = np.atleast_1d(np.asarray(s, dtype=float))
    d = np.arange(2 * n - 1)
    A = gammainc(d[None, :] + 1, s[:, None]) * np.exp(gammaln(d + 1))[None, :]
    H = A[:, d[:n, None] + d[None, :n]]
    return np.linalg.det(H) / np.exp(2 * gammaln(np.arange(n) + 1).sum())


def edge_law(n, s):
    """P((T(n,n) - 4n)/(2^{4/3} n^{1/3}) <= s) = det(I - int_t^infinity phi_j phi_k), t = 4n + 2^{4/3} n^{1/3} s."""
    scale = 2 ** (4 / 3) * n ** (1 / 3)
    out = []
    for v in s:
        t = 4 * n + scale * v
        M = gram(n, np.linspace(t, 4 * n + 14 * scale, 5), nodes=60)
        out.append(np.linalg.det(np.eye(n) - M))
    return np.array(out)


def current_moments(t, panels=None):
    """Exact mean and variance of J(t), with the probabilities P(J(t) >= n)."""
    sigma = 2 ** (-4 / 3) * t ** (1 / 3)
    nmax = int(t / 4 + 9 * sigma) + 12
    p = crossing_law(t, nmax, panels)
    n = np.arange(1, nmax + 1)
    mean = p.sum()
    return mean, ((2 * n - 1) * p).sum() - mean ** 2, p


def free_variance(t):
    """Var J(t) for independent rate-one particles started at 1 - n: sum_n P(K >= n) P(K < n), K ~ Poisson(t)."""
    n = np.arange(1, int(t + 40 * np.sqrt(t)) + 40)
    F = gammainc(n, t)
    return np.sum(F * (1 - F))


def last_passage(n, samples, draw):
    """Diagonal times T(m, m), m = 1..n, of up-right last passage from (1, 1), weights drawn by draw(shape)."""
    prev = np.full((samples, n), -np.inf)
    diag = np.empty((samples, n))
    for k in range(n):
        w = draw((samples, n))
        row = np.empty((samples, n))
        left = np.full(samples, -np.inf)
        for j in range(n):
            best = np.zeros(samples) if k == 0 and j == 0 else np.maximum(prev[:, j], left)
            row[:, j] = w[:, j] + best
            left = row[:, j]
        prev = row
        diag[:, k] = row[:, k]
    return diag


def exponential(shape):
    return rng.exponential(size=shape)


def gillespie_current(t_end, runs, particles=40):
    """J(t_end) for continuous-time TASEP from step data, simulated event by event. The leading particles evolve
    autonomously, and the leading 40 suffice: J(12) >= 40 would need T(40, 40) <= 12."""
    out = np.empty(runs, dtype=int)
    for r in range(runs):
        pos = list(range(0, -particles, -1))
        free = [True] + [False] * (particles - 1)
        movable = [0]
        t, crossed = 0.0, 0
        while True:
            t += pyrng.expovariate(len(movable))
            if t > t_end:
                break
            i = movable[pyrng.randrange(len(movable))]
            pos[i] += 1
            crossed += pos[i] == 1
            for q in (i, i + 1):
                if q < particles:
                    now = q == 0 or pos[q] + 1 < pos[q - 1]
                    if now != free[q]:
                        free[q] = now
                        movable.append(q) if now else movable.remove(q)
        out[r] = crossed
    return out


def wishart_largest(n, samples):
    G = (rng.normal(size=(samples, n, n)) + 1j * rng.normal(size=(samples, n, n))) / np.sqrt(2)
    return np.linalg.eigvalsh(np.conj(np.swapaxes(G, 1, 2)) @ G)[:, -1]


def ks_statistic(samples, cdf):
    x = np.sort(samples)
    F = cdf(x)
    i = np.arange(1, len(x) + 1)
    return max(np.max(i / len(x) - F), np.max(F - (i - 1) / len(x)))


def main():
    checks, controls = {}, {}

    # 1. The Tracy-Widom distribution.
    mean, var, s_grid, F_grid = tw_moments()
    mean2, var2, _, _ = tw_moments(h=0.0025, m=80)
    print(f'F2 by Nystrom: mean {mean:.10f}, variance {var:.10f}; with half the step and 80 nodes '
          f'{mean2:.10f}, {var2:.10f}; F2(0) = {F2(0.0):.6f}')
    checks['F2 moments stable under refinement (1e-9) and equal to -1.7710868 and 0.8131948 to eight digits'] = (
        abs(mean - mean2) < 1e-9 and abs(var - var2) < 1e-9 and abs(mean + 1.7710868) < 5e-8
        and abs(var - 0.8131948) < 5e-8 and abs(mean - TW_MEAN) < 1e-9 and abs(var - TW_VAR) < 1e-9)

    # 2. Gram minors against Hankel determinants.
    t_obs = 12.0
    p12 = crossing_law(t_obs, 14)
    hank = hankel_law(t_obs, 8)
    err = np.max(np.abs(p12[:8] - hank))
    print(f'P(J(12) >= n), n = 1..8:', ' '.join(f'{v:.10f}' for v in p12[:8]), f'; Hankel difference {err:.1e}')
    checks['Gram minors equal the Hankel determinants for n <= 8 at t = 12 (1e-12)'] = err < 1e-12
    mp.mp.dps = 50
    small = hankel_law(1e-5, 4, dps=50)
    c = [float(mp.det(mp.matrix([[mp.mpf(1) / (j + k + 1) for k in range(n)] for j in range(n)]))
               / mp.fprod(mp.factorial(k) ** 2 for k in range(n))) for n in (2, 3, 4)]
    ratio = [small[n - 1] / 1e-5 ** (n * n) / cn for n, cn in zip((2, 3, 4), c)]
    print('short times: 1/c_n =', ' '.join(f'{1 / v:.0f}' for v in c),
          '; P(J(t) >= n) / (c_n t^{n^2}) at t = 1e-5:', ' '.join(f'{v:.6f}' for v in ratio))
    checks['P(J(t) >= n) ~ c_n t^{n^2} with c_n from the Hilbert determinant, n = 2, 3, 4 (1e-4 at t = 1e-5)'] = (
        max(abs(v - 1) for v in ratio) < 1e-4)

    # 3. TASEP dynamics against the exact law.
    runs = 20000
    pmf = -np.diff(np.r_[1.0, p12, 0.0])
    print('P(J(12) = n), n = 0..8:', ' '.join(f'{v:.5f}' for v in pmf[:9]))
    J_sim = gillespie_current(t_obs, runs)
    J_lpp = np.sum(last_passage(16, runs, exponential) <= t_obs, axis=1)
    tv = [0.5 * np.sum(np.abs(np.bincount(J, minlength=len(pmf))[:len(pmf)] / runs - pmf)) for J in (J_sim, J_lpp)]
    print(f'J(12): exact mean {p12.sum():.4f}, Gillespie {J_sim.mean():.4f}, last passage {J_lpp.mean():.4f}; '
          f'total variation to the exact law {tv[0]:.4f} and {tv[1]:.4f}')
    checks['Gillespie TASEP and sampled last passage follow the exact law of J(12) (TV < 0.02)'] = max(tv) < 0.02

    # 4. The finite identity with Wishart matrices.
    n, M = 6, 20000
    crit = 1.95 / np.sqrt(M)
    cdf6 = lambda x: lue_cdf(n, x)
    samples = {'last passage': last_passage(n, M, exponential)[:, -1], 'Wishart': wishart_largest(n, M)}
    ks = {name: ks_statistic(v, cdf6) for name, v in samples.items()}
    gauss = last_passage(n, M, lambda shape: 1 + rng.normal(size=shape))[:, -1]
    ks_gauss = ks_statistic(gauss, cdf6)
    tail = 1 - cdf6(np.linspace(0.0, 80.0, 8001))
    exact_mean = 0.01 * (tail.sum() - (tail[0] + tail[-1]) / 2)
    print(f'n = 6: exact mean {exact_mean:.4f}; sample means',
          ', '.join(f'{name} {v.mean():.4f}' for name, v in samples.items()),
          f'; KS statistics', ', '.join(f'{name} {v:.4f}' for name, v in ks.items()),
          f'(critical {crit:.4f}); Gaussian weights mean {gauss.mean():.4f}, KS {ks_gauss:.4f}')
    checks['n = 6: last passage and Wishart samples follow the exact law (KS < 1.95/sqrt(M))'] = max(ks.values()) < crit
    controls['Gaussian last-passage weights fail the same test (KS above three times the critical value)'] = (
        ks_gauss > 3 * crit)

    # 5. Edge limit of the exact law.
    s_edge = np.linspace(-5.0, 3.0, 81)
    F_edge = np.interp(s_edge, s_grid, F_grid)
    dist = {}
    for n in (25, 50, 100, 200, 400):
        dist[n] = np.max(np.abs(edge_law(n, s_edge) - F_edge))
    print('Kolmogorov distance to F2 of (T(n,n) - 4n)/(2^{4/3} n^{1/3}):',
          ', '.join(f'n = {n}: {d:.4f}' for n, d in dist.items()))
    d = list(dist.values())
    print('ratios per doubling of n:', ' '.join(f'{b / a:.3f}' for a, b in zip(d, d[1:])))
    checks['edge law: distance to F2 falls with each doubling of n and is below 0.03 at n = 400'] = (
        all(a > b for a, b in zip(d, d[1:])) and d[-1] < 0.03)
    p1000 = current_moments(1000.0)[2][249]
    e1000 = edge_law(250, [0.0])[0]
    print(f'P(J(1000) >= 250): Gram minor on [0, 1000] {p1000:.13f}, det(I - K_250) on [1000, inf) {e1000:.13f}; '
          f'P(J(1000) <= 249) = {1 - e1000:.5f} against 1 - F2(0) = {1 - F2(0.0):.5f}')
    checks['P(J(1000) >= 250) by quadrature on [0, t] and on [t, infinity) agrees to 1e-12'] = (
        abs(p1000 - e1000) < 1e-12)

    # 6. Exact moments of the current.
    times = [100.0, 200.0, 400.0, 800.0, 1600.0]
    rows = []
    for t in times:
        m, v, p = current_moments(t)
        sigma = 2 ** (-4 / 3) * t ** (1 / 3)
        rows.append((t, m, v, (t / 4 - m) / sigma, v / sigma ** 2, p[-1], free_variance(t)))
    _, _, p_fine = current_moments(1600.0, panels=2 * max(16, int(3 * np.sqrt(len(p) * 1600.0) / 10)))
    refine = np.max(np.abs(p_fine - p))
    print('   t     E J - t/4    Var J    scaled mean  scaled var   last P   Var without exclusion')
    for t, m, v, sm, sv, last, fv in rows:
        print(f'{t:6.0f} {m - t / 4:10.5f} {v:10.5f} {sm:11.5f} {sv:11.5f} {last:9.1e} {fv:12.5f}')
    print(f'doubling the panels at t = 1600 changes the probabilities by at most {refine:.1e}')
    em = [abs(r[3] - TW_MEAN) for r in rows]
    ev = [abs(r[4] - TW_VAR) for r in rows]
    slope = np.log(rows[-1][2] / rows[-2][2]) / np.log(2)
    free_slope = np.log(rows[-1][6] / rows[-2][6]) / np.log(2)
    print(f'variance slope between t = 800 and 1600: {slope:.4f} with exclusion, {free_slope:.4f} without; '
          f'without exclusion at t = 1600 Var = {rows[-1][6]:.4f} against sqrt(t/pi) = {np.sqrt(1600 / np.pi):.4f}')
    print('error ratios per doubling of t: scaled mean', ' '.join(f'{b / a:.4f}' for a, b in zip(em, em[1:])),
          '; scaled variance', ' '.join(f'{b / a:.4f}' for a, b in zip(ev, ev[1:])))
    print('E J(t) - t/4 - 1.7711 sigma_t:',
          ' '.join(f'{r[1] - r[0] / 4 + TW_MEAN * 2 ** (-4 / 3) * r[0] ** (1 / 3):.3f}' for r in rows))
    checks['scaled mean and variance of J(t) approach the Tracy-Widom values at every doubling of t'] = (
        all(a > b for a, b in zip(em, em[1:])) and all(a > b for a, b in zip(ev, ev[1:])))
    checks['Var J(t) slope between t = 800 and 1600 in (0.64, 0.69)'] = 0.64 < slope < 0.69
    checks['quadrature refinement changes no probability by more than 1e-12'] = refine < 1e-12
    controls['without exclusion the variance slope lies in (0.49, 0.51)'] = 0.49 < free_slope < 0.51

    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)


if __name__ == '__main__':
    main()
