"""Checks for the reduced periodic Toda action and the quantum spin-oscillator.

Run with Python 3, NumPy and SciPy. The Toda test uses dimensionless Hamiltonian
time. The quantum count uses the J=1 column at hbar=2/(n+1).
"""

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

import numpy as np
from scipy.integrate import quad, solve_ivp
from scipy.linalg import eigvalsh_tridiagonal
from scipy.special import ellipk


def toda_action(energy):
    a2 = (energy - 2) / 4
    integral, _ = quad(lambda t: cos(t) ** 2 / sqrt(1 + a2 * sin(t) ** 2),
                       0, pi / 2, epsabs=2e-13, epsrel=2e-13)
    return 8 * a2 * integral / pi


def check_toda():
    energy = 6
    period = 2 * ellipk(-(energy - 2) / 4)
    previous_error = None
    print(f"Toda action {toda_action(energy):.11f}, period {period:.11f}")
    for step in (0.08, 0.04, 0.02, 0.01):
        derivative = (toda_action(energy + step) - toda_action(energy - step)) / (2 * step)
        error = abs(2 * pi * derivative - period)
        print(f"  central difference h={step:.2f}: absolute period error {error:.3g}")
        if previous_error is not None:
            assert 3.9 < previous_error / error < 4.1
        previous_error = error

    def equations(t, state):
        r, p = state
        return (2 * p, -2 * sinh(r))

    def crossing(t, state):
        return state[0]

    crossing.direction = 1
    for tolerance in (1e-9, 1e-12):
        sol = solve_ivp(equations, (0, 4), (0, 2), method="DOP853",
                        atol=tolerance / 10, rtol=tolerance, events=crossing)
        assert sol.success and len(sol.t_events[0]) == 2
        crossing_error = abs(sol.t_events[0][1] - period)
        energy_error = max(abs(p * p + 2 * cosh(r) - energy) for r, p in sol.y.T)
        print(f"  rtol={tolerance:.0e}: crossing error {crossing_error:.3g}, "
              f"max energy residual at solver nodes {energy_error:.3g}")
        assert crossing_error < 20 * tolerance and energy_error < 100 * tolerance


def spin_column(n, offset):
    """H eigenvalues in the J = 1 + offset*hbar column at hbar = 2/(n+1)."""
    occupation = n + offset
    if occupation < 0:
        return np.array([])
    dimension = min(n, occupation) + 1
    k = np.arange(dimension - 1, dtype=float)
    links = np.sqrt((occupation-k)*(k+1)*(n-k)) / (n+1)**1.5
    return eigvalsh_tridiagonal(np.zeros(dimension), links)


def check_spin_height():
    for n in (3, 4, 8, 16, 32):
        hbar = 2 / (n + 1)
        eigenvalues = spin_column(n, 0)
        threshold = 64 * np.finfo(float).eps * max(1, max(abs(eigenvalues)))
        count = np.count_nonzero(eigenvalues < -threshold)
        assert count == (n + 1) // 2
        assert max(abs(eigenvalues + eigenvalues[::-1])) < threshold
        print(f"Spin n={n:2d}: {count} negative eigenvalues, height {hbar * count:.10f}")


def check_shrinking_strip():
    for scale in (2, 4, 8, 16, 32):
        n = 2 * scale**3 - 1
        half_span = scale**2
        count = 0
        for offset in range(-half_span, half_span + 1):
            occupation = n + offset
            dimension = min(n, occupation) + 1
            nonpositive = (dimension + 1) // 2
            if scale <= 4:
                levels = spin_column(n, offset)
                atol = 64 * np.finfo(float).eps * max(1, max(abs(levels)))
                assert np.count_nonzero(levels <= atol) == nonpositive
            count += nonpositive
        expected = (2 * half_span + 1) * scale**3 - half_span**2 // 4
        assert count == expected
        print(f"Strip hbar=1/{scale**3}, {2*half_span+1} columns, "
              f"{count} nonpositive levels, height {count/(2*scale**5):.9f}")


def check_focus_trajectory():
    # Order (x, y, z, u, v), integrated from a regular point at the south pole.
    def rhs(t, state):
        x, y, z, u, v = state
        return (-z*v/2, z*u/2, (x*v-y*u)/2, y/2, -x/2)

    t = np.linspace(0, 9, 91)
    solution = solve_ivp(rhs, (0, t[-1]), (0, 0, -1, 2, 0), t_eval=t,
                         method="DOP853", rtol=1e-12, atol=1e-14)
    assert solution.success
    sech = 1 / np.cosh(t/2)
    expected = np.array((np.zeros_like(t), -2*sech*np.tanh(t/2), 1-2*sech**2,
                         2*sech, np.zeros_like(t)))
    error = np.max(abs(solution.y-expected))
    assert error < 2e-10
    print(f"Spin focus orbit: sampled maximum component error {error:.3g}")


if __name__ == "__main__":
    check_toda()
    check_spin_height()
    check_shrinking_strip()
    check_focus_trajectory()
