"""MQG test 27: frozen predictions for the three-site boson ring with flux (three-outcome choice).

Model: H = -sum_j (e^{i theta} a_{j+1}^dag a_j + h.c.) + (U/2) sum_j n_j (n_j - 1), U = 3 g / N, g < 0.
Initial state: SU(3) coherent state, uniform condensate plus a bias of size s * sigma_N along the growing
C3 mode, at phase phi_b = 0 (run '+') and phi_b = pi (run '-').
Readout: P_k(t), the probability that site k holds the most atoms (ties shared). Observable: the first
harmonic of the bias-odd part, F = sum_k (P+_k - P-_k)/2 e^{-2 pi i k/3}, amplitude a = (2/3)|F|, phase arg F.

Rules (all classical, computed here before any exact run at a test cell):
  K  fixed-time projected-noise rule: each shot's pattern amplitude c (Gaussian, mean s sigma e^{i phi_b},
     sd sigma per component) grows along the unstable mode; the shot reaches radius r0 at t1 = ln(r0/|c|)/lambda
     with phase arg c + nu ln(r0/|c|); its leading site at time t is that of the noiseless trajectory started
     at radius r0 with that phase, after elapsed time t - t1. No fitted constant.
  B  frozen-outcome rule: as K until the noiseless trajectory first puts half the atoms on one site, after
     which the leading site stays at that site.
  L  linear rule: the leading site of the linear pattern, rotating at omega with no saturation.
  Z  no-lag rule (N differences only): the phase does not depend on N.
  W  truncated Wigner (TWA) ensemble of the same initial state (reported, not a rival).

Usage: python mqg_test27_predict.py            -> writes mqg_test27_predictions.json
       python mqg_test27_predict.py --selftest -> linear theory and quadrature checks only
"""
import json, sys, hashlib, platform
import numpy as np

CELLS = [  # name, theta, g   (chosen from linear theory and these classical predictors only)
    ("C1", 0.45, -1.60),
    ("C2", 0.90, -1.30),
    ("C3", 0.98, -1.20),
    ("C0", 0.00, -1.75),   # no flux: control
]
NS = (400, 800)
S_BIAS = 0.3
R0, NPHI, DT_MAP, REC, TAUMAX, PC = 1e-5, 1440, 0.005, 0.05, 20.0, 0.5
NR, NPH, UMAX = 1500, 1440, 8.0
TWA_M, TWA_DT, TWA_SEED, TWA_BATCH = 200000, 0.01, 27, 20
CHI = np.exp(2j*np.pi/3)

# ---------- linear theory ----------
def eps(th, k): return -2*np.cos(th - 2*np.pi*k/3)
def analytic(th, g):
    A1 = eps(th, 1) - eps(th, 0) + g; A2 = eps(th, 2) - eps(th, 0) + g
    d = g*g - ((A1 + A2)/2)**2
    return (np.sqrt(d) if d > 0 else 0.0), (eps(th, 1) - eps(th, 2))/2
def rhs(psi, th, u):
    hop = -(np.exp(1j*th)*np.roll(psi, 1, axis=-1) + np.exp(-1j*th)*np.roll(psi, -1, axis=-1))
    return -1j*(hop + u*np.abs(psi)**2*psi)
def jacobian(th, g):
    u = 3*g; psi0 = np.ones(3)/np.sqrt(3); mu = eps(th, 0) + g
    def f(x):
        p = x[:3] + 1j*x[3:]; r = rhs(p, th, u) + 1j*mu*p
        return np.concatenate([r.real, r.imag])
    x0 = np.concatenate([psi0.real, psi0.imag]); h = 1e-7
    return np.array([(f(x0 + h*e) - f(x0 - h*e))/(2*h) for e in np.eye(6)]).T
def c3_mode(th, g):
    """Growing C3 mode: right vector v, left vector w (w^T v = 1), rate lambda + i omega of c = w^T x."""
    Jm = jacobian(th, g)
    P = np.roll(np.eye(3), 1, axis=0); S = np.zeros((6, 6)); S[:3, :3] = P; S[3:, 3:] = P
    def span(A):
        ev, V = np.linalg.eig(A); lam = ev.real.max(); idx = np.where(abs(ev.real - lam) < 1e-8)[0]
        Bm = np.column_stack([V[:, i].real for i in idx] + [V[:, i].imag for i in idx])
        U_, sv, _ = np.linalg.svd(Bm, full_matrices=False); return U_[:, sv > 1e-8*sv.max()]
    out = []
    for A, Sm in ((Jm, S), (Jm.T, S.T)):
        Q = span(A); assert Q.shape[1] == 2
        e, y = np.linalg.eig(Q.T @ Sm @ Q); out.append(Q @ y[:, np.argmin(abs(e - CHI))])
    v, w = out; w = w/(w @ v)
    return complex(w @ Jm @ v), v, w
def sigma_N(w, N): return float(np.sqrt(np.sum(abs(w)**2)/(8*N)))

# ---------- noiseless maps ----------
def maps(th, g):
    """K[phi, tau] leading site of the noiseless run started at radius R0 with phase phi;
    tauc[phi] first time the largest site population reaches PC, kc[phi] that site."""
    rate, v, w = c3_mode(th, g)
    phis = (np.arange(NPHI) + 0.5)*2*np.pi/NPHI
    x = 2*np.real(R0*np.exp(1j*phis)[:, None]*v[None, :])
    psi = np.ones(3)/np.sqrt(3) + x[:, :3] + 1j*x[:, 3:]; psi /= np.linalg.norm(psi, axis=1)[:, None]
    u = 3*g; every = int(round(REC/DT_MAP)); Ks = []
    tauc = np.full(NPHI, np.inf); kc = np.full(NPHI, -1)
    for n in range(int(round(TAUMAX/DT_MAP)) + 1):
        p = np.abs(psi)**2
        hit = (kc < 0) & (p.max(1) >= PC); tauc[hit] = n*DT_MAP; kc[hit] = p.argmax(1)[hit]
        if n % every == 0: Ks.append(p.argmax(1))
        k1 = rhs(psi, th, u); k2 = rhs(psi + 0.5*DT_MAP*k1, th, u); k3 = rhs(psi + 0.5*DT_MAP*k2, th, u); k4 = rhs(psi + DT_MAP*k3, th, u)
        psi = psi + DT_MAP*(k1 + 2*k2 + 2*k3 + k4)/6
    K = np.array(Ks).T
    taus = np.arange(K.shape[1])*REC
    KB = np.where((taus[None, :] >= tauc[:, None]) & (kc[:, None] >= 0), kc[:, None], K)
    return phis, K, KB, tauc, kc, rate, v, w

def rule_P(Kmap, rate, sigma, phib, t, linear=False):
    lam, om = rate.real, rate.imag; nu = om/lam
    u = (np.arange(NR) + 0.5)*(UMAX/NR); ph = (np.arange(NPH) + 0.5)*2*np.pi/NPH
    U_, PH = np.meshgrid(u, ph, indexing='ij')
    dens = np.exp(-((U_*np.cos(PH) - S_BIAS*np.cos(phib))**2 + (U_*np.sin(PH) - S_BIAS*np.sin(phib))**2)/2)/(2*np.pi)*U_*(UMAX/NR)*(2*np.pi/NPH)
    if linear:
        phase = (PH + om*t) % (2*np.pi); kk = Kmap[np.minimum((phase/(2*np.pi)*NPHI).astype(int), NPHI - 1), 0]
        early = 0.0
    else:
        Lg = np.log(R0/(sigma*U_)); phase = (PH + nu*Lg) % (2*np.pi); tau = t - Lg/lam
        ip = np.minimum((phase/(2*np.pi)*NPHI).astype(int), NPHI - 1)
        it = np.clip(np.round(tau/REC).astype(int), 0, Kmap.shape[1] - 1)
        kk = Kmap[ip, it]; early = float(dens[tau < 0].sum())
        if np.any(tau/REC > Kmap.shape[1] - 1): raise RuntimeError("map too short")
    return np.array([dens[kk == k].sum() for k in range(3)]), early, float(dens.sum())

def harm(Pp, Pm):
    odd = (np.asarray(Pp) - np.asarray(Pm))/2; F = (odd*np.exp(-2j*np.pi*np.arange(3)/3)).sum(-1)
    return (2/3)*np.abs(F), np.angle(F)

# ---------- truncated Wigner ----------
def twa(th, g, N, phib, times, v, w):
    rng = np.random.default_rng([TWA_SEED, int(round(1000*th)), int(round(-1000*g)), N, int(phib > 1)])
    u = 3*g; sig = sigma_N(w, N)
    xb = 2*np.real(S_BIAS*sig*np.exp(1j*phib)*v)
    psi0 = np.ones(3)/np.sqrt(3) + xb[:3] + 1j*xb[3:]; psi0 /= np.linalg.norm(psi0)
    psi = psi0[None, :] + (rng.standard_normal((TWA_M, 3)) + 1j*rng.standard_normal((TWA_M, 3)))*np.sqrt(1/(4*N))
    f = lambda p: rhs(p, th, u) + 1j*u/N*p      # symmetric-ordering correction
    steps = {int(round(t/TWA_DT)): t for t in times}; out = {}
    for n in range(max(steps) + 1):
        if n in steps:
            lead = np.abs(psi).argmax(1)
            out[steps[n]] = np.array([np.bincount(b, minlength=3)/len(b) for b in np.array_split(lead, TWA_BATCH)])
        k1 = f(psi); k2 = f(psi + 0.5*TWA_DT*k1); k3 = f(psi + 0.5*TWA_DT*k2); k4 = f(psi + TWA_DT*k3)
        psi = psi + TWA_DT*(k1 + 2*k2 + 2*k3 + k4)/6
    return out          # t -> (batches, 3)

def window(lam, sig400):
    t1 = np.ceil(10*np.log(1/(np.sqrt(2)*sig400))/lam - 1e-9)/10
    return [round(float(t1 + 0.5*j), 1) for j in range(6)]

def selftest():
    ok = True
    for name, th, g in CELLS:
        lam, om = analytic(th, g); rate, v, w = c3_mode(th, g)
        e1, e2 = abs(rate.real - lam), abs(abs(rate.imag) - abs(om))
        print(f"{name}: lambda {lam:.6f} (mode {rate.real:.6f}), |omega| {abs(om):.6f} (mode {abs(rate.imag):.6f}), "
              f"w.v* {abs(w @ v.conj()):.1e}"); ok &= (e1 < 1e-6) and (e2 < 1e-6) and abs(w @ v.conj()) < 1e-8
    u = (np.arange(NR) + 0.5)*(UMAX/NR); ph = (np.arange(NPH) + 0.5)*2*np.pi/NPH
    U_, PH = np.meshgrid(u, ph, indexing='ij')
    m = (np.exp(-((U_*np.cos(PH) - S_BIAS)**2 + (U_*np.sin(PH))**2)/2)/(2*np.pi)*U_*(UMAX/NR)*(2*np.pi/NPH)).sum()
    print(f"quadrature weight {m:.12f}"); ok &= abs(m - 1) < 1e-5
    print("SELFTEST", "PASS" if ok else "FAIL"); return ok

def main():
    res = {"test": "MQG test 27", "model": "three-site boson ring with flux, attractive interaction",
           "settings": dict(S_BIAS=S_BIAS, R0=R0, NPHI=NPHI, DT_MAP=DT_MAP, REC=REC, TAUMAX=TAUMAX, PC=PC,
                            NR=NR, NPH=NPH, UMAX=UMAX, TWA_M=TWA_M, TWA_DT=TWA_DT, TWA_SEED=TWA_SEED, TWA_BATCH=TWA_BATCH),
           "software": dict(python=platform.python_version(), numpy=np.__version__),
           "cells": {}}
    for name, th, g in CELLS:
        lam_a, om_a = analytic(th, g)
        phis, K, KB, tauc, kc, rate, v, w = maps(th, g)
        lam = rate.real; times = window(lam, sigma_N(w, 400))
        segs = int(np.sum(kc != np.roll(kc, 1)))
        cell = dict(theta=th, g=g, lam=lam, omega=rate.imag, nu=rate.imag/lam, lam_analytic=lam_a, omega_analytic=om_a,
                    v=[[z.real, z.imag] for z in v], w=[[z.real, z.imag] for z in w],
                    times=times, first_collapse=dict(boundaries=segs, unresolved=int(np.sum(kc < 0)),
                    tau_c_min=float(tauc[kc >= 0].min()), tau_c_max=float(tauc[kc >= 0].max())), N={})
        for N in NS:
            sig = sigma_N(w, N); rows = []
            tw = {+1: twa(th, g, N, 0.0, times, v, w), -1: twa(th, g, N, np.pi, times, v, w)}
            for t in times:
                row = dict(t=t, rho=float(np.sqrt(2)*sig*np.exp(lam*t)))
                for rname, Km, lin in (("K", K, False), ("B", KB, False), ("L", K, True)):
                    Pp, ep, mp = rule_P(Km, rate, sig, 0.0, t, lin); Pm, em, mm = rule_P(Km, rate, sig, np.pi, t, lin)
                    a, ph = harm(Pp, Pm)
                    row[rname] = dict(a=float(a), ph=float(ph), Pp=Pp.tolist(), Pm=Pm.tolist(), early=max(ep, em), mass=min(mp, mm))
                bp, bm = tw[+1][t], tw[-1][t]
                a, ph = harm(bp.mean(0), bm.mean(0)); ab, phb = harm(bp, bm)
                row["W"] = dict(a=float(a), ph=float(ph), Pp=bp.mean(0).tolist(), Pm=bm.mean(0).tolist(),
                                a_se=float(ab.std(ddof=1)/np.sqrt(TWA_BATCH)),
                                ph_se=float(np.angle(np.exp(1j*(phb - ph))).std(ddof=1)/np.sqrt(TWA_BATCH)))
                rows.append(row)
            cell["N"][str(N)] = dict(sigma=sig, rows=rows)
        res["cells"][name] = cell
        print(name, "done", flush=True)
    s = json.dumps(res, indent=1, sort_keys=True)
    open("mqg_test27_predictions.json", "w").write(s)
    print("wrote mqg_test27_predictions.json  SHA-256", hashlib.sha256(s.encode()).hexdigest())

if __name__ == "__main__":
    if "--selftest" in sys.argv: sys.exit(0 if selftest() else 1)
    main()
