"""Independent probes of rank-two oper monodromy, frames, and Gaudin spins.

Run with Python 3, NumPy and SciPy. Spin lengths, times and surface
coordinates are dimensionless, with the normalizations in the readings.
"""
import numpy as np
from scipy.integrate import quad, solve_ivp
from scipy.linalg import eigvalsh, expm, expm_frechet


def hat(v):
    x, y, z = v
    return np.array([[0, -z, y], [z, 0, -x], [-y, x, 0]])


def oper_monodromy(nu, tol):
    # Fundamental solution in (y,y_x) at x=1, along x=exp(i t).
    def rhs(t, state):
        x = np.exp(1j*t)
        coefficient = (nu**2-1) / (4*x*x)
        generator = 1j*x*np.array([[0, 1], [coefficient, 0]])
        return (generator @ state.reshape(2, 2)).ravel()

    result = solve_ivp(rhs, (0, 2*np.pi), np.eye(2, dtype=complex).ravel(),
                       method="DOP853", rtol=tol, atol=tol/100)
    assert result.success
    return result.y[:, -1].reshape(2, 2)


def geometric_checks():
    eps = .25
    cut = np.sqrt(eps)
    period = 2*quad(lambda x: np.sqrt(eps-x*x), -cut, cut)[0]
    np.testing.assert_allclose(period, np.pi*eps, atol=1e-12)
    # Principal curvatures from the generalized symmetric eigenproblem.
    angle = np.pi/3
    first = np.array([[1, np.cos(angle)], [np.cos(angle), 1]])
    second = np.array([[0, np.sin(angle)], [np.sin(angle), 0]])
    print("Imaginary part of shrinking period and principal curvatures:",
          period, eigvalsh(second, first))
    # At the origin the covariant acceleration is the symmetric part of
    # the x derivative of F^{-1} F_x: the skew connection is zero there.
    h = np.diag([1., -1., 0.])
    c = np.array([[0., 1., 0.], [1., 0., 0.], [0., 0., 0.]])
    d = np.diag([1., 1., -2.])

    def tangent(x):
        gauge = expm(x*x*c/2)
        raw = np.linalg.solve(gauge, h @ gauge) + x*c
        return (raw + raw.T)/2

    for x in (-.33, 0., .41):
        np.testing.assert_allclose(tangent(x)@d, d@tangent(x), atol=1e-12)
    accel = (tangent(1e-5)-tangent(-1e-5))/(2e-5)
    np.testing.assert_allclose(accel, c, atol=1e-10)
    print("Normal acceleration norm in the trace metric:", np.linalg.norm(accel))
    # Compare the transverse and axial displacements in the figure to the
    # derivative of a matrix exponential, at intermediate points as well.
    phi = 4*np.arctan(np.exp(-1.))
    for lam in (1., 2+np.sqrt(3.)):
        vector = np.array([lam+np.cos(phi)/lam, np.sin(phi)/lam, -2/np.cosh(1)])/2
        tangent = np.array([lam-np.cos(phi)/lam, -np.sin(phi)/lam, 0.])/2
        freq = np.linalg.norm(vector)
        axis = vector/freq
        axial_speed = tangent @ axis
        perpendicular = tangent-axial_speed*axis
        side = np.cross(axis, perpendicular)
        errors = []
        for y in np.linspace(0, 2*np.pi, 21):
            frame, derivative = expm_frechet(y*hat(vector), y*hat(tangent))
            skew = derivative @ frame.T
            measured = skew[[2, 0, 1], [1, 2, 0]]
            exact = (axial_speed*y*axis + np.sin(freq*y)*perpendicular/freq
                     + (1-np.cos(freq*y))*side/freq)
            errors.append(np.linalg.norm(measured-exact))
        assert max(errors) < 6e-13
        print("Frame frequency, orbit radius, axial advance, maximum path error:",
              freq, np.linalg.norm(perpendicular)/freq, axial_speed*2*np.pi, max(errors))


def quantum_and_classical_spins():
    # Build the full eight-dimensional product representation directly.
    sigma = [np.array([[0, 1], [1, 0]]), np.array([[0, -1j], [1j, 0]]),
             np.diag([1, -1])]
    spins = []
    for site in range(3):
        block = []
        for pauli in sigma:
            factors = [pauli/2 if k == site else np.eye(2) for k in range(3)]
            block.append(np.kron(np.kron(factors[0], factors[1]), factors[2]))
        spins.append(block)
    z = [0., 1., 3.]
    charges = []
    for i in range(3):
        charge = np.zeros((8, 8), dtype=complex)
        for j in range(3):
            if i != j:
                charge += sum(a @ b for a, b in zip(spins[i], spins[j]))/(z[i]-z[j])
        charges.append(charge)
    g1 = eigvalsh(charges[0])
    expect = np.repeat(np.array([-1/3, (2-np.sqrt(7))/6, (2+np.sqrt(7))/6]), [4, 2, 2])
    np.testing.assert_allclose(g1, expect, atol=1e-13)
    total = sum(z[i]*charges[i] for i in range(3))
    np.testing.assert_allclose(eigvalsh(total), np.repeat([-.75, .75], 4), atol=1e-13)
    print("Distinct first-charge readings:", expect[[0, 4, 6]])

    def spin_rhs(t, flat):
        s = flat.reshape(3, 3)
        return np.cross(s.sum(axis=0), s).ravel()

    half_time = np.pi/np.sqrt(3)
    result = solve_ivp(spin_rhs, (0, 2*half_time), np.eye(3).ravel(),
                       t_eval=[half_time, 2*half_time], rtol=2e-12, atol=1e-14,
                       method="DOP853")
    assert result.success
    z_readings = result.y[2]
    np.testing.assert_allclose(z_readings, [2/3, 0.], atol=3e-12)
    print("Classical site-one z at half and full period:", z_readings)


if __name__ == "__main__":
    geometric_checks()
    for nu in (0, 2):
        # Columns' initial values and derivatives for sqrt(x), sqrt(x) log(x),
        # or the two distinct powers, convert solution-base to Cauchy-data monodromy.
        base = np.array([[1., 0], [.5, 1.]]) if nu == 0 else np.eye(2)
        change = np.array([[-1., -2j*np.pi], [0., -1.]]) if nu == 0 else -np.eye(2)
        exact = base @ change @ np.linalg.inv(base)
        for tol in (1e-9, 1e-12):
            current = oper_monodromy(nu, tol)
            err = np.linalg.norm(current-exact)
            assert err < 100*tol
            print("Oper exponent difference, relative tolerance, monodromy error:", nu, tol, err)
    quantum_and_classical_spins()
