"""Examples of measured frequencies, reduction and reconstruction.

Run with Python 3, NumPy and SciPy. The variables use the dimensionless
normalizations of the linked articles. No input data files are required.
"""
from fractions import Fraction
from math import acos, cos, cosh, log, pi, sin, sinh, sqrt

import numpy as np
from scipy.integrate import quad, solve_ivp


def nutation():
    s = 0.5
    j = (1 - s*s) / sqrt(s)
    theta0 = acos(-s)
    target = 2*pi*sqrt(s/(1 + 3*s*s))

    def rhs(t, state):
        theta, momentum = state
        return momentum, sin(theta) + j*j*cos(theta)/sin(theta)**3

    def maximum(t, state):
        return state[1]

    maximum.direction = -1
    errors = []
    for shift in (0.02, 0.01, 0.005):
        sol = solve_ivp(rhs, (0, 12), (theta0 + shift, 0), events=maximum,
                        method="DOP853", rtol=2e-12, atol=2e-14, max_step=0.15)
        assert sol.success
        period = np.diff(sol.t_events[0]).mean()
        errors.append(abs(period - target))
        print("Polar displacement, measured period:", shift, period)
    assert errors[0] > 3*errors[1] > 9*errors[2] and errors[-1] < 2e-5
    print("Linearized period:", target)


def reduced_geometry():
    for j in (-0.1, 0.025):
        angle = quad(lambda t: j/(t*t + j*j), -np.inf, np.inf)[0]
        assert np.isclose(angle, np.sign(j)*pi)
        # Orbit representation gives x p_y - y p_x = j at every sampled time.
        t = np.linspace(-2, 2, 401)
        np.testing.assert_allclose((t*t + j*j) - t*t, j*j, atol=1e-15)
    winding_flux = 2*pi*quad(lambda chi: sin(chi)/2, 0, pi)[0]
    assert np.isclose(winding_flux, 2*pi)
    print("Curvature flux in full turns:", winding_flux/(2*pi))

    # At transverse energy -1/8 both wells of V=-q^2/2+q^4/4 have an oval.
    turns = sorted(np.roots([0.25, 0., -0.5, 0., 0.125]))
    assert len(turns) == 4 and turns[1] < 0 < turns[2]
    print("Four turning positions:", np.round(turns, 7))

    cut = Fraction(1, 4)
    corners = [(cut, 0), (1, 0), (0, 1), (0, cut)]
    cross = lambda a, b: a[0]*b[1] - a[1]*b[0]
    area = sum(cross(corners[i-1], c) for i, c in enumerate(corners))/2
    assert area == Fraction(15, 32)
    for basis in (((1, 0), (-1, 1)), ((0, 1), (1, -1))):
        assert abs(cross(*basis)) == 1
    print("Retained polygon area:", area, "removed fraction:", 1 - 2*area)


def caustic_contact():
    table = np.array([4., 1.])
    x = np.array([0., 1.])
    for d, expected in ((0.25, 32/19), (0.75, 96/43)):
        v = np.array([sqrt(1-d*d), -d])
        c = 4*d*d
        hit = -2*(x/table @ v)/(v/table @ v)
        tangent = -(x/(table-c) @ v)/(v/(table-c) @ v)
        y = x + tangent*v
        assert abs(hit-expected) < 2e-15 and abs(tangent-4*d) < 2e-15
        assert abs(y/(table-c) @ y - 1) < 2e-15
        assert abs(y/(table-c) @ v) < 2e-15
        print("Billiard launch, wall time, tangent time:", d, hit, tangent)
    axes = np.array([1., 4., 9.])
    x = np.array([1., 0., 0.])
    for alpha in (pi/6, pi/4, pi/3):
        v = np.array([0., cos(alpha), sin(alpha)])
        c = 9*v[1]**2 + 4*v[2]**2
        assert abs(v/(axes-c) @ v) < 2e-15 and x/(axes-c) @ v == 0
        assert abs(x/(axes-c) @ x - 1 - c/(1-c)) < 2e-15
        if alpha == pi/4:
            assert abs(c/(1-c) + 13/11) < 1e-15


def kepler():
    def rhs(t, state):
        x, y, vx, vy = state
        inverse_cube = (x*x + y*y)**(-1.5)
        return vx, vy, -x*inverse_cube, -y*inverse_cube

    def minor_axis(t, state):
        return state[0] + 1

    minor_axis.terminal = True
    sol = solve_ivp(rhs, (0, 10), (1, 0, 0, sqrt(1.5)), events=minor_axis,
                    method="DOP853", rtol=1e-12, atol=1e-14)
    assert sol.success and len(sol.t_events[0]) == 1
    time = sol.t_events[0][0]
    pos = sol.y_events[0][0, :2]
    assert abs(time - sqrt(2)*(pi-1)) < 2e-11
    np.testing.assert_allclose(pos, [-1, sqrt(3)], atol=2e-11, rtol=0)
    print("Kepler minor-axis arrival:", time, pos)


def neumann():
    coefficients = np.array([3., 3., 1.])

    def rhs(t, state):
        q, p = state[:3], state[3:]
        aq = coefficients*q
        return np.r_[p, -aq + (q @ aq - p @ p)*q]

    for omega, expected in ((1., cosh(1.)), (2., cos(sqrt(2)))):
        errors = []
        for dz in (0.01, 0.005, 0.0025):
            initial = [sqrt(1-dz*dz), 0., dz, 0., omega, 0.]
            sol = solve_ivp(rhs, (0, 1), initial, method="DOP853",
                            rtol=1e-12, atol=1e-14)
            assert sol.success
            q, p = sol.y[:3, -1], sol.y[3:, -1]
            assert abs(q @ p) < 1e-11 and abs(q @ q - 1) < 1e-11
            errors.append(abs(q[2]/dz - expected))
        assert errors[0] > 3*errors[1] > 9*errors[2]
        print("Equatorial speed, linear z(1)/z(0), errors:", omega, expected, errors)


def moving_pair():
    # Evolve the original two particles, then form the midpoint.
    def rhs(t, state):
        q1, q2, p1, p2 = state
        r = q1 - q2
        f = sqrt(1 + 1/r**2)
        force = (cosh(p1) + cosh(p2))/(f*r**3)
        return f*sinh(p1), f*sinh(p2), force, -force

    sol = solve_ivp(rhs, (0, 2), (0.5, -0.5, log(2), log(2)), method="DOP853",
                    t_eval=np.linspace(0, 2, 101), rtol=1e-12, atol=1e-14)
    assert sol.success
    midpoint = (sol.y[0] + sol.y[1])/2
    error = max(abs(midpoint - 3*sqrt(2)*sol.t/4))
    assert error < 2e-11
    print("Moving-pair maximum midpoint error, eta=g=1:", error)


if __name__ == "__main__":
    nutation()
    reduced_geometry()
    caustic_contact()
    kepler()
    neumann()
    moving_pair()
