# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""Print checks/cases.json, computed with the reference implementation.

Maintainers: uv run checks/make_cases.py > checks/cases.json
verify/check_cases.py fails if the stored file no longer matches this output.
"""

import json
import sys
from pathlib import Path

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

MASS = [1.3, 0.7]


def poly_grad(theta):
    """Gradient of V_theta = theta * (0.6 x^2 + 0.4 y^2 + 0.18 x y + 0.05 x^4 + 0.025 y^4)."""
    def grad(q):
        x, y = q
        return (theta * (1.2 * x + 0.18 * y + 0.2 * x ** 3), theta * (0.8 * y + 0.18 * x + 0.1 * y ** 3))
    return grad


def poly_hvp(theta):
    def hvp(q, v):
        x, y = q
        return (theta * ((1.2 + 0.6 * x * x) * v[0] + 0.18 * v[1]), theta * (0.18 * v[0] + (0.8 + 0.3 * y * y) * v[1]))
    return hvp


def loss_derivative(qs, forces, h, mass, theta):
    """dL/dtheta for V_theta = theta * V_1, in closed form.

    g = theta g1 and grad^2 V = theta B1, so g~ = theta g1 + (h^2/12) theta^2 B1 M^-1 g1 and
    d(g~)/d(theta) = g1 + (h^2/6) theta B1 M^-1 g1: both copies of grad V depend on theta.
    """
    g1, b1 = poly_grad(1.0), poly_hvp(1.0)
    total = 0.0
    for q, f in zip(qs, forces):
        base = g1(q)
        bmg = b1(q, tuple(gi / mi for gi, mi in zip(base, mass)))
        g_mod = [theta * a + (h * h / 12) * theta * theta * c for a, c in zip(base, bmg)]
        dg = [a + (h * h / 6) * theta * c for a, c in zip(base, bmg)]
        total += sum(2 * (gm + fi) * d for gm, fi, d in zip(g_mod, f, dg))
    return total / len(qs)


PROBLEMS = {
    "poly2": {
        "description": "Two coupled coordinates with a polynomial potential and different masses",
        "potential": "V_theta(q) = theta * (0.6*x^2 + 0.4*y^2 + 0.18*x*y + 0.05*x^4 + 0.025*y^4), q = (x, y)",
        "gradient": "grad V_theta = theta * (1.2*x + 0.18*y + 0.2*x^3, 0.8*y + 0.18*x + 0.1*y^3)",
        "hessian": "grad^2 V_theta = theta * [[1.2 + 0.6*x^2, 0.18], [0.18, 0.8 + 0.3*y^2]]",
        "mass": MASS,
    },
}

META = (Path(__file__).resolve().parent.parent / "meta.yaml").read_text()
VERSION = next(line.split(":", 1)[1].strip() for line in META.splitlines() if line.startswith("version:"))

H, THETA = 0.12, 1.07
QS = [[0.4, -0.35], [-0.6, 0.5], [0.2, 0.7]]
FORCES = [[-0.48, 0.27], [0.61, -0.28], [-0.4, -0.5]]
Q0, P0 = [0.4, -0.35], [0.1, 0.3]


def build():
    grad, hvp = poly_grad(THETA), poly_hvp(THETA)
    cases = []
    for q in QS:
        cases.append({
            "kind": "modified_gradient", "problem": "poly2", "q": q, "h": H, "theta": THETA,
            "expected": list(modified_gradient(tuple(q), H, tuple(MASS), grad, hvp)), "tol": 1e-12,
        })
    cases.append({
        "kind": "loss", "problem": "poly2", "q": QS, "forces": FORCES, "h": H, "theta": THETA,
        "expected": {
            "loss": force_loss(list(zip(map(tuple, QS), map(tuple, FORCES))), H, tuple(MASS), grad, hvp),
            "dloss_dtheta": loss_derivative(QS, FORCES, H, MASS, THETA),
        },
        "tol": 1e-12,
    })
    for post in (False, True):
        q, p = process(tuple(Q0), tuple(P0), H, tuple(MASS), grad, post=post)
        cases.append({
            "kind": "process", "problem": "poly2", "q": Q0, "p": P0, "h": H, "theta": THETA, "post": post,
            "expected": {"q": list(q), "p": list(p)}, "tol": 1e-14,
        })
    for h, n, every in ((H, 26, 6), (-H, 10, 10)):
        out = rollout(Q0, P0, h, n, MASS, grad, every=every)
        cases.append({
            "kind": "rollout", "problem": "poly2", "q0": Q0, "p0": P0, "h": h, "n_steps": n, "every": every,
            "theta": THETA,
            "expected": {
                "outputs": [{"step": s, "q": list(q), "p": list(p)} for s, q, p in out],
                "gradient_evaluations": gradient_evaluations(n, every),
            },
            "tol": 1e-12,
        })
    return {
        "format": 1,
        "method": "processed-dkd-meal",
        "version": VERSION,
        "interface": (
            "Training: modified_gradient(q, h, mass, theta) -> g~(q) = grad V + (h^2/12) (grad^2 V) M^-1 grad V for the "
            "potential V_theta of the case's problem; loss_and_derivative(qs, forces, h, mass, theta) -> (L, dL/dtheta) with "
            "L = mean over configurations i of |g~(q_i) + F_i|^2 (squared Euclidean norm) and dL/dtheta its derivative "
            "with respect to theta, both copies of grad V depending on theta. Simulation: process(q, p, h, mass, grad, post) "
            "-> (q, p) applies the postprocessor (post=true: shears D(s), K(s), D(-s), K(-s), D(-s), K(-s), D(s), K(s) "
            "in this order, s = |h|/sqrt(48)) or its exact inverse, the preprocessor (post=false: reverse order, negated "
            "durations), where D(t): q += t M^-1 p and K(t): p -= t grad V(q); rollout(q0, p0, h, n_steps, every, mass, grad) "
            "-> list of (step, q, p): preprocess once, n_steps drift-kick-drift steps of size h with the ordinary grad V, "
            "and a postprocessed copy of the state at step 0 (the input itself), at every step divisible by every, and at "
            "the final step. p is canonical momentum, p_i = mass_i * v_i; grad(q) returns +grad V(q)."
        ),
        "comparison": (
            "Pass when every number differs from expected by at most tol (absolute); rollout must emit exactly the "
            "listed steps. gradient_evaluations is the number of grad calls rollout should make: n_steps + 4 + "
            "4 * ceil(n_steps / every)."
        ),
        "problems": PROBLEMS,
        "cases": cases,
    }


if __name__ == "__main__":
    print(json.dumps(build(), indent=1, ensure_ascii=False))
