"""Open three-particle Toda with a centre-of-mass invariant perturbation.

Run with Python 3, NumPy and SciPy. Times and positions are dimensionless.
The reported maxima use a common sample grid on [0,4].
"""
import numpy as np
from scipy.integrate import solve_ivp


def force(q, strength):
    left, right = np.exp(q[:-1] - q[1:])
    separation = q[0] - q[2]
    return np.array([-left - strength * separation, left - right,
                     right + strength * separation])


def observables(state, strength):
    q, p = state[:3], state[3:]
    a, b = np.exp((q[:-1] - q[1:]) / 2)
    lax = np.diag(p) + np.diag([a, b], 1) + np.diag([a, b], -1)
    energy = np.trace(lax @ lax) / 2 + strength * (q[0] - q[2])**2 / 2
    return np.array([energy, np.trace(lax @ lax @ lax) / 3, p.sum()])


def experiment(strength, step):
    initial = np.array([.2, -.3, .1, .7, -.4, .2])
    q, p = initial[:3].copy(), initial[3:].copy()
    grid = np.linspace(0, 4, 101)
    per_sample = round(.04 / step)
    if per_sample < 1 or not np.isclose(per_sample * step, .04):
        raise ValueError("step must divide the sampling interval 0.04")
    states = [initial]
    for _ in grid[1:]:
        for _ in range(per_sample):
            p += step * force(q, strength) / 2
            q += step * p
            p += step * force(q, strength) / 2
        states.append(np.r_[q, p])
    def rhs(_t, state):
        return np.r_[state[3:], force(state[:3], strength)]
    ref = solve_ivp(rhs, (0, 4), initial, method="DOP853", t_eval=grid,
                    rtol=2e-13, atol=2e-15)
    if not ref.success:
        raise RuntimeError(ref.message)
    vals = np.array([observables(x, strength) for x in states])
    other = np.array([observables(x, strength) for x in ref.y.T])
    return (*np.max(abs(vals - vals[0]), axis=0),
            np.max(abs(vals[:, 1] - other[:, 1])),
            np.max(abs(other[:, 1] - other[0, 1])))


if __name__ == "__main__":
    print("strength step max_energy_drift max_I3_drift max_momentum_drift "
          "max_I3_difference reference_I3_drift")
    for strength in (0, .01, .02):
        for step in (.02, .01, .005):
            print(strength, step, *("%.9g" % x for x in experiment(strength, step)))
