"""Quadratures and body-frame orbit checks for the Euler and Lagrange tops.

Run with Python 3, NumPy and SciPy. Angles are radians; the examples use the
dimensionless inertia, momentum and gravity scales specified in each article.
"""

from math import pi, sin, sqrt

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


def cross_matrix(v):
    a, b, c = v
    return np.array([[0, -c, b], [c, 0, -a], [-b, a, 0]])


def euler_separatrix():
    t = np.linspace(-6, 6, 41)
    rate = 1/sqrt(2)
    u, v = np.tanh(rate*t), 1/np.cosh(rate*t)
    m = 6*np.column_stack((v/sqrt(3), u, sqrt(2/3)*v))
    derivative = 6*rate*np.column_stack((-v*u/sqrt(3), v*v, -sqrt(2/3)*v*u))
    np.testing.assert_allclose(np.cross(m, m / [2, 3, 4]), derivative, atol=1e-14)
    np.testing.assert_allclose(np.sum(m*m / [2, 3, 4], axis=1)/2, 6, atol=1e-14)


def euler_return(tol):
    # z=M3, z=sqrt(2)*sin(u) removes both square-root endpoints.
    period = 12*quad(lambda u: 1/sqrt(4 + 2*sin(u)**2), 0, pi/2)[0]
    m0 = np.array([2/sqrt(3), -sqrt(8/3), 0])

    def rhs(t, state):
        m, attitude = state[:3], state[3:].reshape(3, 3)
        omega = m / [1, 2, 3]
        return np.r_[np.cross(m, omega), (attitude @ cross_matrix(omega)).ravel()]

    times = np.linspace(0, period, 101)
    motion = solve_ivp(rhs, (0, period), np.r_[m0, np.eye(3).ravel()], t_eval=times,
                       method="DOP853", rtol=tol, atol=tol/100)
    assert motion.success
    momentum = motion.y[:3].T
    attitudes = motion.y[3:].T.reshape(-1, 3, 3)
    space_momentum = (attitudes @ momentum[..., None])[..., 0]
    assert np.max(np.abs(space_momentum - m0)) < 10*tol
    assert np.linalg.norm(momentum[-1] - m0) < tol
    rot = attitudes[-1]
    skew = (rot-rot.T)/2
    sine = np.dot(m0/2, [skew[2, 1], skew[0, 2], skew[1, 0]])
    angle = np.arctan2(sine, (np.trace(rot)-1)/2)
    return period, angle


def lagrange_nutation(tol):
    lower, outer = (1-sqrt(17))/4, (1+sqrt(17))/4

    def integrand(u, precession=False):
        z = lower*(1-sin(u)**2)
        time_density = 4/sqrt(2*(outer-z))
        return time_density*(-z)/(1-z*z) if precession else time_density

    period = quad(integrand, 0, pi/2)[0]
    angle = quad(integrand, 0, pi/2, args=(True,))[0]

    def rhs(t, state):
        m, vertical = state[:3], state[3:6]
        omega = m / [1, 1, .5]
        z = vertical[2]
        return np.r_[np.cross(m, omega) + np.cross(vertical, [0, 0, 1]),
                     np.cross(vertical, omega), -z/(1-z*z)]

    motion = solve_ivp(rhs, (0, period), [0, 0, 1, 1, 0, 0, 0],
                       t_eval=[0, period/2, period], method="DOP853", rtol=tol, atol=tol/100)
    assert motion.success
    np.testing.assert_allclose(motion.y[5], [0, lower, 0], atol=tol, rtol=0)
    assert abs(motion.y[6, -1]-angle) < tol
    return period, angle


if __name__ == "__main__":
    euler_separatrix()
    for tol in (1e-9, 1e-12):
        T, rotation = euler_return(tol)
        print(f"Euler body period {T:.10f}, attitude angle {rotation:+.10f} (rtol {tol:g})")
        T, azimuth = lagrange_nutation(tol)
        print(f"Lagrange nutation period {T:.10f}, azimuth {azimuth:+.10f} (rtol {tol:g})")
