# /// 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"))
import stochastic
from pca import whitening

reference = SimpleNamespace(**vars(stochastic), whitening=whitening)


def build():
    cases = [
        dict(name="correlated increments at a short lag",operation="transition",tol=1e-11,
             inputs=dict(start=[0.2,-0.5],end=[0.1,-0.25],dt=0.08,velocity=[-0.7,0.4],sigma=[[0.55,0.2],[-0.15,0.4]])),
        dict(name="normalized scalar density",operation="transition",tol=1e-12,
             inputs=dict(start=[0.0],end=[0.25],dt=0.25,velocity=[1.0],sigma=[[2.0]])),
        dict(name="dissipation independent of diffusion",operation="drift",tol=1e-12,
             inputs=dict(grad_v=[0.5,-0.75],lower=[[1.,0.],[0.4,0.8]],skew=[[0.,-0.3],[0.3,0.]],alpha=.02)),
        dict(name="observable before whitened closure",operation="coordinates",tol=1e-12,
             inputs=dict(x=[-.4,.7,1.2],observed=[2.1],projection=[[.5,-.3,.7]],residual=[.2])),
        dict(name="penalty above PCA reconstruction error",operation="rec_loss",tol=1e-12,
             inputs=dict(x=[0.,1.],decoded=[2.,2.],pca_decoded=[0.,2.],penalty=.25)),
        dict(name="zero penalty when decoder beats PCA", operation="rec_loss", tol=1e-12,
             inputs=dict(x=[0.,1.], decoded=[.25,1.], pca_decoded=[0.,2.], penalty=.4)),
        dict(name="whitening and inverse of a correlated covariance", operation="whitening", tol=1e-11,
             inputs=dict(samples=[[3.,4.],[-3.,-4.],[-.8,.6],[.8,-.6]], count=2)),
        dict(name="joint closure loss and three weight derivatives", operation="closure_loss_gradient", tol=1e-10,
             inputs=dict(pairs=[[[.3,-.7],[.26,-.55],.08], [[-.4,.9],[-.27,.62],.19]],
                         weights=[.82,1.4,.65], weight=.3, penalty=.2)),
    ]
    for case in cases:
        case["expected"] = getattr(reference, case["operation"])(**case["inputs"])
    return {"format": 1, "method": "stochastic-onsagernet", "version": "0.1.0",
            "interface": (
                "Double precision. drift(grad_v,lower,skew,alpha=0) uses M=L L^T+alpha I, W=skew and returns -(M+W) grad_v. "
                "transition(start,end,dt,velocity,sigma) returns [full normalized Gaussian negative log density, derivative w.r.t. velocity]; conditional covariance is dt*sigma*sigma^T. "
                "coordinates(x,observed,projection,residual) concatenates observed and projection*x+residual for training-centered x. "
                "rec_loss(x,decoded,pca_decoded,penalty,floor=1e-15) is squared reconstruction error plus penalty*max(0,log(max(error,floor))-log(max(PCA_error,floor))). "
                "whitening(samples,count) returns [P,P_pinv] from already-centered samples. Divide the second moments by the number of samples. Order the retained eigenvectors by decreasing eigenvalue. Orient each unit eigenvector so its largest-magnitude component is positive (first index breaks ties). P has rows equal to unit eigenvectors divided by sqrt(eigenvalue), and P_pinv has columns equal to unit eigenvectors multiplied by sqrt(eigenvalue). "
                "closure_loss_gradient(pairs,weights,weight,penalty) uses weights [a,k,s]. Encode x as [x[0],a*x[1]], decode the hidden coordinate h as [0,h], and use [0,x[1]] as the PCA reconstruction. "
                "Use drift [-z[0],-k*z[1]] and noise factor diag(1,s). For each pair [x,y,lag] add the normalized transition loss to weight*rec_loss at x, then average. "
                "Return [loss,[d/da,d/dk,d/ds]], differentiating both encoded endpoints and the reconstruction. "
                "Vectors are columns, matrices row-major. Absolute tolerances. Export all six functions from port_adapter.py."
            ), "cases": cases}


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