# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""Properties of processed-leapfrog MEAL claimed in SKILL.md, on the reference implementation.

1. Order 4 with the step-specific potential; order 2 for classical leapfrog, for a
   checkpoint trained for 2h, and for auxiliary states emitted without postprocessing.
2. Each processed step is symplectic and symmetric; the processors invert each other.
3. Output frequency does not change the trajectory; gradient evaluations follow
   N + 4 + 4 ceil(N/k); the final state is always emitted.
4. The loss has zero residual for the right sign of the force labels only.
"""

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, gradient_evaluations, process, rollout  # noqa: E402

failures = []


def verdict(ok, text):
    print(f"{'PASS' if ok else 'FAIL'} {text}")
    if not ok:
        failures.append(text)


def gap(a, b):
    return max(abs(x - y) for x, y in zip(a, b))


# 1. Convergence on a spring (mass 1.5, stiffness 2) at T = 4 against the exact solution.
MASS, K, T = (1.5,), 2.0, 4.0
Q0, P0 = (0.8,), (0.3,)
w = math.sqrt(K / MASS[0])
EXACT = (Q0[0] * math.cos(w * T) + P0[0] * math.sin(w * T) / (MASS[0] * w),
         P0[0] * math.cos(w * T) - MASS[0] * w * Q0[0] * math.sin(w * T))


def trained_stiffness(h):
    """Minimizer of the MEAL loss for V = k q^2/2 on labels F = -K q: k + h^2 k^2/(12 m) = K."""
    return 2 * K / (1 + math.sqrt(1 + h * h * K / (3 * MASS[0])))


def err(q, p):
    return math.hypot(q[0] - EXACT[0], p[0] - EXACT[1])


series = {"classical leapfrog": [], "processed leapfrog, MEAL potential": [],
          "MEAL potential trained for 2h (negative)": [], "auxiliary state without postprocessing (negative)": []}
for h in (0.2, 0.1, 0.05, 0.025):
    n = round(T / h)
    k, k_wrong = trained_stiffness(h), trained_stiffness(2 * h)
    q, p = Q0, P0
    for _ in range(n):
        q, p = dkd_step(q, p, h, MASS, lambda x: (K * x[0],))
    series["classical leapfrog"].append(err(q, p))
    series["processed leapfrog, MEAL potential"].append(err(*rollout(Q0, P0, h, n, MASS, lambda x, k=k: (k * x[0],), every=n)[-1][1:]))
    series["MEAL potential trained for 2h (negative)"].append(err(*rollout(Q0, P0, h, n, MASS, lambda x, k=k_wrong: (k * x[0],), every=n)[-1][1:]))
    g = lambda x, k=k: (k * x[0],)  # noqa: E731
    q, p = process(Q0, P0, h, MASS, g, post=False)
    for _ in range(n):
        q, p = dkd_step(q, p, h, MASS, g)
    series["auxiliary state without postprocessing (negative)"].append(err(q, p))
for (label, errors), (lo, hi) in zip(series.items(), ((1.9, 2.1), (3.85, 4.15), (1.9, 2.1), (1.9, 2.1))):
    orders = [math.log2(a / b) for a, b in zip(errors, errors[1:])]
    verdict(all(lo < o < hi for o in orders), f"{label}: orders " + ", ".join(f"{o:.3f}" for o in orders) + f" (expected {round((lo + hi) / 2)})")

# A nonlinear coupled problem with different masses for the remaining checks.
mass, h = (1.3, 0.7), 0.12
QA, PA = (0.4, -0.35), (0.1, 0.3)
calls = {"n": 0}


def grad(q):
    calls["n"] += 1
    x, y = q
    return (1.2 * x + 0.18 * y + 0.2 * x ** 3, 0.8 * y + 0.18 * x + 0.1 * y ** 3)


# 2. Symplecticity of one processed step: J^T Omega J = Omega (central differences).
def one_step(z):
    _, q, p = rollout(z[:2], z[2:], h, 1, mass, grad)[-1]
    return q + p


z0, eps = QA + PA, 1e-5
cols = []
for i in range(4):
    zp = tuple(x + (eps if j == i else 0.0) for j, x in enumerate(z0))
    zm = tuple(x - (eps if j == i else 0.0) for j, x in enumerate(z0))
    cols.append([(a - b) / (2 * eps) for a, b in zip(one_step(zp), one_step(zm))])
omega = lambda a, b: sum(a[i] * b[i + 2] - a[i + 2] * b[i] for i in range(2))  # noqa: E731
defect = max(abs(omega(cols[i], cols[j]) - ((j == i + 2) - (i == j + 2))) for i in range(4) for j in range(4))
verdict(defect < 5e-9, f"one processed step is symplectic: |J^T Omega J - Omega| = {defect:.1e}")

aux = process(QA, PA, h, mass, grad, post=False)
verdict(gap(process(*aux, h, mass, grad, post=True)[0] + process(*aux, h, mass, grad, post=True)[1], QA + PA) < 1e-15,
        "preprocessor then postprocessor returns the input to rounding")
_, q, p = rollout(QA, PA, h, 400, mass, grad, every=400)[-1]
_, qb, pb = rollout(q, p, -h, 400, mass, grad, every=400)[-1]
verdict(gap(qb + pb, QA + PA) < 1e-13, f"symmetric: 400 steps with h then with -h return within {gap(qb + pb, QA + PA):.1e}")
_, qf, pf = rollout(q, tuple(-x for x in p), h, 400, mass, grad, every=400)[-1]
flip = gap(qf + tuple(-x for x in pf), QA + PA)
verdict(flip < 1e-8, f"momentum-flip round trip returns within {flip:.1e} (not exact: the processor is not flip-symmetric, so this gap is at the processor-error level)")

# 3. Output and cost.
calls["n"] = 0
every1 = rollout(QA, PA, h, 24, mass, grad, every=1)
verdict(calls["n"] == 24 + 4 + 4 * 24 == gradient_evaluations(24, 1), f"output every step: {calls['n']} gradient evaluations (N + 4 + 4N)")
calls["n"] = 0
sparse = rollout(QA, PA, h, 26, mass, grad, every=6)
verdict(calls["n"] == 26 + 4 + 4 * 5 == gradient_evaluations(26, 6), f"26 steps, output every 6: {calls['n']} gradient evaluations (N + 4 + 4 ceil(N/k))")
verdict([s for s, _, _ in sparse] == [0, 6, 12, 18, 24, 26], "outputs at steps 0, 6, 12, 18, 24 and the final step 26")
shared = {s: (q, p) for s, q, p in every1}
verdict(all(shared[s] == (q, p) for s, q, p in sparse if s in shared), "output every 1 and every 6 steps give identical states at shared steps")
calls["n"] = 0
verdict(rollout(QA, PA, h, 0, mass, grad) == [(0, QA, PA)] and calls["n"] == 0, "zero steps: the input is returned without gradient evaluations")

# 4. Loss sign: force labels are -grad V of the target.
k, m = 1.5, (2.0,)
k_corr = k + h * h * k * k / (12 * m[0])
g1 = lambda q: (k * q[0],)  # noqa: E731
hv = lambda q, v: (k * v[0],)  # noqa: E731
verdict(force_loss([((1.0,), (-k_corr,))], h, m, g1, hv) < 1e-28 and force_loss([((1.0,), (k_corr,))], h, m, g1, hv) > 9.0,
        "loss vanishes for labels F = -g~ and not for the opposite sign")

sys.exit(1 if failures else 0)
