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

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.
- Two couplings, beta = 2.2 and beta = 2.4, so the gap estimate can be
  tracked as the lattice spacing changes. Both are in the confined
  phase for N_t = 8.

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.py
Output: prints a summary and writes data/yang_mills.json next to
the millennium-lab directory layout (../data/yang_mills.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)


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 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
    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())
        ploops.append(lat.polyakov_loops())
        pspat.append([lat.polyakov_spatial(mu) for mu in (0, 1, 2)])
        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"}

    # 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,
        "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()
    runs = []
    for beta in (2.2, 2.4):
        print(f"Running beta={beta} on 8^4 SU(2), Metropolis", flush=True)
        runs.append(run(beta))
    total = time.time() - t_start

    by_beta = {str(r["beta"]): r for r in runs}
    def pick_mass(masses):
        """Best effective mass for a channel: m_eff(1) when it exists
        with a relative jackknife error under 50 percent, else
        m_eff(0). m_eff(0) carries excited-state contamination, so
        it is an upper estimate of the ground-state mass."""
        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)", {})

    gap_estimates = []
    for r in runs:
        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 (m_eff(1) preferred, "
                          "m_eff(0) otherwise)",
            })
        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",
            })

    # Gap in units of the string tension scale, per beta.
    # Primary channel is the 0++ glueball; fall back to the 2++ tensor
    # channel if the 0++ effective mass is not available.
    def primary_glue(r):
        g = pick_mass(r["glueball_effective_masses"])
        if g.get("value") is not None:
            return g
        return pick_mass(r["tensor_effective_masses"])

    ratios = {}
    for r in runs:
        g = primary_glue(r)
        s = r["string_tension"]
        if g.get("value") is not None and s["value"] > 0:
            ratios[str(r["beta"])] = g["value"] / math.sqrt(s["value"])

    out = {
        "method": "Metropolis, checkerboard even/odd updates, "
                  "random SU(2) rotation near identity, eps=0.35, "
                  "seed 20261120, cold start",
        "lattice": "8^4",
        "gauge_group": "SU(2)",
        "beta": [2.2, 2.4],
        "thermalization_sweeps": 400,
        "measurement_sweeps": 1500,
        "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,
        "continuum_extrapolation": "",
        "runs": runs,
        "runtime_seconds": round(total, 1),
        "date": "2026-11-20",
    }

    # Continuum extrapolation paragraph, written from the two points.
    # Every direction word below is computed from the measured values,
    # not assumed. The honest summary is that two points cannot fix
    # an extrapolation, and the glueball channel disagrees with itself
    # between tau = 0 and tau = 1, so no stable continuum value can
    # be read off this run.
    b1, b2 = runs[0], runs[1]
    g1 = primary_glue(b1)
    g2 = primary_glue(b2)
    t1 = pick_mass(b1["torelon_effective_masses"])
    t2 = pick_mass(b2["torelon_effective_masses"])
    g1_1 = b1["glueball_effective_masses"].get("m_eff(1)", {})
    g2_1 = b2["glueball_effective_masses"].get("m_eff(1)", {})

    def direction(a, b):
        if a is None or b is None:
            return "cannot be tracked"
        if b > a:
            return "rises"
        if b < a:
            return "falls"
        return "is unchanged"

    if g1.get("value") is not None and g2.get("value") is not None:
        r1 = ratios.get("2.2")
        r2 = ratios.get("2.4")
        gdir = direction(g1["value"], g2["value"])
        g1dir = direction(g1_1.get("value"), g2_1.get("value"))
        tdir = direction(t1.get("value"), t2.get("value"))
        rdir = direction(r1, r2)
        out["continuum_extrapolation"] = (
            "Two lattice spacings only, beta 2.2 and beta 2.4 on an 8^4 "
            "lattice. The primary glueball estimate (m_eff(0), which "
            "carries excited-state contamination) "
            f"{gdir} from beta 2.2 to beta 2.4, while the cleaner "
            f"m_eff(1) {g1dir}, but with errors too large to settle the "
            "direction. In units of the string tension scale, "
            f"m / sqrt(sigma) {rdir} from beta 2.2 to beta 2.4, moving "
            "substantially between the two spacings, so no stable "
            "continuum value can be read off. The torelon estimate "
            f"{tdir} with beta, which is the expected direction as the "
            "lattice spacing shrinks, and stays nonzero at both "
            "spacings. Two points cannot fix an extrapolation: no "
            "functional form in a^2 can be fit, no third spacing "
            "confirms any trend, and the 8^4 volume leaves "
            "finite-volume effects uncontrolled. The signal at both "
            "spacings is consistent with a nonzero gap at finite "
            "spacing, and the torelon channel points in the direction "
            "of a nonzero continuum gap, but this is a hint from two "
            "points, not a proof of the continuum mass gap. A real "
            "extrapolation needs at least three beta values, larger "
            "volumes, better glueball operators, and a controlled "
            "continuum limit."
        )
    else:
        out["continuum_extrapolation"] = (
            "The glueball effective mass could not be extracted at one "
            "or both beta values, so no extrapolation direction can be "
            "stated. No continuum statement follows from this run."
        )

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

    print("=" * 60)
    for r in runs:
        print(f"beta={r['beta']}  lattice={r['lattice']}  SU(2)  "
              f"therm={r['thermalization_sweeps']}  "
              f"meas={r['measurement_sweeps']}  "
              f"acceptance={r['acceptance_rate']:.3f}")
        print(f"  avg plaquette = {r['avg_plaquette']:.6f} "
              f"+/- {r['plaquette_error']:.6f}")
        for k, v in r["creutz_ratios"].items():
            err = f"{v['error']:.4f}" if v['error'] is not None else "n/a"
            print(f"  {k} = {v['value']:.4f} +/- {err}")
        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"  glueball {k}: no positive correlator")
            else:
                err = f"{v['error']:.4f}" if v['error'] is not None else "n/a"
                print(f"  glueball {k} = {v['value']:.4f} +/- {err}")
        for k, v in r["tensor_effective_masses"].items():
            if v["value"] is None:
                print(f"  tensor 2++ {k}: no positive correlator")
            else:
                err = f"{v['error']:.4f}" if v['error'] is not None else "n/a"
                print(f"  tensor 2++ {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}")
        v1 = r["static_potential_V1"]
        if v1["value"] is None:
            print("  static potential V(1): C_P(1) not positive")
        else:
            verr = f"{v1['error']:.4f}" if v1['error'] is not None else "n/a"
            print(f"  static potential V(1) = {v1['value']:.4f} "
                  f"+/- {verr}")
        print(f"  runtime = {r['runtime_seconds']:.1f} s")
    print(f"total runtime = {total:.1f} s")
    print(f"wrote {out_path}")


if __name__ == "__main__":
    main()
