"""Finite-rank and Airy checks. Run with Python 3.9+, NumPy and SciPy."""

from math import erf, exp, pi, sqrt

import numpy as np
from scipy.integrate import quad, solve_ivp
from scipy.special import airy, roots_legendre

def grid(lo, hi, n):
    x, w = roots_legendre(n)
    return lo + (x + 1) * (hi - lo)/2, w * (hi - lo)/2


def kernel(x, y):
    a, ap = airy(x)[:2]
    b, bp = airy(y)[:2]
    d = x[:, None] - y[None, :]
    out = (a[:, None]*bp - ap[:, None]*b) / np.where(d == 0, 1, d)
    return np.where(d == 0, (ap**2 - x*a**2)[:, None], out)


def weighted(x, w, y, v):
    return np.sqrt(w[:, None]*v) * kernel(x, y)


def log_gap(matrix, retention=1):
    eig = np.linalg.eigvalsh(matrix)
    return np.log1p(-retention*eig).sum()


def gap(matrix, retention=1):
    return np.exp(log_gap(matrix, retention))


def hermite_gap(n, s, cutoff, order):
    """Gram matrix of the finite Hermite orbitals, integrating in Airy units."""
    z, w = grid(s, cutoff, order)
    width = 1/(sqrt(2)*n**(1/6))
    x = sqrt(2*n) + width*z
    previous = np.zeros_like(x)
    phi = pi**(-.25) * np.exp(-x*x/2)
    columns = []
    for j in range(n):
        columns.append(np.sqrt(w*width)*phi)
        previous, phi = phi, sqrt(2/(j+1))*x*phi - sqrt(j/(j+1))*previous
    factor = np.array(columns)
    return gap(factor @ factor.T)


def overlap_check():
    a = .5
    given = erf(a) - 2*a*exp(-a*a)/sqrt(pi)
    integral = quad(lambda y: 2*y*y*exp(-y*y)/sqrt(pi), -a, a)[0]
    assert abs(integral - given) < 1e-14
    print("half-width 0.5, conditional partner probability", given)


def resolvent(s, cutoff, order):
    x, w = grid(s, cutoff, order)
    matrix = weighted(x, w, x, w)
    a, ap = airy(x)[:2]
    rhs = np.sqrt(w)[:, None]*np.column_stack((a, ap))
    solved = np.linalg.solve(np.eye(order) - matrix, rhs)
    # Gauss nodes exclude the endpoint. Evaluate the integral equations there.
    endpoint = airy(s)[:2] + (kernel(np.array([s]), x)[0]*np.sqrt(w)) @ solved
    u, v = rhs[:, 0] @ solved
    return endpoint[0], endpoint[1], u, v


def painleve(s, amplitude, cutoff=12, tol=2e-13):
    """Evolve q,q', the log derivative u, and the normalized logarithm L."""
    a, ap = amplitude*np.array(airy(cutoff)[:2])
    def rhs(x, state):
        q, qp, u, _ = state
        return qp, x*q+2*q**3, -q**2, u
    absolute = tol*np.array([abs(a), abs(ap), a*a, a*a])/100
    result = solve_ivp(rhs, (cutoff,s), (a,ap,0,0), method="DOP853",
                       rtol=tol, atol=absolute)
    if not result.success:
        raise RuntimeError(result.message)
    return result.y[:, -1]


def one_position():
    for s in (-2, 2):
        x, w = grid(s, 12, 64)
        mat = weighted(x, w, x, w)
        for retention in (.25, 1):
            logdet = log_gap(mat, retention)
            amplitude = sqrt(retention)
            logode = painleve(s, amplitude)[3]
            assert abs(logdet-logode) < 2e-11
            earlier = painleve(s, amplitude, cutoff=10)[3]
            looser = painleve(s, amplitude, tol=2e-12)[3]
            change = max(abs(logode-earlier), abs(logode-looser))
            assert change < 2e-10
            print("s, retention, gap, exceedance, max log-ODE refinement change",
                  s, retention, np.exp(logdet), -np.expm1(logdet), change)

    for s in (-2, 0):
        for n in (1, 4, 16, 64):
            g = hermite_gap(n, s, 11, 56)
            refined = hermite_gap(n, s, 14, 80)
            assert abs(g-refined) < 1e-11
            if n == 1:
                assert abs(refined - (1 + erf(sqrt(2)+s/sqrt(2)))/2) < 1e-12
            print("finite Hermite s, N, gap", s, n, refined)

    for s in (-2, 0):
        q, p, u, v = resolvent(s, 11, 56)
        assert np.max(np.abs(np.array((q,p,u,v)) - resolvent(s, 14, 80))) < 2e-12
        q_ode, qp_ode, u_ode, _ = painleve(s, 1)
        assert abs(q-q_ode) < 2e-11 and abs(p-q*u-qp_ode) < 2e-11
        assert abs(u-u_ode) < 2e-11
        print("resolved s,q,p,u,v,q',first-integral residual", s,q,p,u,v,p-q*u,u*u-2*v-q*q)

    x, w = grid(-2, 0, 64)
    y, v = grid(0, 12, 64)
    left, right, cross = weighted(x,w,x,w), weighted(y,v,y,v), weighted(x,w,y,v)
    both = np.block([[left, cross], [cross.T, right]])
    print("separate windows: left gap, right gap, both, conditional left, covariance",
          gap(left), gap(right), gap(both), gap(both)/gap(right), -np.sum(cross**2))
    xall, wall = grid(-2, 14, 80)
    assert abs(gap(both)-gap(weighted(xall,wall,xall,wall))) < 2e-13


def close_nodes():
    x = 1.
    a, ap = airy(x)[:2]
    for power in (12, 24, 36, 44):
        h = 2.**(-power)
        y = x + h
        direct = kernel(np.array([x]),np.array([y]))[0,0]
        gram = quad(lambda u: airy(x+u)[0]*airy(y+u)[0], 0, np.inf,
                    epsabs=1e-15, epsrel=2e-13)[0]
        linear = ap**2 - x*a*a - h*a*a/2
        print("separation 2^-k, quotient, Gram, Taylor",power,direct,gram,linear)


def two_positions(delta, left=-2., right=-1., cutoff=10., order=40, spectral_order=96,
                  spectral_cutoff=36., heat=False):
    """Joint CDF for earlier threshold left and later threshold right, delta>0."""
    x, w = grid(left, cutoff, order)
    y, v = grid(right, cutoff, order)
    t, a = grid(0, 24 if heat else 14, spectral_order)
    ax, ay = airy(x[:,None]+t)[0], airy(y[:,None]+t)[0]
    later_earlier = (ay*(a*np.exp(-delta*t))) @ ax.T
    if heat:
        # Completeness for the linear-potential heat kernel: subtract its full line.
        full = np.exp(-(x[:,None]-y)**2/(4*delta) - delta*(x[:,None]+y)/2
                      + delta**3/12) / sqrt(4*pi*delta)
        earlier_later = (ax*(a*np.exp(delta*t))) @ ay.T - full
    else:
        u, b = grid(0, spectral_cutoff, spectral_order)
        earlier_later = -((airy(x[:,None]-u)[0]*(b*np.exp(-delta*u)))
                          @ airy(y[:,None]-u)[0].T)
    split = np.sqrt(w[:,None]*v)
    both = np.block([[weighted(x,w,x,w), split*earlier_later],
                     [split.T*later_earlier, weighted(y,v,y,v)]])
    sign, logdet = np.linalg.slogdet(np.eye(2*order)-both)
    assert sign == 1
    return exp(logdet)


def main():
    overlap_check()
    one_position()
    close_nodes()
    for d in (1., 2., 4.):
        base = two_positions(d)
        refined = two_positions(d, cutoff=12, order=56, spectral_order=160, spectral_cutoff=48)
        alternative = two_positions(d, cutoff=12, order=56, spectral_order=96, heat=True)
        assert abs(base-refined) < 2e-10 and abs(alternative-refined) < 2e-10
        print("two positions, separation, direct, refined, heat",d,base,refined,alternative)


if __name__ == "__main__":
    main()
