# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""Check the small coefficient fit on unseen starts and recording intervals."""

import sys
from math import exp, fsum, log, pi, sqrt, tanh
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "reference"))
from benes import fit, sample_pairs, score

training = sample_pairs([-1.1, -.6, .1, .6, 1.25], [.21,.46,.72], count=40)
held_out = sample_pairs([-.88, .34, 1.52], [.28,.61], count=72)
weights, _ = fit(training)
noise = exp(weights[1])
assert abs(weights[0]-1) < .08 and abs(noise-1) < .04
learned = score(held_out, weights)
initial = score(held_out, [.4, log(.7)])
assert learned < initial-.1

# The one-step Euler baseline fits the same two-parameter model by weighted least squares.
drift_factor = fsum(tanh(x)*(y-x) for x, y, _ in training)
drift_factor /= fsum(t*tanh(x)**2 for x, _, t in training)
variance = fsum((y-x-t*drift_factor*tanh(x))**2/t for x, y, t in training)/len(training)
euler = fsum(
    (log(2*pi*t*variance)+(y-x-t*drift_factor*tanh(x))**2/(t*variance))/2
    for x, y, t in held_out
)/len(held_out)
assert abs(noise-1) < abs(sqrt(variance)-1)
assert learned < euler-.003
print(f"fitted drift amplitude {weights[0]:.4f}, noise {noise:.4f}, Euler noise {sqrt(variance):.4f}")
print(f"held-out negative log density {learned:.4f}, Euler {euler:.4f}, initial {initial:.4f}")
