"""Count axial turns from the physical spherical pendulum (NumPy and SciPy).

Dimensionless H = |p|²/2 + z, J = (q × p)_z. The positive loop is in
(H-1,J), and a positive axial turn is counterclockwise viewed from above.
"""
from math import pi, sin, sqrt

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


def turning_heights(energy, j):
    # The probe energies have an accessible equator and two simple turns.
    def polynomial(z):
        return 2 * (energy - z) * (1 - z*z) - j*j

    low = brentq(polynomial, -1, 0, xtol=5e-16)
    high = brentq(polynomial, 0, 1, xtol=5e-16)
    return low, high, energy - low - high


def rotation(energy, j):
    """Signed turns per nutation; substitute z=low+(high-low)sin²(u)."""
    low, high, third = turning_heights(energy, j)

    def integrand(u):
        z = low + (high - low) * sin(u)**2
        return 1 / ((1 - z*z) * sqrt(third - z))

    integral = quad(integrand, 0, pi/2, epsabs=2e-10, epsrel=1e-10)[0]
    return sqrt(2) * j * integral / pi


def cartesian_turn(energy, j):
    """Integrate the bob in space until its next maximum height."""
    low, _, _ = turning_heights(energy, j)
    radius = sqrt(1 - low*low)
    start = [radius, 0, low, 0, j/radius, 0]
    vertical = np.array([0., 0., 1.])

    def equation(t, state):
        q, p = state[:3], state[3:]
        return np.r_[p, -vertical + (q[2] - p @ p) * q]

    def upper_turn(t, state):
        return state[5]

    upper_turn.direction = -1
    upper_turn.terminal = True
    sol = solve_ivp(equation, (0, 20), start, events=upper_turn,
                    method="DOP853", rtol=3e-12, atol=1e-13, dense_output=True)
    assert sol.success and len(sol.t_events[0]) == 1
    path = sol.sol(np.linspace(0, sol.t_events[0][0], 601))
    azimuth = np.unwrap(np.arctan2(path[1], path[0]))
    return (azimuth[-1] - azimuth[0]) / pi


def transported_turns(count, direction=1):
    angles = pi/4 + direction * 2*pi * np.arange(count + 1)/count
    # Offset every angle slightly so J stays nonzero at all sampled tori.
    angles += .027
    raw = np.array([rotation(1 + .18*np.cos(u), .18*np.sin(u)) for u in angles])
    lifted = np.unwrap(2*pi*raw)/(2*pi)
    assert max(abs(np.diff(lifted))) < .1
    return raw[0], lifted[-1], lifted[-1] - lifted[0]


if __name__ == "__main__":
    for energy in (.82, 1.18):
        for j in (.02, .01, .005):
            print("H, J, turns:", energy, j, rotation(energy, j))
    for energy, j in ((1.1, .15), (.92, -.12)):
        quadrature = rotation(energy, j)
        direct = cartesian_turn(energy, j)
        print("H, J, turns (quadrature and trajectory):", energy, j, quadrature, direct)
        assert abs(quadrature - direct) < 1e-8
    for count in (48, 96):
        for direction in (1, -1):
            start, end, change = transported_turns(count, direction)
            print("Loop samples, orientation, first/returned turns, change:",
                  count, direction, start, end, change)
            assert abs(change + direction) < 1e-8
