"""Numerical checks for the Library article "Isomonodromic deformations of Fuchsian systems".

System: dY/dz = (A0/z + At/(z - t) + A1/(z - 1)) Y with traceless 2x2 residues and
A_inf = -(A0 + At + A1). Schlesinger flow in t (sign convention of "Moving Fuchsian residues"):
    dA0/dt = [At, A0]/t,  dA1/dt = [At, A1]/(t - 1),  dAt/dt = [A0, At]/t + [A1, At]/(t - 1).

1. Monodromy. Matrices around 0, t and 1 are computed from the base point 0.5 - i along based loops
   that stay at least 0.1 from every pole during the deformation. Their traces and the traces of
   their pairwise products are conjugation invariants and must stay fixed along the flow.
   Controls: the sign-reversed flow and frozen residues keep every residue's eigenvalues (and, for
   the reversed flow, A_inf) but change the pairwise traces.
2. Painleve VI. After a constant conjugation making A_inf = diag(k1, k2), the zero q(t) of the (1,2)
   entry of A(z) must satisfy Painleve VI with alpha = (theta_inf - 1)^2/2, beta = -theta_0^2/2,
   gamma = theta_1^2/2 and delta = (1 - theta_t^2)/2, where theta_inf = k1 - k2. The derivatives of q
   come exactly from the flow and are compared with finite differences. Controls: delta without its
   shift, and theta_inf with the wrong sign.
3. Hamiltonians. For four finite poles, H_j = sum_{i != j} tr(A_j A_i)/(a_j - a_i) must generate the
   Schlesinger equations through {F, G} = sum_i tr(A_i [grad_i F, grad_i G]) and Poisson commute,
   so that sum_j H_j da_j is closed. Control: squared denominators do not commute.
Run with Python 3, NumPy and SciPy:  python3 schlesinger_monodromy.py
"""
import numpy as np
from scipy.integrate import solve_ivp

TOL = dict(rtol=1e-12, atol=1e-13, method='DOP853')
LOOSE = dict(rtol=1e-10, atol=1e-11, method='DOP853')
THETA = {'0': 0.3, 't': 0.45, '1': 0.25}
T0, T1 = 0.3 + 0.2j, 0.45 + 0.35j
BASE = 0.5 - 1.0j
RADII = {'0': 0.15, 't': 0.1, '1': 0.15}


def initial_residues(seed=7):
    """Random sl2 residues with eigenvalues +-theta/2 at 0, t and 1."""
    rng = np.random.default_rng(seed)
    out = []
    for key in ('0', 't', '1'):
        g = rng.normal(size=(2, 2)) + 1j * rng.normal(size=(2, 2))
        out.append(g @ np.diag([THETA[key] / 2, -THETA[key] / 2]) @ np.linalg.inv(g))
    return tuple(out)


def comm(a, b):
    return a @ b - b @ a


def schlesinger(t, A0, At, A1, sign=1.0):
    """Right sides (dA0, dAt, dA1); sign = -1 gives the reversed look-alike flow."""
    u, v = 1 / t, 1 / (t - 1)
    return (sign * u * comm(At, A0),
            sign * (u * comm(A0, At) + v * comm(A1, At)),
            sign * v * comm(At, A1))


def flow(residues, samples, sign=1.0, tol=TOL, t0=T0, t1=T1):
    """Residues at t0 + s (t1 - t0) for increasing s in samples, integrating segment by segment."""
    dt = t1 - t0

    def rhs(s, y):
        A0, At, A1 = y.reshape(3, 2, 2)
        return np.concatenate([d.ravel() for d in schlesinger(t0 + s * dt, A0, At, A1, sign)]) * dt

    y = np.concatenate([A.ravel() for A in residues]).astype(complex)
    out, s_now = [], 0.0
    for s in samples:
        if s > s_now:
            y = solve_ivp(rhs, (s_now, s), y, **tol).y[:, -1]
            s_now = s
        out.append(tuple(y.reshape(3, 2, 2)))
    return out


def segment(a, b):
    return lambda s: (a + s * (b - a), b - a)


def circle(center, radius):
    def path(s):
        w = radius * np.exp(1j * (-np.pi / 2 + 2 * np.pi * s))
        return center + w, 2j * np.pi * w
    return path


def loops(t):
    """Based loops: base -> bottom of a small circle -> once counterclockwise -> back to base."""
    out = {}
    for key, center in (('0', 0.0), ('t', t), ('1', 1.0)):
        start = center - 1j * RADII[key]
        out[key] = [segment(BASE, start), circle(center, RADII[key]), segment(start, BASE)]
    return out


def clearance(t, n=2001):
    """Smallest distance between a pole and any loop, sampled along every piece."""
    poles = np.array([0.0, t, 1.0])
    s = np.linspace(0, 1, n)
    points = np.concatenate([piece(s)[0] * np.ones(n)
                             for pieces in loops(t).values() for piece in pieces])
    return np.min(np.abs(points[:, None] - poles[None, :]))


def transport(residues, t, path, tol=TOL):
    """Solve dY/dz = A(z) Y along z(s), s in [0, 1], from Y = I."""
    A0, At, A1 = residues

    def rhs(s, y):
        z, dz = path(s)
        A = A0 / z + At / (z - t) + A1 / (z - 1)
        return (A @ y.reshape(2, 2)).ravel() * dz

    sol = solve_ivp(rhs, (0, 1), np.eye(2, dtype=complex).ravel(), **tol)
    return sol.y[:, -1].reshape(2, 2)


def monodromy(residues, t, tol=TOL):
    """Continue the fundamental matrix with Y(base) = I once around each pole.

    Each piece's fundamental solution (identity at the piece's start) maps the value at the start
    to the value at the end, so a loop's matrix is the ordered product of its pieces.
    """
    out = {}
    for key, pieces in loops(t).items():
        Y = np.eye(2, dtype=complex)
        for piece in pieces:
            Y = transport(residues, t, piece, tol) @ Y
        out[key] = Y
    return out


def invariants(residues, t, tol=TOL):
    M = monodromy(residues, t, tol)
    m0, mt, m1 = M['0'], M['t'], M['1']
    return np.array([np.trace(m0), np.trace(mt), np.trace(m1),
                     np.trace(m0 @ mt), np.trace(mt @ m1), np.trace(m0 @ m1)])


def eig(A):
    return np.sort_complex(np.linalg.eigvals(A))


# Painleve VI from the (1,2) zero ------------------------------------------------------------
def diagonalize_infinity(residues):
    """Conjugate every residue by one constant matrix so that A_inf = -(A0 + At + A1) is diagonal."""
    w, V = np.linalg.eig(-sum(residues))
    Vi = np.linalg.inv(V)
    return tuple(Vi @ A @ V for A in residues), w[0] - w[1]


def q_jet(t, A0, At, A1):
    """q = zero of the (1,2) entry of A(z) and its first two t-derivatives along the flow.

    With A_inf diagonal the (1,2) numerator b0 (z-t)(z-1) + bt z(z-1) + b1 z(z-t) is linear in z,
    so q = -b0 t / (t bt + b1). Derivatives of the residues come from the flow and its derivative.
    """
    D0, Dt, D1 = schlesinger(t, A0, At, A1)
    u, v = 1 / t, 1 / (t - 1)
    E0 = -u**2 * comm(At, A0) + u * (comm(Dt, A0) + comm(At, D0))
    E1 = -v**2 * comm(At, A1) + v * (comm(Dt, A1) + comm(At, D1))
    Et = (-u**2 * comm(A0, At) + u * (comm(D0, At) + comm(A0, Dt))
          - v**2 * comm(A1, At) + v * (comm(D1, At) + comm(A1, Dt)))
    b = [M[0, 1] for M in (A0, At, A1)]
    db = [M[0, 1] for M in (D0, Dt, D1)]
    ddb = [M[0, 1] for M in (E0, Et, E1)]
    n, dn, ddn = -b[0] * t, -db[0] * t - b[0], -ddb[0] * t - 2 * db[0]
    d, dd, ddd = t * b[1] + b[2], b[1] + t * db[1] + db[2], 2 * db[1] + t * ddb[1] + ddb[2]
    q = n / d
    dq = (dn * d - n * dd) / d**2
    ddq = (ddn * d - n * ddd) / d**2 - 2 * dd * (dn * d - n * dd) / d**3
    return q, dq, ddq


def painleve_vi_rhs(t, q, dq, alpha, beta, gamma, delta):
    return (0.5 * (1 / q + 1 / (q - 1) + 1 / (q - t)) * dq**2
            - (1 / t + 1 / (t - 1) + 1 / (q - t)) * dq
            + q * (q - 1) * (q - t) / (t**2 * (t - 1)**2)
            * (alpha + beta * t / q**2 + gamma * (t - 1) / (q - 1)**2
               + delta * t * (t - 1) / (q - t)**2))


def pvi_parameters(theta_inf, shift_delta=True):
    return (0.5 * (theta_inf - 1)**2, -0.5 * THETA['0']**2, 0.5 * THETA['1']**2,
            0.5 * ((1 if shift_delta else 0) - THETA['t']**2))


# Hamiltonians for four finite poles ---------------------------------------------------------
def hamiltonian_checks(seed=11, power=1):
    """Max deviation of Hamilton's equations from Schlesinger, and max |{H_j, H_k}|."""
    rng = np.random.default_rng(seed)
    a = np.array([0.0, 0.3 + 0.2j, 1.0, 2.5 - 0.4j])
    A = []
    for _ in a:
        X = rng.normal(size=(2, 2)) + 1j * rng.normal(size=(2, 2))
        A.append(X - np.trace(X) / 2 * np.eye(2))

    def grad(j):
        """Gradients of H_j = sum_{i != j} tr(A_j A_i)/(a_j - a_i)^power, using dF = sum tr(grad_i F dA_i)."""
        g = [np.zeros((2, 2), complex) for _ in a]
        for i in range(len(a)):
            if i != j:
                w = 1 / (a[j] - a[i])**power
                g[i] = g[i] + w * A[j]
                g[j] = g[j] + w * A[i]
        return g

    def bracket(gF, gG):
        return sum(np.trace(A[i] @ comm(gF[i], gG[i])) for i in range(len(a)))

    def direct(j, i):
        """The Schlesinger right side for dA_i/da_j."""
        if i != j:
            return comm(A[i], A[j]) / (a[i] - a[j])
        return -sum(comm(A[k], A[j]) / (a[k] - a[j]) for k in range(len(a)) if k != j)

    worst = max(np.max(np.abs(comm(grad(j)[i], A[i]) - direct(j, i)))
                for j in range(len(a)) for i in range(len(a)))
    brackets = max(abs(bracket(grad(j), grad(k))) for j in range(4) for k in range(j + 1, 4))
    # Along solutions dH_j/da_k = (implicit part through the residues) + tr(A_j A_k)/(a_j - a_k)^2;
    # the implicit part, computed from the direct Schlesinger formula, must vanish.
    implicit = max(abs(sum(np.trace(grad(j)[i] @ direct(k, i)) for i in range(len(a))))
                   for j in range(4) for k in range(4) if j != k)

    # The proof's decomposition: each pair of terms sharing an index contributes T_{jkl} times
    # 1/((a_j-a_l)(a_k-a_l)), 1/((a_j-a_l)(a_j-a_k)) or -1/((a_j-a_k)(a_k-a_l)).
    def term(p, q, weight):
        g = [np.zeros((2, 2), complex) for _ in a]
        g[p], g[q] = weight * A[q], weight * A[p]
        return g

    def T(j, k, l):
        return np.trace(A[j] @ comm(A[k], A[l]))

    w = lambda x, y: 1 / (a[x] - a[y])**power
    pieces = 0.0
    for j, k in ((0, 1), (1, 3), (2, 0)):
        for l in range(len(a)):
            if l in (j, k):
                continue
            pieces = max(pieces,
                         abs(bracket(term(j, l, w(j, l)), term(k, l, w(k, l))) - w(j, l) * w(k, l) * T(j, k, l)),
                         abs(bracket(term(j, l, w(j, l)), term(k, j, w(k, j))) - w(j, l) * w(j, k) * T(j, k, l)),
                         abs(bracket(term(j, k, w(j, k)), term(k, l, w(k, l))) + w(j, k) * w(k, l) * T(j, k, l)))
    return worst, brackets, implicit, pieces


def trace_paths(samples):
    """tr(M0 M1) along the deformation for the Schlesinger flow, its sign reversal and frozen residues."""
    residues = initial_residues()
    times = [T0 + s * (T1 - T0) for s in samples]
    out = {}
    for name, states in (('schlesinger', flow(residues, samples)),
                         ('reversed', flow(residues, samples, sign=-1.0)),
                         ('frozen', [residues] * len(samples))):
        out[name] = np.array([invariants(R, t)[5] for R, t in zip(states, times)])
    return out


def main():
    np.set_printoptions(precision=10, suppress=True)
    residues = initial_residues()
    A0, At, A1 = residues
    (R1,), (Rrev,) = flow(residues, [1.0]), flow(residues, [1.0], sign=-1.0)
    inv0, inv1 = invariants(residues, T0), invariants(R1, T1)
    inv_rev, inv_frozen = invariants(Rrev, T1), invariants(residues, T1)
    local = [2 * np.cos(np.pi * THETA[k]) for k in ('0', 't', '1')]
    refine = np.max(np.abs(invariants(residues, T0, LOOSE) - inv0))
    gap = min(clearance(T0 + s * (T1 - T0)) for s in np.linspace(0, 1, 101))

    print('pairwise traces (M0Mt, MtM1, M0M1) at t0:          ', inv0[3:])
    print('after the Schlesinger flow to t1:                   ', inv1[3:])
    print('after the sign-reversed flow to t1:                 ', inv_rev[3:])
    print('residues frozen, pole moved to t1:                  ', inv_frozen[3:])
    print(f'max change of all six invariants along the true flow: {np.max(np.abs(inv1 - inv0)):.2e}')
    print(f'tolerance refinement at t0 (rtol 1e-10 vs 1e-12):     {refine:.2e}')
    print(f'smallest pole-to-loop distance along the deformation: {gap:.3f}')

    checks = {
        'residue eigenvalues preserved by the flow': all(
            np.allclose(eig(R1[i]), eig(R), atol=1e-10) for i, R in enumerate(residues)),
        'A_inf = -(A0 + At + A1) preserved by the flow': np.allclose(sum(R1), sum(residues), atol=1e-10),
        'local traces tr M_i = 2 cos(pi theta_i) for every deformation': all(
            np.allclose(inv[:3], local, atol=1e-9) for inv in (inv0, inv1, inv_rev, inv_frozen)),
        'reversed flow also preserves A_inf': np.allclose(sum(Rrev), sum(residues), atol=1e-10),
        'pairwise traces preserved along the Schlesinger flow (1e-8)': np.allclose(inv0, inv1, atol=1e-8),
        'no loop comes within 0.05 of a pole during the deformation': gap > 0.05,
    }
    controls = {
        'reversed flow keeps local data but changes the pairwise traces': not np.allclose(inv0[3:], inv_rev[3:], atol=1e-4),
        'frozen residues with a moved pole change the pairwise traces': not np.allclose(inv0[3:], inv_frozen[3:], atol=1e-4),
    }
    # Chain rule: d tr/dt = (moving the pole) + (changing the residues). The Schlesinger change cancels
    # the first term, so the reversed flow starts at twice the frozen-residue velocity.
    early = trace_paths([0.0, 1e-3, 2e-3])
    velocity = {k: -3 * v[0] + 4 * v[1] - v[2] for k, v in early.items()}
    ratio = velocity['reversed'] / velocity['frozen']
    print(f'initial velocity of tr(M0 M1), reversed / frozen:    {ratio:.6f}')
    checks['reversed flow starts at twice the frozen velocity (1e-4)'] = abs(ratio - 2) < 1e-4

    # Painleve VI along the flow, in the gauge with A_inf diagonal.
    gauged, theta_inf = diagonalize_infinity(residues)
    samples = [0.0, 0.5, 1.0]
    states = flow(gauged, samples)
    print(f'theta_inf = k1 - k2 = {theta_inf:.10f}')
    worst, worst_shift, worst_sign, worst_fd = 0.0, np.inf, np.inf, 0.0
    h = 2.5e-3  # errors fall as h^4; nearby singularities of q(t), such as t = 0, bound h
    for s, R in zip(samples, states):
        t = T0 + s * (T1 - T0)
        q, dq, ddq = q_jet(t, *R)
        scale = max(1.0, abs(ddq))
        worst = max(worst, abs(ddq - painleve_vi_rhs(t, q, dq, *pvi_parameters(theta_inf))) / scale)
        worst_shift = min(worst_shift, abs(ddq - painleve_vi_rhs(t, q, dq, *pvi_parameters(theta_inf, False))) / scale)
        worst_sign = min(worst_sign, abs(ddq - painleve_vi_rhs(t, q, dq, *pvi_parameters(-theta_inf))) / scale)
        # Five-point stencils on q from the integrated flow, independent of the jet formulas.
        qs = {k: q_jet(t + k * h, *flow(R, [1.0], t0=t, t1=t + k * h)[0])[0] for k in (-2, -1, 1, 2)}
        fd1 = (-qs[2] + 8 * qs[1] - 8 * qs[-1] + qs[-2]) / (12 * h)
        fd2 = (-qs[2] + 16 * qs[1] - 30 * q + 16 * qs[-1] - qs[-2]) / (12 * h**2)
        worst_fd = max(worst_fd, abs(fd1 - dq) / max(1, abs(dq)), abs(fd2 - ddq) / scale)
        print(f'  s = {s:.1f}: q = {q:.8f}, distances to 0, 1, t = '
              f'{abs(q):.3f}, {abs(q - 1):.3f}, {abs(q - t):.3f}')
    print(f'Painleve VI relative residual (true parameters): {worst:.2e}')
    print(f'finite-difference check of dq/dt and d2q/dt2:    {worst_fd:.2e}')
    print(f'smallest residual with delta = -theta_t^2/2:     {worst_shift:.2e}')
    print(f'smallest residual with theta_inf -> -theta_inf:  {worst_sign:.2e}')
    checks['q(t) satisfies Painleve VI along the flow (1e-9)'] = worst < 1e-9
    checks['exact q derivatives agree with five-point differences (1e-6)'] = worst_fd < 1e-6
    controls['delta without its shift leaves a residual above 1e-3'] = worst_shift > 1e-3
    controls['theta_inf with the wrong sign leaves a residual above 1e-3'] = worst_sign > 1e-3

    hamilton, brackets, implicit, pieces = hamiltonian_checks()
    bad_brackets = hamiltonian_checks(power=2)[1]
    print(f'Hamilton equations vs Schlesinger, four finite poles: {hamilton:.2e}')
    print(f'max |{{H_j, H_k}}|: {brackets:.2e}; with squared denominators: {bad_brackets:.2e}')
    print(f'implicit part of dH_j/da_k along the flow: {implicit:.2e}')
    print(f'largest error in the three-term decomposition of {{H_j, H_k}}: {pieces:.2e}')
    checks['H_j generate the Schlesinger equations'] = hamilton < 1e-12
    checks['each shared-index pair gives the T_jkl term used in the proof'] = pieces < 1e-12
    checks['the H_j Poisson commute'] = brackets < 1e-12
    checks['dH_j/da_k = tr(A_j A_k)/(a_j - a_k)^2, so sum H_j da_j is closed'] = implicit < 1e-12
    controls['squared denominators do not Poisson commute'] = bad_brackets > 1e-3

    for name, ok in checks.items():
        print(f"{'PASS' if ok else 'FAIL'}  {name}")
    for name, ok in controls.items():
        print(f"{'PASS' if ok else 'FAIL'}  control: {name}")
    if not all(checks.values()) or not all(controls.values()):
        raise SystemExit(1)
    print('Monodromy, Painleve VI and Hamiltonian checks pass; every control fails as it should.')


if __name__ == '__main__':
    main()
