"""MQG test 27 runner: exact quantum dynamics of the three-site boson ring with flux at the registered cells.

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, in the Fock basis
n_1 + n_2 + n_3 = N (dimension (N+1)(N+2)/2), propagated with scipy.sparse.linalg.expm_multiply on the grid
t = 0, 0.1, ..., 7.0. Initial state: SU(3) coherent state, uniform condensate plus a bias s * sigma_N along the
growing C3 mode, phase phi_b = 0 (sign +1) or pi (sign -1). Output per run: P_k(t), the probability that site k
holds the most atoms (ties shared), the norm error and the run facts.

The growing-mode vector v that sets the bias direction is read from the predictions file (cells) or stored below
(smoke point), never recomputed for the initial state: numpy.linalg.eig returns v with a platform-dependent overall phase,
which would rotate the bias. The runner checks that each stored v is a growing mode of the recomputed linear flow.

Modes:
  --selftest                      tiny-N checks (no test cell is computed)
  --smoke                         development point theta = pi/4, g = -1.4, N = 100 (not a test cell); compares
                                  with stored development values
  --deposit-doi 10.5281/zenodo.X  the registered runs (refuses to start without it)
Options: --outdir DIR (default mqg_test27_out), --predictions FILE (default mqg_test27_predictions.json)
"""
import sys, os, json, time, hashlib, platform, argparse, re, datetime
import numpy as np
import scipy
from scipy.sparse import coo_matrix
from scipy.sparse.linalg import expm_multiply
from scipy.special import gammaln

PREDICTIONS_SHA256 = "d579a8e72fd728e03a8675e1e9b727f27d8aff04efef2d98ae480d8a03eee994"
CELLS = {"C1": (0.45, -1.60), "C2": (0.90, -1.30), "C3": (0.98, -1.20), "C0": (0.00, -1.75)}
ORDER = [("C1", 400), ("C2", 400), ("C3", 400), ("C0", 400), ("C1", 800), ("C2", 800), ("C3", 800), ("C0", 800)]
S_BIAS, TMAX, NUM = 0.3, 7.0, 71
CHI = np.exp(2j*np.pi/3)

def eps(th, k): return -2*np.cos(th - 2*np.pi*k/3)
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):
    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 basis(N):
    st = [(n1, n2, N - n1 - n2) for n1 in range(N + 1) for n2 in range(N + 1 - n1)]
    return np.array(st), {s: i for i, s in enumerate(st)}
def hamiltonian(N, th, g, B, idx):
    U = 3*g/N; D = len(B); rows, cols, vals = [], [], []
    rows += list(range(D)); cols += list(range(D)); vals += list(0.5*U*np.sum(B*(B - 1), axis=1))
    for j in range(3):
        jp = (j + 1) % 3
        for i, s in enumerate(B):                      # a_{j+1}^dag a_j |s>
            if s[j] == 0: continue
            t = list(s); t[j] -= 1; t[jp] += 1
            k = idx[tuple(t)]; amp = -np.exp(1j*th)*np.sqrt(s[j]*(s[jp] + 1))
            rows += [k, i]; cols += [i, k]; vals += [amp, np.conj(amp)]
    return coo_matrix((vals, (rows, cols)), shape=(D, D)).tocsr()
def coherent(N, c, B):
    c = c/np.linalg.norm(c)
    logamp = 0.5*(gammaln(N + 1) - gammaln(B + 1).sum(1)) + (B*np.log(np.abs(c) + 1e-300)).sum(1)
    return np.exp(logamp + 1j*(B*np.angle(c)).sum(1))
def winner_weights(B):
    mx = B.max(1, keepdims=True); W = (B == mx).astype(float); return W/W.sum(1, keepdims=True)
def initial_mode(th, g, N, phib, v):
    rate, _, w = c3_mode(th, g)                      # |w| does not depend on the phase convention of the mode
    v = np.asarray(v, dtype=complex)
    sig = np.sqrt(np.sum(abs(w)**2)/(8*N))
    xb = 2*np.real(S_BIAS*sig*np.exp(1j*phib)*v)
    return np.ones(3)/np.sqrt(3) + xb[:3] + 1j*xb[3:], rate, sig, v, w
def check_mode(th, g, v):
    """Largest residual of J v = (lambda + i omega) v and of the C3 relation S v = chi v for a stored mode vector v."""
    rate, _, _ = c3_mode(th, g); 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
    v = np.asarray(v)/np.linalg.norm(v)
    return float(max(np.abs(Jm @ v - rate*v).max(), np.abs(S @ v - CHI*v).max()))
def run(N, th, g, phib, v):
    psi0, rate, sig, v, w = initial_mode(th, g, N, phib, v)
    B, idx = basis(N); H = hamiltonian(N, th, g, B, idx); Wt = winner_weights(B)
    states = expm_multiply(-1j*H, coherent(N, psi0, B), start=0.0, stop=TMAX, num=NUM, endpoint=True)
    P = np.array([(np.abs(st)**2) @ Wt for st in states])
    norm = np.array([np.sum(np.abs(st)**2) for st in states])
    return np.linspace(0, TMAX, NUM), P, norm, len(B)
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)

def sha256_file(p): return hashlib.sha256(open(p, "rb").read()).hexdigest()
def log(outdir, msg):
    line = f"{datetime.datetime.now(datetime.timezone.utc).strftime('%Y-%m-%d %H:%M:%S')} UTC  {msg}"
    print(line, flush=True); open(os.path.join(outdir, "log.txt"), "a").write(line + "\n")

def selftest():
    ok = True
    # 1. Fock-basis Hamiltonian against a direct second-quantised construction (cutoff N per site), N = 3
    N, th, g = 3, 0.7, -1.3; B, idx = basis(N); H = hamiltonian(N, th, g, B, idx).toarray()
    d = N + 1; a = np.diag(np.sqrt(np.arange(1, d)), 1); I = np.eye(d)
    ops = [np.kron(np.kron(a, I), I), np.kron(np.kron(I, a), I), np.kron(np.kron(I, I), a)]
    U = 3*g/N; Hf = sum(0.5*U*(o.conj().T @ o @ o.conj().T @ o - o.conj().T @ o) for o in ops)
    for j in range(3):
        T = -np.exp(1j*th)*ops[(j + 1) % 3].conj().T @ ops[j]; Hf = Hf + T + T.conj().T
    Ntot = sum(o.conj().T @ o for o in ops); sel = np.where(abs(np.diag(Ntot) - N) < 1e-9)[0]
    e1 = np.sort(np.linalg.eigvalsh(H)); e2 = np.sort(np.linalg.eigvalsh(Hf[np.ix_(sel, sel)]))
    print(f"selftest 1: spectrum N = 3, max difference {np.abs(e1 - e2).max():.1e}"); ok &= np.abs(e1 - e2).max() < 1e-10
    # 2. coherent state normalisation and mean occupations, N = 60
    N = 60; B, _ = basis(N); c = np.array([0.6, 0.5 + 0.2j, 0.3 - 0.4j]); psi = coherent(N, c, B)
    occ = (np.abs(psi)**2) @ B; c = c/np.linalg.norm(c)
    print(f"selftest 2: norm error {abs(np.sum(abs(psi)**2) - 1):.1e}, occupation error {np.abs(occ - N*abs(c)**2).max():.1e}")
    ok &= abs(np.sum(abs(psi)**2) - 1) < 1e-12 and np.abs(occ - N*abs(c)**2).max() < 1e-9
    # 3. a short run at a non-test point (N = 30): probabilities sum to 1, norm conserved
    t, P, norm, D = run(30, 0.3, -1.6, 0.0, c3_mode(0.3, -1.6)[1])
    print(f"selftest 3: N = 30 run, max |sum P - 1| {np.abs(P.sum(1) - 1).max():.1e}, max |norm - 1| {np.abs(norm - 1).max():.1e}")
    ok &= np.abs(P.sum(1) - 1).max() < 1e-10 and np.abs(norm - 1).max() < 1e-10
    print("SELFTEST", "PASS" if ok else "FAIL"); return ok

SMOKE_REF = {  # development point theta = pi/4, g = -1.4, N = 100 (development exact run of 29 Nov 2026)
    2.5: (0.08738176474140708, 2.05051736165179), 3.0: (0.07201093662403829, 1.9509381757885338),
    4.0: (0.07370252780291478, 1.8094818445687837), 5.0: (0.06080163692972757, 1.9031551174769854)}
SMOKE_V = [complex(a, b) for a, b in [  # growing-mode vector of the development point, as used for SMOKE_REF
    [0.5025317266632646, -8.546501238565809e-16], [-0.25126586333163303, -0.4352052414980441],
    [-0.2512658633316315, 0.4352052414980454], [0.28424495955103796, -2.277712226064466e-10],
    [-0.14212247997277494, -0.24616335575499362], [-0.14212247957826327, 0.24616335598276512]]]
def smoke():
    th, g, N = np.pi/4, -1.4, 100; t0 = time.time()
    res = check_mode(th, g, SMOKE_V); print(f"smoke: stored mode vector residual {res:.1e}"); ok = res < 1e-6
    t, Pp, n1, D = run(N, th, g, 0.0, SMOKE_V); _, Pm, n2, _ = run(N, th, g, np.pi, SMOKE_V); a, ph = harm(Pp, Pm)
    for tt, (a0, p0) in SMOKE_REF.items():
        i = int(round(tt/0.1)); da, dp = abs(a[i] - a0), abs(np.angle(np.exp(1j*(ph[i] - p0))))
        print(f"smoke t {tt}: a {a[i]:.8f} (ref {a0:.8f})  phase {ph[i]:+.8f} (ref {p0:+.8f})"); ok &= da < 1e-6 and dp < 1e-5
    print(f"smoke: dim {D}, max |norm - 1| {max(abs(n1 - 1).max(), abs(n2 - 1).max()):.1e}, {time.time() - t0:.0f} s")
    print("SMOKE", "PASS" if ok else "FAIL"); return ok

def main_runs(doi, outdir, pred_path):
    if not re.fullmatch(r"10\.5281/zenodo\.\d+", doi or ""): sys.exit("refused: --deposit-doi 10.5281/zenodo.<number> is required")
    if not os.path.exists(pred_path): sys.exit(f"refused: {pred_path} not found")
    if sha256_file(pred_path) != PREDICTIONS_SHA256: sys.exit("refused: predictions file SHA-256 differs from the plan")
    pred = json.load(open(pred_path)); runner_sha = sha256_file(os.path.abspath(__file__))
    for name, (th, g) in CELLS.items():           # frozen inputs recomputed and compared with the predictions file
        c = pred["cells"][name]; rate, v, w = c3_mode(th, g)
        if abs(c["theta"] - th) > 0 or abs(c["g"] - g) > 0 or abs(c["lam"] - rate.real) > 1e-9 or abs(c["omega"] - rate.imag) > 1e-9:
            sys.exit(f"refused: frozen input of {name} differs from the predictions file")
        for N in (400, 800):
            if abs(c["N"][str(N)]["sigma"] - np.sqrt(np.sum(abs(w)**2)/(8*N))) > 1e-12: sys.exit(f"refused: sigma of {name} N {N} differs")
        if check_mode(th, g, [complex(a, b) for a, b in c["v"]]) > 1e-6: sys.exit(f"refused: stored mode vector of {name} is not a growing mode")
    os.makedirs(os.path.join(outdir, "run_records"), exist_ok=True)
    log(outdir, f"start: runner SHA-256 {runner_sha}, DOI {doi}, numpy {np.__version__}, scipy {scipy.__version__}, python {platform.python_version()}")
    for name, N in ORDER:
        th, g = CELLS[name]
        for sign, phib in ((+1, 0.0), (-1, np.pi)):
            fn = os.path.join(outdir, "run_records", f"{name}_N{N}_{'p' if sign > 0 else 'm'}.json")
            if os.path.exists(fn):
                r = json.load(open(fn))
                if r.get("runner_sha256") == runner_sha and r.get("deposit_doi") == doi:
                    log(outdir, f"{name} N {N} sign {sign:+d}: already done, skipped"); continue
            t0 = time.time(); log(outdir, f"{name} N {N} sign {sign:+d}: started")
            t, P, norm, D = run(N, th, g, phib, [complex(a, b) for a, b in pred["cells"][name]["v"]])
            rec = dict(cell=name, theta=th, g=g, N=N, sign=sign, phi_b=phib, s_bias=S_BIAS, dim=D, t=t.tolist(), P=P.tolist(),
                       norm_err_max=float(np.abs(norm - 1).max()), psum_err_max=float(np.abs(P.sum(1) - 1).max()),
                       seconds=round(time.time() - t0, 1), runner_sha256=runner_sha, predictions_sha256=PREDICTIONS_SHA256,
                       deposit_doi=doi, numpy=np.__version__, scipy=scipy.__version__, python=platform.python_version(),
                       finished_utc=datetime.datetime.now(datetime.timezone.utc).isoformat())
            json.dump(rec, open(fn + ".tmp", "w")); os.replace(fn + ".tmp", fn)
            log(outdir, f"{name} N {N} sign {sign:+d}: done in {rec['seconds']} s, dim {D}, norm error {rec['norm_err_max']:.1e}")
    open(os.path.join(outdir, "runs_complete.txt"), "w").write("all 16 runs complete\n"); log(outdir, "all 16 runs complete")

if __name__ == "__main__":
    ap = argparse.ArgumentParser()
    ap.add_argument("--selftest", action="store_true"); ap.add_argument("--smoke", action="store_true")
    ap.add_argument("--deposit-doi"); ap.add_argument("--outdir", default="mqg_test27_out")
    ap.add_argument("--predictions", default="mqg_test27_predictions.json")
    A = ap.parse_args()
    if A.selftest: sys.exit(0 if selftest() else 1)
    if A.smoke: sys.exit(0 if smoke() else 1)
    main_runs(A.deposit_doi, A.outdir, A.predictions)
