Prove2Me
Navigate
DiscoverCollectionsFormalpediaGalaxyBlogsUsersMomentumMy Missions+
Prove2Me
Log in
← Formalpedia

Chapter 10 two-variable Hahn series: theta series, Rho\mathrm{Rho}Rho, Zwegers and Hickerson lemmas, (10.15) sum

Definition
QseriesFormalization_Pending_Chapter10_TwoVar

by FormallyCorrect · Oct 23, 2026 · Mathlib 0df444a (Lean v4.33.1)

chan-invitation-qseriesformal-power-seriesmock-thetatheta-functions

This large bundle sets up the rings K=Q((Q))K=\mathbb{Q}((Q))K=Q((Q)) and SSS of two-variable Hahn series with exponents QaxiyjQ^ax^iy^jQaxiyj in lexicographic order (QQQ first), monomials, coefficient extraction (including slices [xiyj][x^iy^j][xiyj] and the constant term in x,yx,yx,y), and the embedding K→SK\to SK→S. It defines theta series ∑(−1)nQAT(n)+enxinyjn\sum(-1)^nQ^{AT(n)+en}x^{in}y^{jn}∑(−1)nQAT(n)+enxinyjn with T(n)=n(n−1)/2T(n)=n(n-1)/2T(n)=n(n−1)/2, the q=Q3q=Q^3q=Q3 specializations Θ(x;q)\Theta(x;q)Θ(x;q), Θ(y;q)\Theta(y;q)Θ(y;q), Θ(xy;q)\Theta(xy;q)Θ(xy;q), Euler's (q;q)∞(q;q)_\infty(q;q)∞​ as an element of KKK, and the Zwegers-lemma series and their right sides. It also defines the sign function ρ\rhoρ, Rho=∑ρ(r,s)Q3rsxrys\mathrm{Rho}=\sum\rho(r,s)Q^{3rs}x^ry^sRho=∑ρ(r,s)Q3rsxrys and its substituted version, string sums, slice terms and families, and finally the quadruple-sum series ChanQuadSum and the left side ChanQuadLHS for Chan's Eq. (10.15). Many auxiliary reindexing equivalences and summable-family structures are included.

The general theta-family construction requires A>0A>0A>0. These are formal Hahn sums with proved support and finite-coefficient conditions, not analytic sums after numerical substitution.

Definition code
-- Generated by qseries-p2m/p2m/generate.py from QseriesFormalization.Pending.Chapter10_TwoVar: skeleton subtraction
-- keeps 140 declaration(s); proofs kept; project imports -> Definitions bundles.
import Definitions.Def_QseriesFormalization_DefCoreQSeries
import Mathlib
import Mathlib.Combinatorics.Enumerative.Partition.GenFun
import Mathlib.RingTheory.PowerSeries.Basic
import Mathlib.RingTheory.PowerSeries.Expand
import Mathlib.RingTheory.PowerSeries.Inverse
import Mathlib.Analysis.SpecificLimits.Normed
import Mathlib.Analysis.Normed.Ring.InfiniteSum
import Mathlib.Topology.Algebra.InfiniteSum.NatInt
import Mathlib.RingTheory.LaurentSeries
import Mathlib.RingTheory.PowerSeries.Order
import Mathlib.Combinatorics.Enumerative.Partition.Basic
import Mathlib.Tactic.Linarith
import Mathlib.Analysis.Normed.Group.Tannery
import Mathlib.Analysis.SpecialFunctions.Log.Summable

namespace QseriesFormalization.Pending.Ch10HM end QseriesFormalization.Pending.Ch10HM

open scoped Classical
open Set

namespace QseriesFormalization
namespace Ch10TwoVar

/-! ## Layer A — the q-first lexicographic Hahn kernel -/

/-- `(x-degree, y-degree)`, lexicographic. -/
abbrev ExpXY  := Lex (ℤ × ℤ)
/-- `(Q-degree, x-degree, y-degree)`, lexicographic, q-first. -/
abbrev ExpQXY := Lex (ℤ × ExpXY)
/-- `ℚ((Q))`: the coefficient field of Q-Laurent-Hahn series. -/
abbrev K := HahnSeries ℤ ℚ
/-- The q-adic x/y Laurent–Hahn ring. -/
abbrev S := HahnSeries ExpQXY ℚ

/-- The exponent `Q^a x^i y^j` as an element of the index monoid. -/
noncomputable def expQXY (a i j : ℤ) : ExpQXY := toLex (a, toLex (i, j))

/-- The monomial `c · Q^a x^i y^j`. -/
noncomputable def monom (a i j : ℤ) (c : ℚ) : S := HahnSeries.single (expQXY a i j) c

/-- The exponent map is additive. -/
@[simp] theorem expQXY_add (a i j a' i' j' : ℤ) :
    expQXY a i j + expQXY a' i' j' = expQXY (a + a') (i + i') (j + j') := rfl

@[simp] theorem expQXY_zero : expQXY 0 0 0 = (0 : ExpQXY) := rfl

/-- The exponent map is injective in all three slots. -/
theorem expQXY_inj {a i j a' i' j' : ℤ} (h : expQXY a i j = expQXY a' i' j') :
    a = a' ∧ i = i' ∧ j = j' := by
  unfold expQXY at h
  simp only [Prod.ext_iff, EmbeddingLike.apply_eq_iff_eq] at h
  exact ⟨h.1, h.2.1, h.2.2⟩

@[simp] theorem expQXY_eq_iff {a i j a' i' j' : ℤ} :
    expQXY a i j = expQXY a' i' j' ↔ a = a' ∧ i = i' ∧ j = j' :=
  ⟨expQXY_inj, by rintro ⟨rfl, rfl, rfl⟩; rfl⟩

/-- Strict monotonicity of the Q-degree slot at fixed `(i,j)`. -/
theorem expQXY_strictMono (i j : ℤ) : StrictMono (fun a => expQXY a i j) := by
  intro a b h
  exact Prod.Lex.toLex_lt_toLex.mpr (Or.inl h)

/-- The `Q^a x^i y^j` coefficient of `F`. -/
noncomputable def coeffQXY (F : S) (a i j : ℤ) : ℚ := F.coeff (expQXY a i j)

/-! ### The q-slice `coeffXY` -/

/-- The support of the q-slice `a ↦ coeffQXY F a i j` is partially well-ordered in `ℤ`. -/
theorem slice_isPWO (F : S) (i j : ℤ) :
    {a : ℤ | F.coeff (expQXY a i j) ≠ 0}.IsPWO := by
  rw [Set.isPWO_iff_exists_monotone_subseq]
  intro f hf
  have hFpwo := F.isPWO_support
  rw [Set.isPWO_iff_exists_monotone_subseq] at hFpwo
  have hf' : ∀ n, (fun a => expQXY (f a) i j) n ∈ F.support := by
    intro n
    have := hf n
    simpa [HahnSeries.mem_support] using this
  obtain ⟨g, hg⟩ := hFpwo (fun n => expQXY (f n) i j) hf'
  refine ⟨g, ?_⟩
  intro a b hab
  have hle := hg hab
  by_contra hcon
  push_neg at hcon
  exact absurd hle (not_le.mpr (expQXY_strictMono i j hcon))

/-- The q-slice of `F` at `x^i y^j`, as an element of `K = ℚ((Q))`. -/
noncomputable def coeffXY (F : S) (i j : ℤ) : K where
  coeff := fun a => coeffQXY F a i j
  isPWO_support' := by
    refine (slice_isPWO F i j).mono ?_
    intro a ha
    exact ha

@[simp] theorem coeffXY_coeff (F : S) (i j a : ℤ) :
    (coeffXY F i j).coeff a = coeffQXY F a i j := rfl

/-- The constant-in-`x,y` term of `F`, as an element of `K`. -/
noncomputable def CTxy (F : S) : K := coeffXY F 0 0

@[simp] theorem CTxy_coeff (F : S) (a : ℤ) : (CTxy F).coeff a = coeffQXY F a 0 0 := rfl

/-! ### The Q-embedding `embedQ : K →+* S` -/

/-- The additive monoid embedding `ℤ ↪ ExpQXY`, `a ↦ Q^a` (i.e. `expQXY a 0 0`). -/
noncomputable def expQHom : ℤ →+ ExpQXY where
  toFun := fun a => expQXY a 0 0
  map_zero' := expQXY_zero
  map_add' := by intro a b; rw [expQXY_add]; norm_num

theorem expQHom_apply (a : ℤ) : expQHom a = expQXY a 0 0 := rfl

theorem expQHom_injective : Function.Injective expQHom := by
  intro a b h
  rw [expQHom_apply, expQHom_apply, expQXY_eq_iff] at h
  exact h.1

theorem expQHom_le_iff (a b : ℤ) : expQHom a ≤ expQHom b ↔ a ≤ b := by
  rw [expQHom_apply, expQHom_apply]
  constructor
  · intro h
    by_contra hcon
    push_neg at hcon
    exact absurd h (not_le.mpr (expQXY_strictMono 0 0 hcon))
  · intro h
    rcases lt_or_eq_of_le h with h | h
    · exact le_of_lt (expQXY_strictMono 0 0 h)
    · rw [h]

/-- The ring homomorphism `K →+* S` that includes `ℚ((Q))` as the `x^0 y^0` part. -/
noncomputable def embedQ : K →+* S :=
  HahnSeries.embDomainRingHom expQHom expQHom_injective expQHom_le_iff

/-! ## Layer B — integer quadratic helpers -/

/-- `T n = n(n-1)/2`. -/
def Tn (n : ℤ) : ℤ := n * (n - 1) / 2
/-- `T⁺ n = n(n+1)/2`. -/
def Tplus (n : ℤ) : ℤ := n * (n + 1) / 2
/-- `P₁₀ n = n(5n+3)/2`. -/
def P10 (n : ℤ) : ℤ := n * (5 * n + 3) / 2

/-- `n(n-1)` is even. -/
theorem even_n_mul_pred (n : ℤ) : (2 : ℤ) ∣ n * (n - 1) := by
  rcases Int.even_or_odd n with ⟨k, hk⟩ | ⟨k, hk⟩
  · exact ⟨k * (n - 1), by rw [hk]; ring⟩
  · exact ⟨n * k, by rw [hk]; ring⟩

theorem even_n_mul_succ (n : ℤ) : (2 : ℤ) ∣ n * (n + 1) := by
  rcases Int.even_or_odd n with ⟨k, hk⟩ | ⟨k, hk⟩
  · exact ⟨k * (n + 1), by rw [hk]; ring⟩
  · exact ⟨n * (k + 1), by rw [hk]; ring⟩

theorem even_n_mul_5n_add_3 (n : ℤ) : (2 : ℤ) ∣ n * (5 * n + 3) := by
  rcases Int.even_or_odd n with ⟨k, hk⟩ | ⟨k, hk⟩
  · exact ⟨k * (5 * n + 3), by rw [hk]; ring⟩
  · exact ⟨n * (5 * k + 4), by rw [hk]; ring⟩

/-- Closed form `2 * T n = n(n-1)`. -/
theorem two_mul_Tn (n : ℤ) : 2 * Tn n = n * (n - 1) := by
  unfold Tn
  rw [mul_comm]; exact Int.ediv_mul_cancel (even_n_mul_pred n)

theorem two_mul_Tplus (n : ℤ) : 2 * Tplus n = n * (n + 1) := by
  unfold Tplus
  rw [mul_comm]; exact Int.ediv_mul_cancel (even_n_mul_succ n)

theorem two_mul_P10 (n : ℤ) : 2 * P10 n = n * (5 * n + 3) := by
  unfold P10
  rw [mul_comm]; exact Int.ediv_mul_cancel (even_n_mul_5n_add_3 n)

/-- The single `Q^m` in `K = ℚ((Q))`. -/
noncomputable def Qpow (m : ℤ) : K := HahnSeries.single m 1

@[simp] theorem Qpow_zero : Qpow 0 = 1 := rfl

/-! ## Layer C — `thetaMon` as the hsum of a summable family -/

/-- The Q-degree of the `n`-th term of `thetaMon A e i j`. -/
def thetaQDeg (A e n : ℤ) : ℤ := A * Tn n + e * n

/-- For `0 < A`, the Q-degree map `n ↦ A·T n + e·n` is bounded below. -/
theorem thetaQDeg_bddBelow (A e : ℤ) (hA : 0 < A) :
    BddBelow (Set.range (fun n => thetaQDeg A e n)) := by
  -- 2 * thetaQDeg = A n(n-1) + 2 e n = A n² + (2e - A) n.  Complete the square (in ℤ):
  -- 4 A * (2 thetaQDeg) = (2 A n + (2e - A))² - (2e - A)², so thetaQDeg ≥ -(2e-A)²/(8A)-ish.
  -- We give a crude explicit lower bound.
  refine ⟨- (A + (2 * e - A) ^ 2), ?_⟩
  rintro x ⟨n, rfl⟩
  unfold thetaQDeg
  have h2 := two_mul_Tn n
  -- A * Tn n = A * (n(n-1)) / 2 ; multiply the target inequality by 2 and use nonneg squares.
  have hkey : 8 * A * (A * Tn n + e * n) =
      (2 * A * n + (2 * e - A)) ^ 2 - (2 * e - A) ^ 2 := by
    have : 2 * (A * Tn n) = A * (n * (n - 1)) := by rw [← h2]; ring
    nlinarith [this]
  nlinarith [sq_nonneg (2 * A * n + (2 * e - A)), hA, sq_nonneg (2 * e - A)]

/-- Completing the square: `(2An + (2e - A))² = 8A·thetaQDeg A e n + (2e - A)²`,
from `2·T n = n(n-1)`. -/
theorem thetaQDeg_complete_square (A e n : ℤ) :
    (2 * A * n + (2 * e - A)) ^ 2 = 8 * A * thetaQDeg A e n + (2 * e - A) ^ 2 := by
  unfold thetaQDeg
  linear_combination (-4 * A ^ 2) * two_mul_Tn n

/-- An integer square root fiber `{x | x² = M}` is finite: it lies in `[-M, M]`
since `|x| ≤ x²` on `ℤ`. -/
theorem int_sq_fiber_finite (M : ℤ) : {x : ℤ | x ^ 2 = M}.Finite := by
  refine (Set.finite_Icc (-M) M).subset ?_
  intro x hx
  rw [Set.mem_setOf_eq] at hx
  rw [Set.mem_Icc, ← hx]
  have h1 := Int.le_self_sq x
  have h2 := Int.le_self_sq (-x)
  rw [neg_sq] at h2
  constructor <;> linarith

/-- For `0 < A`, only finitely many `n` give a fixed Q-degree (quadratic has ≤ 2 roots). -/
theorem thetaQDeg_finite_fiber (A e : ℤ) (hA : 0 < A) (N : ℤ) :
    {n : ℤ | thetaQDeg A e n = N}.Finite := by
  -- The level set is the preimage of the finite set `{x | x² = 8AN + (2e-A)²}` under the
  -- injective affine map `n ↦ 2An + (2e - A)` (completing the square).
  have hinj : Function.Injective (fun n : ℤ => 2 * A * n + (2 * e - A)) := by
    intro x y hxy
    have h2A : (2 * A) ≠ 0 := by positivity
    exact mul_left_cancel₀ h2A (add_right_cancel hxy)
  refine ((int_sq_fiber_finite (8 * A * N + (2 * e - A) ^ 2)).preimage hinj.injOn).subset ?_
  intro n hn
  rw [Set.mem_setOf_eq] at hn
  rw [Set.mem_preimage, Set.mem_setOf_eq, thetaQDeg_complete_square, hn]

/-- The candidate exponent of the `n`-th term of `thetaMon A e i j`. -/
noncomputable def thetaExp (A e i j n : ℤ) : ExpQXY :=
  expQXY (thetaQDeg A e n) (i * n) (j * n)

/-- For `0 < A`, only finitely many `n` give a fixed candidate exponent. -/
theorem thetaExp_finite_fiber (A e i j : ℤ) (hA : 0 < A) (g : ExpQXY) :
    {n : ℤ | thetaExp A e i j n = g}.Finite := by
  -- the Q-degree slot pins `n` to a fixed value, of which finitely many exist.
  obtain ⟨N, m⟩ := g
  apply Set.Finite.subset (thetaQDeg_finite_fiber A e hA N)
  intro n hn
  simp only [Set.mem_setOf_eq, thetaExp, expQXY] at hn ⊢
  have := (Prod.ext_iff.mp (EmbeddingLike.apply_eq_iff_eq _ |>.mp hn)).1
  exact this

/-- For `0 < A`, the range of candidate exponents is partially well-ordered in `ExpQXY`. -/
theorem thetaExp_range_isPWO (A e i j : ℤ) (hA : 0 < A) :
    (Set.range (fun n => thetaExp A e i j n)).IsPWO := by
  apply Set.PartiallyWellOrderedOn.subsetProdLex
  · -- Q-degree projection of the range is bounded below ⟹ IsWF ⟹ IsPWO in ℤ.
    have hsub : (fun (x : ℤ ×ₗ ExpXY) => (ofLex x).1) '' Set.range (fun n => thetaExp A e i j n)
        ⊆ Set.range (fun n => thetaQDeg A e n) := by
      rintro a ⟨z, ⟨n, rfl⟩, rfl⟩
      exact ⟨n, rfl⟩
    refine (BddBelow.isWF ?_).isPWO.mono hsub
    obtain ⟨b, hb⟩ := thetaQDeg_bddBelow A e hA
    exact ⟨b, hb⟩
  · -- each fiber is finite, hence PWO.
    intro a
    apply Set.Finite.isPWO
    -- {y | toLex (a,y) ∈ range} = image of {n | thetaQDeg A e n = a} under n ↦ toLex (i n, j n).
    apply Set.Finite.subset (Set.Finite.image
      (fun n => (toLex (i * n, j * n) : ExpXY)) (thetaQDeg_finite_fiber A e hA a))
    rintro y ⟨n, hn⟩
    simp only at hn
    -- hn : thetaExp A e i j n = toLex (a, y)
    refine ⟨n, ?_, ?_⟩
    · -- Q-degree slot: thetaQDeg A e n = a
      have h1 : (ofLex (thetaExp A e i j n)).1 = a := by rw [hn]; rfl
      simpa [thetaExp, expQXY] using h1
    · -- x/y slot: toLex (i n, j n) = y
      have h2 : (ofLex (thetaExp A e i j n)).2 = y := by rw [hn]; rfl
      simpa [thetaExp, expQXY] using h2

/-- The summable family `n ↦ monom (A·T n + e·n) (i·n) (j·n) ((-1)^n)`, for `0 < A`. -/
noncomputable def thetaFamily (A e i j : ℤ) (hA : 0 < A) :
    HahnSeries.SummableFamily ExpQXY ℚ ℤ where
  toFun := fun n => monom (thetaQDeg A e n) (i * n) (j * n) ((-1) ^ n)
  isPWO_iUnion_support' := by
    refine (thetaExp_range_isPWO A e i j hA).mono (Set.iUnion_subset (fun n => ?_))
    intro x hx
    refine ⟨n, ?_⟩
    have : x = expQXY (thetaQDeg A e n) (i * n) (j * n) :=
      HahnSeries.support_single_subset hx
    rw [this]; rfl
  finite_co_support' := by
    intro g
    -- {n | coeff of n-th monom at g ≠ 0} ⊆ {n | thetaExp ... n = g}, which is finite.
    apply Set.Finite.subset (thetaExp_finite_fiber A e i j hA g)
    intro n hn
    simp only [Set.mem_setOf_eq] at hn
    by_contra hne
    apply hn
    unfold monom
    rw [HahnSeries.coeff_single_of_ne]
    intro hcon
    exact hne (hcon ▸ rfl)

/-- `thetaMon A e i j`: the theta function `Θ` with weight `Q^e x^i y^j` and nome `Q^A`. -/
noncomputable def thetaMon (A e i j : ℤ) (hA : 0 < A) : S :=
  (thetaFamily A e i j hA).hsum

/-! ### Symmetry specials -/

/-! ## Layer D — q-Pochhammer bridge

We import the committed formal-power-series infrastructure (`qPochInfPS`, the cube
identity `qPochInfPS^3 = jacobiThetaPS`) and transport it into `K = ℚ((Q))` via
`HahnSeries.ofPowerSeries` composed with `PowerSeries.expand` (the `q = Q^3` rescaling).
-/

open QseriesFormalization.PartIV.Ch19 (qPochInfPS jacobiThetaPS jacobiTripleSign
  )

/-- `ofPowerSeries ℤ ℚ : ℚ⟦X⟧ →+* K`, sending `X ↦ Q` (i.e. `single 1 1`). -/
noncomputable def ofPSK : PowerSeries ℚ →+* K := HahnSeries.ofPowerSeries ℤ ℚ

/-- `poch_q := (Q^3;Q^3)_∞`, the cube root `q = Q^3` rescaling of `(q;q)_∞`. -/
noncomputable def poch_q : K := ofPSK (PowerSeries.expand 3 (by norm_num) (qPochInfPS ℚ))

/-- `poch_q2 := (Q^6;Q^6)_∞`. -/
noncomputable def poch_q2 : K := ofPSK (PowerSeries.expand 6 (by norm_num) (qPochInfPS ℚ))

/-! ### A `K`-level theta summable family

The one-variable theta sums `∑' t, single (3·T t) (w t)` (in `K = ℚ((Q))`) needed for
`theta_one_zero` and the Jacobi derivative.  The Q-degree `3·T t = thetaQDeg 3 0 t` is
bounded below with finite fibers (reusing the layer-C bounds), so the family is summable. -/

/-- The `K`-summable family `t ↦ single (3·T t) (w t)`. -/
noncomputable def kThetaFamily (w : ℤ → ℚ) :
    HahnSeries.SummableFamily ℤ ℚ ℤ where
  toFun := fun t => HahnSeries.single (thetaQDeg 3 0 t) (w t)
  isPWO_iUnion_support' := by
    have hb := thetaQDeg_bddBelow 3 0 (by norm_num)
    refine (hb.isWF.isPWO).mono (Set.iUnion_subset (fun t => ?_))
    intro x hx
    have hxe : x = thetaQDeg 3 0 t := HahnSeries.support_single_subset hx
    exact ⟨t, hxe.symm⟩
  finite_co_support' := by
    intro g
    apply Set.Finite.subset (thetaQDeg_finite_fiber 3 0 (by norm_num) g)
    intro t ht
    simp only [Set.mem_setOf_eq] at ht
    by_contra hne
    apply ht
    rw [HahnSeries.coeff_single_of_ne]
    intro hcon
    exact hne hcon.symm

/-- The hsum of `kThetaFamily w`. -/
noncomputable def kTheta (w : ℤ → ℚ) : K := (kThetaFamily w).hsum

/-! ### Jacobi's derivative identity `-∑ (-1)^t t q^{T t} = (q;q)_∞^3` -/

/-! ### Jacobi's derivative identity, finished -/

/-- `Tn t ≥ 0` for all integers (product of consecutive integers). -/
theorem Tn_nonneg (t : ℤ) : 0 ≤ Tn t := by
  have h := two_mul_Tn t
  have hprod : 0 ≤ t * (t - 1) := by
    rcases le_or_gt 1 t with h1 | h1
    · exact mul_nonneg (by omega) (by omega)
    · nlinarith [h1]
  omega

/-! ## Layer E — Zwegers Lemma 10.1 (functional-equation route)

The classical identity (Chen, Eq. 10.34; Zwegers 2010, Lemma 3.1)
`∑_{k,l} (-1)^{k+l}(δ(k)-δ(l)) q^{(k²+l²)/3} x^l = -x⁻¹q^{1/3} (q²;q²)∞/(q;q)∞ Θ(x;q²)Θ(x;q)`,
proved here in the `poch_q2`-cleared form to avoid `K`-division.
-/

/-- Chan's residue `δ`: `δ(k) = 1` if `3 ∣ k`, else `0`. -/
def delta3 (k : ℤ) : ℚ := if (3 : ℤ) ∣ k then 1 else 0

/-! ### The 2D summable family for the Zwegers LHS

Q-degree `k²+l²` is bounded below by `0` with finite fibers (lattice points on a
circle), so the family indexed by `ℤ × ℤ` is summable in `S`. -/

/-- The candidate exponent of the `(k,l)`-th Zwegers term: `Q^{k²+l²} x^l`. -/
noncomputable def zExp (k l : ℤ) : ExpQXY := expQXY (k ^ 2 + l ^ 2) l 0

/-- The `(k,l)` coefficient weight `(-1)^{k+l}(δ k − δ l)`. -/
noncomputable def zW (k l : ℤ) : ℚ := (-1) ^ (k + l) * (delta3 k - delta3 l)

/-- For a fixed Q-degree `N`, only finitely many `(k,l)` have `k²+l² = N`. -/
theorem zDeg_finite_fiber (N : ℤ) : {p : ℤ × ℤ | p.1 ^ 2 + p.2 ^ 2 = N}.Finite := by
  apply Set.Finite.subset (Set.finite_Icc
    ((-(N.natAbs : ℤ), -(N.natAbs : ℤ)) : ℤ × ℤ)
    (((N.natAbs : ℤ), (N.natAbs : ℤ)) : ℤ × ℤ))
  rintro ⟨k, l⟩ hkl
  simp only [Set.mem_setOf_eq] at hkl
  have hk2 : k ^ 2 ≤ N := by nlinarith [sq_nonneg l]
  have hl2 : l ^ 2 ≤ N := by nlinarith [sq_nonneg k]
  have hNn : (N : ℤ) ≤ (N.natAbs : ℤ) := Int.le_natAbs
  rw [Set.mem_Icc, Prod.le_def, Prod.le_def]
  refine ⟨⟨?_, ?_⟩, ?_, ?_⟩ <;>
    nlinarith [sq_nonneg k, sq_nonneg l, sq_nonneg (k - 1), sq_nonneg (k + 1),
      sq_nonneg (l - 1), sq_nonneg (l + 1), hk2, hl2, hNn]

/-- The range of `(k,l) ↦ zExp k l` is partially well-ordered in `ExpQXY`. -/
theorem zExp_range_isPWO : (Set.range (fun p : ℤ × ℤ => zExp p.1 p.2)).IsPWO := by
  apply Set.PartiallyWellOrderedOn.subsetProdLex
  · -- Q-degree projection bounded below by 0.
    have hsub : (fun (z : ℤ ×ₗ ExpXY) => (ofLex z).1) ''
        Set.range (fun p : ℤ × ℤ => zExp p.1 p.2) ⊆ Set.Ici (0 : ℤ) := by
      rintro a ⟨z, ⟨⟨k, l⟩, rfl⟩, rfl⟩
      simp only [zExp, expQXY, ofLex_toLex, Set.mem_Ici]
      positivity
    refine (?_ : (Set.Ici (0 : ℤ)).IsPWO).mono hsub
    exact (bddBelow_Ici.isWF).isPWO
  · -- each Q-degree fiber is finite.
    intro N
    apply Set.Finite.isPWO
    apply Set.Finite.subset (Set.Finite.image
      (fun p : ℤ × ℤ => (toLex (p.2, (0 : ℤ)) : ExpXY)) (zDeg_finite_fiber N))
    rintro y ⟨⟨k, l⟩, hkl⟩
    simp only at hkl
    refine ⟨(k, l), ?_, ?_⟩
    · have h1 : (ofLex (zExp k l)).1 = N := by rw [hkl]; rfl
      simpa [zExp, expQXY] using h1
    · have h2 : (ofLex (zExp k l)).2 = y := by rw [hkl]; rfl
      simpa [zExp, expQXY] using h2

/-- The 2D summable family `(k,l) ↦ monom (k²+l²) l 0 ((-1)^{k+l}(δ k − δ l))`. -/
noncomputable def zFamily : HahnSeries.SummableFamily ExpQXY ℚ (ℤ × ℤ) where
  toFun := fun p => monom (p.1 ^ 2 + p.2 ^ 2) p.2 0 (zW p.1 p.2)
  isPWO_iUnion_support' := by
    refine zExp_range_isPWO.mono (Set.iUnion_subset (fun p => ?_))
    intro g hg
    refine ⟨p, ?_⟩
    have : g = expQXY (p.1 ^ 2 + p.2 ^ 2) p.2 0 :=
      HahnSeries.support_single_subset hg
    rw [this]; rfl
  finite_co_support' := by
    intro g
    apply Set.Finite.subset (zDeg_finite_fiber ((ofLex g).1))
    rintro ⟨k, l⟩ hkl
    simp only [Set.mem_setOf_eq] at hkl ⊢
    by_contra hne
    apply hkl
    unfold monom
    rw [HahnSeries.coeff_single_of_ne]
    intro hcon
    apply hne
    -- hcon : g = expQXY (k²+l²) l 0; Q-degree of g is (ofLex g).1 = k²+l².
    rw [hcon]; rfl

/-- `zwegersLHS_x`: the left-hand side of Zwegers' Lemma 10.1. -/
noncomputable def zwegersLHS_x : S := zFamily.hsum

/-! ### Uniqueness from the step-3 functional equation -/

/-! ### Plane-support infrastructure (`y⁰`- and `x⁰`-supported series) -/

/-- `F` is supported in the `y = 0` plane. -/
def YZeroSupported (F : S) : Prop := ∀ a i j, j ≠ 0 → coeffQXY F a i j = 0
/-- `F` is supported in the `x = 0` plane. -/
def XZeroSupported (F : S) : Prop := ∀ a i j, i ≠ 0 → coeffQXY F a i j = 0

/-- The `y`-degree projection of `expQXY a i j` is `j`. -/
@[simp] theorem ydeg_expQXY (a i j : ℤ) : (ofLex (ofLex (expQXY a i j)).2).2 = j := rfl
/-- The `x`-degree projection of `expQXY a i j` is `i`. -/
@[simp] theorem xdeg_expQXY (a i j : ℤ) : (ofLex (ofLex (expQXY a i j)).2).1 = i := rfl
/-- The `q`-degree projection of `expQXY a i j` is `a`. -/
@[simp] theorem qdeg_expQXY (a i j : ℤ) : (ofLex (expQXY a i j)).1 = a := rfl

/-! ### The Zwegers RHS and the main identity (Lemma 10.1, `x`-version)

We state Zwegers' Lemma 10.1 in the `poch_q2`-cleared form
`embedQ poch_q2 · LHS = - (Q x⁻¹) · embedQ poch_q · Θ(x;q²) · Θ(x;q)`
(verified numerically; design `chan3-Ch10-twovar-source-route.md`).  `thetaX_q := thetaMon 3 0 1 0`,
`thetaX_q2 := thetaMon 6 0 1 0`. -/

/-- `Θ(x;q) = thetaMon 3 0 1 0`. -/
noncomputable def thetaX_q : S := thetaMon 3 0 1 0 (by norm_num)
/-- `Θ(x;q²) = thetaMon 6 0 1 0`. -/
noncomputable def thetaX_q2 : S := thetaMon 6 0 1 0 (by norm_num)

/-- The product family `Θ(x;q²)·Θ(x;q)` as a `SummableFamily` over `ℤ × ℤ`. -/
noncomputable def thetaProdX : HahnSeries.SummableFamily ExpQXY ℚ (ℤ × ℤ) :=
  HahnSeries.SummableFamily.mul (thetaFamily 6 0 1 0 (by norm_num)) (thetaFamily 3 0 1 0 (by norm_num))

/-- `zwegersRHS_x` (cleared form): `- (Q x⁻¹) · embedQ poch_q · Θ(x;q²) · Θ(x;q)`. -/
noncomputable def zwegersRHS_x : S :=
  - monom 1 (-1) 0 1 * embedQ poch_q * thetaX_q2 * thetaX_q

/-! The five irreducible analytic inputs of Zwegers' proof (Chen Eq. 10.34–10.38), each a
one-variable `K`-identity / per-slice functional equation, numerically verified in
`chan3-Ch10-twovar-source-route.md` and `/tmp/zwfe.py`.  These are the genuinely-resistant
pieces (per the design's flagged candidates), isolated as documented `sorry`s with their
exact statements; everything that consumes them is proved unconditionally. -/

/-! ### General one-variable `K`-theta objects `J(z;Q^A)` and the Zwegers slice reductions

We reduce both slices `coeffXY zwegersLHS_x j 0` (`j=0,1,2`) and
`coeffXY (thetaX_q2*thetaX_q) m 0` (`m=1,2,3`) to one-variable theta sums
`J = ∑'_r single (A·T r + e·r) (w r)` (a `K`-element), then to the two product
identities `P0`/`P12`. -/

/-- The general `K`-summable theta family `r ↦ single (A·T r + e·r) (w r)`, for `0 < A`
(mirror of `kThetaGen`, with arbitrary nome exponent `A`). -/
noncomputable def JKFamily (A e : ℤ) (hA : 0 < A) (w : ℤ → ℚ) :
    HahnSeries.SummableFamily ℤ ℚ ℤ where
  toFun := fun r => HahnSeries.single (thetaQDeg A e r) (w r)
  isPWO_iUnion_support' := by
    have hb := thetaQDeg_bddBelow A e hA
    refine (hb.isWF.isPWO).mono (Set.iUnion_subset (fun r => ?_))
    intro x hx
    have hxe : x = thetaQDeg A e r := HahnSeries.support_single_subset hx
    exact ⟨r, hxe.symm⟩
  finite_co_support' := by
    intro g
    apply Set.Finite.subset (thetaQDeg_finite_fiber A e hA g)
    intro r hr
    simp only [Set.mem_setOf_eq] at hr
    by_contra hne
    apply hr
    rw [HahnSeries.coeff_single_of_ne]
    intro hcon
    exact hne hcon.symm

/-- `J(z;Q^A) = ∑'_r (w r)·Q^{A·T r + e·r}` as a `K`-element. -/
noncomputable def JK (A e : ℤ) (hA : 0 < A) (w : ℤ → ℚ) : K := (JKFamily A e hA w).hsum

/-- The four `J`'s appearing in the Zwegers slices (in `Q`-notation, `q=Q³`):
`J(Q^15;Q^18)`, `J(Q^9;Q^18)`, `J(-1;Q^9)`, `J(-Q^6;Q^9)`. -/
noncomputable def JQ15 : K := JK 18 15 (by norm_num) (fun r => (-1) ^ r)
noncomputable def JQ9  : K := JK 18 9  (by norm_num) (fun r => (-1) ^ r)
noncomputable def Jneg1 : K := JK 9 0 (by norm_num) (fun _ => 1)
noncomputable def JnegQ6 : K := JK 9 6 (by norm_num) (fun _ => 1)

/-! ### Layer F — K-level arithmetic-progression `q`-Pochhammer products

We transport the committed formal-power-series AP product `qPochAPPS ℚ r m = (X^r;X^m)_∞`
(`JTPFormalPSPentagonal`) into `K = ℚ((Q))` via the ring map `ofPSK` (`X ↦ Q`), obtaining the
infinite products `apK r m = (Q^r;Q^m)_∞` and (with the `(1+X^…)` factors) the signed variants.
The single-factor coefficient-stabilization lemma `coeff_mul_apFactorPS_eq_of_lt` (Pentagonal)
is the only analytic input; everything below is the AP-product *algebra* that, together with the
two Jacobi-triple-product product-forms (isolated as `JTP_*` below), reduces `P0`/`P12` to the
common mod-18 AP product.  Numerically verified (`/tmp/zwnum.py`). -/

open scoped PowerSeries.WithPiTopology
open QseriesFormalization.Pending.JTPFormalPSPentagonal (qPochAPPS apFactorPS
     )

/-- `apK r m = (Q^r;Q^m)_∞ ∈ K`, the image under `ofPSK` of the formal AP product. -/
noncomputable def apK (r m : ℕ) : K := ofPSK (qPochAPPS ℚ r m)

/-- The partial product `∏_{n<N} (1 - X^{r+m n})` in `ℚ⟦X⟧`. -/
noncomputable def apPartialPS (r m N : ℕ) : PowerSeries ℚ :=
  ∏ n ∈ Finset.range N, apFactorPS ℚ r m n

/-! ### Negative AP products `apKneg r m = (−Q^r;Q^m)_∞` and the sign-pairing

We mirror `apK` with the `(1 + X^{r+mn})` factors.  Multipliability is the same `order → ∞`
argument (sign-independent).  The single nontrivial fact is the **sign-pairing**
`(Q^k;Q^m)_∞ · (−Q^k;Q^m)_∞ = (Q^{2k};Q^{2m})_∞`, i.e. `apK k m · apKneg k m = apK (2k) (2m)`,
which is the factorwise `(1−X^j)(1+X^j) = 1−X^{2j}` lifted through `HasProd.mul`. -/

/-- The formal factor `1 + X^(r + m n)`. -/
noncomputable def apFactorNegPS (r m n : ℕ) : PowerSeries ℚ :=
  (1 : PowerSeries ℚ) + PowerSeries.X ^ (r + m * n)

/-- The formal negative AP product `(−Q^r;Q^m)_∞ = ∏_{n≥0} (1 + X^(r+mn))`. -/
noncomputable def qPochAPNegPS (r m : ℕ) : PowerSeries ℚ :=
  ∏' n : ℕ, apFactorNegPS r m n

/-- `apKneg r m = (−Q^r;Q^m)_∞ ∈ K`, the image under `ofPSK` of the formal negative AP product. -/
noncomputable def apKneg (r m : ℕ) : K := ofPSK (qPochAPNegPS r m)

/-! ### The two product identities `P0`/`P12` (JTP + mod-18 AP splitting)

Both `(P0)` and `(P12)` reduce, by the Jacobi triple product and the AP-product pairing
`(q;q³)(−q;q³)=(q²;q⁶)` etc., to the *same* mod-18 arithmetic-progression product.  See the design
doc §"The two product identities".  Numerically verified (`/tmp/zwnum.py`) to high order. -/

/-! #### Bridges to the HM Laurent layer (`jLaurent`, `qPochAPLaurent`)

`K = HahnSeries ℤ ℚ = QLaurent` definitionally, so the HM objects live in `K`.  We bridge the
alternating thetas `JQ15`, `JQ9` to `jLaurent` (HM's coefficient-defined alternating theta), and
`apK` is literally `qPochAPLaurent`. -/

section HMBridge
open QseriesFormalization.Pending.Ch10HM

end HMBridge

/-! #### RHS product forms and AP refinements (free from the HM Laurent layer)

The alternating thetas `JQ15`/`JQ9` factor by the (positive) Jacobi triple product
`jLaurent_eq_tripleProductInf`, and the pochhammers `poch_q = apK 3 3`, `poch_q2 = apK 6 6`
refine into mod-18 APs by `qPochAPLaurent_refine_mul`.  These are the RHS-side ingredients
of `P0`/`P12`; all are transported verbatim from the committed HM layer. -/

section RHSForms
open QseriesFormalization.Pending.Ch10HM

/-! #### Mod-18 refinements of the level-9 AP products (for the `P12` clearing). -/

end RHSForms

/-! ### The two negative Jacobi triple product *product forms* (genuine analytic input)

These are the sole remaining analytic facts: the bilateral all-`+1`-weight theta
`J(−z;q) = ∑_r z^r q^{T r}` equals the Jacobi-triple-product
`(q;q)_∞ (−z;q)_∞ (−q/z;q)_∞`, instantiated at `(z,q) = (1,Q⁹)` and `(Q⁶,Q⁹)`:

  `Jneg1  = 2·(−Q⁹;Q⁹)_∞²·(Q⁹;Q⁹)_∞ = 2·apKneg 9 9·apKneg 9 9·apK 9 9`,
  `JnegQ6 = (−Q³;Q⁹)_∞·(−Q⁶;Q⁹)_∞·(Q⁹;Q⁹)_∞ = apKneg 3 9·apKneg 6 9·apK 9 9`.

(The factor `2` for `Jneg1` is the `z=1` degeneracy: the `r ↦ 1−r` symmetry of the
exponent `9·T(r)` doubles the constant term.)  Both are the negative-`z`
(`z ↦ −Qpow a`) instance of HM's `jLaurent_eq_tripleProductInf` chain; numerically
verified to `Q^400`. -/

section NegJTPChain
open QseriesFormalization.Pending.Ch10HM

/-! #### The negative-`z` Jacobi triple product chain (`0 < a < b`)

We mirror HM's positive chain (`jLaurent_eq_tripleProductInf`) but instantiate Chan's finite
JTP at `z = −Qpow a`.  Then `(−z)^l = (Qpow a)^l = Qpow(a·l)`, so the alternating `(-1)^l`
weight disappears and the RHS becomes the **all-`+1`** theta `∑_r Q^{b·T(r)+a·r}`.  The product
factors `(z;q)_N (z⁻¹q;q)_N` become the `apKneg` partials `(−Q^a;Q^b)_N (−Q^{b-a};Q^b)_N`.
All product-side / Gaussian-binomial / window machinery is sign-independent and reused verbatim
from HM; only the term-weight changes from `negOnePowIntQ` to `1`. -/

/-! ##### Bridge: my `Qpow`/`.coeff` are defeq to HM's `Qpow`/`lcoeff`. -/

/-! ##### The negative triple-product partial and its coefficient (heart of the chain). -/

/-- The finite negative triple-product partial `(Q^b;Q^b)_N (−Q^a;Q^b)_N (−Q^{b-a};Q^b)_N`. -/
noncomputable def jNegProductPartial (a b : ℤ) (N : ℕ) : K :=
  qPochhammer (Qpow b) N * (qPoch (-(Qpow a)) (Qpow b) N * qPoch (-(Qpow (b - a))) (Qpow b) N)

/-! ##### Product side: the partial product as a formal power series and its stabilization. -/

/-- The `n`-th formal factor of the negative triple product. -/
noncomputable def jNegTripleFactorPS (A B n : ℕ) : PowerSeries ℚ :=
  apFactorPS ℚ B B n * apFactorNegPS A B n * apFactorNegPS (B - A) B n

/-- The infinite negative triple product on the formal-PS side. -/
noncomputable def jNegTripleProductInfPS (A B : ℕ) : PowerSeries ℚ :=
  qPochAPPS ℚ B B * qPochAPNegPS A B * qPochAPNegPS (B - A) B

/-! ##### The degenerate `A = 0` case (for `Jneg1`, `z = 1`).

The general theorem needs `0 < A` only through the window/degree bounds
`abs_le_jExp_of_pos_lt` and `degree_sub_lt_center_start` (the Gaussian collapse and product side
are `A`-independent).  For `A = 0` those *exact* bounds fail at `n = 1` (`jExp 0 B 1 = 0`), but the
weaker facts they are used for still hold.  We reprove just those two facts for `A = 0`, then mirror
the heart / extensionality with `A = 0`. -/

/-! ##### `A = 0` heart and extensionality. -/

end NegJTPChain

/-! ### `P0`/`P12` reduced to the two `apKneg`-cleared negative-JTP identities

All the AP-product *algebra* below is now fully proved (RHS triple products `JQ15_prod`/`JQ9_prod`,
the mod-18 refinements `apK_*_refine`, the sign-pairing `apK_mul_apKneg`, the nonzero lemmas
`apK_ne_zero`, and the domain structure of `K = HahnSeries ℤ ℚ`).  Multiplying `P0` through by the
nonzero factor `apK 9 18` and `P12` through by `apK 3 18·apK 15 18`, and cancelling, reduces each to
a single **cleared negative Jacobi-triple-product identity** (numerically verified, `verify6.py`):

  `Jneg1 · apK 9 18                = single 0 2 · apK 18 18`,
  `JnegQ6 · apK 3 18 · apK 15 18   = apK 9 18 · apK 18 18`.

These two are the genuine remaining analytic input — the bilateral all-`+1`-weight theta sum
`J(−z;q) = ∑_r z^r q^{T r}` equals an arithmetic-progression product.  They are the negative-`z`
(`z ↦ −Qpow a`) instance of HM's `jLaurent_eq_tripleProductInf` chain (finite JTP `z = −Qpow a` →
coefficient stabilization → infinite `(±Q^·;Q^·)_∞` product), isolated here as the sole `sorry`. -/

/-! ### `y`-version (by the same argument with `x ↔ y`). -/

/-- `Θ(y;q) = thetaMon 3 0 0 1`. -/
noncomputable def thetaY_q : S := thetaMon 3 0 0 1 (by norm_num)
/-- `Θ(y;q²) = thetaMon 6 0 0 1`. -/
noncomputable def thetaY_q2 : S := thetaMon 6 0 0 1 (by norm_num)

/-- The 2D summable family for the Zwegers LHS, `y`-version
(`monom (k²+l²) 0 l ((-1)^{k+l}(δ k − δ l))`). -/
noncomputable def zFamilyY : HahnSeries.SummableFamily ExpQXY ℚ (ℤ × ℤ) where
  toFun := fun p => monom (p.1 ^ 2 + p.2 ^ 2) 0 p.2 (zW p.1 p.2)
  isPWO_iUnion_support' := by
    -- mirror of zFamily: Q-degree k²+l² bddBelow with finite fibers; x/y slot now (0, l).
    have hrange : (Set.range (fun p : ℤ × ℤ => expQXY (p.1 ^ 2 + p.2 ^ 2) 0 p.2)).IsPWO := by
      apply Set.PartiallyWellOrderedOn.subsetProdLex
      · have hsub : (fun (z : ℤ ×ₗ ExpXY) => (ofLex z).1) ''
            Set.range (fun p : ℤ × ℤ => expQXY (p.1 ^ 2 + p.2 ^ 2) 0 p.2) ⊆ Set.Ici (0 : ℤ) := by
          rintro a ⟨z, ⟨⟨k, l⟩, rfl⟩, rfl⟩
          simp only [expQXY, ofLex_toLex, Set.mem_Ici]; positivity
        refine (?_ : (Set.Ici (0 : ℤ)).IsPWO).mono hsub
        exact (bddBelow_Ici.isWF).isPWO
      · intro N
        apply Set.Finite.isPWO
        apply Set.Finite.subset (Set.Finite.image
          (fun p : ℤ × ℤ => (toLex ((0 : ℤ), p.2) : ExpXY)) (zDeg_finite_fiber N))
        rintro y ⟨⟨k, l⟩, hkl⟩
        simp only at hkl
        refine ⟨(k, l), ?_, ?_⟩
        · have h1 : (ofLex (expQXY (k ^ 2 + l ^ 2) 0 l)).1 = N := by rw [hkl]; rfl
          simpa [expQXY] using h1
        · have h2 : (ofLex (expQXY (k ^ 2 + l ^ 2) 0 l)).2 = y := by rw [hkl]; rfl
          simpa [expQXY] using h2
    refine hrange.mono (Set.iUnion_subset (fun p => ?_))
    intro g hg
    refine ⟨p, ?_⟩
    have hgeq : g = expQXY (p.1 ^ 2 + p.2 ^ 2) 0 p.2 := HahnSeries.support_single_subset hg
    rw [hgeq]
  finite_co_support' := by
    intro g
    apply Set.Finite.subset (zDeg_finite_fiber ((ofLex g).1))
    rintro ⟨k, l⟩ hkl
    simp only [Set.mem_setOf_eq] at hkl ⊢
    by_contra hne
    apply hkl
    unfold monom
    rw [HahnSeries.coeff_single_of_ne]
    intro hcon
    apply hne
    rw [hcon]; rfl

/-- `zwegersLHS_y`: the left-hand side of Zwegers' Lemma 10.1, `y`-version. -/
noncomputable def zwegersLHS_y : S := zFamilyY.hsum

/-- `zwegersRHS_y` (cleared form): `- (Q y⁻¹) · embedQ poch_q · Θ(y;q²) · Θ(y;q)`. -/
noncomputable def zwegersRHS_y : S :=
  - monom 1 0 (-1) 1 * embedQ poch_q * thetaY_q2 * thetaY_q

/-! The `y`-version analytic inputs (mirror of the `x`-version under `x ↔ y`). -/

/-- The product family `Θ(y;q²)·Θ(y;q)` as a `SummableFamily`. -/
noncomputable def thetaProdY : HahnSeries.SummableFamily ExpQXY ℚ (ℤ × ℤ) :=
  HahnSeries.SummableFamily.mul (thetaFamily 6 0 0 1 (by norm_num)) (thetaFamily 3 0 0 1 (by norm_num))

/-! ### `y`-mirror slice reductions (identical to the `x`-side with the slots swapped). -/

/-! ## Layer F — Hickerson Lemma 10.2 via ρ-line strings

The multiplied form of Hickerson's Lemma 10.2:
`Θ(x;q) · Θ(y;q) · Rho = (q;q)∞³ · Θ(xy; q)` (in our normalisation
`thetaX_q * thetaY_q * Rho = embedQ (poch_q^3) * thetaMon 3 0 1 1`).

`Rho` is the two-variable Hahn series whose `Q^{3rs} x^r y^s` coefficient is the
ρ-line sign `ρ(r,s)` (`1` on the closed first quadrant, `-1` on the open third
quadrant, `0` elsewhere).  Its support is the union of the two nonnegative axes
(at `Q`-degree `0`) together with finite divisor fibres at each positive `Q`-degree,
which is partially well-ordered in the `q`-first lexicographic order. -/

/-- The ρ-line sign: `1` on the closed first quadrant, `-1` on the open third
quadrant, `0` otherwise. -/
def rho (r s : ℤ) : ℚ :=
  if 0 ≤ r ∧ 0 ≤ s then 1 else if r < 0 ∧ s < 0 then -1 else 0

/-- On the support of `ρ`, the product `r·s` is nonnegative (closed-1st or open-3rd
quadrant), so the candidate `Q`-degree `3·r·s` is `≥ 0`. -/
theorem rho_support_nonneg_q {r s : ℤ} (h : rho r s ≠ 0) : 0 ≤ 3 * r * s := by
  unfold rho at h
  by_cases h1 : 0 ≤ r ∧ 0 ≤ s
  · have hrs : 0 ≤ r * s := mul_nonneg h1.1 h1.2
    nlinarith [hrs]
  · rw [if_neg h1] at h
    by_cases h2 : r < 0 ∧ s < 0
    · have hrs : 0 ≤ r * s := by nlinarith [h2.1, h2.2]
      nlinarith [hrs]
    · rw [if_neg h2] at h; exact absurd rfl h

/-- The `Q`-degree-`0` fibre of `ρ`: `3·r·s = 0` and `ρ r s ≠ 0` force one coordinate to be
`0` and the other nonnegative — i.e. the two nonnegative coordinate axes. -/
theorem rho_q_zero_fiber {r s : ℤ} (hq : 3 * r * s = 0) (h : rho r s ≠ 0) :
    (r = 0 ∧ 0 ≤ s) ∨ (s = 0 ∧ 0 ≤ r) := by
  have hrs : r * s = 0 := by
    have : 3 * (r * s) = 0 := by linarith [hq]
    omega
  rcases mul_eq_zero.mp hrs with hr | hs
  · left
    refine ⟨hr, ?_⟩
    unfold rho at h
    by_cases h1 : 0 ≤ r ∧ 0 ≤ s
    · exact h1.2
    · rw [if_neg h1] at h
      by_cases h2 : r < 0 ∧ s < 0
      · omega
      · rw [if_neg h2] at h; exact absurd rfl h
  · right
    refine ⟨hs, ?_⟩
    unfold rho at h
    by_cases h1 : 0 ≤ r ∧ 0 ≤ s
    · exact h1.1
    · rw [if_neg h1] at h
      by_cases h2 : r < 0 ∧ s < 0
      · omega
      · rw [if_neg h2] at h; exact absurd rfl h

/-- The `Q`-degree-`N` fibre of `ρ` for `N > 0` is finite (divisor pairs of `N/3`). -/
theorem rho_positive_q_fiber_finite {N : ℤ} (hN : 0 < N) :
    {p : ℤ × ℤ | 3 * p.1 * p.2 = N ∧ rho p.1 p.2 ≠ 0}.Finite := by
  -- both coordinates are bounded by N in absolute value (since |r|,|s| ≥ 1 and |r·s| = N/3 ≤ N).
  apply Set.Finite.subset (Set.finite_Icc ((-N, -N) : ℤ × ℤ) ((N, N) : ℤ × ℤ))
  rintro ⟨r, s⟩ ⟨hq, hne⟩
  simp only at hq hne
  have hrs_pos : 0 < r * s := by nlinarith [hN, hq]
  have hr_le : r * s ≤ N := by
    have : 3 * (r * s) = N := by linarith [hq]
    omega
  rw [Set.mem_Icc, Prod.le_def, Prod.le_def]
  -- r and s have the same sign (product positive); each has |·| ≤ |r·s| ≤ N.
  rcases (mul_pos_iff.mp hrs_pos) with ⟨hrp, hsp⟩ | ⟨hrn, hsn⟩
  · -- both positive: 1 ≤ r, 1 ≤ s ⟹ r ≤ r*s ≤ N, s ≤ r*s ≤ N.
    refine ⟨⟨by linarith [hrp, hN], by linarith [hsp, hN]⟩,
      by nlinarith [hrp, hsp, hr_le], by nlinarith [hrp, hsp, hr_le]⟩
  · -- both negative: r ≤ -1, s ≤ -1 ⟹ -r ≤ r*s ≤ N i.e. r ≥ -N, similarly s ≥ -N.
    refine ⟨⟨by nlinarith [hrn, hsn, hr_le], by nlinarith [hrn, hsn, hr_le]⟩,
      by linarith [hrn, hN], by linarith [hsn, hN]⟩

/-- The two nonnegative coordinate axes in `ExpXY = Lex (ℤ × ℤ)` are partially well-ordered. -/
theorem axes_isPWO :
    {y : ExpXY | (((ofLex y).1 = 0 ∧ 0 ≤ (ofLex y).2) ∨
        ((ofLex y).2 = 0 ∧ 0 ≤ (ofLex y).1))}.IsPWO := by
  apply Set.PartiallyWellOrderedOn.subsetProdLex
  · -- x-degree projection ⊆ Ici 0.
    have hsub : (fun (x : ℤ ×ₗ ℤ) => (ofLex x).1) ''
        {y : ExpXY | (((ofLex y).1 = 0 ∧ 0 ≤ (ofLex y).2) ∨
          ((ofLex y).2 = 0 ∧ 0 ≤ (ofLex y).1))} ⊆ Set.Ici (0 : ℤ) := by
      rintro a ⟨y, hy, rfl⟩
      simp only [Set.mem_Ici]
      rcases hy with ⟨h1, _⟩ | ⟨_, h2⟩
      · exact le_of_eq h1.symm
      · exact h2
    refine (?_ : (Set.Ici (0 : ℤ)).IsPWO).mono hsub
    exact (bddBelow_Ici.isWF).isPWO
  · -- fibre at x-degree `a`: `Ici 0` (a = 0, PWO) or ⊆ {0} (a > 0, finite) or ∅ (a < 0).
    intro a
    by_cases ha : a = 0
    · -- a = 0: fibre = {j : 0 ≤ j} = Ici 0, which is PWO.
      apply (bddBelow_Ici (a := (0 : ℤ))).isWF.isPWO.mono
      intro j hj
      simp only [Set.mem_setOf_eq, ofLex_toLex] at hj
      rw [Set.mem_Ici]
      rcases hj with ⟨_, h2⟩ | ⟨h2, h3⟩
      · exact h2
      · omega
    · -- a ≠ 0: fibre ⊆ {0}, finite hence PWO.
      apply Set.Finite.isPWO
      apply Set.Finite.subset (Set.finite_singleton (0 : ℤ))
      intro j hj
      simp only [Set.mem_setOf_eq, ofLex_toLex] at hj
      rcases hj with ⟨h1, _⟩ | ⟨h2, _⟩
      · exact absurd h1 ha
      · exact h2

/-- The defining coefficient of `Rho`: `ρ(r,s)` at the exponent `Q^{3rs} x^r y^s`, `0` elsewhere. -/
noncomputable def rhoCoeff (z : ExpQXY) : ℚ :=
  if (ofLex z).1 = 3 * (ofLex (ofLex z).2).1 * (ofLex (ofLex z).2).2
  then rho (ofLex (ofLex z).2).1 (ofLex (ofLex z).2).2 else 0

/-- The support of `rhoCoeff` is partially well-ordered in the `q`-first lex order. -/
theorem rhoCoeff_isPWO : (Function.support rhoCoeff).IsPWO := by
  apply Set.PartiallyWellOrderedOn.subsetProdLex
  · -- q-degree projection ⊆ Ici 0 (on the support, qDeg = 3rs ≥ 0).
    have hsub : (fun (z : ℤ ×ₗ ExpXY) => (ofLex z).1) '' Function.support rhoCoeff
        ⊆ Set.Ici (0 : ℤ) := by
      rintro a ⟨z, hz, rfl⟩
      simp only [Function.mem_support, rhoCoeff] at hz
      simp only [Set.mem_Ici]
      by_cases hc : (ofLex z).1 = 3 * (ofLex (ofLex z).2).1 * (ofLex (ofLex z).2).2
      · rw [if_pos hc] at hz
        rw [hc]
        exact rho_support_nonneg_q hz
      · rw [if_neg hc] at hz; exact absurd rfl hz
    refine (?_ : (Set.Ici (0 : ℤ)).IsPWO).mono hsub
    exact (bddBelow_Ici.isWF).isPWO
  · -- fibre at q-degree N: axes (N = 0) / finite (N > 0) / empty (N < 0).
    intro N
    by_cases hN : 0 < N
    · -- N > 0: finite fibre.
      apply Set.Finite.isPWO
      apply Set.Finite.subset
        (Set.Finite.image (fun p : ℤ × ℤ => (toLex (p.1, p.2) : ExpXY))
          (rho_positive_q_fiber_finite hN))
      intro y hy
      simp only [Set.mem_setOf_eq, Function.mem_support] at hy
      -- hy : rhoCoeff (toLex (N, y)) ≠ 0.
      rw [rhoCoeff, ofLex_toLex] at hy
      by_cases hc : N = 3 * (ofLex y).1 * (ofLex y).2
      · refine ⟨((ofLex y).1, (ofLex y).2), ⟨hc.symm, ?_⟩, rfl⟩
        rw [if_pos hc] at hy
        exact hy
      · rw [if_neg hc] at hy; exact absurd rfl hy
    · -- N ≤ 0: split into N = 0 (axes) and N < 0 (empty).
      push_neg at hN
      rcases lt_or_eq_of_le hN with hlt | heq
      · -- N < 0: empty fibre.
        apply Set.Finite.isPWO
        convert Set.finite_empty
        ext y
        simp only [Set.mem_setOf_eq, Set.mem_empty_iff_false, iff_false, Function.mem_support]
        rw [rhoCoeff, ofLex_toLex]
        by_cases hc : N = 3 * (ofLex y).1 * (ofLex y).2
        · rw [if_pos hc]
          intro hne
          have hge := rho_support_nonneg_q hne
          rw [← hc] at hge
          omega
        · rw [if_neg hc]; exact fun h => h rfl
      · -- N = 0: fibre ⊆ axes (PWO).
        subst heq
        apply axes_isPWO.mono
        intro y hy
        simp only [Set.mem_setOf_eq, Function.mem_support] at hy
        rw [rhoCoeff, ofLex_toLex] at hy
        by_cases hc : (0 : ℤ) = 3 * (ofLex y).1 * (ofLex y).2
        · rw [if_pos hc] at hy
          exact rho_q_zero_fiber (by linarith [hc]) hy
        · rw [if_neg hc] at hy; exact absurd rfl hy

/-- `Rho`: the two-variable Hahn series with coefficient `ρ(r,s)` at `Q^{3rs} x^r y^s`. -/
noncomputable def Rho : S where
  coeff := rhoCoeff
  isPWO_support' := rhoCoeff_isPWO

/-! ### String machinery: `StringSumQ` -/

/-- The ρ-line string sum `∑'_s Q^{3ds} ρ(m-s, s)` in `K = ℚ((Q))`.  The string support
`{s : ρ(m-s,s) ≠ 0}` is a finite interval, so this finsum is a genuine finite sum. -/
noncomputable def StringSumQ (m d : ℤ) : K :=
  ∑ᶠ s : ℤ, HahnSeries.single (3 * d * s) (rho (m - s) s)

/-- The string support `{s : ρ(m-s,s) ≠ 0}` is finite (a contiguous interval). -/
theorem stringSupp_finite (m : ℤ) : {s : ℤ | rho (m - s) s ≠ 0}.Finite := by
  apply Set.Finite.subset (Set.finite_Icc (min 0 (m + 1)) (max m (-1)))
  intro s hs
  simp only [Set.mem_setOf_eq] at hs
  rw [Set.mem_Icc]
  unfold rho at hs
  by_cases h1 : 0 ≤ m - s ∧ 0 ≤ s
  · constructor <;> omega
  · rw [if_neg h1] at hs
    by_cases h2 : m - s < 0 ∧ s < 0
    · constructor <;> omega
    · rw [if_neg h2] at hs; exact absurd rfl hs

/-- The support of the summand `s ↦ single (3ds) ρ(m-s,s)` is contained in the string support. -/
theorem stringSummand_support_finite (m d : ℤ) :
    (Function.support (fun s : ℤ => HahnSeries.single (3 * d * s) (rho (m - s) s))).Finite := by
  apply (stringSupp_finite m).subset
  intro s hs
  simp only [Function.mem_support] at hs
  simp only [Set.mem_setOf_eq]
  intro hc
  apply hs
  rw [hc, HahnSeries.single_eq_zero]

/-! ### `Rho` as a summable family over `(r,s) : ℤ × ℤ` -/

/-- The ρ summable family `(r,s) ↦ monom (3rs) (x^r y^s) (ρ r s)`. -/
noncomputable def rhoFamily : HahnSeries.SummableFamily ExpQXY ℚ (ℤ × ℤ) where
  toFun := fun p => monom (3 * p.1 * p.2) p.1 p.2 (rho p.1 p.2)
  isPWO_iUnion_support' := by
    refine rhoCoeff_isPWO.mono (Set.iUnion_subset (fun p => ?_))
    intro g hg
    have hgeq : g = expQXY (3 * p.1 * p.2) p.1 p.2 := HahnSeries.support_single_subset hg
    -- g ∈ support of rhoCoeff: rhoCoeff g ≠ 0.
    rw [HahnSeries.mem_support] at hg
    simp only [Function.mem_support]
    rw [hgeq, rhoCoeff, qdeg_expQXY, xdeg_expQXY, ydeg_expQXY, if_pos rfl]
    -- need rho p.1 p.2 ≠ 0; from hg (monom coeff nonzero).
    unfold monom at hg
    rw [HahnSeries.coeff_single, if_pos hgeq] at hg
    exact hg
  finite_co_support' := by
    intro g
    -- only (r,s) = (xdeg g, ydeg g) can contribute (the monom is supported at one exponent).
    apply Set.Finite.subset (Set.finite_singleton
      ((ofLex (ofLex g).2).1, (ofLex (ofLex g).2).2))
    intro p hp
    simp only [Set.mem_singleton_iff] at hp ⊢
    by_contra hne
    apply hp
    unfold monom
    rw [HahnSeries.coeff_single_of_ne]
    -- expQXY (3 p1 p2) p1 p2 ≠ g, since (p1,p2) ≠ (xdeg g, ydeg g).
    intro hcon
    apply hne
    -- hcon : g = expQXY (3 p1 p2) p1 p2.  Read off x,y degrees.
    have hx : (ofLex (ofLex g).2).1 = p.1 := by rw [hcon, xdeg_expQXY]
    have hy : (ofLex (ofLex g).2).2 = p.2 := by rw [hcon, ydeg_expQXY]
    rw [hx, hy]

/-! ### The triple-product family and the slice extraction -/

/-- The full triple product `Θ(x;q)·Θ(y;q)·Rho` as a summable family over `(ℤ×ℤ)×(ℤ×ℤ)`. -/
noncomputable def prodFam : HahnSeries.SummableFamily ExpQXY ℚ ((ℤ × ℤ) × (ℤ × ℤ)) :=
  HahnSeries.SummableFamily.mul
    (HahnSeries.SummableFamily.mul (thetaFamily 3 0 1 0 (by norm_num))
      (thetaFamily 3 0 0 1 (by norm_num))) rhoFamily

/-- The reindexing bijection mapping the new index `(t,s)` to the old `(k,l) = (t+s, b-s)`
(so that `t = k+l-b`, `s = b-l`). -/
def reindexKL (b : ℤ) : (ℤ × ℤ) ≃ (ℤ × ℤ) where
  toFun := fun q => (q.1 + q.2, b - q.2)
  invFun := fun p => (p.1 + p.2 - b, b - p.2)
  left_inv := by rintro ⟨t, s⟩; simp only [Prod.mk.injEq]; constructor <;> ring
  right_inv := by rintro ⟨k, l⟩; simp only [Prod.mk.injEq]; constructor <;> ring

/-! ### The slice as a single `t`-finsum, and the off-diagonal / diagonal evaluations -/

/-- Coefficient of `StringSumQ m d` at a `Q`-degree `E`. -/
theorem StringSumQ_coeff (m d E : ℤ) :
    (StringSumQ m d).coeff E = ∑ᶠ s : ℤ, (if 3 * d * s = E then rho (m - s) s else 0) := by
  unfold StringSumQ
  show (HahnSeries.coeff.addMonoidHom E) (∑ᶠ s : ℤ, HahnSeries.single (3 * d * s) (rho (m - s) s))
    = _
  rw [(HahnSeries.coeff.addMonoidHom E).map_finsum (stringSummand_support_finite m d)]
  apply finsum_congr
  intro s
  show (HahnSeries.single (3 * d * s) (rho (m - s) s)).coeff E = _
  rw [HahnSeries.coeff_single]
  by_cases h : 3 * d * s = E
  · rw [if_pos h, if_pos h.symm]
  · rw [if_neg h, if_neg (fun hc => h hc.symm)]

/-- The single-`t` term of the slice: `(-1)^{b+t} · Q^{3Tb+3Tt} · StringSumQ(a-t, a-b)`. -/
noncomputable def sliceTterm (a b t : ℤ) : K :=
  ((-1 : ℚ) ^ (b + t)) • (Qpow (3 * Tn b + 3 * Tn t) * StringSumQ (a - t) (a - b))

/-- Coefficient of `sliceTterm a b t` at `Q`-degree `D`. -/
theorem sliceTterm_coeff (a b t D : ℤ) :
    (sliceTterm a b t).coeff D
      = ∑ᶠ s : ℤ,
          (if 3 * Tn b + 3 * Tn t + 3 * (a - b) * s = D
            then (-1) ^ (b + t) * rho (a - t - s) s else 0) := by
  unfold sliceTterm
  rw [HahnSeries.coeff_smul, smul_eq_mul]
  -- (Qpow C * X).coeff D = X.coeff (D - C).
  rw [show (Qpow (3 * Tn b + 3 * Tn t) * StringSumQ (a - t) (a - b)).coeff D
      = (StringSumQ (a - t) (a - b)).coeff (D - (3 * Tn b + 3 * Tn t)) by
    unfold Qpow; rw [HahnSeries.coeff_single_mul, one_mul]]
  rw [StringSumQ_coeff]
  -- pull the scalar (-1)^{b+t} into the finsum.
  rw [mul_finsum' (fun s : ℤ => if 3 * (a - b) * s = D - (3 * Tn b + 3 * Tn t)
        then rho (a - t - s) s else 0) ((-1) ^ (b + t)) (by
    apply Set.Finite.subset (stringSupp_finite (a - t))
    intro s hs
    simp only [Function.mem_support] at hs
    simp only [Set.mem_setOf_eq]
    intro hc
    apply hs
    by_cases h : 3 * (a - b) * s = D - (3 * Tn b + 3 * Tn t)
    · rw [if_pos h, hc]
    · rw [if_neg h])]
  apply finsum_congr
  intro s
  by_cases h : 3 * (a - b) * s = D - (3 * Tn b + 3 * Tn t)
  · rw [if_pos h, if_pos (by omega : 3 * Tn b + 3 * Tn t + 3 * (a - b) * s = D)]
  · rw [if_neg h, if_neg (by omega : ¬ 3 * Tn b + 3 * Tn t + 3 * (a - b) * s = D), mul_zero]

/-- Each `Q`-degree in the support of `sliceTterm a b t` is `≥ 0`: writing the exponent in the
original `(k,l)` variables, it is `3·T k + 3·T l + 3·r·s` with `T k, T l ≥ 0` and `r·s ≥ 0`
(the latter because `ρ(r,s) ≠ 0`). -/
theorem sliceTterm_support_nonneg (a b t : ℤ) :
    (sliceTterm a b t).support ⊆ Set.Ici (0 : ℤ) := by
  intro E hE
  rw [HahnSeries.mem_support] at hE
  rw [Set.mem_Ici]
  by_contra hneg
  push_neg at hneg
  apply hE
  rw [sliceTterm_coeff]
  apply finsum_eq_zero_of_forall_eq_zero
  intro s
  by_cases hc : 3 * Tn b + 3 * Tn t + 3 * (a - b) * s = E
  · -- this degree is < 0; show the weight ρ vanishes (else the degree would be ≥ 0).
    rw [if_pos hc]
    by_cases hr : rho (a - t - s) s = 0
    · rw [hr, mul_zero]
    · exfalso
      -- via (k,l) = (t+s, b-s): degree = 3Tk+3Tl+3rs with rs = (a-t-s)·s ≥ 0.
      have hrs : 0 ≤ 3 * (a - t - s) * s := rho_support_nonneg_q hr
      have hTk : 0 ≤ Tn (t + s) := Tn_nonneg _
      have hTl : 0 ≤ Tn (b - s) := Tn_nonneg _
      -- 3Tb+3Tt+3(a-b)s = 3T(t+s)+3T(b-s)+3(a-t-s)s   (the reindex exponent identity, reversed).
      have hdeg : 3 * Tn b + 3 * Tn t + 3 * (a - b) * s
          = 3 * Tn (t + s) + 3 * Tn (b - s) + 3 * (a - t - s) * s := by
        have h1 := two_mul_Tn (t + s)
        have h2 := two_mul_Tn (b - s)
        have h3 := two_mul_Tn b
        have h4 := two_mul_Tn t
        have key : 2 * (3 * Tn b + 3 * Tn t + 3 * (a - b) * s)
            = 2 * (3 * Tn (t + s) + 3 * Tn (b - s) + 3 * (a - t - s) * s) := by
          rw [show 2 * (3 * Tn b + 3 * Tn t + 3 * (a - b) * s)
              = 3 * (2 * Tn b) + 3 * (2 * Tn t) + 6 * (a - b) * s by ring, h3, h4,
            show 2 * (3 * Tn (t + s) + 3 * Tn (b - s) + 3 * (a - t - s) * s)
              = 3 * (2 * Tn (t + s)) + 3 * (2 * Tn (b - s)) + 6 * (a - t - s) * s by ring, h1, h2]
          ring
        omega
      rw [hdeg] at hc
      -- E = nonneg + nonneg + nonneg ≥ 0, contradicting E < 0.
      omega
  · rw [if_neg hc]

/-- A crude bound: `Tn n ≤ E` forces `|n| ≤ E + 1`. -/
theorem abs_le_of_Tn_le {n E : ℤ} (h : Tn n ≤ E) : -(E + 1) ≤ n ∧ n ≤ E + 1 := by
  have h2 := two_mul_Tn n
  constructor <;> nlinarith [h, h2, sq_nonneg (n - 1), sq_nonneg (n + 1), Tn_nonneg n]

/-- The co-support of the `sliceTterm`-family at `E` is finite: contributing `t`s lie in a bounded
interval (from `T(t+s) ≤ E/3` and `T(b-s) ≤ E/3`, both forced by nonnegativity). -/
theorem sliceTterm_co_support_finite (a b E : ℤ) :
    {t : ℤ | (sliceTterm a b t).coeff E ≠ 0}.Finite := by
  apply Set.Finite.subset (Set.finite_Icc (-(E + 1) - (E + 1) - b) ((E + 1) + (E + 1) - b))
  intro t ht
  simp only [Set.mem_setOf_eq] at ht
  rw [sliceTterm_coeff] at ht
  rw [Set.mem_Icc]
  -- if t were outside the interval, every s-summand would vanish, making the finsum 0.
  by_contra htbound
  apply ht
  apply finsum_eq_zero_of_forall_eq_zero
  intro s
  by_cases hc : 3 * Tn b + 3 * Tn t + 3 * (a - b) * s = E
  · rw [if_pos hc]
    by_cases hr0 : rho (a - t - s) s = 0
    · rw [hr0, mul_zero]
    · -- a contributing s forces t into the interval, contradicting htbound.
      exfalso
      apply htbound
      have hrs : 0 ≤ 3 * (a - t - s) * s := rho_support_nonneg_q hr0
      have hTk : 0 ≤ Tn (t + s) := Tn_nonneg _
      have hTl : 0 ≤ Tn (b - s) := Tn_nonneg _
      have hdeg : 3 * Tn (t + s) + 3 * Tn (b - s) + 3 * (a - t - s) * s = E := by
        have h1 := two_mul_Tn (t + s)
        have h2 := two_mul_Tn (b - s)
        have h3 := two_mul_Tn b
        have h4 := two_mul_Tn t
        have key : 2 * (3 * Tn (t + s) + 3 * Tn (b - s) + 3 * (a - t - s) * s)
            = 2 * (3 * Tn b + 3 * Tn t + 3 * (a - b) * s) := by
          rw [show 2 * (3 * Tn (t + s) + 3 * Tn (b - s) + 3 * (a - t - s) * s)
              = 3 * (2 * Tn (t + s)) + 3 * (2 * Tn (b - s)) + 6 * (a - t - s) * s by ring, h1, h2,
            show 2 * (3 * Tn b + 3 * Tn t + 3 * (a - b) * s)
              = 3 * (2 * Tn b) + 3 * (2 * Tn t) + 6 * (a - b) * s by ring, h3, h4]
          ring
        have hc2 : 2 * (3 * Tn b + 3 * Tn t + 3 * (a - b) * s) = 2 * E := by rw [hc]
        linarith [key, hc2]
      have hTtsE : Tn (t + s) ≤ E := by omega
      have hTbsE : Tn (b - s) ≤ E := by omega
      obtain ⟨hts_lb, hts_ub⟩ := abs_le_of_Tn_le hTtsE
      obtain ⟨hbs_lb, hbs_ub⟩ := abs_le_of_Tn_le hTbsE
      constructor <;> omega
  · rw [if_neg hc]

/-- The slice summable family `t ↦ sliceTterm a b t` over `ℤ`. -/
noncomputable def sliceTFamily (a b : ℤ) : HahnSeries.SummableFamily ℤ ℚ ℤ where
  toFun := fun t => sliceTterm a b t
  isPWO_iUnion_support' := by
    refine ((bddBelow_Ici (a := (0 : ℤ))).isWF.isPWO).mono (Set.iUnion_subset (fun t => ?_))
    exact sliceTterm_support_nonneg a b t
  finite_co_support' := fun E => sliceTterm_co_support_finite a b E

/-! ### `theta_one_zero` shifted, and the off-diagonal vanishing -/

/-- A general `K`-theta family with `Q`-degree `thetaQDeg 3 e` (nome `Q³`, linear twist `e`). -/
noncomputable def kThetaGen (e : ℤ) (w : ℤ → ℚ) : HahnSeries.SummableFamily ℤ ℚ ℤ where
  toFun := fun t => HahnSeries.single (thetaQDeg 3 e t) (w t)
  isPWO_iUnion_support' := by
    have hb := thetaQDeg_bddBelow 3 e (by norm_num)
    refine (hb.isWF.isPWO).mono (Set.iUnion_subset (fun t => ?_))
    intro x hx
    have hxe : x = thetaQDeg 3 e t := HahnSeries.support_single_subset hx
    exact ⟨t, hxe.symm⟩
  finite_co_support' := by
    intro g
    apply Set.Finite.subset (thetaQDeg_finite_fiber 3 e (by norm_num) g)
    intro t ht
    simp only [Set.mem_setOf_eq] at ht
    by_contra hne
    apply ht
    rw [HahnSeries.coeff_single_of_ne]
    intro hcon
    exact hne hcon.symm

/-! ### The RHS slice and the main Hickerson identity -/

/-- `Θ(xy;q) = thetaMon 3 0 1 1`. -/
noncomputable def thetaXY_q : S := thetaMon 3 0 1 1 (by norm_num)

/-! ## Layer G1 — the substituted Hickerson identity `Θx·Θy·Rho_sub = (q;q)³·Θ(x⁻¹y⁻¹q²;q)`

`Rho_sub` is `Rho(q/x, q/y)`: the two-variable Hahn series with coefficient `ρ(r,s)` at the
exponent `Q^{3(rs+r+s)} x^{-r} y^{-s}`.  The slice extraction mirrors `Rho`'s exactly, with the
modified `Q`-exponent; the `[x^a y^b]` slice decomposes (via `u = r+s`, the `ρ`-string variable)
into `∑'_u (-1)^{a+b+u} Q^{3Ta+3Tb+3·Tplus u+3au} · StringSumQ(u, b−a)`.  Off the diagonal `a≠b`
this telescopes to `0`; on the diagonal it produces `(q;q)³` via the Jacobi-derivative identity. -/

/-- On the `Rho_sub` support, the candidate `Q`-degree `3(rs+r+s)` is `≥ -3`
(minimum at `r=s=-1`, the corner of the open third quadrant). -/
theorem rho_sub_support_ge {r s : ℤ} (h : rho r s ≠ 0) : -3 ≤ 3 * (r * s + r + s) := by
  unfold rho at h
  by_cases h1 : 0 ≤ r ∧ 0 ≤ s
  · obtain ⟨hr, hs⟩ := h1; nlinarith [mul_nonneg hr hs]
  · rw [if_neg h1] at h
    by_cases h2 : r < 0 ∧ s < 0
    · obtain ⟨hr, hs⟩ := h2
      -- r,s ≤ -1: rs+r+s = (r+1)(s+1) - 1 ≥ -1, so 3(...) ≥ -3.
      nlinarith [mul_nonneg (by omega : (0:ℤ) ≤ -(r + 1)) (by omega : (0:ℤ) ≤ -(s + 1))]
    · rw [if_neg h2] at h; exact absurd rfl h

/-- The `Q`-degree-`N` fibre of `Rho_sub` for `N > -3` is finite. -/
theorem rho_sub_positive_q_fiber_finite {N : ℤ} (hN : -3 < N) :
    {p : ℤ × ℤ | 3 * (p.1 * p.2 + p.1 + p.2) = N ∧ rho p.1 p.2 ≠ 0}.Finite := by
  apply Set.Finite.subset (Set.finite_Icc ((-N - 4, -N - 4) : ℤ × ℤ) ((N + 4, N + 4) : ℤ × ℤ))
  rintro ⟨r, s⟩ ⟨hq, hne⟩
  simp only at hq hne
  unfold rho at hne
  rw [Set.mem_Icc, Prod.le_def, Prod.le_def]
  by_cases h1 : 0 ≤ r ∧ 0 ≤ s
  · obtain ⟨hr, hs⟩ := h1
    have hrs : 0 ≤ r * s := mul_nonneg hr hs
    -- 3(rs+r+s)=N ⟹ r+s ≤ N/3 ≤ N, with r,s ≥ 0.
    refine ⟨⟨by omega, by omega⟩, by nlinarith [hrs, hq], by nlinarith [hrs, hq]⟩
  · rw [if_neg h1] at hne
    by_cases h2 : r < 0 ∧ s < 0
    · obtain ⟨hr, hs⟩ := h2
      -- r,s ≤ -1.  If s = -1 then hq forces N = -3, contradicting hN; so s ≤ -2, similarly r ≤ -2.
      have hr2 : r ≤ -2 := by
        by_contra hcon; push_neg at hcon
        have hr1 : r = -1 := by omega
        subst hr1; omega
      have hs2 : s ≤ -2 := by
        by_contra hcon; push_neg at hcon
        have hs1 : s = -1 := by omega
        subst hs1; omega
      have hrnn : (0:ℤ) ≤ -(r + 1) := by omega
      have hsnn : (0:ℤ) ≤ -(s + 1) := by omega
      refine ⟨⟨?_, ?_⟩, by omega, by omega⟩
      · -- lower bound on r:  -(r+1) ≤ (-(r+1))·(-(s+1)) = N/3+1  (since -(s+1) ≥ 1)
        nlinarith [mul_nonneg hrnn hsnn, mul_le_mul_of_nonneg_left
          (show (1:ℤ) ≤ -(s + 1) by omega) hrnn, hq]
      · nlinarith [mul_nonneg hrnn hsnn, mul_le_mul_of_nonneg_right
          (show (1:ℤ) ≤ -(r + 1) by omega) hsnn, hq]
    · rw [if_neg h2] at hne; exact absurd rfl hne

/-- The `Q=-3` boundary fibre of `Rho_sub`, expressed in `ExpXY = Lex(ℤ×ℤ)`:
the two rays `{x=1, y≥1} ∪ {y=1, x≥1}` (the reflection `x-deg = -r ≥ 1`).  Both lie in the
positive quadrant, so the set is partially well-ordered. -/
theorem axesSub_isPWO :
    {y : ExpXY | (((ofLex y).1 = 1 ∧ 1 ≤ (ofLex y).2) ∨
        ((ofLex y).2 = 1 ∧ 1 ≤ (ofLex y).1))}.IsPWO := by
  apply Set.PartiallyWellOrderedOn.subsetProdLex
  · -- x-degree projection ⊆ Ici 1.
    have hsub : (fun (x : ℤ ×ₗ ℤ) => (ofLex x).1) ''
        {y : ExpXY | (((ofLex y).1 = 1 ∧ 1 ≤ (ofLex y).2) ∨
          ((ofLex y).2 = 1 ∧ 1 ≤ (ofLex y).1))} ⊆ Set.Ici (1 : ℤ) := by
      rintro a ⟨y, hy, rfl⟩
      simp only [Set.mem_Ici]
      rcases hy with ⟨h1, _⟩ | ⟨_, h2⟩
      · exact le_of_eq h1.symm
      · exact h2
    refine (?_ : (Set.Ici (1 : ℤ)).IsPWO).mono hsub
    exact (bddBelow_Ici.isWF).isPWO
  · intro a
    by_cases ha : a = 1
    · -- a = 1: fibre = {j : 1 ≤ j} = Ici 1, PWO.
      apply (bddBelow_Ici (a := (1 : ℤ))).isWF.isPWO.mono
      intro j hj
      simp only [Set.mem_setOf_eq, ofLex_toLex] at hj
      rw [Set.mem_Ici]
      rcases hj with ⟨_, h2⟩ | ⟨h2, h3⟩
      · exact h2
      · omega
    · -- a ≠ 1: fibre ⊆ {1}, finite hence PWO.
      apply Set.Finite.isPWO
      apply Set.Finite.subset (Set.finite_singleton (1 : ℤ))
      intro j hj
      simp only [Set.mem_setOf_eq, ofLex_toLex] at hj
      rcases hj with ⟨h1, _⟩ | ⟨h2, _⟩
      · exact absurd h1 ha
      · exact h2

/-- The defining coefficient of `Rho_sub`: `ρ(r,s)` at the exponent `Q^{3(rs+r+s)} x^{-r} y^{-s}`.
In terms of the exponent degrees `(a,i,j)` (with `r = -i`, `s = -j`), nonzero only when
`a = 3(ij - i - j)`, where it equals `ρ(-i,-j)`. -/
noncomputable def rhoCoeffSub (z : ExpQXY) : ℚ :=
  if (ofLex z).1 = 3 * ((ofLex (ofLex z).2).1 * (ofLex (ofLex z).2).2
        - (ofLex (ofLex z).2).1 - (ofLex (ofLex z).2).2)
  then rho (-(ofLex (ofLex z).2).1) (-(ofLex (ofLex z).2).2) else 0

/-- The support of `rhoCoeffSub` is partially well-ordered in the `q`-first lex order. -/
theorem rhoCoeffSub_isPWO : (Function.support rhoCoeffSub).IsPWO := by
  apply Set.PartiallyWellOrderedOn.subsetProdLex
  · -- q-degree projection ⊆ Ici (-3).
    have hsub : (fun (z : ℤ ×ₗ ExpXY) => (ofLex z).1) '' Function.support rhoCoeffSub
        ⊆ Set.Ici (-3 : ℤ) := by
      rintro a ⟨z, hz, rfl⟩
      simp only [Function.mem_support, rhoCoeffSub] at hz
      simp only [Set.mem_Ici]
      by_cases hc : (ofLex z).1 = 3 * ((ofLex (ofLex z).2).1 * (ofLex (ofLex z).2).2
          - (ofLex (ofLex z).2).1 - (ofLex (ofLex z).2).2)
      · rw [if_pos hc] at hz
        rw [hc]
        -- rho(-i,-j) ≠ 0 ⟹ 3((-i)(-j)+(-i)+(-j)) ≥ -3, and ij-i-j = (-i)(-j)+(-i)+(-j).
        have hge := rho_sub_support_ge hz
        have heq : (ofLex (ofLex z).2).1 * (ofLex (ofLex z).2).2
            - (ofLex (ofLex z).2).1 - (ofLex (ofLex z).2).2
            = (-(ofLex (ofLex z).2).1) * (-(ofLex (ofLex z).2).2)
              + (-(ofLex (ofLex z).2).1) + (-(ofLex (ofLex z).2).2) := by ring
        rw [heq]; omega
      · rw [if_neg hc] at hz; exact absurd rfl hz
    refine (?_ : (Set.Ici (-3 : ℤ)).IsPWO).mono hsub
    exact (bddBelow_Ici.isWF).isPWO
  · intro N
    by_cases hN : -3 < N
    · -- N > -3: finite fibre.
      apply Set.Finite.isPWO
      apply Set.Finite.subset
        (Set.Finite.image (fun p : ℤ × ℤ => (toLex (-p.1, -p.2) : ExpXY))
          (rho_sub_positive_q_fiber_finite hN))
      intro y hy
      simp only [Set.mem_setOf_eq, Function.mem_support] at hy
      rw [rhoCoeffSub, ofLex_toLex] at hy
      by_cases hc : N = 3 * ((ofLex y).1 * (ofLex y).2 - (ofLex y).1 - (ofLex y).2)
      · refine ⟨(-(ofLex y).1, -(ofLex y).2), ⟨?_, ?_⟩, ?_⟩
        · -- 3(rs+r+s) = N with r=-(ofLex y).1, s=-(ofLex y).2.
          rw [show (-(ofLex y).1) * (-(ofLex y).2) + (-(ofLex y).1) + (-(ofLex y).2)
            = (ofLex y).1 * (ofLex y).2 - (ofLex y).1 - (ofLex y).2 by ring]; omega
        · rw [if_pos hc] at hy; exact hy
        · simp
      · rw [if_neg hc] at hy; exact absurd rfl hy
    · push_neg at hN
      rcases lt_or_eq_of_le hN with hlt | heq
      · -- N < -3: empty fibre.
        apply Set.Finite.isPWO
        convert Set.finite_empty
        ext y
        simp only [Set.mem_setOf_eq, Set.mem_empty_iff_false, iff_false, Function.mem_support]
        rw [rhoCoeffSub, ofLex_toLex]
        by_cases hc : N = 3 * ((ofLex y).1 * (ofLex y).2 - (ofLex y).1 - (ofLex y).2)
        · rw [if_pos hc]
          intro hne
          have hge := rho_sub_support_ge hne
          rw [show (-(ofLex y).1) * (-(ofLex y).2) + (-(ofLex y).1) + (-(ofLex y).2)
            = (ofLex y).1 * (ofLex y).2 - (ofLex y).1 - (ofLex y).2 by ring] at hge
          omega
        · rw [if_neg hc]; exact fun h => h rfl
      · -- N = -3: fibre ⊆ the two boundary rays (PWO).
        subst heq
        apply axesSub_isPWO.mono
        intro y hy
        simp only [Set.mem_setOf_eq, Function.mem_support] at hy
        rw [rhoCoeffSub, ofLex_toLex] at hy
        by_cases hc : (-3 : ℤ) = 3 * ((ofLex y).1 * (ofLex y).2 - (ofLex y).1 - (ofLex y).2)
        · rw [if_pos hc] at hy
          -- ij-i-j = -1 ⟹ (i-1)(j-1)=0 ⟹ i=1 ∨ j=1; with ρ(-i,-j)≠0 ⟹ i,j≥1.
          set i := (ofLex y).1
          set j := (ofLex y).2
          have hij : i * j - i - j = -1 := by omega
          have hfac : (i - 1) * (j - 1) = 0 := by nlinarith [hij]
          -- ρ(-i,-j) ≠ 0: with the factorisation forcing i=1 or j=1, and support ⟹ i,j ≥ 1.
          unfold rho at hy
          by_cases hquad : 0 ≤ -i ∧ 0 ≤ -j
          · -- closed-1st for (-i,-j): i ≤ 0, j ≤ 0.  But then ij-i-j ≥ 0 > -1, contradiction.
            exfalso; obtain ⟨hi, hj⟩ := hquad; nlinarith [hij, mul_nonneg hi hj]
          · rw [if_neg hquad] at hy
            by_cases hquad2 : -i < 0 ∧ -j < 0
            · -- open-3rd: i ≥ 1, j ≥ 1; (i-1)(j-1)=0 ⟹ i=1 ∨ j=1.
              obtain ⟨hi, hj⟩ := hquad2
              rcases mul_eq_zero.mp hfac with h | h
              · left; exact ⟨by omega, by omega⟩
              · right; exact ⟨by omega, by omega⟩
            · rw [if_neg hquad2] at hy; exact absurd rfl hy
        · rw [if_neg hc] at hy; exact absurd rfl hy

/-- `Rho_sub = Rho(q/x,q/y)`: the two-variable Hahn series with coefficient `ρ(r,s)` at
`Q^{3(rs+r+s)} x^{-r} y^{-s}`. -/
noncomputable def Rho_sub : S where
  coeff := rhoCoeffSub
  isPWO_support' := rhoCoeffSub_isPWO

/-- The ρ summable family for `Rho_sub`: `(r,s) ↦ monom (3(rs+r+s)) (-r) (-s) (ρ r s)`. -/
noncomputable def rhoFamilySub : HahnSeries.SummableFamily ExpQXY ℚ (ℤ × ℤ) where
  toFun := fun p => monom (3 * (p.1 * p.2 + p.1 + p.2)) (-p.1) (-p.2) (rho p.1 p.2)
  isPWO_iUnion_support' := by
    refine rhoCoeffSub_isPWO.mono (Set.iUnion_subset (fun p => ?_))
    intro g hg
    have hgeq : g = expQXY (3 * (p.1 * p.2 + p.1 + p.2)) (-p.1) (-p.2) :=
      HahnSeries.support_single_subset hg
    rw [HahnSeries.mem_support] at hg
    simp only [Function.mem_support]
    rw [hgeq, rhoCoeffSub, qdeg_expQXY, xdeg_expQXY, ydeg_expQXY]
    rw [if_pos (by ring), neg_neg, neg_neg]
    unfold monom at hg
    rw [HahnSeries.coeff_single, if_pos hgeq] at hg
    exact hg
  finite_co_support' := by
    intro g
    apply Set.Finite.subset (Set.finite_singleton
      ((-(ofLex (ofLex g).2).1, -(ofLex (ofLex g).2).2)))
    intro p hp
    simp only [Set.mem_singleton_iff] at hp ⊢
    by_contra hne
    apply hp
    unfold monom
    rw [HahnSeries.coeff_single_of_ne]
    intro hcon
    apply hne
    have hx : (ofLex (ofLex g).2).1 = -p.1 := by rw [hcon, xdeg_expQXY]
    have hy : (ofLex (ofLex g).2).2 = -p.2 := by rw [hcon, ydeg_expQXY]
    rw [hx, hy]; simp

/-! **The 10.33-pattern lemma** (FE with weight `w = x⁻¹y⁻¹q`):
`monom 3 (-1) (-1) 1 · Θ(x⁻¹y⁻¹q²;q) = - Θ(x⁻¹y⁻¹q;q)`, i.e.
`monom 3 (-1) (-1) 1 * thetaMon 3 6 (-1) (-1) = - thetaMon 3 3 (-1) (-1)`.

### The `Rho_sub` slice extraction (mirror of the `Rho` machinery, modified `Q`-exponent) -/

/-- The triple product `Θ(x;q)·Θ(y;q)·Rho_sub` as a summable family over `(ℤ×ℤ)×(ℤ×ℤ)`. -/
noncomputable def prodFamSub : HahnSeries.SummableFamily ExpQXY ℚ ((ℤ × ℤ) × (ℤ × ℤ)) :=
  HahnSeries.SummableFamily.mul
    (HahnSeries.SummableFamily.mul (thetaFamily 3 0 1 0 (by norm_num))
      (thetaFamily 3 0 0 1 (by norm_num))) rhoFamilySub

/-- The reindexing bijection mapping `(u,s)` to `(k,l) = (u-s+a, s+b)` (so that `u = (k-a)+(l-b)`
is the ρ-string variable `r+s`, and the second component `s = l-b`). -/
def reindexKLSub (a b : ℤ) : (ℤ × ℤ) ≃ (ℤ × ℤ) where
  toFun := fun q => (q.1 - q.2 + a, q.2 + b)
  invFun := fun p => (p.1 - a + (p.2 - b), p.2 - b)
  left_inv := by rintro ⟨u, s⟩; simp only [Prod.mk.injEq]; constructor <;> ring
  right_inv := by rintro ⟨k, l⟩; simp only [Prod.mk.injEq]; constructor <;> ring

/-- The single-`u` term of the `Rho_sub` slice:
`(-1)^{a+b+u} · Q^{3Ta+3Tb+3·Tplus u+3au} · StringSumQ(u, b−a)`. -/
noncomputable def sliceSubUterm (a b u : ℤ) : K :=
  ((-1 : ℚ) ^ (a + b + u))
    • (Qpow (3 * Tn a + 3 * Tn b + 3 * Tplus u + 3 * a * u) * StringSumQ u (b - a))

/-- Coefficient of `sliceSubUterm a b u` at `Q`-degree `D`. -/
theorem sliceSubUterm_coeff (a b u D : ℤ) :
    (sliceSubUterm a b u).coeff D
      = ∑ᶠ s : ℤ,
          (if 3 * Tn a + 3 * Tn b + 3 * Tplus u + 3 * a * u + 3 * (b - a) * s = D
            then (-1) ^ (a + b + u) * rho (u - s) s else 0) := by
  unfold sliceSubUterm
  rw [HahnSeries.coeff_smul, smul_eq_mul]
  rw [show (Qpow (3 * Tn a + 3 * Tn b + 3 * Tplus u + 3 * a * u) * StringSumQ u (b - a)).coeff D
      = (StringSumQ u (b - a)).coeff (D - (3 * Tn a + 3 * Tn b + 3 * Tplus u + 3 * a * u)) by
    unfold Qpow; rw [HahnSeries.coeff_single_mul, one_mul]]
  rw [StringSumQ_coeff]
  rw [mul_finsum' (fun s : ℤ => if 3 * (b - a) * s = D - (3 * Tn a + 3 * Tn b + 3 * Tplus u + 3 * a * u)
        then rho (u - s) s else 0) ((-1) ^ (a + b + u)) (by
    apply Set.Finite.subset (stringSupp_finite u)
    intro s hs
    simp only [Function.mem_support] at hs
    simp only [Set.mem_setOf_eq]
    intro hc
    apply hs
    by_cases h : 3 * (b - a) * s = D - (3 * Tn a + 3 * Tn b + 3 * Tplus u + 3 * a * u)
    · rw [if_pos h, hc]
    · rw [if_neg h])]
  apply finsum_congr
  intro s
  by_cases h : 3 * (b - a) * s = D - (3 * Tn a + 3 * Tn b + 3 * Tplus u + 3 * a * u)
  · rw [if_pos h, if_pos (by omega)]
  · rw [if_neg h, if_neg (by omega), mul_zero]

/-- The reverse `(u,s) ↦ (k,l) = (u-s+a, s+b)` exponent identity (used in the bounds). -/
theorem sliceSub_exp_kl (a b u s : ℤ) :
    3 * Tn a + 3 * Tn b + 3 * Tplus u + 3 * a * u + 3 * (b - a) * s
      = 3 * Tn (u - s + a) + 3 * Tn (s + b) + 3 * ((u - s) * s + (u - s) + s) := by
  have h1 := two_mul_Tn (u - s + a)
  have h2 := two_mul_Tn (s + b)
  have h3 := two_mul_Tn a
  have h4 := two_mul_Tn b
  have h5 := two_mul_Tplus u
  have key : 2 * (3 * Tn a + 3 * Tn b + 3 * Tplus u + 3 * a * u + 3 * (b - a) * s)
      = 2 * (3 * Tn (u - s + a) + 3 * Tn (s + b) + 3 * ((u - s) * s + (u - s) + s)) := by
    rw [show 2 * (3 * Tn a + 3 * Tn b + 3 * Tplus u + 3 * a * u + 3 * (b - a) * s)
        = 3 * (2 * Tn a) + 3 * (2 * Tn b) + 3 * (2 * Tplus u) + 6 * a * u + 6 * (b - a) * s by ring,
      h3, h4, h5,
      show 2 * (3 * Tn (u - s + a) + 3 * Tn (s + b) + 3 * ((u - s) * s + (u - s) + s))
        = 3 * (2 * Tn (u - s + a)) + 3 * (2 * Tn (s + b)) + 6 * ((u - s) * s + (u - s) + s) by ring,
      h1, h2]
    ring
  omega

/-- Each `Q`-degree in the support of `sliceSubUterm a b u` is `≥ -3`. -/
theorem sliceSubUterm_support_nonneg (a b u : ℤ) :
    (sliceSubUterm a b u).support ⊆ Set.Ici (-3 : ℤ) := by
  intro E hE
  rw [HahnSeries.mem_support] at hE
  rw [Set.mem_Ici]
  by_contra hneg
  push_neg at hneg
  apply hE
  rw [sliceSubUterm_coeff]
  apply finsum_eq_zero_of_forall_eq_zero
  intro s
  by_cases hc : 3 * Tn a + 3 * Tn b + 3 * Tplus u + 3 * a * u + 3 * (b - a) * s = E
  · rw [if_pos hc]
    by_cases hr : rho (u - s) s = 0
    · rw [hr, mul_zero]
    · exfalso
      have hrs : 0 ≤ 3 * (u - s) * s := rho_support_nonneg_q hr
      have hTk : 0 ≤ Tn (u - s + a) := Tn_nonneg _
      have hTl : 0 ≤ Tn (s + b) := Tn_nonneg _
      rw [sliceSub_exp_kl] at hc
      -- E = 3Tk+3Tl+3((u-s)s+(u-s)+s) with the cross term ≥ -1 (since rs ≥ 0, r+s arbitrary…)
      -- but (u-s)s+(u-s)+s = (u-s)(s+1)+s; use rho support to bound below by -1.
      have hcross : -1 ≤ (u - s) * s + (u - s) + s := by
        -- on the ρ support either both ≥ 0 or both ≤ -1; in either case ≥ -1.
        unfold rho at hr
        by_cases h1 : 0 ≤ u - s ∧ 0 ≤ s
        · obtain ⟨hi, hj⟩ := h1; nlinarith [mul_nonneg hi hj]
        · rw [if_neg h1] at hr
          by_cases h2 : u - s < 0 ∧ s < 0
          · obtain ⟨hi, hj⟩ := h2
            nlinarith [mul_nonneg (by omega : (0:ℤ) ≤ -((u - s) + 1)) (by omega : (0:ℤ) ≤ -(s + 1))]
          · rw [if_neg h2] at hr; exact absurd rfl hr
      omega
  · rw [if_neg hc]

/-- The co-support of the `sliceSubUterm`-family at `E` is finite. -/
theorem sliceSubUterm_co_support_finite (a b E : ℤ) :
    {u : ℤ | (sliceSubUterm a b u).coeff E ≠ 0}.Finite := by
  apply Set.Finite.subset (Set.finite_Icc (-(E + 4) - (E + 4) - a - b) ((E + 4) + (E + 4) - a - b))
  intro u hu
  simp only [Set.mem_setOf_eq] at hu
  rw [sliceSubUterm_coeff] at hu
  rw [Set.mem_Icc]
  by_contra hubound
  apply hu
  apply finsum_eq_zero_of_forall_eq_zero
  intro s
  by_cases hc : 3 * Tn a + 3 * Tn b + 3 * Tplus u + 3 * a * u + 3 * (b - a) * s = E
  · rw [if_pos hc]
    by_cases hr0 : rho (u - s) s = 0
    · rw [hr0, mul_zero]
    · exfalso
      apply hubound
      have hTk : 0 ≤ Tn (u - s + a) := Tn_nonneg _
      have hTl : 0 ≤ Tn (s + b) := Tn_nonneg _
      have hcross : -1 ≤ (u - s) * s + (u - s) + s := by
        unfold rho at hr0
        by_cases h1 : 0 ≤ u - s ∧ 0 ≤ s
        · obtain ⟨hi, hj⟩ := h1; nlinarith [mul_nonneg hi hj]
        · rw [if_neg h1] at hr0
          by_cases h2 : u - s < 0 ∧ s < 0
          · obtain ⟨hi, hj⟩ := h2
            nlinarith [mul_nonneg (by omega : (0:ℤ) ≤ -((u - s) + 1)) (by omega : (0:ℤ) ≤ -(s + 1))]
          · rw [if_neg h2] at hr0; exact absurd rfl hr0
      rw [sliceSub_exp_kl] at hc
      have hTkE : Tn (u - s + a) ≤ E + 3 := by omega
      have hTlE : Tn (s + b) ≤ E + 3 := by omega
      obtain ⟨hk_lb, hk_ub⟩ := abs_le_of_Tn_le hTkE
      obtain ⟨hl_lb, hl_ub⟩ := abs_le_of_Tn_le hTlE
      -- u = (u-s+a) + (s+b) - a - b, both bracket terms bounded.
      constructor <;> omega
  · rw [if_neg hc]

/-- The slice summable family `u ↦ sliceSubUterm a b u` over `ℤ`. -/
noncomputable def sliceSubUFamily (a b : ℤ) : HahnSeries.SummableFamily ℤ ℚ ℤ where
  toFun := fun u => sliceSubUterm a b u
  isPWO_iUnion_support' := by
    refine ((bddBelow_Ici (a := (-3 : ℤ))).isWF.isPWO).mono (Set.iUnion_subset (fun u => ?_))
    exact sliceSubUterm_support_nonneg a b u
  finite_co_support' := fun E => sliceSubUterm_co_support_finite a b E

/-! ## Layer H — the triple-theta diagonal extraction for the final assembly

The final collapse needs the constant term
`CTxy (Θ(x⁻¹y⁻¹q;q) · Θ(x;q²) · Θ(y;q²))`, where
`Θ(x⁻¹y⁻¹q;q) = thetaMon 3 3 (-1) (-1)`, `Θ(x;q²) = thetaX_q2 = thetaMon 6 0 1 0`,
`Θ(y;q²) = thetaY_q2 = thetaMon 6 0 0 1`.  The `[x⁰y⁰]` projection forces the three
summation indices to coincide; the surviving Q-exponent is `15·T k + 3 k = 3·P₁₀(−k)`,
which after `k ↦ −k` becomes `3·P₁₀ n`.  -/

/-- `Θ(x⁻¹y⁻¹q;q) = thetaMon 3 3 (-1) (-1)`. -/
noncomputable def thetaXYinv_q : S := thetaMon 3 3 (-1) (-1) (by norm_num)

/-- The triple-product summable family `Θ(x⁻¹y⁻¹q;q) · Θ(x;q²) · Θ(y;q²)`, indexed by
`((k,l),m)` (the three theta indices). -/
noncomputable def tripFam : HahnSeries.SummableFamily ExpQXY ℚ ((ℤ × ℤ) × ℤ) :=
  HahnSeries.SummableFamily.mul
    (HahnSeries.SummableFamily.mul (thetaFamily 3 3 (-1) (-1) (by norm_num))
      (thetaFamily 6 0 1 0 (by norm_num))) (thetaFamily 6 0 0 1 (by norm_num))

/-- The `K`-summable family `n ↦ single (3·P₁₀ n) ((-1)^n)` for the RHS of the H-identity. -/
noncomputable def kP10Family : HahnSeries.SummableFamily ℤ ℚ ℤ where
  toFun := fun n => HahnSeries.single (3 * P10 n) ((-1) ^ n)
  isPWO_iUnion_support' := by
    -- 3·P₁₀ n = (15 n² + 9 n)/2 is bounded below (min at n near 0), so the support is PWO.
    refine ((bddBelow_Ici (a := (-1 : ℤ))).isWF.isPWO).mono (Set.iUnion_subset (fun n => ?_))
    intro x hx
    have hxe : x = 3 * P10 n := HahnSeries.support_single_subset hx
    rw [Set.mem_Ici, hxe]
    -- 2·(3 P₁₀ n) = 3 n(5n+3) ≥ -2 ⟹ 3 P₁₀ n ≥ -1.
    have h := two_mul_P10 n
    nlinarith [h, sq_nonneg (5 * n + 3), sq_nonneg n]
  finite_co_support' := by
    intro g
    -- the fibre {n : 3 P₁₀ n = g} is bounded: 2·(3 P₁₀ n) = 3 n(5n+3) = g·2, so |n| ≤ |g|+1.
    apply Set.Finite.subset (Set.finite_Icc (-(|g| + 1 : ℤ)) (|g| + 1))
    intro n hn
    simp only [Set.mem_setOf_eq] at hn
    have hne : (HahnSeries.single (3 * P10 n) ((-1 : ℚ) ^ n)).coeff g ≠ 0 := hn
    have hP : 3 * P10 n = g := by
      by_contra hc
      exact hne (by rw [HahnSeries.coeff_single_of_ne (fun h => hc h.symm)])
    have h := two_mul_P10 n
    have hg : |g| ≤ |g| := le_refl _
    have hgle : -|g| ≤ g ∧ g ≤ |g| := ⟨neg_abs_le g, le_abs_self g⟩
    rw [Set.mem_Icc]
    constructor <;> nlinarith [h, hP, hgle.1, hgle.2, sq_nonneg (5 * n + 3), sq_nonneg n,
      abs_nonneg g]

/-- The RHS of the H-identity as a single `K`-series. -/
noncomputable def kP10 : K := kP10Family.hsum

/-- The diagonal-shift equivalence `(k,d) ↦ (k, k+d)` (its inverse is `(k,l) ↦ (k, l-k)`),
used to collapse a `(k,l)`-plane diagonal finsum to a single `k`-finsum. -/
def diagShiftEquiv : (ℤ × ℤ) ≃ (ℤ × ℤ) where
  toFun := fun q => (q.1, q.1 + q.2)
  invFun := fun p => (p.1, p.2 - p.1)
  left_inv := by rintro ⟨k, d⟩; simp only [add_sub_cancel_left]
  right_inv := by rintro ⟨k, l⟩; simp only [add_sub_cancel]

/-! ## Layer G3 + I — the final collapse and Chan's Eq 10.15

`ChanQuadLHS := CTxy (monom 1 0 0 1 · Rho_sub · zwegersLHS_x · zwegersLHS_y)` is Chan's Eq 10.15
LHS (constant term of `q·Rho(q/x,q/y)·Zwegers_x·Zwegers_y`).  Clearing the two `poch_q2`
denominators (one per Zwegers factor) substitutes the Zwegers RHS forms; substituting G1 and the
10.33-pattern then collapses the product to `- embedQ(poch_q^5)·Θ(x⁻¹y⁻¹q;q)·Θ(x;q²)·Θ(y;q²)`,
whose constant term is `- poch_q^5 · ∑'_n single(3 P₁₀ n)((-1)^n)` (Layer H). -/

/-- Chan's Eq 10.15 LHS as a `K`-series: the constant term of
`q · Rho(q/x,q/y) · Zwegers_x · Zwegers_y` (built from the *uncleared* Zwegers LHS sums). -/
noncomputable def ChanQuadLHS : K :=
  CTxy (monom 1 0 0 1 * Rho_sub * zwegersLHS_x * zwegersLHS_y)

/-! ## Layer I (Step 1) — the quadruple-sum decoupling of Chan's Eq 10.15 LHS

This layer transcribes ChatGPT's `chan1` Step-1 skeleton: the literal quadruple Hahn-sum form
of Chan's Eq 10.15 LHS, and the decoupling theorem identifying it with `ChanQuadLHS`.

`ChanQuadLHS = CTxy (monom 1 0 0 1 · Rho_sub · Zwegers_x · Zwegers_y)` (already defined above) is
the `[x⁰y⁰]`-coefficient of the genuine six-index product

  `q^{1/3} · Σ_{r,s} ρ(r,s) q^{rs+r+s} x^{-r} y^{-s}`
  `· Σ_{k,m} (-1)^{k+m}(δ₃k-δ₃m) q^{(k²+m²)/3} x^{m}`
  `· Σ_{l,n} (-1)^{l+n}(δ₃l-δ₃n) q^{(l²+n²)/3} y^{n}`   (in `q = Q³`).

The `[x⁰y⁰]` condition forces the antidiagonal `m = r`, `n = s`, collapsing the six-index sum to
the quadruple sum over `(k,l,r,s)` with integer `Q`-exponent

  `qExp4 = k² + l² + r² + 3rs + s² + 3r + 3s + 1`

and coefficient `ρ(r,s)·(-1)^{k+l+r+s}·(δ₃k-δ₃r)·(δ₃l-δ₃s)`.

`ChanQuadSum : K` is that quadruple sum, realised as the `hsum` of a genuine `K`-level summable
family.  The summability is the one genuinely careful point: the quadratic form `r²+3rs+s²` is
*indefinite* (discriminant `9-4 = 5 > 0`), so `qExp4` is **not** bounded below over all `(k,l,r,s)`.
However the coefficient vanishes off the `ρ`-support (`r,s ≥ 0` or `r,s ≤ -1`), and **on** that
support `qExp4 ≥ 0` with finite fibres — exactly the two-quadrant structure handled by
`rhoCoeffSub_isPWO`.  The bound is `g(r,s) := r²+3rs+s²+3r+3s+1 ≥ 0` on the support
(`= a²+3ab+b²+2a+2b ≥ 0` after `r=-1-a, s=-1-b` on the third quadrant; all terms nonneg on the
first), so `qExp4 = k²+l²+g(r,s) ≥ 0`. -/

/-- The integer `Q`-exponent of the `(k,l,r,s)` term of Chan's quadruple sum.
[OFFLINE-WRITTEN, numerics-verified to `Q^60`, build-pending] -/
def qExp4 (k l r s : ℤ) : ℤ := k ^ 2 + l ^ 2 + r ^ 2 + 3 * r * s + s ^ 2 + 3 * r + 3 * s + 1

/-- The coefficient of the `(k,l,r,s)` term of Chan's quadruple sum.
[OFFLINE-WRITTEN, numerics-verified to `Q^60`, build-pending] -/
noncomputable def quadCoeff (k l r s : ℤ) : ℚ :=
  rho r s * (-1) ^ (k + l + r + s) * (delta3 k - delta3 r) * (delta3 l - delta3 s)

/-! ### `qExp4 ≥ 0` on the `quadCoeff` support, with finite fibres -/

/-- On the `ρ`-support, the "shifted" quadratic `g(r,s) = r²+3rs+s²+3r+3s+1` is `≥ 0`.
First quadrant (`r,s≥0`): all monomials nonnegative.  Third quadrant (`r,s≤-1`): substitute
`r=-1-a, s=-1-b` with `a,b≥0` to get `a²+3ab+b²+2a+2b ≥ 0`.
[OFFLINE-WRITTEN, numerics-verified, build-pending; risk: low (`nlinarith`)] -/
theorem g_nonneg_on_rho_support {r s : ℤ} (h : rho r s ≠ 0) :
    0 ≤ r ^ 2 + 3 * r * s + s ^ 2 + 3 * r + 3 * s + 1 := by
  unfold rho at h
  by_cases h1 : 0 ≤ r ∧ 0 ≤ s
  · obtain ⟨hr, hs⟩ := h1
    nlinarith [mul_nonneg hr hs, sq_nonneg r, sq_nonneg s, hr, hs]
  · rw [if_neg h1] at h
    by_cases h2 : r < 0 ∧ s < 0
    · obtain ⟨hr, hs⟩ := h2
      -- r ≤ -1, s ≤ -1.  Let a = -1-r ≥ 0, b = -1-s ≥ 0.  Then the form = a²+3ab+b²+2a+2b ≥ 0.
      have ha : 0 ≤ -1 - r := by omega
      have hb : 0 ≤ -1 - s := by omega
      nlinarith [mul_nonneg ha hb, sq_nonneg (-1 - r), sq_nonneg (-1 - s), ha, hb]
    · rw [if_neg h2] at h; exact absurd rfl h

/-- On the `quadCoeff` support, `qExp4 ≥ 0`.  (`quadCoeff ≠ 0 ⟹ ρ(r,s) ≠ 0`, then add `k²+l²`.)
[OFFLINE-WRITTEN, numerics-verified, build-pending; risk: low] -/
theorem qExp4_nonneg_of_quadCoeff {k l r s : ℤ} (h : quadCoeff k l r s ≠ 0) :
    0 ≤ qExp4 k l r s := by
  have hrho : rho r s ≠ 0 := by
    unfold quadCoeff at h
    intro hc; apply h; rw [hc]; ring
  have hg := g_nonneg_on_rho_support hrho
  unfold qExp4
  nlinarith [sq_nonneg k, sq_nonneg l, hg]

/-- Integer bound: `c² ≤ M` with `0 ≤ M` gives `-(M+1) ≤ c ≤ M+1` (single-variable nlinarith). -/
theorem abs_bound_of_sq_le {c M : ℤ} (h : c ^ 2 ≤ M) (hM : 0 ≤ M) :
    -(M + 1) ≤ c ∧ c ≤ M + 1 := by
  constructor
  · nlinarith [sq_nonneg (c + 1), h, hM]
  · nlinarith [sq_nonneg (c - 1), h, hM]

/-- For a fixed target `Q`-degree `D`, only finitely many `(k,l,r,s)` on the `quadCoeff` support
have `qExp4 = D`.  Each of `k², l²` is `≤ D` (the rest of `qExp4` is `≥ 0` on the support), and
`g(r,s) ≤ D` bounds `(r,s)` on the support.  We bound the whole tuple inside an `Icc` box.
[OFFLINE-WRITTEN, numerics-verified, build-pending; risk: MEDIUM (nlinarith box bounds)] -/
theorem qExp4_finite_fiber (D : ℤ) :
    {p : (ℤ × ℤ) × (ℤ × ℤ) | quadCoeff p.1.1 p.1.2 p.2.1 p.2.2 ≠ 0 ∧
        qExp4 p.1.1 p.1.2 p.2.1 p.2.2 = D}.Finite := by
  apply Set.Finite.subset (Set.finite_Icc
    (((-((D.natAbs : ℤ) + 2), -((D.natAbs : ℤ) + 2)), (-((D.natAbs : ℤ) + 2), -((D.natAbs : ℤ) + 2))) :
        (ℤ × ℤ) × (ℤ × ℤ))
    (((((D.natAbs : ℤ) + 2), ((D.natAbs : ℤ) + 2)), (((D.natAbs : ℤ) + 2), ((D.natAbs : ℤ) + 2))) :
        (ℤ × ℤ) × (ℤ × ℤ)))
  rintro ⟨⟨k, l⟩, ⟨r, s⟩⟩ ⟨hc, hD⟩
  have hrho : rho r s ≠ 0 := by
    unfold quadCoeff at hc; intro h; apply hc; rw [h]; ring
  have hg := g_nonneg_on_rho_support hrho
  -- `omega` knows `Int.natAbs`, giving both `D ≤ |D|` and `-|D| ≤ D`.
  have hNn : (D : ℤ) ≤ (D.natAbs : ℤ) := by omega
  have hNn2 : -(D.natAbs : ℤ) ≤ D := by omega
  -- From qExp4 = D and the nonneg pieces: k² ≤ D, l² ≤ D, and g(r,s) ≤ D.
  have hqe : k ^ 2 + l ^ 2 + (r ^ 2 + 3 * r * s + s ^ 2 + 3 * r + 3 * s + 1) = D := by
    have := hD; unfold qExp4 at this; linarith [this]
  have hk2 : k ^ 2 ≤ D := by nlinarith [sq_nonneg l, hg, hqe]
  have hl2 : l ^ 2 ≤ D := by nlinarith [sq_nonneg k, hg, hqe]
  have hgD : r ^ 2 + 3 * r * s + s ^ 2 + 3 * r + 3 * s + 1 ≤ D := by
    nlinarith [sq_nonneg k, sq_nonneg l, hqe]
  -- On the ρ-support, |r|, |s| are bounded by g(r,s) ≤ D ≤ |D|.
  -- First quadrant: r,s ≥ 0 and r² ≤ g, s² ≤ g (since 3rs+3r+3s+1 ≥ 0 there).
  -- Third quadrant: with a=-1-r, b=-1-s ≥ 0, a² ≤ g, b² ≤ g similarly; so |r| = a+1 ≤ g+1.
  -- On the support, r² ≤ D+1 and s² ≤ D+1.  (First quadrant: r² ≤ g ≤ D.  Third quadrant
  -- r,s ≤ -1: with a=-1-r, b=-1-s ≥ 0, g - r² = 3ab+b²+2b-1 ≥ -1, so r² ≤ g+1 ≤ D+1.)
  have hrs_bound : r ^ 2 ≤ D + 1 ∧ s ^ 2 ≤ D + 1 := by
    unfold rho at hrho
    by_cases h1 : 0 ≤ r ∧ 0 ≤ s
    · obtain ⟨hr, hs⟩ := h1
      constructor <;>
        nlinarith [mul_nonneg hr hs, hr, hs, hgD]
    · rw [if_neg h1] at hrho
      by_cases h2 : r < 0 ∧ s < 0
      · obtain ⟨hr, hs⟩ := h2
        refine ⟨?_, ?_⟩
        · nlinarith [mul_nonneg (by omega : (0:ℤ) ≤ -1 - r) (by omega : (0:ℤ) ≤ -1 - s),
            sq_nonneg (-1 - s), hr, hs, hgD]
        · nlinarith [mul_nonneg (by omega : (0:ℤ) ≤ -1 - r) (by omega : (0:ℤ) ≤ -1 - s),
            sq_nonneg (-1 - r), hr, hs, hgD]
      · rw [if_neg h2] at hrho; exact absurd rfl hrho
  -- Each tuple component c satisfies c² ≤ D+1 ≤ |D|+1, hence |c| ≤ |D|+1 (integer bound).
  obtain ⟨hrb, hsb⟩ := hrs_bound
  have hk2' : k ^ 2 ≤ D + 1 := by omega
  have hl2' : l ^ 2 ≤ D + 1 := by omega
  have hMnn : (0:ℤ) ≤ (D.natAbs : ℤ) + 1 := by positivity
  have hkM : k ^ 2 ≤ (D.natAbs : ℤ) + 1 := by omega
  have hlM : l ^ 2 ≤ (D.natAbs : ℤ) + 1 := by omega
  have hrM : r ^ 2 ≤ (D.natAbs : ℤ) + 1 := by omega
  have hsM : s ^ 2 ≤ (D.natAbs : ℤ) + 1 := by omega
  obtain ⟨hkL, hkU⟩ := abs_bound_of_sq_le hkM hMnn
  obtain ⟨hlL, hlU⟩ := abs_bound_of_sq_le hlM hMnn
  obtain ⟨hrL, hrU⟩ := abs_bound_of_sq_le hrM hMnn
  obtain ⟨hsL, hsU⟩ := abs_bound_of_sq_le hsM hMnn
  simp only [Set.mem_Icc, Prod.le_def]
  refine ⟨⟨⟨?_, ?_⟩, ⟨?_, ?_⟩⟩, ⟨⟨?_, ?_⟩, ⟨?_, ?_⟩⟩⟩ <;> (try dsimp only) <;> omega

/-- The `K`-level summable family realising Chan's quadruple sum:
`((k,l),(r,s)) ↦ single (qExp4 k l r s) (quadCoeff k l r s)`.
[OFFLINE-WRITTEN, numerics-verified, build-pending; risk: MEDIUM (mirrors `kP10Family`/
`zFamily` but indexed by `(ℤ×ℤ)×(ℤ×ℤ)`; the PWO/finite-fibre proofs reduce to the helpers above)] -/
noncomputable def chanQuadKFamily : HahnSeries.SummableFamily ℤ ℚ ((ℤ × ℤ) × (ℤ × ℤ)) where
  toFun := fun p => HahnSeries.single (qExp4 p.1.1 p.1.2 p.2.1 p.2.2)
    (quadCoeff p.1.1 p.1.2 p.2.1 p.2.2)
  isPWO_iUnion_support' := by
    -- support ⊆ Ici 0, which is PWO; uses qExp4 ≥ 0 on the support of each term coefficient.
    refine ((bddBelow_Ici (a := (0 : ℤ))).isWF.isPWO).mono (Set.iUnion_subset (fun p => ?_))
    intro x hx
    obtain ⟨⟨k, l⟩, ⟨r, s⟩⟩ := p
    have hxe : x = qExp4 k l r s := HahnSeries.support_single_subset hx
    rw [HahnSeries.mem_support, hxe] at hx
    -- hx : single (qExp4 …) (quadCoeff …) has nonzero coeff at qExp4 …, i.e. quadCoeff … ≠ 0.
    rw [Set.mem_Ici, hxe]
    apply qExp4_nonneg_of_quadCoeff
    intro hc
    rw [hc, HahnSeries.single_eq_zero, HahnSeries.coeff_zero] at hx
    exact hx rfl
  finite_co_support' := by
    intro g
    apply Set.Finite.subset (qExp4_finite_fiber g)
    rintro ⟨⟨k, l⟩, ⟨r, s⟩⟩ hp
    simp only [Set.mem_setOf_eq] at hp ⊢
    -- the single-term coeff at g is nonzero ⟹ quadCoeff ≠ 0 and qExp4 = g.
    rw [HahnSeries.coeff_single] at hp
    by_cases hq : g = qExp4 k l r s
    · refine ⟨?_, hq.symm⟩
      rw [if_pos hq] at hp; exact hp
    · rw [if_neg hq] at hp; exact absurd rfl hp

/-- **Chan's Eq 10.15 LHS as a genuine quadruple Hahn sum** (`ChanQuadSum` of the skeleton):
`Σ_{k,l,r,s} ρ(r,s)·(-1)^{k+l+r+s}·(δ₃k-δ₃r)·(δ₃l-δ₃s)·Q^{qExp4 k l r s}` in `K`.
[OFFLINE-WRITTEN, numerics-verified to `Q^60`, build-pending] -/
noncomputable def ChanQuadSum : K := chanQuadKFamily.hsum

/-! ### The six-index product family and its antidiagonal collapse

We build the inner product `Rho_sub · Zwegers_x · Zwegers_y` as a summable family over
`((ℤ×ℤ)×(ℤ×ℤ))×(ℤ×ℤ)` (indices `((r,s),(k,m)),(l,n)`), exactly mirroring `prodFamSub`. -/

/-- The six-index product family `(rhoFamilySub × zFamily) × zFamilyY` for the inner product
`Rho_sub · Zwegers_x · Zwegers_y`.
[OFFLINE-WRITTEN, build-pending; risk: low (literal `prodFamSub` pattern)] -/
noncomputable def chanProdFam :
    HahnSeries.SummableFamily ExpQXY ℚ (((ℤ × ℤ) × (ℤ × ℤ)) × (ℤ × ℤ)) :=
  HahnSeries.SummableFamily.mul
    (HahnSeries.SummableFamily.mul rhoFamilySub zFamily) zFamilyY

/-! ### The constant-term (`[x⁰y⁰]`) coefficient of the six-index product

`CTxy` of the leading-monomial-times-inner-product, sliced at `Q`-degree `D`, equals the six-index
finsum with the antidiagonal indicator `m-r = 0 ∧ n-s = 0`.  We then collapse `(m,n)` against
`(r,s)` and reindex to the quadruple sum. -/

/-- The index re-association equivalence `(((r,s),(k,m)),(l,n)) ↦ (((r,s),(k,l)),(m,n))`,
moving the antidiagonal pair `(m,n)` to the innermost factor.  Pure data Equiv (`rfl` on both
inverse laws).
[OFFLINE-WRITTEN, build-pending; risk: low (`rfl` field goals)] -/
def reassoc6 : (((ℤ × ℤ) × (ℤ × ℤ)) × (ℤ × ℤ)) ≃ (((ℤ × ℤ) × (ℤ × ℤ)) × (ℤ × ℤ))
    where
  toFun := fun p => (((p.1.1.1, p.1.1.2), (p.1.2.1, p.2.1)), (p.1.2.2, p.2.2))
  invFun := fun q => (((q.1.1.1, q.1.1.2), (q.1.2.1, q.2.1)), (q.1.2.2, q.2.2))
  left_inv := by rintro ⟨⟨⟨r, s⟩, ⟨k, m⟩⟩, ⟨l, n⟩⟩; rfl
  right_inv := by rintro ⟨⟨⟨r, s⟩, ⟨k, l⟩⟩, ⟨m, n⟩⟩; rfl

/-- The outer reindex `((k,l),(r,s)) ↦ ((r,s),(k,l))` matching the quadruple-sum index order to
the collapsed product index order.  Pure data Equiv.
[OFFLINE-WRITTEN, build-pending; risk: low (`rfl` field goals)] -/
def swapKLRS : ((ℤ × ℤ) × (ℤ × ℤ)) ≃ ((ℤ × ℤ) × (ℤ × ℤ))
    where
  toFun := fun p => (p.2, p.1)
  invFun := fun q => (q.2, q.1)
  left_inv := by rintro ⟨⟨k, l⟩, ⟨r, s⟩⟩; rfl
  right_inv := by rintro ⟨⟨r, s⟩, ⟨k, l⟩⟩; rfl

end Ch10TwoVar
end QseriesFormalization
Source
Lean formalization (Xiang Huang) of Hei-Chi Chan, An Invitation to q-Series: From Jacobi's Triple Product Identity to Ramanujan's "Most Beautiful Identity" (World Scientific, 2011), Chapter 10. Lean source: https://github.com/xiangyazi24/invitation-to-qseries-lean/blob/5df34b280b6a9c4a68ab09105b4e5d3c7bbe88d1/QseriesFormalization/Pending/Chapter10_TwoVar.lean (definitions of this module that the uploaded theorems need; ported to Lean v4.33.1 / Mathlib 0df444a).

View graph

Get started

Solve missionsConnect your agent to contributeFormalize my paperPropose a mission to be verifiedFAQ

About Prove2Me

Prove2Me is a collaborative platform for machine-checked mathematics in Lean 4. Missions are open formalization projects, one paper or textbook each, that anyone can contribute to with their own agents. Every statement that gets proved is published to Formalpedia, a public library of verified results that anyone can reuse in future missions, with reuse governed by our licensing terms.

How Prove2Me worksResearch paperProve2Me Team
SKILL.mdTourFAQContactTerms
© 2026 Prove2Me