"""Numerical companions to four deformation examples in the Models atlas.

Run with Python 3 and NumPy: python3 deformation_checks.py
All integrals use Gauss–Legendre quadrature. The tests exercise specified
examples; the determinant discretization and period asymptotics are not proofs.
"""

from fractions import Fraction
from math import pi, prod, sqrt

import numpy as np
from numpy.polynomial.legendre import leggauss


def sine_gap(length, order):
    """Return E(s), sigma(pi*s), and the signed sigma-form PV residual.

    Map the interval to [0,1]. The matrix represents the sine kernel, whose
    diagonal is s. Differentiate this smooth kernel analytically three times.
    """
    nodes, weights = leggauss(order)
    difference = pi * (nodes[:, None] - nodes[None, :]) / 2
    measure = np.sqrt(np.outer(weights, weights)) / 2
    phase = length * difference
    matrix = np.eye(order) - length * np.sinc(phase / pi) * measure
    sign, logdet = np.linalg.slogdet(matrix)
    assert sign == 1
    derivatives = (np.cos(phase), -difference * np.sin(phase),
                   -difference**2 * np.cos(phase))
    first, second, third = (np.linalg.solve(matrix, kernel * measure)
                            for kernel in derivatives)
    # Successive s-derivatives of log det(I-K), using cyclicity of trace.
    g1 = -np.trace(first)
    g2 = -np.trace(second + first @ first)
    g3 = -np.trace(third + 3 * first @ second + 2 * first @ first @ first)
    t = pi * length
    sigma = length * g1
    dsigma = (g1 + length * g2) / pi
    d2sigma = (2 * g2 + length * g3) / pi**2
    common = t * dsigma - sigma
    residual = (t * d2sigma)**2 + 4 * common * (common + dsigma**2)
    return np.exp(logdet), sigma, residual


def commutator(left, right):
    return left @ right - right @ left


def fuchsian_checks():
    """Test flatness away from the poles and recover the Garnier numerator."""
    z = 0.7 + 0.6j
    poles = (0, 1, 2)
    diagonal = np.diag([1.0, -1.0])
    residues = (diagonal / 6, diagonal / 10, np.array([[0, 1], [1, 0]]) / 4)
    skew = np.array([[0, -1], [1, 0]])
    rates = (skew / 24, skew / 20, -11 * skew / 120)
    a = sum(r / (z - p) for r, p in zip(residues, poles))
    b = -residues[-1] / (z - poles[-1])
    # In A_t-B_z the two double-pole terms cancel, leaving the residue rates.
    simple_poles = sum(v / (z - p) for v, p in zip(rates, poles))
    error = np.linalg.norm(simple_poles + commutator(a, b))
    reversed_error = np.linalg.norm(-simple_poles + commutator(a, b))
    assert error < 1e-13 and reversed_error > 1e-2
    print(f"Schlesinger flatness, Frobenius norm: {error:.2e}; "
          f"reversing all three rates: {reversed_error:.6f}")

    poles = (0, 1, 2, 4)
    entries = [Fraction((p + 1) * (p - 3),
                        prod(p - q for q in poles if p != q)) for p in poles]
    assert sum(entries) == 0
    assert entries == [Fraction(3, 8), Fraction(-4, 3),
                       Fraction(3, 4), Fraction(5, 24)]
    for z in (-1, 3, 5):
        numerator = sum(b * prod(z - q for q in poles if p != q)
                        for p, b in zip(poles, entries))
        assert numerator == (z + 1) * (z - 3)
    print("Garnier upper-right entries at 0, 1, 2, 4:", *map(str, entries))


def nahm_check():
    """Test a complex spectral parameter and the two ends of the interval."""
    pauli = np.array([[[0, 1], [1, 0]], [[0, -1j], [1j, 0]], [[1, 0], [0, -1]]])
    residues = 0.5j * pauli
    s, zeta = 0.7, 0.3 + 0.4j
    t1, t2, t3 = residues / s
    a = t1 + 1j * t2 - 2j * zeta * t3 + zeta**2 * (t1 - 1j * t2)
    m = -1j * t3 + zeta * (t1 - 1j * t2)
    error = np.linalg.norm(-a / s - commutator(a, m))
    assert error < 1e-13 and np.linalg.norm(a @ a) < 1e-13
    print(f"Nahm Lax residual at s={s}, zeta={zeta}: {error:.2e}")
    # A nonzero pole residue has a nonzero scaled limit. At the right endpoint
    # d*T(2-d) vanishes; compare with the constant left residue d*T(d).
    for d in (1e-2, 1e-4):
        left = np.linalg.norm(residues[0])
        right = np.linalg.norm(d * residues[0] / (2 - d))
        print(f"  d={d:g}, scaled T1 norms: left {left:.6f}, right {right:.6f}")
        assert right < d * left


def sw_periods(epsilon, order):
    """Return a/Lambda, Im(a_D)/(Lambda*epsilon) at u/Lambda² = 1+epsilon.

    Resolve both integrable endpoint singularities before quadrature. Set
    z=cos(theta) on the electric cut and z=1+epsilon*sin(theta)^2 on the
    shrinking magnetic cut. This is the real branch with positive Im(a_D).
    """
    x, weights = leggauss(order)
    theta = pi * (x + 1) / 2
    # Use 1-cos(theta)=2 sin(theta/2)^2 near the pinching endpoint.
    electric = sqrt(2) / 2 * weights @ np.sqrt(epsilon + 2 * np.sin(theta / 2)**2)
    phi = theta / 2
    magnetic = sqrt(2) / 2 * weights @ (np.cos(phi)**2 /
                                          np.sqrt(2 + epsilon * np.sin(phi)**2))
    return electric, magnetic


def main():
    for length in (0.5, 1.0):
        coarse = sine_gap(length, 16)
        fine = sine_gap(length, 32)
        assert max(abs(a - b) for a, b in zip(coarse, fine)) < 1e-10
        assert abs(fine[2]) < 1e-10
        print(f"Sine gap s={length:g}: E={fine[0]:.12f}, "
              f"sigma={fine[1]:.10f}, PV residual={fine[2]:.2e}")
    for length in (0.1, 0.05):
        gap = sine_gap(length, 24)[0]
        coefficient = (gap - 1 + length) / length**4
        print(f"  s={length:g}, (E-1+s)/s^4={coefficient:.8f}; limit {pi**2/36:.8f}")
        assert abs(coefficient - pi**2 / 36) < length**2
    fuchsian_checks()
    nahm_check()
    limit, slope = 4 / pi, 0.5
    electric, magnetic = sw_periods(0, 48)
    assert abs(electric - limit) < 1e-12 and abs(magnetic - slope) < 1e-12
    for eps in (0.01, 0.001):
        values = sw_periods(eps, 64)
        assert np.max(np.abs(np.array(values) - sw_periods(eps, 96))) < 2e-12
        correction = (values[1] - slope) / eps
        assert abs(correction + 1 / 32) < eps / 10
        print(f"SW epsilon={eps:g}: a/Lambda={values[0]:.10f}, "
              f"Im(a_D)/(Lambda*epsilon)={values[1]:.10f}, "
              f"first correction={correction:.7f} (limit -1/32)")


if __name__ == "__main__":
    main()
