"""Independent adaptive reference for the first FPUT alpha-chain energy return.

Run: python3 fput_reference.py  (NumPy and SciPy required)
Dimensionless unit masses and springs, 32 intervals and 31 evolving
coordinates. The endpoints q[0] and q[32] are fixed at zero. The two
integrations may take a minute and store dense output until t=11000.
"""
import numpy as np
from scipy.integrate import solve_ivp
from scipy.optimize import minimize_scalar


def first_mode_return(max_step, rtol):
    interior = np.arange(1, 32)
    first_mode = np.sin(np.pi * interior / 32) / 4
    frequency = 2 * np.sin(np.pi / 64)
    alpha = 0.25

    def flow(time, state):
        position, momentum = state[:31], state[31:]
        full = np.r_[0., position, 0.]
        laplacian = full[:-2] - 2 * position + full[2:]
        # Difference of neighboring strains squared, factored as (a-b)(a+b).
        force = laplacian * (1 + alpha * (full[2:] - full[:-2]))
        return np.r_[momentum, force]

    initial = np.r_[4 * first_mode, np.zeros(31)]
    trajectory = solve_ivp(flow, (0, 11000), initial, method="DOP853",
                           dense_output=True, max_step=max_step,
                           rtol=rtol, atol=rtol / 100)
    if not trajectory.success:
        raise RuntimeError(trajectory.message)

    def energy_fraction(time):
        state = trajectory.sol(time)
        q1, p1 = first_mode @ state[:31], first_mode @ state[31:]
        return (p1**2 + (frequency * q1)**2) / (4 * frequency)**2

    # Find the largest return in the published comparison window. On this
    # data the maximum lies in the interior; refine just its local bracket.
    grid = np.arange(7500., 11000.1, 0.25)
    peak = grid[np.argmax(energy_fraction(grid))]
    optimum = minimize_scalar(lambda time: -energy_fraction(time),
                              bounds=(peak - 0.5, peak + 0.5), method="bounded")
    assert optimum.success and peak > grid[0] and peak < grid[-1]
    # Use both canonical quadratures of every mode, normalized to the
    # initial harmonic-energy radius. The linear first-mode orbit is a circle.
    basis = np.sin(np.pi * np.outer(interior, interior) / 32) / 4
    frequencies = 2 * np.sin(np.pi * interior / 64)
    state = trajectory.sol(optimum.x)
    coordinates = (frequencies * (basis @ state[:31]) + 1j * (basis @ state[31:])) / (4 * frequency)
    prepared = np.zeros(31)
    prepared[0] = 1
    same_phase = coordinates[0] / abs(coordinates[0])
    literal_distance = np.linalg.norm(coordinates - prepared)
    orbit_distance = np.linalg.norm(coordinates - same_phase * prepared)
    np.testing.assert_allclose(abs(coordinates[0])**2, -optimum.fun, atol=2e-14)
    np.testing.assert_allclose(orbit_distance**2,
        (1 - abs(coordinates[0]))**2 + np.vdot(coordinates[1:], coordinates[1:]).real)
    coarse = np.arange(7500., 11000.1, 2.)
    coarse_fraction = energy_fraction(coarse)
    coarse_index = np.argmax(coarse_fraction)
    prior = np.arange(0., optimum.x, 0.5)
    print(f"max step {max_step}, relative/absolute tolerances {rtol:g}/{rtol/100:g}")
    print(f"  refined maximum: t={optimum.x:.6f}, E1/E1(0)={-optimum.fun:.10f}")
    print(f"  sampled every 2: t={coarse[coarse_index]:g}, "
          f"E1/E1(0)={coarse_fraction[coarse_index]:.10f}")
    print(f"  minimum sampled every 0.5 before return: {energy_fraction(prior).min():.9f}")
    print(f"  normalized first-mode quadratures: {coordinates[0].real:.7f}, {coordinates[0].imag:.7f}")
    print(f"  full-state distance / distance to linear orbit: {literal_distance:.7f} / {orbit_distance:.7f}")


if __name__ == "__main__":
    first_mode_return(0.7, 1e-9)
    first_mode_return(0.45, 1e-11)
