"""Fixed-end alpha-chain reproduction of LA-1940, Fig. 1.

Requires Python 3 and NumPy. Run with --csv modes.csv to save the finer
trajectory. Times are in the unit-mass, unit-spring convention.
"""
import argparse
import numpy as np


def simulate(intervals, alpha, step, duration, sample_time):
    interior = np.arange(1, intervals)
    basis = np.sqrt(2 / intervals) * np.sin(np.pi * np.outer(interior, interior) / intervals)
    omega = 2 * np.sin(np.pi * interior / (2 * intervals))
    q = np.zeros(intervals + 1)
    q[1:-1] = np.sin(np.pi * interior / intervals)
    velocity = np.zeros(intervals - 1)

    def acceleration():
        strain = np.diff(q)
        return np.diff(strain + alpha * strain**2)

    def observe(time):
        strain = np.diff(q)
        energy = velocity @ velocity / 2 + np.sum(strain**2/2 + alpha * strain**3/3)
        modes = ((basis @ velocity)**2 + (omega * (basis @ q[1:-1]))**2) / 2
        assert np.isclose(sum(modes), energy - alpha*np.sum(strain**3)/3)
        return [time, energy, *modes[:5]]

    stride = round(sample_time / step)
    assert stride > 0 and np.isclose(stride * step, sample_time)
    rows = [observe(0.)]
    a = acceleration()
    for n in range(1, round(duration / step) + 1):
        velocity += step * a / 2
        q[1:-1] += step * velocity
        a = acceleration()
        velocity += step * a / 2
        if n % stride == 0:
            rows.append(observe(n * step))
    return np.array(rows)


def diagnostics(rows):
    time, energy, first = rows[:, :3].T
    first = first / first[0]
    # Select the first strong return after the initial transfer.
    window = np.flatnonzero((time >= 7500) & (time <= 11000))
    peak = window[np.argmax(first[window])]
    return time[peak], first[peak], min(first[:peak]), max(abs(energy / energy[0] - 1))


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--csv', help='save the more finely integrated nonlinear run')
    args = parser.parse_args()
    original_step = np.sqrt(1/8)
    historical = simulate(32, .25, original_step, 30000 * original_step, 8 * original_step)
    peak, fraction, _, _ = diagnostics(historical)
    print(f'LA-1940 step: {peak / original_step:.0f} cycles, E1/E1(0)={fraction:.6f}')
    for dt in (.25, .125, .0625, .03125):
        trajectory = simulate(32, .25, dt, 11000, 2)
        peak, fraction, minimum, drift = diagnostics(trajectory)
        print(f'dt={dt:g} return at {peak:g}, E1/E1(0)={fraction:.8f}, '
              f'prior minimum={minimum:.8f}, max |H/H0-1|={drift:.3g}')
    if args.csv:
        np.savetxt(args.csv, trajectory, delimiter=',', header='time,H,E1,E2,E3,E4,E5', comments='')
    linear = simulate(32, 0., .125, 11000, 2)
    leakage = np.max(np.abs(linear[:, 3:] / linear[0, 2]))
    assert leakage < 1.e-20
    print(f'linear control, maximum E2 through E5 divided by initial E1: {leakage:.3g}')
