# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""Print the portable JSON fixtures generated by the reference."""

import json
import sys
import warnings
from pathlib import Path

from check_port import evaluate_case

sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "reference"))
from learned_rk import objective, step
from train_rk import classical_order_conditions, flow_derivatives, rk_derivatives, train


def quiet_train(*args, **options):
    """The fixed training case uses two stages and a finite-step term, so it matches second
    order only approximately; the reference rightly warns, which is not news here."""
    with warnings.catch_warnings():
        warnings.filterwarnings("ignore", message="the fitted tableau matches", category=RuntimeWarning)
        return train(*args, **options)


REFERENCE = dict(step=step, objective=objective, rk_derivatives=rk_derivatives,
                 flow_derivatives=flow_derivatives, train=quiet_train,
                 order_conditions=classical_order_conditions)

RK3_ROWS, RK3_LOGITS = [[], [0.5], [-1.0, 2.0]], [0.0, 1.3862943611198906, 0.0]  # log 4: b = (1/6, 2/3, 1/6)


def training_samples():
    return [
        dict(rhs="decay", state=[1.2], h=0.35, target=[1.0073484249230489], baseline=[1.008375]),
        dict(rhs="decay-quadratic-high", state=[1.8], h=0.30, target=[1.2904377004009195], baseline=[1.3068697536]),
        dict(rhs="decay-quadratic-low", state=[1.4], h=0.40, target=[1.0651313221971292], baseline=[1.0708158272]),
    ]


def build():
    samples = [
        {
            "target": [2, -1], "prediction": [2.5, -1.25], "baseline": [3, -0.5],
            "target_derivatives": [[1, -2], [4, 1], [-6, 3]],
            "prediction_derivatives": [[1, -2], [3, 2], [-4, 2]],
        },
        {
            "target": [-2, 3], "prediction": [-1.75, 2.5], "baseline": [-2.5, 3.5],
            "target_derivatives": [[-1, 3], [2, 2], [1, -4]],
            "prediction_derivatives": [[-1, 3], [2, 2], [0, -2]],
        },
    ]
    cases = [
        dict(name="two-stage square tableau", operation="step", rhs="square", state=[2.5],
             h=0.125, a=[[], [2.0]], b=[0.75, 0.25]),
        dict(name="three-stage coupled affine ODE", operation="step", rhs="affine", state=[0.5, -1.0],
             h=0.25, a=[[], [0.5], [-0.25, 0.75]], b=[0.125, 0.375, 0.5]),
        dict(name="three-stage nonlinear ODE", operation="step", rhs="nonlinear", state=[1.75, 0.5],
             h=0.2, a=[[], [0.8], [0.6, -0.2]], b=[0.2, 0.3, 0.5]),
        dict(name="weighted per-sample loss and Taylor penalty", operation="objective",
             samples=samples, fit_weight=2.0, order_weight=0.125),
        dict(name="Taylor-only loss with exact baseline", operation="objective",
             samples=[dict(samples[0], baseline=samples[0]["target"])], fit_weight=0.0, order_weight=0.5),
        dict(name="RK step derivatives at zero for a coupled ODE", operation="rk_derivatives",
             rhs="nonlinear", state=[1.75, 0.5], a=[[], [0.8], [0.6, -0.2]], b=[0.2, 0.3, 0.5], order=4),
        dict(name="exact flow derivatives at zero for a coupled ODE", operation="flow_derivatives",
             rhs="nonlinear", state=[1.75, 0.5], order=3),
        dict(name="four exact flow derivatives of linear decay", operation="flow_derivatives",
             rhs="decay", state=[1.5], order=4),
        dict(name="stable softmax on initial logits", operation="train", samples=training_samples(),
             a0=[[], [0.8]], logits0=[1002.0, 1000.0], order=3, fit_weight=1.0, order_weight=0.02, max_iters=0),
        dict(name="fit one tableau to several decay tasks using both terms", operation="train",
             samples=training_samples(), a0=[[], [0.8]], logits0=[1.25, 0.75], order=3, fit_weight=1.0,
             order_weight=0.02, max_iters=None),
        dict(name="classical order conditions up to order 3 for a three-stage tableau",
             operation="order_conditions", a=[[], [0.8], [0.6, -0.2]], b=[0.2, 0.3, 0.5], order=3),
        dict(name="classical order conditions up to order 4 for a four-stage tableau",
             operation="order_conditions", a=[[], [0.4], [0.1, 0.5], [0.3, -0.2, 0.6]],
             b=[0.1, 0.4, 0.3, 0.2], order=4),
        dict(name="keep third order exactly while fitting a fourth-order target on Duffing oscillators",
             operation="train", compare="loss and order conditions", keep_order=3,
             samples=[dict(rhs="duffing-0.5", state=[1.2, 0.0]), dict(rhs="duffing-2", state=[0.4, 0.9]),
                      dict(rhs="duffing-1", state=[-0.8, 0.5])],
             a0=RK3_ROWS, logits0=RK3_LOGITS, order=4, fit_weight=0.0, order_weight=1.0, max_iters=None),
    ]
    for case in cases:
        case["expected"] = evaluate_case(case, REFERENCE)
        case["tol"] = 3e-5 if case.get("max_iters", 0) != 0 else 1e-12
    return {
        "format": 1,
        "method": "learned-rk",
        "version": "0.1.0",
        "interface": (
            "Export step, objective, rk_derivatives, flow_derivatives, train and order_conditions "
            "from port_adapter.py in the working directory.\n\n"
            "step(rhs, state, h, a, b) returns the next state vector. rhs maps a state vector to its "
            "autonomous derivative vector. With zero-based indices, A row i stores exactly i "
            "coefficients a[i][j] for j < i. From the unchanged step-start state, use "
            "K_i = rhs(state + h * sum_j a[i][j] K_j), then return state + h * sum_i b[i] K_i. "
            "Use the supplied b directly.\n\n"
            "objective(samples, fit_weight, order_weight) returns a scalar. For each sample, add "
            "fit_weight * ||target - prediction||^2 / ||target - baseline||^2 and "
            "order_weight * sum_k ||target_derivatives[k] - prediction_derivatives[k]||^2. "
            "Take the arithmetic mean of the per-sample sums. Norms are Euclidean. The derivative "
            "lists contain state vectors for h derivatives of orders 1 through p evaluated at h=0, "
            "with factorials already included. Skip terms whose weight is zero. Fit-active samples "
            "have nonzero baseline error.\n\n"
            "rk_derivatives(rhs, state, a, b, order) and flow_derivatives(rhs, state, order) "
            "return lists of state vectors for the h derivatives of the RK step and the exact "
            "flow at zero, respectively. Entry k-1 is the kth derivative, including the k! factor.\n\n"
            "train(samples, a0, logits0, order, fit_weight, order_weight, max_iters) returns "
            "[A, b, mean objective]. Each sample contains rhs, state and, for an active "
            "finite-step term, h, target and baseline. The Python checker resolves rhs names "
            "to callables before invoking the adapter. For other languages use the functions in "
            "problems. Compute prediction and derivatives from "
            "the raw task. Fit a shared compact A and softmax logits to the weighted objective "
            "specified above. max_iters=0 evaluates the supplied initial tableau in softmax "
            "parameterization. max_iters=null leaves the iteration count to the port: fit until "
            "converged with any suitable optimizer. The check compares only the result with the "
            "stated tolerance. A second-order method such as damped Gauss-Newton converges in tens "
            "of iterations; a first-order one such as Adam, used in the paper, can need thousands. "
            "A train case may also give keep_order=q: hold the classical order conditions of orders "
            "2..q exactly (to rounding) for the whole fit, for example by constrained Gauss-Newton or "
            "by optimising in coordinates of the constraint set. Such a case has compare = "
            "'loss and order conditions': the optimum is not unique, so the check compares only the "
            "mean objective and verifies the conditions of the returned tableau.\n\n"
            "order_conditions(a, b, order) returns the residuals of the classical order conditions of "
            "orders 2 through order (at most 4), with c = A 1, in this sequence: b.c - 1/2; "
            "b.c^2 - 1/3, b.(Ac) - 1/6; b.c^3 - 1/4, b.(c*Ac) - 1/8, b.(A c^2) - 1/12, b.(A A c) - 1/24.\n\n"
            "tol is a componentwise absolute tolerance with double-precision arithmetic."
        ),
        "problems": {
            "affine": "For y=(x,z), rhs(y) = (2*x-z+1, x+3*z-2).",
            "nonlinear": "For y=(x,z), rhs(y) = (-x*x+z, x*z-2*z).",
            "square": "For y=(x,), rhs(y) = (-0.4*x*x,).",
            "decay": "For y=(x,), rhs(y) = (-0.5*x,).",
            "decay-quadratic-low": "For y=(x,), rhs(y) = (-0.5*x-0.15*x*x,).",
            "decay-quadratic-high": "For y=(x,), rhs(y) = (-0.5*x-0.4*x*x,).",
            "duffing-0.5": "For y=(x,v), rhs(y) = (v, -x-0.5*x^3).",
            "duffing-1": "For y=(x,v), rhs(y) = (v, -x-x^3).",
            "duffing-2": "For y=(x,v), rhs(y) = (v, -x-2*x^3).",
        },
        "cases": cases,
    }


if __name__ == "__main__":
    print(json.dumps(build(), indent=2))
