"""Exact finite Toda and Ablowitz--Ladik checks, plus a continuum consistency test."""
import cmath
import math
import sympy as sp


def open_toda():
    h = sp.Rational(1, 4)
    old = sp.Matrix([[1, sp.sqrt(2)], [sp.sqrt(2), -1]])
    chol = (sp.eye(2) + h*old).cholesky()
    new = ((chol.T*chol-sp.eye(2))/h).applyfunc(sp.simplify)
    assert (old*chol-chol*new).applyfunc(sp.simplify) == sp.zeros(2)
    assert (old*chol-chol*old).applyfunc(sp.simplify) != sp.zeros(2)
    assert sp.simplify(new.trace()-old.trace()) == 0
    assert new.det() == old.det() == -3
    assert new[0, 0] == sp.Rational(7, 5)
    assert new[0, 1]**2 == sp.Rational(26, 25)
    print("Toda new diagonals and squared bond:", new[0, 0], new[1, 1], new[0, 1]**2)


def ablowitz_ladik():
    z = sp.symbols("z", nonzero=True)
    q = sp.symbols("q0:3")
    r = sp.symbols("r0:3")
    def space(j):
        return sp.Matrix([[z, q[j]], [r[j], 1/z]])
    def time(j):
        return sp.I*sp.Matrix([
            [z**2-1-q[j]*r[j-1], z*q[j]-q[j-1]/z],
            [z*r[j-1]-r[j]/z, 1-z**-2+q[j-1]*r[j]],
        ])
    flow = {}
    for j in range(3):
        next_j = (j+1) % 3
        defect = (time(next_j)*space(j) - space(j)*time(j)).applyfunc(sp.expand)
        flow[q[j]] = sp.I*((1-q[j]*r[j])*(q[next_j]+q[j-1])-2*q[j])
        flow[r[j]] = -sp.I*((1-q[j]*r[j])*(r[next_j]+r[j-1])-2*r[j])
        assert (defect-sp.Matrix([[0,flow[q[j]]],[flow[r[j]],0]])).applyfunc(sp.expand)==sp.zeros(2)
    trace = sp.expand((space(2)*space(1)*space(0)).trace())
    coeff = trace.coeff(z, 1)
    assert sp.expand(sum(sp.diff(coeff,v)*dv for v,dv in flow.items())) == 0
    values = dict(zip(q, [sp.Rational(1,5),(1+sp.I)/4,(-1+2*sp.I)/7]))
    values.update({r[j]:-sp.conjugate(values[q[j]]) for j in range(3)})
    print("Three-site focusing trace coefficient:", sp.simplify(coeff.subs(values)))


def continuum_error(h, sigma):
    x = 0.4
    def field(y):
        return cmath.exp(1j*y)*(1+0.25*math.cos(2*y))
    f = field(x)
    fxx = cmath.exp(1j*x)*(-1-1.25*math.cos(2*x)-1j*math.sin(2*x))
    neighbors = field(x+h)+field(x-h)
    lattice = (neighbors-2*f)/h**2 - sigma*abs(f)**2*neighbors
    return abs(lattice - (fxx-2*sigma*abs(f)**2*f))


def spectral_clocks():
    from numpy import array, diag, eye, linalg, log, testing

    h = 0.25
    bond = array([1., 1.])
    old = diag(bond, 1) + diag(bond, -1)
    lower = linalg.cholesky(eye(3) + h * old)
    new = (lower.T @ lower - eye(3)) / h
    levels, vectors = linalg.eigh(old)
    new_levels, new_vectors = linalg.eigh(new)
    weights, updated = vectors[0]**2, new_vectors[0]**2
    testing.assert_allclose(new_levels, levels, atol=1e-14)
    testing.assert_allclose(updated, (1 + h * levels) * weights)
    gains = log(updated / weights)
    print("Toda pair durations:", (gains[1:] - gains[:-1]) / (levels[1:] - levels[:-1]))


def pulse_and_sidebands():
    import numpy as np

    beta = math.log(2)
    for center in (0., 0.5):
        sites = np.arange(-44, 45)
        pulse = np.sinh(beta) / np.cosh(beta * (sites - center))
        neighbors = pulse[2:] + pulse[:-2]
        residual = (1 + pulse[1:-1]**2) * neighbors - 2*np.cosh(beta)*pulse[1:-1]
        assert max(abs(residual)) < 1e-14
        assert abs(np.log1p(pulse**2).sum() - 2*beta) < 1e-14
    amplitude = 0.5
    for count in (6, 8):
        def field(perturbation):
            q = amplitude + perturbation[:count] + 1j*perturbation[count:]
            neighbors = np.roll(q, 1) + np.roll(q, -1)
            velocity = 1j*((1 + abs(q)**2)*neighbors - 2*(1 + amplitude**2)*q)
            return np.concatenate((velocity.real, velocity.imag))

        # Differentiate all real site variables, independently of the Fourier formula.
        basis = np.eye(2*count) * 1e-6
        jacobian = np.column_stack([(field(v) - field(-v)) / 2e-6 for v in basis])
        measured = max(np.linalg.eigvals(jacobian).real)
        cd = (1+amplitude**2) * 4*np.sin(np.pi/count)**2
        expected = math.sqrt(max(0., cd*(4*amplitude**2-cd)))
        assert abs(measured - expected) < 2e-5
        print("Ring size, maximum linear growth:", count, expected)


if __name__ == "__main__":
    open_toda()
    ablowitz_ladik()
    spectral_clocks()
    pulse_and_sidebands()
    for sigma in (-1,1):
        errors = [continuum_error(h,sigma) for h in (0.1,0.05,0.025)]
        print("Reduction, generator errors:",sigma,*(f"{e:.9g}" for e in errors))
