#!/usr/bin/env python3
"""Independent controls for the Toda, Calogero and Ruijsenaars particle readings.

Run python3 toda_particle_checks.py with NumPy and SymPy installed. The Toda
rank and graph calculations use exact algebra. Other controls compare direct
diagonalization, quadrature or limiting trajectories with the derived results.
"""

import math

import numpy as np
import sympy as sp


def rank_and_graph():
    x, y, z, u, v = sp.symbols("x y z u v")
    mixed = sp.Matrix([[1, 1, 0], [x, y, u],
                       [x*x + u, y*y + u + v, u*(x+y)]])
    assert sp.factor(mixed.det()) == -u*v
    for bonds, diagonals in [([1, 1, 1], [0]*4), ([1, 3, 2], [1, 1, 5, -1]),
                             ([2, 1, 1, 3], [1]*5)]:
        n = len(diagonals)
        matrix = sp.diag(*diagonals)
        for i, bond in enumerate(bonds):
            matrix[i, i+1] = matrix[i+1, i] = bond
        rows = []
        for k in range(n):
            power = matrix**k
            rows.append([power[i, i] for i in range(n)]
                        + [2*power[i, i+1] for i in range(n-1)])
        assert sp.Matrix(rows).rank() == n
    triangle = sp.Matrix([[0, 1, z], [1, 0, 1], [z, 1, 0]])
    assert sp.expand(sp.trace(triangle**2)/2) == 2 + z**2
    assert sp.expand(sp.trace(triangle**3)/3) == 2*z
    print("Mixed minor -uv; Jacobi ranks 4, 4, 5; signed triangle traces verified.")


def open_reconstruction():
    first = np.sqrt(0.5)*np.array([[0, 1, 0], [1, 0, 1], [0, 1, 0]])
    later = np.array([[-1, 2, 0], [2, 0, 2], [0, 2, 1]]) / 3
    spectra = []
    weights = []
    for matrix in [first, later]:
        values, vectors = np.linalg.eigh(matrix)
        spectra.append(values)
        weights.append(vectors[0]**2)
    np.testing.assert_allclose(spectra, [[-1, 0, 1]]*2, atol=3e-15)
    evolved = weights[0]*np.exp(-spectra[0]*math.log(2))
    np.testing.assert_allclose(weights[1], evolved / evolved.sum(), atol=2e-15)
    np.testing.assert_allclose(weights[1], np.array([4, 4, 1])/9)
    for w in weights:
        assert abs(w[1]**2 / (w[0]*w[2]) - 4) < 1e-13
    print("Independent diagonalization recovers endpoint weights 4/9, 4/9, 1/9.")


def action_control():
    # Gaussian quadrature on the regularized angular interval; no elliptic-function routine.
    nodes, weights = np.polynomial.legendre.leggauss(48)
    theta = (math.pi/4)*(nodes + 1)
    weights = (math.pi/4)*weights
    sine_sq = np.sin(theta)**2

    def period(energy):
        return 2*np.dot(weights, (1 + (energy-2)*sine_sq/4)**(-0.5))

    def slope(energy):
        return -0.25*np.dot(weights, sine_sq*(1+(energy-2)*sine_sq/4)**(-1.5))

    for energy in [2.1, 3, 6, 10]:
        h = 1e-4
        estimate = (period(energy + h) - period(energy - h)) / (2*h)
        assert abs(slope(energy) - estimate) < 9e-11
    omega_action_slope = -4*math.pi**2 * slope(2) / period(2)**3
    assert abs(omega_action_slope - 0.25) < 1e-14
    print(f"Period slope at E=6 is {slope(6):.12f}; limiting dΩ/dI = 1/4.")


def calogero_acceleration():
    positions = np.array([-1.0, 0, 2])
    momentum = np.diag([0.7, -0.5, 0.2]).astype(complex)
    for i, qi in enumerate(positions):
        for j, qj in enumerate(positions):
            if i != j:
                momentum[i, j] = 1j/(qi-qj)

    def positions_at(t):
        return np.linalg.eigvalsh(np.diag(positions) + t*momentum)

    expected = np.array([-56/27, 7/4, 35/108])
    errors = []
    for h in [0.01, 0.005, 0.0025]:
        second = (positions_at(h) - 2*positions + positions_at(-h))/h**2
        errors.append(np.max(abs(second-expected)))
    assert all(3.9 < a/b < 4.1 for a, b in zip(errors, errors[1:]))
    print("Calogero acceleration errors:", ", ".join(f"{e:.4g}" for e in errors))


def matched_scattering():
    g = k = 1
    tau = 0.75
    calogero = math.hypot(g/k, 2*k*tau)
    errors = []
    for eta in [0.5, 0.25, 0.125, 0.0625]:
        closest = eta*g/math.sinh(eta*k)
        speed = 2*math.sinh(eta*k)/eta
        assert abs(closest*speed-2*g) < 1e-14
        errors.append(abs(math.hypot(closest, speed*tau)-calogero))
    assert all(3.8 < a/b < 4.4 for a, b in zip(errors, errors[1:]))
    print("Matched scattering at τ=3/4, position errors:",
          ", ".join(f"{e:.4g}" for e in errors))


def bond_calibration():
    # Joint translation of an origin and coupling preserves the whole vector field.
    for q in [[0, 0, 0], [0.3, -0.4, 0.1], [-1, 0.7, 1.4]]:
        q = np.array(q, dtype=float)
        first = np.array([2.0, 1])*np.exp(q[:-1] - q[1:])
        q[0] += math.log(2)
        second = np.exp(q[:-1] - q[1:])
        np.testing.assert_allclose(second, first, atol=2e-15)
    print("Calibrated shift preserved both bonds at three asymmetric configurations.")


if __name__ == "__main__":
    rank_and_graph()
    open_reconstruction()
    action_control()
    calogero_acceleration()
    matched_scattering()
    bond_calibration()
