"""Wilson lattice gauge theory, SU(2), with a mass gap hunt. Round 5.

Method
------
- Gauge group SU(2). SU(2) is cheaper than SU(3) and shows the same
  confinement physics at this scale: a confining potential, a nonzero
  string tension, and a massive lightest glueball.
- Action: standard Wilson plaquette action, beta = 4 / g^2.
- Updates: Metropolis with checkerboard (even/odd) ordering, one
  direction and one parity per sub-sweep, so all links updated at once
  are independent of each other. Proposal is a random SU(2) rotation
  near the identity.
- Lattice: 8^4, periodic in all directions.
- One coupling, beta = 2.6, the fifth beta point of the series
  (2.2, 2.3, 2.4, 2.5 from rounds 1-3, 2.6 here), so the torelon
  series can be extended to five points and the continuum
  extrapolation re-attempted. Beta 2.6 is in the confined phase
  for N_t = 8.

Round 5 reuses the round 4 code unchanged: the run() function,
Lattice class, APE smearing (alpha 0.5, levels 0, 2, 4), GEVP,
jackknife machinery, thermalization (400 sweeps) and statistics
(1500 measurement sweeps, seed 20261120 + int(beta*100)) are the
same as round 4. Only main() differs: it runs beta 2.6 alone and
builds the five-point torelon series from the prior rounds' data
files (beta 2.2 from data/yang_mills.json, 2.3 and 2.4 from
data/yang_mills_r4.json, 2.5 from data/yang_mills_r3.json) plus the
new 2.6 point, then attempts the weighted linear continuum
extrapolation of m_tor / sqrt(sigma) vs sigma a^2. The fit method
is the same as rounds 2 and 3 and was verified to reproduce the
round 3 four-point fit exactly (c0 = 1.6345 +/- 0.8198,
c1 = 6.1915 +/- 3.4763, chi2 = 2.6478, dof 2) before this run.

Measurements per configuration
------------------------------
- Average plaquette, with jackknife error over blocks of sweeps.
- Wilson loops W(R, T) for R, T = 1..3, measured every 5 sweeps.
  Creutz ratios chi(R, T) from those loops, with jackknife errors.
  The string tension estimate is sigma a^2 = chi(2, 2).
- Gap hunt, method 1 (glueball): the time-slice plaquette operator
  O(t), averaged over the three spatial plaquette orientations in
  time slice t. Its connected correlator C(tau) = <O(0) O(tau)> -
  <O>^2 decays as exp(-m tau) with m the lightest 0++ glueball mass
  in lattice units. Effective mass m_eff(tau) = -ln(C(tau+1)/C(tau)).
  A second glueball channel uses D(t) = P_xy(t) - P_xz(t), whose
  vacuum expectation value vanishes by cubic symmetry, so its
  correlator needs no disconnected subtraction and measures the
  lightest 2++ tensor glueball.
- Gap hunt, method 2 (torelon): Polyakov loops winding around a
  SPATIAL direction, correlated in time. Their correlator
  C_T(tau) = <P_s(0) P_s*(tau)> decays as exp(-m_tor tau) with
  m_tor the torelon mass, m_tor = sigma * L_s in lattice units.
  Effective mass from the same log ratio. The time-like Polyakov
  loop correlator is kept as a separate confinement diagnostic:
  <P_t(0) P_t*(r)> decays as exp(-N_t V(r)) with V(r) the static
  quark potential.

Errors are jackknife errors over blocks of 50 consecutive
measurements. A finite-spacing, finite-volume lattice gap estimate
is not a proof of the continuum mass gap. It is a measurement of
what the data says at these spacings, nothing more.

Run: python3 wilson_lattice_r5.py
Output: prints a summary and writes data/yang_mills_r5.json next to
the millennium-lab directory layout (../data/yang_mills_r5.json).
"""

import json
import math
import os
import time

import numpy as np

# Pauli matrices, as complex arrays.
SIGMA = np.array([
    [[0, 1], [1, 0]],
    [[0, -1j], [1j, 0]],
    [[1, 0], [0, -1]],
], dtype=np.complex128)

IDENTITY = np.eye(2, dtype=np.complex128)

# Round 4: APE smearing of the spatial links for the 0++ glueball
# operator. Basis levels are 0, 2 and 4 smearing steps at alpha 0.5:
# level 0 is the plain operator, levels 2 and 4 spread the operator
# over roughly 1.4 and 2 lattice spacings. The variational analysis
# uses all three levels as its operator basis.
SMEAR_LEVELS = (0, 2, 4)
APE_ALPHA = 0.5


def dag(a):
    """Conjugate transpose over the last two axes."""
    return np.conjugate(np.swapaxes(a, -1, -2))


def rand_su2_near(n, eps, rng):
    """n random SU(2) matrices near the identity.

    Rotation angle eps * |v| about axis v / |v|, v standard normal.
    """
    v = rng.normal(size=(n, 3))
    norm = np.linalg.norm(v, axis=1)
    angle = eps * norm
    axis = np.zeros_like(v)
    good = norm > 0
    axis[good] = v[good] / norm[good, None]
    c = np.cos(angle)
    s = np.sin(angle)
    # n . sigma
    nsigma = (
        axis[:, 0, None, None] * SIGMA[0]
        + axis[:, 1, None, None] * SIGMA[1]
        + axis[:, 2, None, None] * SIGMA[2]
    )
    return c[:, None, None] * IDENTITY + 1j * s[:, None, None] * nsigma


class Lattice:
    def __init__(self, size, beta, rng):
        self.L = size
        self.beta = beta
        self.rng = rng
        # Links U[mu][x, y, z, t], each a 2x2 SU(2) matrix.
        # Cold start: all identity.
        shape = (4, size, size, size, size, 2, 2)
        self.U = np.zeros(shape, dtype=np.complex128)
        self.U[:] = IDENTITY
        # Parity mask: (x + y + z + t) % 2 == 0.
        idx = np.indices((size, size, size, size))
        self.parity = (idx.sum(axis=0) % 2 == 0)
        self.accepted = 0
        self.proposed = 0

    def staples(self, mu):
        """Sum of staples for links in direction mu, at every site.

        Staple sum S satisfies: link action = -(beta/2) Re Tr[U S^dag].
        """
        U = self.U
        total = np.zeros_like(U[mu])
        for nu in range(4):
            if nu == mu:
                continue
            # Forward plaquette staple.
            t1 = np.matmul(
                np.matmul(U[nu], np.roll(U[mu], -1, axis=nu)),
                dag(np.roll(U[nu], -1, axis=mu)),
            )
            # Backward plaquette staple.
            unu_m = np.roll(U[nu], 1, axis=nu)  # U_nu(x - nu)
            umu_m = np.roll(U[mu], 1, axis=nu)  # U_mu(x - nu)
            t2 = np.matmul(
                np.matmul(dag(unu_m), umu_m),
                np.roll(unu_m, -1, axis=mu),
            )
            total = total + t1 + t2
        return total

    def sweep(self, eps=0.35):
        """One Metropolis sweep: all 4 directions, both parities.

        Staples are recomputed for each (direction, parity) pair:
        updating one parity changes the links the other parity's
        staples depend on, so a staple sum computed before the first
        parity update would be stale for the second.
        """
        for mu in range(4):
            for even in (True, False):
                stap = self.staples(mu)
                mask = self.parity if even else ~self.parity
                u_old = self.U[mu][mask]
                s_old = stap[mask]
                n = u_old.shape[0]
                x = rand_su2_near(n, eps, self.rng)
                u_new = np.matmul(x, u_old)
                ds = -0.5 * self.beta * np.real(
                    np.trace(
                        np.matmul(u_new - u_old, dag(s_old)),
                        axis1=-2, axis2=-1,
                    )
                )
                # Accept with probability min(1, exp(-dS)).
                accept = (ds <= 0) | (
                    self.rng.random(n) < np.exp(-np.where(ds > 0, ds, 0.0))
                )
                u_old[accept] = u_new[accept]
                self.U[mu][mask] = u_old
                self.accepted += int(accept.sum())
                self.proposed += n

    def plaquette(self):
        """Average (1/2) Re Tr U_p over all 6 orientations, all sites."""
        U = self.U
        total = 0.0
        count = 0
        for mu in range(4):
            for nu in range(mu + 1, 4):
                p = np.matmul(
                    np.matmul(U[mu], np.roll(U[nu], -1, axis=mu)),
                    np.matmul(
                        dag(np.roll(U[mu], -1, axis=nu)),
                        dag(U[nu]),
                    ),
                )
                total += float(np.real(np.trace(p, axis1=-2, axis2=-1)).sum())
                count += p.shape[0] * p.shape[1] * p.shape[2] * p.shape[3]
        return total / (2.0 * count)

    def plaquette_by_time(self):
        """O(t): spatial plaquette average in time slice t, shape (L,)."""
        return self.plaquette_by_time_orientation().mean(axis=0)

    def plaquette_by_time_orientation(self):
        """Per-orientation spatial plaquette average, shape (3, L).

        Row 0 is the xy plane, row 1 the xz plane, row 2 the yz plane,
        each averaged over the spatial volume at fixed time t.
        """
        U = self.U
        out = np.zeros((3, self.L))
        row = 0
        for mu in range(3):
            for nu in range(mu + 1, 3):
                p = np.matmul(
                    np.matmul(U[mu], np.roll(U[nu], -1, axis=mu)),
                    np.matmul(
                        dag(np.roll(U[mu], -1, axis=nu)),
                        dag(U[nu]),
                    ),
                )
                # p axes are (x, y, z, t); average over x, y, z.
                out[row] += 0.5 * np.real(np.trace(p, axis1=-2, axis2=-1)).mean(axis=(0, 1, 2))
                row += 1
        return out

    def transporter(self, mu, length):
        """Product of `length` links in direction mu starting at each site."""
        result = np.zeros_like(self.U[mu])
        result[:] = IDENTITY
        for i in range(length):
            result = np.matmul(result, np.roll(self.U[mu], -i, axis=mu))
        return result

    def wilson_loop(self, r, t):
        """W(R, T) averaged over all sites and all 6 mu-nu planes."""
        total = 0.0
        count = 0
        for mu in range(4):
            for nu in range(mu + 1, 4):
                a = self.transporter(mu, r)
                b = np.roll(self.transporter(nu, t), -r, axis=mu)
                c = dag(np.roll(self.transporter(mu, r), -t, axis=nu))
                d = dag(self.transporter(nu, t))
                loop = np.matmul(np.matmul(a, b), np.matmul(c, d))
                total += float(np.real(np.trace(loop, axis1=-2, axis2=-1)).sum())
                count += loop.shape[0] * loop.shape[1] * loop.shape[2] * loop.shape[3]
        return total / (2.0 * count)

    def polyakov_loops(self):
        """Traced Polyakov loop at each spatial site, shape (L, L, L).

        The time direction is mu = 3 (site axis 3). The loop is the
        ordered product of the mu = 3 links along time at fixed
        spatial site (x, y, z).
        """
        m = np.zeros((self.L, self.L, self.L, 2, 2), dtype=np.complex128)
        m[:] = IDENTITY
        u3 = self.U[3]  # axes (x, y, z, t)
        for t in range(self.L):
            m = np.matmul(m, u3[:, :, :, t])
        return np.trace(m, axis1=-2, axis2=-1)

    def polyakov_spatial(self, mu):
        """Traced Polyakov loop winding around spatial direction mu.

        mu is 0, 1, or 2 (x, y, z). Returns a complex array indexed
        by the two other spatial axes and time, e.g. (y, z, t) for
        mu = 0. Its time correlator decays with the torelon mass.
        """
        u = np.moveaxis(self.U[mu], mu, 0)  # winding axis first
        m = np.zeros_like(u[0])
        m[:] = IDENTITY
        for i in range(self.L):
            m = np.matmul(m, u[i])
        return np.trace(m, axis1=-2, axis2=-1)


def spatial_staples(U3, mu):
    """Staple sum for spatial links in direction mu, spatial planes only.

    U3 holds the three spatial link directions, shape (3, L, L, L, L, 2, 2).
    Only the other two spatial directions enter, so a staple never leaves
    its time slice: smearing stays local in time, which is what a
    time-slice glueball operator needs.
    """
    total = np.zeros_like(U3[mu])
    for nu in range(3):
        if nu == mu:
            continue
        t1 = np.matmul(
            np.matmul(U3[nu], np.roll(U3[mu], -1, axis=nu)),
            dag(np.roll(U3[nu], -1, axis=mu)),
        )
        unu_m = np.roll(U3[nu], 1, axis=nu)
        umu_m = np.roll(U3[mu], 1, axis=nu)
        t2 = np.matmul(
            np.matmul(dag(unu_m), umu_m),
            np.roll(unu_m, -1, axis=mu),
        )
        total = total + t1 + t2
    return total


def project_su2(A):
    """Project a 2x2 matrix field onto SU(2).

    A sum of SU(2) matrices has the form a0 I + i a . sigma, so its
    determinant is real and non-negative; dividing by sqrt(det) gives
    the SU(2) matrix. Verified in the benchmark: det stays 1 and
    U U^dag - I stays at 1e-16 after smearing.
    """
    det = A[..., 0, 0] * A[..., 1, 1] - A[..., 0, 1] * A[..., 1, 0]
    d = np.real(det)
    bad = d <= 0
    if bad.any():
        d = np.where(bad, 1.0, d)
    return A / np.sqrt(d)[..., None, None]


def ape_step(U3, alpha):
    """One APE smearing step on the spatial links.

    U' = Proj[(1 - alpha) U + (alpha / 4) sum of the 4 spatial staples].
    Four staples because only the two other spatial directions contribute.
    """
    out = np.empty_like(U3)
    for mu in range(3):
        stap = spatial_staples(U3, mu)
        mat = (1.0 - alpha) * U3[mu] + (alpha / 4.0) * stap
        out[mu] = project_su2(mat)
    return out


def plaquette_by_time_smeared(U3):
    """Per-orientation spatial plaquette average by time slice, from
    smeared spatial links U3. Same formula as
    Lattice.plaquette_by_time_orientation, applied to the smeared links.
    At zero smearing steps this reproduces the plain operator exactly
    (checked: max abs difference 0.0 in the benchmark).
    """
    out = np.zeros((3, U3.shape[1]))
    row = 0
    for mu in range(3):
        for nu in range(mu + 1, 3):
            p = np.matmul(
                np.matmul(U3[mu], np.roll(U3[nu], -1, axis=mu)),
                np.matmul(
                    dag(np.roll(U3[mu], -1, axis=nu)),
                    dag(U3[nu]),
                ),
            )
            out[row] += 0.5 * np.real(np.trace(p, axis1=-2, axis2=-1)).mean(axis=(0, 1, 2))
            row += 1
    return out


def gevp_ground(C0, C1):
    """Largest generalized eigenvalue and vector of C1 v = lam C0 v.

    C0 and C1 are symmetric (n, n) correlation matrices at two time
    separations. Solved by Cholesky: C0 = L L^T, then the standard
    eigenproblem for L^-1 C1 L^-T. The vector is normalized to
    v^T C0 v = 1. Returns (lam, v), or (nan, None) when C0 is not
    numerically positive definite even after a small ridge is added.
    """
    C0 = 0.5 * (C0 + C0.T)
    C1 = 0.5 * (C1 + C1.T)
    n = C0.shape[0]
    scale = float(np.trace(C0)) / n if n else 1.0
    for ridge in (0.0, 1e-12, 1e-10, 1e-8):
        try:
            L = np.linalg.cholesky(C0 + ridge * scale * np.eye(n))
            break
        except np.linalg.LinAlgError:
            continue
    else:
        return float("nan"), None
    Linv = np.linalg.inv(L)
    M = Linv @ C1 @ Linv.T
    M = 0.5 * (M + M.T)
    vals, vecs = np.linalg.eigh(M)
    lam = float(vals[-1])
    v = np.linalg.solve(L.T, vecs[:, -1])
    nrm = float(v @ C0 @ v)
    if nrm <= 0:
        return float("nan"), None
    return lam, v / math.sqrt(nrm)


def jackknife_error(block_values, func):
    """Jackknife error of func applied to block-deleted means.

    block_values: array shape (n_blocks, ...) of per-block means of
    the raw per-measurement quantities. func takes the array of
    per-block means and returns a scalar computed from the grand
    mean. The jackknife deletes one block at a time and recomputes
    func. The variance is ((m - 1) / m) * sum((theta_i - mean)^2)
    over the m finite delete-one estimates theta_i. Delete-one
    estimates that are not finite (a correlator going non-positive
    in that subsample) are dropped; if fewer than two survive, the
    error is reported as NaN.
    """
    n = block_values.shape[0]
    full = func(block_values.mean(axis=0))
    estimates = []
    for b in range(n):
        keep = np.delete(block_values, b, axis=0)
        estimates.append(func(keep.mean(axis=0)))
    estimates = np.array(estimates, dtype=float)
    good = estimates[np.isfinite(estimates)]
    m = good.size
    if m < 2:
        return full, float("nan")
    var = ((m - 1.0) / m) * np.sum((good - good.mean()) ** 2)
    return full, math.sqrt(var)


def safe_meff(c0, c1):
    """-ln(c1 / c0), or NaN when the ratio is not positive."""
    if c0 is None or c1 is None:
        return float("nan")
    if c0 <= 0 or c1 <= 0:
        return float("nan")
    return -math.log(c1 / c0)


def run(beta, size=8, n_therm=400, n_meas=1500, seed=20261120, eps=0.35):
    rng = np.random.default_rng(seed + int(beta * 100))
    lat = Lattice(size, beta, rng)
    t0 = time.time()
    # Thermalization.
    for i in range(n_therm):
        lat.sweep(eps=eps)
        if (i + 1) % 100 == 0:
            print(f"  beta={beta} therm sweep {i + 1}/{n_therm} "
                  f"plaquette={lat.plaquette():.4f}", flush=True)
    therm_seconds = time.time() - t0

    # Measurement.
    plaq = []
    ot_ori = []      # per-orientation time-slice plaquette, per config
    ot_smear = []    # smeared 0++ operators, per config: (n_levels, 3, L)
    ploops = []      # time-like Polyakov loops, per config
    pspat = []       # spatial Polyakov loops, per config
    wilson = []      # Wilson loops W(R, T), every 5 sweeps
    for i in range(n_meas):
        lat.sweep(eps=eps)
        plaq.append(lat.plaquette())
        ot_ori.append(lat.plaquette_by_time_orientation())
        # Round 4: APE-smeared spatial links, alpha 0.5, levels 0, 2, 4
        # smearing steps. Level 0 is the plain operator, recomputed
        # from the unsmeared links; levels 2 and 4 use the iteratively
        # smeared links. The operator at each level is the mean over
        # the three spatial plaquette orientations in time slice t.
        cur = lat.U[:3].copy()
        step = 0
        levels = []
        for lv in SMEAR_LEVELS:
            while step < lv:
                cur = ape_step(cur, APE_ALPHA)
                step += 1
            levels.append(plaquette_by_time_smeared(cur))
        ot_smear.append(np.array(levels))
        ploops.append(lat.polyakov_loops())
        pspat.append([lat.polyakov_spatial(mu) for mu in (0, 1, 2)])
        if (i + 1) % 300 == 0:
            print(f"  beta={beta} meas sweep {i + 1}/{n_meas}", flush=True)
        if i % 5 == 0:
            wilson.append({
                (r, t): lat.wilson_loop(r, t)
                for r in (1, 2, 3) for t in (1, 2, 3)
            })
    meas_seconds = time.time() - t0 - therm_seconds
    total_seconds = time.time() - t0

    plaq = np.array(plaq)
    ot_ori = np.array(ot_ori)            # (n_meas, 3, L)
    ot = ot_ori.mean(axis=1)             # (n_meas, L), 0++ operator
    ploops = np.array(ploops)            # (n_meas, L, L, L) complex
    pspat = np.array(pspat)              # (n_meas, 3, L, L, L) complex
    n_blocks = 30 if n_meas >= 300 else 5
    block = n_meas // n_blocks

    # Plaquette average and jackknife error over blocks of sweeps.
    plaq_blocks = plaq[: n_blocks * block].reshape(n_blocks, block).mean(axis=1)
    plaq_mean, plaq_err = jackknife_error(
        plaq_blocks, lambda v: float(np.mean(v)))
    plaq_mean = float(plaq_mean)
    plaq_err = float(plaq_err)

    # Wilson loops and Creutz ratios, jackknife over blocks of the
    # every-5-sweeps measurements.
    wkeys = [(r, t) for r in (1, 2, 3) for t in (1, 2, 3)]
    w_arr = np.array([[w[k] for k in wkeys] for w in wilson])
    n_w = w_arr.shape[0]
    w_blocks_n = 20 if n_w >= 100 else 5
    w_block = n_w // w_blocks_n
    w_blockmeans = w_arr[: w_blocks_n * w_block].reshape(
        w_blocks_n, w_block, len(wkeys)).mean(axis=1)
    w_mean = dict(zip(wkeys, w_arr.mean(axis=0)))

    def creutz(wvec, r, t):
        # chi(R, T) = -ln[W(R,T) W(R-1,T-1) / (W(R,T-1) W(R-1,T))]
        i = {k: j for j, k in enumerate(wkeys)}
        num = wvec[i[(r, t)]] * wvec[i[(r - 1, t - 1)]]
        den = wvec[i[(r, t - 1)]] * wvec[i[(r - 1, t)]]
        return -math.log(num / den)

    creutz_ratios = {}
    for (r, t) in ((2, 2), (2, 3), (3, 3)):
        full, err = jackknife_error(
            w_blockmeans, lambda v, r=r, t=t: creutz(v, r, t))
        creutz_ratios[f"chi({r},{t})"] = {
            "value": float(full),
            "error": float(err) if math.isfinite(err) else None}

    # String tension from chi(2, 2).
    st = creutz_ratios["chi(2,2)"]

    # Gap hunt 1: glueball from plaquette-plaquette correlator.
    # Per-config connected correlator contributions:
    # c[tau] = mean_t O(t) O(t + tau); C(tau) = <c[tau]> - <O>^2.
    max_tau = 4
    c_tau = np.zeros((n_meas, max_tau + 1))
    o_mean_per = ot.mean(axis=1)
    for tau in range(max_tau + 1):
        c_tau[:, tau] = np.mean(
            ot * np.roll(ot, -tau, axis=1), axis=1)
    # Stack per-config [c_tau..., o_mean] for jackknife.
    raw = np.concatenate([c_tau, o_mean_per[:, None]], axis=1)
    raw_blocks = raw[: n_blocks * block].reshape(n_blocks, block, raw.shape[1]).mean(axis=1)

    def c_of(blockmean):
        cmean = blockmean[: max_tau + 1]
        omea = blockmean[max_tau + 1]
        return cmean - omea ** 2

    def meff_glue(blockmean, tau):
        c = c_of(blockmean)
        return safe_meff(c[tau], c[tau + 1])

    c_full = c_of(raw_blocks.mean(axis=0))
    glue_masses = {}
    for tau in (0, 1, 2):
        if c_full[tau] > 0 and c_full[tau + 1] > 0:
            full, err = jackknife_error(
                raw_blocks, lambda v, tau=tau: meff_glue(v, tau))
            glue_masses[f"m_eff({tau})"] = {
                "value": float(full),
                "error": float(err) if math.isfinite(err) else None}
        else:
            glue_masses[f"m_eff({tau})"] = {
                "value": None, "error": None,
                "note": "correlator not positive at this separation"}

    # Gap hunt 1b: tensor (2++) glueball from an operator with zero
    # vacuum expectation value, D(t) = P_xy(t) - P_xz(t). Cubic
    # symmetry forces <D> = 0, so its correlator needs no disconnected
    # subtraction: C_D(tau) = <D(0) D(tau)> decays as exp(-m_2 tau).
    d_op = ot_ori[:, 0, :] - ot_ori[:, 1, :]
    d_tau = np.zeros((n_meas, max_tau + 1))
    for tau in range(max_tau + 1):
        d_tau[:, tau] = np.mean(
            d_op * np.roll(d_op, -tau, axis=1), axis=1)
    d_blocks = d_tau[: n_blocks * block].reshape(
        n_blocks, block, max_tau + 1).mean(axis=1)

    def meff_tens(blockmean, tau):
        return safe_meff(blockmean[tau], blockmean[tau + 1])

    d_full = d_blocks.mean(axis=0)
    tens_masses = {}
    for tau in (0, 1, 2):
        if d_full[tau] > 0 and d_full[tau + 1] > 0:
            full, err = jackknife_error(
                d_blocks, lambda v, tau=tau: meff_tens(v, tau))
            tens_masses[f"m_eff({tau})"] = {
                "value": float(full),
                "error": float(err) if math.isfinite(err) else None}
        else:
            tens_masses[f"m_eff({tau})"] = {
                "value": None, "error": None,
                "note": "correlator not positive at this separation"}

    # Round 4: smeared 0++ operators and the variational (GEVP) analysis.
    # ot_smear holds, per config, the mean-over-orientations plaquette
    # operator at each smearing level. Per-level connected correlators
    # use the same jackknife machinery as the plain operator. The
    # variational basis is the three levels; the GEVP C(1) v = lam C(0) v
    # gives the ground state, and the projected correlator
    # v^T C(tau) v gives its effective masses.
    ot_sm = np.array(ot_smear)           # (n_meas, n_levels, 3, L)
    n_levels = ot_sm.shape[1]
    ot_sm_op = ot_sm.mean(axis=2)        # (n_meas, n_levels, L)
    smear_vev = ot_sm_op.mean(axis=(0, 2))
    max_tau_g = 3

    def c_of_l(blockmean):
        cmean = blockmean[: max_tau_g + 1]
        omea = blockmean[max_tau_g + 1]
        return cmean - omea ** 2

    def meff_l(blockmean, tau):
        c = c_of_l(blockmean)
        return safe_meff(c[tau], c[tau + 1])

    smear_correlators = {}
    smear_masses = {}
    for li, lv in enumerate(SMEAR_LEVELS):
        o = ot_sm_op[:, li, :]
        c_tau_l = np.zeros((n_meas, max_tau_g + 1))
        o_mean_l = o.mean(axis=1)
        for tau in range(max_tau_g + 1):
            c_tau_l[:, tau] = np.mean(o * np.roll(o, -tau, axis=1), axis=1)
        raw_l = np.concatenate([c_tau_l, o_mean_l[:, None]], axis=1)
        raw_l_blocks = raw_l[: n_blocks * block].reshape(
            n_blocks, block, raw_l.shape[1]).mean(axis=1)
        c_full_l = c_of_l(raw_l_blocks.mean(axis=0))
        smear_correlators[f"level_{lv}"] = {
            f"C({tau})": float(c_full_l[tau]) for tau in range(max_tau_g + 1)}
        masses_l = {}
        for tau in (0, 1, 2):
            if c_full_l[tau] > 0 and c_full_l[tau + 1] > 0:
                full, err = jackknife_error(
                    raw_l_blocks, lambda v, tau=tau: meff_l(v, tau))
                masses_l[f"m_eff({tau})"] = {
                    "value": float(full),
                    "error": float(err) if math.isfinite(err) else None}
            else:
                masses_l[f"m_eff({tau})"] = {
                    "value": None, "error": None,
                    "note": "correlator not positive at this separation"}
        smear_masses[f"level_{lv}"] = masses_l

    # Variational basis: cross-correlators C_ij(tau) between levels.
    cij = np.zeros((n_meas, n_levels, n_levels, max_tau_g + 1))
    for tau in range(max_tau_g + 1):
        for i in range(n_levels):
            for j in range(n_levels):
                cij[:, i, j, tau] = np.mean(
                    ot_sm_op[:, i, :] * np.roll(ot_sm_op[:, j, :], -tau, axis=1),
                    axis=1)
    oi = ot_sm_op.mean(axis=2)  # (n_meas, n_levels)
    raw_g = np.concatenate([cij.reshape(n_meas, -1), oi], axis=1)
    raw_g_blocks = raw_g[: n_blocks * block].reshape(
        n_blocks, block, raw_g.shape[1]).mean(axis=1)
    n_cij = n_levels * n_levels * (max_tau_g + 1)

    def cmat_of(blockmean):
        c = blockmean[:n_cij].reshape(n_levels, n_levels, max_tau_g + 1)
        o = blockmean[n_cij:n_cij + n_levels]
        C = np.zeros((n_levels, n_levels, max_tau_g + 1))
        for tau in range(max_tau_g + 1):
            C[:, :, tau] = c[:, :, tau] - np.outer(o, o)
            C[:, :, tau] = 0.5 * (C[:, :, tau] + C[:, :, tau].T)
        return C

    def gevp_projected_meff(blockmean, tau):
        C = cmat_of(blockmean)
        lam, v = gevp_ground(C[:, :, 0], C[:, :, 1])
        if v is None or not math.isfinite(lam) or lam <= 0 or lam >= 1:
            return float("nan")
        cp = np.array([float(v @ C[:, :, t] @ v)
                       for t in range(max_tau_g + 1)])
        return safe_meff(cp[tau], cp[tau + 1])

    def gevp_mass_of(blockmean):
        C = cmat_of(blockmean)
        lam, v = gevp_ground(C[:, :, 0], C[:, :, 1])
        if v is None or not math.isfinite(lam) or lam <= 0 or lam >= 1:
            return float("nan")
        return -math.log(lam)

    C_full = cmat_of(raw_g_blocks.mean(axis=0))
    lam_full, v_full = gevp_ground(C_full[:, :, 0], C_full[:, :, 1])
    var_lambda = None
    var_eigenvector = None
    cp_full = None
    if v_full is not None and math.isfinite(lam_full) and 0 < lam_full < 1:
        var_lambda = float(lam_full)
        var_eigenvector = [float(x) for x in v_full]
        cp_full = np.array([float(v_full @ C_full[:, :, t] @ v_full)
                            for t in range(max_tau_g + 1)])
        var_masses = {}
        for tau in (0, 1, 2):
            if cp_full[tau] > 0 and cp_full[tau + 1] > 0:
                full, err = jackknife_error(
                    raw_g_blocks,
                    lambda v, tau=tau: gevp_projected_meff(v, tau))
                var_masses[f"m_eff({tau})"] = {
                    "value": float(full),
                    "error": float(err) if math.isfinite(err) else None}
            else:
                var_masses[f"m_eff({tau})"] = {
                    "value": None, "error": None,
                    "note": "projected correlator not positive at this separation"}
        # GEVP eigenvalue mass equals the projected m_eff(0) by
        # construction; report it separately with its own jackknife.
        full_m, err_m = jackknife_error(raw_g_blocks, gevp_mass_of)
        var_ground = {"value": float(full_m),
                      "error": float(err_m) if math.isfinite(err_m) else None}
    else:
        var_masses = {f"m_eff({tau})": {"value": None, "error": None,
                      "note": "GEVP did not yield a usable ground state"}
                      for tau in (0, 1, 2)}
        var_ground = {"value": None, "error": None,
                      "note": "GEVP did not yield a usable ground state"}

    # Gap hunt 2: torelon from SPATIAL Polyakov loop correlator.
    # Per-config ct[tau] = mean over directions, transverse sites and
    # time of P_s(t) conj(P_s(t + tau)); C_T(tau) = <ct[tau]> -
    # |<P_s>|^2. In the confined phase <P_s> vanishes and C_T decays
    # as exp(-m_tor tau).
    ct = np.zeros((n_meas, max_tau + 1))
    psmean = np.zeros(n_meas, dtype=np.complex128)
    for i in range(n_meas):
        ps = pspat[i]  # (3, L, L, L), axes (dir, trans1, trans2, t)
        psmean[i] = ps.mean()
        for tau in range(max_tau + 1):
            ct[i, tau] = np.real(np.mean(
                ps * np.conj(np.roll(ps, -tau, axis=3))))
    raw3 = np.concatenate(
        [ct, psmean.real[:, None], psmean.imag[:, None]], axis=1)
    raw3_blocks = raw3[: n_blocks * block].reshape(
        n_blocks, block, raw3.shape[1]).mean(axis=1)

    def ct_of(blockmean):
        cmean = blockmean[: max_tau + 1]
        pm = blockmean[max_tau + 1] + 1j * blockmean[max_tau + 2]
        return cmean - abs(pm) ** 2

    def meff_tor(blockmean, tau):
        c = ct_of(blockmean)
        return safe_meff(c[tau], c[tau + 1])

    ct_full = ct_of(raw3_blocks.mean(axis=0))
    tor_masses = {}
    for tau in (0, 1, 2):
        if ct_full[tau] > 0 and ct_full[tau + 1] > 0:
            full, err = jackknife_error(
                raw3_blocks, lambda v, tau=tau: meff_tor(v, tau))
            tor_masses[f"m_eff({tau})"] = {
                "value": float(full),
                "error": float(err) if math.isfinite(err) else None}
        else:
            tor_masses[f"m_eff({tau})"] = {
                "value": None, "error": None,
                "note": "correlator not positive at this separation"}

    # Confinement diagnostic: time-like Polyakov loop correlator.
    # Per-config cp[r] = mean over sites of P_t(x) conj(P_t(x + r))
    # along x, and pmean = mean of P_t over sites. The correlator
    # decays as exp(-N_t V(r)) with V(r) the static quark potential,
    # so V(1) = -ln(C_P(1) / C_P(0)) / L when C_P(1) is positive.
    max_r = 4
    cp = np.zeros((n_meas, max_r + 1))
    pmean = np.zeros(n_meas, dtype=np.complex128)
    for i in range(n_meas):
        p = ploops[i]
        pmean[i] = p.mean()
        for r in range(max_r + 1):
            cp[i, r] = np.real(np.mean(p * np.conj(np.roll(p, -r, axis=0))))
    raw2 = np.concatenate(
        [cp, pmean.real[:, None], pmean.imag[:, None]], axis=1)
    raw2_blocks = raw2[: n_blocks * block].reshape(
        n_blocks, block, raw2.shape[1]).mean(axis=1)

    def cp_of(blockmean):
        cmean = blockmean[: max_r + 1]
        pm = blockmean[max_r + 1] + 1j * blockmean[max_r + 2]
        return cmean - abs(pm) ** 2

    cp_full = cp_of(raw2_blocks.mean(axis=0))
    static_v1 = None
    static_v1_err = None
    if cp_full[0] > 0 and cp_full[1] > 0:
        def v1_of(blockmean):
            c = cp_of(blockmean)
            return -math.log(c[1] / c[0]) / size

        static_v1, static_v1_err = jackknife_error(raw2_blocks, v1_of)
        static_v1 = float(static_v1)
        static_v1_err = float(static_v1_err) if math.isfinite(static_v1_err) else None

    acceptance = lat.accepted / max(lat.proposed, 1)

    result = {
        "beta": beta,
        "lattice": f"{size}^4",
        "gauge_group": "SU(2)",
        "thermalization_sweeps": n_therm,
        "measurement_sweeps": n_meas,
        "acceptance_rate": float(acceptance),
        "avg_plaquette": plaq_mean,
        "plaquette_error": plaq_err,
        "wilson_loops": {f"W({r},{t})": float(w_mean[(r, t)])
                         for (r, t) in wkeys},
        "creutz_ratios": creutz_ratios,
        "string_tension": {
            "value": st["value"], "error": st["error"],
            "method": "Creutz ratio chi(2,2)",
        },
        "glueball_correlator": {
            f"C({tau})": float(c_full[tau]) for tau in range(max_tau + 1)},
        "glueball_effective_masses": glue_masses,
        "tensor_correlator": {
            f"C_D({tau})": float(d_full[tau]) for tau in range(max_tau + 1)},
        "tensor_effective_masses": tens_masses,
        "smeared_glueball_vev": {
            f"level_{lv}": float(smear_vev[li])
            for li, lv in enumerate(SMEAR_LEVELS)},
        "smeared_glueball_correlators": smear_correlators,
        "smeared_glueball_effective_masses": smear_masses,
        "variational_glueball": {
            "basis": [f"APE level {lv} (alpha {APE_ALPHA})"
                      for lv in SMEAR_LEVELS],
            "gevp": "C(1) v = lambda C(0) v, ground state is the largest lambda",
            "lambda": var_lambda,
            "eigenvector": var_eigenvector,
            "ground_state_mass": var_ground,
            "projected_effective_masses": var_masses,
            "projected_correlator": (
                {f"C_proj({tau})": float(cp_full[tau])
                 for tau in range(max_tau_g + 1)}
                if cp_full is not None else None),
            "correlation_matrix_C0": C_full[:, :, 0].tolist(),
            "correlation_matrix_C1": C_full[:, :, 1].tolist(),
        },
        "torelon_correlator": {
            f"C_T({tau})": float(ct_full[tau]) for tau in range(max_tau + 1)},
        "torelon_effective_masses": tor_masses,
        "polyakov_correlator": {
            f"C_P({r})": float(cp_full[r]) for r in range(max_r + 1)},
        "static_potential_V1": {
            "value": static_v1, "error": static_v1_err,
            "method": "V(1) = -ln(C_P(1)/C_P(0)) / L from time-like "
                      "Polyakov loop correlator",
        },
        "thermalization_seconds": round(therm_seconds, 1),
        "measurement_seconds": round(meas_seconds, 1),
        "runtime_seconds": round(total_seconds, 1),
    }
    return result


def main():
    t_start = time.time()
    # Round 5 checkpoint: after beta 2.6 finishes, its full result
    # dict is written to data/yang_mills_r5_checkpoint.json, so a VM
    # restart cannot lose the completed run. On a fresh start the
    # checkpoint is loaded and the run is reused, not re-run.
    here = os.path.dirname(os.path.abspath(__file__))
    ckpt_path = os.path.join(here, "..", "data",
                             "yang_mills_r5_checkpoint.json")
    runs = []
    if os.path.exists(ckpt_path):
        with open(ckpt_path) as f:
            runs = json.load(f).get("runs", [])
        print(f"checkpoint found: reusing completed betas "
              f"{[r['beta'] for r in runs]}", flush=True)
    done_betas = {r["beta"] for r in runs}
    for beta in (2.6,):
        if beta in done_betas:
            print(f"beta {beta} already complete in checkpoint, skipping",
                  flush=True)
            continue
        print(f"Round 5: beta={beta} on 8^4 SU(2), Metropolis + APE smearing",
              flush=True)
        runs.append(run(beta))
        print(f"beta {beta} 8^4 done in {runs[-1]['runtime_seconds']:.1f} s",
              flush=True)
        with open(ckpt_path, "w") as f:
            json.dump({"runs": runs, "date": "2026-11-21"}, f, indent=2)
        print(f"checkpoint written: {ckpt_path}", flush=True)
    total = time.time() - t_start

    def pick_mass(masses):
        """Best effective mass: m_eff(1) when it exists with relative
        jackknife error under 50 percent, else m_eff(0). Same rule as
        rounds 1, 2, 3 and 4."""
        m1 = masses.get("m_eff(1)", {})
        if (m1.get("value") is not None and m1.get("error") is not None
                and m1["error"] < 0.5 * abs(m1["value"])):
            return m1
        return masses.get("m_eff(0)", {})

    def usable(m):
        """An effective mass counts as usable when it exists and its
        jackknife error is under 50 percent of its value."""
        return (m.get("value") is not None and m.get("error") is not None
                and m["error"] < 0.5 * abs(m["value"]))

    def agree(a, b):
        """True when two estimates agree within combined errors,
        False when they disagree, None when the comparison cannot
        be made."""
        if a.get("value") is None or b.get("value") is None:
            return None
        if a.get("error") is None or b.get("error") is None:
            return None
        diff = abs(a["value"] - b["value"])
        comb = math.sqrt(a["error"] ** 2 + b["error"] ** 2)
        return diff <= comb

    gap_estimates = []
    comparison = {}
    for r in runs:
        b = str(r["beta"])
        g = pick_mass(r["glueball_effective_masses"])
        if g.get("value") is not None:
            gap_estimates.append({
                "beta": r["beta"],
                "lattice": r["lattice"],
                "gap_estimate": g["value"],
                "error": g["error"],
                "method": "0++ glueball effective mass from time-slice "
                          "plaquette correlator, plain operator "
                          "(m_eff(1) preferred, m_eff(0) otherwise)",
            })
        for lv in SMEAR_LEVELS:
            gm = pick_mass(
                r["smeared_glueball_effective_masses"][f"level_{lv}"])
            if gm.get("value") is not None:
                gap_estimates.append({
                    "beta": r["beta"],
                    "lattice": r["lattice"],
                    "gap_estimate": gm["value"],
                    "error": gm["error"],
                    "method": f"0++ glueball effective mass from "
                              f"APE-smeared time-slice plaquette "
                              f"correlator, level {lv} "
                              f"(alpha {APE_ALPHA}) (m_eff(1) preferred, "
                              f"m_eff(0) otherwise)",
                })
        vg = r["variational_glueball"]["ground_state_mass"]
        if vg.get("value") is not None:
            gap_estimates.append({
                "beta": r["beta"],
                "lattice": r["lattice"],
                "gap_estimate": vg["value"],
                "error": vg["error"],
                "method": "0++ glueball ground-state mass from "
                          "variational GEVP over APE levels 0, 2, 4, "
                          "eigenvalue -ln(lambda), C(1) v = lambda C(0) v",
            })
        t2 = pick_mass(r["tensor_effective_masses"])
        if t2.get("value") is not None:
            gap_estimates.append({
                "beta": r["beta"],
                "lattice": r["lattice"],
                "gap_estimate": t2["value"],
                "error": t2["error"],
                "method": "2++ tensor glueball effective mass from "
                          "orientation-difference plaquette correlator",
            })
        t = pick_mass(r["torelon_effective_masses"])
        if t.get("value") is not None:
            gap_estimates.append({
                "beta": r["beta"],
                "lattice": r["lattice"],
                "gap_estimate": t["value"],
                "error": t["error"],
                "method": "torelon effective mass from spatial "
                          "Polyakov loop correlator",
            })

        # Comparison: plain vs smeared vs variational at this beta.
        plain = r["glueball_effective_masses"]
        sm = r["smeared_glueball_effective_masses"]
        var = r["variational_glueball"]
        var1 = var["projected_effective_masses"].get("m_eff(1)", {})
        sm4_1 = sm["level_4"].get("m_eff(1)", {})
        sm2_1 = sm["level_2"].get("m_eff(1)", {})
        if usable(var1):
            verdict = ("STABILIZED: the variational projected m_eff(1) is "
                       "usable (relative jackknife error under 50 "
                       "percent), so the 0++ ground-state estimate no "
                       "longer rests on the contaminated m_eff(0).")
        elif usable(sm4_1):
            verdict = ("PARTIALLY STABILIZED: the level-4 smeared "
                       "m_eff(1) is usable, but the variational projected "
                       "m_eff(1) is not.")
        elif usable(sm2_1):
            verdict = ("PARTIALLY STABILIZED: the level-2 smeared "
                       "m_eff(1) is usable, but the level-4 and "
                       "variational m_eff(1) are not.")
        else:
            verdict = ("NOT STABILIZED: m_eff(1) remains unusable "
                       "(relative error over 50 percent or no positive "
                       "correlator) for every smeared level and for the "
                       "variational projection, so the 0++ estimate "
                       "still rests on m_eff(0).")
        comparison[b] = {
            "plain_m_eff_0": plain.get("m_eff(0)", {}),
            "plain_m_eff_1": plain.get("m_eff(1)", {}),
            "smeared_level_2_m_eff_0": sm["level_2"].get("m_eff(0)", {}),
            "smeared_level_2_m_eff_1": sm2_1,
            "smeared_level_4_m_eff_0": sm["level_4"].get("m_eff(0)", {}),
            "smeared_level_4_m_eff_1": sm4_1,
            "variational_ground_state_mass": vg,
            "variational_m_eff_1": var1,
            "variational_m_eff_1_usable": usable(var1),
            "smeared_level_4_m_eff_1_usable": usable(sm4_1),
            "variational_agrees_with_plain_m_eff_0_within_errors":
                agree(vg, plain.get("m_eff(0)", {})),
            "smeared_level_4_agrees_with_plain_m_eff_0_within_errors":
                agree(pick_mass(sm["level_4"]), plain.get("m_eff(0)", {})),
            "verdict": verdict,
        }

    # Gap in units of the string tension scale.
    ratios = {}
    ratios_var = {}
    for r in runs:
        s = r["string_tension"]
        g = pick_mass(r["glueball_effective_masses"])
        if g.get("value") is not None and s["value"] > 0:
            ratios[str(r["beta"])] = g["value"] / math.sqrt(s["value"])
        vg = r["variational_glueball"]["ground_state_mass"]
        if vg.get("value") is not None and s["value"] > 0:
            ratios_var[str(r["beta"])] = vg["value"] / math.sqrt(s["value"])

    # Five-point torelon series: beta 2.2 from round 1, 2.3 and 2.4
    # from round 4, 2.5 from round 3, 2.6 from this run. Same
    # pick_mass rule (m_eff(1) preferred, m_eff(0) otherwise) and
    # same y = m_tor / sqrt(sigma a^2) definition as rounds 2 and 3.
    def load_runs(fname):
        with open(os.path.join(here, "..", "data", fname)) as f:
            return json.load(f)["runs"]

    series_src = []
    for r in load_runs("yang_mills.json"):
        if str(r["beta"]) == "2.2" and r["lattice"] == "8^4":
            series_src.append(r)
    for r in load_runs("yang_mills_r4.json"):
        if r["lattice"] == "8^4":
            series_src.append(r)
    for r in load_runs("yang_mills_r3.json"):
        if str(r["beta"]) == "2.5" and r["lattice"] == "8^4":
            series_src.append(r)
    series_src.extend(runs)
    series_src.sort(key=lambda r: r["beta"])

    points = []
    for r in series_src:
        s = r["string_tension"]
        m = pick_mass(r["torelon_effective_masses"])
        y = m["value"] / math.sqrt(s["value"])
        ey = y * math.sqrt((m["error"] / m["value"]) ** 2
                           + (0.5 * s["error"] / s["value"]) ** 2)
        points.append({
            "beta": r["beta"],
            "sigma_a2": s["value"],
            "sigma_a2_error": s["error"],
            "m_tor": m["value"],
            "m_tor_error": m["error"],
            "m_tor_over_sqrt_sigma": y,
            "m_tor_over_sqrt_sigma_error": ey,
        })

    # Weighted linear fit y = c0 + c1 * x, x = sigma a^2, weights
    # 1 / ey^2. Same method as rounds 2 and 3; verified to reproduce
    # the round 3 four-point fit exactly before this run.
    xs = np.array([p["sigma_a2"] for p in points])
    ys = np.array([p["m_tor_over_sqrt_sigma"] for p in points])
    es = np.array([p["m_tor_over_sqrt_sigma_error"] for p in points])
    X = np.column_stack([np.ones_like(xs), xs])
    W = np.diag(1.0 / es ** 2)
    XtWX = X.T @ W @ X
    cov = np.linalg.inv(XtWX)
    coef = cov @ (X.T @ W @ ys)
    resid = ys - X @ coef
    chi2 = float(np.sum((resid / es) ** 2))
    dof = len(points) - 2
    c0, c1 = float(coef[0]), float(coef[1])
    c0_err = float(math.sqrt(cov[0, 0]))
    c1_err = float(math.sqrt(cov[1, 1]))

    extrapolation = {
        "channel": "torelon m_eff(1) preferred, m_eff(0) otherwise, "
                   "in units of sqrt(sigma)",
        "fit": "weighted linear fit of m_tor / sqrt(sigma) vs sigma a^2 "
               "(a^2 proxy at fixed physical sigma)",
        "points": points,
        "continuum_value_c0": c0,
        "continuum_value_error": c0_err,
        "slope_c1": c1,
        "slope_error": c1_err,
        "chi2": chi2,
        "dof": dof,
        "note": "Five points, two fit parameters, three degrees of "
            "freedom. The fit is still thin: the beta 2.2 torelon "
            "error is large, sigma a^2 is itself an estimate from "
            "chi(2,2) that overestimates the asymptotic tension, the "
            "8^4 volume leaves finite-volume effects uncontrolled, "
            "and a linear a^2 form is assumed, not established. This "
            "is an extrapolation attempt, not a continuum result.",
    }

    out = {
        "method": "Metropolis, checkerboard even/odd updates, random "
                  "SU(2) rotation near identity, eps=0.35, seed "
                  "20261120 + int(beta*100), cold start; APE smearing of "
                  "spatial links, alpha 0.5, levels 0, 2, 4 steps, "
                  "variational GEVP over the three levels",
        "lattice": "8^4",
        "gauge_group": "SU(2)",
        "beta": [2.6],
        "thermalization_sweeps": 400,
        "measurement_sweeps": 1500,
        "seed": 20261120 + int(2.6 * 100),
        "smearing": {
            "method": "APE smearing of spatial links only (spatial "
                      "staples, so smearing stays local in time), "
                      "U' = Proj[(1 - alpha) U + (alpha/4) sum of 4 "
                      "spatial staples], SU(2) projection by dividing "
                      "by sqrt(det)",
            "alpha": APE_ALPHA,
            "levels_steps": list(SMEAR_LEVELS),
            "operator": "mean over the three spatial plaquette "
                        "orientations in time slice t, built from the "
                        "smeared spatial links",
            "variational_basis": [f"APE level {lv}" for lv in SMEAR_LEVELS],
            "gevp": "C(1) v = lambda C(0) v, ground state is the "
                    "largest lambda; projected correlator v^T C(tau) v",
        },
        "avg_plaquette": {str(r["beta"]): r["avg_plaquette"] for r in runs},
        "plaquette_error": {str(r["beta"]): r["plaquette_error"] for r in runs},
        "creutz_ratios": {str(r["beta"]): r["creutz_ratios"] for r in runs},
        "string_tension": {str(r["beta"]): r["string_tension"] for r in runs},
        "string_tension_note": "sigma a^2 from Creutz ratio chi(2,2); "
            "chi(3,3) also reported in creutz_ratios for comparison. "
            "Finite 8^4 volume, no continuum limit taken.",
        "gap_estimates": gap_estimates,
        "gap_over_sqrt_sigma": ratios,
        "gap_over_sqrt_sigma_variational": ratios_var,
        "comparison_plain_vs_smeared": comparison,
        "continuum_extrapolation_torelon": extrapolation,
        "runs": runs,
        "runtime_seconds": round(total, 1),
        "date": "2026-11-21",
    }

    out_path = os.path.join(here, "..", "data", "yang_mills_r5.json")
    with open(out_path, "w") as f:
        json.dump(out, f, indent=2)

    print("=" * 60)
    for r in runs:
        b = str(r["beta"])
        print(f"beta={r['beta']}  lattice={r['lattice']}  SU(2)  "
              f"acceptance={r['acceptance_rate']:.3f}")
        print(f"  avg plaquette = {r['avg_plaquette']:.6f} "
              f"+/- {r['plaquette_error']:.6f}")
        s = r["string_tension"]
        serr = f"{s['error']:.4f}" if s['error'] is not None else "n/a"
        print(f"  string tension sigma a^2 = {s['value']:.4f} "
              f"+/- {serr} (chi(2,2))")
        for k, v in r["glueball_effective_masses"].items():
            if v["value"] is None:
                print(f"  plain glueball {k}: no positive correlator")
            else:
                err = f"{v['error']:.4f}" if v['error'] is not None else "n/a"
                print(f"  plain glueball {k} = {v['value']:.4f} +/- {err}")
        for lv in SMEAR_LEVELS:
            for k, v in r["smeared_glueball_effective_masses"][
                    f"level_{lv}"].items():
                if v["value"] is None:
                    print(f"  smeared level {lv} {k}: no positive correlator")
                else:
                    err = f"{v['error']:.4f}" if v['error'] is not None else "n/a"
                    print(f"  smeared level {lv} {k} = {v['value']:.4f} +/- {err}")
        vg = r["variational_glueball"]["ground_state_mass"]
        if vg.get("value") is None:
            print("  variational ground state: GEVP unusable")
        else:
            err = f"{vg['error']:.4f}" if vg['error'] is not None else "n/a"
            print(f"  variational ground state = {vg['value']:.4f} +/- {err}")
            print(f"  variational lambda = "
                  f"{r['variational_glueball']['lambda']:.4f}, "
                  f"eigenvector = "
                  f"{[round(x, 3) for x in r['variational_glueball']['eigenvector']]}")
        for k, v in r["variational_glueball"]["projected_effective_masses"].items():
            if v["value"] is None:
                print(f"  variational projected {k}: no positive correlator")
            else:
                err = f"{v['error']:.4f}" if v['error'] is not None else "n/a"
                print(f"  variational projected {k} = {v['value']:.4f} +/- {err}")
        for k, v in r["torelon_effective_masses"].items():
            if v["value"] is None:
                print(f"  torelon {k}: no positive correlator")
            else:
                err = f"{v['error']:.4f}" if v['error'] is not None else "n/a"
                print(f"  torelon {k} = {v['value']:.4f} +/- {err}")
        print(f"  runtime = {r['runtime_seconds']:.1f} s")
        print(f"  verdict: {comparison[b]['verdict']}")
    print("five-point torelon series (m_tor / sqrt(sigma) vs sigma a^2):")
    for p in points:
        print(f"  beta {p['beta']}: sigma a^2 = {p['sigma_a2']:.4f} +/- "
              f"{p['sigma_a2_error']:.4f}, m_tor = {p['m_tor']:.4f} +/- "
              f"{p['m_tor_error']:.4f}, "
              f"m_tor/sqrt(sigma) = {p['m_tor_over_sqrt_sigma']:.4f} +/- "
              f"{p['m_tor_over_sqrt_sigma_error']:.4f}")
    print(f"continuum extrapolation: c0 = {c0:.4f} +/- {c0_err:.4f}, "
          f"c1 = {c1:.4f} +/- {c1_err:.4f}, chi2 = {chi2:.4f}, dof = {dof}")
    print(f"total runtime = {total:.1f} s")
    print(f"wrote {out_path}")


if __name__ == "__main__":
    main()
