# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""Test synthetic coefficient recovery and held-out increments in observable space."""
import math
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]/"reference"))
from closure_demo import model,samples,train

theta, _ = train(samples(81,10))
test = samples(66,18)
encoder, _, _, dynamics = model(theta)
curvature = math.exp(theta[6])
sse, q_only = 0.,0.
for i in range(0,len(test),4):
    group = test[i:i+4]
    x, _, dt = group[0]
    observed,hidden = encoder(x)
    z = observed+hidden
    f,sigma = dynamics(z)
    increments = [y[0]-x[0] for _, y, _ in group]
    mean = sum(increments)/len(increments)
    variance = sum((v-mean)**2 for v in increments)/len(increments)
    sse += (mean/dt-f[0])**2
    q_only += (mean/dt+0.6*z[0])**2
    predicted_std = math.sqrt(dt*sum(a*a for a in sigma[0]))
    assert abs(math.sqrt(variance)-predicted_std) < .001
print(f"held-out closure/observable-only mean-rate RMSE ratio {math.sqrt(sse/q_only):.4f}")
print(f"fitted encoder {theta[0]:.4f}, rotation {theta[3]:.4f}, noise {math.exp(theta[4]):.4f}, {math.exp(theta[5]):.4f}")
assert sse < 0.05*q_only
assert abs(curvature-1.) < .02 and abs(theta[0]-.4) < .01 and abs(theta[3]-1.3) < .01
assert abs(math.exp(theta[4])-.12) < .003 and abs(math.exp(theta[5])-.19) < .003
print(f"fitted potential curvature {curvature:.4f}")
print("PASS held-out observable increment spread")
