# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""Continuous dissipation, a conservative Euler counterexample, and a learned field."""
from math import cos, exp, pi, sin, sqrt
from pathlib import Path
import sys
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/"reference"))
from spectral import energy_force, forward, modes, symbols, transport
from waves import predictor, series, train

# Check the complex symbols before any real-valued inverse transform can discard leakage.
even = symbols(6, [0.]*4, [.8,.75,0.,.4])
odd = symbols(7, [0.]*4, [.8,.75,0.,.4])
assert even[0].imag == even[3].imag == 0.
assert odd[3].imag == -odd[4].imag == .4

u = [.2,-.5,.3,.8,-.4,.2,.1]
length = 3.5
energy,mu = energy_force(u,length,.15,.03,.2,.6)
head = [.6,-.3,.2,.4]
imag = [0.,-.4,.3,-.2]
field = transport(mu,head,imag)
rate = length*sum(a*b for a,b in zip(mu,field))/len(u)
expected = -length*sum(a.real*abs(b)**2 for a,b in zip(symbols(len(u),head,imag),forward(mu)))
assert rate < 0 and abs(rate-expected) < 1e-12

wave = [cos(2*pi*j/8) for j in range(8)]
f = transport(wave,[0.]*5,[0.,1.,0.,0.,0.])
assert max(abs(a-sin(2*pi*j/8)) for j,a in enumerate(f)) < 1e-12
def quadratic(u):
    return sum(v*v for v in u)/(2*len(u))
dt = .2
growth = quadratic([x+dt*d for x,d in zip(wave,f)])-quadratic(wave)
assert abs(growth-dt*dt*quadratic(f)) < 1e-12 and growth > 0
print(f"continuous energy rate {rate:.7f}, conservative Euler energy increase {growth:.7f}")

theta,_ = train(series(23,3))
physical = [exp(theta[0]),exp(theta[1]),theta[2]]
assert max(abs(a-b) for a,b in zip(physical,[.45,.12,.7])) < .008
errors = []
for path in series(103,3,frames=16):
    u = path[0]
    advance = predictor(theta,len(u))
    for _ in path[1:]:
        u = advance(u)
    errors.append(sqrt(sum((a-b)**2 for a,b in zip(u,path[-1]))/sum(a*a for a in path[-1])))
assert max(errors) < .004
print("held-out 15-step relative errors", *(f"{e:.6f}" for e in errors))
