# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""Published linear benchmark. Integrate the pointwise EPR with exact Gaussian second moments."""
from math import sqrt
from pathlib import Path
import sys
sys.path.insert(0, str(Path(__file__).resolve().parents[1]/"reference"))
from fit import dot
from uidd import decompose, local_epr

# Rounded M, W_01, S printed by the authors' linear_plot.ipynb for Figure 2.
m = [[.02595867,-.01463836],[-.01463836,.02783796]]
s = [[33.97958886,-10.35827272],[-10.35827272,13.60290032]]
def chol2(a):
    x = sqrt(a[0][0])
    y = a[1][0]/x
    return [[x,0.],[y,sqrt(a[1][1]-y*y)]]

sigma = chol2([[2*a for a in row] for row in m])
det = s[0][0]*s[1][1]-s[0][1]**2
cov = [[s[1][1]/det,-s[1][0]/det],[-s[0][1]/det,s[0][0]/det]]
axes = list(zip(*chol2(cov)))
for lam, reported in [(1.,47.0598338),(.5,11.7649584),(.25,2.94123961),(.125,.735309903),(0.,0.)]:
    band = -0.12367745*lam
    weighted = []
    for axis in axes:
        for sign in (-1.,1.):
            z = [sign*sqrt(2)*a for a in axis]
            grad = [dot(row,z) for row in s]
            _,irr,_ = decompose(grad,sigma,[band],[0.,0.],[0.,0.])
            weighted.append(local_epr(irr,sigma)/4)
    total = sum(weighted)
    assert abs(total-reported) < 1e-5
    print(f"lambda {lam:.3f}, stationary EPR {total:.7f}, reported {reported:.7f}")
