"""Check the Painlevé VI endpoint amplitude ratio (Python 3, mpmath 1.3).

Its–Lisovyy–Prokhorov (arXiv:1604.03082), Theorem A;
Iorgov–Lisovyy–Tykhyy (arXiv:1308.4092), Eqs. (4.25)–(4.28).
Run: python3 pvi_connection.py
"""
import itertools

import mpmath as mp


def endpoint_ratio(theta, u, v, trace_01):
    a, b, c, d = theta
    nu = (u+a+b, u+c+d, v+a+d, v+b+c)
    lam = (a+b+c+d, u+v+a+c, u+v+b+d, 0)
    half_sum = sum(nu)/2
    frequency = 2*mp.pi
    phase = 1j*frequency
    numerator = (2*mp.cos(frequency*(u-v)) - 2*mp.cos(frequency*(a+c))
                 - 2*mp.cos(frequency*(d+b)) + trace_01)
    denominator = sum(mp.exp(phase*(half_sum-n)) - mp.exp(phase*(half_sum-l))
                      for n, l in zip(nu, lam))
    zeta = mp.log(numerator/denominator)/phase
    g = mp.barnesg
    ratio = 1
    for sign, other in itertools.product((-1, 1), repeat=2):
        ratio *= (g(1+sign*v+other*b-sign*other*c) *
                  g(1+sign*v+other*a-sign*other*d) /
                  (g(1+sign*u+other*b+sign*other*a) *
                   g(1+sign*u+other*c+sign*other*d)))
    for sign in (-1, 1):
        ratio *= g(1+2*sign*u)/g(1+2*sign*v)
    for n, l in zip(nu, lam):
        ratio *= (g(1+zeta+n)*g(1-zeta-l) /
                  (g(1-zeta-n)*g(1+zeta+l)))
    return ratio


def check(precision):
    with mp.workdps(precision):
        u, v = mp.mpf(1)/6, mp.mpf(1)/4
        theta = (v, v, v, mp.mpf(3)/8)
        phi = (mp.pi-mp.atan(7/(4*mp.sqrt(2))))/8
        exact = (mp.power(2, -mp.mpf(19)/72) *
                 mp.power(3, -mp.mpf(1)/64) * mp.exp(1j*phi))

        def on_sheet(x):
            trace = 2*mp.cos(2*mp.pi*x)
            return endpoint_ratio(theta, x, v, mp.sqrt(2-trace**2))

        ratio = on_sheet(u)
        derivative = mp.diff(on_sheet, u)/ratio
        h = mp.power(10, -precision//4)
        centered = (mp.log(on_sheet(u+h))-mp.log(on_sheet(u-h)))/(2*h)
        error = abs(ratio-exact)
        sheet_error = abs(endpoint_ratio(theta, u, v, -1)-mp.conj(exact))
        print(precision, "digits; C1/C0 =", mp.nstr(ratio, 20))
        print("|ratio - algebraic| =", mp.nstr(error, 4),
              "; opposite-sheet error =", mp.nstr(sheet_error, 4))
        print("d log(C1/C0)/du =", mp.nstr(derivative, 20),
              "; centered error =", mp.nstr(abs(centered-derivative), 4))
        assert max(error, sheet_error) < mp.power(10, 3-precision)
        assert abs(centered-derivative) < 10000*h*h


if __name__ == "__main__":
    for digits in (35, 60):
        check(digits)
