"""Finite checks for the classical perturbation and course readings.

Python 3.9+, NumPy, SciPy and SymPy. Run this file directly.
"""

from math import cos, cosh, pi, sin, sinh, sqrt, tanh

import numpy as np
import sympy as sp
from scipy.integrate import quad, solve_ivp
from scipy.linalg import expm


def rotating_ellipse():
    """Integrate the laboratory matrix, then compare with the rotating frame."""
    poisson = np.array([[0., 1.], [-1., 0.]])
    A, C = 4., 1.
    diagonal = np.diag([A, C])
    omega = sqrt(A*C)

    def connection(phi):
        b = (A-C)*sin(phi)*cos(phi)
        c = A*sin(phi)**2 + C*cos(phi)**2
        db = (A-C)*cos(2*phi)
        dc = 2*b
        return -(db - (b/c)*dc)/(2*omega)

    angle, error = quad(connection, 0, pi, epsabs=2e-13, epsrel=2e-13)
    assert abs(angle-pi/4) < 1e-12 and error < 1e-12
    for rate in (0.2, 0.1, 0.05):
        def rhs(t, flat):
            co, si = cos(rate*t), sin(rate*t)
            rotation = np.array([[co, -si], [si, co]])
            return (poisson @ rotation @ diagonal @ rotation.T @ flat.reshape(2, 2)).ravel()

        period = pi/rate
        result = solve_ivp(rhs, (0, period), np.eye(2).ravel(), method="DOP853",
                           rtol=2e-12, atol=2e-13)
        assert result.success
        exact = -expm(poisson @ (diagonal+rate*np.eye(2))*period)
        defect = np.max(np.abs(exact-result.y[:, -1].reshape(2, 2)))
        assert defect < 2e-10
        omega_rate = sqrt((A+rate)*(C+rate))
        phase = pi*((A+C+rate)/(omega_rate+omega)-1)
        print(f"Ellipse rate {rate:.2f}: phase {phase:.9f}, return matrix error {defect:.2e}")
    print(f"Geometric connection integral: {angle:.10f}")


def torus_and_resonance():
    eps, x, y, psi = sp.symbols("eps x y psi", real=True)
    shift = eps*sp.cos(psi)
    a, b = x-shift, y+shift
    pulled = (a*a+b*b)/2 + eps*(a-b)*sp.cos(psi)
    assert sp.expand(pulled-((x*x+y*y)/2-shift**2)) == 0

    # Hamilton's equations in the lab for H = |I-eps*k*cos(psi)|^2/2.
    k = sp.Matrix([2, -1])
    I = sp.Matrix([x, y])
    J = I-eps*k*sp.cos(psi)
    H = J.dot(J)/2
    theta_velocity = sp.Matrix([H.diff(x), H.diff(y)])
    action_velocity = -k*H.diff(psi)
    discrepancy = action_velocity + eps*k*sp.sin(psi)*k.dot(theta_velocity)
    assert all(sp.expand(term) == 0 for term in discrepancy)

    # Resonant energy contours at psi=0, in units N=1.
    intersections = sorted(float(r) for r in sp.solve(3*x*(1-x)/2-sp.Rational(1, 8), x))
    assert np.allclose(intersections, [(1-sqrt(2/3))/2, (1+sqrt(2/3))/2])
    print("Resonant oscillator action fractions:", intersections)
    kinetic = (x+y-1)**2/2 + 2*eps*sp.cos(psi)
    along = eps*sp.sin(psi)*(kinetic.diff(x)+kinetic.diff(y)) + (x+y-1)*kinetic.diff(psi)
    assert sp.expand(along) == 0
    # At psi=pi the diagonal actions saturate the single-mode width.
    assert sp.expand(kinetic.subs({x:sp.Rational(3, 5), y:sp.Rational(3, 5),
                                  eps:sp.Rational(1, 200), psi:sp.pi})) == sp.Rational(1, 100)

    n = np.arange(256)
    h, s = 2*pi, 2*pi/sqrt(2)
    pooled = (np.cos(n*h).mean()+np.cos(n*s).mean())/2
    rectangular = np.cos(n[:, None]*h+n[None, :]*s).mean()
    assert abs(pooled-.5) < .005 and abs(rectangular) < .005
    print(f"First-angle cosine, two clocks: pooled {pooled:.7f}, combined {rectangular:.7f}")


def melnikov_and_polynomials():
    omega = 1.3
    strength = sqrt(2.)
    b = -strength*cosh(pi*omega/2)/4
    amplitude = 2*pi*omega**2/sinh(pi*omega/2)
    for phi in (0., pi/4, pi/2, pi):
        def integrand(t):
            phase = omega*t+phi
            return 4*tanh(t)/cosh(t)**2*(cos(phase)+b*cos(2*phase))
        observed = quad(integrand, -30., 30., epsabs=2e-12, epsrel=2e-12)[0]
        expected = -amplitude*sin(phi)*(1-strength*cos(phi))
        assert abs(observed-expected) < 2e-12
    print("Two-tone Melnikov integral agrees at four phases, including the extra root.")
    t = sp.symbols("t")
    for degree in range(2, 11):
        g = degree*(degree-1)
        coefficients = [0]*degree+[sp.Integer(1)]
        for j in range(degree-1, -1, -1):
            coefficients[j] = j*(j+1)*coefficients[j+1]/(j*(j-1)-g)
        p = sum(c*t**j for j, c in enumerate(coefficients))
        assert sp.expand(t*(t-1)*p.diff(t, 2)-g*p) == 0
        assert p.subs(t, 0) == p.subs(t, 1) == 0
    print("Exceptional normal equations: all monic polynomial identities pass in degrees 2 to 10.")


def course_exercises():
    jet = sp.symbols("u:9")
    a, b, c = sp.symbols("a b c")
    u, u1, u2, u3 = jet[:4]
    third = u3+6*u*u1
    fifth = jet[5]+a*u*u3+b*u1*u2+c*u*u*u1

    def derivative(polynomial):
        return sum(polynomial.diff(j)*dj for j, dj in zip(jet, jet[1:]))

    def vary(polynomial, velocity):
        result = 0
        for index, coord in enumerate(jet[:6]):
            result += polynomial.diff(coord)*velocity
            if index < 5:
                velocity = derivative(velocity)
        return result

    bracket = sp.Poly(vary(fifth, third)-vary(third, fifth), *jet)
    coefficients = [bracket.coeff_monomial(m) for m in [u1*jet[5], u3*u3, u*u2*u2]]
    inferred = sp.solve(coefficients, [a, b, c])
    assert inferred == {a:10, b:20, c:30} and bracket.as_expr().subs(inferred) == 0
    print("KdV commutator coefficient tests:", coefficients)

    def periodic_toda(_, z):
        q, p = z[:3], z[3:]
        bonds = np.exp(q-np.roll(q, -1))
        return np.r_[p, np.roll(bonds, 1)-bonds]

    initial = np.array([0., 0., 0., -1., 0., 2.])
    for step in (.02, .01, .005):
        def measured(sign):
            end = sign*step
            sol = solve_ivp(periodic_toda, (0., end), initial, method="DOP853",
                            rtol=2e-13, atol=2e-14)
            assert sol.success
            return periodic_toda(end, sol.y[:, -1])[3:]
        rates = (measured(1)-measured(-1))/(2*step)
        error = np.max(np.abs(rates-[4., 1., -5.]))
        assert error < 10*step**2
        print(f"Periodic Toda at step {step:g}: max force-derivative error {error:.3g}")


if __name__ == "__main__":
    rotating_ellipse()
    torus_and_resonance()
    melnikov_and_polynomials()
    course_exercises()
