Skip to content

Lean formalization of the Riemann Hypothesis (Alpöge, 2026-11-20) being cleaned up by members of the Lean community.

Python
64.2 KB
Raw Blame
module

public import Mathlib.Order.CompletePartialOrder
import Mathlib.Algebra.Module.StablyFree.Basic
import Mathlib.Algebra.MvPolynomial.Coeff
import Mathlib.RingTheory.Coalgebra.IsFrobenius
import Mathlib.RingTheory.Etale.Weakly
import Mathlib.RingTheory.Finiteness.Lattice
import Mathlib.RingTheory.HopfAlgebra.Basic
import Mathlib.RingTheory.SimpleRing.Principal
import Mathlib.RingTheory.TotallySplit
import TauCeti.Algebra.BigOperators.ZPow
import TauCeti.RingTheory.MvPolynomial.Evaluation.Homogeneous
public import Lib.GLn.SchurModule.Basic
public import Lib.General.Groups.BesselGroups

/-!
# An average on polynomials in the entries of a matrix

Let `L` be a Levi subgroup of `GL_k`, `W` a local ring with large finite residue field, and
`ι : W → O` a ring map to a valuation domain of characteristic `0` in which the prime `p` is not a
unit. Let `ρ ∈ ℤ ^ k` weigh the indices, and call a monomial in the matrix entries *bad* if its row
weight exceeds a threshold. The file constructs an `O`-linear form `I` on polynomials in the matrix
entries (`New.Average.exists_isAverage`) that is invariant under conjugation by `L(W)`, vanishes
on bad monomials, and agrees modulo an ideal `J` with a power of `p` times evaluation at the matrix
`1` on every polynomial of small degree whose conjugates have no bad monomial modulo `J`
(`New.Average.IsAverage`, `New.Average.evalAtOne`).

* `New.Average.exists_isAdjointWeight`: the multinomial coefficients of the monomials of
  degree `< p ^ f` in `m` variables divide `p ^ (m f)` in `O`, and the quotients make the
  substitutions by a matrix and by its transpose adjoint.
* `New.Average.eq_top_of_schurMap_eq_leviMonomialValues`: the points of `L(W)` span the Schur
  algebra of `L` of degree `d`, which acts on `U = (O ^ k)^{⊗ d}`.
* `New.Average.dualOperator`: with the quotients above, a polynomial `ψ` gives an element `ψ♯`
  of the Schur algebra. For `d < p ^ f` its trace on `U` is the scaled value at `1` of the part of
  degree `d` of `ψ`, and conjugation of `ψ` becomes conjugation of `ψ♯`.
* `New.Average.averagePart`: in degree `d ≤ D` the form `I` is the trace of `ψ♯` on `U` minus its
  trace on the submodule `U₊` (`New.Average.largeWeightSubmodule`) generated by the basis tensors of
  large weight.

All `k ^ 2` entries are variables; a monomial with an entry outside the blocks has `ψ♯ = 0`.
The row weight of a monomial `α` is `∑ α (i, j) • ρ i`; the column weight has `ρ j` in place of
`ρ i`. The Schur algebra is built on the transpose of the matrix of variables, so the row indices
of a monomial are the column indices of `ψ♯`, and no transpose appears in the rule for conjugation.
Transposing the variables gives the same statements with column weights, since `L(W)` is closed
under transposition.

Notions from other files:
* `New.linSubst z`: for an `m × σ` matrix `z` over `R`, the `R`-algebra map from polynomials in
  variables indexed by `σ` to those indexed by `m` that sends `X b` to `∑ t, z t b • X t`.
* `New.levi W τ`: the Levi subgroup of a labelling `τ` of the indices, made of the matrices in
  `GL_k(W)` whose entry `(i, j)` vanishes whenever `τ i ≠ τ j`.
* `New.kroneckerPi A`: the Kronecker product of a family of matrices `A s`; its entry at `(β, α)`
  is `∏ s, A s (β s) (α s)`.
* `New.fockPairing`: the bilinear form on polynomials for which monomials are orthogonal and
  `⟨x ^ α, x ^ α⟩ = α!`.

The average serves the map `Av` of `New.UpperBound.ElementaryDivisors.AveragingMap`.

## Relation to the literature

Known result: the Schur algebra, and that group elements span it in degrees below the size of the
field. Here this is proved for Levi subgroups over local rings, in degrees `d` with `d + k` at most
the size of the residue field. Source: Green, Polynomial representations of GL_n, 1980; Benson–Doty,
Schur–Weyl duality over finite fields, 2009.
-/

@[expose] public section

namespace New.Average

open MvPolynomial Matrix IsLocalRing Finsupp Module LinearMap Submodule Finset Nat Fintype

/-! ### Multinomial coefficients and adjoint substitutions -/

/-- Let the prime `p` be a non-unit of the valuation domain `O`. A binomial coefficient with upper
index `< p ^ f` divides `p ^ f` in `O`. -/
lemma cast_choose_dvd_pow {O : Type} [CommRing O] [IsDomain O] [ValuationRing O] {p : ℕ}
    (hp_prime : p.Prime) (hp : ¬IsUnit (p : O)) {f n m : ℕ} (h_lt : n + m < p ^ f) :
    ((n + m).choose n : O) ∣ p ^ f := by
  -- The coefficient `c` is a unit times `p ^ v`, where `v ≤ f` is its `p`-adic valuation.
  set c : ℕ := (n + m).choose n
  have h_coprime : p.Coprime (ordCompl[p] c) :=
    coprime_ordCompl hp_prime (choose_ne_zero le_self_add)
  have h_unit : IsUnit ((ordCompl[p] c : ℕ) : O) :=
    notMem_maximalIdeal.1 (Ideal.IsPrime.notMem_of_isCoprime_of_mem h_coprime.cast hp)
  have h_le : c.factorization p ≤ f :=
    calc c.factorization p ≤ log p (n + m) := factorization_choose_le_log
      _ ≤ log p (p ^ f) := log_mono_right h_lt.le
      _ = f := log_pow hp_prime.one_lt f
  rw [← ordProj_mul_ordCompl_eq_self c p, cast_mul, cast_pow, h_unit.mul_right_dvd]
  exact pow_dvd_pow (p : O) h_le

/-- Let the prime `p` be a non-unit of the valuation domain `O`. A multinomial coefficient over `s`
of total degree `< p ^ f` divides `p ^ (#s * f)` in `O`. -/
lemma cast_multinomial_dvd_pow {O : Type} [CommRing O] [IsDomain O] [ValuationRing O] {p : ℕ}
    (hp_prime : p.Prime) (hp : ¬IsUnit (p : O)) {κ : Type*} {f : ℕ} (s : Finset κ) (α : κ → ℕ)
    (h_lt : ∑ i ∈ s, α i < p ^ f) : (multinomial s α : O) ∣ p ^ (#s * f) := by
  -- The coefficient is a product of `#s` binomial coefficients.
  induction s using cons_induction with
  | empty => simp
  | cons a s ha ih =>
    rw [multinomial_cons, cast_mul, card_cons, Nat.add_one_mul, pow_add, mul_comm]
    exact mul_dvd_mul (ih (by grind)) (cast_choose_dvd_pow hp_prime hp (by simpa using h_lt))

/-- Give the polynomials in the variables `σ` the bilinear form for which monomials are orthogonal
and `⟨x ^ α, x ^ α⟩ = η α`. The weights `η` are adjoint weights if, for every matrix `A`, the linear
substitutions of the variables (`linSubst`) by `A` and by `Aᵀ` are adjoint for this form. -/
def IsAdjointWeight {O σ : Type} [CommRing O] [Fintype σ] (η : (σ →₀ ℕ) → O) : Prop :=
  ∀ (A : Matrix σ σ O) (α β : σ →₀ ℕ),
    (linSubst A (monomial β 1)).coeff α * η α = η β * (linSubst Aᵀ (monomial α 1)).coeff β

/-- The linear substitutions (`linSubst`) of the variables `σ` by a matrix `A` and by `Aᵀ` have
matrices in the monomial basis that are transposes of each other up to the factors
`α! = ∏ i, (α i)!`. This is their adjointness for `fockPairing`, the bilinear form with
`⟨x ^ α, x ^ α⟩ = α!`, written out for two monomials. -/
lemma prod_factorial_mul_coeff_linSubst {O σ : Type} [CommRing O] [Fintype σ] (A : Matrix σ σ O)
    (α β : σ →₀ ℕ) :
    (∏ i : σ, (α i)! : ℕ) * (linSubst A (monomial β 1)).coeff α =
      (∏ i : σ, (β i)! : ℕ) * (linSubst Aᵀ (monomial α 1)).coeff β := by
  classical
  have h_pairing (γ : σ →₀ ℕ) (g : MvPolynomial σ O) :
      fockPairing O (monomial γ 1) g = (∏ i : σ, (γ i)! : ℕ) * g.coeff γ := by
    simp [fockPairing_monomial, prod_fintype]
  rw [← h_pairing, ← h_pairing, fockPairing_linSubst, fockPairing_comm]

/-- A linear substitution of the variables preserves the degree: the image of the monomial `δ` has
no monomial `γ` of another degree. -/
lemma coeff_linSubst_monomial_eq_zero {O σ : Type} [CommRing O] [Fintype σ] (B : Matrix σ σ O)
    {γ δ : σ →₀ ℕ} (h_ne : ∑ i : σ, γ i ≠ ∑ i : σ, δ i) :
    (linSubst B (monomial δ 1)).coeff γ = 0 := by
  classical exact (Monomials.isHomogeneous_linSubst B
    (⟨δ, by simp⟩ : Monomials σ (∑ i : σ, δ i))).coeff_eq_zero (by rwa [degree_eq_sum])

/-- Let `O` be a valuation domain of characteristic `0` in which the prime `p` is not a unit. There
are weights `η γ ∈ O` of the monomials in the variables `σ`, with
`p ^ (#σ * f) = multinomial γ * η γ` in degree `< p ^ f`, such that the symmetric bilinear form with
the diagonal values `η γ` is invariant in the sense that linear substitutions by a matrix and by its
transpose are adjoint for it (`IsAdjointWeight`). -/
lemma exists_isAdjointWeight {O : Type} (σ : Type) [CommRing O] [Fintype σ] [IsDomain O]
    [CharZero O] [ValuationRing O] {p : ℕ} (hp_prime : p.Prime) (hp : ¬IsUnit (p : O)) (f : ℕ) :
    ∃ η : (σ →₀ ℕ) → O,
      (∀ γ : σ →₀ ℕ, γ.degree < p ^ f → (p : O) ^ (Fintype.card σ * f) = γ.multinomial * η γ) ∧
      IsAdjointWeight η := by
  classical
  -- `η γ` is `p ^ (card σ * f)` over the multinomial coefficient in degree `< p ^ f`, else `0`.
  have h_quot (γ : σ → ℕ) : ∃ c : O,
      (if ∑ i, γ i < p ^ f then (p : O) ^ (card σ * f) else 0) = multinomial univ γ * c := by
    split_ifs with h_lt
    exacts [cast_multinomial_dvd_pow hp_prime hp univ γ h_lt, dvd_zero _]
  choose (η : (σ → ℕ) → O) hη using h_quot
  refine ⟨fun γ ↦ η γ, fun γ hγ ↦ ?_, fun A α β ↦ ?_⟩
  · rw [multinomial_eq_of_support_subset (subset_univ _), ← hη γ, ← degree_eq_sum, ite_eq_left hγ]
  by_cases h_deg : ∑ i, α i = ∑ i, β i
  · -- Multiply by the factorial of the common degree and use adjointness for the weights `α!`.
    refine mul_left_cancel₀ (cast_ne_zero.2 (∑ i, α i).factorial_ne_zero) ?_
    calc ((∑ i, α i)! : O) * ((linSubst A (monomial β 1)).coeff α * η α)
        = (∏ i, (α i)! : ℕ) * (linSubst A (monomial β 1)).coeff α * (multinomial univ α * η α) := by
          rw [← multinomial_spec univ α, cast_mul]; ring
      _ = (∏ i, (β i)! : ℕ) * (linSubst Aᵀ (monomial α 1)).coeff β *
            (multinomial univ β * η β) := by
          rw [prod_factorial_mul_coeff_linSubst, ← hη α, ← hη β, h_deg]
      _ = (∑ i, α i)! * (η β * (linSubst Aᵀ (monomial α 1)).coeff β) := by
          rw [h_deg, ← multinomial_spec univ β, cast_mul]; ring
  · -- In different degrees both coefficients vanish.
    simp [coeff_linSubst_monomial_eq_zero, h_deg, Ne.symm h_deg]

/-! ### Conjugation and averages -/

/-- Conjugation of the generic matrix: the `O`-algebra map that substitutes `ι(a⁻¹) * X * ι(a)` for
`X`, so `X (i, j) ↦ ∑ s t, ι (a⁻¹ i s) * ι (a t j) • X (s, t)`. It is written as the linear
substitution `New.linSubst` by the Kronecker product of `ι(a⁻¹)ᵀ` and `ι(a)`, whose entry at
`((s, t), (i, j))` is that coefficient. -/
noncomputable def conjSubst {k : ℕ} {W O : Type} [CommRing W] [CommRing O] (ι : W →+* O)
    (a : GL (Fin k) W) :
    MvPolynomial (Fin k × Fin k) O →ₐ[O] MvPolynomial (Fin k × Fin k) O :=
  linSubst (a⁻¹.valᵀ.kroneckerMap (fun s t : W ↦ ι s * ι t) a.val)

/-- Conjugation (`conjSubst`) by the diagonal matrix `diagGL u` with unit entries `u i` scales the
variable `X (i, j)` by `ι ((u i)⁻¹ * u j)`. -/
lemma conjSubst_diagGL_X {k : ℕ} {W O : Type} [CommRing W] [CommRing O] (ι : W →+* O)
    (u : Fin k → Wˣ) (v : Fin k × Fin k) :
    conjSubst ι (diagGL u) (X v) =
      ι ((u v.1)⁻¹ * u v.2 : Wˣ) • (X v : MvPolynomial (Fin k × Fin k) O) := by
  rw [conjSubst, ← map_inv diagGL, coe_diagGL, coe_diagGL]
  simp [linSubst, sum_prod_type, diagonal_apply, apply_ite ι]

/-- The form `ψ ↦ c * ψ(1)`: evaluation at the identity matrix, times `c`. -/
noncomputable def evalAtOne {k : ℕ} {O : Type} [CommRing O] (c : O) :
    Dual O (MvPolynomial (Fin k × Fin k) O) :=
  c • (aeval (vec (1 : Matrix (Fin k) (Fin k) O))).toLinearMap

/-- The form `evalAtOne c` sends `ψ` to `c` times the value of `ψ` at the identity matrix. -/
lemma evalAtOne_apply {k : ℕ} {O : Type} [CommRing O] (c : O) (ψ : MvPolynomial (Fin k × Fin k) O) :
    evalAtOne c ψ = c * eval (vec (1 : Matrix (Fin k) (Fin k) O)) ψ := by
  simp [evalAtOne]

/-- Let `ι : W → O` be a map of commutative rings and `a ∈ GL_k(W)`. The substitution
`conjSubst ι a : X ↦ ι(a⁻¹) * X * ι(a)` of the matrix of variables does not change
`evalAtOne c ψ = c * ψ(1)`, because conjugation fixes the identity matrix. -/
lemma evalAtOne_conjSubst {k : ℕ} {W O : Type} [CommRing W] [CommRing O] (ι : W →+* O) (c : O)
    (a : GL (Fin k) W) (ψ : MvPolynomial (Fin k × Fin k) O) :
    evalAtOne c (conjSubst ι a ψ) = evalAtOne c ψ := by
  have hev : (aeval (vec 1)).comp (conjSubst ι a) = aeval (vec (1 : Matrix (Fin k) (Fin k) O)) := by
    ext ⟨i, j⟩
    calc _ = ∑ s : Fin k, ι (a⁻¹.val i s) * ι (a.val s j) := by
          simp [conjSubst, linSubst, sum_prod_type, Matrix.one_apply]
      _ = ι ((a⁻¹ * a).val i j) := by simp only [Units.val_mul, Matrix.mul_apply, map_sum, map_mul]
      _ = _ := by simp [Matrix.one_apply, eq_comm]
  simpa [evalAtOne] using congrArg (c * ·) (AlgHom.congr_fun hev ψ)

/-- Let `ι : W → O` be a map of commutative rings, `u` a unit of `W`, and `a` the diagonal matrix
with entries `u ^ ρ i`. The substitution `conjSubst ι a : X ↦ ι(a⁻¹) * X * ι(a)` of the matrix of
variables multiplies the monomial `α` by `ι u ^ e`, where `e` is the column weight
`∑ α (i, j) • ρ j` less the row weight `∑ α (i, j) • ρ i`. -/
lemma conjSubst_diagGL_zpow_monomial {k : ℕ} {W O : Type} [CommRing W] [CommRing O] (ι : W →+* O)
    (u : Wˣ) (ρ : Fin k → ℤ) (α : Fin k × Fin k →₀ ℕ) :
    conjSubst ι (diagGL fun i : Fin k ↦ u ^ ρ i) (monomial α 1) =
      (Units.map (ι : W →* O) u ^ (weight (fun v : Fin k × Fin k ↦ ρ v.2) α -
        weight (fun v : Fin k × Fin k ↦ ρ v.1) α) : Oˣ).val •
          (monomial α 1 : MvPolynomial (Fin k × Fin k) O) := by
  set u' : Oˣ := Units.map (ι : W →* O) u
  set e : ℤ := weight (fun v : Fin k × Fin k ↦ ρ v.2) α - weight (fun v : Fin k × Fin k ↦ ρ v.1) α
  have h_factor (i j : Fin k) : ι ((u ^ ρ i)⁻¹ * u ^ ρ j : Wˣ) = (u' ^ (ρ j - ρ i) : Oˣ) := by
    simp [u', _root_.zpow_sub, mul_comm, ← map_zpow]
  have h_prod : ∏ v : Fin k × Fin k, (u' ^ (ρ v.2 - ρ v.1)) ^ α v = u' ^ e := by
    simp [e, ← zpow_natCast, ← _root_.zpow_mul, Finset.prod_zpow_eq_zpow_sum, weight_eq_sum,
      sub_mul, mul_comm (α _ : ℤ)]
  simp only [monomial_eq, C_1, one_mul, prod_fintype _ _ fun _ ↦ pow_zero _, map_prod, map_pow,
    conjSubst_diagGL_X, h_factor, smul_pow, prod_smul, ← h_prod, Units.coe_prod,
    Units.val_pow_eq_pow_val]

/-- Let `ι : W → O` be a ring map from a local ring to a domain of characteristic `0` in which
`p > 0` is not a unit. Let `levi W τ` be the group of the `a ∈ GL_k(W)` with `a i j = 0` whenever
the labels `τ i` and `τ j` differ, and let the linear form `I` on polynomials in the entries of a
matrix `X` be invariant under the substitutions `conjSubst ι a : X ↦ ι(a⁻¹) * X * ι(a)` for `a` in
this group. Then `I` vanishes on the monomials `α` whose row weight `∑ α (i, j) • ρ i` and column
weight `∑ α (i, j) • ρ j` differ. -/
lemma apply_monomial_eq_zero_of_weight_ne {k : ℕ} {W O : Type} [CommRing W] [IsLocalRing W]
    [CommRing O] (τ : Fin k → ℕ) (ι : W →+* O) [IsDomain O] [CharZero O] {p : ℕ} (hp_pos : 0 < p)
    (hp : ¬IsUnit (p : O)) (ρ : Fin k → ℤ) {I : Dual O (MvPolynomial (Fin k × Fin k) O)}
    (hI : ∀ a ∈ levi W τ, ∀ ψ : MvPolynomial (Fin k × Fin k) O, I (conjSubst ι a ψ) = I ψ)
    {α : Fin k × Fin k →₀ ℕ}
    (hα : weight (fun v : Fin k × Fin k ↦ ρ v.1) α ≠ weight (fun v : Fin k × Fin k ↦ ρ v.2) α) :
    I (monomial α 1) = 0 := by
  -- Conjugation by `diag ((1 + p) ^ ρ i)` multiplies the monomial by `(1 + p) ^ e`, where `e` is
  -- the column weight less the row weight, and `1 + p` is not a root of unity.
  have h_unit : IsUnit (1 + p : W) := by
    simpa using (isUnit_or_isUnit_one_sub_self (-p : W)).resolve_left
      fun h ↦ hp (by simpa using h.map ι)
  let u : Oˣ := Units.map ι h_unit.unit
  have h_levi : diagGL (fun i : Fin k ↦ h_unit.unit ^ ρ i) ∈ levi W τ := fun i j hij ↦ by
    simp [ne_of_apply_ne τ hij]
  have h_order : ¬IsOfFinOrder u := fun h ↦ by
    obtain ⟨m, hm_pos, hm⟩ := h.exists_pow_eq_one
    have h_cast : (((1 + p) ^ m : ℕ) : O) = (1 : ℕ) := by simpa [u] using congrArg Units.val hm
    exact (Nat.one_lt_pow hm_pos.ne' (by lia)).ne' (Nat.cast_injective h_cast)
  let e : ℤ := weight (fun v : Fin k × Fin k ↦ ρ v.2) α - weight (fun v : Fin k × Fin k ↦ ρ v.1) α
  have h_ne : (u ^ e : Oˣ).val ≠ 1 := fun h ↦
    h_order (isOfFinOrder_iff_zpow_eq_one.2 ⟨e, sub_ne_zero.2 hα.symm, Units.ext h⟩)
  have h_inv : (u ^ e : Oˣ).val * I (monomial α 1) = I (monomial α 1) := by
    rw [← smul_eq_mul, ← map_smul, ← conjSubst_diagGL_zpow_monomial, hI _ h_levi]
  exact (mul_left_eq_self₀.1 h_inv).resolve_left h_ne

/-- The linear form `I` on polynomials over `O` in the entries of a `k × k` matrix `X` is an average
for the Levi subgroup `L(W) = levi W τ` of the `a ∈ GL_k(W)` with `a i j = 0` whenever `τ i ≠ τ j`,
which acts by the substitutions `conjSubst ι a : X ↦ ι(a⁻¹) * X * ι(a)`. A monomial `α` is bad if
its row weight `∑ α (i, j) • ρ i` exceeds `t`; `c` scales the evaluation at the matrix `1`, and `D`
bounds the degree. If `W` is local and `O` is a domain of characteristic `0` in which some `p > 0`
is not a unit, then by invariance `I` also vanishes on the monomials whose row weight and column
weight differ (`apply_monomial_eq_zero_of_weight_ne`). -/
structure IsAverage {k : ℕ} {W O : Type} [CommRing W] [CommRing O] (τ : Fin k → ℕ) (ι : W →+* O)
    (ρ : Fin k → ℤ) (t : ℤ) (c : O) (D : ℕ)
    (I : Dual O (MvPolynomial (Fin k × Fin k) O)) : Prop where
  /-- `I` is invariant under conjugation by `L(W)`. -/
  map_conjSubst : ∀ a ∈ levi W τ, ∀ ψ : MvPolynomial (Fin k × Fin k) O, I (conjSubst ι a ψ) = I ψ
  /-- `I` vanishes on bad monomials. -/
  map_monomial_eq_zero : ∀ α : Fin k × Fin k →₀ ℕ,
    t < weight (fun v : Fin k × Fin k ↦ ρ v.1) α → I (monomial α 1) = 0
  /-- If `ψ` has degree at most `D` and the bad monomials of all its conjugates have coefficients
  in the ideal `J`, then `I ψ ≡ c * ψ(1)` modulo `J`. -/
  sub_evalAtOne_mem : ∀ (J : Ideal O) (ψ : MvPolynomial (Fin k × Fin k) O), ψ.totalDegree ≤ D →
    (∀ a ∈ levi W τ, ∀ α : Fin k × Fin k →₀ ℕ,
      t < weight (fun v : Fin k × Fin k ↦ ρ v.1) α → (conjSubst ι a ψ).coeff α ∈ J) →
    I ψ - evalAtOne c ψ ∈ J

/-- An `O`-linear form `l` on polynomials, applied entry by entry to a matrix `X`, commutes with
multiplication by constant matrices `A` and `B`. -/
lemma map_C_mul_mul_C {O σ : Type} [CommRing O] [Fintype σ] {ν : Type*} (A B : Matrix σ σ O)
    (X : Matrix σ σ (MvPolynomial ν O)) (l : Dual O (MvPolynomial ν O)) :
    (A.map C * X * B.map C).map l = A * X.map l * B := by
  ext i j
  simp [mul_comm (∑ _, _), C_mul', Matrix.mul_apply]

/-- Zariski density over local rings. Let the polynomial `g` over the local ring `W` be homogeneous
of degree `e` and take a unit value at some point `b₀`, and let `n + e ≤ Nat.card` of the residue
field of `W`. Let `γ` run over `Monomials σ n`, the exponent vectors of degree `n`, and let
`ι : W → O` be a ring map. Then the vectors `γ ↦ ι (b ^ γ)`, at the points `b` where `g (b)` is a
unit, span `Monomials σ n → O`: a submodule `V` that contains them is everything. -/
lemma eq_top_of_eval_monomial {W O σ : Type} [CommRing W] [IsLocalRing W] [CommRing O]
    (ι : W →+* O) [Fintype σ] [DecidableEq σ] (n : ℕ) {e : ℕ} {g : MvPolynomial σ W}
    (hg : g.IsHomogeneous e) (hW : n + e ≤ Nat.card (ResidueField W)) {b₀ : σ → W}
    (hb₀ : IsUnit (eval b₀ g)) {V : Submodule O (Monomials σ n → O)}
    (hV : ∀ b : σ → W, IsUnit (eval b g) →
      (fun γ : Monomials σ n ↦ ι (eval b (monomial γ.val 1))) ∈ V) : V = ⊤ := by
  -- Reindex exponents from `Monomials σ n` to `{γ // γ.degree = n}`.
  let e_mon : Monomials σ n ≃ {γ : σ →₀ ℕ // γ.degree = n} :=
    Equiv.subtypeEquivRight fun γ ↦ by simp [mem_finsuppAntidiag, degree_eq_sum]
  -- Transport functions along `e_mon` via `LinearEquiv.funCongrLeft`.
  let L : ({γ : σ →₀ ℕ // γ.degree = n} → O) ≃ₗ[O] (Monomials σ n → O) :=
    LinearEquiv.funCongrLeft O O e_mon
  -- Apply `span_range_prod_pow_eq_top` using `Nat.card ≤ Cardinal.mk`.
  have h_span := hg.span_range_prod_pow_eq_top ι
    ((Nat.cast_le.2 hW).trans (Cardinal.natCast_toNat_le _)) ⟨b₀, hb₀⟩
  -- Map the spanning set along `L` and reduce to `V`.
  rw [← top_le_iff, ← LinearMap.range_eq_top.2 L.surjective, ← Submodule.map_top, ← h_span,
    Submodule.map_span, Submodule.span_le]
  rintro _ ⟨_, ⟨⟨b, hb⟩, rfl⟩, rfl⟩
  -- Each mapped generator evaluates `monomial γ.val 1` at `b` as `∏ i, b i ^ γ.val i`.
  change (fun γ : Monomials σ n ↦ ι (∏ i, b i ^ γ.val i)) ∈ V
  simpa [eval_monomial, prod_fintype] using hV b hb

section SchurAlgebra

/-- The generic block matrix of the labelling `τ` of the indices, transposed: the entry at `(i, j)`
is the variable `X (j, i)` if `τ i = τ j` and `0` otherwise. This is the index order of
`Matrix.vec`. -/
noncomputable def leviGeneric {k : ℕ} (O : Type) [CommRing O] (τ : Fin k → ℕ) :
    Matrix (Fin k) (Fin k) (MvPolynomial (Fin k × Fin k) O) :=
  of fun i j : Fin k ↦ C (if τ i = τ j then 1 else 0) * X (j, i)

/-- The `d`-th tensor power of the generic block matrix `leviGeneric O τ`. -/
noncomputable def leviTensor {k : ℕ} (O : Type) [CommRing O] (τ : Fin k → ℕ) (d : ℕ) :
    Matrix (Fin d → Fin k) (Fin d → Fin k) (MvPolynomial (Fin k × Fin k) O) :=
  kroneckerPi fun _ : Fin d ↦ leviGeneric O τ

/-- The map onto the Schur algebra of degree `d`: a linear form, given by its values on the
monomials of degree `d`, is applied to the entries of `leviTensor O τ d`. -/
noncomputable def schurMap {k : ℕ} (O : Type) [CommRing O] (τ : Fin k → ℕ) (d : ℕ) :
    (Monomials (Fin k × Fin k) d → O) →ₗ[O] Matrix (Fin d → Fin k) (Fin d → Fin k) O :=
  (Pi.basisFun O (Monomials (Fin k × Fin k) d)).constr O fun γ : Monomials (Fin k × Fin k) d ↦
    (leviTensor O τ d).map (·.coeff γ.val)

/-- The values of the monomials of degree `d` at the point `a` of the Levi subgroup, mapped to `O`
by `ι`. The variable `X (j, i)` takes the value `a i j`, as in `Matrix.vec`. -/
noncomputable def leviMonomialValues {k : ℕ} {W O : Type} [CommRing W] [CommRing O]
    (τ : Fin k → ℕ) (ι : W →+* O) (d : ℕ) (a : levi W τ) : Monomials (Fin k × Fin k) d → O :=
  fun γ ↦ aeval (ι ∘ vec (a.val : Matrix (Fin k) (Fin k) W)) (monomial γ.val (1 : O))

/-- The coefficients of degree `d` of a polynomial, scaled by `η`: `ψ ↦ (γ ↦ coeff γ ψ * η γ)`. -/
noncomputable def scaledCoeff {k : ℕ} {O : Type} [CommRing O] (η : (Fin k × Fin k →₀ ℕ) → O)
    (d : ℕ) :
    MvPolynomial (Fin k × Fin k) O →ₗ[O] Monomials (Fin k × Fin k) d → O :=
  pi fun γ : Monomials (Fin k × Fin k) d ↦ (lcoeff O γ.val).smulRight (η γ.val)

/-- Polynomials as operators: the element `ψ♯` of the Schur algebra of degree `d` dual to the
polynomial `ψ`, a matrix that acts on `(O ^ k)^{⊗ d}`. For multi-indices `i, j : Fin d → Fin k` its
entry at `(i, j)` is `η α` times the coefficient in `ψ` of the monomial `α = ∏ l, X (j l, i l)` if
`τ (i l) = τ (j l)` for all `l`, and `0` otherwise. Only the part of degree `d` of `ψ` matters. -/
noncomputable def dualOperator {k : ℕ} {O : Type} [CommRing O] (τ : Fin k → ℕ)
    (η : (Fin k × Fin k →₀ ℕ) → O) (d : ℕ) :
    MvPolynomial (Fin k × Fin k) O →ₗ[O] Matrix (Fin d → Fin k) (Fin d → Fin k) O :=
  schurMap O τ d ∘ₗ scaledCoeff η d

/-- The map that sends `c` to the image of the basis tensor with indices `j` under the element
`schurMap O τ d c` of the Schur algebra. -/
noncomputable def tensorOrbit {k : ℕ} (O : Type) [CommRing O] (τ : Fin k → ℕ) {d : ℕ}
    (j : Fin d → Fin k) : (Monomials (Fin k × Fin k) d → O) →ₗ[O] (Fin d → Fin k) → O :=
  toLin'.toLinearMap.flip (Pi.single j 1) ∘ₗ schurMap O τ d

/-- The submodule `U₊` of the `d`-th tensor power of `O ^ k` that is generated under the Schur
algebra by the basis tensors `j` whose weight `∑ l, ρ (j l)` exceeds `t`. -/
noncomputable def largeWeightSubmodule {k : ℕ} (O : Type) [CommRing O] (τ : Fin k → ℕ)
    (ρ : Fin k → ℤ) (t : ℤ) (d : ℕ) : Submodule O ((Fin d → Fin k) → O) :=
  ⨆ j : {j : Fin d → Fin k // t < ∑ l : Fin d, ρ (j l)}, range (tensorOrbit O τ j.val)

/-- `largeWeightSubmodule` is a finite sum of images of finite modules. -/
instance finite_largeWeightSubmodule {k : ℕ} {O : Type} [CommRing O] (τ : Fin k → ℕ) {d : ℕ}
    (ρ : Fin k → ℤ) (t : ℤ) :
    Module.Finite O (largeWeightSubmodule O τ ρ t d) :=
  inferInstanceAs (Module.Finite O (⨆ j : {j : Fin d → Fin k // t < ∑ l : Fin d, ρ (j l)},
    range (tensorOrbit O τ j.val) : Submodule O ((Fin d → Fin k) → O)))

lemma tensorOrbit_apply {k : ℕ} {O : Type} [CommRing O] (τ : Fin k → ℕ) {d : ℕ}
    (j : Fin d → Fin k) (c : Monomials (Fin k × Fin k) d → O) :
    tensorOrbit O τ j c = schurMap O τ d c *ᵥ Pi.single j 1 := rfl

/-- An element `schurMap O τ d c` of the Schur algebra maps a basis tensor `j` of weight
`∑ l, ρ (j l) > t` into `largeWeightSubmodule O τ ρ t d`, which such images generate. -/
lemma schurMap_mulVec_single_mem_largeWeightSubmodule {k : ℕ} {O : Type} [CommRing O]
    (τ : Fin k → ℕ) {d : ℕ} {ρ : Fin k → ℤ} {t : ℤ} {j : Fin d → Fin k}
    (hj : t < ∑ l : Fin d, ρ (j l)) (c : Monomials (Fin k × Fin k) d → O) :
    schurMap O τ d c *ᵥ Pi.single j 1 ∈ largeWeightSubmodule O τ ρ t d :=
  mem_iSup_of_mem ⟨j, hj⟩ ⟨c, rfl⟩

/-- The entry `(i, j)` of `leviTensor O τ d`, the `d`-th tensor power of the generic block matrix,
is the monomial `∏ l, X (j l, i l)` if `τ (i l) = τ (j l)` for all `l`, and zero otherwise. -/
lemma leviTensor_apply {k : ℕ} {O : Type} [CommRing O] (τ : Fin k → ℕ) {d : ℕ}
    (i j : Fin d → Fin k) :
    leviTensor O τ d i j = monomial (∑ l : Fin d, single (j l, i l) 1)
      (∏ l : Fin d, if τ (i l) = τ (j l) then 1 else 0) := by
  simp only [leviTensor, leviGeneric, kroneckerPi, of_apply, C_mul_X_eq_monomial, monomial_sum_prod]

lemma scaledCoeff_apply {k : ℕ} {O : Type} [CommRing O] {d : ℕ} (η : (Fin k × Fin k →₀ ℕ) → O)
    (ψ : MvPolynomial (Fin k × Fin k) O) (γ : Monomials (Fin k × Fin k) d) :
    scaledCoeff η d ψ γ = ψ.coeff γ.val * η γ.val := rfl

lemma dualOperator_apply {k : ℕ} {O : Type} [CommRing O] (τ : Fin k → ℕ) {d : ℕ}
    (η : (Fin k × Fin k →₀ ℕ) → O) (ψ : MvPolynomial (Fin k × Fin k) O) :
    dualOperator τ η d ψ = schurMap O τ d (scaledCoeff η d ψ) := rfl

/-- If `α` has a nonzero coefficient in the entry `(i, j)` of the tensor power `leviTensor O τ d` of
the generic block matrix, then the weight of `α` under `w` is `∑ l, w (j l, i l)`. -/
lemma weight_eq_of_coeff_leviTensor_ne_zero {k : ℕ} {O : Type} [CommRing O] (τ : Fin k → ℕ)
    {d : ℕ} (i j : Fin d → Fin k) (α : Fin k × Fin k →₀ ℕ) (w : Fin k × Fin k → ℤ)
    (h_coeff : (leviTensor O τ d i j).coeff α ≠ 0) :
    weight w α = ∑ l : Fin d, w (j l, i l) := by
  obtain rfl : ∑ l : Fin d, single (j l, i l) 1 = α := by simp_all [leviTensor_apply]
  simp [weight]

lemma isHomogeneous_leviTensor {k : ℕ} {O : Type} [CommRing O] (τ : Fin k → ℕ) {d : ℕ}
    (i j : Fin d → Fin k) : (leviTensor O τ d i j).IsHomogeneous d := by
  simpa [leviTensor_apply] using isHomogeneous_monomial _ (by simp)

/-- Let `T = leviTensor O τ d` be the `d`-th tensor power of the generic block matrix of `τ`, a
matrix of polynomials. The linear map `schurMap O τ d` sends the basis vector at a monomial `γ` of
degree `d` to the matrix of the coefficients of `γ` in the entries of `T`. It sends the vector of
values of a linear form `l` on these monomials to `T` with `l` applied to each entry. -/
lemma schurMap_apply_monomial {k : ℕ} {O : Type} [CommRing O] (τ : Fin k → ℕ) {d : ℕ}
    (l : Dual O (MvPolynomial (Fin k × Fin k) O)) :
    schurMap O τ d (fun γ : Monomials (Fin k × Fin k) d ↦ l (monomial γ.val 1)) =
      (leviTensor O τ d).map l := by
  ext i j
  have h_sum : ∑ γ : Monomials (Fin k × Fin k) d,
      (leviTensor O τ d i j).coeff γ.val • monomial γ.val 1 = leviTensor O τ d i j :=
    sum_monomials_eq_of_isHomogeneous (isHomogeneous_leviTensor τ i j)
  rw [Matrix.map_apply, ← h_sum]
  simp [Matrix.sum_apply, schurMap, mul_comm]

/-- Evaluation at `ι ∘ b` goes, in the Schur algebra, to the `d`-th tensor power of the generic
block matrix `leviGeneric W τ` evaluated at `b` and mapped to `O` by `ι`. -/
lemma schurMap_aeval {k : ℕ} {W O : Type} [CommRing W] [CommRing O] (τ : Fin k → ℕ) (ι : W →+* O)
    {d : ℕ} (b : Fin k × Fin k → W) :
    schurMap O τ d (fun γ : Monomials (Fin k × Fin k) d ↦ aeval (ι ∘ b) (monomial γ.val (1 : O))) =
      kroneckerPi fun _ : Fin d ↦ ((leviGeneric W τ).map (eval b)).map ι := by
  refine (schurMap_apply_monomial τ (aeval (ι ∘ b)).toLinearMap).trans ?_
  ext i j
  simp [leviTensor, leviGeneric, kroneckerPi, apply_ite ι, apply_ite (eval _)]

/-- The generic block matrix evaluated at a point `a` of the Levi subgroup is `a`. -/
lemma leviGeneric_map_eval {k : ℕ} {W : Type} [CommRing W] (τ : Fin k → ℕ) (a : levi W τ) :
    (leviGeneric W τ).map (eval (vec (a.val : Matrix (Fin k) (Fin k) W))) = a.val := by
  ext i j
  by_cases hij : τ i = τ j
  · simp [leviGeneric, hij]
  · simp [leviGeneric, hij, a.prop i j hij]

/-- The image in the Schur algebra of a point `a` of the Levi subgroup (`leviMonomialValues` lists
the values of the monomials at `a`) is the `d`-th tensor power of `ι(a)`. -/
lemma schurMap_leviMonomialValues {k : ℕ} {W O : Type} [CommRing W] [CommRing O] (τ : Fin k → ℕ)
    (ι : W →+* O) {d : ℕ} (a : levi W τ) :
    schurMap O τ d (leviMonomialValues τ ι d a) =
      kroneckerPi fun _ : Fin d ↦ (a.val : Matrix (Fin k) (Fin k) W).map ι := by
  rw [← leviGeneric_map_eval τ a]
  exact schurMap_aeval τ ι _

/-- The element `dualOperator τ η d (monomial α 1)` of the Schur algebra dual to the monomial `α`
has as entries the coefficients of `α` in the entries of the tensor power `leviTensor O τ d` of the
generic block matrix, times `η α`. -/
lemma dualOperator_monomial {k : ℕ} {O : Type} [CommRing O] (τ : Fin k → ℕ) {d : ℕ}
    (η : (Fin k × Fin k →₀ ℕ) → O) (α : Fin k × Fin k →₀ ℕ) :
    dualOperator τ η d (monomial α 1) = (leviTensor O τ d).map (η α • lcoeff O α) := by
  rw [← schurMap_apply_monomial, dualOperator_apply]
  exact congrArg _ (funext fun γ ↦ by simp +contextual [scaledCoeff_apply, eq_comm])

/-- The operator `dualOperator τ η d (monomial α 1)` dual to the monomial `α` kills the basis tensor
`Pi.single j 1` unless the weight `∑ l, ρ (j l)` of `j` equals the weight of `α`. Here the weight of
`α` is `weight (fun v ↦ ρ v.1) α`. -/
lemma dualOperator_monomial_mulVec_single_eq_zero {k : ℕ} {O : Type} [CommRing O] (τ : Fin k → ℕ)
    {d : ℕ} (η : (Fin k × Fin k →₀ ℕ) → O) (ρ : Fin k → ℤ) {α : Fin k × Fin k →₀ ℕ}
    {j : Fin d → Fin k} (h_ne : weight (fun v : Fin k × Fin k ↦ ρ v.1) α ≠ ∑ l : Fin d, ρ (j l)) :
    dualOperator τ η d (monomial α 1) *ᵥ Pi.single j 1 = 0 := by
  have h_zero (i : Fin d → Fin k) : (leviTensor O τ d i j).coeff α = 0 :=
    by_contra fun h ↦ h_ne (weight_eq_of_coeff_leviTensor_ne_zero τ i j α _ h)
  ext i
  simp [dualOperator_monomial, mulVec_single, h_zero]

/-- The trace of the `d`-th tensor power of the generic block matrix is the `d`-th power of the sum
of the diagonal variables, written here as the linear form with coefficients the matrix `1`. -/
lemma trace_leviTensor {k : ℕ} {O : Type} [CommRing O] (τ : Fin k → ℕ) {d : ℕ} :
    (leviTensor O τ d).trace =
      (∑ v : Fin k × Fin k, vec (1 : Matrix (Fin k) (Fin k) O) v • X v) ^ d := by
  simp [leviTensor, leviGeneric, kroneckerPi, sum_pow', Matrix.trace, Matrix.one_apply,
    sum_prod_type]

/-- The matrix `dualOperator τ η d (monomial α 1)`, indexed by multi-indices `i, j : Fin d → Fin k`,
has the entry `η α` where `α` is the monomial `∏ l, X (j l, i l)` and `τ (i l) = τ (j l)` for all
`l`, and `0` elsewhere. If `α` has degree `d`, its trace is the multinomial coefficient of `α` times
`η α` times the value of the monomial at the matrix `1`. Otherwise it is zero. -/
lemma trace_dualOperator_monomial {k : ℕ} {O : Type} [CommRing O] (τ : Fin k → ℕ) {d : ℕ}
    (η : (Fin k × Fin k →₀ ℕ) → O) (α : Fin k × Fin k →₀ ℕ) :
    (dualOperator τ η d (monomial α 1)).trace =
      if degree α = d then evalAtOne (α.multinomial * η α) (monomial α 1) else 0 := by
  have h_trace : (dualOperator τ η d (monomial α 1)).trace =
      η α * (leviTensor O τ d).trace.coeff α := by
    simp [dualOperator_monomial, Matrix.trace, Finset.mul_sum]
  have h_coeff : (leviTensor O τ d).trace.coeff α = if degree α = d then
      α.multinomial * eval (vec (1 : Matrix (Fin k) (Fin k) O)) (monomial α 1) else 0 := by
    -- This is the multinomial theorem.
    rw [trace_leviTensor, coeff_linearCombination_X_pow_of_fintype]
    simp [eval_monomial, degree_apply, Finsupp.sum]
  rw [h_trace, h_coeff, mul_ite, mul_zero, evalAtOne_apply, mul_left_comm, mul_assoc]

/-- For `a` in the Levi subgroup, the entries `a⁻¹ s j` and `a i t` vanish off the blocks, so on
their product the conditions `τ i = τ j` and `τ t = τ s` agree. -/
lemma ite_inv_mul_eq_of_mem_levi {k : ℕ} {W O : Type} [CommRing W] [CommRing O] (τ : Fin k → ℕ)
    (ι : W →+* O) {a : GL (Fin k) W} (ha : a ∈ levi W τ) (i j s t : Fin k) :
    (if τ i = τ j then ι (a⁻¹.val s j) * ι (a.val i t) else 0) =
      if τ t = τ s then ι (a⁻¹.val s j) * ι (a.val i t) else 0 := by
  have h_inv : τ s ≠ τ j → a⁻¹.val s j = 0 := inv_mem ha s j
  have h_val : τ i ≠ τ t → a.val i t = 0 := ha i t
  grind

/-- Let `a ∈ GL_k(W)` lie in the Levi subgroup `levi W τ`. Let `G = leviGeneric O τ` be the matrix
with the variable `X (j, i)` at `(i, j)` if `τ i = τ j` and `0` otherwise. The linear substitution
of the variables (`linSubst`) by the transpose of the Kronecker product of `ι(a⁻¹)ᵀ` and `ι(a)`
takes `G` to `ι(a) * G * ι(a⁻¹)`. -/
lemma leviGeneric_map_linSubst_transpose {k : ℕ} {W O : Type} [CommRing W] [CommRing O]
    (τ : Fin k → ℕ) (ι : W →+* O) {a : GL (Fin k) W} (ha : a ∈ levi W τ) :
    (leviGeneric O τ).map (linSubst (a⁻¹.valᵀ.kroneckerMap (fun s t : W ↦ ι s * ι t) a.val)ᵀ) =
      (a.val.map ι).map C * leviGeneric O τ * (a⁻¹.val.map ι).map C := by
  ext1 i j
  calc _ = ∑ s, ∑ t, (if τ i = τ j then ι (a⁻¹.val s j) * ι (a.val i t) else 0) • X (s, t) := by
        by_cases hij : τ i = τ j <;> simp [leviGeneric, linSubst, sum_prod_type, hij]
    _ = ∑ s, ∑ t, (if τ t = τ s then ι (a⁻¹.val s j) * ι (a.val i t) else 0) • X (s, t) := by
        simp only [ite_inv_mul_eq_of_mem_levi τ ι ha i j]
    _ = _ := by
        simp [leviGeneric, Matrix.mul_apply, Finset.mul_sum, apply_ite, ← C_mul', mul_comm,
          mul_left_comm]

/-- Let `ψ♯ = dualOperator τ η d ψ` be the matrix on `(O ^ k)^{⊗ d}` whose entry at the
multi-indices `(i, j)` is `η α` times the coefficient in `ψ` of `α = ∏ l, X (j l, i l)` if
`τ (i l) = τ (j l)` for all `l`, and `0` otherwise. Assume `IsAdjointWeight η`: the linear
substitutions by a matrix and by its transpose are adjoint for the diagonal form with
`⟨x ^ α, x ^ α⟩ = η α`. Let `a ∈ GL_k(W)` have `a i j = 0` whenever `τ i ≠ τ j`. Then the
substitution `conjSubst ι a : X ↦ ι(a⁻¹) * X * ι(a)` in `ψ` conjugates `ψ♯` by
`schurMap O τ d (leviMonomialValues τ ι d a)`, which is the tensor power `ι(a)^{⊗ d}`. -/
lemma dualOperator_conjSubst {k : ℕ} {W O : Type} [CommRing W] [CommRing O] (τ : Fin k → ℕ)
    (ι : W →+* O) {d : ℕ} {η : (Fin k × Fin k →₀ ℕ) → O} (h_adj : IsAdjointWeight η)
    (a : levi W τ) (ψ : MvPolynomial (Fin k × Fin k) O) :
    dualOperator τ η d (conjSubst ι a.val ψ) =
      schurMap O τ d (leviMonomialValues τ ι d a) * dualOperator τ η d ψ *
        schurMap O τ d (leviMonomialValues τ ι d a⁻¹) := by
  let P : Matrix (Fin d → Fin k) (Fin d → Fin k) O := schurMap O τ d (leviMonomialValues τ ι d a)
  let P' : Matrix (Fin d → Fin k) (Fin d → Fin k) O := schurMap O τ d (leviMonomialValues τ ι d a⁻¹)
  -- Both sides are linear in `ψ`, so it is enough to treat a monomial.
  suffices h_lin : dualOperator τ η d ∘ₗ conjSubst ι a.val =
      mulLeftRight O (P, P') ∘ₗ dualOperator τ η d from LinearMap.congr_fun h_lin ψ
  refine linearMap_ext fun α ↦ ext_ring ?_
  let A : Matrix (Fin k × Fin k) (Fin k × Fin k) O :=
    a.val⁻¹.valᵀ.kroneckerMap (fun s t : W ↦ ι s * ι t) a.val.val
  have h_factor : (leviGeneric O τ).map (linSubst Aᵀ) =
      (a.val.val.map ι).map C * leviGeneric O τ * (a.val⁻¹.val.map ι).map C :=
    leviGeneric_map_linSubst_transpose τ ι a.prop
  have h_tensor : (leviTensor O τ d).map (linSubst Aᵀ) = P.map C * leviTensor O τ d * P'.map C :=
    calc _ = kroneckerPi fun _ : Fin d ↦ (leviGeneric O τ).map (linSubst Aᵀ) :=
          (kroneckerPi_map (fun _ : Fin d ↦ leviGeneric O τ) (linSubst Aᵀ).toRingHom).symm
      _ = _ := by
          simp only [h_factor, P, P', schurMap_leviMonomialValues, leviTensor, ← kroneckerPi_map,
            ← kroneckerPi_mul, InvMemClass.coe_inv]
  -- Adjointness moves the substitution, transposed, onto the entries of `leviTensor`.
  calc dualOperator τ η d (conjSubst ι a.val (monomial α 1))
      = (leviTensor O τ d).map ((η α • lcoeff O α) ∘ₗ (linSubst Aᵀ).toLinearMap) := by
        rw [← schurMap_apply_monomial, dualOperator_apply]
        congr 1
        ext γ
        rw [scaledCoeff_apply, conjSubst]
        exact h_adj A γ α
    _ = P * dualOperator τ η d (monomial α 1) * P' := by
        rw [dualOperator_monomial, ← map_C_mul_mul_C, ← h_tensor, Matrix.map_map,
          LinearMap.coe_comp, AlgHom.coe_toLinearMap]

/-- The product of two points of the Levi subgroup goes to the product of their images in the
Schur algebra of degree `d`, which are the tensor powers of their images under `ι`. -/
lemma schurMap_leviMonomialValues_mul {k : ℕ} {W O : Type} [CommRing W] [CommRing O]
    (τ : Fin k → ℕ) (ι : W →+* O) {d : ℕ} (a a' : levi W τ) :
    schurMap O τ d (leviMonomialValues τ ι d (a * a')) =
      schurMap O τ d (leviMonomialValues τ ι d a) *
        schurMap O τ d (leviMonomialValues τ ι d a') := by
  simp [schurMap_leviMonomialValues, ← kroneckerPi_mul]

/-- The images of `a⁻¹` and `a` in the Schur algebra of degree `d` are inverse matrices. -/
lemma schurMap_leviMonomialValues_inv_mul {k : ℕ} {W O : Type} [CommRing W] [CommRing O]
    (τ : Fin k → ℕ) (ι : W →+* O) {d : ℕ} (a : levi W τ) :
    schurMap O τ d (leviMonomialValues τ ι d a⁻¹) * schurMap O τ d (leviMonomialValues τ ι d a) =
      1 := by
  simp [← schurMap_leviMonomialValues_mul, schurMap_leviMonomialValues τ ι 1]

/-- The determinant of the generic block matrix is homogeneous of degree `k`. -/
lemma isHomogeneous_det_leviGeneric {k : ℕ} {O : Type} [CommRing O] (τ : Fin k → ℕ) :
    (leviGeneric O τ).det.IsHomogeneous k := by
  rw [det_apply']
  refine .sum _ _ _ fun π _ ↦ .C_mul ?_ _
  simpa using IsHomogeneous.prod univ (fun i : Fin k ↦ leviGeneric O τ (π i) i) 1
    fun i _ ↦ isHomogeneous_C_mul_X _ (i, π i)

/-- The points of the Levi subgroup `levi W τ` span the Schur algebra of degree `d`, if the residue
field of `W` is finite with at least `d + k` elements. A submodule `V` is `⊤` as soon as it contains
every `c` with the same `schurMap O τ d` image as some `leviMonomialValues τ ι d a`. -/
lemma eq_top_of_schurMap_eq_leviMonomialValues {k : ℕ} {W O : Type} [CommRing W] [IsLocalRing W]
    [CommRing O] (τ : Fin k → ℕ) (ι : W →+* O) {d : ℕ} (hW : d + k ≤ Nat.card (ResidueField W))
    (V : Submodule O (Monomials (Fin k × Fin k) d → O))
    (hV : ∀ {c : Monomials (Fin k × Fin k) d → O} (a : levi W τ),
      schurMap O τ d c = schurMap O τ d (leviMonomialValues τ ι d a) → c ∈ V) :
    V = ⊤ := by
  -- The block part of a matrix lies in the Levi subgroup if its determinant is a unit.
  have h_unit_one :
      IsUnit (eval (vec (1 : Matrix (Fin k) (Fin k) W)) (leviGeneric W τ).det) := by
    simp [RingHom.map_det, show (leviGeneric W τ).map (eval (vec 1)) = 1 from
      leviGeneric_map_eval τ 1]
  refine eq_top_of_eval_monomial ι d (isHomogeneous_det_leviGeneric τ) hW h_unit_one
    fun b hb ↦ ?_
  rw [RingHom.map_det, RingHom.mapMatrix_apply] at hb
  let g : GL (Fin k) W := GeneralLinearGroup.mk'' ((leviGeneric W τ).map (eval b)) hb
  have hg_levi : g ∈ levi W τ := by
    intro i j hij
    simp [g, leviGeneric, hij]
  have h_point : schurMap O τ d (fun γ ↦ aeval (ι ∘ b) (monomial γ.val (1 : O))) =
      schurMap O τ d (leviMonomialValues τ ι d ⟨g, hg_levi⟩) :=
    (schurMap_aeval τ ι b).trans (schurMap_leviMonomialValues τ ι ⟨g, hg_levi⟩).symm
  simpa [eval_monomial, aeval_monomial] using hV ⟨g, hg_levi⟩ h_point

/-- Let `levi W τ` be the group of the `a ∈ GL_k(W)` with `a i j = 0` whenever `τ i ≠ τ j`; the
matrix `schurMap O τ d (leviMonomialValues τ ι d a)` is the tensor power `ι(a)^{⊗ d}`. Let
`U₊ = largeWeightSubmodule O τ ρ t d ⊆ (O ^ k)^{⊗ d}` be generated, under the Schur algebra of this
group, by the basis tensors `j` with `∑ l, ρ (j l) > t`. If the residue field of `W` is finite with
at least `d + k` elements, the images of these tensors under the `ι(a)^{⊗ d}` already span `U₊`: it
lies in every submodule `N` that contains them. -/
lemma largeWeightSubmodule_le_of_forall_leviMonomialValues {k : ℕ} {W O : Type} [CommRing W]
    [IsLocalRing W] [CommRing O] (τ : Fin k → ℕ) (ι : W →+* O) {d : ℕ}
    (hW : d + k ≤ Nat.card (ResidueField W)) {ρ : Fin k → ℤ} {t : ℤ}
    {N : Submodule O ((Fin d → Fin k) → O)}
    (hN : ∀ (a : levi W τ) (j : Fin d → Fin k), t < ∑ l : Fin d, ρ (j l) →
      schurMap O τ d (leviMonomialValues τ ι d a) *ᵥ Pi.single j 1 ∈ N) :
    largeWeightSubmodule O τ ρ t d ≤ N := by
  refine iSup_le fun ⟨j, hj⟩ ↦ range_le_iff_comap.2 ?_
  refine eq_top_of_schurMap_eq_leviMonomialValues τ ι hW (N.comap (tensorOrbit O τ j))
    fun {c} a hc ↦ ?_
  simpa only [mem_comap, tensorOrbit_apply, hc] using hN a j hj

/-- The matrices `schurMap O τ d c`, for vectors `c` indexed by the monomials of degree `d` in the
entries of a `k × k` matrix, form the Schur algebra of the Levi subgroup whose blocks are the fibres
of `τ`. The submodule `largeWeightSubmodule O τ ρ t d` of `(O ^ k)^{⊗ d}` is spanned by the images
under these matrices of the basis tensors `j` with `∑ l, ρ (j l) > t`. If the residue field of `W`
is finite with at least `d + k` elements, each of these matrices keeps the submodule. -/
lemma schurMap_mem_largeWeightSubmodule {k : ℕ} {W O : Type} [CommRing W] [IsLocalRing W]
    [CommRing O] (τ : Fin k → ℕ) (ι : W →+* O) {d : ℕ} (hW : d + k ≤ Nat.card (ResidueField W))
    (ρ : Fin k → ℤ) (t : ℤ) (c : Monomials (Fin k × Fin k) d → O) :
    ∀ v ∈ largeWeightSubmodule O τ ρ t d,
      (schurMap O τ d c).toLin' v ∈ largeWeightSubmodule O τ ρ t d := by
  let U : Submodule O ((Fin d → Fin k) → O) := largeWeightSubmodule O τ ρ t d
  -- The vectors `c` whose image in the Schur algebra preserves `U` form a submodule.
  let S : Submodule O (Monomials (Fin k × Fin k) d → O) :=
    (U.compatibleMaps U).comap (toLin'.toLinearMap ∘ₗ schurMap O τ d)
  -- By density twice, it is enough to multiply two points of the Levi subgroup.
  have h_top : S = ⊤ := by
    refine eq_top_of_schurMap_eq_leviMonomialValues τ ι hW S fun {c'} a hc' ↦ ?_
    change U ≤ U.comap (schurMap O τ d c').toLin'
    rw [hc']
    refine largeWeightSubmodule_le_of_forall_leviMonomialValues τ ι hW fun a' j hj ↦ ?_
    rw [mem_comap, toLin'_apply, mulVec_mulVec, ← schurMap_leviMonomialValues_mul]
    exact schurMap_mulVec_single_mem_largeWeightSubmodule τ hj (leviMonomialValues τ ι d (a * a'))
  exact h_top.ge (mem_top (x := c))

/-- The action of the Schur algebra on `U₊ = largeWeightSubmodule O τ ρ t d`, the submodule of the
`d`-th tensor power of `O ^ k` that it generates from the basis tensors `j` of weight
`∑ l, ρ (j l) > t`. The vector `c` acts by the restriction of the matrix `schurMap O τ d c`; the
ring map `ι` and the bound `hW` serve only to show that this matrix keeps `U₊`. -/
noncomputable def largeWeightRep {k : ℕ} {W O : Type} [CommRing W] [IsLocalRing W] [CommRing O]
    (τ : Fin k → ℕ) (ι : W →+* O) {d : ℕ} (hW : d + k ≤ Nat.card (ResidueField W)) (ρ : Fin k → ℤ)
    (t : ℤ) :
    (Monomials (Fin k × Fin k) d → O) →ₗ[O] End O (largeWeightSubmodule O τ ρ t d) where
  toFun c := (schurMap O τ d c).toLin'.restrict (schurMap_mem_largeWeightSubmodule τ ι hW ρ t c)
  map_add' := by simp [LinearMap.ext_iff, restrict_apply]
  map_smul' := by simp [LinearMap.ext_iff, restrict_apply]

lemma coe_largeWeightRep_apply {k : ℕ} {W O : Type} [CommRing W] [IsLocalRing W] [CommRing O]
    (τ : Fin k → ℕ) (ι : W →+* O) {d : ℕ} (hW : d + k ≤ Nat.card (ResidueField W)) (ρ : Fin k → ℤ)
    (t : ℤ) (c : Monomials (Fin k × Fin k) d → O) (v : largeWeightSubmodule O τ ρ t d) :
    (largeWeightRep τ ι hW ρ t c v : (Fin d → Fin k) → O) = schurMap O τ d c *ᵥ v.val :=
  rfl

end SchurAlgebra

section Trace

/-- An endomorphism of a finite free module with values in `J` times the module has its trace in
the ideal `J`. -/
lemma trace_mem_of_forall_mem_smul_top {O : Type} [CommRing O] {M : Type*} [AddCommGroup M]
    [Module O M] [Free O M] [Module.Finite O M] {J : Ideal O} {f : End O M}
    (hf : ∀ v : M, f v ∈ J • (⊤ : Submodule O M)) : trace O M f ∈ J := by
  have h_dual (l : Dual O M) : J • (⊤ : Submodule O M) ≤ Submodule.comap l J :=
    smul_le.2 fun c hc v _ ↦ by simpa using J.mul_mem_right (l v) hc
  let b := Free.chooseBasis O M
  rw [trace_eq_matrix_trace O b]
  exact J.sum_mem fun i _ ↦ by simpa [toMatrix_apply] using h_dual (b.coord i) (hf (b i))

/-- The trace on `U₊ = largeWeightSubmodule O τ ρ t d` of the operator `ψ♯ = dualOperator τ η d ψ`,
which keeps `U₊` because it lies in the Schur algebra (`schurMap_mem_largeWeightSubmodule`). -/
noncomputable def largeWeightTrace {k : ℕ} {W O : Type} [CommRing W] [IsLocalRing W] [CommRing O]
    (τ : Fin k → ℕ) (ι : W →+* O) {d : ℕ} (hW : d + k ≤ Nat.card (ResidueField W)) (ρ : Fin k → ℤ)
    (t : ℤ) (η : (Fin k × Fin k →₀ ℕ) → O) : Dual O (MvPolynomial (Fin k × Fin k) O) :=
  trace O (largeWeightSubmodule O τ ρ t d) ∘ₗ largeWeightRep τ ι hW ρ t ∘ₗ scaledCoeff η d

/-- `largeWeightTrace` at `ψ` is the trace on `U₊ = largeWeightSubmodule O τ ρ t d` of the action
(`largeWeightRep`) of the vector `scaledCoeff η d ψ`, whose entries are the coefficients of degree
`d` of `ψ` times the weights `η`. -/
lemma largeWeightTrace_apply {k : ℕ} {W O : Type} [CommRing W] [IsLocalRing W] [CommRing O]
    (τ : Fin k → ℕ) (ι : W →+* O) {d : ℕ} (hW : d + k ≤ Nat.card (ResidueField W)) (ρ : Fin k → ℤ)
    (t : ℤ) (η : (Fin k × Fin k →₀ ℕ) → O) (ψ : MvPolynomial (Fin k × Fin k) O) :
    largeWeightTrace τ ι hW ρ t η ψ =
      trace O (largeWeightSubmodule O τ ρ t d) (largeWeightRep τ ι hW ρ t (scaledCoeff η d ψ)) :=
  rfl

/-- The part of degree `d` of the average: the trace of `ψ♯ = dualOperator τ η d ψ` on the whole
tensor power `(O ^ k)^{⊗ d}` minus its trace on `U₊ = largeWeightSubmodule O τ ρ t d`. -/
noncomputable def averagePart {k : ℕ} {W O : Type} [CommRing W] [IsLocalRing W] [CommRing O]
    (τ : Fin k → ℕ) (ι : W →+* O) {d : ℕ} (hW : d + k ≤ Nat.card (ResidueField W)) (ρ : Fin k → ℤ)
    (t : ℤ) (η : (Fin k × Fin k →₀ ℕ) → O) : Dual O (MvPolynomial (Fin k × Fin k) O) :=
  traceLinearMap (Fin d → Fin k) O O ∘ₗ dualOperator τ η d - largeWeightTrace τ ι hW ρ t η

lemma averagePart_apply {k : ℕ} {W O : Type} [CommRing W] [IsLocalRing W] [CommRing O]
    (τ : Fin k → ℕ) (ι : W →+* O) {d : ℕ} (hW : d + k ≤ Nat.card (ResidueField W)) (ρ : Fin k → ℤ)
    (t : ℤ) (η : (Fin k × Fin k →₀ ℕ) → O) (ψ : MvPolynomial (Fin k × Fin k) O) :
    averagePart τ ι hW ρ t η ψ = (dualOperator τ η d ψ).trace - largeWeightTrace τ ι hW ρ t η ψ :=
  rfl

/-- Let the residue field of `W` be finite with at least `d + k` elements, and let the substitutions
by a matrix and by its transpose be adjoint for the diagonal form `⟨x ^ α, x ^ α⟩ = η α`
(`IsAdjointWeight`). Then `averagePart` does not change under the substitution
`conjSubst ι a : X ↦ ι(a⁻¹) * X * ι(a)`, for `a ∈ GL_k(W)` with `a i j = 0` whenever `τ i ≠ τ j`. -/
lemma averagePart_conjSubst {k : ℕ} {W O : Type} [CommRing W] [IsLocalRing W] [CommRing O]
    (τ : Fin k → ℕ) (ι : W →+* O) {d : ℕ} (hW : d + k ≤ Nat.card (ResidueField W)) (ρ : Fin k → ℤ)
    (t : ℤ) (η : (Fin k × Fin k →₀ ℕ) → O) (h_adj : IsAdjointWeight η) (a : levi W τ)
    (ψ : MvPolynomial (Fin k × Fin k) O) :
    averagePart τ ι hW ρ t η (conjSubst ι a.val ψ) = averagePart τ ι hW ρ t η ψ := by
  -- The point `a` acts by an automorphism on the tensor power and on `U₊`, and both traces are
  -- invariant under conjugation by it.
  let u : End O (largeWeightSubmodule O τ ρ t d) :=
    largeWeightRep τ ι hW ρ t (leviMonomialValues τ ι d a)
  let u' : End O (largeWeightSubmodule O τ ρ t d) :=
    largeWeightRep τ ι hW ρ t (leviMonomialValues τ ι d a⁻¹)
  have h_conj : largeWeightRep τ ι hW ρ t (scaledCoeff η d (conjSubst ι a.val ψ)) =
      u * largeWeightRep τ ι hW ρ t (scaledCoeff η d ψ) * u' := by
    ext1 v
    simp [Subtype.ext_iff, u, u', coe_largeWeightRep_apply, ← dualOperator_apply,
      dualOperator_conjSubst τ ι h_adj, mul_assoc]
  have h_inv : u' * u = 1 := by
    ext1 v
    simp [Subtype.ext_iff, u, u', coe_largeWeightRep_apply, schurMap_leviMonomialValues_inv_mul]
  have h_whole : (dualOperator τ η d (conjSubst ι a.val ψ)).trace =
      (dualOperator τ η d ψ).trace := by
    rw [dualOperator_conjSubst τ ι h_adj, Matrix.trace_mul_cycle,
      schurMap_leviMonomialValues_inv_mul, one_mul]
  rw [averagePart_apply, averagePart_apply, h_whole, largeWeightTrace_apply, largeWeightTrace_apply,
    h_conj, LinearMap.trace_mul_cycle, h_inv, one_mul]

/-- If the row weight `∑ α (r, s) • ρ r` of the monomial `α` exceeds `t`, then the operator
`dualOperator τ η d (monomial α 1)` dual to `α` maps the whole `d`-th tensor power of `O ^ k` into
`largeWeightSubmodule O τ ρ t d`. -/
lemma range_dualOperator_monomial_le {k : ℕ} {O : Type} [CommRing O] (τ : Fin k → ℕ) {d : ℕ}
    (ρ : Fin k → ℤ) (t : ℤ) (η : (Fin k × Fin k →₀ ℕ) → O) {α : Fin k × Fin k →₀ ℕ}
    (hα : t < weight (fun v : Fin k × Fin k ↦ ρ v.1) α) :
    (dualOperator τ η d (monomial α 1)).toLin'.range ≤ largeWeightSubmodule O τ ρ t d := by
  rw [range_toLin', span_le]
  rintro _ ⟨j, rfl⟩
  rw [← mulVec_single_one]
  by_cases hj : t < ∑ l : Fin d, ρ (j l)
  · exact schurMap_mulVec_single_mem_largeWeightSubmodule τ hj _
  · rw [dualOperator_monomial_mulVec_single_eq_zero τ η ρ ((not_lt.1 hj).trans_lt hα).ne']
    exact zero_mem _

/-- Let `ψ♯ = dualOperator τ η d ψ` be the matrix on `U = (O ^ k)^{⊗ d}` whose entry at `(i, j)` is
`η α` times the coefficient in `ψ` of `α = ∏ l, X (j l, i l)` if `τ (i l) = τ (j l)` for all `l`,
and `0` otherwise. Let `U₊ = largeWeightSubmodule O τ ρ t d ⊆ U` be generated under the Schur
algebra by the basis tensors `j` of weight `∑ l, ρ (j l) > t`. If the coefficients in `ψ` of the
monomials `α` of row weight `∑ α (r, s) • ρ r > t` lie in the ideal `J`, then `ψ♯` maps every basis
tensor of weight `> t` into `J U₊`. -/
lemma dualOperator_mulVec_single_mem_smul {k : ℕ} {O : Type} [CommRing O] (τ : Fin k → ℕ) {d : ℕ}
    (ρ : Fin k → ℤ) (t : ℤ) (η : (Fin k × Fin k →₀ ℕ) → O) {J : Ideal O}
    {ψ : MvPolynomial (Fin k × Fin k) O}
    (hψ : ∀ α : Fin k × Fin k →₀ ℕ, t < weight (fun v : Fin k × Fin k ↦ ρ v.1) α → ψ.coeff α ∈ J)
    {j : Fin d → Fin k} (hj : t < ∑ l : Fin d, ρ (j l)) :
    dualOperator τ η d ψ *ᵥ Pi.single j 1 ∈ J • largeWeightSubmodule O τ ρ t d := by
  have h_expand : dualOperator τ η d ψ *ᵥ Pi.single j 1 =
      ∑ α ∈ ψ.support, ψ.coeff α • dualOperator τ η d (monomial α 1) *ᵥ Pi.single j 1 := by
    conv_lhs => rw [ψ.as_sum, map_sum, sum_mulVec]
    simp only [← smul_mulVec, ← map_smul, smul_eq_mul, mul_one]
  rw [h_expand]
  refine sum_mem fun α _ ↦ ?_
  by_cases hα : t < weight (fun v : Fin k × Fin k ↦ ρ v.1) α
  · exact smul_mem_smul (hψ α hα) (schurMap_mulVec_single_mem_largeWeightSubmodule τ hj _)
  · rw [dualOperator_monomial_mulVec_single_eq_zero τ η ρ ((not_lt.1 hα).trans_lt hj).ne, smul_zero]
    exact zero_mem _

/-- Let `ψ♯ = dualOperator τ η d ψ` be the matrix on `U = (O ^ k)^{⊗ d}` whose entry at `(i, j)` is
`η α` times the coefficient in `ψ` of `α = ∏ l, X (j l, i l)` if `τ (i l) = τ (j l)` for all `l`,
and `0` otherwise. Let `U₊ = largeWeightSubmodule O τ ρ t d ⊆ U` be generated under the Schur
algebra by the basis tensors `j` with `∑ l, ρ (j l) > t`. Let the residue field of `W` be finite
with at least `d + k` elements, and let the substitutions by a matrix and by its transpose be
adjoint for the diagonal form `⟨x ^ α, x ^ α⟩ = η α` (`IsAdjointWeight`). Suppose that in all
conjugates `conjSubst ι a ψ = ψ(ι(a⁻¹) * X * ι(a))`, for `a ∈ GL_k(W)` with `a i j = 0` whenever
`τ i ≠ τ j`, the monomials `α` of row weight `∑ α (r, s) • ρ r > t` have their coefficients in the
ideal `J`. Then `ψ♯` maps `U₊` into `J U₊`. -/
lemma dualOperator_mulVec_mem_smul {k : ℕ} {W O : Type} [CommRing W] [IsLocalRing W] [CommRing O]
    (τ : Fin k → ℕ) (ι : W →+* O) {d : ℕ} (hW : d + k ≤ Nat.card (ResidueField W)) (ρ : Fin k → ℤ)
    (t : ℤ) (η : (Fin k × Fin k →₀ ℕ) → O) (h_adj : IsAdjointWeight η) {J : Ideal O}
    {ψ : MvPolynomial (Fin k × Fin k) O}
    (hψ : ∀ a ∈ levi W τ, ∀ α : Fin k × Fin k →₀ ℕ,
      t < weight (fun v : Fin k × Fin k ↦ ρ v.1) α → (conjSubst ι a ψ).coeff α ∈ J) :
    ∀ v ∈ largeWeightSubmodule O τ ρ t d,
      dualOperator τ η d ψ *ᵥ v ∈ J • largeWeightSubmodule O τ ρ t d := by
  let U : Submodule O ((Fin d → Fin k) → O) := largeWeightSubmodule O τ ρ t d
  -- By density it is enough to treat the image of a basis tensor `j` of large weight under a point
  -- `a` of the Levi subgroup.
  suffices h_le : U ≤ (J • U).comap (dualOperator τ η d ψ).toLin' from fun v hv ↦ h_le hv
  refine largeWeightSubmodule_le_of_forall_leviMonomialValues τ ι hW fun a j hj ↦ ?_
  let P : Matrix (Fin d → Fin k) (Fin d → Fin k) O := schurMap O τ d (leviMonomialValues τ ι d a)
  -- `dualOperator τ η d ψ * P = P * dualOperator τ η d φ` for the conjugate `φ` of `ψ` by `a⁻¹`,
  -- and `a` keeps `J U₊`.
  have h_move : dualOperator τ η d ψ * P = P * dualOperator τ η d (conjSubst ι (a⁻¹).val ψ) := by
    rw [dualOperator_conjSubst τ ι h_adj, inv_inv, ← mul_assoc, ← mul_assoc,
      mul_eq_one_comm.1 (schurMap_leviMonomialValues_inv_mul τ ι a), one_mul]
  have h_stable : (J • U).map P.toLin' ≤ J • U := by
    rw [map_smul'']
    exact smul_mono_right J (map_le_iff_le_comap.2 (schurMap_mem_largeWeightSubmodule τ ι hW ρ t _))
  rw [mem_comap, toLin'_apply, mulVec_mulVec, h_move, ← mulVec_mulVec]
  exact h_stable (mem_map_of_mem
    (dualOperator_mulVec_single_mem_smul τ ρ t η (hψ (a⁻¹).val (a⁻¹).prop) hj))

/-- Let `O` be a valuation domain. The submodule `largeWeightSubmodule O τ ρ t d` of the `d`-th
tensor power of `O ^ k`, generated under the Schur algebra by the basis tensors `j` of weight
`∑ l, ρ (j l) > t`, is finitely generated and torsion-free, hence free. -/
lemma free_largeWeightSubmodule {k : ℕ} {O : Type} [CommRing O] (τ : Fin k → ℕ) {d : ℕ}
    [IsDomain O] [ValuationRing O] (ρ : Fin k → ℤ) (t : ℤ) :
    Free O (largeWeightSubmodule O τ ρ t d) :=
  have : Flat O (largeWeightSubmodule O τ ρ t d) :=
    Flat.flat_iff_torsion_eq_bot_of_isBezout.2 (isTorsionFree_iff_torsion_eq_bot.1 inferInstance)
  free_of_flat_of_isLocalRing

/-- Let `ψ♯ = dualOperator τ η d ψ` be the matrix on `U = (O ^ k)^{⊗ d}` whose entry at `(i, j)` is
`η α` times the coefficient in `ψ` of `α = ∏ l, X (j l, i l)` if `τ (i l) = τ (j l)` for all `l`,
and `0` otherwise. Let `U₊ ⊆ U` be generated under the Schur algebra by the basis tensors `j` with
`∑ l, ρ (j l) > t`; `averagePart` sends `ψ` to the trace of `ψ♯` on `U` minus its trace on `U₊`.
Let `O` be a valuation domain and let the residue field of `W` be finite with at least `d + k`
elements. Then `averagePart` vanishes on a monomial `α` of row weight `∑ α (r, s) • ρ r > t`,
because `α♯` has its image in `U₊`. -/
lemma averagePart_monomial_eq_zero_of_lt {k : ℕ} {W O : Type} [CommRing W] [IsLocalRing W]
    [CommRing O] (τ : Fin k → ℕ) (ι : W →+* O) {d : ℕ} (hW : d + k ≤ Nat.card (ResidueField W))
    (ρ : Fin k → ℤ) (t : ℤ) (η : (Fin k × Fin k →₀ ℕ) → O) [IsDomain O] [ValuationRing O]
    {α : Fin k × Fin k →₀ ℕ} (hα : t < weight (fun v : Fin k × Fin k ↦ ρ v.1) α) :
    averagePart τ ι hW ρ t η (monomial α 1) = 0 := by
  let U : Submodule O ((Fin d → Fin k) → O) := largeWeightSubmodule O τ ρ t d
  have : Free O U := free_largeWeightSubmodule τ ρ t
  have h_mem (v : (Fin d → Fin k) → O) : (dualOperator τ η d (monomial α 1)).toLin' v ∈ U :=
    range_dualOperator_monomial_le τ ρ t η hα (LinearMap.mem_range_self _ v)
  let f : ((Fin d → Fin k) → O) →ₗ[O] U :=
    (dualOperator τ η d (monomial α 1)).toLin'.codRestrict U h_mem
  have h_restrict : largeWeightRep τ ι hW ρ t (scaledCoeff η d (monomial α 1)) = f ∘ₗ U.subtype :=
    LinearMap.ext fun v ↦ Subtype.ext (coe_largeWeightRep_apply τ ι hW ρ t _ v)
  rw [averagePart_apply, sub_eq_zero, eq_comm]
  calc largeWeightTrace τ ι hW ρ t η (monomial α 1) = trace O U (f ∘ₗ U.subtype) := by
        rw [largeWeightTrace_apply, h_restrict]
    _ = trace O ((Fin d → Fin k) → O) (U.subtype ∘ₗ f) := trace_comp_comm' U.subtype f
    _ = (dualOperator τ η d (monomial α 1)).trace := by
        rw [subtype_comp_codRestrict, trace_toLin'_eq]

/-- Let `ψ♯` be the matrix on `U = (O ^ k)^{⊗ d}` whose entry at `(i, j)` is `η α` times the
coefficient in `ψ` of `α = ∏ l, X (j l, i l)` if `τ (i l) = τ (j l)` for all `l`, and `0` otherwise.
Let `U₊ ⊆ U` be generated under the Schur algebra by the basis tensors `j` with `∑ l, ρ (j l) > t`.
Let the residue field of `W` be finite with at least `d + k` elements; then `ψ♯` keeps `U₊`, and
`largeWeightTrace` sends `ψ` to its trace there. Let `O` be a valuation domain, and let the
substitutions by a matrix and by its transpose be adjoint for the diagonal form
`⟨x ^ α, x ^ α⟩ = η α` (`IsAdjointWeight`). Suppose that in all conjugates
`conjSubst ι a ψ = ψ(ι(a⁻¹) * X * ι(a))`, for `a ∈ GL_k(W)` with `a i j = 0` whenever `τ i ≠ τ j`,
the monomials `α` of row weight `∑ α (r, s) • ρ r > t` have their coefficients in the ideal `J`.
Then this trace lies in `J`. -/
lemma largeWeightTrace_mem {k : ℕ} {W O : Type} [CommRing W] [IsLocalRing W] [CommRing O]
    (τ : Fin k → ℕ) (ι : W →+* O) {d : ℕ} (hW : d + k ≤ Nat.card (ResidueField W)) (ρ : Fin k → ℤ)
    (t : ℤ) (η : (Fin k × Fin k →₀ ℕ) → O) [IsDomain O] [ValuationRing O]
    (h_adj : IsAdjointWeight η) {J : Ideal O} {ψ : MvPolynomial (Fin k × Fin k) O}
    (hψ : ∀ a ∈ levi W τ, ∀ α : Fin k × Fin k →₀ ℕ,
      t < weight (fun v : Fin k × Fin k ↦ ρ v.1) α → (conjSubst ι a ψ).coeff α ∈ J) :
    largeWeightTrace τ ι hW ρ t η ψ ∈ J := by
  have : Free O (largeWeightSubmodule O τ ρ t d) := free_largeWeightSubmodule τ ρ t
  refine trace_mem_of_forall_mem_smul_top fun v ↦ (mem_smul_top_iff ..).2 ?_
  exact dualOperator_mulVec_mem_smul τ ι hW ρ t η h_adj hψ v.val v.prop

end Trace

/-- The matrix `dualOperator τ η d ψ` on `(O ^ k)^{⊗ d}` has at `(i, j)` the entry `η α` times the
coefficient in `ψ` of `α = ∏ l, X (j l, i l)` if `τ (i l) = τ (j l)` for all `l`, and `0` otherwise.
If `c = multinomial α * η α` for all monomials `α` of degree at most `D` and `ψ` has degree at most
`D`, then the traces of these matrices for `d ≤ D` add up to `evalAtOne c ψ`, which is `c` times the
value of `ψ` at the matrix `1`. -/
lemma sum_trace_dualOperator {k : ℕ} {O : Type} [CommRing O] (τ : Fin k → ℕ)
    {η : (Fin k × Fin k →₀ ℕ) → O} {c : O} {D : ℕ}
    (hc : ∀ α : Fin k × Fin k →₀ ℕ, degree α ≤ D → c = α.multinomial * η α)
    {ψ : MvPolynomial (Fin k × Fin k) O} (h_deg : ψ.totalDegree ≤ D) :
    ∑ d : Fin (D + 1), (dualOperator τ η d ψ).trace = evalAtOne c ψ := by
  have h_monomial (α : Fin k × Fin k →₀ ℕ) (hα : degree α ≤ D) : ∑ d : Fin (D + 1),
      (dualOperator τ η d (monomial α 1)).trace = evalAtOne c (monomial α 1) := by
    rw [Fin.sum_univ_eq_sum_range fun d ↦ (dualOperator τ η d (monomial α 1)).trace]
    simp [trace_dualOperator_monomial, hc α hα, hα]
  have h_expand : ψ = ∑ α ∈ ψ.support, ψ.coeff α • monomial α 1 := by simp [smul_monomial]
  rw [h_expand]
  simp only [map_sum, map_smul, trace_sum, trace_smul, sum_comm (s := univ), ← Finset.smul_sum]
  exact sum_congr rfl fun α hα ↦ by rw [h_monomial α ((le_totalDegree hα).trans h_deg)]

/-- Let `O` be a valuation domain of characteristic `0` in which the prime `p` is not a unit, let
`ι : W → O` be a ring map from a local ring whose residue field is finite with at least `D + k`
elements, and let `D < p ^ f`. The matrices `a ∈ GL_k(W)` with `a i j = 0` whenever `τ i ≠ τ j` act
on polynomials in the entries of a `k × k` matrix `X` by the conjugation `X ↦ ι(a⁻¹) * X * ι(a)`.
For all weights `ρ` of the indices and every threshold `t` there is a linear form `I` on these
polynomials that is invariant under conjugation, vanishes on the monomials `α` of row weight
`∑ α (i, j) • ρ i > t`, and agrees modulo an ideal `J` with `p ^ (k² f) ψ(1)` on every `ψ` of degree
at most `D` whose conjugates have the coefficients of such monomials in `J` (`IsAverage`). -/
theorem exists_isAverage {k : ℕ} {W O : Type} [CommRing W] [IsLocalRing W] [CommRing O]
    (τ : Fin k → ℕ) (ι : W →+* O) [IsDomain O] [CharZero O] [ValuationRing O] {p : ℕ}
    (hp_prime : p.Prime) (hp : ¬IsUnit (p : O)) (f : ℕ) {D : ℕ} (hD : D < p ^ f)
    (hW : D + k ≤ Nat.card (ResidueField W)) (ρ : Fin k → ℤ) (t : ℤ) :
    ∃ I : Dual O (MvPolynomial (Fin k × Fin k) O),
      IsAverage τ ι ρ t ((p : O) ^ (k ^ 2 * f)) D I := by
  -- `I` is the sum of the parts of degree `d ≤ D`, for the weights
  -- `η γ = p ^ (k² f) / multinomial γ`.
  obtain ⟨η, hη_mul, hη_adj : IsAdjointWeight η⟩ :=
    exists_isAdjointWeight (Fin k × Fin k) hp_prime hp f
  have h_const (α : Fin k × Fin k →₀ ℕ) (hα : degree α ≤ D) :
      (p : O) ^ (k ^ 2 * f) = α.multinomial * η α := by
    simpa [sq] using hη_mul α (hα.trans_lt hD)
  have h_card (d : Fin (D + 1)) : d + k ≤ Nat.card (ResidueField W) := by lia
  refine ⟨∑ d : Fin (D + 1), averagePart τ ι (h_card d) ρ t η, fun a ha ψ ↦ ?_, fun α hα ↦ ?_,
    fun J ψ h_deg hψ ↦ ?_⟩
  · simp [averagePart_conjSubst τ ι _ ρ t η hη_adj ⟨a, ha⟩]
  · simp [averagePart_monomial_eq_zero_of_lt τ ι _ ρ t η hα]
  · have h_diff : (∑ d : Fin (D + 1), averagePart τ ι (h_card d) ρ t η) ψ -
        evalAtOne ((p : O) ^ (k ^ 2 * f)) ψ =
          -∑ d : Fin (D + 1), largeWeightTrace τ ι (h_card d) ρ t η ψ := by
      simp [averagePart_apply, sum_trace_dualOperator τ h_const h_deg]
    rw [h_diff]
    exact neg_mem (sum_mem fun d _ ↦ largeWeightTrace_mem τ ι (h_card d) ρ t η hη_adj hψ)

end New.Average