"""Unitary soft-edge probabilities by Nyström and nonlinear shooting.

Run with Python 3, NumPy and SciPy. Logarithmic evaluation resolves tiny right tails.
"""
import numpy as np
from scipy.integrate import quad, solve_ivp
from scipy.special import airy, roots_legendre


def log_determinant(cutoff, count, control=False, threshold=0):
    if cutoff <= threshold:
        raise ValueError("the upper endpoint must exceed the gap threshold")
    nodes, weights = roots_legendre(count)
    half_width = (cutoff-threshold)/2
    x = threshold + (nodes+1)*half_width
    weights = weights*half_width
    if control:
        kernel = np.exp(-x[:,None]-x[None,:])
    else:
        a, ap, _, _ = airy(x)
        diff = x[:,None]-x[None,:]
        np.fill_diagonal(diff,1)
        kernel = (np.outer(a,ap)-np.outer(ap,a))/diff
        np.fill_diagonal(kernel, ap**2-x*a**2)
    w = np.sqrt(weights)
    eig = np.linalg.eigvalsh(w[:,None]*kernel*w[None,:])
    return np.log1p(-eig).sum()


def determinant(cutoff, count, control=False):
    return np.exp(log_determinant(cutoff, count, control))


def shoot(cutoff, threshold, tol, amplitude=1):
    a, ap, _, _ = airy(cutoff)
    a, ap = amplitude*a, amplitude*ap
    def rhs(x,y):
        q, qp, _ = y
        return qp, x*q+2*q**3, (x-threshold)*q*q
    absolute = tol * np.array([abs(a), abs(ap), a*a]) / 100
    sol = solve_ivp(rhs,(cutoff,threshold),[a,ap,0],method="DOP853",rtol=tol,atol=absolute)
    if not sol.success:
        raise RuntimeError(sol.message)
    return sol.y[:,-1]


def nonlinear(cutoff, tol):
    return np.exp(shoot(cutoff, 0, tol)[2])


if __name__ == "__main__":
    for b in (6,8,10):
        control = determinant(b,48,True)
        assert abs(control-(1+np.exp(-2*b))/2)<1e-12
        print("B, rank-one, Airy N=12,24,48:", b, control, *[determinant(b,n) for n in (12,24,48)])
    for b in (6,8,10):
        print("PII B and values at rtol 1e-7, 1e-10, 2e-13:",
              b,*[nonlinear(b,tol) for tol in (1e-7,1e-10,2e-13)])
    assert abs(determinant(10,48)-nonlinear(10,2e-13))<5e-12
    for s in (0,4,6,8):
        trace = quad(lambda x: (x-s)*airy(x)[0]**2, s, np.inf,
                     epsabs=1e-34, epsrel=3e-14)[0]
        print("s, Airy trace, two-occupancy upper bound:", s, trace, trace**2/2)
        for b, n in ((12,32),(14,48)):
            via_kernel = -np.expm1(log_determinant(b,n,threshold=s))
            q, qp, log_gap = shoot(b,s,2e-13)
            via_ode = -np.expm1(log_gap)
            print("s B N, right tails, q(s):",s,b,n,via_kernel,via_ode,q)
            assert abs(via_kernel/via_ode-1) < 1e-8
    for s in (0,-4):
        for k in (0.5,1.0):
            print("PII s, k, q, q':",s,k,*shoot(10,s,2e-13,k)[:2])
    q, qp, _ = shoot(12, 0, 2e-13)
    print("resolvent log-gap derivatives", qp**2-q**4, -q*q)
    for step in (0.01, 0.001, 0.0002):
        lower, center, upper = [log_determinant(12,48,threshold=s)
                                 for s in (-step,0,step)]
        first = (upper-lower)/(2*step)
        second = (lower+upper-2*center)/step**2
        print("kernel finite differences",step,first,second)
