"""Compare direct transport with the gamma connection matrix of a real 3F2.

Run with Python, mpmath, NumPy and SciPy. Both normalized local bases
use the real logarithm of -z; rows label zero modes and columns infinity.
"""
import mpmath as mp
import numpy as np
from scipy.integrate import solve_ivp

mp.mp.dps = 45
numerators = tuple(mp.mpf(n) / d for n, d in [(1, 6), (2, 5), (3, 4)])
denominators = (mp.mpf(1), mp.mpf(4)/5, mp.mpf(13)/10)


def columns(solutions, time):
    """Fundamental matrix at t = log(-z), including two t-derivatives."""
    return np.array([[mp.diff(solution, time, order) for solution in solutions]
                     for order in range(3)], dtype=float)


def at_zero(j, time):
    exponent = 1 - denominators[j]
    upper = [a + exponent for a in numerators]
    lower = [b + exponent for i, b in enumerate(denominators) if i != j]
    return mp.exp(exponent * time) * mp.hyper(upper, lower, -mp.exp(time))


def at_infinity(k, time):
    power = numerators[k]
    upper = [1 + power - b for b in denominators]
    lower = [1 + power - a for i, a in enumerate(numerators) if i != k]
    return mp.exp(-power * time) * mp.hyper(upper, lower, -mp.exp(-time))


def gamma_coefficient(j, k):
    exponent = 1 - denominators[j]
    power = numerators[k]
    lower_factor = mp.fprod(mp.gamma(b + exponent) / mp.gamma(b - power)
                            for i, b in enumerate(denominators) if i != j)
    upper_factor = mp.fprod(mp.gamma(a - power) / mp.gamma(a + exponent)
                            for i, a in enumerate(numerators) if i != k)
    return lower_factor * upper_factor


def transported(relative_tolerance):
    # For theta=d/dt, the scalar ODE is (p(theta)-z*q(theta)) y = 0.
    p = np.poly(-np.array([float(b - 1) for b in denominators]))
    q = np.poly(-np.array(numerators, dtype=float))

    def flow(time, state):
        z = -np.exp(time)
        coefficients = (z*q - p) / (1 - z)
        companion = np.array([[0, 1, 0], [0, 0, 1], coefficients[1:][::-1]])
        return (companion @ state.reshape(3, 3)).ravel()

    start, end = mp.log(mp.mpf(1)/4), mp.log(2)
    origin_basis = columns([lambda t, j=j: at_zero(j, t) for j in range(3)], start)
    infinity_basis = columns([lambda t, k=k: at_infinity(k, t) for k in range(3)], end)
    result = solve_ivp(flow, (float(start), float(end)), origin_basis.ravel(),
                       method="DOP853", rtol=relative_tolerance,
                       atol=relative_tolerance / 100)
    if not result.success:
        raise RuntimeError(result.message)
    return np.linalg.solve(infinity_basis, result.y[:, -1].reshape(3, 3)).T


if __name__ == "__main__":
    reference = np.array([[float(gamma_coefficient(j, k)) for k in range(3)]
                          for j in range(3)])
    print("Reference matrix, rows at zero and columns at infinity:")
    print(reference)
    for tolerance in (1e-9, 1e-12):
        numerical = transported(tolerance)
        error = np.max(abs(numerical - reference))
        ratio = numerical[0, 0]*numerical[1, 1] / (numerical[0, 1]*numerical[1, 0])
        print(f"relative tolerance={tolerance:g}, max entry error={error:.3e}, "
              f"cross ratio={ratio:.12f}")
        assert error < tolerance
