"""Checks for the Library article "Integrable particle chains and their scattering".

Open Toda chain in the convention of the classical Toda model record (unit masses):
    H = sum p_i^2 / 2 + sum_{i<N} exp(q_i - q_{i+1}),  L = tridiag(a_i; p_i; a_i), a_i = exp((q_i - q_{i+1})/2).
Particles start ordered q_1 < ... < q_N with incoming velocities alpha_1 > ... > alpha_N. Long after the
collisions particle k carries alpha_{N+1-k}. A velocity label alpha_m moves from the incoming line
q = alpha_m t + beta_m^- of particle m to the outgoing line of particle N+1-m, a displacement
Delta(alpha_m) = beta_{N+1-m}^+ - beta_m^-.

1. Two bodies (exact): the faster label moves back by 2 log(v) and the slower forward by 2 log(v),
   v = relative velocity.
2. N bodies (Moser): the outgoing velocities are the incoming ones, they equal the eigenvalues of L,
   and each displacement is the sum of the two-body displacements with every other label.
3. Rational Calogero-Moser, H = sum p^2/2 + sum_{i<j} g^2/(q_i - q_j)^2: velocities are preserved and every
   displacement vanishes.
Control: the equal-mass chain with V(r) = exp(r) + exp(2r)/2 between neighbours is not integrable; its
outgoing velocities differ from the incoming ones in three-body collisions.
Run with Python 3, NumPy and SciPy:  python3 particle_scattering.py
"""
import numpy as np
from scipy.integrate import solve_ivp

TOL = dict(method='DOP853', rtol=1e-13, atol=1e-13)


def toda_force(q, extra=0.0):
    """Forces of the nearest-neighbour potential V(r) = e^r + extra e^{2r} / 2, r = q_i - q_{i+1}."""
    r = q[:-1] - q[1:]
    dv = np.exp(r) + extra * np.exp(2 * r)
    f = np.zeros_like(q)
    f[:-1] -= dv
    f[1:] += dv
    return f


def cm_force(q, g=1.0):
    """Forces of the rational Calogero-Moser potential sum g^2 / (q_i - q_j)^2."""
    d = q[:, None] - q[None, :]
    np.fill_diagonal(d, np.inf)
    return np.sum(2 * g * g / d ** 3, axis=1)


def evolve(q0, p0, t_end, force):
    n = len(q0)
    rhs = lambda t, y: np.concatenate([y[n:], force(y[:n])])
    sol = solve_ivp(rhs, (0, t_end), np.concatenate([q0, p0]), **TOL)
    return sol.y[:n, -1], sol.y[n:, -1]


def asymptotes(q0, p0, force, T=90.0):
    """Incoming (t -> -T) and outgoing (t -> +T) velocities and intercepts of every particle."""
    q_in, p_in = evolve(q0, -p0, T, force)          # time reversal: run the reversed velocities forward
    p_in = -p_in
    q_out, p_out = evolve(q0, p0, T, force)
    beta_in = q_in + p_in * T                         # q(-T) = alpha (-T) + beta
    beta_out = q_out - p_out * T
    return p_in, beta_in, p_out, beta_out


def lax_eigenvalues(q, p):
    a = np.exp((q[:-1] - q[1:]) / 2)
    L = np.diag(p) + np.diag(a, 1) + np.diag(a, -1)
    return np.sort(np.linalg.eigvalsh(L))[::-1]


def pairwise_prediction(alpha):
    """Moser's sum of two-body displacements for each incoming label alpha_m (ordered decreasing)."""
    out = np.zeros(len(alpha))
    for m, a in enumerate(alpha):
        for b in alpha:
            if b > a:
                out[m] += 2 * np.log(b - a)
            elif b < a:
                out[m] -= 2 * np.log(a - b)
    return out


def measured_displacements(p_in, beta_in, beta_out):
    n = len(p_in)
    return np.array([beta_out[n - 1 - m] - beta_in[m] for m in range(n)])


def colliding_state(rng, n, spread=4.0):
    """A configuration at t = 0 in the middle of a multi-particle collision."""
    q = np.sort(rng.normal(0, 0.6, n))
    p = rng.normal(0, 1.0, n)
    return q, p


def main():
    rng = np.random.default_rng(1975)
    checks, controls = {}, {}

    # 1. Two bodies: the exact displacement 2 log v.
    q0, p0 = np.array([-0.3, 0.4]), np.array([1.1, -0.7])
    p_in, b_in, p_out, b_out = asymptotes(q0, p0, toda_force)
    v = p_in[0] - p_in[1]
    d = measured_displacements(p_in, b_in, b_out)
    print(f'two bodies: v = {v:.10f}; displacements {d[0]:+.10f}, {d[1]:+.10f}; 2 log v = {2 * np.log(v):.10f}')
    checks['two-body displacements are -2 log v and +2 log v'] = abs(d[0] + 2 * np.log(v)) < 1e-9 and abs(d[1] - 2 * np.log(v)) < 1e-9

    # 2. Many bodies: velocities preserved, eigenvalues of L, pairwise sum of displacements.
    worst_vel = worst_eig = worst_shift = 0.0
    example = None
    kept = 0
    for n, trials in ((3, 60), (4, 60), (5, 30)):
        for _ in range(trials):
            q0, p0 = colliding_state(rng, n)
            p_in, b_in, p_out, b_out = asymptotes(q0, p0, toda_force)
            gaps = -np.diff(p_in)
            if np.any(gaps < 0.25):
                continue                                # keep fully colliding states with separated velocities
            T = min(2000.0, 40.0 / gaps.min())          # long enough that exp(-gap T) is negligible
            p_in, b_in, p_out, b_out = asymptotes(q0, p0, toda_force, T=T)
            kept += 1
            worst_vel = max(worst_vel, np.max(np.abs(np.sort(p_out) - np.sort(p_in))))
            worst_eig = max(worst_eig, np.max(np.abs(lax_eigenvalues(q0, p0) - np.sort(p_in)[::-1])))
            meas, pred = measured_displacements(p_in, b_in, b_out), pairwise_prediction(p_in)
            worst_shift = max(worst_shift, np.max(np.abs(meas - pred)))
            if n == 3 and example is None:
                example = (q0, p0, p_in, meas, pred)
    q0, p0, p_in, meas, pred = example
    print('three-body example: q(0) =', np.round(q0, 6), 'p(0) =', np.round(p0, 6))
    print('   incoming velocities', np.round(p_in, 10))
    print('   measured displacements', np.round(meas, 10), 'pairwise sums', np.round(pred, 10))
    print(f'largest deviations over {kept} experiments with N = 3, 4, 5: velocity set {worst_vel:.1e}, eigenvalues of L {worst_eig:.1e}, '
          f'displacement against the pairwise sum {worst_shift:.1e}')
    checks['outgoing velocities equal the incoming ones (1e-9)'] = worst_vel < 1e-9
    checks['asymptotic velocities are the eigenvalues of L (1e-9)'] = worst_eig < 1e-9
    checks['displacements are sums of two-body displacements (1e-8)'] = worst_shift < 1e-8

    # 3. Rational Calogero-Moser: no displacement.
    worst_cm_vel = worst_cm = worst_cm_raw = 0.0
    cm_trials = 0
    while cm_trials < 30:
        q0 = np.sort(rng.normal(0, 1.5, 3)) + np.array([-1.0, 0.0, 1.0])
        p0 = rng.normal(0, 1.0, 3)
        p_in, _, _, _ = asymptotes(q0, p0, cm_force, T=200.0)
        if np.any(-np.diff(p_in) < 0.5):
            continue
        cm_trials += 1
        # The 1/r^2 tail bends each trajectory by O(1/T); extrapolate the intercepts from T and 2T.
        p_in, b1_in, p_out, b1_out = asymptotes(q0, p0, cm_force, T=2000.0)
        _, b2_in, _, b2_out = asymptotes(q0, p0, cm_force, T=4000.0)
        raw = measured_displacements(p_in, b2_in, b2_out)
        extrap = 2 * raw - measured_displacements(p_in, b1_in, b1_out)
        worst_cm_vel = max(worst_cm_vel, np.max(np.abs(np.sort(p_out) - np.sort(p_in))))
        worst_cm_raw = max(worst_cm_raw, np.max(np.abs(raw)))
        worst_cm = max(worst_cm, np.max(np.abs(extrap)))
    print(f'rational Calogero-Moser, {cm_trials} three-body experiments: velocity set {worst_cm_vel:.1e}; largest displacement '
          f'{worst_cm_raw:.1e} read at T = 4000 and {worst_cm:.1e} after extrapolating in 1/T')
    checks['Calogero-Moser preserves velocities and has no displacement (1e-4 after extrapolation)'] = worst_cm_vel < 1e-6 and worst_cm < 1e-4

    # Control: a non-integrable nearest-neighbour potential changes the velocity set in three-body collisions.
    defect = 0.0
    for _ in range(40):
        q0, p0 = colliding_state(rng, 3)
        p_in, _, p_out, _ = asymptotes(q0, p0, lambda q: toda_force(q, extra=1.0), T=60.0)
        defect = max(defect, np.max(np.abs(np.sort(p_out) - np.sort(p_in))))
    print(f'potential e^r + e^(2r)/2: largest change of the velocity set over 40 three-body collisions {defect:.3f}')
    controls['a non-integrable potential changes the velocity set (above 0.01)'] = defect > 0.01

    for name, ok in checks.items():
        print(f"{'PASS' if ok else 'FAIL'}  {name}")
    for name, ok in controls.items():
        print(f"{'PASS' if ok else 'FAIL'}  control: {name}")
    if not all(checks.values()) or not all(controls.values()):
        raise SystemExit(1)
    print('Toda scattering factorizes into two-body displacements; Calogero-Moser scattering is free; the control diffracts.')


if __name__ == '__main__':
    main()
