"""Airy point counts on (s, infinity). Run with Python 3, NumPy and SciPy.

Tracy and Widom, Commun. Math. Phys. 159 (1994), pp. 155–156, 165–166,
doi:10.1007/BF02100489. The quadrature uses binary64 arithmetic.
"""
from math import exp

import numpy as np
from scipy.special import airy, roots_legendre


def grid(left, right, order):
    nodes, weights = roots_legendre(order)
    half = (right - left) / 2
    return left + half * (1 + nodes), half * weights


def eigenvalues(threshold, cutoff, order, method="quotient", auxiliary_cutoff=12):
    """Nyström spectrum on [threshold, cutoff], with the indicated kernel."""
    if threshold >= cutoff or auxiliary_cutoff <= 0:
        raise ValueError("cutoff must exceed threshold and auxiliary cutoff must be positive")
    x, w = grid(threshold, cutoff, order)
    if method == "quotient":
        a, derivative = airy(x)[:2]
        difference = x[:, None] - x[None, :]
        np.fill_diagonal(difference, 1.0)
        kernel = (a[:, None]*derivative[None, :] - derivative[:, None]*a[None, :]) / difference
        np.fill_diagonal(kernel, derivative**2 - x*a**2)
        matrix = np.sqrt(w[:, None]*w[None, :]) * kernel
    elif method == "gram":
        t, v = grid(0, auxiliary_cutoff, order)
        factor = np.sqrt(w[:, None]*v[None, :]) * airy(x[:, None] + t[None, :])[0]
        matrix = factor @ factor.T
    else:
        raise ValueError("method must be 'quotient' or 'gram'")
    spectrum = np.linalg.eigvalsh(matrix)
    if spectrum.min() < -1e-12 or spectrum.max() >= 1:
        raise ArithmeticError("increase the mesh resolution or use a less extreme left threshold")
    return spectrum


def count_probabilities(spectrum, maximum, retention=1.0):
    """Coefficients P(N=0),...,P(N=maximum) of the count polynomial."""
    if maximum < 0 or not 0 <= retention <= 1:
        raise ValueError("maximum must be nonnegative and retention between zero and one")
    p = np.zeros(maximum+1)
    p[0] = 1.
    for eigenvalue in retention * spectrum:
        previous = p.copy()
        p *= 1 - eigenvalue
        p[1:] += previous[:-1] * eigenvalue
    return p


def report():
    threshold = -2.
    print("threshold -2: physical cutoff, Gauss order, P0, P1, P0+P1")
    for cutoff, order in [(4,16), (6,16), (9,16), (9,32), (9,64)]:
        spectrum = eigenvalues(threshold, cutoff, order)
        p0, p1 = count_probabilities(spectrum, 1)
        print(f"{cutoff:2} {order:2} {p0:.12f} {p1:.12f} {p0+p1:.12f}")
    for threshold in (-2., 0.):
        spectrum = eigenvalues(threshold, 11., 64)
        p = count_probabilities(spectrum, 2)
        for auxiliary_cutoff in (9., 12.):
            check = eigenvalues(threshold, 11., 64, "gram", auxiliary_cutoff)
            assert np.max(np.abs(p-count_probabilities(check, 2))) < 3e-12
        # Direct Fredholm product and logarithmic derivative independently
        # extract coefficients without the Bernoulli polynomial recursion.
        p0 = np.exp(np.log1p(-spectrum).sum())
        p1 = p0 * (spectrum/(1-spectrum)).sum()
        np.testing.assert_allclose(p[:2], [p0,p1], rtol=1e-13, atol=1e-15)
        print(f"s={threshold:g}: P(X1<=s), P(X2<=s), P(X3<=s) =", np.cumsum(p))
        expected = spectrum.sum()
        print("mean count, Poisson P0 and determinantal P0:", expected, exp(-expected), p0)
        kept = count_probabilities(spectrum, 1, retention=.5)
        print("after retaining each point with probability 1/2:", kept, "second CDF", kept.sum())
        full_polynomial = count_probabilities(spectrum, len(spectrum))
        np.testing.assert_allclose(full_polynomial.sum(), 1., rtol=0., atol=3e-14)
        np.testing.assert_allclose(np.arange(len(full_polynomial)) @ full_polynomial, expected)
    assert abs(count_probabilities(eigenvalues(-2.,11.,64),1).sum() - .98608079530655) < 2e-13


if __name__ == "__main__":
    report()
