# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""Regenerate the portable fixtures on standard output."""
import json
import sys
from pathlib import Path
from types import SimpleNamespace

sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "reference"))
from onsager import drift, model_loss, potential
from spring import spring_loss_gradient

reference = SimpleNamespace(drift=drift, model_loss=model_loss, potential=potential,
                            spring_loss_gradient=spring_loss_gradient)


def build():
    nonlinear_model = dict(hidden=[[0.6,-1.], [0.7,0.2]], hidden_bias=[0.14,-0.11],
                           lift=[[0.3,0.5],[-0.1,0.8]], lift_bias=[0.2,-0.4], skip=[[1.,0.3],[0.,1.]],
                           matrix=[[1.,0.],[0.,-0.4],[0.6,0.5],[0.,1.]], matrix_bias=[0.2,0.1,0.3,-0.1],
                           drive=[[0.1,0.3],[0.,-0.05]], drive_bias=[0.,0.2], alpha=0.1, beta=0.07)
    cases = [
        dict(name="two unequal snapshot intervals and three Heun substeps", operation="model_loss", tol=1e-10,
             inputs=dict(model=nonlinear_model, pairs=[[[0.2,0.3],[0.21,0.27],0.06],
                                                       [[-0.5,0.2],[-0.49,0.21],0.14]], substeps=3)),
        dict(name="driven nonsymmetric heads", operation="drift", tol=1e-12,
             inputs=dict(grad_v=[1.5,-2.], lower=[[1.,4.],[0.5,2.]], upper=[[3.,-0.7],[2.,4.]],
                         drive=[0.2,-0.1], alpha=0.3)),
        dict(name="signed acceleration at a turning point", operation="drift", tol=1e-12,
             inputs=dict(grad_v=[4.,0.], lower=[[0.,0.],[0.,1.]], upper=[[0.,-1.],[0.,0.]], drive=[0.,0.])),
        dict(name="rectangular nonlinear lift Jacobian", operation="potential", tol=1e-12,
             inputs=dict(x=[0.4,-1.2], lift=[1.5,-0.2,0.9], jacobian=[[2.,-1.],[0.3,0.2],[0.,-0.5]], beta=0.125)),
        dict(name="training loss and all three spring weight derivatives",
             operation="spring_loss_gradient", tol=2e-8,
             inputs=dict(weights=[1.3, 0.35, 0.85], substeps=2,
                         pairs=[[[0.45, -0.3], [0.39, -0.33], 0.15],
                                [[-0.6, 0.2], [-0.57, 0.29], 0.1]])),
    ]
    for case in cases:
        case["expected"] = getattr(reference, case["operation"])(**case["inputs"])
    return {"format": 1, "method": "onsagernet", "version": "0.1.0",
            "interface": (
                "Double precision, zero-based row-major arrays and absolute tolerance. "
                "drift(grad_v, lower, upper, drive, alpha=0) returns -(L L^T + alpha I + R - R^T) grad_v + drive, "
                "using the lower triangle including the diagonal for L and only the strictly upper triangle for R. "
                "potential(x,lift,jacobian,beta=0) returns [V,grad_V] for V=dot(lift,lift)/2+beta*dot(x,x), "
                "jacobian[i][j]=d lift_i/d x_j. model_loss(model,pairs,substeps=1) returns Eq. (12), averaged "
                "over interval-scaled squared residual norms. The one-hidden-layer tanh model uses row-major "
                "affine hidden, lift and flattened raw-matrix heads with the named biases. Add skip*x to the lift. "
                "The affine drive acts directly on x. Each pair is [start,end,dt]. "
                "spring_loss_gradient(weights,pairs,substeps=1) returns [loss,[d_loss/ds,d_loss/da,d_loss/dc]] "
                "for weights [s,a,c], state [q,v], V=((s*q+a*tanh(q))^2+v^2)/2, q'=v and v'=-dV/dq-c^2*v. "
                "Differentiate through every Heun stage in the same loss as model_loss. "
                "Export these four functions in port_adapter.py. See SKILL.md, Algorithm."
            ), "cases": cases}


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