Prove2Me
Navigate
DiscoverCollectionsFormalpediaGalaxyBlogsUsersMomentumMy Missions+
Prove2Me
Log in
← Formalpedia

Curve-duality library (Poincaré duality on curves over finite fields), part 50 of 71

Definition
RPLib_S4_CDPack50

by Nickrobbins95 · Nov 18, 2026 · Mathlib 0df444a (Lean v4.33.1)

algebraic-geometryfinite-fieldsnumber-theory

Part 50 of 71 of the curve-duality library: the following library modules, in dependency order.

  • Def_RP_ThetaCube_Pull: S4-ThetaCube, T7a: the ideal sheaf of a pulled-back effective divisor
  • Def_RP_IntersectB_Pen4: S4-IntersectB, O9 part 4: the pencil function f / (f - 1) and its fibres over 0 and 1
  • Def_RP_IntersectB_Pen5: S4-IntersectB, file Pen5: the two fibres of the pencil have the same length (L34, B4)
  • Def_RP_IntersectB_Pen6: S4-IntersectB, file Pen6: transport along isomorphisms (L34, B4)
  • Def_RP_IntersectB_Pen7: S4-IntersectB, file Pen7: generic translates of a small configuration do not meet (L34, B4)
  • Def_RP_IntersectB_Pen8: S4-IntersectB, file Pen8: the pencil for generic translates (L34, B4)
  • Def_RP_IntersectB_Pen9: S4-IntersectB, file Pen9: the intersection form respects linear equivalence (L34, B4)

Formalization note. Library package of a formalization of Poincaré duality for constant coefficients on an affine curve over a finite field (the cup pairing Hc1(Uˉ,Λ)×H1(Uˉ,σ)→ΛH^1_c(\bar U,\Lambda)\times H^1(\bar U,\sigma)\to\LambdaHc1​(Uˉ,Λ)×H1(Uˉ,σ)→Λ of the geometric fundamental group is perfect). The modules are copied verbatim (import lines removed), each inside its own section ... end, in dependency order. They contain definitions together with proved lemmas (no sorry; where divisibility facts about Picard groups are used they are explicit hypotheses), so that later solution files can import them.

Definition code
import Mathlib
import Definitions.Def_RPLib_S4_CDPack38
import Definitions.Def_RPLib_S4_CDPack48
import Definitions.Def_RPLib_S4_CDPack49

/-!
# Curve-duality library package, part 50 of 71

Library modules of the formalization of Poincaré duality for constant coefficients on an affine curve over a
finite field (`RamanujanPetersson.CupDuality.constDuality_S3_perfect`). Each module below is copied verbatim
(import lines removed) inside its own `section` ... `end`:

* `Def_RP_ThetaCube_Pull`: S4-ThetaCube, T7a: the ideal sheaf of a pulled-back effective divisor
* `Def_RP_IntersectB_Pen4`: S4-IntersectB, O9 part 4: the pencil function `f / (f - 1)` and its fibres over `0` and `1`
* `Def_RP_IntersectB_Pen5`: S4-IntersectB, file Pen5: the two fibres of the pencil have the same length (L34, B4)
* `Def_RP_IntersectB_Pen6`: S4-IntersectB, file Pen6: transport along isomorphisms (L34, B4)
* `Def_RP_IntersectB_Pen7`: S4-IntersectB, file Pen7: generic translates of a small configuration do not meet (L34, B4)
* `Def_RP_IntersectB_Pen8`: S4-IntersectB, file Pen8: the pencil for generic translates (L34, B4)
* `Def_RP_IntersectB_Pen9`: S4-IntersectB, file Pen9: the intersection form respects linear equivalence (L34, B4)
-/

set_option autoImplicit false

-- ===== S4.Def_RP_ThetaCube_Pull =====
section

/-!
# S4-ThetaCube, T7a: the ideal sheaf of a pulled-back effective divisor

For `f : C ⟶ Y` between integral locally Noetherian schemes with factorial stalks, `C` quasi-compact and
`f` quasi-compact, and an effective Weil divisor `D` of finite support on `Y` whose support avoids
`f (η_C)`, the ideal sheaf of the pulled-back divisor is the pulled-back ideal sheaf:
`effI (cpull f D) = (effI D).comap f` (`effI_cpull`).
* `gff_res`: the function-field image of a section is unchanged by restriction.
* `exists_span_eq`: two sections with the same orders along the codimension-one points of an open set
  generate the same ideal on an affine neighbourhood of any point.
* `isLocEq_of_chart`, `fpull_gff`: a chart generator of `effI D` is a local equation of `D`, and its pull-back.
* `exists_span_cpull`: near every point of `f⁻¹ U`, `effI (cpull f D)` is generated by the pull-back of a
  chart generator of `effI D` on `U`.
-/

set_option autoImplicit false

namespace RamanujanPetersson.ThetaCube

open AlgebraicGeometry CategoryTheory Order Topology RamanujanPetersson.JacDivisors
  RamanujanPetersson.IntersectB RamanujanPetersson.ThetaSquare

universe u

section Span

variable {X : Scheme.{u}} [IsIntegral X]

lemma gff_res {U V : X.Opens} (h : V ≤ U) [Nonempty V] [Nonempty U] (a : Γ(X, U)) :
    X.germToFunctionField V (X.presheaf.map (homOfLE h).op a) = X.germToFunctionField U a := by
  obtain ⟨⟨x, hx⟩⟩ := ‹Nonempty V›
  rw [← Scheme.algebraMap_germ_eq_germToFunctionField X hx,
    ← Scheme.algebraMap_germ_eq_germToFunctionField X (h hx), TopCat.Presheaf.germ_res_apply]

variable [IsLocallyNoetherian X]

/-- Two sections with the same orders along the codimension-one points of `W` generate the same
ideal on an affine neighbourhood of any point of `W`. -/
lemma exists_span_eq {W : X.Opens} [Nonempty W] {a b : Γ(X, W)}
    (ha : X.germToFunctionField W a ≠ 0) (hb : X.germToFunctionField W b ≠ 0)
    (hab : ∀ w ∈ W, coheight w = 1 →
      Scheme.ord (X.germToFunctionField W a) w = Scheme.ord (X.germToFunctionField W b) w)
    (x : X) [UniqueFactorizationMonoid (X.presheaf.stalk x)] (hx : x ∈ W) :
    ∃ W' : X.affineOpens, ∃ h : (W' : X.Opens) ≤ W, x ∈ (W' : X.Opens) ∧
      Ideal.span {X.presheaf.map (homOfLE h).op a} = Ideal.span {X.presheaf.map (homOfLE h).op b} := by
  obtain ⟨r, hr, hrA⟩ := exists_isUnit_of_ord_eq_zero x (div_ne_zero ha hb) fun z hz h1 =>
    ord_eq_of_div_eq ha hb (hab z (hz.mem_open W.isOpen hx) h1)
  obtain ⟨V₁, hx₁, s, hs⟩ := X.presheaf.exists_germ_eq r
  obtain ⟨V₂, hx₂, t, ht⟩ := X.presheaf.exists_germ_eq (↑hr.unit⁻¹ : X.presheaf.stalk x)
  obtain ⟨_, ⟨V, hV, rfl⟩, hxV, hVle⟩ := X.isBasis_affineOpens.exists_subset_of_mem_open
    (show x ∈ ((W ⊓ V₁ ⊓ V₂ : X.Opens) : Set X) from ⟨⟨hx, hx₁⟩, hx₂⟩) (W ⊓ V₁ ⊓ V₂).isOpen
  have h0 : V ≤ W := fun y hy => (hVle hy).1.1
  have h1 : V ≤ V₁ := fun y hy => (hVle hy).1.2
  have h2 : V ≤ V₂ := fun y hy => (hVle hy).2
  have : Nonempty V := ⟨⟨x, hxV⟩⟩
  have : Nonempty V₁ := ⟨⟨x, hx₁⟩⟩
  have : Nonempty V₂ := ⟨⟨x, hx₂⟩⟩
  have es : X.germToFunctionField V (X.presheaf.map (homOfLE h1).op s) = algebraMap _ _ r := by
    rw [gff_res h1 s, ← Scheme.algebraMap_germ_eq_germToFunctionField X hx₁, hs]
  have et : X.germToFunctionField V (X.presheaf.map (homOfLE h2).op t) =
      algebraMap _ _ (↑hr.unit⁻¹ : X.presheaf.stalk x) := by
    rw [gff_res h2 t, ← Scheme.algebraMap_germ_eq_germToFunctionField X hx₂, ht]
  have hu : IsUnit (X.presheaf.map (homOfLE h1).op s) := by
    refine isUnit_iff_exists_inv.mpr ⟨X.presheaf.map (homOfLE h2).op t,
      X.germToFunctionField_injective V ?_⟩
    rw [map_mul, map_one, es, et, ← map_mul, hr.mul_val_inv, map_one]
  have hab' : X.presheaf.map (homOfLE h0).op a =
      X.presheaf.map (homOfLE h1).op s * X.presheaf.map (homOfLE h0).op b := by
    refine X.germToFunctionField_injective V ?_
    rw [map_mul, es, hrA, gff_res h0 a, gff_res h0 b, div_mul_cancel₀ _ hb]
  refine ⟨⟨V, hV⟩, h0, hxV, ?_⟩
  show Ideal.span {X.presheaf.map (homOfLE h0).op a} = Ideal.span {X.presheaf.map (homOfLE h0).op b}
  rw [hab', Ideal.span_singleton_mul_left_unit hu]

/-- A section whose orders on `U` are those of an effective Weil divisor `D` is a local equation of
`D` at every point of `U`. -/
lemma isLocEq_of_chart {D : AlgebraicCycle X ℤ} (hD : D ∈ weilDivisors X) (hD0 : ∀ z, 0 ≤ D z)
    {U : X.Opens} [Nonempty U] {u : Γ(X, U)} (hu : X.germToFunctionField U u ≠ 0)
    (ho : ∀ w ∈ U, coheight w = 1 → Scheme.ord (X.germToFunctionField U u) w = (D w).toNat)
    {y : X} (hy : y ∈ U) : IsLocEq D y (X.germToFunctionField U u) := by
  refine ⟨hu, U, U.isOpen, hy, fun w hw => ?_⟩
  rw [div_apply]
  by_cases h1 : coheight w = 1
  · rw [ho w hw h1, Int.toNat_of_nonneg (hD0 w)]
  · rw [Scheme.ord_eq_zero_of_coheight_neq_one h1]
    by_contra h
    exact h1 (hD w h)

end Span

/-- Restriction commutes with the ring maps of a morphism. -/
lemma map_app_apply {X Y : Scheme.{u}} (g : X ⟶ Y) {U W : Y.Opens} (e : W ≤ U)
    (h : g ⁻¹ᵁ W ≤ g ⁻¹ᵁ U) (s : Γ(Y, U)) :
    X.presheaf.map (homOfLE h).op (g.app U s) = g.app W (Y.presheaf.map (homOfLE e).op s) := by
  rw [← CommRingCat.comp_apply, ← CommRingCat.comp_apply, g.naturality]
  rfl

section Pull

variable {C Y : Scheme.{u}} [IsIntegral C] [IsLocallyNoetherian C] [IsIntegral Y] [IsLocallyNoetherian Y]
  [∀ y : Y, UniqueFactorizationMonoid (Y.presheaf.stalk y)] (f : C ⟶ Y)

omit [IsLocallyNoetherian C] [IsLocallyNoetherian Y] [∀ y : Y, UniqueFactorizationMonoid (Y.presheaf.stalk y)] in
lemma fpull_gff {U : Y.Opens} {W : C.Opens} (e : W ≤ f ⁻¹ᵁ U) [Nonempty U] [Nonempty W]
    (u : Γ(Y, U)) :
    fpull f (Y.germToFunctionField U u) = C.germToFunctionField W (f.appLE U W e u) := by
  obtain ⟨⟨x, hx⟩⟩ := ‹Nonempty W›
  rw [← Scheme.algebraMap_germ_eq_germToFunctionField Y (show f x ∈ U from e hx), fpull_algebraMap_at,
    Scheme.Hom.germ_stalkMap_apply, ← Scheme.algebraMap_germ_eq_germToFunctionField C hx]
  show _ = algebraMap _ _ (C.presheaf.germ W x hx ((f.app U ≫ C.presheaf.map (homOfLE e).op) u))
  rw [CommRingCat.comp_apply, TopCat.Presheaf.germ_res_apply]

variable [∀ x : C, UniqueFactorizationMonoid (C.presheaf.stalk x)] [CompactSpace C]

/-- Near every point of `f⁻¹ U`, `effI (cpull f D)` is generated by the pull-back of a chart
generator of `effI D` on `U`. -/
lemma exists_span_cpull {D : AlgebraicCycle Y ℤ} (hD : D ∈ weilDivisors Y) (hD0 : ∀ z, 0 ≤ D z)
    (hA : Avoid f D) {U : Y.Opens} [Nonempty U] {u : Γ(Y, U)} (hu : Y.germToFunctionField U u ≠ 0)
    (ho : ∀ w ∈ U, coheight w = 1 → Scheme.ord (Y.germToFunctionField U u) w = (D w).toNat)
    (x : C) (hx : f x ∈ U) :
    ∃ W : C.affineOpens, ∃ e : (W : C.Opens) ≤ f ⁻¹ᵁ U, x ∈ (W : C.Opens) ∧
      (effI (cpull f D)).ideal W = Ideal.span {f.appLE U W e u} := by
  have hloc := fun y (hy : y ∈ U) => isLocEq_of_chart hD hD0 hu ho hy
  have hE0 : ∀ z, 0 ≤ cpull f D z := fun z => cpull_nonneg f hD hA z fun w _ _ => hD0 w
  have hEW : cpull f D ∈ weilDivisors C := fun z hz => by
    by_contra h1
    exact hz (by rw [cpull_apply f hD hA, Scheme.ord_eq_zero_of_coheight_neq_one h1])
  obtain ⟨W₁, hxW₁, v, hv, hKv, hov⟩ :=
    effGen (fun z => inferInstance) hEW (support_finite_of_compact (cpull f D)) x
  obtain ⟨_, ⟨W₀, hW₀, rfl⟩, hxW₀, hW₀le⟩ := C.isBasis_affineOpens.exists_subset_of_mem_open
    (show x ∈ ((W₁.1 ⊓ f ⁻¹ᵁ U : C.Opens) : Set C) from ⟨hxW₁, hx⟩) (W₁.1 ⊓ f ⁻¹ᵁ U).isOpen
  have h1 : W₀ ≤ W₁.1 := fun y hy => (hW₀le hy).1
  have h2 : W₀ ≤ f ⁻¹ᵁ U := fun y hy => (hW₀le hy).2
  have : Nonempty W₀ := ⟨⟨x, hxW₀⟩⟩
  have : Nonempty W₁.1 := ⟨⟨x, hxW₁⟩⟩
  have hga : C.germToFunctionField W₀ (f.appLE U W₀ h2 u) = fpull f (Y.germToFunctionField U u) :=
    (fpull_gff f h2 u).symm
  have hgb : C.germToFunctionField W₀ (C.presheaf.map (homOfLE h1).op v) =
      C.germToFunctionField W₁.1 v := gff_res h1 v
  have hfne : fpull f (Y.germToFunctionField U u) ≠ 0 := by
    obtain ⟨w, hw, hw'⟩ := exists_unit_of_isLocEq f hA (hloc (f x) hx)
    rw [← hw']
    exact fpull_ne_zero f hw
  have hvne : C.germToFunctionField W₁.1 v ≠ 0 := germToFunctionField_ne_zero hv
  obtain ⟨W, hW, hxW, hspan⟩ := exists_span_eq (W := W₀) (a := f.appLE U W₀ h2 u)
    (b := C.presheaf.map (homOfLE h1).op v) (by rw [hga]; exact hfne) (by rw [hgb]; exact hvne)
    (fun w hw hw1 => by
      rw [hga, hgb, ← cpull_eq_of f hD hA (hloc (f w) (h2 hw)),
        ← Scheme.algebraMap_germ_eq_germToFunctionField C hxW₁ v, hov w (h1 hw) hw1,
        Int.toNat_of_nonneg (hE0 w)]) x hxW₀
  have hWW₁ : W ≤ W₁ := Subtype.coe_le_coe.mp (hW.trans h1)
  refine ⟨W, hW.trans h2, hxW, ?_⟩
  rw [ideal_res_span (effI (cpull f D)) hWW₁ hKv]
  have e1 : C.presheaf.map (homOfLE hW).op (f.appLE U W₀ h2 u) = f.appLE U W (hW.trans h2) u := by
    rw [← CommRingCat.comp_apply, Scheme.Hom.appLE_map]
  have e2 : C.presheaf.map (homOfLE hW).op (C.presheaf.map (homOfLE h1).op v) =
      C.presheaf.map (homOfLE (hW.trans h1)).op v := by
    rw [← CommRingCat.comp_apply, ← Functor.map_comp]
    rfl
  rw [← e1, hspan, e2]
  rfl

/-- **T7a**: the ideal sheaf of the pull-back of an effective divisor is the pull-back of its ideal
sheaf. -/
theorem effI_cpull [QuasiCompact f] {D : AlgebraicCycle Y ℤ} (hD : D ∈ weilDivisors Y)
    (hD0 : ∀ z, 0 ≤ D z) (hfin : (Function.support D).Finite) (hA : Avoid f D) :
    effI (cpull f D) = (effI D).comap f := by
  have hufd : ∀ y : Y, UniqueFactorizationMonoid (Y.presheaf.stalk y) := fun y => inferInstance
  choose U hyU u hu hIu hou using fun y : Y => effGen hufd hD hfin y
  have hne : ∀ y, Nonempty ((U y : Y.Opens)) := fun y => ⟨⟨y, hyU y⟩⟩
  have hgu : ∀ y, Y.germToFunctionField (U y) (u y) ≠ 0 := fun y => germToFunctionField_ne_zero (hu y)
  have ho : ∀ y, ∀ w ∈ (U y : Y.Opens), coheight w = 1 →
      Scheme.ord (Y.germToFunctionField (U y) (u y)) w = (D w).toNat := fun y w hw hw1 => by
    rw [← Scheme.algebraMap_germ_eq_germToFunctionField Y (hyU y)]
    exact hou y w hw hw1
  apply le_antisymm
  · choose W e hxW hW using fun x : C =>
      exists_span_cpull f hD hD0 hA (hgu (f x)) (ho (f x)) x (hyU (f x))
    refine Scheme.IdealSheafData.le_of_iSup_eq_top W
      (eq_top_iff.mpr fun x _ => TopologicalSpace.Opens.mem_iSup.mpr ⟨x, hxW x⟩) fun x => ?_
    rw [hW x, Ideal.span_le, Set.singleton_subset_iff]
    exact appLE_mem_comap _ f (U (f x)) (W x) (e x) (by rw [hIu]; exact Ideal.subset_span rfl)
  · refine (Scheme.IdealSheafData.map_gc f _ _).mpr ?_
    refine Scheme.IdealSheafData.le_of_iSup_eq_top U
      (eq_top_iff.mpr fun y _ => TopologicalSpace.Opens.mem_iSup.mpr ⟨y, hyU y⟩) fun y => ?_
    rw [hIu y, Ideal.span_le, Set.singleton_subset_iff]
    show u y ∈ ((effI (cpull f D)).subschemeι ≫ f).ker.ideal (U y)
    rw [Scheme.Hom.ker_apply, RingHom.mem_ker]
    change (effI (cpull f D)).subschemeι.app (f ⁻¹ᵁ (U y : Y.Opens)) (f.app (U y) (u y)) = 0
    refine (effI (cpull f D)).subscheme.IsSheaf.section_ext fun z hz => ?_
    obtain ⟨W, e, hxW, hW⟩ := exists_span_cpull f hD hD0 hA (hgu y) (ho y)
      ((effI (cpull f D)).subschemeι z) hz
    have hmem : f.appLE (U y) W e (u y) ∈ (effI (cpull f D)).ideal W := by
      rw [hW]
      exact Ideal.subset_span rfl
    rw [← (effI (cpull f D)).ker_subschemeι, Scheme.Hom.ker_apply, RingHom.mem_ker] at hmem
    refine ⟨(effI (cpull f D)).subschemeι ⁻¹ᵁ W,
      ((TopologicalSpace.Opens.map (effI (cpull f D)).subschemeι.base).map (homOfLE e)).le, hxW, ?_⟩
    rw [map_zero]
    exact (map_app_apply _ e _ _).trans hmem

end Pull

end RamanujanPetersson.ThetaCube

end

-- ===== S4.Def_RP_IntersectB_Pen4 =====
section

/-!
# S4-IntersectB, O9 part 4: the pencil function `f / (f - 1)` and its fibres over `0` and `1`

* `exists_regOpen`: the regular locus of a rational function on an integral scheme, with the
  section it defines there (sheaf gluing).
* `hid_of_res`: an identity of sections on `O ⊓ W` gives the identity on `C ∩ O` used by
  `isPullback_fibre`.
* `appLE_eq_of_local`: a section pulled back along a morphism is computed stalkwise.
* `pencil_chart`: near every point, local equations `u`, `v` of the zeros and poles of `f` with
  `(u - v) (f / (f - 1) - n) = h` for the generator `h` of the fibre over `n ∈ {0, 1}`.
* `isPullback_pencil`: the fibres over `0` and `1` of the graph family of `f / (f - 1)` on `C`
  are the subschemes `effI (div f) ⊔ C` and `effI (-div f) ⊔ C`, provided `C` misses the common
  points of the zero and pole divisors.
-/

set_option autoImplicit false

universe u

open CategoryTheory AlgebraicGeometry Topology IsLocalRing

namespace RamanujanPetersson.IntersectB

open RamanujanPetersson.JacDivisors

lemma isUnit_sub_of_nonunit {R : Type*} [CommRing R] [IsLocalRing R] {a b : R} (ha : ¬IsUnit a)
    (hb : IsUnit b) : IsUnit (a - b) := by
  by_contra h
  have := (maximalIdeal R).sub_mem ((mem_maximalIdeal a).mpr ha) ((mem_maximalIdeal _).mpr h)
  rw [sub_sub_cancel] at this
  exact (mem_maximalIdeal b).mp this hb

lemma pencil_K {K : Type*} [Field K] {f U V H : K} (hf1 : f ≠ 1) (n : K) (huv : U = f * V)
    (hh : H = U - n * (U - V)) : (U - V) * (f / (f - 1) - n) = H := by
  have : f - 1 ≠ 0 := sub_ne_zero.mpr hf1
  rw [hh, huv]
  field_simp

lemma appLE_res {X Y : Scheme.{u}} (f : X ⟶ Y) {U U' : Y.Opens} (hU : U' ≤ U) {V : X.Opens}
    (e : V ≤ f ⁻¹ᵁ U') (s : Γ(Y, U)) :
    f.appLE U' V e (Y.presheaf.map (homOfLE hU).op s) =
      f.appLE U V (e.trans ((TopologicalSpace.Opens.map f.base).map (homOfLE hU)).le) s := by
  rw [← CommRingCat.comp_apply, Scheme.Hom.map_appLE]

lemma res_appLE {X Y : Scheme.{u}} (f : X ⟶ Y) {U : Y.Opens} {V V' : X.Opens} (e : V ≤ f ⁻¹ᵁ U)
    (hV : V' ≤ V) (s : Γ(Y, U)) :
    X.presheaf.map (homOfLE hV).op (f.appLE U V e s) = f.appLE U V' (hV.trans e) s := by
  rw [← CommRingCat.comp_apply, Scheme.Hom.appLE_map]

lemma res_appTop {X Y : Scheme.{u}} (f : X ⟶ Y) {V : X.Opens} (s : Γ(Y, ⊤)) :
    X.presheaf.map (homOfLE (le_top : V ≤ ⊤)).op (f.appTop s) = f.appLE ⊤ V le_top s := rfl

section Reg

variable {X : Scheme.{u}} [IsIntegral X]

/-- The regular locus `O` of a rational function `r` on an integral scheme, with the section of
`𝒪(O)` that `r` defines. -/
theorem exists_regOpen (r : X.functionField) :
    ∃ O : X.Opens, ∃ g : Γ(X, O), (∀ x (hx : x ∈ O),
      algebraMap (X.presheaf.stalk x) X.functionField (X.presheaf.germ O x hx g) = r) ∧
      ∀ x : X, r ∈ Set.range (algebraMap (X.presheaf.stalk x) X.functionField) → x ∈ O := by
  let ι := {p : Σ U : X.Opens, Γ(X, U) // ∀ x (hx : x ∈ p.1),
    algebraMap (X.presheaf.stalk x) X.functionField (X.presheaf.germ p.1 x hx p.2) = r}
  let U : ι → X.Opens := fun i => i.1.1
  let sf : ∀ i : ι, Γ(X, U i) := fun i => i.1.2
  have hc : TopCat.Presheaf.IsCompatible X.sheaf.1 U sf := by
    intro i j
    refine TopCat.Presheaf.section_ext X.sheaf _ _ _ fun x hx => ?_
    show X.presheaf.germ (U i ⊓ U j) x hx
        (X.presheaf.map (TopologicalSpace.Opens.infLELeft (U i) (U j)).op (sf i)) =
      X.presheaf.germ (U i ⊓ U j) x hx
        (X.presheaf.map (TopologicalSpace.Opens.infLERight (U i) (U j)).op (sf j))
    rw [TopCat.Presheaf.germ_res_apply, TopCat.Presheaf.germ_res_apply]
    exact IsFractionRing.injective (X.presheaf.stalk x) X.functionField
      ((i.2 x hx.1).trans (j.2 x hx.2).symm)
  obtain ⟨s, hs, -⟩ := X.sheaf.existsUnique_gluing U sf hc
  refine ⟨iSup U, s, fun x hx => ?_, fun x ⟨y, hy⟩ => ?_⟩
  · obtain ⟨i, hi⟩ := TopologicalSpace.Opens.mem_iSup.mp hx
    have e := X.presheaf.germ_res_apply (TopologicalSpace.Opens.leSupr U i) x hi s
    rw [show X.presheaf.map (TopologicalSpace.Opens.leSupr U i).op s = sf i from hs i] at e
    rw [← e]
    exact i.2 x hi
  · obtain ⟨W, hxW, t, rfl⟩ := X.presheaf.exists_germ_eq (x := x) y
    haveI : Nonempty W := ⟨⟨x, hxW⟩⟩
    rw [Scheme.algebraMap_germ_eq_germToFunctionField] at hy
    let i : ι := ⟨⟨W, t⟩, fun x' hx' => by
      haveI : Nonempty W := ⟨⟨x', hx'⟩⟩
      rw [Scheme.algebraMap_germ_eq_germToFunctionField]; exact hy⟩
    exact TopologicalSpace.Opens.mem_iSup.mpr ⟨i, hxW⟩

lemma mem_range_generic (r : X.functionField) (x : X) (hx : x = genericPoint X) :
    r ∈ Set.range (algebraMap (X.presheaf.stalk x) X.functionField) := by
  subst hx
  obtain ⟨W, hW, t, rfl⟩ := X.presheaf.exists_germ_eq (x := genericPoint X) r
  haveI : Nonempty W := ⟨⟨_, hW⟩⟩
  exact ⟨X.presheaf.germ W _ hW t, Scheme.algebraMap_germ_eq_germToFunctionField X hW t⟩

lemma res_eq_of_germ {U : X.Opens} (x : X) (hx : x ∈ U) {s t : Γ(X, U)}
    (h : algebraMap (X.presheaf.stalk x) X.functionField (X.presheaf.germ U x hx s) =
      algebraMap (X.presheaf.stalk x) X.functionField (X.presheaf.germ U x hx t)) : s = t :=
  germ_injective_of_isIntegral X x hx (IsFractionRing.injective _ _ h)

end Reg

section Hid

variable {X S : Scheme.{u}} (π : X ⟶ S) (C : X.IdealSheafData) (O : X.Opens)

lemma ιCO_preimage_le (W : X.Opens) : ιCO C O ⁻¹ᵁ W ≤ ιCO C O ⁻¹ᵁ (O ⊓ W) := fun y hy =>
  ⟨le_ιCO_preimage C O (show y ∈ (⊤ : (COo C O).toScheme.Opens) from trivial), hy⟩

/-- An identity of sections on `O ⊓ W` gives the identity on `C ∩ O ∩ W` of `isPullback_fibre`. -/
lemma hid_of_res (g : Γ(X, O)) (l : Γ(S, ⊤)) (W : X.Opens) (a h : Γ(X, W))
    (hΓ : X.presheaf.map (homOfLE (inf_le_right : O ⊓ W ≤ W)).op a *
      (X.presheaf.map (homOfLE (inf_le_left : O ⊓ W ≤ O)).op g -
        X.presheaf.map (homOfLE (le_top : O ⊓ W ≤ ⊤)).op (π.appTop l)) =
      X.presheaf.map (homOfLE (inf_le_right : O ⊓ W ≤ W)).op h) :
    (ιCO C O).app W a * (COo C O).toScheme.presheaf.map (homOfLE le_top).op
        (gCO C O g - (ιCO C O ≫ π).appTop l) = (ιCO C O).app W h := by
  have e := congrArg ((ιCO C O).appLE (O ⊓ W) _ (ιCO_preimage_le C O W)) hΓ
  simp only [map_mul, map_sub, appLE_res] at e
  rw [map_sub, gCO, res_appLE, Scheme.Hom.comp_appTop, CommRingCat.comp_apply, res_appTop,
    Scheme.Hom.app_eq_appLE]
  exact e

/-- A section pulled back along `ι` is computed stalkwise: it suffices that near every point of
the image, `a (s - c) = h` with `a` a unit at the point and `h` killed by `ι`. -/
lemma appLE_eq_of_local {Y : Scheme.{u}} (ι : Y ⟶ X) (U : X.Opens) (e : ⊤ ≤ ι ⁻¹ᵁ U)
    (s : Γ(X, U)) (c : Γ(X, ⊤))
    (H : ∀ y : Y, ∃ W : X.Opens, ∃ hW : ι y ∈ W, ∃ a h : Γ(X, W),
      IsUnit (X.presheaf.germ W (ι y) hW a) ∧ ι.app W h = 0 ∧
      X.presheaf.germ W (ι y) hW a * (X.presheaf.germ U (ι y)
        (e (show y ∈ (⊤ : Y.Opens) from trivial)) s - X.presheaf.germ ⊤ (ι y) trivial c) =
        X.presheaf.germ W (ι y) hW h) :
    ι.appLE U ⊤ e s = ι.appTop c := by
  refine TopCat.Presheaf.section_ext Y.sheaf _ _ _ fun y _ => ?_
  obtain ⟨W, hW, a, h, ha, h0, hid⟩ := H y
  have hu : IsUnit (ι.stalkMap y (X.presheaf.germ W (ι y) hW a)) := ha.map _
  have := congrArg (ι.stalkMap y) hid
  simp only [map_mul, map_sub, Scheme.Hom.germ_stalkMap_apply, h0, map_zero] at this hu
  have h2 := sub_eq_zero.mp ((hu.mul_right_eq_zero).mp this)
  rw [Scheme.Hom.appLE, CommRingCat.comp_apply]
  erw [TopCat.Presheaf.germ_res_apply]
  erw [Scheme.Hom.germ_stalkMap_apply, Scheme.Hom.germ_stalkMap_apply] at h2
  exact h2

end Hid

section Pencil

variable {X S : Scheme.{u}} [IsIntegral X] [IsLocallyNoetherian X] (π : X ⟶ S)
  (C : X.IdealSheafData) (O : X.Opens)

lemma mem_support_iff_germ (I : X.IdealSheafData) {W : X.affineOpens} {x : X}
    (hx : x ∈ (W : X.Opens)) {u : Γ(X, W)} (hu : I.ideal W = Ideal.span {u}) :
    x ∈ I.support ↔ ¬IsUnit (X.presheaf.germ W x hx u) := by
  rw [Scheme.IdealSheafData.mem_support_iff_of_mem hx, hu, Scheme.zeroLocus_span,
    Scheme.mem_zeroLocus_iff]
  simp [Scheme.mem_basicOpen X u x hx]

/-- Charts of the pencil: local equations `u`, `v` of the zeros and poles of `f`, the generator
`h` of the fibre over `n ∈ {0, 1}`, the identity `(u - v) (f / (f - 1) - n) = h` in `K(X)`, and
`u - v` a unit at points of the fibre when `C` misses the common points of zeros and poles. -/
theorem pencil_chart (hufd : ∀ x : X, UniqueFactorizationMonoid (X.presheaf.stalk x))
    {f : X.functionField} (hf : f ≠ 0) (hf1 : f ≠ 1) (hfin : (Function.support (div X f)).Finite)
    (J : X.IdealSheafData) (n : ℤ)
    (hJ : J = effI (div X f) ⊔ C ∧ n = 0 ∨ J = effI (-div X f) ⊔ C ∧ n = 1) (x : X) :
    ∃ W : X.affineOpens, ∃ hxW : x ∈ (W : X.Opens), ∃ u v h : Γ(X, W),
      J.ideal W = Ideal.span {h} ⊔ C.ideal W ∧
      algebraMap (X.presheaf.stalk x) X.functionField (X.presheaf.germ W x hxW (u - v)) *
        (f / (f - 1) - n) =
        algebraMap (X.presheaf.stalk x) X.functionField (X.presheaf.germ W x hxW h) ∧
      ((∀ y, y ∈ C.support → y ∈ (effI (div X f)).support → y ∉ (effI (-div X f)).support) →
        x ∈ J.support → IsUnit (X.presheaf.germ W x hxW (u - v))) := by
  obtain ⟨W, hxW, u, v, hu, hv, huv⟩ := exists_bridge hufd hf hfin x
  have hP := mem_support_iff_germ (effI (div X f)) hxW hu
  have hN := mem_support_iff_germ (effI (-div X f)) hxW hv
  rcases hJ with ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩
  · refine ⟨W, hxW, u, v, u, ?_, ?_, ?_⟩
    · show (effI (div X f)).ideal W ⊔ C.ideal W = _
      rw [hu]
    · simp only [map_sub]
      exact pencil_K hf1 _ huv (by simp)
    · intro hCPN hx
      rw [Scheme.IdealSheafData.support_sup] at hx
      have h1 := hP.mp hx.1
      have h2 : IsUnit (X.presheaf.germ W x hxW v) := not_not.mp (mt hN.mpr (hCPN x hx.2 hx.1))
      rw [map_sub]
      exact isUnit_sub_of_nonunit h1 h2
  · refine ⟨W, hxW, u, v, v, ?_, ?_, ?_⟩
    · show (effI (-div X f)).ideal W ⊔ C.ideal W = _
      rw [hv]
    · simp only [map_sub]
      exact pencil_K hf1 _ huv (by push_cast; ring)
    · intro hCPN hx
      rw [Scheme.IdealSheafData.support_sup] at hx
      have h1 := hN.mp hx.1
      have h2 : IsUnit (X.presheaf.germ W x hxW u) :=
        not_not.mp (mt hP.mpr (fun hp => hCPN x hx.2 hp hx.1))
      rw [map_sub, ← neg_sub]
      exact (isUnit_sub_of_nonunit h1 h2).neg

/-- The chart hypothesis `H` of `isPullback_fibre` for the pencil. -/
theorem pencil_H (hufd : ∀ x : X, UniqueFactorizationMonoid (X.presheaf.stalk x))
    {f : X.functionField} (hf : f ≠ 0) (hf1 : f ≠ 1) (hfin : (Function.support (div X f)).Finite)
    (g : Γ(X, O)) (hO : genericPoint X ∈ O)
    (hg : ∀ x (hx : x ∈ O),
      algebraMap (X.presheaf.stalk x) X.functionField (X.presheaf.germ O x hx g) = f / (f - 1))
    (J : X.IdealSheafData) (n : ℤ)
    (hJ : J = effI (div X f) ⊔ C ∧ n = 0 ∨ J = effI (-div X f) ⊔ C ∧ n = 1)
    (l : Γ(S, ⊤)) (hl : l = n) (x : X) :
    ∃ W : X.affineOpens, x ∈ W.1 ∧ ∃ a h : Γ(X, W),
      J.ideal W ≤ Ideal.span {h} ⊔ C.ideal W ∧
      (ιCO C O).app W a * (COo C O).toScheme.presheaf.map (homOfLE le_top).op
        (gCO C O g - (ιCO C O ≫ π).appTop l) = (ιCO C O).app W h := by
  obtain ⟨W, hxW, u, v, h, hJW, hK, -⟩ := pencil_chart C hufd hf hf1 hfin J n hJ x
  refine ⟨W, hxW, u - v, h, hJW.le, hid_of_res π C O g l W _ _ ?_⟩
  have hηW : genericPoint X ∈ (W : X.Opens) :=
    ((genericPoint_spec X).mem_open_set_iff W.1.isOpen).mpr ⟨x, trivial, hxW⟩
  haveI : Nonempty (W : X.Opens) := ⟨⟨x, hxW⟩⟩
  haveI : Nonempty O := ⟨⟨_, hO⟩⟩
  have hg' := hg _ hO
  apply res_eq_of_germ (genericPoint X) (show genericPoint X ∈ O ⊓ (W : X.Opens) from ⟨hO, hηW⟩)
  simp only [map_sub, Scheme.algebraMap_germ_eq_germToFunctionField] at hK hg'
  simp only [hl, map_intCast, map_mul, map_sub, TopCat.Presheaf.germ_res_apply,
    Scheme.algebraMap_germ_eq_germToFunctionField]
  rw [hg']
  exact hK

lemma top_le_preimage (J : X.IdealSheafData) {O : X.Opens} (hJO : (J.support : Set X) ⊆ O) :
    (⊤ : J.subscheme.Opens) ≤ J.subschemeι ⁻¹ᵁ O := fun y _ =>
  show J.subschemeι y ∈ O from hJO (show J.subschemeι y ∈ (J.support : Set X) by
    rw [← Scheme.IdealSheafData.range_subschemeι]; exact ⟨y, rfl⟩)

/-- A subscheme `J ≥ C` supported in `O` maps into `C ∩ O`. -/
noncomputable def mCO (J : X.IdealSheafData) (hCJ : C ≤ J) (hJO : (J.support : Set X) ⊆ O) :
    J.subscheme ⟶ (COo C O).toScheme :=
  IsOpenImmersion.lift (COo C O).ι (Scheme.IdealSheafData.inclusion hCJ) (by
    rw [Scheme.Opens.range_ι]
    rintro _ ⟨y, rfl⟩
    show C.subschemeι (Scheme.IdealSheafData.inclusion hCJ y) ∈ O
    rw [← Scheme.Hom.comp_apply, Scheme.IdealSheafData.inclusion_subschemeι]
    exact top_le_preimage J hJO (show y ∈ (⊤ : J.subscheme.Opens) from trivial))

lemma mCO_ιCO (J : X.IdealSheafData) (hCJ : C ≤ J) (hJO : (J.support : Set X) ⊆ O) :
    mCO C O J hCJ hJO ≫ ιCO C O = J.subschemeι := by
  rw [mCO, ιCO, ← Category.assoc, IsOpenImmersion.lift_fac,
    Scheme.IdealSheafData.inclusion_subschemeι]

variable {C O} in
/-- Points of the fibre lie in the regular locus of `f / (f - 1)`. -/
lemma pencil_supp_le (hufd : ∀ x : X, UniqueFactorizationMonoid (X.presheaf.stalk x))
    {f : X.functionField} (hf : f ≠ 0) (hf1 : f ≠ 1) (hfin : (Function.support (div X f)).Finite)
    (hreg : ∀ x : X, f / (f - 1) ∈ Set.range (algebraMap (X.presheaf.stalk x) X.functionField) →
      x ∈ O)
    (hCPN : ∀ y, y ∈ C.support → y ∈ (effI (div X f)).support → y ∉ (effI (-div X f)).support)
    (J : X.IdealSheafData) (n : ℤ)
    (hJ : J = effI (div X f) ⊔ C ∧ n = 0 ∨ J = effI (-div X f) ⊔ C ∧ n = 1) :
    (J.support : Set X) ⊆ O := by
  intro x hx
  obtain ⟨W, hxW, u, v, h, -, hK, hU⟩ := pencil_chart C hufd hf hf1 hfin J n hJ x
  have hu := hU hCPN hx
  apply hreg x
  refine ⟨n + X.presheaf.germ W x hxW h * ↑hu.unit⁻¹, ?_⟩
  have hne : algebraMap (X.presheaf.stalk x) X.functionField
      (X.presheaf.germ W x hxW (u - v)) ≠ 0 := (hu.map _).ne_zero
  rw [map_add, map_intCast, map_mul, map_units_inv, IsUnit.unit_spec, ← hK, mul_right_comm,
    mul_inv_cancel₀ hne, one_mul]
  ring

theorem pencil_hg (hufd : ∀ x : X, UniqueFactorizationMonoid (X.presheaf.stalk x))
    {f : X.functionField} (hf : f ≠ 0) (hf1 : f ≠ 1) (hfin : (Function.support (div X f)).Finite)
    (g : Γ(X, O))
    (hg : ∀ x (hx : x ∈ O),
      algebraMap (X.presheaf.stalk x) X.functionField (X.presheaf.germ O x hx g) = f / (f - 1))
    (hCPN : ∀ y, y ∈ C.support → y ∈ (effI (div X f)).support → y ∉ (effI (-div X f)).support)
    (J : X.IdealSheafData) (n : ℤ)
    (hJ : J = effI (div X f) ⊔ C ∧ n = 0 ∨ J = effI (-div X f) ⊔ C ∧ n = 1)
    (hCJ : C ≤ J) (hJO : (J.support : Set X) ⊆ O) (l : Γ(S, ⊤)) (hl : l = n) :
    (mCO C O J hCJ hJO).appTop (gCO C O g) = (J.subschemeι ≫ π).appTop l := by
  have e1 : (mCO C O J hCJ hJO).appTop (gCO C O g) =
      J.subschemeι.appLE O ⊤ (top_le_preimage J hJO) g := by
    show (mCO C O J hCJ hJO).app ⊤ (gCO C O g) = _
    rw [← Scheme.Hom.appLE_eq_app, gCO, ← CommRingCat.comp_apply, Scheme.Hom.appLE_comp_appLE,
      appLE_congr_hom (mCO_ιCO C O J hCJ hJO)]
    rfl
  rw [e1, Scheme.Hom.comp_appTop, CommRingCat.comp_apply]
  refine appLE_eq_of_local _ O _ g _ fun y => ?_
  have hxJ : J.subschemeι y ∈ (J.support : Set X) := by
    rw [← Scheme.IdealSheafData.range_subschemeι]; exact ⟨y, rfl⟩
  obtain ⟨W, hxW, u, v, h, hJW, hK, hU⟩ :=
    pencil_chart C hufd hf hf1 hfin J n hJ (J.subschemeι y)
  refine ⟨W, hxW, u - v, h, hU hCPN hxJ, ?_, ?_⟩
  · have hh : h ∈ J.ideal W := hJW ▸ Ideal.mem_sup_left (Ideal.mem_span_singleton_self h)
    rw [← Scheme.IdealSheafData.ker_subschemeι_app] at hh
    exact hh
  · apply IsFractionRing.injective (X.presheaf.stalk (J.subschemeι y)) X.functionField
    simp only [hl, map_intCast, map_mul, map_sub, hg _ (hJO hxJ)] at hK ⊢
    exact hK

/-- **The fibres of the pencil** over `0` and `1`: with `O`, `g` the regular locus and section of
`f / (f - 1)`, the fibre of the graph family of `g` on `C` over `n ∈ {0, 1}` is the subscheme
`effI (div f) ⊔ C`, resp. `effI (-div f) ⊔ C`. -/
theorem isPullback_pencil (hufd : ∀ x : X, UniqueFactorizationMonoid (X.presheaf.stalk x))
    {f : X.functionField} (hf : f ≠ 0) (hf1 : f ≠ 1) (hfin : (Function.support (div X f)).Finite)
    (g : Γ(X, O))
    (hg : ∀ x (hx : x ∈ O),
      algebraMap (X.presheaf.stalk x) X.functionField (X.presheaf.germ O x hx g) = f / (f - 1))
    (hreg : ∀ x : X, f / (f - 1) ∈ Set.range (algebraMap (X.presheaf.stalk x) X.functionField) →
      x ∈ O)
    (hCPN : ∀ y, y ∈ C.support → y ∈ (effI (div X f)).support → y ∉ (effI (-div X f)).support)
    [QuasiCompact (gam C O g)] (J : X.IdealSheafData) (n : ℤ)
    (hJ : J = effI (div X f) ⊔ C ∧ n = 0 ∨ J = effI (-div X f) ⊔ C ∧ n = 1)
    (l : Γ(S, ⊤)) (hl : l = n) :
    ∃ m : J.subscheme ⟶ (COo C O).toScheme, m ≫ ιCO C O = J.subschemeι ∧
      IsPullback (m ≫ (gam C O g).toImage) (J.subschemeι ≫ π) (famL π C O g) (ptL l) := by
  have hO : genericPoint X ∈ O := hreg _ (mem_range_generic _ _ rfl)
  have hCJ : C ≤ J := by rcases hJ with ⟨rfl, -⟩ | ⟨rfl, -⟩ <;> exact le_sup_right
  have hJO := pencil_supp_le hufd hf hf1 hfin hreg hCPN J n hJ
  exact ⟨mCO C O J hCJ hJO, mCO_ιCO C O J hCJ hJO,
    isPullback_fibre π C O g l J _ (mCO_ιCO C O J hCJ hJO)
      (pencil_hg π C O hufd hf hf1 hfin g hg hCPN J n hJ hCJ hJO l hl)
      (pencil_H π C O hufd hf hf1 hfin g hO hg J n hJ l hl)⟩

end Pencil

end RamanujanPetersson.IntersectB

end

-- ===== S4.Def_RP_IntersectB_Pen5 =====
section

/-!
# S4-IntersectB, file Pen5: the two fibres of the pencil have the same length (L34, B4)

* `mem_of_mul_mem_of_ass`, `nzd_algebraMap`: non-zero-divisors from associated primes and
  under localisation.
* `nzd_germ_subscheme`, `nzd_germ_CO`: a local equation avoiding the associated points of `C`
  is a non-zero-divisor in the stalks of `C` and of `C ∩ O`.
* `pencil_chart2`: charts of the pencil at a point of the fibre with the unit `u - v` and the
  associated-prime condition on the fibre equation.
* `hy_pencil`, `hm_pencil`: the two hypotheses of `flat_famL`.
* `len_pencil`: `len (effI (div f) ⊔ C) = len (effI (-div f) ⊔ C)` for `C` avoiding the common
  points of zeros and poles and with no associated point on them.
-/

set_option autoImplicit false

universe u

open CategoryTheory AlgebraicGeometry Topology IsLocalRing

namespace RamanujanPetersson.IntersectB

open RamanujanPetersson.JacDivisors RamanujanPetersson.IsogDegA RamanujanPetersson.IntersectA

section NZD

/-- An element outside every associated prime of `R ⧸ I` is a non-zero-divisor modulo `I`. -/
lemma mem_of_mul_mem_of_ass {R : Type*} [CommRing R] [IsNoetherianRing R] (I : Ideal R) {h : R}
    (hh : ∀ p ∈ associatedPrimes R (R ⧸ I), h ∉ p) {r : R} (hr : h * r ∈ I) : r ∈ I := by
  have hreg : IsSMulRegular (R ⧸ I) h := by
    by_contra hc
    have hmem : h ∈ ⋃ p ∈ associatedPrimes R (R ⧸ I), (p : Set R) := by
      rw [biUnion_associatedPrimes_eq_compl_regular R (R ⧸ I)]; exact hc
    simp only [Set.mem_iUnion, SetLike.mem_coe] at hmem
    obtain ⟨p, hp, hhp⟩ := hmem
    exact hh p hp hhp
  have e : h • Ideal.Quotient.mk I r = h • (0 : R ⧸ I) := by
    rw [smul_zero]; exact Ideal.Quotient.eq_zero_iff_mem.2 hr
  exact Ideal.Quotient.eq_zero_iff_mem.1 (hreg e)

/-- The image of a non-zero-divisor in a localisation is a non-zero-divisor. -/
lemma nzd_algebraMap {R T : Type*} [CommRing R] [CommRing T] [Algebra R T] (M : Submonoid R)
    [IsLocalization M T] {t : R} (ht : ∀ r, t * r = 0 → r = 0) :
    ∀ b : T, algebraMap R T t * b = 0 → b = 0 := by
  intro b hb
  obtain ⟨r, s, rfl⟩ := IsLocalization.mk'_surjective M b
  rw [IsLocalization.mul_mk'_eq_mk'_of_mul, IsLocalization.mk'_eq_zero_iff] at hb
  rw [IsLocalization.mk'_eq_zero_iff]
  obtain ⟨m, hm⟩ := hb
  exact ⟨m, ht _ (by rw [mul_left_comm]; exact hm)⟩

variable {X : Scheme.{u}} [IsLocallyNoetherian X] (C : X.IdealSheafData)

/-- A section avoiding the associated primes of `C` is a non-zero-divisor in the stalks of `C`. -/
lemma nzd_germ_subscheme (W : X.affineOpens) {h : Γ(X, W)}
    (hh : ∀ p ∈ associatedPrimes Γ(X, W) (Γ(X, W) ⧸ C.ideal W), h ∉ p)
    (z : C.subscheme) (hz : z ∈ C.subschemeι ⁻¹ᵁ (W : X.Opens)) :
    ∀ b : C.subscheme.presheaf.stalk z,
      C.subscheme.presheaf.germ _ z hz (C.subschemeι.app W h) * b = 0 → b = 0 := by
  have hV : IsAffineOpen (C.subschemeι ⁻¹ᵁ (W : X.Opens)) := W.2.preimage C.subschemeι
  have : IsNoetherianRing Γ(X, W) := IsLocallyNoetherian.component_noetherian W
  let φ := (C.subschemeObjIso W).commRingCatIsoToRingEquiv
  have hφ : ∀ a : Γ(X, W), C.subschemeι.app W a = φ.symm (Ideal.Quotient.mk _ a) := fun a => by
    rw [Scheme.IdealSheafData.subschemeι_app]; rfl
  have ht : ∀ r : Γ(C.subscheme, C.subschemeι ⁻¹ᵁ (W : X.Opens)),
      C.subschemeι.app W h * r = 0 → r = 0 := by
    intro r hr
    obtain ⟨r', hr'⟩ := Ideal.Quotient.mk_surjective (φ r)
    have hr2 : r = φ.symm (Ideal.Quotient.mk _ r') := by rw [hr', RingEquiv.symm_apply_apply]
    rw [hr2, hφ, ← map_mul, ← map_mul, map_eq_zero_iff _ φ.symm.injective,
      Ideal.Quotient.eq_zero_iff_mem] at hr
    rw [hr2, Ideal.Quotient.eq_zero_iff_mem.2 (mem_of_mul_mem_of_ass _ hh hr), map_zero]
  letI := TopCat.Presheaf.algebra_section_stalk C.subscheme.presheaf ⟨z, hz⟩
  have hloc := hV.isLocalization_stalk ⟨z, hz⟩
  exact nzd_algebraMap (hV.primeIdealOf ⟨z, hz⟩).asIdeal.primeCompl ht

variable (O : X.Opens)

/-- The same in the stalks of the open part `C ∩ O`. -/
lemma nzd_germ_CO (W : X.affineOpens) {h : Γ(X, W)}
    (hh : ∀ p ∈ associatedPrimes Γ(X, W) (Γ(X, W) ⧸ C.ideal W), h ∉ p)
    (x : (COo C O).toScheme) (hx : x ∈ ιCO C O ⁻¹ᵁ (W : X.Opens)) :
    ∀ b : (COo C O).toScheme.presheaf.stalk x,
      (COo C O).toScheme.presheaf.germ _ x hx ((ιCO C O).app W h) * b = 0 → b = 0 := by
  intro b hb
  have hz : (COo C O).ι x ∈ C.subschemeι ⁻¹ᵁ (W : X.Opens) := hx
  have e1 : (COo C O).toScheme.presheaf.germ _ x hx ((ιCO C O).app W h) =
      (COo C O).ι.stalkMap x (C.subscheme.presheaf.germ _ _ hz (C.subschemeι.app W h)) := by
    rw [Scheme.Hom.germ_stalkMap_apply]; rfl
  let ψ := (asIso ((COo C O).ι.stalkMap x)).commRingCatIsoToRingEquiv
  obtain ⟨b', rfl⟩ : ∃ b', ψ b' = b := ψ.surjective b
  rw [e1] at hb
  have hb' : C.subscheme.presheaf.germ _ _ hz (C.subschemeι.app W h) * b' = 0 := by
    apply ψ.injective
    rw [map_mul, map_zero]
    exact hb
  rw [nzd_germ_subscheme C W hh _ hz b' hb', map_zero]

end NZD

section Chart

variable {X S : Scheme.{u}} [IsIntegral X] [IsLocallyNoetherian X] (π : X ⟶ S)
  (C : X.IdealSheafData) (O : X.Opens)

/-- Charts of the pencil at a point of the fibre: the identity of `isPullback_fibre` with `a` a
unit at the point and the fibre equation `h` outside the associated primes of `C`. -/
theorem pencil_chart2 (hufd : ∀ x : X, UniqueFactorizationMonoid (X.presheaf.stalk x))
    {f : X.functionField} (hf : f ≠ 0) (hf1 : f ≠ 1) (hfin : (Function.support (div X f)).Finite)
    (g : Γ(X, O)) (hO : genericPoint X ∈ O)
    (hg : ∀ x (hx : x ∈ O),
      algebraMap (X.presheaf.stalk x) X.functionField (X.presheaf.germ O x hx g) = f / (f - 1))
    (hCPN : ∀ y, y ∈ C.support → y ∈ (effI (div X f)).support → y ∉ (effI (-div X f)).support)
    (hAss : ∀ ξ ∈ assSet C, ξ ∉ (effI (div X f)).support ∧ ξ ∉ (effI (-div X f)).support)
    (J : X.IdealSheafData) (n : ℤ)
    (hJ : J = effI (div X f) ⊔ C ∧ n = 0 ∨ J = effI (-div X f) ⊔ C ∧ n = 1)
    (l : Γ(S, ⊤)) (hl : l = n) (x : X) (hx : x ∈ J.support) :
    ∃ W : X.affineOpens, ∃ hxW : x ∈ (W : X.Opens), ∃ a h : Γ(X, W),
      IsUnit (X.presheaf.germ W x hxW a) ∧
      (∀ p ∈ associatedPrimes Γ(X, W) (Γ(X, W) ⧸ C.ideal W), h ∉ p) ∧
      (ιCO C O).app W a * (COo C O).toScheme.presheaf.map (homOfLE le_top).op
        (gCO C O g - (ιCO C O ≫ π).appTop l) = (ιCO C O).app W h := by
  obtain ⟨W, hxW, u, v, hu, hv, huv⟩ := exists_bridge hufd hf hfin x
  have hP := mem_support_iff_germ (effI (div X f)) hxW hu
  have hN := mem_support_iff_germ (effI (-div X f)) hxW hv
  have key : ∀ h : Γ(X, W), algebraMap _ X.functionField (X.presheaf.germ W x hxW (u - v)) *
      (f / (f - 1) - n) = algebraMap _ X.functionField (X.presheaf.germ W x hxW h) →
      (ιCO C O).app W (u - v) * (COo C O).toScheme.presheaf.map (homOfLE le_top).op
        (gCO C O g - (ιCO C O ≫ π).appTop l) = (ιCO C O).app W h := by
    intro h hK
    refine hid_of_res π C O g l W _ _ ?_
    have hηW : genericPoint X ∈ (W : X.Opens) :=
      ((genericPoint_spec X).mem_open_set_iff W.1.isOpen).mpr ⟨x, trivial, hxW⟩
    haveI : Nonempty (W : X.Opens) := ⟨⟨x, hxW⟩⟩
    haveI : Nonempty O := ⟨⟨_, hO⟩⟩
    have hg' := hg _ hO
    apply res_eq_of_germ (genericPoint X) (show genericPoint X ∈ O ⊓ (W : X.Opens) from ⟨hO, hηW⟩)
    simp only [map_sub, Scheme.algebraMap_germ_eq_germToFunctionField] at hK hg'
    simp only [hl, map_intCast, map_mul, map_sub, TopCat.Presheaf.germ_res_apply,
      Scheme.algebraMap_germ_eq_germToFunctionField]
    rw [hg']
    exact hK
  rcases hJ with ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩
  · rw [Scheme.IdealSheafData.support_sup] at hx
    refine ⟨W, hxW, u - v, u, ?_, ?_, key u ?_⟩
    · rw [map_sub]
      exact isUnit_sub_of_nonunit (hP.mp hx.1) (not_not.mp (mt hN.mpr (hCPN x hx.2 hx.1)))
    · intro p hp hup
      exact not_le_of_ass C _ (fun ξ hξ => (hAss ξ hξ).1) W p hp
        (by rw [hu]; exact (Ideal.span_singleton_le_iff_mem p).2 hup)
    · simp only [map_sub]
      exact pencil_K hf1 _ huv (by simp)
  · rw [Scheme.IdealSheafData.support_sup] at hx
    refine ⟨W, hxW, u - v, v, ?_, ?_, key v ?_⟩
    · have h2 : IsUnit (X.presheaf.germ W x hxW u) :=
        not_not.mp (mt hP.mpr (fun hp => hCPN x hx.2 hp hx.1))
      rw [map_sub, ← neg_sub]
      exact (isUnit_sub_of_nonunit (hN.mp hx.1) h2).neg
    · intro p hp hvp
      exact not_le_of_ass C _ (fun ξ hξ => (hAss ξ hξ).2) W p hp
        (by rw [hv]; exact (Ideal.span_singleton_le_iff_mem p).2 hvp)
    · simp only [map_sub]
      exact pencil_K hf1 _ huv (by push_cast; ring)

/-- `flat_famL`'s non-zero-divisor hypothesis at a point of the fibre. -/
theorem hy_pencil (hufd : ∀ x : X, UniqueFactorizationMonoid (X.presheaf.stalk x))
    {f : X.functionField} (hf : f ≠ 0) (hf1 : f ≠ 1) (hfin : (Function.support (div X f)).Finite)
    (g : Γ(X, O)) (hO : genericPoint X ∈ O)
    (hg : ∀ x (hx : x ∈ O),
      algebraMap (X.presheaf.stalk x) X.functionField (X.presheaf.germ O x hx g) = f / (f - 1))
    (hCPN : ∀ y, y ∈ C.support → y ∈ (effI (div X f)).support → y ∉ (effI (-div X f)).support)
    (hAss : ∀ ξ ∈ assSet C, ξ ∉ (effI (div X f)).support ∧ ξ ∉ (effI (-div X f)).support)
    (J : X.IdealSheafData) (n : ℤ)
    (hJ : J = effI (div X f) ⊔ C ∧ n = 0 ∨ J = effI (-div X f) ⊔ C ∧ n = 1)
    (l : Γ(S, ⊤)) (hl : l = n) (x : (COo C O).toScheme) (hxJ : ιCO C O x ∈ J.support) :
    ∀ b : (COo C O).toScheme.presheaf.stalk x,
      (COo C O).toScheme.presheaf.germ ⊤ x trivial
        (gCO C O g - (ιCO C O ≫ π).appTop l) * b = 0 → b = 0 := by
  obtain ⟨W, hxW, a, h, hu, hh, hid⟩ :=
    pencil_chart2 π C O hufd hf hf1 hfin g hO hg hCPN hAss J n hJ l hl _ hxJ
  intro b hb
  have hx : x ∈ ιCO C O ⁻¹ᵁ (W : X.Opens) := hxW
  have e := congrArg ((COo C O).toScheme.presheaf.germ _ x hx) hid
  rw [map_mul, TopCat.Presheaf.germ_res_apply] at e
  have hua : IsUnit ((COo C O).toScheme.presheaf.germ _ x hx ((ιCO C O).app W a)) := by
    have e2 := Scheme.Hom.germ_stalkMap_apply (ιCO C O) (W : X.Opens) x hx a
    have h3 := hu.map ((ιCO C O).stalkMap x).hom
    rw [e2] at h3
    exact h3
  apply nzd_germ_CO C O W hh x hx b
  rw [← e, mul_assoc, hb, mul_zero]

omit [IsIntegral X] [IsLocallyNoetherian X] in
/-- `flat_famL`'s maximal-ideal hypothesis at a point of the fibre. -/
theorem hm_pencil (g : Γ(X, O)) (l : Γ(S, ⊤)) (J : X.IdealSheafData)
    (m : J.subscheme ⟶ (COo C O).toScheme) (hm : m ≫ ιCO C O = J.subschemeι)
    (hg : m.appTop (gCO C O g) = (J.subschemeι ≫ π).appTop l) (y : J.subscheme) :
    (COo C O).toScheme.presheaf.germ ⊤ (m y) trivial
      (gCO C O g - (ιCO C O ≫ π).appTop l) ∈ maximalIdeal _ := by
  have e : (m.stalkMap y).hom ((COo C O).toScheme.presheaf.germ ⊤ (m y) trivial
      (gCO C O g - (ιCO C O ≫ π).appTop l)) = 0 := by
    refine (Scheme.Hom.germ_stalkMap_apply m ⊤ y trivial _).trans ?_
    have h2 : m.app ⊤ ((ιCO C O ≫ π).appTop l) = (J.subschemeι ≫ π).appTop l := by
      rw [← hm]
      simp only [Scheme.Hom.comp_appTop, CommRingCat.comp_apply, Category.assoc]
      rfl
    rw [map_sub, h2, show m.app ⊤ (gCO C O g) = _ from hg]
    exact (congrArg _ (sub_self _)).trans (map_zero _)
  rw [IsLocalRing.mem_maximalIdeal, mem_nonunits_iff]
  intro hu
  have h3 := hu.map (m.stalkMap y).hom
  rw [e] at h3
  exact not_isUnit_zero h3

end Chart

section Len

variable {k : Type u} [Field k] (A : Over (Spec (.of k))) [IsProper A.hom] [IsIntegral A.left]
  [IsLocallyNoetherian A.left]

lemma finite_subscheme {X : Scheme.{u}} (J : X.IdealSheafData) (h : (J.support : Set X).Finite) :
    Finite J.subscheme := by
  have hi : Function.Injective J.subschemeι := J.subschemeι.isEmbedding.injective
  refine Set.finite_univ_iff.mp (Set.Finite.of_finite_image (h.subset ?_) hi.injOn)
  rintro _ ⟨z, -, rfl⟩
  rw [← Scheme.IdealSheafData.range_subschemeι]
  exact ⟨z, rfl⟩

/-- **The pencil**: the zeros and the poles of `f` meet `C` in subschemes of the same length,
when `C` misses their common points and has no associated point on them. -/
theorem len_pencil (hufd : ∀ x : A.left, UniqueFactorizationMonoid (A.left.presheaf.stalk x))
    {f : A.left.functionField} (hf : f ≠ 0) (hf1 : f ≠ 1)
    (hfin : (Function.support (div A.left f)).Finite) (C : A.left.IdealSheafData)
    (hCPN : ∀ y, y ∈ C.support → y ∈ (effI (div A.left f)).support →
      y ∉ (effI (-div A.left f)).support)
    (hAss : ∀ ξ ∈ assSet C,
      ξ ∉ (effI (div A.left f)).support ∧ ξ ∉ (effI (-div A.left f)).support)
    (hfin0 : ((effI (div A.left f) ⊔ C).support : Set A.left).Finite)
    (hfin1 : ((effI (-div A.left f) ⊔ C).support : Set A.left).Finite) :
    len A (effI (div A.left f) ⊔ C) = len A (effI (-div A.left f) ⊔ C) := by
  have : CompactSpace A.left := QuasiCompact.compactSpace_of_compactSpace A.hom
  have : IsNoetherian A.left := { }
  have : IsLocallyNoetherian (Ln (Spec (.of k))) :=
    LocallyOfFiniteType.isLocallyNoetherian (prL (Spec (.of k)))
  obtain ⟨O, g, hg, hreg⟩ := exists_regOpen (f / (f - 1))
  have hO : genericPoint A.left ∈ O := hreg _ (mem_range_generic _ _ rfl)
  have : TopologicalSpace.NoetherianSpace (COo C O).toScheme := 
    (C.subschemeι.isEmbedding.comp (COo C O).ι.isEmbedding).isInducing.noetherianSpace
  let σ : k ≃+* Γ(Spec (.of k), ⊤) := (Scheme.ΓSpecIso (.of k)).commRingCatIsoToRingEquiv.symm
  have hfib : ∀ (J : A.left.IdealSheafData) (n : ℤ),
      (J = effI (div A.left f) ⊔ C ∧ n = 0 ∨ J = effI (-div A.left f) ⊔ C ∧ n = 1) →
      (J.support : Set A.left).Finite →
      ∃ m : J.subscheme ⟶ (COo C O).toScheme,
        IsPullback (m ≫ (gam C O g).toImage) (J.subschemeι ≫ A.hom) (famL A.hom C O g)
          (ptL (σ (n : k))) ∧
        ((famL A.hom C O g) ⁻¹' {ptL (σ (n : k)) (pt0 k)}).Finite ∧
        ∀ z, famL A.hom C O g z = ptL (σ (n : k)) (pt0 k) →
          ((famL A.hom C O g).stalkMap z).hom.Flat := by
    intro J n hJ hJf
    have hl : σ (n : k) = (n : Γ(Spec (.of k), ⊤)) := map_intCast σ n
    have hCJ : C ≤ J := by rcases hJ with ⟨rfl, -⟩ | ⟨rfl, -⟩ <;> exact le_sup_right
    have hJO := pencil_supp_le hufd hf hf1 hfin hreg hCPN J n hJ
    have hgm := pencil_hg A.hom C O hufd hf hf1 hfin g hg hCPN J n hJ hCJ hJO _ hl
    have hpb := isPullback_fibre A.hom C O g _ J _ (mCO_ιCO C O J hCJ hJO) hgm
      (pencil_H A.hom C O hufd hf hf1 hfin g hO hg J n hJ _ hl)
    have : Finite J.subscheme := finite_subscheme J hJf
    refine ⟨mCO C O J hCJ hJO, hpb, (Set.finite_range _).subset (preimage_subset_range hpb _),
      fun z hz => ?_⟩
    obtain ⟨y, rfl⟩ := preimage_subset_range hpb (pt0 k) hz
    have hxJ : ιCO C O (mCO C O J hCJ hJO y) ∈ J.support := by
      rw [← Scheme.Hom.comp_apply, mCO_ιCO]
      show J.subschemeι y ∈ (J.support : Set A.left)
      rw [← Scheme.IdealSheafData.range_subschemeι]
      exact ⟨y, rfl⟩
    rw [Scheme.Hom.comp_apply]
    exact flat_famL A.hom C O σ g (n : k) _
      (hy_pencil A.hom C O hufd hf hf1 hfin g hO hg hCPN hAss J n hJ _ hl _ hxJ)
      (hm_pencil A.hom C O g _ J _ (mCO_ιCO C O J hCJ hJO) hgm y)
  obtain ⟨m0, h0, hfin0', hflat0⟩ := hfib _ 0 (Or.inl ⟨rfl, rfl⟩) hfin0
  obtain ⟨m1, h1, hfin1', hflat1⟩ := hfib _ 1 (Or.inr ⟨rfl, rfl⟩) hfin1
  exact finrank_eq_of_fibres (famL A.hom C O g) _ _ hfin0' hfin1' hflat0 hflat1 _ _ _ h0
    (fun s => by rw [Subsingleton.elim (α := Spec (.of k)) s (pt0 k)]) _ _ _ h1
    (fun s => by rw [Subsingleton.elim (α := Spec (.of k)) s (pt0 k)]) (pt0 k) (pt0 k)

end Len

end RamanujanPetersson.IntersectB

end

-- ===== S4.Def_RP_IntersectB_Pen6 =====
section

/-!
# S4-IntersectB, file Pen6: transport along isomorphisms (L34, B4)

* `flat_isFinite_len`: a closed subscheme with finite support inside an affine open is finite
  and flat over `k`.
* `len_comap_iso`, `len_comap_iso'`: the length is unchanged by pulling back along an
  automorphism over `Spec k`.
* `assSet_comap_iso`: associated points move with an isomorphism.
(Pullback of ideal sheaves preserves `⊔` for every morphism: Mathlib's
`Scheme.IdealSheafData.comap_sup`.)
-/

set_option autoImplicit false

universe u

open CategoryTheory AlgebraicGeometry Limits

namespace RamanujanPetersson.IntersectB

open RamanujanPetersson.IsogDegA RamanujanPetersson.IntersectA

section Len

variable {k : Type u} [Field k] (A : Over (Spec (.of k)))

/-- A closed subscheme with finite support inside an affine open is finite and flat over `k`. -/
theorem flat_isFinite_len [LocallyOfFiniteType A.hom] (J : A.left.IdealSheafData)
    (V : A.left.affineOpens) (hV : (J.support : Set A.left) ⊆ V)
    (hfin : (J.support : Set A.left).Finite) :
    Flat (J.subschemeι ≫ A.hom) ∧ IsFinite (J.subschemeι ≫ A.hom) := by
  letI := (algV A V).hom.toAlgebra
  obtain ⟨hmf, -⟩ := len_eq_finrank A J V hV hfin
  let f : Spec (.of (Γ(A.left, V) ⧸ J.ideal V)) ⟶ J.subscheme := J.subschemeCover.f V
  have hfo : IsOpenImmersion f := J.subschemeCover.map_prop V
  have hf : IsIso f := by
    rw [isIso_iff_isOpenImmersion_and_surjective]
    refine ⟨hfo, ⟨fun z => ?_⟩⟩
    have h2 := J.opensRange_subschemeCover_map V
    have hz : z ∈ J.subschemeι ⁻¹ᵁ (V : A.left.Opens) :=
      hV (by rw [← Scheme.IdealSheafData.range_subschemeι]; exact ⟨z, rfl⟩)
    rw [← h2] at hz
    exact hz
  have hcomp : f ≫ J.subschemeι ≫ A.hom =
      Spec.map (CommRingCat.ofHom (algebraMap k (Γ(A.left, V) ⧸ J.ideal V))) := by
    have h1 : f ≫ J.subschemeι = Spec.map (CommRingCat.ofHom (Ideal.Quotient.mk (J.ideal V))) ≫
        V.2.fromSpec :=
      (J.subschemeCover_map_subschemeι V).trans (J.glueDataObjι_ι V)
    rw [← Category.assoc, h1, Category.assoc, ← algV_spec, ← Spec.map_comp]
    rfl
  have hg : J.subschemeι ≫ A.hom = inv f ≫
      Spec.map (CommRingCat.ofHom (algebraMap k (Γ(A.left, V) ⧸ J.ideal V))) := by
    rw [← hcomp, IsIso.inv_hom_id_assoc]
  have : Flat (Spec.map (CommRingCat.ofHom (algebraMap k (Γ(A.left, V) ⧸ J.ideal V)))) := by
    rw [Flat.SpecMap_iff, CommRingCat.hom_ofHom, RingHom.flat_algebraMap_iff]; infer_instance
  have : IsFinite (Spec.map (CommRingCat.ofHom (algebraMap k (Γ(A.left, V) ⧸ J.ideal V)))) := by
    rw [IsFinite.SpecMap_iff, CommRingCat.hom_ofHom, RingHom.finite_algebraMap]; exact hmf
  rw [hg]
  exact ⟨inferInstance, inferInstance⟩

/-- (T2) The length is unchanged by pulling back along an automorphism over `Spec k`. -/
theorem len_comap_iso [LocallyOfFiniteType A.hom] (J : A.left.IdealSheafData)
    (V : A.left.affineOpens) (hV : (J.support : Set A.left) ⊆ V)
    (hfin : (J.support : Set A.left).Finite) (e : A.left ⟶ A.left) [IsIso e]
    (he : e ≫ A.hom = A.hom) : len A (J.comap e) = len A J := by
  obtain ⟨h1, h2⟩ := flat_isFinite_len A J V hV hfin
  have hc : (J.comap e).subschemeι ≫ A.hom =
      ((J.comapIso e).hom ≫ pullback.snd e J.subschemeι) ≫ J.subschemeι ≫ A.hom := by
    rw [← Scheme.IdealSheafData.comapIso_hom_fst J e]
    simp only [Category.assoc]
    rw [← pullback.condition_assoc, he]
  show Scheme.Hom.finrank _ (pt0 k) = Scheme.Hom.finrank _ (pt0 k)
  rw [hc, Scheme.Hom.finrank_comp_left_of_isIso]

/-- (T2') The same on a group scheme over an algebraically closed field (no chart needed). -/
theorem len_comap_iso' [GrpObj A] [IsAlgClosed k] [LocallyOfFiniteType A.hom]
    [IrreducibleSpace A.left] (J : A.left.IdealSheafData)
    (hfin : (J.support : Set A.left).Finite) (e : A.left ⟶ A.left) [IsIso e]
    (he : e ≫ A.hom = A.hom) : len A (J.comap e) = len A J := by
  obtain ⟨V, hV⟩ := exists_affine_mem A hfin.toFinset
  exact len_comap_iso A J V (fun x hx => hV x (hfin.mem_toFinset.mpr hx)) hfin e he

end Len

section AssIso

/-- (T3) Associated points move with an isomorphism. -/
theorem assSet_comap_iso {X Y : Scheme.{u}} [IsLocallyNoetherian Y] (C : Y.IdealSheafData)
    (e : X ⟶ Y) [IsIso e] (x : X) (hx : x ∈ assSet (C.comap e)) : e x ∈ assSet C := by
  obtain ⟨V, hxV, hA⟩ := hx
  let V' : Y.affineOpens := ⟨e ''ᵁ V, V.2.image_of_isOpenImmersion e⟩
  have hx' : e x ∈ (V' : Y.Opens) := ⟨x, hxV, rfl⟩
  refine ⟨V', hx', ?_⟩
  let φ := (e.appIso V.1).commRingCatIsoToRingEquiv
  letI : Algebra Γ(Y, V') Γ(X, V) := φ.toRingHom.toAlgebra
  haveI : IsNoetherianRing Γ(Y, V') := IsLocallyNoetherian.component_noetherian V'
  haveI : IsLocalization (⊥ : Submonoid Γ(Y, V')) Γ(X, V) := by
    haveI : IsLocalization (⊥ : Submonoid Γ(Y, V')) Γ(Y, V') := IsLocalization.self bot_le
    exact IsLocalization.isLocalization_of_algEquiv ⊥ (AlgEquiv.ofRingEquiv (f := φ) fun _ => rfl)
  have hI : (C.comap e).ideal V = (C.ideal V').map (algebraMap Γ(Y, V') Γ(X, V)) := by
    rw [Scheme.IdealSheafData.ideal_comap_of_isOpenImmersion]
    exact (Ideal.map_comap_of_equiv φ).symm
  have hP : (V'.2.primeIdealOf ⟨e x, hx'⟩).asIdeal =
      (V.2.primeIdealOf ⟨x, hxV⟩).asIdeal.comap (algebraMap Γ(Y, V') Γ(X, V)) := by
    ext a
    rw [Ideal.mem_comap, ← not_iff_not]
    refine (mem_basicOpen_iff_primeIdealOf V'.2 (e x) hx' a).symm.trans
      (Iff.trans ?_ (mem_basicOpen_iff_primeIdealOf V.2 x hxV _))
    have h1 := Scheme.image_basicOpen e (U := V.1) (algebraMap Γ(Y, V') Γ(X, V) a)
    have h2 : (e.appIso V.1).inv (algebraMap Γ(Y, V') Γ(X, V) a) = a := by
      simp [φ, RingHom.algebraMap_toAlgebra]
    rw [h2] at h1
    rw [← h1]
    exact e.isOpenEmbedding.injective.mem_set_image
  unfold IsAssPt at hA ⊢
  rw [hI] at hA
  rw [hP]
  exact (ass_localization ⊥ (C.ideal V') _).mpr hA

end AssIso

end RamanujanPetersson.IntersectB

end

-- ===== S4.Def_RP_IntersectB_Pen7 =====
section

/-!
# S4-IntersectB, file Pen7: generic translates of a small configuration do not meet (L34, B4)

* `exists_empty_inter`: one cut more than the height bound empties an intersection.
* `mem_range_famP_iff`: a parameter lies in the image of the family exactly when the translated
  intersection is nonempty.
* `exists_open_empty`: if the slot-`0` support has height `< n`, generic translates of
  `X0, E 0, …, E (n-1)` have empty intersection.
-/

set_option autoImplicit false

universe u

open CategoryTheory MonoidalCategory AlgebraicGeometry MonObj CartesianMonoidalCategory Limits
  TopologicalSpace

namespace RamanujanPetersson.IntersectB

open RamanujanPetersson.IsogDegA RamanujanPetersson.IntersectA

section EmptyTop

variable {X : Scheme.{u}} [NoetherianSpace X]

/-- One cut more than the height bound empties the intersection. -/
theorem exists_empty_inter {α : Type*} (m : ℕ) (H : ℕ → α → Set X)
    (hHc : ∀ i a, IsClosed (H i a)) (hH : ∀ i (S : Finset X), ∃ a, ∀ t ∈ S, t ∉ H i a)
    (S0 : Finset X) (hS0 : ∀ t ∈ S0, Order.height t + 1 ≤ m) :
    ∃ a : ℕ → α, (⋃ t ∈ S0, closure {t}) ∩ (⋂ i < m, H i (a i)) = ∅ := by
  classical
  cases m with
  | zero =>
    obtain ⟨a0, -⟩ := hH 0 ∅
    refine ⟨fun _ => a0, ?_⟩
    have hS : S0 = ∅ := Finset.eq_empty_of_forall_notMem fun t ht => by
      have h := hS0 t ht
      simp at h
    subst hS
    simp
  | succ m =>
    have hS0' : ∀ t ∈ S0, Order.height t ≤ m := fun t ht => by
      have h := hS0 t ht
      push_cast at h
      exact (WithTop.add_le_add_iff_right ENat.one_ne_top).mp h
    obtain ⟨a, S, hsub, hht⟩ := gp_aux m H hHc hH S0 hS0' m le_rfl
    obtain ⟨b, hb⟩ := hH m S
    refine ⟨Function.update a m b, Set.eq_empty_of_forall_notMem fun x hx => ?_⟩
    obtain ⟨hx0, hx⟩ := hx
    have hx' : x ∈ ⋂ i < m, H i (a i) := Set.mem_iInter₂.2 fun i hi => by
      have := Set.mem_iInter₂.1 hx i (Nat.lt_succ_of_lt hi)
      rwa [Function.update_of_ne (Nat.ne_of_lt hi)] at this
    have hxm : x ∈ H m b := by
      have := Set.mem_iInter₂.1 hx m (Nat.lt_succ_self m)
      rwa [Function.update_self] at this
    have hxS := hsub ⟨hx0, hx'⟩
    simp only [Set.mem_iUnion, exists_prop] at hxS
    obtain ⟨t, ht, hxt⟩ := hxS
    have h0 : Order.height t = 0 := by
      have h1 := hht t ht
      by_contra h
      have h3 : (1 : ℕ∞) + m ≤ Order.height t + m := by
        gcongr
        exact Order.one_le_iff_ne_zero.mpr h
      have h2 := h3.trans h1
      norm_cast at h2
      omega
    rw [(isClosed_singleton_of_height_eq_zero t h0).closure_eq, Set.mem_singleton_iff] at hxt
    exact hb t ht (hxt ▸ hxm)

end EmptyTop

section Empty

variable {k : Type u} [Field k] (A : Over (Spec (.of k))) [GrpObj A]

/-- A parameter lies in the image of the family iff the translated intersection is nonempty. -/
theorem mem_range_famP_iff {g : ℕ} (D : Fin g → A.left.IdealSheafData)
    (c : 𝟙_ (Over (Spec (.of k))) ⟶ Pw A g) :
    pt (Pw A g) c ∈ Set.range (famP A D) ↔
      ((Zid A D (fun i => c ≫ proj A g i)).support : Set A.left).Nonempty := by
  have hP := RamanujanPetersson.IntersectA.isPullback_fibre A D c
  rw [← comap_famI, ← Scheme.IdealSheafData.range_subschemeι]
  constructor
  · rintro ⟨w, hw⟩
    obtain ⟨z, -, -⟩ := Scheme.Pullback.exists_preimage_pullback (f := famP A D) (g := c.left)
      w (pt0 k) hw
    exact ⟨_, hP.isoPullback.inv z, rfl⟩
  · rintro ⟨_, z, rfl⟩
    refine ⟨((((famI A D).comapIso (sec A c).left).hom ≫ pullback.snd _ _) z), ?_⟩
    rw [← Scheme.Hom.comp_apply, hP.w, Scheme.Hom.comp_apply]
    show c.left _ = c.left (pt0 k)
    exact congrArg (fun p : Spec (.of k) => c.left p) (@Subsingleton.elim (Spec (.of k)) _ _ _)

variable [IsAlgClosed k] [IsProper A.hom] [IsIntegral A.left]

/-- (G1) If the slot-`0` support has height `< n`, generic translates have empty intersection. -/
theorem exists_open_empty (n : ℕ) (X0 : A.left.IdealSheafData) (E : Fin n → A.left.IdealSheafData)
    (hE : ∀ j, (E j).support ≠ ⊤)
    (h0 : ∀ x ∈ (X0.support : Set A.left), Order.height x + 1 ≤ n) :
    ∃ U : Set (Pw A (n + 1)).left, IsOpen U ∧ U.Nonempty ∧
      ∀ c : 𝟙_ (Over (Spec (.of k))) ⟶ Pw A (n + 1), pt (Pw A (n + 1)) c ∈ U →
        ((Zid A (Fin.cons X0 E : Fin (n + 1) → A.left.IdealSheafData)
          (fun i => c ≫ proj A (n + 1) i)).support : Set A.left) = ∅ := by
  classical
  have := noetherianSpace_left A
  have := isProper_famP A (Fin.cons X0 E : Fin (n + 1) → A.left.IdealSheafData)
  refine ⟨(Set.range (famP A (Fin.cons X0 E : Fin (n + 1) → A.left.IdealSheafData)))ᶜ,
    (Scheme.Hom.isClosedMap _).isClosed_range.isOpen_compl, ?_, fun c hc => ?_⟩
  · let H : ℕ → (𝟙_ (Over (Spec (.of k))) ⟶ A) → Set A.left := fun i a =>
      if h : i < n then (transl A a).left ⁻¹' (E ⟨i, h⟩).support else ∅
    have hHc : ∀ i a, IsClosed (H i a) := by
      intro i a
      by_cases h : i < n
      · simp only [H, dif_pos h]
        exact (E ⟨i, h⟩).support.isClosed.preimage (transl A a).left.continuous
      · simp only [H, dif_neg h]
        exact isClosed_empty
    have hH : ∀ i (S : Finset A.left), ∃ a, ∀ y ∈ S, y ∉ H i a := by
      intro i S
      by_cases h : i < n
      · have hne : ((E ⟨i, h⟩).support : Set A.left) ≠ Set.univ := fun he =>
          hE ⟨i, h⟩ (TopologicalSpace.Closeds.ext (by rw [he]; rfl))
        obtain ⟨a, ha⟩ := exists_good A S _ (E ⟨i, h⟩).support.isClosed hne
        exact ⟨a, fun y hy => by simp only [H, dif_pos h]; exact ha y hy⟩
      · exact ⟨1, fun y _ => by simp only [H, dif_neg h]; exact Set.notMem_empty y⟩
    obtain ⟨S0, hS0m, hS0⟩ := exists_finset_closure (X0.support : Set A.left) X0.support.isClosed
    obtain ⟨a, ha⟩ := exists_empty_inter n H hHc hH S0 (fun t ht => h0 t (hS0m t ht))
    let a' : Fin (n + 1) → (𝟙_ (Over (Spec (.of k))) ⟶ A) := Fin.cons 1 (fun j => a j)
    refine ⟨pt (Pw A (n + 1)) (ptOf A (n + 1) a'), fun hmem => ?_⟩
    obtain ⟨y, hy⟩ := (mem_range_famP_iff A _ _).mp hmem
    have he : (fun i => ptOf A (n + 1) a' ≫ proj A (n + 1) i) = a' :=
      funext (ptOf_proj A (n + 1) a')
    rw [he, coe_support_Zid, Set.mem_iInter] at hy
    refine (Set.eq_empty_iff_forall_notMem.mp ha) y ⟨?_, Set.mem_iInter₂.2 fun i hi => ?_⟩
    · rw [← hS0]
      simpa [a', transl_one] using hy 0
    · simp only [H, dif_pos hi]
      have h := hy (Fin.succ ⟨i, hi⟩)
      simp only [a', Fin.cons_succ, Fin.val_mk] at h
      exact h
  · by_contra hne
    exact hc ((mem_range_famP_iff A _ c).mpr (Set.nonempty_iff_ne_empty.mpr hne))

end Empty

end RamanujanPetersson.IntersectB

end

-- ===== S4.Def_RP_IntersectB_Pen8 =====
section

/-!
# S4-IntersectB, file Pen8: the pencil for generic translates (L34, B4)

* `mem_support_prod`, `mem_support_effI`: points of the support of a product and of `effI D`.
* `height_add_one_le_of_lt`, `height_effI_inf`: the common points of the zeros and the poles of
  `f` have height `< n` when every point has height `≤ n + 1`.
* `len_pencil_comap`: `len_pencil` transported along an automorphism over `k`.
* `inum_pencil`: `inum (effI (div f), E) = inum (effI (-div f), E)`.
-/

set_option autoImplicit false

universe u

open CategoryTheory MonoidalCategory AlgebraicGeometry MonObj CartesianMonoidalCategory Limits
  TopologicalSpace

namespace RamanujanPetersson.IntersectB

open RamanujanPetersson.JacDivisors RamanujanPetersson.IsogDegA RamanujanPetersson.IntersectA

section Height

variable {X : Scheme.{u}}

lemma mem_support_prod {β : Type*} (s : Finset β) (I : β → X.IdealSheafData) {x : X}
    (hx : x ∈ ((∏ z ∈ s, I z).support : Set X)) : ∃ z ∈ s, x ∈ ((I z).support : Set X) := by
  classical
  induction s using Finset.induction_on with
  | empty =>
    rw [Finset.prod_empty, Scheme.IdealSheafData.one_eq_top,
      Scheme.IdealSheafData.support_top] at hx
    simp at hx
  | insert a s ha ih =>
    rw [Finset.prod_insert ha, Scheme.IdealSheafData.support_mul, Closeds.coe_sup] at hx
    rcases hx with h | h
    · exact ⟨a, Finset.mem_insert_self _ _, h⟩
    · obtain ⟨z, hz, h⟩ := ih h
      exact ⟨z, Finset.mem_insert_of_mem hz, h⟩

lemma mem_support_effI (D : AlgebraicCycle X ℤ) (hfin : (Function.support D).Finite) {x : X}
    (hx : x ∈ ((effI D).support : Set X)) : ∃ z, 0 < D z ∧ x ∈ closure {z} := by
  rw [effI_eq_prod D hfin.toFinset fun z hz => hfin.mem_toFinset.mpr hz] at hx
  obtain ⟨z, -, hz⟩ := mem_support_prod _ _ hx
  by_cases h : (D z).toNat = 0
  · rw [h, pow_zero, Scheme.IdealSheafData.one_eq_top, Scheme.IdealSheafData.support_top] at hz
    simp at hz
  · rw [(primeI z).support_pow _ h, coe_support_primeI] at hz
    exact ⟨z, lt_of_not_ge fun h' => h (Int.toNat_eq_zero.mpr h'), hz⟩

lemma height_add_one_le_of_lt [IrreducibleSpace X] (n : ℕ)
    (hdim : ∀ x : X, Order.height x ≤ (n + 1 : ℕ)) {x y : X} (hxy : x < y)
    (hy : Order.coheight y = 1) : Order.height x + 1 ≤ n := by
  have hyη : y < genericPoint X := by
    refine lt_of_le_not_ge (Scheme.le_iff_specializes.mpr (genericPoint_specializes y)) fun h => ?_
    have hmax : IsMax y := fun b _ => (Scheme.le_iff_specializes.mpr (genericPoint_specializes b)).trans h
    rw [Order.coheight_eq_zero.mpr hmax] at hy
    exact zero_ne_one hy
  have h4 : Order.height x + 1 + 1 ≤ (n : ℕ∞) + 1 :=
    calc Order.height x + 1 + 1 ≤ Order.height y + 1 := by
          gcongr; exact Order.height_add_one_le hxy
      _ ≤ Order.height (genericPoint X) := Order.height_add_one_le hyη
      _ ≤ ((n + 1 : ℕ) : ℕ∞) := hdim _
      _ = (n : ℕ∞) + 1 := Nat.cast_succ n
  exact (WithTop.add_le_add_iff_right ENat.one_ne_top).mp h4

variable [IsIntegral X] [IsLocallyNoetherian X]

/-- The common points of the zeros and the poles of `f` have height `< n`. -/
lemma height_effI_inf (n : ℕ) (hdim : ∀ x : X, Order.height x ≤ (n + 1 : ℕ))
    (f : X.functionField) (hfin : (Function.support (div X f)).Finite) (x : X)
    (hx : x ∈ ((effI (div X f) ⊔ effI (-div X f)).support : Set X)) :
    Order.height x + 1 ≤ n := by
  rw [Scheme.IdealSheafData.support_sup, Closeds.coe_inf] at hx
  obtain ⟨z, hz, hxz⟩ := mem_support_effI _ hfin hx.1
  obtain ⟨w, hw, hxw⟩ := mem_support_effI _ (hfin.subset fun a ha => by simpa using ha) hx.2
  rw [Function.locallyFinsuppWithin.coe_neg, Pi.neg_apply] at hw
  have hle : ∀ y, x ∈ closure {y} → x ≤ y := fun y h =>
    Scheme.le_iff_specializes.mpr (specializes_iff_mem_closure.mpr h)
  have hlt : ∀ y, x ∈ closure {y} → x ≠ y → x < y := fun y h hne =>
    lt_of_le_not_ge (hle y h) fun h' =>
      hne ((Scheme.le_iff_specializes.mp h').antisymm (Scheme.le_iff_specializes.mp (hle y h))).eq
  have h1 : ∀ y, div X f y ≠ 0 → Order.coheight y = 1 := fun y hy => div_mem_weilDivisors f y hy
  by_cases hxz' : x = z
  · subst hxz'
    exact height_add_one_le_of_lt n hdim (hlt w hxw fun h => by subst h; omega) (h1 w (by omega))
  · exact height_add_one_le_of_lt n hdim (hlt z hxz hxz') (h1 z (by omega))

end Height

section Pencil

variable {k : Type u} [Field k] [IsAlgClosed k] (A : Over (Spec (.of k))) [GrpObj A]
  [IsProper A.hom] [IsIntegral A.left] [IsLocallyNoetherian A.left]

/-- `len_pencil` transported along an automorphism `s` of `A` over `k`. -/
lemma len_pencil_comap (hufd : ∀ x : A.left, UniqueFactorizationMonoid (A.left.presheaf.stalk x))
    {f : A.left.functionField} (hf : f ≠ 0) (hf1 : f ≠ 1)
    (hfin : (Function.support (div A.left f)).Finite) (C : A.left.IdealSheafData)
    (s : A.left ⟶ A.left) [IsIso s] (hs : s ≫ A.hom = A.hom)
    (hemp : (((effI (div A.left f) ⊔ effI (-div A.left f)).comap s ⊔ C).support : Set A.left)
      = ∅)
    (hAss : ∀ ξ ∈ assSet C, s ξ ∉ ((effI (div A.left f)).support : Set A.left) ∧
      s ξ ∉ ((effI (-div A.left f)).support : Set A.left))
    (hfin0 : (((effI (div A.left f)).comap s ⊔ C).support : Set A.left).Finite)
    (hfin1 : (((effI (-div A.left f)).comap s ⊔ C).support : Set A.left).Finite) :
    len A ((effI (div A.left f)).comap s ⊔ C) = len A ((effI (-div A.left f)).comap s ⊔ C) := by
  have hse : ∀ y, s (inv s y) = y := fun y => by
    rw [← Scheme.Hom.comp_apply, IsIso.inv_hom_id] <;> rfl
  have hid (Y : A.left.IdealSheafData) : Y.comap s ⊔ C = (Y ⊔ C.comap (inv s)).comap s := by
    rw [Scheme.IdealSheafData.comap_sup, ← Scheme.IdealSheafData.comap_comp, IsIso.hom_inv_id,
      Scheme.IdealSheafData.comap_id]
  have hsurj : Function.Surjective s := fun y => ⟨inv s y, hse y⟩
  rw [hid, Scheme.IdealSheafData.support_comap, Closeds.coe_preimage] at hemp hfin0 hfin1
  rw [hid, hid, len_comap_iso' A _ (hfin0.of_preimage hsurj) s hs,
    len_comap_iso' A _ (hfin1.of_preimage hsurj) s hs]
  refine len_pencil A hufd hf hf1 hfin _ (fun y hyC hyP hyN => ?_) (fun ξ hξ => ?_)
    (hfin0.of_preimage hsurj) (hfin1.of_preimage hsurj)
  · refine Set.eq_empty_iff_forall_notMem.mp hemp (inv s y) ?_
    rw [Set.mem_preimage, hse]
    simp only [Scheme.IdealSheafData.support_sup, Closeds.coe_inf, Set.mem_inter_iff]
    exact ⟨⟨hyP, hyN⟩, hyC⟩
  · have h := hAss (inv s ξ) (assSet_comap_iso C (inv s) ξ hξ)
    rwa [hse] at h

/-- **B4** for `inum`: the zeros and the poles of `f` have the same intersection number. -/
theorem inum_pencil (n : ℕ) (hdim : ∀ x : A.left, Order.height x ≤ (n + 1 : ℕ))
    (hufd : ∀ x : A.left, UniqueFactorizationMonoid (A.left.presheaf.stalk x))
    {f : A.left.functionField} (hf : f ≠ 0) (hf1 : f ≠ 1) (E : Fin n → A.left.IdealSheafData)
    (h1 : ∀ i, ((Fin.cons (effI (div A.left f)) E : Fin (n + 1) → A.left.IdealSheafData) i).support
      ≠ ⊤)
    (h2 : ∀ i, ((Fin.cons (effI (-div A.left f)) E : Fin (n + 1) → A.left.IdealSheafData) i).support
      ≠ ⊤) :
    inum A (n + 1) hdim (Fin.cons (effI (div A.left f)) E) h1 =
      inum A (n + 1) hdim (Fin.cons (effI (-div A.left f)) E) h2 := by
  have := isIntegral_Pw A (n + 1)
  have := isProper_Pw A (n + 1)
  have : CompactSpace A.left := QuasiCompact.compactSpace_of_compactSpace A.hom
  have hfin := support_finite_of_compact (div A.left f)
  have hE : ∀ j, (E j).support ≠ ⊤ := fun j => by simpa only [Fin.cons_succ] using h1 j.succ
  obtain ⟨U1, hU1o, hU1n, hU1⟩ := inum_spec A (n + 1) hdim _ h1
  obtain ⟨U2, hU2o, hU2n, hU2⟩ := inum_spec A (n + 1) hdim _ h2
  obtain ⟨U3, hU3o, hU3n, hU3⟩ := exists_open_empty A n
    (effI (div A.left f) ⊔ effI (-div A.left f)) E hE (height_effI_inf n hdim f hfin)
  have hUo : IsOpen (U1 ∩ U2 ∩ U3) := (hU1o.inter hU2o).inter hU3o
  obtain ⟨cs, hcs⟩ := exists_pt_mem (Pw A (n + 1)) (U1 ∩ U2 ∩ U3) hUo.isLocallyClosed
    (nonempty_preirreducible_inter (hU1o.inter hU2o) hU3o
      (nonempty_preirreducible_inter hU1o hU2o hU1n hU2n) hU3n)
  obtain ⟨C, hC⟩ : ∃ C : A.left.IdealSheafData,
      C = ⨆ j, (E j).comap (transl A (cs ≫ proj A (n + 1) j.succ)).left := ⟨_, rfl⟩
  have hEf := assSet_finite C
  have hPN : ((effI (div A.left f) * effI (-div A.left f)).support : Set A.left) ≠ Set.univ :=
    fun h => support_mul_ne_top (by simpa only [Fin.cons_zero] using h1 0)
      (by simpa only [Fin.cons_zero] using h2 0)
      (SetLike.coe_injective (h.trans Closeds.coe_top.symm))
  choose G hGo hGn hG using fun ξ => exists_open_good A ξ _
    (effI (div A.left f) * effI (-div A.left f)).support.isClosed hPN
  have hO : IsOpen ((slice A cs).left ⁻¹' (U1 ∩ U2 ∩ U3)) :=
    hUo.preimage (slice A cs).left.continuous
  have hOn : pt A (cs ≫ proj A (n + 1) 0) ∈ (slice A cs).left ⁻¹' (U1 ∩ U2 ∩ U3) := by
    show (slice A cs).left (pt A _) ∈ U1 ∩ U2 ∩ U3
    rw [← pt_comp, slice_self]; exact hcs
  obtain ⟨c0, hc0O, hc0G⟩ := exists_pt_mem A _
    (hO.inter (isOpen_biInter_finset fun ξ _ => hGo ξ)).isLocallyClosed
    (nonempty_preirreducible_inter hO (isOpen_biInter_finset fun ξ _ => hGo ξ) ⟨_, hOn⟩
      (nonempty_biInter_finset hEf.toFinset G (fun ξ _ => hGo ξ) fun ξ _ => hGn ξ))
  have hc : pt (Pw A (n + 1)) (c0 ≫ slice A cs) ∈ U1 ∩ U2 ∩ U3 := by rw [pt_comp]; exact hc0O
  have hZ (Y : A.left.IdealSheafData) :
      Zid A (Fin.cons Y E : Fin (n + 1) → A.left.IdealSheafData)
        (fun i => (c0 ≫ slice A cs) ≫ proj A (n + 1) i) = Y.comap (transl A c0).left ⊔ C := by
    rw [Zid_cons, hC, pt_slice_zero]
    simp only [pt_slice_succ]
  have := isIso_translL A c0
  obtain ⟨hfin1, hl1⟩ := hU1 _ hc.1.1
  obtain ⟨hfin2, hl2⟩ := hU2 _ hc.1.2
  have hemp := hU3 _ hc.2
  rw [hZ] at hfin1 hl1 hfin2 hl2 hemp
  rw [← hl1, ← hl2]
  refine len_pencil_comap A hufd hf hf1 hfin C _ (Over.w (transl A c0)) hemp (fun ξ hξ => ?_)
    hfin1 hfin2
  have h := hG ξ c0 (Set.mem_iInter₂.1 hc0G ξ (hEf.mem_toFinset.2 hξ))
  rw [Scheme.IdealSheafData.support_mul, Closeds.coe_sup, Set.mem_union] at h
  exact not_or.mp h

end Pencil

end RamanujanPetersson.IntersectB

end

-- ===== S4.Def_RP_IntersectB_Pen9 =====
section

/-!
# S4-IntersectB, file Pen9: the intersection form respects linear equivalence (L34, B4)

* `support_effI_ne_top`: `effI D` of a Weil divisor has a proper support.
* `inumZ_cons_effI'`: slot-`0` expansion of `effI D` for any Weil divisor (positive parts).
* `inumZ_pencil`: `inumZ (effI (div f), E) = inumZ (effI (-div f), E)`.
* `iform_cons`: slot-`0` expansion of `iform`.
* `iform_cons_div`, `iform_update_div`: `iform` vanishes with a principal divisor in any slot.
* `iform_linEquiv`, `iform_linEquiv_all`: `iform` is invariant under linear equivalence.
-/

set_option autoImplicit false

universe u

open CategoryTheory MonoidalCategory AlgebraicGeometry MonObj CartesianMonoidalCategory Limits
  TopologicalSpace

namespace RamanujanPetersson.IntersectB

open RamanujanPetersson.JacDivisors RamanujanPetersson.IsogDegA RamanujanPetersson.IntersectA

section Top

variable {X : Scheme.{u}} [IsIntegral X] [IsLocallyNoetherian X]

lemma support_effI_ne_top (D : AlgebraicCycle X ℤ) (hW : D ∈ weilDivisors X)
    (hfin : (Function.support D).Finite) : (effI D).support ≠ ⊤ := by
  rw [effI_eq_prod D hfin.toFinset fun z hz => hfin.mem_toFinset.mpr hz,
    ← _root_.mul_one (∏ z ∈ hfin.toFinset, primeI z ^ (D z).toNat),
    Scheme.IdealSheafData.one_eq_top]
  refine support_prod_mul_ne_top primeI (fun z => (D z).toNat) _
    (fun z hz => support_primeI_ne_top (hW z (hfin.mem_toFinset.mp hz))) ?_
  intro h
  obtain ⟨x⟩ : Nonempty X := inferInstance
  have hx : x ∈ ((⊤ : X.IdealSheafData).support : Set X) := by
    rw [h]; exact Set.mem_univ _
  simp [Scheme.IdealSheafData.support_top] at hx

end Top

section Iform

variable {k : Type u} [Field k] [IsAlgClosed k] (A : Over (Spec (.of k))) [GrpObj A]
  [IsProper A.hom] [IsIntegral A.left] [IsLocallyNoetherian A.left]

/-- Slot-`0` expansion of `effI D` for any Weil divisor `D` (only `D⁺` contributes). -/
theorem inumZ_cons_effI' (hufd : ∀ x : A.left, UniqueFactorizationMonoid (A.left.presheaf.stalk x))
    (n : ℕ) (hdim : ∀ x : A.left, Order.height x ≤ (n + 1 : ℕ)) (D : AlgebraicCycle A.left ℤ)
    (hW : D ∈ weilDivisors A.left) (E : Fin n → A.left.IdealSheafData) :
    inumZ A (n + 1) hdim (Fin.cons (effI D) E : Fin (n + 1) → A.left.IdealSheafData) =
      ∑ᶠ z, ((D z).toNat : ℤ) *
        inumZ A (n + 1) hdim (Fin.cons (primeI z) E : Fin (n + 1) → A.left.IdealSheafData) := by
  have : CompactSpace A.left := QuasiCompact.compactSpace_of_compactSpace A.hom
  have hfin := support_finite_of_compact D
  have hs : Function.support D ⊆ hfin.toFinset := fun z hz => hfin.mem_toFinset.mpr hz
  have h1 : ∀ z ∈ hfin.toFinset, Order.coheight z = 1 := fun z hz =>
    hW z (hfin.mem_toFinset.mp hz)
  have htop : (⊤ : A.left.IdealSheafData).support ≠ ⊤ := by
    intro h
    obtain ⟨x⟩ : Nonempty A.left := inferInstance
    have hx : x ∈ ((⊤ : A.left.IdealSheafData).support : Set A.left) := by
      rw [h]; exact Set.mem_univ _
    simp [Scheme.IdealSheafData.support_top] at hx
  rw [effI_eq_prod D _ hs, ← _root_.mul_one (∏ z ∈ hfin.toFinset, primeI z ^ (D z).toNat),
    Scheme.IdealSheafData.one_eq_top,
    inumZ_prod_mul A n hdim primeI (fun z => (D z).toNat) E _
      (fun z hz => support_primeI_ne_top (h1 z hz)) (fun z hz => isLocPrin_primeI hufd (h1 z hz))
      htop, inumZ_cons_top, add_zero,
    finsum_eq_sum_of_support_subset (fun z => ((D z).toNat : ℤ) *
        inumZ A (n + 1) hdim (Fin.cons (primeI z) E : Fin (n + 1) → A.left.IdealSheafData))
      (fun z hz => hs fun h => left_ne_zero_of_mul hz (by simp [h]))] <;> rfl

/-- **B4** for `inumZ`: zeros and poles of `f` give the same intersection number. -/
theorem inumZ_pencil (hufd : ∀ x : A.left, UniqueFactorizationMonoid (A.left.presheaf.stalk x))
    (n : ℕ) (hdim : ∀ x : A.left, Order.height x ≤ (n + 1 : ℕ)) {f : A.left.functionField}
    (hf : f ≠ 0) (E : Fin n → A.left.IdealSheafData) :
    inumZ A (n + 1) hdim (Fin.cons (effI (div A.left f)) E : Fin (n + 1) → A.left.IdealSheafData) =
      inumZ A (n + 1) hdim
        (Fin.cons (effI (-div A.left f)) E : Fin (n + 1) → A.left.IdealSheafData) := by
  by_cases hf1 : f = 1
  · subst hf1
    rw [RamanujanPetersson.JacDivisors.div_one, neg_zero]
  have : CompactSpace A.left := QuasiCompact.compactSpace_of_compactSpace A.hom
  by_cases hE : ∀ j, (E j).support ≠ ⊤
  · have hW := div_mem_weilDivisors f
    have h1 := cons_support_ne_top A
      (support_effI_ne_top _ hW (support_finite_of_compact _)) hE
    have h2 := cons_support_ne_top A
      (support_effI_ne_top _ (neg_mem hW) (support_finite_of_compact _)) hE
    rw [inumZ_of A _ hdim _ h1, inumZ_of A _ hdim _ h2, inum_pencil A n hdim hufd hf hf1 E h1 h2]
  · rw [inumZ_cons_of_not A n hdim hE, inumZ_cons_of_not A n hdim hE]

/-- Slot-`0` expansion of the intersection form. -/
theorem iform_cons (n : ℕ) (hdim : ∀ x : A.left, Order.height x ≤ (n + 1 : ℕ))
    (D : AlgebraicCycle A.left ℤ) (E : Fin n → AlgebraicCycle A.left ℤ) :
    iform A (n + 1) hdim (Fin.cons D E) = ∑ᶠ z' : Fin n → A.left, (∏ j, E j (z' j)) *
      ∑ᶠ a, D a * inumZ A (n + 1) hdim
        (Fin.cons (primeI a) fun j => primeI (z' j) : Fin (n + 1) → A.left.IdealSheafData) := by
  have : CompactSpace A.left := QuasiCompact.compactSpace_of_compactSpace A.hom
  let e : (Fin n → A.left) × A.left ≃ (Fin (n + 1) → A.left) :=
    (Equiv.prodComm _ _).trans (Fin.consEquiv fun _ => A.left)
  have hfin := finite_support_prod
    (fun i => ⇑((Fin.cons D E : Fin (n + 1) → AlgebraicCycle A.left ℤ) i))
    (fun i => support_finite_of_compact _) (fun z => inumZ A (n + 1) hdim fun i => primeI (z i))
  simp only [iform]
  rw [← finsum_comp_equiv e,
    finsum_curry _ ((hfin.preimage e.injective.injOn).subset fun x hx => hx)]
  refine finsum_congr fun z' => ?_
  rw [mul_finsum]
  refine finsum_congr fun a => ?_
  show (∏ i, (Fin.cons D E : Fin (n + 1) → AlgebraicCycle A.left ℤ) i
      ((Fin.cons a z' : Fin (n + 1) → A.left) i)) *
    inumZ A (n + 1) hdim (fun i => primeI ((Fin.cons a z' : Fin (n + 1) → A.left) i)) = _
  have hc : (fun i => primeI ((Fin.cons a z' : Fin (n + 1) → A.left) i)) =
      (Fin.cons (primeI a) fun j => primeI (z' j) : Fin (n + 1) → A.left.IdealSheafData) := by
    funext i
    exact Fin.cases rfl (fun j => rfl) i
  rw [hc]
  simp only [Fin.prod_univ_succ, Fin.cons_zero, Fin.cons_succ]
  ring

/-- `iform` vanishes when slot `0` is a principal divisor. -/
theorem iform_cons_div (hufd : ∀ x : A.left, UniqueFactorizationMonoid (A.left.presheaf.stalk x))
    (n : ℕ) (hdim : ∀ x : A.left, Order.height x ≤ (n + 1 : ℕ)) {f : A.left.functionField}
    (hf : f ≠ 0) (E : Fin n → AlgebraicCycle A.left ℤ) :
    iform A (n + 1) hdim (Fin.cons (div A.left f) E) = 0 := by
  have : CompactSpace A.left := QuasiCompact.compactSpace_of_compactSpace A.hom
  have hW := div_mem_weilDivisors f
  have hfin := support_finite_of_compact (div A.left f)
  have key : ∀ E' : Fin n → A.left.IdealSheafData, ∑ᶠ a, div A.left f a *
      inumZ A (n + 1) hdim (Fin.cons (primeI a) E' : Fin (n + 1) → A.left.IdealSheafData) = 0 := by
    intro E'
    have hP := inumZ_cons_effI' A hufd n hdim _ hW E'
    have hN := inumZ_cons_effI' A hufd n hdim _ (neg_mem hW) E'
    have hsub : ∀ D : AlgebraicCycle A.left ℤ, (Function.support D).Finite →
        (Function.support fun a => ((D a).toNat : ℤ) *
          inumZ A (n + 1) hdim (Fin.cons (primeI a) E' : Fin (n + 1) → A.left.IdealSheafData)).Finite :=
      fun D hD => hD.subset fun a ha =>
        Function.mem_support.mpr fun h => left_ne_zero_of_mul ha (by simp [h])
    have e1 : ∀ a, div A.left f a *
        inumZ A (n + 1) hdim (Fin.cons (primeI a) E' : Fin (n + 1) → A.left.IdealSheafData) =
        ((div A.left f a).toNat : ℤ) *
          inumZ A (n + 1) hdim (Fin.cons (primeI a) E' : Fin (n + 1) → A.left.IdealSheafData) -
        (((-div A.left f) a).toNat : ℤ) *
          inumZ A (n + 1) hdim (Fin.cons (primeI a) E' : Fin (n + 1) → A.left.IdealSheafData) :=
      fun a => by
        rw [← sub_mul, Function.locallyFinsuppWithin.coe_neg, Pi.neg_apply,
          Int.toNat_sub_toNat_neg]
    rw [finsum_congr e1, finsum_sub_distrib (hsub _ hfin) (hsub _ (support_finite_of_compact _)),
      ← hP, ← hN, inumZ_pencil A hufd n hdim hf E', sub_self]
  rw [iform_cons]
  exact finsum_eq_zero_of_forall_eq_zero fun z' => by rw [key, mul_zero]

/-- `iform` vanishes when any slot is a principal divisor. -/
theorem iform_update_div (hufd : ∀ x : A.left, UniqueFactorizationMonoid (A.left.presheaf.stalk x))
    (n : ℕ) (hdim : ∀ x : A.left, Order.height x ≤ n) (D : Fin n → AlgebraicCycle A.left ℤ)
    (i : Fin n) {f : A.left.functionField} (hf : f ≠ 0) :
    iform A n hdim (Function.update D i (div A.left f)) = 0 := by
  cases n with
  | zero => exact i.elim0
  | succ m =>
    rw [← iform_perm A (m + 1) hdim _ (Equiv.swap 0 i), update_swap]
    exact iform_cons_div A hufd m hdim hf _

/-- **L34** (linear part): `iform` is invariant under linear equivalence in each slot. -/
theorem iform_linEquiv (hufd : ∀ x : A.left, UniqueFactorizationMonoid (A.left.presheaf.stalk x))
    (n : ℕ) (hdim : ∀ x : A.left, Order.height x ≤ n) (D : Fin n → AlgebraicCycle A.left ℤ)
    (i : Fin n) {D₁ D₂ : AlgebraicCycle A.left ℤ} (h : LinEquiv A.left D₁ D₂) :
    iform A n hdim (Function.update D i D₁) = iform A n hdim (Function.update D i D₂) := by
  obtain ⟨f, hf, rfl⟩ := linEquiv_iff.mp h
  rw [iform_update_add, iform_update_div A hufd n hdim D i hf, add_zero]

/-- **L34** (linear part): `iform` only depends on the linear equivalence classes. -/
theorem iform_linEquiv_all
    (hufd : ∀ x : A.left, UniqueFactorizationMonoid (A.left.presheaf.stalk x))
    (n : ℕ) (hdim : ∀ x : A.left, Order.height x ≤ n) (D D' : Fin n → AlgebraicCycle A.left ℤ)
    (h : ∀ i, LinEquiv A.left (D i) (D' i)) : iform A n hdim D = iform A n hdim D' := by
  classical
  have key : ∀ s : Finset (Fin n),
      iform A n hdim (fun i => if i ∈ s then D' i else D i) = iform A n hdim D := by
    intro s
    induction s using Finset.induction_on with
    | empty => simp
    | insert j s hj ih =>
      have e : (fun i => if i ∈ insert j s then D' i else D i) =
          Function.update (fun i => if i ∈ s then D' i else D i) j (D' j) := by
        funext i
        by_cases hij : i = j
        · subst hij; simp
        · simp [Function.update_of_ne hij, hij]
      have e2 : Function.update (fun i => if i ∈ s then D' i else D i) j (D j) =
          fun i => if i ∈ s then D' i else D i := by
        rw [Function.update_eq_self_iff]; simp [hj]
      rw [e, iform_linEquiv A hufd n hdim _ j ((linEquiv_equivalence (X := A.left)).symm (h j)),
        e2, ih]
  have := key Finset.univ
  simp only [Finset.mem_univ, if_true] at this
  exact this.symm

end Iform

end RamanujanPetersson.IntersectB

end
Source
J. S. Milne, Étale Cohomology, Princeton University Press (1980), Chapter V, §2 (Poincaré duality for curves); P. Deligne, Cohomologie étale (SGA 4½), Lecture Notes in Math. 569, Springer (1977), « Dualité »; J. S. Milne, Jacobian varieties, in Arithmetic Geometry (G. Cornell, J. H. Silverman, eds.), Springer (1986), 167-212; H. Stichtenoth, Algebraic Function Fields and Codes, 2nd ed., GTM 254, Springer (2009)

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