"""Independent dense check of the test-21 exact observables at N = 8 and 12 (not test points).
Builds J_A, J_B as (2j+1)^2 matrices directly in the flavour frame, evolves with expm, and compares
<|du|^2>(t), the slaving numerator and the n.J_A distribution with the runner's block code."""
import sys, math, numpy as np
from scipy.linalg import expm, eigh
sys.path.insert(0, sys.argv[1])
import mqg_test21_runner as R
def spin(j):
    m = np.arange(j, -j-1, -1.0)
    jp = np.diag(np.sqrt(j*(j+1)-m[1:]*(m[1:]+1)), 1)
    return (jp+jp.T)/2, (jp-jp.T)/2j, np.diag(m)
worst = 0
for N, th, mu in ((8, 0.07, 1.8), (12, 0.11, 2.3)):
    j = N//4; d = 2*j+1; I = np.eye(d)
    sx, sy, sz = spin(j)
    A = [np.kron(o, I) for o in (sx, sy, sz)]; Bm = [np.kron(I, o) for o in (sx, sy, sz)]
    Bv = (math.sin(2*th), 0, math.cos(2*th))
    J = [A[k]+Bm[k] for k in range(3)]
    H = sum(Bv[k]*(A[k]-Bm[k]) for k in range(3)) + (mu/N)*(J[0]@J[0]+J[1]@J[1]+J[2]@J[2] - 0.75*N*np.eye(d*d))
    up = np.zeros(d); up[0] = 1; dn = np.zeros(d); dn[-1] = 1
    psi0 = np.kron(up, dn).astype(complex)
    eps = math.sin(2*th)
    ts = [0.0, 0.7, 1.9, 3.3]
    tb = np.array(ts)
    ex = R.exact_series(N, mu, th, tb)
    for i, t in enumerate(ts):
        psi = expm(-1j*H*t) @ psi0
        e = lambda O: np.vdot(psi, O @ psi)
        du = A[0]/j - eps*np.eye(d*d); D2 = (du@du + A[1]@A[1]/j**2)
        du2 = e(D2).real
        Bp = Bm[0] + j*eps*np.eye(d*d) + 1j*Bm[1]; Am = A[0] - j*eps*np.eye(d*d) - 1j*A[1]
        num = e(Bp@Am)
        # n.J_A distribution
        phi = R.phi_plus(mu); n = (math.cos(phi), math.sin(phi), 0)
        nJ = n[0]*sx + n[1]*sy + n[2]*sz
        lam, W = eigh(nJ)
        Psi = psi.reshape(d, d)
        P = np.sum(np.abs(W.conj().T @ Psi)**2, axis=1)
        Pd = float(np.sum(P[lam > j*eps*math.cos(phi)]))
        Psi_b, Bk = R.exact_state(N, mu, th, t)
        lb, pb = R.ndotJ_distribution(Psi_b, j, R.flavour_n_blockframe(Bk.vth, phi))
        Pb = R.p_plus(lb, pb, j, j*eps*math.cos(phi))[0]
        dd = (abs(du2-ex['du2'][i]), abs(num-ex['num'][i]), abs(Pd-Pb), float(np.max(np.abs(np.sort(P)-np.sort(pb)))))
        worst = max(worst, *dd)
        print(f"N={N} t={t}: du2 {du2:.6f} vs {ex['du2'][i]:.6f}  num {num:.5f} vs {ex['num'][i]:.5f}  P+ {Pd:.6f} vs {Pb:.6f}  dists {dd[3]:.1e}")
print('worst difference', f'{worst:.1e}', 'OK' if worst < 1e-10 else 'FAIL')
