"""Finite Painlevé measurements. Run with Python 3, NumPy, SciPy and mpmath.

Both Airy variables use the dimensionless GUE soft-edge convention. The PVI
algebraic solution is Iorgov–Lisovyy–Tykhyy (4.21)–(4.22), arXiv:1308.4092.
"""
import mpmath as mp
import numpy as np
from scipy.integrate import solve_ivp
from scipy.optimize import brentq
from scipy.special import airy, ai_zeros, loggamma, roots_legendre


def airy_solution(amplitude, left, right, tolerance):
    a, ap = airy(right)[:2]
    initial = np.array([amplitude*a, amplitude*ap])

    def rhs(x, state):
        q, qp = state
        return qp, x*q+2*q**3

    solution = solve_ivp(rhs, (right, left), initial, dense_output=True,
                         rtol=tolerance, atol=tolerance*abs(initial)/100, method="DOP853")
    if not solution.success:
        raise RuntimeError(solution.message)
    return solution.sol


def zero_measurements(amplitude=.8, right=10, tolerance=1e-12):
    solution = airy_solution(amplitude, -45, right, tolerance)
    d2 = -np.log1p(-amplitude**2)/np.pi
    theta = 1.5*d2*np.log(2)+loggamma(1-.5j*d2).imag-np.pi/4
    result = []
    for n in range(3, 60):
        def phase(r):
            return 2*r**1.5/3-.75*d2*np.log(r)-theta-n*np.pi

        corrected = brentq(phase, 2, 45)
        bare = (1.5*(n*np.pi+theta))**(2/3)
        half = .4*np.pi/np.sqrt(corrected)
        measured = brentq(lambda r: solution(-r)[0], corrected-half, corrected+half,
                          xtol=4e-14)
        result.append([n, measured, corrected, bare])
    return np.array(result)


def kernel_spectrum(s, top, count):
    # Use the integral of Ai(x+z)Ai(y+z) instead of a subtractive quotient.
    nodes, weights = roots_legendre(count)
    xhalf = (top-s)/2
    zhalf = (top-min(0, s))/2
    x = s + xhalf*(nodes+1)
    z = zhalf*(nodes+1)
    matrix = airy(x[:, None]+z[None, :])[0]
    matrix *= np.sqrt(np.outer(xhalf*weights, zhalf*weights))
    return np.linalg.eigvalsh(matrix @ matrix.T)


def log_gap(s, gamma, top, count):
    return np.log1p(-gamma*kernel_spectrum(s, top, count)).sum()


def density_peak():
    for right, tol, step, order in [(8, 1e-10, .002, 48), (10, 2e-13, .001, 80)]:
        wave = airy_solution(1, -3, right, tol)

        def turning_signal(s):
            q, qp = wave(s)
            return qp**2-s*q*q-q**4-q

        assert turning_signal(-2) > 0 > turning_signal(-1.5)
        root = brentq(turning_signal, -2, -1.5)

        def curvature(s):
            gaps = [np.exp(log_gap(s+d, 1, 14, order)) for d in (-step, 0, step)]
            return (gaps[0]-2*gaps[1]+gaps[2])/step**2

        matrix_root = brentq(curvature, -2, -1.5, xtol=1e-9)
        density = np.exp(log_gap(root, 1, 14, order))*wave(root)[0]
        print("Density maximum, ODE position / kernel position / density:", root, matrix_root, density)
        assert abs(root-matrix_root) < 3e-7


def thinning_contrast():
    v = np.log(2.)
    def constant(w):
        return float(2*mp.log(abs(mp.barnesg(1+1j*w/(2*mp.pi)))))
    exact = constant(2*v)-2*constant(v)
    print("Two-thinning Barnes log contrast:", exact)
    for s in [-8, -16, -24, -40]:
        data = []
        for upper, order in [(12, 160), (16, 205)]:
            eigs = kernel_spectrum(s, upper, order)
            contrast = np.log1p(-.75*eigs).sum() - 2*np.log1p(-.5*eigs).sum()
            data.append(contrast)
        extracted = contrast - v*v*np.log(8*(-s)**1.5)/(2*np.pi**2)
        print("Threshold / log contrast / finite constant / remainder / refinement:",
              s, contrast, extracted, extracted-exact, abs(data[1]-data[0]))
        assert contrast >= 0 and abs(extracted-exact) < .005
        assert abs(data[1]-data[0]) < 1e-10


def algebraic_pvi(s):
    i = mp.j
    frac = mp.mpf(1)
    t = -(1+s*s)**2*(1-6*s*s+s**4)**3 / (32*s*s*(1+s**4)**3)
    tau = ((s**4-1)**(-frac/8)*(s**4+1)**(-5*frac/192)*(i+(1-i)*s+s*s)
           / (s**(frac/32)*(1+2*s-s*s)**(7*frac/24)
              *(s*s+2*s-1)**(frac/24)*(1+6*s*s+s**4)**(frac/6)))
    factor = (s*s+i)*(1-2*i*s+s*s)/((s*s-i)*(1+2*i*s+s*s))
    return t, tau * mp.exp(mp.log(factor)/8)


def pvi_endpoints():
    with mp.workdps(65):
        one = mp.mpf(1)
        angle = (mp.pi-mp.atan(7/(4*mp.sqrt(2))))/8
        exact = 2**(-19*one/72)*3**(-one/64)*mp.exp(1j*angle)
        for dec in (2, 3, 4, 5):
            h = 10**(-dec*one)
            t0, tau0 = algebraic_pvi(1+mp.sqrt(2)-h)
            t1, tau1 = algebraic_pvi(1+h)
            estimate = tau1*(1-t1)**(one/16)/(tau0*t0**(7*one/72))
            first = (3*one/8)*mp.exp(-1j*mp.pi/4)*mp.sqrt(1-t1)
            corrected = estimate/(1+first)
            print("PVI h / leading and corrected ratio errors:", mp.nstr(h, 4),
                  mp.nstr(abs(estimate-exact), 9), mp.nstr(abs(corrected-exact), 9))
            assert abs(corrected-exact) < 4*h*h


def local_poles():
    a = .7
    t0 = 1.
    def regular_rhs(t, state):
        u, h = state
        v = np.sqrt(1+(t*u**4+u**5+h*u**6)/2)
        return v, (t*u*u+u**3+h*u**4)/(2*(v+1))
    for radius in [.2, .1, .05]:
        samples = []
        for direction in (-1, 1):
            result = solve_ivp(regular_rhs, (t0, t0+direction*radius), [0., -14*a],
                               method="DOP853", rtol=3e-14, atol=1e-16)
            assert result.success
            samples.append(result.y[0, -1]**-2)
        estimate = (np.mean(samples)-radius**-2+t0*radius**2/10)/radius**4
        print("PI side radius / symmetric estimate of a:", radius, estimate)
    # Independent Taylor coefficients give the O(radius^2) error t0^2/300.
    zero = ai_zeros(1)[0][0]
    slope = -2**(1/3)/(np.pi*airy(zero)[1]**2)
    def root(c):
        def denominator(x):
            ai, _, bi, _ = airy(x)
            return ai+c*bi
        return -2**(1/3)*brentq(denominator, -2.55, -2.1)
    h = .0001
    numerical = (root(h)-root(-h))/(2*h)
    print("Riccati initial pole / analytic speed / centered speed:", root(0.), slope, numerical)
    assert abs(slope-numerical) < 2e-8


if __name__ == "__main__":
    local_poles()
    coarse = zero_measurements(right=8, tolerance=1e-10)
    fine = zero_measurements()
    print("Maximum zero-location change under refinement:", max(abs(fine[:, 1]-coarse[:, 1])))
    for i in (7, 27, 47):
        print("n / measured r / full-phase r / r without log:", *fine[i])
    density_peak()
    thinning_contrast()
    pvi_endpoints()
