# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""Independent current, divergence and conditional-moment checks."""
from math import exp, sqrt
from pathlib import Path
import sys
sys.path.insert(0, str(Path(__file__).resolve().parents[1]/"reference"))
from linear import model, samples, train
from uidd import evaluate, pair_loss, stationary_epr

parts,_ = evaluate([2.], lambda x: x[0]**2/2, lambda x: [[sqrt(2*(1+x[0]**2))]], lambda x: [])
# (M rho)'/rho at x=2 is 4 - 5*2. With a minus divergence the residual current is -8.
rate = parts[2][0]
assert abs(rate+6) < 1e-8 and abs((-5*2-4)-(-6)) == 8
def varying_w(x):
    return [x[0]**2+3*x[1]]
parts,_ = evaluate([0.5,-0.25],lambda x: sum(a*a for a in x)/2,
                   lambda x: [[1.,0.],[0.,1.]],varying_w)
# At this point w=-1/2. Row divergence of W is (+3,-1).
assert max(abs(a-b) for a,b in zip(parts[1],[2.875,-1.25])) < 1e-8
theta,_ = train(samples(91,12))
s1,s2,m1,m2 = [exp(v) for v in theta[:4]]
print(f"learned stationary precision {s1:.5f}, {s2:.5f} and upper skew band {theta[4]:.5f}")
assert max(abs(a-b) for a,b in zip([s1,s2,m1,m2,theta[4]],[1.5,2.5,.35,.60,.4])) < 2e-5
test = samples(18,15)
assert pair_loss(test,model(theta)) < pair_loss(test,model([0.,0.,-.6,-.1,.05]))
fitted = model(theta)
columns = [fitted(x)[0][2] for x in ([1.,0.],[0.,1.])]
cov_diag = [1/s1,1/s2]
sigma = fitted([0.,0.])[1]
for i in range(2):
    for j in range(2):
        # The fitted S^-1 satisfies the Lyapunov identity by construction.
        balance = (columns[j][i]*cov_diag[j] + cov_diag[i]*columns[i][j]
                   + sum(a*b for a,b in zip(sigma[i],sigma[j])))
        assert abs(balance) < 1e-12
# Exact second moments of the target stationary Gaussian for the EPR comparison.
cloud = [[sqrt(2/1.5),0.],[-sqrt(2/1.5),0.],[0.,sqrt(2/2.5)],[0.,-sqrt(2/2.5)]]
rate_global = stationary_epr(cloud,fitted)
expected = .4**2*(2.5/.35 + 1.5/.60)
assert abs(rate_global-expected) < 2e-5
print(f"structural covariance balance passed, stationary EPR {rate_global:.5f}, target {expected:.5f}")
print(f"state-dependent reversible drift {rate:.5f}, reversed divergence gives current/density -8")
