"""Two repulsive elliptic Calogero–Moser particles on the real period circle.

Python 3, NumPy, and SciPy. Time is in the units of the Hamiltonian in the
model article. SciPy's elliptic-function argument m is the squared modulus.
"""

import numpy as np
from scipy.integrate import quad, solve_ivp
from scipy.special import ellipj, ellipk, ellipkinc


def regular_period(energy, coupling, e1, e2, e3):
    """Complete excursion using W = ℘(r); the integrand stays regular at both ends."""
    a = energy / coupling**2

    def integrand(theta):
        shift = a*np.sin(theta)**2
        return 2 / (coupling*np.sqrt((e1-e2+shift)*(e1-e3+shift)))

    return quad(integrand, 0, np.pi/2, epsabs=1e-13, epsrel=1e-13)[0]


def lemniscatic_flow(time, state):
    """Canonical equations for g2=4, g3=0, γ=1."""
    root_two = np.sqrt(2)
    r, p = state
    sn, cn, dn, _ = ellipj(root_two*r, 0.5)
    return 2*p, 4*root_two*cn*dn/sn**3


def orbit(energy, relative_tolerance):
    """Independent time evolution in the original separation."""
    half_period = ellipk(0.5)/np.sqrt(2)

    def crossing(time, state):
        return state[0] - half_period

    crossing.direction = 1
    solution = solve_ivp(lemniscatic_flow, (0, 4.6), (half_period, np.sqrt(energy)),
                         method="DOP853", rtol=relative_tolerance,
                         atol=relative_tolerance/10, events=crossing)
    if not solution.success or len(solution.t_events[0]) < 2:
        raise RuntimeError(solution.message)
    positions, momenta = solution.y
    sn = ellipj(np.sqrt(2)*positions, 0.5)[0]
    drift = np.max(np.abs(momenta**2 + 2/sn**2 - 2 - energy))
    return solution.t_events[0][1], drift


if __name__ == "__main__":
    half_period = ellipk(0.5) / np.sqrt(2)
    inner = ellipkinc(np.arcsin(np.sqrt(2/3)), 0.5) / np.sqrt(2)
    print("half period of lattice, turning positions:", half_period, inner, 2*half_period-inner)
    for energy in (0, 0.001, 0.1, 1, 4):
        print("energy, complete oscillation period:", energy, regular_period(energy, 1, 1, 0, -1))
    assert abs(regular_period(0, 1, 1, 0, -1)-2*np.pi/np.sqrt(8)) < 2e-14
    for tolerance in (1e-9, 1e-12):
        period, drift = orbit(1, tolerance)
        print("ODE rtol, complete period, largest sampled energy error:", tolerance, period, drift)
        assert abs(period-regular_period(1, 1, 1, 0, -1)) < 30*tolerance
