"""Check oscillator splittings and the relative and center motions of open Toda."""
from fractions import Fraction
from math import acos, atan2, atanh, cosh, exp, isclose, log, pi, sqrt, tanh


def kick_drift_kick(q, p, h):
    p -= h*q/2
    q += h*p
    p -= h*q/2
    return q, p


def oscillator(h=0.2, steps=1000):
    q, p = 1., 0.
    energy = []
    modified = []
    alpha = 1-h*h/4
    previous_angle = phase = 0.
    for _ in range(steps):
        q, p = kick_drift_kick(q, p, h)
        energy.append((p*p+q*q)/2)
        modified.append((p*p+alpha*q*q)/2)
        angle = atan2(-p, sqrt(alpha)*q)
        phase += (angle-previous_angle+pi) % (2*pi)-pi
        previous_angle = angle
    theta = acos(1-h*h/2)
    assert abs(phase-steps*theta) < 1e-11
    print("Energy range and maximum quadratic-invariant drift:",
          min(energy), max(energy), max(abs(v-alpha/2) for v in modified))
    print("Measured phase error and explicit Euler energy:", phase-steps*h, (1+h*h)**steps/2)


def alternating_steps():
    # Apply the two shears to each basis vector in exact rational arithmetic.
    def pair(q, p):
        q, p = kick_drift_kick(q, p, Fraction(1))
        return kick_drift_kick(q, p, Fraction(9, 5))

    a, c = pair(1, 0)
    b, d = pair(0, 1)
    trace = a+d
    assert a*d-b*c == 1 and trace == Fraction(-289, 125)
    multipliers = [(trace+sign*sqrt(trace**2-4))/2 for sign in (-1, 1)]
    print("Alternating pair trace and eigenvalues:", trace, multipliers)


def toda():
    p, a = 1., 2.
    energy = p*p+a
    root = sqrt(energy)
    for h in (0.25, 0.125, 0.0625):
        pivot = 1+h*p
        next_pivot = 1-h*p-h*h*a/pivot
        discrete_p = p+h*a/pivot
        discrete_a = a*next_pivot/pivot
        half = p+h*a/2
        verlet_a = a*exp(-2*h*half)
        verlet_p = half+h*verlet_a/2
        print("Step, factor-reversal and Verlet energy defects:", h,
              discrete_p**2+discrete_a-energy, verlet_p**2+verlet_a-energy)

        duration = atanh(h*root)/root
        angle = atanh(p/root)+root*duration
        assert isclose(discrete_p, root*tanh(angle), rel_tol=2e-15)
        assert isclose(discrete_a, energy/cosh(angle)**2, rel_tol=2e-15)
        center_shift = (log(pivot)+log(next_pivot))/2
        assert isclose(center_shift, log(1-h*h*energy)/2, abs_tol=2e-16)
        nominal_p = root*tanh(atanh(p/root)+root*h)
        print("Relative duration, p at nominal time, discrete p, center shift:",
              duration, nominal_p, discrete_p, center_shift)


if __name__ == "__main__":
    oscillator()
    alternating_steps()
    toda()
