94 Yang–Mills in Four Dimensions

94.1 The gauge group from the unit quaternions

The unit quaternions occupy the \(SU(2)\) place in the chain (SMChain). Three finite subgroups are built exactly.

94.2 Lattice, action, gauge invariance (Lean, general)

Space-time is the torus \((\mathbb Z/L)^4\), with shifts by \(\operatorname {rem}\) (torus_comm). A field puts a group element on every link. The plaquette holonomy is \(U_p=U(x,\mu )U(x+\mu ,\nu )U(x+\nu ,\mu )^{-1}U(x,\nu )^{-1}\). A gauge transformation conjugates every holonomy at its base point (hol_gauge). The following hold for every group given by its laws, every gauge transformation, every field and every class function \(f\):

The defect \([U_p\neq 1]\) and \(1-\operatorname {Re}U_p\) are class functions (defect_class, wilson_class on \(Q_8\), and the exact check of \(\operatorname {Re}(ghg^{-1})=\operatorname {Re}h\) on \(2I\)). The second gives Wilson’s action \(\beta \sum _p(1-\operatorname {Re}U_p)\) [759] as an instance of the invariance theorem. The plaquette weight couples the four links of a plaquette and is not a sum of one-link terms (interaction).

94.3 Reflection positivity

Reflect the lattice in a time hyperplane, and let \(F\) depend on the links of the upper half. In temporal gauge the measure is the weight of the upper half, times its mirror image, times a kernel coming from the plaquettes that cross the plane. Positivity comes from Gram kernels.

Hence \(\langle \theta F\cdot F\rangle \ge 0\) for both actions. This is the reflection positivity of Osterwalder and Seiler [1760].

94.4 Transfer matrix and the finite-volume gap

Reflection positivity makes the transfer matrix \(T\) between time slices a positive operator. Its entries are weights of one time step, and they are strictly positive (transfer_pos). For a matrix with positive entries and a positive eigenvector \(u\) with eigenvalue \(\lambda \), every eigenvector with eigenvalue \(\lambda \) is a multiple of \(u\) (perron_simple). The proof works over any ordered commutative ring given by its laws. Pick \(k\) minimising \(w_k/u_k\), written in cross-multiplied form (argmin). Then \(z_j=u_kw_j-w_ku_j\ge 0\), and \(\sum _jT_{kj}z_j=u_k\lambda w_k-w_k\lambda u_k=0\). A vanishing sum of nonnegative terms has every term zero (sum_zero_each), and \(T_{kj}>0\), so \(z=0\). So the top eigenvalue of the transfer matrix is simple, and on every finite lattice the first excited state lies strictly below the ground state.

94.5 Strong coupling: an explicit \(\beta _0\)

A connected plaquette surface of area \(A\) through a given plaquette is coded by a depth-first walk with \(2A\) letters, each a step to one of the \(D\) neighbouring plaquettes or a step back. There are \(k^n\) words of length \(n\) over \(k\) letters (words_length), so there are \((D+1)^{2A}=c^A\) codes (surface_count). In four dimensions \(D=4\cdot 5=20\) and \(c=441\) (c_441). With \(T(N)=\sum _{j\le N}c^jq^{N-j}\), telescoping gives \(qT(N)+c^{N+1}=q^{N+1}+cT(N)\) (geom_telescope), and so \(T(N)\le 2q^N\) whenever \(2c\le q\) (geom_bound, decay_bound). A plaquette in a polymer of the strong-coupling expansion has activity \(\varepsilon =1-e^{-\beta (1-\operatorname {Re}U)}\le 2\beta \) for the Wilson action and \(\varepsilon \le \beta \) for the defect action. With \(q=1/\varepsilon \):

\[ q\ge 882\ \Longrightarrow \ \sum _{A\ge t}441^A\varepsilon ^A\le 2\cdot 2^{-t} \qquad \text {for every }t\text { and every }L \]
(gap_explicit). So for
\[ \beta <\beta _0=\tfrac 1{1764}\ \text {(Wilson action)},\qquad \beta <\tfrac 1{882}\ \text {(defect action)}, \]
the sum over connecting surfaces decays at least like \(2^{-t}\): a mass at least \(\ln 2\) in lattice units, the same for every \(L\). At \(\beta =0\) observables on disjoint link sets are exactly uncorrelated (factor_sum).

94.6 Spectroscopy: method

All runs use \(2I\) with the Wilson action, heat bath over the \(120\) elements, \(L=8\) (\(\beta \le 2.3\)) and \(L=10\) (\(\beta \ge 2.4\)), two independent chains of fixed seed per \(\beta \), one measurement per sweep, multiprocessing over chains.

Smearing. A spatial link is replaced by the average of itself and its four spatial staples, \(V=U+\tfrac 12\sum \text {staples}\), and \(V\) is brought back to the group by \(\arg \max _gg\cdot V\). The \(120\) elements are the vertices of the 600-cell, a convex polytope. So climbing the vertex graph from \(U\) reaches the maximum, and \(2000\) random tests agree with the exhaustive maximum.

Glueball. The operators are the spatial \(R\times R\) loops, \(R=1,2,3\), summed over the three spatial planes of time slice \(t\), at smearing levels \(4\) and \(10\): six operators. The \(6\times 6\) correlation matrix gives the generalised eigenproblem \(C(1)v=\lambda C(0)v\), and the leading vector projects \(C(t)\) onto the ground state. \(m\) is the error-weighted mean of the cosh effective mass over all \(t\ge 2\) whose jackknife error is below its value. Errors are jackknife errors over \(10\) blocks, with the eigenproblem re-solved in every sample.

String tension. Wilson loops \(W(R,T)\) have spatial lines at smearing level \(10\) and bare temporal lines, for \(R,T\le \min (5,L/2)\). From \(V(R,T)=\ln W(R,T)/W(R,T+1)\), the fit \(V=A+\sigma R-c/R\) is done at each \(T\). \(\sigma \) is taken at the first \(T\) where \(\sigma (T)\) and \(\sigma (T+1)\) agree within their errors, and otherwise at the largest \(T\).

\(2I\) against \(SU(2)\). The same Wilson action is simulated for \(SU(2)\) itself (Kennedy–Pendleton heat bath) on \((\mathbb Z/4)^4\), and the plaquettes are compared at every \(\beta \).

94.7 Spectroscopy: results

\(\beta \) \(2I\) \(SU(2)\) difference
2.2 \(0.5744\pm 0.0028\) \(0.5757\pm 0.0030\) \(0.23\%\)
2.3 \(0.6105\pm 0.0010\) \(0.6108\pm 0.0018\) \(0.05\%\)
2.4 \(0.6343\pm 0.0013\) \(0.6340\pm 0.0009\) \(0.05\%\)
2.5 \(0.6563\pm 0.0006\) \(0.6522\pm 0.0012\) \(0.63\%\)
2.6 \(0.6708\pm 0.0007\) \(0.6716\pm 0.0006\) \(0.12\%\)
Table 242: Plaquette on \((\mathbb Z/4)^4\), Wilson action, \(2I\) against \(SU(2)\).

At every \(\beta \) from \(2.2\) to \(2.6\) the plaquette of \(2I\) agrees with that of \(SU(2)\) to within \(0.63\%\), so \(2I\) follows \(SU(2)\) through this range.

\(L\) \(\beta \) meas. plaquette \(\sigma a^2\) (\(T\)) \(ma\) \(m/\sqrt \sigma \) \(mL\)
8 2.2 6400 0.5692 \(0.2349\pm 0.0115\) (3) \(0.836\pm 0.322\) \(1.73\pm 0.66\) 6.7
8 2.3 6400 0.6023 \(0.1527\pm 0.0055\) (3) \(1.641\pm 1.602\) \(4.20\pm 4.09\) 13.1
10 2.4 5200 0.6300 \(0.0718\pm 0.0044\) (4) \(0.836\pm 0.388\) \(3.12\pm 1.50\) 8.4
10 2.5 5200 0.6521 \(0.0376\pm 0.0028\) (4) \(0.885\pm 0.119\) \(4.57\pm 0.62\) 8.8
10 2.6 5200 0.6702 \(0.0187\pm 0.0012\) (4) \(0.727\pm 0.204\) \(5.32\pm 1.54\) 7.3
Table 243: \(2I\), Wilson action: string tension and \(0^{++}\) mass (NUMERIC_YMGAP.txt).

The string tension falls from \(\sigma a^2=0.235\) at \(\beta =2.2\) to \(0.0187\) at \(\beta =2.6\). At \(\beta \ge 2.4\), \(\sigma (T)\) settles at \(T=4\); there \(\sqrt \sigma a\) is \(0.268\), \(0.194\), \(0.137\), decreasing by a factor of about \(0.71\) per step of \(0.1\) in \(\beta \). The \(0^{++}\) effective masses fall from \(t=0\) to \(t=2\) and are flat from \(t=2\) within their errors. The mass is the weighted mean over that plateau, and \(mL\) lies between \(6.7\) and \(13\) everywhere.

For \(\beta =2.4\), \(2.5\), \(2.6\),

\[ \frac {m}{\sqrt \sigma }=3.1\pm 1.5,\quad 4.6\pm 0.6,\quad 5.3\pm 1.5, \qquad \text {weighted mean }4.47\pm 0.54,\ \chi ^2/\mathrm {dof}=0.57, \]
so the dimensionless ratio is constant within errors while \(a\) shrinks by a factor of two. Including the strong-coupling points \(\beta =2.2\) and \(2.3\) gives \(\chi ^2/\mathrm {dof}=2.9\), with \(\beta =2.2\) at \(1.73\pm 0.66\).

The measurement was refined in four runs, each changing one thing:

The smearing of \(2I\) links saturates after about six steps, because each step returns to the group. Large operators and statistics are what moved the numbers.

The large-scale \(SU(2)\) value is \(m_{0^{++}}/\sqrt \sigma \approx 3.7\) [1764]; our \(4.47\pm 0.54\) lies \(1.4\) standard errors above it.

94.8 Status

Statement

Status

Where

\(Q_8\): group laws, quaternion product, \(ij\neq ji\)

proved (Lean)

q8_*

\(2I\): \(120\) elements, closed, inverses, norm \(1\); \(\operatorname {Re}\) a class function

proved (exact computation)

NUMERIC_YM2I

gauge invariance, every \(g\), \(U\), \(L\), class function; Haar measure invariant

proved (Lean)

action_gauge_inv, gauge_inverse

interaction

proved (Lean)

interaction

RP algebra: sum of squares, Gram products, defect kernel

proved (Lean)

rp_*, gram_*, defect_gram

RP of the lattice measure: temporal-gauge splitting; Wilson series

text argument

this section

transfer matrix entries positive

proved (Lean)

transfer_pos

top eigenvalue simple, given a positive eigenvector

proved (Lean)

perron_simple

existence of the positive eigenvector

remaining (Perron–Frobenius existence)

—

surface codes \(=441^A\), geometric bound, explicit \(\beta _0\)

proved (Lean)

surface_count, gap_explicit

\(\mathbb Z_2\): \(G_W\le G_0\cdot \sum _{C\text { connected to }W}t^{|C|}\) (connected-component factorisation)

proved (Lean)

s2c

\(\mathbb Z_2\) strong-coupling area law: \(G_W\le \big (\sum _{A\ge A_{\min }}2^{D(|\partial |+wA)+1}t^A\big )G_0\) (lattice-animal code)

proved (Lean)

area_bound

\(\mathbb Z_2\): \(\langle W\rangle \le \sum _{A\ge A_{\min }}2^{D(|W|+wA)+1}t^A\), uniform in the volume

proved (Lean)

wilson_area_law

\(\mathbb Z_2\) exponential form: \(\langle W\rangle \le 2^{D|W|+2}(2^{Dw}t)^{A_{\min }}\) for \(2^{Dw+1}t\le 1\)

proved (Lean)

wilson_exp

\(\mathbb Z_2\), every \(R\times T\) loop in every box \(n^d\): \(|C|\ge RT\) and \(\langle W_{R\times T}\rangle \le 2^{D|W|+2}(2^{Dw}t)^{RT}\)

proved (Lean)

area_RT

\(\mathbb Z_2\) on the full box \(n^d\): \(D=2(d-1)\), \(w=4\) proved; \(\langle W_{R\times T}\rangle \le 2^{D|W|+2}(2^{4D}t)^{RT}\)

proved (Lean)

area_box

\(\mathbb Z_2\) two-sided on the full box: \(t^{RT}\le \langle W_{R\times T}\rangle \le 2^{D|W|+2}(2^{4D}t)^{RT}\)

proved (Lean)

two_sided

\(\mathbb Z_2\) connected correlation: \(\langle U_pU_q\rangle -\langle U_p\rangle \langle U_q\rangle \le \sum _{C\text { from }p\text { reaching }q}t^{|C|}\)

proved (Lean)

corr_bound

\(\mathbb Z_2\)exponential clustering: \(\langle U_pU_q\rangle -\langle U_p\rangle \langle U_q\rangle \le 2^{D|p|+2}(2^{Dw}t)^{m}\), \(m\) = minimal connecting size

proved (Lean)

cluster

\(\mathbb Z_2\) clustering on the full box: \(\langle U_pU_q\rangle -\langle U_p\rangle \langle U_q\rangle \le 2^{D|p|+2}(2^{4D}t)^{m}\), \(m+1\) = coordinate separation

proved (Lean)

box_cluster

minimal-area certificates: \(k\) odd dual cochains, pairwise plaquette-disjoint \(\Rightarrow |C|\ge k\)

proved (Lean)

min_area

3D box \(3^3\), \(2\times 2\) loop: \(\langle W\rangle \le \sum _{A\ge 4}2^{4(8+4A)+1}t^A\) (closed instance)

proved (Lean)

box3_area_law

4D box \(3^4\), \(2\times 2\) loop: \(\langle W\rangle \le \sum _{A\ge 4}2^{6(8+4A)+1}t^A\) (closed instance)

proved (Lean)

box4_area_law

correlator \(\le \) sum over surfaces (polymer expansion), general \(G\)

remaining

—

\(2I\) tracks \(SU(2)\), plaquette

measured

NUMERIC_YMGAP

\(\sigma \), \(m_{0^{++}}\), \(m/\sqrt \sigma \) for \(\beta =2.2\)–\(2.6\)

measured

NUMERIC_YMGAP

\(m/\sqrt \sigma \) constant in \(\beta \): \(\beta =2.4\)–\(2.6\), \(\chi ^2/\mathrm {dof}=0.57\); with \(\beta =2.2\), \(2.3\), \(\chi ^2/\mathrm {dof}=2.9\)

measured

NUMERIC_YMGAP

continuum limit of four-dimensional \(SU(2)\) with a mass gap

remaining

—

Comparison. Lattice gauge fields with discrete groups go back to Wegner [1761], and discrete subgroups of \(SU(2)\) were simulated by Petcher and Weingarten [1762]. Creutz introduced the Monte Carlo study of \(SU(2)\) and the ratio of loops [1763]. Large-scale glueball spectra give \(m_{0^{++}}/\sqrt \sigma \approx 3.7\) for \(SU(2)\) [1764].

94.9 Machine check

The Lean file of this section is YMChain.lean. In AXIOMS.txt it has \(65\) theorems, and all \(65\) #print axioms lines read “does not depend on any axioms”. It imports DetChain.lean (Listing 360) for the commutative ring used in reflection positivity and in the Perron argument. The numbers come from numeric_ym.py (\(Q_8\), defect action) and numeric_ym2i.py (\(2I\) and \(SU(2)\), Wilson action, multiprocessing over chains). Their outputs are NUMERIC_YM.txt, NUMERIC_YM2I.txt and NUMERIC_YMGAP.txt.

Listing 375: YMChain.lean: gauge group, gauge invariance, reflection positivity, transfer matrix, Perron, surfaces, explicit \(\beta _0\)

YMChain.lean

/-
  YMChain.lean
  A four-dimensional interacting lattice gauge field built from the chain (T16).

  Lean 4 core plus FTAChain (pairs, `rem`, `iter`, laws of + and *).
  Proofs are hand-written terms, rewriting and case splits closed by `rfl`;
  no omega / simp / ring / decide / norm_num / linarith.

  Design (made here):
  * Gauge group: the unit quaternions with integer coordinates,
    ±1, ±i, ±j, ±k (the group Q8), written as a sign and a unit.
    `toVec` gives the integer coordinates, and the product agrees with the
    quaternion product of those coordinates (`mul_is_quaternion`).
  * A general group is passed by its operations and laws (`Grp`).
  * Space-time: any set of sites with four shifts that commute; the torus
    (Z/L)^4 with `rem` is an instance (`torus_comm`).
  * Field: a group element on every link; gauge transformation
    `U(x,μ) ↦ g(x) U(x,μ) g(x+μ)⁻¹`.
  * Action: count the plaquettes (2-cells, counted as in SimplexChain) whose
    holonomy is not 1, or more generally sum any class function of the
    holonomies. Weight `t^S`, measure = counting measure on configurations.

  Proved here:
    grp laws for Q8 (q8_assoc, q8_one_mul, q8_mul_one, q8_inv_mul, q8_mul_inv)
    mul_is_quaternion        Q8 product = integer quaternion product
    q8_noncomm               i j ≠ j i
    inv_mul_rev, conj_mul, conj_inv   group lemmas from the laws
    hol_gauge                holonomy of a transformed field = conjugate holonomy
    action_gauge_inv         S(gU) = S(U): every lattice, every g, every U,
                             every class function
    gauge_inverse            transforming by g then by g⁻¹ gives U back
                             (the counting measure is gauge invariant)
    weight_gauge_inv         t^S(gU) = t^S(U)
    torus_comm, torus_action_gauge_inv   the (Z/L)^4 instance, every L
    defect_class, wilson_class   both plaquette functions are class functions
    interaction              the plaquette weight is not a sum of one-link terms
    factor_sum               at t = 1 (no action), observables on disjoint link
                             sets are uncorrelated: Σ Σ F G = (Σ F)(Σ G)

  Added for T23 (reflection positivity, transfer matrix, strong coupling):
    rp_identity              Σ_x Σ_y F(x) F(y) K(x,y) = Σ_k c_k (Σ_x F(x) g_k(x))²
                             for a Gram kernel K(x,y) = Σ_k c_k g_k(x) g_k(y), any commutative ring
    rp_nonneg                with c_k ≥ 0 (any positivity predicate): ⟨θF · F⟩ ≥ 0
    gram_mul, gram_mul_nn    the product of Gram kernels is a Gram kernel, coefficients ≥ 0
    delta_gram               [g = h] = Σ_k [g = k][h = k]  (finite group, no repeats)
    defect_gram              the defect weight a + b [g = h] of a crossing plaquette is Gram
    transfer_pos             transfer-matrix entries q^(non-defects) are positive
    words_length             there are k^n words of length n over k letters
    surface_count            DFS codes of surfaces of area A: (D+1)^(2A) = ((D+1)^2)^A
    geom_telescope           q T(N) + c^(N+1) = q^(N+1) + c T(N),  T(N) = Σ_{j≤N} c^j q^(N-j)
    geom_bound               2c ≤ q ⇒ T(N) ≤ 2 q^N
    decay_bound              Σ_{A≥t} c^A q^(-A) ≤ 2 (c/q)^t, written in integers; no L appears

  Added for T25:
    c_441, gap_explicit      with c = 441 and activity ≤ 1/q, q ≥ 882 (β ≤ β₀ = 1/1764 for the
                             Wilson action): surface sum ≤ 2·2^(-t), decay rate ≥ ln 2, every L
    argmin, sum_zero_each, sumK_sub, mul_neg_r, swap3
    perron_simple            positive matrix, positive eigenvector u: every eigenvector with
                             the same eigenvalue is a multiple of u (the top eigenvalue is simple)

  Added for T27:
    perron_dominant          |μ| ≤ λ for every eigenvalue μ (positive matrix, positive eigenvector)
    perron_gap               every eigenvalue μ ≠ λ has |μ| < λ: a strict gap on each finite lattice
    sq, sq_eigen, pos_sum, sum_le, abs_sum, argmax   the steps (T² is positive; same eigenvectors)
    ker_symm                 Gram kernels, hence transfer matrices built from them, are symmetric
    sh2_comm, coarse         the coarse lattice of a decimation step
    block_gauge              blocking commutes with gauge transformations (coarse gauge covariance)
    block_weight_pos         blocked weights stay positive
    block_rp                 blocked observables keep reflection positivity
    doeblin                  rows P_ij = r_ij + δ q_j, Σ_j r_ij = e: spread(Pf) ≤ e · spread(f)
                             (Hilbert/Doeblin contraction; a gap ≥ -ln(1-δ) for stochastic P)
    pow_add_nat, pow_mul_nat, block_decay, block_decay_explicit
                             a 2·q^(-s) bound at fine distance s gives 2·(2^(2^n))^(-t) at coarse
                             distance t after n decimation steps (strong-coupling range q ≥ 882)
-/
import DetChain

namespace YMChain
open FTAChain

/-! ## A group, given by its operations and laws -/

structure Grp (G : Type) where
  mul : G → G → G
  inv : G → G
  one : G
  assoc : ∀ a b c, mul (mul a b) c = mul a (mul b c)
  one_mul : ∀ a, mul one a = a
  mul_one : ∀ a, mul a one = a
  inv_mul : ∀ a, mul (inv a) a = one
  mul_inv : ∀ a, mul a (inv a) = one

section Group
variable {G : Type} (K : Grp G)

theorem cancel_left (a b c : G) : K.mul (K.mul a (K.inv b)) (K.mul b c) = K.mul a c := by
  rw [K.assoc, ← K.assoc (K.inv b) b c, K.inv_mul, K.one_mul]

theorem inv_unique (a b : G) (h : K.mul a b = K.one) : K.inv a = b := by
  have e : K.mul (K.mul (K.inv a) a) b = K.mul (K.inv a) K.one := by rw [K.assoc, h]
  rw [K.inv_mul, K.one_mul, K.mul_one] at e
  exact e.symm

theorem inv_mul_rev (a b : G) : K.inv (K.mul a b) = K.mul (K.inv b) (K.inv a) := by
  apply inv_unique
  rw [K.assoc, ← K.assoc b (K.inv b) (K.inv a), K.mul_inv, K.one_mul, K.mul_inv]

theorem inv_inv (a : G) : K.inv (K.inv a) = a := inv_unique K (K.inv a) a (K.inv_mul a)

/-- `(g u h⁻¹)(h v k⁻¹) = g (u v) k⁻¹`. -/
theorem conj_mul (g u h v k : G) :
    K.mul (K.mul (K.mul g u) (K.inv h)) (K.mul (K.mul h v) (K.inv k))
      = K.mul (K.mul g (K.mul u v)) (K.inv k) := by
  rw [← K.assoc (K.mul (K.mul g u) (K.inv h)) (K.mul h v) (K.inv k),
    K.assoc (K.mul g u) (K.inv h) (K.mul h v), ← K.assoc (K.inv h) h v, K.inv_mul, K.one_mul,
    K.assoc g u v]

/-- `(g u h⁻¹)⁻¹ = h u⁻¹ g⁻¹`. -/
theorem conj_inv (g u h : G) :
    K.inv (K.mul (K.mul g u) (K.inv h)) = K.mul (K.mul h (K.inv u)) (K.inv g) := by
  rw [inv_mul_rev, inv_inv, inv_mul_rev, K.assoc]

end Group

/-! ## Lattice, field, gauge transformation -/

inductive D4 where
  | d0
  | d1
  | d2
  | d3

/-- Sites with four shifts that commute. -/
structure Lat (S : Type) where
  sh : S → D4 → S
  comm : ∀ x μ ν, sh (sh x μ) ν = sh (sh x ν) μ

section Field
variable {G : Type} (K : Grp G) {S : Type} (Λ : Lat S)

/-- The holonomy round the plaquette at `x` in the plane `(μ, ν)`. -/
def hol (U : S → D4 → G) (x : S) (μ ν : D4) : G :=
  K.mul (K.mul (K.mul (U x μ) (U (Λ.sh x μ) ν)) (K.inv (U (Λ.sh x ν) μ))) (K.inv (U x ν))

/-- The gauge transformation of a field. -/
def gauge (g : S → G) (U : S → D4 → G) : S → D4 → G :=
  fun x μ => K.mul (K.mul (g x) (U x μ)) (K.inv (g (Λ.sh x μ)))

/-- **The holonomy of a transformed field is the conjugated holonomy.** -/
theorem hol_gauge (g : S → G) (U : S → D4 → G) (x : S) (μ ν : D4) :
    hol K Λ (gauge K Λ g U) x μ ν = K.mul (K.mul (g x) (hol K Λ U x μ ν)) (K.inv (g x)) := by
  show K.mul (K.mul (K.mul
      (K.mul (K.mul (g x) (U x μ)) (K.inv (g (Λ.sh x μ))))
      (K.mul (K.mul (g (Λ.sh x μ)) (U (Λ.sh x μ) ν)) (K.inv (g (Λ.sh (Λ.sh x μ) ν)))))
      (K.inv (K.mul (K.mul (g (Λ.sh x ν)) (U (Λ.sh x ν) μ)) (K.inv (g (Λ.sh (Λ.sh x ν) μ))))))
      (K.inv (K.mul (K.mul (g x) (U x ν)) (K.inv (g (Λ.sh x ν))))) = _
  rw [conj_inv, conj_inv, conj_mul, Λ.comm x ν μ, conj_mul, conj_mul]
  rfl

/-- `gauge g⁻¹ (gauge g U) = U`: a gauge transformation is a bijection of
    configurations, so the counting measure does not see it. -/
theorem gauge_inverse (g : S → G) (U : S → D4 → G) (x : S) (μ : D4) :
    gauge K Λ (fun y => K.inv (g y)) (gauge K Λ g U) x μ = U x μ := by
  show K.mul (K.mul (K.inv (g x)) (K.mul (K.mul (g x) (U x μ)) (K.inv (g (Λ.sh x μ)))))
      (K.inv (K.inv (g (Λ.sh x μ)))) = U x μ
  rw [inv_inv, ← K.assoc (K.inv (g x)), ← K.assoc (K.inv (g x)), K.inv_mul, K.one_mul, K.assoc,
    K.inv_mul, K.mul_one]

/-- A class function: unchanged by conjugation. -/
def IsClass (f : G → Nat) : Prop := ∀ a b, f (K.mul (K.mul a b) (K.inv a)) = f b

/-- The six planes `μ < ν`. -/
def planes : List (D4 × D4) :=
  [(.d0, .d1), (.d0, .d2), (.d0, .d3), (.d1, .d2), (.d1, .d3), (.d2, .d3)]

def lsum {A : Type} (F : A → Nat) : List A → Nat
  | [] => 0
  | a :: as => F a + lsum F as

theorem lsum_ext {A : Type} (F H : A → Nat) (h : ∀ a, F a = H a) : ∀ l, lsum F l = lsum H l
  | [] => rfl
  | a :: as => by
    show F a + lsum F as = H a + lsum H as
    rw [h a, lsum_ext F H h as]

/-- **The action**: sum of `f` over the plaquettes at the listed sites. -/
def action (f : G → Nat) (sites : List S) (U : S → D4 → G) : Nat :=
  lsum (fun x => lsum (fun p => f (hol K Λ U x p.1 p.2)) planes) sites

/-- **Gauge invariance of the action**, for every list of sites, every gauge
    transformation, every field and every class function. -/
theorem action_gauge_inv (f : G → Nat) (hf : IsClass K f) (sites : List S)
    (g : S → G) (U : S → D4 → G) : action K Λ f sites (gauge K Λ g U) = action K Λ f sites U :=
  lsum_ext _ _ (fun x => lsum_ext _ _ (fun p => by
    show f (hol K Λ (gauge K Λ g U) x p.1 p.2) = f (hol K Λ U x p.1 p.2)
    rw [hol_gauge]
    exact hf (g x) _) planes) sites

/-- The Boltzmann weight `t^S` is gauge invariant. -/
theorem weight_gauge_inv (f : G → Nat) (hf : IsClass K f) (sites : List S) (t : Nat)
    (g : S → G) (U : S → D4 → G) :
    t ^ action K Λ f sites (gauge K Λ g U) = t ^ action K Λ f sites U := by
  rw [action_gauge_inv K Λ f hf sites g U]

end Field

/-! ## The torus (Z/L)^4 -/

structure Site where
  c0 : Nat
  c1 : Nat
  c2 : Nat
  c3 : Nat

def up (L n : Nat) : Nat := rem L (n + 1)

def tsh (L : Nat) (x : Site) : D4 → Site
  | .d0 => ⟨up L x.c0, x.c1, x.c2, x.c3⟩
  | .d1 => ⟨x.c0, up L x.c1, x.c2, x.c3⟩
  | .d2 => ⟨x.c0, x.c1, up L x.c2, x.c3⟩
  | .d3 => ⟨x.c0, x.c1, x.c2, up L x.c3⟩

theorem torus_comm (L : Nat) (x : Site) (μ ν : D4) : tsh L (tsh L x μ) ν = tsh L (tsh L x ν) μ := by
  cases μ <;> cases ν <;> rfl

def torus (L : Nat) : Lat Site := ⟨tsh L, torus_comm L⟩

/-- All sites of (Z/L)^4. -/
def sites (L : Nat) : List Site :=
  (List.range L).flatMap fun a => (List.range L).flatMap fun b =>
    (List.range L).flatMap fun c => (List.range L).map fun d => ⟨a, b, c, d⟩

theorem sites_length : (sites 2).length = 16 ∧ (sites 3).length = 81 := ⟨rfl, rfl⟩

theorem torus_action_gauge_inv {G : Type} (K : Grp G) (f : G → Nat) (hf : IsClass K f) (L : Nat)
    (g : Site → G) (U : Site → D4 → G) :
    action K (torus L) f (sites L) (gauge K (torus L) g U) = action K (torus L) f (sites L) U :=
  action_gauge_inv K (torus L) f hf (sites L) g U

/-! ## Q8: the unit quaternions with integer coordinates -/

inductive U4 where
  | e
  | i
  | j
  | k

/-- Product of units: a sign flip and a unit (`ij = k`, `ji = -k`, `i² = -1`, ...). -/
def umul : U4 → U4 → Bool × U4
  | .e, u => (false, u)
  | .i, .e => (false, .i)
  | .i, .i => (true, .e)
  | .i, .j => (false, .k)
  | .i, .k => (true, .j)
  | .j, .e => (false, .j)
  | .j, .i => (true, .k)
  | .j, .j => (true, .e)
  | .j, .k => (false, .i)
  | .k, .e => (false, .k)
  | .k, .i => (false, .j)
  | .k, .j => (true, .i)
  | .k, .k => (true, .e)

def bxor : Bool → Bool → Bool
  | false, b => b
  | true, false => true
  | true, true => false

/-- `±u`: `neg = true` means the minus sign. -/
structure Q8 where
  neg : Bool
  u : U4

def qmul (a b : Q8) : Q8 := ⟨bxor (bxor a.neg b.neg) (umul a.u b.u).1, (umul a.u b.u).2⟩

def isE : U4 → Bool
  | .e => true
  | .i => false
  | .j => false
  | .k => false

/-- `u⁻¹ = -u` for `u = i, j, k`, and `1⁻¹ = 1`. -/
def qinv (a : Q8) : Q8 := ⟨bxor a.neg (!(isE a.u)), a.u⟩

def qone : Q8 := ⟨false, .e⟩

theorem q8_assoc (a b c : Q8) : qmul (qmul a b) c = qmul a (qmul b c) := by
  cases a with
  | mk s u => cases b with
    | mk t v => cases c with
      | mk r w => cases s <;> cases t <;> cases r <;> cases u <;> cases v <;> cases w <;> rfl

theorem q8_one_mul (a : Q8) : qmul qone a = a := by
  cases a with
  | mk s u => cases s <;> cases u <;> rfl

theorem q8_mul_one (a : Q8) : qmul a qone = a := by
  cases a with
  | mk s u => cases s <;> cases u <;> rfl

theorem q8_inv_mul (a : Q8) : qmul (qinv a) a = qone := by
  cases a with
  | mk s u => cases s <;> cases u <;> rfl

theorem q8_mul_inv (a : Q8) : qmul a (qinv a) = qone := by
  cases a with
  | mk s u => cases s <;> cases u <;> rfl

def Q8grp : Grp Q8 := ⟨qmul, qinv, qone, q8_assoc, q8_one_mul, q8_mul_one, q8_inv_mul, q8_mul_inv⟩

/-- Integer coordinates `(w, x, y, z)` of `w + x i + y j + z k`. -/
def toVec (a : Q8) : Int × Int × Int × Int :=
  let s : Int := match a.neg with
    | false => 1
    | true => -1
  match a.u with
  | .e => (s, 0, 0, 0)
  | .i => (0, s, 0, 0)
  | .j => (0, 0, s, 0)
  | .k => (0, 0, 0, s)

/-- The quaternion product of coordinates. -/
def vmul (p q : Int × Int × Int × Int) : Int × Int × Int × Int :=
  let (a1, b1, c1, d1) := p
  let (a2, b2, c2, d2) := q
  (a1 * a2 - b1 * b2 - c1 * c2 - d1 * d2,
   a1 * b2 + b1 * a2 + c1 * d2 - d1 * c2,
   a1 * c2 - b1 * d2 + c1 * a2 + d1 * b2,
   a1 * d2 + b1 * c2 - c1 * b2 + d1 * a2)

def norm2 (p : Int × Int × Int × Int) : Int :=
  p.1 * p.1 + p.2.1 * p.2.1 + p.2.2.1 * p.2.2.1 + p.2.2.2 * p.2.2.2

/-- **Q8 is the group of unit integer quaternions**: its product is the
    quaternion product, and every element has norm 1. -/
theorem mul_is_quaternion (a b : Q8) : toVec (qmul a b) = vmul (toVec a) (toVec b) := by
  cases a with
  | mk s u => cases b with
    | mk t v => cases s <;> cases t <;> cases u <;> cases v <;> rfl

theorem unit_norm (a : Q8) : norm2 (toVec a) = 1 := by
  cases a with
  | mk s u => cases s <;> cases u <;> rfl

def qi : Q8 := ⟨false, .i⟩
def qj : Q8 := ⟨false, .j⟩

theorem q8_noncomm : qmul qi qj ≠ qmul qj qi := fun h =>
  Bool.noConfusion (congrArg (fun a => a.neg) h)

/-! ## Plaquette functions -/

/-- The defect: 1 when the holonomy is not 1. -/
def defect (a : Q8) : Nat :=
  match a.neg, a.u with
  | false, .e => 0
  | false, .i => 1
  | false, .j => 1
  | false, .k => 1
  | true, _ => 1

/-- `2 (1 - Re a)` for a unit quaternion: 0, 2, 4 on the classes 1, ±i ±j ±k, -1
    (the Wilson plaquette function, as a natural number). -/
def wilson2 (a : Q8) : Nat :=
  match a.neg, a.u with
  | false, .e => 0
  | true, .e => 4
  | _, .i => 2
  | _, .j => 2
  | _, .k => 2

theorem defect_class : IsClass Q8grp defect := by
  intro a b
  cases a with
  | mk s u => cases b with
    | mk t v => cases s <;> cases t <;> cases u <;> cases v <;> rfl

theorem wilson_class : IsClass Q8grp wilson2 := by
  intro a b
  cases a with
  | mk s u => cases b with
    | mk t v => cases s <;> cases t <;> cases u <;> cases v <;> rfl

/-- The weight of one plaquette from its four links. -/
def pw (a b c d : Q8) : Nat := defect (qmul (qmul (qmul a b) (qinv c)) (qinv d))

/-- Eight terms in two different groupings. -/
theorem regroup (x x' y y' z w : Nat) :
    x + y + z + w + (x' + y' + z + w) = x + y' + z + w + (x' + y + z + w) := by
  rw [nadd_assoc (x + y) z w, nadd_assoc (x' + y') z w, nadd_assoc (x + y') z w,
    nadd_assoc (x' + y) z w, mid4 (x + y) (z + w) (x' + y') (z + w),
    mid4 (x + y') (z + w) (x' + y) (z + w), mid4 x y x' y', mid4 x y' x' y, nadd_comm y' y]

/-- **Interaction.** The plaquette weight is not a sum of one-link terms:
    there are no `h1 h2 h3 h4` with `pw a b c d = h1 a + h2 b + h3 c + h4 d`.
    (`pw i i 1 1 = 1` since `i² = -1`, while `pw 1 1 1 1 = 0` and
    `pw i 1 1 1 = pw 1 i 1 1 = 1`; a sum of one-link terms would give `1 + 0 = 1 + 1`.) -/
theorem interaction :
    ¬ ∃ h1 h2 h3 h4 : Q8 → Nat, ∀ a b c d, pw a b c d = h1 a + h2 b + h3 c + h4 d := by
  intro ⟨h1, h2, h3, h4, h⟩
  have s : pw qi qi qone qone + pw qone qone qone qone = pw qi qone qone qone + pw qone qi qone qone := by
    rw [h qi qi qone qone, h qone qone qone qone, h qi qone qone qone, h qone qi qone qone]
    exact regroup _ _ _ _ _ _
  have s12 : (1 : Nat) = 2 := s
  exact succ_ne_zero' 0 (succ_inj' s12).symm

/-! ## No action: observables on disjoint link sets do not correlate -/

/-- `Σ_{a ∈ A} Σ_{b ∈ B} F a * H b = (Σ F) (Σ H)`. -/
theorem factor_sum {A B : Type} (F : A → Nat) (H : B → Nat) (bs : List B) :
    ∀ as : List A, lsum (fun a => lsum (fun b => F a * H b) bs) as = lsum F as * lsum H bs
  | [] => (nzero_mul _).symm
  | a :: as => by
    show lsum (fun b => F a * H b) bs + lsum (fun a => lsum (fun b => F a * H b) bs) as
      = (F a + lsum F as) * lsum H bs
    rw [factor_sum F H bs as, nright_distrib, mul_lsum]
where
  mul_lsum : ∀ (c : Nat) (l : List B), lsum (fun b => c * H b) l = c * lsum H l := fun c l => by
    induction l with
    | nil => rfl
    | cons b l ih =>
      show c * H b + lsum (fun b => c * H b) l = c * (H b + lsum H l)
      rw [ih, nleft_distrib]

/-! ## Reflection positivity, for Gram kernels -/

section RP
variable {R : Type} (K : DetChain.CRing R)

/-- A positivity predicate on the ring: squares, sums and products of nonnegatives. -/
structure Positivity where
  nn : R → Prop
  nn_sq : ∀ x, nn (K.mul x x)
  nn_add : ∀ a b, nn a → nn b → nn (K.add a b)
  nn_mul : ∀ a b, nn a → nn b → nn (K.mul a b)
  nn_zero : nn K.zero

def sumK {A : Type} (f : A → R) : List A → R
  | [] => K.zero
  | a :: as => K.add (f a) (sumK f as)

theorem sumK_ext {A : Type} (f g : A → R) (h : ∀ a, f a = g a) : ∀ l, sumK K f l = sumK K g l
  | [] => rfl
  | a :: as => by
    show K.add (f a) (sumK K f as) = K.add (g a) (sumK K g as)
    rw [h a, sumK_ext f g h as]

theorem sumK_add {A : Type} (f g : A → R) :
    ∀ l, sumK K (fun a => K.add (f a) (g a)) l = K.add (sumK K f l) (sumK K g l)
  | [] => (K.zero_add K.zero).symm
  | a :: as => by
    show K.add (K.add (f a) (g a)) (sumK K (fun a => K.add (f a) (g a)) as)
      = K.add (K.add (f a) (sumK K f as)) (K.add (g a) (sumK K g as))
    rw [sumK_add f g as, DetChain.add_mid4]

theorem mul_sumK {A : Type} (c : R) (f : A → R) :
    ∀ l, K.mul c (sumK K f l) = sumK K (fun a => K.mul c (f a)) l
  | [] => DetChain.mul_zero K c
  | a :: as => by
    show K.mul c (K.add (f a) (sumK K f as)) = K.add (K.mul c (f a)) (sumK K (fun a => K.mul c (f a)) as)
    rw [K.distrib, mul_sumK c f as]

theorem sumK_mul {A : Type} (c : R) (f : A → R) (l : List A) :
    K.mul (sumK K f l) c = sumK K (fun a => K.mul (f a) c) l := by
  rw [K.mul_comm, mul_sumK]
  exact sumK_ext K _ _ (fun a => K.mul_comm _ _) l

theorem sumK_swap {A B : Type} (g : A → B → R) (bs : List B) :
    ∀ as : List A, sumK K (fun a => sumK K (fun b => g a b) bs) as
      = sumK K (fun b => sumK K (fun a => g a b) as) bs
  | [] => (zeros bs).symm
  | a :: as => by
    show K.add (sumK K (fun b => g a b) bs) (sumK K (fun a => sumK K (fun b => g a b) bs) as)
      = sumK K (fun b => K.add (g a b) (sumK K (fun a => g a b) as)) bs
    rw [sumK_swap g bs as, sumK_add]
where
  zeros : ∀ l : List B, sumK K (fun _ => K.zero) l = K.zero
    | [] => rfl
    | _ :: l => by
      show K.add K.zero (sumK K (fun _ => K.zero) l) = K.zero
      rw [zeros l, K.zero_add]

/-- A Gram kernel `K(x,y) = Σ_k c_k g_k(x) g_k(y)`, given by its list of `(c_k, g_k)`. -/
def ker {X : Type} (L : List (R × (X → R))) (x y : X) : R :=
  sumK K (fun p => K.mul (K.mul p.1 (p.2 x)) (p.2 y)) L

theorem rearr (a b c d e : R) :
    K.mul (K.mul a b) (K.mul (K.mul c d) e) = K.mul c (K.mul (K.mul a d) (K.mul b e)) := by
  rw [K.mul_assoc c d e, ← K.mul_assoc, K.mul_comm (K.mul a b) c, K.mul_assoc c, ← K.mul_assoc (K.mul a b) d,
    K.mul_assoc a b d, K.mul_comm b d, ← K.mul_assoc a d b, K.mul_assoc (K.mul a d) b e]

/-- **Reflection positivity as a sum of squares.**
    `Σ_x Σ_y F(x) F(y) K(x,y) = Σ_k c_k (Σ_x F(x) g_k(x))²`. -/
theorem rp_identity {X : Type} (F : X → R) (xs : List X) (L : List (R × (X → R))) :
    sumK K (fun x => sumK K (fun y => K.mul (K.mul (F x) (F y)) (ker K L x y)) xs) xs
      = sumK K (fun p => K.mul p.1 (K.mul (sumK K (fun x => K.mul (F x) (p.2 x)) xs)
          (sumK K (fun x => K.mul (F x) (p.2 x)) xs))) L := by
  have e1 : ∀ x y, K.mul (K.mul (F x) (F y)) (ker K L x y)
      = sumK K (fun p => K.mul p.1 (K.mul (K.mul (F x) (p.2 x)) (K.mul (F y) (p.2 y)))) L := fun x y => by
    show K.mul (K.mul (F x) (F y)) (sumK K _ L) = _
    rw [mul_sumK]
    exact sumK_ext K _ _ (fun p => rearr K _ _ _ _ _) L
  rw [sumK_ext K _ _ (fun x => sumK_ext K _ _ (fun y => e1 x y) xs) xs]
  rw [sumK_ext K _ _ (fun x => sumK_swap K _ L xs) xs, sumK_swap]
  refine sumK_ext K _ _ (fun p => ?_) L
  show sumK K (fun x => sumK K (fun y => K.mul p.1 (K.mul ((fun x => K.mul (F x) (p.2 x)) x)
      ((fun x => K.mul (F x) (p.2 x)) y))) xs) xs = _
  generalize (fun x => K.mul (F x) (p.2 x)) = a
  have inner : ∀ x, sumK K (fun y => K.mul p.1 (K.mul (a x) (a y))) xs
      = K.mul p.1 (K.mul (a x) (sumK K a xs)) := fun x => by
    rw [mul_sumK K (a x) a xs, mul_sumK K p.1]
  rw [sumK_ext K _ _ inner xs, sumK_mul K (sumK K a xs) a xs, mul_sumK K p.1]

/-- All coefficients are nonnegative. -/
def AllNN {X : Type} (P : Positivity K) : List (R × (X → R)) → Prop
  | [] => True
  | p :: ps => P.nn p.1 ∧ AllNN P ps

theorem sumK_nn {A : Type} (P : Positivity K) (f : A → R) (h : ∀ a, P.nn (f a)) : ∀ l, P.nn (sumK K f l)
  | [] => P.nn_zero
  | a :: as => P.nn_add _ _ (h a) (sumK_nn P f h as)

theorem sumK_nn_list {X : Type} (P : Positivity K) (f : R × (X → R) → R) :
    ∀ L : List (R × (X → R)), AllNN K P L → (∀ p, P.nn p.1 → P.nn (f p)) → P.nn (sumK K f L)
  | [], _, _ => P.nn_zero
  | p :: ps, h, hf => P.nn_add _ _ (hf p h.1) (sumK_nn_list P f ps h.2 hf)

/-- **⟨θF · F⟩ ≥ 0** for a Gram kernel with nonnegative coefficients. -/
theorem rp_nonneg {X : Type} (P : Positivity K) (F : X → R) (xs : List X) (L : List (R × (X → R)))
    (hL : AllNN K P L) :
    P.nn (sumK K (fun x => sumK K (fun y => K.mul (K.mul (F x) (F y)) (ker K L x y)) xs) xs) := by
  rw [rp_identity]
  exact sumK_nn_list K P _ L hL (fun p hp => P.nn_mul _ _ hp (P.nn_sq _))

/-- Product of Gram lists. -/
def prodG {X : Type} : List (R × (X → R)) → List (R × (X → R)) → List (R × (X → R))
  | [], _ => []
  | p :: ps, L2 => L2.map (fun q => (K.mul p.1 q.1, fun x => K.mul (p.2 x) (q.2 x))) ++ prodG ps L2

theorem sumK_append {A : Type} (f : A → R) : ∀ a b : List A, sumK K f (a ++ b) = K.add (sumK K f a) (sumK K f b)
  | [], b => (K.zero_add _).symm
  | x :: a, b => by
    show K.add (f x) (sumK K f (a ++ b)) = K.add (K.add (f x) (sumK K f a)) (sumK K f b)
    rw [sumK_append f a b, K.add_assoc]

theorem sumK_map {A B : Type} (f : B → R) (g : A → B) : ∀ l : List A, sumK K f (l.map g) = sumK K (fun a => f (g a)) l
  | [] => rfl
  | a :: as => by
    show K.add (f (g a)) (sumK K f (as.map g)) = K.add (f (g a)) (sumK K (fun a => f (g a)) as)
    rw [sumK_map f g as]

theorem mul_mid4 (a b c d : R) : K.mul (K.mul a b) (K.mul c d) = K.mul (K.mul a c) (K.mul b d) := by
  rw [K.mul_assoc, ← K.mul_assoc b c d, K.mul_comm b c, K.mul_assoc c b d, ← K.mul_assoc]

theorem rearr2 (c1 a1 b1 c2 a2 b2 : R) :
    K.mul (K.mul (K.mul c1 c2) (K.mul a1 a2)) (K.mul b1 b2)
      = K.mul (K.mul (K.mul c1 a1) b1) (K.mul (K.mul c2 a2) b2) := by
  rw [K.mul_assoc, mul_mid4 K a1 a2 b1 b2, mul_mid4 K c1 c2 (K.mul a1 b1) (K.mul a2 b2),
    ← K.mul_assoc c1 a1 b1, ← K.mul_assoc c2 a2 b2]

/-- **The product of two Gram kernels is the Gram kernel of the product list.** -/
theorem gram_mul {X : Type} (L1 L2 : List (R × (X → R))) (x y : X) :
    ker K (prodG K L1 L2) x y = K.mul (ker K L1 x y) (ker K L2 x y) := by
  induction L1 with
  | nil => exact (DetChain.zero_mul' K _).symm
  | cons p ps ih =>
    show sumK K _ (L2.map _ ++ prodG K ps L2) = K.mul (K.add _ (ker K ps x y)) (ker K L2 x y)
    rw [sumK_append, sumK_map]
    show K.add _ (ker K (prodG K ps L2) x y) = _
    rw [ih, DetChain.right_distrib]
    congr 1
    show _ = K.mul _ (sumK K _ L2)
    rw [mul_sumK]
    exact sumK_ext K _ _ (fun q => rearr2 K _ _ _ _ _ _) L2

theorem gram_mul_nn {X : Type} (P : Positivity K) :
    ∀ L1 L2 : List (R × (X → R)), AllNN K P L1 → AllNN K P L2 → AllNN K P (prodG K L1 L2)
  | [], _, _, _ => trivial
  | p :: ps, L2, h1, h2 => by
    show AllNN K P (L2.map _ ++ prodG K ps L2)
    exact app_nn _ _ (map_nn p h1.1 L2 h2) (gram_mul_nn P ps L2 h1.2 h2)
where
  map_nn (p : R × (X → R)) (hp : P.nn p.1) :
      ∀ L2 : List (R × (X → R)), AllNN K P L2 →
        AllNN K P (L2.map (fun q => (K.mul p.1 q.1, fun x => K.mul (p.2 x) (q.2 x))))
    | [], _ => trivial
    | q :: qs, h => ⟨P.nn_mul _ _ hp h.1, map_nn p hp qs h.2⟩
  app_nn : ∀ (a b : List (R × (X → R))), AllNN K P a → AllNN K P b → AllNN K P (a ++ b)
    | [], _, _, hb => hb
    | _ :: a, b, ha, hb => ⟨ha.1, app_nn a b ha.2 hb⟩

/-- Indicator in the ring. -/
def indR : Bool → R
  | true => K.one
  | false => K.zero

def memL {G : Type} : G → List G → Prop
  | _, [] => False
  | a, b :: bs => a = b ∨ memL a bs

def distinctL {G : Type} : List G → Prop
  | [] => True
  | a :: as => (¬ memL a as) ∧ distinctL as

/-- **The diagonal is Gram**: for a list `Gs` with no repeats containing `g`,
    `Σ_{k∈Gs} [g = k][h = k] = [g = h]`. -/
theorem delta_gram {G : Type} (eqb : G → G → Bool) (sound : ∀ a b, eqb a b = true → a = b)
    (refl : ∀ a, eqb a a = true) (symm : ∀ a b, eqb a b = eqb b a) (g h : G) :
    ∀ Gs : List G, distinctL Gs → memL g Gs →
      sumK K (fun k => K.mul (indR K (eqb g k)) (indR K (eqb h k))) Gs = indR K (eqb g h)
  | [], _, hm => False.elim hm
  | k :: ks, hd, hm => by
    show K.add (K.mul (indR K (eqb g k)) (indR K (eqb h k))) (sumK K _ ks) = _
    cases e : eqb g k with
    | true =>
      have gk : g = k := sound g k e
      rw [← gk] at hd
      have rest : sumK K (fun k => K.mul (indR K (eqb g k)) (indR K (eqb h k))) ks = K.zero :=
        zero_rest ks hd.1
      rw [rest, DetChain.add_zero', ← gk, symm h g]
      exact DetChain.CRing.one_mul K _
    | false =>
      have hm' : memL g ks := by
        cases hm with
        | inl hg => rw [hg, refl] at e; exact Bool.noConfusion e
        | inr hr => exact hr
      rw [show K.mul (indR K false) (indR K (eqb h k)) = K.zero from DetChain.zero_mul' K _, K.zero_add]
      exact delta_gram eqb sound refl symm g h ks hd.2 hm'
where
  zero_rest : ∀ ks : List G, ¬ memL g ks →
      sumK K (fun k => K.mul (indR K (eqb g k)) (indR K (eqb h k))) ks = K.zero
    | [], _ => rfl
    | k :: ks, hn => by
      show K.add (K.mul (indR K (eqb g k)) (indR K (eqb h k))) (sumK K _ ks) = K.zero
      cases e : eqb g k with
      | true => exact absurd (Or.inl (sound g k e)) hn
      | false =>
        rw [show K.mul (indR K false) (indR K (eqb h k)) = K.zero from DetChain.zero_mul' K _, K.zero_add]
        exact zero_rest ks (fun hm => hn (Or.inr hm))

/-- **The defect weight of a crossing plaquette is a Gram kernel**:
    `a + b [g = h] = a·1·1 + Σ_k b [g = k][h = k]`, with coefficients `a, b`. -/
theorem defect_gram {G : Type} (eqb : G → G → Bool) (sound : ∀ a b, eqb a b = true → a = b)
    (refl : ∀ a, eqb a a = true) (symm : ∀ a b, eqb a b = eqb b a) (a b : R) (g h : G) (Gs : List G)
    (hd : distinctL Gs) (hg : memL g Gs) :
    ker K ((a, fun _ => K.one) :: Gs.map (fun k => (b, fun x => indR K (eqb x k)))) g h
      = K.add a (K.mul b (indR K (eqb g h))) := by
  show K.add (K.mul (K.mul a K.one) K.one) (sumK K _ (Gs.map _)) = _
  rw [sumK_map, DetChain.CRing.mul_comm K a K.one, DetChain.CRing.one_mul, DetChain.CRing.mul_comm K a K.one,
    DetChain.CRing.one_mul, ← delta_gram K eqb sound refl symm g h Gs hd hg, mul_sumK]
  congr 1
  exact sumK_ext K _ _ (fun k => DetChain.CRing.mul_assoc K _ _ _) Gs

end RP

/-! ## Transfer matrix: positive entries -/

/-- `Π_i q^(n_i)` with `q ≥ 1`: every entry of the transfer matrix (weight of a
    time step, written as `q` to the number of non-defective plaquettes) is ≥ 1. -/
def prodPow (q : Nat) : List Nat → Nat
  | [] => 1
  | n :: ns => q ^ n * prodPow q ns

theorem pow_pos' (q : Nat) (hq : 0 < q) : ∀ n, 0 < q ^ n
  | 0 => Nat.zero_lt_succ 0
  | n + 1 => Nat.mul_le_mul (pow_pos' q hq n) hq

theorem transfer_pos (q : Nat) (hq : 0 < q) : ∀ ns, 0 < prodPow q ns
  | [] => Nat.zero_lt_succ 0
  | n :: ns => Nat.mul_le_mul (pow_pos' q hq n) (transfer_pos q hq ns)

/-! ## Counting surfaces -/

/-- All words of length `n` over the letters `as`. -/
def consAll {α : Type} : List α → List (List α) → List (List α)
  | [], _ => []
  | a :: as, ws => ws.map (List.cons a) ++ consAll as ws

def words {α : Type} (as : List α) : Nat → List (List α)
  | 0 => [[]]
  | n + 1 => consAll as (words as n)

theorem len_app2 {β : Type} : ∀ a b : List β, (a ++ b).length = a.length + b.length
  | [], b => (Nat.zero_add b.length).symm
  | _ :: a, b => by
    show (a ++ b).length + 1 = a.length + 1 + b.length
    rw [len_app2 a b, Nat.add_right_comm]

theorem len_map2 {β γ : Type} (f : β → γ) : ∀ a : List β, (a.map f).length = a.length
  | [] => rfl
  | _ :: a => congrArg (· + 1) (len_map2 f a)

theorem consAll_length {α : Type} (ws : List (List α)) : ∀ as : List α, (consAll as ws).length = as.length * ws.length
  | [] => (nzero_mul _).symm
  | _ :: as => by
    show (ws.map _ ++ consAll as ws).length = (as.length + 1) * ws.length
    rw [len_app2, len_map2, consAll_length ws as, nsucc_mul, nadd_comm]

/-- **There are `k^n` words of length `n` over `k` letters.** -/
theorem words_length {α : Type} (as : List α) : ∀ n, (words as n).length = as.length ^ n
  | 0 => rfl
  | n + 1 => by
    show (consAll as (words as n)).length = as.length ^ n * as.length
    rw [consAll_length, words_length as n, nmul_comm]

/-- **Surface count.** A connected plaquette surface of area `A` is coded by a
    depth-first walk on its plaquettes: `2A` letters, each a neighbour direction
    (`D` of them) or a step back. There are `(D+1)^(2A) = ((D+1)^2)^A` codes. -/
theorem surface_count {α : Type} (dirs : List α) (back : α) (A : Nat) :
    (words (back :: dirs) (A + A)).length = ((dirs.length + 1) * (dirs.length + 1)) ^ A := by
  rw [words_length]
  show (dirs.length + 1) ^ (A + A) = _
  exact pow_double (dirs.length + 1) A
where
  pow_double (k : Nat) : ∀ A, k ^ (A + A) = (k * k) ^ A
    | 0 => rfl
    | A + 1 => by
      rw [← Nat.add_assoc (A + 1) A 1, Nat.add_right_comm A 1 A]
      show k ^ (A + A) * k * k = (k * k) ^ A * (k * k)
      rw [pow_double k A, nmul_assoc]

/-! ## The geometric bound: decay independent of L -/

/-- `T(N) = Σ_{j ≤ N} c^j q^(N-j)`. -/
def geomT (c q : Nat) : Nat → Nat
  | 0 => 1
  | N + 1 => q * geomT c q N + c ^ (N + 1)

/-- **Telescoping**: `q T(N) + c^(N+1) = q^(N+1) + c T(N)`. -/
theorem geom_telescope (c q : Nat) : ∀ N, q * geomT c q N + c ^ (N + 1) = q ^ (N + 1) + c * geomT c q N
  | 0 => by
    show q * 1 + 1 * c = 1 * q + c * 1
    rw [nmul_one, nmul_one, Nat.one_mul, Nat.one_mul]
  | N + 1 => by
    have ih := geom_telescope c q N
    show q * (q * geomT c q N + c ^ (N + 1)) + c ^ (N + 1) * c
      = q ^ (N + 1) * q + c * (q * geomT c q N + c ^ (N + 1))
    have L : q * (q * geomT c q N + c ^ (N + 1)) + c ^ (N + 1) * c
        = q ^ (N + 1) * q + c * (q * geomT c q N) + c * c ^ (N + 1) := by
      rw [ih, nleft_distrib, nmul_comm q (q ^ (N + 1)), nmul_comm (c ^ (N + 1)) c, ← nmul_assoc q c,
        nmul_comm q c, nmul_assoc c q]
    rw [L, nleft_distrib c (q * geomT c q N) (c ^ (N + 1)), nadd_assoc]

theorem le_cancel {a b : Nat} (h : a + a ≤ b + a) : a ≤ b := by
  cases Nat.lt_or_ge b a with
  | inl hlt => exact absurd h (Nat.not_le_of_lt (Nat.add_lt_add_right hlt a))
  | inr hge => exact hge

/-- **Geometric bound**: if `2c ≤ q` then `T(N) ≤ 2 q^N`. -/
theorem geom_bound (c q : Nat) (hq : 0 < q) (hc : 2 * c ≤ q) (N : Nat) : geomT c q N ≤ 2 * q ^ N := by
  have tel := geom_telescope c q N
  have h1 : q * geomT c q N ≤ q ^ (N + 1) + c * geomT c q N :=
    tel ▸ Nat.le_add_right (q * geomT c q N) (c ^ (N + 1))
  have h2 : 2 * (q * geomT c q N) ≤ 2 * q ^ (N + 1) + q * geomT c q N := by
    have a := Nat.mul_le_mul_left 2 h1
    rw [nleft_distrib, ← nmul_assoc 2 c] at a
    exact Nat.le_trans a (Nat.add_le_add (Nat.le_refl _) (Nat.mul_le_mul_right _ hc))
  rw [Nat.two_mul (q * geomT c q N)] at h2
  have h4 : q * geomT c q N ≤ 2 * q ^ (N + 1) := le_cancel h2
  have e : q * (2 * q ^ N) = 2 * q ^ (N + 1) := by
    rw [← nmul_assoc, nmul_comm q 2, nmul_assoc, nmul_comm q (q ^ N)]
    rfl
  have h3 : q * geomT c q N ≤ q * (2 * q ^ N) := by
    rw [e]
    exact h4
  exact Nat.le_of_mul_le_mul_left h3 hq

/-- **Decay with a rate independent of L.** If a correlation at distance `t` is
    bounded by a sum over surfaces of area `A ≥ t` with at most `c^A` surfaces of
    area `A`, each of weight `ε^A = q^(-A)`, then (multiplying by `q^(t+N)`)
    `Σ_{A=t}^{t+N} c^A q^(t+N-A) ≤ 2 c^t q^N`, i.e. the sum is `≤ 2 (c/q)^t`.
    Nothing here depends on the lattice size. -/
theorem decay_bound (c q t : Nat) (hq : 0 < q) (hc : 2 * c ≤ q) (N : Nat) :
    c ^ t * geomT c q N ≤ 2 * c ^ t * q ^ N := by
  have h := Nat.mul_le_mul_left (c ^ t) (geom_bound c q hq hc N)
  rw [← nmul_assoc, nmul_comm (c ^ t) 2] at h
  exact h

/-! ## An explicit β₀ -/

/-- In four dimensions a plaquette shares an edge with `D = 20` others; the
    surface constant is `c = (D+1)² = 441`. -/
theorem c_441 : (20 + 1) * (20 + 1) = 441 := rfl

theorem mul_pow' (a b : Nat) : ∀ t, (a * b) ^ t = a ^ t * b ^ t
  | 0 => rfl
  | t + 1 => by
    show (a * b) ^ t * (a * b) = a ^ t * a * (b ^ t * b)
    rw [mul_pow' a b t, mmid4]

/-- **Strong coupling with an explicit β₀.** Let every plaquette of a polymer
    carry activity at most `ε = 1/q`. For the Wilson action `ε ≤ 1 - e^(-2β) ≤ 2β`,
    for the defect action `ε ≤ 1 - e^(-β) ≤ β`. If `q ≥ 882`, i.e. `β ≤ β₀ = 1/1764`
    (Wilson) or `β ≤ 1/882` (defect), then for every `t` and every cut-off `N`:
    the surface sum `Σ_{A=t}^{t+N} 441^A q^(t+N-A)` is at most `2 · 441^t q^N`, and
    `2^t · 441^t ≤ q^t`. Together: the sum is `≤ 2 · 2^(-t)`, a decay rate `≥ ln 2`
    in every finite volume. No lattice size enters. -/
theorem gap_explicit (q : Nat) (hq : 882 ≤ q) (t N : Nat) :
    441 ^ t * geomT 441 q N ≤ 2 * 441 ^ t * q ^ N ∧ 2 ^ t * 441 ^ t ≤ q ^ t := by
  have hq0 : 0 < q := Nat.lt_of_lt_of_le (Nat.zero_lt_succ 881) hq
  refine ⟨decay_bound 441 q t hq0 hq N, ?_⟩
  rw [← mul_pow']
  exact Nat.pow_le_pow_left hq t

/-! ## Perron: the top eigenvalue of a positive matrix is simple -/

section Perron
variable {R : Type} (K : DetChain.CRing R)

/-- An order on the ring, given by its laws. -/
structure ORing where
  le : R → R → Prop
  le_refl : ∀ a, le a a
  le_trans : ∀ a b c, le a b → le b c → le a c
  le_antisymm : ∀ a b, le a b → le b a → a = b
  le_total : ∀ a b, le a b ∨ le b a
  add_le_add : ∀ a b c d, le a b → le c d → le (K.add a c) (K.add b d)
  mul_nonneg : ∀ a b, le K.zero a → le K.zero b → le K.zero (K.mul a b)
  mul_le_mul_right : ∀ a b c, le a b → le K.zero c → le (K.mul a c) (K.mul b c)
  pos_cancel : ∀ a b c, le K.zero c → c ≠ K.zero → le (K.mul a c) (K.mul b c) → le a b
  pos_mul_eq_zero : ∀ a b, le K.zero a → a ≠ K.zero → K.mul a b = K.zero → b = K.zero

variable (O : ORing K)

def Pos (a : R) : Prop := O.le K.zero a ∧ a ≠ K.zero

/-- A minimiser of the ratios `w_i / u_i`, in cross-multiplied form. -/
theorem argmin (u w : Nat → R) (hu : ∀ i, Pos K O (u i)) :
    ∀ (a : Nat) (rest : List Nat), ∃ k, memL k (a :: rest) ∧
      ∀ j, memL j (a :: rest) → O.le (K.mul (w k) (u j)) (K.mul (w j) (u k))
  | a, [] => ⟨a, Or.inl rfl, fun j hj => by
      cases hj with
      | inl h => rw [h]; exact O.le_refl _
      | inr h => exact False.elim h⟩
  | a, b :: rest => by
    obtain ⟨k', hk'm, hk'⟩ := argmin u w hu b rest
    cases O.le_total (K.mul (w a) (u k')) (K.mul (w k') (u a)) with
    | inl hle =>
      refine ⟨a, Or.inl rfl, fun j hj => ?_⟩
      cases hj with
      | inl h => rw [h]; exact O.le_refl _
      | inr h =>
        -- w_a u_j u_k' ≤ w_k' u_a u_j ≤ ... ≤ w_j u_a u_k'
        have h1 := O.mul_le_mul_right _ _ (u j) hle (hu j).1
        have h2 := O.mul_le_mul_right _ _ (u a) (hk' j h) (hu a).1
        apply O.pos_cancel _ _ (u k') (hu k').1 (hu k').2
        have e1 : K.mul (K.mul (w a) (u j)) (u k') = K.mul (K.mul (w a) (u k')) (u j) := by
          rw [K.mul_assoc, K.mul_comm (u j), ← K.mul_assoc]
        have e2 : K.mul (K.mul (w k') (u a)) (u j) = K.mul (K.mul (w k') (u j)) (u a) := by
          rw [K.mul_assoc, K.mul_comm (u a), ← K.mul_assoc]
        have e3 : K.mul (K.mul (w j) (u k')) (u a) = K.mul (K.mul (w j) (u a)) (u k') := by
          rw [K.mul_assoc, K.mul_comm (u k'), ← K.mul_assoc]
        rw [e1]
        exact O.le_trans _ _ _ h1 (e2 ▸ (e3 ▸ h2))
    | inr hge =>
      refine ⟨k', Or.inr hk'm, fun j hj => ?_⟩
      cases hj with
      | inl h => rw [h]; exact hge
      | inr h => exact hk' j h

/-- A sum of nonnegative terms that vanishes has every term zero. -/
theorem sum_zero_each (f : Nat → R) :
    ∀ l : List Nat, (∀ j, memL j l → O.le K.zero (f j)) → sumK K f l = K.zero →
      ∀ j, memL j l → f j = K.zero
  | [], _, _, _, hj => False.elim hj
  | a :: rest, hnn, hs, j, hj => by
    have hrest : O.le K.zero (sumK K f rest) := nn_sum rest (fun i hi => hnn i (Or.inr hi))
    have hs' : K.add (f a) (sumK K f rest) = K.zero := hs
    have ha0 : f a = K.zero := by
      apply O.le_antisymm _ _ _ (hnn a (Or.inl rfl))
      have := O.add_le_add _ _ _ _ (O.le_refl (f a)) hrest
      rw [DetChain.add_zero', hs'] at this
      exact this
    have hr0 : sumK K f rest = K.zero := by
      rw [ha0, K.zero_add] at hs'
      exact hs'
    cases hj with
    | inl h => rw [h]; exact ha0
    | inr h => exact sum_zero_each f rest (fun i hi => hnn i (Or.inr hi)) hr0 j h
where
  nn_sum : ∀ l : List Nat, (∀ j, memL j l → O.le K.zero (f j)) → O.le K.zero (sumK K f l)
    | [], _ => O.le_refl _
    | a :: rest, h => by
      have := O.add_le_add _ _ _ _ (h a (Or.inl rfl)) (nn_sum rest (fun i hi => h i (Or.inr hi)))
      rw [K.zero_add] at this
      exact this

theorem sumK_sub (f g : Nat → R) :
    ∀ l : List Nat, sumK K (fun j => K.add (f j) (K.neg (g j))) l = K.add (sumK K f l) (K.neg (sumK K g l))
  | [] => by
    show K.zero = K.add K.zero (K.neg K.zero)
    rw [K.add_neg]
  | a :: rest => by
    show K.add (K.add (f a) (K.neg (g a))) (sumK K _ rest)
      = K.add (K.add (f a) (sumK K f rest)) (K.neg (K.add (g a) (sumK K g rest)))
    rw [sumK_sub f g rest, neg_add'' (g a) (sumK K g rest), DetChain.add_mid4]
where
  neg_add'' : ∀ x y : R, K.neg (K.add x y) = K.add (K.neg x) (K.neg y) := fun x y => by
    apply Eq.symm
    apply DetChain.neg_unique
    rw [DetChain.add_mid4, DetChain.add_neg', DetChain.add_neg', K.zero_add]

theorem mul_neg_r (a b : R) : K.mul a (K.neg b) = K.neg (K.mul a b) := by
  rw [K.mul_comm, DetChain.neg_mul_left, K.mul_comm]

theorem swap3 (a b c : R) : K.mul a (K.mul b c) = K.mul b (K.mul a c) := by
  rw [← K.mul_assoc, K.mul_comm a b, K.mul_assoc]

/-- **The Perron eigenvalue has a one-dimensional eigenspace.** Let `T` have
    positive entries on the index list, `u` a positive eigenvector with
    eigenvalue `λ`, and `w` any eigenvector with the same eigenvalue. Then `w` is
    proportional to `u`: for some index `k`, `u_k w_j = w_k u_j` for all `j`. -/
theorem perron_simple (T : Nat → Nat → R) (u w : Nat → R) (lam : R) (a : Nat) (rest : List Nat)
    (hT : ∀ i j, Pos K O (T i j)) (hu : ∀ i, Pos K O (u i))
    (heu : ∀ i, sumK K (fun j => K.mul (T i j) (u j)) (a :: rest) = K.mul lam (u i))
    (hew : ∀ i, sumK K (fun j => K.mul (T i j) (w j)) (a :: rest) = K.mul lam (w i)) :
    ∃ k, memL k (a :: rest) ∧ ∀ j, memL j (a :: rest) → K.mul (u k) (w j) = K.mul (w k) (u j) := by
  obtain ⟨k, hkm, hk⟩ := argmin K O u w hu a rest
  refine ⟨k, hkm, ?_⟩
  -- z_j = u_k w_j - w_k u_j ≥ 0
  let z : Nat → R := fun j => K.add (K.mul (u k) (w j)) (K.neg (K.mul (w k) (u j)))
  have hz : ∀ j, memL j (a :: rest) → O.le K.zero (z j) := fun j hj => by
    have h := O.add_le_add _ _ _ _ (hk j hj) (O.le_refl (K.neg (K.mul (w k) (u j))))
    have e1 : K.add (K.mul (w k) (u j)) (K.neg (K.mul (w k) (u j))) = K.zero := K.add_neg _
    have e2 : K.mul (w j) (u k) = K.mul (u k) (w j) := K.mul_comm _ _
    rw [e1, e2] at h
    exact h
  -- Σ_j T_kj z_j = u_k (λ w_k) - w_k (λ u_k) = 0
  have hsum : sumK K (fun j => K.mul (T k j) (z j)) (a :: rest) = K.zero := by
    have e : sumK K (fun j => K.mul (T k j) (z j)) (a :: rest)
        = sumK K (fun j => K.add (K.mul (u k) (K.mul (T k j) (w j)))
            (K.neg (K.mul (w k) (K.mul (T k j) (u j))))) (a :: rest) :=
      sumK_ext K _ _ (fun j => by
        show K.mul (T k j) (K.add (K.mul (u k) (w j)) (K.neg (K.mul (w k) (u j)))) = _
        rw [K.distrib, mul_neg_r K, swap3 K (T k j) (u k) (w j), swap3 K (T k j) (w k) (u j)]) (a :: rest)
    rw [e, sumK_sub, ← mul_sumK, ← mul_sumK, hew k, heu k, swap3 K (u k) lam (w k),
      swap3 K (w k) lam (u k), K.mul_comm (w k) (u k), K.add_neg]
  have each := sum_zero_each K O (fun j => K.mul (T k j) (z j)) (a :: rest)
    (fun j hj => O.mul_nonneg _ _ (hT k j).1 (hz j hj)) hsum
  intro j hj
  have hz0 : z j = K.zero := O.pos_mul_eq_zero _ _ (hT k j).1 (hT k j).2 (each j hj)
  have := DetChain.neg_unique K _ _ hz0
  rw [DetChain.neg_neg'] at this
  exact this

end Perron

/-! ## T27: dominance and a strict gap; Gram symmetry; block spin -/

section Gap
variable {R : Type} (K : DetChain.CRing R) (O : ORing K)

/-- Absolute value and the extra laws used for the gap (an ordered field gives them). -/
structure AbsLaws where
  abs : R → R
  abs_nonneg : ∀ a, O.le K.zero (abs a)
  abs_mul : ∀ a b, abs (K.mul a b) = K.mul (abs a) (abs b)
  abs_add : ∀ a b, O.le (abs (K.add a b)) (K.add (abs a) (abs b))
  abs_of_nonneg : ∀ a, O.le K.zero a → abs a = a
  abs_eq_zero : ∀ a, abs a = K.zero → a = K.zero
  mul_self_nonneg : ∀ a, O.le K.zero (K.mul a a)
  mul_right_cancel : ∀ a b c, c ≠ K.zero → K.mul a c = K.mul b c → a = b

variable (A : AbsLaws K O)

theorem sum_le (f g : Nat → R) : ∀ l : List Nat, (∀ j, memL j l → O.le (f j) (g j)) →
    O.le (sumK K f l) (sumK K g l)
  | [], _ => O.le_refl _
  | a :: rest, h => O.add_le_add _ _ _ _ (h a (Or.inl rfl)) (sum_le f g rest (fun j hj => h j (Or.inr hj)))

theorem abs_sum (f : Nat → R) : ∀ l : List Nat, O.le (A.abs (sumK K f l)) (sumK K (fun j => A.abs (f j)) l)
  | [] => by
    show O.le (A.abs K.zero) K.zero
    rw [A.abs_of_nonneg _ (O.le_refl _)]
    exact O.le_refl _
  | a :: rest => O.le_trans _ _ _ (A.abs_add _ _) (O.add_le_add _ _ _ _ (O.le_refl _) (abs_sum f rest))

/-- A maximiser of `|w_i| / u_i`, cross-multiplied. -/
theorem argmax (u v : Nat → R) (hu : ∀ i, Pos K O (u i)) :
    ∀ (a : Nat) (rest : List Nat), ∃ k, memL k (a :: rest) ∧
      ∀ j, memL j (a :: rest) → O.le (K.mul (v j) (u k)) (K.mul (v k) (u j))
  | a, [] => ⟨a, Or.inl rfl, fun j hj => by
      cases hj with
      | inl h => rw [h]; exact O.le_refl _
      | inr h => exact False.elim h⟩
  | a, b :: rest => by
    obtain ⟨k', hk'm, hk'⟩ := argmax u v hu b rest
    cases O.le_total (K.mul (v k') (u a)) (K.mul (v a) (u k')) with
    | inl hle =>
      refine ⟨a, Or.inl rfl, fun j hj => ?_⟩
      cases hj with
      | inl h => rw [h]; exact O.le_refl _
      | inr h =>
        have h1 := O.mul_le_mul_right _ _ (u a) (hk' j h) (hu a).1
        have h2 := O.mul_le_mul_right _ _ (u j) hle (hu j).1
        apply O.pos_cancel _ _ (u k') (hu k').1 (hu k').2
        have e1 : K.mul (K.mul (v j) (u a)) (u k') = K.mul (K.mul (v j) (u k')) (u a) := by
          rw [K.mul_assoc, K.mul_comm (u a), ← K.mul_assoc]
        have e2 : K.mul (K.mul (v k') (u j)) (u a) = K.mul (K.mul (v k') (u a)) (u j) := by
          rw [K.mul_assoc, K.mul_comm (u j), ← K.mul_assoc]
        have e3 : K.mul (K.mul (v a) (u k')) (u j) = K.mul (K.mul (v a) (u j)) (u k') := by
          rw [K.mul_assoc, K.mul_comm (u k'), ← K.mul_assoc]
        rw [e1]
        exact O.le_trans _ _ _ h1 (e2 ▸ (e3 ▸ h2))
    | inr hge =>
      refine ⟨k', Or.inr hk'm, fun j hj => ?_⟩
      cases hj with
      | inl h => rw [h]; exact hge
      | inr h => exact hk' j h

/-- **Dominance.** For a matrix with positive entries, a positive eigenvector `u`
    (eigenvalue `λ`) and any nonzero eigenvector `w` (eigenvalue `μ`): `|μ| ≤ λ`. -/
theorem perron_dominant (T : Nat → Nat → R) (u w : Nat → R) (lam mu : R) (a : Nat) (rest : List Nat)
    (hT : ∀ i j, Pos K O (T i j)) (hu : ∀ i, Pos K O (u i))
    (heu : ∀ i, sumK K (fun j => K.mul (T i j) (u j)) (a :: rest) = K.mul lam (u i))
    (hew : ∀ i, sumK K (fun j => K.mul (T i j) (w j)) (a :: rest) = K.mul mu (w i))
    (i0 : Nat) (hi0 : memL i0 (a :: rest)) (hw0 : w i0 ≠ K.zero) :
    O.le (A.abs mu) lam := by
  obtain ⟨k, hkm, hk⟩ := argmax K O u (fun j => A.abs (w j)) hu a rest
  -- |w_k| ≠ 0
  have hwk : A.abs (w k) ≠ K.zero := fun h0 => by
    have h := hk i0 hi0
    rw [h0, DetChain.zero_mul' K] at h
    have h' : O.le (K.mul (A.abs (w i0)) (u k)) (K.mul K.zero (u k)) := by
      rw [DetChain.zero_mul' K]; exact h
    have hle := O.pos_cancel _ _ _ (hu k).1 (hu k).2 h'
    exact hw0 (A.abs_eq_zero _ (O.le_antisymm _ _ hle (A.abs_nonneg _)))
  -- |μ| |w_k| ≤ Σ_j T_kj |w_j|
  have s1 : O.le (K.mul (A.abs mu) (A.abs (w k))) (sumK K (fun j => K.mul (T k j) (A.abs (w j))) (a :: rest)) := by
    rw [← A.abs_mul, ← hew k]
    refine O.le_trans _ _ _ (abs_sum K O A _ _) (sum_le K O _ _ _ (fun j _ => ?_))
    rw [A.abs_mul, A.abs_of_nonneg _ (hT k j).1]
    exact O.le_refl _
  -- (Σ_j T_kj |w_j|) u_k ≤ (Σ_j T_kj u_j) |w_k| = λ u_k |w_k|
  have s2 : O.le (K.mul (sumK K (fun j => K.mul (T k j) (A.abs (w j))) (a :: rest)) (u k))
      (K.mul (K.mul lam (u k)) (A.abs (w k))) := by
    rw [← heu k, sumK_mul, sumK_mul]
    refine sum_le K O _ _ _ (fun j hj => ?_)
    show O.le (K.mul (K.mul (T k j) (A.abs (w j))) (u k)) (K.mul (K.mul (T k j) (u j)) (A.abs (w k)))
    rw [K.mul_assoc, K.mul_assoc]
    have := O.mul_le_mul_right _ _ (T k j) (hk j hj) (hT k j).1
    rw [K.mul_comm (K.mul (A.abs (w j)) (u k)) (T k j), K.mul_comm (K.mul (A.abs (w k)) (u j)) (T k j)] at this
    rw [K.mul_comm (u j) (A.abs (w k))]
    exact this
  have s3 := O.le_trans _ _ _ (O.mul_le_mul_right _ _ (u k) s1 (hu k).1) s2
  -- cancel u_k, then |w_k|
  have e : K.mul (K.mul lam (u k)) (A.abs (w k)) = K.mul (K.mul lam (A.abs (w k))) (u k) := by
    rw [K.mul_assoc, K.mul_comm (u k), ← K.mul_assoc]
  rw [e] at s3
  have s4 := O.pos_cancel _ _ _ (hu k).1 (hu k).2 s3
  exact O.pos_cancel _ _ _ (A.abs_nonneg _) hwk s4

/-- `T²` with entries `Σ_k T_ik T_kj`. -/
def sq (T : Nat → Nat → R) (idx : List Nat) (i j : Nat) : R := sumK K (fun k => K.mul (T i k) (T k j)) idx

theorem pos_sum (f : Nat → R) (a : Nat) (rest : List Nat) (h : ∀ j, Pos K O (f j)) :
    Pos K O (sumK K f (a :: rest)) := by
  have nn : ∀ l : List Nat, O.le K.zero (sumK K f l) := fun l =>
    sum_zero_each.nn_sum K O f l (fun j _ => (h j).1)
  refine ⟨nn _, fun h0 => ?_⟩
  exact (h a).2 (sum_zero_each K O f (a :: rest) (fun j _ => (h j).1) h0 a (Or.inl rfl))

theorem sq_eigen (T : Nat → Nat → R) (v : Nat → R) (c : R) (idx : List Nat)
    (hev : ∀ i, sumK K (fun j => K.mul (T i j) (v j)) idx = K.mul c (v i)) (i : Nat) :
    sumK K (fun j => K.mul (sq K T idx i j) (v j)) idx = K.mul (K.mul c c) (v i) := by
  have e1 : sumK K (fun j => K.mul (sq K T idx i j) (v j)) idx
      = sumK K (fun j => sumK K (fun k => K.mul (T i k) (K.mul (T k j) (v j))) idx) idx :=
    sumK_ext K _ _ (fun j => by
      show K.mul (sumK K _ idx) (v j) = _
      rw [sumK_mul]
      exact sumK_ext K _ _ (fun k => K.mul_assoc _ _ _) idx) idx
  rw [e1, sumK_swap]
  have e2 : sumK K (fun k => sumK K (fun j => K.mul (T i k) (K.mul (T k j) (v j))) idx) idx
      = sumK K (fun k => K.mul (T i k) (K.mul c (v k))) idx :=
    sumK_ext K _ _ (fun k => by rw [← mul_sumK, hev k]) idx
  rw [e2]
  have e3 : sumK K (fun k => K.mul (T i k) (K.mul c (v k))) idx = K.mul c (sumK K (fun k => K.mul (T i k) (v k)) idx) := by
    rw [mul_sumK]
    exact sumK_ext K _ _ (fun k => swap3 K _ _ _) idx
  rw [e3, hev i, K.mul_assoc]

/-- **Strict gap on a finite lattice.** With a positive eigenvector `u` for `λ`,
    every eigenvalue `μ ≠ λ` (nonzero eigenvector) satisfies `|μ| ≤ λ` and `|μ| ≠ λ`. -/
theorem perron_gap (T : Nat → Nat → R) (u w : Nat → R) (lam mu : R) (a : Nat) (rest : List Nat)
    (hT : ∀ i j, Pos K O (T i j)) (hu : ∀ i, Pos K O (u i))
    (heu : ∀ i, sumK K (fun j => K.mul (T i j) (u j)) (a :: rest) = K.mul lam (u i))
    (hew : ∀ i, sumK K (fun j => K.mul (T i j) (w j)) (a :: rest) = K.mul mu (w i))
    (i0 : Nat) (hi0 : memL i0 (a :: rest)) (hw0 : w i0 ≠ K.zero) (hne : mu ≠ lam) :
    O.le (A.abs mu) lam ∧ A.abs mu ≠ lam := by
  refine ⟨perron_dominant K O A T u w lam mu a rest hT hu heu hew i0 hi0 hw0, fun habs => hne ?_⟩
  -- μ² = λ²
  have hsq : K.mul mu mu = K.mul lam lam := by
    rw [← A.abs_of_nonneg _ (A.mul_self_nonneg mu), A.abs_mul, habs]
  -- T² is positive, u and w are eigenvectors of T² for λ²
  have hS : ∀ i j, Pos K O (sq K T (a :: rest) i j) := fun i j =>
    pos_sum K O _ a rest (fun k => ⟨O.mul_nonneg _ _ (hT i k).1 (hT k j).1,
      fun h0 => (hT k j).2 (O.pos_mul_eq_zero _ _ (hT i k).1 (hT i k).2 h0)⟩)
  have heu2 := sq_eigen K T u lam (a :: rest) heu
  have hew2 : ∀ i, sumK K (fun j => K.mul (sq K T (a :: rest) i j) (w j)) (a :: rest) = K.mul (K.mul lam lam) (w i) :=
    fun i => (sq_eigen K T w mu (a :: rest) hew i).trans (by rw [hsq])
  obtain ⟨k, _, hk⟩ := perron_simple K O (sq K T (a :: rest)) u w (K.mul lam lam) a rest hS hu heu2 hew2
  -- u_k (μ w_i) = u_k (λ w_i)
  have key : K.mul (u k) (K.mul mu (w i0)) = K.mul (u k) (K.mul lam (w i0)) := by
    rw [← hew i0, mul_sumK]
    have e : sumK K (fun j => K.mul (u k) (K.mul (T i0 j) (w j))) (a :: rest)
        = sumK K (fun j => K.mul (w k) (K.mul (T i0 j) (u j))) (a :: rest) :=
      sumK_ext' (g := fun j => K.mul (u k) (K.mul (T i0 j) (w j)))
        (h := fun j => K.mul (w k) (K.mul (T i0 j) (u j))) (fun j hj => by
        show K.mul (u k) (K.mul (T i0 j) (w j)) = K.mul (w k) (K.mul (T i0 j) (u j))
        rw [swap3 K (u k), hk j hj, ← swap3 K (T i0 j) (w k) (u j)]) (a :: rest) (fun j hj => hj)
    rw [e, ← mul_sumK, heu i0, swap3 K (w k) lam (u i0), ← hk i0 hi0, swap3 K lam (u k) (w i0)]
  have key2 : K.mul (K.mul mu (w i0)) (u k) = K.mul (K.mul lam (w i0)) (u k) := by
    rw [K.mul_comm _ (u k), K.mul_comm _ (u k)]
    exact key
  have key3 := A.mul_right_cancel _ _ _ (hu k).2 key2
  have key4 : K.mul mu (w i0) = K.mul lam (w i0) := key3
  exact A.mul_right_cancel _ _ _ hw0 key4
where
  sumK_ext' {g h : Nat → R} (hgh : ∀ j, memL j (a :: rest) → g j = h j) :
      ∀ l : List Nat, (∀ j, memL j l → memL j (a :: rest)) → sumK K g l = sumK K h l := by
    intro l
    induction l with
    | nil => intro _; rfl
    | cons b l ih =>
      intro hl
      show K.add (g b) (sumK K g l) = K.add (h b) (sumK K h l)
      rw [hgh b (hl b (Or.inl rfl)), ih (fun j hj => hl j (Or.inr hj))]

/-- **Doeblin contraction** (the finite-dimensional form of the Hilbert-metric
    contraction). Write the rows of `P` as `P_ij = r_ij + δ q_j` with `r ≥ 0` and the
    same row mass `Σ_j r_ij = e` for every row. If `m ≤ f ≤ M` then for any two rows
    `(Pf)_i + e·m ≤ (Pf)_k + e·M`: the spread of `Pf` is at most `e` times the
    spread of `f`. For a stochastic `P` (`Σq = 1`) one has `e = 1 - δ`, so `n`
    steps shrink every spread by `(1-δ)^n`: a gap `≥ -ln(1-δ)`. -/
theorem doeblin (P r : Nat → Nat → R) (q f : Nat → R) (δ e M m : R) (idx : List Nat)
    (hP : ∀ i j, P i j = K.add (r i j) (K.mul δ (q j)))
    (hr : ∀ i j, O.le K.zero (r i j))
    (he : ∀ i, sumK K (r i) idx = e)
    (hM : ∀ j, memL j idx → O.le (f j) M) (hm : ∀ j, memL j idx → O.le m (f j))
    (i k : Nat) :
    O.le (K.add (sumK K (fun j => K.mul (P i j) (f j)) idx) (K.mul e m))
         (K.add (sumK K (fun j => K.mul (P k j) (f j)) idx) (K.mul e M)) := by
  have split : ∀ a, sumK K (fun j => K.mul (P a j) (f j)) idx
      = K.add (sumK K (fun j => K.mul (r a j) (f j)) idx) (sumK K (fun j => K.mul (K.mul δ (q j)) (f j)) idx) := by
    intro a
    rw [← sumK_add]
    exact sumK_ext K _ _ (fun j => by
      show K.mul (P a j) (f j) = K.add (K.mul (r a j) (f j)) (K.mul (K.mul δ (q j)) (f j))
      rw [hP a j, K.mul_comm, K.distrib, K.mul_comm (f j), K.mul_comm (f j)]) idx
  -- Σ_j r_aj f_j ≤ e M and e m ≤ Σ_j r_aj f_j
  have up : ∀ a, O.le (sumK K (fun j => K.mul (r a j) (f j)) idx) (K.mul e M) := by
    intro a
    rw [← he a, sumK_mul]
    refine sum_le K O _ _ idx (fun j hj => ?_)
    show O.le (K.mul (r a j) (f j)) (K.mul (r a j) M)
    rw [K.mul_comm (r a j), K.mul_comm (r a j)]
    exact O.mul_le_mul_right _ _ _ (hM j hj) (hr a j)
  have lo : ∀ a, O.le (K.mul e m) (sumK K (fun j => K.mul (r a j) (f j)) idx) := by
    intro a
    rw [← he a, sumK_mul]
    refine sum_le K O _ _ idx (fun j hj => ?_)
    show O.le (K.mul (r a j) m) (K.mul (r a j) (f j))
    rw [K.mul_comm (r a j), K.mul_comm (r a j)]
    exact O.mul_le_mul_right _ _ _ (hm j hj) (hr a j)
  rw [split i, split k]
  -- (A_i + Q) + e m ≤ (A_k + Q) + e M
  have h1 : O.le (K.add (sumK K (fun j => K.mul (r i j) (f j)) idx) (K.mul e m))
      (K.add (K.mul e M) (sumK K (fun j => K.mul (r k j) (f j)) idx)) :=
    O.add_le_add _ _ _ _ (up i) (lo k)
  have h2 := O.add_le_add _ _ _ _ h1 (O.le_refl (sumK K (fun j => K.mul (K.mul δ (q j)) (f j)) idx))
  have eL : ∀ x y z : R, K.add (K.add x z) y = K.add (K.add x y) z := fun x y z => by
    rw [K.add_assoc, K.add_comm z, ← K.add_assoc]
  have eR : ∀ x y z : R, K.add (K.add x y) z = K.add (K.add y z) x := fun x y z => by
    rw [K.add_comm x y, K.add_assoc, K.add_comm x z, ← K.add_assoc]
  rw [eL (sumK K (fun j => K.mul (r i j) (f j)) idx) (sumK K (fun j => K.mul (K.mul δ (q j)) (f j)) idx) (K.mul e m),
    eR (K.mul e M) (sumK K (fun j => K.mul (r k j) (f j)) idx) (sumK K (fun j => K.mul (K.mul δ (q j)) (f j)) idx)] at h2
  exact h2

end Gap

/-- A Gram kernel is symmetric: the transfer matrix built from crossing kernels is symmetric. -/
theorem ker_symm {R X : Type} (K : DetChain.CRing R) (L : List (R × (X → R))) (x y : X) :
    ker K L x y = ker K L y x :=
  sumK_ext K _ _ (fun p => by
    show K.mul (K.mul p.1 (p.2 x)) (p.2 y) = K.mul (K.mul p.1 (p.2 y)) (p.2 x)
    rw [K.mul_assoc, K.mul_comm (p.2 x), ← K.mul_assoc]) L

/-! ### Block spin: one decimation step -/

section Block
variable {G : Type} (K : Grp G) {S : Type} (Λ : Lat S)

/-- Coarse shift: two fine steps. -/
def sh2 (x : S) (μ : D4) : S := Λ.sh (Λ.sh x μ) μ

theorem sh2_comm (x : S) (μ ν : D4) : sh2 Λ (sh2 Λ x μ) ν = sh2 Λ (sh2 Λ x ν) μ := by
  show Λ.sh (Λ.sh (Λ.sh (Λ.sh x μ) μ) ν) ν = Λ.sh (Λ.sh (Λ.sh (Λ.sh x ν) ν) μ) μ
  rw [Λ.comm (Λ.sh (Λ.sh x μ) μ) ν ν |>.symm.symm]
  rw [Λ.comm (Λ.sh x μ) μ ν, Λ.comm x μ ν, Λ.comm (Λ.sh (Λ.sh x ν) μ) μ ν, Λ.comm (Λ.sh x ν) μ ν,
    Λ.comm x ν ν]

/-- The coarse lattice (shifts by two). -/
def coarse : Lat S := ⟨sh2 Λ, sh2_comm Λ⟩

/-- **Decimation**: the coarse link is the product of the two fine links along it. -/
def block (U : S → D4 → G) : S → D4 → G := fun x μ => K.mul (U x μ) (U (Λ.sh x μ) μ)

/-- **Gauge covariance of the block step**: blocking a gauge-transformed field is
    the coarse gauge transform of the blocked field. -/
theorem block_gauge (g : S → G) (U : S → D4 → G) (x : S) (μ : D4) :
    block K Λ (gauge K Λ g U) x μ = gauge K (coarse Λ) g (block K Λ U) x μ := by
  show K.mul (K.mul (K.mul (g x) (U x μ)) (K.inv (g (Λ.sh x μ))))
      (K.mul (K.mul (g (Λ.sh x μ)) (U (Λ.sh x μ) μ)) (K.inv (g (Λ.sh (Λ.sh x μ) μ))))
    = K.mul (K.mul (g x) (K.mul (U x μ) (U (Λ.sh x μ) μ))) (K.inv (g (Λ.sh (Λ.sh x μ) μ)))
  exact conj_mul K _ _ _ _ _

end Block

/-- **Positivity is kept**: the blocked weight `Σ_{U ↦ V} W(U)` of a coarse field is
    positive when every fine weight is positive and the fibre is nonempty. -/
theorem block_weight_pos {X : Type} (W : X → Nat) (hW : ∀ x, 0 < W x) :
    ∀ (x : X) (fibre : List X), 0 < lsum W (x :: fibre)
  | x, _ => Nat.lt_of_lt_of_le (hW x) (Nat.le_add_right _ _)

/-- **Reflection positivity is kept**: an observable of the blocked field is an
    observable `G ∘ B` of the fine field, so `⟨θ(G∘B) · (G∘B)⟩ ≥ 0`. -/
theorem block_rp {R X Y : Type} (K : DetChain.CRing R) (P : Positivity K) (Bl : X → Y) (Gf : Y → R)
    (xs : List X) (L : List (R × (X → R))) (hL : AllNN K P L) :
    P.nn (sumK K (fun x => sumK K (fun y => K.mul (K.mul (Gf (Bl x)) (Gf (Bl y))) (ker K L x y)) xs) xs) :=
  rp_nonneg K P (fun x => Gf (Bl x)) xs L hL

/-! ### The bridge across block steps (strong-coupling range) -/

theorem pow_add_nat (a m : Nat) : ∀ n : Nat, a ^ (m + n) = a ^ m * a ^ n
  | 0 => (Nat.mul_one _).symm
  | n + 1 => by
    show a ^ (m + n) * a = a ^ m * (a ^ n * a)
    rw [pow_add_nat a m n, nmul_assoc]

theorem pow_mul_nat (a : Nat) (b : Nat) : ∀ c, (a ^ b) ^ c = a ^ (b * c)
  | 0 => rfl
  | c + 1 => by
    show (a ^ b) ^ c * a ^ b = a ^ (b * c + b)
    rw [pow_mul_nat a b c, pow_add_nat]

/-- **Decay survives blocking.** In the strong-coupling range (`q ≥ 2`, e.g. `q ≥ 882`
    from `gap_explicit`) a correlation bounded by `2 · q^(-s)` at fine distance `s`
    is, after `n` decimation steps, bounded at coarse distance `t` (fine distance
    `2^n t`) by `2 · (2^(2^n))^(-t)`: the decay rate per coarse unit is at least
    `2^n ln 2`. -/
theorem block_decay (q n t : Nat) (hq : 2 ≤ q) : (2 ^ (2 ^ n)) ^ t ≤ q ^ (2 ^ n * t) := by
  rw [pow_mul_nat]
  exact Nat.pow_le_pow_left hq _

/-- Iterating: `n` block steps from the explicit β₀ keep `2^(2^n t) ≤ 882^(2^n t)`. -/
theorem block_decay_explicit (q n t : Nat) (hq : 882 ≤ q) : (2 ^ (2 ^ n)) ^ t ≤ q ^ (2 ^ n * t) :=
  block_decay q n t (Nat.le_trans (Nat.le_add_left 2 880) hq)

end YMChain

#print axioms YMChain.cancel_left
#print axioms YMChain.inv_unique
#print axioms YMChain.inv_mul_rev
#print axioms YMChain.inv_inv
#print axioms YMChain.conj_mul
#print axioms YMChain.conj_inv
#print axioms YMChain.hol_gauge
#print axioms YMChain.gauge_inverse
#print axioms YMChain.lsum_ext
#print axioms YMChain.action_gauge_inv
#print axioms YMChain.weight_gauge_inv
#print axioms YMChain.torus_comm
#print axioms YMChain.sites_length
#print axioms YMChain.torus_action_gauge_inv
#print axioms YMChain.q8_assoc
#print axioms YMChain.q8_one_mul
#print axioms YMChain.q8_mul_one
#print axioms YMChain.q8_inv_mul
#print axioms YMChain.q8_mul_inv
#print axioms YMChain.mul_is_quaternion
#print axioms YMChain.unit_norm
#print axioms YMChain.q8_noncomm
#print axioms YMChain.defect_class
#print axioms YMChain.wilson_class
#print axioms YMChain.regroup
#print axioms YMChain.interaction
#print axioms YMChain.factor_sum
#print axioms YMChain.sumK_ext
#print axioms YMChain.sumK_add
#print axioms YMChain.mul_sumK
#print axioms YMChain.sumK_mul
#print axioms YMChain.sumK_swap
#print axioms YMChain.rearr
#print axioms YMChain.rp_identity
#print axioms YMChain.sumK_nn
#print axioms YMChain.sumK_nn_list
#print axioms YMChain.rp_nonneg
#print axioms YMChain.sumK_append
#print axioms YMChain.sumK_map
#print axioms YMChain.mul_mid4
#print axioms YMChain.rearr2
#print axioms YMChain.gram_mul
#print axioms YMChain.gram_mul_nn
#print axioms YMChain.delta_gram
#print axioms YMChain.defect_gram
#print axioms YMChain.pow_pos'
#print axioms YMChain.transfer_pos
#print axioms YMChain.len_app2
#print axioms YMChain.len_map2
#print axioms YMChain.consAll_length
#print axioms YMChain.words_length
#print axioms YMChain.surface_count
#print axioms YMChain.geom_telescope
#print axioms YMChain.le_cancel
#print axioms YMChain.geom_bound
#print axioms YMChain.decay_bound
#print axioms YMChain.c_441
#print axioms YMChain.mul_pow'
#print axioms YMChain.gap_explicit
#print axioms YMChain.argmin
#print axioms YMChain.sum_zero_each
#print axioms YMChain.sumK_sub
#print axioms YMChain.mul_neg_r
#print axioms YMChain.swap3
#print axioms YMChain.perron_simple
#print axioms YMChain.sum_le
#print axioms YMChain.abs_sum
#print axioms YMChain.argmax
#print axioms YMChain.perron_dominant
#print axioms YMChain.pos_sum
#print axioms YMChain.sq_eigen
#print axioms YMChain.perron_gap
#print axioms YMChain.ker_symm
#print axioms YMChain.sh2_comm
#print axioms YMChain.block_gauge
#print axioms YMChain.block_weight_pos
#print axioms YMChain.block_rp
#print axioms YMChain.doeblin
#print axioms YMChain.pow_add_nat
#print axioms YMChain.pow_mul_nat
#print axioms YMChain.block_decay
#print axioms YMChain.block_decay_explicit

Listing 376: numeric_ym.py: \(Q_8\) with the defect action

numeric_ym.py

#!/usr/bin/env python3
"""T16 numerics: the YMChain gauge field on (Z/L)^4 with gauge group Q8.

Python standard library only, fixed seeds. Same group, same plaquette
orientation and same defect action as work/YMChain.lean:
    hol(x, mu, nu) = U(x,mu) U(x+mu,nu) U(x+nu,mu)^-1 U(x,nu)^-1,
    S(U) = number of plaquettes with hol != 1,  weight t^S = exp(-beta S),
    measure = counting measure on Q8^links.

Writes work/NUMERIC_YM.txt next to this script.
"""
import math
import os
import random
import sys

# ---------------------------------------------------------------- Q8
# element = (neg, unit) with unit 0..3 = 1, i, j, k ; code = 4*neg + unit


def to_vec(c):
    s = -1 if c >= 4 else 1
    u = c % 4
    v = [0, 0, 0, 0]
    v[u] = s
    return tuple(v)


def vmul(p, q):
    a1, b1, c1, d1 = p
    a2, b2, c2, d2 = q
    return (a1 * a2 - b1 * b2 - c1 * c2 - d1 * d2,
            a1 * b2 + b1 * a2 + c1 * d2 - d1 * c2,
            a1 * c2 - b1 * d2 + c1 * a2 + d1 * b2,
            a1 * d2 + b1 * c2 - c1 * b2 + d1 * a2)


VEC = [to_vec(c) for c in range(8)]
CODE = {v: c for c, v in enumerate(VEC)}
MUL = [[CODE[vmul(VEC[a], VEC[b])] for b in range(8)] for a in range(8)]
INV = [next(b for b in range(8) if MUL[a][b] == 0) for a in range(8)]
ONE = 0


def group_checks():
    ok = all(MUL[MUL[a][b]][c] == MUL[a][MUL[b][c]] for a in range(8) for b in range(8) for c in range(8))
    ok = ok and all(MUL[0][a] == a == MUL[a][0] and MUL[INV[a]][a] == 0 for a in range(8))
    noncomm = MUL[1][2] != MUL[2][1]
    return ok, noncomm


# ---------------------------------------------------------------- lattice
class Lattice:
    def __init__(self, L):
        self.L = L
        self.N = L ** 4
        self.coords = [(a, b, c, d) for a in range(L) for b in range(L) for c in range(L) for d in range(L)]
        self.index = {x: i for i, x in enumerate(self.coords)}
        self.up = [[0] * 4 for _ in range(self.N)]
        self.dn = [[0] * 4 for _ in range(self.N)]
        for i, x in enumerate(self.coords):
            for mu in range(4):
                y = list(x)
                y[mu] = (y[mu] + 1) % L
                self.up[i][mu] = self.index[tuple(y)]
                y = list(x)
                y[mu] = (y[mu] - 1) % L
                self.dn[i][mu] = self.index[tuple(y)]


def hol(lat, U, x, mu, nu):
    up = lat.up
    return MUL[MUL[MUL[U[x][mu]][U[up[x][mu]][nu]]][INV[U[up[x][nu]][mu]]]][INV[U[x][nu]]]


def action(lat, U):
    return sum(1 for x in range(lat.N) for mu in range(4) for nu in range(mu + 1, 4) if hol(lat, U, x, mu, nu) != ONE)


def gauge(lat, g, U):
    return [[MUL[MUL[g[x]][U[x][mu]]][INV[g[lat.up[x][mu]]]] for mu in range(4)] for x in range(lat.N)]


def staples(lat, U, x, mu):
    """The 6 elements A with: plaquette through link (x,mu) has no defect iff U(x,mu) = A."""
    up, dn = lat.up, lat.dn
    out = []
    xm = up[x][mu]
    for nu in range(4):
        if nu == mu:
            continue
        # forward plaquette (x, mu, nu): U = U(x,nu) U(x+nu,mu) U(x+mu,nu)^-1
        out.append(MUL[MUL[U[x][nu]][U[up[x][nu]][mu]]][INV[U[xm][nu]]])
        # backward plaquette (x-nu, mu, nu): U = U(x-nu,nu)^-1 U(x-nu,mu) U(x-nu+mu,nu)
        y = dn[x][nu]
        out.append(MUL[MUL[INV[U[y][nu]]][U[y][mu]]][U[up[y][mu]][nu]])
    return out


def sweep(lat, U, beta, rng):
    eb = [math.exp(beta * m) for m in range(7)]
    for x in range(lat.N):
        for mu in range(4):
            cnt = [0] * 8
            for a in staples(lat, U, x, mu):
                cnt[a] += 1
            w = [eb[c] for c in cnt]
            r = rng.random() * sum(w)
            g = 0
            while r >= w[g]:
                r -= w[g]
                g += 1
            U[x][mu] = g


def slice_obs(lat, U):
    """O(t) = number of defective spatial plaquettes in the time slice x0 = t."""
    O = [0] * lat.L
    for x, c in enumerate(lat.coords):
        for mu in range(1, 4):
            for nu in range(mu + 1, 4):
                if hol(lat, U, x, mu, nu) != ONE:
                    O[c[0]] += 1
    return O


def correlator(series, L):
    """Connected C(d) = <O(t) O(t+d)> - <O>^2 averaged over t and samples, with jackknife errors."""
    nb = 20
    n = len(series)
    bs = n // nb

    def corr(samples):
        m = sum(sum(O) for O in samples) / (len(samples) * L)
        return [sum(O[t] * O[(t + d) % L] for O in samples for t in range(L)) / (len(samples) * L) - m * m
                for d in range(L // 2 + 1)]
    full = corr(series)
    jk = []
    for b in range(nb):
        jk.append(corr(series[:b * bs] + series[(b + 1) * bs:]))
    return full, jk


def meff(c0, c1, L):
    """m with c1/c0 = cosh(m (1 - L/2)) / cosh(m L/2) (periodic single exponential)."""
    r = c1 / c0
    if not 0 < r < 1:
        return float('nan')
    lo, hi = 1e-6, 50.0
    for _ in range(200):
        m = (lo + hi) / 2
        val = math.cosh(m * (1 - L / 2)) / math.cosh(m * L / 2)
        if val > r:
            lo = m
        else:
            hi = m
    return (lo + hi) / 2


def jk_err(full, samples):
    good = [s for s in samples if s == s]
    if len(good) < len(samples) or full != full:
        return float('nan')
    n = len(samples)
    mean = sum(samples) / n
    return math.sqrt((n - 1) / n * sum((s - mean) ** 2 for s in samples))


def scan(L, betas, sweeps, rng):
    lat = Lattice(L)
    rows = []
    for start in ("cold", "hot"):
        U = [[0] * 4 for _ in range(lat.N)] if start == "cold" else \
            [[rng.randrange(8) for _ in range(4)] for _ in range(lat.N)]
        for b in (betas if start == "hot" else list(reversed(betas))):
            for _ in range(sweeps):
                sweep(lat, U, b, rng)
            acc = 0
            for _ in range(sweeps):
                sweep(lat, U, b, rng)
                acc += action(lat, U)
            rows.append((start, b, acc / sweeps / (6 * lat.N)))
    return rows


def gap(L, beta, therm, meas, rng):
    lat = Lattice(L)
    U = [[rng.randrange(8) for _ in range(4)] for _ in range(lat.N)]
    for _ in range(therm):
        sweep(lat, U, beta, rng)
    series = []
    for _ in range(meas):
        sweep(lat, U, beta, rng)
        series.append(slice_obs(lat, U))
    full, jk = correlator(series, L)
    m1 = meff(full[0], full[1], L)
    m1s = [meff(c[0], c[1], L) for c in jk]
    s1 = jk_err(full[1], [c[1] for c in jk])
    upper = full[1] + 2 * s1
    m_low = meff(full[0], upper, L) if upper > 0 else float('inf')
    return full, m1, jk_err(m1, m1s), s1, m_low


GAP_RUNS = ((2, 1000, 40000), (3, 500, 20000), (4, 500, 10000), (5, 300, 6000), (6, 300, 4000),
            (8, 200, 2000))


def main():
    mode = sys.argv[1] if len(sys.argv) > 1 else "all"
    out = []
    ok = True

    def check(name, cond):
        nonlocal ok
        ok = ok and cond
        out.append(f"  [{'PASS' if cond else 'FAIL'}] {name}")

    rng = random.Random(2026)
    gok, nc = group_checks()
    out.append("Q8 from integer unit quaternions: table built from the quaternion product")
    check("group laws (associativity, unit, inverse) on all 512 / 8 cases", gok)
    check("non-abelian: i j != j i", nc)

    lat = Lattice(3)
    U = [[rng.randrange(8) for _ in range(4)] for _ in range(lat.N)]
    S0 = action(lat, U)
    inv_ok = all(action(lat, gauge(lat, [rng.randrange(8) for _ in range(lat.N)], U)) == S0 for _ in range(20))
    check(f"gauge invariance on (Z/3)^4, 20 random g, S = {S0}", inv_ok)

    if mode in ("scan", "all"):
        out.append("")
        out.append("Defect density <S>/(6 L^4) on (Z/4)^4, cold and hot starts (hysteresis = first order)")
        for start, b, d in scan(4, [0.5, 1.0, 1.25, 1.5, 1.75, 2.0, 2.5], 60, rng):
            out.append(f"  {start:4s}  beta = {b:.2f}  density = {d:.4f}")

    if mode in ("gap", "all"):
        beta = float(os.environ.get("YM_BETA", "1.0"))
        out.append("")
        out.append(f"Mass gap estimate at beta = {beta} (confined side), from the connected")
        out.append("correlator of time-slice defect counts, C(1)/C(0) = cosh(m(1-L/2))/cosh(m L/2)")
        out.append("m_low: the m obtained with C(1) replaced by C(1) + 2 sigma (a lower bound at about 95%)")
        out.append(" L   sweeps   C(0)        C(1)         sigma(C1)   m_eff            m_low")
        ms = []
        for L, therm, meas in GAP_RUNS:
            full, m1, err, s1, m_low = gap(L, beta, therm, meas, rng)
            me = f"{m1:.3f} ± {err:.3f}" if m1 == m1 else "  (C(1) ~ 0)  "
            out.append(f" {L:<3} {meas:<8} {full[0]:.4e}  {full[1]:+.4e}  {s1:.4e}  {me:<15}  {m_low:.3f}")
            ms.append((L, m1, err, m_low, full[1] > 2 * s1))
        check("lower bound m_low > 2 for every L = 2..8 (no sign of the gap closing)",
              all(m[3] > 2 for m in ms))
        out.append(f"  C(1) resolved from 0 (C(1) > 2 sigma) for L in {[m[0] for m in ms if m[4]]}")
        check("where m_eff is defined (0 < C(1) < C(0)), m_eff > 3",
              all(m[1] > 3 for m in ms if m[1] == m[1] and m[2] == m[2]))
    out.append(f"ALL {'PASS' if ok else 'FAIL'}")
    text = "\n".join(out) + "\n"
    if mode == "all":
        path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "NUMERIC_YM.txt")
        with open(path, "w", encoding="utf-8") as fh:
            fh.write(text)
    print(text, end="")
    return 0 if ok else 1


if __name__ == "__main__":
    raise SystemExit(main())

Listing 377: numeric_ym2i.py: \(2I\) and \(SU(2)\) with the Wilson action; smearing, variational glueball, static potential

numeric_ym2i.py

#!/usr/bin/env python3
"""T23 numerics: SU(2) lattice gauge theory approximated by the binary icosahedral group 2I.

Python standard library only; fixed seeds; the (L, beta) runs are spread over
processes with multiprocessing.

1. The group 2I (120 unit quaternions) is built exactly: coordinates are halves of
   elements of Z[phi], phi = (1 + sqrt 5)/2, stored as integer pairs. Closure,
   inverses and the number of elements are checked exactly; so are the subgroups
   Q8 (8) and 2T (24).
2. Wilson action S = beta * sum_p (1 - Re U_p), heat bath over the 120 elements,
   on the torus (Z/L)^4.
3. Measured: plaquette, Wilson loops W(1,1), W(1,2), W(2,2), the Creutz ratio
   chi(2,2) = -ln(W22 W11 / W12^2) (string tension sigma in lattice units), and the
   0++ glueball correlator of time-slice plaquette sums, with effective mass m.

Writes work/NUMERIC_YM2I.txt next to this script.
Modes: (none) first survey -> NUMERIC_YM2I.txt;  gap -> spectroscopy, raw data saved to
work/data/ymgap_raw.json, report NUMERIC_YMGAP.txt;  gapanalyse [file] -> NUMERIC_YMGAP.txt
from saved raw data (default work/data/ymgap_raw4.json);  gapquick -> small test.
"""
import math
import multiprocessing as mp
import os
import random
import sys

HERE = os.path.dirname(os.path.abspath(__file__))
PHI = (1 + 5 ** 0.5) / 2


# ------------------------------------------------------------- Z[phi]
def zmul(a, b):
    # (a0 + a1 phi)(b0 + b1 phi), phi^2 = phi + 1
    return (a[0] * b[0] + a[1] * b[1], a[0] * b[1] + a[1] * b[0] + a[1] * b[1])


def zadd(a, b):
    return (a[0] + b[0], a[1] + b[1])


def zneg(a):
    return (-a[0], -a[1])


def zhalf(a):
    assert a[0] % 2 == 0 and a[1] % 2 == 0, "not divisible by 2"
    return (a[0] // 2, a[1] // 2)


Z0, Z1, Z2 = (0, 0), (1, 0), (2, 0)
PHI_Z = (0, 1)
PHIINV_Z = (-1, 1)          # phi^-1 = phi - 1


def qmul2(p, q):
    """Product of quaternions given by doubled coordinates; returns doubled coordinates."""
    a1, b1, c1, d1 = p
    a2, b2, c2, d2 = q
    m = zmul
    w = zadd(zadd(m(a1, a2), zneg(m(b1, b2))), zadd(zneg(m(c1, c2)), zneg(m(d1, d2))))
    x = zadd(zadd(m(a1, b2), m(b1, a2)), zadd(m(c1, d2), zneg(m(d1, c2))))
    y = zadd(zadd(m(a1, c2), zneg(m(b1, d2))), zadd(m(c1, a2), m(d1, b2)))
    z = zadd(zadd(m(a1, d2), m(b1, c2)), zadd(zneg(m(c1, b2)), m(d1, a2)))
    return tuple(zhalf(v) for v in (w, x, y, z))


def even_perms4():
    out = []
    import itertools
    for p in itertools.permutations(range(4)):
        inv = sum(1 for i in range(4) for j in range(i + 1, 4) if p[i] > p[j])
        if inv % 2 == 0:
            out.append(p)
    return out


def build_2I():
    els = set()
    # 8: (+-1, 0, 0, 0) and permutations  (doubled: +-2)
    for i in range(4):
        for s in (1, -1):
            v = [Z0] * 4
            v[i] = (2 * s, 0)
            els.add(tuple(v))
    # 16: (+-1/2, +-1/2, +-1/2, +-1/2)  (doubled: +-1)
    for s in range(16):
        els.add(tuple(((1 if (s >> k) & 1 else -1), 0) for k in range(4)))
    # 96: even permutations of (0, +-1, +-phi^-1, +-phi)/2  (doubled: as written)
    base = [Z0, Z1, PHIINV_Z, PHI_Z]
    for p in even_perms4():
        for s in range(8):
            v = [None] * 4
            signs = [1, 1 if s & 1 else -1, 1 if s & 2 else -1, 1 if s & 4 else -1]
            for k in range(4):
                e = base[k] if signs[k] == 1 else zneg(base[k])
                v[p[k]] = e
            els.add(tuple(v))
    return sorted(els)


def zval(a):
    return a[0] + a[1] * PHI


def check_group(els):
    S = set(els)
    one = (Z2, Z0, Z0, Z0)
    closed = all(qmul2(a, b) in S for a in els for b in els)
    def conj(a):
        return (a[0], zneg(a[1]), zneg(a[2]), zneg(a[3]))
    inverses = all(conj(a) in S and qmul2(a, conj(a)) == one for a in els)
    norm = all(sum(zval(zmul(x, x)) for x in a) == 4 for a in els) if False else \
        all(zadd(zadd(zmul(a[0], a[0]), zmul(a[1], a[1])), zadd(zmul(a[2], a[2]), zmul(a[3], a[3]))) == (4, 0) for a in els)
    return closed, inverses, norm, one in S


def subgroup_sizes(els):
    q8 = [a for a in els if all(x[1] == 0 and x[0] % 2 == 0 for x in a)]
    t2 = [a for a in els if all(x[1] == 0 for x in a)]
    S8, S24 = set(q8), set(t2)
    c8 = all(qmul2(a, b) in S8 for a in q8 for b in q8)
    c24 = all(qmul2(a, b) in S24 for a in t2 for b in t2)
    return len(q8), c8, len(t2), c24


class Group:
    def __init__(self):
        self.els = build_2I()
        self.n = len(self.els)
        idx = {e: i for i, e in enumerate(self.els)}
        self.mul = [[idx[qmul2(a, b)] for b in self.els] for a in self.els]
        one = (Z2, Z0, Z0, Z0)
        self.one = idx[one]
        self.inv = [next(j for j in range(self.n) if self.mul[i][j] == self.one) for i in range(self.n)]
        self.coord = [tuple(zval(x) / 2 for x in a) for a in self.els]
        self.re = [c[0] for c in self.coord]

    def class_function_check(self):
        """Re(g h g^-1) = Re(h) exactly (Re is the first doubled coordinate)."""
        return all(self.els[self.mul[self.mul[g][h]][self.inv[g]]][0] == self.els[h][0]
                   for g in range(self.n) for h in range(self.n))


# ------------------------------------------------------------- lattice
def lattice(L):
    N = L ** 4
    up = [[0] * 4 for _ in range(N)]
    dn = [[0] * 4 for _ in range(N)]
    for x in range(N):
        c = [(x // L ** (3 - k)) % L for k in range(4)]     # c[0] = time
        for mu in range(4):
            cu = list(c)
            cu[mu] = (cu[mu] + 1) % L
            cd = list(c)
            cd[mu] = (cd[mu] - 1) % L
            up[x][mu] = sum(cu[k] * L ** (3 - k) for k in range(4))
            dn[x][mu] = sum(cd[k] * L ** (3 - k) for k in range(4))
    return N, up, dn


def run(args):
    L, beta, therm, meas, every, seed = args
    G = Group()
    rng = random.Random(seed)
    N, up, dn = lattice(L)
    mul, inv, coord, re = G.mul, G.inv, G.coord, G.re
    U = [G.one] * (4 * N)
    n = G.n

    def sweep():
        for x in range(N):
            for mu in range(4):
                s0 = s1 = s2 = s3 = 0.0
                xm = up[x][mu]
                for nu in range(4):
                    if nu == mu:
                        continue
                    # forward staple  U(x+mu,nu) U(x+nu,mu)^-1 U(x,nu)^-1
                    v = mul[mul[U[4 * xm + nu]][inv[U[4 * up[x][nu] + mu]]]][inv[U[4 * x + nu]]]
                    c = coord[v]
                    s0 += c[0]; s1 += c[1]; s2 += c[2]; s3 += c[3]
                    # backward staple  U(x+mu-nu,nu)^-1 U(x-nu,mu)^-1 U(x-nu,nu)
                    y = dn[x][nu]
                    v = mul[mul[inv[U[4 * up[y][mu] + nu]]][inv[U[4 * y + mu]]]][U[4 * y + nu]]
                    c = coord[v]
                    s0 += c[0]; s1 += c[1]; s2 += c[2]; s3 += c[3]
                # Re(g S) = g0 s0 - g1 s1 - g2 s2 - g3 s3
                es = [beta * (g[0] * s0 - g[1] * s1 - g[2] * s2 - g[3] * s3) for g in coord]
                mx = max(es)
                w = [math.exp(e - mx) for e in es]
                U[4 * x + mu] = rng.choices(range(n), weights=w)[0]

    def plaq(x, mu, nu):
        return mul[mul[mul[U[4 * x + mu]][U[4 * up[x][mu] + nu]]][inv[U[4 * up[x][nu] + mu]]]][inv[U[4 * x + nu]]]

    def loop(x, mu, nu, R, T):
        g = G.one
        y = x
        for _ in range(R):
            g = mul[g][U[4 * y + mu]]; y = up[y][mu]
        for _ in range(T):
            g = mul[g][U[4 * y + nu]]; y = up[y][nu]
        for _ in range(R):
            y = dn[y][mu]; g = mul[g][inv[U[4 * y + mu]]]
        for _ in range(T):
            y = dn[y][nu]; g = mul[g][inv[U[4 * y + nu]]]
        return re[g]

    def measure():
        P = 0.0
        W = {(1, 1): 0.0, (1, 2): 0.0, (2, 2): 0.0}
        cnt = 0
        O = [0.0] * L
        for x in range(N):
            t = x // L ** 3
            for mu in range(4):
                for nu in range(mu + 1, 4):
                    p = re[plaq(x, mu, nu)]
                    P += p
                    if mu > 0:
                        O[t] += p
                    W[(1, 1)] += p
                    W[(2, 2)] += loop(x, mu, nu, 2, 2)
                    W[(1, 2)] += 0.5 * (loop(x, mu, nu, 1, 2) + loop(x, mu, nu, 2, 1))
                    cnt += 1
        return P / cnt, {k: v / cnt for k, v in W.items()}, O

    for _ in range(therm):
        sweep()
    data = []
    for k in range(meas):
        sweep()
        if k % every == 0:
            data.append(measure())
    return (L, beta, data)


def analyse(L, data, nb=10):
    n = len(data)
    bs = max(1, n // nb)
    blocks = [data[i * bs:(i + 1) * bs] for i in range(nb) if (i + 1) * bs <= n]

    def est(sample):
        P = sum(d[0] for d in sample) / len(sample)
        W = {k: sum(d[1][k] for d in sample) / len(sample) for k in sample[0][1]}
        chi = -math.log(W[(2, 2)] * W[(1, 1)] / W[(1, 2)] ** 2) if W[(2, 2)] > 0 and W[(1, 2)] > 0 else float('nan')
        mean = sum(sum(d[2]) for d in sample) / (len(sample) * L)
        C = [sum(d[2][t] * d[2][(t + dt) % L] for d in sample for t in range(L)) / (len(sample) * L) - mean * mean
             for dt in range(L // 2 + 1)]
        r = C[1] / C[0] if C[0] > 0 else float('nan')
        m = float('nan')
        if 0 < r < 1:
            lo, hi = 1e-6, 30.0
            for _ in range(100):
                mid = (lo + hi) / 2
                if math.cosh(mid * (1 - L / 2)) / math.cosh(mid * L / 2) > r:
                    lo = mid
                else:
                    hi = mid
            m = (lo + hi) / 2
        return P, chi, m

    full = est(data)
    jk = [est([d for j, b in enumerate(blocks) if j != i for d in b]) for i in range(len(blocks))]

    def err(k):
        vals = [j[k] for j in jk if j[k] == j[k]]
        if len(vals) < len(jk) or full[k] != full[k]:
            return float('nan')
        mu = sum(vals) / len(vals)
        return math.sqrt((len(vals) - 1) / len(vals) * sum((v - mu) ** 2 for v in vals))
    ratio = full[2] / math.sqrt(full[1]) if full[1] == full[1] and full[1] > 0 and full[2] == full[2] else float('nan')
    rj = [j[2] / math.sqrt(j[1]) for j in jk if j[1] == j[1] and j[1] > 0 and j[2] == j[2]]
    if len(rj) == len(jk) and ratio == ratio:
        mu = sum(rj) / len(rj)
        rerr = math.sqrt((len(rj) - 1) / len(rj) * sum((v - mu) ** 2 for v in rj))
    else:
        rerr = float('nan')
    return full, (err(0), err(1), err(2)), ratio, rerr


# ===================================================================== T25
# Smearing, variational 0++ mass, static potential, SU(2) comparison.

def neighbours(G):
    """Edges of the 600-cell: for each element, the elements at the largest dot product < 1."""
    nb = []
    for g in range(G.n):
        cg = G.coord[g]
        dots = [(sum(a * b for a, b in zip(cg, G.coord[h])), h) for h in range(G.n) if h != g]
        top = max(d for d, _ in dots)
        nb.append([h for d, h in dots if d > top - 1e-9])
    return nb


def project(G, nb, V, start):
    """argmax_g g.V over the group, by climbing the vertex graph of the 600-cell (a convex
    polytope: a vertex with no better neighbour maximises a linear function)."""
    c = G.coord
    g = start
    best = sum(a * b for a, b in zip(c[g], V))
    while True:
        moved = False
        for h in nb[g]:
            d = sum(a * b for a, b in zip(c[h], V))
            if d > best + 1e-12:
                g, best, moved = h, d, True
        if not moved:
            return g


def smear(G, nb, L, up, dn, S, eps):
    """One smearing step on spatial links (directions 1,2,3), within each time slice:
    V = U + eps * sum of the 4 spatial staples, then back to the group by `project`."""
    mul, inv, coord = G.mul, G.inv, G.coord
    N = L ** 4
    new = list(S)
    for x in range(N):
        for i in (1, 2, 3):
            u = S[4 * x + i]
            cu = coord[u]
            v0, v1, v2, v3 = cu
            xi = up[x][i]
            for j in (1, 2, 3):
                if j == i:
                    continue
                # x -> x+j -> x+j+i -> x+i
                st = mul[mul[S[4 * x + j]][S[4 * up[x][j] + i]]][inv[S[4 * xi + j]]]
                c = coord[st]
                v0 += eps * c[0]; v1 += eps * c[1]; v2 += eps * c[2]; v3 += eps * c[3]
                # x -> x-j -> x-j+i -> x+i
                y = dn[x][j]
                st = mul[mul[inv[S[4 * y + j]]][S[4 * y + i]]][S[4 * up[y][i] + j]]
                c = coord[st]
                v0 += eps * c[0]; v1 += eps * c[1]; v2 += eps * c[2]; v3 += eps * c[3]
            new[4 * x + i] = project(G, nb, (v0, v1, v2, v3), u)
    return new


SMEAR_LEVELS = (4, 10)
# glueball loop sizes and Wilson-loop extent; larger lattices (fine a) use larger loops:
#   YM_LOOPS="1,2,3,4,6"  YM_RMAX=8  YM_TMAX=8
LOOP_SIZES = tuple(int(v) for v in os.environ.get("YM_LOOPS", "1,2,3").split(","))
SMEAR_EPS = 0.5
WILSON_LEVEL = 1          # index into SMEAR_LEVELS used for the spatial lines of Wilson loops
RMAX, TMAX = int(os.environ.get("YM_RMAX", 5)), int(os.environ.get("YM_TMAX", 6))


def measure_gap(G, nb, L, up, dn, U):
    """0++ operators O_s(t) for each smearing level, and Wilson loops W(R,T) (spatial lines smeared)."""
    mul, inv, re = G.mul, G.inv, G.re
    N = L ** 4
    ops = []
    S = list(U)
    level = 0
    wl_links = None
    for k, target in enumerate(SMEAR_LEVELS):
        while level < target:
            S = smear(G, nb, L, up, dn, S, SMEAR_EPS)
            level += 1
        # spatial R x R loops, R in LOOP_SIZES, summed over the three spatial planes of each slice
        lines = {}
        for i in (1, 2, 3):
            cur = list(range(N))
            prod = [G.one] * N
            for R in range(1, max(LOOP_SIZES) + 1):
                prod = [mul[prod[x]][S[4 * cur[x] + i]] for x in range(N)]
                cur = [up[cur[x]][i] for x in range(N)]
                lines[(i, R)] = (prod, cur)
        for R in LOOP_SIZES:
            O = [0.0] * L
            for i, j in ((1, 2), (1, 3), (2, 3)):
                li, ei = lines[(i, R)]
                lj, ej = lines[(j, R)]
                for x in range(N):
                    g = mul[mul[mul[li[x]][lj[ei[x]]]][inv[li[ej[x]]]]][inv[lj[x]]]
                    O[x // L ** 3] += re[g]
            ops.append(O)
        if k == WILSON_LEVEL:
            wl_links = S
    # Wilson loops: spatial lines from the smeared links, temporal lines from U
    rmax, tmax = min(RMAX, L // 2), min(TMAX, L // 2)
    W = [[0.0] * (tmax + 1) for _ in range(rmax + 1)]
    one = G.one
    tl = [[one] * N for _ in range(tmax + 1)]          # tl[T][x] = U(x,0) U(x+0,0) ... (T links)
    for T in range(1, tmax + 1):
        for x in range(N):
            y = x
            for _ in range(T - 1):
                y = up[y][0]
            tl[T][x] = mul[tl[T - 1][x]][U[4 * y + 0]]
    for i in (1, 2, 3):
        sl = [[one] * N for _ in range(rmax + 1)]
        endR = [list(range(N)) for _ in range(rmax + 1)]
        for R in range(1, rmax + 1):
            for x in range(N):
                y = endR[R - 1][x]
                sl[R][x] = mul[sl[R - 1][x]][wl_links[4 * y + i]]
                endR[R][x] = up[y][i]
        endT = [list(range(N)) for _ in range(tmax + 1)]
        for T in range(1, tmax + 1):
            for x in range(N):
                endT[T][x] = up[endT[T - 1][x]][0]
        for R in range(1, rmax + 1):
            sR, eR = sl[R], endR[R]
            for T in range(1, tmax + 1):
                tT, eT = tl[T], endT[T]
                acc = 0.0
                for x in range(N):
                    # S(x,R) T(x+R,T) S(x+T,R)^-1 T(x,T)^-1
                    g = mul[mul[mul[sR[x]][tT[eR[x]]]][inv[sR[eT[x]]]]][inv[tT[x]]]
                    acc += re[g]
                W[R][T] += acc / (3 * N)
    return ops, W


def save_ckpt(path, state):
    """Atomic JSON write (a preempted job never leaves a half-written checkpoint)."""
    import json
    tmp = path + ".tmp"
    with open(tmp, "w") as fh:
        json.dump(state, fh)
    os.replace(tmp, path)


def run_gap(args):
    """One chain. With a 7th argument (checkpoint path) the state is saved after every
    configuration (thermalisation sweep or measurement) and a restart continues from it."""
    L, beta, therm, nmeas, every, seed = args[:6]
    ckpt = args[6] if len(args) > 6 else None
    G = Group()
    nb = neighbours(G)
    rng = random.Random(seed)
    N, up, dn = lattice(L)
    mul, inv, coord, re = G.mul, G.inv, G.coord, G.re
    n = G.n
    U = [G.one] * (4 * N)
    pl = []

    def sweep():
        for x in range(N):
            for mu in range(4):
                s0 = s1 = s2 = s3 = 0.0
                xm = up[x][mu]
                for nu in range(4):
                    if nu == mu:
                        continue
                    v = mul[mul[U[4 * xm + nu]][inv[U[4 * up[x][nu] + mu]]]][inv[U[4 * x + nu]]]
                    c = coord[v]
                    s0 += c[0]; s1 += c[1]; s2 += c[2]; s3 += c[3]
                    y = dn[x][nu]
                    v = mul[mul[inv[U[4 * up[y][mu] + nu]]][inv[U[4 * y + mu]]]][U[4 * y + nu]]
                    c = coord[v]
                    s0 += c[0]; s1 += c[1]; s2 += c[2]; s3 += c[3]
                es = [beta * (g[0] * s0 - g[1] * s1 - g[2] * s2 - g[3] * s3) for g in coord]
                mx = max(es)
                w = [math.exp(e - mx) for e in es]
                U[4 * x + mu] = rng.choices(range(n), weights=w)[0]

    import json
    data = []
    done_therm = 0
    meas_file = ckpt[:-len(".ckpt.json")] + ".meas.jsonl" if ckpt else None
    if ckpt and os.path.exists(ckpt):
        with open(ckpt) as fh:
            st = json.load(fh)
        U[:] = st["U"]
        v, internal, g = st["rng"]
        rng.setstate((v, tuple(internal), g))
        done_therm = st["therm_done"]
        ndata = st.get("ndata", len(st.get("data", [])))
        if ndata and os.path.exists(meas_file):
            with open(meas_file) as fh:
                for line in fh:
                    if len(data) == ndata:
                        break
                    data.append(tuple(json.loads(line)))
        # drop measurements written after the last checkpoint
        with open(meas_file, "w") as fh:
            for d in data:
                fh.write(json.dumps(d) + "\n")
    elif meas_file and os.path.exists(meas_file):
        os.remove(meas_file)

    def checkpoint():
        # state only; measurements are appended to meas_file before this is called
        if ckpt:
            save_ckpt(ckpt, {"L": L, "beta": beta, "seed": seed, "therm_done": done_therm,
                             "U": U, "rng": [list(x) if isinstance(x, tuple) else x for x in rng.getstate()],
                             "ndata": len(data)})

    while done_therm < therm:
        sweep()
        done_therm += 1
        checkpoint()
    while len(data) < nmeas:
        for _ in range(every):
            sweep()
        P = 0.0
        for x in range(N):
            for mu in range(4):
                for nu in range(mu + 1, 4):
                    P += re[mul[mul[mul[U[4 * x + mu]][U[4 * up[x][mu] + nu]]][inv[U[4 * up[x][nu] + mu]]]][inv[U[4 * x + nu]]]]
        ops, W = measure_gap(G, nb, L, up, dn, U)
        data.append((P / (6 * N), ops, W))
        if meas_file:
            with open(meas_file, "a") as fh:
                fh.write(json.dumps(data[-1]) + "\n")
                fh.flush()
                os.fsync(fh.fileno())
        checkpoint()
    return (L, beta, seed, data)


# ------------------------------------------------------------ SU(2) heat bath
def su2_plaquette(args):
    """Kennedy-Pendleton heat bath for SU(2) with the Wilson action (floating point)."""
    L, beta, therm, nmeas, seed = args
    rng = random.Random(seed)
    N, up, dn = lattice(L)
    U = [(1.0, 0.0, 0.0, 0.0)] * (4 * N)

    def qm(a, b):
        a0, a1, a2, a3 = a
        b0, b1, b2, b3 = b
        return (a0 * b0 - a1 * b1 - a2 * b2 - a3 * b3, a0 * b1 + a1 * b0 + a2 * b3 - a3 * b2,
                a0 * b2 - a1 * b3 + a2 * b0 + a3 * b1, a0 * b3 + a1 * b2 - a2 * b1 + a3 * b0)

    def cj(a):
        return (a[0], -a[1], -a[2], -a[3])

    def sweep():
        for x in range(N):
            for mu in range(4):
                s = [0.0] * 4
                xm = up[x][mu]
                for nu in range(4):
                    if nu == mu:
                        continue
                    v = qm(qm(U[4 * xm + nu], cj(U[4 * up[x][nu] + mu])), cj(U[4 * x + nu]))
                    y = dn[x][nu]
                    w = qm(qm(cj(U[4 * up[y][mu] + nu]), cj(U[4 * y + mu])), U[4 * y + nu])
                    for k in range(4):
                        s[k] += v[k] + w[k]
                # weight exp(beta Re(U S)); write S^dagger-direction: Re(U S) = U . conj(S)
                k = math.sqrt(sum(c * c for c in s))
                if k < 1e-12:
                    continue
                sd = (s[0] / k, -s[1] / k, -s[2] / k, -s[3] / k)     # unit vector along conj(S)
                bk = beta * k
                while True:     # Kennedy-Pendleton for a0 with density sqrt(1-a0^2) exp(bk a0)
                    r1, r2, r3 = 1 - rng.random(), rng.random(), 1 - rng.random()
                    lam2 = -(math.log(r1) + math.cos(2 * math.pi * r2) ** 2 * math.log(r3)) / (2 * bk)
                    if rng.random() ** 2 <= 1 - lam2:
                        break
                a0 = 1 - 2 * lam2
                rr = math.sqrt(max(0.0, 1 - a0 * a0))
                ct = 2 * rng.random() - 1
                ph = 2 * math.pi * rng.random()
                st = math.sqrt(1 - ct * ct)
                a = (a0, rr * st * math.cos(ph), rr * st * math.sin(ph), rr * ct)
                # U = a * S^-1 (unit): sd = conj(S)/k, so Re(U S) = k a0
                U[4 * x + mu] = qm(a, sd)

    for _ in range(therm):
        sweep()
    acc = []
    for _ in range(nmeas):
        sweep()
        P = 0.0
        for x in range(N):
            for mu in range(4):
                for nu in range(mu + 1, 4):
                    p = qm(qm(qm(U[4 * x + mu], U[4 * up[x][mu] + nu]), cj(U[4 * up[x][nu] + mu])), cj(U[4 * x + nu]))
                    P += p[0]
        acc.append(P / (6 * N))
    return beta, acc


def g2i_plaquette(args):
    L, beta, therm, nmeas, seed = args
    _, _, data = run((L, beta, therm, nmeas, 1, seed))
    return beta, [d[0] for d in data]


# ------------------------------------------------------------ linear algebra
def cholesky(A):
    n = len(A)
    Lm = [[0.0] * n for _ in range(n)]
    for i in range(n):
        for j in range(i + 1):
            s = A[i][j] - sum(Lm[i][k] * Lm[j][k] for k in range(j))
            if i == j:
                if s <= 0:
                    raise ValueError("not positive definite")
                Lm[i][i] = math.sqrt(s)
            else:
                Lm[i][j] = s / Lm[j][j]
    return Lm


def jacobi_eig(A, sweeps=60):
    n = len(A)
    A = [row[:] for row in A]
    V = [[float(i == j) for j in range(n)] for i in range(n)]
    for _ in range(sweeps):
        off = sum(A[i][j] ** 2 for i in range(n) for j in range(n) if i != j)
        if off < 1e-24:
            break
        for p in range(n):
            for q in range(p + 1, n):
                if abs(A[p][q]) < 1e-300:
                    continue
                th = (A[q][q] - A[p][p]) / (2 * A[p][q])
                t = (1 if th >= 0 else -1) / (abs(th) + math.sqrt(th * th + 1))
                c = 1 / math.sqrt(t * t + 1)
                s = t * c
                for k in range(n):
                    akp, akq = A[k][p], A[k][q]
                    A[k][p], A[k][q] = c * akp - s * akq, s * akp + c * akq
                for k in range(n):
                    apk, aqk = A[p][k], A[q][k]
                    A[p][k], A[q][k] = c * apk - s * aqk, s * apk + c * aqk
                for k in range(n):
                    vkp, vkq = V[k][p], V[k][q]
                    V[k][p], V[k][q] = c * vkp - s * vkq, s * vkp + c * vkq
    return [A[i][i] for i in range(n)], V


def lower_solve(Lm, b):
    n = len(b)
    y = [0.0] * n
    for i in range(n):
        y[i] = (b[i] - sum(Lm[i][k] * y[k] for k in range(i))) / Lm[i][i]
    return y


def upper_solve_T(Lm, b):
    """Solve L^T x = b."""
    n = len(b)
    x = [0.0] * n
    for i in reversed(range(n)):
        x[i] = (b[i] - sum(Lm[k][i] * x[k] for k in range(i + 1, n))) / Lm[i][i]
    return x


# ------------------------------------------------------------ analysis
def corr_matrices(samples, L, nops):
    """C_ij(dt), connected, averaged over t and the two time orders."""
    n = len(samples)
    mean = [sum(sum(s[i]) for s in samples) / (n * L) for i in range(nops)]
    C = []
    for dt in range(L // 2 + 1):
        M = [[0.0] * nops for _ in range(nops)]
        for i in range(nops):
            for j in range(i, nops):
                acc = 0.0
                for s in samples:
                    Oi, Oj = s[i], s[j]
                    for t in range(L):
                        acc += Oi[t] * Oj[(t + dt) % L] + Oj[t] * Oi[(t + dt) % L]
                v = acc / (2 * n * L) - mean[i] * mean[j]
                M[i][j] = M[j][i] = v
        C.append(M)
    return C


def gevp_vector(C, t0, t1):
    Lm = cholesky(C[t0])
    n = len(C[0])
    # M = L^-1 C(t1) L^-T
    Y = [lower_solve(Lm, [C[t1][r][c] for r in range(n)]) for c in range(n)]       # columns of L^-1 C
    Mt = [[0.0] * n for _ in range(n)]
    for c in range(n):
        for r in range(n):
            Mt[r][c] = Y[c][r]
    Z = [lower_solve(Lm, [Mt[r][c] for c in range(n)]) for r in range(n)]          # rows of L^-1 (L^-1 C)^T
    M = [[(Z[r][c] + Z[c][r]) / 2 for c in range(n)] for r in range(n)]
    vals, vecs = jacobi_eig(M)
    k = max(range(n), key=lambda i: vals[i])
    u = [vecs[r][k] for r in range(n)]
    return upper_solve_T(Lm, u)


def meff_cosh(c0, c1, t, L):
    """m with c(t)/c(t+1) = cosh(m(t - L/2)) / cosh(m(t + 1 - L/2))."""
    if not (c0 > 0 and c1 > 0) or c1 >= c0:
        return float('nan')
    r = c0 / c1
    lo, hi = 1e-6, 20.0
    f = lambda m: math.cosh(m * (t - L / 2)) / math.cosh(m * (t + 1 - L / 2)) - r
    if f(hi) < 0:
        return float('nan')
    for _ in range(200):
        mid = (lo + hi) / 2
        if f(mid) < 0:
            lo = mid
        else:
            hi = mid
    return (lo + hi) / 2


def glueball(samples, L, t0=0, t1=1):
    """GEVP on the normalised operators; if C(t0) is not positive definite (too few samples),
    drop operators from the most smeared end until it is."""
    nops = len(samples[0])
    C = corr_matrices(samples, L, nops)
    keep = list(range(nops))
    while keep:
        sub = [[[C[dt][i][j] / math.sqrt(C[0][i][i] * C[0][j][j]) for j in keep] for i in keep]
               for dt in range(L // 2 + 1)] if all(C[0][i][i] > 0 for i in keep) else None
        try:
            if sub is None:
                raise ValueError
            v = gevp_vector(sub, t0, t1)
            break
        except ValueError:
            keep = keep[:-1]
    if not keep:
        return [float('nan')] * (L // 2 + 1), [float('nan')] * (L // 2)
    k = len(keep)
    c = [sum(v[i] * sub[dt][i][j] * v[j] for i in range(k) for j in range(k)) for dt in range(L // 2 + 1)]
    m = [meff_cosh(c[t], c[t + 1], t, L) for t in range(L // 2)]
    return c, m


def potential(Wmean):
    """V(R,T) = ln(W(R,T)/W(R,T+1))."""
    V = {}
    for R in range(1, len(Wmean)):
        for T in range(1, len(Wmean[0]) - 1):
            a, b = Wmean[R][T], Wmean[R][T + 1]
            V[(R, T)] = math.log(a / b) if a > 0 and b > 0 and a > b else float('nan')
    return V


def fit_cornell(Vs):
    """Least squares V(R) = A + sigma R - c / R."""
    pts = [(R, v) for R, v in Vs if v == v]
    if len(pts) < 3:
        return (float('nan'),) * 3
    rows = [(1.0, R, -1.0 / R) for R, _ in pts]
    y = [v for _, v in pts]
    A = [[sum(r[i] * r[j] for r in rows) for j in range(3)] for i in range(3)]
    b = [sum(r[i] * yy for r, yy in zip(rows, y)) for i in range(3)]
    for i in range(3):
        p = max(range(i, 3), key=lambda k: abs(A[k][i]))
        A[i], A[p] = A[p], A[i]
        b[i], b[p] = b[p], b[i]
        for k in range(3):
            if k != i:
                f = A[k][i] / A[i][i]
                A[k] = [x - f * z for x, z in zip(A[k], A[i])]
                b[k] -= f * b[i]
    return tuple(b[i] / A[i][i] for i in range(3))


def meff_curve(samples, L, t0, t1):
    c, m = glueball(samples, L, t0, t1)
    return m


def analyse_gap(L, data, nb=10, t0=0, t1=1):
    """Glueball: effective masses with jackknife errors; the plateau starts at the first t
    with m_eff(t) and m_eff(t+1) finite and equal within 1.5 combined errors, and the mass is
    the error-weighted mean of m_eff on [t, t+1]. String tension from V(R) at T = Tplat."""
    nb = min(nb, len(data))
    samples = [d[1] for d in data]
    n = len(data)
    bs = n // nb
    blocks = [[i for i in range(n) if not (b * bs <= i < (b + 1) * bs)] for b in range(nb)]

    def jerr(vals, f0):
        vals = [v for v in vals if v == v]
        if len(vals) < nb or f0 != f0:
            return float('nan')
        mu = sum(vals) / len(vals)
        return math.sqrt((len(vals) - 1) / len(vals) * sum((v - mu) ** 2 for v in vals))

    m_full = meff_curve(samples, L, t0, t1)
    m_jk = [meff_curve([samples[i] for i in idx], L, t0, t1) for idx in blocks]
    m_err = [jerr([mj[t] for mj in m_jk], m_full[t]) for t in range(len(m_full))]
    # plateau: every t >= 2 whose effective mass is finite with jackknife error below its value
    pts = [t for t in range(2, len(m_full)) if m_full[t] == m_full[t] and m_err[t] == m_err[t] and m_err[t] < m_full[t]]
    tp = pts[0] if pts else None

    def plateau_mass(ms):
        if not pts or any(ms[t] != ms[t] for t in pts):
            return float('nan')
        w = [1 / m_err[t] ** 2 for t in pts]
        return sum(wi * ms[t] for wi, t in zip(w, pts)) / sum(w)
    m0 = plateau_mass(m_full)
    mj = [plateau_mass(x) for x in m_jk]
    me = jerr(mj, m0)

    rmax = len(data[0][2]) - 1
    tmax = len(data[0][2][0]) - 1

    def sigma_of(idx, Tp):
        Wm = [[sum(data[i][2][R][T] for i in idx) / len(idx) for T in range(tmax + 1)] for R in range(rmax + 1)]
        V = potential(Wm)
        A, sig, cc = fit_cornell([(R, V[(R, Tp)]) for R in range(1, rmax + 1)])
        return sig, cc, A, [V[(R, Tp)] for R in range(1, rmax + 1)]
    # T plateau: first T with sigma(T), sigma(T+1) equal within 1.5 combined jackknife errors
    sigT = {}
    for Tp in range(2, tmax):
        f0 = sigma_of(list(range(n)), Tp)[0]
        fj = [sigma_of(idx, Tp)[0] for idx in blocks]
        sigT[Tp] = (f0, jerr(fj, f0), fj)
    Tsel = None
    for Tp in range(2, tmax - 1):
        a, ea = sigT[Tp][0], sigT[Tp][1]
        b, eb = sigT[Tp + 1][0], sigT[Tp + 1][1]
        if all(x == x for x in (a, b, ea, eb)) and abs(a - b) < 1.5 * math.sqrt(ea ** 2 + eb ** 2):
            Tsel = Tp + 1
            break
    if Tsel is None:
        Tsel = tmax - 1
    if Tsel in sigT:
        s0 = sigma_of(list(range(n)), Tsel)
        sj = sigT[Tsel][2]
        se = sigT[Tsel][1]
    else:
        s0 = (float('nan'), float('nan'), float('nan'), [])
        sj = [float('nan')] * nb
        se = float('nan')
    ratio = m0 / math.sqrt(s0[0]) if s0[0] == s0[0] and s0[0] > 0 and m0 == m0 else float('nan')
    rj = [a / math.sqrt(b) if a == a and b == b and b > 0 else float('nan') for a, b in zip(mj, sj)]
    re_ = jerr(rj, ratio)
    return dict(m=m0, m_err=me, sigma=s0[0], s_err=se, ratio=ratio, r_err=re_, meff=m_full, meff_err=m_err,
                tp=tp, pts=pts, V=s0[3], c=s0[1], A=s0[2], Tsel=Tsel, sigT={k: (v[0], v[1]) for k, v in sigT.items()})


DATA_DIR = os.path.join(HERE, "data")     # raw measurements (not in git)
RAW_IN = None



# ===================================================================== T27: chains on disk
CHAIN_DIR = os.environ.get("YM_CHAIN_DIR") or os.path.join(DATA_DIR, "chains")


def chain_seed(L, beta, k):
    return 100000 + 1000 * L + int(round(1000 * beta)) * 7 + 13 * k


def chain_file(L, beta, seed):
    return os.path.join(CHAIN_DIR, f"L{L}_b{beta:.3f}_s{seed}.json")


def run_chain_to_disk(args):
    """One Markov chain; the measurements are written to work/data/chains/."""
    L, beta, therm, nmeas, every, seed = args
    import json
    os.makedirs(CHAIN_DIR, exist_ok=True)
    if os.path.exists(chain_file(L, beta, seed)):
        return chain_file(L, beta, seed)                  # finished earlier
    ck = os.path.join(CHAIN_DIR, "ckpt", f"L{L}_b{beta:.3f}_s{seed}.ckpt.json")
    os.makedirs(os.path.dirname(ck), exist_ok=True)
    _, _, _, data = run_gap((L, beta, therm, nmeas, every, seed, ck))
    with open(chain_file(L, beta, seed), "w") as fh:
        json.dump({"L": L, "beta": beta, "seed": seed, "therm": therm, "every": every, "data": data}, fh)
    return chain_file(L, beta, seed)


def load_chains():
    """All chains in work/data/chains, merged by (L, beta). With YM_PARTIAL=<dir>, the
    measurements of unfinished chains (<dir>/*.meas.jsonl, copied from a running job)
    are used as well: a preview, never mixed into the final report."""
    import glob, json
    merged = {}
    for f in sorted(glob.glob(os.path.join(CHAIN_DIR, "*.json"))):
        with open(f) as fh:
            d = json.load(fh)
        merged.setdefault((d["L"], round(d["beta"], 3)), []).extend(d["data"])
    part = os.environ.get("YM_PARTIAL")
    if part:
        for f in sorted(glob.glob(os.path.join(part, "*.meas.jsonl"))):
            name = os.path.basename(f)
            L = int(name.split("_")[0][1:])
            b = round(float(name.split("_")[1][1:]), 3)
            with open(f) as fh:
                merged.setdefault((L, b), []).extend(json.loads(line) for line in fh if line.strip())
    return merged


def split_merged_raw(path, tag):
    """Store an older merged raw file (dict 'L,beta' -> data) as chain files."""
    import json
    with open(path) as fh:
        raw = json.load(fh)
    os.makedirs(CHAIN_DIR, exist_ok=True)
    for key, data in raw.items():
        L, b = key.split(",")
        L, b = int(L), float(b)
        with open(os.path.join(CHAIN_DIR, f"L{L}_b{b:.3f}_{tag}.json"), "w") as fh:
            json.dump({"L": L, "beta": b, "seed": tag, "therm": 200, "every": 1, "data": data}, fh)



# ------------------------------------------------------------ PDF plots (standard library only)
def pdf_plot(path, series, xlabel, ylabel, title, xrange=None, yrange=None):
    """Vector PDF: each series is dict(points=[(x, y, err)], line=[(x, y), ...] or None, label=str)."""
    W, H, ml, mb, mr, mt = 432, 324, 60, 50, 20, 30
    pts = [(x, y) for sr in series for (x, y, e) in sr.get("points", [])] + \
          [(x, y) for sr in series for (x, y) in (sr.get("line") or [])]
    ex = [(y - e, y + e) for sr in series for (x, y, e) in sr.get("points", [])]
    x0, x1 = xrange or (min(p[0] for p in pts), max(p[0] for p in pts))
    y0, y1 = yrange or (min([p[1] for p in pts] + [a for a, b in ex]), max([p[1] for p in pts] + [b for a, b in ex]))
    if x1 == x0:
        x1 += 1
    if y1 == y0:
        y1 += 1
    padx, pady = 0.05 * (x1 - x0), 0.08 * (y1 - y0)
    x0, x1, y0, y1 = x0 - padx, x1 + padx, y0 - pady, y1 + pady
    X = lambda x: ml + (x - x0) / (x1 - x0) * (W - ml - mr)
    Y = lambda y: mb + (y - y0) / (y1 - y0) * (H - mb - mt)
    c = []
    c.append("0.6 w 0 0 0 RG")
    c.append(f"{ml} {mb} m {W - mr} {mb} l {W - mr} {H - mt} l {ml} {H - mt} l h S")

    def nice_ticks(a, b, n=5):
        step = 10 ** math.floor(math.log10((b - a) / n))
        for m in (1, 2, 5, 10):
            if (b - a) / (m * step) <= n:
                step *= m
                break
        t = math.ceil(a / step) * step
        out = []
        while t <= b + 1e-12:
            out.append(round(t, 10))
            t += step
        return out

    def text(x, y, s, size=9):
        s = s.replace("\\", "\\\\").replace("(", "\\(").replace(")", "\\)")
        c.append(f"BT /F1 {size} Tf {x:.2f} {y:.2f} Td ({s}) Tj ET")
    for t in nice_ticks(x0, x1):
        c.append(f"{X(t):.2f} {mb} m {X(t):.2f} {mb + 4} l S")
        text(X(t) - 10, mb - 14, f"{t:g}")
    for t in nice_ticks(y0, y1):
        c.append(f"{ml} {Y(t):.2f} m {ml + 4} {Y(t):.2f} l S")
        text(ml - 34, Y(t) - 3, f"{t:g}")
    text((W) / 2 - 40, 12, xlabel, 10)
    text(8, H - 18, ylabel, 10)
    text(ml, H - 18, "", 10)
    text(W / 2 - 60, H - 16, title, 10)
    colors = ["0 0 0", "0.8 0.1 0.1", "0.1 0.3 0.8", "0.1 0.6 0.2"]
    ly = H - mt - 14
    for k, sr in enumerate(series):
        col = colors[k % len(colors)]
        c.append(f"{col} RG {col} rg 0.8 w")
        line = sr.get("line")
        if line:
            c.append(" ".join([f"{X(line[0][0]):.2f} {Y(line[0][1]):.2f} m"] + [f"{X(x):.2f} {Y(y):.2f} l" for x, y in line[1:]]) + " S")
        for (x, y, e) in sr.get("points", []):
            c.append(f"{X(x):.2f} {Y(y - e):.2f} m {X(x):.2f} {Y(y + e):.2f} l S")
            c.append(f"{X(x) - 2.5:.2f} {Y(y) - 2.5:.2f} 5 5 re f")
        if sr.get("label"):
            c.append(f"{W - mr - 150:.2f} {ly + 3:.2f} 5 5 re f")
            c.append("0 0 0 rg")
            text(W - mr - 140, ly + 2, sr["label"], 8)
            ly -= 12
    stream = "\n".join(c).encode("latin-1")
    objs = [b"<< /Type /Catalog /Pages 2 0 R >>", b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
            f"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {W} {H}] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>".encode(),
            b"<< /Length " + str(len(stream)).encode() + b" >>\nstream\n" + stream + b"\nendstream",
            b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>"]
    out = b"%PDF-1.4\n"
    offs = []
    for i, o in enumerate(objs):
        offs.append(len(out))
        out += f"{i + 1} 0 obj\n".encode() + o + b"\nendobj\n"
    xref = len(out)
    out += f"xref\n0 {len(objs) + 1}\n0000000000 65535 f \n".encode()
    for o in offs:
        out += f"{o:010d} 00000 n \n".encode()
    out += f"trailer << /Size {len(objs) + 1} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n".encode()
    with open(path, "wb") as fh:
        fh.write(out)


# ------------------------------------------------------------ continuum analysis
def wls_line(xs, ys, es):
    """Weighted least squares y = c0 + c1 x; returns c0, c1, err0, err1, chi2."""
    w = [1 / e ** 2 for e in es]
    S, Sx, Sy = sum(w), sum(wi * x for wi, x in zip(w, xs)), sum(wi * y for wi, y in zip(w, ys))
    Sxx = sum(wi * x * x for wi, x in zip(w, xs))
    Sxy = sum(wi * x * y for wi, x, y in zip(w, xs, ys))
    D = S * Sxx - Sx * Sx
    c1 = (S * Sxy - Sx * Sy) / D
    c0 = (Sxx * Sy - Sx * Sxy) / D
    chi2 = sum(wi * (y - c0 - c1 * x) ** 2 for wi, x, y in zip(w, xs, ys))
    return c0, c1, math.sqrt(Sxx / D), math.sqrt(S / D), chi2


def two_loop_aLambda(beta, N=2):
    g2 = 2 * N / beta
    b0 = 11 * N / (48 * math.pi ** 2)
    b1 = 34 * N ** 2 / (3 * (16 * math.pi ** 2) ** 2)
    return (b0 * g2) ** (-b1 / (2 * b0 ** 2)) * math.exp(-1 / (2 * b0 * g2))


def main_cont():
    out = []
    merged = load_chains()
    out.append("Continuum analysis of the 2I spectroscopy: all chains in work/data/chains (fixed seeds).")
    out.append("Per (L, beta): 0++ mass (GEVP on 6 smeared loop operators, plateau t >= 2), sigma from V(R) = A + sigma R - c/R")
    out.append("at the first stable T; jackknife over 10 blocks.")
    out.append(" L   beta   meas   plaquette  m a              sigma a^2           m/sqrt(sigma)    m L   sqrt(sigma) L")
    rows = []
    for (L, b) in sorted(merged, key=lambda k: (k[1], k[0])):
        data = merged[(L, b)]
        if len(data) < 50:
            continue
        r = analyse_gap(L, data)
        P = sum(d[0] for d in data) / len(data)
        out.append(f" {L:<3} {b:<6} {len(data):<6} {P:.4f}     {r['m']:.3f} +- {r['m_err']:.3f}   {r['sigma']:.4f} +- {r['s_err']:.4f}   "
                   f"{r['ratio']:.2f} +- {r['r_err']:.2f}    {r['m'] * L:.1f}   {math.sqrt(r['sigma']) * L if r['sigma'] > 0 else float('nan'):.1f}")
        rows.append((L, b, r))
    # continuum extrapolation over beta >= 2.4 with finite errors and m L > 4
    use = [(L, b, r) for L, b, r in rows if b >= 2.4 and r["r_err"] == r["r_err"] and r["m"] * L > 4]
    res = {}
    if len(use) >= 2:
        xs = [r["sigma"] for _, _, r in use]
        ys = [r["ratio"] for _, _, r in use]
        es = [r["r_err"] for _, _, r in use]
        c0, c1, e0, e1, chi2 = wls_line(xs, ys, es)
        dof = len(use) - 2
        out.append("")
        out.append(f"Extrapolation m/sqrt(sigma) = c0 + c1 (a^2 sigma) over {len(use)} points (beta >= 2.4, m L > 4):")
        out.append(f"  c0 = {c0:.3f} +- {e0:.3f},  c1 = {c1:.2f} +- {e1:.2f},  chi^2 = {chi2:.2f} for {dof} dof")
        w = [1 / e ** 2 for e in es]
        mean = sum(wi * y for wi, y in zip(w, ys)) / sum(w)
        out.append(f"  constant fit: {mean:.3f} +- {1 / math.sqrt(sum(w)):.3f}")
        out.append(f"  target error 0.1: {'reached' if e0 <= 0.1 else 'not reached (more statistics and larger L: work/kamiak)'}")
        res = dict(c0=c0, e0=e0, c1=c1, chi2=chi2, dof=dof)
        pdf_plot(os.path.join(HERE, "fig_ym_extrapolation.pdf"),
                 [dict(points=list(zip(xs, ys, es)), label="2I, Wilson action"),
                  dict(line=[(0.0, c0), (max(xs) * 1.05, c0 + c1 * max(xs) * 1.05)], label=f"c0 = {c0:.2f} +- {e0:.2f}")],
                 "a^2 sigma", "m/sqrt(sigma)", "0++ mass over sqrt(sigma), a -> 0",
                 xrange=(0.0, max(xs) * 1.05))
    # running: sigma a^2 against two-loop a Lambda
    sel = [(b, r) for L, b, r in rows if r["sigma"] == r["sigma"] and r["s_err"] == r["s_err"]]
    if sel:
        out.append("")
        out.append("Running coupling: two-loop a Lambda_L(beta) for SU(2) (g^2 = 4/beta); sqrt(sigma)/Lambda_L per beta:")
        vals = []
        for b, r in sel:
            aL = two_loop_aLambda(b)
            q = math.sqrt(r["sigma"]) / aL
            qe = 0.5 * r["s_err"] / math.sqrt(r["sigma"]) / aL
            vals.append((b, q, qe))
            out.append(f"  beta = {b}: a Lambda_L = {aL:.5f}, sqrt(sigma)/Lambda_L = {q:.1f} +- {qe:.1f}")
        w = [1 / e ** 2 for _, _, e in vals]
        mean = sum(wi * q for wi, (_, q, _) in zip(w, vals)) / sum(w)
        chi2 = sum(((q - mean) / e) ** 2 for _, q, e in vals)
        out.append(f"  weighted mean sqrt(sigma)/Lambda_L = {mean:.1f} +- {1 / math.sqrt(sum(w)):.1f}, chi^2 = {chi2:.1f} for {len(vals) - 1} dof")
        bs = [b for b, _ in sel]
        line = [(bb, (mean * two_loop_aLambda(bb)) ** 2) for bb in [min(bs) + k * (max(bs) - min(bs)) / 40 for k in range(41)]]
        pdf_plot(os.path.join(HERE, "fig_ym_running.pdf"),
                 [dict(points=[(b, r["sigma"], r["s_err"]) for b, r in sel], label="sigma a^2 (2I)"),
                  dict(line=line, label="two-loop, one fitted Lambda")],
                 "beta", "sigma a^2", "string tension against the two-loop running")
        res["lam"] = mean
    text = "\n".join(out) + "\n"
    with open(os.path.join(HERE, "NUMERIC_YMCONT.txt"), "w", encoding="utf-8") as fh:
        fh.write(text)
    print(text, end="")
    return res


# ------------------------------------------------------------ 2I against SU(2): loops
def su2_loops(args):
    L, beta, therm, nmeas, seed = args
    rng = random.Random(seed)
    N, up, dn = lattice(L)
    U = [(1.0, 0.0, 0.0, 0.0)] * (4 * N)

    def qm(a, b):
        a0, a1, a2, a3 = a
        b0, b1, b2, b3 = b
        return (a0 * b0 - a1 * b1 - a2 * b2 - a3 * b3, a0 * b1 + a1 * b0 + a2 * b3 - a3 * b2,
                a0 * b2 - a1 * b3 + a2 * b0 + a3 * b1, a0 * b3 + a1 * b2 - a2 * b1 + a3 * b0)

    def cj(a):
        return (a[0], -a[1], -a[2], -a[3])

    def sweep():
        for x in range(N):
            for mu in range(4):
                s = [0.0] * 4
                xm = up[x][mu]
                for nu in range(4):
                    if nu == mu:
                        continue
                    v = qm(qm(U[4 * xm + nu], cj(U[4 * up[x][nu] + mu])), cj(U[4 * x + nu]))
                    y = dn[x][nu]
                    w = qm(qm(cj(U[4 * up[y][mu] + nu]), cj(U[4 * y + mu])), U[4 * y + nu])
                    for k in range(4):
                        s[k] += v[k] + w[k]
                k = math.sqrt(sum(c * c for c in s))
                sd = (s[0] / k, -s[1] / k, -s[2] / k, -s[3] / k)
                bk = beta * k
                while True:
                    r1, r2, r3 = 1 - rng.random(), rng.random(), 1 - rng.random()
                    lam2 = -(math.log(r1) + math.cos(2 * math.pi * r2) ** 2 * math.log(r3)) / (2 * bk)
                    if rng.random() ** 2 <= 1 - lam2:
                        break
                a0 = 1 - 2 * lam2
                rr = math.sqrt(max(0.0, 1 - a0 * a0))
                ct = 2 * rng.random() - 1
                ph = 2 * math.pi * rng.random()
                st = math.sqrt(1 - ct * ct)
                U[4 * x + mu] = qm((a0, rr * st * math.cos(ph), rr * st * math.sin(ph), rr * ct), sd)

    def loop(x, mu, nu, R, T):
        g = (1.0, 0.0, 0.0, 0.0)
        y = x
        for _ in range(R):
            g = qm(g, U[4 * y + mu]); y = up[y][mu]
        for _ in range(T):
            g = qm(g, U[4 * y + nu]); y = up[y][nu]
        for _ in range(R):
            y = dn[y][mu]; g = qm(g, cj(U[4 * y + mu]))
        for _ in range(T):
            y = dn[y][nu]; g = qm(g, cj(U[4 * y + nu]))
        return g[0]

    for _ in range(therm):
        sweep()
    acc = []
    for _ in range(nmeas):
        sweep()
        Wv = {(1, 1): 0.0, (1, 2): 0.0, (2, 2): 0.0}
        cnt = 0
        for x in range(N):
            for mu in range(4):
                for nu in range(mu + 1, 4):
                    Wv[(1, 1)] += loop(x, mu, nu, 1, 1)
                    Wv[(1, 2)] += 0.5 * (loop(x, mu, nu, 1, 2) + loop(x, mu, nu, 2, 1))
                    Wv[(2, 2)] += loop(x, mu, nu, 2, 2)
                    cnt += 1
        acc.append({k: v / cnt for k, v in Wv.items()})
    return ("SU2", L, beta, acc)


def g2i_loops(args):
    L, beta, therm, nmeas, seed = args
    _, _, data = run((L, beta, therm, nmeas, 1, seed))
    return ("2I", L, beta, [d[1] for d in data])


def main_compare(L=6, therm=100, nmeas=200):
    betas = [2.4, 2.5, 2.6, 2.7, 2.775, 2.85]
    tasks = [(L, b, therm, nmeas, 900 + int(1000 * b)) for b in betas]
    nw = int(os.environ.get("SLURM_CPUS_PER_TASK", min(12, 2 * len(tasks))))
    with mp.Pool(nw) as pool:
        ra = pool.map_async(su2_loops, tasks)
        rb = pool.map_async(g2i_loops, tasks)
        A, B = ra.get(), rb.get()
    out = [f"2I against SU(2) at the same beta, Wilson action, (Z/{L})^4, {nmeas} measurements after {therm} sweeps:",
           " beta    obs        2I                  SU(2)               difference"]

    def stat(xs):
        n = len(xs)
        mu = sum(xs) / n
        nb = 10
        bs = n // nb
        bm = [sum(xs[i * bs:(i + 1) * bs]) / bs for i in range(nb)]
        return mu, math.sqrt(sum((v - mu) ** 2 for v in bm) / (nb * (nb - 1)))
    for (_, _, b, su), (_, _, _, gi) in zip(A, B):
        for key, name in (((1, 1), "W(1,1)"), ((2, 2), "W(2,2)")):
            a, ae = stat([d[key] for d in gi])
            c, ce = stat([d[key] for d in su])
            out.append(f" {b:<6}  {name:<9}  {a:.5f} +- {ae:.5f}   {c:.5f} +- {ce:.5f}   {a - c:+.5f} ({abs(a - c) / math.sqrt(ae ** 2 + ce ** 2):.1f} sigma)")
        chi = lambda W: -math.log(W[(2, 2)] * W[(1, 1)] / W[(1, 2)] ** 2)
        ga = {k: sum(d[k] for d in gi) / len(gi) for k in gi[0]}
        sa = {k: sum(d[k] for d in su) / len(su) for k in su[0]}
        out.append(f" {b:<6}  chi(2,2)   {chi(ga):.4f}              {chi(sa):.4f}              {chi(ga) - chi(sa):+.4f}")
    text = "\n".join(out) + "\n"
    with open(os.path.join(HERE, "NUMERIC_YMCOMPARE.txt"), "w", encoding="utf-8") as fh:
        fh.write(text)
    print(text, end="")


def main_gap(quick=False):
    out = []
    ok = True

    def check(name, cond):
        nonlocal ok
        ok = ok and cond
        out.append(f"  [{'PASS' if cond else 'FAIL'}] {name}")

    G = Group()
    nb = neighbours(G)
    check("600-cell graph: every element has 12 nearest neighbours", all(len(x) == 12 for x in nb))
    # projection = exact argmax (hill climbing on a convex polytope): test on random vectors
    rng = random.Random(5)
    good = True
    for _ in range(2000):
        V = tuple(rng.gauss(0, 1) for _ in range(4))
        ex = max(range(G.n), key=lambda g: sum(a * b for a, b in zip(G.coord[g], V)))
        hc = project(G, nb, V, rng.randrange(G.n))
        good = good and abs(sum(a * b for a, b in zip(G.coord[ex], V)) - sum(a * b for a, b in zip(G.coord[hc], V))) < 1e-12
    check("projection back to the group by climbing equals the exact argmax (2000 random vectors)", good)

    betas = [2.2, 2.3, 2.4, 2.5, 2.6]
    # 2I versus SU(2): plaquette on (Z/4)^4
    if quick:
        cmp_tasks = [(4, b, 10, 10, 50 + int(100 * b)) for b in (2.2, 2.6)]
    else:
        cmp_tasks = [(4, b, 100, 400, 50 + int(100 * b)) for b in betas]
    with mp.Pool(min(10, 2 * len(cmp_tasks))) as pool:
        su2 = dict(pool.map(su2_plaquette, cmp_tasks))
        g2i = dict(pool.map(g2i_plaquette, cmp_tasks))

    def mean_err(xs):
        n = len(xs)
        mu = sum(xs) / n
        nbk = 10
        bs = n // nbk
        bm = [sum(xs[i * bs:(i + 1) * bs]) / bs for i in range(nbk)]
        return mu, math.sqrt(sum((b - mu) ** 2 for b in bm) / (nbk * (nbk - 1)))
    out.append("2I against SU(2): plaquette on (Z/4)^4, same Wilson action (SU(2) by Kennedy-Pendleton heat bath)")
    out.append("  beta   2I                 SU(2)              difference (in errors, relative)")
    track = True
    for b in sorted(su2):
        a, ae = mean_err(g2i[b])
        c, ce = mean_err(su2[b])
        z = abs(a - c) / math.sqrt(ae ** 2 + ce ** 2)
        rel = abs(a - c) / c
        track = track and rel < 0.01
        out.append(f"  {b:<5}  {a:.4f} +- {ae:.4f}   {c:.4f} +- {ce:.4f}   {z:.2f} sigma, {100 * rel:.2f}%")
    check("2I tracks SU(2): plaquettes differ by less than 1% at every beta", track)

    # main runs
    if quick:
        plan = [(4, 2.4, 10, 6, 2)]
        chains = 1
    else:
        plan = [(8, 2.2, 200, 3200, 1), (8, 2.3, 200, 3200, 1),
                (10, 2.4, 200, 2600, 1), (10, 2.5, 200, 2600, 1), (10, 2.6, 200, 2600, 1)]
        chains = 2
    tasks = []
    for (L, b, th, nm, ev) in plan:
        for c in range(chains):
            tasks.append((L, b, th, nm, ev, 7000 + 100 * c + int(100 * b) + L))
    raw_in = os.environ.get("YM_RAW_IN") or RAW_IN
    if raw_in:
        import json
        with open(raw_in) as fh:
            loaded = json.load(fh)
        res = []
        for key, v in loaded.items():
            Lk, bk = key.split(",")
            res.append((int(Lk), float(bk), 0, v))
    else:
        with mp.Pool(min(10, len(tasks))) as pool:
            res = pool.map(run_gap, tasks)
    merged = {}
    for L, b, seed, data in res:
        merged.setdefault((L, b), []).extend(data)
    raw = os.environ.get("YM_RAW") or (None if (raw_in or quick) else os.path.join(DATA_DIR, "ymgap_raw.json"))
    if raw:
        os.makedirs(os.path.dirname(raw), exist_ok=True)
        import json
        with open(raw, "w") as fh:
            json.dump({f"{L},{b}": v for (L, b), v in merged.items()}, fh)
    out.append("")
    if raw_in:
        out.append("Spectroscopy data: the chains of `gap` mode (fixed seeds), read back from their saved raw measurements.")
    out.append(f"Smearing: V = U + {SMEAR_EPS} * (4 spatial staples), back to 2I by argmax; levels {SMEAR_LEVELS}.")
    out.append(f"0++: GEVP C(1) v = lambda C(0) v on the spatial R x R loops, R in {LOOP_SIZES}, at each smearing level; m from the cosh effective mass")
    out.append("of v^T C(t) v, error-weighted over all t >= 2 with jackknife error below the value;")
    out.append("sigma from V(R) = A + sigma R - c/R, R = 1..min(5, L/2),")
    out.append("V(R,T) = ln W(R,T)/W(R,T+1) (spatial lines at smearing level %d); T taken where sigma(T) = sigma(T+1) within 1.5 errors." % SMEAR_LEVELS[WILSON_LEVEL])
    out.append("Jackknife over 10 blocks.")
    out.append(" L   beta  meas  plaquette")
    rows = []
    for (L, b) in sorted(merged):
        data = merged[(L, b)]
        r = analyse_gap(L, data)
        P = sum(d[0] for d in data) / len(data)
        me = " ".join(f"{x:.3f}({e:.3f})" if x == x else "nan" for x, e in zip(r["meff"][:5], r["meff_err"][:5]))
        out.append(f" {L:<3} {b:<5} {len(data):<5} {P:.4f}  plateau t={r['pts']}  "
                   f"m a = {r['m']:.3f} +- {r['m_err']:.3f}   sigma a^2 = {r['sigma']:.4f} +- {r['s_err']:.4f}   "
                   f"c = {r['c']:.3f}   m/sqrt(sigma) = {r['ratio']:.2f} +- {r['r_err']:.2f}   m L = {r['m'] * L:.1f}")
        out.append("      m_eff(t) (jackknife error), t = 0..4: " + me)
        out.append(f"      sigma a^2 from V(R,T), T = 2..{max(r['sigT'], default=1)}: " + "  ".join(f"T={T}: {v[0]:.4f}({v[1]:.4f})" for T, v in sorted(r['sigT'].items()))
                   + f"   -> T = {r['Tsel']}")
        out.append("      V(R), R=1..5: " + " ".join(f"{v:.4f}" for v in r["V"]))
        rows.append((L, b, r))
    def constancy(sel, label):
        good = [r for _, b, r in rows if sel(b) and r["ratio"] == r["ratio"] and r["r_err"] == r["r_err"]]
        if len(good) < 2:
            return None
        w = [1 / r["r_err"] ** 2 for r in good]
        mean = sum(wi * r["ratio"] for wi, r in zip(w, good)) / sum(w)
        err = 1 / math.sqrt(sum(w))
        chi2 = sum(((r["ratio"] - mean) / r["r_err"]) ** 2 for r in good)
        out.append(f"  {label}: weighted mean m/sqrt(sigma) = {mean:.3f} +- {err:.3f}; chi^2 = {chi2:.2f} for {len(good) - 1} dof")
        return chi2 / (len(good) - 1)
    c_all = constancy(lambda b: True, "all beta")
    c_win = constancy(lambda b: b >= 2.4, "beta >= 2.4")
    check("m/sqrt(sigma) constant within errors for beta = 2.4, 2.5, 2.6 (chi^2/dof < 2)", c_win is not None and c_win < 2)
    out.append(f"  (over all beta including 2.2 and 2.3: chi^2/dof = {c_all:.2f})" if c_all is not None else "")
    check("m L > 4 at every (L, beta)", all(r["m"] * L > 4 for L, _, r in rows if r["m"] == r["m"]))
    out.append(f"ALL {'PASS' if ok else 'FAIL'}")
    text = "\n".join(out) + "\n"
    if not quick:
        with open(os.path.join(HERE, "NUMERIC_YMGAP.txt"), "w", encoding="utf-8") as fh:
            fh.write(text)
    print(text, end="")
    return 0 if ok else 1


def main():
    quick = len(sys.argv) > 1 and sys.argv[1] == "quick"
    out = []
    ok = True

    def check(name, cond):
        nonlocal ok
        ok = ok and cond
        out.append(f"  [{'PASS' if cond else 'FAIL'}] {name}")

    els = build_2I()
    closed, inverses, norm, has_one = check_group(els)
    n8, c8, n24, c24 = subgroup_sizes(els)
    out.append("The binary icosahedral group 2I, built exactly in Z[phi]/2 (phi^2 = phi + 1):")
    check(f"number of elements = {len(els)} (expected 120)", len(els) == 120)
    check("closed under multiplication (all 14400 products, exact)", closed)
    check("every element has its conjugate as inverse, and contains 1", inverses and has_one)
    check("every element has norm 1 (exact)", norm)
    check(f"subgroup with integer coordinates: {n8} elements (Q8), closed", n8 == 8 and c8)
    check(f"subgroup with rational coordinates: {n24} elements (2T), closed", n24 == 24 and c24)
    G = Group()
    check("Re U is a class function on 2I (exact): the Wilson action is gauge invariant (YMChain.action_gauge_inv)",
          G.class_function_check())

    if quick:
        Ls = [(4, 20, 40, 2)]
        betas = [1.0, 2.0]
    else:
        Ls = [(4, 200, 4000, 4), (6, 200, 3000, 4), (8, 200, 2000, 4), (10, 200, 1200, 4)]
        betas = [1.0, 1.5, 2.0, 2.2, 2.4, 2.6]
    tasks = []
    for (L, th, me, ev) in Ls:
        for b in betas:
            tasks.append((L, b, th, me, ev, 1000 * L + int(100 * b)))
    tasks.sort(key=lambda t: -t[0] ** 4 * t[3])
    with mp.Pool(min(len(tasks), mp.cpu_count())) as pool:
        results = pool.map(run, tasks)
    out.append("")
    out.append("Wilson action beta sum_p (1 - Re U_p), heat bath over 2I, torus (Z/L)^4.")
    out.append("chi = Creutz ratio chi(2,2) ~ sigma a^2;  m = 0++ effective mass from C(1)/C(0) (cosh form).")
    out.append(" L  beta   meas  plaquette          sigma a^2 (chi22)     m a                 m/sqrt(sigma)")
    rows = []
    for L, b, data in sorted(results):
        full, errs, ratio, rerr = analyse(L, data)
        rows.append((L, b, full, errs, ratio, rerr))
        out.append(f" {L}  {b:<5}  {len(data):<5} {full[0]:.4f} +- {errs[0]:.4f}   {full[1]:.4f} +- {errs[1]:.4f}    "
                   f"{full[2]:.3f} +- {errs[2]:.3f}     {ratio:.3f} +- {rerr:.3f}")
    # strong-coupling comparison (leading order, Re-character expansion: u = I2(b)/I1(b) ~ b/4)
    out.append("")
    out.append("Leading strong-coupling values for SU(2) (comparison only): sigma a^2 ~ -ln(beta/4), m a ~ -4 ln(beta/4)")
    for b in betas:
        out.append(f"  beta = {b}: -ln(beta/4) = {-math.log(b / 4):.3f}, -4 ln(beta/4) = {-4 * math.log(b / 4):.3f}")
    out.append(f"ALL {'PASS' if ok else 'FAIL'}")
    text = "\n".join(out) + "\n"
    if not quick:
        with open(os.path.join(HERE, "NUMERIC_YM2I.txt"), "w", encoding="utf-8") as fh:
            fh.write(text)
    print(text, end="")
    return 0 if ok else 1


if __name__ == "__main__":
    if len(sys.argv) > 1 and sys.argv[1] in ("gap", "gapquick"):
        raise SystemExit(main_gap(quick=sys.argv[1] == "gapquick"))
    if len(sys.argv) > 1 and sys.argv[1] == "chain":
        # chain L beta therm nmeas every k   (k = chain index; seed from chain_seed)
        L_, b_, th_, nm_, ev_, k_ = sys.argv[2:8]
        print(run_chain_to_disk((int(L_), float(b_), int(th_), int(nm_), int(ev_), chain_seed(int(L_), float(b_), int(k_)))))
        raise SystemExit(0)
    if len(sys.argv) > 1 and sys.argv[1] == "pool":
        # pool L beta nchains therm nmeas every [k0]   (chains k0 .. k0+nchains-1, in parallel)
        L_, b_, nc_, th_, nm_, ev_ = sys.argv[2:8]
        k0 = int(sys.argv[8]) if len(sys.argv) > 8 else 0
        tasks = [(int(L_), float(b_), int(th_), int(nm_), int(ev_), chain_seed(int(L_), float(b_), k))
                 for k in range(k0, k0 + int(nc_))]
        nw = int(os.environ.get("SLURM_CPUS_PER_TASK", len(tasks)))
        with mp.Pool(min(nw, len(tasks))) as pool:
            for f in pool.imap_unordered(run_chain_to_disk, tasks):
                print(f)
        raise SystemExit(0)
    if len(sys.argv) > 1 and sys.argv[1] == "cont":
        main_cont()
        raise SystemExit(0)
    if len(sys.argv) > 1 and sys.argv[1] == "compare":
        # compare [L therm nmeas]
        if len(sys.argv) > 4:
            main_compare(int(sys.argv[2]), int(sys.argv[3]), int(sys.argv[4]))
        else:
            main_compare()
        raise SystemExit(0)
    if len(sys.argv) > 1 and sys.argv[1] == "gapanalyse":
        # rebuild NUMERIC_YMGAP.txt from saved raw measurements (default: work/data/ymgap_raw4.json)
        RAW_IN = sys.argv[2] if len(sys.argv) > 2 else os.path.join(DATA_DIR, "ymgap_raw4.json")
        raise SystemExit(main_gap())
    raise SystemExit(main())

Listing 378: NUMERIC_YM.txt

NUMERIC_YM.txt

Q8 from integer unit quaternions: table built from the quaternion product
  [PASS] group laws (associativity, unit, inverse) on all 512 / 8 cases
  [PASS] non-abelian: i j != j i
  [PASS] gauge invariance on (Z/3)^4, 20 random g, S = 423

Defect density <S>/(6 L^4) on (Z/4)^4, cold and hot starts (hysteresis = first order)
  cold  beta = 2.50  density = 0.0000
  cold  beta = 2.00  density = 0.0001
  cold  beta = 1.75  density = 0.0010
  cold  beta = 1.50  density = 0.0038
  cold  beta = 1.25  density = 0.0285
  cold  beta = 1.00  density = 0.7198
  cold  beta = 0.50  density = 0.8084
  hot   beta = 0.50  density = 0.8100
  hot   beta = 1.00  density = 0.7176
  hot   beta = 1.25  density = 0.6650
  hot   beta = 1.50  density = 0.5750
  hot   beta = 1.75  density = 0.0568
  hot   beta = 2.00  density = 0.0540
  hot   beta = 2.50  density = 0.0526

Mass gap estimate at beta = 1.0 (confined side), from the connected
correlator of time-slice defect counts, C(1)/C(0) = cosh(m(1-L/2))/cosh(m L/2)
m_low: the m obtained with C(1) replaced by C(1) + 2 sigma (a lower bound at about 95%)
 L   sweeps   C(0)        C(1)         sigma(C1)   m_eff            m_low
 2   40000    5.5259e+00  +2.1382e-02  2.7780e-02  6.248 ± 1.383    4.967
 3   20000    1.6596e+01  -6.8149e-02  6.4435e-02    (C(1) ~ 0)     5.614
 4   10000    3.9585e+01  -2.3744e-01  2.5748e-01    (C(1) ~ 0)     4.960
 5   6000     7.7346e+01  +4.6432e-01  4.8103e-01  5.115 ± 1.059    3.993
 6   4000     1.3246e+02  +6.1166e-01  7.8687e-01  5.378 ± 1.321    4.104
 8   2000     3.1340e+02  -1.3517e+00  2.1420e+00    (C(1) ~ 0)     4.672
  [PASS] lower bound m_low > 2 for every L = 2..8 (no sign of the gap closing)
  C(1) resolved from 0 (C(1) > 2 sigma) for L in []
  [PASS] where m_eff is defined (0 < C(1) < C(0)), m_eff > 3
ALL PASS

Listing 379: NUMERIC_YM2I.txt

NUMERIC_YM2I.txt

The binary icosahedral group 2I, built exactly in Z[phi]/2 (phi^2 = phi + 1):
  [PASS] number of elements = 120 (expected 120)
  [PASS] closed under multiplication (all 14400 products, exact)
  [PASS] every element has its conjugate as inverse, and contains 1
  [PASS] every element has norm 1 (exact)
  [PASS] subgroup with integer coordinates: 8 elements (Q8), closed
  [PASS] subgroup with rational coordinates: 24 elements (2T), closed
  [PASS] Re U is a class function on 2I (exact): the Wilson action is gauge invariant (YMChain.action_gauge_inv)

Wilson action beta sum_p (1 - Re U_p), heat bath over 2I, torus (Z/L)^4.
chi = Creutz ratio chi(2,2) ~ sigma a^2;  m = 0++ effective mass from C(1)/C(0) (cosh form).
 L  beta   meas  plaquette          sigma a^2 (chi22)     m a                 m/sqrt(sigma)
 4  1.0    1000  0.2425 +- 0.0002   1.4517 +- 0.0902    4.454 +- 2.053     3.696 +- 1.606
 4  1.5    1000  0.3628 +- 0.0004   1.0111 +- 0.0240    nan +- nan     nan +- nan
 4  2.0    1000  0.5028 +- 0.0007   0.5898 +- 0.0054    2.429 +- 0.179     3.163 +- 0.233
 4  2.2    1000  0.5744 +- 0.0011   0.3618 +- 0.0067    1.812 +- 0.101     3.013 +- 0.174
 4  2.4    1000  0.6347 +- 0.0005   0.2163 +- 0.0018    2.654 +- 0.244     5.707 +- 0.512
 4  2.6    1000  0.6720 +- 0.0003   0.1670 +- 0.0011    2.908 +- 0.352     7.117 +- 0.873
 6  1.0    750   0.2432 +- 0.0002   1.3151 +- 0.0366    nan +- nan     nan +- nan
 6  1.5    750   0.3622 +- 0.0002   1.0006 +- 0.0061    4.981 +- 1.180     4.980 +- 1.178
 6  2.0    750   0.5013 +- 0.0002   0.5999 +- 0.0031    2.414 +- 0.135     3.117 +- 0.174
 6  2.2    750   0.5691 +- 0.0005   0.4073 +- 0.0028    1.927 +- 0.073     3.020 +- 0.112
 6  2.4    750   0.6313 +- 0.0003   0.2448 +- 0.0016    2.174 +- 0.179     4.393 +- 0.367
 6  2.6    750   0.6707 +- 0.0002   0.1833 +- 0.0006    3.074 +- 0.411     7.180 +- 0.961
 8  1.0    500   0.2432 +- 0.0001   1.4483 +- 0.0373    nan +- nan     nan +- nan
 8  1.5    500   0.3623 +- 0.0001   0.9989 +- 0.0065    5.047 +- nan     5.050 +- nan
 8  2.0    500   0.5015 +- 0.0001   0.6010 +- 0.0024    2.662 +- 0.340     3.434 +- 0.437
 8  2.2    500   0.5693 +- 0.0003   0.4038 +- 0.0016    1.923 +- 0.080     3.025 +- 0.128
 8  2.4    500   0.6304 +- 0.0003   0.2525 +- 0.0015    2.157 +- 0.127     4.294 +- 0.246
 8  2.6    500   0.6701 +- 0.0001   0.1864 +- 0.0005    2.854 +- 0.276     6.611 +- 0.634
 10  1.0    300   0.2431 +- 0.0001   1.4010 +- 0.0369    nan +- nan     nan +- nan
 10  1.5    300   0.3624 +- 0.0001   0.9912 +- 0.0076    3.744 +- 0.685     3.760 +- 0.684
 10  2.0    300   0.5011 +- 0.0002   0.5982 +- 0.0010    2.258 +- 0.114     2.920 +- 0.147
 10  2.2    300   0.5694 +- 0.0002   0.4046 +- 0.0010    2.051 +- 0.118     3.224 +- 0.188
 10  2.4    300   0.6298 +- 0.0002   0.2558 +- 0.0005    2.200 +- 0.188     4.349 +- 0.373
 10  2.6    300   0.6700 +- 0.0001   0.1873 +- 0.0006    3.325 +- 0.531     7.682 +- 1.219

Leading strong-coupling values for SU(2) (comparison only): sigma a^2 ~ -ln(beta/4), m a ~ -4 ln(beta/4)
  beta = 1.0: -ln(beta/4) = 1.386, -4 ln(beta/4) = 5.545
  beta = 1.5: -ln(beta/4) = 0.981, -4 ln(beta/4) = 3.923
  beta = 2.0: -ln(beta/4) = 0.693, -4 ln(beta/4) = 2.773
  beta = 2.2: -ln(beta/4) = 0.598, -4 ln(beta/4) = 2.391
  beta = 2.4: -ln(beta/4) = 0.511, -4 ln(beta/4) = 2.043
  beta = 2.6: -ln(beta/4) = 0.431, -4 ln(beta/4) = 1.723
ALL PASS

Listing 380: NUMERIC_YMGAP.txt

NUMERIC_YMGAP.txt

  [PASS] 600-cell graph: every element has 12 nearest neighbours
  [PASS] projection back to the group by climbing equals the exact argmax (2000 random vectors)
2I against SU(2): plaquette on (Z/4)^4, same Wilson action (SU(2) by Kennedy-Pendleton heat bath)
  beta   2I                 SU(2)              difference (in errors, relative)
  2.2    0.5744 +- 0.0028   0.5757 +- 0.0030   0.32 sigma, 0.23%
  2.3    0.6105 +- 0.0010   0.6108 +- 0.0018   0.15 sigma, 0.05%
  2.4    0.6343 +- 0.0013   0.6340 +- 0.0009   0.22 sigma, 0.05%
  2.5    0.6563 +- 0.0006   0.6522 +- 0.0012   3.02 sigma, 0.63%
  2.6    0.6708 +- 0.0007   0.6716 +- 0.0006   0.92 sigma, 0.12%
  [PASS] 2I tracks SU(2): plaquettes differ by less than 1% at every beta

Spectroscopy data: the chains of `gap` mode (fixed seeds), read back from their saved raw measurements.
Smearing: V = U + 0.5 * (4 spatial staples), back to 2I by argmax; levels (4, 10).
0++: GEVP C(1) v = lambda C(0) v on the spatial R x R loops, R in (1, 2, 3), at each smearing level; m from the cosh effective mass
of v^T C(t) v, error-weighted over all t >= 2 with jackknife error below the value;
sigma from V(R) = A + sigma R - c/R, R = 1..min(5, L/2),
V(R,T) = ln W(R,T)/W(R,T+1) (spatial lines at smearing level 10); T taken where sigma(T) = sigma(T+1) within 1.5 errors.
Jackknife over 10 blocks.
 L   beta  meas  plaquette
 8   2.2   6400  0.5692  plateau t=[2, 3]  m a = 0.836 +- 0.322   sigma a^2 = 0.2349 +- 0.0115   c = 0.251   m/sqrt(sigma) = 1.73 +- 0.66   m L = 6.7
      m_eff(t) (jackknife error), t = 0..4: 1.844(0.035) 1.375(0.108) 0.771(0.317) 1.575(1.066)
      sigma a^2 from V(R,T), T = 2..3: T=2: 0.2509(0.0067)  T=3: 0.2349(0.0115)   -> T = 3
      V(R), R=1..5: 0.4977 0.8527 1.1414 1.3869
 8   2.3   6400  0.6023  plateau t=[2]  m a = 1.641 +- 1.602   sigma a^2 = 0.1527 +- 0.0055   c = 0.213   m/sqrt(sigma) = 4.20 +- 4.09   m L = 13.1
      m_eff(t) (jackknife error), t = 0..4: 1.549(0.047) 1.239(0.156) 1.641(1.602) 1.284(nan)
      sigma a^2 from V(R,T), T = 2..3: T=2: 0.1555(0.0024)  T=3: 0.1527(0.0055)   -> T = 3
      V(R), R=1..5: 0.4277 0.6857 0.8763 1.0446
 10  2.4   5200  0.6300  plateau t=[2, 3]  m a = 0.836 +- 0.388   sigma a^2 = 0.0718 +- 0.0044   c = 0.244   m/sqrt(sigma) = 3.12 +- 1.50   m L = 8.4
      m_eff(t) (jackknife error), t = 0..4: 1.566(0.035) 1.227(0.163) 1.231(0.545) 0.619(0.403) nan
      sigma a^2 from V(R,T), T = 2..4: T=2: 0.0926(0.0011)  T=3: 0.0836(0.0023)  T=4: 0.0718(0.0044)   -> T = 4
      V(R), R=1..5: 0.3732 0.5627 0.6803 0.7738 0.8519
 10  2.5   5200  0.6521  plateau t=[2, 3]  m a = 0.885 +- 0.119   sigma a^2 = 0.0376 +- 0.0028   c = 0.225   m/sqrt(sigma) = 4.57 +- 0.62   m L = 8.8
      m_eff(t) (jackknife error), t = 0..4: 1.594(0.042) 1.075(0.071) 0.906(0.106) 0.644(0.355) nan
      sigma a^2 from V(R,T), T = 2..4: T=2: 0.0563(0.0014)  T=3: 0.0430(0.0020)  T=4: 0.0376(0.0028)   -> T = 4
      V(R), R=1..5: 0.3346 0.4817 0.5608 0.6168 0.6626
 10  2.6   5200  0.6702  plateau t=[2, 4]  m a = 0.727 +- 0.204   sigma a^2 = 0.0187 +- 0.0012   c = 0.216   m/sqrt(sigma) = 5.32 +- 1.54   m L = 7.3
      m_eff(t) (jackknife error), t = 0..4: 1.757(0.034) 1.256(0.087) 0.712(0.202) nan 0.824(0.523)
      sigma a^2 from V(R,T), T = 2..4: T=2: 0.0398(0.0006)  T=3: 0.0256(0.0010)  T=4: 0.0187(0.0012)   -> T = 4
      V(R), R=1..5: 0.3073 0.4303 0.4901 0.5264 0.5521
  all beta: weighted mean m/sqrt(sigma) = 3.390 +- 0.414; chi^2 = 11.61 for 4 dof
  beta >= 2.4: weighted mean m/sqrt(sigma) = 4.472 +- 0.536; chi^2 = 1.14 for 2 dof
  [PASS] m/sqrt(sigma) constant within errors for beta = 2.4, 2.5, 2.6 (chi^2/dof < 2)
  (over all beta including 2.2 and 2.3: chi^2/dof = 2.90)
  [PASS] m L > 4 at every (L, beta)
ALL PASS