# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""Regenerate the method's offline portable fixtures."""

import json
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "reference"))
import particle as reference


def build():
    cases = [
        dict(name="separate mean pools with unequal species counts", operation="encode", tol=1e-12,
             inputs=dict(groups=[[[.2,.7],[-.6,.1],[.9,-.3]],[[.1,-.4],[-.8,.5]]],
                         point_weights=[[.2,.7],[-.4,.6]], point_bias=[.1,-.3],
                         set_weights=[[1.2,-.6],[.3,.4]], set_bias=[-.15,.2])),
        dict(name="normalized two-dimensional smoothed empirical density", operation="target_logpdf", tol=1e-12,
             inputs=dict(points=[[.1,.3],[-.6,.2],[.3,-.7]], query=[.48,-.32], epsilon=.22)),
        dict(name="finite density score in the far tail", operation="target_logpdf", tol=1e-9,
             inputs=dict(points=[[.1],[-.2]], query=[18.], epsilon=.1)),
        dict(name="fixed KL reconstruction and encoder decoder derivatives", operation="reconstruction_gradient",
             tol=1e-11, inputs=dict(points=[[-.7],[1.1],[1.55]], queries=[[-.63],[-.11],[.8],[1.9]],
                                     epsilon=.35, weights=[.8,-.15,-.25])),
        dict(name="correlated endpoint likelihood and drift derivatives", operation="transition_nll", tol=1e-12,
             inputs=dict(start=[.3,-.7], end=[.47,-.61], lag=.17, drift=[-.21,.4],
                         lower=[[.29,0.],[.11,.43]])),
        dict(name="biased multiscale MMD with unequal ensemble sizes", operation="mmd_squared", tol=1e-12,
             inputs=dict(predicted=[[.1,.5],[.4,-.06]], observed=[[.24,.31],[.07,-.42],[.37,.02]],
                         sigmas=[.01,.05,.25,1.25])),
        dict(name="deterministic squared endpoint error and drift derivatives",
             operation="deterministic_endpoint_loss", tol=1e-12,
             inputs=dict(start=[.6, -.5], end=[.55, -.3], lag=.23, drift=[.12, .35])),
        dict(name="mean of per-trajectory squared relative errors", operation="mean_relative_error", tol=1e-12,
             inputs=dict(predicted=[[[1.2], [.7]], [[3.6], [5.2]]],
                         observed=[[[1.], [.5]], [[4.], [5.]]])),
        dict(name="normalized interaction energy of a four-particle frame",
             operation="normalized_interaction_energy", tol=1e-12,
             inputs=dict(points=[[0., 0.], [.6, 0.], [0., .8], [.6, 1.6]])),
    ]
    for case in cases:
        case["expected"] = getattr(reference,case["operation"])(**case["inputs"])
    return {
        "format": 1, "method": "permutation-invariant-macrodynamics", "version": "0.2.0",
        "interface": (
            "Double precision, row-major matrices, absolute tolerances. "
            "encode(groups,point_weights,point_bias,set_weights,set_bias) separately maps each nonempty group "
            "through phi(x)=tanh(point_weights*x+point_bias), taking tanh elementwise, averages within that group, "
            "then applies rho(v)=set_weights*v+set_bias. Share parameters across groups and concatenate in input "
            "group order. target_logpdf(points,query,epsilon) returns log[(1/n) sum of normalized d-dimensional "
            "Gaussians with means at the points and covariance epsilon^2 I]. Use stable log-sum-exp. "
            "reconstruction_gradient(points,queries,epsilon,weights) is the mean of log q_X(y)-log p(y|h) over "
            "the given one-dimensional queries. For weights [a,b,s], use h=a*mean(points), p=N(h+b,exp(2*s)). "
            "Return [loss,[d_loss/d_a,d_loss/d_b,d_loss/d_s]] with points and queries fixed. "
            "transition_nll(start,end,lag,drift,lower) returns [full normalized Gaussian endpoint NLL, gradient "
            "with respect to drift]. Mean start+lag*drift, covariance lag*lower*lower^T. The lower triangular factor "
            "is the noise amplitude per square root of time. "
            "mmd_squared(predicted,observed,sigmas) is the mean across sigmas of XX+YY-2*XY, where each term is "
            "the mean RBF kernel over all pairs between the indicated ensembles, including self terms within "
            "an ensemble. Kernel exp(-||x-y||^2/(2*sigma^2)). Return squared MMD with no square root. "
            "deterministic_endpoint_loss(start,end,lag,drift) returns [error, gradient with respect to drift], "
            "where error is the sum of squared components of start + lag*drift - end for one pair. "
            "mean_relative_error(predicted,observed) takes arrays in trajectory, forecast time, observable "
            "coordinate order, with the initial frame omitted. For each trajectory divide the sum of squared "
            "errors by the sum of squared observed values, then average the ratios. The denominators are nonzero. "
            "normalized_interaction_energy(points) averages log(cosh(4*(1-r)))/4 + 0.1*(1-r) over pairs i<j, "
            "where r is Euclidean separation. Use at least two particles. "
            "Export all eight functions from port_adapter.py."
        ),
        "cases": cases,
    }


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