"""Continue variational equations (orders 1–3) in Appendix B of
Morales-Ruiz, Ramis and Simó (2007), doi:10.1016/j.ansens.2007.09.002.
Run with Python 3, NumPy and SciPy. The two large loops enclose pi*i.
"""
import numpy as np
from scipy.integrate import solve_ivp


def transport(center, radius, tolerance, orientation=1):
    """Continue eta=dy/de, h=d2x/de2, v=d3y/de3 from e=y(0)."""
    # The chosen circle starts at t=0 when center = i*radius.
    def rhs(s, state):
        phase = np.exp(orientation * 2j * np.pi * s)
        t = center - 1j * radius * phase
        dt = orientation * 2 * np.pi * radius * phase
        x = 1.5 / np.cosh(t / 2)**2 - 1
        eta, eta_t, h, h_t, v, v_t = state
        return dt * np.array([
            eta_t, -(1 + x) * eta,
            h_t, -(1 + 2*x) * h - eta**2,
            v_t, -(1 + x) * v - 3*h*eta,
        ])

    initial = np.array([1, 0, 0, 0, 0, 0], dtype=complex)
    solution = solve_ivp(rhs, (0, 1), initial, method="DOP853",
                         rtol=tolerance, atol=tolerance * 1e-2, max_step=0.02)
    if not solution.success:
        raise RuntimeError(solution.message)
    return solution.y[:, -1]


if __name__ == "__main__":
    for radius, direction in [(np.pi, 1), (np.pi, -1), (np.pi/4, 1)]:
        expected = direction * 2j*np.pi*72/5 if radius == np.pi else 0j
        for tolerance in (1e-9, 3e-12):
            state = transport(1j*radius, radius, tolerance, direction)
            print(f"radius={radius:.6f} direction={direction:+} tol={tolerance:.0e} "
                  f"third displacement={state[4]:.10f} "
                  f"abs error={abs(state[4]-expected):.2e} "
                  f"third velocity={abs(state[5]):.2e}")
        if max(abs(state[4]-expected), abs(state[5])) > 2e-5:
            raise AssertionError("third-order monodromy check failed")
