92 The Determinant Condition for \(l_0 = 1\)

92.1 Rings from the chain, and what is asked

A commutative ring is passed by its operations and laws, exactly as the semiring of the Hecke recursion and the group of the gauge section were (CRing). The laws are: \(+\) associative and commutative with \(0\) and negatives, \(\cdot \) associative and commutative with \(1\), and distributive. From these alone come cancellation, \(a\cdot 0=0\), uniqueness of negatives, \((-a)b=-(ab)\) and \(-(-a)=a\) (add_cancel_left, mul_zero, neg_unique, neg_mul_left, neg_neg’). A ring without zero divisors adds: \(ab=0\Rightarrow a=0\) or \(b=0\) (NoZD).

In the defect count of the Langlands part (\(l_0\), Section 78, links 69–71), the case \(l_0=1\) needs a map \(d\) between two cohomology groups that keeps its rank at a generic point, i.e. \(\det d\neq 0\). This section proves the algebra behind that statement in Lean, and computes the smallest Bianchi cases.

92.2 \(\det d\neq 0\) gives an injective map (Lean, every \(n\))

For \(n=1\): if \(a\neq 0\) and \(ax=0\) then \(x=0\) (inj1), and \(ax=ax'\) implies \(x=x'\) (inj1’). For \(n=2\), write \(d=\begin {pmatrix}a&b\\ c&e\end {pmatrix}\) and \(\det d=ae-bc\). Multiplying by the adjugate gives, as identities of the ring,

\[ e(ax+by)-b(cx+ey)=\det d\cdot x,\qquad -c(ax+by)+a(cx+ey)=\det d\cdot y \]
(adj2_left, adj2_right). So if \(d(x,y)=0\) and \(\det d\neq 0\), then \(\det d\cdot x=\det d\cdot y=0\) and hence \(x=y=0\) (inj2). The hypothesis on zero divisors cannot be dropped: over \(\mathbb Z/6\) the matrix \(\begin {pmatrix}0&1\\2&0\end {pmatrix}\) has \(\det =4\neq 0\) and kernel vector \((3,0)\) (numerical search, NUMERIC_DET.txt). For general \(n\) we build the determinant by hand (DetNChain). A matrix is a list of columns, a column is a function from rows to \(R\), and \(\det \) is the Laplace expansion along row \(0\), written as a walk over the list of columns (lapS, det). From the definition alone:

If \(Ax=0\), put the column \(Ax=\sum _kx_kc_k\) in the place of \(c_j\). The determinant vanishes, because the column is zero on the \(n\) rows. It also equals \(x_j\det A\), because every other term has a repeated column. So \(x_j\det A=0\), and \(x_j=0\) when \(\det A\neq 0\) and \(R\) has no zero divisors (kernel_trivial). This holds for every \(n\), with no axioms. The random integer checks of NUMERIC_DET.txt (\(n=3,\dots ,6\)) are consistent with it.

92.3 Koszul complexes of length 1 and 2 (Lean, general)

Length 1: \(0\to R\xrightarrow {\,x\,}R\to 0\). If \(x\) is a non-zero-divisor then \(H_1=\ker x=0\) (koszul1_exact).

Length 2: \(0\to R\xrightarrow {d_2}R^2\xrightarrow {d_1}R\to 0\) with \(d_1(a,b)=ax+by\) and \(d_2(r)=(-ry,\,rx)\). It is a complex, \(d_1d_2=0\) (koszul2_complex). Let \((x,y)\) be regular: \(x\) is a non-zero-divisor, and \(y\) is a non-zero-divisor on \(R/(x)\), i.e. \(by\in (x)\Rightarrow b\in (x)\) (Regular2). Then:

This is the length-two case of the classical statement that the Koszul complex of a regular sequence is a resolution [1757]. Over \(\mathbb Z\), for the \(91\) coprime pairs \(1\le x,y\le 12\), every cycle in \([-20,20]^2\) was checked to be a boundary.

92.4 Bianchi groups: computation (Python)

The cases \(l_0=1\) of smallest size are \(GL_2\) over imaginary quadratic fields [985]. We compute with the Bianchi groups \(PSL_2(\mathcal O_d)\), \(d=1\) (discriminant \(-4\)) and \(d=3\) (discriminant \(-3\)), and their subgroups \(\Gamma _0(\pi )\) for prime elements \(\pi \). This is computation, so a presentation of the group is used as input.

Input. For \(d=1\) we use the standard presentation

\[ PSL_2(\mathbb Z[i])=\langle a,l,t,u\mid a^2=l^2=(al)^2=(tl)^2=(ul)^2=(at)^3=(ual)^3=[t,u]=1\rangle \]
of Fine [1758], going back to Swan [1759], with \(a=\begin {pmatrix}0&-1\\1&0\end {pmatrix}\), \(t=\begin {pmatrix}1&1\\0&1\end {pmatrix}\), \(u=\begin {pmatrix}1&i\\0&1\end {pmatrix}\), \(l=\begin {pmatrix}-i&0\\0&i\end {pmatrix}\). Every relator was checked to be \(\pm 1\) on the matrices. The abelianisation it gives, \(\mathbb Z/2\oplus \mathbb Z/2\), is the known one. For \(d=3\) we use every reduced word of length \(\le 6\) in \(a,t,u,l\) (with \(u=\begin {pmatrix}1&\omega \\0&1\end {pmatrix}\), \(l=\operatorname {diag}(\omega ,\omega ^2)\)) that is \(\pm 1\) on the matrices: \(228\) relators up to cyclic order and inversion. It gives the known abelianisation \(\mathbb Z/3\). Adding all relators of length \(7\) (\(814\)) changes none of the groups \(H_1(\Gamma _0(\pi ))\) for \(N(\pi )\le 43\). The Hecke check below at level \((11)\) also comes out as predicted.

Method. The cosets of \(\Gamma _0(\pi )\) are the points of \(\mathbb P^1(\mathcal O/\pi )\). Reidemeister–Schreier gives a presentation of \(\Gamma _0(\pi )\), and the Smith normal form of its relation matrix gives \(H_1(\Gamma _0(\pi ),\mathbb Z)=\mathbb Z^{b_1}\oplus T\). Then:

Hecke operators \(T_\ell \) act on \(H^1=\operatorname {Hom}(\Gamma _0(\pi ),\mathbb Q)\) through the coset decomposition of \(\Gamma _0\operatorname {diag}(1,\ell )\Gamma _0\). Each matrix is written as a word by the Euclidean algorithm of \(\mathcal O_d\), and the word is rewritten by Reidemeister–Schreier. Ranks and Hecke matrices are computed modulo two large primes, and the lifted integers are accepted only when both primes agree. The torsion is exact, by Smith normal form, for \(N(\pi )\le 113\) (\(d=1\)) and \(N(\pi )\le 50\) (\(d=3\)).

Results (NUMERIC_BIANCHI.txt).

Pairing and \(\det \neq 0\).

92.5 Status

Statement

Status

Where

ring lemmas from the laws

Lean, general

add_cancel_left, …

\(1\times 1\): \(a\neq 0\) \(\Rightarrow \) injective

Lean, general

inj1, inj1’

\(2\times 2\): \(\det d\neq 0\) \(\Rightarrow \) kernel \(0\)

Lean, general

inj2

no-zero-divisor hypothesis needed

counterexample (search)

NUMERIC_DET 2

\(n\times n\), every \(n\): \(\det A\neq 0\), \(Ax=0\Rightarrow x=0\)

Lean, general

kernel_trivial

Koszul length 1: \(H_1=0\)

Lean, general

koszul1_exact

Koszul length 2: complex, \(H_2=0\), \(H_1=0\)

Lean, general

koszul2_*

triangular and block-triangular \(\det \), every \(n\)

Lean, general

det_tri, det_block

Koszul length \(n\): \(H_1=0\) for a regular sequence

Lean, general

koszulH1

Koszul length \(n\): \(H_{k}=0\) for all \(k\ge 1\)

Lean, general

KoszulAll.exact

column operations keep \(\det \), every \(n\)

Lean, general

colop_left, colop_right

\(\det d\neq 0\) on a maximal minor, \(N(\pi )=13\), \(d=1\)

Lean (matrix computed)

Bianchi13.det_ne

\(\det d\neq 0\) on a maximal minor, \(N(\pi )=17\), \(d=1\)

Lean (matrix computed)

Bianchi17.det_ne

\(\det d\neq 0\) on a maximal minor, \(N(\pi )=29\), \(d=1\)

Lean (matrix computed)

Bianchi29.det_ne

\(\det d\neq 0\) on a maximal minor, \(N(\pi )=41\), \(d=1\)

Lean (matrix computed)

Bianchi41.det_ne

\(\det d\neq 0\) on a maximal minor, \(N(\pi )=7,13\), \(d=3\)

Lean (matrix computed)

BianchiW7, BianchiW13

\(\det d\neq 0\) on a maximal minor, \(N(\pi )=9,37,49,53,61\), \(d=1\)

Lean (matrix computed)

Bianchi9, …, Bianchi61

\(\det d\neq 0\) on a maximal minor, \(N(\pi )=19,\dots ,109\) prime, \(\neq 73\), \(d=3\)

Lean (matrix computed)

BianchiW19, …, BianchiW109

rank of the true relators \(=\#\)columns\(-1\) at \(N(\pi )=73\), \(d=3\)

Lean (matrix computed)

BianchiW73.ker

rank \(=\#\)columns\(-1\) at \(N(\pi )=73\), \(d=3\), Swan’s complete presentation

Lean (matrix computed)

BianchiW73s.ker

Hecke eigen-equations \(T_\ell V=a_\ell V\) at \(\pi =11\) (\(d=1\)) and \(N(\pi )=73\) (\(d=3\))

Lean (Hecke matrices computed)

Bianchi121H, BianchiW73sH

Hecke eigen-equations on the cuspidal class, \(d=2\) (\(N=41,49\)), \(d=7\) (\(N=79\)), \(d=11\) (\(N=47\))

Lean (Hecke matrices computed)

BianchiS41H, …, BianchiD11N47H

\(\det d\neq 0\) on a maximal minor, \(N(\pi )=73,89,97,101,109,113\), \(d=1\)

Lean (matrix computed)

Bianchi73, …, Bianchi113

rank \(=\#\)columns\(-1\) at \(\pi =11\), \(d=1\) (minor det \(6144\), kernel vector)

Lean (matrix computed)

Bianchi121.ker

rank \(=\#\)columns\(-k\), \(d=2\): \(k=2\) at \(N(\pi )=3,11\), \(k=3\) at \(N(\pi )=41,49\)

Lean (matrix computed)

BianchiS3, …, BianchiS49

rank \(=\#\)columns\(-k\), \(d=7,11\): \(k=3\) at \(N(\pi )=79\) (\(d=7\)), \(47\) (\(d=11\)), else \(k=2\)

Lean (matrix computed)

BianchiD7N79, BianchiD11N47

rank \(=\#\)columns\(-2\) at every other prime \(\pi \): \(d=2\), \(N\le 113\); \(d=7,11\), \(N\le 71\)

Lean (matrix computed)

BianchiS17, …, BianchiD11N67

Bianchi \(d=1\): \(H^1\), tors \(H^2\), \(T_\ell \), base change of \(11a\)

computed (standard presentation)

NUMERIC_BIANCHI

Bianchi \(d=3\): same

computed; Swan’s complete presentation used for \(N(\pi )=73\)

NUMERIC_BIANCHI

rank \(H^2\)

from duality

—

\(\det d\neq 0\) off the cuspidal directions, \(|\det d|=|\mathrm {tors}\,H^2|\)

computed

NUMERIC_BIANCHI

Hecke on \(H^2\), \(H^1\)–\(H^2\) pairing determinant

remaining (Hecke on \(H^1\) cusp classes: see above)

—

92.6 Triangular and block determinants

Laplace expansion along row 0 gives the triangular and block-triangular formulas at every size.

\[ \det (A\,|\,B)=\det A\cdot \det B'\quad (B=0\text { in the first }|A|\text { rows}). \]

lang/DetTri.lean

/-
  lang/DetTri — T52 (tool for T21), cycle 801: **the determinant of a triangular matrix, every size n**.
  DetNChain.det is the Laplace expansion along row 0 of a list of columns. Here:
    Z0 cs          every column of cs vanishes in row 0
    lapS_z0        a Laplace walk over columns vanishing in row 0 is 0
    det_first      Z0 cs ⇒ det (n+1) (c :: cs) = c(0) · det n (cs with row 0 dropped)        (block step)
    Tri n, dg n    lower triangular of size n (Z0 of the later columns, then the same for the minor) and the diagonal product
    det_tri        Tri n cs, |cs| = n ⇒ det n cs = Π diagonal                                (induction on n)
  Lean 4 core only, proofs by hand, no axioms.
-/
import DetNChain

namespace DetTri

open DetChain DetN

variable {R : Type} (K : CRing R)

/-- every column vanishes in row 0. -/
def Z0 : List (Nat → R) → Prop
  | [] => True
  | d :: ds => d 0 = K.zero ∧ Z0 ds

/-- lower triangular of size n (fuel n). -/
def Tri : Nat → List (Nat → R) → Prop
  | 0, _ => True
  | _ + 1, [] => True
  | n + 1, _ :: cs => Z0 K cs ∧ Tri n (cs.map shc)

/-- the diagonal product (fuel n). -/
def dg : Nat → List (Nat → R) → R
  | 0, _ => K.one
  | _ + 1, [] => K.one
  | n + 1, c :: cs => K.mul (c 0) (dg n (cs.map shc))

theorem lapS_z0 (D : List (Nat → R) → R) : ∀ (xs pre suf : List (Nat → R)), Z0 K xs → lapS K D pre xs suf = K.zero
  | [], _, _, _ => rfl
  | x :: xs, pre, suf, ⟨h0, h⟩ => by
    show K.add (sgn K pre.length (K.mul (x 0) (D ((pre ++ (xs ++ suf)).map shc)))) (lapS K D (pre ++ [x]) xs suf) = K.zero
    rw [h0, zero_mul' K, sgn_zero, lapS_z0 D xs (pre ++ [x]) suf h, K.zero_add]

/-- **Block step**: a first row (c(0), 0, …, 0) splits off. -/
theorem det_first (n : Nat) (c : Nat → R) (cs : List (Nat → R)) (h : Z0 K cs) :
    det K (n + 1) (c :: cs) = K.mul (c 0) (det K n (cs.map shc)) := by
  show K.add (K.mul (c 0) (det K n ((cs ++ []).map shc))) (lapS K (det K n) [c] cs []) = _
  rw [lapS_z0 K (det K n) cs [c] [] h, app_nil', add_zero' K]

/-- **Triangular determinant**: det = product of the diagonal, every size. -/
theorem det_tri : ∀ (n : Nat) (cs : List (Nat → R)), cs.length = n → Tri K n cs → det K n cs = dg K n cs
  | 0, _, _, _ => rfl
  | n + 1, [], hl, _ => Nat.noConfusion hl
  | n + 1, c :: cs, hl, ⟨h0, ht⟩ => by
    have hl' : (cs.map shc).length = n := (len_map' shc cs).trans (Nat.succ.inj hl)
    show det K (n + 1) (c :: cs) = K.mul (c 0) (dg K n (cs.map shc))
    rw [det_first K n c cs h0, det_tri n (cs.map shc) hl' ht]

end DetTri

#print axioms DetTri.lapS_z0
#print axioms DetTri.det_first
#print axioms DetTri.det_tri

lang/DetBlock.lean

/-
  lang/DetBlock — T52 (tool for T21), cycle 802: **block-triangular determinants, every size**.
  Columns A (k of them) followed by columns B (m of them) that vanish in the first k rows:
      det (m + k) (A ++ B) = det k A · det m (B with its first k rows dropped).
    lapS_mul     a Laplace walk whose minors factor as D(zs ++ B) = D'(zs) · X factors as (walk of D') · X
    ZR k B       every column of B vanishes in rows 0 … k − 1;   shN k B   B with rows 0 … k − 1 dropped
    det_block    the block formula (induction on k; DetNChain.lapS_split, DetTri.lapS_z0)
  This is the inductive step behind Koszul/Bianchi determinants of general size (T21).
  Lean 4 core only, proofs by hand (lib_ring), no axioms.
-/
import lang.DetTri
import lib.RingTac

namespace DetBlock

open DetChain DetN DetTri

variable {R : Type} (K : CRing R)

def ZR : Nat → List (Nat → R) → Prop
  | 0, _ => True
  | k + 1, B => Z0 K B ∧ ZR k (B.map shc)

def shN : Nat → List (Nat → R) → List (Nat → R)
  | 0, B => B
  | k + 1, B => shN k (B.map shc)

theorem sgn_fac (j : Nat) (a d X : R) : sgn K j (K.mul a (K.mul d X)) = K.mul (sgn K j (K.mul a d)) X := by
  have e : K.mul a (K.mul d X) = K.mul X (K.mul a d) := by lib_ring
  rw [e, sgn_mul]
  lib_ring

theorem lapS_mul (D D' : List (Nat → R) → R) (X : R) (B : List (Nat → R)) (k : Nat)
    (H : ∀ zs : List (Nat → R), zs.length = k → D ((zs ++ B).map shc) = K.mul (D' (zs.map shc)) X) :
    ∀ (xs pre : List (Nat → R)), (pre ++ xs).length = k + 1 → lapS K D pre xs B = K.mul (lapS K D' pre xs []) X
  | [], _, _ => by
    show K.zero = K.mul K.zero X
    rw [zero_mul' K]
  | x :: xs, pre, hl => by
    have h2 : (pre ++ x :: xs).length = pre.length + (xs.length + 1) := len_app' pre (x :: xs)
    have h3 : (pre ++ xs).length + 1 = k + 1 := by
      rw [len_app']
      exact h2.symm.trans hl
    have hk : (pre ++ xs).length = k := Nat.succ.inj h3
    have hl' : ((pre ++ [x]) ++ xs).length = k + 1 := by
      rw [app_assoc' pre [x] xs]
      exact hl
    show K.add (sgn K pre.length (K.mul (x 0) (D ((pre ++ (xs ++ B)).map shc)))) (lapS K D (pre ++ [x]) xs B)
      = K.mul (K.add (sgn K pre.length (K.mul (x 0) (D' ((pre ++ (xs ++ [])).map shc)))) (lapS K D' (pre ++ [x]) xs [])) X
    rw [← app_assoc' pre xs B, H (pre ++ xs) hk, lapS_mul D D' X B k H xs (pre ++ [x]) hl', app_nil', sgn_fac]
    lib_ring

/-- **Block-triangular determinant.** -/
theorem det_block (m : Nat) : ∀ (k : Nat) (A B : List (Nat → R)), A.length = k → B.length = m → ZR K k B →
    det K (m + k) (A ++ B) = K.mul (det K k A) (det K m (shN k B))
  | 0, [], B, _, _, _ => (K.one_mul _).symm
  | 0, _ :: _, _, hA, _, _ => Nat.noConfusion hA
  | k + 1, A, B, hA, hB, ⟨h0, hz⟩ => by
    have H : ∀ zs : List (Nat → R), zs.length = k →
        det K (m + k) ((zs ++ B).map shc) = K.mul (det K k (zs.map shc)) (det K m (shN k (B.map shc))) := fun zs hz' => by
      rw [map_app']
      exact det_block m k (zs.map shc) (B.map shc) ((len_map' shc zs).trans hz') ((len_map' shc B).trans hB) hz
    show lapS K (det K (m + k)) [] (A ++ B) [] = K.mul (lapS K (det K k) [] A []) (det K m (shN k (B.map shc)))
    rw [lapS_split K (det K (m + k)) [] A B [], app_nil', lapS_z0 K (det K (m + k)) B ([] ++ A) [] h0, add_zero' K]
    exact lapS_mul K (det K (m + k)) (det K k) _ B k H A [] hA

end DetBlock

#print axioms DetBlock.sgn_fac
#print axioms DetBlock.lapS_mul
#print axioms DetBlock.det_block

#print axioms: 6 theorems, no axioms.

92.7 Koszul \(H_1\) in every length

For a regular sequence every Koszul 1-cycle is a boundary.

\[ \textstyle \sum _i a_ix_i=0\ \Rightarrow \ a_i=\sum _j b_{ij}x_j,\ b\text { alternating}. \]

lang/KoszulN.lean

/-
  lang/KoszulN — T52 (tool for T21), cycle 803: **the first Koszul homology of a regular sequence vanishes, every length n**.
  For x₀, …, x_(n−1) in a commutative ring with x_k regular modulo (x₀, …, x_(k−1)) for every k < n (Reg x n):
      Σ_(i<n) a_i x_i = 0   ⇒   a_i = Σ_(j<n) b_ij x_j   with b alternating (b_ii = 0, b_ij = −b_ji),
  i.e. every 1-cycle of the Koszul complex is a boundary d₂(Σ b_ij e_i ∧ e_j)  (H₁(x; R) = 0).
  This is the length-n form of DetChain.koszul1_exact / koszul2_H1.
    sm, AB, InI, Reg        finite sums, "for all j < n", ideal membership, regular sequence (recursive, no order lemmas)
    sm_ext, sm_add, sm_mul  sum lemmas;  ab_lt, lt_ne  j < n ⇒ j ≠ n
    koszulH1                the theorem (induction on n: a_n ∈ (x₀…x_(n−1)) by regularity, shift a, extend b by ±c)
  Lean 4 core only, proofs by hand (lib_ring, lib_nat), no axioms.
-/
import DetChain
import FiniteRecChain
import lib.RingTac
import lib.Semi

namespace KoszulN

open DetChain FiniteRecChain

variable {R : Type} (K : CRing R)

def sm (f : Nat → R) : Nat → R
  | 0 => K.zero
  | n + 1 => K.add (sm f n) (f n)

/-- P j for every j < n. -/
def AB (P : Nat → Prop) : Nat → Prop
  | 0 => True
  | n + 1 => AB P n ∧ P n

def InI (x : Nat → R) (n : Nat) (r : R) : Prop := ∃ c : Nat → R, r = sm K (fun j => K.mul (c j) (x j)) n

/-- x₀, …, x_(n−1) is a regular sequence. -/
def Reg (x : Nat → R) : Nat → Prop
  | 0 => True
  | n + 1 => Reg x n ∧ ∀ r, InI K x n (K.mul r (x n)) → InI K x n r

theorem sm_ext (f g : Nat → R) : ∀ n, AB (fun j => f j = g j) n → sm K f n = sm K g n
  | 0, _ => rfl
  | n + 1, ⟨h, e⟩ => by
    show K.add (sm K f n) (f n) = K.add (sm K g n) (g n)
    rw [sm_ext f g n h, e]

theorem sm_all (f g : Nat → R) (h : ∀ j, f j = g j) : ∀ n, sm K f n = sm K g n
  | 0 => rfl
  | n + 1 => by
    show K.add (sm K f n) (f n) = K.add (sm K g n) (g n)
    rw [sm_all f g h n, h n]

theorem sm_add (f g : Nat → R) : ∀ n, sm K (fun j => K.add (f j) (g j)) n = K.add (sm K f n) (sm K g n)
  | 0 => by show K.zero = K.add K.zero K.zero; lib_ring
  | n + 1 => by
    show K.add (sm K (fun j => K.add (f j) (g j)) n) (K.add (f n) (g n)) = K.add (K.add (sm K f n) (f n)) (K.add (sm K g n) (g n))
    rw [sm_add f g n]
    lib_ring

theorem sm_mul (c : R) (f : Nat → R) : ∀ n, sm K (fun j => K.mul c (f j)) n = K.mul c (sm K f n)
  | 0 => by show K.zero = K.mul c K.zero; lib_ring
  | n + 1 => by
    show K.add (sm K (fun j => K.mul c (f j)) n) (K.mul c (f n)) = K.mul c (K.add (sm K f n) (f n))
    rw [sm_mul c f n]
    lib_ring

theorem ab_mono (P Q : Nat → Prop) (h : ∀ j, P j → Q j) : ∀ n, AB P n → AB Q n
  | 0, _ => trivial
  | n + 1, ⟨hp, e⟩ => ⟨ab_mono P Q h n hp, h n e⟩

theorem ab_two (P Q S : Nat → Prop) (h : ∀ j, P j → Q j → S j) : ∀ n, AB P n → AB Q n → AB S n
  | 0, _, _ => trivial
  | n + 1, ⟨hp, e⟩, ⟨hq, e'⟩ => ⟨ab_two P Q S h n hp hq, h n e e'⟩

theorem ab_lt : ∀ n, AB (fun j => ∃ d, j + d + 1 = n) n
  | 0 => trivial
  | n + 1 => ⟨ab_mono _ _ (fun j ⟨d, hd⟩ => ⟨d + 1, by rw [← hd]; lib_nat⟩) n (ab_lt n), ⟨0, rfl⟩⟩

theorem self_lt : ∀ n d, n + d + 1 = n → False
  | 0, d, h => Nat.noConfusion h
  | n + 1, d, h => self_lt n d (Nat.succ.inj (show n + d + 1 + 1 = n + 1 by rw [← h]; lib_nat))

theorem ab_ne (n : Nat) : AB (fun j => j = n → False) n :=
  ab_mono _ _ (fun j ⟨d, hd⟩ e => self_lt n d (by rw [e] at hd; exact hd)) n (ab_lt n)

/-- the alternating matrix b extended by the column −c and the row c at index n. -/
def ext (b : Nat → Nat → R) (c : Nat → R) (n i j : Nat) : R :=
  if i = n then (if j = n then K.zero else c j) else (if j = n then K.neg (c i) else b i j)

theorem ext_nn (b : Nat → Nat → R) (c : Nat → R) (n : Nat) : ext K b c n n n = K.zero := by
  unfold ext; rw [ite_pos' _ _ (rfl : n = n), ite_pos' _ _ (rfl : n = n)]

theorem ext_nj (b : Nat → Nat → R) (c : Nat → R) (n j : Nat) (hj : j = n → False) : ext K b c n n j = c j := by
  unfold ext; rw [ite_pos' _ _ (rfl : n = n), ite_neg' _ _ hj]

theorem ext_in (b : Nat → Nat → R) (c : Nat → R) (n i : Nat) (hi : i = n → False) : ext K b c n i n = K.neg (c i) := by
  unfold ext; rw [ite_neg' _ _ hi, ite_pos' _ _ (rfl : n = n)]

theorem ext_ij (b : Nat → Nat → R) (c : Nat → R) (n i j : Nat) (hi : i = n → False) (hj : j = n → False) :
    ext K b c n i j = b i j := by
  unfold ext; rw [ite_neg' _ _ hi, ite_neg' _ _ hj]

/-- **H₁ of the Koszul complex of a regular sequence vanishes**, every length n. -/
theorem koszulH1 (x : Nat → R) : ∀ n, Reg K x n → ∀ a : Nat → R, sm K (fun i => K.mul (a i) (x i)) n = K.zero →
    ∃ b : Nat → Nat → R, (∀ i, b i i = K.zero) ∧ (∀ i j, b i j = K.neg (b j i)) ∧
      AB (fun i => a i = sm K (fun j => K.mul (b i j) (x j)) n) n
  | 0, _, _, _ => ⟨fun _ _ => K.zero, fun _ => rfl, fun _ _ => by show K.zero = K.neg K.zero; lib_ring, trivial⟩
  | n + 1, ⟨hreg, hx⟩, a, ha => by
    have ha' : K.add (sm K (fun i => K.mul (a i) (x i)) n) (K.mul (a n) (x n)) = K.zero := ha
    have hneg : sm K (fun j => K.mul (K.neg (a j)) (x j)) n = K.neg (sm K (fun i => K.mul (a i) (x i)) n) := by
      rw [sm_all K (fun j => K.mul (K.neg (a j)) (x j)) (fun j => K.mul (K.neg K.one) (K.mul (a j) (x j)))
        (fun j => by show K.mul (K.neg (a j)) (x j) = K.mul (K.neg K.one) (K.mul (a j) (x j)); lib_ring) n,
        sm_mul K]
      lib_ring
    have hin : InI K x n (K.mul (a n) (x n)) := ⟨fun j => K.neg (a j), by
      rw [hneg]
      calc K.mul (a n) (x n) = K.add (K.add (sm K (fun i => K.mul (a i) (x i)) n) (K.mul (a n) (x n)))
            (K.neg (sm K (fun i => K.mul (a i) (x i)) n)) := by lib_ring
        _ = _ := by rw [ha']; lib_ring⟩
    match hx (a n) hin with
    | ⟨c, hc⟩ =>
      have ha2 : sm K (fun i => K.mul (K.add (a i) (K.mul (c i) (x n))) (x i)) n = K.zero := by
        rw [sm_all K (fun i => K.mul (K.add (a i) (K.mul (c i) (x n))) (x i)) (fun i => K.add (K.mul (a i) (x i)) (K.mul (x n) (K.mul (c i) (x i))))
          (fun i => by show K.mul (K.add (a i) (K.mul (c i) (x n))) (x i) = K.add (K.mul (a i) (x i)) (K.mul (x n) (K.mul (c i) (x i))); lib_ring) n,
          sm_add K, sm_mul K, ← hc]
        calc _ = K.add (sm K (fun i => K.mul (a i) (x i)) n) (K.mul (a n) (x n)) := by lib_ring
          _ = K.zero := ha'
      match koszulH1 x n hreg (fun i => K.add (a i) (K.mul (c i) (x n))) ha2 with
      | ⟨b, hd, hanti, hrow⟩ =>
        refine ⟨ext K b c n, fun i => ?_, fun i j => ?_, ?_⟩
        · by_cases hi : i = n
          · rw [hi]; exact ext_nn K b c n
          · rw [ext_ij K b c n i i hi hi, hd i]
        · by_cases hi : i = n
          · by_cases hj : j = n
            · rw [hi, hj, ext_nn K b c n]; lib_ring
            · rw [hi, ext_nj K b c n j hj, ext_in K b c n j hj, neg_neg' K]
          · by_cases hj : j = n
            · rw [hj, ext_in K b c n i hi, ext_nj K b c n i hi]
            · rw [ext_ij K b c n i j hi hj, ext_ij K b c n j i hj hi]; exact hanti i j
        · refine ⟨?_, ?_⟩
          · refine ab_two _ _ _ (fun i hr hi => ?_) n hrow (ab_ne n)
            show a i = K.add (sm K (fun j => K.mul (ext K b c n i j) (x j)) n) (K.mul (ext K b c n i n) (x n))
            have e : sm K (fun j => K.mul (ext K b c n i j) (x j)) n = sm K (fun j => K.mul (b i j) (x j)) n :=
              sm_ext K _ _ n (ab_mono _ _ (fun j hj => by
                show K.mul (ext K b c n i j) (x j) = K.mul (b i j) (x j)
                rw [ext_ij K b c n i j hi hj]) n (ab_ne n))
            rw [e, ext_in K b c n i hi, ← hr]
            lib_ring
          · show a n = K.add (sm K (fun j => K.mul (ext K b c n n j) (x j)) n) (K.mul (ext K b c n n n) (x n))
            have e : sm K (fun j => K.mul (ext K b c n n j) (x j)) n = sm K (fun j => K.mul (c j) (x j)) n :=
              sm_ext K _ _ n (ab_mono _ _ (fun j hj => by
                show K.mul (ext K b c n n j) (x j) = K.mul (c j) (x j)
                rw [ext_nj K b c n j hj]) n (ab_ne n))
            rw [e, ext_nn K b c n, ← hc]
            lib_ring

end KoszulN

#print axioms KoszulN.sm_ext
#print axioms KoszulN.sm_all
#print axioms KoszulN.sm_add
#print axioms KoszulN.sm_mul
#print axioms KoszulN.ab_mono
#print axioms KoszulN.ab_two
#print axioms KoszulN.ab_lt
#print axioms KoszulN.self_lt
#print axioms KoszulN.ab_ne
#print axioms KoszulN.ext_nn
#print axioms KoszulN.ext_nj
#print axioms KoszulN.ext_in
#print axioms KoszulN.ext_ij
#print axioms KoszulN.koszulH1

#print axioms: 14 theorems, no axioms.

92.8 Koszul exactness in every degree

The Koszul complex of a regular sequence, built as an iterated mapping cone, is exact in every positive degree.

\[ H_k(x_0,\dots ,x_{n-1};R)=0\quad (k\ge 1,\ n\ge 0). \]

lang/KoszulAll.lean

/-
  lang/KoszulAll — T52 (tool for T21), cycle 804: **the Koszul complex of a regular sequence is exact in every positive degree,
  every length n**.
  The Koszul complex K(x₀, …, x_(n−1)) is built recursively as a mapping cone: K(x₀…x_n) = cone(x_n : K(x₀…x_(n−1)) → K(x₀…x_(n−1))),
    KC 0 n = R,   KC (k+1) 0 = 0,   KC (k+1) (n+1) = KC (k+1) n × KC k n,
    d (u, v) = (d u + (−1)^(k+1) x_n v, d v)      (degree 0 of the new factor: d (u, v) = d u + x_n v).
    KZ, KA, KS        zero, addition, scalar multiplication (componentwise, by recursion)
    ks_add, ka4, ks_comm, cancel     the module laws used
    d_add, d_smul     d is linear
    surj, img         d : KC 1 n → R has image exactly the ideal (x₀, …, x_(n−1))
    exact             Reg x n (KoszulN) ⇒ every cycle of degree k + 1 ≥ 1 is a boundary: H_(k+1)(x; R) = 0 for all k, n
  Proof of exact: induction on n; for z = (u, v) with d z = 0, v is a cycle (or, in degree 1, x_n v ∈ (x₀…x_(n−1)) so v is in the
  ideal by regularity), so v = d w'; then u − (±x_n) w' is a cycle of K(x₀…x_(n−1)), = d t, and z = d (t, w').
  Lean 4 core only, proofs by hand (lib_ring), no axioms.
-/
import lang.KoszulN

namespace KoszulAll

open DetChain FiniteRecChain KoszulN

/-- degree k + 1 over n generators: KCn prev 0 = 0, KCn prev (n+1) = KCn prev n × prev n. -/
@[reducible] def KCn (prev : Nat → Type) : Nat → Type
  | 0 => Unit
  | n + 1 => KCn prev n × prev n

@[reducible] def KC (R : Type) : Nat → Nat → Type
  | 0 => fun _ => R
  | k + 1 => KCn (KC R k)

variable {R : Type} (K : CRing R) (x : Nat → R)

noncomputable def KZ : (k : Nat) → (n : Nat) → KC R k n
  | 0 => fun _ => K.zero
  | k + 1 => fun n => Nat.rec (motive := fun n => KC R (k + 1) n) () (fun n acc => (acc, KZ k n)) n

noncomputable def KA : (k : Nat) → (n : Nat) → KC R k n → KC R k n → KC R k n
  | 0 => fun _ a b => K.add a b
  | k + 1 => fun n => Nat.rec (motive := fun n => KC R (k + 1) n → KC R (k + 1) n → KC R (k + 1) n)
      (fun _ _ => ()) (fun n acc a b => (acc a.1 b.1, KA k n a.2 b.2)) n

noncomputable def KS (c : R) : (k : Nat) → (n : Nat) → KC R k n → KC R k n
  | 0 => fun _ a => K.mul c a
  | k + 1 => fun n => Nat.rec (motive := fun n => KC R (k + 1) n → KC R (k + 1) n)
      (fun _ => ()) (fun n acc a => (acc a.1, KS c k n a.2)) n

def sg : Nat → R
  | 0 => K.one
  | k + 1 => K.neg (sg k)

noncomputable def d : (k : Nat) → (n : Nat) → KC R (k + 1) n → KC R k n
  | 0 => fun n => Nat.rec (motive := fun n => KC R 1 n → KC R 0 n)
      (fun _ => K.zero) (fun n acc z => K.add (acc z.1) (K.mul (x n) z.2)) n
  | k + 1 => fun n => Nat.rec (motive := fun n => KC R (k + 2) n → KC R (k + 1) n)
      (fun _ => ()) (fun n acc z => (KA K (k + 1) n (acc z.1) (KS K (K.mul (sg K (k + 1)) (x n)) (k + 1) n z.2), d k n z.2)) n

theorem pext {α β : Type} : ∀ {p q : α × β}, p.1 = q.1 → p.2 = q.2 → p = q
  | (_, _), (_, _), h1, h2 => by cases h1; cases h2; rfl

theorem ks_add (c : R) : ∀ k n (a b : KC R k n), KS K c k n (KA K k n a b) = KA K k n (KS K c k n a) (KS K c k n b)
  | 0, _, a, b => by show K.mul c (K.add a b) = K.add (K.mul c a) (K.mul c b); lib_ring
  | _ + 1, 0, _, _ => rfl
  | k + 1, n + 1, a, b => pext (ks_add c (k + 1) n a.1 b.1) (ks_add c k n a.2 b.2)

theorem ka4 : ∀ k n (p q r t : KC R k n), KA K k n (KA K k n p q) (KA K k n r t) = KA K k n (KA K k n p r) (KA K k n q t)
  | 0, _, p, q, r, t => by show K.add (K.add p q) (K.add r t) = K.add (K.add p r) (K.add q t); lib_ring
  | _ + 1, 0, _, _, _, _ => rfl
  | k + 1, n + 1, p, q, r, t => pext (ka4 (k + 1) n p.1 q.1 r.1 t.1) (ka4 k n p.2 q.2 r.2 t.2)

theorem ks_comm (c e : R) : ∀ k n (a : KC R k n), KS K c k n (KS K e k n a) = KS K e k n (KS K c k n a)
  | 0, _, a => by show K.mul c (K.mul e a) = K.mul e (K.mul c a); lib_ring
  | _ + 1, 0, _ => rfl
  | k + 1, n + 1, a => pext (ks_comm c e (k + 1) n a.1) (ks_comm c e k n a.2)

theorem cancel (c : R) : ∀ k n (u w : KC R k n), KA K k n (KA K k n u (KS K c k n w)) (KS K (K.neg c) k n w) = u
  | 0, _, u, w => by show K.add (K.add u (K.mul c w)) (K.mul (K.neg c) w) = u; lib_ring
  | _ + 1, 0, _, _ => rfl
  | k + 1, n + 1, u, w => pext (cancel c (k + 1) n u.1 w.1) (cancel c k n u.2 w.2)

theorem d_add : ∀ k n (a b : KC R (k + 1) n), d K x k n (KA K (k + 1) n a b) = KA K k n (d K x k n a) (d K x k n b)
  | 0, 0, _, _ => by show K.zero = K.add K.zero K.zero; lib_ring
  | _ + 1, 0, _, _ => rfl
  | 0, n + 1, a, b => by
    show K.add (d K x 0 n (KA K 1 n a.1 b.1)) (K.mul (x n) (K.add a.2 b.2))
      = K.add (K.add (d K x 0 n a.1) (K.mul (x n) a.2)) (K.add (d K x 0 n b.1) (K.mul (x n) b.2))
    rw [d_add 0 n a.1 b.1]
    show K.add (K.add (d K x 0 n a.1) (d K x 0 n b.1)) (K.mul (x n) (K.add a.2 b.2)) = _
    lib_ring
  | k + 1, n + 1, a, b => pext (by
      show KA K (k + 1) n (d K x (k + 1) n (KA K (k + 2) n a.1 b.1)) (KS K (K.mul (sg K (k + 1)) (x n)) (k + 1) n (KA K (k + 1) n a.2 b.2))
        = KA K (k + 1) n (KA K (k + 1) n (d K x (k + 1) n a.1) (KS K (K.mul (sg K (k + 1)) (x n)) (k + 1) n a.2))
            (KA K (k + 1) n (d K x (k + 1) n b.1) (KS K (K.mul (sg K (k + 1)) (x n)) (k + 1) n b.2))
      rw [d_add (k + 1) n a.1 b.1, ks_add, ka4]) (d_add k n a.2 b.2)

theorem d_smul (c : R) : ∀ k n (a : KC R (k + 1) n), d K x k n (KS K c (k + 1) n a) = KS K c k n (d K x k n a)
  | 0, 0, _ => by show K.zero = K.mul c K.zero; lib_ring
  | _ + 1, 0, _ => rfl
  | 0, n + 1, a => by
    show K.add (d K x 0 n (KS K c 1 n a.1)) (K.mul (x n) (K.mul c a.2)) = K.mul c (K.add (d K x 0 n a.1) (K.mul (x n) a.2))
    rw [d_smul c 0 n a.1]
    show K.add (K.mul c (d K x 0 n a.1)) (K.mul (x n) (K.mul c a.2)) = _
    lib_ring
  | k + 1, n + 1, a => pext (by
      show KA K (k + 1) n (d K x (k + 1) n (KS K c (k + 2) n a.1)) (KS K (K.mul (sg K (k + 1)) (x n)) (k + 1) n (KS K c (k + 1) n a.2))
        = KS K c (k + 1) n (KA K (k + 1) n (d K x (k + 1) n a.1) (KS K (K.mul (sg K (k + 1)) (x n)) (k + 1) n a.2))
      rw [d_smul c (k + 1) n a.1, ks_add, ks_comm]) (d_smul c k n a.2)

/-- every element of the ideal (x₀, …, x_(n−1)) is a d-image of degree 1. -/
theorem surj (c : Nat → R) : ∀ n, ∃ w : KC R 1 n, d K x 0 n w = sm K (fun j => K.mul (c j) (x j)) n
  | 0 => ⟨(), rfl⟩
  | n + 1 => by
    match surj c n with
    | ⟨w, hw⟩ =>
      refine ⟨(w, c n), ?_⟩
      show K.add (d K x 0 n w) (K.mul (x n) (c n)) = K.add (sm K (fun j => K.mul (c j) (x j)) n) (K.mul (c n) (x n))
      rw [hw]
      lib_ring

/-- every d-image of degree 1 is in the ideal (x₀, …, x_(n−1)). -/
theorem img : ∀ n (u : KC R 1 n), InI K x n (d K x 0 n u)
  | 0, _ => ⟨fun _ => K.zero, rfl⟩
  | n + 1, u => by
    match img n u.1 with
    | ⟨c, hc⟩ =>
      refine ⟨fun j => if j = n then u.2 else c j, ?_⟩
      show K.add (d K x 0 n u.1) (K.mul (x n) u.2)
        = K.add (sm K (fun j => K.mul (if j = n then u.2 else c j) (x j)) n) (K.mul (if n = n then u.2 else c n) (x n))
      have e : sm K (fun j => K.mul (if j = n then u.2 else c j) (x j)) n = sm K (fun j => K.mul (c j) (x j)) n :=
        sm_ext K _ _ n (ab_mono _ _ (fun j hj => by
          show K.mul (if j = n then u.2 else c j) (x j) = K.mul (c j) (x j)
          rw [ite_neg' _ _ hj]) n (ab_ne n))
      rw [e, ite_pos' _ _ (rfl : n = n), ← hc]
      lib_ring

/-- **Koszul exactness**: for a regular sequence, H_(k+1)(x₀, …, x_(n−1); R) = 0 for every k and n. -/
theorem exact : ∀ n, Reg K x n → ∀ k (z : KC R (k + 1) n), d K x k n z = KZ K k n → ∃ w : KC R (k + 2) n, d K x (k + 1) n w = z
  | 0, _, _, _, _ => ⟨(), rfl⟩
  | n + 1, ⟨hreg, hx⟩, 0, z, hz => by
    have hz' : K.add (d K x 0 n z.1) (K.mul (x n) z.2) = K.zero := hz
    -- x_n v lies in the ideal, hence v does
    have hin : InI K x n (K.mul z.2 (x n)) := by
      match img K x n (KS K (K.neg K.one) 1 n z.1) with
      | ⟨c, hc⟩ =>
        refine ⟨c, ?_⟩
        rw [← hc, d_smul]
        show K.mul z.2 (x n) = K.mul (K.neg K.one) (d K x 0 n z.1)
        calc K.mul z.2 (x n) = K.add (K.mul (K.neg K.one) (d K x 0 n z.1)) (K.add (d K x 0 n z.1) (K.mul (x n) z.2)) := by lib_ring
          _ = _ := by rw [hz']; lib_ring
    match hx z.2 hin with
    | ⟨c, hc⟩ =>
      match surj K x c n with
      | ⟨w', hw'⟩ =>
        have hv : d K x 0 n w' = z.2 := hw'.trans hc.symm
        let s : R := K.mul (sg K 1) (x n)
        have hcyc : d K x 0 n (KA K 1 n z.1 (KS K (K.neg s) 1 n w')) = KZ K 0 n := by
          rw [d_add, d_smul, hv]
          show K.add (d K x 0 n z.1) (K.mul (K.neg (K.mul (K.neg K.one) (x n))) z.2) = K.zero
          calc _ = K.add (d K x 0 n z.1) (K.mul (x n) z.2) := by lib_ring
            _ = K.zero := hz'
        match exact n hreg 0 _ hcyc with
        | ⟨t, ht⟩ =>
          refine ⟨(t, w'), pext ?_ hv⟩
          show KA K 1 n (d K x 1 n t) (KS K s 1 n w') = z.1
          rw [ht]
          have e := cancel K (K.neg s) 1 n z.1 w'
          have e2 : K.neg (K.neg s) = s := neg_neg' K s
          rw [e2] at e
          exact e
  | n + 1, ⟨hreg, hx⟩, k + 1, z, hz => by
    have hz1 : KA K (k + 1) n (d K x (k + 1) n z.1) (KS K (K.mul (sg K (k + 1)) (x n)) (k + 1) n z.2) = KZ K (k + 1) n :=
      congrArg Prod.fst hz
    have hz2 : d K x k n z.2 = KZ K k n := congrArg Prod.snd hz
    match exact n hreg k z.2 hz2 with
    | ⟨w', hv⟩ =>
      let s : R := K.mul (sg K (k + 2)) (x n)
      have hcyc : d K x (k + 1) n (KA K (k + 2) n z.1 (KS K (K.neg s) (k + 2) n w')) = KZ K (k + 1) n := by
        rw [d_add, d_smul, hv]
        have es : K.neg s = K.mul (sg K (k + 1)) (x n) := by
          show K.neg (K.mul (K.neg (sg K (k + 1))) (x n)) = K.mul (sg K (k + 1)) (x n)
          lib_ring
        rw [es]
        exact hz1
      match exact n hreg (k + 1) _ hcyc with
      | ⟨t, ht⟩ =>
        refine ⟨(t, w'), pext ?_ hv⟩
        show KA K (k + 2) n (d K x (k + 2) n t) (KS K s (k + 2) n w') = z.1
        rw [ht]
        have e := cancel K (K.neg s) (k + 2) n z.1 w'
        have e2 : K.neg (K.neg s) = s := neg_neg' K s
        rw [e2] at e
        exact e

end KoszulAll

#print axioms KoszulAll.pext
#print axioms KoszulAll.ks_add
#print axioms KoszulAll.ka4
#print axioms KoszulAll.ks_comm
#print axioms KoszulAll.cancel
#print axioms KoszulAll.d_add
#print axioms KoszulAll.d_smul
#print axioms KoszulAll.surj
#print axioms KoszulAll.img
#print axioms KoszulAll.exact

#print axioms: 10 theorems, no axioms.

92.9 Column operations

Adding a multiple of one column to another leaves the determinant unchanged at every size.

\[ \det (\dots ,u+cv,\dots ,v,\dots )=\det (\dots ,u,\dots ,v,\dots ). \]

lang/DetColOp.lean

/-
  lang/DetColOp — T21 retry (T52 tool), cycle 805: **elementary column operations keep the determinant, every size n**.
  Adding c times another column v to the column u (clin 1 u c v = u + c·v) does not change det, whether v stands to the left or
  to the right of u (DetNChain.det_lin, det_eq_cols). With DetNChain.det_swap and DetTri.det_tri this turns an integer
  elimination certificate into a proof of det M = ± (product of pivots) ≠ 0 — the form needed for the Bianchi relation matrices of T21.
    colop_right   det (P ++ (u + c v) :: (Q₁ ++ v :: Q₂)) = det (P ++ u :: (Q₁ ++ v :: Q₂))
    colop_left    det ((P₁ ++ v :: P₂) ++ (u + c v) :: Q) = det ((P₁ ++ v :: P₂) ++ u :: Q)
  Lean 4 core only, proofs by hand (lib_ring), no axioms.
-/
import DetNChain
import lib.RingTac

namespace DetColOp

open DetChain DetN

variable {R : Type} (K : CRing R)

theorem lin1 (a c : R) : K.add (K.mul K.one a) (K.mul c K.zero) = a := by lib_ring

theorem colop_right (n : Nat) (P Q1 Q2 : List (Nat → R)) (u v : Nat → R) (c : R)
    (hl : (P ++ u :: (Q1 ++ v :: Q2)).length = n) :
    det K n (P ++ clin K K.one u c v :: (Q1 ++ v :: Q2)) = det K n (P ++ u :: (Q1 ++ v :: Q2)) := by
  have hl' : (P ++ v :: (Q1 ++ v :: Q2)).length = n := by
    rw [len_app'] at hl ⊢
    exact hl
  rw [det_lin K n P (Q1 ++ v :: Q2) u v K.one c hl, det_eq_cols K n Q2 v Q1 P hl', lin1]

theorem colop_left (n : Nat) (P1 P2 Q : List (Nat → R)) (u v : Nat → R) (c : R)
    (hl : ((P1 ++ v :: P2) ++ u :: Q).length = n) :
    det K n ((P1 ++ v :: P2) ++ clin K K.one u c v :: Q) = det K n ((P1 ++ v :: P2) ++ u :: Q) := by
  have e : (P1 ++ v :: P2) ++ v :: Q = P1 ++ v :: (P2 ++ v :: Q) := app_assoc' P1 (v :: P2) (v :: Q)
  have hl' : (P1 ++ v :: (P2 ++ v :: Q)).length = n := by
    rw [← e, len_app']
    rw [len_app'] at hl
    exact hl
  rw [det_lin K n (P1 ++ v :: P2) Q u v K.one c hl, e, det_eq_cols K n Q v P2 P1 hl', lin1]

end DetColOp

#print axioms DetColOp.lin1
#print axioms DetColOp.colop_right
#print axioms DetColOp.colop_left

#print axioms: 3 theorems, no axioms.

92.10 A determinant certificate for \(\Gamma _0(3+2i)\)

A \(43\times 43\) maximal minor of the relation matrix of \(\Gamma _0(3+2i)\subset PSL_2(\mathbb Z[i])\) has determinant \(48\neq 0\) (generated file lang/Bianchi13.lean, 120 column operations).

\[ \det S_{13}=48,\qquad |\mathrm {tors}\,H^2(\Gamma _0(3+2i))|=24\mid 48. \]

lang/ColCert.lean

/-
  lang/ColCert — T21 retry, cycle 806: **determinant certificates by column operations** (generic, every size).
  Columns are given as lists (gd L r = r-th entry, 0 past the end). An integer elimination is replayed in Lean:
    zw c Lu Lv            the list of u + c·v
    gd_zw                 gd (zw c Lu Lv) r = 1·gd Lu r + c·gd Lv r   (all r)
    stepR, stepL          replacing the column Lu by zw c Lu Lv keeps det, when the column Lv stands right / left of it
                          (DetNChain.det_congr + DetColOp)
    z0B, triB, tri_of     a Boolean check of the lower-triangular shape, sound for any equality test beq
  With DetTri.det_tri the final triangular list gives det = product of the diagonal, evaluated by rfl.
  Lean 4 core only, proofs by hand (lib_ring), no axioms.
-/
import lang.DetColOp
import lang.DetTri

namespace ColCert

open DetChain DetN DetTri DetColOp

variable {R : Type} (K : CRing R)

def gd : List R → Nat → R
  | [], _ => K.zero
  | a :: _, 0 => a
  | _ :: as, r + 1 => gd as r

def zw (c : R) : List R → List R → List R
  | a :: as, b :: bs => K.add (K.mul K.one a) (K.mul c b) :: zw c as bs
  | as, [] => as
  | [], b :: bs => K.add (K.mul K.one K.zero) (K.mul c b) :: zw c [] bs

theorem gd_zw (c : R) : ∀ (Lu Lv : List R) (r : Nat),
    gd K (zw K c Lu Lv) r = K.add (K.mul K.one (gd K Lu r)) (K.mul c (gd K Lv r))
  | _ :: _, _ :: _, 0 => rfl
  | _ :: as, _ :: bs, r + 1 => gd_zw c as bs r
  | [], [], r => by show K.zero = K.add (K.mul K.one K.zero) (K.mul c K.zero); lib_ring
  | a :: as, [], r => by
    show gd K (a :: as) r = K.add (K.mul K.one (gd K (a :: as) r)) (K.mul c K.zero)
    lib_ring
  | [], _ :: _, 0 => rfl
  | [], _ :: bs, r + 1 => gd_zw c [] bs r

theorem stepR (n : Nat) (P Q1 Q2 : List (Nat → R)) (Lu Lv : List R) (c : R)
    (hl : (P ++ gd K Lu :: (Q1 ++ gd K Lv :: Q2)).length = n) :
    det K n (P ++ gd K (zw K c Lu Lv) :: (Q1 ++ gd K Lv :: Q2)) = det K n (P ++ gd K Lu :: (Q1 ++ gd K Lv :: Q2)) := by
  rw [det_congr K n _ (P ++ clin K K.one (gd K Lu) c (gd K Lv) :: (Q1 ++ gd K Lv :: Q2))
    (peq_app n P P _ _ (peq_refl n P)
      (show PeqB n (gd K (zw K c Lu Lv) :: (Q1 ++ gd K Lv :: Q2)) (clin K K.one (gd K Lu) c (gd K Lv) :: (Q1 ++ gd K Lv :: Q2)) from
        ⟨fun r _ => gd_zw K c Lu Lv r, peq_refl n _⟩))]
  exact colop_right K n P Q1 Q2 (gd K Lu) (gd K Lv) c hl

theorem stepL (n : Nat) (P1 P2 Q : List (Nat → R)) (Lu Lv : List R) (c : R)
    (hl : ((P1 ++ gd K Lv :: P2) ++ gd K Lu :: Q).length = n) :
    det K n ((P1 ++ gd K Lv :: P2) ++ gd K (zw K c Lu Lv) :: Q) = det K n ((P1 ++ gd K Lv :: P2) ++ gd K Lu :: Q) := by
  rw [det_congr K n _ ((P1 ++ gd K Lv :: P2) ++ clin K K.one (gd K Lu) c (gd K Lv) :: Q)
    (peq_app n (P1 ++ gd K Lv :: P2) (P1 ++ gd K Lv :: P2) _ _ (peq_refl n _)
      (show PeqB n (gd K (zw K c Lu Lv) :: Q) (clin K K.one (gd K Lu) c (gd K Lv) :: Q) from
        ⟨fun r _ => gd_zw K c Lu Lv r, peq_refl n Q⟩))]
  exact colop_left K n P1 P2 Q (gd K Lu) (gd K Lv) c hl

variable (beq : R → R → Bool)

def z0B : List (Nat → R) → Bool
  | [] => true
  | d :: ds => beq (d 0) K.zero && z0B ds

def triB : Nat → List (Nat → R) → Bool
  | 0, _ => true
  | _ + 1, [] => true
  | n + 1, _ :: cs => z0B K beq cs && triB n (cs.map shc)

theorem z0_of (hbeq : ∀ a b, beq a b = true → a = b) : ∀ cs : List (Nat → R), z0B K beq cs = true → Z0 K cs
  | [], _ => trivial
  | d :: ds, h => by
    have h2 : (beq (d 0) K.zero && z0B K beq ds) = true := h
    cases hb : beq (d 0) K.zero with
    | false =>
      rw [hb] at h2
      have h' : false = true := h2
      exact Bool.noConfusion h'
    | true =>
      rw [hb] at h2
      exact ⟨hbeq _ _ hb, z0_of hbeq ds h2⟩

theorem tri_of (hbeq : ∀ a b, beq a b = true → a = b) : ∀ (n : Nat) (cs : List (Nat → R)), triB K beq n cs = true → Tri K n cs
  | 0, _, _ => trivial
  | _ + 1, [], _ => trivial
  | n + 1, _ :: cs, h => by
    have h2 : (z0B K beq cs && triB K beq n (cs.map shc)) = true := h
    cases hb : z0B K beq cs with
    | false =>
      rw [hb] at h2
      have h' : false = true := h2
      exact Bool.noConfusion h'
    | true =>
      rw [hb] at h2
      exact ⟨z0_of K beq hbeq cs hb, tri_of hbeq n (cs.map shc) h2⟩

end ColCert

#print axioms ColCert.gd_zw
#print axioms ColCert.stepR
#print axioms ColCert.stepL
#print axioms ColCert.z0_of
#print axioms ColCert.tri_of

#print axioms: 9 theorems, no axioms.

92.11 List certificates at scale

Column operations by position, kernel vectors, and an \(O(n^2)\) triangular check on list columns.

\[ \det (g\,L_0,\dots ,g\,L_{n-1})=\textstyle \prod _j L_j[j]\quad (L_j[r]=0\ \text {for}\ r<j),\qquad M v=0. \]

lang/ColCert2.lean

/-
  lang/ColCert2 — T21 retry, cycle 811: **index-based column certificates and kernel vectors** (for large relation matrices).
    takeL, dropL      list slicing by hand (no library lemmas), so a column-operation step is written by positions:
                      L = takeL u L ++ L_u :: (takeL (v−u−1) (dropL (u+1) L) ++ L_v :: dropL (v+1) L), checked by rfl
    dot, Rows0, rows0_of     M·v = 0 for an integer matrix (rows as lists), from a Boolean check by rfl
  Lean 4 core only, proofs by hand, no axioms.
-/
import lang.ColCert
import lib.IntRing

namespace ColCert2

def takeL {α : Type} : Nat → List α → List α
  | 0, _ => []
  | _ + 1, [] => []
  | n + 1, a :: as => a :: takeL n as

def dropL {α : Type} : Nat → List α → List α
  | 0, l => l
  | _ + 1, [] => []
  | n + 1, _ :: as => dropL n as

/-- Σ_i a_i b_i over the common length. -/
def dot : List Int → List Int → Int
  | [], _ => 0
  | _ :: _, [] => 0
  | a :: as, b :: bs => a * b + dot as bs

/-- every row r of M has dot r v = 0. -/
def Rows0 (v : List Int) : List (List Int) → Prop
  | [] => True
  | r :: rs => dot r v = 0 ∧ Rows0 v rs

variable (beq : Int → Int → Bool)

def rows0B (v : List Int) : List (List Int) → Bool
  | [] => true
  | r :: rs => beq (dot r v) 0 && rows0B v rs

/-- a Boolean conjunction that is true splits into two true halves. -/
theorem band_split : ∀ (a b : Bool), (a && b) = true → a = true ∧ b = true
  | true, true, _ => And.intro rfl rfl
  | true, false, h => Bool.noConfusion h
  | false, _, h => Bool.noConfusion h

theorem rows0_of (hbeq : ∀ a b, beq a b = true → a = b) (v : List Int) : ∀ M : List (List Int), rows0B beq v M = true → Rows0 v M
  | [], _ => True.intro
  | r :: rs, h =>
    let hh := band_split (beq (dot r v) 0) (rows0B beq v rs) h
    show dot r v = 0 ∧ Rows0 v rs from And.intro (hbeq _ _ hh.1) (rows0_of hbeq v rs hh.2)

/-- M·v = 0 and N·v = 0 give (M ++ N)·v = 0. -/
theorem rows0_app (v : List Int) : ∀ A B : List (List Int), Rows0 v A → Rows0 v B → Rows0 v (A ++ B)
  | [], _, _, hb => hb
  | r :: rs, B, ⟨h1, h2⟩, hb =>
    show dot r v = 0 ∧ Rows0 v (rs ++ B) from And.intro h1 (rows0_app v rs B h2 hb)

end ColCert2

#print axioms ColCert2.band_split
#print axioms ColCert2.rows0_of
#print axioms ColCert2.rows0_app

lang/ColCert3.lean

/-
  lang/ColCert3 — T21 retry, cycle 811: **triangular determinants of columns given as lists, checked in O(n²)**.
    Pw            two column lists agree entrywise (no function extensionality needed)
    tri_pw, dg_pw Tri and the diagonal product respect Pw
    pw_tl         shifting the columns gd L by one row is the same as taking tails of the lists
    triL_of       a Boolean list check (heads zero, then recurse on tails) gives Tri for gd-columns
    dg_list       the diagonal product of gd-columns is the list product dgL
  Lean 4 core only, proofs by hand, no axioms.
-/
import lang.ColCert2

namespace ColCert3

open DetChain DetN DetTri

variable {R : Type} (K : CRing R)

/-- two column lists agree entrywise. -/
def Pw : List (Nat → R) → List (Nat → R) → Prop
  | [], [] => True
  | f :: fs, h :: hs => (∀ r, f r = h r) ∧ Pw fs hs
  | [], _ :: _ => False
  | _ :: _, [] => False

theorem z0_pw : ∀ (a b : List (Nat → R)), Pw a b → Z0 K b → Z0 K a
  | [], [], _, _ => True.intro
  | f :: fs, _ :: hs, ⟨e, p⟩, ⟨z, zs⟩ =>
    show f 0 = K.zero ∧ Z0 K fs from And.intro ((e 0).trans z) (z0_pw fs hs p zs)
  | [], _ :: _, p, _ => False.elim p
  | _ :: _, [], p, _ => False.elim p

theorem pw_shc : ∀ (a b : List (Nat → R)), Pw a b → Pw (a.map shc) (b.map shc)
  | [], [], _ => True.intro
  | f :: fs, h :: hs, ⟨e, p⟩ =>
    show (∀ r, shc f r = shc h r) ∧ Pw (fs.map shc) (hs.map shc) from And.intro (fun r => e (r + 1)) (pw_shc fs hs p)
  | [], _ :: _, p => False.elim p
  | _ :: _, [], p => False.elim p

theorem tri_pw : ∀ (n : Nat) (a b : List (Nat → R)), Pw a b → Tri K n b → Tri K n a
  | 0, _, _, _, _ => True.intro
  | _ + 1, [], _, _, _ => True.intro
  | _ + 1, _ :: _, [], p, _ => False.elim p
  | n + 1, _ :: fs, _ :: hs, ⟨_, p⟩, ⟨z, t⟩ =>
    show Z0 K fs ∧ Tri K n (fs.map shc) from
      And.intro (z0_pw K fs hs p z) (tri_pw n (fs.map shc) (hs.map shc) (pw_shc fs hs p) t)

theorem dg_pw : ∀ (n : Nat) (a b : List (Nat → R)), Pw a b → dg K n a = dg K n b
  | 0, _, _, _ => rfl
  | _ + 1, [], [], _ => rfl
  | _ + 1, [], _ :: _, p => False.elim p
  | _ + 1, _ :: _, [], p => False.elim p
  | n + 1, f :: fs, h :: hs, ⟨e, p⟩ =>
    show K.mul (f 0) (dg K n (fs.map shc)) = K.mul (h 0) (dg K n (hs.map shc)) from
      congr (congrArg K.mul (e 0)) (dg_pw n (fs.map shc) (hs.map shc) (pw_shc fs hs p))

/-- the tail of a list (empty for the empty list). -/
def tl : List R → List R
  | [] => []
  | _ :: as => as

theorem shc_gd (L : List R) (r : Nat) : shc (ColCert.gd K L) r = ColCert.gd K (tl L) r :=
  match L with
  | [] => rfl
  | _ :: _ => rfl

theorem pw_tl : ∀ Ls : List (List R), Pw ((Ls.map (ColCert.gd K)).map shc) ((Ls.map tl).map (ColCert.gd K))
  | [] => True.intro
  | L :: Ls =>
    show (∀ r, shc (ColCert.gd K L) r = ColCert.gd K (tl L) r) ∧
        Pw ((Ls.map (ColCert.gd K)).map shc) ((Ls.map tl).map (ColCert.gd K)) from
      And.intro (fun r => shc_gd K L r) (pw_tl Ls)

/-- the diagonal product of list columns (fuel n). -/
def dgL : Nat → List (List R) → R
  | 0, _ => K.one
  | _ + 1, [] => K.one
  | n + 1, L :: Ls => K.mul (ColCert.gd K L 0) (dgL n (Ls.map tl))

theorem dg_list : ∀ (n : Nat) (Ls : List (List R)), dg K n (Ls.map (ColCert.gd K)) = dgL K n Ls
  | 0, _ => rfl
  | _ + 1, [] => rfl
  | n + 1, L :: Ls =>
    show K.mul (ColCert.gd K L 0) (dg K n ((Ls.map (ColCert.gd K)).map shc)) = K.mul (ColCert.gd K L 0) (dgL K n (Ls.map tl)) from
      congrArg (K.mul (ColCert.gd K L 0)) ((dg_pw K n _ _ (pw_tl K Ls)).trans (dg_list n (Ls.map tl)))

variable (beq : R → R → Bool)

/-- every list starts with zero (or is empty). -/
def zhB : List (List R) → Bool
  | [] => true
  | L :: Ls => beq (ColCert.gd K L 0) K.zero && zhB Ls

/-- lower triangularity of list columns, O(n²) to evaluate. -/
def triLB : Nat → List (List R) → Bool
  | 0, _ => true
  | _ + 1, [] => true
  | n + 1, _ :: Ls => zhB K beq Ls && triLB n (Ls.map tl)

theorem zh_of (hbeq : ∀ a b, beq a b = true → a = b) : ∀ Ls : List (List R), zhB K beq Ls = true → Z0 K (Ls.map (ColCert.gd K))
  | [], _ => True.intro
  | L :: Ls, h =>
    let hh := ColCert2.band_split (beq (ColCert.gd K L 0) K.zero) (zhB K beq Ls) h
    show ColCert.gd K L 0 = K.zero ∧ Z0 K (Ls.map (ColCert.gd K)) from And.intro (hbeq _ _ hh.1) (zh_of hbeq Ls hh.2)

theorem triL_of (hbeq : ∀ a b, beq a b = true → a = b) :
    ∀ (n : Nat) (Ls : List (List R)), triLB K beq n Ls = true → Tri K n (Ls.map (ColCert.gd K))
  | 0, _, _ => True.intro
  | _ + 1, [], _ => True.intro
  | n + 1, _ :: Ls, h =>
    let hh := ColCert2.band_split (zhB K beq Ls) (triLB K beq n (Ls.map tl)) h
    show Z0 K (Ls.map (ColCert.gd K)) ∧ Tri K n ((Ls.map (ColCert.gd K)).map shc) from
      And.intro (zh_of K beq hbeq Ls hh.1) (tri_pw K n _ _ (pw_tl K Ls) (triL_of hbeq n (Ls.map tl) hh.2))

end ColCert3

#print axioms ColCert3.z0_pw
#print axioms ColCert3.pw_shc
#print axioms ColCert3.tri_pw
#print axioms ColCert3.dg_pw
#print axioms ColCert3.shc_gd
#print axioms ColCert3.pw_tl
#print axioms ColCert3.dg_list
#print axioms ColCert3.zh_of
#print axioms ColCert3.triL_of

#print axioms: 12 theorems, no axioms.

92.12 Sparse kernel certificates

Rows stored as (column, entry) pairs are checked against an integer vector by evaluation.

\[ \textstyle \sum _{(j,c)\in r}c\,v_j=0\ \text {for every row } r. \]

lang/ColCert4.lean

/-
  lang/ColCert4 — T21 retry, cycle 811: **sparse kernel certificates** for tall relation matrices.
    nthZ           the j-th entry of an integer list (0 past the end)
    sdot           a sparse row (list of (column, entry) pairs) against a dense vector
    SRows0         every sparse row kills v;  srows0_of from a Boolean check by rfl;  srows0_app for concatenation
  Lean 4 core only, proofs by hand, no axioms.
-/
import lang.ColCert2

namespace ColCert4

/-- the j-th entry of an integer list, 0 past the end. -/
def nthZ : List Int → Nat → Int
  | [], _ => 0
  | a :: _, 0 => a
  | _ :: as, k + 1 => nthZ as k

/-- Σ c · v_j over the pairs (j, c) of a sparse row. -/
def sdot : List (Nat × Int) → List Int → Int
  | [], _ => 0
  | (j, c) :: r, v => c * nthZ v j + sdot r v

/-- every sparse row r of M has sdot r v = 0. -/
def SRows0 (v : List Int) : List (List (Nat × Int)) → Prop
  | [] => True
  | r :: rs => sdot r v = 0 ∧ SRows0 v rs

variable (beq : Int → Int → Bool)

def srows0B (v : List Int) : List (List (Nat × Int)) → Bool
  | [] => true
  | r :: rs => beq (sdot r v) 0 && srows0B v rs

theorem srows0_of (hbeq : ∀ a b, beq a b = true → a = b) (v : List Int) :
    ∀ M : List (List (Nat × Int)), srows0B beq v M = true → SRows0 v M
  | [], _ => True.intro
  | r :: rs, h =>
    let hh := ColCert2.band_split (beq (sdot r v) 0) (srows0B beq v rs) h
    show sdot r v = 0 ∧ SRows0 v rs from And.intro (hbeq _ _ hh.1) (srows0_of hbeq v rs hh.2)

/-- M·v = 0 and N·v = 0 give (M ++ N)·v = 0. -/
theorem srows0_app (v : List Int) :
    ∀ A B : List (List (Nat × Int)), SRows0 v A → SRows0 v B → SRows0 v (A ++ B)
  | [], _, _, hb => hb
  | r :: rs, B, ⟨h1, h2⟩, hb =>
    show sdot r v = 0 ∧ SRows0 v (rs ++ B) from And.intro h1 (srows0_app v rs B h2 hb)

end ColCert4

#print axioms ColCert4.srows0_of
#print axioms ColCert4.srows0_app

#print axioms: 2 theorems, no axioms.

92.13 Kernel vectors modulo \(p\)

Rows of a relation matrix are checked to vanish on an integer vector modulo \(p\); this certifies \(p\)-torsion classes and Hecke eigen-congruences.

\[ (r\cdot f)\bmod p=0\ \text {for every row } r,\qquad (T_\ell -a)f\equiv 0\pmod p. \]

lang/ColCert5.lean

/-
  lang/ColCert5 — T21, cycle 819: **kernel vectors modulo p** (p-torsion certificates for H₁ = ℤ^cols / rows).
    RowsP p f M    every row r of M has dot r f ≡ 0 (mod p), i.e. (dot r f) % p = 0
    rowsP_of       from a Boolean check by rfl;  rowsP_app for concatenation
  Lean 4 core only, proofs by hand, no axioms.
-/
import lang.ColCert2

namespace ColCert5

/-- every row r of M has dot r f ≡ 0 (mod p). -/
def RowsP (p : Int) (f : List Int) : List (List Int) → Prop
  | [] => True
  | r :: rs => ColCert2.dot r f % p = 0 ∧ RowsP p f rs

variable (beq : Int → Int → Bool)

def rowsPB (p : Int) (f : List Int) : List (List Int) → Bool
  | [] => true
  | r :: rs => beq (ColCert2.dot r f % p) 0 && rowsPB p f rs

theorem rowsP_of (hbeq : ∀ a b, beq a b = true → a = b) (p : Int) (f : List Int) :
    ∀ M : List (List Int), rowsPB beq p f M = true → RowsP p f M
  | [], _ => True.intro
  | r :: rs, h =>
    let hh := ColCert2.band_split (beq (ColCert2.dot r f % p) 0) (rowsPB beq p f rs) h
    show ColCert2.dot r f % p = 0 ∧ RowsP p f rs from And.intro (hbeq _ _ hh.1) (rowsP_of hbeq p f rs hh.2)

theorem rowsP_app (p : Int) (f : List Int) :
    ∀ A B : List (List Int), RowsP p f A → RowsP p f B → RowsP p f (A ++ B)
  | [], _, _, hb => hb
  | r :: rs, B, ⟨h1, h2⟩, hb =>
    show ColCert2.dot r f % p = 0 ∧ RowsP p f (rs ++ B) from And.intro h1 (rowsP_app p f rs B h2 hb)

end ColCert5

#print axioms ColCert5.rowsP_of
#print axioms ColCert5.rowsP_app

#print axioms: 2 theorems, no axioms.

92.14 Dual-basis certificates

Dot products are linear in integer combinations, so a dual basis modulo \(d\) reaches every residue.

\[ (F\cdot w_j)_j=d\,q+e_i\ \Longrightarrow \ F\cdot \textstyle \sum _j c_jw_j=d\,(c\cdot q)+c_i. \]

lang/ColCert6.lean

/-
  lang/ColCert6 — T21, cycle 819: **integer combinations and dual-basis certificates** (exact order of H₁ = ℤ^cols / rows).
    vadd, vsc, lcomb   vector sum (padded), scalar multiple, the combination Σ c_j w_j
    dot_vadd, dot_vsc  dot f is additive and homogeneous;  dot_lcomb  dot f (Σ c_j w_j) = Σ c_j (dot f w_j)
    dot_unit           dot cs (e_i) = c_i
    surj               if (dot F w_j)_j = d·q + e_i, then dot F (Σ c_j w_j) = d·(cs · q) + c_i: so x ↦ (F_i · x mod d_i)_i
                       reaches every target (c_i mod d_i)_i when this holds for each i with the same w_j
  Lean 4 core only, proofs by hand, no axioms.
-/
import lang.ColCert2
import lib.IntRing

namespace ColCert6

open ColCert2

/-- vector sum, the shorter list padded by zeros. -/
def vadd : List Int → List Int → List Int
  | [], ys => ys
  | x :: xs, [] => x :: xs
  | x :: xs, y :: ys => (x + y) :: vadd xs ys

/-- scalar multiple. -/
def vsc (c : Int) : List Int → List Int
  | [] => []
  | x :: xs => c * x :: vsc c xs

/-- the integer combination Σ c_j w_j. -/
def lcomb : List Int → List (List Int) → List Int
  | [], _ => []
  | _ :: _, [] => []
  | c :: cs, w :: ws => vadd (vsc c w) (lcomb cs ws)

/-- the unit vector e_i. -/
def unitL : Nat → List Int
  | 0 => [1]
  | n + 1 => 0 :: unitL n

/-- the i-th entry (0 past the end). -/
def nth0 : List Int → Nat → Int
  | [], _ => 0
  | x :: _, 0 => x
  | _ :: xs, n + 1 => nth0 xs n

theorem dot_nil_right : ∀ f : List Int, dot f [] = 0
  | [] => rfl
  | _ :: _ => rfl

theorem dot_vadd : ∀ f x y : List Int, dot f (vadd x y) = dot f x + dot f y
  | [], _, _ => rfl
  | _ :: _, [], y => (LibInt.i_zero_add _).symm
  | a :: f, x :: xs, [] =>
    ((LibInt.i_add_comm (dot (a :: f) (x :: xs)) 0).trans (LibInt.i_zero_add _)).symm
  | a :: f, x :: xs, y :: ys => by
    show a * (x + y) + dot f (vadd xs ys) = (a * x + dot f xs) + (a * y + dot f ys)
    rw [dot_vadd f xs ys]
    lib_int

theorem dot_vsc (c : Int) : ∀ f x : List Int, dot f (vsc c x) = c * dot f x
  | [], _ => by
    show (0 : Int) = c * 0
    lib_int
  | _ :: _, [] => by
    show (0 : Int) = c * 0
    lib_int
  | a :: f, x :: xs => by
    show a * (c * x) + dot f (vsc c xs) = c * (a * x + dot f xs)
    rw [dot_vsc c f xs]
    lib_int

theorem dot_lcomb (f : List Int) : ∀ (cs : List Int) (ws : List (List Int)), dot f (lcomb cs ws) = dot cs (ws.map (dot f))
  | [], _ => dot_nil_right f
  | _ :: _, [] => dot_nil_right f
  | c :: cs, w :: ws => by
    show dot f (vadd (vsc c w) (lcomb cs ws)) = c * dot f w + dot cs (ws.map (dot f))
    rw [dot_vadd, dot_vsc, dot_lcomb f cs ws]

theorem dot_unit : ∀ (cs : List Int) (i : Nat), dot cs (unitL i) = nth0 cs i
  | [], 0 => rfl
  | [], _ + 1 => rfl
  | c :: cs, 0 => by
    show c * 1 + dot cs [] = c
    rw [dot_nil_right]
    lib_int
  | c :: cs, n + 1 => by
    show c * 0 + dot cs (unitL n) = nth0 cs n
    rw [dot_unit cs n]
    lib_int

/-- **dual-basis surjectivity**: if dot F w_j = d·q_j + δ_ij for all j, then the combination x = Σ c_j w_j has
    dot F x = d·(cs · q) + c_i, i.e. F · x ≡ c_i (mod d). -/
theorem surj (F : List Int) (d : Int) (ws : List (List Int)) (qs : List Int) (i : Nat)
    (hP : ws.map (dot F) = vadd (vsc d qs) (unitL i)) (cs : List Int) :
    dot F (lcomb cs ws) = d * dot cs qs + nth0 cs i := by
  rw [dot_lcomb, hP, dot_vadd, dot_vsc, dot_unit]

end ColCert6

#print axioms ColCert6.dot_vadd
#print axioms ColCert6.dot_vsc
#print axioms ColCert6.dot_lcomb
#print axioms ColCert6.dot_unit
#print axioms ColCert6.surj

#print axioms: 5 theorems, no axioms.

92.15 Inequivalent combinations modulo the rows

Quotient certificates for the rows and a dual basis give pairwise inequivalent vectors, so the finite group has at least \(\prod d_i\) elements.

\[ \textstyle \sum _j c_jw_j=\sum _j c'_jw_j+\sum _k a_kr_k\ \Longrightarrow \ c_i\equiv c'_i\pmod d. \]

lang/ColCert7.lean

/-
  lang/ColCert7 — T21, cycle 820: **lower bound for |H₁| = |ℤ^cols / row lattice|** without `%`.
    map_app, vsc_app, quot_app   gluing chunked quotient certificates (M.map (dot F) = d · QM, checked by rfl per chunk)
    lower   if F · w_j = d·q_j + δ_ij and F · r = d·(QM)_r for every row r of M, then two combinations Σ c_j w_j and
            Σ c'_j w_j that differ by an element Σ a_k r_k of the row lattice have c_i ≡ c'_i (mod d).
            With one such F_i for every invariant factor d_i, the vectors Σ c_j w_j (0 ≤ c_i < d_i) are pairwise
            inequivalent modulo the rows: H₁ has at least ∏ d_i elements.
  Lean 4 core only, proofs by hand, no axioms.
-/
import lang.ColCert6

namespace ColCert7

open ColCert2 ColCert6

theorem map_app (f : List Int → Int) : ∀ A B : List (List Int), (A ++ B).map f = A.map f ++ B.map f
  | [], _ => rfl
  | a :: A, B => congrArg (f a :: ·) (map_app f A B)

theorem vsc_app (d : Int) : ∀ A B : List Int, vsc d (A ++ B) = vsc d A ++ vsc d B
  | [], _ => rfl
  | a :: A, B => congrArg (d * a :: ·) (vsc_app d A B)

/-- gluing two chunks of a quotient certificate. -/
theorem quot_app (F : List Int) (d : Int) (A B : List (List Int)) (qa qb : List Int)
    (ha : A.map (dot F) = vsc d qa) (hb : B.map (dot F) = vsc d qb) :
    (A ++ B).map (dot F) = vsc d (qa ++ qb) := by
  rw [map_app, ha, hb, vsc_app]

/-- **inequivalent combinations**: Σ c_j w_j = Σ c'_j w_j + Σ a_k r_k forces c_i ≡ c'_i (mod d). -/
theorem lower (F : List Int) (d : Int) (Ws M : List (List Int)) (Q QM : List Int) (i : Nat)
    (hP : Ws.map (dot F) = vadd (vsc d Q) (unitL i)) (hM : M.map (dot F) = vsc d QM)
    (c c' a : List Int) (h : lcomb c Ws = vadd (lcomb c' Ws) (lcomb a M)) :
    ∃ k : Int, nth0 c i = nth0 c' i + d * k := by
  have h1 := congrArg (dot F) h
  rw [dot_vadd, surj F d Ws Q i hP c, surj F d Ws Q i hP c', dot_lcomb, hM, dot_vsc] at h1
  have h2 := congrArg (fun t => t - d * dot c Q) h1
  refine ⟨dot c' Q + dot a QM - dot c Q, ?_⟩
  calc nth0 c i = (d * dot c Q + nth0 c i) - d * dot c Q := by lib_int
    _ = (d * dot c' Q + nth0 c' i + d * dot a QM) - d * dot c Q := h2
    _ = nth0 c' i + d * (dot c' Q + dot a QM - dot c Q) := by lib_int

end ColCert7

#print axioms ColCert7.map_app
#print axioms ColCert7.vsc_app
#print axioms ColCert7.quot_app
#print axioms ColCert7.lower

#print axioms: 4 theorems, no axioms.

92.16 The row lattice of a relation matrix

If \(F_i\cdot x=d_ik_i\) for every dual coordinate, then \(x\) lies in the row lattice of \(M\), with explicit coefficients.

\[ x=\sum _k\Big (\sum _c x_c\,a_{ck}+\sum _i k_i\,B_{ik}\Big )\,r_k\qquad \text {when } d_iW_i=\sum _k B_{ik}r_k \text { and } e_c\equiv \sum _i F_i[c]\,W_i. \]

lang/ColCert8.lean

/-
  lang/ColCert8 — T21, cycle 820: **upper bound for |H₁| without division**: every vector is congruent, modulo the row
  lattice of M, to Σ_i (F_i · x) w_i.
    nth0_vadd, nth0_vsc, nth0_lcomb, dot_comm      coordinates of sums, multiples and combinations
    nth0_lcomb_vadd, nth0_lcomb_vsc                 combinations are linear in the coefficient list
    idN, nth0_idN                                   identity rows: Σ x_c e_c = x (first n coordinates)
    RepC, rep    if e_c = Σ_k a_ck r_k + Σ_i g_ci w_i for every c (certificate RepC, rows u = e_c), then for every x
                 Σ_c x_c e_c = Σ_k (Σ_c x_c a_ck) r_k + Σ_i (Σ_c x_c g_ci) w_i, coordinatewise
  With g_ci = F_i[c] (so Σ_c x_c g_ci = F_i · x) and d_i w_i in the row lattice, the kernel of x ↦ (F_i · x mod d_i)_i
  is exactly the row lattice (ColCert7 gives the other inclusion): H₁ ≅ ⊕ ℤ/d_i.
  Lean 4 core only, proofs by hand, no axioms.
-/
import lang.ColCert7

namespace ColCert8

open ColCert2 ColCert6

theorem nth0_vadd : ∀ (u v : List Int) (j : Nat), nth0 (vadd u v) j = nth0 u j + nth0 v j
  | [], v, j => (LibInt.i_zero_add (nth0 v j)).symm
  | x :: xs, [], j => ((LibInt.i_add_comm (nth0 (x :: xs) j) 0).trans (LibInt.i_zero_add _)).symm
  | _ :: _, _ :: _, 0 => rfl
  | _ :: xs, _ :: ys, j + 1 => nth0_vadd xs ys j

theorem nth0_vsc (c : Int) : ∀ (u : List Int) (j : Nat), nth0 (vsc c u) j = c * nth0 u j
  | [], _ => by
    show (0 : Int) = c * 0
    lib_int
  | _ :: _, 0 => rfl
  | _ :: xs, j + 1 => nth0_vsc c xs j

theorem nth0_lcomb : ∀ (cs : List Int) (ws : List (List Int)) (j : Nat),
    nth0 (lcomb cs ws) j = dot cs (ws.map (fun w => nth0 w j))
  | [], _, _ => rfl
  | _ :: _, [], _ => rfl
  | c :: cs, w :: ws, j => by
    show nth0 (vadd (vsc c w) (lcomb cs ws)) j = c * nth0 w j + dot cs (ws.map (fun w => nth0 w j))
    rw [nth0_vadd, nth0_vsc, nth0_lcomb cs ws j]

theorem dot_comm : ∀ a b : List Int, dot a b = dot b a
  | [], b => (dot_nil_right b).symm
  | _ :: _, [] => rfl
  | a :: as, b :: bs => by
    show a * b + dot as bs = b * a + dot bs as
    rw [dot_comm as bs]
    lib_int

theorem nth0_lcomb_vadd (p q : List Int) (M : List (List Int)) (j : Nat) :
    nth0 (lcomb (vadd p q) M) j = nth0 (lcomb p M) j + nth0 (lcomb q M) j := by
  rw [nth0_lcomb, nth0_lcomb, nth0_lcomb, dot_comm (vadd p q), dot_vadd, dot_comm _ p, dot_comm _ q]

theorem nth0_lcomb_vsc (c : Int) (p : List Int) (M : List (List Int)) (j : Nat) :
    nth0 (lcomb (vsc c p) M) j = c * nth0 (lcomb p M) j := by
  rw [nth0_lcomb, nth0_lcomb, dot_comm (vsc c p), dot_vsc, dot_comm _ p]

/-! ## Identity rows -/

def zerosN : Nat → List Int
  | 0 => []
  | n + 1 => 0 :: zerosN n

/-- the rows e_0, …, e_(n−1) of the n × n identity matrix. -/
def idN : Nat → List (List Int)
  | 0 => []
  | n + 1 => (1 :: zerosN n) :: (idN n).map (fun r => 0 :: r)

theorem nth0_zerosN : ∀ (n j : Nat), nth0 (zerosN n) j = 0
  | 0, _ => rfl
  | _ + 1, 0 => rfl
  | n + 1, j + 1 => nth0_zerosN n j

theorem map_shift (j : Nat) : ∀ R : List (List Int),
    (R.map (fun r => 0 :: r)).map (fun w => nth0 w (j + 1)) = R.map (fun w => nth0 w j)
  | [] => rfl
  | r :: R => congrArg (nth0 r j :: ·) (map_shift j R)

theorem map_head0 : ∀ R : List (List Int), (R.map (fun r => 0 :: r)).map (fun w => nth0 w 0) = R.map (fun _ => 0)
  | [] => rfl
  | _ :: R => congrArg ((0 : Int) :: ·) (map_head0 R)

theorem dot_zeros : ∀ (xs : List Int) (R : List (List Int)), dot xs (R.map (fun _ => (0 : Int))) = 0
  | [], _ => rfl
  | _ :: _, [] => rfl
  | x :: xs, _ :: R => by
    show x * 0 + dot xs (R.map (fun _ => (0 : Int))) = 0
    rw [dot_zeros xs R]
    lib_int

theorem nth0_idN : ∀ (n : Nat) (x : List Int) (j : Nat), nth0 (lcomb x (idN n)) j = nth0 (takeL n x) j
  | 0, [], _ => rfl
  | 0, _ :: _, _ => rfl
  | _ + 1, [], _ => rfl
  | n + 1, c :: xs, 0 => by
    show nth0 (vadd (vsc c (1 :: zerosN n)) (lcomb xs ((idN n).map (fun r => 0 :: r)))) 0 = c
    rw [nth0_vadd, nth0_vsc, nth0_lcomb, map_head0, dot_zeros]
    show c * 1 + 0 = c
    lib_int
  | n + 1, c :: xs, j + 1 => by
    show nth0 (vadd (vsc c (1 :: zerosN n)) (lcomb xs ((idN n).map (fun r => 0 :: r)))) (j + 1) = nth0 (takeL n xs) j
    rw [nth0_vadd, nth0_vsc, nth0_lcomb, map_shift, ← nth0_lcomb, nth0_idN n xs j]
    show c * nth0 (zerosN n) j + nth0 (takeL n xs) j = nth0 (takeL n xs) j
    rw [nth0_zerosN]
    lib_int

/-! ## The representation certificate -/

/-- row by row: Σ_k a_k r_k + Σ_i g_i w_i = u (u = e_c). -/
def RepC (M Ws : List (List Int)) : List (List Int) → List (List Int) → List (List Int) → Prop
  | [], [], [] => True
  | a :: As, g :: G, u :: U => vadd (lcomb a M) (lcomb g Ws) = u ∧ RepC M Ws As G U
  | [], [], _ :: _ => False
  | [], _ :: _, [] => False
  | [], _ :: _, _ :: _ => False
  | _ :: _, [], [] => False
  | _ :: _, [], _ :: _ => False
  | _ :: _, _ :: _, [] => False

/-- **representation**: for every coefficient list x, Σ_c x_c u_c = Σ_k (Σ_c x_c a_ck) r_k + Σ_i (Σ_c x_c g_ci) w_i. -/
theorem rep (M Ws : List (List Int)) : ∀ (As G U : List (List Int)), RepC M Ws As G U → ∀ (x : List Int) (j : Nat),
    nth0 (lcomb (lcomb x As) M) j + nth0 (lcomb (lcomb x G) Ws) j = nth0 (lcomb x U) j := by
  intro As
  induction As with
  | nil =>
    intro G U h x j
    cases G with
    | nil =>
      cases U with
      | nil => cases x <;> rfl
      | cons _ _ => exact h.elim
    | cons _ _ =>
      cases U with
      | nil => exact h.elim
      | cons _ _ => exact h.elim
  | cons a As ih =>
    intro G U h x j
    cases G with
    | nil =>
      cases U with
      | nil => exact h.elim
      | cons _ _ => exact h.elim
    | cons g G =>
      cases U with
      | nil => exact h.elim
      | cons u U =>
        cases x with
        | nil => rfl
        | cons c xs =>
          show nth0 (lcomb (vadd (vsc c a) (lcomb xs As)) M) j + nth0 (lcomb (vadd (vsc c g) (lcomb xs G)) Ws) j
            = nth0 (vadd (vsc c u) (lcomb xs U)) j
          have ih' := ih G U h.2 xs j
          have hu : nth0 u j = nth0 (lcomb a M) j + nth0 (lcomb g Ws) j := by rw [← h.1, nth0_vadd]
          rw [nth0_lcomb_vadd, nth0_lcomb_vadd, nth0_lcomb_vsc, nth0_lcomb_vsc, nth0_vadd, nth0_vsc, hu, ← ih']
          lib_int

/-- Boolean check of RepC (list equality decided by evaluation). -/
def repB (M Ws : List (List Int)) : List (List Int) → List (List Int) → List (List Int) → Bool
  | [], [], [] => true
  | a :: As, g :: G, u :: U => decide (vadd (lcomb a M) (lcomb g Ws) = u) && repB M Ws As G U
  | [], [], _ :: _ => false
  | [], _ :: _, [] => false
  | [], _ :: _, _ :: _ => false
  | _ :: _, [], [] => false
  | _ :: _, [], _ :: _ => false
  | _ :: _, _ :: _, [] => false

theorem repC_of (M Ws : List (List Int)) : ∀ (As G U : List (List Int)), repB M Ws As G U = true → RepC M Ws As G U
  | [], [], [], _ => True.intro
  | a :: As, g :: G, u :: U, h =>
    let hh := band_split (decide (vadd (lcomb a M) (lcomb g Ws) = u)) (repB M Ws As G U) h
    And.intro (of_decide_eq_true hh.1) (repC_of M Ws As G U hh.2)
  | [], [], _ :: _, h => Bool.noConfusion h
  | [], _ :: _, [], h => Bool.noConfusion h
  | [], _ :: _, _ :: _, h => Bool.noConfusion h
  | _ :: _, [], [], h => Bool.noConfusion h
  | _ :: _, [], _ :: _, h => Bool.noConfusion h
  | _ :: _, _ :: _, [], h => Bool.noConfusion h

/-- the coordinates of Σ_c x_c g_c are dot products with the columns of G. -/
theorem lcomb_col (x : List Int) (G : List (List Int)) (i : Nat) (F : List Int)
    (hF : G.map (fun g => nth0 g i) = F) : nth0 (lcomb x G) i = dot x F := by
  rw [nth0_lcomb, hF]

/-! ## The kernel: F_i · x = d_i k_i for all i ⇒ x lies in the row lattice -/

/-- (d_i k_i)_i. -/
def mulL : List Int → List Int → List Int
  | [], _ => []
  | _ :: _, [] => []
  | d :: ds, k :: ks => d * k :: mulL ds ks

/-- (d_i w_i)_i. -/
def scl : List Int → List (List Int) → List (List Int)
  | [], _ => []
  | _ :: _, [] => []
  | d :: ds, w :: ws => vsc d w :: scl ds ws

/-- g and g' agree at the n coordinates i, i + 1, …, i + n − 1. -/
def Agree : Nat → List Int → List Int → Nat → Prop
  | 0, _, _, _ => True
  | n + 1, g, g', i => nth0 g i = nth0 g' i ∧ Agree n g g' (i + 1)

/-- Σ_k V_k g_(i+k). -/
def dotN : List Int → List Int → Nat → Int
  | [], _, _ => 0
  | v :: V, g, i => v * nth0 g i + dotN V g (i + 1)

theorem dotN_nil : ∀ (V : List Int) (i : Nat), dotN V [] i = 0
  | [], _ => rfl
  | v :: V, i => by
    show v * nth0 [] i + dotN V [] (i + 1) = 0
    rw [dotN_nil V (i + 1)]
    show v * 0 + 0 = 0
    lib_int

theorem dotN_shift (b : Int) (g : List Int) : ∀ (V : List Int) (i : Nat), dotN V (b :: g) (i + 1) = dotN V g i
  | [], _ => rfl
  | v :: V, i => by
    show v * nth0 g i + dotN V (b :: g) (i + 1 + 1) = v * nth0 g i + dotN V g (i + 1)
    rw [dotN_shift b g V (i + 1)]

theorem dot_dotN : ∀ (V g : List Int), dot V g = dotN V g 0
  | [], _ => rfl
  | v :: V, [] => by
    show (0 : Int) = v * 0 + dotN V [] (0 + 1)
    rw [dotN_nil]
    lib_int
  | v :: V, b :: g => by
    show v * b + dot V g = v * b + dotN V (b :: g) (0 + 1)
    rw [dotN_shift, dot_dotN V g]

theorem dotN_congr : ∀ (V g g' : List Int) (i : Nat), Agree V.length g g' i → dotN V g i = dotN V g' i
  | [], _, _, _, _ => rfl
  | v :: V, g, g', i, h => by
    have h' : nth0 g i = nth0 g' i ∧ Agree V.length g g' (i + 1) := h
    show v * nth0 g i + dotN V g (i + 1) = v * nth0 g' i + dotN V g' (i + 1)
    rw [h'.1, dotN_congr V g g' (i + 1) h'.2]

theorem len_map (f : List Int → Int) : ∀ Ws : List (List Int), (Ws.map f).length = Ws.length
  | [] => rfl
  | _ :: Ws => congrArg (· + 1) (len_map f Ws)

theorem lcomb_scl : ∀ (ds ks : List Int) (Ws : List (List Int)) (j : Nat),
    nth0 (lcomb (mulL ds ks) Ws) j = nth0 (lcomb ks (scl ds Ws)) j
  | [], [], _, _ => rfl
  | [], _ :: _, _, _ => rfl
  | _ :: _, [], _, _ => rfl
  | _ :: _, _ :: _, [], _ => rfl
  | d :: ds, k :: ks, w :: Ws, j => by
    show nth0 (vadd (vsc (d * k) w) (lcomb (mulL ds ks) Ws)) j = nth0 (vadd (vsc k (vsc d w)) (lcomb ks (scl ds Ws))) j
    rw [nth0_vadd, nth0_vadd, nth0_vsc, nth0_vsc, nth0_vsc, lcomb_scl ds ks Ws j]
    lib_int

theorem lcomb_map (M : List (List Int)) : ∀ (ks : List Int) (Bs : List (List Int)) (j : Nat),
    nth0 (lcomb ks (Bs.map (fun B => lcomb B M))) j = nth0 (lcomb (lcomb ks Bs) M) j
  | [], _, _ => rfl
  | _ :: _, [], _ => rfl
  | k :: ks, B :: Bs, j => by
    show nth0 (vadd (vsc k (lcomb B M)) (lcomb ks (Bs.map (fun B => lcomb B M)))) j
      = nth0 (lcomb (vadd (vsc k B) (lcomb ks Bs)) M) j
    rw [nth0_vadd, nth0_vsc, nth0_lcomb_vadd, nth0_lcomb_vsc, lcomb_map M ks Bs j]

/-- **kernel**: if x ≡ Σ_i g_i W_i modulo the rows (hrep), g_i = d_i k_i (hag) and d_i W_i = Σ_k B_ik r_k (hB),
    then x = Σ_k ((Σ_c x_c a_ck) + Σ_i k_i B_ik) r_k coordinatewise. -/
theorem kernel (M Ws As G Bs : List (List Int)) (ds ks x : List Int) (X : Nat → Int)
    (hrep : ∀ j, nth0 (lcomb (lcomb x As) M) j + nth0 (lcomb (lcomb x G) Ws) j = X j)
    (hag : Agree Ws.length (lcomb x G) (mulL ds ks) 0)
    (hB : Bs.map (fun B => lcomb B M) = scl ds Ws) (j : Nat) :
    nth0 (lcomb (vadd (lcomb x As) (lcomb ks Bs)) M) j = X j := by
  have hag' : Agree (Ws.map (fun w => nth0 w j)).length (lcomb x G) (mulL ds ks) 0 := by
    rw [len_map]
    exact hag
  have e : nth0 (lcomb (lcomb x G) Ws) j = nth0 (lcomb (lcomb ks Bs) M) j := by
    rw [nth0_lcomb, dot_comm, dot_dotN, dotN_congr _ _ _ 0 hag', ← dot_dotN, dot_comm, ← nth0_lcomb, lcomb_scl, ← hB,
      lcomb_map]
  rw [nth0_lcomb_vadd, ← e]
  exact hrep j

end ColCert8

#print axioms ColCert8.RepC
#print axioms ColCert8.repB
#print axioms ColCert8.nth0_vadd
#print axioms ColCert8.nth0_vsc
#print axioms ColCert8.nth0_lcomb
#print axioms ColCert8.dot_comm
#print axioms ColCert8.nth0_lcomb_vadd
#print axioms ColCert8.nth0_lcomb_vsc
#print axioms ColCert8.nth0_idN
#print axioms ColCert8.rep
#print axioms ColCert8.lcomb_col
#print axioms ColCert8.repC_of
#print axioms ColCert8.dotN_nil
#print axioms ColCert8.dotN_shift
#print axioms ColCert8.dot_dotN
#print axioms ColCert8.dotN_congr
#print axioms ColCert8.len_map
#print axioms ColCert8.lcomb_scl
#print axioms ColCert8.lcomb_map
#print axioms ColCert8.kernel

#print axioms: 18 theorems, no axioms.

92.17 Residues below the modulus

Two residues in \([0,d)\) that differ by a multiple of \(d\) are equal, so distinct box vectors give distinct classes.

\[ 0\le a,b<d,\quad a=b+d\,k\ \Longrightarrow \ a=b. \]

lang/ColCert9.lean

/-
  lang/ColCert9 — T21, cycle 822: **the box injects into H₁** (the order bound |H₁| ≥ ∏ d_i without counting).
    no_pos     a < d and a = b + d·(m + 1) (as integers) is impossible
    small_eq   0 ≤ a, b < d and a = b + d·k  ⇒  a = b
    zero_eq    a = b + 0·k  ⇒  a = b (free coordinates)
  With ColCert7.lower (Σ c_j w_j ≡ Σ c'_j w_j mod rows ⇒ c_i ≡ c'_i mod d_i), two box vectors
  (0 ≤ c_i, c'_i < d_i) in the same class of H₁ are equal: the ∏ d_i box vectors are pairwise distinct in H₁.
  Lean 4 core only, proofs by hand, no axioms.
-/
import lang.ColCert7

namespace ColCert9

/-- **no positive multiple fits**: a < d and a = b + d·(m + 1) is impossible. -/
theorem no_pos (a b d m : Nat) (ha : a < d) (h : (a : Int) = (b : Int) + (d : Int) * ((m + 1 : Nat) : Int)) : False := by
  have e : ((b + (d * m + d) : Nat) : Int) = (b : Int) + (d : Int) * ((m + 1 : Nat) : Int) := rfl
  have hn : a = b + (d * m + d) := Int.ofNat.inj (h.trans e.symm)
  have hle : d ≤ a := by
    rw [hn, ← Nat.add_assoc]
    exact Nat.le_add_left d (b + d * m)
  exact Nat.lt_irrefl a (Nat.lt_of_lt_of_le ha hle)

/-- **residues below d are determined by their class**: 0 ≤ a, b < d and a = b + d·k force a = b. -/
theorem small_eq (a b d : Nat) (ha : a < d) (hb : b < d) (k : Int) (h : (a : Int) = (b : Int) + (d : Int) * k) :
    a = b := by
  cases k with
  | ofNat n =>
    cases n with
    | zero =>
      have e : (b : Int) + (d : Int) * Int.ofNat 0 = (b : Int) := rfl
      exact Int.ofNat.inj (h.trans e)
    | succ m => exact (no_pos a b d m ha h).elim
  | negSucc m =>
    have e : Int.negSucc m = -((m + 1 : Nat) : Int) := rfl
    rw [e] at h
    have h2 : (b : Int) = (a : Int) + (d : Int) * ((m + 1 : Nat) : Int) := by
      calc (b : Int) = ((b : Int) + (d : Int) * -((m + 1 : Nat) : Int)) + (d : Int) * ((m + 1 : Nat) : Int) := by lib_int
        _ = (a : Int) + (d : Int) * ((m + 1 : Nat) : Int) := by rw [← h]
    exact (no_pos b a d m hb h2).elim

/-- a free coordinate (d = 0): a = b + 0·k forces a = b. -/
theorem zero_eq (a b k : Int) (h : a = b + 0 * k) : a = b :=
  h.trans (by lib_int)

end ColCert9

#print axioms ColCert9.no_pos
#print axioms ColCert9.small_eq
#print axioms ColCert9.zero_eq

#print axioms: 3 theorems, no axioms.

92.18 Division with remainder and covering by the box

Every integer has a remainder in \([0,e]\) modulo \(e+1\), computed by structural recursion, so every class has a box representative.

\[ z=r+(e+1)q,\quad 0\le r\le e;\qquad F_i\cdot x=r_i+d_iq_i\ \Longrightarrow \ x\equiv \textstyle \sum _i r_iW_i. \]

lang/ColCert10.lean

/-
  lang/ColCert10 — T21, cycle 822: **division with remainder without `%`** (for the box covering every class of H₁).
    step, dm    division by e + 1 by structural recursion, carrying (q, r, s) with r + s = e (no Nat subtraction)
    dm_spec     n = r + (e + 1) q and r + s = e
    ediv        every integer z is r + (e + 1) q with 0 ≤ r ≤ e (r + s = e)
    cover       if F_i · x = r_i + d_i q_i for all i, then x ≡ Σ r_i W_i modulo the rows (with explicit coefficients)
  Lean 4 core only, proofs by hand, no axioms.
-/
import lang.ColCert8

namespace ColCert10

/-- one step of division by e + 1 on (quotient, remainder, e − remainder). -/
def step : Nat × Nat × Nat → Nat × Nat × Nat
  | (q, r, 0) => (q + 1, 0, r)
  | (q, r, s + 1) => (q, r + 1, s)

/-- (n / (e + 1), n % (e + 1), e − n % (e + 1)) by counting up. -/
def dm (e : Nat) : Nat → Nat × Nat × Nat
  | 0 => (0, 0, e)
  | n + 1 => step (dm e n)

theorem step_spec (e n : Nat) : ∀ p : Nat × Nat × Nat, n = p.2.1 + (e + 1) * p.1 → p.2.1 + p.2.2 = e →
    n + 1 = (step p).2.1 + (e + 1) * (step p).1 ∧ (step p).2.1 + (step p).2.2 = e
  | (q, r, 0), h1, h2 => by
    have h1' : n = r + (e + 1) * q := h1
    have h2' : r + 0 = e := h2
    show n + 1 = 0 + (e + 1) * (q + 1) ∧ 0 + r = e
    constructor
    · rw [h1', ← h2']
      lib_nat
    · rw [← h2']
      lib_nat
  | (q, r, s + 1), h1, h2 => by
    have h1' : n = r + (e + 1) * q := h1
    have h2' : r + (s + 1) = e := h2
    show n + 1 = (r + 1) + (e + 1) * q ∧ (r + 1) + s = e
    constructor
    · rw [h1']
      lib_nat
    · rw [← h2']
      lib_nat

/-- **division by e + 1**: n = r + (e + 1) q with r + s = e. -/
theorem dm_spec (e : Nat) : ∀ n : Nat, n = (dm e n).2.1 + (e + 1) * (dm e n).1 ∧ (dm e n).2.1 + (dm e n).2.2 = e
  | 0 => And.intro (by show 0 = 0 + (e + 1) * 0; lib_nat) (by show 0 + e = e; lib_nat)
  | n + 1 => step_spec e n (dm e n) (dm_spec e n).1 (dm_spec e n).2

/-- **every integer has a remainder in [0, e]**: z = r + (e + 1) q with r + s = e. -/
theorem ediv (e : Nat) (z : Int) : ∃ (q : Int) (r s : Nat), r + s = e ∧ z = (r : Int) + ((e + 1 : Nat) : Int) * q := by
  cases z with
  | ofNat n =>
    have h := dm_spec e n
    have c : (((dm e n).2.1 + (e + 1) * (dm e n).1 : Nat) : Int)
        = ((dm e n).2.1 : Int) + ((e + 1 : Nat) : Int) * ((dm e n).1 : Int) := rfl
    exact ⟨((dm e n).1 : Int), (dm e n).2.1, (dm e n).2.2, h.2, (congrArg Int.ofNat h.1).trans c⟩
  | negSucc n =>
    have h := dm_spec e n
    refine ⟨-(((dm e n).1 : Int) + 1), (dm e n).2.2, (dm e n).2.1, ?_, ?_⟩
    · show (dm e n).2.2 + (dm e n).2.1 = e
      rw [Nat.add_comm]
      exact h.2
    · generalize (dm e n).1 = q at h ⊢
      generalize (dm e n).2.1 = r at h ⊢
      generalize (dm e n).2.2 = s at h ⊢
      have e1 : Int.negSucc n = -((n : Int) + 1) := rfl
      rw [e1, h.1, ← h.2]
      have c1 : ((r + (r + s + 1) * q : Nat) : Int) = (r : Int) + ((r : Int) + (s : Int) + 1) * (q : Int) := rfl
      have c2 : ((r + s + 1 : Nat) : Int) = (r : Int) + (s : Int) + 1 := rfl
      rw [c1, c2]
      lib_int

/-- the free coordinate's "remainder" is the value itself: z = z + 0·0. -/
theorem free_rem (z : Int) : z = z + 0 * 0 := by lib_int

open ColCert2 ColCert6 ColCert8 in
/-- **covering**: if x ≡ Σ g_i W_i (hrep), g_i = r_i + d_i q_i (hag) and d_i W_i = Σ_k B_ik r_k (hB), then
    x ≡ Σ r_i W_i modulo the rows, with coefficients Σ_c x_c a_c + Σ_i q_i B_i. -/
theorem cover (M Ws As G Bs : List (List Int)) (ds qs rs x : List Int) (X : Nat → Int)
    (hrep : ∀ j, nth0 (lcomb (lcomb x As) M) j + nth0 (lcomb (lcomb x G) Ws) j = X j)
    (hag : Agree Ws.length (lcomb x G) (vadd rs (mulL ds qs)) 0)
    (hB : Bs.map (fun B => lcomb B M) = scl ds Ws) (j : Nat) :
    nth0 (lcomb (vadd (lcomb x As) (lcomb qs Bs)) M) j + nth0 (lcomb rs Ws) j = X j := by
  have hag' : Agree (Ws.map (fun w => nth0 w j)).length (lcomb x G) (vadd rs (mulL ds qs)) 0 := by
    rw [len_map]
    exact hag
  have e : nth0 (lcomb (lcomb x G) Ws) j = nth0 (lcomb rs Ws) j + nth0 (lcomb (lcomb qs Bs) M) j := by
    rw [nth0_lcomb, dot_comm, dot_dotN, dotN_congr _ _ _ 0 hag', ← dot_dotN, dot_comm, ← nth0_lcomb,
      nth0_lcomb_vadd, lcomb_scl, ← hB, lcomb_map]
  rw [nth0_lcomb_vadd, ← hrep j, e]
  lib_int

/-- mapping a concatenation (rows to rows). -/
theorem mapL_app (f : List Int → List Int) : ∀ A B : List (List Int), (A ++ B).map f = A.map f ++ B.map f
  | [], _ => rfl
  | a :: A, B => congrArg (f a :: ·) (mapL_app f A B)

/-- gluing two chunks of a row-image certificate: A.map f = CA.map g and B.map f = CB.map g. -/
theorem pres_app (f g : List Int → List Int) (A B CA CB : List (List Int))
    (ha : A.map f = CA.map g) (hb : B.map f = CB.map g) : (A ++ B).map f = (CA ++ CB).map g := by
  rw [mapL_app, mapL_app, ha, hb]

end ColCert10

#print axioms ColCert10.step_spec
#print axioms ColCert10.dm_spec
#print axioms ColCert10.ediv
#print axioms ColCert10.cover
#print axioms ColCert10.free_rem
#print axioms ColCert10.mapL_app
#print axioms ColCert10.pres_app

#print axioms: 7 theorems, no axioms.

92.19 Machine check

The Lean files of this section are DetChain.lean (rings, \(n=1,2\), Koszul complexes) and DetNChain.lean (the determinant for every \(n\)). In AXIOMS.txt they have \(19\) and \(42\) theorems, \(61\) in all, and every one of the \(61\) #print axioms lines reads “does not depend on any axioms”. DetChain.lean imports FTAChain.lean from the earlier links. The numbers come from numeric_det.py and numeric_bianchi.py; their outputs are NUMERIC_DET.txt and NUMERIC_BIANCHI.txt.

Listing 360: DetChain.lean: rings from their laws, \(1\times 1\) and \(2\times 2\), Koszul complexes

DetChain.lean

/-
  DetChain.lean
  det ≠ 0 gives an injective map, and regular sequences give exact Koszul
  complexes (T21, the algebraic part).

  Lean 4 core only (with FTAChain for nothing beyond the conventions).
  A commutative ring is passed by its operations and laws (`CRing`); a ring
  without zero divisors adds `noZD`. Proofs are hand-written rewriting;
  no omega / simp / ring / decide / norm_num / linarith.

  Proved here:
    add_cancel_left, mul_zero, zero_mul', neg_unique, neg_mul_left, neg_neg',
    add_neg', right_distrib          ring lemmas from the laws
    inj1, inj1'                      1×1: det = a ≠ 0 ⇒ x ↦ a x has trivial kernel, is injective
    adj2_left, adj2_right            2×2: adj(d) · d = det · 1, written out
    inj2                             2×2: det ≠ 0 ⇒ d(x,y) = 0 forces x = y = 0
    koszul1_exact                    length 1: x regular ⇒ H_1 = 0
    koszul2_complex                  length 2: d1 ∘ d2 = 0
    koszul2_H2, koszul2_H1           length 2: (x, y) regular ⇒ H_2 = 0 and H_1 = 0
-/
import FTAChain

namespace DetChain

/-- A commutative ring, given by its operations and laws. -/
structure CRing (R : Type) where
  add : R → R → R
  mul : R → R → R
  neg : R → R
  zero : R
  one : R
  add_assoc : ∀ a b c, add (add a b) c = add a (add b c)
  add_comm : ∀ a b, add a b = add b a
  zero_add : ∀ a, add zero a = a
  add_neg : ∀ a, add a (neg a) = zero
  mul_assoc : ∀ a b c, mul (mul a b) c = mul a (mul b c)
  mul_comm : ∀ a b, mul a b = mul b a
  one_mul : ∀ a, mul one a = a
  distrib : ∀ a b c, mul a (add b c) = add (mul a b) (mul a c)

section Ring
variable {R : Type} (K : CRing R)

theorem add_zero' (a : R) : K.add a K.zero = a := (K.add_comm a K.zero).trans (K.zero_add a)

theorem add_cancel_left (a b c : R) (h : K.add a b = K.add a c) : b = c := by
  have e : K.add (K.neg a) (K.add a b) = K.add (K.neg a) (K.add a c) := by rw [h]
  rw [← K.add_assoc, ← K.add_assoc, K.add_comm (K.neg a) a, K.add_neg, K.zero_add, K.zero_add] at e
  exact e

theorem right_distrib (a b c : R) : K.mul (K.add a b) c = K.add (K.mul a c) (K.mul b c) := by
  rw [K.mul_comm, K.distrib, K.mul_comm c a, K.mul_comm c b]

theorem mul_zero (a : R) : K.mul a K.zero = K.zero := by
  apply add_cancel_left K (K.mul a K.zero)
  rw [← K.distrib, K.zero_add, add_zero']

theorem zero_mul' (a : R) : K.mul K.zero a = K.zero := by
  rw [K.mul_comm, mul_zero]

/-- If `u + v = 0` then `u = -v`. -/
theorem neg_unique (u v : R) (h : K.add u v = K.zero) : u = K.neg v := by
  apply add_cancel_left K v
  rw [K.add_comm v u, h, K.add_neg]

theorem neg_mul_left (a b : R) : K.mul (K.neg a) b = K.neg (K.mul a b) := by
  apply neg_unique
  rw [← right_distrib, K.add_comm, K.add_neg, zero_mul']

theorem neg_neg' (a : R) : K.neg (K.neg a) = a :=
  (neg_unique K a (K.neg a) (K.add_neg a)).symm

theorem add_neg' (a : R) : K.add (K.neg a) a = K.zero := by
  rw [K.add_comm, K.add_neg]

/-- `(u + v) + (w + z) = (u + w) + (v + z)`. -/
theorem add_mid4 (u v w z : R) : K.add (K.add u v) (K.add w z) = K.add (K.add u w) (K.add v z) := by
  rw [K.add_assoc, ← K.add_assoc v w z, K.add_comm v w, K.add_assoc w v z, ← K.add_assoc]

end Ring

/-- No zero divisors. -/
def NoZD {R : Type} (K : CRing R) : Prop := ∀ a b, K.mul a b = K.zero → a = K.zero ∨ b = K.zero

/-! ## 1 × 1 -/

/-- **1×1.** If `a ≠ 0`, then `a x = 0` forces `x = 0`. -/
theorem inj1 {R : Type} (K : CRing R) (hK : NoZD K) (a x : R) (ha : a ≠ K.zero)
    (h : K.mul a x = K.zero) : x = K.zero := by
  cases hK a x h with
  | inl h' => exact absurd h' ha
  | inr h' => exact h'

/-- **1×1, injective.** If `a ≠ 0` and `a x = a x'`, then `x = x'`. -/
theorem inj1' {R : Type} (K : CRing R) (hK : NoZD K) (a x x' : R) (ha : a ≠ K.zero)
    (h : K.mul a x = K.mul a x') : x = x' := by
  have e : K.mul a (K.add x (K.neg x')) = K.zero := by
    rw [K.distrib, h, ← K.distrib, K.add_neg, mul_zero]
  have e2 := inj1 K hK a _ ha e
  have e3 := neg_unique K x (K.neg x') e2
  rw [e3, neg_neg']

/-! ## 2 × 2 -/

/-- `det [[a, b], [c, e]] = a e - b c`. -/
def det2 {R : Type} (K : CRing R) (a b c e : R) : R := K.add (K.mul a e) (K.neg (K.mul b c))

/-- First row of `adj(d) · d`: `e (a x + b y) - b (c x + e y) = det · x`. -/
theorem adj2_left {R : Type} (K : CRing R) (a b c e x y : R) :
    K.add (K.mul e (K.add (K.mul a x) (K.mul b y))) (K.mul (K.neg b) (K.add (K.mul c x) (K.mul e y)))
      = K.mul (det2 K a b c e) x := by
  show _ = K.mul (K.add (K.mul a e) (K.neg (K.mul b c))) x
  rw [K.distrib, K.distrib, neg_mul_left, neg_mul_left, ← K.mul_assoc e a x, ← K.mul_assoc e b y,
    ← K.mul_assoc b c x, ← K.mul_assoc b e y, add_mid4, K.mul_comm e b, K.add_neg, add_zero',
    right_distrib, neg_mul_left, K.mul_comm e a]

/-- Second row of `adj(d) · d`: `-c (a x + b y) + a (c x + e y) = det · y`. -/
theorem adj2_right {R : Type} (K : CRing R) (a b c e x y : R) :
    K.add (K.mul (K.neg c) (K.add (K.mul a x) (K.mul b y))) (K.mul a (K.add (K.mul c x) (K.mul e y)))
      = K.mul (det2 K a b c e) y := by
  show _ = K.mul (K.add (K.mul a e) (K.neg (K.mul b c))) y
  rw [K.distrib, K.distrib, neg_mul_left, neg_mul_left, ← K.mul_assoc c a x, ← K.mul_assoc c b y,
    ← K.mul_assoc a c x, ← K.mul_assoc a e y, add_mid4, K.mul_comm c a, add_neg', K.zero_add,
    right_distrib, neg_mul_left, K.mul_comm c b]
  exact K.add_comm _ _

/-- **2×2.** Over a commutative ring without zero divisors, if `det d ≠ 0`
    then `d (x, y) = 0` forces `x = y = 0`: the map is injective. -/
theorem inj2 {R : Type} (K : CRing R) (hK : NoZD K) (a b c e x y : R)
    (hdet : det2 K a b c e ≠ K.zero)
    (h1 : K.add (K.mul a x) (K.mul b y) = K.zero) (h2 : K.add (K.mul c x) (K.mul e y) = K.zero) :
    x = K.zero ∧ y = K.zero := by
  have ex := adj2_left K a b c e x y
  have ey := adj2_right K a b c e x y
  rw [h1, h2, mul_zero, mul_zero, K.zero_add] at ex
  rw [h1, h2, mul_zero, mul_zero, K.zero_add] at ey
  exact ⟨inj1 K hK _ x hdet ex.symm, inj1 K hK _ y hdet ey.symm⟩

/-! ## Koszul complexes -/

/-- `x` is a non-zero-divisor. -/
def Regular1 {R : Type} (K : CRing R) (x : R) : Prop := ∀ r, K.mul r x = K.zero → r = K.zero

/-- **Length 1.** `0 → R --x--> R → 0`: if `x` is regular, `H_1 = ker(x) = 0`. -/
theorem koszul1_exact {R : Type} (K : CRing R) (x : R) (hx : Regular1 K x) (r : R)
    (h : K.mul r x = K.zero) : r = K.zero := hx r h

/-- `(x, y)` is a regular sequence: `x` regular, and `y` regular on `R/(x)`. -/
def Regular2 {R : Type} (K : CRing R) (x y : R) : Prop :=
  Regular1 K x ∧ ∀ b c, K.mul b y = K.mul c x → ∃ r, b = K.mul r x

/-- `d1 (a, b) = a x + b y`. -/
def d1 {R : Type} (K : CRing R) (x y : R) (p : R × R) : R := K.add (K.mul p.1 x) (K.mul p.2 y)

/-- `d2 r = (-(r y), r x)`. -/
def d2 {R : Type} (K : CRing R) (x y : R) (r : R) : R × R := (K.neg (K.mul r y), K.mul r x)

/-- **It is a complex**: `d1 ∘ d2 = 0`. -/
theorem koszul2_complex {R : Type} (K : CRing R) (x y r : R) : d1 K x y (d2 K x y r) = K.zero := by
  show K.add (K.mul (K.neg (K.mul r y)) x) (K.mul (K.mul r x) y) = K.zero
  rw [neg_mul_left, K.mul_assoc, K.mul_comm y x, ← K.mul_assoc, add_neg']

/-- **Length 2, H_2 = 0**: `d2 r = 0` forces `r = 0`. -/
theorem koszul2_H2 {R : Type} (K : CRing R) (x y : R) (hreg : Regular2 K x y) (r : R)
    (h : d2 K x y r = (K.zero, K.zero)) : r = K.zero :=
  hreg.1 r (congrArg Prod.snd h)

/-- **Length 2, H_1 = 0**: every `(a, b)` with `a x + b y = 0` is `d2 r` for some `r`. -/
theorem koszul2_H1 {R : Type} (K : CRing R) (x y : R) (hreg : Regular2 K x y) (a b : R)
    (h : d1 K x y (a, b) = K.zero) : ∃ r, (a, b) = d2 K x y r := by
  have h' : K.add (K.mul a x) (K.mul b y) = K.zero := h
  have hb : K.mul b y = K.mul (K.neg a) x := by
    rw [neg_mul_left]
    exact neg_unique K _ _ ((K.add_comm _ _).trans h')
  obtain ⟨r, hr⟩ := hreg.2 b (K.neg a) hb
  refine ⟨r, ?_⟩
  -- a x + (r x) y = 0, so (a + r y) x = 0, so a = -(r y)
  have e1 : K.mul (K.add a (K.mul r y)) x = K.zero := by
    rw [right_distrib, K.mul_assoc, K.mul_comm y x, ← K.mul_assoc, ← hr]
    exact h'
  have e2 := hreg.1 _ e1
  have e3 : a = K.neg (K.mul r y) := neg_unique K _ _ e2
  show (a, b) = (K.neg (K.mul r y), K.mul r x)
  rw [e3, hr]

end DetChain

#print axioms DetChain.add_zero'
#print axioms DetChain.add_cancel_left
#print axioms DetChain.right_distrib
#print axioms DetChain.mul_zero
#print axioms DetChain.zero_mul'
#print axioms DetChain.neg_unique
#print axioms DetChain.neg_mul_left
#print axioms DetChain.neg_neg'
#print axioms DetChain.add_neg'
#print axioms DetChain.add_mid4
#print axioms DetChain.inj1
#print axioms DetChain.inj1'
#print axioms DetChain.adj2_left
#print axioms DetChain.adj2_right
#print axioms DetChain.inj2
#print axioms DetChain.koszul1_exact
#print axioms DetChain.koszul2_complex
#print axioms DetChain.koszul2_H2
#print axioms DetChain.koszul2_H1

Listing 361: DetNChain.lean: the Laplace determinant and det \(\neq 0\) \(\Rightarrow \) injective for every \(n\)

DetNChain.lean

/-
  DetNChain.lean
  det d ≠ 0 ⇒ injective, for every n (T21).

  Lean 4 core plus DetChain (the commutative ring `CRing` and its lemmas).
  Proofs are hand-written rewriting; no omega / simp / ring / decide /
  norm_num / linarith. The list lemmas of the core library that use `propext`
  are re-proved here by hand.

  A matrix is a list of columns; a column is a function `Nat → R` (row ↦ entry).
  The determinant is the Laplace expansion along row 0, built by hand:
    det 0 cs       = 1
    det (n+1) cs   = Σ_j (-1)^j · cs_j(0) · det n (cs without column j, rows shifted up)
  The sum is a walk over the list (`lapS pre rest suf`): `pre` are the columns
  already passed, `rest` those still to come, and `suf` a fixed tail.

  Proved here:
    list lemmas      app_nil', app_assoc', map_app', len_app', len_map'
    ring lemmas      neg_zero', neg_add', mul_neg', sgn_*
    lapS_split       the walk over xs ++ ys splits
    lapS_vanish      a walk whose minors all vanish is 0
    det_adj          two equal adjacent columns ⇒ det = 0
    det_add, det_smul  det is additive and homogeneous in every column
    det_swap         exchanging adjacent columns changes the sign
    det_eq_cols      two equal columns anywhere ⇒ det = 0
    det_congr        det only sees rows < n
    det_comb         det (… , Σ_k x_k c_k , …) = Σ_k x_k det (…, c_k, …)
    kernel_trivial   **det A ≠ 0 and A x = 0 ⇒ x = 0**, every n, over a ring
                     without zero divisors
-/
import DetChain

namespace DetN
open DetChain

/-! ## Lists, by hand -/

theorem app_nil' {A : Type} : ∀ l : List A, l ++ [] = l
  | [] => rfl
  | a :: l => congrArg (List.cons a) (app_nil' l)

theorem app_assoc' {A : Type} : ∀ a b c : List A, (a ++ b) ++ c = a ++ (b ++ c)
  | [], _, _ => rfl
  | x :: a, b, c => congrArg (List.cons x) (app_assoc' a b c)

theorem map_app' {A B : Type} (f : A → B) : ∀ a b : List A, (a ++ b).map f = a.map f ++ b.map f
  | [], _ => rfl
  | x :: a, b => congrArg (List.cons (f x)) (map_app' f a b)

theorem len_app' {A : Type} : ∀ a b : List A, (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_app' a b, Nat.add_right_comm]

theorem len_map' {A B : Type} (f : A → B) : ∀ a : List A, (a.map f).length = a.length
  | [] => rfl
  | _ :: a => congrArg (· + 1) (len_map' f a)

section Det
variable {R : Type} (K : CRing R)

/-! ## Ring lemmas -/

theorem neg_zero' : K.neg K.zero = K.zero :=
  (neg_unique K K.zero K.zero (K.zero_add K.zero)).symm

theorem neg_add' (x y : R) : K.neg (K.add x y) = K.add (K.neg x) (K.neg y) := by
  apply Eq.symm
  apply neg_unique
  rw [add_mid4, add_neg', add_neg', K.zero_add]

theorem mul_neg' (a x : R) : K.mul a (K.neg x) = K.neg (K.mul a x) := by
  rw [K.mul_comm, neg_mul_left, K.mul_comm]

/-- `(-1)^k · x`. -/
def sgn : Nat → R → R
  | 0, x => x
  | k + 1, x => K.neg (sgn k x)

theorem sgn_zero : ∀ k, sgn K k K.zero = K.zero
  | 0 => rfl
  | k + 1 => by
    show K.neg (sgn K k K.zero) = K.zero
    rw [sgn_zero k, neg_zero']

theorem sgn_add : ∀ k (x y : R), sgn K k (K.add x y) = K.add (sgn K k x) (sgn K k y)
  | 0, _, _ => rfl
  | k + 1, x, y => by
    show K.neg (sgn K k (K.add x y)) = K.add (K.neg (sgn K k x)) (K.neg (sgn K k y))
    rw [sgn_add k, neg_add']

theorem sgn_mul : ∀ k (a x : R), sgn K k (K.mul a x) = K.mul a (sgn K k x)
  | 0, _, _ => rfl
  | k + 1, a, x => by
    show K.neg (sgn K k (K.mul a x)) = K.mul a (K.neg (sgn K k x))
    rw [sgn_mul k, mul_neg']

/-! ## The determinant -/

/-- Drop row 0: the column read from row 1 on. -/
def shc (c : Nat → R) : Nat → R := fun r => c (r + 1)

/-- The Laplace walk. -/
def lapS (D : List (Nat → R) → R) : List (Nat → R) → List (Nat → R) → List (Nat → R) → R
  | _, [], _ => K.zero
  | pre, c :: cs, suf =>
    K.add (sgn K pre.length (K.mul (c 0) (D ((pre ++ (cs ++ suf)).map shc)))) (lapS D (pre ++ [c]) cs suf)

/-- The determinant, by expansion along row 0 (fuel `n` = size). -/
def det : Nat → List (Nat → R) → R
  | 0, _ => K.one
  | n + 1, cs => lapS K (det n) [] cs []

theorem det_succ (n : Nat) (cs : List (Nat → R)) : det K (n + 1) cs = lapS K (det K n) [] cs [] := rfl

theorem lapS_split (D : List (Nat → R) → R) (suf : List (Nat → R)) :
    ∀ (xs ys pre : List (Nat → R)),
      lapS K D pre (xs ++ ys) suf = K.add (lapS K D pre xs (ys ++ suf)) (lapS K D (pre ++ xs) ys suf)
  | [], ys, pre => by
    show lapS K D pre ys suf = K.add K.zero (lapS K D (pre ++ []) ys suf)
    rw [app_nil', K.zero_add]
  | x :: xs, ys, pre => by
    show K.add (sgn K pre.length (K.mul (x 0) (D ((pre ++ ((xs ++ ys) ++ suf)).map shc))))
        (lapS K D (pre ++ [x]) (xs ++ ys) suf)
      = K.add (K.add (sgn K pre.length (K.mul (x 0) (D ((pre ++ (xs ++ (ys ++ suf))).map shc))))
          (lapS K D (pre ++ [x]) xs (ys ++ suf))) (lapS K D (pre ++ (x :: xs)) ys suf)
    rw [lapS_split D suf xs ys (pre ++ [x]), app_assoc' xs ys suf, app_assoc' pre [x] xs, K.add_assoc]
    rfl

theorem len_fix (a b s m : Nat) (h : a + (b + 1) + s = m + 1) : a + b + s = m := by
  rw [← Nat.add_assoc, Nat.add_right_comm] at h
  exact Nat.succ.inj h

/-- A walk whose minors all vanish is 0. -/
theorem lapS_vanish (D : List (Nat → R) → R) (m : Nat) (suf : List (Nat → R)) :
    ∀ (xs pre : List (Nat → R)),
      (∀ zs, ((pre ++ zs) ++ suf).length = m → D (((pre ++ zs) ++ suf).map shc) = K.zero) →
      ((pre ++ xs) ++ suf).length = m + 1 → lapS K D pre xs suf = K.zero
  | [], _, _, _ => rfl
  | x :: xs, pre, H, hl => by
    have hl' : ((pre ++ xs) ++ suf).length = m := by
      rw [len_app', len_app'] at hl
      rw [len_app', len_app']
      exact len_fix _ _ _ _ hl
    have h1 : D ((pre ++ (xs ++ suf)).map shc) = K.zero := by
      rw [← app_assoc']
      exact H xs hl'
    have H' : ∀ zs, (((pre ++ [x]) ++ zs) ++ suf).length = m →
        D ((((pre ++ [x]) ++ zs) ++ suf).map shc) = K.zero := fun zs h => by
      rw [app_assoc' pre [x] zs] at h
      rw [app_assoc' pre [x] zs]
      exact H (x :: zs) h
    have hl2 : (((pre ++ [x]) ++ xs) ++ suf).length = m + 1 := by
      rw [app_assoc' pre [x] xs]
      exact hl
    show K.add (sgn K pre.length (K.mul (x 0) (D ((pre ++ (xs ++ suf)).map shc))))
      (lapS K D (pre ++ [x]) xs suf) = K.zero
    rw [h1, mul_zero, sgn_zero, lapS_vanish D m suf xs (pre ++ [x]) H' hl2, K.zero_add]

theorem reshape2 (P zs : List (Nat → R)) (u : Nat → R) :
    ((P ++ [u]) ++ [u]) ++ zs = P ++ (u :: u :: zs) := by
  rw [app_assoc' (P ++ [u]) [u] zs, app_assoc' P [u] ([u] ++ zs)]
  rfl

/-- **Two equal adjacent columns give determinant 0.** -/
theorem det_adj : ∀ (n : Nat) (P Q : List (Nat → R)) (u : Nat → R),
    (P ++ u :: u :: Q).length = n → det K n (P ++ u :: u :: Q) = K.zero
  | 0, P, Q, u, h => by
    rw [len_app'] at h
    exact absurd h (FTAChain.succ_ne_zero' _)
  | m + 1, P, Q, u, h => by
    rw [det_succ, lapS_split K (det K m) [] P (u :: u :: Q) []]
    have part1 : lapS K (det K m) [] P ((u :: u :: Q) ++ []) = K.zero := by
      apply lapS_vanish K (det K m) m ((u :: u :: Q) ++ []) P []
      · intro zs hz
        have e : (([] ++ zs) ++ ((u :: u :: Q) ++ [])).map shc
            = zs.map shc ++ (shc u :: shc u :: (Q ++ []).map shc) := map_app' shc zs _
        rw [e]
        apply det_adj m
        rw [← e, len_map']
        exact hz
      · show (P ++ ((u :: u :: Q) ++ [])).length = m + 1
        rw [app_nil']
        exact h
    have rest : lapS K (det K m) ((P ++ [u]) ++ [u]) Q [] = K.zero := by
      apply lapS_vanish K (det K m) m [] Q ((P ++ [u]) ++ [u])
      · intro zs hz
        have e : ((((P ++ [u]) ++ [u]) ++ zs) ++ []).map shc
            = P.map shc ++ (shc u :: shc u :: (zs ++ []).map shc) := by
          rw [reshape2, app_assoc', map_app']
          rfl
        rw [e]
        apply det_adj m
        rw [← e, len_map']
        exact hz
      · rw [reshape2, app_nil']
        exact h
    rw [part1, K.zero_add]
    show K.add (sgn K ([] ++ P).length (K.mul (u 0) (det K m (List.map shc (([] ++ P) ++ ((u :: Q) ++ []))))))
      (K.add (sgn K (([] ++ P) ++ [u]).length
          (K.mul (u 0) (det K m (List.map shc ((([] ++ P) ++ [u]) ++ (Q ++ []))))))
        (lapS K (det K m) ((([] ++ P) ++ [u]) ++ [u]) Q [])) = K.zero
    have hP : ([] ++ P) = P := rfl
    rw [hP, rest, add_zero', app_assoc' P [u] (Q ++ []), len_app']
    show K.add (sgn K P.length _) (K.neg (sgn K P.length _)) = K.zero
    exact K.add_neg _

/-! ## Linearity in one column -/

/-- The column `α u + β v`. -/
def clin (α : R) (u : Nat → R) (β : R) (v : Nat → R) : Nat → R :=
  fun r => K.add (K.mul α (u r)) (K.mul β (v r))

theorem len_step {A : Type} (m : Nat) (pre xs suf : List A) (x : A)
    (h : (pre ++ ((x :: xs) ++ suf)).length = m + 1) : (pre ++ (xs ++ suf)).length = m := by
  rw [len_app'] at h
  rw [len_app']
  exact Nat.succ.inj h

theorem len_col {A : Type} (P M : List A) (a b : A) : (P ++ a :: M).length = (P ++ b :: M).length := by
  rw [len_app', len_app']
  rfl

theorem lin_comb (α β a b c d : R) :
    K.add (K.add (K.mul α a) (K.mul β b)) (K.add (K.mul α c) (K.mul β d))
      = K.add (K.mul α (K.add a c)) (K.mul β (K.add b d)) := by
  rw [add_mid4, ← K.distrib, ← K.distrib]

theorem lin_zero (α β : R) : K.zero = K.add (K.mul α K.zero) (K.mul β K.zero) := by
  rw [mul_zero, mul_zero, K.zero_add]

theorem swap_mul (x α a : R) : K.mul x (K.mul α a) = K.mul α (K.mul x a) := by
  rw [← K.mul_assoc, K.mul_comm x α, K.mul_assoc]

theorem term_lin (k : Nat) (x α a β b : R) :
    sgn K k (K.mul x (K.add (K.mul α a) (K.mul β b)))
      = K.add (K.mul α (sgn K k (K.mul x a))) (K.mul β (sgn K k (K.mul x b))) := by
  rw [K.distrib, sgn_add, swap_mul K x α a, swap_mul K x β b, sgn_mul K k α (K.mul x a),
    sgn_mul K k β (K.mul x b)]

theorem term_col (k : Nat) (X α a β b : R) :
    sgn K k (K.mul (K.add (K.mul α a) (K.mul β b)) X)
      = K.add (K.mul α (sgn K k (K.mul a X))) (K.mul β (sgn K k (K.mul b X))) := by
  rw [right_distrib, K.mul_assoc α a X, K.mul_assoc β b X, sgn_add, sgn_mul K k α (K.mul a X),
    sgn_mul K k β (K.mul b X)]

/-- The walk is linear in a column of the fixed tail. -/
theorem lapS_lin_suf (D : List (Nat → R) → R) (m : Nat) (S : List (Nat → R)) (u v : Nat → R) (α β : R) :
    ∀ (xs pre : List (Nat → R)),
      (∀ zs, (pre ++ (zs ++ (clin K α u β v :: S))).length = m →
        D ((pre ++ (zs ++ (clin K α u β v :: S))).map shc)
          = K.add (K.mul α (D ((pre ++ (zs ++ (u :: S))).map shc)))
              (K.mul β (D ((pre ++ (zs ++ (v :: S))).map shc)))) →
      (pre ++ (xs ++ (clin K α u β v :: S))).length = m + 1 →
      lapS K D pre xs (clin K α u β v :: S)
        = K.add (K.mul α (lapS K D pre xs (u :: S))) (K.mul β (lapS K D pre xs (v :: S)))
  | [], _, _, _ => lin_zero K α β
  | x :: xs, pre, H, hl => by
    have H' : ∀ zs, ((pre ++ [x]) ++ (zs ++ (clin K α u β v :: S))).length = m →
        D (((pre ++ [x]) ++ (zs ++ (clin K α u β v :: S))).map shc)
          = K.add (K.mul α (D (((pre ++ [x]) ++ (zs ++ (u :: S))).map shc)))
              (K.mul β (D (((pre ++ [x]) ++ (zs ++ (v :: S))).map shc))) := fun zs h => by
      rw [app_assoc' pre [x]] at h
      rw [app_assoc' pre [x], app_assoc' pre [x], app_assoc' pre [x]]
      exact H (x :: zs) h
    have hl' : ((pre ++ [x]) ++ (xs ++ (clin K α u β v :: S))).length = m + 1 := by
      rw [app_assoc' pre [x]]
      exact hl
    show K.add (sgn K pre.length (K.mul (x 0) (D ((pre ++ (xs ++ (clin K α u β v :: S))).map shc))))
        (lapS K D (pre ++ [x]) xs (clin K α u β v :: S))
      = K.add (K.mul α (K.add (sgn K pre.length (K.mul (x 0) (D ((pre ++ (xs ++ (u :: S))).map shc))))
            (lapS K D (pre ++ [x]) xs (u :: S))))
          (K.mul β (K.add (sgn K pre.length (K.mul (x 0) (D ((pre ++ (xs ++ (v :: S))).map shc))))
            (lapS K D (pre ++ [x]) xs (v :: S))))
    rw [H xs (len_step m pre xs _ x hl), term_lin, lapS_lin_suf D m S u v α β xs (pre ++ [x]) H' hl', lin_comb]

/-- The walk is linear in a column of the passed prefix. -/
theorem lapS_lin_pre (D : List (Nat → R) → R) (m : Nat) (P suf : List (Nat → R)) (u v : Nat → R) (α β : R) :
    ∀ (xs M : List (Nat → R)),
      (∀ M zs, ((P ++ clin K α u β v :: M) ++ (zs ++ suf)).length = m →
        D (((P ++ clin K α u β v :: M) ++ (zs ++ suf)).map shc)
          = K.add (K.mul α (D (((P ++ u :: M) ++ (zs ++ suf)).map shc)))
              (K.mul β (D (((P ++ v :: M) ++ (zs ++ suf)).map shc)))) →
      ((P ++ clin K α u β v :: M) ++ (xs ++ suf)).length = m + 1 →
      lapS K D (P ++ clin K α u β v :: M) xs suf
        = K.add (K.mul α (lapS K D (P ++ u :: M) xs suf)) (K.mul β (lapS K D (P ++ v :: M) xs suf))
  | [], _, _, _ => lin_zero K α β
  | x :: xs, M, H, hl => by
    have e : ∀ w : Nat → R, (P ++ w :: M) ++ [x] = P ++ w :: (M ++ [x]) := fun w => app_assoc' P (w :: M) [x]
    have hl' : ((P ++ clin K α u β v :: (M ++ [x])) ++ (xs ++ suf)).length = m + 1 := by
      rw [← e, app_assoc' (P ++ clin K α u β v :: M) [x]]
      exact hl
    show K.add (sgn K (P ++ clin K α u β v :: M).length
          (K.mul (x 0) (D (((P ++ clin K α u β v :: M) ++ (xs ++ suf)).map shc))))
        (lapS K D ((P ++ clin K α u β v :: M) ++ [x]) xs suf)
      = K.add (K.mul α (K.add (sgn K (P ++ u :: M).length
              (K.mul (x 0) (D (((P ++ u :: M) ++ (xs ++ suf)).map shc))))
            (lapS K D ((P ++ u :: M) ++ [x]) xs suf)))
          (K.mul β (K.add (sgn K (P ++ v :: M).length
              (K.mul (x 0) (D (((P ++ v :: M) ++ (xs ++ suf)).map shc))))
            (lapS K D ((P ++ v :: M) ++ [x]) xs suf)))
    rw [H M xs (len_step m _ xs suf x hl), len_col P M (clin K α u β v) u, len_col P M v u, term_lin,
      e, e, e, lapS_lin_pre D m P suf u v α β xs (M ++ [x]) H hl', lin_comb]

/-- **The determinant is linear in every column.** -/
theorem det_lin : ∀ (n : Nat) (P Q : List (Nat → R)) (u v : Nat → R) (α β : R),
    (P ++ u :: Q).length = n →
    det K n (P ++ clin K α u β v :: Q)
      = K.add (K.mul α (det K n (P ++ u :: Q))) (K.mul β (det K n (P ++ v :: Q)))
  | 0, P, Q, u, _, _, _, h => by
    rw [len_app'] at h
    exact absurd h (FTAChain.succ_ne_zero' _)
  | m + 1, P, Q, u, v, α, β, h => by
    have hw : (P ++ clin K α u β v :: Q).length = m + 1 := (len_col P Q _ u).trans h
    rw [det_succ, det_succ, det_succ, lapS_split K (det K m) [] P (clin K α u β v :: Q) [],
      lapS_split K (det K m) [] P (u :: Q) [], lapS_split K (det K m) [] P (v :: Q) []]
    have hA := lapS_lin_suf K (det K m) m (Q ++ []) u v α β P []
      (fun zs hz => by
        have e : ∀ w : Nat → R, ([] ++ (zs ++ (w :: (Q ++ [])))).map shc
            = zs.map shc ++ (shc w :: (Q ++ []).map shc) := fun w => map_app' shc zs _
        have hu : (List.map shc zs ++ shc u :: List.map shc (Q ++ [])).length = m := by
          rw [← e u, len_map']
          exact (len_col zs (Q ++ []) u (clin K α u β v)).trans hz
        rw [e, e, e]
        exact det_lin m (zs.map shc) ((Q ++ []).map shc) (shc u) (shc v) α β hu)
      (by rw [app_nil']; exact hw)
    have hB := lapS_lin_pre K (det K m) m P [] u v α β Q []
      (fun M zs hz => by
        have e : ∀ w : Nat → R, ((P ++ w :: M) ++ (zs ++ [])).map shc
            = P.map shc ++ (shc w :: (M ++ (zs ++ [])).map shc) := fun w => by
          rw [app_assoc', map_app']
          rfl
        have hu : (List.map shc P ++ shc u :: List.map shc (M ++ (zs ++ []))).length = m := by
          rw [← e u, len_map', app_assoc']
          rw [app_assoc'] at hz
          have hz' : (P ++ clin K α u β v :: (M ++ (zs ++ []))).length = m := hz
          exact (len_col P (M ++ (zs ++ [])) u (clin K α u β v)).trans hz'
        rw [e, e, e]
        exact det_lin m (P.map shc) ((M ++ (zs ++ [])).map shc) (shc u) (shc v) α β hu)
      (by rw [app_assoc', app_nil']; exact hw)
    show K.add (lapS K (det K m) [] P (clin K α u β v :: (Q ++ [])))
        (K.add (sgn K P.length (K.mul (clin K α u β v 0) (det K m ((P ++ (Q ++ [])).map shc))))
          (lapS K (det K m) (P ++ [clin K α u β v]) Q []))
      = K.add (K.mul α (K.add (lapS K (det K m) [] P (u :: (Q ++ [])))
            (K.add (sgn K P.length (K.mul (u 0) (det K m ((P ++ (Q ++ [])).map shc))))
              (lapS K (det K m) (P ++ [u]) Q []))))
          (K.mul β (K.add (lapS K (det K m) [] P (v :: (Q ++ [])))
            (K.add (sgn K P.length (K.mul (v 0) (det K m ((P ++ (Q ++ [])).map shc))))
              (lapS K (det K m) (P ++ [v]) Q []))))
    have hc : clin K α u β v 0 = K.add (K.mul α (u 0)) (K.mul β (v 0)) := rfl
    rw [hA, hB, hc, term_col, lin_comb, lin_comb]

/-! ## det only sees rows < n -/

/-- Two lists of columns that agree on rows `< k`. -/
def PeqB (k : Nat) : List (Nat → R) → List (Nat → R) → Prop
  | [], [] => True
  | [], _ :: _ => False
  | _ :: _, [] => False
  | c :: cs, c' :: cs' => (∀ r, r < k → c r = c' r) ∧ PeqB k cs cs'

theorem peq_refl (k : Nat) : ∀ a : List (Nat → R), PeqB k a a
  | [] => trivial
  | _ :: a => ⟨fun _ _ => rfl, peq_refl k a⟩

theorem peq_app (k : Nat) : ∀ a a' b b' : List (Nat → R), PeqB k a a' → PeqB k b b' → PeqB k (a ++ b) (a' ++ b')
  | [], [], _, _, _, hb => hb
  | [], _ :: _, _, _, h, _ => False.elim h
  | _ :: _, [], _, _, h, _ => False.elim h
  | _ :: a, _ :: a', b, b', h, hb => ⟨h.1, peq_app k a a' b b' h.2 hb⟩

theorem peq_map (k : Nat) : ∀ a a' : List (Nat → R), PeqB (k + 1) a a' → PeqB k (a.map shc) (a'.map shc)
  | [], [], _ => trivial
  | [], _ :: _, h => False.elim h
  | _ :: _, [], h => False.elim h
  | _ :: a, _ :: a', h => ⟨fun r hr => h.1 (r + 1) (Nat.succ_lt_succ hr), peq_map k a a' h.2⟩

theorem peq_len (k : Nat) : ∀ a a' : List (Nat → R), PeqB k a a' → a.length = a'.length
  | [], [], _ => rfl
  | [], _ :: _, h => False.elim h
  | _ :: _, [], h => False.elim h
  | _ :: a, _ :: a', h => congrArg (· + 1) (peq_len k a a' h.2)

theorem lapS_congr (D : List (Nat → R) → R) (m : Nat)
    (HD : ∀ A A', PeqB (m + 1) A A' → D (A.map shc) = D (A'.map shc)) (suf suf' : List (Nat → R))
    (hs : PeqB (m + 1) suf suf') :
    ∀ xs xs' pre pre', PeqB (m + 1) pre pre' → PeqB (m + 1) xs xs' →
      lapS K D pre xs suf = lapS K D pre' xs' suf'
  | [], [], _, _, _, _ => rfl
  | [], _ :: _, _, _, _, h => False.elim h
  | _ :: _, [], _, _, _, h => False.elim h
  | c :: cs, c' :: cs', pre, pre', hp, h => by
    show K.add (sgn K pre.length (K.mul (c 0) (D ((pre ++ (cs ++ suf)).map shc)))) (lapS K D (pre ++ [c]) cs suf)
      = K.add (sgn K pre'.length (K.mul (c' 0) (D ((pre' ++ (cs' ++ suf')).map shc))))
          (lapS K D (pre' ++ [c']) cs' suf')
    rw [peq_len _ pre pre' hp, h.1 0 (Nat.zero_lt_succ m),
      HD _ _ (peq_app _ _ _ _ _ hp (peq_app _ _ _ _ _ h.2 hs)),
      lapS_congr D m HD suf suf' hs cs cs' (pre ++ [c]) (pre' ++ [c'])
        (peq_app _ _ _ _ _ hp ⟨h.1, trivial⟩) h.2]

/-- **det n reads only rows < n.** -/
theorem det_congr : ∀ (n : Nat) (L L' : List (Nat → R)), PeqB n L L' → det K n L = det K n L'
  | 0, _, _, _ => rfl
  | m + 1, L, L', h =>
    lapS_congr K (det K m) m (fun A A' hA => det_congr m _ _ (peq_map m A A' hA)) [] [] trivial
      L L' [] [] trivial h

/-- A column that vanishes on rows `< n` gives determinant 0. -/
theorem det_zero_col (n : Nat) (P Q : List (Nat → R)) (z : Nat → R) (hl : (P ++ z :: Q).length = n)
    (hz : ∀ r, r < n → z r = K.zero) : det K n (P ++ z :: Q) = K.zero := by
  have e : det K n (P ++ z :: Q) = det K n (P ++ clin K K.zero z K.zero z :: Q) := by
    apply det_congr
    apply peq_app _ _ _ _ _ (peq_refl n P)
    refine ⟨fun r hr => ?_, peq_refl n Q⟩
    show z r = K.add (K.mul K.zero (z r)) (K.mul K.zero (z r))
    rw [zero_mul', K.zero_add, hz r hr]
  rw [e, det_lin K n P Q z z K.zero K.zero hl, zero_mul', K.zero_add]

/-! ## Alternating -/

/-- **Exchanging two adjacent columns changes the sign.** -/
theorem swap_alg (X Y : R) :
    K.add (K.mul K.one (K.add (K.mul K.one K.zero) (K.mul K.one X)))
      (K.mul K.one (K.add (K.mul K.one Y) (K.mul K.one K.zero))) = K.add X Y := by
  rw [K.one_mul (K.add (K.mul K.one K.zero) (K.mul K.one X)),
    K.one_mul (K.add (K.mul K.one Y) (K.mul K.one K.zero)), K.one_mul K.zero, K.one_mul X, K.one_mul Y,
    K.zero_add, add_zero']

theorem det_swap (n : Nat) (P Q : List (Nat → R)) (u v : Nat → R)
    (hl : (P ++ u :: v :: Q).length = n) :
    det K n (P ++ u :: v :: Q) = K.neg (det K n (P ++ v :: u :: Q)) := by
  have L1 : ∀ a b c d : Nat → R, (P ++ a :: b :: Q).length = (P ++ c :: d :: Q).length := fun a b c d => by
    rw [len_app', len_app']
    rfl
  have L2 : ∀ a b : Nat → R, (P ++ a :: b :: Q) = (P ++ [a]) ++ b :: Q := fun a b => (app_assoc' P [a] _).symm
  have h0 := det_adj K n P Q (clin K K.one u K.one v) ((L1 _ _ _ _).trans hl)
  have e1 := det_lin K n P (clin K K.one u K.one v :: Q) u v K.one K.one ((L1 _ _ _ _).trans hl)
  have eu := det_lin K n (P ++ [u]) Q u v K.one K.one (by rw [← L2]; exact (L1 _ _ _ _).trans hl)
  have ev := det_lin K n (P ++ [v]) Q u v K.one K.one (by rw [← L2]; exact (L1 _ _ _ _).trans hl)
  rw [← L2, ← L2, ← L2] at eu
  rw [← L2, ← L2, ← L2] at ev
  have zu := det_adj K n P Q u ((L1 _ _ _ _).trans hl)
  have zv := det_adj K n P Q v ((L1 _ _ _ _).trans hl)
  rw [eu, ev, zu, zv, swap_alg, h0] at e1
  exact neg_unique K _ _ e1.symm

/-- **Two equal columns anywhere give determinant 0.** -/
theorem det_eq_cols (n : Nat) (Q : List (Nat → R)) (u : Nat → R) :
    ∀ (M P : List (Nat → R)), (P ++ u :: (M ++ u :: Q)).length = n → det K n (P ++ u :: (M ++ u :: Q)) = K.zero
  | [], P, hl => det_adj K n P Q u hl
  | m :: M, P, hl => by
    have hs := det_swap K n P (M ++ u :: Q) u m hl
    have e : P ++ m :: u :: (M ++ u :: Q) = (P ++ [m]) ++ u :: (M ++ u :: Q) := (app_assoc' P [m] _).symm
    have hl' : ((P ++ [m]) ++ u :: (M ++ u :: Q)).length = n := by
      rw [← e, len_app']
      rw [len_app'] at hl
      exact hl
    show det K n (P ++ u :: m :: (M ++ u :: Q)) = K.zero
    rw [hs, e, det_eq_cols n Q u M (P ++ [m]) hl', neg_zero']

/-! ## Combinations of columns and the kernel -/

/-- `Σ_k x_k c_k`, as a column. -/
def comb : List (R × (Nat → R)) → Nat → R
  | [] => fun _ => K.zero
  | (x, c) :: rest => clin K x c K.one (comb rest)

/-- `Σ_k x_k det(P, c_k, Q)`. -/
def sumC (n : Nat) (P Q : List (Nat → R)) : List (R × (Nat → R)) → R
  | [] => K.zero
  | (x, c) :: rest => K.add (K.mul x (det K n (P ++ c :: Q))) (sumC n P Q rest)

/-- **det(P, Σ_k x_k c_k, Q) = Σ_k x_k det(P, c_k, Q).** -/
theorem det_comb (n : Nat) (P Q : List (Nat → R)) (w0 : Nat → R) (hl : (P ++ w0 :: Q).length = n) :
    ∀ ps, det K n (P ++ comb K ps :: Q) = sumC K n P Q ps
  | [] => det_zero_col K n P Q _ ((len_col P Q _ w0).trans hl) (fun _ _ => rfl)
  | (x, c) :: rest => by
    show det K n (P ++ clin K x c K.one (comb K rest) :: Q) = K.add (K.mul x (det K n (P ++ c :: Q))) (sumC K n P Q rest)
    rw [det_lin K n P Q c (comb K rest) x K.one ((len_col P Q _ w0).trans hl), K.one_mul,
      det_comb n P Q w0 hl rest]

def zipL : List R → List (Nat → R) → List (R × (Nat → R))
  | [], _ => []
  | _ :: _, [] => []
  | x :: xs, c :: cs => (x, c) :: zipL xs cs

theorem sumC_app (n : Nat) (P Q : List (Nat → R)) :
    ∀ a b, sumC K n P Q (a ++ b) = K.add (sumC K n P Q a) (sumC K n P Q b)
  | [], b => (K.zero_add _).symm
  | (x, c) :: a, b => by
    show K.add (K.mul x (det K n (P ++ c :: Q))) (sumC K n P Q (a ++ b))
      = K.add (K.add (K.mul x (det K n (P ++ c :: Q))) (sumC K n P Q a)) (sumC K n P Q b)
    rw [sumC_app n P Q a b, K.add_assoc]

/-- Terms whose column already stands in `P` contribute 0. -/
theorem sum_in_P (n : Nat) (Q : List (Nat → R)) (c0 : Nat → R) :
    ∀ (P2 P1 : List (Nat → R)) (xs : List R), ((P1 ++ P2) ++ c0 :: Q).length = n →
      sumC K n (P1 ++ P2) Q (zipL xs P2) = K.zero
  | [], _, [], _ => rfl
  | [], _, _ :: _, _ => rfl
  | _ :: _, _, [], _ => rfl
  | c :: P2, P1, x :: xs, hl => by
    have e : (P1 ++ [c]) ++ P2 = P1 ++ c :: P2 := app_assoc' P1 [c] P2
    have hl' : (((P1 ++ [c]) ++ P2) ++ c0 :: Q).length = n := by rw [e]; exact hl
    have hz : det K n ((P1 ++ c :: P2) ++ c :: Q) = K.zero := by
      rw [app_assoc']
      apply det_eq_cols K n Q c P2 P1
      have h2 : ((P1 ++ c :: P2) ++ c :: Q).length = n := (len_col _ Q c c0).trans hl
      rw [app_assoc'] at h2
      exact h2
    show K.add (K.mul x (det K n ((P1 ++ c :: P2) ++ c :: Q))) (sumC K n (P1 ++ c :: P2) Q (zipL xs P2)) = K.zero
    rw [hz, mul_zero, ← e, sum_in_P n Q c0 P2 (P1 ++ [c]) xs hl', K.zero_add]

/-- Terms whose column already stands in `Q` contribute 0. -/
theorem sum_in_Q (n : Nat) (P : List (Nat → R)) (c0 : Nat → R) :
    ∀ (Q2 Q1 : List (Nat → R)) (xs : List R), (P ++ c0 :: (Q1 ++ Q2)).length = n →
      sumC K n P (Q1 ++ Q2) (zipL xs Q2) = K.zero
  | [], _, [], _ => rfl
  | [], _, _ :: _, _ => rfl
  | _ :: _, _, [], _ => rfl
  | c :: Q2, Q1, x :: xs, hl => by
    have e : (Q1 ++ [c]) ++ Q2 = Q1 ++ c :: Q2 := app_assoc' Q1 [c] Q2
    have hl' : (P ++ c0 :: ((Q1 ++ [c]) ++ Q2)).length = n := by rw [e]; exact hl
    have hz : det K n (P ++ c :: (Q1 ++ c :: Q2)) = K.zero :=
      det_eq_cols K n Q2 c Q1 P ((len_col P _ c c0).trans hl)
    show K.add (K.mul x (det K n (P ++ c :: (Q1 ++ c :: Q2)))) (sumC K n P (Q1 ++ c :: Q2) (zipL xs Q2)) = K.zero
    rw [hz, mul_zero, ← e, sum_in_Q n P c0 Q2 (Q1 ++ [c]) xs hl', K.zero_add]

/-- **det A ≠ 0 and A x = 0 force x = 0**, for every size `n`, over a
    commutative ring without zero divisors. The matrix is `A = (P, c, Q)`, the
    coefficient of the column `c` is `x`, and `A x = 0` means that the column
    `Σ_k x_k c_k` vanishes on the `n` rows. Since `c` can be any column, every
    coefficient is 0. -/
theorem kernel_trivial (hK : NoZD K) (n : Nat) (P Q : List (Nat → R)) (c : Nat → R) (xP xQ : List R) (x : R)
    (hl : (P ++ c :: Q).length = n) (hdet : det K n (P ++ c :: Q) ≠ K.zero)
    (hAx : ∀ r, r < n → comb K (zipL xP P ++ (x, c) :: zipL xQ Q) r = K.zero) : x = K.zero := by
  have h0 := det_zero_col K n P Q _ ((len_col P Q _ c).trans hl) hAx
  rw [det_comb K n P Q c hl, sumC_app] at h0
  have hP : sumC K n P Q (zipL xP P) = K.zero := sum_in_P K n Q c P [] xP hl
  have hQ : sumC K n P Q (zipL xQ Q) = K.zero := sum_in_Q K n P c Q [] xQ hl
  rw [hP] at h0
  have h1 : K.add K.zero (K.add (K.mul x (det K n (P ++ c :: Q))) (sumC K n P Q (zipL xQ Q))) = K.zero := h0
  rw [hQ, K.zero_add, add_zero'] at h1
  cases hK x _ h1 with
  | inl hx => exact hx
  | inr hd => exact absurd hd hdet

end Det
end DetN

#print axioms DetN.app_nil'
#print axioms DetN.app_assoc'
#print axioms DetN.map_app'
#print axioms DetN.len_app'
#print axioms DetN.len_map'
#print axioms DetN.neg_zero'
#print axioms DetN.neg_add'
#print axioms DetN.mul_neg'
#print axioms DetN.sgn_zero
#print axioms DetN.sgn_add
#print axioms DetN.sgn_mul
#print axioms DetN.det_succ
#print axioms DetN.lapS_split
#print axioms DetN.len_fix
#print axioms DetN.lapS_vanish
#print axioms DetN.reshape2
#print axioms DetN.det_adj
#print axioms DetN.len_step
#print axioms DetN.len_col
#print axioms DetN.lin_comb
#print axioms DetN.lin_zero
#print axioms DetN.swap_mul
#print axioms DetN.term_lin
#print axioms DetN.term_col
#print axioms DetN.lapS_lin_suf
#print axioms DetN.lapS_lin_pre
#print axioms DetN.det_lin
#print axioms DetN.peq_refl
#print axioms DetN.peq_app
#print axioms DetN.peq_map
#print axioms DetN.peq_len
#print axioms DetN.lapS_congr
#print axioms DetN.det_congr
#print axioms DetN.det_zero_col
#print axioms DetN.swap_alg
#print axioms DetN.det_swap
#print axioms DetN.det_eq_cols
#print axioms DetN.det_comb
#print axioms DetN.sumC_app
#print axioms DetN.sum_in_P
#print axioms DetN.sum_in_Q
#print axioms DetN.kernel_trivial

Listing 362: numeric_det.py: integer checks around det and Koszul

numeric_det.py

#!/usr/bin/env python3
"""T21 numerics (partial): checks around det d != 0 => injective, and Koszul exactness.

Python standard library only, fixed seed. What this file does NOT do: the
cohomology H^1, H^2 of Bianchi groups and their Hecke operators (see
SECTION_DET.tex for why).

Writes work/NUMERIC_DET.txt next to this script.
"""
import itertools
import os
import random
from fractions import Fraction

HERE = os.path.dirname(os.path.abspath(__file__))


def det(M):
    """Exact determinant by fraction-free elimination (Bareiss)."""
    A = [list(map(Fraction, r)) for r in M]
    n = len(A)
    d = Fraction(1)
    for k in range(n):
        p = next((i for i in range(k, n) if A[i][k] != 0), None)
        if p is None:
            return Fraction(0)
        if p != k:
            A[k], A[p] = A[p], A[k]
            d = -d
        d *= A[k][k]
        for i in range(k + 1, n):
            f = A[i][k] / A[k][k]
            A[i] = [x - f * y for x, y in zip(A[i], A[k])]
    return d


def kernel_dim(M):
    A = [list(map(Fraction, r)) for r in M]
    n, m = len(A), len(A[0])
    r = 0
    for c in range(m):
        p = next((i for i in range(r, n) if A[i][c] != 0), None)
        if p is None:
            continue
        A[r], A[p] = A[p], A[r]
        for i in range(n):
            if i != r and A[i][c] != 0:
                f = A[i][c] / A[r][c]
                A[i] = [x - f * y for x, y in zip(A[i], A[r])]
        r += 1
    return m - r


def main():
    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(21)
    out.append("1. General n over Z (exact rationals): det != 0  =>  kernel = 0.")
    for n in (3, 4, 5, 6):
        bad = 0
        tried = 0
        for _ in range(2000):
            M = [[rng.randint(-3, 3) for _ in range(n)] for _ in range(n)]
            if det(M) != 0:
                tried += 1
                if kernel_dim(M) != 0:
                    bad += 1
        out.append(f"   n = {n}: {tried} random matrices with det != 0, {bad} with nonzero kernel")
        check(f"n = {n}: no counterexample", bad == 0)

    out.append("2. Zero divisors break it: over Z/6, 2x2 matrices with det != 0 but a nonzero kernel vector.")
    found = None
    for a, b, c, e in itertools.product(range(6), repeat=4):
        dd = (a * e - b * c) % 6
        if dd == 0:
            continue
        for x, y in itertools.product(range(6), repeat=2):
            if (x, y) != (0, 0) and (a * x + b * y) % 6 == 0 and (c * x + e * y) % 6 == 0:
                found = ((a, b, c, e), dd, (x, y))
                break
        if found:
            break
    out.append(f"   example: d = [[{found[0][0]},{found[0][1]}],[{found[0][2]},{found[0][3]}]], "
               f"det = {found[1]} mod 6, kernel vector {found[2]}")
    check("the no-zero-divisor hypothesis of inj2 cannot be dropped", found is not None)

    out.append("3. Koszul complex of (x, y) over Z: exact in degrees 1, 2 for regular pairs.")
    bad = 0
    pairs = 0
    for x in range(1, 13):
        for y in range(1, 13):
            from math import gcd
            regular = gcd(x, y) == 1          # y is a non-zero-divisor on Z/x
            if not regular:
                continue
            pairs += 1
            for a in range(-20, 21):
                for b in range(-20, 21):
                    if a * x + b * y == 0:
                        # must be d2(r) = (-r y, r x)
                        if b % x != 0 or a != -(b // x) * y:
                            bad += 1
    out.append(f"   {pairs} regular pairs, cycles checked in [-20,20]^2: {bad} not boundaries")
    check("H_1 = 0 for every regular pair checked", bad == 0)

    out.append("4. Bianchi groups (H^1, H^2, torsion, Hecke T_p): see numeric_bianchi.py -> NUMERIC_BIANCHI.txt.")
    out.append(f"ALL {'PASS' if ok else 'FAIL'}")
    text = "\n".join(out) + "\n"
    with open(os.path.join(HERE, "NUMERIC_DET.txt"), "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 363: numeric_bianchi.py: \(\Gamma _0(\pi )\) in Bianchi groups, \(H^1\), torsion, Hecke operators

numeric_bianchi.py

#!/usr/bin/env python3
"""T21 numerics: cohomology of Gamma_0(p) in Bianchi groups PSL_2(O_d), and Hecke operators.

Python standard library only (no randomness). This is a computation, not a proof.
Input: a standard presentation (generators and relations) of PSL_2(O_d), with
explicit matrices for the generators; the source is recorded in PRESENTATIONS.
Every relator is checked on the matrices before use.

Method, for a prime ideal (pi) of O_d:
  * cosets of Gamma_0(pi) = points of P^1(O/pi), acted on by the generators;
  * Reidemeister-Schreier: generators and relators of Gamma_0(pi);
  * H_1(Gamma_0(pi), Z) by Smith normal form (rank and torsion);
    H^1(Gamma_0(pi), Z) = Hom(H_1, Z) (rank), and the torsion of H_1 is the Ext part of H^2;
  * Hom(Gamma_0(pi), Q), its cuspidal part (vanishing on the parabolic subgroups of the
    two cusps 0 and infinity), and Hecke operators T_l acting on it, with words for matrices
    found by the Euclidean algorithm of O_d.
"""
import os
from fractions import Fraction

HERE = os.path.dirname(os.path.abspath(__file__))


# ------------------------------------------------------------ the rings O_d
class Ring:
    """O_d = Z[theta], theta = i (d = 1), sqrt -2 (d = 2), (1 + sqrt -d)/2 (d = 7, 11) or omega = (-1 + sqrt -3)/2 (d = 3). Elements (x, y) = x + y theta."""

    def __init__(self, d):
        self.d = d
        # theta^2 = c0 + c1 theta
        self.c0, self.c1 = {1: (-1, 0), 2: (-2, 0), 3: (-1, -1), 7: (-2, 1), 11: (-3, 1)}[d]
        self.units = self._units()

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

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

    def sub(self, a, b):
        return (a[0] - b[0], a[1] - b[1])

    def mul(self, a, b):
        x, y = a
        z, w = b
        # (x + y t)(z + w t) = xz + (xw + yz) t + yw t^2
        return (x * z + y * w * self.c0, x * w + y * z + y * w * self.c1)

    def conj(self, a):
        x, y = a
        if self.d in (1, 2):
            return (x, -y)
        if self.d in (7, 11):
            return (x + y, -y)        # conj(theta) = 1 - theta
        return (x - y, -y)            # conj(omega) = -1 - omega

    def norm(self, a):
        p = self.mul(a, self.conj(a))
        assert p[1] == 0
        return p[0]

    def _units(self):
        return [u for u in [(x, y) for x in range(-1, 2) for y in range(-1, 2)] if u != (0, 0) and self.norm(u) == 1]

    def divround(self, a, b):
        """Nearest q with N(a - q b) < N(b) (norm-Euclidean for d = 1, 3)."""
        n = self.norm(b)
        p = self.mul(a, self.conj(b))
        best = None
        for qx in (p[0] // n, p[0] // n + 1):
            for qy in (p[1] // n, p[1] // n + 1):
                q = (qx, qy)
                r = self.sub(a, self.mul(q, b))
                if best is None or self.norm(r) < best[0]:
                    best = (self.norm(r), q)
        assert best[0] < n
        return best[1]

    def divides(self, b, a):
        """b | a in O."""
        n = self.norm(b)
        p = self.mul(a, self.conj(b))
        return p[0] % n == 0 and p[1] % n == 0

    def exact_div(self, a, b):
        n = self.norm(b)
        p = self.mul(a, self.conj(b))
        assert p[0] % n == 0 and p[1] % n == 0
        return (p[0] // n, p[1] // n)


def mmul(R, A, B):
    return ((R.add(R.mul(A[0][0], B[0][0]), R.mul(A[0][1], B[1][0])),
             R.add(R.mul(A[0][0], B[0][1]), R.mul(A[0][1], B[1][1]))),
            (R.add(R.mul(A[1][0], B[0][0]), R.mul(A[1][1], B[1][0])),
             R.add(R.mul(A[1][0], B[0][1]), R.mul(A[1][1], B[1][1]))))


def minv(R, A):
    """Inverse of a determinant-1 matrix."""
    return ((A[1][1], R.neg(A[0][1])), (R.neg(A[1][0]), A[0][0]))


ONE, ZERO = (1, 0), (0, 0)
I2 = ((ONE, ZERO), (ZERO, ONE))


def proj_eq(R, A, B):
    """Equality in PSL_2: A = u B for a unit u with u^2 = 1 (u = +-1)."""
    for u in ((1, 0), (-1, 0)):
        if all(A[i][j] == R.mul(u, B[i][j]) for i in range(2) for j in range(2)):
            return True
    return False


# ----------------------------------------------------- presentations (input)
def presentation(d):
    if d == "3s":
        R, gens, _, _ = presentation(3)
        # Swan's presentation in the generators T, U, A and L_Swan = diag(tau^-1, tau) = l^-1 (letters: L = l^-1)
        rels = ["tuTU", "lll", "aLaL", "aa", "tatata", "uaLuaLuaL", "luLT", "ltLut"]
        src = ("R. G. Swan, Adv. Math. 6 (1971), as quoted in arXiv:2208.14499, Section 3: Bi(3) = <T, U, L, A | [T,U] = L^3 = "
               "(AL)^2 = A^2 = (TA)^3 = (UAL)^3 = 1, L^-1 U L = T, L^-1 T L = T^-1 U^-1>")
        return R, gens, rels, src
    R = Ring(d)
    if d == 1:
        gens = {
            "a": ((ZERO, (-1, 0)), (ONE, ZERO)),
            "t": ((ONE, ONE), (ZERO, ONE)),
            "u": ((ONE, (0, 1)), (ZERO, ONE)),
            "l": (((0, -1), ZERO), (ZERO, (0, 1))),
        }
        rels = ["aa", "ll", "alal", "tltl", "ulul", "atatat", "ualualual", "tuTU"]
        src = ("B. Fine, Algebraic Theory of the Bianchi Groups (1989), presentation of PSL_2(O_1); "
               "R. G. Swan, Adv. Math. 6 (1971)")
    elif d == 2:
        gens = {
            "a": ((ZERO, (-1, 0)), (ONE, ZERO)),
            "t": ((ONE, ONE), (ZERO, ONE)),
            "u": ((ONE, (0, 1)), (ZERO, ONE)),
        }
        rels = ["aa", "atatat", "UauaUaua", "tuTU"]
        src = ("R. G. Swan, Adv. Math. 6 (1971); B. Fine, Algebraic Theory of the Bianchi Groups (1989): "
               "PSL_2(O_2) = <a, t, u | a^2 = (at)^3 = (u^-1 a u a)^2 = [t, u] = 1>")
    elif d in (7, 11):
        gens = {
            "a": ((ZERO, (-1, 0)), (ONE, ZERO)),
            "t": ((ONE, ONE), (ZERO, ONE)),
            "u": ((ONE, (0, 1)), (ZERO, ONE)),
        }
        rels = ["aa", "atatat", "tuTU", "atUau" * (2 if d == 7 else 3)]
        src = ("R. G. Swan, Adv. Math. 6 (1971); B. Fine (1989): PSL_2(O_%d) = <a, t, u | a^2 = (at)^3 = [t, u] = "
               "(a t u^-1 a u)^%d = 1>" % (d, 2 if d == 7 else 3))
    elif d == 3:
        w = (0, 1)
        gens = {
            "a": ((ZERO, (-1, 0)), (ONE, ZERO)),
            "t": ((ONE, ONE), (ZERO, ONE)),
            "u": ((ONE, w), (ZERO, ONE)),
            "l": ((w, ZERO), (ZERO, R.mul(w, w))),
        }
        rels = saturated_relators(R, gens, SAT_LEN)
        src = ("NOT a standard presentation: all reduced words of length <= %d in a, t, u, l that are "
               "+-1 on the matrices (completeness not certified)" % SAT_LEN)
    else:
        raise ValueError("no presentation entered for d = %d" % d)
    return R, gens, rels, src


SAT_LEN = 6


def saturated_relators(R, gens, maxlen):
    """All reduced words of length <= maxlen equal to +-1, one per cyclic/inverse class."""
    letters = "atulATUL"
    mats = {ch: (gens[ch] if ch.islower() else minv(R, gens[ch.lower()])) for ch in letters}
    out = []
    seen = set()
    frontier = [("", I2)]
    for _ in range(maxlen):
        nf = []
        for W, M in frontier:
            for ch in letters:
                if W and W[-1].lower() == ch.lower() and W[-1] != ch:
                    continue
                W2 = W + ch
                M2 = mmul(R, M, mats[ch])
                if proj_eq(R, M2, I2):
                    variants = [W2[k:] + W2[:k] for k in range(len(W2))]
                    inv = invert(W2)
                    variants += [inv[k:] + inv[:k] for k in range(len(inv))]
                    key = min(variants)
                    if key not in seen:
                        seen.add(key)
                        out.append(W2)
                else:
                    nf.append((W2, M2))
        frontier = nf
    return out


def word_matrix(R, gens, w):
    M = I2
    for ch in w:
        g = gens[ch.lower()]
        M = mmul(R, M, g if ch.islower() else minv(R, g))
    return M


# ------------------------------------------------------- words for matrices
def to_word(R, gens, M):
    """Write M in PSL_2(O_d) as a word in a, t, u, l (d = 1), by the Euclidean algorithm."""
    word = []
    a = gens["a"]
    M0 = M
    while M[1][0] != ZERO:
        if R.norm(M[0][0]) < R.norm(M[1][0]):
            # M = a^{-1} (a M);  a M = [[-c, -d], [a, b]]
            M = mmul(R, a, M)
            word.append("A")
            continue
        q = R.divround(M[0][0], M[1][0])
        # M = T(q) (T(-q) M)
        word += ["t"] * q[0] if q[0] >= 0 else ["T"] * (-q[0])
        word += ["u"] * q[1] if q[1] >= 0 else ["U"] * (-q[1])
        T = ((ONE, R.neg(q)), (ZERO, ONE))
        M = mmul(R, T, M)
    # M = [[e, b], [0, e^-1]] with e a unit; peel a power of l so that e = +-1
    l = gens.get("l")             # d = 2, 7, 11: units are +-1, no l needed
    for k in range(6):
        if M[0][0] in ((1, 0), (-1, 0)):
            break
        word.append("l")
        M = mmul(R, minv(R, l), M)
    e = M[0][0]
    assert e in ((1, 0), (-1, 0))
    b = R.mul(e, M[0][1])
    word += ["t"] * b[0] if b[0] >= 0 else ["T"] * (-b[0])
    word += ["u"] * b[1] if b[1] >= 0 else ["U"] * (-b[1])
    # undo: the letters were peeled from the left of M0
    w = "".join(word)
    assert proj_eq(R, word_matrix(R, gens, w), M0), "word does not reproduce the matrix"
    return w


# --------------------------------------------------------------- residues
class Residue:
    """O/(pi) for a prime element pi."""

    def __init__(self, R, pi):
        self.R, self.pi = R, pi
        self.q = R.norm(pi)
        q = self.q
        self.prime_norm = all(q % k for k in range(2, int(q ** 0.5) + 1)) and q > 1
        if self.prime_norm:
            # theta = r mod pi
            self.r = next(r for r in range(q) if R.divides(pi, R.sub((0, 1), (r, 0))))
        else:
            self.p = int(round(q ** 0.5))
            assert self.p * self.p == q and (pi == (self.p, 0) or pi == (-self.p, 0))

    def red(self, a):
        if self.prime_norm:
            return (a[0] + a[1] * self.r) % self.q
        return (a[0] % self.p, a[1] % self.p)

    def elements(self):
        if self.prime_norm:
            return list(range(self.q))
        return [(x, y) for x in range(self.p) for y in range(self.p)]

    def mul(self, x, y):
        if self.prime_norm:
            return x * y % self.q
        a = self.R.mul(x, y)
        return (a[0] % self.p, a[1] % self.p)

    def add(self, x, y):
        if self.prime_norm:
            return (x + y) % self.q
        return ((x[0] + y[0]) % self.p, (x[1] + y[1]) % self.p)

    def zero(self):
        return 0 if self.prime_norm else (0, 0)

    def one(self):
        return 1 if self.prime_norm else (1, 0)

    def inv(self, x):
        for y in self.elements():
            if self.mul(x, y) == self.one():
                return y
        raise ZeroDivisionError


def p1_points(F):
    pts = [(F.one(), F.zero())]                      # (1 : 0)
    pts += [(c, F.one()) for c in F.elements()]      # (c : 1)
    return pts


def p1_norm(F, c, d):
    if d != F.zero():
        return (F.mul(c, F.inv(d)), F.one())
    return (F.one(), F.zero())


def p1_act(F, pt, M):
    """Row vector (c, d) times M."""
    c, d = pt
    m = [[F.red(M[i][j]) for j in range(2)] for i in range(2)]
    return p1_norm(F, F.add(F.mul(c, m[0][0]), F.mul(d, m[1][0])), F.add(F.mul(c, m[0][1]), F.mul(d, m[1][1])))


# ---------------------------------------------------- Reidemeister-Schreier
class Gamma0:
    def __init__(self, R, gens, rels, pi):
        self.R, self.gens, self.rels = R, gens, rels
        self.F = Residue(R, pi)
        self.pi = pi
        pts = p1_points(self.F)
        self.index = {p: k for k, p in enumerate(pts)}
        self.n = len(pts)
        self.base = self.index[(self.F.zero(), self.F.one())]        # (0 : 1): Gamma_0 is its stabiliser
        self.G = sorted(gens)
        self.act = {g: [self.index[p1_act(self.F, p, gens[g])] for p in pts] for g in self.G}
        self.inv = {g: [0] * self.n for g in self.G}
        for g in self.G:
            for c in range(self.n):
                self.inv[g][self.act[g][c]] = c
        # spanning tree (BFS) with coset representatives as words
        self.rep = {self.base: ""}
        tree = set()
        frontier = [self.base]
        while frontier:
            nxt = []
            for c in frontier:
                for g in self.G:
                    c2 = self.act[g][c]
                    if c2 not in self.rep:
                        self.rep[c2] = self.rep[c] + g
                        tree.add((c, g))
                        nxt.append(c2)
                    c3 = self.inv[g][c]
                    if c3 not in self.rep:
                        self.rep[c3] = self.rep[c] + g.upper()
                        tree.add((c3, g))
                        nxt.append(c3)
            frontier = nxt
        assert len(self.rep) == self.n
        self.cols = [(c, g) for c in range(self.n) for g in self.G if (c, g) not in tree]
        self.col = {k: i for i, k in enumerate(self.cols)}

    def rewrite(self, w, c=None):
        """Abelianised Reidemeister-Schreier rewriting of the word w read from coset c."""
        c = self.base if c is None else c
        v = {}
        for ch in w:
            g = ch.lower()
            if ch.islower():
                k = self.col.get((c, g))
                if k is not None:
                    v[k] = v.get(k, 0) + 1
                c = self.act[g][c]
            else:
                c2 = self.inv[g][c]
                k = self.col.get((c2, g))
                if k is not None:
                    v[k] = v.get(k, 0) - 1
                c = c2
        return v, c

    def relation_matrix(self):
        rows = []
        for c in range(self.n):
            for r in self.rels:
                v, c2 = self.rewrite(r, c)
                assert c2 == c
                rows.append(v)
        return rows


# --------------------------------------------------------- integer algebra
def smith_diagonal(rows, ncols):
    """Invariant factors of the integer matrix (list of sparse dict rows)."""
    A = [[r.get(j, 0) for j in range(ncols)] for r in rows if any(r.values())]
    diag = []
    m = len(A)
    nc = ncols
    r0 = 0
    while True:
        # find smallest nonzero entry in the remaining block
        best = None
        for i in range(r0, m):
            for j in range(r0, nc):
                x = A[i][j]
                if x and (best is None or abs(x) < best[0]):
                    best = (abs(x), i, j)
        if best is None:
            break
        _, i, j = best
        A[r0], A[i] = A[i], A[r0]
        for row in A:
            row[r0], row[j] = row[j], row[r0]
        while True:
            p = A[r0][r0]
            done = True
            for i in range(r0 + 1, m):
                if A[i][r0]:
                    f = A[i][r0] // p
                    if f:
                        A[i] = [x - f * y for x, y in zip(A[i], A[r0])]
                    if A[i][r0]:
                        done = False
            for j in range(r0 + 1, nc):
                if A[r0][j]:
                    f = A[r0][j] // p
                    if f:
                        for row in A:
                            row[j] -= f * row[r0]
                    if A[r0][j]:
                        done = False
            if done:
                # divisibility of the rest by p
                bad = next(((i, j) for i in range(r0 + 1, m) for j in range(r0 + 1, nc) if A[i][j] % p), None)
                if bad is None:
                    break
                A[r0] = [x + y for x, y in zip(A[r0], A[bad[0]])]
                continue
            # move the smallest nonzero of row/col r0 to the pivot
            best = (abs(p), r0, r0)
            for i in range(r0, m):
                if A[i][r0] and abs(A[i][r0]) < best[0]:
                    best = (abs(A[i][r0]), i, r0)
            for j in range(r0, nc):
                if A[r0][j] and abs(A[r0][j]) < best[0]:
                    best = (abs(A[r0][j]), r0, j)
            _, i, j = best
            A[r0], A[i] = A[i], A[r0]
            for row in A:
                row[r0], row[j] = row[j], row[r0]
        diag.append(abs(A[r0][r0]))
        r0 += 1
        if r0 >= m or r0 >= nc:
            break
    return diag


def nullspace_q(rows, ncols):
    """Basis of {x in Q^ncols : rows . x = 0}."""
    A = [[Fraction(r.get(j, 0)) for j in range(ncols)] for r in rows if any(r.values())]
    piv = []
    rk = 0
    for c in range(ncols):
        p = next((i for i in range(rk, len(A)) if A[i][c] != 0), None)
        if p is None:
            continue
        A[rk], A[p] = A[p], A[rk]
        inv = 1 / A[rk][c]
        A[rk] = [x * inv for x in A[rk]]
        for i in range(len(A)):
            if i != rk and A[i][c] != 0:
                f = A[i][c]
                A[i] = [x - f * y for x, y in zip(A[i], A[rk])]
        piv.append(c)
        rk += 1
    free = [c for c in range(ncols) if c not in piv]
    basis = []
    for fcol in free:
        x = [Fraction(0)] * ncols
        x[fcol] = Fraction(1)
        for i, c in enumerate(piv):
            x[c] = -A[i][fcol]
        basis.append(x)
    return basis


def solve_in_span(basis, v):
    """Coordinates of v in the span of basis (exact)."""
    n = len(basis)
    m = len(v)
    # columns = basis vectors; solve B c = v
    A = [[basis[j][i] for j in range(n)] + [v[i]] for i in range(m)]
    rk = 0
    piv = []
    for c in range(n):
        p = next((i for i in range(rk, m) if A[i][c] != 0), None)
        if p is None:
            continue
        A[rk], A[p] = A[p], A[rk]
        inv = 1 / A[rk][c]
        A[rk] = [x * inv for x in A[rk]]
        for i in range(m):
            if i != rk and A[i][c] != 0:
                f = A[i][c]
                A[i] = [x - f * y for x, y in zip(A[i], A[rk])]
        piv.append(c)
        rk += 1
    assert all(A[i][n] == 0 for i in range(rk, m)), "vector not in span"
    coords = [Fraction(0)] * n
    for i, c in enumerate(piv):
        coords[c] = A[i][n]
    return coords


def charpoly(M):
    """Characteristic polynomial of a rational square matrix (Faddeev-LeVerrier), coefficients high to low."""
    n = len(M)
    if n == 0:
        return [Fraction(1)]
    coeffs = [Fraction(1)]
    Mk = [[Fraction(0)] * n for _ in range(n)]
    I = [[Fraction(int(i == j)) for j in range(n)] for i in range(n)]
    for k in range(1, n + 1):
        AM = [[sum(M[i][t] * Mk[t][j] for t in range(n)) for j in range(n)] for i in range(n)]
        Mk = [[AM[i][j] + coeffs[-1] * I[i][j] for j in range(n)] for i in range(n)]
        AMk = [[sum(M[i][t] * Mk[t][j] for t in range(n)) for j in range(n)] for i in range(n)]
        ck = -sum(AMk[i][i] for i in range(n)) / k
        coeffs.append(ck)
    return coeffs


def det_q(M):
    n = len(M)
    A = [row[:] for row in M]
    d = Fraction(1)
    for c in range(n):
        p = next((i for i in range(c, n) if A[i][c] != 0), None)
        if p is None:
            return Fraction(0)
        if p != c:
            A[c], A[p] = A[p], A[c]
            d = -d
        d *= A[c][c]
        for i in range(c + 1, n):
            f = A[i][c] / A[c][c]
            A[i] = [x - f * y for x, y in zip(A[i], A[c])]
    return d


# --------------------------------------------------------------- Hecke
class Cohomology:
    def __init__(self, R, gens, rels, pi):
        self.R = R
        self.gens = gens
        self.G0 = Gamma0(R, gens, rels, pi)
        self.rows = self.G0.relation_matrix()
        nc = len(self.G0.cols)
        self.ncols = nc
        self.diag = smith_diagonal(self.rows, nc)
        self.rank = nc - len(self.diag)
        self.torsion = [x for x in self.diag if x > 1]
        self.hom = nullspace_q(self.rows, nc)           # Hom(Gamma_0, Q)
        assert len(self.hom) == self.rank
        # Schreier generators as matrices
        self.smat = []
        for (c, g) in self.G0.cols:
            w = self.G0.rep[c] + g + invert(self.G0.rep[self.G0.act[g][c]])
            self.smat.append(word_matrix(R, gens, w))
        pi_ = pi
        theta = (0, 1)
        self.parabolic = [gens["t"], gens["u"],
                          ((ONE, ZERO), (pi_, ONE)), ((ONE, ZERO), (R.mul(theta, pi_), ONE))]
        # cuspidal subspace: phi vanishing on the parabolic elements
        cons = [self.eval_vec(P) for P in self.parabolic]
        if self.hom:
            Hm = [[sum(c.get(k, 0) * h[k] for k in c) for h in self.hom] for c in cons]
            sol = nullspace_q([{j: x for j, x in enumerate(r) if x} for r in Hm], len(self.hom))
            self.cusp = [[sum(s[j] * self.hom[j][k] for j in range(len(self.hom))) for k in range(nc)] for s in sol]
        else:
            self.cusp = []

    def eval_vec(self, M):
        """Abelianised class of M in Gamma_0, as a sparse vector on Schreier generators."""
        w = to_word(self.R, self.gens, M)
        v, c = self.G0.rewrite(w)
        assert c == self.G0.base, "matrix not in Gamma_0"
        return v

    def hecke(self, ell):
        """T_ell on the cuspidal subspace (matrix in the basis self.cusp)."""
        R = self.R
        F = Residue(R, ell)
        reps = [((ONE, r), (ZERO, ell)) for r in residue_lifts(R, F)] + [((ell, ZERO), (ZERO, ONE))]
        cols = []
        for b in self.cusp:
            # (T phi)(s) for each Schreier generator s
            vals = []
            for S in self.smat:
                tot = Fraction(0)
                for D in reps:
                    DS = mmul(R, D, S)
                    found = False
                    for E in reps:
                        X = mmul(R, DS, adj(R, E))
                        if all(R.divides(ell, X[i][j]) for i in range(2) for j in range(2)):
                            Y = tuple(tuple(R.exact_div(X[i][j], ell) for j in range(2)) for i in range(2))
                            if self.G0.F.red(Y[1][0]) == self.G0.F.zero():
                                v = self.eval_vec(Y)
                                tot += sum(b[k] * x for k, x in v.items())
                                found = True
                                break
                    assert found
                vals.append(tot)
            cols.append(solve_in_span(self.cusp, vals))
        n = len(self.cusp)
        return [[cols[j][i] for j in range(n)] for i in range(n)]


def adj(R, E):
    return ((E[1][1], R.neg(E[0][1])), (R.neg(E[1][0]), E[0][0]))


def invert(w):
    return "".join(ch.upper() if ch.islower() else ch.lower() for ch in reversed(w))


def residue_lifts(R, F):
    if F.prime_norm:
        return [(x, 0) for x in range(F.q)]
    return [(x, y) for x in range(F.p) for y in range(F.p)]


def primes_of(R, maxnorm):
    """One generator for each prime ideal of norm <= maxnorm (up to units)."""
    seen = []
    out = []
    for x in range(-20, 21):
        for y in range(-20, 21):
            a = (x, y)
            n = R.norm(a)
            if n < 2 or n > maxnorm:
                continue
            # a is prime if its norm is a prime, or the square of an inert rational prime
            isp = all(n % k for k in range(2, int(n ** 0.5) + 1))
            if not isp:
                p = int(round(n ** 0.5))
                if p * p != n or not all(p % k for k in range(2, int(p ** 0.5) + 1)):
                    continue
                if a not in [R.mul(u, (p, 0)) for u in R.units]:
                    continue
                # p inert: no element of norm p
                if any(R.norm((s, t)) == p for s in range(-p, p + 1) for t in range(-p, p + 1)):
                    continue
                a = (p, 0)
            assoc = {R.mul(u, a) for u in R.units}
            if any(b in assoc for b in seen):
                continue
            seen.append(a)
            out.append((n, a))
    out.sort()
    return [a for _, a in out]


# ------------------------------------------------ linear algebra mod p
def nullspace_mod(rows, ncols, P):
    A = [[r.get(j, 0) % P for j in range(ncols)] for r in rows if any(r.values())]
    piv = []
    rk = 0
    for c in range(ncols):
        p = next((i for i in range(rk, len(A)) if A[i][c]), None)
        if p is None:
            continue
        A[rk], A[p] = A[p], A[rk]
        inv = pow(A[rk][c], P - 2, P)
        A[rk] = [x * inv % P for x in A[rk]]
        for i in range(len(A)):
            if i != rk and A[i][c]:
                f = A[i][c]
                A[i] = [(x - f * y) % P for x, y in zip(A[i], A[rk])]
        piv.append(c)
        rk += 1
    free = [c for c in range(ncols) if c not in piv]
    basis = []
    for fcol in free:
        x = [0] * ncols
        x[fcol] = 1
        for i, c in enumerate(piv):
            x[c] = (-A[i][fcol]) % P
        basis.append(x)
    return basis


def solve_mod(basis, v, P):
    n, m = len(basis), len(v)
    A = [[basis[j][i] % P for j in range(n)] + [v[i] % P] for i in range(m)]
    rk = 0
    piv = []
    for c in range(n):
        p = next((i for i in range(rk, m) if A[i][c]), None)
        if p is None:
            continue
        A[rk], A[p] = A[p], A[rk]
        inv = pow(A[rk][c], P - 2, P)
        A[rk] = [x * inv % P for x in A[rk]]
        for i in range(m):
            if i != rk and A[i][c]:
                f = A[i][c]
                A[i] = [(x - f * y) % P for x, y in zip(A[i], A[rk])]
        piv.append(c)
        rk += 1
    assert all(A[i][n] == 0 for i in range(rk, m)), "not in span mod p"
    out = [0] * n
    for i, c in enumerate(piv):
        out[c] = A[i][n]
    return out


def charpoly_mod(M, P):
    """Characteristic polynomial mod P (Faddeev-LeVerrier needs division by k < P)."""
    n = len(M)
    coeffs = [1]
    Mk = [[0] * n for _ in range(n)]
    for k in range(1, n + 1):
        AM = [[sum(M[i][t] * Mk[t][j] for t in range(n)) % P for j in range(n)] for i in range(n)]
        Mk = [[(AM[i][j] + (coeffs[-1] if i == j else 0)) % P for j in range(n)] for i in range(n)]
        AMk = [[sum(M[i][t] * Mk[t][j] for t in range(n)) % P for j in range(n)] for i in range(n)]
        tr = sum(AMk[i][i] for i in range(n)) % P
        coeffs.append((-tr * pow(k, P - 2, P)) % P)
    return coeffs


def sym(x, P):
    return x - P if x > P // 2 else x


class CohomologyMod:
    """Rank of H_1, Hom(Gamma_0, F_P), cuspidal part and Hecke operators, all mod a large prime P."""

    def __init__(self, R, gens, rels, pi, P):
        self.R, self.gens, self.P = R, gens, P
        self.G0 = Gamma0(R, gens, rels, pi)
        rows = self.G0.relation_matrix()
        nc = len(self.G0.cols)
        self.hom = nullspace_mod(rows, nc, P)
        self.b1 = len(self.hom)
        self.smat = []
        for (c, g) in self.G0.cols:
            w = self.G0.rep[c] + g + invert(self.G0.rep[self.G0.act[g][c]])
            self.smat.append(word_matrix(R, gens, w))
        theta = (0, 1)
        parab = [gens["t"], gens["u"], ((ONE, ZERO), (pi, ONE)), ((ONE, ZERO), (R.mul(theta, pi), ONE))]
        cons = [self.eval_vec(M) for M in parab]
        if self.hom:
            Hm = [{j: sum(c.get(k, 0) * h[k] for k in c) % P for j, h in enumerate(self.hom)} for c in cons]
            sol = nullspace_mod(Hm, len(self.hom), P)
            self.cusp = [[sum(s[j] * self.hom[j][k] for j in range(len(self.hom))) % P for k in range(nc)] for s in sol]
        else:
            self.cusp = []

    def eval_vec(self, M):
        w = to_word(self.R, self.gens, M)
        v, c = self.G0.rewrite(w)
        assert c == self.G0.base
        return v

    def hecke(self, ell):
        R, P = self.R, self.P
        F = Residue(R, ell)
        reps = [((ONE, r), (ZERO, ell)) for r in residue_lifts(R, F)] + [((ell, ZERO), (ZERO, ONE))]
        cols = []
        for b in self.cusp:
            vals = []
            for S in self.smat:
                tot = 0
                for D in reps:
                    DS = mmul(R, D, S)
                    for E in reps:
                        X = mmul(R, DS, adj(R, E))
                        if all(R.divides(ell, X[i][j]) for i in range(2) for j in range(2)):
                            Y = tuple(tuple(R.exact_div(X[i][j], ell) for j in range(2)) for i in range(2))
                            if self.G0.F.red(Y[1][0]) == self.G0.F.zero():
                                v = self.eval_vec(Y)
                                tot += sum(b[k] * x for k, x in v.items())
                                break
                    else:
                        raise AssertionError("no matching coset")
                vals.append(tot % P)
            cols.append(solve_mod(self.cusp, vals, P))
        n = len(self.cusp)
        return [[cols[j][i] for j in range(n)] for i in range(n)]


def ap_11a(p):
    """a_p of y^2 + y = x^3 - x^2 by counting points."""
    cnt = 1
    for x in range(p):
        for y in range(p):
            if (y * y + y - x ** 3 + x * x) % p == 0:
                cnt += 1
    return p + 1 - cnt


def run_field(d, out, check, maxnorm, sat_check_norm, snf_norm):
    R, gens, rels, src = presentation(d)
    disc = -4 if d == 1 else -3
    out.append(f"d = {d} (discriminant {disc}). Generators a, t, u, l; presentation: {src}")
    out.append(f"  {len(rels)} relators" + (": " + ", ".join(rels) if len(rels) < 20 else ""))
    check(f"d = {d}: every relator is +-1 on the matrices", all(proj_eq(R, word_matrix(R, gens, r), I2) for r in rels))
    G = sorted(gens)
    rows = []
    for r in rels:
        v = {}
        for ch in r:
            k = G.index(ch.lower())
            v[k] = v.get(k, 0) + (1 if ch.islower() else -1)
        rows.append(v)
    ab = [x for x in smith_diagonal(rows, 4) if x != 1]
    known = [2, 2] if d == 1 else [3]
    out.append(f"  H_1(PSL_2(O), Z) from the presentation: " + " + ".join(f"Z/{x}" for x in ab))
    check(f"d = {d}: H_1 of the full group equals the known value " + " + ".join(f"Z/{x}" for x in known), ab == known)
    if d == 3:
        global SAT_LEN
        old = SAT_LEN
        SAT_LEN = 7
        _, _, rels7, _ = presentation(3)
        SAT_LEN = old
        stable = True
        for pi in primes_of(R, sat_check_norm):
            A = Gamma0(R, gens, rels, pi)
            B = Gamma0(R, gens, rels7, pi)
            dA = smith_diagonal(A.relation_matrix(), len(A.cols))
            dB = smith_diagonal(B.relation_matrix(), len(B.cols))
            stable = stable and dA == dB
        check(f"d = 3: H_1(Gamma_0(pi)) unchanged when relators of length 7 are added (N(pi) <= {sat_check_norm})", stable)
    out.append("  N(pi)  pi          index  b1  H_1 torsion = tors H^2      rank H^2  dim H^1_cusp")
    P1, P2 = 1000003, 998244353
    cuspidal = []
    for pi in primes_of(R, maxnorm):
        n = R.norm(pi)
        C = CohomologyMod(R, gens, rels, pi, P1)
        tors = "-"
        if n <= snf_norm:
            Ci = Gamma0(R, gens, rels, pi)
            dd = smith_diagonal(Ci.relation_matrix(), len(Ci.cols))
            assert len(Ci.cols) - len(dd) == C.b1
            tors = " + ".join(f"Z/{x}" for x in dd if x > 1) or "0"
        out.append(f"  {n:<6} {str(pi):<11} {C.G0.n:<6} {C.b1:<3} {tors:<27} {C.b1 + 1:<9} {len(C.cusp)}")
        if C.cusp:
            cuspidal.append((pi, C))
    check(f"d = {d}: every class in H^1 vanishes on the parabolic subgroups (no Eisenstein H^1)",
          all(len(C.cusp) == C.b1 for _, C in cuspidal))
    ells = [l for l in primes_of(R, 13)]
    seen = set()
    for pi, C in cuspidal:
        key = R.norm(pi)
        if key in seen:
            continue
        seen.add(key)
        C2 = CohomologyMod(R, gens, rels, pi, P2)
        parts = []
        eig = {}
        for ell in ells:
            if R.divides(ell, pi) or R.divides(pi, ell):
                continue
            cp1 = [sym(x, P1) for x in charpoly_mod(C.hecke(ell), P1)]
            cp2 = [sym(x, P2) for x in charpoly_mod(C2.hecke(ell), P2)]
            check(f"d = {d}, N = {key}, T_{ell}: the two moduli agree", cp1 == cp2)
            if len(cp1) == 2:
                a_l = -cp1[1]
                eig[ell] = a_l
                parts.append(f"a{ell} = {a_l}")
                check(f"d = {d}, N = {key}: |a{ell}| <= 2 sqrt(N(l))", abs(a_l) <= 2 * R.norm(ell) ** 0.5)
            else:
                parts.append(f"charpoly T{ell} = {cp1}")
        out.append(f"  Hecke at N(pi) = {key}, pi = {pi}: " + ", ".join(parts))
        if key == 121:
            # level (11): the base change of 11a must be among the eigen-systems
            okb = True
            preds = []
            for ell in ells:
                if R.divides(ell, pi) or R.divides(pi, ell):
                    continue
                n = R.norm(ell)
                pr = n if all(n % k for k in range(2, int(n ** 0.5) + 1)) else int(round(n ** 0.5))
                ap = ap_11a(pr)
                pred = ap if n == pr else ap * ap - 2 * pr
                preds.append(f"{ell}: {pred}")
                cp = [sym(x, P1) for x in charpoly_mod(C.hecke(ell), P1)]
                val = 0
                for c in cp:
                    val = val * pred + c
                okb = okb and val == 0
            out.append("    base change of 11a predicts " + ", ".join(preds))
            check(f"d = {d}, level (11): the base change of 11a is an eigen-system of every T_l", okb)


def main():
    out = []
    ok = True

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

    out.append("Gamma_0(pi), pi prime. H^1(Z) = Z^b1. Torsion of H^2(Z) = Ext(H_1, Z) = torsion of H_1 (universal")
    out.append("coefficients). rank H^2 = b1 + (number of cusps - 1) = b1 + 1, from Lefschetz duality with")
    out.append("H^1(cusp groups, Q) = 0 (input theorem, not computed). Torsion by Smith normal form for small N(pi);")
    out.append("ranks mod 1000003; Hecke operators mod two primes, lifted to integers.")
    out.append("")
    run_field(1, out, check, maxnorm=260, sat_check_norm=0, snf_norm=113)
    out.append("")
    run_field(3, out, check, maxnorm=200, sat_check_norm=43, snf_norm=50)
    out.append(f"ALL {'PASS' if ok else 'FAIL'}")
    text = "\n".join(out) + "\n"
    with open(os.path.join(HERE, "NUMERIC_BIANCHI.txt"), "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 364: NUMERIC_DET.txt

NUMERIC_DET.txt

1. General n over Z (exact rationals): det != 0  =>  kernel = 0.
   n = 3: 1859 random matrices with det != 0, 0 with nonzero kernel
  [PASS] n = 3: no counterexample
   n = 4: 1933 random matrices with det != 0, 0 with nonzero kernel
  [PASS] n = 4: no counterexample
   n = 5: 1972 random matrices with det != 0, 0 with nonzero kernel
  [PASS] n = 5: no counterexample
   n = 6: 1995 random matrices with det != 0, 0 with nonzero kernel
  [PASS] n = 6: no counterexample
2. Zero divisors break it: over Z/6, 2x2 matrices with det != 0 but a nonzero kernel vector.
   example: d = [[0,1],[2,0]], det = 4 mod 6, kernel vector (3, 0)
  [PASS] the no-zero-divisor hypothesis of inj2 cannot be dropped
3. Koszul complex of (x, y) over Z: exact in degrees 1, 2 for regular pairs.
   91 regular pairs, cycles checked in [-20,20]^2: 0 not boundaries
  [PASS] H_1 = 0 for every regular pair checked
4. Bianchi groups (H^1, H^2, torsion, Hecke T_p): see numeric_bianchi.py -> NUMERIC_BIANCHI.txt.
ALL PASS

Listing 365: NUMERIC_BIANCHI.txt

NUMERIC_BIANCHI.txt

Gamma_0(pi), pi prime. H^1(Z) = Z^b1. Torsion of H^2(Z) = Ext(H_1, Z) = torsion of H_1 (universal
coefficients). rank H^2 = b1 + (number of cusps - 1) = b1 + 1, from Lefschetz duality with
H^1(cusp groups, Q) = 0 (input theorem, not computed). Torsion by Smith normal form for small N(pi);
ranks mod 1000003; Hecke operators mod two primes, lifted to integers.

d = 1 (discriminant -4). Generators a, t, u, l; presentation: B. Fine, Algebraic Theory of the Bianchi Groups (1989), presentation of PSL_2(O_1); R. G. Swan, Adv. Math. 6 (1971)
  8 relators: aa, ll, alal, tltl, ulul, atatat, ualualual, tuTU
  [PASS] d = 1: every relator is +-1 on the matrices
  H_1(PSL_2(O), Z) from the presentation: Z/2 + Z/2
  [PASS] d = 1: H_1 of the full group equals the known value Z/2 + Z/2
  N(pi)  pi          index  b1  H_1 torsion = tors H^2      rank H^2  dim H^1_cusp
  2      (-1, -1)    3      0   Z/2 + Z/2 + Z/2 + Z/2       1         0
  5      (-2, -1)    6      0   Z/2 + Z/2 + Z/2             1         0
  5      (-2, 1)     6      0   Z/2 + Z/2 + Z/2             1         0
  9      (3, 0)      10     0   Z/2 + Z/2 + Z/4             1         0
  13     (-3, -2)    14     0   Z/2 + Z/2 + Z/6             1         0
  13     (-3, 2)     14     0   Z/2 + Z/2 + Z/6             1         0
  17     (-4, -1)    18     0   Z/2 + Z/2 + Z/8             1         0
  17     (-4, 1)     18     0   Z/2 + Z/2 + Z/8             1         0
  29     (-5, -2)    30     0   Z/2 + Z/2 + Z/42            1         0
  29     (-5, 2)     30     0   Z/2 + Z/2 + Z/42            1         0
  37     (-6, -1)    38     0   Z/2 + Z/2 + Z/18            1         0
  37     (-6, 1)     38     0   Z/2 + Z/2 + Z/18            1         0
  41     (-5, -4)    42     0   Z/2 + Z/2 + Z/2 + Z/20      1         0
  41     (-5, 4)     42     0   Z/2 + Z/2 + Z/2 + Z/20      1         0
  49     (7, 0)      50     0   Z/2 + Z/2 + Z/4 + Z/24      1         0
  53     (-7, -2)    54     0   Z/2 + Z/2 + Z/26            1         0
  53     (-7, 2)     54     0   Z/2 + Z/2 + Z/26            1         0
  61     (-6, -5)    62     0   Z/2 + Z/2 + Z/30            1         0
  61     (-6, 5)     62     0   Z/2 + Z/2 + Z/30            1         0
  73     (-8, -3)    74     0   Z/2 + Z/2 + Z/36            1         0
  73     (-8, 3)     74     0   Z/2 + Z/2 + Z/36            1         0
  89     (-8, -5)    90     0   Z/2 + Z/22 + Z/44           1         0
  89     (-8, 5)     90     0   Z/2 + Z/22 + Z/44           1         0
  97     (-9, -4)    98     0   Z/2 + Z/2 + Z/240           1         0
  97     (-9, 4)     98     0   Z/2 + Z/2 + Z/240           1         0
  101    (-10, -1)   102    0   Z/2 + Z/2 + Z/850           1         0
  101    (-10, 1)    102    0   Z/2 + Z/2 + Z/850           1         0
  109    (-10, -3)   110    0   Z/2 + Z/2 + Z/54            1         0
  109    (-10, 3)    110    0   Z/2 + Z/2 + Z/54            1         0
  113    (-8, -7)    114    0   Z/2 + Z/2 + Z/4 + Z/56      1         0
  113    (-8, 7)     114    0   Z/2 + Z/2 + Z/4 + Z/56      1         0
  121    (11, 0)     122    1   -                           2         1
  137    (-11, -4)   138    1   -                           2         1
  137    (-11, 4)    138    1   -                           2         1
  149    (-10, -7)   150    0   -                           1         0
  149    (-10, 7)    150    0   -                           1         0
  157    (-11, -6)   158    0   -                           1         0
  157    (-11, 6)    158    0   -                           1         0
  173    (-13, -2)   174    0   -                           1         0
  173    (-13, 2)    174    0   -                           1         0
  181    (-10, -9)   182    0   -                           1         0
  181    (-10, 9)    182    0   -                           1         0
  193    (-12, -7)   194    0   -                           1         0
  193    (-12, 7)    194    0   -                           1         0
  197    (-14, -1)   198    0   -                           1         0
  197    (-14, 1)    198    0   -                           1         0
  229    (-15, -2)   230    0   -                           1         0
  229    (-15, 2)    230    0   -                           1         0
  233    (-13, -8)   234    1   -                           2         1
  233    (-13, 8)    234    1   -                           2         1
  241    (-15, -4)   242    0   -                           1         0
  241    (-15, 4)    242    0   -                           1         0
  257    (-16, -1)   258    1   -                           2         1
  257    (-16, 1)    258    1   -                           2         1
  [PASS] d = 1: every class in H^1 vanishes on the parabolic subgroups (no Eisenstein H^1)
  [PASS] d = 1, N = 121, T_(-1, -1): the two moduli agree
  [PASS] d = 1, N = 121: |a(-1, -1)| <= 2 sqrt(N(l))
  [PASS] d = 1, N = 121, T_(-2, -1): the two moduli agree
  [PASS] d = 1, N = 121: |a(-2, -1)| <= 2 sqrt(N(l))
  [PASS] d = 1, N = 121, T_(-2, 1): the two moduli agree
  [PASS] d = 1, N = 121: |a(-2, 1)| <= 2 sqrt(N(l))
  [PASS] d = 1, N = 121, T_(3, 0): the two moduli agree
  [PASS] d = 1, N = 121: |a(3, 0)| <= 2 sqrt(N(l))
  [PASS] d = 1, N = 121, T_(-3, -2): the two moduli agree
  [PASS] d = 1, N = 121: |a(-3, -2)| <= 2 sqrt(N(l))
  [PASS] d = 1, N = 121, T_(-3, 2): the two moduli agree
  [PASS] d = 1, N = 121: |a(-3, 2)| <= 2 sqrt(N(l))
  Hecke at N(pi) = 121, pi = (11, 0): a(-1, -1) = -2, a(-2, -1) = 1, a(-2, 1) = 1, a(3, 0) = -5, a(-3, -2) = 4, a(-3, 2) = 4
    base change of 11a predicts (-1, -1): -2, (-2, -1): 1, (-2, 1): 1, (3, 0): -5, (-3, -2): 4, (-3, 2): 4
  [PASS] d = 1, level (11): the base change of 11a is an eigen-system of every T_l
  [PASS] d = 1, N = 137, T_(-1, -1): the two moduli agree
  [PASS] d = 1, N = 137: |a(-1, -1)| <= 2 sqrt(N(l))
  [PASS] d = 1, N = 137, T_(-2, -1): the two moduli agree
  [PASS] d = 1, N = 137: |a(-2, -1)| <= 2 sqrt(N(l))
  [PASS] d = 1, N = 137, T_(-2, 1): the two moduli agree
  [PASS] d = 1, N = 137: |a(-2, 1)| <= 2 sqrt(N(l))
  [PASS] d = 1, N = 137, T_(3, 0): the two moduli agree
  [PASS] d = 1, N = 137: |a(3, 0)| <= 2 sqrt(N(l))
  [PASS] d = 1, N = 137, T_(-3, -2): the two moduli agree
  [PASS] d = 1, N = 137: |a(-3, -2)| <= 2 sqrt(N(l))
  [PASS] d = 1, N = 137, T_(-3, 2): the two moduli agree
  [PASS] d = 1, N = 137: |a(-3, 2)| <= 2 sqrt(N(l))
  Hecke at N(pi) = 137, pi = (-11, -4): a(-1, -1) = 1, a(-2, -1) = 0, a(-2, 1) = 2, a(3, 0) = -2, a(-3, -2) = 0, a(-3, 2) = -2
  [PASS] d = 1, N = 233, T_(-1, -1): the two moduli agree
  [PASS] d = 1, N = 233: |a(-1, -1)| <= 2 sqrt(N(l))
  [PASS] d = 1, N = 233, T_(-2, -1): the two moduli agree
  [PASS] d = 1, N = 233: |a(-2, -1)| <= 2 sqrt(N(l))
  [PASS] d = 1, N = 233, T_(-2, 1): the two moduli agree
  [PASS] d = 1, N = 233: |a(-2, 1)| <= 2 sqrt(N(l))
  [PASS] d = 1, N = 233, T_(3, 0): the two moduli agree
  [PASS] d = 1, N = 233: |a(3, 0)| <= 2 sqrt(N(l))
  [PASS] d = 1, N = 233, T_(-3, -2): the two moduli agree
  [PASS] d = 1, N = 233: |a(-3, -2)| <= 2 sqrt(N(l))
  [PASS] d = 1, N = 233, T_(-3, 2): the two moduli agree
  [PASS] d = 1, N = 233: |a(-3, 2)| <= 2 sqrt(N(l))
  Hecke at N(pi) = 233, pi = (-13, -8): a(-1, -1) = -2, a(-2, -1) = -2, a(-2, 1) = -3, a(3, 0) = -4, a(-3, -2) = 3, a(-3, 2) = -3
  [PASS] d = 1, N = 257, T_(-1, -1): the two moduli agree
  [PASS] d = 1, N = 257: |a(-1, -1)| <= 2 sqrt(N(l))
  [PASS] d = 1, N = 257, T_(-2, -1): the two moduli agree
  [PASS] d = 1, N = 257: |a(-2, -1)| <= 2 sqrt(N(l))
  [PASS] d = 1, N = 257, T_(-2, 1): the two moduli agree
  [PASS] d = 1, N = 257: |a(-2, 1)| <= 2 sqrt(N(l))
  [PASS] d = 1, N = 257, T_(3, 0): the two moduli agree
  [PASS] d = 1, N = 257: |a(3, 0)| <= 2 sqrt(N(l))
  [PASS] d = 1, N = 257, T_(-3, -2): the two moduli agree
  [PASS] d = 1, N = 257: |a(-3, -2)| <= 2 sqrt(N(l))
  [PASS] d = 1, N = 257, T_(-3, 2): the two moduli agree
  [PASS] d = 1, N = 257: |a(-3, 2)| <= 2 sqrt(N(l))
  Hecke at N(pi) = 257, pi = (-16, -1): a(-1, -1) = -1, a(-2, -1) = 2, a(-2, 1) = -2, a(3, 0) = 2, a(-3, -2) = 6, a(-3, 2) = -2

d = 3 (discriminant -3). Generators a, t, u, l; presentation: NOT a standard presentation: all reduced words of length <= 6 in a, t, u, l that are +-1 on the matrices (completeness not certified)
  228 relators
  [PASS] d = 3: every relator is +-1 on the matrices
  H_1(PSL_2(O), Z) from the presentation: Z/3
  [PASS] d = 3: H_1 of the full group equals the known value Z/3
  [PASS] d = 3: H_1(Gamma_0(pi)) unchanged when relators of length 7 are added (N(pi) <= 43)
  N(pi)  pi          index  b1  H_1 torsion = tors H^2      rank H^2  dim H^1_cusp
  3      (-2, -1)    4      0   Z/3 + Z/3                   1         0
  4      (2, 0)      5      0   Z/3 + Z/3                   1         0
  7      (-3, -2)    8      0   Z/3 + Z/3                   1         0
  7      (-3, -1)    8      0   Z/3 + Z/3                   1         0
  13     (-4, -3)    14     0   Z/3 + Z/6                   1         0
  13     (-4, -1)    14     0   Z/3 + Z/6                   1         0
  19     (-5, -3)    20     0   Z/3 + Z/9                   1         0
  19     (-5, -2)    20     0   Z/3 + Z/9                   1         0
  25     (5, 0)      26     0   Z/6 + Z/12                  1         0
  31     (-6, -5)    32     0   Z/3 + Z/15                  1         0
  31     (-6, -1)    32     0   Z/3 + Z/15                  1         0
  37     (-7, -4)    38     0   Z/3 + Z/18                  1         0
  37     (-7, -3)    38     0   Z/3 + Z/18                  1         0
  43     (-7, -6)    44     0   Z/3 + Z/21                  1         0
  43     (-7, -1)    44     0   Z/3 + Z/21                  1         0
  61     (-9, -5)    62     0   -                           1         0
  61     (-9, -4)    62     0   -                           1         0
  67     (-9, -7)    68     0   -                           1         0
  67     (-9, -2)    68     0   -                           1         0
  73     (-9, -8)    74     1   -                           2         1
  73     (-9, -1)    74     1   -                           2         1
  79     (-10, -7)   80     0   -                           1         0
  79     (-10, -3)   80     0   -                           1         0
  97     (-11, -8)   98     0   -                           1         0
  97     (-11, -3)   98     0   -                           1         0
  103    (-11, -9)   104    0   -                           1         0
  103    (-11, -2)   104    0   -                           1         0
  109    (-12, -7)   110    0   -                           1         0
  109    (-12, -5)   110    0   -                           1         0
  121    (11, 0)     122    2   -                           3         2
  127    (-13, -7)   128    0   -                           1         0
  127    (-13, -6)   128    0   -                           1         0
  139    (-13, -10)  140    0   -                           1         0
  139    (-13, -3)   140    0   -                           1         0
  151    (-14, -9)   152    0   -                           1         0
  151    (-14, -5)   152    0   -                           1         0
  157    (-13, -12)  158    0   -                           1         0
  157    (-13, -1)   158    0   -                           1         0
  163    (-14, -11)  164    0   -                           1         0
  163    (-14, -3)   164    0   -                           1         0
  181    (-15, -11)  182    0   -                           1         0
  181    (-15, -4)   182    0   -                           1         0
  193    (-16, -9)   194    0   -                           1         0
  193    (-16, -7)   194    0   -                           1         0
  199    (-15, -13)  200    0   -                           1         0
  199    (-15, -2)   200    0   -                           1         0
  [PASS] d = 3: every class in H^1 vanishes on the parabolic subgroups (no Eisenstein H^1)
  [PASS] d = 3, N = 73, T_(-2, -1): the two moduli agree
  [PASS] d = 3, N = 73: |a(-2, -1)| <= 2 sqrt(N(l))
  [PASS] d = 3, N = 73, T_(2, 0): the two moduli agree
  [PASS] d = 3, N = 73: |a(2, 0)| <= 2 sqrt(N(l))
  [PASS] d = 3, N = 73, T_(-3, -2): the two moduli agree
  [PASS] d = 3, N = 73: |a(-3, -2)| <= 2 sqrt(N(l))
  [PASS] d = 3, N = 73, T_(-3, -1): the two moduli agree
  [PASS] d = 3, N = 73: |a(-3, -1)| <= 2 sqrt(N(l))
  [PASS] d = 3, N = 73, T_(-4, -3): the two moduli agree
  [PASS] d = 3, N = 73: |a(-4, -3)| <= 2 sqrt(N(l))
  [PASS] d = 3, N = 73, T_(-4, -1): the two moduli agree
  [PASS] d = 3, N = 73: |a(-4, -1)| <= 2 sqrt(N(l))
  Hecke at N(pi) = 73, pi = (-9, -8): a(-2, -1) = -2, a(2, 0) = -1, a(-3, -2) = -4, a(-3, -1) = 2, a(-4, -3) = 2, a(-4, -1) = 2
  [PASS] d = 3, N = 121, T_(-2, -1): the two moduli agree
  [PASS] d = 3, N = 121, T_(2, 0): the two moduli agree
  [PASS] d = 3, N = 121, T_(-3, -2): the two moduli agree
  [PASS] d = 3, N = 121, T_(-3, -1): the two moduli agree
  [PASS] d = 3, N = 121, T_(-4, -3): the two moduli agree
  [PASS] d = 3, N = 121, T_(-4, -1): the two moduli agree
  Hecke at N(pi) = 121, pi = (11, 0): charpoly T(-2, -1) = [1, 1, 0], charpoly T(2, 0) = [1, -3, 0], charpoly T(-3, -2) = [1, 4, 4], charpoly T(-3, -1) = [1, 0, -4], charpoly T(-4, -3) = [1, -6, 8], charpoly T(-4, -1) = [1, -2, -8]
    base change of 11a predicts (-2, -1): -1, (2, 0): 0, (-3, -2): -2, (-3, -1): -2, (-4, -3): 4, (-4, -1): 4
  [PASS] d = 3, level (11): the base change of 11a is an eigen-system of every T_l
ALL PASS