"""Two Camassa-Holm peaks from a discrete string and from Hamilton's equations.

Run with Python 3 and NumPy. The string lives on [-1, 1]. Its spectral
parameters are negative for positive masses, and the time variable used by
Beals, Sattinger and Szmigielski equals half the physical time below.
"""
import numpy as np
from numpy.polynomial import Polynomial


def forward(positions, amplitudes):
    nodes = np.tanh(positions / 2)
    weights = 2 * amplitudes / (1 - nodes**2)
    value, slope = Polynomial([0]), Polynomial([1])
    z = Polynomial([0, 1])
    left = -1
    for node, weight in zip(nodes, weights):
        value = value + (node - left) * slope
        slope = slope + z * weight * value
        left = node
    value = value + (1 - left) * slope
    poles = value.roots()
    residues = slope(poles) / (poles * value.deriv()(poles))
    return poles, residues


def reconstruct(time, poles, residues):
    weights = residues * np.exp(-time / poles)
    m0, m1, m2 = (np.sum(weights * (-poles)**j) for j in range(3))
    determinant = (poles[0] - poles[1])**2 * np.prod(weights)
    positions = np.log([2 * determinant / m2, 2 * m0])
    amplitudes = np.array([m2 / (np.prod(poles) * m1), m0 / m1])
    return np.concatenate((positions, amplitudes))


def hamiltonian_field(state):
    q1, q2, p1, p2 = state
    overlap = np.exp(q1 - q2)
    exchange = p1 * p2 * overlap
    return np.array([p1 + p2 * overlap, p2 + p1 * overlap, -exchange, exchange])


def integrate(state, time, steps):
    state = state.copy()
    step = time / steps
    for _ in range(steps):
        k1 = hamiltonian_field(state)
        k2 = hamiltonian_field(state + step * k1 / 2)
        k3 = hamiltonian_field(state + step * k2 / 2)
        k4 = hamiltonian_field(state + step * k3)
        state += step * (k1 + 2 * k2 + 2 * k3 + k4) / 6
    return state


if __name__ == "__main__":
    initial = np.array([-1., 1., 1., 2.])
    poles, residues = forward(initial[:2], initial[2:])
    print("poles", poles, "residues", residues)
    assert np.max(np.abs(reconstruct(0., poles, residues) - initial)) < 1e-13
    time = 1.0
    result = reconstruct(time, poles, residues)
    print("state at t=1", result)
    for steps in (20, 40, 80):
        error = np.max(np.abs(integrate(initial, time, steps) - result))
        print("steps", steps, "maximum coordinate difference", error)
    assert error < 1e-9
    opposite, positive_residues = forward(initial[:2], np.array([1., -2.]))
    print("one antipeakon: poles", opposite, "residues", positive_residues)
    assert np.prod(opposite) < 0 and np.all(positive_residues > 0)
