# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""Fit a one-parameter potential to four (position, force) labels with the MEAL loss,
then simulate it with processed leapfrog and compare with classical training + leapfrog.

The labels come from a spring with stiffness 2 and mass 1.5. Classical training fits
the stiffness 2; MEAL fits the stiffness whose corrected gradient matches the labels.
"""

import math
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "reference"))
from processed_dkd import dkd_step, force_loss, rollout  # noqa: E402

h, steps, mass = 0.2, 50, (1.5,)
samples = [((q,), (f,)) for q, f in [(-1.2, 2.4), (-0.7, 1.4), (0.25, -0.5), (1.1, -2.2)]]

# Classical training: least squares for V = k q^2 / 2, gradient k q against -F.
k_classical = -sum(q[0] * f[0] for q, f in samples) / sum(q[0] ** 2 for q, _ in samples)
# MEAL: the corrected gradient of V = k q^2 / 2 is (k + h^2 k^2 / (12 m)) q, so the loss
# is zero when k + h^2 k^2 / (12 m) = k_classical; take the root near k_classical.
alpha = h * h / (12 * mass[0])
k_meal = 2 * k_classical / (1 + math.sqrt(1 + 4 * alpha * k_classical))

calls = 0


def grad_meal(q):
    global calls
    calls += 1
    return (k_meal * q[0],)


def hvp_meal(q, v):
    return (k_meal * v[0],)


q0, p0 = (0.8,), (0.3,)
_, q_meal, p_meal = rollout(q0, p0, h, steps, mass, grad_meal, every=steps)[-1]
rollout_calls = calls
q_cl, p_cl = q0, p0
for _ in range(steps):
    q_cl, p_cl = dkd_step(q_cl, p_cl, h, mass, lambda q: (k_classical * q[0],))

omega = math.sqrt(k_classical / mass[0])
t = steps * h
exact_q = q0[0] * math.cos(omega * t) + p0[0] * math.sin(omega * t) / (mass[0] * omega)
exact_p = p0[0] * math.cos(omega * t) - mass[0] * omega * q0[0] * math.sin(omega * t)


def error(q, p):
    return math.hypot(q[0] - exact_q, p[0] - exact_p)


print(f"Classical stiffness              {k_classical:.8f}")
print(f"MEAL stiffness for h = {h}       {k_meal:.8f}")
print(f"MEAL loss below 1e-28            {force_loss(samples, h, mass, grad_meal, hvp_meal) < 1e-28}")
print(f"Classical + leapfrog error       {error(q_cl, p_cl):.6e}")
print(f"MEAL + processed leapfrog error  {error(q_meal, p_meal):.6e}")
print(f"Processed gradient evaluations   {rollout_calls} (= {steps} + 4 + 4)")
