# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""Check the two-stage synthetic fit and held-out observable distributions."""

import sys
from math import fsum, log
from pathlib import Path
from random import Random

sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "reference"))
from fit import TRUE_MATRIX, TRUE_NOISE, advance, cloud, fit_affine, forecast, moments, state, train, training_pairs
from particle import dot, mmd_squared


scale, width, coefficients, noise = train()
assert abs(scale-.5)<1e-12
assert all(abs(a-b)<1e-12 for row, expected in zip(coefficients,TRUE_MATRIX)
           for a,b in zip(row,[0.,*expected]))
assert all(abs(a-b)<1e-12 for row, expected in zip(noise,TRUE_NOISE)
           for a,b in zip(row,expected))
stats = [moments(x) for x,_,_ in training_pairs()]


def cross_entropy(slope, sd):
    return log(sd)+fsum(((m-2*slope*m)**2+v+.12**2)/(2*sd*sd) for m,v in stats)/len(stats)


assert cross_entropy(scale,width) < cross_entropy(0.,width)
assert cross_entropy(scale,width) < cross_entropy(scale,1.)
observable_pairs = [(state(x,scale)[:1],state(y,scale)[:1],dt) for x,y,dt in training_pairs()]
baseline, baseline_noise = fit_affine(observable_pairs)
lags = [.11,.17,.09]
sigmas = [.01,.05,.25,1.25]
score, control = 0.,0.

for initial, count in (([.2,-.55],9),([-.18,.65],11)):
    points = cloud(*initial,count)
    example = forecast(points,scale,coefficients,noise,lags,Random(7))
    reordered = forecast(list(reversed(points)),scale,coefficients,noise,lags,Random(7))
    assert example == reordered
    assert all(abs(a-b)<1e-12 for a,b in zip(state(points,scale),initial))

    predictions, truth, reduced = [], [], []
    prediction_rng, truth_rng, baseline_rng = Random(295), Random(71), Random(295)
    for _ in range(64):
        predictions.append(forecast(points,scale,coefficients,noise,lags,prediction_rng))
        x, r = list(initial), initial[:1]
        path, baseline_path = [], []
        for dt in lags:
            x = advance(x,[dot(row,x) for row in TRUE_MATRIX],TRUE_NOISE,dt,
                        [truth_rng.gauss(0.,1.),truth_rng.gauss(0.,1.)])
            r = advance(r,[dot(baseline[0],[1.,*r])],baseline_noise,dt,
                        [baseline_rng.gauss(0.,1.)])
            path.append(x[:1])
            baseline_path.append(r)
        truth.append(path)
        reduced.append(baseline_path)
    for k in range(len(lags)):
        target = [path[k] for path in truth]
        score += mmd_squared([path[k] for path in predictions],target,sigmas)
        control += mmd_squared([path[k] for path in reduced],target,sigmas)

score /= 2*len(lags)
control /= 2*len(lags)
assert score < control/2
print(f"held-out observable MMD squared {score:.5f}, observable-only model {control:.5f}")
print("PASS two-stage fit and reorder-invariant forecasts on 9- and 11-particle frames")
