"""Reproduce six local reconstruction tests. Requires Python 3, NumPy and SciPy."""

from fractions import Fraction as Fr
from math import atan, atan2, cos, pi, sin, sqrt, tan

import numpy as np
from scipy.integrate import quad


def kepler_apses():
    # V_eff(r) = ell²/(2r²) - 1/r. At p_r=0 solve the quadratic for r.
    ell_squared = 3 / 4

    def radii(energy):
        e = sqrt(1 + 2 * energy * ell_squared)
        return np.array([ell_squared / (1 + e), ell_squared / (1 - e)])

    energy = -0.5
    for h in (1e-4, 1e-5, 1e-6):
        inverse_slopes = (radii(energy + h) - radii(energy - h)) / (2 * h)
        error = max(abs(inverse_slopes - np.array([-0.5, 4.5])))
        print(f"Kepler dr/dE at both apses, h={h:g}, max error {error:.3g}")
    assert error < 1e-9


def crossing_angle():
    eta = pi / 6
    for delta in (0.2, 0.05, 0.01):
        lo, hi = pi / 2 - eta, pi / 2 + eta
        advance = quad(lambda t: delta / (cos(t)**2 + (delta * sin(t))**2),
                       lo, hi, epsabs=2e-12, points=[pi / 2])[0]
        angles = [atan2(delta * sin(t), cos(t)) for t in (lo, hi)]
        exact = pi - 2 * atan(delta / tan(eta))
        assert max(abs(advance - exact), abs(advance - (angles[1] - angles[0]))) < 5e-12
        print(f"Oscillator delta={delta:.2f}, advance {advance:.10f} rad")


def stackel_minor():
    # Differentiate the inverted Hamiltonians numerically with complex steps.
    def integrals(x, py):
        f, g = 2 + x*x, 2
        hx, hy = x**4 / 4, (py*py + 1) / 2
        return np.linalg.solve([[f, 1], [g, -1]], [hx, hy])

    step = 1e-20
    for x, expected in [(0, 0), (1, -0.1)]:
        jac = np.column_stack([integrals(x + 1j*step, 1).imag / step,
                               integrals(x, 1 + 1j*step).imag / step])
        jac_det = np.linalg.det(jac)
        assert np.allclose(integrals(x, 1), [0.25, -0.5])
        assert abs(jac_det - expected) < 1e-14
        print(f"Stäckel x={x}, (x,p_y) minor {jac_det:g}")


def ellipsoid_line():
    # Intersect (1, t/sqrt(2), t/sqrt(2)) with the confocal quadric.
    c = Fr(13, 2)
    constant = 1 / (1 - c) - 1
    quadratic = Fr(1, 2) / (4 - c) + Fr(1, 2) / (9 - c)
    assert constant == Fr(-13, 11) and quadratic == 0
    print(f"Confocal ellipsoid line: constant {constant}, quadratic {quadratic}")


def lax_turn():
    # At P=0, differentiate u(theta) twice using the angular Hamiltonian.
    theta = pi / 6
    u = 4 * cos(theta)**2 + sin(theta)**2
    force = -3 * sin(theta) * cos(theta)
    acceleration = -6 * sin(theta) * cos(theta) * force
    assert abs(u - 13/4) < 2e-15 and abs(acceleration - 27/8) < 2e-15
    for displacement in (1e-4, 1e-6, 1e-8):
        lam = u + displacement
        b = cos(theta)**2 / (lam - 1) + sin(theta)**2 / (lam - 4)
        mu = sqrt(-b)
        assert abs(mu * (mu / b) + 1) < 3e-16
    print(f"Neumann turning point: u={u:g}, d²u/dt²={acceleration:g}, pole residue −1")


def billiard_return():
    point = np.array([2.0, 0.0])
    direction = np.array([-2.0, 1.0]) / sqrt(5)
    initial_direction = direction.copy()
    axes_squared = np.array([4.0, 1.0])
    distance = 0.0
    for _ in range(4):
        flight = -2 * (point @ (direction / axes_squared)) / (direction @ (direction / axes_squared))
        assert flight > 0
        point += flight * direction
        distance += flight
        normal = point / axes_squared
        assert abs(4 * (direction @ normal)**2 - 0.8) < 5e-14
        direction -= 2 * (direction @ normal) * normal / (normal @ normal)
    assert np.linalg.norm(point - [2, 0]) < 5e-14
    assert np.linalg.norm(direction - initial_direction) < 5e-14
    assert abs(distance - 4 * sqrt(5)) < 5e-14
    print(f"Four specular impacts: total unit-speed flight time {distance:.10f}")


if __name__ == "__main__":
    kepler_apses()
    crossing_angle()
    stackel_minor()
    ellipsoid_line()
    lax_turn()
    billiard_return()
