# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""Check the analytic long-wave FPUT dispersion coefficient and its moving-frame sign."""
from math import cos, pi, sin, sqrt
from pathlib import Path
import sys
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/"reference"))
from spectral import transport

def measured_coefficient(n):
    eps = 2*pi/n
    basis = [cos(eps*j) for j in range(n)]
    amplitude = eps**2
    r = [amplitude*v for v in basis]
    # V'(r)=r+r² for c=alpha=1. Project the exact lattice acceleration onto its fundamental.
    tension = [a+a*a for a in r]
    acc = [tension[(j+1)%n]-2*tension[j]+tension[j-1] for j in range(n)]
    omega = sqrt(-sum(a*c for a,c in zip(acc,basis))/sum(a*c for a,c in zip(r,basis)))
    assert abs(omega-2*sin(eps/2)) < 1e-12
    return (eps-omega)/eps**3

values = [measured_coefficient(n) for n in (24,48,96)]
error = [abs(v-1/24) for v in values]
assert 3.9 < error[0]/error[1] < 4.1 and 3.9 < error[1]/error[2] < 4.1
assert error[-1] < 2.5e-6
extrapolated = (4*values[-1]-values[-2])/3
assert abs(extrapolated-1/24) < 2e-9
# u_tau=-b*u_xxx takes cos(x) to -b*sin(x) in the co-moving frame.
u = [cos(2*pi*j/9) for j in range(9)]
bands = [-extrapolated*k**3 for k in range(5)]
rate = transport(u,[0.]*5,bands)
assert max(abs(a+sin(2*pi*j/9)/24) for j,a in enumerate(rate)) < 2e-9
print("lattice estimates", *(f"{v:.8f}" for v in values))
print(f"extrapolated b = {extrapolated:.9f}, paper Eq. (52) gives {1/24:.9f}")
