"""Independent finite calculations used in the Research methods and evidence pages.

Run with Python 3, NumPy and SciPy. The last-passage and Wishart computations
use disjoint probability representations. The sine-kernel derivative compares
an endpoint resolvent with a centered finite difference of a determinant.
"""
from math import exp, pi, sin, sqrt
import numpy as np
from numpy.polynomial.legendre import leggauss
from scipy.integrate import quad
from scipy.special import airy


def passage_cdf(t):
    # Condition on the sum of the two common exponential endpoint weights.
    return quad(lambda a: a * exp(-a) * (-np.expm1(a-t))**2, 0, t,
                epsabs=1e-14, epsrel=1e-13)[0]


def wishart_cdf(t):
    mu = [quad(lambda x: x**k * exp(-x), 0, t)[0] for k in range(3)]
    return mu[0] * mu[2] - mu[1]**2


def sine_gap(s, n):
    # Nyström determinant and diagonal endpoint of K(I-K)^-1.
    x, w = leggauss(n)
    x, w = s*(x+1)/2, np.sqrt(w*s/2)
    matrix = np.eye(n) - np.sinc(x[:, None] - x[None, :])*np.outer(w,w)
    edge = w*np.sinc(s-x)
    return np.linalg.det(matrix), 1+edge @ np.linalg.solve(matrix,edge)


def sector_check():
    shift = np.roll(np.eye(4), 1, axis=0)
    h = np.eye(4) - (shift + shift.T)/2
    k = pi/2
    right = np.exp(-1j*k*np.arange(4))/2
    trial = sqrt(3)*right/2 + np.conj(right)/2
    print('Hamiltonian residual, wrong momentum amplitude:',
          np.linalg.norm(h@trial-trial), np.linalg.norm(trial-right*np.vdot(right,trial)))
    for time in (0, pi/2, pi):
        e, states = np.linalg.eigh(h)
        weights = abs(states[0,:])**2
        corr = np.sum(weights*np.exp(-1j*time*e))
        assert abs(corr-(1+np.exp(-1j*time))**2/4) < 2e-14


if __name__ == '__main__':
    sector_check()
    for t in (1.,2.,4.):
        p, q = passage_cdf(t), wishart_cdf(t)
        exact = 1-(2+t*t)*exp(-t)+exp(-2*t)
        assert max(abs(p-q), abs(p-exact)) < 2e-14
        print(f'LPP/Wishart, t={t:g}: {p:.12f}, {q:.12f}')
    for n in (2,4,8,16,32):
        gap, endpoint = sine_gap(1.,n)
        print(f'unit sine gap, n={n}: {gap:.12f}; endpoint R={endpoint:.10f}')
    for step in (1.e-2,1.e-3,1.e-4):
        slope=(np.log(sine_gap(1+step,32)[0])-np.log(sine_gap(1-step,32)[0]))/(2*step)
        print(f'centered log derivative, h={step:g}: {slope:.10f}; error {abs(slope+endpoint):.3g}')
    for a in (1.,4.,16.):
        exact = airy(-a)[0]
        leading = sin(2*a**1.5/3 + pi/4) / (sqrt(pi)*a**.25)
        print(f'Airy at -{a:g}: {exact:.10f}, separated saddles {leading:.10f}, error {abs(exact-leading):.3g}')
