source
stringlengths
17
118
lean4
stringlengths
0
335k
.lake/packages/mathlib/Mathlib/Topology/Algebra/Valued/WithVal.lean
import Mathlib.RingTheory.Valuation.ValuativeRel.Basic import Mathlib.Topology.UniformSpace.Completion import Mathlib.Topology.Algebra.Valued.ValuationTopology import Mathlib.NumberTheory.NumberField.Basic /-! # Ring topologised by a valuation For a given valuation `v : Valuation R Γ₀` on a ring `R` taking values in `Γ₀`, this file defines the type synonym `WithVal v` of `R`. By assigning a `Valued (WithVal v) Γ₀` instance, `WithVal v` represents the ring `R` equipped with the topology coming from `v`. The type synonym `WithVal v` is in isomorphism to `R` as rings via `WithVal.equiv v`. This isomorphism should be used to explicitly map terms of `WithVal v` to terms of `R`. The `WithVal` type synonym is used to define the completion of `R` with respect to `v` in `Valuation.Completion`. An example application of this is `IsDedekindDomain.HeightOneSpectrum.adicCompletion`, which is the completion of the field of fractions of a Dedekind domain with respect to a height-one prime ideal of the domain. ## Main definitions - `WithVal` : type synonym for a ring equipped with the topology coming from a valuation. - `WithVal.equiv` : the canonical ring equivalence between `WithValuation v` and `R`. - `Valuation.Completion` : the uniform space completion of a field `K` according to the uniform structure defined by the specified valuation. -/ noncomputable section variable {R Γ₀ : Type*} [LinearOrderedCommGroupWithZero Γ₀] /-- Type synonym for a ring equipped with the topology coming from a valuation. -/ @[nolint unusedArguments] def WithVal [Ring R] : Valuation R Γ₀ → Type _ := fun _ => R namespace WithVal section Instances variable {P S : Type*} [LinearOrderedCommGroupWithZero Γ₀] instance [Ring R] (v : Valuation R Γ₀) : Ring (WithVal v) := inferInstanceAs (Ring R) instance [CommRing R] (v : Valuation R Γ₀) : CommRing (WithVal v) := inferInstanceAs (CommRing R) instance [Field R] (v : Valuation R Γ₀) : Field (WithVal v) := inferInstanceAs (Field R) instance [Ring R] (v : Valuation R Γ₀) : Inhabited (WithVal v) := ⟨0⟩ instance [CommSemiring S] [CommRing R] [Algebra S R] (v : Valuation R Γ₀) : Algebra S (WithVal v) := inferInstanceAs (Algebra S R) instance [CommRing S] [CommRing R] [Algebra S R] [IsFractionRing S R] (v : Valuation R Γ₀) : IsFractionRing S (WithVal v) := inferInstanceAs (IsFractionRing S R) instance [Ring R] [SMul S R] (v : Valuation R Γ₀) : SMul S (WithVal v) := inferInstanceAs (SMul S R) instance [Ring R] [SMul P S] [SMul S R] [SMul P R] [IsScalarTower P S R] (v : Valuation R Γ₀) : IsScalarTower P S (WithVal v) := inferInstanceAs (IsScalarTower P S R) variable [CommRing R] (v : Valuation R Γ₀) instance {S : Type*} [Ring S] [Algebra R S] : Algebra (WithVal v) S := inferInstanceAs (Algebra R S) instance {S : Type*} [Ring S] [Algebra R S] (w : Valuation S Γ₀) : Algebra R (WithVal w) := inferInstanceAs (Algebra R S) instance {P S : Type*} [Ring S] [Semiring P] [Module P R] [Module P S] [Algebra R S] [IsScalarTower P R S] : IsScalarTower P (WithVal v) S := inferInstanceAs (IsScalarTower P R S) end Instances section Ring variable [Ring R] (v : Valuation R Γ₀) /-- Canonical ring equivalence between `WithVal v` and `R`. -/ def equiv : WithVal v ≃+* R := RingEquiv.refl _ /-- Canonical valuation on the `WithVal v` type synonym. -/ def valuation : Valuation (WithVal v) Γ₀ := v.comap (equiv v) @[simp] lemma valuation_equiv_symm (x : R) : valuation v ((equiv v).symm x) = v x := rfl instance {R} [Ring R] (v : Valuation R Γ₀) : Valued (WithVal v) Γ₀ := Valued.mk' (valuation v) theorem apply_equiv (r : WithVal v) : v (equiv v r) = Valued.v r := rfl @[simp] theorem apply_symm_equiv (r : R) : Valued.v ((equiv v).symm r) = v r := rfl end Ring section CommRing variable [CommRing R] (v : Valuation R Γ₀) instance : ValuativeRel (WithVal v) := .ofValuation (valuation v) instance : (valuation v).Compatible := .ofValuation (valuation v) end CommRing end WithVal /-! The completion of a field with respect to a valuation. -/ namespace Valuation open WithVal variable {R : Type*} [Ring R] (v : Valuation R Γ₀) /-- The completion of a field with respect to a valuation. -/ abbrev Completion := UniformSpace.Completion (WithVal v) instance : Coe R v.Completion := inferInstanceAs <| Coe (WithVal v) (UniformSpace.Completion (WithVal v)) end Valuation namespace NumberField.RingOfIntegers variable {K : Type*} [Field K] [NumberField K] (v : Valuation K Γ₀) instance : CoeHead (𝓞 (WithVal v)) (WithVal v) := inferInstanceAs (CoeHead (𝓞 K) K) instance : IsDedekindDomain (𝓞 (WithVal v)) := inferInstanceAs (IsDedekindDomain (𝓞 K)) instance (R : Type*) [CommRing R] [Algebra R K] [IsIntegralClosure R ℤ K] : IsIntegralClosure R ℤ (WithVal v) := ‹IsIntegralClosure R ℤ K› /-- The ring equivalence between `𝓞 (WithVal v)` and an integral closure of `ℤ` in `K`. -/ @[simps!] def withValEquiv (R : Type*) [CommRing R] [Algebra R K] [IsIntegralClosure R ℤ K] : 𝓞 (WithVal v) ≃+* R := NumberField.RingOfIntegers.equiv R end NumberField.RingOfIntegers open scoped NumberField in /-- The ring of integers of `WithVal v`, when `v` is a valuation on `ℚ`, is equivalent to `ℤ`. -/ @[simps! apply] def Rat.ringOfIntegersWithValEquiv (v : Valuation ℚ Γ₀) : 𝓞 (WithVal v) ≃+* ℤ := NumberField.RingOfIntegers.withValEquiv v ℤ
.lake/packages/mathlib/Mathlib/Topology/Algebra/Valued/NormedValued.lean
import Mathlib.Analysis.Normed.Field.Basic import Mathlib.Analysis.Normed.Group.Ultra import Mathlib.RingTheory.Valuation.RankOne import Mathlib.Topology.Algebra.Valued.ValuationTopology /-! # Correspondence between nontrivial nonarchimedean norms and rank one valuations Nontrivial nonarchimedean norms correspond to rank one valuations. ## Main Definitions * `NormedField.toValued` : the valued field structure on a nonarchimedean normed field `K`, determined by the norm. * `Valued.toNormedField` : the normed field structure determined by a rank one valuation. ## Tags norm, nonarchimedean, nontrivial, valuation, rank one -/ noncomputable section open Filter Set Valuation open scoped NNReal section variable {K : Type*} [hK : NormedField K] [IsUltrametricDist K] namespace NormedField /-- The valuation on a nonarchimedean normed field `K` defined as `nnnorm`. -/ def valuation : Valuation K ℝ≥0 where toFun := nnnorm map_zero' := nnnorm_zero map_one' := nnnorm_one map_mul' := nnnorm_mul map_add_le_max' := IsUltrametricDist.norm_add_le_max @[simp] theorem valuation_apply (x : K) : valuation x = ‖x‖₊ := rfl /-- The valued field structure on a nonarchimedean normed field `K`, determined by the norm. -/ def toValued : Valued K ℝ≥0 := { hK.toUniformSpace, inferInstanceAs (IsUniformAddGroup K) with v := valuation is_topological_valuation := fun U => by rw [Metric.mem_nhds_iff] exact ⟨fun ⟨ε, hε, h⟩ => ⟨Units.mk0 ⟨ε, le_of_lt hε⟩ (ne_of_gt hε), fun x hx ↦ h (mem_ball_zero_iff.mpr hx)⟩, fun ⟨ε, hε⟩ => ⟨(ε : ℝ), NNReal.coe_pos.mpr (Units.zero_lt _), fun x hx ↦ hε (mem_ball_zero_iff.mp hx)⟩⟩ } instance {K : Type*} [NontriviallyNormedField K] [IsUltrametricDist K] : Valuation.RankOne (valuation (K := K)) where hom := .id _ strictMono' := strictMono_id exists_val_nontrivial := (exists_one_lt_norm K).imp fun x h ↦ by have h' : x ≠ 0 := norm_eq_zero.not.mp (h.gt.trans' (by simp)).ne' simp [valuation_apply, ← NNReal.coe_inj, h.ne', h'] end NormedField end namespace Valued variable {L : Type*} [Field L] {Γ₀ : Type*} [LinearOrderedCommGroupWithZero Γ₀] [val : Valued L Γ₀] [hv : RankOne val.v] /-- The norm function determined by a rank one valuation on a field `L`. -/ def norm : L → ℝ := fun x : L => hv.hom (Valued.v x) theorem norm_def {x : L} : Valued.norm x = hv.hom (Valued.v x) := rfl theorem norm_nonneg (x : L) : 0 ≤ norm x := by simp only [norm, NNReal.zero_le_coe] theorem norm_add_le (x y : L) : norm (x + y) ≤ max (norm x) (norm y) := by simp only [norm, NNReal.coe_le_coe, le_max_iff, StrictMono.le_iff_le hv.strictMono] exact le_max_iff.mp (Valuation.map_add_le_max' val.v _ _) theorem norm_eq_zero {x : L} (hx : norm x = 0) : x = 0 := by simpa [norm, NNReal.coe_eq_zero, RankOne.hom_eq_zero_iff, zero_iff] using hx theorem norm_pos_iff_valuation_pos {x : L} : 0 < Valued.norm x ↔ (0 : Γ₀) < v x := by rw [norm_def, ← NNReal.coe_zero, NNReal.coe_lt_coe, ← map_zero (RankOne.hom (v (R := L))), StrictMono.lt_iff_lt] exact RankOne.strictMono v variable (L) (Γ₀) /-- The normed field structure determined by a rank one valuation. -/ def toNormedField : NormedField L := { (inferInstance : Field L) with norm := norm dist := fun x y => norm (x - y) dist_self := fun x => by simp only [sub_self, norm, Valuation.map_zero, hv.hom.map_zero, NNReal.coe_zero] dist_comm := fun x y => by simp only [norm]; rw [← neg_sub, Valuation.map_neg] dist_triangle := fun x y z => by simp only [← sub_add_sub_cancel x y z] exact le_trans (norm_add_le _ _) (max_le_add_of_nonneg (norm_nonneg _) (norm_nonneg _)) eq_of_dist_eq_zero := fun hxy => eq_of_sub_eq_zero (norm_eq_zero hxy) dist_eq := fun x y => rfl norm_mul := fun x y => by simp only [norm, ← NNReal.coe_mul, map_mul] toUniformSpace := Valued.toUniformSpace uniformity_dist := by haveI : Nonempty { ε : ℝ // ε > 0 } := nonempty_Ioi_subtype ext U rw [hasBasis_iff.mp (Valued.hasBasis_uniformity L Γ₀), iInf_subtype', mem_iInf_of_directed] · simp only [true_and, mem_principal, Subtype.exists, gt_iff_lt, exists_prop] refine ⟨fun ⟨ε, hε⟩ => ?_, fun ⟨r, hr_pos, hr⟩ => ?_⟩ · set δ : ℝ≥0 := hv.hom ε with hδ have hδ_pos : 0 < δ := by rw [hδ, ← map_zero hv.hom] exact hv.strictMono _ (Units.zero_lt ε) use δ, hδ_pos apply subset_trans _ hε intro x hx simp only [mem_setOf_eq, norm, hδ, NNReal.coe_lt_coe] at hx rw [mem_setOf, ← neg_sub, Valuation.map_neg] exact (RankOne.strictMono Valued.v).lt_iff_lt.mp hx · haveI : Nontrivial Γ₀ˣ := (nontrivial_iff_exists_ne (1 : Γ₀ˣ)).mpr ⟨RankOne.unit val.v, RankOne.unit_ne_one val.v⟩ obtain ⟨u, hu⟩ := Real.exists_lt_of_strictMono hv.strictMono hr_pos use u apply subset_trans _ hr intro x hx simp only [norm, mem_setOf_eq] apply lt_trans _ hu rw [NNReal.coe_lt_coe, ← neg_sub, Valuation.map_neg] exact (RankOne.strictMono Valued.v).lt_iff_lt.mpr hx · simp only [Directed] intro x y use min x y simp only [le_principal_iff, mem_principal, setOf_subset_setOf, Prod.forall] exact ⟨fun a b hab => lt_of_lt_of_le hab (min_le_left _ _), fun a b hab => lt_of_lt_of_le hab (min_le_right _ _)⟩ } -- When a field is valued, one inherits a `NormedField`. -- Scoped instance to avoid a typeclass loop or non-defeq topology or norms. scoped[Valued] attribute [instance] Valued.toNormedField scoped[NormedField] attribute [instance] NormedField.toValued section NormedField open scoped Valued protected lemma isNonarchimedean_norm : IsNonarchimedean ((‖·‖) : L → ℝ) := Valued.norm_add_le instance : IsUltrametricDist L := ⟨fun x y z ↦ by refine (Valued.norm_add_le (x - y) (y - z)).trans_eq' ?_ simp only [sub_add_sub_cancel] rfl ⟩ lemma coe_valuation_eq_rankOne_hom_comp_valuation : ⇑NormedField.valuation = hv.hom ∘ val.v := rfl end NormedField variable {L} {Γ₀} namespace toNormedField variable {x x' : L} @[simp] theorem norm_le_iff : ‖x‖ ≤ ‖x'‖ ↔ val.v x ≤ val.v x' := (Valuation.RankOne.strictMono val.v).le_iff_le @[simp] theorem norm_lt_iff : ‖x‖ < ‖x'‖ ↔ val.v x < val.v x' := (Valuation.RankOne.strictMono val.v).lt_iff_lt @[simp] theorem norm_le_one_iff : ‖x‖ ≤ 1 ↔ val.v x ≤ 1 := by simpa only [map_one] using (Valuation.RankOne.strictMono val.v).le_iff_le (b := 1) @[simp] theorem norm_lt_one_iff : ‖x‖ < 1 ↔ val.v x < 1 := by simpa only [map_one] using (Valuation.RankOne.strictMono val.v).lt_iff_lt (b := 1) @[simp] theorem one_le_norm_iff : 1 ≤ ‖x‖ ↔ 1 ≤ val.v x := by simpa only [map_one] using (Valuation.RankOne.strictMono val.v).le_iff_le (a := 1) @[simp] theorem one_lt_norm_iff : 1 < ‖x‖ ↔ 1 < val.v x := by simpa only [map_one] using (Valuation.RankOne.strictMono val.v).lt_iff_lt (a := 1) lemma setOf_mem_integer_eq_closedBall : { x : L | x ∈ Valued.v.integer } = Metric.closedBall 0 1 := by ext x simp [mem_integer_iff] end toNormedField /-- The nontrivially normed field structure determined by a rank one valuation. -/ def toNontriviallyNormedField : NontriviallyNormedField L := { val.toNormedField with non_trivial := by obtain ⟨x, hx⟩ := Valuation.RankOne.nontrivial val.v rcases Valuation.val_le_one_or_val_inv_le_one val.v x with h | h · use x⁻¹ simp only [toNormedField.one_lt_norm_iff, map_inv₀, one_lt_inv₀ (zero_lt_iff.mpr hx.1), lt_of_le_of_ne h hx.2] · use x simp only [map_inv₀, inv_le_one₀ <| zero_lt_iff.mpr hx.1] at h simp only [toNormedField.one_lt_norm_iff, lt_of_le_of_ne h hx.2.symm] } scoped[Valued] attribute [instance] Valued.toNontriviallyNormedField end Valued
.lake/packages/mathlib/Mathlib/Topology/Algebra/Valued/LocallyCompact.lean
import Mathlib.Analysis.Normed.Field.Lemmas import Mathlib.Analysis.Normed.Field.ProperSpace import Mathlib.RingTheory.DiscreteValuationRing.Basic import Mathlib.RingTheory.Ideal.IsPrincipalPowQuotient import Mathlib.RingTheory.Valuation.Archimedean import Mathlib.Topology.Algebra.Valued.NormedValued import Mathlib.Topology.Algebra.Valued.ValuedField /-! # Necessary and sufficient conditions for a locally compact valued field ## Main Definitions * `totallyBounded_iff_finite_residueField`: when the valuation ring is a DVR, it is totally bounded iff the residue field is finite. ## Tags norm, nonarchimedean, rank one, compact, locally compact -/ open NNReal section NormedField open scoped NormedField variable {K : Type*} [NontriviallyNormedField K] [IsUltrametricDist K] @[simp] lemma NormedField.v_eq_valuation (x : K) : Valued.v x = NormedField.valuation x := rfl namespace Valued.integer -- should we do this all in the Valuation namespace instead? /-- An element is in the valuation ring if the norm is bounded by 1. This is a variant of `Valuation.mem_integer_iff`, phrased using norms instead of the valuation. -/ lemma mem_iff {x : K} : x ∈ 𝒪[K] ↔ ‖x‖ ≤ 1 := by simp [Valuation.mem_integer_iff, ← NNReal.coe_le_coe] lemma norm_le_one (x : 𝒪[K]) : ‖x‖ ≤ 1 := mem_iff.mp x.prop @[simp] lemma norm_coe_unit (u : 𝒪[K]ˣ) : ‖((u : 𝒪[K]) : K)‖ = 1 := by simpa [← NNReal.coe_inj] using (Valuation.integer.integers (NormedField.valuation (K := K))).valuation_unit u lemma norm_unit (u : 𝒪[K]ˣ) : ‖(u : 𝒪[K])‖ = 1 := by simp lemma isUnit_iff_norm_eq_one {u : 𝒪[K]} : IsUnit u ↔ ‖u‖ = 1 := by simpa [← NNReal.coe_inj] using (Valuation.integer.integers (NormedField.valuation (K := K))).isUnit_iff_valuation_eq_one lemma norm_irreducible_lt_one {ϖ : 𝒪[K]} (h : Irreducible ϖ) : ‖ϖ‖ < 1 := Valuation.integer.v_irreducible_lt_one h lemma norm_irreducible_pos {ϖ : 𝒪[K]} (h : Irreducible ϖ) : 0 < ‖ϖ‖ := Valuation.integer.v_irreducible_pos h lemma coe_span_singleton_eq_closedBall (x : 𝒪[K]) : (Ideal.span {x} : Set 𝒪[K]) = Metric.closedBall 0 ‖x‖ := by simp [Valuation.integer.coe_span_singleton_eq_setOf_le_v_coe, Set.ext_iff, ← NNReal.coe_le_coe] lemma _root_.Irreducible.maximalIdeal_eq_closedBall [IsDiscreteValuationRing 𝒪[K]] {ϖ : 𝒪[K]} (h : Irreducible ϖ) : (𝓂[K] : Set 𝒪[K]) = Metric.closedBall 0 ‖ϖ‖ := by simp [h.maximalIdeal_eq_setOf_le_v_coe, Set.ext_iff, ← NNReal.coe_le_coe] lemma _root_.Irreducible.maximalIdeal_pow_eq_closedBall_pow [IsDiscreteValuationRing 𝒪[K]] {ϖ : 𝒪[K]} (h : Irreducible ϖ) (n : ℕ) : ((𝓂[K] ^ n : Ideal 𝒪[K]) : Set 𝒪[K]) = Metric.closedBall 0 (‖ϖ‖ ^ n) := by simp [h.maximalIdeal_pow_eq_setOf_le_v_coe_pow, Set.ext_iff, ← NNReal.coe_le_coe] variable (K) in lemma exists_norm_coe_lt_one : ∃ x : 𝒪[K], 0 < ‖(x : K)‖ ∧ ‖(x : K)‖ < 1 := by obtain ⟨x, hx, hx'⟩ := NormedField.exists_norm_lt_one K refine ⟨⟨x, hx'.le⟩, ?_⟩ simpa [hx', Subtype.ext_iff] using hx variable (K) in lemma exists_norm_lt_one : ∃ x : 𝒪[K], 0 < ‖x‖ ∧ ‖x‖ < 1 := exists_norm_coe_lt_one K variable (K) in lemma exists_nnnorm_lt_one : ∃ x : 𝒪[K], 0 < ‖x‖₊ ∧ ‖x‖₊ < 1 := exists_norm_coe_lt_one K end Valued.integer end NormedField namespace Valued.integer variable {K Γ₀ : Type*} [Field K] [LinearOrderedCommGroupWithZero Γ₀] [Valued K Γ₀] section FiniteResidueField open Valued lemma finite_quotient_maximalIdeal_pow_of_finite_residueField [IsDiscreteValuationRing 𝒪[K]] (h : Finite 𝓀[K]) (n : ℕ) : Finite (𝒪[K] ⧸ 𝓂[K] ^ n) := by induction n with | zero => simp only [pow_zero, Ideal.one_eq_top] exact Finite.of_fintype (↥𝒪[K] ⧸ ⊤) | succ n ih => have : 𝓂[K] ^ (n + 1) ≤ 𝓂[K] ^ n := Ideal.pow_le_pow_right (by simp) replace ih := Finite.of_equiv _ (DoubleQuot.quotQuotEquivQuotOfLE this).symm.toEquiv suffices Finite (Ideal.map (Ideal.Quotient.mk (𝓂[K] ^ (n + 1))) (𝓂[K] ^ n)) from .of_ideal_quotient (.map (Ideal.Quotient.mk _) (𝓂[K] ^ n)) exact @Finite.of_equiv _ _ h ((Ideal.quotEquivPowQuotPowSuccEquiv (IsPrincipalIdealRing.principal 𝓂[K]) (IsDiscreteValuationRing.not_a_field _) n).trans (Ideal.powQuotPowSuccEquivMapMkPowSuccPow _ n)) open scoped Valued lemma totallyBounded_iff_finite_residueField [(Valued.v : Valuation K Γ₀).RankOne] [IsDiscreteValuationRing 𝒪[K]] : TotallyBounded (Set.univ (α := 𝒪[K])) ↔ Finite 𝓀[K] := by constructor · intro H obtain ⟨p, hp⟩ := IsDiscreteValuationRing.exists_irreducible 𝒪[K] have := Metric.finite_approx_of_totallyBounded H ‖p‖ (norm_pos_iff.mpr hp.ne_zero) simp only [Set.subset_univ, Set.univ_subset_iff, true_and] at this obtain ⟨t, ht, ht'⟩ := this rw [← Set.finite_univ_iff] refine (ht.image (IsLocalRing.residue _)).subset ?_ rintro ⟨x⟩ replace ht' := ht'.ge (Set.mem_univ x) simp only [Set.mem_iUnion, Metric.mem_ball, exists_prop] at ht' obtain ⟨y, hy, hy'⟩ := ht' simp only [Submodule.Quotient.quot_mk_eq_mk, Ideal.Quotient.mk_eq_mk, Set.mem_univ, IsLocalRing.residue, Set.mem_image, true_implies] refine ⟨y, hy, ?_⟩ convert (Ideal.Quotient.mk_eq_mk_iff_sub_mem (I := 𝓂[K]) y x).mpr _ -- TODO: make Valued.maximalIdeal abbreviations instead of def rw [Valued.maximalIdeal, hp.maximalIdeal_eq, ← SetLike.mem_coe, (Valuation.integer.integers _).coe_span_singleton_eq_setOf_le_v_algebraMap] rw [dist_comm] at hy' simpa [dist_eq_norm] using hy'.le · intro H rw [Metric.totallyBounded_iff] intro ε εpos obtain ⟨p, hp⟩ := IsDiscreteValuationRing.exists_irreducible 𝒪[K] have hp' := Valuation.integer.v_irreducible_lt_one hp obtain ⟨n, hn⟩ : ∃ n : ℕ, ‖(p : K)‖ ^ n < ε := exists_pow_lt_of_lt_one εpos (toNormedField.norm_lt_one_iff.mpr hp') have hF := finite_quotient_maximalIdeal_pow_of_finite_residueField H n refine ⟨Quotient.out '' (Set.univ (α := 𝒪[K] ⧸ (𝓂[K] ^ n))), Set.toFinite _, ?_⟩ have : {y : 𝒪[K] | v (y : K) ≤ v (p : K) ^ n} = Metric.closedBall 0 (‖p‖ ^ n) := by ext simp [← norm_pow] simp only [Ideal.univ_eq_iUnion_image_add (𝓂[K] ^ n), hp.maximalIdeal_pow_eq_setOf_le_v_coe_pow, this, AddSubgroupClass.coe_norm, Set.image_univ, Set.mem_range, Set.iUnion_exists, Set.iUnion_iUnion_eq', Set.iUnion_subset_iff, Metric.vadd_closedBall, vadd_eq_add, add_zero] intro exact (Metric.closedBall_subset_ball hn).trans (Set.subset_iUnion_of_subset _ le_rfl) end FiniteResidueField section CompactDVR open Valued lemma locallyFiniteOrder_units_mrange_of_isCompact_integer (hc : IsCompact (X := K) 𝒪[K]) : Nonempty (LocallyFiniteOrder (MonoidHom.mrange (Valued.v : Valuation K Γ₀))ˣ):= by -- TODO: generalize to `Valuation.Integer`, which will require showing that `IsCompact` -- pulls back across `TopologicalSpace.induced` from a `LocallyCompactSpace`. constructor refine LocallyFiniteOrder.ofFiniteIcc ?_ -- We only need to show that we can construct a finite set for some set between -- a non-zero `z : Γ₀` and 1, because we can scale/invert this set to cover the whole group. suffices ∀ z : (MonoidHom.mrange (Valued.v : Valuation K Γ₀))ˣ, (Set.Icc z 1).Finite by rintro x y rcases lt_trichotomy y x with hxy | rfl | hxy · rw [Set.Icc_eq_empty_of_lt] · exact Set.finite_empty · simp [hxy] · simp wlog h : x ≤ 1 generalizing x y · push_neg at h specialize this y⁻¹ x⁻¹ (inv_lt_inv' hxy) (inv_le_one_of_one_le (h.trans hxy).le) refine (this.inv).subset ?_ rw [Set.inv_Icc] intro simp +contextual generalize_proofs _ _ _ _ hxu hyu rcases le_total y 1 with hy | hy · exact (this x).subset (Set.Icc_subset_Icc_right hy) · have H : (Set.Icc y⁻¹ 1).Finite := this _ refine ((this x).union H.inv).subset (le_of_eq ?_) rw [Set.inv_Icc, inv_one, Set.Icc_union_Icc_eq_Icc] <;> simp [h, hy] -- We can construct a family of spheres at every single element of the valuation ring -- outside of a closed ball, which will cover. -- Since we are in a compact space, this cover has a finite subcover. -- First, we need to pick a threshold element with a nontrivial valuation less than 1, -- which will form -- the inner closed ball of the cover, which we need to cover 0. intro z obtain ⟨a, ha⟩ := z.val.prop rcases lt_or_ge 1 z with hz1 | hz1 · rw [Set.Icc_eq_empty_of_lt] · exact Set.finite_empty · simp [hz1] have z0' : 0 < (z : MonoidHom.mrange (Valued.v : Valuation K Γ₀)) := by simp have z0 : 0 < ((z : MonoidHom.mrange (Valued.v : Valuation K Γ₀)) : Γ₀) := Subtype.coe_lt_coe.mpr z0' have a0 : 0 < v a := by simp [ha, z0] -- Construct our cover, which has an inner closed ball, and spheres for each element -- outside of the closed ball. These are all open sets by the nonarchimedean property. let U : K → Set K := fun y ↦ if v (y : K) ≤ z then {w | v (w : K) ≤ z} else {w | v (w : K) = v (y : K)} have := hc.elim_finite_subcover U specialize this ?_ ?_ · intro w simp only [U] split_ifs with hw · exact Valued.isOpen_closedBall _ z0.ne' · refine Valued.isOpen_sphere _ ?_ push_neg at hw refine (hw.trans' ?_).ne' simp [z0] · intro w simp only [integer, SetLike.mem_coe, Valuation.mem_integer_iff, Set.mem_iUnion, U] intro hw use if v w ≤ z then a else w split_ifs <;> simp_all -- For each element of the valuation ring that is bigger than our threshold element above, -- there must be something in the cover that has the precise valuation of the element, -- because it must be outside the inner closed ball, and thus is covered by some sphere. obtain ⟨t, ht⟩ := this classical refine (t.finite_toSet.dependent_image ?_).subset ?_ · refine fun i hi ↦ if hi' : v i ≤ z then z else Units.mk0 ⟨(v i), by simp⟩ ?_ push_neg at hi' exact Subtype.coe_injective.ne_iff.mp (hi'.trans' z0).ne' · intro i simp only [Set.mem_Icc, Finset.mem_coe, exists_prop, Set.mem_setOf_eq, and_imp] -- we get the `c` from the cover that covers our arbitrary `i` with its set obtain ⟨c, hc⟩ := i.val.prop intro hzi hi1 have hj := ht (hc.trans_le hi1) simp only [Set.mem_iUnion, exists_prop, U] at hj obtain ⟨j, hj, hj'⟩ := hj use j, hj -- and this `c` is either less than or greater than (or equal to) the threshold element split_ifs at hj' with hcj · simp only [Set.mem_setOf_eq, hc, Subtype.coe_le_coe, Units.val_le_val] at hj' simp [hcj, le_antisymm hj' hzi] · simp only [Set.mem_setOf_eq] at hj' rw [dif_neg hcj] simp [← hj', hc] lemma mulArchimedean_mrange_of_isCompact_integer (hc : IsCompact (X := K) 𝒪[K]) : MulArchimedean (MonoidHom.mrange (Valued.v : Valuation K Γ₀)) := by rw [← Units.mulArchimedean_iff] obtain ⟨_⟩ := locallyFiniteOrder_units_mrange_of_isCompact_integer hc exact MulArchimedean.of_locallyFiniteOrder lemma isPrincipalIdealRing_of_compactSpace [hc : CompactSpace 𝒪[K]] : IsPrincipalIdealRing 𝒪[K] := by -- The strategy to show that we have a PIR is by contradiction, -- assuming that the range of the valuation is densely ordered. have hi : Valuation.Integers (R := K) Valued.v 𝒪[K] := Valuation.integer.integers v have hc : IsCompact (X := K) 𝒪[K] := isCompact_iff_compactSpace.mpr hc -- We can also construct that it has a locally finite order, by compactness -- which leads to a contradiction. obtain ⟨_⟩ := locallyFiniteOrder_units_mrange_of_isCompact_integer hc have hm := mulArchimedean_mrange_of_isCompact_integer hc -- The key result is that a valuation ring that maps into a `MulArchimedean` value group -- is a PIR iff the value group is not densely ordered. refine hi.isPrincipalIdealRing_iff_not_denselyOrdered_mrange.mpr fun _ ↦ ?_ -- since we are densely ordered, we necessarily are nontrivial exact not_subsingleton (MonoidHom.mrange (v : Valuation K Γ₀))ˣ (LocallyFiniteOrder.denselyOrdered_iff_subsingleton.mp inferInstance) theorem _root_.Valuation.isNontrivial_iff_not_a_field {K Γ : Type*} [Field K] [LinearOrderedCommGroupWithZero Γ] (v : Valuation K Γ) : v.IsNontrivial ↔ IsLocalRing.maximalIdeal v.integer ≠ ⊥ := by simp_rw [ne_eq, eq_bot_iff, v.isNontrivial_iff_exists_lt_one, SetLike.le_def, Ideal.mem_bot, not_forall, exists_prop, IsLocalRing.notMem_maximalIdeal.not_right, Valuation.Integer.not_isUnit_iff_valuation_lt_one] exact ⟨fun ⟨x, hx0, hx1⟩ ↦ ⟨⟨x, hx1.le⟩, by simp [Subtype.ext_iff, *]⟩, fun ⟨x, hx1, hx0⟩ ↦ ⟨x, by simp [*]⟩⟩ lemma isDiscreteValuationRing_of_compactSpace [hn : (Valued.v : Valuation K Γ₀).IsNontrivial] [CompactSpace 𝒪[K]] : IsDiscreteValuationRing 𝒪[K] where -- To prove we have a DVR, we need to show it is -- a local ring (instance is directly inferred) and a PIR and not a field. __ := isPrincipalIdealRing_of_compactSpace not_a_field' := v.isNontrivial_iff_not_a_field.mp hn end CompactDVR lemma compactSpace_iff_completeSpace_and_isDiscreteValuationRing_and_finite_residueField [(Valued.v : Valuation K Γ₀).RankOne] : CompactSpace 𝒪[K] ↔ CompleteSpace 𝒪[K] ∧ IsDiscreteValuationRing 𝒪[K] ∧ Finite 𝓀[K] := by refine ⟨fun h ↦ ?_, fun ⟨_, _, h⟩ ↦ ⟨?_⟩⟩ · have : IsDiscreteValuationRing 𝒪[K] := isDiscreteValuationRing_of_compactSpace refine ⟨complete_of_compact, by assumption, ?_⟩ rw [← isCompact_univ_iff, isCompact_iff_totallyBounded_isComplete, totallyBounded_iff_finite_residueField] at h exact h.left · rw [← totallyBounded_iff_finite_residueField] at h rw [isCompact_iff_totallyBounded_isComplete] exact ⟨h, completeSpace_iff_isComplete_univ.mp ‹_›⟩ lemma properSpace_iff_compactSpace_integer [(Valued.v : Valuation K Γ₀).RankOne] : ProperSpace K ↔ CompactSpace 𝒪[K] := by simp only [← isCompact_univ_iff, Subtype.isCompact_iff, Set.image_univ, Subtype.range_coe_subtype, toNormedField.setOf_mem_integer_eq_closedBall] constructor <;> intro h · exact isCompact_closedBall 0 1 · suffices LocallyCompactSpace K from .of_nontriviallyNormedField_of_weaklyLocallyCompactSpace K exact IsCompact.locallyCompactSpace_of_mem_nhds_of_addGroup h <| Metric.closedBall_mem_nhds 0 zero_lt_one lemma properSpace_iff_completeSpace_and_isDiscreteValuationRing_integer_and_finite_residueField [(Valued.v : Valuation K Γ₀).RankOne] : ProperSpace K ↔ CompleteSpace K ∧ IsDiscreteValuationRing 𝒪[K] ∧ Finite 𝓀[K] := by simp only [properSpace_iff_compactSpace_integer, compactSpace_iff_completeSpace_and_isDiscreteValuationRing_and_finite_residueField, toNormedField.setOf_mem_integer_eq_closedBall, completeSpace_iff_isComplete_univ (α := 𝒪[K]), Subtype.isComplete_iff, NormedField.completeSpace_iff_isComplete_closedBall, Set.image_univ, Subtype.range_coe_subtype] end Valued.integer
.lake/packages/mathlib/Mathlib/Topology/Algebra/Valued/ValuativeRel.lean
import Mathlib.RingTheory.Valuation.ValuativeRel.Basic import Mathlib.Topology.Algebra.Valued.ValuationTopology import Mathlib.Topology.Algebra.WithZeroTopology /-! # Valuative Relations as Valued In this temporary file, we provide a helper instance for `Valued R Γ` derived from a `ValuativeRel R`, so that downstream files can refer to `ValuativeRel R`, to facilitate a refactor. -/ namespace IsValuativeTopology section /-! ### Alternate constructors -/ variable {R : Type*} [CommRing R] [ValuativeRel R] [TopologicalSpace R] open ValuativeRel TopologicalSpace Filter Topology Set local notation "v" => valuation R /-- Assuming `ContinuousConstVAdd R R`, we only need to check the neighbourhood of `0` in order to prove `IsValuativeTopology R`. -/ theorem of_zero [ContinuousConstVAdd R R] (h₀ : ∀ s : Set R, s ∈ 𝓝 0 ↔ ∃ γ : (ValueGroupWithZero R)ˣ, { z | v z < γ } ⊆ s) : IsValuativeTopology R where mem_nhds_iff {s x} := by simpa [← vadd_mem_nhds_vadd_iff (t := s) (-x), ← image_vadd, ← image_subset_iff] using h₀ ((x + ·) ⁻¹' s) end variable {R : Type*} [CommRing R] [ValuativeRel R] [TopologicalSpace R] [IsValuativeTopology R] open ValuativeRel TopologicalSpace Filter Topology Set local notation "v" => valuation R /-- A version mentioning subtraction. -/ lemma mem_nhds_iff' {s : Set R} {x : R} : s ∈ 𝓝 (x : R) ↔ ∃ γ : (ValueGroupWithZero R)ˣ, { z | v (z - x) < γ } ⊆ s := by convert mem_nhds_iff (s := s) using 4 ext z simp [neg_add_eq_sub] @[deprecated (since := "2025-08-01")] alias _root_.ValuativeTopology.mem_nhds := mem_nhds_iff' lemma mem_nhds_zero_iff (s : Set R) : s ∈ 𝓝 (0 : R) ↔ ∃ γ : (ValueGroupWithZero R)ˣ, { x | v x < γ } ⊆ s := by convert IsValuativeTopology.mem_nhds_iff' (x := (0 : R)) rw [sub_zero] @[deprecated (since := "2025-08-04")] alias _root_.ValuativeTopology.mem_nhds_iff := mem_nhds_zero_iff /-- Helper `Valued` instance when `ValuativeTopology R` over a `UniformSpace R`, for use in porting files from `Valued` to `ValuativeRel`. -/ instance (priority := low) {R : Type*} [CommRing R] [ValuativeRel R] [UniformSpace R] [IsUniformAddGroup R] [IsValuativeTopology R] : Valued R (ValueGroupWithZero R) where «v» := valuation R is_topological_valuation := mem_nhds_zero_iff lemma v_eq_valuation {R : Type*} [CommRing R] [ValuativeRel R] [UniformSpace R] [IsUniformAddGroup R] [IsValuativeTopology R] : Valued.v = valuation R := rfl theorem hasBasis_nhds (x : R) : (𝓝 x).HasBasis (fun _ => True) fun γ : (ValueGroupWithZero R)ˣ => { z | v (z - x) < γ } := by simp [Filter.hasBasis_iff, mem_nhds_iff'] /-- A variant of `hasBasis_nhds` where `· ≠ 0` is unbundled. -/ lemma hasBasis_nhds' (x : R) : (𝓝 x).HasBasis (· ≠ 0) ({ y | v (y - x) < · }) := (hasBasis_nhds x).to_hasBasis (fun γ _ ↦ ⟨γ, by simp⟩) fun γ hγ ↦ ⟨.mk0 γ hγ, by simp⟩ variable (R) in theorem hasBasis_nhds_zero : (𝓝 (0 : R)).HasBasis (fun _ => True) fun γ : (ValueGroupWithZero R)ˣ => { x | v x < γ } := by convert hasBasis_nhds (0 : R); rw [sub_zero] variable (R) in /-- A variant of `hasBasis_nhds_zero` where `· ≠ 0` is unbundled. -/ lemma hasBasis_nhds_zero' : (𝓝 0).HasBasis (· ≠ 0) ({ x | v x < · }) := (hasBasis_nhds_zero R).to_hasBasis (fun γ _ ↦ ⟨γ, by simp⟩) fun γ hγ ↦ ⟨.mk0 γ hγ, by simp⟩ @[deprecated (since := "2025-08-01")] alias _root_.ValuativeTopology.hasBasis_nhds_zero := hasBasis_nhds_zero variable (R) in instance (priority := low) isTopologicalAddGroup : IsTopologicalAddGroup R := by have cts_add : ContinuousConstVAdd R R := ⟨fun x ↦ continuous_iff_continuousAt.2 fun z ↦ ((hasBasis_nhds z).tendsto_iff (hasBasis_nhds (x + z))).2 fun γ _ ↦ ⟨γ, trivial, fun y hy ↦ by simpa using hy⟩⟩ have basis := hasBasis_nhds_zero R refine .of_comm_of_nhds_zero ?_ ?_ fun x₀ ↦ (map_eq_of_inverse (-x₀ + ·) ?_ ?_ ?_).symm · exact (basis.prod_self.tendsto_iff basis).2 fun γ _ ↦ ⟨γ, trivial, fun ⟨_, _⟩ hx ↦ (v).map_add_lt hx.left hx.right⟩ · exact (basis.tendsto_iff basis).2 fun γ _ ↦ ⟨γ, trivial, fun y hy ↦ by simpa using hy⟩ · ext; simp · simpa [ContinuousAt] using (cts_add.1 x₀).continuousAt (x := (0 : R)) · simpa [ContinuousAt] using (cts_add.1 (-x₀)).continuousAt (x := x₀) instance (priority := low) : IsTopologicalRing R := letI := IsTopologicalAddGroup.rightUniformSpace R letI := isUniformAddGroup_of_addCommGroup (G := R) inferInstance theorem isOpen_ball (r : ValueGroupWithZero R) : IsOpen {x | v x < r} := by rw [isOpen_iff_mem_nhds] rcases eq_or_ne r 0 with rfl | hr · simp · intro x hx rw [mem_nhds_iff'] simp only [setOf_subset_setOf] exact ⟨Units.mk0 _ hr, fun y hy => (sub_add_cancel y x).symm ▸ ((v).map_add _ x).trans_lt (max_lt hy hx)⟩ @[deprecated (since := "2025-08-01")] alias _root_.ValuativeTopology.isOpen_ball := isOpen_ball theorem isClosed_ball (r : ValueGroupWithZero R) : IsClosed {x | v x < r} := by rcases eq_or_ne r 0 with rfl | hr · simp · exact AddSubgroup.isClosed_of_isOpen (Valuation.ltAddSubgroup v (Units.mk0 r hr)) (isOpen_ball _) @[deprecated (since := "2025-08-01")] alias _root_.ValuativeTopology.isClosed_ball := isClosed_ball theorem isClopen_ball (r : ValueGroupWithZero R) : IsClopen {x | v x < r} := ⟨isClosed_ball _, isOpen_ball _⟩ @[deprecated (since := "2025-08-01")] alias _root_.ValuativeTopology.isClopen_ball := isClopen_ball lemma isOpen_closedBall {r : ValueGroupWithZero R} (hr : r ≠ 0) : IsOpen {x | v x ≤ r} := by rw [isOpen_iff_mem_nhds] intro x hx rw [mem_nhds_iff'] simp only [setOf_subset_setOf] exact ⟨Units.mk0 _ hr, fun y hy => (sub_add_cancel y x).symm ▸ le_trans ((v).map_add _ _) (max_le (le_of_lt hy) hx)⟩ @[deprecated (since := "2025-08-01")] alias _root_.ValuativeTopology.isOpen_closedBall := isOpen_closedBall theorem isClosed_closedBall (r : ValueGroupWithZero R) : IsClosed {x | v x ≤ r} := by rw [← isOpen_compl_iff, isOpen_iff_mem_nhds] intro x hx simp only [mem_compl_iff, mem_setOf_eq, not_le] at hx rw [mem_nhds_iff'] have hx' : v x ≠ 0 := ne_of_gt <| lt_of_le_of_lt zero_le' <| hx exact ⟨Units.mk0 _ hx', fun y hy hy' => ne_of_lt hy <| Valuation.map_sub_swap v x y ▸ (Valuation.map_sub_eq_of_lt_left _ <| lt_of_le_of_lt hy' hx)⟩ @[deprecated (since := "2025-08-01")] alias _root_.ValuativeTopology.isClosed_closedBall := isClosed_closedBall theorem isClopen_closedBall {r : ValueGroupWithZero R} (hr : r ≠ 0) : IsClopen {x | v x ≤ r} := ⟨isClosed_closedBall _, isOpen_closedBall hr⟩ @[deprecated (since := "2025-08-01")] alias _root_.ValuativeTopology.isClopen_closedBall := isClopen_closedBall theorem isClopen_sphere {r : ValueGroupWithZero R} (hr : r ≠ 0) : IsClopen {x | v x = r} := by have h : {x : R | v x = r} = {x | v x ≤ r} \ {x | v x < r} := by ext x simp [← le_antisymm_iff] rw [h] exact IsClopen.diff (isClopen_closedBall hr) (isClopen_ball _) @[deprecated (since := "2025-08-01")] alias _root_.ValuativeTopology.isClopen_sphere := isClopen_sphere lemma isOpen_sphere {r : ValueGroupWithZero R} (hr : r ≠ 0) : IsOpen {x | v x = r} := isClopen_sphere hr |>.isOpen @[deprecated (since := "2025-08-01")] alias _root_.ValuativeTopology.isOpen_sphere := isOpen_sphere open WithZeroTopology in lemma continuous_valuation : Continuous v := by simp only [continuous_iff_continuousAt, ContinuousAt] rintro x by_cases hx : v x = 0 · simpa [hx, (hasBasis_nhds _).tendsto_iff WithZeroTopology.hasBasis_nhds_zero, Valuation.map_sub_of_right_eq_zero _ hx] using fun i hi ↦ ⟨.mk0 i hi, fun y ↦ id⟩ · simpa [(hasBasis_nhds _).tendsto_iff (WithZeroTopology.hasBasis_nhds_of_ne_zero hx)] using ⟨.mk0 (v x) hx, fun _ ↦ Valuation.map_eq_of_sub_lt _⟩ end IsValuativeTopology namespace ValuativeRel @[inherit_doc] scoped notation "𝒪[" R "]" => Valuation.integer (valuation R) @[inherit_doc] scoped notation "𝓂[" K "]" => IsLocalRing.maximalIdeal 𝒪[K] @[inherit_doc] scoped notation "𝓀[" K "]" => IsLocalRing.ResidueField 𝒪[K] end ValuativeRel
.lake/packages/mathlib/Mathlib/Topology/Algebra/Valued/WithZeroMulInt.lean
import Mathlib.GroupTheory.ArchimedeanDensely import Mathlib.Topology.Algebra.Valued.ValuationTopology /-! # Topological results for integer-valued rings This file contains topological results for valuation rings taking values in the multiplicative integers with zero adjoined. These are useful for cases where there is a `Valued R ℤₘ₀` instance but no canonical base with which to embed this into `NNReal`. -/ open Filter WithZero Set open scoped Topology namespace Valued variable {R Γ₀ : Type*} [Ring R] [LinearOrderedCommGroupWithZero Γ₀] -- TODO: use ValuativeRel after https://github.com/leanprover-community/mathlib4/issues/26833 lemma tendsto_zero_pow_of_v_lt_one [MulArchimedean Γ₀] [Valued R Γ₀] {x : R} (hx : v x < 1) : Tendsto (fun n : ℕ ↦ x ^ n) atTop (𝓝 0) := by simp only [(hasBasis_nhds_zero _ _).tendsto_right_iff, mem_setOf_eq, map_pow, eventually_atTop, forall_const] intro y obtain ⟨n, hn⟩ := exists_pow_lt₀ hx y refine ⟨n, fun m hm ↦ ?_⟩ refine hn.trans_le' ?_ exact pow_le_pow_right_of_le_one' hx.le hm /-- In a `ℤᵐ⁰`-valued ring, powers of `x` tend to zero if `v x ≤ exp (-1)`. -/ lemma tendsto_zero_pow_of_le_exp_neg_one [Valued R ℤᵐ⁰] {x : R} (hx : v x ≤ exp (-1)) : Tendsto (fun n : ℕ ↦ x ^ n) atTop (𝓝 0) := by refine tendsto_zero_pow_of_v_lt_one (hx.trans_lt ?_) rw [← exp_zero, exp_lt_exp] simp lemma exists_pow_lt_of_le_exp_neg_one [Valued R ℤᵐ⁰] {x : R} (hx : v x ≤ exp (-1)) (γ : ℤᵐ⁰ˣ) : ∃ n, v x ^ n < γ := by refine exists_pow_lt₀ (hx.trans_lt ?_) _ rw [← exp_zero, exp_lt_exp] simp end Valued
.lake/packages/mathlib/Mathlib/Topology/Algebra/Valued/ValuationTopology.lean
import Mathlib.Algebra.Order.Group.Units import Mathlib.Topology.Algebra.Nonarchimedean.Bases import Mathlib.Topology.Algebra.UniformFilterBasis import Mathlib.RingTheory.Valuation.ValuationSubring /-! # The topology on a valued ring In this file, we define the non-Archimedean topology induced by a valuation on a ring. The main definition is a `Valued` type class which equips a ring with a valuation taking values in a group with zero. Other instances are then deduced from this. *NOTE* (2025-07-02): The `Valued` class defined in this file will eventually get replaced with `ValuativeRel` from `Mathlib.RingTheory.Valuation.ValuativeRel.Basic`. New developments on valued rings/fields should take this into consideration. -/ open scoped Topology uniformity open Set Valuation noncomputable section universe v u variable {R K : Type u} [Ring R] [DivisionRing K] {Γ₀ : Type v} [LinearOrderedCommGroupWithZero Γ₀] namespace Valuation variable (v : Valuation R Γ₀) lemma map_eq_one_of_forall_lt [MulArchimedean Γ₀] {v : Valuation K Γ₀} {r : Γ₀} (hr : r ≠ 0) (h : ∀ x : K, v x ≠ 0 → r < v x) (x : K) (hx : v x ≠ 0) : v x = 1 := by lift r to Γ₀ˣ using IsUnit.mk0 _ hr rcases lt_trichotomy (Units.mk0 _ hx) 1 with H | H | H · obtain ⟨k, hk⟩ := exists_pow_lt H r specialize h (x ^ k) (by simp [hx]) simp [← Units.val_lt_val, ← map_pow, h.not_gt] at hk · simpa [Units.ext_iff] using H · rw [← inv_lt_one'] at H obtain ⟨k, hk⟩ := exists_pow_lt H r specialize h (x ^ (-k : ℤ)) (by simp [hx]) simp only [zpow_neg, zpow_natCast, map_inv₀, map_pow] at h simp [← Units.val_lt_val, h.not_gt, inv_pow] at hk /-- The basis of open subgroups for the topology on a ring determined by a valuation. -/ theorem subgroups_basis : RingSubgroupsBasis fun γ : Γ₀ˣ => (v.ltAddSubgroup γ : AddSubgroup R) := { inter := by rintro γ₀ γ₁ use min γ₀ γ₁ simp only [ltAddSubgroup, Units.min_val, lt_inf_iff, le_inf_iff, AddSubgroup.mk_le_mk, AddSubmonoid.mk_le_mk, AddSubsemigroup.mk_le_mk, setOf_subset_setOf] tauto mul := by rintro γ obtain ⟨γ₀, h⟩ := exists_square_le γ use γ₀ rintro - ⟨r, r_in, s, s_in, rfl⟩ simp only [ltAddSubgroup, AddSubgroup.coe_set_mk, AddSubmonoid.coe_set_mk, AddSubsemigroup.coe_set_mk, mem_setOf_eq] at r_in s_in calc (v (r * s) : Γ₀) = v r * v s := Valuation.map_mul _ _ _ _ < γ₀ * γ₀ := by gcongr <;> exact zero_le' _ ≤ γ := mod_cast h leftMul := by rintro x γ rcases GroupWithZero.eq_zero_or_unit (v x) with (Hx | ⟨γx, Hx⟩) · use (1 : Γ₀ˣ) rintro y _ change v (x * y) < _ rw [Valuation.map_mul, Hx, zero_mul] exact Units.zero_lt γ · use γx⁻¹ * γ rintro y (vy_lt : v y < ↑(γx⁻¹ * γ)) change (v (x * y) : Γ₀) < γ rw [Valuation.map_mul, Hx, mul_comm] rw [Units.val_mul, mul_comm] at vy_lt simpa using mul_inv_lt_of_lt_mul₀ vy_lt rightMul := by rintro x γ rcases GroupWithZero.eq_zero_or_unit (v x) with (Hx | ⟨γx, Hx⟩) · use 1 rintro y _ change v (y * x) < _ rw [Valuation.map_mul, Hx, mul_zero] exact Units.zero_lt γ · use γx⁻¹ * γ rintro y (vy_lt : v y < ↑(γx⁻¹ * γ)) change (v (y * x) : Γ₀) < γ rw [Valuation.map_mul, Hx] rw [Units.val_mul, mul_comm] at vy_lt simpa using mul_inv_lt_of_lt_mul₀ vy_lt } end Valuation /-- A valued ring is a ring that comes equipped with a distinguished valuation. The class `Valued` is designed for the situation that there is a canonical valuation on the ring. TODO: show that there always exists an equivalent valuation taking values in a type belonging to the same universe as the ring. See Note [forgetful inheritance] for why we extend `UniformSpace`, `IsUniformAddGroup`. -/ class Valued (R : Type u) [Ring R] (Γ₀ : outParam (Type v)) [LinearOrderedCommGroupWithZero Γ₀] extends UniformSpace R, IsUniformAddGroup R where v : Valuation R Γ₀ is_topological_valuation : ∀ s, s ∈ 𝓝 (0 : R) ↔ ∃ γ : Γ₀ˣ, { x : R | v x < γ } ⊆ s namespace Valued /-- Alternative `Valued` constructor for use when there is no preferred `UniformSpace` structure. -/ def mk' (v : Valuation R Γ₀) : Valued R Γ₀ := { v toUniformSpace := @IsTopologicalAddGroup.rightUniformSpace R _ v.subgroups_basis.topology _ toIsUniformAddGroup := @isUniformAddGroup_of_addCommGroup _ _ v.subgroups_basis.topology _ is_topological_valuation := by letI := @IsTopologicalAddGroup.rightUniformSpace R _ v.subgroups_basis.topology _ intro s rw [Filter.hasBasis_iff.mp v.subgroups_basis.hasBasis_nhds_zero s] exact exists_congr fun γ => by rw [true_and]; rfl } variable (R Γ₀) variable [_i : Valued R Γ₀] theorem hasBasis_nhds_zero : (𝓝 (0 : R)).HasBasis (fun _ => True) fun γ : Γ₀ˣ => { x | v x < (γ : Γ₀) } := by simp [Filter.hasBasis_iff, is_topological_valuation] open Uniformity in theorem hasBasis_uniformity : (𝓤 R).HasBasis (fun _ => True) fun γ : Γ₀ˣ => { p : R × R | v (p.2 - p.1) < (γ : Γ₀) } := by rw [uniformity_eq_comap_nhds_zero] exact (hasBasis_nhds_zero R Γ₀).comap _ theorem toUniformSpace_eq : toUniformSpace = @IsTopologicalAddGroup.rightUniformSpace R _ v.subgroups_basis.topology _ := UniformSpace.ext ((hasBasis_uniformity R Γ₀).eq_of_same_basis <| v.subgroups_basis.hasBasis_nhds_zero.comap _) variable {R Γ₀} theorem mem_nhds {s : Set R} {x : R} : s ∈ 𝓝 x ↔ ∃ γ : Γ₀ˣ, { y | (v (y - x) : Γ₀) < γ } ⊆ s := by simp only [← nhds_translation_add_neg x, ← sub_eq_add_neg, preimage_setOf_eq, true_and, ((hasBasis_nhds_zero R Γ₀).comap fun y => y - x).mem_iff] theorem mem_nhds_zero {s : Set R} : s ∈ 𝓝 (0 : R) ↔ ∃ γ : Γ₀ˣ, { x | v x < (γ : Γ₀) } ⊆ s := by simp only [mem_nhds, sub_zero] theorem loc_const {x : R} (h : (v x : Γ₀) ≠ 0) : { y : R | v y = v x } ∈ 𝓝 x := by rw [mem_nhds] use Units.mk0 _ h rw [Units.val_mk0] intro y y_in exact Valuation.map_eq_of_sub_lt _ y_in instance (priority := 100) : IsTopologicalRing R := (toUniformSpace_eq R Γ₀).symm ▸ v.subgroups_basis.toRingFilterBasis.isTopologicalRing section Discrete lemma discreteTopology_of_forall_map_eq_one (h : ∀ x : R, x ≠ 0 → v x = 1) : DiscreteTopology R := by simp only [discreteTopology_iff_isOpen_singleton_zero, isOpen_iff_mem_nhds, mem_singleton_iff, forall_eq, mem_nhds_zero, subset_singleton_iff, mem_setOf_eq] use 1 contrapose! h obtain ⟨x, hx, hx'⟩ := h exact ⟨x, hx', hx.ne⟩ lemma discreteTopology_of_forall_lt [MulArchimedean Γ₀] [Valued K Γ₀] {r : Γ₀} (hr : r ≠ 0) (h : ∀ x : K, v x ≠ 0 → r < v x) : DiscreteTopology K := discreteTopology_of_forall_map_eq_one (by simpa using Valued.v.map_eq_one_of_forall_lt hr h) end Discrete theorem cauchy_iff {F : Filter R} : Cauchy F ↔ F.NeBot ∧ ∀ γ : Γ₀ˣ, ∃ M ∈ F, ∀ᵉ (x ∈ M) (y ∈ M), (v (y - x) : Γ₀) < γ := by rw [toUniformSpace_eq, AddGroupFilterBasis.cauchy_iff] apply and_congr Iff.rfl simp_rw [Valued.v.subgroups_basis.mem_addGroupFilterBasis_iff] constructor · intro h γ exact h _ (Valued.v.subgroups_basis.mem_addGroupFilterBasis _) · rintro h - ⟨γ, rfl⟩ exact h γ variable (R) /-- An open ball centred at the origin in a valued ring is open. -/ theorem isOpen_ball (r : Γ₀) : IsOpen (X := R) {x | v x < r} := by rw [isOpen_iff_mem_nhds] rcases eq_or_ne r 0 with rfl | hr · simp intro x hx rw [mem_nhds] simp only [setOf_subset_setOf] exact ⟨Units.mk0 _ hr, fun y hy => (sub_add_cancel y x).symm ▸ (v.map_add _ x).trans_lt (max_lt hy hx)⟩ /-- An open ball centred at the origin in a valued ring is closed. -/ theorem isClosed_ball (r : Γ₀) : IsClosed (X := R) {x | v x < r} := by rcases eq_or_ne r 0 with rfl | hr · simp exact AddSubgroup.isClosed_of_isOpen (Valuation.ltAddSubgroup v (Units.mk0 r hr)) (isOpen_ball _ _) /-- An open ball centred at the origin in a valued ring is clopen. -/ theorem isClopen_ball (r : Γ₀) : IsClopen (X := R) {x | v x < r} := ⟨isClosed_ball _ _, isOpen_ball _ _⟩ /-- A closed ball centred at the origin in a valued ring is open. -/ theorem isOpen_closedBall {r : Γ₀} (hr : r ≠ 0) : IsOpen (X := R) {x | v x ≤ r} := by rw [isOpen_iff_mem_nhds] intro x hx rw [mem_nhds] simp only [setOf_subset_setOf] exact ⟨Units.mk0 _ hr, fun y hy => (sub_add_cancel y x).symm ▸ le_trans (v.map_add _ _) (max_le (le_of_lt hy) hx)⟩ @[deprecated (since := "2025-10-09")] alias isOpen_closedball := isOpen_closedBall /-- A closed ball centred at the origin in a valued ring is closed. -/ theorem isClosed_closedBall (r : Γ₀) : IsClosed (X := R) {x | v x ≤ r} := by rw [← isOpen_compl_iff, isOpen_iff_mem_nhds] intro x hx rw [mem_nhds] have hx' : v x ≠ 0 := ne_of_gt <| lt_of_le_of_lt zero_le' <| lt_of_not_ge hx exact ⟨Units.mk0 _ hx', fun y hy hy' => ne_of_lt hy <| map_sub_swap v x y ▸ (Valuation.map_sub_eq_of_lt_left _ <| lt_of_le_of_lt hy' (lt_of_not_ge hx))⟩ /-- A closed ball centred at the origin in a valued ring is clopen. -/ theorem isClopen_closedBall {r : Γ₀} (hr : r ≠ 0) : IsClopen (X := R) {x | v x ≤ r} := ⟨isClosed_closedBall _ _, isOpen_closedBall _ hr⟩ /-- A sphere centred at the origin in a valued ring is clopen. -/ theorem isClopen_sphere {r : Γ₀} (hr : r ≠ 0) : IsClopen (X := R) {x | v x = r} := by have h : {x : R | v x = r} = {x | v x ≤ r} \ {x | v x < r} := by ext x simp [← le_antisymm_iff] rw [h] exact IsClopen.diff (isClopen_closedBall _ hr) (isClopen_ball _ _) /-- A sphere centred at the origin in a valued ring is open. -/ theorem isOpen_sphere {r : Γ₀} (hr : r ≠ 0) : IsOpen (X := R) {x | v x = r} := isClopen_sphere _ hr |>.isOpen /-- A sphere centred at the origin in a valued ring is closed. -/ theorem isClosed_sphere (r : Γ₀) : IsClosed (X := R) {x | v x = r} := by rcases eq_or_ne r 0 with rfl | hr · simpa using isClosed_closedBall R 0 exact isClopen_sphere _ hr |>.isClosed /-- The closed unit ball in a valued ring is open. -/ theorem isOpen_integer : IsOpen (_i.v.integer : Set R) := isOpen_closedBall _ one_ne_zero @[deprecated (since := "2025-04-25")] alias integer_isOpen := isOpen_integer /-- The closed unit ball of a valued ring is closed. -/ theorem isClosed_integer : IsClosed (_i.v.integer : Set R) := isClosed_closedBall _ _ /-- The closed unit ball of a valued ring is clopen. -/ theorem isClopen_integer : IsClopen (_i.v.integer : Set R) := ⟨isClosed_integer _, isOpen_integer _⟩ /-- The valuation subring of a valued field is open. -/ theorem isOpen_valuationSubring (K : Type u) [Field K] [hv : Valued K Γ₀] : IsOpen (hv.v.valuationSubring : Set K) := isOpen_integer K @[deprecated (since := "2025-04-25")] alias valuationSubring_isOpen := isOpen_valuationSubring /-- The valuation subring of a valued field is closed. -/ theorem isClosed_valuationSubring (K : Type u) [Field K] [hv : Valued K Γ₀] : IsClosed (hv.v.valuationSubring : Set K) := isClosed_integer K /-- The valuation subring of a valued field is clopen. -/ theorem isClopen_valuationSubring (K : Type u) [Field K] [hv : Valued K Γ₀] : IsClopen (hv.v.valuationSubring : Set K) := isClopen_integer K end Valued
.lake/packages/mathlib/Mathlib/Topology/Algebra/Valued/ValuedField.lean
import Mathlib.Topology.Algebra.Valued.ValuationTopology import Mathlib.Topology.Algebra.WithZeroTopology import Mathlib.Topology.Algebra.UniformField /-! # Valued fields and their completions In this file we study the topology of a field `K` endowed with a valuation (in our application to adic spaces, `K` will be the valuation field associated to some valuation on a ring, defined in valuation.basic). We already know from valuation.topology that one can build a topology on `K` which makes it a topological ring. The first goal is to show `K` is a topological *field*, i.e. inversion is continuous at every non-zero element. The next goal is to prove `K` is a *completable* topological field. This gives us a completion `hat K` which is a topological field. We also prove that `K` is automatically separated, so the map from `K` to `hat K` is injective. Then we extend the valuation given on `K` to a valuation on `hat K`. -/ open Filter Set open Topology section DivisionRing variable {K : Type*} [DivisionRing K] {Γ₀ : Type*} [LinearOrderedCommGroupWithZero Γ₀] section ValuationTopologicalDivisionRing section InversionEstimate variable (v : Valuation K Γ₀) -- The following is the main technical lemma ensuring that inversion is continuous -- in the topology induced by a valuation on a division ring (i.e. the next instance) -- and the fact that a valued field is completable -- [BouAC, VI.5.1 Lemme 1] theorem Valuation.inversion_estimate {x y : K} {γ : Γ₀ˣ} (y_ne : y ≠ 0) (h : v (x - y) < min (γ * (v y * v y)) (v y)) : v (x⁻¹ - y⁻¹) < γ := by have hyp1 : v (x - y) < γ * (v y * v y) := lt_of_lt_of_le h (min_le_left _ _) have hyp1' : v (x - y) * (v y * v y)⁻¹ < γ := mul_inv_lt_of_lt_mul₀ hyp1 have hyp2 : v (x - y) < v y := lt_of_lt_of_le h (min_le_right _ _) have key : v x = v y := Valuation.map_eq_of_sub_lt v hyp2 have x_ne : x ≠ 0 := by intro h apply y_ne rw [h, v.map_zero] at key exact v.zero_iff.1 key.symm have decomp : x⁻¹ - y⁻¹ = x⁻¹ * (y - x) * y⁻¹ := by rw [mul_sub_left_distrib, sub_mul, mul_assoc, show y * y⁻¹ = 1 from mul_inv_cancel₀ y_ne, show x⁻¹ * x = 1 from inv_mul_cancel₀ x_ne, mul_one, one_mul] calc v (x⁻¹ - y⁻¹) = v (x⁻¹ * (y - x) * y⁻¹) := by rw [decomp] _ = v x⁻¹ * (v <| y - x) * v y⁻¹ := by repeat' rw [Valuation.map_mul] _ = (v x)⁻¹ * (v <| y - x) * (v y)⁻¹ := by rw [map_inv₀, map_inv₀] _ = (v <| y - x) * (v y * v y)⁻¹ := by rw [mul_assoc, mul_comm, key, mul_assoc, mul_inv_rev] _ = (v <| y - x) * (v y * v y)⁻¹ := rfl _ = (v <| x - y) * (v y * v y)⁻¹ := by rw [Valuation.map_sub_swap] _ < γ := hyp1' theorem Valuation.inversion_estimate' {x y r s : K} (y_ne : y ≠ 0) (hr : r ≠ 0) (hs : s ≠ 0) (h : v (x - y) < min ((v s / v r) * (v y * v y)) (v y)) : v (x⁻¹ - y⁻¹) * v r < v s := by have hr' : 0 < v r := by simp [zero_lt_iff, hr] let γ : Γ₀ˣ := .mk0 (v s / v r) (by simp [hs, hr]) calc v (x⁻¹ - y⁻¹) * v r < γ * v r := by gcongr; exact Valuation.inversion_estimate v y_ne h _ = v s := div_mul_cancel₀ _ (by simpa) end InversionEstimate open Valued /-- The topology coming from a valuation on a division ring makes it a topological division ring [BouAC, VI.5.1 middle of Proposition 1] -/ instance (priority := 100) Valued.isTopologicalDivisionRing [Valued K Γ₀] : IsTopologicalDivisionRing K := { (by infer_instance : IsTopologicalRing K) with continuousAt_inv₀ := by intro x x_ne s s_in obtain ⟨γ, hs⟩ := Valued.mem_nhds.mp s_in; clear s_in rw [mem_map, Valued.mem_nhds] change ∃ γ : Γ₀ˣ, { y : K | (v (y - x) : Γ₀) < γ } ⊆ { x : K | x⁻¹ ∈ s } have vx_ne := (Valuation.ne_zero_iff <| v).mpr x_ne let γ' := Units.mk0 _ vx_ne use min (γ * (γ' * γ')) γ' intro y y_in apply hs simp only [mem_setOf_eq] at y_in rw [Units.min_val, Units.val_mul, Units.val_mul] at y_in exact Valuation.inversion_estimate _ x_ne y_in } /-- A valued division ring is separated. -/ instance (priority := 100) ValuedRing.separated [Valued K Γ₀] : T0Space K := by suffices T2Space K by infer_instance apply IsTopologicalAddGroup.t2Space_of_zero_sep intro x x_ne refine ⟨{ k | v k < v x }, ?_, fun h => lt_irrefl _ h⟩ rw [Valued.mem_nhds] have vx_ne := (Valuation.ne_zero_iff <| v).mpr x_ne let γ' := Units.mk0 _ vx_ne exact ⟨γ', fun y hy => by simpa using hy⟩ section open WithZeroTopology open Valued theorem Valued.continuous_valuation [Valued K Γ₀] : Continuous (v : K → Γ₀) := by rw [continuous_iff_continuousAt] intro x rcases eq_or_ne x 0 with (rfl | h) · rw [ContinuousAt, map_zero, WithZeroTopology.tendsto_zero] intro γ hγ rw [Filter.Eventually, Valued.mem_nhds_zero] use Units.mk0 γ hγ; rfl · have v_ne : (v x : Γ₀) ≠ 0 := (Valuation.ne_zero_iff _).mpr h rw [ContinuousAt, WithZeroTopology.tendsto_of_ne_zero v_ne] apply Valued.loc_const v_ne end end ValuationTopologicalDivisionRing end DivisionRing namespace Valued open UniformSpace variable {K : Type*} [Field K] {Γ₀ : Type*} [LinearOrderedCommGroupWithZero Γ₀] [hv : Valued K Γ₀] local notation "hat " => Completion /-- A valued field is completable. -/ instance (priority := 100) completable : CompletableTopField K := { ValuedRing.separated with nice := by rintro F hF h0 have : ∃ γ₀ : Γ₀ˣ, ∃ M ∈ F, ∀ x ∈ M, (γ₀ : Γ₀) ≤ v x := by rcases Filter.inf_eq_bot_iff.mp h0 with ⟨U, U_in, M, M_in, H⟩ rcases Valued.mem_nhds_zero.mp U_in with ⟨γ₀, hU⟩ exists γ₀, M, M_in intro x xM apply le_of_not_gt _ intro hyp have : x ∈ U ∩ M := ⟨hU hyp, xM⟩ rwa [H] at this rcases this with ⟨γ₀, M₀, M₀_in, H₀⟩ rw [Valued.cauchy_iff] at hF ⊢ refine ⟨hF.1.map _, ?_⟩ replace hF := hF.2 intro γ rcases hF (min (γ * γ₀ * γ₀) γ₀) with ⟨M₁, M₁_in, H₁⟩ clear hF use (fun x : K => x⁻¹) '' (M₀ ∩ M₁) constructor · rw [mem_map] apply mem_of_superset (Filter.inter_mem M₀_in M₁_in) exact subset_preimage_image _ _ · rintro _ ⟨x, ⟨x_in₀, x_in₁⟩, rfl⟩ _ ⟨y, ⟨_, y_in₁⟩, rfl⟩ simp only specialize H₁ x x_in₁ y y_in₁ replace x_in₀ := H₀ x x_in₀ clear H₀ apply Valuation.inversion_estimate · have : (v x : Γ₀) ≠ 0 := by intro h rw [h] at x_in₀ simp at x_in₀ exact (Valuation.ne_zero_iff _).mp this · refine lt_of_lt_of_le H₁ ?_ grw [Units.min_val, mul_assoc, Units.val_mul, Units.val_mul, x_in₀] } open WithZeroTopology lemma valuation_isClosedMap : IsClosedMap (v : K → Γ₀) := by refine IsClosedMap.of_nonempty ?_ intro U hU hU' simp only [← isOpen_compl_iff, isOpen_iff_mem_nhds, mem_compl_iff, mem_nhds, subset_compl_comm, compl_setOf, not_lt] at hU simp only [isClosed_iff, mem_image, map_eq_zero, exists_eq_right, ne_eq, image_subset_iff] refine (em _).imp_right fun h ↦ ?_ obtain ⟨γ, h⟩ := hU _ h simp only [sub_zero] at h refine ⟨γ, γ.ne_zero, h.trans ?_⟩ intro simp /-- The extension of the valuation of a valued field to the completion of the field. -/ noncomputable def extension : hat K → Γ₀ := Completion.isDenseInducing_coe.extend (v : K → Γ₀) theorem continuous_extension : Continuous (Valued.extension : hat K → Γ₀) := by refine Completion.isDenseInducing_coe.continuous_extend ?_ intro x₀ rcases eq_or_ne x₀ 0 with (rfl | h) · refine ⟨0, ?_⟩ erw [← Completion.isDenseInducing_coe.isInducing.nhds_eq_comap] exact Valued.continuous_valuation.tendsto' 0 0 (map_zero v) · have preimage_one : v ⁻¹' {(1 : Γ₀)} ∈ 𝓝 (1 : K) := by have : (v (1 : K) : Γ₀) ≠ 0 := by rw [Valuation.map_one] exact zero_ne_one.symm convert Valued.loc_const this ext x rw [Valuation.map_one, mem_preimage, mem_singleton_iff, mem_setOf_eq] obtain ⟨V, V_in, hV⟩ : ∃ V ∈ 𝓝 (1 : hat K), ∀ x : K, (x : hat K) ∈ V → (v x : Γ₀) = 1 := by rwa [Completion.isDenseInducing_coe.nhds_eq_comap, mem_comap] at preimage_one have : ∃ V' ∈ 𝓝 (1 : hat K), (0 : hat K) ∉ V' ∧ ∀ (x) (_ : x ∈ V') (y) (_ : y ∈ V'), x * y⁻¹ ∈ V := by have : Tendsto (fun p : hat K × hat K => p.1 * p.2⁻¹) ((𝓝 1) ×ˢ (𝓝 1)) (𝓝 1) := by rw [← nhds_prod_eq] conv => congr rfl rfl rw [← one_mul (1 : hat K)] refine Tendsto.mul continuous_fst.continuousAt (Tendsto.comp ?_ continuous_snd.continuousAt) convert (continuousAt_inv₀ (zero_ne_one.symm : 1 ≠ (0 : hat K))).tendsto exact inv_one.symm rcases tendsto_prod_self_iff.mp this V V_in with ⟨U, U_in, hU⟩ let hatKstar := ({0}ᶜ : Set <| hat K) have : hatKstar ∈ 𝓝 (1 : hat K) := compl_singleton_mem_nhds zero_ne_one.symm use U ∩ hatKstar, Filter.inter_mem U_in this constructor · rintro ⟨_, h'⟩ rw [mem_compl_singleton_iff] at h' exact h' rfl · rintro x ⟨hx, _⟩ y ⟨hy, _⟩ apply hU <;> assumption rcases this with ⟨V', V'_in, zeroV', hV'⟩ have nhds_right : (fun x => x * x₀) '' V' ∈ 𝓝 x₀ := by have l : Function.LeftInverse (fun x : hat K => x * x₀⁻¹) fun x : hat K => x * x₀ := by intro x simp only [mul_assoc, mul_inv_cancel₀ h, mul_one] have r : Function.RightInverse (fun x : hat K => x * x₀⁻¹) fun x : hat K => x * x₀ := by intro x simp only [mul_assoc, inv_mul_cancel₀ h, mul_one] have c : Continuous fun x : hat K => x * x₀⁻¹ := continuous_id.mul continuous_const rw [image_eq_preimage_of_inverse l r] rw [← mul_inv_cancel₀ h] at V'_in exact c.continuousAt V'_in have : ∃ z₀ : K, ∃ y₀ ∈ V', ↑z₀ = y₀ * x₀ ∧ z₀ ≠ 0 := by rcases Completion.denseRange_coe.mem_nhds nhds_right with ⟨z₀, y₀, y₀_in, H : y₀ * x₀ = z₀⟩ refine ⟨z₀, y₀, y₀_in, ⟨H.symm, ?_⟩⟩ rintro rfl exact mul_ne_zero (ne_of_mem_of_not_mem y₀_in zeroV') h H rcases this with ⟨z₀, y₀, y₀_in, hz₀, z₀_ne⟩ have vz₀_ne : (v z₀ : Γ₀) ≠ 0 := by rwa [Valuation.ne_zero_iff] refine ⟨v z₀, ?_⟩ rw [WithZeroTopology.tendsto_of_ne_zero vz₀_ne, eventually_comap] filter_upwards [nhds_right] with x x_in a ha rcases x_in with ⟨y, y_in, rfl⟩ have : (v (a * z₀⁻¹) : Γ₀) = 1 := by apply hV have : (z₀⁻¹ : K) = (z₀ : hat K)⁻¹ := map_inv₀ (Completion.coeRingHom : K →+* hat K) z₀ rw [Completion.coe_mul, this, ha, hz₀, mul_inv, mul_comm y₀⁻¹, ← mul_assoc, mul_assoc y, mul_inv_cancel₀ h, mul_one] solve_by_elim calc v a = v (a * z₀⁻¹ * z₀) := by rw [mul_assoc, inv_mul_cancel₀ z₀_ne, mul_one] _ = v (a * z₀⁻¹) * v z₀ := Valuation.map_mul _ _ _ _ = v z₀ := by rw [this, one_mul] @[simp, norm_cast] theorem extension_extends (x : K) : extension (x : hat K) = v x := by refine Completion.isDenseInducing_coe.extend_eq_of_tendsto ?_ rw [← Completion.isDenseInducing_coe.nhds_eq_comap] exact Valued.continuous_valuation.continuousAt /-- the extension of a valuation on a division ring to its completion. -/ noncomputable def extensionValuation : Valuation (hat K) Γ₀ where toFun := Valued.extension map_zero' := by rw [← v.map_zero (R := K), ← Valued.extension_extends (0 : K)] rfl map_one' := by rw [← Completion.coe_one, Valued.extension_extends (1 : K)] exact Valuation.map_one _ map_mul' x y := by apply Completion.induction_on₂ x y (p := fun x y => extension (x * y) = extension x * extension y) · have c1 : Continuous fun x : hat K × hat K => Valued.extension (x.1 * x.2) := Valued.continuous_extension.comp (continuous_fst.mul continuous_snd) have c2 : Continuous fun x : hat K × hat K => Valued.extension x.1 * Valued.extension x.2 := (Valued.continuous_extension.comp continuous_fst).mul (Valued.continuous_extension.comp continuous_snd) exact isClosed_eq c1 c2 · intro x y norm_cast exact Valuation.map_mul _ _ _ map_add_le_max' x y := by rw [le_max_iff] apply Completion.induction_on₂ x y (p := fun x y => extension (x + y) ≤ extension x ∨ extension (x + y) ≤ extension y) · have cont : Continuous (Valued.extension : hat K → Γ₀) := Valued.continuous_extension exact (isClosed_le (cont.comp continuous_add) <| cont.comp continuous_fst).union (isClosed_le (cont.comp continuous_add) <| cont.comp continuous_snd) · intro x y norm_cast rw [← le_max_iff] exact v.map_add x y @[simp] lemma extensionValuation_apply_coe (x : K) : Valued.extensionValuation (x : hat K) = v x := extension_extends x @[simp] lemma extension_eq_zero_iff {x : hat K} : extension x = 0 ↔ x = 0 := by suffices extensionValuation x = 0 ↔ x = 0 from this simp lemma continuous_extensionValuation : Continuous (Valued.extensionValuation : hat K → Γ₀) := continuous_extension lemma exists_coe_eq_v (x : hat K) : ∃ r : K, extensionValuation x = v r := by rcases eq_or_ne x 0 with (rfl | h) · use 0 exact extensionValuation_apply_coe 0 · refine Completion.denseRange_coe.induction_on x ?_ (by simp) simpa [eq_comm] using valuation_isClosedMap.isClosed_range.preimage continuous_extensionValuation -- Bourbaki CA VI §5 no.3 Proposition 5 (d) theorem closure_coe_completion_v_lt {γ : Γ₀ˣ} : closure ((↑) '' { x : K | v x < (γ : Γ₀) }) = { x : hat K | extensionValuation x < (γ : Γ₀) } := by ext x let γ₀ := extensionValuation x suffices γ₀ ≠ 0 → (x ∈ closure ((↑) '' { x : K | v x < (γ : Γ₀) }) ↔ γ₀ < (γ : Γ₀)) by rcases eq_or_ne γ₀ 0 with h | h · simp only [(Valuation.zero_iff _).mp h, mem_setOf_eq, Valuation.map_zero, Units.zero_lt, iff_true] apply subset_closure exact ⟨0, by simp only [mem_setOf_eq, Valuation.map_zero, Units.zero_lt, true_and]; rfl⟩ · exact this h intro h have hγ₀ : extension ⁻¹' {γ₀} ∈ 𝓝 x := continuous_extension.continuousAt.preimage_mem_nhds (WithZeroTopology.singleton_mem_nhds_of_ne_zero h) rw [mem_closure_iff_nhds'] refine ⟨fun hx => ?_, fun hx s hs => ?_⟩ · obtain ⟨⟨-, y, hy₁ : v y < (γ : Γ₀), rfl⟩, hy₂⟩ := hx _ hγ₀ replace hy₂ : v y = γ₀ := by simpa using hy₂ rwa [← hy₂] · obtain ⟨y, hy₁, hy₂⟩ := Completion.denseRange_coe.mem_nhds (inter_mem hγ₀ hs) replace hy₁ : v y = γ₀ := by simpa using hy₁ rw [← hy₁] at hx exact ⟨⟨y, ⟨y, hx, rfl⟩⟩, hy₂⟩ theorem closure_coe_completion_v_mul_v_lt {r s : K} (hr : r ≠ 0) (hs : s ≠ 0) : closure ((↑) '' { x : K | v x * v r < v s }) = { x : hat K | extensionValuation x * v r < v s } := by have hrs : v s / v r ≠ 0 := by simp [hr, hs] convert closure_coe_completion_v_lt (γ := .mk0 _ hrs) using 3 all_goals simp [← lt_div_iff₀, zero_lt_iff, hr] noncomputable instance valuedCompletion : Valued (hat K) Γ₀ where v := extensionValuation is_topological_valuation s := by suffices HasBasis (𝓝 (0 : hat K)) (fun _ => True) fun γ : Γ₀ˣ => { x | extensionValuation x < γ } by rw [this.mem_iff] exact exists_congr fun γ => by simp simp_rw [← closure_coe_completion_v_lt] exact (hasBasis_nhds_zero K Γ₀).hasBasis_of_isDenseInducing Completion.isDenseInducing_coe @[simp] theorem valuedCompletion_apply (x : K) : Valued.v (x : hat K) = v x := extension_extends x lemma valuedCompletion_surjective_iff : Function.Surjective (v : hat K → Γ₀) ↔ Function.Surjective (v : K → Γ₀) := by constructor <;> intro h γ <;> obtain ⟨a, ha⟩ := h γ · induction a using Completion.induction_on · by_cases H : ∃ x : K, (v : K → Γ₀) x = γ · simp [H] · simp only [H, imp_false] rcases eq_or_ne γ 0 with rfl | hγ · simp at H · convert isClosed_univ.sdiff (isOpen_sphere (hat K) hγ) using 1 ext x simp · exact ⟨_, by simpa using ha⟩ · exact ⟨a, by simp [ha]⟩ instance {R : Type*} [CommSemiring R] [Algebra R K] [UniformContinuousConstSMul R K] [FaithfulSMul R K] : FaithfulSMul R (hat K) := by rw [faithfulSMul_iff_algebraMap_injective R (hat K)] exact (FaithfulSMul.algebraMap_injective K (hat K)).comp (FaithfulSMul.algebraMap_injective R K) end Valued section Notation namespace Valued variable (K : Type*) [Field K] {Γ₀ : outParam Type*} [LinearOrderedCommGroupWithZero Γ₀] [vK : Valued K Γ₀] /-- A `Valued` version of `Valuation.integer`, enabling the notation `𝒪[K]` for the valuation integers of a valued field `K`. -/ @[reducible] def integer : Subring K := (vK.v).integer @[inherit_doc] scoped notation "𝒪[" K "]" => Valued.integer K /-- An abbreviation for `IsLocalRing.maximalIdeal 𝒪[K]` of a valued field `K`, enabling the notation `𝓂[K]` for the maximal ideal in `𝒪[K]` of a valued field `K`. -/ @[reducible] def maximalIdeal : Ideal 𝒪[K] := IsLocalRing.maximalIdeal 𝒪[K] @[inherit_doc] scoped notation "𝓂[" K "]" => maximalIdeal K /-- An abbreviation for `IsLocalRing.ResidueField 𝒪[K]` of a `Valued` instance, enabling the notation `𝓀[K]` for the residue field of a valued field `K`. -/ @[reducible] def ResidueField := IsLocalRing.ResidueField (𝒪[K]) @[inherit_doc] scoped notation "𝓀[" K "]" => ResidueField K end Valued end Notation
.lake/packages/mathlib/Mathlib/Topology/Algebra/Algebra/Rat.lean
import Mathlib.Algebra.Algebra.Rat import Mathlib.Topology.Algebra.ConstMulAction import Mathlib.Topology.Algebra.Monoid.Defs /-! # Topological (sub)algebras over `Rat` ## Results This is just a minimal stub for now! -/ section DivisionRing /-- The action induced by `DivisionRing.toRatAlgebra` is continuous. -/ instance DivisionRing.continuousConstSMul_rat {A} [DivisionRing A] [TopologicalSpace A] [ContinuousMul A] [CharZero A] : ContinuousConstSMul ℚ A := ⟨fun r => by simpa only [Algebra.smul_def] using continuous_const.mul continuous_id⟩ end DivisionRing
.lake/packages/mathlib/Mathlib/Topology/Algebra/Algebra/Equiv.lean
import Mathlib.Topology.Algebra.Algebra /-! # Isomorphisms of topological algebras This file contains an API for `ContinuousAlgEquiv R A B`, the type of continuous `R`-algebra isomorphisms with continuous inverses. Here `R` is a commutative (semi)ring, and `A` and `B` are `R`-algebras with topologies. ## Main definitions Let `R` be a commutative semiring and let `A` and `B` be `R`-algebras which are also topological spaces. * `ContinuousAlgEquiv R A B`: the type of continuous `R`-algebra isomorphisms from `A` to `B` with continuous inverses. ## Notation `A ≃A[R] B` : notation for `ContinuousAlgEquiv R A B`. ## Tags * continuous, isomorphism, algebra -/ open scoped Topology /-- `ContinuousAlgEquiv R A B`, with notation `A ≃A[R] B`, is the type of bijections between the topological `R`-algebras `A` and `B` which are both homeomorphisms and `R`-algebra isomorphisms. -/ structure ContinuousAlgEquiv (R A B : Type*) [CommSemiring R] [Semiring A] [TopologicalSpace A] [Semiring B] [TopologicalSpace B] [Algebra R A] [Algebra R B] extends A ≃ₐ[R] B, A ≃ₜ B @[inherit_doc] notation:50 A " ≃A[" R "] " B => ContinuousAlgEquiv R A B attribute [nolint docBlame] ContinuousAlgEquiv.toHomeomorph /-- `ContinuousAlgEquivClass F R A B` states that `F` is a type of topological algebra structure-preserving equivalences. You should extend this class when you extend `ContinuousAlgEquiv`. -/ class ContinuousAlgEquivClass (F : Type*) (R A B : outParam Type*) [CommSemiring R] [Semiring A] [TopologicalSpace A] [Semiring B] [TopologicalSpace B] [Algebra R A] [Algebra R B] [EquivLike F A B] : Prop extends AlgEquivClass F R A B, HomeomorphClass F A B namespace ContinuousAlgEquiv variable {R A B C : Type*} [CommSemiring R] [Semiring A] [TopologicalSpace A] [Semiring B] [TopologicalSpace B] [Semiring C] [TopologicalSpace C] [Algebra R A] [Algebra R B] [Algebra R C] /-- The natural coercion from a continuous algebra isomorphism to a continuous algebra morphism. -/ @[coe] def toContinuousAlgHom (e : A ≃A[R] B) : A →A[R] B where __ := e.toAlgHom cont := e.continuous_toFun instance coe : Coe (A ≃A[R] B) (A →A[R] B) := ⟨toContinuousAlgHom⟩ instance equivLike : EquivLike (A ≃A[R] B) A B where coe f := f.toFun inv f := f.invFun coe_injective' f g h₁ h₂ := by obtain ⟨f', _⟩ := f obtain ⟨g', _⟩ := g rcases f' with ⟨⟨_, _⟩, _⟩ rcases g' with ⟨⟨_, _⟩, _⟩ congr left_inv f := f.left_inv right_inv f := f.right_inv instance continuousAlgEquivClass : ContinuousAlgEquivClass (A ≃A[R] B) R A B where map_add f := f.map_add' map_mul f := f.map_mul' commutes f := f.commutes' map_continuous := continuous_toFun inv_continuous := continuous_invFun theorem coe_apply (e : A ≃A[R] B) (a : A) : (e : A →A[R] B) a = e a := rfl @[simp] theorem coe_coe (e : A ≃A[R] B) : ⇑(e : A →A[R] B) = e := rfl theorem toAlgEquiv_injective : Function.Injective (toAlgEquiv : (A ≃A[R] B) → A ≃ₐ[R] B) := by rintro ⟨e, _, _⟩ ⟨e', _, _⟩ rfl rfl @[ext] theorem ext {f g : A ≃A[R] B} (h : ⇑f = ⇑g) : f = g := toAlgEquiv_injective <| AlgEquiv.ext <| congr_fun h theorem coe_injective : Function.Injective ((↑) : (A ≃A[R] B) → A →A[R] B) := fun _ _ h => ext <| funext <| ContinuousAlgHom.ext_iff.1 h @[simp] theorem coe_inj {f g : A ≃A[R] B} : (f : A →A[R] B) = g ↔ f = g := coe_injective.eq_iff @[simp] theorem coe_toAlgEquiv (e : A ≃A[R] B) : ⇑e.toAlgEquiv = e := rfl theorem isOpenMap (e : A ≃A[R] B) : IsOpenMap e := e.toHomeomorph.isOpenMap theorem image_closure (e : A ≃A[R] B) (S : Set A) : e '' closure S = closure (e '' S) := e.toHomeomorph.image_closure S theorem preimage_closure (e : A ≃A[R] B) (S : Set B) : e ⁻¹' closure S = closure (e ⁻¹' S) := e.toHomeomorph.preimage_closure S @[simp] theorem isClosed_image (e : A ≃A[R] B) {S : Set A} : IsClosed (e '' S) ↔ IsClosed S := e.toHomeomorph.isClosed_image theorem map_nhds_eq (e : A ≃A[R] B) (a : A) : Filter.map e (𝓝 a) = 𝓝 (e a) := e.toHomeomorph.map_nhds_eq a theorem map_eq_zero_iff (e : A ≃A[R] B) {a : A} : e a = 0 ↔ a = 0 := e.toAlgEquiv.toLinearEquiv.map_eq_zero_iff attribute [continuity] ContinuousAlgEquiv.continuous_invFun ContinuousAlgEquiv.continuous_toFun @[fun_prop] theorem continuous (e : A ≃A[R] B) : Continuous e := e.continuous_toFun theorem continuousOn (e : A ≃A[R] B) {S : Set A} : ContinuousOn e S := e.continuous.continuousOn theorem continuousAt (e : A ≃A[R] B) {a : A} : ContinuousAt e a := e.continuous.continuousAt theorem continuousWithinAt (e : A ≃A[R] B) {S : Set A} {a : A} : ContinuousWithinAt e S a := e.continuous.continuousWithinAt theorem comp_continuous_iff {α : Type*} [TopologicalSpace α] (e : A ≃A[R] B) {f : α → A} : Continuous (e ∘ f) ↔ Continuous f := e.toHomeomorph.comp_continuous_iff theorem comp_continuous_iff' {β : Type*} [TopologicalSpace β] (e : A ≃A[R] B) {g : B → β} : Continuous (g ∘ e) ↔ Continuous g := e.toHomeomorph.comp_continuous_iff' variable (R A) /-- The identity isomorphism as a continuous `R`-algebra equivalence. -/ @[refl] def refl : A ≃A[R] A where __ := AlgEquiv.refl continuous_toFun := continuous_id continuous_invFun := continuous_id @[simp] theorem refl_apply (a : A) : refl R A a = a := rfl @[simp] theorem coe_refl : refl R A = ContinuousAlgHom.id R A := rfl @[simp] theorem coe_refl' : ⇑(refl R A) = id := rfl variable {R A} /-- The inverse of a continuous algebra equivalence. -/ @[symm] def symm (e : A ≃A[R] B) : B ≃A[R] A where __ := e.toAlgEquiv.symm continuous_toFun := e.continuous_invFun continuous_invFun := e.continuous_toFun @[simp] theorem apply_symm_apply (e : A ≃A[R] B) (b : B) : e (e.symm b) = b := e.1.right_inv b @[simp] theorem symm_apply_apply (e : A ≃A[R] B) (a : A) : e.symm (e a) = a := e.1.left_inv a @[simp] theorem symm_image_image (e : A ≃A[R] B) (S : Set A) : e.symm '' (e '' S) = S := e.toEquiv.symm_image_image S @[simp] theorem image_symm_image (e : A ≃A[R] B) (S : Set B) : e '' (e.symm '' S) = S := e.symm.symm_image_image S @[simp] theorem symm_toAlgEquiv (e : A ≃A[R] B) : e.symm.toAlgEquiv = e.toAlgEquiv.symm := rfl @[simp] theorem symm_toHomeomorph (e : A ≃A[R] B) : e.symm.toHomeomorph = e.toHomeomorph.symm := rfl theorem symm_map_nhds_eq (e : A ≃A[R] B) (a : A) : Filter.map e.symm (𝓝 (e a)) = 𝓝 a := e.toHomeomorph.symm_map_nhds_eq a /-- The composition of two continuous algebra equivalences. -/ @[trans] def trans (e₁ : A ≃A[R] B) (e₂ : B ≃A[R] C) : A ≃A[R] C where __ := e₁.toAlgEquiv.trans e₂.toAlgEquiv continuous_toFun := e₂.continuous_toFun.comp e₁.continuous_toFun continuous_invFun := e₁.continuous_invFun.comp e₂.continuous_invFun @[simp] theorem trans_toAlgEquiv (e₁ : A ≃A[R] B) (e₂ : B ≃A[R] C) : (e₁.trans e₂).toAlgEquiv = e₁.toAlgEquiv.trans e₂.toAlgEquiv := rfl @[simp] theorem trans_apply (e₁ : A ≃A[R] B) (e₂ : B ≃A[R] C) (a : A) : (e₁.trans e₂) a = e₂ (e₁ a) := rfl @[simp] theorem symm_trans_apply (e₁ : B ≃A[R] A) (e₂ : C ≃A[R] B) (a : A) : (e₂.trans e₁).symm a = e₂.symm (e₁.symm a) := rfl theorem comp_coe (e₁ : A ≃A[R] B) (e₂ : B ≃A[R] C) : e₂.toAlgHom.comp e₁.toAlgHom = e₁.trans e₂ := by rfl @[simp high] theorem coe_comp_coe_symm (e : A ≃A[R] B) : e.toContinuousAlgHom.comp e.symm = ContinuousAlgHom.id R B := ContinuousAlgHom.ext e.apply_symm_apply @[simp high] theorem coe_symm_comp_coe (e : A ≃A[R] B) : e.symm.toContinuousAlgHom.comp e = ContinuousAlgHom.id R A := ContinuousAlgHom.ext e.symm_apply_apply @[simp] theorem symm_comp_self (e : A ≃A[R] B) : (e.symm : B → A) ∘ e = id := by exact funext <| e.symm_apply_apply @[simp] theorem self_comp_symm (e : A ≃A[R] B) : (e : A → B) ∘ e.symm = id := funext <| e.apply_symm_apply @[simp] theorem symm_symm (e : A ≃A[R] B) : e.symm.symm = e := rfl theorem symm_bijective : Function.Bijective (symm : (A ≃A[R] B) → _) := Function.bijective_iff_has_inverse.mpr ⟨_, symm_symm, symm_symm⟩ @[simp] theorem refl_symm : (refl R A).symm = refl R A := rfl theorem symm_symm_apply (e : A ≃A[R] B) (a : A) : e.symm.symm a = e a := rfl theorem symm_apply_eq (e : A ≃A[R] B) {a : A} {b : B} : e.symm b = a ↔ b = e a := e.toEquiv.symm_apply_eq theorem eq_symm_apply (e : A ≃A[R] B) {a : A} {b : B} : a = e.symm b ↔ e a = b := e.toEquiv.eq_symm_apply theorem image_eq_preimage_symm (e : A ≃A[R] B) (S : Set A) : e '' S = e.symm ⁻¹' S := e.toEquiv.image_eq_preimage_symm S theorem image_symm_eq_preimage (e : A ≃A[R] B) (S : Set B) : e.symm '' S = e ⁻¹' S := by rw [e.symm.image_eq_preimage_symm, e.symm_symm] @[simp] theorem symm_preimage_preimage (e : A ≃A[R] B) (S : Set B) : e.symm ⁻¹' (e ⁻¹' S) = S := e.toEquiv.symm_preimage_preimage S @[simp] theorem preimage_symm_preimage (e : A ≃A[R] B) (S : Set A) : e ⁻¹' (e.symm ⁻¹' S) = S := e.symm.symm_preimage_preimage S theorem isUniformEmbedding {E₁ E₂ : Type*} [UniformSpace E₁] [UniformSpace E₂] [Ring E₁] [IsUniformAddGroup E₁] [Algebra R E₁] [Ring E₂] [IsUniformAddGroup E₂] [Algebra R E₂] (e : E₁ ≃A[R] E₂) : IsUniformEmbedding e := e.toAlgEquiv.isUniformEmbedding e.toContinuousAlgHom.uniformContinuous e.symm.toContinuousAlgHom.uniformContinuous theorem _root_.AlgEquiv.isUniformEmbedding {E₁ E₂ : Type*} [UniformSpace E₁] [UniformSpace E₂] [Ring E₁] [IsUniformAddGroup E₁] [Algebra R E₁] [Ring E₂] [IsUniformAddGroup E₂] [Algebra R E₂] (e : E₁ ≃ₐ[R] E₂) (h₁ : Continuous e) (h₂ : Continuous e.symm) : IsUniformEmbedding e := ContinuousAlgEquiv.isUniformEmbedding { e with continuous_toFun := h₁ continuous_invFun := by dsimp; fun_prop } end ContinuousAlgEquiv
.lake/packages/mathlib/Mathlib/Topology/Algebra/SeparationQuotient/Basic.lean
import Mathlib.Topology.Algebra.Module.LinearMap /-! # Algebraic operations on `SeparationQuotient` In this file we define algebraic operations (multiplication, addition etc) on the separation quotient of a topological space with corresponding operation, provided that the original operation is continuous. We also prove continuity of these operations and show that they satisfy the same kind of laws (`Monoid` etc) as the original ones. Finally, we construct a section of the quotient map which is a continuous linear map `SeparationQuotient E →L[K] E`. -/ assert_not_exists LinearIndependent open scoped Topology namespace SeparationQuotient section SMul variable {M X : Type*} [TopologicalSpace X] [SMul M X] [ContinuousConstSMul M X] @[to_additive] instance instSMul : SMul M (SeparationQuotient X) where smul c := Quotient.map' (c • ·) fun _ _ h ↦ h.const_smul c @[to_additive (attr := simp)] theorem mk_smul (c : M) (x : X) : mk (c • x) = c • mk x := rfl @[to_additive] instance instContinuousConstSMul : ContinuousConstSMul M (SeparationQuotient X) where continuous_const_smul c := isQuotientMap_mk.continuous_iff.2 <| continuous_mk.comp <| continuous_const_smul c @[to_additive] instance instIsPretransitiveSMul [MulAction.IsPretransitive M X] : MulAction.IsPretransitive M (SeparationQuotient X) where exists_smul_eq := surjective_mk.forall₂.2 fun x y ↦ (MulAction.exists_smul_eq M x y).imp fun _ ↦ congr_arg mk @[to_additive] instance instIsCentralScalar [SMul Mᵐᵒᵖ X] [IsCentralScalar M X] : IsCentralScalar M (SeparationQuotient X) where op_smul_eq_smul a := surjective_mk.forall.2 (congr_arg mk <| op_smul_eq_smul a ·) variable {N : Type*} [SMul N X] @[to_additive] instance instSMulCommClass [ContinuousConstSMul N X] [SMulCommClass M N X] : SMulCommClass M N (SeparationQuotient X) := surjective_mk.smulCommClass mk_smul mk_smul @[to_additive] instance instIsScalarTower [SMul M N] [ContinuousConstSMul N X] [IsScalarTower M N X] : IsScalarTower M N (SeparationQuotient X) where smul_assoc a b := surjective_mk.forall.2 fun x ↦ congr_arg mk <| smul_assoc a b x end SMul instance instContinuousSMul {M X : Type*} [SMul M X] [TopologicalSpace M] [TopologicalSpace X] [ContinuousSMul M X] : ContinuousSMul M (SeparationQuotient X) where continuous_smul := by rw [(IsOpenQuotientMap.id.prodMap isOpenQuotientMap_mk).isQuotientMap.continuous_iff] exact continuous_mk.comp continuous_smul instance instSMulZeroClass {M X : Type*} [Zero X] [SMulZeroClass M X] [TopologicalSpace X] [ContinuousConstSMul M X] : SMulZeroClass M (SeparationQuotient X) := ZeroHom.smulZeroClass ⟨mk, mk_zero⟩ mk_smul @[to_additive] instance instMulAction {M X : Type*} [Monoid M] [MulAction M X] [TopologicalSpace X] [ContinuousConstSMul M X] : MulAction M (SeparationQuotient X) := surjective_mk.mulAction mk mk_smul section Monoid variable {M : Type*} [TopologicalSpace M] @[to_additive] instance instMul [Mul M] [ContinuousMul M] : Mul (SeparationQuotient M) where mul := Quotient.map₂ (· * ·) fun _ _ h₁ _ _ h₂ ↦ Inseparable.mul h₁ h₂ @[to_additive (attr := simp)] theorem mk_mul [Mul M] [ContinuousMul M] (a b : M) : mk (a * b) = mk a * mk b := rfl @[to_additive] instance instContinuousMul [Mul M] [ContinuousMul M] : ContinuousMul (SeparationQuotient M) where continuous_mul := isQuotientMap_prodMap_mk.continuous_iff.2 <| continuous_mk.comp continuous_mul @[to_additive] instance instCommMagma [CommMagma M] [ContinuousMul M] : CommMagma (SeparationQuotient M) := surjective_mk.commMagma mk mk_mul @[to_additive] instance instSemigroup [Semigroup M] [ContinuousMul M] : Semigroup (SeparationQuotient M) := surjective_mk.semigroup mk mk_mul @[to_additive] instance instCommSemigroup [CommSemigroup M] [ContinuousMul M] : CommSemigroup (SeparationQuotient M) := surjective_mk.commSemigroup mk mk_mul @[to_additive] instance instMulOneClass [MulOneClass M] [ContinuousMul M] : MulOneClass (SeparationQuotient M) := surjective_mk.mulOneClass mk mk_one mk_mul /-- `SeparationQuotient.mk` as a `MonoidHom`. -/ @[to_additive (attr := simps) /-- `SeparationQuotient.mk` as an `AddMonoidHom`. -/] def mkMonoidHom [MulOneClass M] [ContinuousMul M] : M →* SeparationQuotient M where toFun := mk map_mul' := mk_mul map_one' := mk_one instance (priority := 900) instNSmul [AddMonoid M] [ContinuousAdd M] : SMul ℕ (SeparationQuotient M) := inferInstance @[to_additive existing instNSmul] instance instPow [Monoid M] [ContinuousMul M] : Pow (SeparationQuotient M) ℕ where pow x n := Quotient.map' (s₁ := inseparableSetoid M) (· ^ n) (fun _ _ h ↦ Inseparable.pow h n) x @[to_additive, simp] -- `mk_nsmul` is not a `simp` lemma because we have `mk_smul` theorem mk_pow [Monoid M] [ContinuousMul M] (x : M) (n : ℕ) : mk (x ^ n) = (mk x) ^ n := rfl @[to_additive] instance instMonoid [Monoid M] [ContinuousMul M] : Monoid (SeparationQuotient M) := surjective_mk.monoid mk mk_one mk_mul mk_pow @[to_additive] instance instCommMonoid [CommMonoid M] [ContinuousMul M] : CommMonoid (SeparationQuotient M) := surjective_mk.commMonoid mk mk_one mk_mul mk_pow end Monoid section Group variable {G : Type*} [TopologicalSpace G] @[to_additive] instance instInv [Inv G] [ContinuousInv G] : Inv (SeparationQuotient G) where inv := Quotient.map' (·⁻¹) fun _ _ ↦ Inseparable.inv @[to_additive (attr := simp)] theorem mk_inv [Inv G] [ContinuousInv G] (x : G) : mk x⁻¹ = (mk x)⁻¹ := rfl @[to_additive] instance instContinuousInv [Inv G] [ContinuousInv G] : ContinuousInv (SeparationQuotient G) where continuous_inv := isQuotientMap_mk.continuous_iff.2 <| continuous_mk.comp continuous_inv @[to_additive] instance instInvolutiveInv [InvolutiveInv G] [ContinuousInv G] : InvolutiveInv (SeparationQuotient G) := surjective_mk.involutiveInv mk mk_inv @[to_additive] instance instInvOneClass [InvOneClass G] [ContinuousInv G] : InvOneClass (SeparationQuotient G) where inv_one := congr_arg mk inv_one @[to_additive] instance instDiv [Div G] [ContinuousDiv G] : Div (SeparationQuotient G) where div := Quotient.map₂ (· / ·) fun _ _ h₁ _ _ h₂ ↦ (Inseparable.prod h₁ h₂).map continuous_div' @[to_additive (attr := simp)] theorem mk_div [Div G] [ContinuousDiv G] (x y : G) : mk (x / y) = mk x / mk y := rfl @[to_additive] instance instContinuousDiv [Div G] [ContinuousDiv G] : ContinuousDiv (SeparationQuotient G) where continuous_div' := isQuotientMap_prodMap_mk.continuous_iff.2 <| continuous_mk.comp continuous_div' instance instZSMul [AddGroup G] [IsTopologicalAddGroup G] : SMul ℤ (SeparationQuotient G) := inferInstance @[to_additive existing] instance instZPow [Group G] [IsTopologicalGroup G] : Pow (SeparationQuotient G) ℤ where pow x n := Quotient.map' (s₁ := inseparableSetoid G) (· ^ n) (fun _ _ h ↦ Inseparable.zpow h n) x @[to_additive, simp] -- `mk_zsmul` is not a `simp` lemma because we have `mk_smul` theorem mk_zpow [Group G] [IsTopologicalGroup G] (x : G) (n : ℤ) : mk (x ^ n) = (mk x) ^ n := rfl @[to_additive] instance instGroup [Group G] [IsTopologicalGroup G] : Group (SeparationQuotient G) := surjective_mk.group mk mk_one mk_mul mk_inv mk_div mk_pow mk_zpow @[to_additive] instance instCommGroup [CommGroup G] [IsTopologicalGroup G] : CommGroup (SeparationQuotient G) := surjective_mk.commGroup mk mk_one mk_mul mk_inv mk_div mk_pow mk_zpow @[to_additive] instance instIsTopologicalGroup [Group G] [IsTopologicalGroup G] : IsTopologicalGroup (SeparationQuotient G) where end Group section IsUniformGroup @[to_additive] instance instIsUniformGroup {G : Type*} [Group G] [UniformSpace G] [IsUniformGroup G] : IsUniformGroup (SeparationQuotient G) where uniformContinuous_div := by rw [uniformContinuous_dom₂] exact uniformContinuous_mk.comp uniformContinuous_div end IsUniformGroup section MonoidWithZero variable {M₀ : Type*} [TopologicalSpace M₀] instance instMulZeroClass [MulZeroClass M₀] [ContinuousMul M₀] : MulZeroClass (SeparationQuotient M₀) := surjective_mk.mulZeroClass mk mk_zero mk_mul instance instSemigroupWithZero [SemigroupWithZero M₀] [ContinuousMul M₀] : SemigroupWithZero (SeparationQuotient M₀) := surjective_mk.semigroupWithZero mk mk_zero mk_mul instance instMulZeroOneClass [MulZeroOneClass M₀] [ContinuousMul M₀] : MulZeroOneClass (SeparationQuotient M₀) := surjective_mk.mulZeroOneClass mk mk_zero mk_one mk_mul instance instMonoidWithZero [MonoidWithZero M₀] [ContinuousMul M₀] : MonoidWithZero (SeparationQuotient M₀) := surjective_mk.monoidWithZero mk mk_zero mk_one mk_mul mk_pow instance instCommMonoidWithZero [CommMonoidWithZero M₀] [ContinuousMul M₀] : CommMonoidWithZero (SeparationQuotient M₀) := surjective_mk.commMonoidWithZero mk mk_zero mk_one mk_mul mk_pow end MonoidWithZero section Ring variable {R : Type*} [TopologicalSpace R] instance instDistrib [Distrib R] [ContinuousMul R] [ContinuousAdd R] : Distrib (SeparationQuotient R) := surjective_mk.distrib mk mk_add mk_mul instance instLeftDistribClass [Mul R] [Add R] [LeftDistribClass R] [ContinuousMul R] [ContinuousAdd R] : LeftDistribClass (SeparationQuotient R) := surjective_mk.leftDistribClass mk mk_add mk_mul instance instRightDistribClass [Mul R] [Add R] [RightDistribClass R] [ContinuousMul R] [ContinuousAdd R] : RightDistribClass (SeparationQuotient R) := surjective_mk.rightDistribClass mk mk_add mk_mul instance instNonUnitalnonAssocSemiring [NonUnitalNonAssocSemiring R] [IsTopologicalSemiring R] : NonUnitalNonAssocSemiring (SeparationQuotient R) := surjective_mk.nonUnitalNonAssocSemiring mk mk_zero mk_add mk_mul mk_smul instance instNonUnitalSemiring [NonUnitalSemiring R] [IsTopologicalSemiring R] : NonUnitalSemiring (SeparationQuotient R) := surjective_mk.nonUnitalSemiring mk mk_zero mk_add mk_mul mk_smul instance instNatCast [NatCast R] : NatCast (SeparationQuotient R) where natCast n := mk n @[simp, norm_cast] theorem mk_natCast [NatCast R] (n : ℕ) : mk (n : R) = n := rfl @[simp] theorem mk_ofNat [NatCast R] (n : ℕ) [n.AtLeastTwo] : mk (ofNat(n) : R) = OfNat.ofNat n := rfl instance instIntCast [IntCast R] : IntCast (SeparationQuotient R) where intCast n := mk n @[simp, norm_cast] theorem mk_intCast [IntCast R] (n : ℤ) : mk (n : R) = n := rfl instance instNonAssocSemiring [NonAssocSemiring R] [IsTopologicalSemiring R] : NonAssocSemiring (SeparationQuotient R) := surjective_mk.nonAssocSemiring mk mk_zero mk_one mk_add mk_mul mk_smul mk_natCast instance instNonUnitalNonAssocRing [NonUnitalNonAssocRing R] [IsTopologicalRing R] : NonUnitalNonAssocRing (SeparationQuotient R) := surjective_mk.nonUnitalNonAssocRing mk mk_zero mk_add mk_mul mk_neg mk_sub mk_smul mk_smul instance instNonUnitalRing [NonUnitalRing R] [IsTopologicalRing R] : NonUnitalRing (SeparationQuotient R) := surjective_mk.nonUnitalRing mk mk_zero mk_add mk_mul mk_neg mk_sub mk_smul mk_smul instance instNonAssocRing [NonAssocRing R] [IsTopologicalRing R] : NonAssocRing (SeparationQuotient R) := surjective_mk.nonAssocRing mk mk_zero mk_one mk_add mk_mul mk_neg mk_sub mk_smul mk_smul mk_natCast mk_intCast instance instSemiring [Semiring R] [IsTopologicalSemiring R] : Semiring (SeparationQuotient R) := surjective_mk.semiring mk mk_zero mk_one mk_add mk_mul mk_smul mk_pow mk_natCast instance instRing [Ring R] [IsTopologicalRing R] : Ring (SeparationQuotient R) := surjective_mk.ring mk mk_zero mk_one mk_add mk_mul mk_neg mk_sub mk_smul mk_smul mk_pow mk_natCast mk_intCast instance instNonUnitalNonAssocCommSemiring [NonUnitalNonAssocCommSemiring R] [IsTopologicalSemiring R] : NonUnitalNonAssocCommSemiring (SeparationQuotient R) := surjective_mk.nonUnitalNonAssocCommSemiring mk mk_zero mk_add mk_mul mk_smul instance instNonUnitalCommSemiring [NonUnitalCommSemiring R] [IsTopologicalSemiring R] : NonUnitalCommSemiring (SeparationQuotient R) := surjective_mk.nonUnitalCommSemiring mk mk_zero mk_add mk_mul mk_smul instance instCommSemiring [CommSemiring R] [IsTopologicalSemiring R] : CommSemiring (SeparationQuotient R) := surjective_mk.commSemiring mk mk_zero mk_one mk_add mk_mul mk_smul mk_pow mk_natCast instance instHasDistribNeg [Mul R] [HasDistribNeg R] [ContinuousMul R] [ContinuousNeg R] : HasDistribNeg (SeparationQuotient R) := surjective_mk.hasDistribNeg mk mk_neg mk_mul instance instNonUnitalNonAssocCommRing [NonUnitalNonAssocCommRing R] [IsTopologicalRing R] : NonUnitalNonAssocCommRing (SeparationQuotient R) := surjective_mk.nonUnitalNonAssocCommRing mk mk_zero mk_add mk_mul mk_neg mk_sub mk_smul mk_smul instance instNonUnitalCommRing [NonUnitalCommRing R] [IsTopologicalRing R] : NonUnitalCommRing (SeparationQuotient R) := surjective_mk.nonUnitalCommRing mk mk_zero mk_add mk_mul mk_neg mk_sub mk_smul mk_smul instance instCommRing [CommRing R] [IsTopologicalRing R] : CommRing (SeparationQuotient R) := surjective_mk.commRing mk mk_zero mk_one mk_add mk_mul mk_neg mk_sub mk_smul mk_smul mk_pow mk_natCast mk_intCast /-- `SeparationQuotient.mk` as a `RingHom`. -/ @[simps] def mkRingHom [NonAssocSemiring R] [IsTopologicalSemiring R] : R →+* SeparationQuotient R where toFun := mk map_one' := mk_one; map_zero' := mk_zero; map_add' := mk_add; map_mul' := mk_mul end Ring section DistribSMul variable {M A : Type*} [TopologicalSpace A] instance instDistribSMul [AddZeroClass A] [DistribSMul M A] [ContinuousAdd A] [ContinuousConstSMul M A] : DistribSMul M (SeparationQuotient A) := surjective_mk.distribSMul mkAddMonoidHom mk_smul instance instDistribMulAction [Monoid M] [AddMonoid A] [DistribMulAction M A] [ContinuousAdd A] [ContinuousConstSMul M A] : DistribMulAction M (SeparationQuotient A) := surjective_mk.distribMulAction mkAddMonoidHom mk_smul instance instMulDistribMulAction [Monoid M] [Monoid A] [MulDistribMulAction M A] [ContinuousMul A] [ContinuousConstSMul M A] : MulDistribMulAction M (SeparationQuotient A) := surjective_mk.mulDistribMulAction mkMonoidHom mk_smul end DistribSMul section Module variable {R S M N : Type*} [Semiring R] [AddCommMonoid M] [Module R M] [TopologicalSpace M] [ContinuousAdd M] [ContinuousConstSMul R M] [Semiring S] [AddCommMonoid N] [Module S N] [TopologicalSpace N] instance instModule : Module R (SeparationQuotient M) := surjective_mk.module R mkAddMonoidHom mk_smul variable (R M) /-- `SeparationQuotient.mk` as a continuous linear map. -/ @[simps] def mkCLM : M →L[R] SeparationQuotient M where toFun := mk map_add' := mk_add map_smul' := mk_smul variable {R M} /-- The lift (as a continuous linear map) of `f` with `f x = f y` for `Inseparable x y`. -/ @[simps] noncomputable def liftCLM {σ : R →+* S} (f : M →SL[σ] N) (hf : ∀ x y, Inseparable x y → f x = f y) : SeparationQuotient M →SL[σ] N where toFun := SeparationQuotient.lift f hf map_add' := Quotient.ind₂ <| map_add f map_smul' {r} := Quotient.ind <| map_smulₛₗ f r @[simp] theorem liftCLM_mk {σ : R →+* S} (f : M →SL[σ] N) (hf : ∀ x y, Inseparable x y → f x = f y) (x : M) : liftCLM f hf (mk x) = f x := rfl end Module section Algebra variable {R A : Type*} [CommSemiring R] [Semiring A] [Algebra R A] [TopologicalSpace A] [IsTopologicalSemiring A] [ContinuousConstSMul R A] instance instAlgebra : Algebra R (SeparationQuotient A) where algebraMap := mkRingHom.comp (algebraMap R A) commutes' r := Quotient.ind fun a => congrArg _ <| Algebra.commutes r a smul_def' r := Quotient.ind fun a => congrArg _ <| Algebra.smul_def r a @[simp] theorem mk_algebraMap (r : R) : mk (algebraMap R A r) = algebraMap R (SeparationQuotient A) r := rfl end Algebra end SeparationQuotient
.lake/packages/mathlib/Mathlib/Topology/Algebra/SeparationQuotient/Section.lean
import Mathlib.Algebra.Module.Projective import Mathlib.LinearAlgebra.Basis.VectorSpace import Mathlib.Topology.Algebra.SeparationQuotient.Basic import Mathlib.Topology.Maps.OpenQuotient /-! # Algebraic operations on `SeparationQuotient` In this file we construct a section of the quotient map `E → SeparationQuotient E` as a continuous linear map `SeparationQuotient E →L[K] E`. -/ open Topology namespace SeparationQuotient section VectorSpace variable (K E : Type*) [DivisionRing K] [AddCommGroup E] [Module K E] [TopologicalSpace E] [IsTopologicalAddGroup E] [ContinuousConstSMul K E] /-- There exists a continuous `K`-linear map from `SeparationQuotient E` to `E` such that `mk (outCLM x) = x` for all `x`. Note that continuity of this map comes for free, because `mk` is a topology inducing map. -/ theorem exists_out_continuousLinearMap : ∃ f : SeparationQuotient E →L[K] E, mkCLM K E ∘L f = .id K (SeparationQuotient E) := by rcases (mkCLM K E).toLinearMap.exists_rightInverse_of_surjective (LinearMap.range_eq_top.mpr surjective_mk) with ⟨f, hf⟩ replace hf : mk ∘ f = id := congr_arg DFunLike.coe hf exact ⟨⟨f, isInducing_mk.continuous_iff.2 (by continuity)⟩, DFunLike.ext' hf⟩ /-- A continuous `K`-linear map from `SeparationQuotient E` to `E` such that `mk (outCLM x) = x` for all `x`. -/ noncomputable def outCLM : SeparationQuotient E →L[K] E := (exists_out_continuousLinearMap K E).choose @[simp] theorem mkCLM_comp_outCLM : mkCLM K E ∘L outCLM K E = .id K (SeparationQuotient E) := (exists_out_continuousLinearMap K E).choose_spec variable {E} in @[simp] theorem mk_outCLM (x : SeparationQuotient E) : mk (outCLM K E x) = x := DFunLike.congr_fun (mkCLM_comp_outCLM K E) x @[simp] theorem mk_comp_outCLM : mk ∘ outCLM K E = id := funext (mk_outCLM K) variable {K} in theorem postcomp_mkCLM_surjective {L : Type*} [Semiring L] (σ : L →+* K) (F : Type*) [AddCommMonoid F] [Module L F] [TopologicalSpace F] : Function.Surjective ((mkCLM K E).comp : (F →SL[σ] E) → (F →SL[σ] SeparationQuotient E)) := by intro f use (outCLM K E).comp f rw [← ContinuousLinearMap.comp_assoc, mkCLM_comp_outCLM, ContinuousLinearMap.id_comp] /-- The `SeparationQuotient.outCLM K E` map is a topological embedding. -/ theorem isEmbedding_outCLM : IsEmbedding (outCLM K E) := Function.LeftInverse.isEmbedding (mk_outCLM K) continuous_mk (map_continuous _) theorem outCLM_injective : Function.Injective (outCLM K E) := (isEmbedding_outCLM K E).injective end VectorSpace section VectorSpaceUniform variable (K E : Type*) [DivisionRing K] [AddCommGroup E] [Module K E] [UniformSpace E] [IsUniformAddGroup E] [ContinuousConstSMul K E] theorem outCLM_isUniformInducing : IsUniformInducing (outCLM K E) := by rw [← isUniformInducing_mk.isUniformInducing_comp_iff, mk_comp_outCLM] exact .id theorem outCLM_isUniformEmbedding : IsUniformEmbedding (outCLM K E) where injective := outCLM_injective K E toIsUniformInducing := outCLM_isUniformInducing K E theorem outCLM_uniformContinuous : UniformContinuous (outCLM K E) := (outCLM_isUniformInducing K E).uniformContinuous end VectorSpaceUniform end SeparationQuotient
.lake/packages/mathlib/Mathlib/Topology/Algebra/SeparationQuotient/Hom.lean
import Mathlib.Topology.Algebra.ContinuousMonoidHom import Mathlib.Topology.Algebra.SeparationQuotient.Basic /-! # Lift of `MonoidHom M N` to `MonoidHom (SeparationQuotient M) N` In this file we define the lift of a continuous monoid homomorphism `f` from `M` to `N` to `SeparationQuotient M`, assuming that `f` maps two inseparable elements to the same element. -/ namespace SeparationQuotient section Monoid variable {M N : Type*} [TopologicalSpace M] [TopologicalSpace N] /-- The lift of a monoid hom from `M` to a monoid hom from `SeparationQuotient M`. -/ @[to_additive /-- The lift of an additive monoid hom from `M` to an additive monoid hom from `SeparationQuotient M`. -/] noncomputable def liftContinuousMonoidHom [CommMonoid M] [ContinuousMul M] [CommMonoid N] (f : ContinuousMonoidHom M N) (hf : ∀ x y, Inseparable x y → f x = f y) : ContinuousMonoidHom (SeparationQuotient M) N where toFun := SeparationQuotient.lift f hf map_one' := map_one f map_mul' := Quotient.ind₂ <| map_mul f continuous_toFun := SeparationQuotient.continuous_lift.mpr f.2 @[to_additive (attr := simp)] theorem liftContinuousCommMonoidHom_mk [CommMonoid M] [ContinuousMul M] [CommMonoid N] (f : ContinuousMonoidHom M N) (hf : ∀ x y, Inseparable x y → f x = f y) (x : M) : liftContinuousMonoidHom f hf (mk x) = f x := rfl end Monoid end SeparationQuotient
.lake/packages/mathlib/Mathlib/Topology/Algebra/SeparationQuotient/FiniteDimensional.lean
import Mathlib.Topology.Algebra.SeparationQuotient.Basic import Mathlib.RingTheory.Finiteness.Basic /-! # Separation quotient is a finite module In this file we show that the separation quotient of a finite module is a finite module. -/ /-- The separation quotient of a finite module is a finite module. -/ instance SeparationQuotient.instModuleFinite {R M : Type*} [Semiring R] [AddCommMonoid M] [Module R M] [Module.Finite R M] [TopologicalSpace M] [ContinuousAdd M] [ContinuousConstSMul R M] : Module.Finite R (SeparationQuotient M) := Module.Finite.of_surjective (mkCLM R M).toLinearMap Quotient.mk_surjective
.lake/packages/mathlib/Mathlib/Topology/Defs/Basic.lean
import Mathlib.Order.SetNotation import Mathlib.Tactic.Continuity import Mathlib.Tactic.FunProp import Mathlib.Tactic.MkIffOfInductiveProp import Mathlib.Tactic.ToAdditive import Mathlib.Util.AssertExists /-! # Basic definitions about topological spaces This file contains definitions about topology that do not require imports other than `Mathlib/Data/Set/Lattice.lean`. ## Main definitions * `TopologicalSpace X`: a typeclass endowing `X` with a topology. By definition, a topology is a collection of sets called *open sets* such that - `isOpen_univ`: the whole space is open; - `IsOpen.inter`: the intersection of two open sets is an open set; - `isOpen_sUnion`: the union of a family of open sets is an open set. * `IsOpen s`: predicate saying that `s` is an open set, same as `TopologicalSpace.IsOpen`. * `IsClosed s`: a set is called *closed*, if its complement is an open set. For technical reasons, this is a typeclass. * `IsClopen s`: a set is *clopen* if it is both closed and open. * `interior s`: the *interior* of a set `s` is the maximal open set that is included in `s`. * `closure s`: the *closure* of a set `s` is the minimal closed set that includes `s`. * `frontier s`: the *frontier* of a set is the set difference `closure s \ interior s`. A point `x` belongs to `frontier s`, if any neighborhood of `x` contains points both from `s` and `sᶜ`. * `Dense s`: a set is *dense* if its closure is the whole space. We define it as `∀ x, x ∈ closure s` so that one can write `(h : Dense s) x`. * `DenseRange f`: a function has *dense range*, if `Set.range f` is a dense set. * `Continuous f`: a map is *continuous*, if the preimage of any open set is an open set. * `IsOpenMap f`: a map is an *open map*, if the image of any open set is an open set. * `IsClosedMap f`: a map is a *closed map*, if the image of any closed set is a closed set. ** Notation We introduce notation `IsOpen[t]`, `IsClosed[t]`, `closure[t]`, `Continuous[t₁, t₂]` that allow passing custom topologies to these predicates and functions without using `@`. -/ assert_not_exists Monoid universe u v open Set /-- A topology on `X`. -/ class TopologicalSpace (X : Type u) where /-- A predicate saying that a set is an open set. Use `IsOpen` in the root namespace instead. -/ protected IsOpen : Set X → Prop /-- The set representing the whole space is an open set. Use `isOpen_univ` in the root namespace instead. -/ protected isOpen_univ : IsOpen univ /-- The intersection of two open sets is an open set. Use `IsOpen.inter` instead. -/ protected isOpen_inter : ∀ s t, IsOpen s → IsOpen t → IsOpen (s ∩ t) /-- The union of a family of open sets is an open set. Use `isOpen_sUnion` in the root namespace instead. -/ protected isOpen_sUnion : ∀ s, (∀ t ∈ s, IsOpen t) → IsOpen (⋃₀ s) variable {X : Type u} {Y : Type v} /-! ### Predicates on sets -/ section Defs variable [TopologicalSpace X] [TopologicalSpace Y] {s t : Set X} /-- `IsOpen s` means that `s` is open in the ambient topological space on `X` -/ def IsOpen : Set X → Prop := TopologicalSpace.IsOpen @[simp] theorem isOpen_univ : IsOpen (univ : Set X) := TopologicalSpace.isOpen_univ theorem IsOpen.inter (hs : IsOpen s) (ht : IsOpen t) : IsOpen (s ∩ t) := TopologicalSpace.isOpen_inter s t hs ht theorem isOpen_sUnion {s : Set (Set X)} (h : ∀ t ∈ s, IsOpen t) : IsOpen (⋃₀ s) := TopologicalSpace.isOpen_sUnion s h /-- A set is closed if its complement is open -/ class IsClosed (s : Set X) : Prop where /-- The complement of a closed set is an open set. -/ isOpen_compl : IsOpen sᶜ /-- A set is clopen if it is both closed and open. -/ def IsClopen (s : Set X) : Prop := IsClosed s ∧ IsOpen s /-- A set is locally closed if it is the intersection of some open set and some closed set. Also see `isLocallyClosed_tfae` and other lemmas in `Mathlib/Topology/LocallyClosed.lean`. -/ def IsLocallyClosed (s : Set X) : Prop := ∃ (U Z : Set X), IsOpen U ∧ IsClosed Z ∧ s = U ∩ Z /-- The interior of a set `s` is the largest open subset of `s`. -/ def interior (s : Set X) : Set X := ⋃₀ { t | IsOpen t ∧ t ⊆ s } /-- The closure of `s` is the smallest closed set containing `s`. -/ def closure (s : Set X) : Set X := ⋂₀ { t | IsClosed t ∧ s ⊆ t } /-- The frontier of a set is the set of points between the closure and interior. -/ def frontier (s : Set X) : Set X := closure s \ interior s /-- The coborder is defined as the complement of `closure s \ s`, or the union of `s` and the complement of `∂(s)`. This is the largest set in which `s` is closed, and `s` is locally closed if and only if `coborder s` is open. This is unnamed in the literature, and this name is due to the fact that `coborder s = (border sᶜ)ᶜ` where `border s = s \ interior s` is the border in the sense of Hausdorff. -/ def coborder (s : Set X) : Set X := (closure s \ s)ᶜ /-- A set is dense in a topological space if every point belongs to its closure. -/ def Dense (s : Set X) : Prop := ∀ x, x ∈ closure s /-- `f : α → X` has dense range if its range (image) is a dense subset of `X`. -/ def DenseRange {α : Type*} (f : α → X) := Dense (range f) /-- A function between topological spaces is continuous if the preimage of every open set is open. Registered as a structure to make sure it is not unfolded by Lean. -/ @[fun_prop] structure Continuous (f : X → Y) : Prop where /-- The preimage of an open set under a continuous function is an open set. Use `IsOpen.preimage` instead. -/ isOpen_preimage : ∀ s, IsOpen s → IsOpen (f ⁻¹' s) /-- A map `f : X → Y` is said to be an *open map*, if the image of any open `U : Set X` is open in `Y`. -/ def IsOpenMap (f : X → Y) : Prop := ∀ U : Set X, IsOpen U → IsOpen (f '' U) /-- A map `f : X → Y` is said to be a *closed map*, if the image of any closed `U : Set X` is closed in `Y`. -/ def IsClosedMap (f : X → Y) : Prop := ∀ U : Set X, IsClosed U → IsClosed (f '' U) /-- An open quotient map is an open map `f : X → Y` which is both an open map and a quotient map. Equivalently, it is a surjective continuous open map. We use the latter characterization as a definition. Many important quotient maps are open quotient maps, including - the quotient map from a topological space to its quotient by the action of a group; - the quotient map from a topological group to its quotient by a normal subgroup; - the quotient map from a topological space to its separation quotient. Contrary to general quotient maps, the category of open quotient maps is closed under `Prod.map`. -/ @[mk_iff] structure IsOpenQuotientMap (f : X → Y) : Prop where /-- An open quotient map is surjective. -/ surjective : Function.Surjective f /-- An open quotient map is continuous. -/ continuous : Continuous f /-- An open quotient map is an open map. -/ isOpenMap : IsOpenMap f end Defs /-! ### Notation for non-standard topologies -/ /-- Notation for `IsOpen` with respect to a non-standard topology. -/ scoped[Topology] notation (name := IsOpen_of) "IsOpen[" t "]" => @IsOpen _ t /-- Notation for `IsClosed` with respect to a non-standard topology. -/ scoped[Topology] notation (name := IsClosed_of) "IsClosed[" t "]" => @IsClosed _ t /-- Notation for `closure` with respect to a non-standard topology. -/ scoped[Topology] notation (name := closure_of) "closure[" t "]" => @closure _ t /-- Notation for `Continuous` with respect to a non-standard topologies. -/ scoped[Topology] notation (name := Continuous_of) "Continuous[" t₁ ", " t₂ "]" => @Continuous _ _ t₁ t₂ /-- The property `BaireSpace α` means that the topological space `α` has the Baire property: any countable intersection of open dense subsets is dense. Formulated here when the source space is ℕ. Use `dense_iInter_of_isOpen` which works for any countable index type instead. -/ class BaireSpace (X : Type*) [TopologicalSpace X] : Prop where baire_property : ∀ f : ℕ → Set X, (∀ n, IsOpen (f n)) → (∀ n, Dense (f n)) → Dense (⋂ n, f n)
.lake/packages/mathlib/Mathlib/Topology/Defs/Filter.lean
import Mathlib.Topology.Defs.Basic import Mathlib.Data.Setoid.Basic import Mathlib.Order.Filter.Defs import Mathlib.Tactic.IrreducibleDef /-! # Definitions about filters in topological spaces In this file we define filters in topological spaces, as well as other definitions that rely on `Filter`s. ## Main Definitions ### Neighborhoods filter * `nhds x`: the filter of neighborhoods of a point in a topological space, denoted by `𝓝 x` in the `Topology` scope. A set is called a neighborhood of `x`, if it includes an open set around `x`. * `nhdsWithin x s`: the filter of neighborhoods of a point within a set, defined as `𝓝 x ⊓ 𝓟 s` and denoted by `𝓝[s] x`. We also introduce notation for some special sets `s`, see below. * `nhdsSet s`: the filter of neighborhoods of a set in a topological space, denoted by `𝓝ˢ s` in the `Topology` scope. A set `t` is called a neighborhood of `s`, if it includes an open set that includes `s`. * `nhdsKer s`: The *neighborhoods kernel* of a set is the intersection of all its neighborhoods. In an Alexandrov-discrete space, this is the smallest neighborhood of the set. Note that this construction is unnamed in the literature. We choose the name in analogy to `interior`. ### Continuity at a point * `ContinuousAt f x`: a function `f` is continuous at a point `x`, if it tends to `𝓝 (f x)` along `𝓝 x`. * `ContinuousWithinAt f s x`: a function `f` is continuous within a set `s` at a point `x`, if it tends to `𝓝 (f x)` along `𝓝[s] x`. * `ContinuousOn f s`: a function `f : X → Y` is continuous on a set `s`, if it is continuous within `s` at every point of `s`. ### Limits * `lim f`: a limit of a filter `f` in a nonempty topological space. If there exists `x` such that `f ≤ 𝓝 x`, then `lim f` is one of such points, otherwise it is `Classical.choice _`. In a Hausdorff topological space, the limit is unique if it exists. * `Ultrafilter.lim f`: a limit of an ultrafilter `f`, defined as the limit of `(f : Filter X)` with a proof of `Nonempty X` deduced from existence of an ultrafilter on `X`. * `limUnder f g`: a limit of a filter `f` along a function `g`, defined as `lim (Filter.map g f)`. ### Cluster points and accumulation points * `ClusterPt x F`: a point `x` is a *cluster point* of a filter `F`, if `𝓝 x` is not disjoint with `F`. * `MapClusterPt x F u`: a point `x` is a *cluster point* of a function `u` along a filter `F`, if it is a cluster point of the filter `Filter.map u F`. * `AccPt x F`: a point `x` is an *accumulation point* of a filter `F`, if `𝓝[≠] x` is not disjoint with `F`. Every accumulation point of a filter is its cluster point, but not vice versa. * `IsCompact s`: a set `s` is compact if for every nontrivial filter `f` that contains `s`, there exists `a ∈ s` such that every set of `f` meets every neighborhood of `a`. Equivalently, a set `s` is compact if for any cover of `s` by open sets, there exists a finite subcover. * `CompactSpace`, `NoncompactSpace`: typeclasses saying that the whole space is a compact set / is not a compact set, respectively. * `WeaklyLocallyCompactSpace X`: typeclass saying that every point of `X` has a compact neighborhood. * `LocallyCompactSpace X`: typeclass saying that every point of `X` has a basis of compact neighborhoods. Every locally compact space is a weakly locally compact space. The reverse implication is true for R₁ (preregular) spaces. * `LocallyCompactPair X Y`: an auxiliary typeclass saying that for any continuous function `f : X → Y`, a point `x`, and a neighborhood `s` of `f x`, there exists a compact neighborhood `K` of `x` such that `f` maps `K` to `s`. * `Filter.cocompact`, `Filter.coclosedCompact`: filters generated by complements to compact and closed compact sets, respectively. ## Notation * `𝓝 x`: the filter `nhds x` of neighborhoods of a point `x`; * `𝓟 s`: the principal filter of a set `s`, defined elsewhere; * `𝓝[s] x`: the filter `nhdsWithin x s` of neighborhoods of a point `x` within a set `s`; * `𝓝[≤] x`: the filter `nhdsWithin x (Set.Iic x)` of left-neighborhoods of `x`; * `𝓝[≥] x`: the filter `nhdsWithin x (Set.Ici x)` of right-neighborhoods of `x`; * `𝓝[<] x`: the filter `nhdsWithin x (Set.Iio x)` of punctured left-neighborhoods of `x`; * `𝓝[>] x`: the filter `nhdsWithin x (Set.Ioi x)` of punctured right-neighborhoods of `x`; * `𝓝[≠] x`: the filter `nhdsWithin x {x}ᶜ` of punctured neighborhoods of `x`; * `𝓝ˢ s`: the filter `nhdsSet s` of neighborhoods of a set. -/ assert_not_exists Ultrafilter variable {X Y : Type*} [TopologicalSpace X] [TopologicalSpace Y] open Filter open scoped Topology /-- A set is called a neighborhood of `x` if it contains an open set around `x`. The set of all neighborhoods of `x` forms a filter, the neighborhood filter at `x`, is here defined as the infimum over the principal filters of all open sets containing `x`. -/ irreducible_def nhds (x : X) : Filter X := ⨅ s ∈ { s : Set X | x ∈ s ∧ IsOpen s }, 𝓟 s @[inherit_doc] scoped[Topology] notation "𝓝" => nhds /-- The "neighborhood within" filter. Elements of `𝓝[s] x` are sets containing the intersection of `s` and a neighborhood of `x`. -/ def nhdsWithin (x : X) (s : Set X) : Filter X := 𝓝 x ⊓ 𝓟 s @[inherit_doc] scoped[Topology] notation "𝓝[" s "] " x:100 => nhdsWithin x s /-- Notation for the filter of punctured neighborhoods of a point. -/ scoped[Topology] notation3 (name := nhdsNE) "𝓝[≠] " x:100 => nhdsWithin x (@singleton _ (Set _) Set.instSingletonSet x)ᶜ /-- Notation for the filter of right neighborhoods of a point. -/ scoped[Topology] notation3 (name := nhdsGE) "𝓝[≥] " x:100 => nhdsWithin x (Set.Ici x) /-- Notation for the filter of left neighborhoods of a point. -/ scoped[Topology] notation3 (name := nhdsLE) "𝓝[≤] " x:100 => nhdsWithin x (Set.Iic x) /-- Notation for the filter of punctured right neighborhoods of a point. -/ scoped[Topology] notation3 (name := nhdsGT) "𝓝[>] " x:100 => nhdsWithin x (Set.Ioi x) /-- Notation for the filter of punctured left neighborhoods of a point. -/ scoped[Topology] notation3 (name := nhdsLT) "𝓝[<] " x:100 => nhdsWithin x (Set.Iio x) /-- The filter of neighborhoods of a set in a topological space. -/ def nhdsSet (s : Set X) : Filter X := sSup (nhds '' s) @[inherit_doc] scoped[Topology] notation "𝓝ˢ" => nhdsSet /-- The *neighborhoods kernel* of a set is the intersection of all its neighborhoods. In an Alexandrov-discrete space, this is the smallest neighborhood of the set. -/ def nhdsKer (s : Set X) : Set X := (𝓝ˢ s).ker @[deprecated (since := "2025-07-09")] alias exterior := nhdsKer /-- A function between topological spaces is continuous at a point `x₀` if `f x` tends to `f x₀` when `x` tends to `x₀`. -/ @[fun_prop] def ContinuousAt (f : X → Y) (x : X) := Tendsto f (𝓝 x) (𝓝 (f x)) /-- A function between topological spaces is continuous at a point `x₀` within a subset `s` if `f x` tends to `f x₀` when `x` tends to `x₀` while staying within `s`. -/ @[fun_prop] def ContinuousWithinAt (f : X → Y) (s : Set X) (x : X) : Prop := Tendsto f (𝓝[s] x) (𝓝 (f x)) /-- A function between topological spaces is continuous on a subset `s` when it's continuous at every point of `s` within `s`. -/ @[fun_prop] def ContinuousOn (f : X → Y) (s : Set X) : Prop := ∀ x ∈ s, ContinuousWithinAt f s x /-- `x` specializes to `y` (notation: `x ⤳ y`) if either of the following equivalent properties hold: * `𝓝 x ≤ 𝓝 y`; this property is used as the definition; * `pure x ≤ 𝓝 y`; in other words, any neighbourhood of `y` contains `x`; * `y ∈ closure {x}`; * `closure {y} ⊆ closure {x}`; * for any closed set `s` we have `x ∈ s → y ∈ s`; * for any open set `s` we have `y ∈ s → x ∈ s`; * `y` is a cluster point of the filter `pure x = 𝓟 {x}`. This relation defines a `Preorder` on `X`. If `X` is a T₀ space, then this preorder is a partial order. If `X` is a T₁ space, then this partial order is trivial : `x ⤳ y ↔ x = y`. -/ def Specializes (x y : X) : Prop := 𝓝 x ≤ 𝓝 y @[inherit_doc] infixl:300 " ⤳ " => Specializes /-- Two points `x` and `y` in a topological space are `Inseparable` if any of the following equivalent properties hold: - `𝓝 x = 𝓝 y`; we use this property as the definition; - for any open set `s`, `x ∈ s ↔ y ∈ s`, see `inseparable_iff_forall_isOpen`; - for any closed set `s`, `x ∈ s ↔ y ∈ s`, see `inseparable_iff_forall_isClosed`; - `x ∈ closure {y}` and `y ∈ closure {x}`, see `inseparable_iff_mem_closure`; - `closure {x} = closure {y}`, see `inseparable_iff_closure_eq`. -/ def Inseparable (x y : X) : Prop := 𝓝 x = 𝓝 y variable (X) /-- Specialization forms a preorder on the topological space. -/ def specializationPreorder : Preorder X := { Preorder.lift (OrderDual.toDual ∘ 𝓝) with le := fun x y => y ⤳ x lt := fun x y => y ⤳ x ∧ ¬x ⤳ y } /-- A `setoid` version of `Inseparable`, used to define the `SeparationQuotient`. -/ def inseparableSetoid : Setoid X := { Setoid.comap 𝓝 ⊥ with r := Inseparable } /-- The quotient of a topological space by its `inseparableSetoid`. This quotient is guaranteed to be a T₀ space. -/ def SeparationQuotient := Quotient (inseparableSetoid X) variable {X} section Lim /-- If `f` is a filter, then `Filter.lim f` is a limit of the filter, if it exists. -/ noncomputable def lim [Nonempty X] (f : Filter X) : X := Classical.epsilon fun x => f ≤ 𝓝 x /-- If `f` is a filter in `α` and `g : α → X` is a function, then `limUnder f g` is a limit of `g` at `f`, if it exists. -/ noncomputable def limUnder {α : Type*} [Nonempty X] (f : Filter α) (g : α → X) : X := lim (f.map g) end Lim /-- A point `x` is a cluster point of a filter `F` if `𝓝 x ⊓ F ≠ ⊥`. Also known as an accumulation point or a limit point, but beware that terminology varies. This is *not* the same as asking `𝓝[≠] x ⊓ F ≠ ⊥`, which is called `AccPt` in Mathlib. See `mem_closure_iff_clusterPt` in particular. -/ def ClusterPt (x : X) (F : Filter X) : Prop := NeBot (𝓝 x ⊓ F) /-- A point `x` is a cluster point of a sequence `u` along a filter `F` if it is a cluster point of `map u F`. -/ def MapClusterPt {ι : Type*} (x : X) (F : Filter ι) (u : ι → X) : Prop := ClusterPt x (map u F) /-- A point `x` is an accumulation point of a filter `F` if `𝓝[≠] x ⊓ F ≠ ⊥`. See also `ClusterPt`. -/ def AccPt (x : X) (F : Filter X) : Prop := NeBot (𝓝[≠] x ⊓ F) /-- A set `s` is compact if for every nontrivial filter `f` that contains `s`, there exists `a ∈ s` such that every set of `f` meets every neighborhood of `a`. -/ def IsCompact (s : Set X) := ∀ ⦃f⦄ [NeBot f], f ≤ 𝓟 s → ∃ x ∈ s, ClusterPt x f variable (X) in /-- Type class for compact spaces. Separation is sometimes included in the definition, especially in the French literature, but we do not include it here. -/ class CompactSpace : Prop where /-- In a compact space, `Set.univ` is a compact set. -/ isCompact_univ : IsCompact (Set.univ : Set X) variable (X) in /-- `X` is a noncompact topological space if it is not a compact space. -/ class NoncompactSpace : Prop where /-- In a noncompact space, `Set.univ` is not a compact set. -/ noncompact_univ : ¬IsCompact (Set.univ : Set X) /-- We say that a topological space is a *weakly locally compact space*, if each point of this space admits a compact neighborhood. -/ class WeaklyLocallyCompactSpace (X : Type*) [TopologicalSpace X] : Prop where /-- Every point of a weakly locally compact space admits a compact neighborhood. -/ exists_compact_mem_nhds (x : X) : ∃ s, IsCompact s ∧ s ∈ 𝓝 x export WeaklyLocallyCompactSpace (exists_compact_mem_nhds) /-- There are various definitions of "locally compact space" in the literature, which agree for Hausdorff spaces but not in general. This one is the precise condition on X needed for the evaluation map `C(X, Y) × X → Y` to be continuous for all `Y` when `C(X, Y)` is given the compact-open topology. See also `WeaklyLocallyCompactSpace`, a typeclass that only assumes that each point has a compact neighborhood. -/ class LocallyCompactSpace (X : Type*) [TopologicalSpace X] : Prop where /-- In a locally compact space, every neighbourhood of every point contains a compact neighbourhood of that same point. -/ local_compact_nhds : ∀ (x : X), ∀ n ∈ 𝓝 x, ∃ s ∈ 𝓝 x, s ⊆ n ∧ IsCompact s /-- We say that `X` and `Y` are a locally compact pair of topological spaces, if for any continuous map `f : X → Y`, a point `x : X`, and a neighbourhood `s ∈ 𝓝 (f x)`, there exists a compact neighbourhood `K ∈ 𝓝 x` such that `f` maps `K` to `s`. This is a technical assumption that appears in several theorems, most notably in `ContinuousMap.continuous_comp'` and `ContinuousMap.continuous_eval`. It is satisfied in two cases: - if `X` is a locally compact topological space, for obvious reasons; - if `X` is a weakly locally compact topological space and `Y` is an R₁ space; this fact is a simple generalization of the theorem saying that a weakly locally compact R₁ topological space is locally compact. -/ class LocallyCompactPair (X Y : Type*) [TopologicalSpace X] [TopologicalSpace Y] : Prop where /-- If `f : X → Y` is a continuous map in a locally compact pair of topological spaces and `s : Set Y` is a neighbourhood of `f x`, `x : X`, then there exists a compact neighbourhood `K` of `x` such that `f` maps `K` to `s`. -/ exists_mem_nhds_isCompact_mapsTo : ∀ {f : X → Y} {x : X} {s : Set Y}, Continuous f → s ∈ 𝓝 (f x) → ∃ K ∈ 𝓝 x, IsCompact K ∧ Set.MapsTo f K s export LocallyCompactPair (exists_mem_nhds_isCompact_mapsTo) variable (X) in /-- `Filter.cocompact` is the filter generated by complements to compact sets. -/ def Filter.cocompact : Filter X := ⨅ (s : Set X) (_ : IsCompact s), 𝓟 sᶜ variable (X) in /-- `Filter.coclosedCompact` is the filter generated by complements to closed compact sets. In a Hausdorff space, this is the same as `Filter.cocompact`. -/ def Filter.coclosedCompact : Filter X := ⨅ (s : Set X) (_ : IsClosed s) (_ : IsCompact s), 𝓟 sᶜ
.lake/packages/mathlib/Mathlib/Topology/Defs/Ultrafilter.lean
import Mathlib.Data.Set.Lattice import Mathlib.Order.Filter.Ultrafilter.Defs import Mathlib.Topology.Defs.Basic import Mathlib.Topology.Defs.Filter /-! # Limit of an ultrafilter. * `Ultrafilter.lim f`: a limit of an ultrafilter `f`, defined as the limit of `(f : Filter X)` with a proof of `Nonempty X` deduced from existence of an ultrafilter on `X`. -/ variable {X : Type*} [TopologicalSpace X] open Filter /-- If `F` is an ultrafilter, then `Filter.Ultrafilter.lim F` is a limit of the filter, if it exists. Note that dot notation `F.lim` can be used for `F : Filter.Ultrafilter X`. -/ noncomputable nonrec def Ultrafilter.lim (F : Ultrafilter X) : X := @lim X _ (nonempty_of_neBot F) F
.lake/packages/mathlib/Mathlib/Topology/Defs/Sequences.lean
import Mathlib.Order.Filter.AtTopBot.Defs import Mathlib.Topology.Defs.Filter /-! # Sequences in topological spaces In this file we define sequential closure, continuity, compactness etc. ## Main definitions ### Set operation * `seqClosure s`: sequential closure of a set, the set of limits of sequences of points of `s`; ### Predicates * `IsSeqClosed s`: predicate saying that a set is sequentially closed, i.e., `seqClosure s ⊆ s`; * `SeqContinuous f`: predicate saying that a function is sequentially continuous, i.e., for any sequence `u : ℕ → X` that converges to a point `x`, the sequence `f ∘ u` converges to `f x`; * `IsSeqCompact s`: predicate saying that a set is sequentially compact, i.e., every sequence taking values in `s` has a converging subsequence. ### Type classes * `FrechetUrysohnSpace X`: a typeclass saying that a topological space is a *Fréchet-Urysohn space*, i.e., the sequential closure of any set is equal to its closure. * `SequentialSpace X`: a typeclass saying that a topological space is a *sequential space*, i.e., any sequentially closed set in this space is closed. This condition is weaker than being a Fréchet-Urysohn space. * `SeqCompactSpace X`: a typeclass saying that a topological space is sequentially compact, i.e., every sequence in `X` has a converging subsequence. ## Tags sequentially closed, sequentially compact, sequential space -/ open Set Filter open scoped Topology variable {X Y : Type*} [TopologicalSpace X] [TopologicalSpace Y] /-- The sequential closure of a set `s : Set X` in a topological space `X` is the set of all `a : X` which arise as limit of sequences in `s`. Note that the sequential closure of a set is not guaranteed to be sequentially closed. -/ def seqClosure (s : Set X) : Set X := { a | ∃ x : ℕ → X, (∀ n : ℕ, x n ∈ s) ∧ Tendsto x atTop (𝓝 a) } /-- A set `s` is sequentially closed if for any converging sequence `x n` of elements of `s`, the limit belongs to `s` as well. Note that the sequential closure of a set is not guaranteed to be sequentially closed. -/ def IsSeqClosed (s : Set X) : Prop := ∀ ⦃x : ℕ → X⦄ ⦃p : X⦄, (∀ n, x n ∈ s) → Tendsto x atTop (𝓝 p) → p ∈ s /-- A function between topological spaces is sequentially continuous if it commutes with limit of convergent sequences. -/ def SeqContinuous (f : X → Y) : Prop := ∀ ⦃x : ℕ → X⦄ ⦃p : X⦄, Tendsto x atTop (𝓝 p) → Tendsto (f ∘ x) atTop (𝓝 (f p)) /-- A set `s` is sequentially compact if every sequence taking values in `s` has a converging subsequence. -/ def IsSeqCompact (s : Set X) := ∀ ⦃x : ℕ → X⦄, (∀ n, x n ∈ s) → ∃ a ∈ s, ∃ φ : ℕ → ℕ, StrictMono φ ∧ Tendsto (x ∘ φ) atTop (𝓝 a) variable (X) /-- A space `X` is sequentially compact if every sequence in `X` has a converging subsequence. -/ @[mk_iff] class SeqCompactSpace : Prop where isSeqCompact_univ : IsSeqCompact (univ : Set X) export SeqCompactSpace (isSeqCompact_univ) /-- A topological space is called a *Fréchet-Urysohn space*, if the sequential closure of any set is equal to its closure. Since one of the inclusions is trivial, we require only the non-trivial one in the definition. -/ class FrechetUrysohnSpace : Prop where closure_subset_seqClosure : ∀ s : Set X, closure s ⊆ seqClosure s /-- A topological space is said to be a *sequential space* if any sequentially closed set in this space is closed. This condition is weaker than being a Fréchet-Urysohn space. -/ class SequentialSpace : Prop where isClosed_of_seq : ∀ s : Set X, IsSeqClosed s → IsClosed s variable {X} /-- In a sequential space, a sequentially closed set is closed. -/ protected theorem IsSeqClosed.isClosed [SequentialSpace X] {s : Set X} (hs : IsSeqClosed s) : IsClosed s := SequentialSpace.isClosed_of_seq s hs
.lake/packages/mathlib/Mathlib/Topology/Defs/Induced.lean
import Mathlib.Data.Set.Lattice.Image import Mathlib.Topology.Basic /-! # Induced and coinduced topologies In this file we define the induced and coinduced topologies, as well as topology inducing maps, topological embeddings, and quotient maps. ## Main definitions * `TopologicalSpace.induced`: given `f : X → Y` and a topology on `Y`, the induced topology on `X` is the collection of sets that are preimages of some open set in `Y`. This is the coarsest topology that makes `f` continuous. * `TopologicalSpace.coinduced`: given `f : X → Y` and a topology on `X`, the coinduced topology on `Y` is defined such that `s : Set Y` is open if the preimage of `s` is open. This is the finest topology that makes `f` continuous. * `IsInducing`: a map `f : X → Y` is called *inducing*, if the topology on the domain is equal to the induced topology. * `IsEmbedding`: a map `f : X → Y` is an *embedding*, if it is a topology inducing map and it is injective. * `IsOpenEmbedding`: a map `f : X → Y` is an *open embedding*, if it is an embedding and its range is open. An open embedding is an open map. * `IsClosedEmbedding`: a map `f : X → Y` is an *open embedding*, if it is an embedding and its range is open. An open embedding is an open map. * `IsQuotientMap`: a map `f : X → Y` is a *quotient map*, if it is surjective and the topology on the codomain is equal to the coinduced topology. -/ open Set open scoped Topology namespace TopologicalSpace variable {X Y : Type*} /-- Given `f : X → Y` and a topology on `Y`, the induced topology on `X` is the collection of sets that are preimages of some open set in `Y`. This is the coarsest topology that makes `f` continuous. -/ def induced (f : X → Y) (t : TopologicalSpace Y) : TopologicalSpace X where IsOpen s := ∃ t, IsOpen t ∧ f ⁻¹' t = s isOpen_univ := ⟨univ, isOpen_univ, preimage_univ⟩ isOpen_inter := by rintro s₁ s₂ ⟨s'₁, hs₁, rfl⟩ ⟨s'₂, hs₂, rfl⟩ exact ⟨s'₁ ∩ s'₂, hs₁.inter hs₂, preimage_inter⟩ isOpen_sUnion S h := by choose! g hgo hfg using h refine ⟨⋃₀ (g '' S), isOpen_sUnion <| forall_mem_image.2 hgo, ?_⟩ rw [preimage_sUnion, biUnion_image, sUnion_eq_biUnion] exact iUnion₂_congr hfg instance _root_.instTopologicalSpaceSubtype {p : X → Prop} [t : TopologicalSpace X] : TopologicalSpace (Subtype p) := induced (↑) t /-- Given `f : X → Y` and a topology on `X`, the coinduced topology on `Y` is defined such that `s : Set Y` is open if the preimage of `s` is open. This is the finest topology that makes `f` continuous. -/ def coinduced (f : X → Y) (t : TopologicalSpace X) : TopologicalSpace Y where IsOpen s := IsOpen (f ⁻¹' s) isOpen_univ := t.isOpen_univ isOpen_inter _ _ h₁ h₂ := h₁.inter h₂ isOpen_sUnion s h := by simpa only [preimage_sUnion] using isOpen_biUnion h end TopologicalSpace namespace Topology variable {X Y : Type*} [tX : TopologicalSpace X] [tY : TopologicalSpace Y] /-- We say that restrictions of the topology on `X` to sets from a family `S` generates the original topology, if either of the following equivalent conditions hold: - a set which is relatively open in each `s ∈ S` is open; - a set which is relatively closed in each `s ∈ S` is closed; - for any topological space `Y`, a function `f : X → Y` is continuous provided that it is continuous on each `s ∈ S`. -/ structure IsCoherentWith (S : Set (Set X)) : Prop where isOpen_of_forall_induced (u : Set X) : (∀ s ∈ S, IsOpen ((↑) ⁻¹' u : Set s)) → IsOpen u /-- A function `f : X → Y` between topological spaces is inducing if the topology on `X` is induced by the topology on `Y` through `f`, meaning that a set `s : Set X` is open iff it is the preimage under `f` of some open set `t : Set Y`. -/ @[fun_prop, mk_iff] structure IsInducing (f : X → Y) : Prop where /-- The topology on the domain is equal to the induced topology. -/ eq_induced : tX = tY.induced f /-- A function between topological spaces is an embedding if it is injective, and for all `s : Set X`, `s` is open iff it is the preimage of an open set. -/ @[fun_prop, mk_iff] structure IsEmbedding (f : X → Y) : Prop extends IsInducing f where /-- A topological embedding is injective. -/ injective : Function.Injective f /-- An open embedding is an embedding with open range. -/ @[fun_prop, mk_iff] structure IsOpenEmbedding (f : X → Y) : Prop extends IsEmbedding f where /-- The range of an open embedding is an open set. -/ isOpen_range : IsOpen <| range f /-- A closed embedding is an embedding with closed image. -/ @[fun_prop, mk_iff] structure IsClosedEmbedding (f : X → Y) : Prop extends IsEmbedding f where /-- The range of a closed embedding is a closed set. -/ isClosed_range : IsClosed <| range f /-- A function between topological spaces is a quotient map if it is surjective, and for all `s : Set Y`, `s` is open iff its preimage is an open set. -/ @[fun_prop, mk_iff isQuotientMap_iff'] structure IsQuotientMap {X : Type*} {Y : Type*} [tX : TopologicalSpace X] [tY : TopologicalSpace Y] (f : X → Y) : Prop where surjective : Function.Surjective f eq_coinduced : tY = tX.coinduced f end Topology
.lake/packages/mathlib/Mathlib/Topology/Sheaves/Stalks.lean
import Mathlib.Topology.Category.TopCat.OpenNhds import Mathlib.Topology.Sheaves.SheafCondition.UniqueGluing /-! # Stalks For a presheaf `F` on a topological space `X`, valued in some category `C`, the *stalk* of `F` at the point `x : X` is defined as the colimit of the composition of the inclusion of categories `(OpenNhds x)ᵒᵖ ⥤ (Opens X)ᵒᵖ` and the functor `F : (Opens X)ᵒᵖ ⥤ C`. For an open neighborhood `U` of `x`, we define the map `F.germ x : F.obj (op U) ⟶ F.stalk x` as the canonical morphism into this colimit. Taking stalks is functorial: For every point `x : X` we define a functor `stalkFunctor C x`, sending presheaves on `X` to objects of `C`. Furthermore, for a map `f : X ⟶ Y` between topological spaces, we define `stalkPushforward` as the induced map on the stalks `(f _* ℱ).stalk (f x) ⟶ ℱ.stalk x`. Some lemmas about stalks and germs only hold for certain classes of concrete categories. A basic property of forgetful functors of categories of algebraic structures (like `MonCat`, `CommRingCat`,...) is that they preserve filtered colimits. Since stalks are filtered colimits, this ensures that the stalks of presheaves valued in these categories behave exactly as for `Type`-valued presheaves. For example, in `germ_exist` we prove that in such a category, every element of the stalk is the germ of a section. Furthermore, if we require the forgetful functor to reflect isomorphisms and preserve limits (as is the case for most algebraic structures), we have access to the unique gluing API and can prove further properties. Most notably, in `is_iso_iff_stalk_functor_map_iso`, we prove that in such a category, a morphism of sheaves is an isomorphism if and only if all of its stalk maps are isomorphisms. See also the definition of "algebraic structures" in the stacks project: https://stacks.math.columbia.edu/tag/007L -/ assert_not_exists IsOrderedMonoid noncomputable section universe v u v' u' open CategoryTheory open TopCat open CategoryTheory.Limits CategoryTheory.Functor open TopologicalSpace Topology open Opposite open scoped AlgebraicGeometry variable {C : Type u} [Category.{v} C] variable [HasColimits.{v} C] variable {X Y Z : TopCat.{v}} namespace TopCat.Presheaf variable (C) in /-- Stalks are functorial with respect to morphisms of presheaves over a fixed `X`. -/ def stalkFunctor (x : X) : X.Presheaf C ⥤ C := (whiskeringLeft _ _ C).obj (OpenNhds.inclusion x).op ⋙ colim /-- The stalk of a presheaf `F` at a point `x` is calculated as the colimit of the functor nbhds x ⥤ opens F.X ⥤ C -/ def stalk (ℱ : X.Presheaf C) (x : X) : C := (stalkFunctor C x).obj ℱ -- -- colimit ((open_nhds.inclusion x).op ⋙ ℱ) @[simp] theorem stalkFunctor_obj (ℱ : X.Presheaf C) (x : X) : (stalkFunctor C x).obj ℱ = ℱ.stalk x := rfl /-- The germ of a section of a presheaf over an open at a point of that open. -/ def germ (F : X.Presheaf C) (U : Opens X) (x : X) (hx : x ∈ U) : F.obj (op U) ⟶ stalk F x := colimit.ι ((OpenNhds.inclusion x).op ⋙ F) (op ⟨U, hx⟩) /-- The germ of a global section of a presheaf at a point. -/ def Γgerm (F : X.Presheaf C) (x : X) : F.obj (op ⊤) ⟶ stalk F x := F.germ ⊤ x True.intro @[reassoc] theorem germ_res (F : X.Presheaf C) {U V : Opens X} (i : U ⟶ V) (x : X) (hx : x ∈ U) : F.map i.op ≫ F.germ U x hx = F.germ V x (i.le hx) := let i' : (⟨U, hx⟩ : OpenNhds x) ⟶ ⟨V, i.le hx⟩ := i colimit.w ((OpenNhds.inclusion x).op ⋙ F) i'.op /-- A variant of `germ_res` with `op V ⟶ op U` so that the LHS is more general and simp fires more easier. -/ @[reassoc (attr := simp)] theorem germ_res' (F : X.Presheaf C) {U V : Opens X} (i : op V ⟶ op U) (x : X) (hx : x ∈ U) : F.map i ≫ F.germ U x hx = F.germ V x (i.unop.le hx) := let i' : (⟨U, hx⟩ : OpenNhds x) ⟶ ⟨V, i.unop.le hx⟩ := i.unop colimit.w ((OpenNhds.inclusion x).op ⋙ F) i'.op @[reassoc] lemma map_germ_eq_Γgerm (F : X.Presheaf C) {U : Opens X} {i : U ⟶ ⊤} (x : X) (hx : x ∈ U) : F.map i.op ≫ F.germ U x hx = F.Γgerm x := germ_res F i x hx variable {FC : C → C → Type*} {CC : C → Type*} [∀ X Y, FunLike (FC X Y) (CC X) (CC Y)] theorem germ_res_apply (F : X.Presheaf C) {U V : Opens X} (i : U ⟶ V) (x : X) (hx : x ∈ U) [ConcreteCategory C FC] (s) : F.germ U x hx (F.map i.op s) = F.germ V x (i.le hx) s := by rw [← ConcreteCategory.comp_apply, germ_res] theorem germ_res_apply' (F : X.Presheaf C) {U V : Opens X} (i : op V ⟶ op U) (x : X) (hx : x ∈ U) [ConcreteCategory C FC] (s) : F.germ U x hx (F.map i s) = F.germ V x (i.unop.le hx) s := by rw [← ConcreteCategory.comp_apply, germ_res'] lemma Γgerm_res_apply (F : X.Presheaf C) {U : Opens X} {i : U ⟶ ⊤} (x : X) (hx : x ∈ U) [ConcreteCategory C FC] (s) : F.germ U x hx (F.map i.op s) = F.Γgerm x s := F.germ_res_apply i x hx s /-- A morphism from the stalk of `F` at `x` to some object `Y` is completely determined by its composition with the `germ` morphisms. -/ @[ext] theorem stalk_hom_ext (F : X.Presheaf C) {x} {Y : C} {f₁ f₂ : F.stalk x ⟶ Y} (ih : ∀ (U : Opens X) (hxU : x ∈ U), F.germ U x hxU ≫ f₁ = F.germ U x hxU ≫ f₂) : f₁ = f₂ := colimit.hom_ext fun U => by induction U with | op U => obtain ⟨U, hxU⟩ := U; exact ih U hxU @[reassoc (attr := simp)] theorem stalkFunctor_map_germ {F G : X.Presheaf C} (U : Opens X) (x : X) (hx : x ∈ U) (f : F ⟶ G) : F.germ U x hx ≫ (stalkFunctor C x).map f = f.app (op U) ≫ G.germ U x hx := colimit.ι_map (whiskerLeft (OpenNhds.inclusion x).op f) (op ⟨U, hx⟩) theorem stalkFunctor_map_germ_apply [ConcreteCategory C FC] {F G : X.Presheaf C} (U : Opens X) (x : X) (hx : x ∈ U) (f : F ⟶ G) (s) : (stalkFunctor C x).map f (F.germ U x hx s) = G.germ U x hx (f.app (op U) s) := by rw [← ConcreteCategory.comp_apply, ← stalkFunctor_map_germ, ConcreteCategory.comp_apply] rfl -- a variant of `stalkFunctor_map_germ_apply` that makes simpNF happy. @[simp] theorem stalkFunctor_map_germ_apply' [ConcreteCategory C FC] {F G : X.Presheaf C} (U : Opens X) (x : X) (hx : x ∈ U) (f : F ⟶ G) (s) : DFunLike.coe (F := ToHom (F.stalk x) (G.stalk x)) (ConcreteCategory.hom ((stalkFunctor C x).map f)) (F.germ U x hx s) = G.germ U x hx (f.app (op U) s) := stalkFunctor_map_germ_apply U x hx f s variable (C) /-- For a presheaf `F` on a space `X`, a continuous map `f : X ⟶ Y` induces a morphisms between the stalk of `f _ * F` at `f x` and the stalk of `F` at `x`. -/ def stalkPushforward (f : X ⟶ Y) (F : X.Presheaf C) (x : X) : (f _* F).stalk (f x) ⟶ F.stalk x := by -- This is a hack; Lean doesn't like to elaborate the term written directly. refine ?_ ≫ colimit.pre _ (OpenNhds.map f x).op exact colim.map (whiskerRight (NatTrans.op (OpenNhds.inclusionMapIso f x).inv) F) @[reassoc (attr := simp), elementwise (attr := simp)] theorem stalkPushforward_germ (f : X ⟶ Y) (F : X.Presheaf C) (U : Opens Y) (x : X) (hx : f x ∈ U) : (f _* F).germ U (f x) hx ≫ F.stalkPushforward C f x = F.germ ((Opens.map f).obj U) x hx := by simp [germ, stalkPushforward] -- Here are two other potential solutions, suggested by @fpvandoorn at -- <https://github.com/leanprover-community/mathlib/pull/1018#discussion_r283978240> -- However, I can't get the subsequent two proofs to work with either one. -- def stalkPushforward'' (f : X ⟶ Y) (ℱ : X.Presheaf C) (x : X) : -- (f _* ℱ).stalk (f x) ⟶ ℱ.stalk x := -- colim.map ((Functor.associator _ _ _).inv ≫ -- whiskerRight (NatTrans.op (OpenNhds.inclusionMapIso f x).inv) ℱ) ≫ -- colimit.pre ((OpenNhds.inclusion x).op ⋙ ℱ) (OpenNhds.map f x).op -- def stalkPushforward''' (f : X ⟶ Y) (ℱ : X.Presheaf C) (x : X) : -- (f _* ℱ).stalk (f x) ⟶ ℱ.stalk x := -- (colim.map (whiskerRight (NatTrans.op (OpenNhds.inclusionMapIso f x).inv) ℱ) : -- colim.obj ((OpenNhds.inclusion (f x) ⋙ Opens.map f).op ⋙ ℱ) ⟶ _) ≫ -- colimit.pre ((OpenNhds.inclusion x).op ⋙ ℱ) (OpenNhds.map f x).op namespace stalkPushforward @[simp] theorem id (ℱ : X.Presheaf C) (x : X) : ℱ.stalkPushforward C (𝟙 X) x = (stalkFunctor C x).map (Pushforward.id ℱ).hom := by ext simp only [stalkPushforward, germ, colim_map, ι_colimMap_assoc, whiskerRight_app] erw [CategoryTheory.Functor.map_id] simp [stalkFunctor] @[simp] theorem comp (ℱ : X.Presheaf C) (f : X ⟶ Y) (g : Y ⟶ Z) (x : X) : ℱ.stalkPushforward C (f ≫ g) x = (f _* ℱ).stalkPushforward C g (f x) ≫ ℱ.stalkPushforward C f x := by ext simp [germ, stalkPushforward] theorem stalkPushforward_iso_of_isInducing {f : X ⟶ Y} (hf : IsInducing f) (F : X.Presheaf C) (x : X) : IsIso (F.stalkPushforward _ f x) := by haveI := Functor.initial_of_adjunction (hf.adjunctionNhds x) convert (Functor.Final.colimitIso (OpenNhds.map f x).op ((OpenNhds.inclusion x).op ⋙ F)).isIso_hom refine stalk_hom_ext _ fun U hU ↦ (stalkPushforward_germ _ f F _ x hU).trans ?_ symm exact colimit.ι_pre ((OpenNhds.inclusion x).op ⋙ F) (OpenNhds.map f x).op _ end stalkPushforward section stalkPullback /-- The morphism `ℱ_{f x} ⟶ (f⁻¹ℱ)ₓ` that factors through `(f_*f⁻¹ℱ)_{f x}`. -/ def stalkPullbackHom (f : X ⟶ Y) (F : Y.Presheaf C) (x : X) : F.stalk (f x) ⟶ ((pullback C f).obj F).stalk x := (stalkFunctor _ (f x)).map ((pushforwardPullbackAdjunction C f).unit.app F) ≫ stalkPushforward _ _ _ x @[reassoc (attr := simp)] lemma germ_stalkPullbackHom (f : X ⟶ Y) (F : Y.Presheaf C) (x : X) (U : Opens Y) (hU : f x ∈ U) : F.germ U (f x) hU ≫ stalkPullbackHom C f F x = ((pushforwardPullbackAdjunction C f).unit.app F).app _ ≫ ((pullback C f).obj F).germ ((Opens.map f).obj U) x hU := by simp [stalkPullbackHom, germ, stalkFunctor, stalkPushforward] /-- The morphism `(f⁻¹ℱ)(U) ⟶ ℱ_{f(x)}` for some `U ∋ x`. -/ def germToPullbackStalk (f : X ⟶ Y) (F : Y.Presheaf C) (U : Opens X) (x : X) (hx : x ∈ U) : ((pullback C f).obj F).obj (op U) ⟶ F.stalk (f x) := ((Opens.map f).op.isPointwiseLeftKanExtensionLeftKanExtensionUnit F (op U)).desc { pt := F.stalk ((f : X → Y) (x : X)) ι := { app := fun V => F.germ _ (f x) (V.hom.unop.le hx) naturality := fun _ _ i => by simp } } variable {C} in @[ext] lemma pullback_obj_obj_ext {Z : C} {f : X ⟶ Y} {F : Y.Presheaf C} (U : (Opens X)ᵒᵖ) {φ ψ : ((pullback C f).obj F).obj U ⟶ Z} (h : ∀ (V : Opens Y) (hV : U.unop ≤ (Opens.map f).obj V), ((pushforwardPullbackAdjunction C f).unit.app F).app (op V) ≫ ((pullback C f).obj F).map (homOfLE hV).op ≫ φ = ((pushforwardPullbackAdjunction C f).unit.app F).app (op V) ≫ ((pullback C f).obj F).map (homOfLE hV).op ≫ ψ) : φ = ψ := by obtain ⟨U⟩ := U apply ((Opens.map f).op.isPointwiseLeftKanExtensionLeftKanExtensionUnit F _).hom_ext rintro ⟨⟨V⟩, ⟨⟩, ⟨b⟩⟩ simpa [pushforwardPullbackAdjunction, Functor.lanAdjunction_unit] using h V (leOfHom b) @[reassoc (attr := simp)] lemma pushforwardPullbackAdjunction_unit_pullback_map_germToPullbackStalk (f : X ⟶ Y) (F : Y.Presheaf C) (U : Opens X) (x : X) (hx : x ∈ U) (V : Opens Y) (hV : U ≤ (Opens.map f).obj V) : ((pushforwardPullbackAdjunction C f).unit.app F).app (op V) ≫ ((pullback C f).obj F).map (homOfLE hV).op ≫ germToPullbackStalk C f F U x hx = F.germ _ (f x) (hV hx) := by simpa [pushforwardPullbackAdjunction] using ((Opens.map f).op.isPointwiseLeftKanExtensionLeftKanExtensionUnit F (op U)).fac _ (CostructuredArrow.mk (homOfLE hV).op) @[reassoc (attr := simp)] lemma germToPullbackStalk_stalkPullbackHom (f : X ⟶ Y) (F : Y.Presheaf C) (U : Opens X) (x : X) (hx : x ∈ U) : germToPullbackStalk C f F U x hx ≫ stalkPullbackHom C f F x = ((pullback C f).obj F).germ _ x hx := by ext V hV dsimp simp only [pushforwardPullbackAdjunction_unit_pullback_map_germToPullbackStalk_assoc, germ_stalkPullbackHom, germ_res] @[reassoc (attr := simp)] lemma pushforwardPullbackAdjunction_unit_app_app_germToPullbackStalk (f : X ⟶ Y) (F : Y.Presheaf C) (V : (Opens Y)ᵒᵖ) (x : X) (hx : f x ∈ V.unop) : ((pushforwardPullbackAdjunction C f).unit.app F).app V ≫ germToPullbackStalk C f F _ x hx = F.germ _ (f x) hx := by simpa using pushforwardPullbackAdjunction_unit_pullback_map_germToPullbackStalk C f F ((Opens.map f).obj V.unop) x hx V.unop (by rfl) /-- The morphism `(f⁻¹ℱ)ₓ ⟶ ℱ_{f(x)}`. -/ def stalkPullbackInv (f : X ⟶ Y) (F : Y.Presheaf C) (x : X) : ((pullback C f).obj F).stalk x ⟶ F.stalk (f x) := colimit.desc ((OpenNhds.inclusion x).op ⋙ (Presheaf.pullback C f).obj F) { pt := F.stalk (f x) ι := { app := fun U => F.germToPullbackStalk _ f (unop U).1 x (unop U).2 naturality := fun U V i => by dsimp ext W hW dsimp [OpenNhds.inclusion] rw [Category.comp_id, ← Functor.map_comp_assoc, pushforwardPullbackAdjunction_unit_pullback_map_germToPullbackStalk] erw [pushforwardPullbackAdjunction_unit_pullback_map_germToPullbackStalk] } } @[reassoc (attr := simp)] lemma germ_stalkPullbackInv (f : X ⟶ Y) (F : Y.Presheaf C) (x : X) (V : Opens X) (hV : x ∈ V) : ((pullback C f).obj F).germ _ x hV ≫ stalkPullbackInv C f F x = F.germToPullbackStalk _ f V x hV := by apply colimit.ι_desc /-- The isomorphism `ℱ_{f(x)} ≅ (f⁻¹ℱ)ₓ`. -/ def stalkPullbackIso (f : X ⟶ Y) (F : Y.Presheaf C) (x : X) : F.stalk (f x) ≅ ((pullback C f).obj F).stalk x where hom := stalkPullbackHom _ _ _ _ inv := stalkPullbackInv _ _ _ _ hom_inv_id := by ext U hU dsimp rw [germ_stalkPullbackHom_assoc, germ_stalkPullbackInv, Category.comp_id, pushforwardPullbackAdjunction_unit_app_app_germToPullbackStalk] inv_hom_id := by ext V hV dsimp rw [germ_stalkPullbackInv_assoc, Category.comp_id, germToPullbackStalk_stalkPullbackHom] end stalkPullback section stalkSpecializes variable {C} /-- If `x` specializes to `y`, then there is a natural map `F.stalk y ⟶ F.stalk x`. -/ noncomputable def stalkSpecializes (F : X.Presheaf C) {x y : X} (h : x ⤳ y) : F.stalk y ⟶ F.stalk x := by refine colimit.desc _ ⟨_, fun U => ?_, ?_⟩ · exact colimit.ι ((OpenNhds.inclusion x).op ⋙ F) (op ⟨(unop U).1, (specializes_iff_forall_open.mp h _ (unop U).1.2 (unop U).2 :)⟩) · intro U V i dsimp rw [Category.comp_id] let U' : OpenNhds x := ⟨_, (specializes_iff_forall_open.mp h _ (unop U).1.2 (unop U).2 :)⟩ let V' : OpenNhds x := ⟨_, (specializes_iff_forall_open.mp h _ (unop V).1.2 (unop V).2 :)⟩ exact colimit.w ((OpenNhds.inclusion x).op ⋙ F) (show V' ⟶ U' from i.unop).op @[reassoc (attr := simp), elementwise nosimp] theorem germ_stalkSpecializes (F : X.Presheaf C) {U : Opens X} {y : X} (hy : y ∈ U) {x : X} (h : x ⤳ y) : F.germ U y hy ≫ F.stalkSpecializes h = F.germ U x (h.mem_open U.isOpen hy) := colimit.ι_desc _ _ @[simp] theorem stalkSpecializes_refl {C : Type*} [Category C] [Limits.HasColimits C] {X : TopCat} (F : X.Presheaf C) (x : X) : F.stalkSpecializes (specializes_refl x) = 𝟙 _ := by ext simp @[reassoc (attr := simp), elementwise (attr := simp)] theorem stalkSpecializes_comp {C : Type*} [Category C] [Limits.HasColimits C] {X : TopCat} (F : X.Presheaf C) {x y z : X} (h : x ⤳ y) (h' : y ⤳ z) : F.stalkSpecializes h' ≫ F.stalkSpecializes h = F.stalkSpecializes (h.trans h') := by ext simp @[reassoc (attr := simp), elementwise (attr := simp)] theorem stalkSpecializes_stalkFunctor_map {F G : X.Presheaf C} (f : F ⟶ G) {x y : X} (h : x ⤳ y) : F.stalkSpecializes h ≫ (stalkFunctor C x).map f = (stalkFunctor C y).map f ≫ G.stalkSpecializes h := by ext simp @[reassoc (attr := simp), elementwise (attr := simp)] theorem stalkSpecializes_stalkPushforward (f : X ⟶ Y) (F : X.Presheaf C) {x y : X} (h : x ⤳ y) : (f _* F).stalkSpecializes (f.hom.map_specializes h) ≫ F.stalkPushforward _ f x = F.stalkPushforward _ f y ≫ F.stalkSpecializes h := by ext simp /-- The stalks are isomorphic on inseparable points -/ @[simps] def stalkCongr {X : TopCat} {C : Type*} [Category C] [HasColimits C] (F : X.Presheaf C) {x y : X} (e : Inseparable x y) : F.stalk x ≅ F.stalk y := ⟨F.stalkSpecializes e.ge, F.stalkSpecializes e.le, by simp, by simp⟩ end stalkSpecializes section Concrete variable {C} {CC : C → Type v} [∀ X Y, FunLike (FC X Y) (CC X) (CC Y)] variable [instCC : ConcreteCategory.{v} C FC] theorem germ_ext (F : X.Presheaf C) {U V : Opens X} {x : X} {hxU : x ∈ U} {hxV : x ∈ V} (W : Opens X) (hxW : x ∈ W) (iWU : W ⟶ U) (iWV : W ⟶ V) {sU : ToType (F.obj (op U))} {sV : ToType (F.obj (op V))} (ih : F.map iWU.op sU = F.map iWV.op sV) : F.germ _ x hxU sU = F.germ _ x hxV sV := by rw [← F.germ_res iWU x hxW, ← F.germ_res iWV x hxW, ConcreteCategory.comp_apply, ConcreteCategory.comp_apply, ih] variable [PreservesFilteredColimits (forget C)] /-- For presheaves valued in a concrete category whose forgetful functor preserves filtered colimits, every element of the stalk is the germ of a section. -/ theorem germ_exist (F : X.Presheaf C) (x : X) (t : ToType (stalk.{v, u} F x)) : ∃ (U : Opens X) (m : x ∈ U) (s : ToType (F.obj (op U))), F.germ _ x m s = t := by obtain ⟨U, s, e⟩ := Types.jointly_surjective.{v, v} _ (isColimitOfPreserves (forget C) (colimit.isColimit _)) t revert s e induction U with | op U => ?_ obtain ⟨V, m⟩ := U intro s e exact ⟨V, m, s, e⟩ theorem germ_eq (F : X.Presheaf C) {U V : Opens X} (x : X) (mU : x ∈ U) (mV : x ∈ V) (s : ToType (F.obj (op U))) (t : ToType (F.obj (op V))) (h : F.germ U x mU s = F.germ V x mV t) : ∃ (W : Opens X) (_m : x ∈ W) (iU : W ⟶ U) (iV : W ⟶ V), F.map iU.op s = F.map iV.op t := by obtain ⟨W, iU, iV, e⟩ := (Types.FilteredColimit.isColimit_eq_iff.{v, v} _ (isColimitOfPreserves (forget C) (colimit.isColimit ((OpenNhds.inclusion x).op ⋙ F)))).mp h exact ⟨(unop W).1, (unop W).2, iU.unop, iV.unop, e⟩ theorem stalkFunctor_map_injective_of_app_injective {F G : Presheaf C X} {f : F ⟶ G} (h : ∀ U : Opens X, Function.Injective (f.app (op U))) (x : X) : Function.Injective ((stalkFunctor C x).map f) := fun s t hst => by rcases germ_exist F x s with ⟨U₁, hxU₁, s, rfl⟩ rcases germ_exist F x t with ⟨U₂, hxU₂, t, rfl⟩ rw [stalkFunctor_map_germ_apply, stalkFunctor_map_germ_apply] at hst obtain ⟨W, hxW, iWU₁, iWU₂, heq⟩ := G.germ_eq x hxU₁ hxU₂ _ _ hst rw [← ConcreteCategory.comp_apply, ← ConcreteCategory.comp_apply, ← f.naturality, ← f.naturality, ConcreteCategory.comp_apply, ConcreteCategory.comp_apply] at heq replace heq := h W heq convert congr_arg (F.germ _ x hxW) heq using 1 exacts [(F.germ_res_apply iWU₁ x hxW s).symm, (F.germ_res_apply iWU₂ x hxW t).symm] section IsBasis variable {B : Set (Opens X)} (hB : Opens.IsBasis B) include hB lemma germ_exist_of_isBasis (F : X.Presheaf C) (x : X) (t : ToType (F.stalk x)) : ∃ (U : Opens X) (m : x ∈ U) (_ : U ∈ B) (s : ToType (F.obj (op U))), F.germ _ x m s = t := by obtain ⟨U, hxU, s, rfl⟩ := F.germ_exist x t obtain ⟨_, ⟨V, hV, rfl⟩, hxV, hVU⟩ := hB.exists_subset_of_mem_open hxU U.2 exact ⟨V, hxV, hV, F.map (homOfLE hVU).op s, by rw [← ConcreteCategory.comp_apply, F.germ_res']⟩ lemma germ_eq_of_isBasis (F : X.Presheaf C) {U V : Opens X} (x : X) (mU : x ∈ U) (mV : x ∈ V) {s : ToType (F.obj (op U))} {t : ToType (F.obj (op V))} (h : F.germ U x mU s = F.germ V x mV t) : ∃ (W : Opens X) (_ : x ∈ W) (_ : W ∈ B) (hWU : W ≤ U) (hWV : W ≤ V), F.map (homOfLE hWU).op s = F.map (homOfLE hWV).op t := by obtain ⟨W, hxW, hWU, hWV, e⟩ := F.germ_eq x mU mV _ _ h obtain ⟨_, ⟨W', hW', rfl⟩, hxW', hW'W⟩ := hB.exists_subset_of_mem_open hxW W.2 refine ⟨W', hxW', hW', hW'W.trans hWU.le, hW'W.trans hWV.le, ?_⟩ simpa only [← ConcreteCategory.comp_apply, ← F.map_comp] using DFunLike.congr_arg (ConcreteCategory.hom (F.map (homOfLE hW'W).op)) e lemma stalkFunctor_map_injective_of_isBasis {F G : X.Presheaf C} {α : F ⟶ G} (hα : ∀ U ∈ B, Function.Injective (α.app (op U))) (x : X) : Function.Injective ((stalkFunctor _ x).map α) := by intro s t hst obtain ⟨U₁, hxU₁, hU₁, s, rfl⟩ := germ_exist_of_isBasis hB _ x s obtain ⟨U₂, hxU₂, hU₂, t, rfl⟩ := germ_exist_of_isBasis hB _ x t rw [stalkFunctor_map_germ_apply, stalkFunctor_map_germ_apply] at hst obtain ⟨W, hxW, hW, iWU₁, iWU₂, heq⟩ := germ_eq_of_isBasis hB _ _ hxU₁ hxU₂ hst simp only [← α.naturality_apply, (hα W hW).eq_iff] at heq simpa [germ_res_apply'] using congr(F.germ W x hxW $heq) end IsBasis variable [HasLimits C] [PreservesLimits (forget C)] [(forget C).ReflectsIsomorphisms] /-- Let `F` be a sheaf valued in a concrete category, whose forgetful functor reflects isomorphisms, preserves limits and filtered colimits. Then two sections who agree on every stalk must be equal. -/ theorem section_ext (F : Sheaf C X) (U : Opens X) (s t : ToType (F.1.obj (op U))) (h : ∀ (x : X) (hx : x ∈ U), F.presheaf.germ U x hx s = F.presheaf.germ U x hx t) : s = t := by -- We use `germ_eq` and the axiom of choice, to pick for every point `x` a neighbourhood -- `V x`, such that the restrictions of `s` and `t` to `V x` coincide. choose V m i₁ i₂ heq using fun x : U => F.presheaf.germ_eq x.1 x.2 x.2 s t (h x.1 x.2) -- Since `F` is a sheaf, we can prove the equality locally, if we can show that these -- neighborhoods form a cover of `U`. apply F.eq_of_locally_eq' V U i₁ · intro x hxU simp only [Opens.coe_iSup, Set.mem_iUnion, SetLike.mem_coe] exact ⟨⟨x, hxU⟩, m ⟨x, hxU⟩⟩ · intro x rw [heq, Subsingleton.elim (i₁ x) (i₂ x)] /- Note that the analogous statement for surjectivity is false: Surjectivity on stalks does not imply surjectivity of the components of a sheaf morphism. However it does imply that the morphism is an epi, but this fact is not yet formalized. -/ theorem app_injective_of_stalkFunctor_map_injective {F : Sheaf C X} {G : Presheaf C X} (f : F.1 ⟶ G) (U : Opens X) (h : ∀ x ∈ U, Function.Injective ((stalkFunctor C x).map f)) : Function.Injective (f.app (op U)) := fun s t hst => section_ext F _ _ _ fun x hx => h x hx <| by rw [stalkFunctor_map_germ_apply, stalkFunctor_map_germ_apply, hst] theorem app_injective_iff_stalkFunctor_map_injective {F : Sheaf C X} {G : Presheaf C X} (f : F.1 ⟶ G) : (∀ x : X, Function.Injective ((stalkFunctor C x).map f)) ↔ ∀ U : Opens X, Function.Injective (f.app (op U)) := ⟨fun h U => app_injective_of_stalkFunctor_map_injective f U fun x _ => h x, stalkFunctor_map_injective_of_app_injective⟩ instance stalkFunctor_preserves_mono (x : X) : Functor.PreservesMonomorphisms (Sheaf.forget.{v} C X ⋙ stalkFunctor C x) := ⟨@fun _𝓐 _𝓑 f _ => ConcreteCategory.mono_of_injective _ <| (app_injective_iff_stalkFunctor_map_injective f.1).mpr (fun c => (ConcreteCategory.mono_iff_injective_of_preservesPullback (f.1.app (op c))).mp ((NatTrans.mono_iff_mono_app f.1).mp (CategoryTheory.presheaf_mono_of_mono ..) <| op c)) x⟩ include instCC in theorem stalk_mono_of_mono {F G : Sheaf C X} (f : F ⟶ G) [Mono f] : ∀ x, Mono <| (stalkFunctor C x).map f.1 := fun x => Functor.map_mono (Sheaf.forget.{v} C X ⋙ stalkFunctor C x) f include instCC in theorem mono_of_stalk_mono {F G : Sheaf C X} (f : F ⟶ G) [∀ x, Mono <| (stalkFunctor C x).map f.1] : Mono f := (Sheaf.Hom.mono_iff_presheaf_mono _ _ _).mpr <| (NatTrans.mono_iff_mono_app _).mpr fun U => (ConcreteCategory.mono_iff_injective_of_preservesPullback _).mpr <| app_injective_of_stalkFunctor_map_injective f.1 U.unop fun _x _hx => (ConcreteCategory.mono_iff_injective_of_preservesPullback ((stalkFunctor C _).map f.val)).mp <| inferInstance include instCC in theorem mono_iff_stalk_mono {F G : Sheaf C X} (f : F ⟶ G) : Mono f ↔ ∀ x, Mono ((stalkFunctor C x).map f.1) := ⟨fun _ => stalk_mono_of_mono _, fun _ => mono_of_stalk_mono _⟩ /-- For surjectivity, we are given an arbitrary section `t` and need to find a preimage for it. We claim that it suffices to find preimages *locally*. That is, for each `x : U` we construct a neighborhood `V ≤ U` and a section `s : F.obj (op V))` such that `f.app (op V) s` and `t` agree on `V`. -/ theorem app_surjective_of_injective_of_locally_surjective {F G : Sheaf C X} (f : F ⟶ G) (U : Opens X) (hinj : ∀ x ∈ U, Function.Injective ((stalkFunctor C x).map f.1)) (hsurj : ∀ (t x) (_ : x ∈ U), ∃ (V : Opens X) (_ : x ∈ V) (iVU : V ⟶ U) (s : ToType (F.1.obj (op V))), f.1.app (op V) s = G.1.map iVU.op t) : Function.Surjective (f.1.app (op U)) := by conv at hsurj => enter [t] rw [Subtype.forall' (p := (· ∈ U))] intro t -- We use the axiom of choice to pick around each point `x` an open neighborhood `V` and a -- preimage under `f` on `V`. choose V mV iVU sf heq using hsurj t -- These neighborhoods clearly cover all of `U`. have V_cover : U ≤ iSup V := by intro x hxU simp only [Opens.coe_iSup, Set.mem_iUnion, SetLike.mem_coe] exact ⟨⟨x, hxU⟩, mV ⟨x, hxU⟩⟩ suffices IsCompatible F.val V sf by -- Since `F` is a sheaf, we can glue all the local preimages together to get a global preimage. obtain ⟨s, s_spec, -⟩ := F.existsUnique_gluing' V U iVU V_cover sf this · use s apply G.eq_of_locally_eq' V U iVU V_cover intro x rw [← ConcreteCategory.comp_apply, ← f.1.naturality, ConcreteCategory.comp_apply, s_spec, heq] intro x y -- What's left to show here is that the sections `sf` are compatible, i.e. they agree on -- the intersections `V x ⊓ V y`. We prove this by showing that all germs are equal. apply section_ext intro z hz -- Here, we need to use injectivity of the stalk maps. apply hinj z ((iVU x).le ((inf_le_left : V x ⊓ V y ≤ V x) hz)) dsimp only rw [stalkFunctor_map_germ_apply, stalkFunctor_map_germ_apply] simp_rw [← ConcreteCategory.comp_apply, f.1.naturality, ConcreteCategory.comp_apply, heq, ← ConcreteCategory.comp_apply, ← G.1.map_comp] rfl theorem app_surjective_of_stalkFunctor_map_bijective {F G : Sheaf C X} (f : F ⟶ G) (U : Opens X) (h : ∀ x ∈ U, Function.Bijective ((stalkFunctor C x).map f.1)) : Function.Surjective (f.1.app (op U)) := by refine app_surjective_of_injective_of_locally_surjective f U (And.left <| h · ·) fun t x hx => ?_ -- Now we need to prove our initial claim: That we can find preimages of `t` locally. -- Since `f` is surjective on stalks, we can find a preimage `s₀` of the germ of `t` at `x` obtain ⟨s₀, hs₀⟩ := (h x hx).2 (G.presheaf.germ U x hx t) -- ... and this preimage must come from some section `s₁` defined on some open neighborhood `V₁` obtain ⟨V₁, hxV₁, s₁, hs₁⟩ := F.presheaf.germ_exist x s₀ subst hs₁; rename' hs₀ => hs₁ rw [stalkFunctor_map_germ_apply V₁ x hxV₁ f.1 s₁] at hs₁ -- Now, the germ of `f.app (op V₁) s₁` equals the germ of `t`, hence they must coincide on -- some open neighborhood `V₂`. obtain ⟨V₂, hxV₂, iV₂V₁, iV₂U, heq⟩ := G.presheaf.germ_eq x hxV₁ hx _ _ hs₁ -- The restriction of `s₁` to that neighborhood is our desired local preimage. use V₂, hxV₂, iV₂U, F.1.map iV₂V₁.op s₁ rw [← ConcreteCategory.comp_apply, f.1.naturality, ConcreteCategory.comp_apply, heq] theorem app_bijective_of_stalkFunctor_map_bijective {F G : Sheaf C X} (f : F ⟶ G) (U : Opens X) (h : ∀ x ∈ U, Function.Bijective ((stalkFunctor C x).map f.1)) : Function.Bijective (f.1.app (op U)) := ⟨app_injective_of_stalkFunctor_map_injective f.1 U fun x hx => (h x hx).1, app_surjective_of_stalkFunctor_map_bijective f U h⟩ include instCC in theorem app_isIso_of_stalkFunctor_map_iso {F G : Sheaf C X} (f : F ⟶ G) (U : Opens X) [∀ x : U, IsIso ((stalkFunctor C x.val).map f.1)] : IsIso (f.1.app (op U)) := by -- Since the forgetful functor of `C` reflects isomorphisms, it suffices to see that the -- underlying map between types is an isomorphism, i.e. bijective. suffices IsIso ((forget C).map (f.1.app (op U))) by exact isIso_of_reflects_iso (f.1.app (op U)) (forget C) rw [isIso_iff_bijective] apply app_bijective_of_stalkFunctor_map_bijective intro x hx apply (isIso_iff_bijective _).mp exact Functor.map_isIso (forget C) ((stalkFunctor C (⟨x, hx⟩ : U).1).map f.1) include instCC in -- Making this an instance would cause a loop in typeclass resolution with `Functor.map_isIso` /-- Let `F` and `G` be sheaves valued in a concrete category, whose forgetful functor reflects isomorphisms, preserves limits and filtered colimits. Then if the stalk maps of a morphism `f : F ⟶ G` are all isomorphisms, `f` must be an isomorphism. -/ theorem isIso_of_stalkFunctor_map_iso {F G : Sheaf C X} (f : F ⟶ G) [∀ x : X, IsIso ((stalkFunctor C x).map f.1)] : IsIso f := by -- Since the inclusion functor from sheaves to presheaves is fully faithful, it suffices to -- show that `f`, as a morphism between _presheaves_, is an isomorphism. suffices IsIso ((Sheaf.forget C X).map f) by exact isIso_of_fully_faithful (Sheaf.forget C X) f -- We show that all components of `f` are isomorphisms. suffices ∀ U : (Opens X)ᵒᵖ, IsIso (f.1.app U) by exact @NatIso.isIso_of_isIso_app _ _ _ _ F.1 G.1 f.1 this intro U; induction U apply app_isIso_of_stalkFunctor_map_iso include instCC in /-- Let `F` and `G` be sheaves valued in a concrete category, whose forgetful functor reflects isomorphisms, preserves limits and filtered colimits. Then a morphism `f : F ⟶ G` is an isomorphism if and only if all of its stalk maps are isomorphisms. -/ theorem isIso_iff_stalkFunctor_map_iso {F G : Sheaf C X} (f : F ⟶ G) : IsIso f ↔ ∀ x : X, IsIso ((stalkFunctor C x).map f.1) := ⟨fun _ x => @Functor.map_isIso _ _ _ _ _ _ (stalkFunctor C x) f.1 ((Sheaf.forget C X).map_isIso f), fun _ => isIso_of_stalkFunctor_map_iso f⟩ end Concrete end TopCat.Presheaf
.lake/packages/mathlib/Mathlib/Topology/Sheaves/Forget.lean
import Mathlib.Topology.Sheaves.Sheaf /-! # Checking the sheaf condition on the underlying presheaf of types. If `G : C ⥤ D` is a functor which reflects isomorphisms and preserves limits (we assume all limits exist in `C`), then checking the sheaf condition for a presheaf `F : Presheaf C X` is equivalent to checking the sheaf condition for `F ⋙ G`. The important special case is when `C` is a concrete category with a forgetful functor that preserves limits and reflects isomorphisms. Then to check the sheaf condition it suffices to check it on the underlying sheaf of types. ## References * https://stacks.math.columbia.edu/tag/0073 -/ universe v v₁ v₂ u₁ u₂ noncomputable section open CategoryTheory Limits namespace TopCat.Presheaf /-- If `G : C ⥤ D` is a functor which reflects isomorphisms and preserves limits (we assume all limits exist in `C`), then checking the sheaf condition for a presheaf `F : Presheaf C X` is equivalent to checking the sheaf condition for `F ⋙ G`. The important special case is when `C` is a concrete category with a forgetful functor that preserves limits and reflects isomorphisms. Then to check the sheaf condition it suffices to check it on the underlying sheaf of types. Another useful example is the forgetful functor `TopCommRingCat ⥤ TopCat`. -/ @[stacks 0073 "In fact we prove a stronger version with arbitrary target category."] theorem isSheaf_iff_isSheaf_comp' {C : Type u₁} [Category.{v₁} C] {D : Type u₂} [Category.{v₂} D] (G : C ⥤ D) [G.ReflectsIsomorphisms] [HasLimitsOfSize.{v, v} C] [PreservesLimitsOfSize.{v, v} G] {X : TopCat.{v}} (F : Presheaf C X) : Presheaf.IsSheaf F ↔ Presheaf.IsSheaf (F ⋙ G) := Presheaf.isSheaf_iff_isSheaf_comp _ F G theorem isSheaf_iff_isSheaf_comp {C : Type u₁} [Category.{v} C] {D : Type u₂} [Category.{v} D] (G : C ⥤ D) [G.ReflectsIsomorphisms] [HasLimits C] [PreservesLimits G] {X : TopCat.{v}} (F : Presheaf C X) : Presheaf.IsSheaf F ↔ Presheaf.IsSheaf (F ⋙ G) := isSheaf_iff_isSheaf_comp' G F end TopCat.Presheaf
.lake/packages/mathlib/Mathlib/Topology/Sheaves/LocallySurjective.lean
import Mathlib.Topology.Sheaves.Presheaf import Mathlib.Topology.Sheaves.Stalks import Mathlib.CategoryTheory.Limits.Preserves.Filtered import Mathlib.CategoryTheory.Sites.LocallySurjective /-! # Locally surjective maps of presheaves. Let `X` be a topological space, `ℱ` and `𝒢` presheaves on `X`, `T : ℱ ⟶ 𝒢` a map. In this file we formulate two notions for what it means for `T` to be locally surjective: 1. For each open set `U`, each section `t : 𝒢(U)` is in the image of `T` after passing to some open cover of `U`. 2. For each `x : X`, the map of *stalks* `Tₓ : ℱₓ ⟶ 𝒢ₓ` is surjective. We prove that these are equivalent. -/ universe v u noncomputable section open CategoryTheory open TopologicalSpace open Opposite namespace TopCat.Presheaf section LocallySurjective open scoped AlgebraicGeometry variable {C : Type u} [Category.{v} C] {FC : C → C → Type*} {CC : C → Type v} variable [∀ X Y, FunLike (FC X Y) (CC X) (CC Y)] [ConcreteCategory C FC] {X : TopCat.{v}} variable {ℱ 𝒢 : X.Presheaf C} /-- A map of presheaves `T : ℱ ⟶ 𝒢` is **locally surjective** if for any open set `U`, section `t` over `U`, and `x ∈ U`, there exists an open set `x ∈ V ⊆ U` and a section `s` over `V` such that `$T_*(s_V) = t|_V$`. See `TopCat.Presheaf.isLocallySurjective_iff` below. -/ def IsLocallySurjective (T : ℱ ⟶ 𝒢) := CategoryTheory.Presheaf.IsLocallySurjective (Opens.grothendieckTopology X) T theorem isLocallySurjective_iff (T : ℱ ⟶ 𝒢) : IsLocallySurjective T ↔ ∀ (U t), ∀ x ∈ U, ∃ (V : _) (ι : V ⟶ U), (∃ s, (T.app _) s = t |_ₕ ι) ∧ x ∈ V := ⟨fun h _ => h.imageSieve_mem, fun h => ⟨h _⟩⟩ section SurjectiveOnStalks variable [Limits.HasColimits C] [Limits.PreservesFilteredColimits (forget C)] /-- An equivalent condition for a map of presheaves to be locally surjective is for all the induced maps on stalks to be surjective. -/ theorem locally_surjective_iff_surjective_on_stalks (T : ℱ ⟶ 𝒢) : IsLocallySurjective T ↔ ∀ x : X, Function.Surjective ((stalkFunctor C x).map T) := by constructor <;> intro hT · /- human proof: Let g ∈ Γₛₜ 𝒢 x be a germ. Represent it on an open set U ⊆ X as ⟨t, U⟩. By local surjectivity, pass to a smaller open set V on which there exists s ∈ Γ_ ℱ V mapping to t |_ V. Then the germ of s maps to g -/ -- Let g ∈ Γₛₜ 𝒢 x be a germ. intro x g -- Represent it on an open set U ⊆ X as ⟨t, U⟩. obtain ⟨U, hxU, t, rfl⟩ := 𝒢.germ_exist x g -- By local surjectivity, pass to a smaller open set V -- on which there exists s ∈ Γ_ ℱ V mapping to t |_ V. rcases hT.imageSieve_mem t x hxU with ⟨V, ι, ⟨s, h_eq⟩, hxV⟩ -- Then the germ of s maps to g. use ℱ.germ _ x hxV s simp [h_eq, germ_res_apply] · /- human proof: Let U be an open set, t ∈ Γ ℱ U a section, x ∈ U a point. By surjectivity on stalks, the germ of t is the image of some germ f ∈ Γₛₜ ℱ x. Represent f on some open set V ⊆ X as ⟨s, V⟩. Then there is some possibly smaller open set x ∈ W ⊆ V ∩ U on which we have T(s) |_ W = t |_ W. -/ constructor intro U t x hxU set t_x := 𝒢.germ _ x hxU t with ht_x obtain ⟨s_x, hs_x : ((stalkFunctor C x).map T) s_x = t_x⟩ := hT x t_x obtain ⟨V, hxV, s, rfl⟩ := ℱ.germ_exist x s_x -- rfl : ℱ.germ x s = s_x have key_W := 𝒢.germ_eq x hxV hxU (T.app _ s) t <| by convert hs_x using 1 symm convert stalkFunctor_map_germ_apply _ _ _ _ s obtain ⟨W, hxW, hWV, hWU, h_eq⟩ := key_W refine ⟨W, hWU, ⟨ℱ.map hWV.op s, ?_⟩, hxW⟩ convert h_eq using 1 simp only [← ConcreteCategory.comp_apply, T.naturality] end SurjectiveOnStalks end LocallySurjective end TopCat.Presheaf
.lake/packages/mathlib/Mathlib/Topology/Sheaves/SheafOfFunctions.lean
import Mathlib.Topology.Sheaves.PresheafOfFunctions import Mathlib.Topology.Sheaves.SheafCondition.UniqueGluing /-! # Sheaf conditions for presheaves of (continuous) functions. We show that * `Top.Presheaf.toType_isSheaf`: not-necessarily-continuous functions into a type form a sheaf * `Top.Presheaf.toTypes_isSheaf`: in fact, these may be dependent functions into a type family For * `Top.sheafToTop`: continuous functions into a topological space form a sheaf please see `Topology/Sheaves/LocalPredicate.lean`, where we set up a general framework for constructing sub(pre)sheaves of the sheaf of dependent functions. ## Future work Obviously there's more to do: * sections of a fiber bundle * various classes of smooth and structure-preserving functions * functions into spaces with algebraic structure, which the sections inherit -/ open CategoryTheory Limits TopologicalSpace Opens noncomputable section variable (X : TopCat) open TopCat namespace TopCat.Presheaf /-- We show that the presheaf of functions to a type `T` (no continuity assumptions, just plain functions) form a sheaf. In fact, the proof is identical when we do this for dependent functions to a type family `T`, so we do the more general case. -/ theorem toTypes_isSheaf (T : X → Type*) : (presheafToTypes X T).IsSheaf := isSheaf_of_isSheafUniqueGluing_types _ fun ι U sf hsf => by -- We use the sheaf condition in terms of unique gluing -- U is a family of open sets, indexed by `ι` and `sf` is a compatible family of sections. -- In the informal comments below, I'll just write `U` to represent the union. -- Our first goal is to define a function "lifted" to all of `U`. -- We do this one point at a time. Using the axiom of choice, we can pick for each -- `x : ↑(iSup U)` an index `i : ι` such that `x` lies in `U i` choose index index_spec using fun x : ↑(iSup U) => Opens.mem_iSup.mp x.2 -- Using this data, we can glue our functions together to a single section let s : ∀ x : ↑(iSup U), T x := fun x => sf (index x) ⟨x.1, index_spec x⟩ refine ⟨s, ?_, ?_⟩ · intro i funext x -- Now we need to verify that this lifted function restricts correctly to each set `U i`. -- Of course, the difficulty is that at any given point `x ∈ U i`, -- we may have used the axiom of choice to pick a different `j` with `x ∈ U j` -- when defining the function. -- Thus we'll need to use the fact that the restrictions are compatible. exact congr_fun (hsf (index ⟨x, _⟩) i) ⟨x, ⟨index_spec ⟨x.1, _⟩, x.2⟩⟩ · -- Now we just need to check that the lift we picked was the only possible one. -- So we suppose we had some other gluing `t` of our sections intro t ht -- and observe that we need to check that it agrees with our choice -- for each `x ∈ ↑(iSup U)`. funext x exact congr_fun (ht (index x)) ⟨x.1, index_spec x⟩ -- We verify that the non-dependent version is an immediate consequence: /-- The presheaf of not-necessarily-continuous functions to a target type `T` satisfies the sheaf condition. -/ theorem toType_isSheaf (T : Type*) : (presheafToType X T).IsSheaf := toTypes_isSheaf X fun _ => T end TopCat.Presheaf namespace TopCat /-- The sheaf of not-necessarily-continuous functions on `X` with values in type family `T : X → Type u`. -/ def sheafToTypes (T : X → Type*) : Sheaf (Type _) X := ⟨presheafToTypes X T, Presheaf.toTypes_isSheaf _ _⟩ /-- The sheaf of not-necessarily-continuous functions on `X` with values in a type `T`. -/ def sheafToType (T : Type*) : Sheaf (Type _) X := ⟨presheafToType X T, Presheaf.toType_isSheaf _ _⟩ end TopCat
.lake/packages/mathlib/Mathlib/Topology/Sheaves/PUnit.lean
import Mathlib.Topology.Sheaves.SheafCondition.Sites /-! # Presheaves on `PUnit` Presheaves on `PUnit` satisfy sheaf condition iff its value at empty set is a terminal object. -/ namespace TopCat.Presheaf universe u v w open CategoryTheory CategoryTheory.Limits TopCat Opposite variable {C : Type u} [Category.{v} C] theorem isSheaf_of_isTerminal_of_indiscrete {X : TopCat.{w}} (hind : X.str = ⊤) (F : Presheaf C X) (it : IsTerminal <| F.obj <| op ⊥) : F.IsSheaf := fun c U s hs => by obtain rfl | hne := eq_or_ne U ⊥ · intro _ _ rw [@existsUnique_iff_exists _ ⟨fun _ _ => _⟩] · refine ⟨it.from _, fun U hU hs => IsTerminal.hom_ext ?_ _ _⟩ rwa [le_bot_iff.1 hU.le] · apply it.hom_ext · convert Presieve.isSheafFor_top_sieve (F ⋙ coyoneda.obj (@op C c)) rw [← Sieve.id_mem_iff_eq_top] have := (U.eq_bot_or_top hind).resolve_left hne subst this obtain he | ⟨⟨x⟩⟩ := isEmpty_or_nonempty X · exact (hne <| SetLike.ext'_iff.2 <| Set.univ_eq_empty_iff.2 he).elim obtain ⟨U, f, hf, hm⟩ := hs x _root_.trivial obtain rfl | rfl := U.eq_bot_or_top hind · cases hm · convert hf theorem isSheaf_iff_isTerminal_of_indiscrete {X : TopCat.{w}} (hind : X.str = ⊤) (F : Presheaf C X) : F.IsSheaf ↔ Nonempty (IsTerminal <| F.obj <| op ⊥) := ⟨fun h => ⟨Sheaf.isTerminalOfEmpty ⟨F, h⟩⟩, fun ⟨it⟩ => isSheaf_of_isTerminal_of_indiscrete hind F it⟩ theorem isSheaf_on_punit_of_isTerminal (F : Presheaf C (TopCat.of PUnit)) (it : IsTerminal <| F.obj <| op ⊥) : F.IsSheaf := isSheaf_of_isTerminal_of_indiscrete (@Subsingleton.elim (TopologicalSpace PUnit) _ _ _) F it theorem isSheaf_on_punit_iff_isTerminal (F : Presheaf C (TopCat.of PUnit)) : F.IsSheaf ↔ Nonempty (IsTerminal <| F.obj <| op ⊥) := ⟨fun h => ⟨Sheaf.isTerminalOfEmpty ⟨F, h⟩⟩, fun ⟨it⟩ => isSheaf_on_punit_of_isTerminal F it⟩ end TopCat.Presheaf
.lake/packages/mathlib/Mathlib/Topology/Sheaves/Presheaf.lean
import Mathlib.Topology.Category.TopCat.Opens import Mathlib.CategoryTheory.Adjunction.Unique import Mathlib.CategoryTheory.Functor.KanExtension.Adjunction import Mathlib.Topology.Sheaves.Init import Mathlib.Data.Set.Subsingleton /-! # Presheaves on a topological space We define `TopCat.Presheaf C X` simply as `(TopologicalSpace.Opens X)ᵒᵖ ⥤ C`, and inherit the category structure with natural transformations as morphisms. We define * Given `{X Y : TopCat.{w}}` and `f : X ⟶ Y`, we define `TopCat.Presheaf.pushforward C f : X.Presheaf C ⥤ Y.Presheaf C`, with notation `f _* ℱ` for `ℱ : X.Presheaf C`. and for `ℱ : X.Presheaf C` provide the natural isomorphisms * `TopCat.Presheaf.Pushforward.id : (𝟙 X) _* ℱ ≅ ℱ` * `TopCat.Presheaf.Pushforward.comp : (f ≫ g) _* ℱ ≅ g _* (f _* ℱ)` along with their `@[simp]` lemmas. We also define the functors `pullback C f : Y.Presheaf C ⥤ X.Presheaf c`, and provide their adjunction at `TopCat.Presheaf.pushforwardPullbackAdjunction`. -/ universe w v u open CategoryTheory TopologicalSpace Opposite Functor variable (C : Type u) [Category.{v} C] namespace TopCat /-- The category of `C`-valued presheaves on a (bundled) topological space `X`. -/ def Presheaf (X : TopCat.{w}) : Type max u v w := (Opens X)ᵒᵖ ⥤ C instance (X : TopCat.{w}) : Category (Presheaf.{w, v, u} C X) := inferInstanceAs (Category ((Opens X)ᵒᵖ ⥤ C : Type max u v w)) variable {C} namespace Presheaf @[simp] theorem comp_app {X : TopCat} {U : (Opens X)ᵒᵖ} {P Q R : Presheaf C X} (f : P ⟶ Q) (g : Q ⟶ R) : (f ≫ g).app U = f.app U ≫ g.app U := rfl @[ext] lemma ext {X : TopCat} {P Q : Presheaf C X} {f g : P ⟶ Q} (w : ∀ U : Opens X, f.app (op U) = g.app (op U)) : f = g := by apply NatTrans.ext ext U induction U with | _ U => ?_ apply w /-- attribute `sheaf_restrict` to mark lemmas related to restricting sheaves -/ macro "sheaf_restrict" : attr => `(attr|aesop safe 50 apply (rule_sets := [$(Lean.mkIdent `Restrict):ident])) attribute [sheaf_restrict] bot_le le_top le_refl inf_le_left inf_le_right le_sup_left le_sup_right /-- `restrict_tac` solves relations among subsets (copied from `aesop cat`) -/ macro (name := restrict_tac) "restrict_tac" c:Aesop.tactic_clause* : tactic => `(tactic| first | assumption | aesop $c* (config := { terminal := true assumptionTransparency := .reducible enableSimp := false }) (rule_sets := [-default, -builtin, $(Lean.mkIdent `Restrict):ident])) /-- `restrict_tac?` passes along `Try this` from `aesop` -/ macro (name := restrict_tac?) "restrict_tac?" c:Aesop.tactic_clause* : tactic => `(tactic| aesop? $c* (config := { terminal := true assumptionTransparency := .reducible enableSimp := false maxRuleApplications := 300 }) (rule_sets := [-default, -builtin, $(Lean.mkIdent `Restrict):ident])) attribute[aesop 10% (rule_sets := [Restrict])] le_trans attribute[aesop safe destruct (rule_sets := [Restrict])] Eq.trans_le attribute[aesop safe -50 (rule_sets := [Restrict])] Aesop.BuiltinRules.assumption example {X} [CompleteLattice X] (v : Nat → X) (w x y z : X) (e : v 0 = v 1) (_ : v 1 = v 2) (h₀ : v 1 ≤ x) (_ : x ≤ z ⊓ w) (h₂ : x ≤ y ⊓ z) : v 0 ≤ y := by restrict_tac variable {X : TopCat} {C : Type*} [Category C] {FC : C → C → Type*} {CC : C → Type*} variable [∀ X Y, FunLike (FC X Y) (CC X) (CC Y)] [ConcreteCategory C FC] /-- The restriction of a section along an inclusion of open sets. For `x : F.obj (op V)`, we provide the notation `x |_ₕ i` (`h` stands for `hom`) for `i : U ⟶ V`, and the notation `x |_ₗ U ⟪i⟫` (`l` stands for `le`) for `i : U ≤ V`. -/ def restrict {F : X.Presheaf C} {V : Opens X} (x : ToType (F.obj (op V))) {U : Opens X} (h : U ⟶ V) : ToType (F.obj (op U)) := F.map h.op x /-- restriction of a section along an inclusion -/ scoped[AlgebraicGeometry] infixl:80 " |_ₕ " => TopCat.Presheaf.restrict /-- restriction of a section along a subset relation -/ scoped[AlgebraicGeometry] notation:80 x " |_ₗ " U " ⟪" e "⟫ " => @TopCat.Presheaf.restrict _ _ _ _ _ _ _ _ _ x U (@homOfLE (Opens _) _ U _ e) open AlgebraicGeometry /-- The restriction of a section along an inclusion of open sets. For `x : F.obj (op V)`, we provide the notation `x |_ U`, where the proof `U ≤ V` is inferred by the tactic `Top.presheaf.restrict_tac'` -/ abbrev restrictOpen {F : X.Presheaf C} {V : Opens X} (x : ToType (F.obj (op V))) (U : Opens X) (e : U ≤ V := by restrict_tac) : ToType (F.obj (op U)) := x |_ₗ U ⟪e⟫ /-- restriction of a section to open subset -/ scoped[AlgebraicGeometry] infixl:80 " |_ " => TopCat.Presheaf.restrictOpen theorem restrict_restrict {F : X.Presheaf C} {U V W : Opens X} (e₁ : U ≤ V) (e₂ : V ≤ W) (x : ToType (F.obj (op W))) : x |_ V |_ U = x |_ U := by delta restrictOpen restrict rw [← ConcreteCategory.comp_apply, ← Functor.map_comp] rfl theorem map_restrict {F G : X.Presheaf C} (e : F ⟶ G) {U V : Opens X} (h : U ≤ V) (x : ToType (F.obj (op V))) : e.app _ (x |_ U) = e.app _ x |_ U := by delta restrictOpen restrict rw [← ConcreteCategory.comp_apply, NatTrans.naturality, ConcreteCategory.comp_apply] open CategoryTheory.Limits variable (C) /-- The pushforward functor. -/ @[simps!] def pushforward {X Y : TopCat.{w}} (f : X ⟶ Y) : X.Presheaf C ⥤ Y.Presheaf C := (whiskeringLeft _ _ _).obj (Opens.map f).op /-- push forward of a presheaf -/ scoped[AlgebraicGeometry] notation f:80 " _* " P:81 => Functor.obj (TopCat.Presheaf.pushforward _ f) P @[simp] theorem pushforward_map_app' {X Y : TopCat.{w}} (f : X ⟶ Y) {ℱ 𝒢 : X.Presheaf C} (α : ℱ ⟶ 𝒢) {U : (Opens Y)ᵒᵖ} : ((pushforward C f).map α).app U = α.app (op <| (Opens.map f).obj U.unop) := rfl lemma id_pushforward (X : TopCat.{w}) : pushforward C (𝟙 X) = 𝟭 (X.Presheaf C) := rfl variable {C} namespace Pushforward /-- The natural isomorphism between the pushforward of a presheaf along the identity continuous map and the original presheaf. -/ def id {X : TopCat.{w}} (ℱ : X.Presheaf C) : 𝟙 X _* ℱ ≅ ℱ := Iso.refl _ @[simp] theorem id_hom_app {X : TopCat.{w}} (ℱ : X.Presheaf C) (U) : (id ℱ).hom.app U = 𝟙 _ := rfl @[simp] theorem id_inv_app {X : TopCat.{w}} (ℱ : X.Presheaf C) (U) : (id ℱ).inv.app U = 𝟙 _ := rfl theorem id_eq {X : TopCat.{w}} (ℱ : X.Presheaf C) : 𝟙 X _* ℱ = ℱ := rfl /-- The natural isomorphism between the pushforward of a presheaf along the composition of two continuous maps and the corresponding pushforward of a pushforward. -/ def comp {X Y Z : TopCat.{w}} (f : X ⟶ Y) (g : Y ⟶ Z) (ℱ : X.Presheaf C) : (f ≫ g) _* ℱ ≅ g _* (f _* ℱ) := Iso.refl _ theorem comp_eq {X Y Z : TopCat.{w}} (f : X ⟶ Y) (g : Y ⟶ Z) (ℱ : X.Presheaf C) : (f ≫ g) _* ℱ = g _* (f _* ℱ) := rfl @[simp] theorem comp_hom_app {X Y Z : TopCat.{w}} (f : X ⟶ Y) (g : Y ⟶ Z) (ℱ : X.Presheaf C) (U) : (comp f g ℱ).hom.app U = 𝟙 _ := rfl @[simp] theorem comp_inv_app {X Y Z : TopCat.{w}} (f : X ⟶ Y) (g : Y ⟶ Z) (ℱ : X.Presheaf C) (U) : (comp f g ℱ).inv.app U = 𝟙 _ := rfl end Pushforward /-- An equality of continuous maps induces a natural isomorphism between the pushforwards of a presheaf along those maps. -/ def pushforwardEq {X Y : TopCat.{w}} {f g : X ⟶ Y} (h : f = g) (ℱ : X.Presheaf C) : f _* ℱ ≅ g _* ℱ := isoWhiskerRight (NatIso.op (Opens.mapIso f g h).symm) ℱ theorem pushforward_eq' {X Y : TopCat.{w}} {f g : X ⟶ Y} (h : f = g) (ℱ : X.Presheaf C) : f _* ℱ = g _* ℱ := by rw [h] @[simp] theorem pushforwardEq_hom_app {X Y : TopCat.{w}} {f g : X ⟶ Y} (h : f = g) (ℱ : X.Presheaf C) (U) : (pushforwardEq h ℱ).hom.app U = ℱ.map (eqToHom (by cat_disch)) := by simp [pushforwardEq] variable (C) section Iso /-- A homeomorphism of spaces gives an equivalence of categories of presheaves. -/ @[simps!] def presheafEquivOfIso {X Y : TopCat} (H : X ≅ Y) : X.Presheaf C ≌ Y.Presheaf C := Equivalence.congrLeft (Opens.mapMapIso H).symm.op variable {C} /-- If `H : X ≅ Y` is a homeomorphism, then given an `H _* ℱ ⟶ 𝒢`, we may obtain an `ℱ ⟶ H ⁻¹ _* 𝒢`. -/ def toPushforwardOfIso {X Y : TopCat} (H : X ≅ Y) {ℱ : X.Presheaf C} {𝒢 : Y.Presheaf C} (α : H.hom _* ℱ ⟶ 𝒢) : ℱ ⟶ H.inv _* 𝒢 := (presheafEquivOfIso _ H).toAdjunction.homEquiv ℱ 𝒢 α @[simp] theorem toPushforwardOfIso_app {X Y : TopCat} (H₁ : X ≅ Y) {ℱ : X.Presheaf C} {𝒢 : Y.Presheaf C} (H₂ : H₁.hom _* ℱ ⟶ 𝒢) (U : (Opens X)ᵒᵖ) : (toPushforwardOfIso H₁ H₂).app U = ℱ.map (eqToHom (by simp [Opens.map, Set.preimage_preimage])) ≫ H₂.app (op ((Opens.map H₁.inv).obj (unop U))) := by simp [toPushforwardOfIso, Adjunction.homEquiv_unit] /-- If `H : X ≅ Y` is a homeomorphism, then given an `H _* ℱ ⟶ 𝒢`, we may obtain an `ℱ ⟶ H ⁻¹ _* 𝒢`. -/ def pushforwardToOfIso {X Y : TopCat} (H₁ : X ≅ Y) {ℱ : Y.Presheaf C} {𝒢 : X.Presheaf C} (H₂ : ℱ ⟶ H₁.hom _* 𝒢) : H₁.inv _* ℱ ⟶ 𝒢 := ((presheafEquivOfIso _ H₁.symm).toAdjunction.homEquiv ℱ 𝒢).symm H₂ @[simp] theorem pushforwardToOfIso_app {X Y : TopCat} (H₁ : X ≅ Y) {ℱ : Y.Presheaf C} {𝒢 : X.Presheaf C} (H₂ : ℱ ⟶ H₁.hom _* 𝒢) (U : (Opens X)ᵒᵖ) : (pushforwardToOfIso H₁ H₂).app U = H₂.app (op ((Opens.map H₁.inv).obj (unop U))) ≫ 𝒢.map (eqToHom (by simp [Opens.map, Set.preimage_preimage])) := by simp [pushforwardToOfIso, Equivalence.toAdjunction, Adjunction.homEquiv_counit] end Iso variable [HasColimits C] noncomputable section /-- Pullback a presheaf on `Y` along a continuous map `f : X ⟶ Y`, obtaining a presheaf on `X`. -/ def pullback {X Y : TopCat.{v}} (f : X ⟶ Y) : Y.Presheaf C ⥤ X.Presheaf C := (Opens.map f).op.lan /-- The pullback and pushforward along a continuous map are adjoint to each other. -/ def pushforwardPullbackAdjunction {X Y : TopCat.{v}} (f : X ⟶ Y) : pullback C f ⊣ pushforward C f := Functor.lanAdjunction _ _ /-- Pulling back along a homeomorphism is the same as pushing forward along its inverse. -/ def pullbackHomIsoPushforwardInv {X Y : TopCat.{v}} (H : X ≅ Y) : pullback C H.hom ≅ pushforward C H.inv := Adjunction.leftAdjointUniq (pushforwardPullbackAdjunction C H.hom) (presheafEquivOfIso C H.symm).toAdjunction /-- Pulling back along the inverse of a homeomorphism is the same as pushing forward along it. -/ def pullbackInvIsoPushforwardHom {X Y : TopCat.{v}} (H : X ≅ Y) : pullback C H.inv ≅ pushforward C H.hom := Adjunction.leftAdjointUniq (pushforwardPullbackAdjunction C H.inv) (presheafEquivOfIso C H).toAdjunction variable {C} /-- If `f '' U` is open, then `f⁻¹ℱ U ≅ ℱ (f '' U)`. -/ def pullbackObjObjOfImageOpen {X Y : TopCat.{v}} (f : X ⟶ Y) (ℱ : Y.Presheaf C) (U : Opens X) (H : IsOpen (f '' SetLike.coe U)) : ((pullback C f).obj ℱ).obj (op U) ≅ ℱ.obj (op ⟨_, H⟩) := by let x : CostructuredArrow (Opens.map f).op (op U) := CostructuredArrow.mk (@homOfLE _ _ _ ((Opens.map f).obj ⟨_, H⟩) (Set.image_preimage.le_u_l _)).op have hx : IsTerminal x := { lift := fun s ↦ by fapply CostructuredArrow.homMk · change op (unop _) ⟶ op (⟨_, H⟩ : Opens _) refine (homOfLE ?_).op apply (Set.image_mono s.pt.hom.unop.le).trans exact Set.image_preimage.l_u_le (SetLike.coe s.pt.left.unop) · simp [eq_iff_true_of_subsingleton] } exact IsColimit.coconePointUniqueUpToIso ((Opens.map f).op.isPointwiseLeftKanExtensionLeftKanExtensionUnit ℱ (op U)) (colimitOfDiagramTerminal hx _) end end Presheaf end TopCat
.lake/packages/mathlib/Mathlib/Topology/Sheaves/Init.lean
import Mathlib.Init import Aesop /-! # Rule sets related to topological (pre)sheaves This module defines the `Restrict` Aesop rule set. Aesop rule sets only become visible once the file in which they're declared is imported, so we must put this declaration into its own file. -/ /- to prove subset relations -/ declare_aesop_rule_sets [Restrict]
.lake/packages/mathlib/Mathlib/Topology/Sheaves/Sheafify.lean
import Mathlib.Topology.Sheaves.LocalPredicate import Mathlib.Topology.Sheaves.Stalks /-! # Sheafification of `Type`-valued presheaves We construct the sheafification of a `Type`-valued presheaf, as the subsheaf of dependent functions into the stalks consisting of functions which are locally germs. We show that the stalks of the sheafification are isomorphic to the original stalks, via `stalkToFiber` which evaluates a germ of a dependent function at a point. We construct a morphism `toSheafify` from a presheaf to (the underlying presheaf of) its sheafification, given by sending a section to its collection of germs. ## Future work Show that the map induced on stalks by `toSheafify` is the inverse of `stalkToFiber`. Show sheafification is a functor from presheaves to sheaves, and that it is the left adjoint of the forgetful functor, following <https://stacks.math.columbia.edu/tag/007X>. -/ assert_not_exists CommRingCat universe v noncomputable section open TopCat Opposite TopologicalSpace CategoryTheory variable {X : TopCat.{v}} (F : Presheaf (Type v) X) namespace TopCat.Presheaf namespace Sheafify attribute [local instance] Types.instFunLike Types.instConcreteCategory in /-- The prelocal predicate on functions into the stalks, asserting that the function is equal to a germ. -/ def isGerm : PrelocalPredicate fun x => F.stalk x where pred {U} f := ∃ g : F.obj (op U), ∀ x : U, f x = F.germ U x.1 x.2 g res := fun i _ ⟨g, p⟩ => ⟨F.map i.op g, fun x ↦ (p (i x)).trans (F.germ_res_apply i x x.2 g).symm⟩ /-- The local predicate on functions into the stalks, asserting that the function is locally equal to a germ. -/ def isLocallyGerm : LocalPredicate fun x => F.stalk x := (isGerm F).sheafify end Sheafify /-- The sheafification of a `Type`-valued presheaf, defined as the functions into the stalks which are locally equal to germs. -/ def sheafify : Sheaf (Type v) X := subsheafToTypes (Sheafify.isLocallyGerm F) attribute [local instance] Types.instFunLike Types.instConcreteCategory in /-- The morphism from a presheaf to its sheafification, sending each section to its germs. (This forms the unit of the adjunction.) -/ def toSheafify : F ⟶ F.sheafify.1 where app U f := ⟨fun x => F.germ _ x x.2 f, PrelocalPredicate.sheafifyOf ⟨f, fun x => rfl⟩⟩ naturality U U' f := by ext x apply Subtype.ext -- Porting note (https://github.com/leanprover-community/mathlib4/issues/11041): Added `apply` ext ⟨u, m⟩ exact germ_res_apply F f.unop u m x /-- The natural morphism from the stalk of the sheafification to the original stalk. In `sheafifyStalkIso` we show this is an isomorphism. -/ def stalkToFiber (x : X) : F.sheafify.presheaf.stalk x ⟶ F.stalk x := TopCat.stalkToFiber (Sheafify.isLocallyGerm F) x attribute [local instance] Types.instFunLike Types.instConcreteCategory in theorem stalkToFiber_surjective (x : X) : Function.Surjective (F.stalkToFiber x) := by apply TopCat.stalkToFiber_surjective intro t obtain ⟨U, m, s, rfl⟩ := F.germ_exist _ t use ⟨U, m⟩ fconstructor · exact fun y => F.germ _ _ y.2 s · exact ⟨PrelocalPredicate.sheafifyOf ⟨s, fun _ => rfl⟩, rfl⟩ attribute [local instance] Types.instFunLike Types.instConcreteCategory in theorem stalkToFiber_injective (x : X) : Function.Injective (F.stalkToFiber x) := by apply TopCat.stalkToFiber_injective intro U V fU hU fV hV e rcases hU ⟨x, U.2⟩ with ⟨U', mU, iU, gU, wU⟩ rcases hV ⟨x, V.2⟩ with ⟨V', mV, iV, gV, wV⟩ have wUx := wU ⟨x, mU⟩ dsimp at wUx; rw [wUx] at e; clear wUx have wVx := wV ⟨x, mV⟩ dsimp at wVx; rw [wVx] at e; clear wVx rcases F.germ_eq x mU mV gU gV e with ⟨W, mW, iU', iV', (e' : F.map iU'.op gU = F.map iV'.op gV)⟩ use ⟨W ⊓ (U' ⊓ V'), ⟨mW, mU, mV⟩⟩ refine ⟨?_, ?_, ?_⟩ · change W ⊓ (U' ⊓ V') ⟶ U.obj exact Opens.infLERight _ _ ≫ Opens.infLELeft _ _ ≫ iU · change W ⊓ (U' ⊓ V') ⟶ V.obj exact Opens.infLERight _ _ ≫ Opens.infLERight _ _ ≫ iV · intro w specialize wU ⟨w.1, w.2.2.1⟩ specialize wV ⟨w.1, w.2.2.2⟩ refine wU.trans <| .trans ?_ wV.symm rw [← F.germ_res iU' w w.2.1, ← F.germ_res iV' w w.2.1, CategoryTheory.types_comp_apply, CategoryTheory.types_comp_apply, e'] /-- The isomorphism between a stalk of the sheafification and the original stalk. -/ def sheafifyStalkIso (x : X) : F.sheafify.presheaf.stalk x ≅ F.stalk x := (Equiv.ofBijective _ ⟨stalkToFiber_injective _ _, stalkToFiber_surjective _ _⟩).toIso -- PROJECT functoriality, and that sheafification is the left adjoint of the forgetful functor. end TopCat.Presheaf
.lake/packages/mathlib/Mathlib/Topology/Sheaves/Over.lean
import Mathlib.Topology.Sets.Opens import Mathlib.CategoryTheory.Comma.Over.Basic /-! # Opens and Over categories In this file, given a topological space `X`, and `U : Opens X`, we show that the category `Over U` (whose objects are the `V : Opens X` equipped with a morphism `V ⟶ U`) is equivalent to the category `Opens U`. ## TODO * show that both functors of the equivalence `overEquivalence U` are continuous and induce an equivalence between `Sheaf ((Opens.grothendieckTopology X).over U) A` and `Sheaf (Opens.grothendieckTopology U) A` for any category `A`. -/ universe u open CategoryTheory Topology namespace TopologicalSpace variable {X : Type u} [TopologicalSpace X] (U : Opens X) namespace Opens /-- If `X` is a topological space and `U : Opens X`, then the category `Over U` is equivalent to `Opens ↥U`. -/ @[simps!] def overEquivalence : Over U ≌ Opens ↥U where functor.obj V := ⟨_, IsOpen.preimage (continuous_subtype_val) V.left.isOpen⟩ functor.map f := homOfLE (Set.preimage_mono (f := Subtype.val) (leOfHom f.left)) inverse.obj W := Over.mk (Y := ⟨_, (U.isOpenEmbedding'.isOpen_iff_image_isOpen).1 W.isOpen⟩) (homOfLE (fun _ _ ↦ by aesop)) inverse.map f := Over.homMk (homOfLE (Set.image_mono (leOfHom f))) unitIso := NatIso.ofComponents (fun V ↦ Over.isoMk (eqToIso (by ext x dsimp simp only [SetLike.mem_coe, Set.mem_image, Set.mem_preimage, Subtype.exists, exists_and_left, exists_prop, exists_eq_right_right, iff_self_and] apply leOfHom V.hom))) counitIso := NatIso.ofComponents (fun V ↦ eqToIso (by aesop)) end Opens end TopologicalSpace
.lake/packages/mathlib/Mathlib/Topology/Sheaves/Functors.lean
import Mathlib.Topology.Sheaves.SheafCondition.Sites import Mathlib.CategoryTheory.Sites.Pullback /-! # functors between categories of sheaves Show that the pushforward of a sheaf is a sheaf, and define the pushforward functor from the category of C-valued sheaves on X to that of sheaves on Y, given a continuous map between topological spaces X and Y. ## Main definitions - `TopCat.Sheaf.pushforward`: The pushforward functor between sheaf categories over topological spaces. - `TopCat.Sheaf.pullback`: The pullback functor between sheaf categories over topological spaces. - `TopCat.Sheaf.pullbackPushforwardAdjunction`: The adjunction between pullback and pushforward for sheaves on topological spaces. -/ noncomputable section universe w v u open CategoryTheory open CategoryTheory.Limits open TopologicalSpace open scoped AlgebraicGeometry variable {C : Type u} [Category.{v} C] variable {X Y : TopCat.{w}} (f : X ⟶ Y) variable ⦃ι : Type w⦄ {U : ι → Opens Y} namespace TopCat namespace Sheaf open Presheaf /-- The pushforward of a sheaf (by a continuous map) is a sheaf. -/ theorem pushforward_sheaf_of_sheaf {F : X.Presheaf C} (h : F.IsSheaf) : (f _* F).IsSheaf := (Opens.map f).op_comp_isSheaf _ _ ⟨_, h⟩ variable (C) /-- The pushforward functor. -/ def pushforward (f : X ⟶ Y) : X.Sheaf C ⥤ Y.Sheaf C := (Opens.map f).sheafPushforwardContinuous _ _ _ lemma pushforward_forget (f : X ⟶ Y) : pushforward C f ⋙ forget C Y = forget C X ⋙ Presheaf.pushforward C f := rfl /-- Pushforward of sheaves is isomorphic (actually definitionally equal) to pushforward of presheaves. -/ def pushforwardForgetIso (f : X ⟶ Y) : pushforward C f ⋙ forget C Y ≅ forget C X ⋙ Presheaf.pushforward C f := Iso.refl _ variable {C} @[simp] lemma pushforward_obj_val (f : X ⟶ Y) (F : X.Sheaf C) : ((pushforward C f).obj F).1 = f _* F.1 := rfl @[simp] lemma pushforward_map (f : X ⟶ Y) {F F' : X.Sheaf C} (α : F ⟶ F') : ((pushforward C f).map α).1 = (Presheaf.pushforward C f).map α.1 := rfl variable (A : Type*) [Category.{w} A] {FA : A → A → Type*} {CA : A → Type w} variable [∀ X Y, FunLike (FA X Y) (CA X) (CA Y)] [ConcreteCategory.{w} A FA] [HasColimits A] variable [HasLimits A] [PreservesLimits (CategoryTheory.forget A)] variable [PreservesFilteredColimits (CategoryTheory.forget A)] variable [(CategoryTheory.forget A).ReflectsIsomorphisms] /-- The pullback functor. -/ def pullback (f : X ⟶ Y) : Y.Sheaf A ⥤ X.Sheaf A := (Opens.map f).sheafPullback _ _ _ /-- The pullback of a sheaf is isomorphic (actually definitionally equal) to the sheafification of the pullback as a presheaf. -/ def pullbackIso (f : X ⟶ Y) : pullback A f ≅ forget A Y ⋙ Presheaf.pullback A f ⋙ presheafToSheaf _ _ := Functor.sheafPullbackConstruction.sheafPullbackIso _ _ _ _ /-- The adjunction between pullback and pushforward for sheaves on topological spaces. -/ def pullbackPushforwardAdjunction (f : X ⟶ Y) : pullback A f ⊣ pushforward A f := (Opens.map f).sheafAdjunctionContinuous _ _ _ instance : (pullback A f).IsLeftAdjoint := (pullbackPushforwardAdjunction A f).isLeftAdjoint instance : (pushforward A f).IsRightAdjoint := (pullbackPushforwardAdjunction A f).isRightAdjoint end Sheaf end TopCat
.lake/packages/mathlib/Mathlib/Topology/Sheaves/CommRingCat.lean
import Mathlib.Algebra.Category.Ring.Colimits import Mathlib.Algebra.Category.Ring.Constructions import Mathlib.Algebra.Category.Ring.FilteredColimits import Mathlib.Topology.Category.TopCommRingCat import Mathlib.Topology.ContinuousMap.Algebra import Mathlib.Topology.Sheaves.Stalks /-! # Sheaves of (commutative) rings. Results specific to sheaves of commutative rings including sheaves of continuous functions `TopCat.continuousFunctions` with natural operations of `pullback` and `map` and sub, quotient, and localization operations on sheaves of rings with - `SubmonoidPresheaf` : A subpresheaf with a submonoid structure on each of the components. - `LocalizationPresheaf` : The localization of a presheaf of commrings at a `SubmonoidPresheaf`. - `TotalQuotientPresheaf` : The presheaf of total quotient rings. As more results accumulate, please consider splitting this file. ## References * https://stacks.math.columbia.edu/tag/0073 -/ universe u v w v₁ v₂ u₁ u₂ noncomputable section open CategoryTheory Limits TopologicalSpace Opposite namespace TopCat.Presheaf /-! As an example, we now have everything we need to check the sheaf condition for a presheaf of commutative rings, merely by checking the sheaf condition for the underlying sheaf of types. Note that the universes for `TopCat` and `CommRingCat` must be the same for this argument to go through. -/ example (X : TopCat.{u₁}) (F : Presheaf CommRingCat.{u₁} X) (h : Presheaf.IsSheaf (F ⋙ (forget CommRingCat))) : F.IsSheaf := (isSheaf_iff_isSheaf_comp (forget CommRingCat) F).mpr h open AlgebraicGeometry in /-- Unfold `restrictOpen` in the category of commutative rings (with the correct carrier type). Although unification hints help with applying `TopCat.Presheaf.restrictOpenCommRingCat`, so it can be safely de-specialized, this lemma needs to be kept to ensure rewrites go right. -/ lemma restrictOpenCommRingCat_apply {X : TopCat} {F : Presheaf CommRingCat X} {V : Opens ↑X} (f : CommRingCat.carrier (F.obj (op V))) (U : Opens ↑X) (e : U ≤ V := by restrict_tac) : f |_ U = F.map (homOfLE e).op f := rfl section SubmonoidPresheaf open scoped nonZeroDivisors variable {X : TopCat.{w}} {C : Type u} [Category.{v} C] -- note: this was specialized to `CommRingCat` in https://github.com/leanprover-community/mathlib4/issues/19757 /-- A subpresheaf with a submonoid structure on each of the components. -/ structure SubmonoidPresheaf (F : X.Presheaf CommRingCat) where /-- The submonoid structure for each component -/ obj : ∀ U, Submonoid (F.obj U) map : ∀ {U V : (Opens X)ᵒᵖ} (i : U ⟶ V), obj U ≤ (obj V).comap (F.map i).hom variable {F : X.Presheaf CommRingCat.{w}} (G : F.SubmonoidPresheaf) /-- The localization of a presheaf of `CommRing`s with respect to a `SubmonoidPresheaf`. -/ protected noncomputable def SubmonoidPresheaf.localizationPresheaf : X.Presheaf CommRingCat where obj U := CommRingCat.of <| Localization (G.obj U) map {_ _} i := CommRingCat.ofHom <| IsLocalization.map _ (F.map i).hom (G.map i) map_id U := by simp_rw [F.map_id] ext x exact IsLocalization.map_id x map_comp {U V W} i j := by delta CommRingCat.ofHom CommRingCat.of Bundled.of simp_rw [F.map_comp] ext : 1 dsimp rw [IsLocalization.map_comp_map] instance (U) : Algebra (F.obj U) (G.localizationPresheaf.obj U) := show Algebra _ (Localization (G.obj U)) from inferInstance instance (U) : IsLocalization (G.obj U) (G.localizationPresheaf.obj U) := show IsLocalization (G.obj U) (Localization (G.obj U)) from inferInstance /-- The map into the localization presheaf. -/ @[simps app] def SubmonoidPresheaf.toLocalizationPresheaf : F ⟶ G.localizationPresheaf where app U := CommRingCat.ofHom <| algebraMap (F.obj U) (Localization <| G.obj U) naturality {_ _} i := CommRingCat.hom_ext <| (IsLocalization.map_comp (G.map i)).symm instance epi_toLocalizationPresheaf : Epi G.toLocalizationPresheaf := @NatTrans.epi_of_epi_app _ _ _ _ _ _ G.toLocalizationPresheaf fun U => Localization.epi' (G.obj U) variable (F) /-- Given a submonoid at each of the stalks, we may define a submonoid presheaf consisting of sections whose restriction onto each stalk falls in the given submonoid. -/ @[simps] noncomputable def submonoidPresheafOfStalk (S : ∀ x : X, Submonoid (F.stalk x)) : F.SubmonoidPresheaf where obj U := ⨅ x : U.unop, Submonoid.comap (F.germ U.unop x.1 x.2).hom (S x) map {U V} i := by intro s hs simp only [Submonoid.mem_comap, Submonoid.mem_iInf] at hs ⊢ intro x change (F.map i.unop.op ≫ F.germ V.unop x.1 x.2) s ∈ _ rw [F.germ_res] exact hs ⟨_, i.unop.le x.2⟩ noncomputable instance : Inhabited F.SubmonoidPresheaf := ⟨F.submonoidPresheafOfStalk fun _ => ⊥⟩ /-- The localization of a presheaf of `CommRing`s at locally non-zero-divisor sections. -/ noncomputable def totalQuotientPresheaf : X.Presheaf CommRingCat.{w} := (F.submonoidPresheafOfStalk fun x => (F.stalk x)⁰).localizationPresheaf /-- The map into the presheaf of total quotient rings -/ noncomputable def toTotalQuotientPresheaf : F ⟶ F.totalQuotientPresheaf := SubmonoidPresheaf.toLocalizationPresheaf _ deriving Epi instance (F : X.Sheaf CommRingCat.{w}) : Mono F.presheaf.toTotalQuotientPresheaf := by apply (config := { allowSynthFailures := true }) NatTrans.mono_of_mono_app intro U apply ConcreteCategory.mono_of_injective dsimp [toTotalQuotientPresheaf] -- Porting note: `M` and `S` need to be specified manually, so used a hack to save some typing set m := _ change Function.Injective (algebraMap _ (Localization m)) refine IsLocalization.injective (M := m) (S := Localization m) ?_ rw [← nonZeroDivisorsRight_eq_nonZeroDivisors] intro s hs t e apply section_ext F (unop U) intro x hx rw [RingHom.map_zero] apply (Submonoid.mem_iInf.mp hs ⟨x, hx⟩).2 rw [← map_mul, e, map_zero] end SubmonoidPresheaf end TopCat.Presheaf section ContinuousFunctions namespace TopCat variable (X : TopCat.{v}) (R : TopCommRingCat.{v}) instance : NatCast (X ⟶ (forget₂ TopCommRingCat TopCat).obj R) where natCast n := ofHom n instance : IntCast (X ⟶ (forget₂ TopCommRingCat TopCat).obj R) where intCast n := ofHom n instance : Zero (X ⟶ (forget₂ TopCommRingCat TopCat).obj R) where zero := ofHom 0 instance : One (X ⟶ (forget₂ TopCommRingCat TopCat).obj R) where one := ofHom 1 instance : Neg (X ⟶ (forget₂ TopCommRingCat TopCat).obj R) where neg f := ofHom (-f.hom) instance : Sub (X ⟶ (forget₂ TopCommRingCat TopCat).obj R) where sub f g := ofHom (f.hom - g.hom) instance : Add (X ⟶ (forget₂ TopCommRingCat TopCat).obj R) where add f g := ofHom (f.hom + g.hom) instance : Mul (X ⟶ (forget₂ TopCommRingCat TopCat).obj R) where mul f g := ofHom (f.hom * g.hom) instance : SMul ℕ (X ⟶ (forget₂ TopCommRingCat TopCat).obj R) where smul n f := ofHom (n • f.hom) instance : SMul ℤ (X ⟶ (forget₂ TopCommRingCat TopCat).obj R) where smul n f := ofHom (n • f.hom) instance : Pow (X ⟶ (forget₂ TopCommRingCat TopCat).obj R) ℕ where pow f n := ofHom (f.hom ^ n) instance : CommRing (X ⟶ (forget₂ TopCommRingCat TopCat).obj R) := Function.Injective.commRing _ ConcreteCategory.hom_injective rfl rfl (fun _ _ => rfl) (fun _ _ => rfl) (fun _ => rfl) (fun _ _ => rfl) (fun _ _ => rfl) (fun _ _ => rfl) (fun _ _ => rfl) (fun _ => rfl) (fun _ => rfl) -- TODO upgrade the result to TopCommRing? /-- The (bundled) commutative ring of continuous functions from a topological space to a topological commutative ring, with pointwise multiplication. -/ def continuousFunctions (X : TopCat.{v}ᵒᵖ) (R : TopCommRingCat.{v}) : CommRingCat.{v} := CommRingCat.of (X.unop ⟶ (forget₂ TopCommRingCat TopCat).obj R) namespace continuousFunctions /-- Pulling back functions into a topological ring along a continuous map is a ring homomorphism. -/ def pullback {X Y : TopCatᵒᵖ} (f : X ⟶ Y) (R : TopCommRingCat) : continuousFunctions X R ⟶ continuousFunctions Y R := CommRingCat.ofHom { toFun g := f.unop ≫ g map_one' := rfl map_zero' := rfl map_add' := by cat_disch map_mul' := by cat_disch } /-- A homomorphism of topological rings can be postcomposed with functions from a source space `X`; this is a ring homomorphism (with respect to the pointwise ring operations on functions). -/ def map (X : TopCat.{u}ᵒᵖ) {R S : TopCommRingCat.{u}} (φ : R ⟶ S) : continuousFunctions X R ⟶ continuousFunctions X S := CommRingCat.ofHom { toFun g := g ≫ (forget₂ TopCommRingCat TopCat).map φ map_one' := by ext; exact φ.1.map_one map_zero' := by ext; exact φ.1.map_zero map_add' _ _ := by ext; exact φ.1.map_add _ _ map_mul' _ _ := by ext; exact φ.1.map_mul _ _ } end continuousFunctions /-- An upgraded version of the Yoneda embedding, observing that the continuous maps from `X : TopCat` to `R : TopCommRingCat` form a commutative ring, functorial in both `X` and `R`. -/ def commRingYoneda : TopCommRingCat.{u} ⥤ TopCat.{u}ᵒᵖ ⥤ CommRingCat.{u} where obj R := { obj := fun X => continuousFunctions X R map := fun {_ _} f => continuousFunctions.pullback f R map_id := fun X => by ext rfl map_comp := fun {_ _ _} _ _ => rfl } map {_ _} φ := { app := fun X => continuousFunctions.map X φ naturality := fun _ _ _ => rfl } map_id X := by ext rfl map_comp {_ _ _} _ _ := rfl /-- The presheaf (of commutative rings), consisting of functions on an open set `U ⊆ X` with values in some topological commutative ring `T`. For example, we could construct the presheaf of continuous complex-valued functions of `X` as ``` presheafToTopCommRing X (TopCommRingCat.of ℂ) ``` (this requires `import Topology.Instances.Complex`). -/ def presheafToTopCommRing (T : TopCommRingCat.{v}) : X.Presheaf CommRingCat.{v} := (Opens.toTopCat X).op ⋙ commRingYoneda.obj T end TopCat end ContinuousFunctions section Stalks namespace TopCat.Presheaf variable {X Y Z : TopCat.{v}} instance algebra_section_stalk (F : X.Presheaf CommRingCat) {U : Opens X} (x : U) : Algebra (F.obj <| op U) (F.stalk x) := (F.germ U x.1 x.2).hom.toAlgebra @[simp] theorem stalk_open_algebraMap {X : TopCat} (F : X.Presheaf CommRingCat) {U : Opens X} (x : U) : algebraMap (F.obj <| op U) (F.stalk x) = (F.germ U x.1 x.2).hom := rfl end TopCat.Presheaf end Stalks noncomputable section Gluing namespace TopCat.Sheaf open TopologicalSpace Opposite CategoryTheory variable {C : Type u} [Category.{v} C] {X : TopCat.{w}} variable (F : X.Sheaf C) (U V : Opens X) open CategoryTheory.Limits /-- `F(U ⊔ V)` is isomorphic to the `eq_locus` of the two maps `F(U) × F(V) ⟶ F(U ⊓ V)`. -/ def objSupIsoProdEqLocus {X : TopCat} (F : X.Sheaf CommRingCat) (U V : Opens X) : F.1.obj (op <| U ⊔ V) ≅ CommRingCat.of <| -- Porting note: Lean 3 is able to figure out the ring homomorphism automatically RingHom.eqLocus (RingHom.comp (F.val.map (homOfLE inf_le_left : U ⊓ V ⟶ U).op).hom (RingHom.fst (F.val.obj <| op U) (F.val.obj <| op V))) (RingHom.comp (F.val.map (homOfLE inf_le_right : U ⊓ V ⟶ V).op).hom (RingHom.snd (F.val.obj <| op U) (F.val.obj <| op V))) := (F.isLimitPullbackCone U V).conePointUniqueUpToIso (CommRingCat.pullbackConeIsLimit _ _) theorem objSupIsoProdEqLocus_hom_fst {X : TopCat} (F : X.Sheaf CommRingCat) (U V : Opens X) (x) : ((F.objSupIsoProdEqLocus U V).hom x).1.fst = F.1.map (homOfLE le_sup_left).op x := ConcreteCategory.congr_hom ((F.isLimitPullbackCone U V).conePointUniqueUpToIso_hom_comp (CommRingCat.pullbackConeIsLimit _ _) WalkingCospan.left) x theorem objSupIsoProdEqLocus_hom_snd {X : TopCat} (F : X.Sheaf CommRingCat) (U V : Opens X) (x) : ((F.objSupIsoProdEqLocus U V).hom x).1.snd = F.1.map (homOfLE le_sup_right).op x := ConcreteCategory.congr_hom ((F.isLimitPullbackCone U V).conePointUniqueUpToIso_hom_comp (CommRingCat.pullbackConeIsLimit _ _) WalkingCospan.right) x theorem objSupIsoProdEqLocus_inv_fst {X : TopCat} (F : X.Sheaf CommRingCat) (U V : Opens X) (x) : F.1.map (homOfLE le_sup_left).op ((F.objSupIsoProdEqLocus U V).inv x) = x.1.1 := ConcreteCategory.congr_hom ((F.isLimitPullbackCone U V).conePointUniqueUpToIso_inv_comp (CommRingCat.pullbackConeIsLimit _ _) WalkingCospan.left) x theorem objSupIsoProdEqLocus_inv_snd {X : TopCat} (F : X.Sheaf CommRingCat) (U V : Opens X) (x) : F.1.map (homOfLE le_sup_right).op ((F.objSupIsoProdEqLocus U V).inv x) = x.1.2 := ConcreteCategory.congr_hom ((F.isLimitPullbackCone U V).conePointUniqueUpToIso_inv_comp (CommRingCat.pullbackConeIsLimit _ _) WalkingCospan.right) x theorem objSupIsoProdEqLocus_inv_eq_iff {X : TopCat.{u}} (F : X.Sheaf CommRingCat.{u}) {U V W UW VW : Opens X} (e : W ≤ U ⊔ V) (x) (y : F.1.obj (op W)) (h₁ : UW = U ⊓ W) (h₂ : VW = V ⊓ W) : F.1.map (homOfLE e).op ((F.objSupIsoProdEqLocus U V).inv x) = y ↔ F.1.map (homOfLE (h₁ ▸ inf_le_left : UW ≤ U)).op x.1.1 = F.1.map (homOfLE <| h₁ ▸ inf_le_right).op y ∧ F.1.map (homOfLE (h₂ ▸ inf_le_left : VW ≤ V)).op x.1.2 = F.1.map (homOfLE <| h₂ ▸ inf_le_right).op y := by subst h₁ h₂ constructor · rintro rfl rw [← TopCat.Sheaf.objSupIsoProdEqLocus_inv_fst, ← TopCat.Sheaf.objSupIsoProdEqLocus_inv_snd] simp only [← CommRingCat.comp_apply, ← Functor.map_comp, ← op_comp, homOfLE_comp, and_self] · rintro ⟨e₁, e₂⟩ refine F.eq_of_locally_eq₂ (homOfLE (inf_le_right : U ⊓ W ≤ W)) (homOfLE (inf_le_right : V ⊓ W ≤ W)) ?_ _ _ ?_ ?_ · rw [← inf_sup_right] exact le_inf e le_rfl · rw [← e₁, ← TopCat.Sheaf.objSupIsoProdEqLocus_inv_fst] simp only [← CommRingCat.comp_apply, ← Functor.map_comp, ← op_comp, homOfLE_comp] · rw [← e₂, ← TopCat.Sheaf.objSupIsoProdEqLocus_inv_snd] simp only [← CommRingCat.comp_apply, ← Functor.map_comp, ← op_comp, homOfLE_comp] end TopCat.Sheaf end Gluing
.lake/packages/mathlib/Mathlib/Topology/Sheaves/Alexandrov.lean
import Mathlib.Combinatorics.Quiver.ReflQuiver import Mathlib.Order.CompletePartialOrder import Mathlib.Topology.Order.UpperLowerSetTopology import Mathlib.Topology.Sheaves.SheafCondition.OpensLeCover /-! Let `X` be a preorder `≤`, and consider the associated Alexandrov topology on `X`. Given a functor `F : X ⥤ C` to a complete category, we can extend `F` to a presheaf on (the topological space) `X` by taking the right Kan extension along the canonical functor `X ⥤ (Opens X)ᵒᵖ` sending `x : X` to the principal open `{y | x ≤ y}` in the Alexandrov topology. This file proves that this presheaf is a sheaf. -/ noncomputable section universe v u open CategoryTheory Limits Functor open TopCat Presheaf SheafCondition open TopologicalSpace Topology variable {X : Type v} [TopologicalSpace X] [Preorder X] [Topology.IsUpperSet X] {C : Type u} [Category.{v} C] [HasLimits C] (F : X ⥤ C) namespace Alexandrov /-- Given `x : X`, this is the principal open subset of `X` generated by `x`. -/ def principalOpen (x : X) : Opens X := .mk { y | x ≤ y } <| by rw [IsUpperSet.isOpen_iff_isUpperSet] intro y z h1 h2 exact le_trans h2 h1 lemma self_mem_principalOpen (x : X) : x ∈ principalOpen x := le_refl _ @[simp] lemma principalOpen_le_iff {x : X} (U : Opens X) : principalOpen x ≤ U ↔ x ∈ U := by refine ⟨fun h => h <| self_mem_principalOpen _, fun hx y hy => ?_⟩ · have := U.isOpen rw [IsUpperSet.isOpen_iff_isUpperSet] at this exact this hy hx lemma principalOpen_le {x y : X} (h : x ≤ y) : principalOpen y ≤ principalOpen x := fun _ hc => le_trans h hc variable (X) in /-- The functor sending `x : X` to the principal open associated with `x`. -/ @[simps] def principals : X ⥤ (Opens X)ᵒᵖ where obj x := .op <| principalOpen x map {x y} f := .op <| principalOpen_le f.le |>.hom lemma exists_le_of_le_sup {ι : Type v} {x : X} (Us : ι → Opens X) (h : principalOpen x ≤ iSup Us) : ∃ i : ι, principalOpen x ≤ Us i := by grind [principalOpen_le_iff, Opens.mem_iSup] /-- The right kan extension of `F` along `X ⥤ (Opens X)ᵒᵖ`. -/ abbrev principalsKanExtension : (Opens X)ᵒᵖ ⥤ C := (principals X).pointwiseRightKanExtension F /-- Given a structured arrow `f` with domain `U : Opens X` over `principals X`, this functor sends `f` to its "generator", an element of `X`. -/ abbrev generator (U : Opens X) : StructuredArrow (.op U) (principals X) ⥤ X := StructuredArrow.proj (.op U) (principals X) /-- Given a structured arrow `f` with domain `iSup Us` over `principals X`, where `Us` is a family of `Opens X`, this functor sends `f` to the principal open associated with it, considered as an object in the full subcategory of all `V : Opens X` such that `V ≤ Us i` for some `i`. This definition is primarily meant to be used in `lowerCone`, and `isLimit` below. -/ @[simps] def projSup {ι : Type v} (Us : ι → Opens X) : StructuredArrow (.op <| iSup Us) (principals X) ⥤ (ObjectProperty.FullSubcategory fun V => ∃ i, V ≤ Us i)ᵒᵖ where obj f := .op <| .mk (principalOpen f.right) <| exists_le_of_le_sup Us f.hom.unop.le map e := .op <| LE.le.hom <| principalOpen_le <| e.right.le variable {F} in /-- This is an auxiliary definition which is only meant to be used in `isLimit` below. -/ @[simps] def lowerCone {α : Type v} (Us : α → Opens X) (S : Cone ((ObjectProperty.ι fun V => ∃ i, V ≤ Us i).op ⋙ principalsKanExtension F)) : Cone (generator (iSup Us) ⋙ F) where pt := S.pt π := { app := fun f => S.π.app ((projSup Us).obj f) ≫ limit.π (generator (principalOpen f.right) ⋙ F) ⟨.mk .unit, f.right, 𝟙 _⟩ naturality := by rintro x y e simp only [Functor.const_obj_obj, Functor.comp_obj, Functor.const_obj_map, Functor.op_obj, ObjectProperty.ι_obj, Functor.pointwiseRightKanExtension_obj, Category.id_comp, Functor.comp_map, Category.assoc] rw [← S.w ((projSup Us).map e), Category.assoc] congr 1 simp only [projSup_obj, Functor.comp_obj, Functor.op_obj, ObjectProperty.ι_obj, Functor.pointwiseRightKanExtension_obj, projSup_map, homOfLE_leOfHom, Functor.comp_map, Functor.op_map, Quiver.Hom.unop_op, Functor.pointwiseRightKanExtension_map, limit.lift_π] let xx : StructuredArrow (Opposite.op (principalOpen x.right)) (principals X) := ⟨.mk .unit, x.right, 𝟙 _⟩ let yy : StructuredArrow (Opposite.op (principalOpen x.right)) (principals X) := ⟨.mk .unit, y.right, .op <| LE.le.hom <| principalOpen_le e.right.le⟩ let ee : xx ⟶ yy := { left := 𝟙 _, right := e.right } exact limit.w (StructuredArrow.proj (Opposite.op (principalOpen x.right)) (principals X) ⋙ F) ee |>.symm } /-- This is the main construction in this file showing that the right Kan extension of `F : X ⥤ C` along `principals : X ⥤ (Opens X)ᵒᵖ` is a sheaf, by showing that a certain cone is a limit cone. See `isSheaf_principalsKanExtension` for the main application. -/ def isLimit {X : TopCat.{v}} [Preorder X] [Topology.IsUpperSet X] (F : X ⥤ C) (α : Type v) (Us : α → Opens X) : IsLimit (mapCone (principalsKanExtension F) (opensLeCoverCocone Us).op) where lift S := limit.lift _ (lowerCone Us S) fac := by rintro S ⟨V, i, hV⟩ dsimp [forget, opensLeCoverCocone] ext ⟨_, x, f⟩ simp only [comp_obj, StructuredArrow.proj_obj, Category.assoc, limit.lift_π, lowerCone_pt, lowerCone_π_app, const_obj_obj, projSup_obj, StructuredArrow.map_obj_right, op_obj, ObjectProperty.ι_obj, pointwiseRightKanExtension_obj] have e : principalOpen x ≤ V := f.unop.le let VV : (ObjectProperty.FullSubcategory fun V => ∃ i, V ≤ Us i) := ⟨V, i, hV⟩ let xx : (ObjectProperty.FullSubcategory fun V => ∃ i, V ≤ Us i) := ⟨principalOpen x, i, le_trans e hV⟩ let ee : xx ⟶ VV := e.hom rw [← S.w ee.op, Category.assoc] congr 1 simp only [comp_obj, op_obj, ObjectProperty.ι_obj, pointwiseRightKanExtension_obj, Functor.comp_map, op_map, Quiver.Hom.unop_op, pointwiseRightKanExtension_map, limit.lift_π, xx, VV] congr uniq := by intro S m hm dsimp symm ext ⟨_, x, f⟩ simp only [lowerCone_pt, comp_obj, limit.lift_π, lowerCone_π_app, const_obj_obj, projSup_obj, op_obj, ObjectProperty.ι_obj, pointwiseRightKanExtension_obj] specialize hm ⟨principalOpen x, ?_⟩ · apply exists_le_of_le_sup exact f.unop.le · rw [← hm] simp only [mapCone_pt, Cocone.op_pt, pointwiseRightKanExtension_obj, const_obj_obj, comp_obj, op_obj, ObjectProperty.ι_obj, mapCone_π_app, Cocone.op_π, NatTrans.op_app, pointwiseRightKanExtension_map, Category.assoc, limit.lift_π] congr theorem isSheaf_principalsKanExtension {X : TopCat.{v}} [Preorder X] [Topology.IsUpperSet X] (F : X ⥤ C) : Presheaf.IsSheaf (principalsKanExtension F) := by rw [isSheaf_iff_isSheafOpensLeCover] intro ι Us constructor apply isLimit end Alexandrov open Alexandrov /-- The main theorem of this file. If `X` is a topological space and preorder whose topology is the `UpperSet` topology associated with the preorder, `F : X ⥤ C` is a functor into a complete category from the preorder category, and `P : (Opens X)ᵒᵖ ⥤ C` denotes the right Kan extension of `F` along the functor `X ⥤ (Open X)ᵒᵖ` which sends `x : X` to `{y | x ≤ y}`, then `P` is a sheaf. -/ theorem Topology.IsUpperSet.isSheaf_of_isRightKanExtension (P : (Opens X)ᵒᵖ ⥤ C) (η : Alexandrov.principals X ⋙ P ⟶ F) [P.IsRightKanExtension η] : Presheaf.IsSheaf (Opens.grothendieckTopology X) P := by let γ : principals X ⋙ principalsKanExtension F ⟶ F := (principals X).pointwiseRightKanExtensionCounit F let _ : (principalsKanExtension F).IsRightKanExtension γ := inferInstance have : P ≅ principalsKanExtension F := @rightKanExtensionUnique _ _ _ _ _ _ _ _ _ _ (by assumption) _ _ (by assumption) change TopCat.Presheaf.IsSheaf (X := TopCat.of X) P rw [isSheaf_iso_iff this] let _ : Preorder (TopCat.of X) := inferInstanceAs <| Preorder X have _ : Topology.IsUpperSet (TopCat.of X) := inferInstanceAs <| Topology.IsUpperSet X exact isSheaf_principalsKanExtension (X := TopCat.of X) F
.lake/packages/mathlib/Mathlib/Topology/Sheaves/Skyscraper.lean
import Mathlib.Topology.Sheaves.PUnit import Mathlib.Topology.Sheaves.Stalks import Mathlib.Topology.Sheaves.Functors /-! # Skyscraper (pre)sheaves A skyscraper (pre)sheaf `𝓕 : (Pre)Sheaf C X` is the (pre)sheaf with value `A` at point `p₀` that is supported only at open sets contain `p₀`, i.e. `𝓕(U) = A` if `p₀ ∈ U` and `𝓕(U) = *` if `p₀ ∉ U` where `*` is a terminal object of `C`. In terms of stalks, `𝓕` is supported at all specializations of `p₀`, i.e. if `p₀ ⤳ x` then `𝓕ₓ ≅ A` and if `¬ p₀ ⤳ x` then `𝓕ₓ ≅ *`. ## Main definitions * `skyscraperPresheaf`: `skyscraperPresheaf p₀ A` is the skyscraper presheaf at point `p₀` with value `A`. * `skyscraperSheaf`: the skyscraper presheaf satisfies the sheaf condition. ## Main statements * `skyscraperPresheafStalkOfSpecializes`: if `y ∈ closure {p₀}` then the stalk of `skyscraperPresheaf p₀ A` at `y` is `A`. * `skyscraperPresheafStalkOfNotSpecializes`: if `y ∉ closure {p₀}` then the stalk of `skyscraperPresheaf p₀ A` at `y` is `*` the terminal object. TODO: generalize universe level when calculating stalks, after generalizing universe level of stalk. -/ noncomputable section open TopologicalSpace TopCat CategoryTheory CategoryTheory.Limits Opposite open scoped AlgebraicGeometry universe u v w variable {X : TopCat.{u}} (p₀ : X) [∀ U : Opens X, Decidable (p₀ ∈ U)] section variable {C : Type v} [Category.{w} C] [HasTerminal C] (A : C) /-- A skyscraper presheaf is a presheaf supported at a single point: if `p₀ ∈ X` is a specified point, then the skyscraper presheaf `𝓕` with value `A` is defined by `U ↦ A` if `p₀ ∈ U` and `U ↦ *` if `p₀ ∉ A` where `*` is some terminal object. -/ @[simps] def skyscraperPresheaf : Presheaf C X where obj U := if p₀ ∈ unop U then A else terminal C map {U V} i := if h : p₀ ∈ unop V then eqToHom <| by rw [if_pos h, if_pos (by simpa using i.unop.le h)] else ((if_neg h).symm.ndrec terminalIsTerminal).from _ map_id U := (em (p₀ ∈ U.unop)).elim (fun h => dif_pos h) fun h => ((if_neg h).symm.ndrec terminalIsTerminal).hom_ext _ _ map_comp {U V W} iVU iWV := by by_cases hW : p₀ ∈ unop W · have hV : p₀ ∈ unop V := leOfHom iWV.unop hW simp only [dif_pos hW, dif_pos hV, eqToHom_trans] · dsimp; rw [dif_neg hW]; apply ((if_neg hW).symm.ndrec terminalIsTerminal).hom_ext theorem skyscraperPresheaf_eq_pushforward [hd : ∀ U : Opens (TopCat.of PUnit.{u + 1}), Decidable (PUnit.unit ∈ U)] : skyscraperPresheaf p₀ A = (ofHom (ContinuousMap.const (TopCat.of PUnit) p₀)) _* skyscraperPresheaf (X := TopCat.of PUnit) PUnit.unit A := by convert_to @skyscraperPresheaf X p₀ (fun U => hd <| (Opens.map <| ofHom <| ContinuousMap.const _ p₀).obj U) C _ _ A = _ <;> congr /-- Taking skyscraper presheaf at a point is functorial: `c ↦ skyscraper p₀ c` defines a functor by sending every `f : a ⟶ b` to the natural transformation `α` defined as: `α(U) = f : a ⟶ b` if `p₀ ∈ U` and the unique morphism to a terminal object in `C` if `p₀ ∉ U`. -/ @[simps] def SkyscraperPresheafFunctor.map' {a b : C} (f : a ⟶ b) : skyscraperPresheaf p₀ a ⟶ skyscraperPresheaf p₀ b where app U := if h : p₀ ∈ U.unop then eqToHom (if_pos h) ≫ f ≫ eqToHom (if_pos h).symm else ((if_neg h).symm.ndrec terminalIsTerminal).from _ naturality U V i := by simp only [skyscraperPresheaf_map] by_cases hV : p₀ ∈ V.unop · have hU : p₀ ∈ U.unop := leOfHom i.unop hV simp only [skyscraperPresheaf_obj, hU, hV, ↓reduceDIte, eqToHom_trans_assoc, Category.assoc, eqToHom_trans] · apply ((if_neg hV).symm.ndrec terminalIsTerminal).hom_ext theorem SkyscraperPresheafFunctor.map'_id {a : C} : SkyscraperPresheafFunctor.map' p₀ (𝟙 a) = 𝟙 _ := by ext U simp only [SkyscraperPresheafFunctor.map'_app]; split_ifs <;> cat_disch theorem SkyscraperPresheafFunctor.map'_comp {a b c : C} (f : a ⟶ b) (g : b ⟶ c) : SkyscraperPresheafFunctor.map' p₀ (f ≫ g) = SkyscraperPresheafFunctor.map' p₀ f ≫ SkyscraperPresheafFunctor.map' p₀ g := by ext U simp only [SkyscraperPresheafFunctor.map'_app] split_ifs with h <;> cat_disch /-- Taking skyscraper presheaf at a point is functorial: `c ↦ skyscraper p₀ c` defines a functor by sending every `f : a ⟶ b` to the natural transformation `α` defined as: `α(U) = f : a ⟶ b` if `p₀ ∈ U` and the unique morphism to a terminal object in `C` if `p₀ ∉ U`. -/ @[simps] def skyscraperPresheafFunctor : C ⥤ Presheaf C X where obj := skyscraperPresheaf p₀ map := SkyscraperPresheafFunctor.map' p₀ map_id _ := SkyscraperPresheafFunctor.map'_id p₀ map_comp := SkyscraperPresheafFunctor.map'_comp p₀ end section -- In this section, we calculate the stalks for skyscraper presheaves. -- We need to restrict universe level. variable {C : Type v} [Category.{u} C] (A : C) [HasTerminal C] /-- The cocone at `A` for the stalk functor of `skyscraperPresheaf p₀ A` when `y ∈ closure {p₀}` -/ @[simps] def skyscraperPresheafCoconeOfSpecializes {y : X} (h : p₀ ⤳ y) : Cocone ((OpenNhds.inclusion y).op ⋙ skyscraperPresheaf p₀ A) where pt := A ι := { app := fun U => eqToHom <| if_pos <| h.mem_open U.unop.1.2 U.unop.2 naturality := fun U V inc => by change dite _ _ _ ≫ _ = _; rw [dif_pos] swap · exact h.mem_open V.unop.1.2 V.unop.2 · simp only [Functor.comp_obj, Functor.op_obj, skyscraperPresheaf_obj, unop_op, Functor.const_obj_obj, eqToHom_trans, Functor.const_obj_map, Category.comp_id] } /-- The cocone at `A` for the stalk functor of `skyscraperPresheaf p₀ A` when `y ∈ closure {p₀}` is a colimit -/ noncomputable def skyscraperPresheafCoconeIsColimitOfSpecializes {y : X} (h : p₀ ⤳ y) : IsColimit (skyscraperPresheafCoconeOfSpecializes p₀ A h) where desc c := eqToHom (if_pos trivial).symm ≫ c.ι.app (op ⊤) fac c U := by dsimp rw [← c.w (homOfLE <| (le_top : unop U ≤ _)).op] change _ ≫ _ ≫ dite _ _ _ ≫ _ = _ rw [dif_pos] · simp only [eqToHom_trans_assoc, eqToHom_refl, Category.id_comp, op_unop] · exact h.mem_open U.unop.1.2 U.unop.2 uniq c f h := by dsimp rw [← h, skyscraperPresheafCoconeOfSpecializes_ι_app, eqToHom_trans_assoc, eqToHom_refl, Category.id_comp] /-- If `y ∈ closure {p₀}`, then the stalk of `skyscraperPresheaf p₀ A` at `y` is `A`. -/ noncomputable def skyscraperPresheafStalkOfSpecializes [HasColimits C] {y : X} (h : p₀ ⤳ y) : (skyscraperPresheaf p₀ A).stalk y ≅ A := colimit.isoColimitCocone ⟨_, skyscraperPresheafCoconeIsColimitOfSpecializes p₀ A h⟩ @[reassoc (attr := simp)] lemma germ_skyscraperPresheafStalkOfSpecializes_hom [HasColimits C] {y : X} (h : p₀ ⤳ y) (U hU) : (skyscraperPresheaf p₀ A).germ U y hU ≫ (skyscraperPresheafStalkOfSpecializes p₀ A h).hom = eqToHom (if_pos (h.mem_open U.2 hU)) := colimit.isoColimitCocone_ι_hom _ _ /-- The cocone at `*` for the stalk functor of `skyscraperPresheaf p₀ A` when `y ∉ closure {p₀}` -/ @[simps] def skyscraperPresheafCocone (y : X) : Cocone ((OpenNhds.inclusion y).op ⋙ skyscraperPresheaf p₀ A) where pt := terminal C ι := { app := fun _ => terminal.from _ naturality := fun _ _ _ => terminalIsTerminal.hom_ext _ _ } /-- The cocone at `*` for the stalk functor of `skyscraperPresheaf p₀ A` when `y ∉ closure {p₀}` is a colimit -/ noncomputable def skyscraperPresheafCoconeIsColimitOfNotSpecializes {y : X} (h : ¬p₀ ⤳ y) : IsColimit (skyscraperPresheafCocone p₀ A y) := let h1 : ∃ U : OpenNhds y, p₀ ∉ U.1 := let ⟨U, ho, h₀, hy⟩ := not_specializes_iff_exists_open.mp h ⟨⟨⟨U, ho⟩, h₀⟩, hy⟩ { desc := fun c => eqToHom (if_neg h1.choose_spec).symm ≫ c.ι.app (op h1.choose) fac := fun c U => by change _ = c.ι.app (op U.unop) simp only [← c.w (homOfLE <| @inf_le_left _ _ h1.choose U.unop).op, ← c.w (homOfLE <| @inf_le_right _ _ h1.choose U.unop).op, ← Category.assoc] congr 1 refine ((if_neg ?_).symm.ndrec terminalIsTerminal).hom_ext _ _ exact fun h => h1.choose_spec h.1 uniq := fun c f H => by dsimp rw [← Category.id_comp f, ← H, ← Category.assoc] congr 1; apply terminalIsTerminal.hom_ext } /-- If `y ∉ closure {p₀}`, then the stalk of `skyscraperPresheaf p₀ A` at `y` is isomorphic to a terminal object. -/ noncomputable def skyscraperPresheafStalkOfNotSpecializes [HasColimits C] {y : X} (h : ¬p₀ ⤳ y) : (skyscraperPresheaf p₀ A).stalk y ≅ terminal C := colimit.isoColimitCocone ⟨_, skyscraperPresheafCoconeIsColimitOfNotSpecializes _ A h⟩ /-- If `y ∉ closure {p₀}`, then the stalk of `skyscraperPresheaf p₀ A` at `y` is a terminal object -/ def skyscraperPresheafStalkOfNotSpecializesIsTerminal [HasColimits C] {y : X} (h : ¬p₀ ⤳ y) : IsTerminal ((skyscraperPresheaf p₀ A).stalk y) := IsTerminal.ofIso terminalIsTerminal <| (skyscraperPresheafStalkOfNotSpecializes _ _ h).symm theorem skyscraperPresheaf_isSheaf : (skyscraperPresheaf p₀ A).IsSheaf := by classical exact (Presheaf.isSheaf_iso_iff (eqToIso <| skyscraperPresheaf_eq_pushforward p₀ A)).mpr <| (Sheaf.pushforward_sheaf_of_sheaf _ (Presheaf.isSheaf_on_punit_of_isTerminal _ (by dsimp [skyscraperPresheaf] rw [if_neg] · exact terminalIsTerminal · #adaptation_note /-- 2024-03-24 Previously the universe annotation was not needed here. -/ exact Set.notMem_empty PUnit.unit.{u + 1}))) /-- The skyscraper presheaf supported at `p₀` with value `A` is the sheaf that assigns `A` to all opens `U` that contain `p₀` and assigns `*` otherwise. -/ def skyscraperSheaf : Sheaf C X := ⟨skyscraperPresheaf p₀ A, skyscraperPresheaf_isSheaf _ _⟩ /-- Taking skyscraper sheaf at a point is functorial: `c ↦ skyscraper p₀ c` defines a functor by sending every `f : a ⟶ b` to the natural transformation `α` defined as: `α(U) = f : a ⟶ b` if `p₀ ∈ U` and the unique morphism to a terminal object in `C` if `p₀ ∉ U`. -/ def skyscraperSheafFunctor : C ⥤ Sheaf C X where obj c := skyscraperSheaf p₀ c map f := Sheaf.Hom.mk <| (skyscraperPresheafFunctor p₀).map f map_id _ := Sheaf.Hom.ext <| (skyscraperPresheafFunctor p₀).map_id _ map_comp _ _ := Sheaf.Hom.ext <| (skyscraperPresheafFunctor p₀).map_comp _ _ namespace StalkSkyscraperPresheafAdjunctionAuxs variable [HasColimits C] /-- If `f : 𝓕.stalk p₀ ⟶ c`, then a natural transformation `𝓕 ⟶ skyscraperPresheaf p₀ c` can be defined by: `𝓕.germ p₀ ≫ f : 𝓕(U) ⟶ c` if `p₀ ∈ U` and the unique morphism to a terminal object if `p₀ ∉ U`. -/ @[simps] def toSkyscraperPresheaf {𝓕 : Presheaf C X} {c : C} (f : 𝓕.stalk p₀ ⟶ c) : 𝓕 ⟶ skyscraperPresheaf p₀ c where app U := if h : p₀ ∈ U.unop then 𝓕.germ _ p₀ h ≫ f ≫ eqToHom (if_pos h).symm else ((if_neg h).symm.ndrec terminalIsTerminal).from _ naturality U V inc := by dsimp by_cases hV : p₀ ∈ V.unop · have hU : p₀ ∈ U.unop := leOfHom inc.unop hV split_ifs rw [← Category.assoc, 𝓕.germ_res' inc, Category.assoc, Category.assoc, eqToHom_trans] · split_ifs exact ((if_neg hV).symm.ndrec terminalIsTerminal).hom_ext .. /-- If `f : 𝓕 ⟶ skyscraperPresheaf p₀ c` is a natural transformation, then there is a morphism `𝓕.stalk p₀ ⟶ c` defined as the morphism from colimit to cocone at `c`. -/ def fromStalk {𝓕 : Presheaf C X} {c : C} (f : 𝓕 ⟶ skyscraperPresheaf p₀ c) : 𝓕.stalk p₀ ⟶ c := let χ : Cocone ((OpenNhds.inclusion p₀).op ⋙ 𝓕) := Cocone.mk c <| { app := fun U => f.app ((OpenNhds.inclusion p₀).op.obj U) ≫ eqToHom (if_pos U.unop.2) naturality := fun U V inc => by dsimp only [Functor.const_obj_map, Functor.const_obj_obj, Functor.comp_map, Functor.comp_obj, Functor.op_obj, skyscraperPresheaf_obj] rw [Category.comp_id, ← Category.assoc, comp_eqToHom_iff, Category.assoc, eqToHom_trans, f.naturality, skyscraperPresheaf_map] have hV : p₀ ∈ (OpenNhds.inclusion p₀).obj V.unop := V.unop.2 simp only [dif_pos hV] } colimit.desc _ χ @[reassoc (attr := simp)] lemma germ_fromStalk {𝓕 : Presheaf C X} {c : C} (f : 𝓕 ⟶ skyscraperPresheaf p₀ c) (U) (hU) : 𝓕.germ U p₀ hU ≫ fromStalk p₀ f = f.app (op U) ≫ eqToHom (if_pos hU) := colimit.ι_desc _ _ theorem to_skyscraper_fromStalk {𝓕 : Presheaf C X} {c : C} (f : 𝓕 ⟶ skyscraperPresheaf p₀ c) : toSkyscraperPresheaf p₀ (fromStalk _ f) = f := by apply NatTrans.ext ext U dsimp split_ifs with h · rw [← Category.assoc, germ_fromStalk, Category.assoc, eqToHom_trans, eqToHom_refl, Category.comp_id] · exact ((if_neg h).symm.ndrec terminalIsTerminal).hom_ext .. theorem fromStalk_to_skyscraper {𝓕 : Presheaf C X} {c : C} (f : 𝓕.stalk p₀ ⟶ c) : fromStalk p₀ (toSkyscraperPresheaf _ f) = f := by refine 𝓕.stalk_hom_ext fun U hxU ↦ ?_ rw [germ_fromStalk, toSkyscraperPresheaf_app, dif_pos hxU, Category.assoc, Category.assoc, eqToHom_trans, eqToHom_refl, Category.comp_id, Presheaf.germ] /-- The unit in `Presheaf.stalkFunctor ⊣ skyscraperPresheafFunctor` -/ @[simps] protected def unit : 𝟭 (Presheaf C X) ⟶ Presheaf.stalkFunctor C p₀ ⋙ skyscraperPresheafFunctor p₀ where app _ := toSkyscraperPresheaf _ <| 𝟙 _ naturality 𝓕 𝓖 f := by ext U; dsimp split_ifs with h · simp only [Category.id_comp, Category.assoc, eqToHom_trans_assoc, eqToHom_refl, Presheaf.stalkFunctor_map_germ_assoc, Presheaf.stalkFunctor_obj] · apply ((if_neg h).symm.ndrec terminalIsTerminal).hom_ext /-- The counit in `Presheaf.stalkFunctor ⊣ skyscraperPresheafFunctor` -/ @[simps] protected def counit : skyscraperPresheafFunctor p₀ ⋙ (Presheaf.stalkFunctor C p₀ : Presheaf C X ⥤ C) ⟶ 𝟭 C where app c := (skyscraperPresheafStalkOfSpecializes p₀ c specializes_rfl).hom naturality x y f := TopCat.Presheaf.stalk_hom_ext _ fun U hxU ↦ by simp [hxU] end StalkSkyscraperPresheafAdjunctionAuxs section open StalkSkyscraperPresheafAdjunctionAuxs /-- `skyscraperPresheafFunctor` is the right adjoint of `Presheaf.stalkFunctor` -/ def skyscraperPresheafStalkAdjunction [HasColimits C] : (Presheaf.stalkFunctor C p₀ : Presheaf C X ⥤ C) ⊣ skyscraperPresheafFunctor p₀ where unit := StalkSkyscraperPresheafAdjunctionAuxs.unit _ counit := StalkSkyscraperPresheafAdjunctionAuxs.counit _ left_triangle_components X := by dsimp [Presheaf.stalkFunctor, toSkyscraperPresheaf] ext simp only [Functor.comp_obj, Functor.op_obj, ι_colimMap_assoc, skyscraperPresheaf_obj, Functor.whiskerLeft_app, Category.comp_id] split_ifs with h · simp [skyscraperPresheafStalkOfSpecializes] rfl · simp only [skyscraperPresheafStalkOfSpecializes, colimit.isoColimitCocone_ι_hom, skyscraperPresheafCoconeOfSpecializes_pt, skyscraperPresheafCoconeOfSpecializes_ι_app, Functor.comp_obj, Functor.op_obj, skyscraperPresheaf_obj, Functor.const_obj_obj] rw [comp_eqToHom_iff] apply ((if_neg h).symm.ndrec terminalIsTerminal).hom_ext right_triangle_components Y := by ext simp only [skyscraperPresheafFunctor_obj, Functor.id_obj, skyscraperPresheaf_obj, Functor.comp_obj, Presheaf.stalkFunctor_obj, unit_app, counit_app, skyscraperPresheafStalkOfSpecializes, skyscraperPresheafFunctor_map, Presheaf.comp_app, toSkyscraperPresheaf_app, Category.id_comp, SkyscraperPresheafFunctor.map'_app] split_ifs with h · simp [Presheaf.germ] rfl · simp rfl instance [HasColimits C] : (skyscraperPresheafFunctor p₀ : C ⥤ Presheaf C X).IsRightAdjoint := (skyscraperPresheafStalkAdjunction _).isRightAdjoint instance [HasColimits C] : (Presheaf.stalkFunctor C p₀).IsLeftAdjoint := -- Use a classical instance instead of the one from `variable`s have : ∀ U : Opens X, Decidable (p₀ ∈ U) := fun _ ↦ Classical.dec _ (skyscraperPresheafStalkAdjunction _).isLeftAdjoint /-- Taking stalks of a sheaf is the left adjoint functor to `skyscraperSheafFunctor` -/ def stalkSkyscraperSheafAdjunction [HasColimits C] : Sheaf.forget C X ⋙ Presheaf.stalkFunctor _ p₀ ⊣ skyscraperSheafFunctor p₀ where -- Porting note (https://github.com/leanprover-community/mathlib4/issues/11041): `ext1` is changed to `Sheaf.Hom.ext`, unit := { app := fun 𝓕 => ⟨(StalkSkyscraperPresheafAdjunctionAuxs.unit p₀).app 𝓕.1⟩ naturality := fun 𝓐 𝓑 f => Sheaf.Hom.ext <| by apply (StalkSkyscraperPresheafAdjunctionAuxs.unit p₀).naturality } counit := StalkSkyscraperPresheafAdjunctionAuxs.counit p₀ left_triangle_components X := ((skyscraperPresheafStalkAdjunction p₀).left_triangle_components X.val) right_triangle_components _ := Sheaf.Hom.ext ((skyscraperPresheafStalkAdjunction p₀).right_triangle_components _) instance [HasColimits C] : (skyscraperSheafFunctor p₀ : C ⥤ Sheaf C X).IsRightAdjoint := (stalkSkyscraperSheafAdjunction _).isRightAdjoint end end
.lake/packages/mathlib/Mathlib/Topology/Sheaves/LocalPredicate.lean
import Mathlib.Topology.Sheaves.SheafOfFunctions import Mathlib.Topology.Sheaves.Stalks import Mathlib.Topology.Sheaves.SheafCondition.UniqueGluing /-! # Functions satisfying a local predicate form a sheaf. At this stage, in `Mathlib/Topology/Sheaves/SheafOfFunctions.lean` we've proved that not-necessarily-continuous functions from a topological space into some type (or type family) form a sheaf. Why do the continuous functions form a sheaf? The point is just that continuity is a local condition, so one can use the lifting condition for functions to provide a candidate lift, then verify that the lift is actually continuous by using the factorisation condition for the lift (which guarantees that on each open set it agrees with the functions being lifted, which were assumed to be continuous). This file abstracts this argument to work for any collection of dependent functions on a topological space satisfying a "local predicate". As an application, we check that continuity is a local predicate in this sense, and provide * `TopCat.sheafToTop`: continuous functions into a topological space form a sheaf A sheaf constructed in this way has a natural map `stalkToFiber` from the stalks to the types in the ambient type family. We give conditions sufficient to show that this map is injective and/or surjective. -/ noncomputable section variable {X : TopCat} variable (T : X → Type*) open TopologicalSpace open Opposite open CategoryTheory open CategoryTheory.Limits open CategoryTheory.Limits.Types namespace TopCat /-- Given a topological space `X : TopCat` and a type family `T : X → Type`, a `P : PrelocalPredicate T` consists of: * a family of predicates `P.pred`, one for each `U : Opens X`, of the form `(Π x : U, T x) → Prop` * a proof that if `f : Π x : V, T x` satisfies the predicate on `V : Opens X`, then the restriction of `f` to any open subset `U` also satisfies the predicate. -/ structure PrelocalPredicate where /-- The underlying predicate of a prelocal predicate -/ pred : ∀ {U : Opens X}, (∀ x : U, T x) → Prop /-- The underlying predicate should be invariant under restriction -/ res : ∀ {U V : Opens X} (i : U ⟶ V) (f : ∀ x : V, T x) (_ : pred f), pred fun x : U ↦ f (i x) variable (X) /-- Continuity is a "prelocal" predicate on functions to a fixed topological space `T`. -/ @[simps!] def continuousPrelocal (T) [TopologicalSpace T] : PrelocalPredicate fun _ : X ↦ T where pred {_} f := Continuous f res {_ _} i _ h := Continuous.comp h (Opens.isOpenEmbedding_of_le i.le).continuous /-- Satisfying the inhabited linter. -/ instance inhabitedPrelocalPredicate (T) [TopologicalSpace T] : Inhabited (PrelocalPredicate fun _ : X ↦ T) := ⟨continuousPrelocal X T⟩ variable {X} in /-- Given a topological space `X : TopCat` and a type family `T : X → Type`, a `P : LocalPredicate T` consists of: * a family of predicates `P.pred`, one for each `U : Opens X`, of the form `(Π x : U, T x) → Prop` * a proof that if `f : Π x : V, T x` satisfies the predicate on `V : Opens X`, then the restriction of `f` to any open subset `U` also satisfies the predicate, and * a proof that given some `f : Π x : U, T x`, if for every `x : U` we can find an open set `x ∈ V ≤ U` so that the restriction of `f` to `V` satisfies the predicate, then `f` itself satisfies the predicate. -/ structure LocalPredicate extends PrelocalPredicate T where /-- A local predicate must be local --- provided that it is locally satisfied, it is also globally satisfied -/ locality : ∀ {U : Opens X} (f : ∀ x : U, T x) (_ : ∀ x : U, ∃ (V : Opens X) (_ : x.1 ∈ V) (i : V ⟶ U), pred fun x : V ↦ f (i x : U)), pred f /-- Continuity is a "local" predicate on functions to a fixed topological space `T`. -/ def continuousLocal (T) [TopologicalSpace T] : LocalPredicate fun _ : X ↦ T := { continuousPrelocal X T with locality := fun {U} f w ↦ by apply continuous_iff_continuousAt.2 intro x specialize w x rcases w with ⟨V, m, i, w⟩ dsimp at w rw [continuous_iff_continuousAt] at w specialize w ⟨x, m⟩ simpa using (Opens.isOpenEmbedding_of_le i.le).continuousAt_iff.1 w } /-- Satisfying the inhabited linter. -/ instance inhabitedLocalPredicate (T) [TopologicalSpace T] : Inhabited (LocalPredicate fun _ : X ↦ T) := ⟨continuousLocal X T⟩ variable {X T} /-- The conjunction of two prelocal predicates is prelocal. -/ def PrelocalPredicate.and (P Q : PrelocalPredicate T) : PrelocalPredicate T where pred f := P.pred f ∧ Q.pred f res i f h := ⟨P.res i f h.1, Q.res i f h.2⟩ /-- The conjunction of two prelocal predicates is prelocal. -/ def LocalPredicate.and (P Q : LocalPredicate T) : LocalPredicate T where __ := P.1.and Q.1 locality f w := by refine ⟨P.locality f ?_, Q.locality f ?_⟩ <;> (intro x; have ⟨V, hV, i, h⟩ := w x; use V, hV, i) exacts [h.1, h.2] /-- The local predicate of being a partial section of a function. -/ def isSection {T} (p : T → X) : LocalPredicate fun _ : X ↦ T where pred f := p ∘ f = (↑) res _ _ h := funext fun _ ↦ congr_fun h _ locality _ w := funext fun x ↦ have ⟨_, hV, _, h⟩ := w x; congr_fun h ⟨x, hV⟩ /-- Given a `P : PrelocalPredicate`, we can always construct a `LocalPredicate` by asking that the condition from `P` holds locally near every point. -/ def PrelocalPredicate.sheafify {T : X → Type*} (P : PrelocalPredicate T) : LocalPredicate T where pred {U} f := ∀ x : U, ∃ (V : Opens X) (_ : x.1 ∈ V) (i : V ⟶ U), P.pred fun x : V ↦ f (i x : U) res {V U} i f w x := by specialize w (i x) rcases w with ⟨V', m', i', p⟩ exact ⟨V ⊓ V', ⟨x.2, m'⟩, V.infLELeft _, P.res (V.infLERight V') _ p⟩ locality {U} f w x := by specialize w x rcases w with ⟨V, m, i, p⟩ specialize p ⟨x.1, m⟩ rcases p with ⟨V', m', i', p'⟩ exact ⟨V', m', i' ≫ i, p'⟩ namespace PrelocalPredicate theorem sheafifyOf {T : X → Type*} {P : PrelocalPredicate T} {U : Opens X} {f : ∀ x : U, T x} (h : P.pred f) : P.sheafify.pred f := fun x ↦ ⟨U, x.2, 𝟙 _, by convert h⟩ /-- For a unary operation (e.g. `x ↦ -x`) defined at each stalk, if a prelocal predicate is closed under the operation on each open set (possibly by refinement), then the sheafified predicate is also closed under the operation. See `sheafify_inductionOn'` for the version without refinement. -/ theorem sheafify_inductionOn {X : TopCat} {T : X → Type*} (P : PrelocalPredicate T) (op : {x : X} → T x → T x) (hop : ∀ {U : Opens X} {a : (x : U) → T x}, P.pred a → ∀ (p : U), ∃ (W : Opens X) (i : W ⟶ U), p.1 ∈ W ∧ P.pred fun x : W ↦ op (a (i x))) {U : Opens X} {a : (x : U) → T x} (ha : P.sheafify.pred a) : P.sheafify.pred (fun x : U ↦ op (a x)) := by intro x rcases ha x with ⟨Va, ma, ia, ha⟩ rcases hop ha ⟨x, ma⟩ with ⟨W, sa, hx, hw⟩ exact ⟨W, hx, sa ≫ ia, hw⟩ /-- For a unary operation (e.g. `x ↦ -x`) defined at each stalk, if a prelocal predicate is closed under the operation on each open set, then the sheafified predicate is also closed under the operation. See `sheafify_inductionOn` for the version with refinement. -/ theorem sheafify_inductionOn' {X : TopCat} {T : X → Type*} (P : PrelocalPredicate T) (op : {x : X} → T x → T x) (hop : ∀ {U : Opens X} {a : (x : U) → T x}, P.pred a → P.pred fun x : U ↦ op (a x)) {U : Opens X} {a : (x : U) → T x} (ha : P.sheafify.pred a) : P.sheafify.pred (fun x : U ↦ op (a x)) := P.sheafify_inductionOn op (fun ha p ↦ ⟨_, 𝟙 _, p.2, hop ha⟩) ha /-- For a binary operation (e.g. `x ↦ y ↦ x + y`) defined at each stalk, if a prelocal predicate is closed under the operation on each open set (possibly by refinement), then the sheafified predicate is also closed under the operation. See `sheafify_inductionOn₂'` for the version without refinement. -/ theorem sheafify_inductionOn₂ {X : TopCat} {T₁ T₂ T₃ : X → Type*} (P₁ : PrelocalPredicate T₁) (P₂ : PrelocalPredicate T₂) (P₃ : PrelocalPredicate T₃) (op : {x : X} → T₁ x → T₂ x → T₃ x) (hop : ∀ {U V : Opens X} {a : (x : U) → T₁ x} {b : (x : V) → T₂ x}, P₁.pred a → P₂.pred b → ∀ (p : (U ⊓ V : Opens X)), ∃ (W : Opens X) (ia : W ⟶ U) (ib : W ⟶ V), p.1 ∈ W ∧ P₃.pred fun x : W ↦ op (a (ia x)) (b (ib x))) {U : Opens X} {a : (x : U) → T₁ x} {b : (x : U) → T₂ x} (ha : P₁.sheafify.pred a) (hb : P₂.sheafify.pred b) : P₃.sheafify.pred (fun x : U ↦ op (a x) (b x)) := by intro x rcases ha x with ⟨Va, ma, ia, ha⟩ rcases hb x with ⟨Vb, mb, ib, hb⟩ rcases hop ha hb ⟨x, ma, mb⟩ with ⟨W, sa, sb, hx, hw⟩ exact ⟨W, hx, sa ≫ ia, hw⟩ /-- For a binary operation (e.g. `x ↦ y ↦ x + y`) defined at each stalk, if a prelocal predicate is closed under the operation on each open set, then the sheafified predicate is also closed under the operation. See `sheafify_inductionOn₂` for the version with refinement. -/ theorem sheafify_inductionOn₂' {X : TopCat} {T₁ T₂ T₃ : X → Type*} (P₁ : PrelocalPredicate T₁) (P₂ : PrelocalPredicate T₂) (P₃ : PrelocalPredicate T₃) (op : {x : X} → T₁ x → T₂ x → T₃ x) (hop : ∀ {U V : Opens X} {a : (x : U) → T₁ x} {b : (x : V) → T₂ x}, P₁.pred a → P₂.pred b → P₃.pred fun x : (U ⊓ V : Opens X) ↦ op (a ⟨x, x.2.1⟩) (b ⟨x, x.2.2⟩)) {U : Opens X} {a : (x : U) → T₁ x} {b : (x : U) → T₂ x} (ha : P₁.sheafify.pred a) (hb : P₂.sheafify.pred b) : P₃.sheafify.pred (fun x : U ↦ op (a x) (b x)) := P₁.sheafify_inductionOn₂ P₂ P₃ op (fun ha hb p ↦ ⟨_, Opens.infLELeft _ _, Opens.infLERight _ _, p.2, hop ha hb⟩) ha hb end PrelocalPredicate /-- The subpresheaf of dependent functions on `X` satisfying the "pre-local" predicate `P`. -/ @[simps!] def subpresheafToTypes (P : PrelocalPredicate T) : Presheaf (Type _) X where obj U := { f : ∀ x : U.unop, T x // P.pred f } map {_ _} i f := ⟨fun x ↦ f.1 (i.unop x), P.res i.unop f.1 f.2⟩ namespace subpresheafToTypes variable (P : PrelocalPredicate T) /-- The natural transformation including the subpresheaf of functions satisfying a local predicate into the presheaf of all functions. -/ def subtype : subpresheafToTypes P ⟶ presheafToTypes X T where app _ f := f.1 open TopCat.Presheaf attribute [local instance] Types.instFunLike Types.instConcreteCategory in /-- The functions satisfying a local predicate satisfy the sheaf condition. -/ theorem isSheaf (P : LocalPredicate T) : (subpresheafToTypes P.toPrelocalPredicate).IsSheaf := Presheaf.isSheaf_of_isSheafUniqueGluing_types _ fun ι U sf sf_comp ↦ by -- We show the sheaf condition in terms of unique gluing. -- First we obtain a family of sections for the underlying sheaf of functions, -- by forgetting that the predicate holds let sf' (i : ι) : (presheafToTypes X T).obj (op (U i)) := (sf i).val -- Since our original family is compatible, this one is as well have sf'_comp : (presheafToTypes X T).IsCompatible U sf' := fun i j ↦ congr_arg Subtype.val (sf_comp i j) -- So, we can obtain a unique gluing obtain ⟨gl, gl_spec, gl_uniq⟩ := (sheafToTypes X T).existsUnique_gluing U sf' -- `by exact` to help Lean infer the `ConcreteCategory` instance (by exact sf'_comp) refine ⟨⟨gl, ?_⟩, ?_, ?_⟩ · -- Our first goal is to show that this chosen gluing satisfies the -- predicate. Of course, we use locality of the predicate. apply P.locality rintro ⟨x, mem⟩ -- Once we're at a particular point `x`, we can select some open set `x ∈ U i`. choose i hi using Opens.mem_iSup.mp mem -- We claim that the predicate holds in `U i` use U i, hi, Opens.leSupr U i -- This follows, since our original family `sf` satisfies the predicate convert (sf i).property using 1 exact gl_spec i -- It remains to show that the chosen lift is really a gluing for the subsheaf and -- that it is unique. Both of which follow immediately from the corresponding facts -- in the sheaf of functions without the local predicate. · exact fun i ↦ Subtype.ext (gl_spec i) · intro gl' hgl' refine Subtype.ext ?_ exact gl_uniq gl'.1 fun i ↦ congr_arg Subtype.val (hgl' i) end subpresheafToTypes /-- The subsheaf of the sheaf of all dependently typed functions satisfying the local predicate `P`. -/ @[simps] def subsheafToTypes (P : LocalPredicate T) : Sheaf (Type _) X := ⟨subpresheafToTypes P.toPrelocalPredicate, subpresheafToTypes.isSheaf P⟩ /-- There is a canonical map from the stalk to the original fiber, given by evaluating sections. -/ def stalkToFiber (P : LocalPredicate T) (x : X) : (subsheafToTypes P).presheaf.stalk x ⟶ T x := by refine colimit.desc _ { pt := T x ι := { app := fun U f ↦ ?_ naturality := ?_ } } · exact f.1 ⟨x, (unop U).2⟩ · aesop theorem stalkToFiber_germ (P : LocalPredicate T) (U : Opens X) (x : X) (hx : x ∈ U) (f) : stalkToFiber P x ((subsheafToTypes P).presheaf.germ U x hx f) = f.1 ⟨x, hx⟩ := by simp [Presheaf.germ, stalkToFiber] /-- The `stalkToFiber` map is surjective at `x` if every point in the fiber `T x` has an allowed section passing through it. -/ theorem stalkToFiber_surjective (P : LocalPredicate T) (x : X) (w : ∀ t : T x, ∃ (U : OpenNhds x) (f : ∀ y : U.1, T y) (_ : P.pred f), f ⟨x, U.2⟩ = t) : Function.Surjective (stalkToFiber P x) := fun t ↦ by rcases w t with ⟨U, f, h, rfl⟩ fconstructor · exact (subsheafToTypes P).presheaf.germ _ x U.2 ⟨f, h⟩ · exact stalkToFiber_germ P U.1 x U.2 ⟨f, h⟩ /-- The `stalkToFiber` map is injective at `x` if any two allowed sections which agree at `x` agree on some neighborhood of `x`. -/ theorem stalkToFiber_injective (P : LocalPredicate T) (x : X) (w : ∀ (U V : OpenNhds x) (fU : ∀ y : U.1, T y) (_ : P.pred fU) (fV : ∀ y : V.1, T y) (_ : P.pred fV) (_ : fU ⟨x, U.2⟩ = fV ⟨x, V.2⟩), ∃ (W : OpenNhds x) (iU : W ⟶ U) (iV : W ⟶ V), ∀ w : W.1, fU (iU w : U.1) = fV (iV w : V.1)) : Function.Injective (stalkToFiber P x) := fun tU tV h ↦ by -- We promise to provide all the ingredients of the proof later: let Q : ∃ (W : (OpenNhds x)ᵒᵖ) (s : ∀ w : (unop W).1, T w) (hW : P.pred s), tU = (subsheafToTypes P).presheaf.germ _ x (unop W).2 ⟨s, hW⟩ ∧ tV = (subsheafToTypes P).presheaf.germ _ x (unop W).2 ⟨s, hW⟩ := ?_ · choose W s hW e using Q exact e.1.trans e.2.symm -- Then use induction to pick particular representatives of `tU tV : stalk x` obtain ⟨U, ⟨fU, hU⟩, rfl⟩ := jointly_surjective' tU obtain ⟨V, ⟨fV, hV⟩, rfl⟩ := jointly_surjective' tV -- Decompose everything into its constituent parts: dsimp simp only [stalkToFiber, Types.Colimit.ι_desc_apply] at h specialize w (unop U) (unop V) fU hU fV hV h rcases w with ⟨W, iU, iV, w⟩ -- and put it back together again in the correct order. refine ⟨op W, fun w ↦ fU (iU w : (unop U).1), P.res ?_ _ hU, ?_⟩ · rcases W with ⟨W, m⟩ exact iU · exact ⟨colimit_sound iU.op (Subtype.eq rfl), colimit_sound iV.op (Subtype.eq (funext w).symm)⟩ universe u /-- Some repackaging: the presheaf of functions satisfying `continuousPrelocal` is just the same thing as the presheaf of continuous functions. -/ def subpresheafContinuousPrelocalIsoPresheafToTop {X : TopCat.{u}} (T : TopCat.{u}) : subpresheafToTypes (continuousPrelocal X T) ≅ presheafToTop X T := NatIso.ofComponents fun X ↦ { hom := by rintro ⟨f, c⟩; exact ofHom ⟨f, c⟩ inv := by rintro ⟨f, c⟩; exact ⟨f, c⟩ } /-- The sheaf of continuous functions on `X` with values in a space `T`. -/ def sheafToTop (T : TopCat) : Sheaf (Type _) X := ⟨presheafToTop X T, Presheaf.isSheaf_of_iso (subpresheafContinuousPrelocalIsoPresheafToTop T) (subpresheafToTypes.isSheaf (continuousLocal X T))⟩ end TopCat
.lake/packages/mathlib/Mathlib/Topology/Sheaves/PresheafOfFunctions.lean
import Mathlib.Topology.Sheaves.Presheaf /-! # Presheaves of functions We construct some simple examples of presheaves of functions on a topological space. * `presheafToTypes X T`, where `T : X → Type`, is the presheaf of dependently-typed (not-necessarily continuous) functions * `presheafToType X T`, where `T : Type`, is the presheaf of (not-necessarily-continuous) functions to a fixed target type `T` * `presheafToTop X T`, where `T : TopCat`, is the presheaf of continuous functions into a topological space `T` * `presheafToTopCommRing X R`, where `R : TopCommRingCat` is the presheaf valued in `CommRing` of functions into a topological ring `R` * as an example of the previous construction, `presheafToTopCommRing X (TopCommRingCat.of ℂ)` is the presheaf of rings of continuous complex-valued functions on `X`. -/ open CategoryTheory TopologicalSpace Opposite namespace TopCat variable (X : TopCat) /-- The presheaf of dependently typed functions on `X`, with fibres given by a type family `T`. There is no requirement that the functions are continuous, here. -/ def presheafToTypes (T : X → Type*) : X.Presheaf (Type _) where obj U := ∀ x : U.unop, T x map {_ V} i g := fun x : V.unop => g (i.unop x) map_id U := by ext g rfl map_comp {_ _ _} _ _ := rfl @[simp] theorem presheafToTypes_obj {T : X → Type*} {U : (Opens X)ᵒᵖ} : (presheafToTypes X T).obj U = ∀ x : U.unop, T x := rfl @[simp] theorem presheafToTypes_map {T : X → Type*} {U V : (Opens X)ᵒᵖ} {i : U ⟶ V} {f} : (presheafToTypes X T).map i f = fun x => f (i.unop x) := rfl -- We don't just define this in terms of `presheafToTypes`, -- as it's helpful later to see (at a syntactic level) that `(presheafToType X T).obj U` -- is a non-dependent function. -- We don't use `@[simps]` to generate the projection lemmas here, -- as it turns out to be useful to have `presheafToType_map` -- written as an equality of functions (rather than being applied to some argument). /-- The presheaf of functions on `X` with values in a type `T`. There is no requirement that the functions are continuous, here. -/ def presheafToType (T : Type*) : X.Presheaf (Type _) where obj U := U.unop → T map {_ _} i g := g ∘ i.unop map_id U := by ext g rfl map_comp {_ _ _} _ _ := rfl @[simp] theorem presheafToType_obj {T : Type*} {U : (Opens X)ᵒᵖ} : (presheafToType X T).obj U = (U.unop → T) := rfl @[simp] theorem presheafToType_map {T : Type*} {U V : (Opens X)ᵒᵖ} {i : U ⟶ V} {f} : (presheafToType X T).map i f = f ∘ i.unop := rfl /-- The presheaf of continuous functions on `X` with values in fixed target topological space `T`. -/ def presheafToTop (T : TopCat) : X.Presheaf (Type _) := (Opens.toTopCat X).op ⋙ yoneda.obj T @[simp] theorem presheafToTop_obj (T : TopCat) (U : (Opens X)ᵒᵖ) : (presheafToTop X T).obj U = ((Opens.toTopCat X).obj (unop U) ⟶ T) := rfl end TopCat
.lake/packages/mathlib/Mathlib/Topology/Sheaves/Sheaf.lean
import Mathlib.Topology.Sheaves.Presheaf import Mathlib.CategoryTheory.Sites.Sheaf import Mathlib.CategoryTheory.Sites.Spaces /-! # Sheaves We define sheaves on a topological space, with values in an arbitrary category. A presheaf on a topological space `X` is a sheaf precisely when it is a sheaf under the Grothendieck topology on `opens X`, which expands out to say: For each open cover `{ Uᵢ }` of `U`, and a family of compatible functions `A ⟶ F(Uᵢ)` for an `A : X`, there exists a unique gluing `A ⟶ F(U)` compatible with the restriction. See the docstring of `TopCat.Presheaf.IsSheaf` for an explanation on the design decisions and a list of equivalent conditions. We provide the instance `CategoryTheory.Category (TopCat.Sheaf C X)` as the full subcategory of presheaves, and the fully faithful functor `Sheaf.forget : TopCat.Sheaf C X ⥤ TopCat.Presheaf C X`. -/ universe w v u noncomputable section open CategoryTheory CategoryTheory.Limits TopologicalSpace Opposite TopologicalSpace.Opens namespace TopCat variable {C : Type u} [Category.{v} C] variable {X : TopCat.{w}} (F : Presheaf C X) {ι : Type v} (U : ι → Opens X) namespace Presheaf /-- The sheaf condition has several different equivalent formulations. The official definition chosen here is in terms of Grothendieck topologies so that the results on sites could be applied here easily, and this condition does not require additional constraints on the value category. The equivalent formulations of the sheaf condition on `presheaf C X` are as follows : 1. `TopCat.Presheaf.IsSheaf`: (the official definition) It is a sheaf with respect to the Grothendieck topology on `opens X`, which is to say: For each open cover `{ Uᵢ }` of `U`, and a family of compatible functions `A ⟶ F(Uᵢ)` for an `A : X`, there exists a unique gluing `A ⟶ F(U)` compatible with the restriction. 2. `TopCat.Presheaf.IsSheafEqualizerProducts`: (requires `C` to have all products) For each open cover `{ Uᵢ }` of `U`, `F(U) ⟶ ∏ᶜ F(Uᵢ)` is the equalizer of the two morphisms `∏ᶜ F(Uᵢ) ⟶ ∏ᶜ F(Uᵢ ∩ Uⱼ)`. See `TopCat.Presheaf.isSheaf_iff_isSheafEqualizerProducts`. 3. `TopCat.Presheaf.IsSheafOpensLeCover`: For each open cover `{ Uᵢ }` of `U`, `F(U)` is the limit of the diagram consisting of arrows `F(V₁) ⟶ F(V₂)` for every pair of open sets `V₁ ⊇ V₂` that are contained in some `Uᵢ`. See `TopCat.Presheaf.isSheaf_iff_isSheafOpensLeCover`. 4. `TopCat.Presheaf.IsSheafPairwiseIntersections`: For each open cover `{ Uᵢ }` of `U`, `F(U)` is the limit of the diagram consisting of arrows from `F(Uᵢ)` and `F(Uⱼ)` to `F(Uᵢ ∩ Uⱼ)` for each pair `(i, j)`. See `TopCat.Presheaf.isSheaf_iff_isSheafPairwiseIntersections`. The following requires `C` to be concrete and complete, and `forget C` to reflect isomorphisms and preserve limits. This applies to most "algebraic" categories, e.g. groups, abelian groups and rings. 5. `TopCat.Presheaf.IsSheafUniqueGluing`: (requires `C` to be concrete and complete; `forget C` to reflect isomorphisms and preserve limits) For each open cover `{ Uᵢ }` of `U`, and a compatible family of elements `x : F(Uᵢ)`, there exists a unique gluing `x : F(U)` that restricts to the given elements. See `TopCat.Presheaf.isSheaf_iff_isSheafUniqueGluing`. 6. The underlying sheaf of types is a sheaf. See `TopCat.Presheaf.isSheaf_iff_isSheaf_comp` and `CategoryTheory.Presheaf.isSheaf_iff_isSheaf_forget`. -/ nonrec def IsSheaf (F : Presheaf.{w, v, u} C X) : Prop := Presheaf.IsSheaf (Opens.grothendieckTopology X) F /-- The presheaf valued in `Unit` over any topological space is a sheaf. -/ theorem isSheaf_unit (F : Presheaf (CategoryTheory.Discrete Unit) X) : F.IsSheaf := fun x U S _ x _ => ⟨eqToHom (Subsingleton.elim _ _), by cat_disch, fun _ => by cat_disch⟩ theorem isSheaf_iso_iff {F G : Presheaf C X} (α : F ≅ G) : F.IsSheaf ↔ G.IsSheaf := Presheaf.isSheaf_of_iso_iff α /-- Transfer the sheaf condition across an isomorphism of presheaves. -/ theorem isSheaf_of_iso {F G : Presheaf C X} (α : F ≅ G) (h : F.IsSheaf) : G.IsSheaf := (isSheaf_iso_iff α).1 h end Presheaf variable (C X) /-- A `TopCat.Sheaf C X` is a presheaf of objects from `C` over a (bundled) topological space `X`, satisfying the sheaf condition. -/ nonrec def Sheaf : Type max u v w := Sheaf (Opens.grothendieckTopology X) C deriving Category variable {C X} /-- The underlying presheaf of a sheaf -/ abbrev Sheaf.presheaf (F : X.Sheaf C) : TopCat.Presheaf C X := F.1 variable (C X) -- Let's construct a trivial example, to keep the inhabited linter happy. instance sheafInhabited : Inhabited (Sheaf (CategoryTheory.Discrete PUnit) X) := ⟨⟨Functor.star _, Presheaf.isSheaf_unit _⟩⟩ namespace Sheaf /-- The forgetful functor from sheaves to presheaves. -/ def forget : TopCat.Sheaf C X ⥤ TopCat.Presheaf C X := sheafToPresheaf _ _ -- The following instances should be constructed by a deriving handler. -- https://github.com/leanprover-community/mathlib4/issues/380 instance forget_full : (forget C X).Full where map_surjective f := ⟨Sheaf.Hom.mk f, rfl⟩ instance forgetFaithful : (forget C X).Faithful where map_injective := Sheaf.Hom.ext -- Note: These can be proved by simp. theorem id_app (F : Sheaf C X) (t) : (𝟙 F : F ⟶ F).1.app t = 𝟙 _ := rfl theorem comp_app {F G H : Sheaf C X} (f : F ⟶ G) (g : G ⟶ H) (t) : (f ≫ g).1.app t = f.1.app t ≫ g.1.app t := rfl end Sheaf lemma Presheaf.IsSheaf.section_ext {X : TopCat.{u}} {A : Type*} [Category.{u} A] {FC : A → A → Type*} {CC : A → Type u} [∀ X Y : A, FunLike (FC X Y) (CC X) (CC Y)] [ConcreteCategory.{u} A FC] [HasLimits A] [PreservesLimits (forget A)] [(forget A).ReflectsIsomorphisms] {F : TopCat.Presheaf A X} (hF : TopCat.Presheaf.IsSheaf F) {U : (Opens X)ᵒᵖ} {s t : ToType (F.obj U)} (hst : ∀ x ∈ U.unop, ∃ V, ∃ hV : V ≤ U.unop, x ∈ V ∧ F.map (homOfLE hV).op s = F.map (homOfLE hV).op t) : s = t := by have := (isSheaf_iff_isSheaf_of_type _ _).mp ((Presheaf.isSheaf_iff_isSheaf_forget (C := Opens X) (A' := A) _ F (forget _)).mp hF) choose V hV hxV H using fun x : U.unop ↦ hst x.1 x.2 refine (this.isSheafFor _ (.ofArrows V fun x ↦ homOfLE (hV x)) ?_).isSeparatedFor.ext ?_ · exact fun x hx ↦ ⟨V ⟨x, hx⟩, homOfLE (hV _), Sieve.le_generate _ _ (.mk _), hxV _⟩ · rintro _ _ ⟨x⟩; exact H x end TopCat
.lake/packages/mathlib/Mathlib/Topology/Sheaves/Limits.lean
import Mathlib.Topology.Sheaves.Sheaf import Mathlib.CategoryTheory.Sites.Limits import Mathlib.CategoryTheory.Limits.FunctorCategory.Basic /-! # Presheaves in `C` have limits and colimits when `C` does. -/ noncomputable section universe v u w t open CategoryTheory open CategoryTheory.Limits variable {C : Type u} [Category.{v} C] {J : Type w} [Category J] namespace TopCat instance [HasLimitsOfShape J C] (X : TopCat.{t}) : HasLimitsOfShape J (Presheaf C X) := functorCategoryHasLimitsOfShape instance [HasLimits C] (X : TopCat.{v}) : HasLimits.{v} (Presheaf C X) where instance [HasColimitsOfShape J C] (X : TopCat) : HasColimitsOfShape J (Presheaf C X) := functorCategoryHasColimitsOfShape instance [HasColimits.{v, u} C] (X : TopCat.{t}) : HasColimitsOfSize.{v, v} (Presheaf C X) where instance [HasLimitsOfShape J C] (X : TopCat.{t}) : CreatesLimitsOfShape J (Sheaf.forget C X) := Sheaf.createsLimitsOfShape instance [HasLimitsOfShape J C] (X : TopCat.{t}) : HasLimitsOfShape J (Sheaf C X) := hasLimitsOfShape_of_hasLimitsOfShape_createsLimitsOfShape (Sheaf.forget C X) instance [HasLimits C] (X : TopCat) : CreatesLimits.{v, v} (Sheaf.forget C X) where instance [HasLimits C] (X : TopCat.{v}) : HasLimitsOfSize.{v, v} (Sheaf.{v} C X) where theorem isSheaf_of_isLimit [HasLimitsOfShape J C] {X : TopCat} (F : J ⥤ Presheaf.{v} C X) (H : ∀ j, (F.obj j).IsSheaf) {c : Cone F} (hc : IsLimit c) : c.pt.IsSheaf := by let F' : J ⥤ Sheaf C X := { obj := fun j => ⟨F.obj j, H j⟩ map := fun f => ⟨F.map f⟩ } let e : F' ⋙ Sheaf.forget C X ≅ F := NatIso.ofComponents fun _ => Iso.refl _ exact Presheaf.isSheaf_of_iso ((isLimitOfPreserves (Sheaf.forget C X) (limit.isLimit F')).conePointsIsoOfNatIso hc e) (limit F').2 theorem limit_isSheaf [HasLimitsOfShape J C] {X : TopCat} (F : J ⥤ Presheaf.{v} C X) (H : ∀ j, (F.obj j).IsSheaf) : (limit F).IsSheaf := isSheaf_of_isLimit F H (limit.isLimit F) end TopCat
.lake/packages/mathlib/Mathlib/Topology/Sheaves/MayerVietoris.lean
import Mathlib.CategoryTheory.Sites.MayerVietorisSquare import Mathlib.CategoryTheory.Sites.Spaces import Mathlib.CategoryTheory.Functor.ReflectsIso.Balanced /-! # Mayer-Vietoris squares Given two open subsets `U` and `V` of a topological space `T`, we construct the associated Mayer-Vietoris square: ``` U ⊓ V ---> U | | v v V ---> U ⊔ V ``` -/ universe u namespace Opens open CategoryTheory Limits TopologicalSpace variable {T : Type u} [TopologicalSpace T] attribute [local instance] Types.instFunLike Types.instConcreteCategory /-- A square consisting of opens `X₂ ⊓ X₃`, `X₂`, `X₃` and `X₂ ⊔ X₃` is a Mayer-Vietoris square. -/ @[simps! toSquare] noncomputable def mayerVietorisSquare' (sq : Square (Opens T)) (h₄ : sq.X₄ = sq.X₂ ⊔ sq.X₃) (h₁ : sq.X₁ = sq.X₂ ⊓ sq.X₃) : (Opens.grothendieckTopology T).MayerVietorisSquare := GrothendieckTopology.MayerVietorisSquare.mk_of_isPullback (J := (Opens.grothendieckTopology T)) sq (Square.IsPullback.mk _ (by refine PullbackCone.IsLimit.mk _ ?_ ?_ ?_ ?_ · intro s apply homOfLE rw [h₁, le_inf_iff] exact ⟨leOfHom s.fst, leOfHom s.snd⟩ all_goals intros; apply Subsingleton.elim)) (fun x hx ↦ by rw [h₄] at hx obtain (hx | hx) := hx · exact ⟨_, _, ⟨Sieve.ofArrows_mk _ _ WalkingPair.left, hx⟩⟩ · exact ⟨_, _, ⟨Sieve.ofArrows_mk _ _ WalkingPair.right, hx⟩⟩) /-- The Mayer-Vietoris square attached to two open subsets of a topological space. -/ @[simps!] noncomputable def mayerVietorisSquare (U V : Opens T) : (Opens.grothendieckTopology T).MayerVietorisSquare := mayerVietorisSquare' { X₁ := U ⊓ V X₂ := U X₃ := V X₄ := U ⊔ V f₁₂ := homOfLE inf_le_left f₁₃ := homOfLE inf_le_right f₂₄ := homOfLE le_sup_left f₃₄ := homOfLE le_sup_right fac := Subsingleton.elim _ _ } rfl rfl end Opens
.lake/packages/mathlib/Mathlib/Topology/Sheaves/SheafCondition/OpensLeCover.lean
import Mathlib.Topology.Sheaves.SheafCondition.Sites /-! # Another version of the sheaf condition. Given a family of open sets `U : ι → Opens X` we can form the subcategory `{ V : Opens X // ∃ i, V ≤ U i }`, which has `iSup U` as a cocone. The sheaf condition on a presheaf `F` is equivalent to `F` sending the opposite of this cocone to a limit cone in `C`, for every `U`. This condition is particularly nice when checking the sheaf condition because we don't need to do any case bashing (depending on whether we're looking at single or double intersections, or equivalently whether we're looking at the first or second object in an equalizer diagram). ## Main statement `TopCat.Presheaf.isSheaf_iff_isSheafOpensLeCover`: for a presheaf on a topological space, the sheaf condition in terms of Grothendieck topology is equivalent to the `OpensLeCover` sheaf condition. This result will be used to further connect to other sheaf conditions on spaces, like `pairwise_intersections` and `equalizer_products`. ## References * This is the definition Lurie uses in [Spectral Algebraic Geometry][LurieSAG]. -/ universe w noncomputable section open CategoryTheory CategoryTheory.Limits TopologicalSpace TopologicalSpace.Opens Opposite namespace TopCat variable {C : Type*} [Category C] variable {X : TopCat.{w}} (F : Presheaf C X) {ι : Type*} (U : ι → Opens X) namespace Presheaf namespace SheafCondition /-- The category of open sets contained in some element of the cover. -/ def OpensLeCover : Type w := ObjectProperty.FullSubcategory fun V : Opens X ↦ ∃ i, V ≤ U i deriving Category instance [h : Nonempty ι] : Inhabited (OpensLeCover U) := ⟨⟨⊥, let ⟨i⟩ := h; ⟨i, bot_le⟩⟩⟩ namespace OpensLeCover variable {U} /-- An arbitrarily chosen index such that `V ≤ U i`. -/ def index (V : OpensLeCover U) : ι := V.property.choose /-- The morphism from `V` to `U i` for some `i`. -/ def homToIndex (V : OpensLeCover U) : V.obj ⟶ U (index V) := V.property.choose_spec.hom end OpensLeCover /-- `iSup U` as a cocone over the opens sets contained in some element of the cover. (In fact this is a colimit cocone.) -/ def opensLeCoverCocone : Cocone (ObjectProperty.ι _ : OpensLeCover U ⥤ Opens X) where pt := iSup U ι := { app := fun V : OpensLeCover U => V.homToIndex ≫ Opens.leSupr U _ } end SheafCondition open SheafCondition /-- An equivalent formulation of the sheaf condition (which we prove equivalent to the usual one below as `isSheaf_iff_isSheafOpensLeCover`). A presheaf is a sheaf if `F` sends the cone `(opensLeCoverCocone U).op` to a limit cone. (Recall `opensLeCoverCocone U`, has cone point `iSup U`, mapping down to any `V` which is contained in some `U i`.) -/ def IsSheafOpensLeCover : Prop := ∀ ⦃ι : Type w⦄ (U : ι → Opens X), Nonempty (IsLimit (F.mapCone (opensLeCoverCocone U).op)) section variable {Y : Opens X} /-- Given a family of opens `U` and an open `Y` equal to the union of opens in `U`, we may take the presieve on `Y` associated to `U` and the sieve generated by it, and form the full subcategory (subposet) of opens contained in `Y` (`over Y`) consisting of arrows in the sieve. This full subcategory is equivalent to `OpensLeCover U`, the (poset) category of opens contained in some `U i`. -/ @[simps] def generateEquivalenceOpensLe_functor' : (ObjectProperty.FullSubcategory fun f : Over Y => (Sieve.generate (presieveOfCoveringAux U Y)).arrows f.hom) ⥤ OpensLeCover U := { obj := fun f => ⟨f.1.left, let ⟨_, h, _, ⟨i, hY⟩, _⟩ := f.2 ⟨i, hY ▸ h.le⟩⟩ map := fun {_ _} g => g.left } /-- Given a family of opens `U` and an open `Y` equal to the union of opens in `U`, we may take the presieve on `Y` associated to `U` and the sieve generated by it, and form the full subcategory (subposet) of opens contained in `Y` (`over Y`) consisting of arrows in the sieve. This full subcategory is equivalent to `OpensLeCover U`, the (poset) category of opens contained in some `U i`. -/ @[simps] def generateEquivalenceOpensLe_inverse' (hY : Y = iSup U) : OpensLeCover U ⥤ (ObjectProperty.FullSubcategory fun f : Over Y => (Sieve.generate (presieveOfCoveringAux U Y)).arrows f.hom) where obj := fun V => ⟨⟨V.obj, ⟨⟨⟩⟩, homOfLE <| hY ▸ (V.2.choose_spec.trans (le_iSup U (V.2.choose)))⟩, ⟨U V.2.choose, V.2.choose_spec.hom, homOfLE <| hY ▸ le_iSup U V.2.choose, ⟨V.2.choose, rfl⟩, rfl⟩⟩ map {_ _} g := Over.homMk g map_id _ := by refine Over.OverMorphism.ext ?_ simp only [Functor.id_obj, Sieve.generate_apply, Functor.const_obj_obj, Over.homMk_left, eq_iff_true_of_subsingleton] map_comp {_ _ _} f g := by refine Over.OverMorphism.ext ?_ simp only [Functor.id_obj, Sieve.generate_apply, Functor.const_obj_obj, Over.homMk_left, eq_iff_true_of_subsingleton] /-- Given a family of opens `U` and an open `Y` equal to the union of opens in `U`, we may take the presieve on `Y` associated to `U` and the sieve generated by it, and form the full subcategory (subposet) of opens contained in `Y` (`over Y`) consisting of arrows in the sieve. This full subcategory is equivalent to `OpensLeCover U`, the (poset) category of opens contained in some `U i`. -/ @[simps] def generateEquivalenceOpensLe (hY : Y = iSup U) : (ObjectProperty.FullSubcategory fun f : Over Y => (Sieve.generate (presieveOfCoveringAux U Y)).arrows f.hom) ≌ OpensLeCover U where functor := generateEquivalenceOpensLe_functor' _ inverse := generateEquivalenceOpensLe_inverse' _ hY unitIso := eqToIso <| CategoryTheory.Functor.ext (by rintro ⟨⟨_, _⟩, _⟩; dsimp; congr) (by intros; refine Over.OverMorphism.ext ?_; simp) counitIso := eqToIso <| CategoryTheory.Functor.hext (by intro; refine ObjectProperty.FullSubcategory.ext ?_; rfl) (by intros; rfl) /-- Given a family of opens `opensLeCoverCocone U` is essentially the natural cocone associated to the sieve generated by the presieve associated to `U` with indexing category changed using the above equivalence. -/ @[simps] def whiskerIsoMapGenerateCocone (hY : Y = iSup U) : (F.mapCone (opensLeCoverCocone U).op).whisker (generateEquivalenceOpensLe U hY).op.functor ≅ F.mapCone (Sieve.generate (presieveOfCoveringAux U Y)).arrows.cocone.op where hom := { hom := F.map (eqToHom (congr_arg op hY.symm)) w := fun j => by erw [← F.map_comp] dsimp congr 1 } inv := { hom := F.map (eqToHom (congr_arg op hY)) w := fun j => by erw [← F.map_comp] dsimp congr 1 } hom_inv_id := by ext simp [eqToHom_map] inv_hom_id := by ext simp [eqToHom_map] /-- Given a presheaf `F` on the topological space `X` and a family of opens `U` of `X`, the natural cone associated to `F` and `U` used in the definition of `F.IsSheafOpensLeCover` is a limit cone iff the natural cone associated to `F` and the sieve generated by the presieve associated to `U` is a limit cone. -/ def isLimitOpensLeEquivGenerate₁ (hY : Y = iSup U) : IsLimit (F.mapCone (opensLeCoverCocone U).op) ≃ IsLimit (F.mapCone (Sieve.generate (presieveOfCoveringAux U Y)).arrows.cocone.op) := (IsLimit.whiskerEquivalenceEquiv (generateEquivalenceOpensLe U hY).op).trans (IsLimit.equivIsoLimit (whiskerIsoMapGenerateCocone F U hY)) /-- Given a presheaf `F` on the topological space `X` and a presieve `R` whose generated sieve is covering for the associated Grothendieck topology (equivalently, the presieve is covering for the associated pretopology), the natural cone associated to `F` and the family of opens associated to `R` is a limit cone iff the natural cone associated to `F` and the generated sieve is a limit cone. Since only the existence of a 1-1 correspondence will be used, the exact definition does not matter, so tactics are used liberally. -/ def isLimitOpensLeEquivGenerate₂ (R : Presieve Y) (hR : Sieve.generate R ∈ Opens.grothendieckTopology X Y) : IsLimit (F.mapCone (opensLeCoverCocone (coveringOfPresieve Y R)).op) ≃ IsLimit (F.mapCone (Sieve.generate R).arrows.cocone.op) := by convert isLimitOpensLeEquivGenerate₁ F (coveringOfPresieve Y R) (coveringOfPresieve.iSup_eq_of_mem_grothendieck Y R hR).symm using 1 rw [covering_presieve_eq_self R] variable {F} in theorem IsSheaf.isSheafOpensLeCover (h : F.IsSheaf) : Nonempty (IsLimit (F.mapCone (opensLeCoverCocone U).op)) := by rw [(isLimitOpensLeEquivGenerate₁ F U rfl).nonempty_congr] apply (Presheaf.isSheaf_iff_isLimit _ _).mp h apply presieveOfCovering.mem_grothendieckTopology /-- A presheaf `(opens X)ᵒᵖ ⥤ C` on a topological space `X` is a sheaf on the site `opens X` iff it satisfies the `IsSheafOpensLeCover` sheaf condition. The latter is not the official definition of sheaves on spaces, but has the advantage that it does not require `has_products C`. -/ theorem isSheaf_iff_isSheafOpensLeCover : F.IsSheaf ↔ F.IsSheafOpensLeCover := by refine ⟨fun h _ ↦ h.isSheafOpensLeCover, fun h ↦ (Presheaf.isSheaf_iff_isLimit _ _).mpr fun Y S ↦ ?_⟩ rw [← Sieve.generate_sieve S] intro hS rw [← (isLimitOpensLeEquivGenerate₂ F S.1 hS).nonempty_congr] apply h end end Presheaf end TopCat
.lake/packages/mathlib/Mathlib/Topology/Sheaves/SheafCondition/PairwiseIntersections.lean
import Mathlib.CategoryTheory.Category.Pairwise import Mathlib.CategoryTheory.Limits.Constructions.BinaryProducts import Mathlib.CategoryTheory.Limits.Final import Mathlib.CategoryTheory.Limits.Preserves.Basic import Mathlib.Topology.Sheaves.SheafCondition.OpensLeCover /-! # Equivalent formulations of the sheaf condition We give an equivalent formulation of the sheaf condition. Given any indexed type `ι`, we define `overlap ι`, a category with objects corresponding to * individual open sets, `single i`, and * intersections of pairs of open sets, `pair i j`, with morphisms from `pair i j` to both `single i` and `single j`. Any open cover `U : ι → Opens X` provides a functor `diagram U : overlap ι ⥤ (Opens X)ᵒᵖ`. There is a canonical cone over this functor, `cone U`, whose cone point is `isup U`, and in fact this is a limit cone. A presheaf `F : Presheaf C X` is a sheaf precisely if it preserves this limit. We express this in two equivalent ways, as * `isLimit (F.mapCone (cone U))`, or * `preservesLimit (diagram U) F` We show that this sheaf condition is equivalent to the `OpensLeCover` sheaf condition, and thereby also equivalent to the default sheaf condition. -/ assert_not_exists IsOrderedMonoid noncomputable section universe w open TopologicalSpace TopCat Opposite CategoryTheory CategoryTheory.Limits variable {C : Type*} [Category C] {X : TopCat.{w}} namespace TopCat.Presheaf section /-- An alternative formulation of the sheaf condition (which we prove equivalent to the usual one below as `isSheaf_iff_isSheafPairwiseIntersections`). A presheaf is a sheaf if `F` sends the cone `(Pairwise.cocone U).op` to a limit cone. (Recall `Pairwise.cocone U` has cone point `iSup U`, mapping down to the `U i` and the `U i ⊓ U j`.) -/ def IsSheafPairwiseIntersections (F : Presheaf C X) : Prop := ∀ ⦃ι : Type w⦄ (U : ι → Opens X), Nonempty (IsLimit (F.mapCone (Pairwise.cocone U).op)) /-- An alternative formulation of the sheaf condition (which we prove equivalent to the usual one below as `isSheaf_iff_isSheafPreservesLimitPairwiseIntersections`). A presheaf is a sheaf if `F` preserves the limit of `Pairwise.diagram U`. (Recall `Pairwise.diagram U` is the diagram consisting of the pairwise intersections `U i ⊓ U j` mapping into the open sets `U i`. This diagram has limit `iSup U`.) -/ def IsSheafPreservesLimitPairwiseIntersections (F : Presheaf C X) : Prop := ∀ ⦃ι : Type w⦄ (U : ι → Opens X), PreservesLimit (Pairwise.diagram U).op F end namespace SheafCondition variable {ι : Type*} (U : ι → Opens X) open CategoryTheory.Pairwise /-- Implementation detail: the object level of `pairwiseToOpensLeCover : Pairwise ι ⥤ OpensLeCover U` -/ @[simp] def pairwiseToOpensLeCoverObj : Pairwise ι → OpensLeCover U | single i => ⟨U i, ⟨i, le_rfl⟩⟩ | Pairwise.pair i j => ⟨U i ⊓ U j, ⟨i, inf_le_left⟩⟩ open CategoryTheory.Pairwise.Hom /-- Implementation detail: the morphism level of `pairwiseToOpensLeCover : Pairwise ι ⥤ OpensLeCover U` -/ def pairwiseToOpensLeCoverMap : ∀ {V W : Pairwise ι}, (V ⟶ W) → (pairwiseToOpensLeCoverObj U V ⟶ pairwiseToOpensLeCoverObj U W) | _, _, id_single _ => 𝟙 _ | _, _, id_pair _ _ => 𝟙 _ | _, _, left _ _ => homOfLE inf_le_left | _, _, right _ _ => homOfLE inf_le_right /-- The category of single and double intersections of the `U i` maps into the category of open sets below some `U i`. -/ @[simps] def pairwiseToOpensLeCover : Pairwise ι ⥤ OpensLeCover U where obj := pairwiseToOpensLeCoverObj U map {_ _} i := pairwiseToOpensLeCoverMap U i instance (V : OpensLeCover U) : Nonempty (StructuredArrow V (pairwiseToOpensLeCover U)) := ⟨@StructuredArrow.mk _ _ _ _ _ (single V.index) _ V.homToIndex⟩ -- This is a case bash: for each pair of types of objects in `Pairwise ι`, -- we have to explicitly construct a zigzag. /-- The diagram consisting of the `U i` and `U i ⊓ U j` is cofinal in the diagram of all opens contained in some `U i`. -/ instance : Functor.Final (pairwiseToOpensLeCover U) := ⟨fun V => isConnected_of_zigzag fun A B => by rcases A with ⟨⟨⟨⟩⟩, ⟨i⟩ | ⟨i, j⟩, a⟩ <;> rcases B with ⟨⟨⟨⟩⟩, ⟨i'⟩ | ⟨i', j'⟩, b⟩ · refine ⟨[{ left := ⟨⟨⟩⟩ right := pair i i' hom := (le_inf a.le b.le).hom }, _], ?_, rfl⟩ exact List.IsChain.cons_cons (Or.inr ⟨{ left := 𝟙 _ right := left i i' }⟩) (List.IsChain.cons_cons (Or.inl ⟨{ left := 𝟙 _ right := right i i' }⟩) (List.IsChain.singleton _)) · refine ⟨[{ left := ⟨⟨⟩⟩ right := pair i' i hom := (le_inf (b.le.trans inf_le_left) a.le).hom }, { left := ⟨⟨⟩⟩ right := single i' hom := (b.le.trans inf_le_left).hom }, _], ?_, rfl⟩ exact List.IsChain.cons_cons (Or.inr ⟨{ left := 𝟙 _ right := right i' i }⟩) (List.IsChain.cons_cons (Or.inl ⟨{ left := 𝟙 _ right := left i' i }⟩) (List.IsChain.cons_cons (Or.inr ⟨{ left := 𝟙 _ right := left i' j' }⟩) (List.IsChain.singleton _))) · refine ⟨[{ left := ⟨⟨⟩⟩ right := single i hom := (a.le.trans inf_le_left).hom }, { left := ⟨⟨⟩⟩ right := pair i i' hom := (le_inf (a.le.trans inf_le_left) b.le).hom }, _], ?_, rfl⟩ exact List.IsChain.cons_cons (Or.inl ⟨{ left := 𝟙 _ right := left i j }⟩) (List.IsChain.cons_cons (Or.inr ⟨{ left := 𝟙 _ right := left i i' }⟩) (List.IsChain.cons_cons (Or.inl ⟨{ left := 𝟙 _ right := right i i' }⟩) (List.IsChain.singleton _))) · refine ⟨[{ left := ⟨⟨⟩⟩ right := single i hom := (a.le.trans inf_le_left).hom }, { left := ⟨⟨⟩⟩ right := pair i i' hom := (le_inf (a.le.trans inf_le_left) (b.le.trans inf_le_left)).hom }, { left := ⟨⟨⟩⟩ right := single i' hom := (b.le.trans inf_le_left).hom }, _], ?_, rfl⟩ exact List.IsChain.cons_cons (Or.inl ⟨{ left := 𝟙 _ right := left i j }⟩) (List.IsChain.cons_cons (Or.inr ⟨{ left := 𝟙 _ right := left i i' }⟩) (List.IsChain.cons_cons (Or.inl ⟨{ left := 𝟙 _ right := right i i' }⟩) (List.IsChain.cons_cons (Or.inr ⟨{ left := 𝟙 _ right := left i' j' }⟩) (List.IsChain.singleton _))))⟩ /-- The diagram in `Opens X` indexed by pairwise intersections from `U` is isomorphic (in fact, equal) to the diagram factored through `OpensLeCover U`. -/ def pairwiseDiagramIso : Pairwise.diagram U ≅ pairwiseToOpensLeCover U ⋙ ObjectProperty.ι _ where hom := { app := by rintro (i | ⟨i, j⟩) <;> exact 𝟙 _ } inv := { app := by rintro (i | ⟨i, j⟩) <;> exact 𝟙 _ } /-- The cocone `Pairwise.cocone U` with cocone point `iSup U` over `Pairwise.diagram U` is isomorphic to the cocone `opensLeCoverCocone U` (with the same cocone point) after appropriate whiskering and postcomposition. -/ def pairwiseCoconeIso : (Pairwise.cocone U).op ≅ (Cones.postcomposeEquivalence (NatIso.op (pairwiseDiagramIso U :) :)).functor.obj ((opensLeCoverCocone U).op.whisker (pairwiseToOpensLeCover U).op) := Cones.ext (Iso.refl _) (by cat_disch) end SheafCondition open SheafCondition variable (F : Presheaf C X) {ι : Type*} (U : ι → Opens X) /-- The diagram over all `{ V : Opens X // ∃ i, V ≤ U i }` is a limit iff the diagram over `U i` and `U i ⊓ U j` is a limit. -/ def isLimitOpensLeCoverEquivPairwise : IsLimit (F.mapCone (opensLeCoverCocone U).op) ≃ IsLimit (F.mapCone (Pairwise.cocone U).op) := calc IsLimit (F.mapCone (opensLeCoverCocone U).op) ≃ IsLimit ((F.mapCone (opensLeCoverCocone U).op).whisker (pairwiseToOpensLeCover U).op) := (Functor.Initial.isLimitWhiskerEquiv (pairwiseToOpensLeCover U).op _).symm _ ≃ IsLimit (F.mapCone ((opensLeCoverCocone U).op.whisker (pairwiseToOpensLeCover U).op)) := (IsLimit.equivIsoLimit F.mapConeWhisker.symm) _ ≃ IsLimit ((Cones.postcomposeEquivalence _).functor.obj (F.mapCone ((opensLeCoverCocone U).op.whisker (pairwiseToOpensLeCover U).op))) := (IsLimit.postcomposeHomEquiv _ _).symm _ ≃ IsLimit (F.mapCone ((Cones.postcomposeEquivalence _).functor.obj ((opensLeCoverCocone U).op.whisker (pairwiseToOpensLeCover U).op))) := (IsLimit.equivIsoLimit (Functor.mapConePostcomposeEquivalenceFunctor _).symm) _ ≃ IsLimit (F.mapCone (Pairwise.cocone U).op) := IsLimit.equivIsoLimit ((Cones.functoriality _ _).mapIso (pairwiseCoconeIso U :).symm) /-- The sheaf condition in terms of a limit diagram over all `{ V : Opens X // ∃ i, V ≤ U i }` is equivalent to the reformulation in terms of a limit diagram over `U i` and `U i ⊓ U j`. -/ theorem isSheafOpensLeCover_iff_isSheafPairwiseIntersections : F.IsSheafOpensLeCover ↔ F.IsSheafPairwiseIntersections := forall₂_congr fun _ U ↦ (F.isLimitOpensLeCoverEquivPairwise U).nonempty_congr variable {F} in theorem IsSheaf.isSheafPairwiseIntersections (h : F.IsSheaf) : Nonempty (IsLimit (F.mapCone (Pairwise.cocone U).op)) := (h.isSheafOpensLeCover U).map (F.isLimitOpensLeCoverEquivPairwise _) /-- The sheaf condition in terms of an equalizer diagram is equivalent to the reformulation in terms of a limit diagram over `U i` and `U i ⊓ U j`. -/ theorem isSheaf_iff_isSheafPairwiseIntersections : F.IsSheaf ↔ F.IsSheafPairwiseIntersections := by rw [isSheaf_iff_isSheafOpensLeCover, isSheafOpensLeCover_iff_isSheafPairwiseIntersections] variable {F} in theorem IsSheaf.isSheafPreservesLimitPairwiseIntersections (h : F.IsSheaf) : PreservesLimit (Pairwise.diagram U).op F := preservesLimit_of_preserves_limit_cone (Pairwise.coconeIsColimit U).op (h.isSheafPairwiseIntersections U).some /-- The sheaf condition in terms of an equalizer diagram is equivalent to the reformulation in terms of the presheaf preserving the limit of the diagram consisting of the `U i` and `U i ⊓ U j`. -/ theorem isSheaf_iff_isSheafPreservesLimitPairwiseIntersections : F.IsSheaf ↔ F.IsSheafPreservesLimitPairwiseIntersections := by refine ⟨fun h U ↦ h.isSheafPreservesLimitPairwiseIntersections, fun h ↦ F.isSheaf_iff_isSheafPairwiseIntersections.mpr fun ι U ↦ ?_⟩ haveI := h U exact ⟨isLimitOfPreserves _ (Pairwise.coconeIsColimit U).op⟩ end TopCat.Presheaf namespace TopCat.Sheaf variable (F : X.Sheaf C) (U V : Opens X) open CategoryTheory.Limits /-- For a sheaf `F`, `F(U ⊔ V)` is the pullback of `F(U) ⟶ F(U ⊓ V)` and `F(V) ⟶ F(U ⊓ V)`. This is the pullback cone. -/ def interUnionPullbackCone : PullbackCone (F.1.map (homOfLE inf_le_left : U ⊓ V ⟶ _).op) (F.1.map (homOfLE inf_le_right).op) := PullbackCone.mk (F.1.map (homOfLE le_sup_left).op) (F.1.map (homOfLE le_sup_right).op) <| by rw [← F.1.map_comp, ← F.1.map_comp] congr 1 @[simp] theorem interUnionPullbackCone_pt : (interUnionPullbackCone F U V).pt = F.1.obj (op <| U ⊔ V) := rfl @[simp] theorem interUnionPullbackCone_fst : (interUnionPullbackCone F U V).fst = F.1.map (homOfLE le_sup_left).op := rfl @[simp] theorem interUnionPullbackCone_snd : (interUnionPullbackCone F U V).snd = F.1.map (homOfLE le_sup_right).op := rfl variable (s : PullbackCone (F.1.map (homOfLE inf_le_left : U ⊓ V ⟶ _).op) (F.1.map (homOfLE inf_le_right).op)) /-- (Implementation). Every cone over `F(U) ⟶ F(U ⊓ V)` and `F(V) ⟶ F(U ⊓ V)` factors through `F(U ⊔ V)`. -/ def interUnionPullbackConeLift : s.pt ⟶ F.1.obj (op (U ⊔ V)) := by let ι : ULift.{w} WalkingPair → Opens X := fun j => WalkingPair.casesOn j.down U V have hι : U ⊔ V = iSup ι := by ext rw [Opens.coe_iSup, Set.mem_iUnion] constructor · rintro (h | h) exacts [⟨⟨WalkingPair.left⟩, h⟩, ⟨⟨WalkingPair.right⟩, h⟩] · rintro ⟨⟨_ | _⟩, h⟩ exacts [Or.inl h, Or.inr h] refine (F.presheaf.isSheaf_iff_isSheafPairwiseIntersections.mp F.2 ι).some.lift ⟨s.pt, { app := ?_ naturality := ?_ }⟩ ≫ F.1.map (eqToHom hι).op · rintro ((_ | _) | (_ | _)) exacts [s.fst, s.snd, s.fst ≫ F.1.map (homOfLE inf_le_left).op, s.snd ≫ F.1.map (homOfLE inf_le_left).op] rintro ⟨i⟩ ⟨j⟩ f let g : j ⟶ i := f.unop have : f = g.op := rfl clear_value g subst this rcases i with (⟨⟨_ | _⟩⟩ | ⟨⟨_ | _⟩, ⟨_⟩⟩) <;> rcases j with (⟨⟨_ | _⟩⟩ | ⟨⟨_ | _⟩, ⟨_⟩⟩) <;> rcases g with ⟨⟩ <;> dsimp [Pairwise.diagram] <;> simp only [ι, Category.id_comp, s.condition, CategoryTheory.Functor.map_id, Category.comp_id] rw [← cancel_mono (F.1.map (eqToHom <| inf_comm U V : U ⊓ V ⟶ _).op), Category.assoc, Category.assoc, ← F.1.map_comp, ← F.1.map_comp] exact s.condition.symm theorem interUnionPullbackConeLift_left : interUnionPullbackConeLift F U V s ≫ F.1.map (homOfLE le_sup_left).op = s.fst := by erw [Category.assoc] simp_rw [← F.1.map_comp] exact (F.presheaf.isSheaf_iff_isSheafPairwiseIntersections.mp F.2 _).some.fac _ <| op <| Pairwise.single <| ULift.up WalkingPair.left theorem interUnionPullbackConeLift_right : interUnionPullbackConeLift F U V s ≫ F.1.map (homOfLE le_sup_right).op = s.snd := by erw [Category.assoc] simp_rw [← F.1.map_comp] exact (F.presheaf.isSheaf_iff_isSheafPairwiseIntersections.mp F.2 _).some.fac _ <| op <| Pairwise.single <| ULift.up WalkingPair.right /-- For a sheaf `F`, `F(U ⊔ V)` is the pullback of `F(U) ⟶ F(U ⊓ V)` and `F(V) ⟶ F(U ⊓ V)`. -/ def isLimitPullbackCone : IsLimit (interUnionPullbackCone F U V) := by let ι : ULift.{w} WalkingPair → Opens X := fun ⟨j⟩ => WalkingPair.casesOn j U V have hι : U ⊔ V = iSup ι := by ext rw [Opens.coe_iSup, Set.mem_iUnion] constructor · rintro (h | h) exacts [⟨⟨WalkingPair.left⟩, h⟩, ⟨⟨WalkingPair.right⟩, h⟩] · rintro ⟨⟨_ | _⟩, h⟩ exacts [Or.inl h, Or.inr h] apply PullbackCone.isLimitAux' intro s use interUnionPullbackConeLift F U V s refine ⟨?_, ?_, ?_⟩ · apply interUnionPullbackConeLift_left · apply interUnionPullbackConeLift_right · intro m h₁ h₂ rw [← cancel_mono (F.1.map (eqToHom hι.symm).op)] apply (F.presheaf.isSheaf_iff_isSheafPairwiseIntersections.mp F.2 ι).some.hom_ext rintro ((_ | _) | (_ | _)) <;> rw [Category.assoc, Category.assoc] · erw [← F.1.map_comp] convert h₁ apply interUnionPullbackConeLift_left · erw [← F.1.map_comp] convert h₂ apply interUnionPullbackConeLift_right all_goals dsimp only [Functor.op, Pairwise.cocone_ι_app, Functor.mapCone_π_app, Cocone.op, Pairwise.coconeιApp, unop_op, op_comp, NatTrans.op] simp_rw [F.1.map_comp, ← Category.assoc] congr 1 simp_rw [Category.assoc, ← F.1.map_comp] · convert h₁ apply interUnionPullbackConeLift_left · convert h₂ apply interUnionPullbackConeLift_right /-- If `U, V` are disjoint, then `F(U ⊔ V) = F(U) × F(V)`. -/ def isProductOfDisjoint (h : U ⊓ V = ⊥) : IsLimit (BinaryFan.mk (F.1.map (homOfLE le_sup_left : _ ⟶ U ⊔ V).op) (F.1.map (homOfLE le_sup_right : _ ⟶ U ⊔ V).op)) := isProductOfIsTerminalIsPullback _ _ _ _ (F.isTerminalOfEqEmpty h) (isLimitPullbackCone F U V) end TopCat.Sheaf
.lake/packages/mathlib/Mathlib/Topology/Sheaves/SheafCondition/Sites.lean
import Mathlib.CategoryTheory.Sites.Spaces import Mathlib.Topology.Sheaves.Sheaf import Mathlib.CategoryTheory.Sites.DenseSubsite.Basic /-! # Coverings and sieves; from sheaves on sites and sheaves on spaces In this file, we connect coverings in a topological space to sieves in the associated Grothendieck topology, in preparation of connecting the sheaf condition on sites to the various sheaf conditions on spaces. We also specialize results about sheaves on sites to sheaves on spaces; we show that the inclusion functor from a topological basis to `TopologicalSpace.Opens` is cover dense, that open maps induce cover-preserving functors, and that open embeddings induce continuous functors. -/ noncomputable section open CategoryTheory TopologicalSpace Topology universe w v u namespace TopCat.Presheaf variable {X : TopCat.{w}} /-- Given a presieve `R` on `U`, we obtain a covering family of open sets in `X`, by taking as index type the type of dependent pairs `(V, f)`, where `f : V ⟶ U` is in `R`. -/ def coveringOfPresieve (U : Opens X) (R : Presieve U) : (Σ V, { f : V ⟶ U // R f }) → Opens X := fun f => f.1 @[simp] theorem coveringOfPresieve_apply (U : Opens X) (R : Presieve U) (f : Σ V, { f : V ⟶ U // R f }) : coveringOfPresieve U R f = f.1 := rfl namespace coveringOfPresieve variable (U : Opens X) (R : Presieve U) /-- If `R` is a presieve in the Grothendieck topology on `Opens X`, the covering family associated to `R` really is _covering_, i.e. the union of all open sets equals `U`. -/ theorem iSup_eq_of_mem_grothendieck (hR : Sieve.generate R ∈ Opens.grothendieckTopology X U) : iSup (coveringOfPresieve U R) = U := by apply le_antisymm · refine iSup_le ?_ intro f exact f.2.1.le intro x hxU rw [Opens.coe_iSup, Set.mem_iUnion] obtain ⟨V, iVU, ⟨W, iVW, iWU, hiWU, -⟩, hxV⟩ := hR x hxU exact ⟨⟨W, ⟨iWU, hiWU⟩⟩, iVW.le hxV⟩ end coveringOfPresieve /-- Given a family of opens `U : ι → Opens X` and any open `Y : Opens X`, we obtain a presieve on `Y` by declaring that a morphism `f : V ⟶ Y` is a member of the presieve if and only if there exists an index `i : ι` such that `V = U i`. -/ def presieveOfCoveringAux {ι : Type v} (U : ι → Opens X) (Y : Opens X) : Presieve Y := fun V _ => ∃ i, V = U i /-- Take `Y` to be `iSup U` and obtain a presieve over `iSup U`. -/ def presieveOfCovering {ι : Type v} (U : ι → Opens X) : Presieve (iSup U) := presieveOfCoveringAux U (iSup U) /-- Given a presieve `R` on `Y`, if we take its associated family of opens via `coveringOfPresieve` (which may not cover `Y` if `R` is not covering), and take the presieve on `Y` associated to the family of opens via `presieveOfCoveringAux`, then we get back the original presieve `R`. -/ @[simp] theorem covering_presieve_eq_self {Y : Opens X} (R : Presieve Y) : presieveOfCoveringAux (coveringOfPresieve Y R) Y = R := by funext Z ext f exact ⟨fun ⟨⟨_, f', h⟩, rfl⟩ => by rwa [Subsingleton.elim f f'], fun h => ⟨⟨Z, f, h⟩, rfl⟩⟩ namespace presieveOfCovering variable {ι : Type v} (U : ι → Opens X) /-- The sieve generated by `presieveOfCovering U` is a member of the Grothendieck topology. -/ theorem mem_grothendieckTopology : Sieve.generate (presieveOfCovering U) ∈ Opens.grothendieckTopology X (iSup U) := by intro x hx obtain ⟨i, hxi⟩ := Opens.mem_iSup.mp hx exact ⟨U i, Opens.leSupr U i, ⟨U i, 𝟙 _, Opens.leSupr U i, ⟨i, rfl⟩, Category.id_comp _⟩, hxi⟩ /-- An index `i : ι` can be turned into a dependent pair `(V, f)`, where `V` is an open set and `f : V ⟶ iSup U` is a member of `presieveOfCovering U f`. -/ def homOfIndex (i : ι) : Σ V, { f : V ⟶ iSup U // presieveOfCovering U f } := ⟨U i, Opens.leSupr U i, i, rfl⟩ /-- By using the axiom of choice, a dependent pair `(V, f)` where `f : V ⟶ iSup U` is a member of `presieveOfCovering U f` can be turned into an index `i : ι`, such that `V = U i`. -/ def indexOfHom (f : Σ V, { f : V ⟶ iSup U // presieveOfCovering U f }) : ι := f.2.2.choose theorem indexOfHom_spec (f : Σ V, { f : V ⟶ iSup U // presieveOfCovering U f }) : f.1 = U (indexOfHom U f) := f.2.2.choose_spec end presieveOfCovering end TopCat.Presheaf namespace TopCat.Opens variable {X : TopCat} {ι : Type*} theorem coverDense_iff_isBasis [Category ι] (B : ι ⥤ Opens X) : B.IsCoverDense (Opens.grothendieckTopology X) ↔ Opens.IsBasis (Set.range B.obj) := by rw [Opens.isBasis_iff_nbhd] constructor · intro hd U x hx; rcases hd.1 U x hx with ⟨V, f, ⟨i, f₁, f₂, _⟩, hV⟩ exact ⟨B.obj i, ⟨i, rfl⟩, f₁.le hV, f₂.le⟩ intro hb; constructor; intro U x hx; rcases hb hx with ⟨_, ⟨i, rfl⟩, hx, hi⟩ exact ⟨B.obj i, ⟨⟨hi⟩⟩, ⟨⟨i, 𝟙 _, ⟨⟨hi⟩⟩, rfl⟩⟩, hx⟩ theorem coverDense_inducedFunctor {B : ι → Opens X} (h : Opens.IsBasis (Set.range B)) : (inducedFunctor B).IsCoverDense (Opens.grothendieckTopology X) := (coverDense_iff_isBasis _).2 h end TopCat.Opens section IsOpenEmbedding open TopCat.Presheaf Opposite variable {C : Type u} [Category.{v} C] variable {X Y : TopCat.{w}} {f : X ⟶ Y} {F : Y.Presheaf C} theorem Topology.IsOpenEmbedding.compatiblePreserving (hf : IsOpenEmbedding f) : CompatiblePreserving (Opens.grothendieckTopology Y) hf.isOpenMap.functor := by haveI : Mono f := (TopCat.mono_iff_injective f).mpr hf.injective apply compatiblePreservingOfDownwardsClosed intro U V i refine ⟨(Opens.map f).obj V, eqToIso <| Opens.ext <| Set.image_preimage_eq_of_subset fun x h ↦ ?_⟩ obtain ⟨_, _, rfl⟩ := i.le h exact ⟨_, rfl⟩ theorem IsOpenMap.coverPreserving (hf : IsOpenMap f) : CoverPreserving (Opens.grothendieckTopology X) (Opens.grothendieckTopology Y) hf.functor := by constructor rintro U S hU _ ⟨x, hx, rfl⟩ obtain ⟨V, i, hV, hxV⟩ := hU x hx exact ⟨_, hf.functor.map i, ⟨_, i, 𝟙 _, hV, rfl⟩, Set.mem_image_of_mem f hxV⟩ lemma Topology.IsOpenEmbedding.functor_isContinuous (h : IsOpenEmbedding f) : h.isOpenMap.functor.IsContinuous (Opens.grothendieckTopology X) (Opens.grothendieckTopology Y) := by apply Functor.isContinuous_of_coverPreserving · exact h.compatiblePreserving · exact h.isOpenMap.coverPreserving theorem TopCat.Presheaf.isSheaf_of_isOpenEmbedding (h : IsOpenEmbedding f) (hF : F.IsSheaf) : IsSheaf (h.isOpenMap.functor.op ⋙ F) := by have := h.functor_isContinuous exact Functor.op_comp_isSheaf _ _ _ ⟨_, hF⟩ variable (f) instance : RepresentablyFlat (Opens.map f) := by constructor intro U refine @IsCofiltered.mk _ _ ?_ ?_ · constructor · intro V W exact ⟨⟨⟨PUnit.unit⟩, V.right ⊓ W.right, homOfLE <| le_inf V.hom.le W.hom.le⟩, StructuredArrow.homMk (homOfLE inf_le_left), StructuredArrow.homMk (homOfLE inf_le_right), trivial⟩ · exact fun _ _ _ _ ↦ ⟨_, 𝟙 _, by simp [eq_iff_true_of_subsingleton]⟩ · exact ⟨StructuredArrow.mk <| show U ⟶ (Opens.map f).obj ⊤ from homOfLE le_top⟩ theorem compatiblePreserving_opens_map : CompatiblePreserving (Opens.grothendieckTopology X) (Opens.map f) := compatiblePreservingOfFlat _ _ theorem coverPreserving_opens_map : CoverPreserving (Opens.grothendieckTopology Y) (Opens.grothendieckTopology X) (Opens.map f) := by constructor intro U S hS x hx obtain ⟨V, i, hi, hxV⟩ := hS (f x) hx exact ⟨_, (Opens.map f).map i, ⟨_, _, 𝟙 _, hi, Subsingleton.elim _ _⟩, hxV⟩ instance : (Opens.map f).IsContinuous (Opens.grothendieckTopology Y) (Opens.grothendieckTopology X) := by apply Functor.isContinuous_of_coverPreserving · exact compatiblePreserving_opens_map f · exact coverPreserving_opens_map f end IsOpenEmbedding namespace TopCat.Sheaf open TopCat Opposite variable {C : Type u} [Category.{v} C] variable {X : TopCat.{w}} {ι : Type*} {B : ι → Opens X} variable (F : X.Presheaf C) (F' : Sheaf C X) /-- The empty component of a sheaf is terminal. -/ def isTerminalOfEmpty (F : Sheaf C X) : Limits.IsTerminal (F.val.obj (op ⊥)) := F.isTerminalOfBotCover ⊥ (fun _ h => h.elim) /-- A variant of `isTerminalOfEmpty` that is easier to `apply`. -/ def isTerminalOfEqEmpty (F : X.Sheaf C) {U : Opens X} (h : U = ⊥) : Limits.IsTerminal (F.val.obj (op U)) := by convert F.isTerminalOfEmpty /-- If a family `B` of open sets forms a basis of the topology on `X`, and if `F'` is a sheaf on `X`, then a homomorphism between a presheaf `F` on `X` and `F'` is equivalent to a homomorphism between their restrictions to the indexing type `ι` of `B`, with the induced category structure on `ι`. -/ def restrictHomEquivHom (h : Opens.IsBasis (Set.range B)) : ((inducedFunctor B).op ⋙ F ⟶ (inducedFunctor B).op ⋙ F'.1) ≃ (F ⟶ F'.1) := @Functor.IsCoverDense.restrictHomEquivHom _ _ _ _ _ _ _ _ (Opens.coverDense_inducedFunctor h) _ F F' @[simp] theorem extend_hom_app (h : Opens.IsBasis (Set.range B)) (α : (inducedFunctor B).op ⋙ F ⟶ (inducedFunctor B).op ⋙ F'.1) (i : ι) : (restrictHomEquivHom F F' h α).app (op (B i)) = α.app (op i) := by nth_rw 2 [← (restrictHomEquivHom F F' h).left_inv α] rfl theorem hom_ext (h : Opens.IsBasis (Set.range B)) {α β : F ⟶ F'.1} (he : ∀ i, α.app (op (B i)) = β.app (op (B i))) : α = β := by apply (restrictHomEquivHom F F' h).symm.injective ext i exact he i.unop end TopCat.Sheaf
.lake/packages/mathlib/Mathlib/Topology/Sheaves/SheafCondition/UniqueGluing.lean
import Mathlib.Topology.Sheaves.Forget import Mathlib.Topology.Sheaves.SheafCondition.PairwiseIntersections /-! # The sheaf condition in terms of unique gluings We provide an alternative formulation of the sheaf condition in terms of unique gluings. We work with sheaves valued in a concrete category `C` admitting all limits, whose forgetful functor `C ⥤ Type` preserves limits and reflects isomorphisms. The usual categories of algebraic structures, such as `MonCat`, `AddCommGrpCat`, `RingCat`, `CommRingCat` etc. are all examples of this kind of category. A presheaf `F : Presheaf C X` satisfies the sheaf condition if and only if, for every compatible family of sections `sf : Π i : ι, F.obj (op (U i))`, there exists a unique gluing `s : F.obj (op (iSup U))`. Here, the family `sf` is called compatible, if for all `i j : ι`, the restrictions of `sf i` and `sf j` to `U i ⊓ U j` agree. A section `s : F.obj (op (iSup U))` is a gluing for the family `sf`, if `s` restricts to `sf i` on `U i` for all `i : ι` We show that the sheaf condition in terms of unique gluings is equivalent to the definition in terms of pairwise intersections. Our approach is as follows: First, we show them to be equivalent for `Type`-valued presheaves. Then we use that composing a presheaf with a limit-preserving and isomorphism-reflecting functor leaves the sheaf condition invariant, as shown in `Mathlib/Topology/Sheaves/Forget.lean`. -/ noncomputable section open TopCat TopCat.Presheaf CategoryTheory CategoryTheory.Limits TopologicalSpace TopologicalSpace.Opens Opposite universe x variable {C : Type*} [Category C] {FC : C → C → Type*} {CC : C → Type*} variable [∀ X Y, FunLike (FC X Y) (CC X) (CC Y)] [ConcreteCategory C FC] namespace TopCat namespace Presheaf section variable {X : TopCat.{x}} (F : Presheaf C X) {ι : Type*} (U : ι → Opens X) /-- A family of sections `sf` is compatible, if the restrictions of `sf i` and `sf j` to `U i ⊓ U j` agree, for all `i` and `j` -/ def IsCompatible (sf : ∀ i : ι, ToType (F.obj (op (U i)))) : Prop := ∀ i j : ι, F.map (infLELeft (U i) (U j)).op (sf i) = F.map (infLERight (U i) (U j)).op (sf j) /-- A section `s` is a gluing for a family of sections `sf` if it restricts to `sf i` on `U i`, for all `i` -/ def IsGluing (sf : ∀ i : ι, ToType (F.obj (op (U i)))) (s : ToType (F.obj (op (iSup U)))) : Prop := ∀ i : ι, F.map (Opens.leSupr U i).op s = sf i /-- The sheaf condition in terms of unique gluings. A presheaf `F : Presheaf C X` satisfies this sheaf condition if and only if, for every compatible family of sections `sf : Π i : ι, F.obj (op (U i))`, there exists a unique gluing `s : F.obj (op (iSup U))`. We prove this to be equivalent to the usual one below in `TopCat.Presheaf.isSheaf_iff_isSheafUniqueGluing` -/ def IsSheafUniqueGluing : Prop := ∀ ⦃ι : Type x⦄ (U : ι → Opens X) (sf : ∀ i : ι, ToType (F.obj (op (U i)))), IsCompatible F U sf → ∃! s : ToType (F.obj (op (iSup U))), IsGluing F U sf s end section TypeValued variable {X : TopCat.{x}} {F : Presheaf Type* X} {ι : Type*} {U : ι → Opens X} /-- Given sections over a family of open sets, extend it to include sections over pairwise intersections of the open sets. -/ def objPairwiseOfFamily (sf : ∀ i, F.obj (op (U i))) : ∀ i, ((Pairwise.diagram U).op ⋙ F).obj i | ⟨Pairwise.single i⟩ => sf i | ⟨Pairwise.pair i j⟩ => F.map (infLELeft (U i) (U j)).op (sf i) attribute [local instance] Types.instFunLike Types.instConcreteCategory /-- Given a compatible family of sections over open sets, extend it to a section of the functor `(Pairwise.diagram U).op ⋙ F`. -/ def IsCompatible.sectionPairwise {sf} (h : IsCompatible F U sf) : ((Pairwise.diagram U).op ⋙ F).sections := by refine ⟨objPairwiseOfFamily sf, ?_⟩ let G := (Pairwise.diagram U).op ⋙ F rintro (i|⟨i,j⟩) (i'|⟨i',j'⟩) (_ | _ | _ | _) · exact congr_fun (G.map_id <| op <| Pairwise.single i) _ · rfl · exact (h i' i).symm · exact congr_fun (G.map_id <| op <| Pairwise.pair i j) _ theorem isGluing_iff_pairwise {sf s} : IsGluing F U sf s ↔ ∀ i, (F.mapCone (Pairwise.cocone U).op).π.app i s = objPairwiseOfFamily sf i := by refine ⟨fun h ↦ ?_, fun h i ↦ h (op <| Pairwise.single i)⟩ rintro (i|⟨i,j⟩) · exact h i · rw [← (F.mapCone (Pairwise.cocone U).op).w (op <| Pairwise.Hom.left i j)] exact congr_arg _ (h i) theorem IsSheaf.isSheafUniqueGluing_types (h : F.IsSheaf) (sf : ∀ i : ι, F.obj (op (U i))) (cpt : IsCompatible F U sf) : ∃! s : F.obj (op (iSup U)), IsGluing F U sf s := by simp_rw [isGluing_iff_pairwise] exact (Types.isLimit_iff _).mp (h.isSheafPairwiseIntersections U) _ cpt.sectionPairwise.prop variable (F) /-- For type-valued presheaves, the sheaf condition in terms of unique gluings is equivalent to the usual sheaf condition. -/ theorem isSheaf_iff_isSheafUniqueGluing_types : F.IsSheaf ↔ F.IsSheafUniqueGluing := by simp_rw [isSheaf_iff_isSheafPairwiseIntersections, IsSheafPairwiseIntersections, Types.isLimit_iff, IsSheafUniqueGluing, isGluing_iff_pairwise] refine forall₂_congr fun ι U ↦ ⟨fun h sf cpt ↦ ?_, fun h s hs ↦ ?_⟩ · exact h _ cpt.sectionPairwise.prop · specialize h (fun i ↦ s <| op <| Pairwise.single i) fun i j ↦ (hs <| op <| Pairwise.Hom.left i j).trans (hs <| op <| Pairwise.Hom.right i j).symm convert h; ext (i|⟨i,j⟩) · rfl · exact (hs <| op <| Pairwise.Hom.left i j).symm /-- The usual sheaf condition can be obtained from the sheaf condition in terms of unique gluings. -/ theorem isSheaf_of_isSheafUniqueGluing_types (Fsh : F.IsSheafUniqueGluing) : F.IsSheaf := (isSheaf_iff_isSheafUniqueGluing_types F).mpr Fsh end TypeValued section variable [HasLimitsOfSize.{x, x} C] [(forget C).ReflectsIsomorphisms] [PreservesLimitsOfSize.{x, x} (forget C)] variable {X : TopCat.{x}} {F : Presheaf C X} theorem IsSheaf.isSheafUniqueGluing (h : F.IsSheaf) {ι : Type*} (U : ι → Opens X) (sf : ∀ i : ι, ToType (F.obj (op (U i)))) (cpt : IsCompatible F U sf) : ∃! s : ToType (F.obj (op (iSup U))), IsGluing F U sf s := ((isSheaf_iff_isSheaf_comp' (forget C) F).mp h).isSheafUniqueGluing_types sf cpt variable (F) /-- For presheaves valued in a concrete category, whose forgetful functor reflects isomorphisms and preserves limits, the sheaf condition in terms of unique gluings is equivalent to the usual one. -/ theorem isSheaf_iff_isSheafUniqueGluing : F.IsSheaf ↔ F.IsSheafUniqueGluing := Iff.trans (isSheaf_iff_isSheaf_comp' (forget C) F) (isSheaf_iff_isSheafUniqueGluing_types (F ⋙ forget C)) end end Presheaf namespace Sheaf open Presheaf CategoryTheory section variable [HasLimitsOfSize.{x, x} C] [(HasForget.forget (C := C)).ReflectsIsomorphisms] variable [PreservesLimitsOfSize.{x, x} (HasForget.forget (C := C))] variable {X : TopCat.{x}} (F : Sheaf C X) {ι : Type*} (U : ι → Opens X) /-- A more convenient way of obtaining a unique gluing of sections for a sheaf. -/ theorem existsUnique_gluing (sf : ∀ i : ι, ToType (F.1.obj (op (U i)))) (h : IsCompatible F.1 U sf) : ∃! s : ToType (F.1.obj (op (iSup U))), IsGluing F.1 U sf s := IsSheaf.isSheafUniqueGluing F.cond U sf h /-- In this version of the lemma, the inclusion homs `iUV` can be specified directly by the user, which can be more convenient in practice. -/ theorem existsUnique_gluing' (V : Opens X) (iUV : ∀ i : ι, U i ⟶ V) (hcover : V ≤ iSup U) (sf : ∀ i : ι, ToType (F.1.obj (op (U i)))) (h : IsCompatible F.1 U sf) : ∃! s : ToType (F.1.obj (op V)), ∀ i : ι, F.1.map (iUV i).op s = sf i := by have V_eq_supr_U : V = iSup U := le_antisymm hcover (iSup_le fun i => (iUV i).le) obtain ⟨gl, gl_spec, gl_uniq⟩ := F.existsUnique_gluing U sf h refine ⟨F.1.map (eqToHom V_eq_supr_U).op gl, ?_, ?_⟩ · intro i rw [← ConcreteCategory.comp_apply, ← F.1.map_comp] exact gl_spec i · intro gl' gl'_spec convert congr_arg _ (gl_uniq (F.1.map (eqToHom V_eq_supr_U.symm).op gl') fun i => _) <;> rw [← ConcreteCategory.comp_apply, ← F.1.map_comp] · rw [eqToHom_op, eqToHom_op, eqToHom_trans, eqToHom_refl, F.1.map_id, ConcreteCategory.id_apply] · exact gl'_spec i @[ext] theorem eq_of_locally_eq (s t : ToType (F.1.obj (op (iSup U)))) (h : ∀ i, F.1.map (Opens.leSupr U i).op s = F.1.map (Opens.leSupr U i).op t) : s = t := by let sf : ∀ i : ι, ToType (F.1.obj (op (U i))) := fun i => F.1.map (Opens.leSupr U i).op s have sf_compatible : IsCompatible _ U sf := by intro i j simp_rw [sf, ← ConcreteCategory.comp_apply, ← F.1.map_comp] rfl obtain ⟨gl, -, gl_uniq⟩ := F.existsUnique_gluing U sf sf_compatible trans gl · apply gl_uniq intro i rfl · symm apply gl_uniq intro i rw [← h] /-- In this version of the lemma, the inclusion homs `iUV` can be specified directly by the user, which can be more convenient in practice. -/ theorem eq_of_locally_eq' (V : Opens X) (iUV : ∀ i : ι, U i ⟶ V) (hcover : V ≤ iSup U) (s t : ToType (F.1.obj (op V))) (h : ∀ i, F.1.map (iUV i).op s = F.1.map (iUV i).op t) : s = t := by have V_eq_supr_U : V = iSup U := le_antisymm hcover (iSup_le fun i => (iUV i).le) suffices F.1.map (eqToHom V_eq_supr_U.symm).op s = F.1.map (eqToHom V_eq_supr_U.symm).op t by convert congr_arg (F.1.map (eqToHom V_eq_supr_U).op) this <;> rw [← ConcreteCategory.comp_apply, ← F.1.map_comp, eqToHom_op, eqToHom_op, eqToHom_trans, eqToHom_refl, F.1.map_id, ConcreteCategory.id_apply] apply eq_of_locally_eq intro i rw [← ConcreteCategory.comp_apply, ← ConcreteCategory.comp_apply, ← F.1.map_comp] exact h i theorem eq_of_locally_eq₂ {U₁ U₂ V : Opens X} (i₁ : U₁ ⟶ V) (i₂ : U₂ ⟶ V) (hcover : V ≤ U₁ ⊔ U₂) (s t : ToType (F.1.obj (op V))) (h₁ : F.1.map i₁.op s = F.1.map i₁.op t) (h₂ : F.1.map i₂.op s = F.1.map i₂.op t) : s = t := by classical fapply F.eq_of_locally_eq' fun t : Bool => if t then U₁ else U₂ · exact fun i => if h : i then eqToHom (if_pos h) ≫ i₁ else eqToHom (if_neg h) ≫ i₂ · refine le_trans hcover ?_ rw [sup_le_iff] constructor · exact le_iSup (fun t : Bool => if t then U₁ else U₂) true · exact le_iSup (fun t : Bool => if t then U₁ else U₂) false · rintro ⟨_ | _⟩ any_goals exact h₁ any_goals exact h₂ end end Sheaf end TopCat
.lake/packages/mathlib/Mathlib/Topology/Sheaves/SheafCondition/EqualizerProducts.lean
import Mathlib.CategoryTheory.Limits.Shapes.Equalizers import Mathlib.CategoryTheory.Limits.Shapes.Products import Mathlib.Topology.Sheaves.SheafCondition.PairwiseIntersections /-! # The sheaf condition in terms of an equalizer of products Here we set up the machinery for the "usual" definition of the sheaf condition, e.g. as in https://stacks.math.columbia.edu/tag/0072 in terms of an equalizer diagram where the two objects are `∏ᶜ F.obj (U i)` and `∏ᶜ F.obj (U i) ⊓ (U j)`. We show that this sheaf condition is equivalent to the "pairwise intersections" sheaf condition when the presheaf is valued in a category with products, and thereby equivalent to the default sheaf condition. -/ universe v' v u noncomputable section open CategoryTheory CategoryTheory.Limits TopologicalSpace Opposite TopologicalSpace.Opens namespace TopCat variable {C : Type u} [Category.{v} C] [HasProducts.{v'} C] variable {X : TopCat.{v'}} (F : Presheaf C X) {ι : Type v'} (U : ι → Opens X) namespace Presheaf namespace SheafConditionEqualizerProducts /-- The product of the sections of a presheaf over a family of open sets. -/ def piOpens : C := ∏ᶜ fun i : ι => F.obj (op (U i)) /-- The product of the sections of a presheaf over the pairwise intersections of a family of open sets. -/ def piInters : C := ∏ᶜ fun p : ι × ι => F.obj (op (U p.1 ⊓ U p.2)) /-- The morphism `Π F.obj (U i) ⟶ Π F.obj (U i) ⊓ (U j)` whose components are given by the restriction maps from `U i` to `U i ⊓ U j`. -/ def leftRes : piOpens F U ⟶ piInters.{v'} F U := Pi.lift fun p : ι × ι => Pi.π _ p.1 ≫ F.map (infLELeft (U p.1) (U p.2)).op /-- The morphism `Π F.obj (U i) ⟶ Π F.obj (U i) ⊓ (U j)` whose components are given by the restriction maps from `U j` to `U i ⊓ U j`. -/ def rightRes : piOpens F U ⟶ piInters.{v'} F U := Pi.lift fun p : ι × ι => Pi.π _ p.2 ≫ F.map (infLERight (U p.1) (U p.2)).op /-- The morphism `F.obj U ⟶ Π F.obj (U i)` whose components are given by the restriction maps from `U j` to `U i ⊓ U j`. -/ def res : F.obj (op (iSup U)) ⟶ piOpens.{v'} F U := Pi.lift fun i : ι => F.map (TopologicalSpace.Opens.leSupr U i).op @[simp, elementwise] theorem res_π (i : ι) : res F U ≫ limit.π _ ⟨i⟩ = F.map (Opens.leSupr U i).op := by rw [res, limit.lift_π, Fan.mk_π_app] /-- Copy of `limit.hom_ext`, specialized to `piOpens` for use by the `ext` tactic. -/ @[ext] theorem piOpens.hom_ext {X : C} {f f' : X ⟶ piOpens F U} (w : ∀ j, f ≫ limit.π _ j = f' ≫ limit.π _ j) : f = f' := limit.hom_ext w /-- Copy of `limit.hom_ext`, specialized to `piInters` for use by the `ext` tactic. -/ @[ext] theorem piInters.hom_ext {X : C} {f f' : X ⟶ piInters F U} (w : ∀ j, f ≫ limit.π _ j = f' ≫ limit.π _ j) : f = f' := limit.hom_ext w @[elementwise] theorem w : res F U ≫ leftRes F U = res F U ≫ rightRes F U := by dsimp [res, leftRes, rightRes] ext simp only [limit.lift_π, limit.lift_π_assoc, Fan.mk_π_app, Category.assoc] rw [← F.map_comp] rw [← F.map_comp] congr 1 /-- The equalizer diagram for the sheaf condition. -/ abbrev diagram : WalkingParallelPair ⥤ C := parallelPair (leftRes.{v'} F U) (rightRes F U) /-- The restriction map `F.obj U ⟶ Π F.obj (U i)` gives a cone over the equalizer diagram for the sheaf condition. The sheaf condition asserts this cone is a limit cone. -/ def fork : Fork.{v} (leftRes F U) (rightRes F U) := Fork.ofι _ (w F U) @[simp] theorem fork_pt : (fork F U).pt = F.obj (op (iSup U)) := rfl @[simp] theorem fork_ι : (fork F U).ι = res F U := rfl @[simp] theorem fork_π_app_walkingParallelPair_zero : (fork F U).π.app WalkingParallelPair.zero = res F U := rfl @[simp] theorem fork_π_app_walkingParallelPair_one : (fork F U).π.app WalkingParallelPair.one = res F U ≫ leftRes F U := rfl variable {F} {G : Presheaf C X} /-- Isomorphic presheaves have isomorphic `piOpens` for any cover `U`. -/ @[simp] def piOpens.isoOfIso (α : F ≅ G) : piOpens F U ≅ piOpens.{v'} G U := Pi.mapIso fun _ => α.app _ /-- Isomorphic presheaves have isomorphic `piInters` for any cover `U`. -/ @[simp] def piInters.isoOfIso (α : F ≅ G) : piInters F U ≅ piInters.{v'} G U := Pi.mapIso fun _ => α.app _ /-- Isomorphic presheaves have isomorphic sheaf condition diagrams. -/ def diagram.isoOfIso (α : F ≅ G) : diagram F U ≅ diagram.{v'} G U := NatIso.ofComponents (by rintro ⟨⟩ · exact piOpens.isoOfIso U α · exact piInters.isoOfIso U α) (by rintro ⟨⟩ ⟨⟩ ⟨⟩ · simp · dsimp ext simp only [leftRes, limit.lift_map, limit.lift_π, Cones.postcompose_obj_π, NatTrans.comp_app, Fan.mk_π_app, Discrete.natIso_hom_app, Iso.app_hom, Category.assoc, NatTrans.naturality, limMap_π_assoc] · dsimp [diagram] ext simp only [rightRes, limit.lift_map, limit.lift_π, Cones.postcompose_obj_π, NatTrans.comp_app, Fan.mk_π_app, Discrete.natIso_hom_app, Iso.app_hom, Category.assoc, NatTrans.naturality, limMap_π_assoc] · simp) /-- If `F G : Presheaf C X` are isomorphic presheaves, then the `fork F U`, the canonical cone of the sheaf condition diagram for `F`, is isomorphic to `fork F G` postcomposed with the corresponding isomorphism between sheaf condition diagrams. -/ def fork.isoOfIso (α : F ≅ G) : fork F U ≅ (Cones.postcompose (diagram.isoOfIso U α).inv).obj (fork G U) := by fapply Fork.ext · apply α.app · dsimp ext dsimp only [Fork.ι] -- Ugh, `simp` can't unfold abbreviations. simp only [res, diagram.isoOfIso, piOpens.isoOfIso, Cones.postcompose_obj_π, NatTrans.comp_app, fork_π_app_walkingParallelPair_zero, NatIso.ofComponents_inv_app, Functor.mapIso_inv, lim_map, limit.lift_map, Category.assoc, limit.lift_π, Fan.mk_π_app, Discrete.natIso_inv_app, Iso.app_inv, NatTrans.naturality, Iso.hom_inv_id_app_assoc] end SheafConditionEqualizerProducts /-- The sheaf condition for a `F : Presheaf C X` requires that the morphism `F.obj U ⟶ ∏ᶜ F.obj (U i)` (where `U` is some open set which is the union of the `U i`) is the equalizer of the two morphisms `∏ᶜ F.obj (U i) ⟶ ∏ᶜ F.obj (U i) ⊓ (U j)`. -/ def IsSheafEqualizerProducts (F : Presheaf.{v', v, u} C X) : Prop := ∀ ⦃ι : Type v'⦄ (U : ι → Opens X), Nonempty (IsLimit (SheafConditionEqualizerProducts.fork F U)) /-! The remainder of this file shows that the "equalizer products" sheaf condition is equivalent to the "pairwise intersections" sheaf condition. -/ namespace SheafConditionPairwiseIntersections open CategoryTheory.Pairwise CategoryTheory.Pairwise.Hom /-- Implementation of `SheafConditionPairwiseIntersections.coneEquiv`. -/ @[simps] def coneEquivFunctorObj (c : Cone ((diagram U).op ⋙ F)) : Cone (SheafConditionEqualizerProducts.diagram F U) where pt := c.pt π := { app := fun Z => WalkingParallelPair.casesOn Z (Pi.lift fun i : ι => c.π.app (op (single i))) (Pi.lift fun b : ι × ι => c.π.app (op (pair b.1 b.2))) naturality := fun Y Z f => by cases Y <;> cases Z <;> cases f · dsimp ext simp · dsimp ext ij rcases ij with ⟨i, j⟩ simpa [SheafConditionEqualizerProducts.leftRes] using c.π.naturality (Quiver.Hom.op (Hom.left i j)) · dsimp ext ij rcases ij with ⟨i, j⟩ simpa [SheafConditionEqualizerProducts.rightRes] using c.π.naturality (Quiver.Hom.op (Hom.right i j)) · dsimp ext simp } section /-- Implementation of `SheafConditionPairwiseIntersections.coneEquiv`. -/ @[simps!] def coneEquivFunctor : Limits.Cone ((diagram U).op ⋙ F) ⥤ Limits.Cone (SheafConditionEqualizerProducts.diagram F U) where obj c := coneEquivFunctorObj F U c map {c c'} f := { hom := f.hom w := fun j => by cases j <;> · dsimp ext simp } end /-- Implementation of `SheafConditionPairwiseIntersections.coneEquiv`. -/ @[simps] def coneEquivInverseObj (c : Limits.Cone (SheafConditionEqualizerProducts.diagram F U)) : Limits.Cone ((diagram U).op ⋙ F) where pt := c.pt π := { app := by intro x induction x with | op x => ?_ rcases x with (⟨i⟩ | ⟨i, j⟩) · exact c.π.app WalkingParallelPair.zero ≫ Pi.π _ i · exact c.π.app WalkingParallelPair.one ≫ Pi.π _ (i, j) naturality := by intro x y f induction x with | op x => ?_ induction y with | op y => ?_ have ef : f = f.unop.op := rfl revert ef generalize f.unop = f' rintro rfl rcases x with (⟨i⟩ | ⟨⟩) <;> rcases y with (⟨⟩ | ⟨j, j⟩) <;> rcases f' with ⟨⟩ · dsimp rw [F.map_id] simp · dsimp simp only [Category.id_comp, Category.assoc] have h := c.π.naturality WalkingParallelPairHom.left dsimp [SheafConditionEqualizerProducts.leftRes] at h simp only [Category.id_comp] at h have h' := h =≫ Pi.π _ (i, j) rw [h'] simp only [Category.assoc, limit.lift_π, Fan.mk_π_app] rfl · dsimp simp only [Category.id_comp, Category.assoc] have h := c.π.naturality WalkingParallelPairHom.right dsimp [SheafConditionEqualizerProducts.rightRes] at h simp only [Category.id_comp] at h have h' := h =≫ Pi.π _ (j, i) rw [h'] simp rfl · dsimp rw [F.map_id] simp } /-- Implementation of `SheafConditionPairwiseIntersections.coneEquiv`. -/ @[simps!] def coneEquivInverse : Limits.Cone (SheafConditionEqualizerProducts.diagram F U) ⥤ Limits.Cone ((diagram U).op ⋙ F) where obj c := coneEquivInverseObj F U c map {c c'} f := { hom := f.hom w := by intro x induction x with | op x => ?_ rcases x with (⟨i⟩ | ⟨i, j⟩) · dsimp dsimp only [Fork.ι] rw [← f.w WalkingParallelPair.zero, Category.assoc] · dsimp rw [← f.w WalkingParallelPair.one, Category.assoc] } /-- Implementation of `SheafConditionPairwiseIntersections.coneEquiv`. -/ @[simps] def coneEquivUnitIsoApp (c : Cone ((diagram U).op ⋙ F)) : (𝟭 (Cone ((diagram U).op ⋙ F))).obj c ≅ (coneEquivFunctor F U ⋙ coneEquivInverse F U).obj c where hom := { hom := 𝟙 _ w := fun j => by induction j with | op j => ?_ rcases j with ⟨⟩ <;> · dsimp [coneEquivInverse] simp only [Limits.Fan.mk_π_app, Category.id_comp, Limits.limit.lift_π] } inv := { hom := 𝟙 _ w := fun j => by induction j with | op j => ?_ rcases j with ⟨⟩ <;> · dsimp [coneEquivInverse] simp only [Limits.Fan.mk_π_app, Category.id_comp, Limits.limit.lift_π] } /-- Implementation of `SheafConditionPairwiseIntersections.coneEquiv`. -/ @[simps!] def coneEquivUnitIso : 𝟭 (Limits.Cone ((diagram U).op ⋙ F)) ≅ coneEquivFunctor F U ⋙ coneEquivInverse F U := NatIso.ofComponents (coneEquivUnitIsoApp F U) /-- Implementation of `SheafConditionPairwiseIntersections.coneEquiv`. -/ @[simps!] def coneEquivCounitIso : coneEquivInverse F U ⋙ coneEquivFunctor F U ≅ 𝟭 (Limits.Cone (SheafConditionEqualizerProducts.diagram F U)) := NatIso.ofComponents (fun c => { hom := { hom := 𝟙 _ w := by rintro ⟨_ | _⟩ · dsimp ext simp · dsimp ext simp } inv := { hom := 𝟙 _ w := by rintro ⟨_ | _⟩ · dsimp ext simp · dsimp ext simp } }) fun {c d} f => by ext dsimp simp only [Category.comp_id, Category.id_comp] /-- Cones over `diagram U ⋙ F` are the same as a cones over the usual sheaf condition equalizer diagram. -/ @[simps] def coneEquiv : Limits.Cone ((diagram U).op ⋙ F) ≌ Limits.Cone (SheafConditionEqualizerProducts.diagram F U) where functor := coneEquivFunctor F U inverse := coneEquivInverse F U unitIso := coneEquivUnitIso F U counitIso := coneEquivCounitIso F U /-- If `SheafConditionEqualizerProducts.fork` is an equalizer, then `F.mapCone (cone U)` is a limit cone. -/ def isLimitMapConeOfIsLimitSheafConditionFork (P : IsLimit (SheafConditionEqualizerProducts.fork F U)) : IsLimit (F.mapCone (cocone U).op) := IsLimit.ofIsoLimit ((IsLimit.ofConeEquiv (coneEquiv F U).symm).symm P) { hom := { hom := 𝟙 _ w := by intro x induction x with | op x => ?_ rcases x with ⟨⟩ · simp rfl · dsimp [coneEquivInverse, SheafConditionEqualizerProducts.res, SheafConditionEqualizerProducts.leftRes] simp only [limit.lift_π, limit.lift_π_assoc, Category.id_comp, Fan.mk_π_app, Category.assoc] rw [← F.map_comp] rfl } inv := { hom := 𝟙 _ w := by intro x induction x with | op x => ?_ rcases x with ⟨⟩ · simp rfl · dsimp [coneEquivInverse, SheafConditionEqualizerProducts.res, SheafConditionEqualizerProducts.leftRes] simp only [limit.lift_π, limit.lift_π_assoc, Category.id_comp, Fan.mk_π_app, Category.assoc] rw [← F.map_comp] rfl } } /-- If `F.mapCone (cone U)` is a limit cone, then `SheafConditionEqualizerProducts.fork` is an equalizer. -/ def isLimitSheafConditionForkOfIsLimitMapCone (Q : IsLimit (F.mapCone (cocone U).op)) : IsLimit (SheafConditionEqualizerProducts.fork F U) := IsLimit.ofIsoLimit ((IsLimit.ofConeEquiv (coneEquiv F U)).symm Q) { hom := { hom := 𝟙 _ w := by rintro ⟨⟩ · simp rfl · dsimp ext dsimp [coneEquivInverse, SheafConditionEqualizerProducts.res, SheafConditionEqualizerProducts.leftRes] simp only [limit.lift_π, limit.lift_π_assoc, Category.id_comp, Fan.mk_π_app, Category.assoc] rw [← F.map_comp] rfl } inv := { hom := 𝟙 _ w := by rintro ⟨⟩ · simp rfl · dsimp ext dsimp [coneEquivInverse, SheafConditionEqualizerProducts.res, SheafConditionEqualizerProducts.leftRes] simp only [limit.lift_π, limit.lift_π_assoc, Category.id_comp, Fan.mk_π_app, Category.assoc] rw [← F.map_comp] rfl } } end SheafConditionPairwiseIntersections open SheafConditionPairwiseIntersections /-- The sheaf condition in terms of an equalizer diagram is equivalent to the default sheaf condition. -/ theorem isSheaf_iff_isSheafEqualizerProducts (F : Presheaf C X) : F.IsSheaf ↔ F.IsSheafEqualizerProducts := (isSheaf_iff_isSheafPairwiseIntersections F).trans <| Iff.intro (fun h _ U => ⟨isLimitSheafConditionForkOfIsLimitMapCone F U (h U).some⟩) fun h _ U => ⟨isLimitMapConeOfIsLimitSheafConditionFork F U (h U).some⟩ end Presheaf end TopCat
.lake/packages/mathlib/Mathlib/Mathport/README.md
Mathport prelude === This directory used to contain instructions for `mathport`, helping it to translate `mathlib` and align declarations and tactics with `mathlib4`. If you still need to use mathport, you will need to move back to the `v3-eol` tag of mathlib, which still contains mathport infrastructure, and migrate your project to that tag, and then upgrade the rest of the way. (That tag also contains the final form of `Syntax.lean`, which implicitly contained a TODO list of unported tactics from Lean 3, which may still be of some interest.)
.lake/packages/mathlib/Mathlib/Lean/EnvExtension.lean
import Mathlib.Init import Lean.ScopedEnvExtension /-! # Helper function for environment extensions and attributes. -/ open Lean instance {σ : Type} [Inhabited σ] : Inhabited (ScopedEnvExtension.State σ) := ⟨{state := default}⟩
.lake/packages/mathlib/Mathlib/Lean/LocalContext.lean
import Mathlib.Init import Lean.LocalContext /-! # Additional methods about `LocalContext` -/ namespace Lean.LocalContext universe u v variable {m : Type u → Type v} [Monad m] [Alternative m] variable {β : Type u} /-- Return the result of `f` on the first local declaration on which `f` succeeds. -/ @[specialize] def firstDeclM (lctx : LocalContext) (f : LocalDecl → m β) : m β := do match (← lctx.findDeclM? (optional ∘ f)) with | none => failure | some b => pure b /-- Return the result of `f` on the last local declaration on which `f` succeeds. -/ @[specialize] def lastDeclM (lctx : LocalContext) (f : LocalDecl → m β) : m β := do match (← lctx.findDeclRevM? (optional ∘ f)) with | none => failure | some b => pure b end Lean.LocalContext
.lake/packages/mathlib/Mathlib/Lean/Json.lean
import Mathlib.Init /-! # Json serialization typeclass for `PUnit` & `Fin n` & `Subtype p` -/ universe u namespace Lean deriving instance FromJson, ToJson for PUnit -- See https://github.com/leanprover/lean4/issues/10295 attribute [nolint unusedArguments] Lean.instToJsonPUnit_mathlib.toJson instance {n : Nat} : FromJson (Fin n) where fromJson? j := do let i : Nat ← fromJson? j if h : i < n then return ⟨i, h⟩ else throw s!"must be less than {n}" instance {n : Nat} : ToJson (Fin n) where toJson i := toJson i.val instance {α : Type u} [FromJson α] (p : α → Prop) [DecidablePred p] : FromJson (Subtype p) where fromJson? j := do let i : α ← fromJson? j if h : p i then return ⟨i, h⟩ else throw "condition does not hold" instance {α : Type u} [ToJson α] (p : α → Prop) : ToJson (Subtype p) where toJson x := toJson x.val end Lean
.lake/packages/mathlib/Mathlib/Lean/Exception.lean
import Mathlib.Init import Lean.Exception /-! # Additional methods for working with `Exception`s This file contains two additional methods for working with `Exception`s * `successIfFail`, a generalisation of `fail_if_success` to arbitrary `MonadError`s * `isFailedToSynthesize`: check if an exception is of the "failed to synthesize" form -/ open Lean /-- A generalisation of `fail_if_success` to an arbitrary `MonadError`. -/ def successIfFail {α : Type} {M : Type → Type} [MonadError M] [Monad M] (m : M α) : M Exception := do match ← tryCatch (m *> pure none) (pure ∘ some) with | none => throwError "Expected an exception." | some ex => return ex namespace Lean namespace Exception /-- Check if an exception is a "failed to synthesize" exception. These exceptions are raised in several different places, and the only commonality is the prefix of the string, so that's what we look for. -/ def isFailedToSynthesize (e : Exception) : IO Bool := do pure <| (← e.toMessageData.toString).startsWith "failed to synthesize" end Exception end Lean
.lake/packages/mathlib/Mathlib/Lean/CoreM.lean
import Mathlib.Init /-! # Additional functions using `CoreM` state. -/ open Lean Core /-- Run a `CoreM α` in a fresh `Environment` with specified `modules : List Name` imported. -/ def CoreM.withImportModules {α : Type} (modules : Array Name) (run : CoreM α) (searchPath : Option SearchPath := none) (options : Options := {}) (trustLevel : UInt32 := 0) (fileName := "") : IO α := unsafe do if let some sp := searchPath then searchPathRef.set sp Lean.withImportModules (modules.map ({ module := · })) options (trustLevel := trustLevel) fun env => let ctx := {fileName, options, fileMap := default} let state := {env} Prod.fst <$> (CoreM.toIO · ctx state) do run
.lake/packages/mathlib/Mathlib/Lean/Thunk.lean
import Mathlib.Init /-! # Basic facts about `Thunk`. -/ namespace Thunk @[simp] theorem get_pure {α} (x : α) : (Thunk.pure x).get = x := rfl @[simp] theorem get_mk {α} (f : Unit → α) : (Thunk.mk f).get = f () := rfl universe u v variable {α : Type u} {β : Type v} instance [DecidableEq α] : DecidableEq (Thunk α) := by intro a b have : a = b ↔ a.get = b.get := ⟨by intro x; rw [x], by intro; ext; assumption⟩ rw [this] infer_instance /-- The Cartesian product of two thunks. -/ def prod (a : Thunk α) (b : Thunk β) : Thunk (α × β) := Thunk.mk fun _ => (a.get, b.get) @[simp] theorem prod_get_fst {a : Thunk α} {b : Thunk β} : (prod a b).get.1 = a.get := rfl @[simp] theorem prod_get_snd {a : Thunk α} {b : Thunk β} : (prod a b).get.2 = b.get := rfl /-- The sum of two thunks. -/ def add [Add α] (a b : Thunk α) : Thunk α := Thunk.mk fun _ => a.get + b.get instance [Add α] : Add (Thunk α) := ⟨add⟩ @[simp] theorem add_get [Add α] {a b : Thunk α} : (a + b).get = a.get + b.get := rfl end Thunk
.lake/packages/mathlib/Mathlib/Lean/GoalsLocation.lean
import Mathlib.Init import Lean.Meta.Tactic.Util import Lean.SubExpr /-! This file defines some functions for dealing with `SubExpr.GoalsLocation`. -/ namespace Lean.SubExpr.GoalsLocation /-- The root expression of the position specified by the `GoalsLocation`. -/ def rootExpr : GoalsLocation → MetaM Expr | ⟨_, .hyp fvarId⟩ => do instantiateMVars (← fvarId.getType) | ⟨_, .hypType fvarId _⟩ => do instantiateMVars (← fvarId.getType) | ⟨_, .hypValue fvarId _⟩ => do instantiateMVars (← fvarId.getDecl).value | ⟨mvarId, .target _⟩ => do instantiateMVars (← mvarId.getType) /-- The `SubExpr.Pos` specified by the `GoalsLocation`. -/ def pos : GoalsLocation → Pos | ⟨_, .hyp _⟩ => .root | ⟨_, .hypType _ pos⟩ => pos | ⟨_, .hypValue _ pos⟩ => pos | ⟨_, .target pos⟩ => pos /-- The hypothesis specified by the `GoalsLocation`. -/ def fvarId? : GoalsLocation → Option FVarId | ⟨_, .hyp fvarId⟩ => fvarId | ⟨_, .hypType fvarId _⟩ => fvarId | ⟨_, .hypValue fvarId _⟩ => fvarId | ⟨_, .target _⟩ => none end Lean.SubExpr.GoalsLocation
.lake/packages/mathlib/Mathlib/Lean/Meta.lean
import Mathlib.Init import Lean.Elab.Term import Lean.Elab.Tactic.Basic import Lean.Meta.Tactic.Assert import Lean.Meta.Tactic.Clear import Batteries.CodeAction -- to enable the hole code action /-! ## Additional utilities in `Lean.MVarId` -/ open Lean Meta namespace Lean.MVarId /-- Add the hypothesis `h : t`, given `v : t`, and return the new `FVarId`. -/ def «let» (g : MVarId) (h : Name) (v : Expr) (t : Option Expr := none) : MetaM (FVarId × MVarId) := do (← g.define h (← t.getDM (inferType v)) v).intro1P /-- Has the effect of `refine ⟨e₁,e₂,⋯, ?_⟩`. -/ def existsi (mvar : MVarId) (es : List Expr) : MetaM MVarId := do es.foldlM (fun mv e ↦ do let (subgoals,_) ← Elab.Term.TermElabM.run <| Elab.Tactic.run mv do Elab.Tactic.evalTactic (← `(tactic| refine ⟨?_,?_⟩)) let [sg1, sg2] := subgoals | throwError "expected two subgoals" sg1.assign e pure sg2) mvar /-- Applies `intro` repeatedly until it fails. We use this instead of `Lean.MVarId.intros` to allowing unfolding. For example, if we want to do introductions for propositions like `¬p`, the `¬` needs to be unfolded into `→ False`, and `intros` does not do such unfolding. -/ partial def intros! (mvarId : MVarId) : MetaM (Array FVarId × MVarId) := run #[] mvarId where /-- Implementation of `intros!`. -/ run (acc : Array FVarId) (g : MVarId) := try let ⟨f, g⟩ ← mvarId.intro1 run (acc.push f) g catch _ => pure (acc, g) end Lean.MVarId namespace Lean.Meta /-- Get the type the given metavariable after instantiating metavariables and cleaning up annotations. -/ def _root_.Lean.MVarId.getType'' (mvarId : MVarId) : MetaM Expr := return (← instantiateMVars (← mvarId.getType)).cleanupAnnotations end Lean.Meta namespace Lean.Elab.Tactic /-- Analogue of `liftMetaTactic` for tactics that return a single goal. -/ -- I'd prefer to call that `liftMetaTactic1`, -- but that is taken in core by a function that lifts a `tac : MVarId → MetaM (Option MVarId)`. def liftMetaTactic' (tac : MVarId → MetaM MVarId) : TacticM Unit := liftMetaTactic fun g => do pure [← tac g] variable {α : Type} @[inline] private def TacticM.runCore (x : TacticM α) (ctx : Context) (s : State) : TermElabM (α × State) := x ctx |>.run s @[inline] private def TacticM.runCore' (x : TacticM α) (ctx : Context) (s : State) : TermElabM α := Prod.fst <$> x.runCore ctx s /-- Copy of `Lean.Elab.Tactic.run` that can return a value. -/ -- We need this because Lean 4 core only provides `TacticM` functions for building simp contexts, -- making it quite painful to call `simp` from `MetaM`. def run_for (mvarId : MVarId) (x : TacticM α) : TermElabM (Option α × List MVarId) := mvarId.withContext do let pendingMVarsSaved := (← get).pendingMVars modify fun s => { s with pendingMVars := [] } let aux : TacticM (Option α × List MVarId) := /- Important: the following `try` does not backtrack the state. This is intentional because we don't want to backtrack the error message when we catch the "abort internal exception" We must define `run` here because we define `MonadExcept` instance for `TacticM` -/ try let a ← x pure (a, ← getUnsolvedGoals) catch ex => if isAbortTacticException ex then pure (none, ← getUnsolvedGoals) else throw ex try aux.runCore' { elaborator := .anonymous } { goals := [mvarId] } finally modify fun s => { s with pendingMVars := pendingMVarsSaved } end Lean.Elab.Tactic
.lake/packages/mathlib/Mathlib/Lean/Message.lean
import Lean.Message import Mathlib.Tactic.Linter.DeprecatedModule deprecated_module (since := "2025-08-18")
.lake/packages/mathlib/Mathlib/Lean/ContextInfo.lean
import Mathlib.Lean.Elab.Tactic.Meta -- Import this linter explicitly to ensure that -- this file has a valid copyright header and module docstring. import Mathlib.Tactic.Linter.Header /-! # Executing actions using the infotree This file contains helper functions for running `CoreM`, `MetaM` and tactic actions in the context of an infotree node. -/ open Lean Elab Term Command Linter namespace Lean.Elab.ContextInfo variable {α} /-- Embeds a `CoreM` action in `CommandElabM` by supplying the information stored in `info`. Copy of `ContextInfo.runCoreM` that makes use of the `CommandElabM` context for: * logging messages produced by the `CoreM` action, * metavariable generation, * auxiliary declaration generation. -/ def runCoreMWithMessages (info : ContextInfo) (x : CoreM α) : CommandElabM α := do -- We assume that this function is used only outside elaboration, mostly in the language server, -- and so we can and should provide access to information regardless whether it is exported. let env := info.env.setExporting false let ctx ← read /- We must execute `x` using the `ngen` stored in `info`. Otherwise, we may create `MVarId`s and `FVarId`s that have been used in `lctx` and `info.mctx`. Similarly, we need to pass in a `namePrefix` because otherwise we can't create auxiliary definitions. -/ let (x, newState) ← (withOptions (fun _ => info.options) x).toIO { currNamespace := info.currNamespace, openDecls := info.openDecls fileName := ctx.fileName, fileMap := ctx.fileMap } { env, ngen := info.ngen, auxDeclNGen := { namePrefix := info.parentDecl?.getD .anonymous } } -- Migrate logs back to the main context. modify fun state => { state with messages := state.messages ++ newState.messages, traceState.traces := state.traceState.traces ++ newState.traceState.traces } return x /-- Embeds a `MetaM` action in `CommandElabM` by supplying the information stored in `info`. Copy of `ContextInfo.runMetaM` that makes use of the `CommandElabM` context for: * message logging (messages produced by the `CoreM` action are migrated back), * metavariable generation, * auxiliary declaration generation, * local instances. -/ def runMetaMWithMessages (info : ContextInfo) (lctx : LocalContext) (x : MetaM α) : CommandElabM α := do (·.1) <$> info.runCoreMWithMessages (Lean.Meta.MetaM.run (ctx := { lctx := lctx }) (s := { mctx := info.mctx }) <| -- Update the local instances, otherwise typeclass search would fail to see anything in the -- local context. Meta.withLocalInstances (lctx.decls.toList.filterMap id) <| x) /-- Run a tactic computation in the context of an infotree node. -/ def runTactic (ctx : ContextInfo) (i : TacticInfo) (goal : MVarId) (x : MVarId → MetaM α) : CommandElabM α := do if !i.goalsBefore.contains goal then panic!"ContextInfo.runTactic: `goal` must be an element of `i.goalsBefore`" let mctx := i.mctxBefore let lctx := (mctx.decls.find! goal).2 ctx.runMetaMWithMessages lctx <| do -- Make a fresh metavariable because the original goal is already assigned. let type ← goal.getType let goal ← Meta.mkFreshExprSyntheticOpaqueMVar type x goal.mvarId! /-- Run tactic code, given by a piece of syntax, in the context of an infotree node. The optional `MetaM` argument `m` performs postprocessing on the goals produced. -/ def runTacticCode (ctx : ContextInfo) (i : TacticInfo) (goal : MVarId) (code : Syntax) (m : Σ α : Type, MVarId → MetaM α := ⟨MVarId, pure⟩) : CommandElabM (List m.1) := do let termCtx ← liftTermElabM read let termState ← liftTermElabM get ctx.runTactic i goal fun goal => do let newGoals ← Lean.Elab.runTactic' (ctx := termCtx) (s := termState) goal code newGoals.mapM m.2 end Lean.Elab.ContextInfo
.lake/packages/mathlib/Mathlib/Lean/Expr.lean
import Mathlib.Lean.Expr.Basic import Mathlib.Lean.Expr.ReplaceRec
.lake/packages/mathlib/Mathlib/Lean/Name.lean
import Mathlib.Init import Lean.Meta.Match.MatcherInfo import Lean.Meta.Tactic.Delta import Std.Data.HashMap.Basic /-! # Additional functions on `Lean.Name`. We provide `allNames` and `allNamesByModule`. -/ open Lean Meta Elab private def isBlackListed (declName : Name) : CoreM Bool := do if declName.toString.startsWith "Lean" then return true let env ← getEnv pure <| declName.isInternalDetail || isAuxRecursor env declName || isNoConfusion env declName <||> isRec declName <||> isMatcher declName /-- Retrieve all names in the environment satisfying a predicate. -/ def allNames (p : Name → Bool) : CoreM (Array Name) := do (← getEnv).constants.foldM (init := #[]) fun names n _ => do if p n && !(← isBlackListed n) then return names.push n else return names /-- Retrieve all names in the environment satisfying a predicate, gathered together into a `HashMap` according to the module they are defined in. -/ def allNamesByModule (p : Name → Bool) : CoreM (Std.HashMap Name (Array Name)) := do (← getEnv).constants.foldM (init := ∅) fun names n _ => do if p n && !(← isBlackListed n) then let some m ← findModuleOf? n | return names -- TODO use `modify` and/or `alter` when available match names[m]? with | some others => return names.insert m (others.push n) | none => return names.insert m #[n] else return names /-- Decapitalize the last component of a name. -/ def Lean.Name.decapitalize (n : Name) : Name := n.modifyBase fun | .str p s => .str p s.decapitalize | n => n /-- Whether the lemma has a name of the form produced by `Lean.Meta.mkAuxLemma`. -/ def Lean.Name.isAuxLemma (n : Name) : Bool := match n with -- `mkAuxLemma` generally allows for arbitrary prefixes but these are the ones produced by core. | .str _ s => "_proof_".isPrefixOf s || "_simp_".isPrefixOf s | _ => false /-- Unfold all lemmas created by `Lean.Meta.mkAuxLemma`. -/ def Lean.Meta.unfoldAuxLemmas (e : Expr) : MetaM Expr := do deltaExpand e Lean.Name.isAuxLemma
.lake/packages/mathlib/Mathlib/Lean/PrettyPrinter/Delaborator.lean
import Mathlib.Init import Lean.PrettyPrinter.Delaborator.Basic /-! # Additions to the delaborator -/ namespace Lean.PrettyPrinter.Delaborator open SubExpr /-- Assuming the current expression in a lambda or pi, descend into the body using an unused name generated from the binder's name. Provides `d` with both `Syntax` for the bound name as an identifier as well as the fresh fvar for the bound variable. See also `Lean.PrettyPrinter.Delaborator.withBindingBodyUnusedName`. -/ def withBindingBodyUnusedName' {α} (d : Syntax → Expr → DelabM α) : DelabM α := do let n ← getUnusedName (← getExpr).bindingName! (← getExpr).bindingBody! withBindingBody' n (fun fvar => return (← mkAnnotatedIdent n fvar, fvar)) (fun (stxN, fvar) => d stxN fvar) /-- Update `OptionsPerPos` at the given position, setting the key `n` to have the Boolean value `v`. -/ def OptionsPerPos.setBool (opts : OptionsPerPos) (p : SubExpr.Pos) (n : Name) (v : Bool) : OptionsPerPos := let e := opts.getD p {} |>.setBool n v opts.insert p e /-- Annotates `stx` with the go-to-def information of `target`. -/ def annotateGoToDef (stx : Term) (target : Name) : DelabM Term := do let module := (← findModuleOf? target).getD (← getEnv).mainModule let some range ← findDeclarationRanges? target | return stx let stx ← annotateCurPos stx let location := { module, range := range.selectionRange } addDelabTermInfo (← getPos) stx (← getExpr) (location? := some location) return stx /-- Annotates `stx` with the go-to-def information of the notation used in `stx`. -/ def annotateGoToSyntaxDef (stx : Term) : DelabM Term := do annotateGoToDef stx stx.raw.getKind end Lean.PrettyPrinter.Delaborator
.lake/packages/mathlib/Mathlib/Lean/Meta/KAbstractPositions.lean
import Mathlib.Init import Lean.HeadIndex import Lean.Meta.ExprLens import Lean.Meta.Check /-! # Find the positions of a pattern in an expression This file defines some tools for dealing with subexpressions and occurrence numbers. This is used for creating a `rw` tactic call that rewrites a selected expression. `viewKAbstractSubExpr` takes an expression and a position in the expression, and returns the subexpression together with an optional occurrence number that would be required to find the subexpression using `kabstract` (which is what `rw` uses to find the position of the rewrite) `rw` can fail if the motive is not type correct. `kabstractIsTypeCorrect` checks whether this is the case. -/ namespace Lean.Meta /-- Return the positions that `kabstract` would abstract for pattern `p` in expression `e`. i.e. the positions that unify with `p`. -/ def kabstractPositions (p e : Expr) : MetaM (Array SubExpr.Pos) := do let e ← instantiateMVars e let mctx ← getMCtx let pHeadIdx := p.toHeadIndex let pNumArgs := p.headNumArgs let rec /-- The main loop that loops through all subexpressions -/ visit (e : Expr) (pos : SubExpr.Pos) (positions : Array SubExpr.Pos) : MetaM (Array SubExpr.Pos) := do let visitChildren : Array SubExpr.Pos → MetaM (Array SubExpr.Pos) := match e with | .app fn arg => visit fn pos.pushAppFn >=> visit arg pos.pushAppArg | .mdata _ expr => visit expr pos | .proj _ _ struct => visit struct pos.pushProj | .letE _ type value body _ => visit type pos.pushLetVarType >=> visit value pos.pushLetValue >=> visit body pos.pushLetBody | .lam _ binderType body _ => visit binderType pos.pushBindingDomain >=> visit body pos.pushBindingBody | .forallE _ binderType body _ => visit binderType pos.pushBindingDomain >=> visit body pos.pushBindingBody | _ => pure if e.hasLooseBVars then visitChildren positions else if e.toHeadIndex != pHeadIdx || e.headNumArgs != pNumArgs then visitChildren positions else if ← isDefEq e p then setMCtx mctx -- reset the `MetavarContext` because `isDefEq` can modify it if it succeeds visitChildren (positions.push pos) else visitChildren positions visit e .root #[] /-- Return the subexpression at position `pos` in `e` together with an occurrence number that allows the expression to be found by `kabstract`. Return `none` when the subexpression contains loose bound variables. -/ def viewKAbstractSubExpr (e : Expr) (pos : SubExpr.Pos) : MetaM (Option (Expr × Option Nat)) := do let subExpr ← Core.viewSubexpr pos e if subExpr.hasLooseBVars then return none let positions ← kabstractPositions subExpr e let some n := positions.idxOf? pos | unreachable! return some (subExpr, if positions.size == 1 then none else some (n + 1)) /-- Determine whether the result of abstracting `subExpr` from `e` at position `pos` results in a well-typed expression. This is important if you want to rewrite at this position. Here is an example of what goes wrong with an ill-typed kabstract result: ``` example (h : [5] ≠ []) : List.getLast [5] h = 5 := by rw [show [5] = [5] from rfl] -- tactic 'rewrite' failed, motive is not type correct ``` -/ def kabstractIsTypeCorrect (e subExpr : Expr) (pos : SubExpr.Pos) : MetaM Bool := do withLocalDeclD `_a (← inferType subExpr) fun fvar => do isTypeCorrect (← replaceSubexpr (fun _ => pure fvar) pos e) end Lean.Meta
.lake/packages/mathlib/Mathlib/Lean/Meta/Basic.lean
import Mathlib.Init import Lean.Meta.AppBuilder import Lean.Meta.Basic /-! # Additions to `Lean.Meta.Basic` Likely these already exist somewhere. Pointers welcome. -/ /-- Restore the metavariable context after execution. -/ def Lean.Meta.preservingMCtx {α : Type} (x : MetaM α) : MetaM α := do let mctx ← getMCtx try x finally setMCtx mctx open Lean Meta /-- This function is similar to `forallMetaTelescopeReducing`: Given `e` of the form `forall ..xs, A`, this combinator will create a new metavariable for each `x` in `xs` until it reaches an `x` whose type is defeq to `t`, and instantiate `A` with these, while also reducing `A` if needed. It uses `forallMetaTelescopeReducing`. This function returns a triple `(mvs, bis, out)` where - `mvs` is an array containing the new metavariables. - `bis` is an array containing the binder infos for the `mvs`. - `out` is `e` but instantiated with the `mvs`. -/ def Lean.Meta.forallMetaTelescopeReducingUntilDefEq (e t : Expr) (kind : MetavarKind := MetavarKind.natural) : MetaM (Array Expr × Array BinderInfo × Expr) := do let (ms, bs, tp) ← forallMetaTelescopeReducing e (some 1) kind unless ms.size == 1 do if ms.size == 0 then throwError m!"Failed: {← ppExpr e} is not the type of a function." else throwError m!"Failed" let mut mvs := ms let mut bis := bs let mut out : Expr := tp while !(← isDefEq (← inferType mvs.toList.getLast!) t) do let (ms, bs, tp) ← forallMetaTelescopeReducing out (some 1) kind unless ms.size == 1 do throwError m!"Failed to find {← ppExpr t} as the type of a parameter of {← ppExpr e}." mvs := mvs ++ ms bis := bis ++ bs out := tp return (mvs, bis, out) /-- `pureIsDefEq e₁ e₂` is short for `withNewMCtxDepth <| isDefEq e₁ e₂`. Determines whether two expressions are definitionally equal to each other when metavariables are not assignable. -/ @[inline] def Lean.Meta.pureIsDefEq (e₁ e₂ : Expr) : MetaM Bool := withNewMCtxDepth <| isDefEq e₁ e₂ /-- `mkRel n lhs rhs` is `mkAppM n #[lhs, rhs]`, but with optimizations for `Eq` and `Iff`. -/ def Lean.Meta.mkRel (n : Name) (lhs rhs : Expr) : MetaM Expr := if n == ``Eq then mkEq lhs rhs else if n == ``Iff then return mkApp2 (.const ``Iff []) lhs rhs else mkAppM n #[lhs, rhs] /-- Given a metavariable `inst` whose type is a class, tries to synthesize the instance then runs `k`. If synthesis fails, then runs `k` with `inst` as a local instance and then substitutes `inst` into the resulting expression. Example: `reassocExprHom` operates by applying simp lemmas that assume a `Category` instance. The category might not yet be known, which can prevent simp lemmas from applying. We can add `inst` as a local instance to deal with this. However, if the instance is synthesizable, we prefer running `k` directly so that the local instance doesn't affect typeclass inference. -/ def Lean.Meta.withEnsuringLocalInstance {α : Type} (inst : MVarId) (k : MetaM (Expr × α)) : MetaM (Expr × α) := do let instE := mkMVar inst match ← trySynthInstance (← inferType instE) with | .some e => unless ← isDefEq instE e do throwError "failed to assign synthesized type class instance {indentExpr e}\n\ to{indentExpr instE}" k | _ => withLetDecl `inst (← inferType instE) instE fun inst' => do let (e, v) ← k let e' := (← e.abstractM #[inst']).instantiate1 instE return (e', v) /-- Checks that `e` has type `expectedType` (i.e. that its type is defeq to `expectedType` at the current transparency). If not, coerces `e` to this type or fails with a descriptive error. -/ def Lean.Meta.ensureHasType (e expectedType : Expr) : MetaM Expr := do let ty ← inferType e if ← withNewMCtxDepth (isDefEq ty expectedType) then return e else (← coerceSimple? e expectedType).toOption.getDM <| throwError "Expected{indentD e}\nto have type{indentD ty}\n or to be coercible to it" /-- Checks that `e` is a function (i.e. that its type is a `.forallE` after `instantiateMVars` and `whnf`). If not, coerces `e` to a function or fails with a descriptive error. -/ def Lean.Meta.ensureIsFunction (e : Expr) : MetaM Expr := do let ty ← whnf <| ← instantiateMVars <| ← inferType e if ty.isForall then return e else (← coerceToFunction? e).getDM <| throwError "Expected{indentD e}\nof type{indentD ty}\nto be a function, or to be coercible to \ a function" /-- Checks that `e` is a type (i.e. that its type is a `Sort` after `instantiateMVars` and `whnf`). If not, coerces `e` to a Sort or fails with a descriptive error. -/ def Lean.Meta.ensureIsSort (e : Expr) : MetaM Expr := do let ty ← whnf <| ← instantiateMVars <| ← inferType e if ty.isSort then return e else (← coerceToSort? e).getDM <| throwError "Expected{indentD e}\nof type{indentD ty}\nto be a Sort, or to be coercible to \ a Sort"
.lake/packages/mathlib/Mathlib/Lean/Meta/Simp.lean
import Mathlib.Init import Lean.Elab.Tactic.Simp /-! # Helper functions for using the simplifier. [TODO] Needs documentation, cleanup, and possibly reunification of `mkSimpContext'` with core. -/ open Lean Elab.Tactic def Lean.PHashSet.toList.{u} {α : Type u} [BEq α] [Hashable α] (s : Lean.PHashSet α) : List α := s.1.toList.map (·.1) namespace Lean namespace Meta.Simp open Elab.Tactic instance : ToFormat SimpTheorems where format s := f!"pre: {s.pre.values.toList} post: {s.post.values.toList} lemmaNames: {s.lemmaNames.toList.map (·.key)} toUnfold: {s.toUnfold.toList} erased: {s.erased.toList.map (·.key)} toUnfoldThms: {s.toUnfoldThms.toList}" /-- Constructs a proof that the original expression is true given a simp result which simplifies the target to `True`. -/ def Result.ofTrue (r : Simp.Result) : MetaM (Option Expr) := if r.expr.isConstOf ``True then some <$> match r.proof? with | some proof => mkOfEqTrue proof | none => pure (mkConst ``True.intro) else pure none /-- Return all propositions in the local context. -/ def getPropHyps : MetaM (Array FVarId) := do let mut result := #[] for localDecl in (← getLCtx) do unless localDecl.isAuxDecl do if (← isProp localDecl.type) then result := result.push localDecl.fvarId return result end Simp /-- Construct a `SimpTheorems` from a list of names. -/ def simpTheoremsOfNames (lemmas : List Name := []) (simpOnly : Bool := false) : MetaM SimpTheorems := do lemmas.foldlM (·.addConst ·) (← if simpOnly then simpOnlyBuiltins.foldlM (·.addConst ·) {} else getSimpTheorems) -- TODO We need to write a `mkSimpContext` in `MetaM` -- that supports all the bells and whistles in `simp`. -- It should generalize this, and another partial implementation in `Tactic.Simps.Basic`. /-- Construct a `Simp.Context` from a list of names. -/ def Simp.Context.ofNames (lemmas : List Name := []) (simpOnly : Bool := false) (config : Simp.Config := {}) : MetaM Simp.Context := do Simp.mkContext config (simpTheorems := #[← simpTheoremsOfNames lemmas simpOnly]) (congrTheorems := ← Lean.Meta.getSimpCongrTheorems) -- adapted from `Lean.Elab.Tactic.mkSimpContext` /-- Construct a `Simp.Context`, following the same algorithm that would be done in a "simp" run: look up all the simp-lemmas in the library, and adjust (add/erase) as specified by the provided `simpArgs` list. -/ def Simp.Context.ofArgs (args : TSyntax ``Parser.Tactic.simpArgs) (config : Simp.Config := {}) : TacticM Simp.Context := do let simpTheorems ← Meta.getSimpTheorems let congrTheorems ← Meta.getSimpCongrTheorems let ctx ← Simp.mkContext config (simpTheorems := #[simpTheorems]) congrTheorems let r ← elabSimpArgs args (eraseLocal := false) (kind := SimpKind.simp) (simprocs := {}) ctx return r.ctx /-- Simplify an expression using only a list of lemmas specified by name. -/ def simpOnlyNames (lemmas : List Name) (e : Expr) (config : Simp.Config := {}) : MetaM Simp.Result := do (·.1) <$> simp e (← Simp.Context.ofNames lemmas true config) /-- Given a simplifier `S : Expr → MetaM Simp.Result`, and an expression `e : Expr`, run `S` on the type of `e`, and then convert `e` into that simplified type, using a combination of type hints as well as casting if the proof is not definitional `Eq.mp`. The optional argument `type?`, if present, must be definitionally equal to the type of `e`. When it is specified we simplify this type rather than the inferred type of `e`. -/ def simpType (S : Expr → MetaM Simp.Result) (e : Expr) (type? : Option Expr := none) : MetaM Expr := do let type ← type?.getDM (inferType e) match ← S type with | ⟨ty', none, _⟩ => mkExpectedTypeHint e ty' -- We use `mkExpectedTypeHint` in this branch as well, in order to preserve the binder types. | ⟨ty', some prf, _⟩ => mkExpectedTypeHint (← mkEqMP prf e) ty' /-- Independently simplify both the left-hand side and the right-hand side of an equality. The equality is allowed to be under binders. Returns the simplified equality and a proof of it. -/ def simpEq (S : Expr → MetaM Simp.Result) (type pf : Expr) : MetaM (Expr × Expr) := do forallTelescope type fun fvars type => do let .app (.app (.app (.const `Eq [u]) α) lhs) rhs := type | throwError "simpEq expecting Eq" let ⟨lhs', lhspf?, _⟩ ← S lhs let ⟨rhs', rhspf?, _⟩ ← S rhs let mut pf' := mkAppN pf fvars if let some lhspf := lhspf? then pf' ← mkEqTrans (← mkEqSymm lhspf) pf' if let some rhspf := rhspf? then pf' ← mkEqTrans pf' rhspf let type' := mkApp3 (mkConst ``Eq [u]) α lhs' rhs' return (← mkForallFVars fvars type', ← mkLambdaFVars fvars pf') /-- Checks whether `declName` is in `SimpTheorems` as either a lemma or definition to unfold. -/ def SimpTheorems.contains (d : SimpTheorems) (declName : Name) := d.isLemma (.decl declName) || d.isDeclToUnfold declName /-- Tests whether `decl` has `simp`-attribute `simpAttr`. Returns `false` is `simpAttr` is not a valid simp-attribute. -/ def isInSimpSet (simpAttr decl : Name) : CoreM Bool := do let some simpDecl ← getSimpExtension? simpAttr | return false return (← simpDecl.getTheorems).contains decl /-- Returns all declarations with the `simp`-attribute `simpAttr`. Note: this also returns many auxiliary declarations. -/ def getAllSimpDecls (simpAttr : Name) : CoreM (List Name) := do let some simpDecl ← getSimpExtension? simpAttr | return [] let thms ← simpDecl.getTheorems return thms.toUnfold.toList ++ thms.lemmaNames.toList.filterMap fun | .decl decl => some decl | _ => none /-- Gets all simp-attributes given to declaration `decl`. -/ def getAllSimpAttrs (decl : Name) : CoreM (Array Name) := do let mut simpAttrs := #[] for (simpAttr, simpDecl) in (← simpExtensionMapRef.get).toList do if (← simpDecl.getTheorems).contains decl then simpAttrs := simpAttrs.push simpAttr return simpAttrs end Lean.Meta
.lake/packages/mathlib/Mathlib/Lean/Meta/CongrTheorems.lean
import Lean.Meta.Tactic.Cleanup import Lean.Meta.Tactic.Refl import Mathlib.Logic.IsEmpty /-! # Additions to `Lean.Meta.CongrTheorems` -/ namespace Lean.Meta initialize registerTraceClass `Meta.CongrTheorems /-- Generates a congruence lemma for a function `f` for `numArgs` of its arguments. The only `Lean.Meta.CongrArgKind` kinds that appear in such a lemma are `.eq`, `.heq`, and `.subsingletonInst`. The resulting lemma proves either an `Eq` or a `HEq` depending on whether the types of the LHS and RHS are equal or not. This function is a wrapper around `Lean.Meta.mkHCongrWithArity`. It transforms the resulting congruence lemma by trying to automatically prove hypotheses using subsingleton lemmas, and if they are so provable they are recorded with `.subsingletonInst`. Note that this is slightly abusing `.subsingletonInst` since (1) the argument might not be for a `Decidable` instance and (2) the argument might not even be an instance. -/ def mkHCongrWithArity' (f : Expr) (numArgs : Nat) : MetaM CongrTheorem := do let thm ← mkHCongrWithArity f numArgs process thm thm.type thm.argKinds.toList #[] #[] #[] #[] where /-- Process the congruence theorem by trying to pre-prove arguments using `prove`. - `cthm` is the original `CongrTheorem`, modified only after visiting every argument. - `type` is type of the congruence theorem, after all the parameters so far have been applied. - `argKinds` is the list of `CongrArgKind`s, which this function recurses on. - `argKinds'` is the accumulated array of `CongrArgKind`s, which is the original array but with some kinds replaced by `.subsingletonInst`. - `params` is the *new* list of parameters, as fvars that need to be abstracted at the end. - `args` is the list of arguments (fvars) to supply to `cthm.proof` before abstracting `params`. - `letArgs` records `(fvar, expr)` assignments for each `fvar` that was solved for by `prove`. -/ process (cthm : CongrTheorem) (type : Expr) (argKinds : List CongrArgKind) (argKinds' : Array CongrArgKind) (params args : Array Expr) (letArgs : Array (Expr × Expr)) : MetaM CongrTheorem := do match argKinds with | [] => if letArgs.isEmpty then -- Then we didn't prove anything, so we can use the CongrTheorem as-is. return cthm else let proof := letArgs.foldr (init := mkAppN cthm.proof args) (fun (fvar, val) proof => (proof.abstract #[fvar]).instantiate1 val) let pf' ← mkLambdaFVars params proof return {proof := pf', type := ← inferType pf', argKinds := argKinds'} | argKind :: argKinds => match argKind with | .eq | .heq => forallBoundedTelescope type (some 3) fun params' type' => do let #[x, y, eq] := params' | unreachable! -- See if we can prove `Eq` from previous parameters. let g := (← mkFreshExprMVar (← inferType eq)).mvarId! let g ← g.clear eq.fvarId! if (← observing? <| prove g args).isSome then let eqPf ← instantiateMVars (.mvar g) process cthm type' argKinds (argKinds'.push .subsingletonInst) (params := params ++ #[x, y]) (args := args ++ params') (letArgs := letArgs.push (eq, eqPf)) else process cthm type' argKinds (argKinds'.push argKind) (params := params ++ params') (args := args ++ params') (letArgs := letArgs) | _ => panic! "Unexpected CongrArgKind" /-- Close the goal given only the fvars in `params`, or else fails. -/ prove (g : MVarId) (params : Array Expr) : MetaM Unit := do -- Prune the local context. let g ← g.cleanup -- Substitute equalities that come from only this congruence lemma. let [g] ← g.casesRec fun localDecl => do return (localDecl.type.isEq || localDecl.type.isHEq) && params.contains localDecl.toExpr | failure try g.refl; return catch _ => pure () try g.hrefl; return catch _ => pure () if ← g.proofIrrelHeq then return -- Make the goal be an eq and then try `Subsingleton.elim` let g ← g.heqOfEq if ← g.subsingletonElim then return -- We have no more tricks. failure universe u v /-- A version of `Subsingleton` with few instances. It should fail fast. -/ class FastSubsingleton (α : Sort u) : Prop where /-- The subsingleton instance. -/ [inst : Subsingleton α] /-- A version of `IsEmpty` with few instances. It should fail fast. -/ class FastIsEmpty (α : Sort u) : Prop where [inst : IsEmpty α] protected theorem FastSubsingleton.elim {α : Sort u} [h : FastSubsingleton α] : (a b : α) → a = b := h.inst.allEq protected theorem FastSubsingleton.helim {α β : Sort u} [FastSubsingleton α] (h₂ : α = β) (a : α) (b : β) : a ≍ b := by have : Subsingleton α := FastSubsingleton.inst exact Subsingleton.helim h₂ a b instance (priority := 100) {α : Type u} [inst : FastIsEmpty α] : FastSubsingleton α where inst := have := inst.inst; inferInstance instance {p : Prop} : FastSubsingleton p := {} instance {p : Prop} : FastSubsingleton (Decidable p) := {} instance : FastSubsingleton (Fin 1) := {} instance : FastSubsingleton PUnit := {} instance : FastIsEmpty Empty := {} instance : FastIsEmpty False := {} instance : FastIsEmpty (Fin 0) := {} instance {α : Sort u} [inst : FastIsEmpty α] {β : (x : α) → Sort v} : FastSubsingleton ((x : α) → β x) where inst.allEq _ _ := funext fun a => (inst.inst.false a).elim instance {α : Sort u} {β : (x : α) → Sort v} [inst : ∀ x, FastSubsingleton (β x)] : FastSubsingleton ((x : α) → β x) where inst := have := fun x ↦ (inst x).inst; inferInstance /-- Runs `mx` in a context where all local `Subsingleton` and `IsEmpty` instances have associated `FastSubsingleton` and `FastIsEmpty` instances. The function passed to `mx` eliminates these instances from expressions, since they are only locally valid inside this context. -/ def withSubsingletonAsFast {α : Type} [Inhabited α] (mx : (Expr → Expr) → MetaM α) : MetaM α := do let insts1 := (← getLocalInstances).filter fun inst => inst.className == ``Subsingleton let insts2 := (← getLocalInstances).filter fun inst => inst.className == ``IsEmpty let mkInst (f : Name) (inst : Expr) : MetaM Expr := do forallTelescopeReducing (← inferType inst) fun args _ => do mkLambdaFVars args <| ← mkAppOptM f #[none, mkAppN inst args] let vals := (← insts1.mapM fun inst => mkInst ``FastSubsingleton.mk inst.fvar) ++ (← insts2.mapM fun inst => mkInst ``FastIsEmpty.mk inst.fvar) let tys ← vals.mapM inferType withLocalDeclsD (tys.map fun ty => (`inst, fun _ => pure ty)) fun args => withNewLocalInstances args 0 do let elim (e : Expr) : Expr := e.replaceFVars args vals mx elim /-- Like `subsingletonElim` but uses `FastSubsingleton` to fail fast. -/ def fastSubsingletonElim (mvarId : MVarId) : MetaM Bool := mvarId.withContext do let res ← observing? do mvarId.checkNotAssigned `fastSubsingletonElim let tgt ← withReducible mvarId.getType' let some (_, lhs, rhs) := tgt.eq? | failure -- Note: `mkAppM` uses `withNewMCtxDepth`, which prevents `Sort _` from specializing to `Prop` let pf ← withSubsingletonAsFast fun elim => elim <$> mkAppM ``FastSubsingleton.elim #[lhs, rhs] mvarId.assign pf return true return res.getD false /-- `mkRichHCongr fType funInfo fixedFun fixedParams forceHEq` create a congruence lemma to prove that `Eq/HEq (f a₁ ... aₙ) (f' a₁' ... aₙ')`. The functions have type `fType` and the number of arguments is governed by the `funInfo` data. Each argument produces an `Eq/HEq aᵢ aᵢ'` hypothesis, but we also provide these hypotheses the additional facts that the preceding equalities have been proved (unlike in `mkHCongrWithArity`). The first two arguments of the resulting theorem are for `f` and `f'`, followed by a proof of `f = f'`, unless `fixedFun` is `true` (see below). When including hypotheses about previous hypotheses, we make use of dependency information and only include relevant equalities. The argument `fty` denotes the type of `f`. The arity of the resulting congruence lemma is controlled by the size of the `info` array. For the purpose of generating nicer lemmas (to help `to_additive` for example), this function supports generating lemmas where certain parameters are meant to be fixed: * If `fixedFun` is `false` (the default) then the lemma starts with three arguments for `f`, `f'`, and `h : f = f'`. Otherwise, if `fixedFun` is `true` then the lemma starts with just `f`. * If the `fixedParams` argument has `true` for a particular argument index, then this is a hint that the congruence lemma may use the same parameter for both sides of the equality. There is no guarantee -- it respects it if the types are equal for that parameter (i.e., if the parameter does not depend on non-fixed parameters). If `forceHEq` is `true` then the conclusion of the generated theorem is a `HEq`. Otherwise it might be an `Eq` if the equality is homogeneous. This is the interpretation of the `CongrArgKind`s in the generated congruence theorem: * `.eq` corresponds to having three arguments `(x : α) (x' : α) (h : x = x')`. Note that `h` might have additional hypotheses. * `.heq` corresponds to having three arguments `(x : α) (x' : α') (h : x ≍ x')` Note that `h` might have additional hypotheses. * `.fixed` corresponds to having a single argument `(x : α)` that is fixed between the LHS and RHS * `.subsingletonInst` corresponds to having two arguments `(x : α) (x' : α')` for which the congruence generator was able to prove that `x ≍ x'` already. This is a slight abuse of this `CongrArgKind` since this is used even for types that are not subsingleton typeclasses. Note that the first entry in this array is for the function itself. -/ partial def mkRichHCongr (fType : Expr) (info : FunInfo) (fixedFun : Bool := false) (fixedParams : Array Bool := #[]) (forceHEq : Bool := false) : MetaM CongrTheorem := do trace[Meta.CongrTheorems] "ftype: {fType}" trace[Meta.CongrTheorems] "deps: {info.paramInfo.map (fun p => p.backDeps)}" trace[Meta.CongrTheorems] "fixedFun={fixedFun}, fixedParams={fixedParams}" doubleTelescope fType info.getArity fixedParams fun xs ys fixedParams => do trace[Meta.CongrTheorems] "xs = {xs}" trace[Meta.CongrTheorems] "ys = {ys}" trace[Meta.CongrTheorems] "computed fixedParams={fixedParams}" let lctx := (← getLCtx) -- checkpoint for a local context that only has the parameters withLocalDeclD `f fType fun ef => withLocalDeclD `f' fType fun pef' => do let ef' := if fixedFun then ef else pef' withLocalDeclD `e (← mkEq ef ef') fun ee => do withNewEqs xs ys fixedParams fun kinds eqs => do let fParams := if fixedFun then #[ef] else #[ef, ef', ee] let mut hs := fParams -- parameters to the basic congruence lemma let mut hs' := fParams -- parameters to the richer congruence lemma let mut vals' := fParams -- how to calculate the basic parameters from the richer ones for i in [0 : info.getArity] do hs := hs.push xs[i]! hs' := hs'.push xs[i]! vals' := vals'.push xs[i]! if let some (eq, eq', val) := eqs[i]! then -- Not a fixed argument hs := hs.push ys[i]! |>.push eq hs' := hs'.push ys[i]! |>.push eq' vals' := vals'.push ys[i]! |>.push val -- Generate the theorem with respect to the simpler hypotheses let mkConcl := if forceHEq then mkHEq else mkEqHEq let congrType ← mkForallFVars hs (← mkConcl (mkAppN ef xs) (mkAppN ef' ys)) trace[Meta.CongrTheorems] "simple congrType: {congrType}" let some proof ← withLCtx lctx (← getLocalInstances) <| trySolve congrType | throwError "Internal error when constructing congruence lemma proof" -- At this point, `mkLambdaFVars hs' (mkAppN proof vals')` is the richer proof. -- We try to precompute some of the arguments using `trySolve`. let mut hs'' := #[] -- eq' parameters that are actually used beyond those in `fParams` let mut pfVars := #[] -- eq' parameters that can be solved for already let mut pfVals := #[] -- the values to use for these parameters let mut kinds' : Array CongrArgKind := #[if fixedFun then .fixed else .eq] for i in [0 : info.getArity] do hs'' := hs''.push xs[i]! if let some (_, eq', _) := eqs[i]! then -- Not a fixed argument hs'' := hs''.push ys[i]! let pf? ← withLCtx lctx (← getLocalInstances) <| trySolve (← inferType eq') if let some pf := pf? then pfVars := pfVars.push eq' pfVals := pfVals.push pf kinds' := kinds'.push .subsingletonInst else hs'' := hs''.push eq' kinds' := kinds'.push kinds[i]! else kinds' := kinds'.push .fixed trace[Meta.CongrTheorems] "CongrArgKinds: {repr kinds'}" -- Take `proof`, abstract the pfVars and provide the solved-for proofs (as an -- optimization for proof term size) then abstract the remaining variables. -- The `usedOnly` probably has no affect. -- Note that since we are doing `proof.beta vals'` there is technically some quadratic -- complexity, but it shouldn't be too bad since they're some applications of just variables. let proof' ← mkLambdaFVars fParams (← mkLambdaFVars (usedOnly := true) hs'' (mkAppN (← mkLambdaFVars pfVars (proof.beta vals')) pfVals)) let congrType' ← inferType proof' trace[Meta.CongrTheorems] "rich congrType: {congrType'}" return {proof := proof', type := congrType', argKinds := kinds'} where /-- Similar to doing `forallBoundedTelescope` twice, but makes use of the `fixed` array, which is used as a hint for whether both variables should be the same. This is only a hint though, since we respect it only if the binding domains are equal. We affix `'` to the second list of variables, and all the variables are introduced with default binder info. Calls `k` with the xs, ys, and a revised `fixed` array -/ doubleTelescope {α} (fty : Expr) (numVars : Nat) (fixed : Array Bool) (k : Array Expr → Array Expr → Array Bool → MetaM α) : MetaM α := do let rec loop (i : Nat) (ftyx ftyy : Expr) (xs ys : Array Expr) (fixed' : Array Bool) : MetaM α := do if i < numVars then let ftyx ← whnfD ftyx let ftyy ← whnfD ftyy unless ftyx.isForall do throwError "doubleTelescope: function doesn't have enough parameters" withLocalDeclD ftyx.bindingName! ftyx.bindingDomain! fun fvarx => do let ftyx' := ftyx.bindingBody!.instantiate1 fvarx if fixed.getD i false && ftyx.bindingDomain! == ftyy.bindingDomain! then -- Fixed: use the same variable for both let ftyy' := ftyy.bindingBody!.instantiate1 fvarx loop (i + 1) ftyx' ftyy' (xs.push fvarx) (ys.push fvarx) (fixed'.push true) else -- Not fixed: use different variables let yname := ftyy.bindingName!.appendAfter "'" withLocalDeclD yname ftyy.bindingDomain! fun fvary => do let ftyy' := ftyy.bindingBody!.instantiate1 fvary loop (i + 1) ftyx' ftyy' (xs.push fvarx) (ys.push fvary) (fixed'.push false) else k xs ys fixed' loop 0 fty fty #[] #[] #[] /-- Introduce variables for equalities between the arrays of variables. Uses `fixedParams` to control whether to introduce an equality for each pair. The array of triples passed to `k` consists of (1) the simple congr lemma HEq arg, (2) the richer HEq arg, and (3) how to compute 1 in terms of 2. -/ withNewEqs {α} (xs ys : Array Expr) (fixedParams : Array Bool) (k : Array CongrArgKind → Array (Option (Expr × Expr × Expr)) → MetaM α) : MetaM α := let rec loop (i : Nat) (kinds : Array CongrArgKind) (eqs : Array (Option (Expr × Expr × Expr))) := do if i < xs.size then let x := xs[i]! let y := ys[i]! if fixedParams[i]! then loop (i+1) (kinds.push .fixed) (eqs.push none) else let deps := info.paramInfo[i]!.backDeps.filterMap (fun j => eqs[j]!) let eq' ← mkForallFVars (deps.map fun (eq, _, _) => eq) (← mkEqHEq x y) withLocalDeclD ((`e).appendIndexAfter (i+1)) (← mkEqHEq x y) fun h => withLocalDeclD ((`e').appendIndexAfter (i+1)) eq' fun h' => do let v := mkAppN h' (deps.map fun (_, _, val) => val) let kind := if (← inferType h).eq?.isSome then .eq else .heq loop (i+1) (kinds.push kind) (eqs.push (h, h', v)) else k kinds eqs loop 0 #[] #[] /-- Given a type that is a bunch of equalities implying a goal (for example, a basic congruence lemma), prove it if possible. Basic congruence lemmas should be provable by this. There are some extra tricks for handling arguments to richer congruence lemmas. -/ trySolveCore (mvarId : MVarId) : MetaM Unit := do -- First cleanup the context since we're going to do `substEqs` and we don't want to -- accidentally use variables not actually used by the theorem. let mvarId ← mvarId.cleanup let (_, mvarId) ← mvarId.intros let mvarId := (← mvarId.substEqs).getD mvarId try mvarId.refl; return catch _ => pure () try mvarId.hrefl; return catch _ => pure () if ← mvarId.proofIrrelHeq then return -- Make the goal be an eq and then try `Subsingleton.elim` let mvarId ← mvarId.heqOfEq if ← fastSubsingletonElim mvarId then return -- We have no more tricks. throwError "was not able to solve for proof" /-- Driver for `trySolveCore`. -/ trySolve (ty : Expr) : MetaM (Option Expr) := observing? do let mvar ← mkFreshExprMVar ty trace[Meta.CongrTheorems] "trySolve {mvar.mvarId!}" -- The proofs we generate shouldn't require unfolding anything. withReducible <| trySolveCore mvar.mvarId! trace[Meta.CongrTheorems] "trySolve success!" let pf ← instantiateMVars mvar return pf end Lean.Meta
.lake/packages/mathlib/Mathlib/Lean/Meta/RefinedDiscrTree.lean
import Mathlib.Lean.Meta.RefinedDiscrTree.Lookup import Mathlib.Lean.Meta.RefinedDiscrTree.Initialize /-! A discrimination tree for the purpose of unifying local expressions with library results. This data structure is based on `Lean.Meta.DiscrTree` and `Lean.Meta.LazyDiscrTree`, and includes many more features. ## New features - The keys `Key.lam`, `Key.forall` and `Key.bvar` have been introduced in order to allow for matching under lambda and forall binders. `Key.lam` has arity 1 and indexes the body. `Key.forall` has arity 2 and indexes the domain and the body. The reason for not indexing the domain of a lambda expression is that it is usually already determined, for example in `∃ a : α, p`, which is `@Exists α fun a : α => p`, we don't want to index the domain `α` twice. In a forall expression we should index the domain, because in an implication `p → q` we need to index both `p` and `q`. `Key.bvar` works the same as `Key.fvar`, but stores the De Bruijn index to identify the variable. For example, this allows for more specific matching with the left-hand side of `∑ i ∈ Finset.range n, i = n * (n - 1) / 2`, which is indexed by `[⟨Finset.sum, 5⟩, ⟨Nat, 0⟩, ⟨Nat, 0⟩, *0, ⟨Finset.Range, 1⟩, *1, λ, ⟨#0, 0⟩]`. - The key `Key.star` takes a `Nat` identifier as an argument. For example, the library pattern `?a + ?a` is encoded as `@HAdd.hAdd *0 *0 *1 *2 *3 *3`. `*0` corresponds to the type of `?a`, `*1` to the outParam of `HAdd.hAdd`, `*2` to the `HAdd` instance, and `*3` to `a`. This means that it will only match an expression `x + y` if `x` is indexed the same as `y`. The matching algorithm ensures that both instances of `*3` match with the same pattern in the lookup expression. - We evaluate the matching score of a unification. This score represents the number of keys that had to be the same for the unification to succeed. For example, matching `(1 + 2) + 3` with `add_comm` gives a score of 2, since the pattern of `add_comm` is `@HAdd.hAdd *0 *0 *0 *1 *2 *3`: matching `HAdd.hAdd` gives 1 point, and matching `*0` again after its first appearance gives another point. Similarly, matching it with `Nat.add_comm` gives a score of 3, and `add_assoc` gives a score of 5. - Patterns that have the potential to be η-reduced are put into the `RefinedDiscrTree` under all possible reduced key sequences. This is for terms of the form `fun x => f (?m x₁ .. xₙ)`, where `?m` is a metavariable, one of `x₁, .., xₙ` is `x`, and `f` is not a metavariable. For example, the pattern `Continuous fun y => Real.exp (f y)])` is indexed by both `@Continuous *0 ℝ *1 *2 (λ, Real.exp *3)` and `@Continuous *0 ℝ *1 *2 Real.exp`, so that it also comes up if you look up `Continuous Real.exp`. - How to deal with number literals is waiting for this issue to be resolved: https://github.com/leanprover/lean4/issues/2867 - The key `Key.opaque` only matches with a `Key.star` key. Depending on the configuration, β-reduction and ζ-reduction may be disabled, so the resulting applied lambda expressions or let-expressions are indexed by `Key.opaque`. ## Lazy computation To encode an `Expr` as a sequence of `Key`s, we start with a `LazyEntry` and we have a incremental evaluation function of type `LazyEntry → MetaM (Option (List (Key × LazyEntry)))`, which computes the next keys and lazy entries, or returns `none` if the last key has been reached already. The `RefinedDiscrTree` then stores these `LazyEntries` at its leafs, and evaluates them only if the lookup algorithm reaches this leaf. ## Alternative optimizations `RefinedDiscrTree` is a non-persistent lazy data-structure. Therefore, when using it, you should try to use it linearly (i.e. having reference count 1). This is ideal for library search purposes, which build the discrimination tree once, and store a reference to the tree. However, for tactics like `simp` and `fun_prop` this is less ideal, because they can't use the data-structure linearly, since copies of the data structure must regularly be stored in the environment. For `fun_prop` this is not a serious problem since it doesn't have that many different lemmas anyways. #### Future work: Make a version of `RefinedDiscrTree` that is optimal for tactics like `simp` and `fun_prop`. This would mean using a persistent data structure, and possibly a non-lazy structure. ## Matching vs Unification A discrimination tree can be used in two ways: either with (unification) or without (matching) allowing metavariables in the target expression to be instantiated. Most applications use matching, and the only common use case where unification is used is type class search. Since the intended applications of the `RefinedDiscrTree` currently use matching, the lookup algorithm is most optimized for matching. #### Future work: Improve the unification lookup. -/ namespace Lean.Meta.RefinedDiscrTree variable {α : Type} /-- Creates the core context used for initializing a tree using the current context. -/ private def withTreeCtx (ctx : Core.Context) : Core.Context := { ctx with maxHeartbeats := 0, diag := getDiag ctx.options } /-- Returns candidates from all imported modules that match the expression. -/ def findImportMatches (ext : EnvExtension (IO.Ref (Option (RefinedDiscrTree α)))) (addEntry : Name → ConstantInfo → MetaM (List (α × List (Key × LazyEntry)))) (ty : Expr) (constantsPerTask : Nat := 1000) (capacityPerTask : Nat := 128) : MetaM (MatchResult α) := do let ngen ← getNGen let (cNGen, ngen) := ngen.mkChild setNGen ngen let _ : Inhabited (IO.Ref (Option (RefinedDiscrTree α))) := ⟨← IO.mkRef none⟩ let ref := EnvExtension.getState ext (← getEnv) -- empty the reference `ref`, so that the reference count stays 1 let importTree? ← ref.modifyGet fun tree? => (tree?, none) let importTree ← importTree?.getDM do profileitM Exception "RefinedDiscrTree import initialization" (← getOptions) <| withTheReader Core.Context withTreeCtx <| createImportedDiscrTree cNGen (← getEnv) addEntry constantsPerTask capacityPerTask let (importCandidates, importTree) ← getMatch importTree ty false false ref.set (some importTree) MonadExcept.ofExcept importCandidates /-- Returns candidates from this module that match the expression. -/ def findModuleMatches (moduleRef : ModuleDiscrTreeRef α) (ty : Expr) : MetaM (MatchResult α) := do profileitM Exception "RefinedDiscrTree local search" (← getOptions) do let discrTree ← moduleRef.ref.get let (localCandidates, localTree) ← getMatch discrTree ty false false moduleRef.ref.set localTree MonadExcept.ofExcept localCandidates /-- `findMatches` combines `findImportMatches` and `findModuleMatches`. * `ext` should be an environment extension with an `IO.Ref` for caching the `RefinedDiscrTree`. * `addEntry` is the function for creating `RefinedDiscrTree` entries from constants. * `ty` is the expression type. * `constantsPerTask` is the number of constants in imported modules to be used for each new task. * `capacityPerTask` is the initial capacity of the `HashMap` at the root of the `RefinedDiscrTree` for each new task. -/ def findMatches (ext : EnvExtension (IO.Ref (Option (RefinedDiscrTree α)))) (addEntry : Name → ConstantInfo → MetaM (List (α × List (Key × LazyEntry)))) (ty : Expr) (constantsPerTask : Nat := 1000) (capacityPerTask : Nat := 128) : MetaM (MatchResult α × MatchResult α) := do let moduleMatches ← findModuleMatches (← createModuleTreeRef addEntry) ty let importMatches ← findImportMatches ext addEntry ty constantsPerTask capacityPerTask return (moduleMatches, importMatches) end Lean.Meta.RefinedDiscrTree
.lake/packages/mathlib/Mathlib/Lean/Meta/DiscrTree.lean
import Mathlib.Init import Lean.Meta.DiscrTree /-! # Additions to `Lean.Meta.DiscrTree` -/ namespace Lean.Meta.DiscrTree /-- Find keys which match the expression, or some subexpression. Note that repeated subexpressions will be visited each time they appear, making this operation potentially very expensive. It would be good to solve this problem! Implementation: we reverse the results from `getMatch`, so that we return lemmas matching larger subexpressions first, and amongst those we return more specific lemmas first. -/ partial def getSubexpressionMatches {α : Type} (d : DiscrTree α) (e : Expr) : MetaM (Array α) := do match e with | .bvar _ => return #[] | .forallE _ _ _ _ => forallTelescope e (fun args body => do args.foldlM (fun acc arg => do pure <| acc ++ (← d.getSubexpressionMatches (← inferType arg))) (← d.getSubexpressionMatches body).reverse) | .lam _ _ _ _ | .letE _ _ _ _ _ => lambdaLetTelescope e (fun args body => do args.foldlM (fun acc arg => do pure <| acc ++ (← d.getSubexpressionMatches (← inferType arg))) (← d.getSubexpressionMatches body).reverse) | _ => e.foldlM (fun a f => do pure <| a ++ (← d.getSubexpressionMatches f)) (← d.getMatch e).reverse /-- Check if a `keys : Array DiscTree.Key` is "specific", i.e. something other than `[*]` or `[=, *, *, *]`. -/ def keysSpecific (keys : Array DiscrTree.Key) : Bool := keys != #[Key.star] && keys != #[Key.const ``Eq 3, Key.star, Key.star, Key.star] end Lean.Meta.DiscrTree
.lake/packages/mathlib/Mathlib/Lean/Meta/Tactic/Rewrite.lean
import Mathlib.Init import Lean.Meta.Tactic.Rewrite /-! # Additional declarations for `Lean.Meta.Tactic.Rewrite` -/ namespace Lean.Expr open Meta /-- Rewrites `e` via some `eq`, producing a proof `e = e'` for some `e'`. Rewrites with a fresh metavariable as the ambient goal. Fails if the rewrite produces any subgoals. -/ def rewrite (e eq : Expr) : MetaM Expr := do let ⟨_, eq', []⟩ ← (← mkFreshExprMVar none).mvarId!.rewrite e eq | throwError "Expr.rewrite may not produce subgoals." return eq' /-- Rewrites the type of `e` via some `eq`, then moves `e` into the new type via `Eq.mp`. Rewrites with a fresh metavariable as the ambient goal. Fails if the rewrite produces any subgoals. -/ def rewriteType (e eq : Expr) : MetaM Expr := do mkEqMP (← (← inferType e).rewrite eq) e end Lean.Expr
.lake/packages/mathlib/Mathlib/Lean/Meta/RefinedDiscrTree/Lookup.lean
import Mathlib.Lean.Meta.RefinedDiscrTree.Encode /-! # Matching with a RefinedDiscrTree This file defines the matching procedure for the `RefinedDiscrTree`. The main definitions are * The structure `MatchResult`, which contains the match results, ordered by matching score. * The (private) function `evalNode` which evaluates a node of the `RefinedDiscrTree` * The (private) function `getMatchLoop`, which is the main function that computes the matches. It implements the non-deterministic computation by keeping a stack of `PartialMatch`es, and repeatedly processing the most recent one. * The matching function `getMatch` that also returns an updated `RefinedDiscrTree` To find the matches, we first encode the expression as a `List Key`. Then using this, we find all matches with the tree. When `unify == true`, we also allow metavariables in the target expression to be assigned. We use a simple unification algorithm. For all star/metavariable patterns in the `RefinedDiscrTree` (and in the target if `unify == true`), we store the assignment, and when it is attempted to be assigned again, we check that it is the same assignment. -/ namespace Lean.Meta.RefinedDiscrTree variable {α β : Type} /-- Monad for working with a `RefinedDiscrTree`. -/ private abbrev TreeM α := StateRefT (Array (Trie α)) MetaM /-- Run a `TreeM` computation using `d : RefinedDiscrTree`, without losing the reference to `d`. -/ @[inline] private def runTreeM (d : RefinedDiscrTree α) (m : TreeM α β) : MetaM (Except Exception β × RefinedDiscrTree α) := do let { tries, root } := d let (result, tries) ← (try Except.ok <$> m catch ex => pure (.error ex)).run tries pure (result, { tries, root }) private def setTrie (i : TrieIndex) (v : Trie α) : TreeM α Unit := modify (·.set! i v) /-- Create a new trie with the given lazy entry. -/ private def newTrie (e : LazyEntry × α) : TreeM α TrieIndex := do modifyGet fun a => (a.size, a.push (.node #[] none {} {} #[e])) /-- Add a lazy entry to an existing trie. -/ private def addLazyEntryToTrie (i : TrieIndex) (e : LazyEntry × α) : TreeM α Unit := modify (·.modify i fun node => { node with pending := node.pending.push e }) /-- Evaluate the `Trie α` at index `trie`, replacing it with the evaluated value, and returning the `Trie α`. -/ private def evalNode (trie : TrieIndex) : TreeM α (Trie α) := do let node := (← get)[trie]! if node.pending.isEmpty then return node setTrie trie default -- reduce the reference count to `node` to be 1 let mut { values, star, labelledStars, children, pending } := node for (entry, value) in pending do let some newEntries ← evalLazyEntry entry true | values := values.push value for (key, entry) in newEntries do let entry := (entry, value) match key with | .labelledStar label => if let some trie := labelledStars[label]? then addLazyEntryToTrie trie entry else labelledStars := labelledStars.insert label (← newTrie entry) | .star => if let some trie := star then addLazyEntryToTrie trie entry else star := some (← newTrie entry) | _ => if let some trie := children[key]? then addLazyEntryToTrie trie entry else children := children.insert key (← newTrie entry) let node := { values, star, labelledStars, children, pending := #[] } setTrie trie node return node /-- A match result contains the results from matching a term against patterns in the discrimination tree. -/ structure MatchResult (α : Type) where /-- The elements in the match result. The `Nat` in the tree map represents the `score` of the results. The elements are arrays of arrays, where each sub-array corresponds to one discr tree pattern. -/ elts : Std.TreeMap Nat (Array (Array α)) := {} deriving Inhabited private def MatchResult.push (mr : MatchResult α) (score : Nat) (e : Array α) : MatchResult α := { elts := mr.elts.alter score fun | some arr => arr.push e | none => #[e] } /-- Convert a `MatchResult` into a `Array`, with better matches at the start of the array. -/ def MatchResult.toArray (mr : MatchResult α) : Array α := mr.elts.foldr (init := #[]) fun _ a r => a.foldl (init := r) (· ++ ·) /-- Convert a `MatchResult` into an `Array` of `Array`s. Each `Array` corresponds to one pattern. The better matching patterns are at the start of the outer array. For each inner array, the entries are ordered in the order they were inserted. -/ def MatchResult.flatten (mr : MatchResult α) : Array (Array α) := mr.elts.foldr (init := #[]) (fun _ arr cand => cand ++ arr) /- A partial match captures the intermediate state of a match execution. N.B. Discrimination tree matching has non-determinism due to stars, so the matching loop maintains a stack of partial match results. -/ private structure PartialMatch where /-- Remaining terms to match -/ keys : List Key /-- Number of non-star matches so far -/ score : Nat /-- Trie to match next -/ trie : TrieIndex /-- Metavariable assignments for `.labelledStar` patterns in the discrimination tree. We use a `List Key`, in the reverse order. -/ treeStars : Std.HashMap Nat (List Key) := {} deriving Inhabited /-- Add to the `todo` stack all matches that result from a `.star` in the query expression. -/ private partial def matchQueryStar (trie : TrieIndex) (pMatch : PartialMatch) (todo : Array PartialMatch) (skip : Nat := 1) : TreeM α (Array PartialMatch) := do match skip with | skip+1 => let { star, labelledStars, children, .. } ← evalNode trie let mut todo := todo if let some trie := star then todo ← matchQueryStar trie pMatch todo skip todo ← labelledStars.foldM (init := todo) fun todo _ trie => matchQueryStar trie pMatch todo skip todo ← children.foldM (init := todo) fun todo key trie => matchQueryStar trie pMatch todo (skip + key.arity) return todo | 0 => return todo.push { pMatch with trie } /-- Return every value that is indexed in the tree. -/ private def matchEverything (root : Std.HashMap Key TrieIndex) : TreeM α (MatchResult α) := do let pMatches ← root.foldM (init := #[]) fun todo key trie => matchQueryStar trie { keys := [], score := 0, trie := 0 } todo key.arity pMatches.foldlM (init := {}) fun result pMatch => do let { values, .. } ← evalNode pMatch.trie return result.push (score := 0) values /-- Add to the `todo` stack all matches that result from a `.star _` in the discrimination tree. -/ private partial def matchTreeStars (key : Key) (node : Trie α) (pMatch : PartialMatch) (todo : Array PartialMatch) (unify : Bool) : Array PartialMatch := Id.run do let { star, labelledStars, .. } := node if labelledStars.isEmpty && star.isNone then todo else let (dropped, keys) := drop [key] pMatch.keys key.arity let mut todo := todo if let some trie := star then todo := todo.push { pMatch with keys, trie } todo := node.labelledStars.fold (init := todo) fun todo id trie => if let some assignment := pMatch.treeStars[id]? then let eq lhs rhs := if unify then (isEq lhs.reverse rhs.reverse).isSome else lhs == rhs if eq dropped assignment then todo.push { pMatch with keys, trie, score := pMatch.score + dropped.length } else todo else let treeStars := pMatch.treeStars.insert id dropped todo.push { pMatch with keys, trie, treeStars } return todo where /-- Drop the keys corresponding to the next `n` expressions. -/ drop (dropped rest : List Key) (n : Nat) : (List Key × List Key) := Id.run do match n with | 0 => (dropped, rest) | n + 1 => let key :: rest := rest | panic! "too few keys" drop (key :: dropped) rest (n + key.arity) isEq (lhs rhs : List Key) : Option (List Key × List Key) := do match lhs with | [] => panic! "too few keys" | .star :: lhs => let (_, rhs) := drop [] rhs 1 return (lhs, rhs) | lHead :: lhs => match rhs with | [] => panic! "too few keys" | .star :: rhs => let (_, lhs) := drop [] lhs 1 return (lhs, rhs) | rHead :: rhs => guard (lHead == rHead) lHead.arity.foldM (init := (lhs, rhs)) fun _ _ (lhs, rhs) => isEq lhs rhs /-- Add to the `todo` stack the match with `key`. -/ private def matchKey (key : Key) (children : Std.HashMap Key TrieIndex) (pMatch : PartialMatch) (todo : Array PartialMatch) : Array PartialMatch := if key == .opaque then todo else match children[key]? with | none => todo | some trie => todo.push { pMatch with trie, score := pMatch.score + 1 } /-- Return the possible `Trie α` that match with `keys`. -/ private partial def getMatchLoop (todo : Array PartialMatch) (result : MatchResult α) (unify : Bool) : TreeM α (MatchResult α) := do if h : todo.size = 0 then return result else let pMatch := todo.back let todo := todo.pop let node ← evalNode pMatch.trie match pMatch.keys with | [] => getMatchLoop todo (result.push (score := pMatch.score) node.values) unify | key :: keys => let pMatch := { pMatch with keys } match key with -- `key` is not a `.labelledStar` | .star => if unify then let todo ← matchQueryStar pMatch.trie pMatch todo getMatchLoop todo result unify else let todo := matchTreeStars key node pMatch todo unify getMatchLoop todo result unify | _ => let todo := matchTreeStars key node pMatch todo unify let todo := matchKey key node.children pMatch todo getMatchLoop todo result unify /-- Return the results from matching the pattern `[.star]` or `[.labelledStar 0]`. -/ private def matchTreeRootStar (root : Std.HashMap Key TrieIndex) : TreeM α (MatchResult α) := do let mut result := {} if let some trie := root[Key.labelledStar 0]? then let { values, .. } ← evalNode trie result := result.push (score := 0) values if let some trie := root[Key.star]? then let { values, .. } ← evalNode trie result := result.push (score := 0) values return result /-- Find values that match `e` in `d`. * If `unify == true` then metavariables in `e` can be assigned. * If `matchRootStar == true` then we allow metavariables at the root to unify. Set this to `false` to avoid getting excessively many results. Note: to preserve the reference to `d`, `getMatch` will never throw an error, and instead it returns an `Except Exception (MatchResult α)`. -/ def getMatch (d : RefinedDiscrTree α) (e : Expr) (unify matchRootStar : Bool) : MetaM (Except Exception (MatchResult α) × RefinedDiscrTree α) := do withReducible do runTreeM d do let (key, keys) ← encodeExpr e (labelledStars := false) let pMatch : PartialMatch := { keys, score := 0, trie := default } if key == .star then if matchRootStar then if unify then matchEverything d.root else matchTreeRootStar d.root else return {} else let todo := matchKey key d.root pMatch #[] if matchRootStar then getMatchLoop todo (← matchTreeRootStar d.root) unify else getMatchLoop todo {} unify end Lean.Meta.RefinedDiscrTree
.lake/packages/mathlib/Mathlib/Lean/Meta/RefinedDiscrTree/Initialize.lean
import Mathlib.Lean.Meta.RefinedDiscrTree.Basic import Lean.Meta.CompletionName /-! # Constructing a RefinedDiscrTree `RefinedDiscrTree` is lazy, so to add an entry, we need to compute the first `Key` and a `LazyEntry`. These are computed by `initializeLazyEntry`. We provide `RefinedDiscrTree.insert` for directly performing this insert. For initializing a `RefinedDiscrTree` using all imported constants, we provide `createImportedDiscrTree`, which loops through all imported constants, and does this with a parallel computation. There is also `createModuleDiscrTree` which does the same but with the constants from the current file. -/ namespace Lean.Meta.RefinedDiscrTree variable {α : Type} /-- Directly insert a `Key`, `LazyEntry` pair into a `RefinedDiscrTree`. -/ def insert (d : RefinedDiscrTree α) (key : Key) (entry : LazyEntry × α) : RefinedDiscrTree α := if let some trie := d.root[key]? then { d with tries := d.tries.modify trie fun node => { node with pending := node.pending.push entry } } else { d with root := d.root.insert key d.tries.size tries := d.tries.push <| .node #[] none {} {} #[entry] } /-- Structure for quickly initializing a lazy discrimination tree with a large number of elements using concurrent functions for generating entries. This preliminary structure is converted to a `RefinedDiscrTree` via `toRefinedDiscrTree`. -/ structure PreDiscrTree (α : Type) where /-- Maps keys to index in tries array. -/ root : Std.HashMap Key Nat := {} /-- Lazy entries for root of trie. -/ tries : Array (Array (LazyEntry × α)) := #[] deriving Inhabited namespace PreDiscrTree @[specialize] private def modifyAt (d : PreDiscrTree α) (k : Key) (f : Array (LazyEntry × α) → Array (LazyEntry × α)) : PreDiscrTree α := let { root, tries } := d match root[k]? with | none => { root := root.insert k tries.size, tries := tries.push (f #[]) } | some i => { root, tries := tries.modify i f } /-- Add an entry to the `PreDiscrTree`. -/ def push (d : PreDiscrTree α) (k : Key) (e : LazyEntry × α) : PreDiscrTree α := d.modifyAt k (·.push e) /-- Convert a `PreDiscrTree` to a `RefinedDiscrTree`. -/ def toRefinedDiscrTree (d : PreDiscrTree α) : RefinedDiscrTree α := let { root, tries } := d { root, tries := tries.map fun pending => .node #[] none {} {} pending } /-- Merge two `PreDiscrTree`s. -/ def append (x y : PreDiscrTree α) : PreDiscrTree α := let (x, y, f) := if x.root.size ≥ y.root.size then (x, y, fun y x => x ++ y) else (y, x, fun x y => x ++ y) let { root := yk, tries := ya } := y yk.fold (init := x) fun d k yi => d.modifyAt k (f ya[yi]!) instance : Append (PreDiscrTree α) where append := PreDiscrTree.append end PreDiscrTree /-- Information about a failed import. -/ private structure ImportFailure where /-- Module containing the constant whose import failed. -/ module : Name /-- Constant whose import failed. -/ const : Name /-- Exception that triggered the error. -/ exception : Exception /-- Information generated from imported modules. -/ private structure ImportErrorData where errors : IO.Ref (Array ImportFailure) private def ImportErrorData.new : BaseIO ImportErrorData := do return { errors := ← IO.mkRef #[] } /-- Return true if `declName` is automatically generated, or otherwise unsuitable as a lemma suggestion. -/ def blacklistInsertion (env : Environment) (declName : Name) : Bool := declName.isInternalDetail || declName.isMetaprogramming || !allowCompletion env declName || Linter.isDeprecated env declName || declName == ``sorryAx || (declName matches .str _ "inj" | .str _ "injEq" | .str _ "sizeOf_spec") /-- Add the entries generated by `act name constInfo` to the `PreDiscrTree`. Note: It is expensive to create two new `IO.Ref`s for every `MetaM` operation, so instead we reuse the same refs `mstate` and `cstate`. These are also used to remember the cache, and the name generator across the operations. -/ @[inline] private def addConstToPreDiscrTree (cctx : Core.Context) (env : Environment) (modName : Name) (data : ImportErrorData) (mstate : IO.Ref Meta.State) (cstate : IO.Ref Core.State) (act : Name → ConstantInfo → MetaM (List (α × List (Key × LazyEntry)))) (tree : PreDiscrTree α) (name : Name) (constInfo : ConstantInfo) : BaseIO (PreDiscrTree α) := do -- here we use an if-then-else clause instead of the more stylish if-then-return, -- because it compiles to more performant code if constInfo.isUnsafe then pure tree else if blacklistInsertion env name then pure tree else /- For efficiency, we leave it up to the implementation of `act` to reset the states if needed -/ -- mstate.modify fun s => { cache := s.cache } -- cstate.modify fun s => { env := s.env, cache := s.cache, ngen := s.ngen } let mctx := { keyedConfig := Config.toConfigWithKey { transparency := .reducible } } match ← (((act name constInfo) mctx mstate) cctx cstate).toBaseIO with | .ok a => return a.foldl (fun t (val, entries) => entries.foldl (fun t (key, entry) => t.push key (entry, val)) t) tree | .error e => let i : ImportFailure := { module := modName, const := name, exception := e } data.errors.modify (·.push i) return tree /-- Contains a `PreDiscrTree` and any errors occurring during initialization of the library search tree. -/ private structure InitResults (α : Type) where tree : PreDiscrTree α := {} errors : Array ImportFailure := #[] namespace InitResults /-- Combine two initial results. -/ protected def append (x y : InitResults α) : InitResults α := let { tree := xv, errors := xe } := x let { tree := yv, errors := ye } := y { tree := xv ++ yv, errors := xe ++ ye } instance : Append (InitResults α) where append := InitResults.append end InitResults private def toInitResults (data : ImportErrorData) (tree : PreDiscrTree α) : BaseIO (InitResults α) := do let de ← data.errors.swap #[] pure ⟨tree, de⟩ /-- Loop through all constants that appear in the module `mdata`, and add the entries generated by `act` to the `PreDiscrTree`. -/ private partial def loadImportedModule (cctx : Core.Context) (env : Environment) (data : ImportErrorData) (mstate : IO.Ref Meta.State) (cstate : IO.Ref Core.State) (act : Name → ConstantInfo → MetaM (List (α × List (Key × LazyEntry)))) (mname : Name) (mdata : ModuleData) (tree : PreDiscrTree α) (i : Nat := 0) : BaseIO (PreDiscrTree α) := do if h : i < mdata.constNames.size then let name := mdata.constNames[i] let constInfo := mdata.constants[i]! let state ← addConstToPreDiscrTree cctx env mname data mstate cstate act tree name constInfo loadImportedModule cctx env data mstate cstate act mname mdata state (i+1) else return tree /-- Loop through all constants that appear in the modules with module index from `start` to `stop - 1`, and add the entries generated by `act` to the `PreDiscrTree`. -/ private def createImportInitResults (cctx : Core.Context) (ngen : NameGenerator) (env : Environment) (act : Name → ConstantInfo → MetaM (List (α × List (Key × LazyEntry)))) (capacity start stop : Nat) : BaseIO (InitResults α) := do let tree := { root := .emptyWithCapacity capacity } go start stop tree (← ImportErrorData.new) (← IO.mkRef {}) (← IO.mkRef { env, ngen }) where go (start stop : Nat) (tree : PreDiscrTree α) (data : ImportErrorData) (mstate : IO.Ref Meta.State) (cstate : IO.Ref Core.State) : BaseIO (InitResults α) := do if start < stop then let mname := env.header.moduleNames[start]! let mdata := env.header.moduleData[start]! let tree ← loadImportedModule cctx env data mstate cstate act mname mdata tree go (start+1) stop tree data mstate cstate else toInitResults data tree termination_by stop - start private def getChildNgen : CoreM NameGenerator := do let ngen ← getNGen let (cngen, ngen) := ngen.mkChild setNGen ngen pure cngen private def logImportFailure (f : ImportFailure) : CoreM Unit := logError m!"Processing failure with {f.const} in {f.module}:\n {f.exception.toMessageData}" /-- Create a `RefinedDiscrTree` consisting of all entries generated by `act` from imported constants; `addConstToPreDiscrTree` calls this helper. This uses parallel computation. -/ def createImportedDiscrTree (ngen : NameGenerator) (env : Environment) (act : Name → ConstantInfo → MetaM (List (α × List (Key × LazyEntry)))) (constantsPerTask capacityPerTask : Nat) : CoreM (RefinedDiscrTree α) := do let numModules := env.header.moduleData.size let cctx ← read let rec /-- Allocate constants to tasks according to `constantsPerTask`. -/ go (ngen : NameGenerator) (tasks : Array (Task (InitResults α))) (start cnt idx : Nat) := do if h : idx < numModules then let mdata := env.header.moduleData[idx] let cnt := cnt + mdata.constants.size if cnt > constantsPerTask then let (childNGen, ngen) := ngen.mkChild let t ← (createImportInitResults cctx childNGen env act capacityPerTask start (idx+1)).asTask go ngen (tasks.push t) (idx+1) 0 (idx+1) else go ngen tasks start cnt (idx+1) else if start < numModules then let (childNGen, _) := ngen.mkChild let t ← (createImportInitResults cctx childNGen env act capacityPerTask start numModules).asTask pure (tasks.push t) else pure tasks termination_by env.header.moduleData.size - idx let tasks ← go ngen #[] 0 0 0 let r : InitResults α := tasks.foldl (init := {}) (· ++ ·.get) r.errors.forM logImportFailure return r.tree.toRefinedDiscrTree /-- A discriminator tree for the current module's declarations only. Note: We use different discrimination trees for imported and current module declarations since imported declarations are typically much more numerous but not changed while the current module is edited. -/ structure ModuleDiscrTreeRef (α : Type _) where /-- The reference to the `RefinedDiscrTree`. -/ ref : IO.Ref (RefinedDiscrTree α) private def createModulePreDiscrTree (cctx : Core.Context) (ngen : NameGenerator) (env : Environment) (act : Name → ConstantInfo → MetaM (List (α × List (Key × LazyEntry)))) : BaseIO (InitResults α) := do let modName := env.header.mainModule let data ← ImportErrorData.new let r ← env.constants.map₂.foldlM (init := {}) (addConstToPreDiscrTree cctx env modName data (← IO.mkRef {}) (← IO.mkRef { env, ngen }) act) toInitResults data r /-- Create a `RefinedDiscrTree` for current module declarations, consisting of all entries generated by `act` from constants in the current file. This is called by `addConstToPreDiscrTree`. -/ def createModuleDiscrTree (act : Name → ConstantInfo → MetaM (List (α × List (Key × LazyEntry)))) : CoreM (RefinedDiscrTree α) := do let env ← getEnv let ngen ← getChildNgen let ctx ← readThe Core.Context let { tree, errors } ← createModulePreDiscrTree ctx ngen env act errors.forM logImportFailure return tree.toRefinedDiscrTree /-- Create a reference for a `RefinedDiscrTree` for current module declarations. -/ def createModuleTreeRef (act : Name → ConstantInfo → MetaM (List (α × List (Key × LazyEntry)))) : MetaM (ModuleDiscrTreeRef α) := do profileitM Exception "build module discriminator tree" (← getOptions) do let t ← createModuleDiscrTree act pure { ref := ← IO.mkRef t } end Lean.Meta.RefinedDiscrTree
.lake/packages/mathlib/Mathlib/Lean/Meta/RefinedDiscrTree/Basic.lean
import Mathlib.Init /-! # Basic Definitions for `RefinedDiscrTree` We define * `Key`, the discrimination tree key * `LazyEntry`, the partial, lazy computation of a sequence of `Key`s * `Trie`, a node of the discrimination tree, which is indexed with `Key`s and stores an array of pending `LazyEntry`s * `RefinedDiscrTree`, the discrimination tree itself. -/ namespace Lean.Meta.RefinedDiscrTree /-- Discrimination tree key. -/ inductive Key where /-- A metavariable. This key matches with anything. -/ | star /-- A metavariable. This key matches with anything. It stores an identifier. -/ | labelledStar (id : Nat) /-- An opaque variable. This key only matches with `Key.star`. -/ | opaque /-- A constant. It stores the name and the arity. -/ | const (declName : Name) (nargs : Nat) /-- A free variable. It stores the `FVarId` and the arity. -/ | fvar (fvarId : FVarId) (nargs : Nat) /-- A bound variable, from a lambda or forall binder. It stores the De Bruijn index and the arity. -/ | bvar (deBruijnIndex nargs : Nat) /-- A literal. -/ | lit (v : Literal) /-- A sort. Universe levels are ignored. -/ | sort /-- A lambda function. -/ | lam /-- A dependent arrow. -/ | forall /-- A projection. It stores the structure name, the projection index and the arity. -/ | proj (typeName : Name) (idx nargs : Nat) deriving Inhabited, BEq /- At the root, `.const` is the most common key, and it is very uncommon to get the same constant name with a different arity. So for performance, we just use `hash name` to hash `.const name _`. -/ private nonrec def Key.hash : Key → UInt64 | .star => 0 | .labelledStar id => mixHash 5 <| hash id | .opaque => 1 | .const name _ => hash name | .fvar fvarId nargs => mixHash 6 <| mixHash (hash fvarId) (hash nargs) | .bvar idx nargs => mixHash 7 <| mixHash (hash idx) (hash nargs) | .lit v => mixHash 8 <| hash v | .sort => 2 | .lam => 3 | .«forall» => 4 | .proj name idx nargs => mixHash (hash nargs) <| mixHash (hash name) (hash idx) instance : Hashable Key := ⟨Key.hash⟩ private def Key.format : Key → Format | .star => f!"*" | .labelledStar id => f!"*{id}" | .opaque => "◾" | .const name nargs => f!"⟨{name}, {nargs}⟩" | .fvar fvarId nargs => f!"⟨{fvarId.name}, {nargs}⟩" | .lit (Literal.natVal n) => f!"{n}" | .lit (Literal.strVal s) => f!"{s.quote}" | .sort => "Sort" | .bvar i nargs => f!"⟨#{i}, {nargs}⟩" | .lam => "λ" | .forall => "∀" | .proj name idx nargs => f!"⟨{name}.{idx}, {nargs}⟩" instance : ToFormat Key := ⟨Key.format⟩ /-- Converts an entry (i.e., `List Key`) to the discrimination tree into `MessageData` that is more user-friendly. This is a copy of `Lean.Meta.DiscrTree.keysAsPattern` -/ partial def keysAsPattern (keys : Array Key) : CoreM MessageData := do let (msg, keys) ← go (paren := false) |>.run keys.toList if !keys.isEmpty then throwError "illegal discrimination tree entry: {keys.map Key.format}" return msg where /-- Get the next key. -/ next : StateRefT (List Key) CoreM Key := do let key :: keys ← get | throwError "illegal discrimination tree entry: {keys.map Key.format}" set keys return key /-- Format the application `f args`. -/ mkApp (f : MessageData) (nargs : Nat) (paren : Bool) : StateRefT (List Key) CoreM MessageData := if nargs == 0 then return f else do let mut r := m!"" for _ in [:nargs] do r := r ++ Format.line ++ (← go) r := f ++ .nest 2 r if paren then return .paren r else return .group r /-- Format the next expression. -/ go (paren := true) : StateRefT (List Key) CoreM MessageData := do let key ← next match key with | .const declName nargs => mkApp m!"{← mkConstWithLevelParams declName}" nargs paren | .fvar fvarId nargs => mkApp m!"{mkFVar fvarId}" nargs paren | .proj _ i nargs => mkApp m!"{← go}.{i+1}" nargs paren | .bvar i nargs => mkApp m!"#{i}" nargs paren | .lam => return parenthesize m!"λ, {← go (paren := false)}" paren | .forall => return parenthesize m!"{← go} → {← go (paren := false)}" paren | _ => return key.format /-- Add parentheses if `paren == true`. -/ parenthesize (msg : MessageData) (paren : Bool) : MessageData := if paren then msg.paren else msg.group /-- Return the number of arguments that the `Key` takes. -/ def Key.arity : Key → Nat | .const _ nargs => nargs | .fvar _ nargs => nargs | .bvar _ nargs => nargs | .lam => 1 | .forall => 2 | .proj _ _ nargs => nargs + 1 | _ => 0 /-- The information for computing the keys of a subexpression. -/ structure ExprInfo where /-- The expression -/ expr : Expr /-- Variables that come from a lambda or forall binder. The list index gives the De Bruijn index. -/ bvars : List FVarId := [] /-- The local context, which contains the introduced bound variables. -/ lctx : LocalContext /-- The local instances, which may contain the introduced bound variables. -/ localInsts : LocalInstances /-- The `Meta.Config` used by this entry. -/ cfg : Config /-- Creates an `ExprInfo` using the current context. -/ def mkExprInfo (expr : Expr) (bvars : List FVarId) : MetaM ExprInfo := return { expr, bvars, lctx := ← getLCtx localInsts := ← getLocalInstances cfg := ← getConfig } /-- The possible values that can appear in the stack -/ inductive StackEntry where /-- `.star` is an expression that will not be explicitly indexed. -/ | star /-- `.expr` is an expression that will be indexed. -/ | expr (info : ExprInfo) private def StackEntry.format : StackEntry → Format | .star => f!".star" | .expr info => f!".expr {info.expr}" instance : ToFormat StackEntry := ⟨StackEntry.format⟩ /-- A `LazyEntry` represents a snapshot of the computation of encoding an `Expr` as `Array Key`. This is used for computing the keys one by one. -/ structure LazyEntry where /-- If an expression creates more entries in the stack, for example because it is an application, then instead of pushing to the stack greedily, we only extend the stack once we need to. So, the field `previous` is used to extend the `stack` before looking in the `stack`. For example in `10.add (20.add 30)`, after computing the key `⟨Nat.add, 2⟩`, the stack is still empty, and `previous` will be `10.add (20.add 30)`. -/ previous : Option ExprInfo := none /-- The stack, used to emulate recursion. It contains the list of all expressions for which the keys still need to be computed, in that order. For example in `10.add (20.add 30)`, after computing the keys `⟨Nat.add, 2⟩` and `10`, the stack will be a list of length 1 containing the expression `20.add 30`. -/ stack : List StackEntry := [] /-- The metavariable context, which may contain variables appearing in this entry. -/ mctx : MetavarContext /-- `MVarId`s corresponding to the `.labelledStar` labels. The index in the array is the label. It is `none` if we use `.star` instead of `labelledStar`, for example when encoding the lookup expression. -/ labelledStars? : Option (Array MVarId) /-- The `Key`s that have already been computed. Sometimes, more than one `Key` ends up being computed in one go. This happens when there are lambda binders (because it depends on the body whether the lambda key should be indexed or not). In that case the remaining `Key`s are stored in `results`. -/ computedKeys : List Key := [] deriving Inhabited /-- Creates a `LazyEntry` using the current metavariable context. -/ def mkInitLazyEntry (labelledStars : Bool) : MetaM LazyEntry := return { mctx := ← getMCtx labelledStars? := if labelledStars then some #[] else none } private def LazyEntry.format (entry : LazyEntry) : Format := Id.run do let mut parts := #[f!"stack: {entry.stack}"] unless entry.computedKeys == [] do parts := parts.push f!"results: {entry.computedKeys}" if let some info := entry.previous then parts := parts.push f!"todo: {info.expr}" return Format.joinSep parts.toList ", " instance : ToFormat LazyEntry := ⟨LazyEntry.format⟩ /-- Array index of a `Trie α` in the `tries` of a `RefinedDiscrTree`. -/ abbrev TrieIndex := Nat /-- Discrimination tree trie. See `RefinedDiscrTree`. A `Trie` will normally have exactly one of the following - nonempty `values` - nonempty `stars`, `labelledStars` and/or `children` - nonempty `pending` But defining it as a structure that can have all at the same time turns out to be easier. -/ structure Trie (α : Type) where node :: /-- Return values, at a leaf -/ values : Array α /-- Following `Trie`s based on a `Key.star`. -/ star : Option TrieIndex /-- Following `Trie`s based on a `Key.labelledStar`. -/ labelledStars : Std.HashMap Nat TrieIndex /-- Following `Trie`s based on the `Key`. -/ children : Std.HashMap Key TrieIndex /-- Lazy entries that still have to be evaluated. -/ pending : Array (LazyEntry × α) instance {α : Type} : Inhabited (Trie α) := ⟨.node #[] none {} {} #[]⟩ end RefinedDiscrTree open RefinedDiscrTree in /-- Lazy refined discrimination tree. It is an index from expressions to values of type `α`. We store all of the nodes in one `Array`, `tries`, instead of using a 'normal' inductive type. This is so that we can modify the tree globally, which is very useful when evaluating lazy entries and saving the result globally. -/ structure RefinedDiscrTree (α : Type) where /-- `Trie`s at the root based of the `Key`. -/ root : Std.HashMap Key TrieIndex := {} /-- Array of trie entries. Should be owned by this trie. -/ tries : Array (Trie α) := #[] deriving Inhabited namespace RefinedDiscrTree variable {α : Type} private partial def format [ToFormat α] (tree : RefinedDiscrTree α) : Format := let lines := tree.root.fold (init := #[]) fun lines key trie => lines.push (Format.nest 2 f!"{key} =>{Format.line}{go trie}") if lines.size = 0 then f!"<empty discrimination tree>" else "Discrimination tree flowchart:" ++ Format.joinSep lines.toList "\n" where go (trie : TrieIndex) : Format := Id.run do let { values, star, labelledStars, children, pending } := tree.tries[trie]! let mut lines := #[] unless pending.isEmpty do lines := lines.push f!"pending entries: {pending.map (·.2)}" unless values.isEmpty do lines := lines.push f!"entries: {values}" if let some trie := star then lines := lines.push (Format.nest 2 f!"* =>{Format.line}{go trie}") lines := labelledStars.fold (init := lines) fun lines key trie => lines.push (Format.nest 2 f!"*{key} =>{Format.line}{go trie}") lines := children.fold (init := lines) fun lines key trie => lines.push (Format.nest 2 f!"{key} =>{Format.line}{go trie}") if lines.isEmpty then f!"<empty node>" else Format.joinSep lines.toList "\n" instance [ToFormat α] : ToFormat (RefinedDiscrTree α) := ⟨format⟩ end Lean.Meta.RefinedDiscrTree
.lake/packages/mathlib/Mathlib/Lean/Meta/RefinedDiscrTree/Encode.lean
import Mathlib.Lean.Meta.RefinedDiscrTree.Basic import Lean.Meta.DiscrTree /-! # Encoding an `Expr` as a sequence of `Key`s We compute the encoding of an expression in a lazy way. This means computing only one `Key` at a time and storing the state of the remaining computation in a `LazyEntry`. Each step is computed by `evalLazyEntryWithEta : LazyEntry → MetaM (Option (List (Key × LazyEntry)))`. It returns `none` when the last `Key` has already been reached. The first step, which is used when initializing the tree, is computed by `initializeLazyEntryWithEta`. To compute all the keys at once, we have * `encodeExprWithEta`, which computes all possible key sequences. * `encodeExpr`, which computes the canonical key sequence. This will be used for expressions that are looked up in a `RefinedDiscrTree` using `getMatch`. -/ namespace Lean.Meta.RefinedDiscrTree /-- The context for the `LazyM` monad -/ private structure Context where /-- Variables that come from a lambda or forall binder. The list index gives the De Bruijn index. -/ bvars : List FVarId /-- The monad used for evaluating a `LazyEntry`. -/ private abbrev LazyM := ReaderT Context <| StateT LazyEntry MetaM private def mkLabelledStar (mvarId : MVarId) : LazyM Key := modifyGet fun entry => if let some stars := entry.labelledStars? then match stars.idxOf? mvarId with | some idx => (.labelledStar idx, entry) | none => (.labelledStar stars.size, { entry with labelledStars? := stars.push mvarId }) else (.star, entry) /-- Sometimes, we need to not index lambda binders, in particular when the body is the application of a metavariable. In the case where we do index the lambda binders, `withLams` efficiently adds the lambdas and `key` to the result. -/ @[inline] private def withLams (lambdas : List FVarId) (key : Key) : StateT LazyEntry MetaM Key := do match lambdas with | [] => return key | _ :: tail => -- Add `key` and `lambdas.length - 1` lambdas to the result, returning the final lambda. modify ({ · with computedKeys := tail.foldl (init := [key]) (fun _ => .lam :: ·) }) return .lam open private toNatLit? from Lean.Meta.DiscrTree in @[inline] private def encodingStepAux (e : Expr) (lambdas : List FVarId) (root : Bool) : LazyM Key := do withLams lambdas (← go) where go := do /- If entries need to be added to the stack, we don't do that now, because of the lazy design. Instead, we set `previous` to be `e`, and later, `processPrevious` adds the required entries to the stack. -/ let setEAsPrevious : LazyM Unit := do let info ← mkExprInfo e (lambdas ++ (← read).bvars) modify fun s => { s with previous := some info } match e.getAppFn with | .const n _ => unless root do if let some v := toNatLit? e then return .lit v if e.getAppNumArgs != 0 then setEAsPrevious return .const n e.getAppNumArgs | .proj n i _ => setEAsPrevious return .proj n i e.getAppNumArgs | .fvar fvarId => let bvars := lambdas ++ (← read).bvars if e.getAppNumArgs != 0 then setEAsPrevious if let some idx := bvars.idxOf? fvarId then return .bvar idx e.getAppNumArgs else return .fvar fvarId e.getAppNumArgs | .mvar mvarId => if e.isApp then /- If `e.isApp`, we don't index `lambdas`, since for example `fun x => ?m x x` may be any function. -/ return .star else /- If `e` is `.mvar mvarId`, we do index `lambdas`, since it is a constant function. We create a `.labelledStar` key that is identified by `mvarId`, so that multiple appearances of `.mvar mvarId` are indexed the same. -/ mkLabelledStar mvarId | .forallE .. => setEAsPrevious return .forall | .lit v => return .lit v | .sort _ => return .sort | .letE .. => return .opaque | .lam .. => return .opaque | _ => unreachable! /-- Run `k` on all pairs of body, bound variables that could possibly appear due to η-reduction -/ private def etaPossibilities (e : Expr) (lambdas : List FVarId) (root : Bool) (entry : LazyEntry) : ReaderT Context MetaM (List (Key × LazyEntry)) := do return (← (encodingStepAux e lambdas root).run (← read) |>.run entry) :: (← match e, lambdas with | .app f a, fvarId :: lambdas => if isStarWithArg (.fvar fvarId) a && !f.getAppFn.isMVar then etaPossibilities f lambdas root entry else return [] | _, _ => return []) where /-- Check whether the expression is represented by `Key.star` and has `arg` as an argument. -/ isStarWithArg (arg : Expr) : Expr → Bool | .app f a => if a == arg then f.getAppFn.isMVar else isStarWithArg arg f | _ => false /-- Repeatedly reduce while stripping lambda binders and introducing their variables -/ @[specialize] private partial def lambdaTelescopeReduce {m} {α} [Nonempty (m α)] [Monad m] [MonadLiftT MetaM m] [MonadControlT MetaM m] (e : Expr) (lambdas : List FVarId) (noIndex : List FVarId → m α) (k : Expr → List FVarId → m α) : m α := do /- expressions marked with `no_index` should be indexed with a star -/ if DiscrTree.hasNoindexAnnotation e then noIndex lambdas else match ← DiscrTree.reduce e with | .lam n d b bi => withLocalDecl n bi d fun fvar => lambdaTelescopeReduce (b.instantiate1 fvar) (fvar.fvarId! :: lambdas) noIndex k | e => k e lambdas /-- A single step in encoding an `Expr` into `Key`s. -/ private def encodingStepWithEta (e : Expr) (root : Bool) (entry : LazyEntry) : ReaderT Context MetaM (List (Key × LazyEntry)) := lambdaTelescopeReduce e [] (fun lambdas => return [← (withLams lambdas .star).run entry]) (fun e lambdas => etaPossibilities e lambdas root entry) /-- A single step in encoding an `Expr` into `Key`s. -/ private def encodingStep (e : Expr) (root : Bool) : LazyM Key := do lambdaTelescopeReduce e [] (fun lambdas => withLams lambdas .star) (fun e lambdas => encodingStepAux e lambdas root) /-- Encode `e` as a sequence of keys, computing only the first `Key`. -/ @[inline] def initializeLazyEntryWithEtaAux (e : Expr) (labelledStars : Bool) : MetaM (List (Key × LazyEntry)) := do (encodingStepWithEta e true (← mkInitLazyEntry labelledStars)).run { bvars := [] } /-- Encode `e` as a sequence of keys, computing only the first `Key`. -/ def initializeLazyEntryWithEta (e : Expr) (labelledStars : Bool := true) : MetaM (List (Key × LazyEntry)) := do withReducible do initializeLazyEntryWithEtaAux e labelledStars /-- Encode `e` as a sequence of keys, computing only the first `Key`. -/ private def initializeLazyEntry (e : Expr) (labelledStars : Bool) : MetaM (Key × LazyEntry) := do ((encodingStep e true).run { bvars := [] }).run (← mkInitLazyEntry labelledStars) /-- Auxiliary function for `evalLazyEntry` -/ private partial def evalLazyEntryAux (entry : LazyEntry) (eta : Bool) : MetaM (Option (List (Key × LazyEntry))) := do match entry.stack with | [] => return none | stackEntry :: stack => let entry := { entry with stack } match stackEntry with | .star => return some [(.star, entry)] | .expr { expr, bvars, lctx, localInsts, cfg } => withLCtx lctx localInsts do withConfig (fun _ => cfg) do if eta then return some (← encodingStepWithEta expr false entry |>.run { bvars := bvars }) else return some [← encodingStep expr false |>.run { bvars := bvars } |>.run entry] /-- Determine for each argument whether it should be ignored, and return a list consisting of one `StackEntry` for each argument. -/ private partial def getStackEntries (fn : Expr) (args : Array Expr) (bvars : List FVarId) : MetaM (List StackEntry) := do let mut fnType ← inferType fn loop fnType 0 0 [] where /-- The main loop of `getStackEntries` -/ loop (fnType : Expr) (i j : Nat) (entries : List StackEntry) : MetaM (List StackEntry) := do if h : i < args.size then let arg := args[i] let cont j d b bi := do if ← isIgnoredArg arg d bi then loop b (i+1) j (.star :: entries) else loop b (i+1) j (.expr (← mkExprInfo arg bvars) :: entries) let rec reduce := do match ← whnfD (fnType.instantiateRevRange j i args) with | .forallE _ d b bi => cont i d b bi | fnType => throwFunctionExpected fnType match fnType with | .forallE _ d b bi => cont j d b bi | _ => reduce else return entries /-- Determine whether the argument should be ignored. -/ isIgnoredArg (arg domain : Expr) (binderInfo : BinderInfo) : MetaM Bool := do if domain.isOutParam then return true else match binderInfo with | .instImplicit => return true | .implicit | .strictImplicit => return !(← isType arg) | .default => isProof arg /-- If `entry.previous.isSome`, then replace it with `none`, and add the required entries to entry.stack`. -/ private def processPrevious (entry : LazyEntry) : MetaM LazyEntry := do let some { expr, bvars, lctx, localInsts, cfg } := entry.previous | return entry let entry := { entry with previous := none } withLCtx lctx localInsts do withConfig (fun _ => cfg) do expr.withApp fun fn args => do let stackArgs (entry : LazyEntry) : MetaM LazyEntry := do let entries ← getStackEntries fn args bvars return { entry with stack := entries.reverseAux entry.stack } match fn with | .forallE n d b bi => let d' := .expr (← mkExprInfo d bvars) let b' ← withLocalDecl n bi d fun fvar => return .expr (← mkExprInfo (b.instantiate1 fvar) (fvar.fvarId! :: bvars)) return { entry with stack := d' :: b' :: entry.stack } | .proj n _ a => let entry ← stackArgs entry if isClass (← getEnv) n then return { entry with stack := .star :: entry.stack } else return { entry with stack := .expr (← mkExprInfo a bvars) :: entry.stack } | _ => stackArgs entry /-- A single step in evaluating a `LazyEntry`. Allow multiple different outcomes. -/ def evalLazyEntry (entry : LazyEntry) (eta : Bool) : MetaM (Option (List (Key × LazyEntry))) := do if let key :: computedKeys := entry.computedKeys then -- If there is already a result available, use it. return some [(key, { entry with computedKeys })] else withMCtx entry.mctx do let entry ← processPrevious entry evalLazyEntryAux entry eta /-- Return all encodings of `e` as a `Array Key`. This is used for testing. -/ partial def encodeExprWithEta (e : Expr) (labelledStars : Bool) : MetaM (Array (Array Key)) := withReducible do let entries ← (encodingStepWithEta e true (← mkInitLazyEntry labelledStars)).run { bvars := [] } let entries := entries.map fun (key, entry) => (#[key], entry) go entries.toArray #[] where /-- The main loop for `encodeExpr`. -/ go (todo : Array (Array Key × LazyEntry)) (result : Array (Array Key)) : MetaM (Array (Array Key)) := do if h : todo.size = 0 then return result else -- use an if-then-else instead of if-then-return, so that `go` is tail recursive let (keys, entry) := todo.back let todo := todo.pop match ← evalLazyEntry entry true with | some xs => let rec /-- This variation on `List.fold` ensures that the array `keys` isn't copied unnecessarily. -/ fold xs todo := match xs with | [] => todo | (key, entry) :: [] => todo.push (keys.push key, entry) | (key, entry) :: xs => fold xs (todo.push (keys.push key, entry)) go (fold xs todo) result | none => go todo (result.push keys) /-- Completely evaluate a `LazyEntry`. -/ partial def LazyEntry.toList (entry : LazyEntry) (result : List Key := []) : MetaM (List Key) := do match ← evalLazyEntry entry false with | some [(key, entry')] => entry'.toList (key :: result) | some _ => panic! "`evalLazyEntry` with `eta := false` can only give a singleton list" | none => return result.reverse /-- Return the canonical encoding of `e` as a `Array Key`. This is used for looking up `e` in a `RefinedDiscrTree`. -/ def encodeExpr (e : Expr) (labelledStars : Bool) : MetaM (Key × List Key) := withReducible do let (key, entry) ← initializeLazyEntry e labelledStars return (key, ← entry.toList) end Lean.Meta.RefinedDiscrTree
.lake/packages/mathlib/Mathlib/Lean/Expr/Rat.lean
import Mathlib.Init /-! # Additional operations on Expr and rational numbers This file defines some operations involving `Expr` and rational numbers. ## Main definitions * `Lean.Expr.isExplicitNumber`: is an expression a number in normal form? This includes natural numbers, integers and rationals. -/ open Lean in instance : ToExpr Rat where toExpr q := mkApp2 (.const ``mkRat []) (toExpr q.num) (toExpr q.den) toTypeExpr := .const ``Rat [0] namespace Lean.Expr /-- Check if an expression is a "rational in normal form", i.e. either an integer number in normal form, or `n / d` where `n` is an integer in normal form, `d` is a natural number in normal form, `d ≠ 1`, and `n` and `d` are coprime (in particular, we check that `(mkRat n d).den = d`). If so returns the rational number. -/ def rat? (e : Expr) : Option Rat := do if e.isAppOfArity ``Div.div 4 then let d ← e.appArg!.nat? guard (d ≠ 1) let n ← e.appFn!.appArg!.int? let q := mkRat n d guard (q.den = d) pure q else e.int? /-- Test if an expression represents an explicit number written in normal form: * A "natural number in normal form" is an expression `OfNat.ofNat n`, even if it is not of type `ℕ`, as long as `n` is a literal. * An "integer in normal form" is an expression which is either a natural number in number form, or `-n`, where `n` is a natural number in normal form. * A "rational in normal form" is an expressions which is either an integer in normal form, or `n / d` where `n` is an integer in normal form, `d` is a natural number in normal form, `d ≠ 1`, and `n` and `d` are coprime (in particular, we check that `(mkRat n d).den = d`). -/ def isExplicitNumber : Expr → Bool | .lit _ => true | .mdata _ e => isExplicitNumber e | e => e.rat?.isSome end Lean.Expr
.lake/packages/mathlib/Mathlib/Lean/Expr/ExtraRecognizers.lean
import Mathlib.Data.Set.Operations /-! # Additional Expr recognizers needing theory imports -/ namespace Lean.Expr /-- If `e` is a coercion of a set to a type, return the set. Succeeds either for `Set.Elem s` terms or `{x // x ∈ s}` subtype terms. -/ def coeTypeSet? (e : Expr) : Option Expr := do if e.isAppOfArity ``Set.Elem 2 then return e.appArg! else if e.isAppOfArity ``Subtype 2 then let .lam _ _ body _ := e.appArg! | failure guard <| body.isAppOfArity ``Membership.mem 5 let #[_, _, inst, .bvar 0, s] := body.getAppArgs | failure guard <| inst.isAppOfArity ``Set.instMembership 1 return s else failure end Lean.Expr
.lake/packages/mathlib/Mathlib/Lean/Expr/ReplaceRec.lean
import Lean.Expr import Mathlib.Util.MemoFix /-! # ReplaceRec We define a more flexible version of `Expr.replace` where we can use recursive calls even when replacing a subexpression. We completely mimic the implementation of `Expr.replace`. -/ namespace Lean.Expr /-- A version of `Expr.replace` where the replacement function is available to the function `f?`. `replaceRec f? e` will call `f? r e` where `r = replaceRec f?`. If `f? r e = none` then `r` will be called on each immediate subexpression of `e` and reassembled. If it is `some x`, traversal terminates and `x` is returned. If you wish to recursively replace things in the implementation of `f?`, you can apply `r`. The function is also memoised, which means that if the same expression (by reference) is encountered the cached replacement is used. -/ def replaceRec (f? : (Expr → Expr) → Expr → Option Expr) : Expr → Expr := memoFix fun r e ↦ match f? r e with | some x => x | none => Id.run <| traverseChildren (pure <| r ·) e end Lean.Expr
.lake/packages/mathlib/Mathlib/Lean/Expr/Basic.lean
import Mathlib.Init import Lean.Expr /-! # Additional operations on Expr and related types This file defines basic operations on the types expr, name, declaration, level, environment. This file is mostly for non-tactics. -/ namespace Lean namespace BinderInfo /-! ### Declarations about `BinderInfo` -/ /-- The brackets corresponding to a given `BinderInfo`. -/ def brackets : BinderInfo → String × String | BinderInfo.implicit => ("{", "}") | BinderInfo.strictImplicit => ("{{", "}}") | BinderInfo.instImplicit => ("[", "]") | _ => ("(", ")") end BinderInfo namespace Name /-! ### Declarations about `name` -/ /-- Find the largest prefix `n` of a `Name` such that `f n != none`, then replace this prefix with the value of `f n`. -/ @[specialize] def mapPrefix (f : Name → Option Name) (n : Name) : Name := Id.run do if let some n' := f n then return n' match n with | anonymous => anonymous | str n' s => mkStr (mapPrefix f n') s | num n' i => mkNum (mapPrefix f n') i /-- Build a name from components. For example, ``from_components [`foo, `bar]`` becomes ``` `foo.bar```. It is the inverse of `Name.components` on list of names that have single components. -/ def fromComponents : List Name → Name := go .anonymous where /-- Auxiliary for `Name.fromComponents` -/ go : Name → List Name → Name | n, [] => n | n, s :: rest => go (s.updatePrefix n) rest /-- Update the last component of a name. -/ def updateLast (f : String → String) : Name → Name | .str n s => .str n (f s) | n => n /-- Get the last field of a name as a string. Doesn't raise an error when the last component is a numeric field. -/ def lastComponentAsString : Name → String | .str _ s => s | .num _ n => toString n | .anonymous => "" /-- `nm.splitAt n` splits a name `nm` in two parts, such that the *second* part has depth `n`, i.e. `(nm.splitAt n).2.getNumParts = n` (assuming `nm.getNumParts ≥ n`). Example: ``splitAt `foo.bar.baz.back.bat 1 = (`foo.bar.baz.back, `bat)``. -/ def splitAt (nm : Name) (n : Nat) : Name × Name := let (nm2, nm1) := nm.componentsRev.splitAt n (.fromComponents <| nm1.reverse, .fromComponents <| nm2.reverse) /-- `isPrefixOf? pre nm` returns `some post` if `nm = pre ++ post`. Note that this includes the case where `nm` has multiple more namespaces. If `pre` is not a prefix of `nm`, it returns `none`. -/ def isPrefixOf? (pre nm : Name) : Option Name := if pre == nm then some anonymous else match nm with | anonymous => none | num p' a => (isPrefixOf? pre p').map (·.num a) | str p' s => (isPrefixOf? pre p').map (·.str s) open Meta -- from Lean.Server.Completion def isBlackListed {m} [Monad m] [MonadEnv m] (declName : Name) : m Bool := do if declName == ``sorryAx then return true if declName matches .str _ "inj" then return true if declName matches .str _ "noConfusionType" then return true let env ← getEnv pure <| declName.isInternalDetail || isAuxRecursor env declName || isNoConfusion env declName <||> isRec declName <||> isMatcher declName end Name namespace ConstantInfo /-- Checks whether this `ConstantInfo` is a definition. -/ def isDef : ConstantInfo → Bool | defnInfo _ => true | _ => false /-- Checks whether this `ConstantInfo` is a theorem. -/ def isThm : ConstantInfo → Bool | thmInfo _ => true | _ => false /-- Update `ConstantVal` (the data common to all constructors of `ConstantInfo`) in a `ConstantInfo`. -/ def updateConstantVal : ConstantInfo → ConstantVal → ConstantInfo | defnInfo info, v => defnInfo {info with toConstantVal := v} | axiomInfo info, v => axiomInfo {info with toConstantVal := v} | thmInfo info, v => thmInfo {info with toConstantVal := v} | opaqueInfo info, v => opaqueInfo {info with toConstantVal := v} | quotInfo info, v => quotInfo {info with toConstantVal := v} | inductInfo info, v => inductInfo {info with toConstantVal := v} | ctorInfo info, v => ctorInfo {info with toConstantVal := v} | recInfo info, v => recInfo {info with toConstantVal := v} /-- Update the name of a `ConstantInfo`. -/ def updateName (c : ConstantInfo) (name : Name) : ConstantInfo := c.updateConstantVal {c.toConstantVal with name} /-- Update the type of a `ConstantInfo`. -/ def updateType (c : ConstantInfo) (type : Expr) : ConstantInfo := c.updateConstantVal {c.toConstantVal with type} /-- Update the level parameters of a `ConstantInfo`. -/ def updateLevelParams (c : ConstantInfo) (levelParams : List Name) : ConstantInfo := c.updateConstantVal {c.toConstantVal with levelParams} /-- Update the value of a `ConstantInfo`, if it has one. -/ def updateValue : ConstantInfo → Expr → ConstantInfo | defnInfo info, v => defnInfo {info with value := v} | thmInfo info, v => thmInfo {info with value := v} | opaqueInfo info, v => opaqueInfo {info with value := v} | d, _ => d /-- Turn a `ConstantInfo` into a declaration. -/ def toDeclaration! : ConstantInfo → Declaration | defnInfo info => Declaration.defnDecl info | thmInfo info => Declaration.thmDecl info | axiomInfo info => Declaration.axiomDecl info | opaqueInfo info => Declaration.opaqueDecl info | quotInfo _ => panic! "toDeclaration for quotInfo not implemented" | inductInfo _ => panic! "toDeclaration for inductInfo not implemented" | ctorInfo _ => panic! "toDeclaration for ctorInfo not implemented" | recInfo _ => panic! "toDeclaration for recInfo not implemented" end ConstantInfo open Meta /-- Same as `mkConst`, but with fresh level metavariables. -/ def mkConst' (constName : Name) : MetaM Expr := do return mkConst constName (← (← getConstInfo constName).levelParams.mapM fun _ => mkFreshLevelMVar) namespace Expr /-! ### Declarations about `Expr` -/ def bvarIdx? : Expr → Option Nat | bvar idx => some idx | _ => none /-- Invariant: `i : ℕ` should be less than the size of `as : Array Expr`. -/ private def getAppAppsAux : Expr → Array Expr → Nat → Array Expr | .app f a, as, i => getAppAppsAux f (as.set! i (.app f a)) (i-1) | _, as, _ => as /-- Given `f a b c`, return `#[f a, f a b, f a b c]`. Each entry in the array is an `Expr.app`, and this array has the same length as the one returned by `Lean.Expr.getAppArgs`. -/ @[inline] def getAppApps (e : Expr) : Array Expr := let dummy := mkSort levelZero let nargs := e.getAppNumArgs getAppAppsAux e (.replicate nargs dummy) (nargs-1) /-- Erase proofs in an expression by replacing them with `sorry`s. This function replaces all proofs in the expression and in the types that appear in the expression by `sorryAx`s. The resulting expression has the same type as the old one. It is useful, e.g., to verify if the proof-irrelevant part of a definition depends on a variable. -/ def eraseProofs (e : Expr) : MetaM Expr := Meta.transform (skipConstInApp := true) e (pre := fun e => do if (← Meta.isProof e) then return .continue (← mkSorry (← inferType e) true) else return .continue) /-- If an `Expr` has the form `Type u`, then return `some u`, otherwise `none`. -/ def type? : Expr → Option Level | .sort u => u.dec | _ => none /-- `isConstantApplication e` checks whether `e` is syntactically an application of the form `(fun x₁ ⋯ xₙ => H) y₁ ⋯ yₙ` where `H` does not contain the variable `xₙ`. In other words, it does a syntactic check that the expression does not depend on `yₙ`. -/ def isConstantApplication (e : Expr) := e.isApp && aux e.getAppNumArgs'.pred e.getAppFn' e.getAppNumArgs' where /-- `aux depth e n` checks whether the body of the `n`-th lambda of `e` has loose bvar `depth - 1`. -/ aux (depth : Nat) : Expr → Nat → Bool | .lam _ _ b _, n + 1 => aux depth b n | e, 0 => !e.hasLooseBVar (depth - 1) | _, _ => false /-- Counts the immediate depth of a nested `let` expression. -/ def letDepth : Expr → Nat | .letE _ _ _ b _ => b.letDepth + 1 | _ => 0 open Meta /-- Check that an expression contains no metavariables (after instantiation). -/ -- There is a `TacticM` level version of this, but it's useful to have in `MetaM`. def ensureHasNoMVars (e : Expr) : MetaM Unit := do let e ← instantiateMVars e if e.hasExprMVar then throwError "tactic failed, resulting expression contains metavariables{indentExpr e}" /-- Construct the term of type `α` for a given natural number (doing typeclass search for the `OfNat` instance required). -/ def ofNat (α : Expr) (n : Nat) : MetaM Expr := do mkAppOptM ``OfNat.ofNat #[α, mkRawNatLit n, none] /-- Construct the term of type `α` for a given integer (doing typeclass search for the `OfNat` and `Neg` instances required). -/ def ofInt (α : Expr) : Int → MetaM Expr | Int.ofNat n => Expr.ofNat α n | Int.negSucc n => do mkAppM ``Neg.neg #[← Expr.ofNat α (n + 1)] section recognizers /-- Return `some n` if `e` is one of the following - a nat literal (numeral) - `Nat.zero` - `Nat.succ x` where `isNumeral x` - `OfNat.ofNat _ x _` where `isNumeral x` -/ partial def numeral? (e : Expr) : Option Nat := if let some n := e.rawNatLit? then n else let e := e.consumeMData -- `OfNat` numerals may have `no_index` around them from `ofNat()` let f := e.getAppFn if !f.isConst then none else let fName := f.constName! if fName == ``Nat.succ && e.getAppNumArgs == 1 then (numeral? e.appArg!).map Nat.succ else if fName == ``OfNat.ofNat && e.getAppNumArgs == 3 then numeral? (e.getArg! 1) else if fName == ``Nat.zero && e.getAppNumArgs == 0 then some 0 else none /-- Test if an expression is either `Nat.zero`, or `OfNat.ofNat 0`. -/ def zero? (e : Expr) : Bool := match e.numeral? with | some 0 => true | _ => false /-- Tests is if an expression matches either `x ≠ y` or `¬ (x = y)`. If it matches, returns `some (type, x, y)`. -/ def ne?' (e : Expr) : Option (Expr × Expr × Expr) := e.ne? <|> (e.not? >>= Expr.eq?) /-- `Lean.Expr.le? e` takes `e : Expr` as input. If `e` represents `a ≤ b`, then it returns `some (t, a, b)`, where `t` is the Type of `a`, otherwise, it returns `none`. -/ @[inline] def le? (p : Expr) : Option (Expr × Expr × Expr) := do let (type, _, lhs, rhs) ← p.app4? ``LE.le return (type, lhs, rhs) /-- `Lean.Expr.lt? e` takes `e : Expr` as input. If `e` represents `a < b`, then it returns `some (t, a, b)`, where `t` is the Type of `a`, otherwise, it returns `none`. -/ @[inline] def lt? (p : Expr) : Option (Expr × Expr × Expr) := do let (type, _, lhs, rhs) ← p.app4? ``LT.lt return (type, lhs, rhs) /-- Given a proposition `ty` that is an `Eq`, `Iff`, or `HEq`, returns `(tyLhs, lhs, tyRhs, rhs)`, where `lhs : tyLhs` and `rhs : tyRhs`, and where `lhs` is related to `rhs` by the respective relation. See also `Lean.Expr.iff?`, `Lean.Expr.eq?`, and `Lean.Expr.heq?`. -/ def sides? (ty : Expr) : Option (Expr × Expr × Expr × Expr) := if let some (lhs, rhs) := ty.iff? then some (.sort .zero, lhs, .sort .zero, rhs) else if let some (ty, lhs, rhs) := ty.eq? then some (ty, lhs, ty, rhs) else ty.heq? end recognizers universe u def modifyAppArgM {M : Type → Type u} [Functor M] [Pure M] (modifier : Expr → M Expr) : Expr → M Expr | app f a => mkApp f <$> modifier a | e => pure e def modifyRevArg (modifier : Expr → Expr) : Nat → Expr → Expr | 0, (.app f x) => .app f (modifier x) | (i+1), (.app f x) => .app (modifyRevArg modifier i f) x | _, e => e /-- Given `f a₀ a₁ ... aₙ₋₁`, runs `modifier` on the `i`th argument or returns the original expression if out of bounds. -/ def modifyArg (modifier : Expr → Expr) (e : Expr) (i : Nat) (n := e.getAppNumArgs) : Expr := modifyRevArg modifier (n - i - 1) e /-- Given `f a₀ a₁ ... aₙ₋₁`, sets the argument on the `i`th argument to `x` or returns the original expression if out of bounds. -/ def setArg (e : Expr) (i : Nat) (x : Expr) (n := e.getAppNumArgs) : Expr := e.modifyArg (fun _ => x) i n def getRevArg? : Expr → Nat → Option Expr | app _ a, 0 => a | app f _, i+1 => getRevArg! f i | _, _ => none /-- Given `f a₀ a₁ ... aₙ₋₁`, returns the `i`th argument or none if out of bounds. -/ def getArg? (e : Expr) (i : Nat) (n := e.getAppNumArgs) : Option Expr := getRevArg? e (n - i - 1) /-- Given `f a₀ a₁ ... aₙ₋₁`, runs `modifier` on the `i`th argument. An argument `n` may be provided which says how many arguments we are expecting `e` to have. -/ def modifyArgM {M : Type → Type u} [Monad M] (modifier : Expr → M Expr) (e : Expr) (i : Nat) (n := e.getAppNumArgs) : M Expr := do let some a := getArg? e i | return e let a ← modifier a return modifyArg (fun _ ↦ a) e i n /-- Traverses an expression `e` and renames bound variables named `old` to `new`. -/ def renameBVar (e : Expr) (old new : Name) : Expr := match e with | app fn arg => app (fn.renameBVar old new) (arg.renameBVar old new) | lam n ty bd bi => lam (if n == old then new else n) (ty.renameBVar old new) (bd.renameBVar old new) bi | forallE n ty bd bi => forallE (if n == old then new else n) (ty.renameBVar old new) (bd.renameBVar old new) bi | mdata d e' => mdata d (e'.renameBVar old new) | e => e open Lean.Meta in /-- `getBinderName e` returns `some n` if `e` is an expression of the form `∀ n, ...` and `none` otherwise. -/ def getBinderName (e : Expr) : MetaM (Option Name) := do match ← withReducible (whnf e) with | .forallE (binderName := n) .. | .lam (binderName := n) .. => pure (some n) | _ => pure none /-- Map binder names in a nested forall `(a₁ : α₁) → ... → (aₙ : αₙ) → _` -/ def mapForallBinderNames : Expr → (Name → Name) → Expr | .forallE n d b bi, f => .forallE (f n) d (mapForallBinderNames b f) bi | e, _ => e /-- If `e` has a structure as type with field `fieldName`, `mkDirectProjection e fieldName` creates the projection expression `e.fieldName` -/ def mkDirectProjection (e : Expr) (fieldName : Name) : MetaM Expr := do let type ← whnf (← inferType e) let .const structName us := type.getAppFn | throwError "{e} doesn't have a structure as type" let some projName := getProjFnForField? (← getEnv) structName fieldName | throwError "{structName} doesn't have field {fieldName}" return mkAppN (.const projName us) (type.getAppArgs.push e) /-- If `e` has a structure as type with field `fieldName` (either directly or in a parent structure), `mkProjection e fieldName` creates the projection expression `e.fieldName` -/ def mkProjection (e : Expr) (fieldName : Name) : MetaM Expr := do let .const structName _ := (← whnf (← inferType e)).getAppFn | throwError "{e} doesn't have a structure as type" let some baseStruct := findField? (← getEnv) structName fieldName | throwError "No parent of {structName} has field {fieldName}" let mut e := e for projName in (getPathToBaseStructure? (← getEnv) baseStruct structName).get! do let type ← whnf (← inferType e) let .const _structName us := type.getAppFn | throwError "{e} doesn't have a structure as type" e := mkAppN (.const projName us) (type.getAppArgs.push e) mkDirectProjection e fieldName /-- If `e` is a projection of the structure constructor, reduce the projection. Otherwise returns `none`. If this function detects that expression is ill-typed, throws an error. For example, given `Prod.fst (x, y)`, returns `some x`. -/ def reduceProjStruct? (e : Expr) : MetaM (Option Expr) := do let .const cname _ := e.getAppFn | return none let some pinfo ← getProjectionFnInfo? cname | return none let args := e.getAppArgs if ha : args.size = pinfo.numParams + 1 then -- The last argument of a projection is the structure. let sarg := args[pinfo.numParams]'(ha ▸ pinfo.numParams.lt_succ_self) -- Check that the structure is a constructor expression. unless sarg.getAppFn.isConstOf pinfo.ctorName do return none let sfields := sarg.getAppArgs -- The ith projection extracts the ith field of the constructor let sidx := pinfo.numParams + pinfo.i if hs : sidx < sfields.size then return some (sfields[sidx]'hs) else throwError m!"ill-formed expression, {cname} is the {pinfo.i + 1}-th projection function \ but {sarg} does not have enough arguments" else return none /-- Returns true if `e` contains a name `n` where `p n` is true. -/ @[specialize] def containsConst (e : Expr) (p : Name → Bool) : Bool := Option.isSome <| e.find? fun | .const n _ => p n | _ => false /-- Given `(hNotEx : Not ex)` where `ex` is of the form `Exists x, p x`, return a `forall x, Not (p x)` and a proof for it. This function handles nested existentials. -/ partial def forallNot_of_notExists (ex hNotEx : Expr) : MetaM (Expr × Expr) := do let .app (.app (.const ``Exists [lvl]) A) p := ex | failure go lvl A p hNotEx where /-- Given `(hNotEx : Not (@Exists.{lvl} A p))`, return a `forall x, Not (p x)` and a proof for it. This function handles nested existentials. -/ go (lvl : Level) (A p hNotEx : Expr) : MetaM (Expr × Expr) := do let xn ← mkFreshUserName `x withLocalDeclD xn A fun x => do let px := p.beta #[x] let notPx := mkNot px let hAllNotPx := mkApp3 (.const ``forall_not_of_not_exists [lvl]) A p hNotEx if let .app (.app (.const ``Exists [lvl']) A') p' := px then let hNotPxN ← mkFreshUserName `h withLocalDeclD hNotPxN notPx fun hNotPx => do let (qx, hQx) ← go lvl' A' p' hNotPx let allQx ← mkForallFVars #[x] qx let hNotPxImpQx ← mkLambdaFVars #[hNotPx] hQx let hAllQx ← mkLambdaFVars #[x] (.app hNotPxImpQx (.app hAllNotPx x)) return (allQx, hAllQx) else let allNotPx ← mkForallFVars #[x] notPx return (allNotPx, hAllNotPx) end Expr /-- Get the projections that are projections to parent structures. Similar to `getParentStructures`, except that this returns the (last component of the) projection names instead of the parent names. -/ def getFieldsToParents (env : Environment) (structName : Name) : Array Name := getStructureFields env structName |>.filter fun fieldName => isSubobjectField? env structName fieldName |>.isSome end Lean
.lake/packages/mathlib/Mathlib/Lean/Elab/InfoTree.lean
import Mathlib.Init import Lean.Server.InfoUtils import Lean.Meta.TryThis /-! # Additions to `Lean.Elab.InfoTree.Main` -/ namespace Lean.Elab open Lean.Meta open Lean.Meta.Tactic.TryThis /-- Collects all suggestions from all `TryThisInfo`s in `trees`. `trees` is visited in order and suggestions in each tree are collected in post-order. -/ def collectTryThisSuggestions (trees : PersistentArray InfoTree) : Array Suggestion := go.run #[] |>.2 where /-- Visits all trees. -/ go : StateM (Array Suggestion) Unit := do for tree in trees do tree.visitM' (postNode := visitNode) /-- Visits a node in a tree. -/ @[nolint unusedArguments] visitNode (_ctx : ContextInfo) (i : Info) (_children : PersistentArray InfoTree) : StateM (Array Suggestion) Unit := do let .ofCustomInfo ci := i | return let some tti := ci.value.get? TryThisInfo | return modify (·.push tti.suggestion) end Lean.Elab
.lake/packages/mathlib/Mathlib/Lean/Elab/Term.lean
import Mathlib.Init import Lean.Elab.Term /-! # Additions to `Lean.Elab.Term` -/ namespace Lean.Elab.Term /-- Fully elaborates the term `patt`, allowing typeclass inference failure, but while setting `errToSorry` to false. Typeclass failures result in plain metavariables. Instantiates all assigned metavariables. -/ def elabPattern (patt : Term) (expectedType? : Option Expr) : TermElabM Expr := do withTheReader Term.Context ({ · with ignoreTCFailures := true, errToSorry := false }) <| withSynthesizeLight do let t ← elabTerm patt expectedType? synthesizeSyntheticMVars (postpone := .no) (ignoreStuckTC := true) instantiateMVars t end Lean.Elab.Term
.lake/packages/mathlib/Mathlib/Lean/Elab/Tactic/Meta.lean
import Lean.Elab.SyntheticMVars -- Import this linter explicitly to ensure that -- this file has a valid copyright header and module docstring. import Mathlib.Tactic.Linter.Header /-! # Additions to `Lean.Elab.Tactic.Meta` -/ namespace Lean.Elab open Term /-- Apply the given tactic code to `mvarId` in `MetaM`. This is a variant of `Lean.Elab.runTactic` that forgets the final `Term.State`. -/ def runTactic' (mvarId : MVarId) (tacticCode : Syntax) (ctx : Context := {}) (s : State := {}) : MetaM (List MVarId) := do instantiateMVarDeclMVars mvarId let go : TermElabM (List MVarId) := withSynthesize do Tactic.run mvarId (Tactic.evalTactic tacticCode *> Tactic.pruneSolvedGoals) go.run' ctx s end Lean.Elab
.lake/packages/mathlib/Mathlib/Lean/Elab/Tactic/Basic.lean
import Mathlib.Lean.Meta /-! # Additions to `Lean.Elab.Tactic.Basic` -/ open Lean Elab Tactic namespace Lean.Elab.Tactic /-- Return expected type for the main goal, cleaning up annotations, using `Lean.MVarId.getType''`. Remark: note that `MVarId.getType'` uses `whnf` instead of `cleanupAnnotations`, and `MVarId.getType''` also uses `cleanupAnnotations` -/ def getMainTarget'' : TacticM Expr := do (← getMainGoal).getType'' /-- Like `done` but takes a scope (e.g. a tactic name) as an argument to produce more detailed error messages. -/ def doneWithScope (scope : MessageData) : TacticM Unit := do let gs ← getUnsolvedGoals unless gs.isEmpty do logError m!"{scope} failed to solve some goals.\n" Term.reportUnsolvedGoals gs throwAbortTactic /-- Like `focusAndDone` but takes a scope (e.g. tactic name) as an argument to produce more detailed error messages. -/ def focusAndDoneWithScope {α : Type} (scope : MessageData) (tactic : TacticM α) : TacticM α := focus do let a ← try tactic catch e => if isAbortTacticException e then throw e else throwError "{scope} failed.\n{← nestedExceptionToMessageData e}" doneWithScope scope pure a end Lean.Elab.Tactic
.lake/packages/mathlib/Mathlib/Dynamics/Flow.lean
import Mathlib.Logic.Function.Iterate import Mathlib.Topology.Algebra.Monoid import Mathlib.Topology.Algebra.Group.Defs import Mathlib.Algebra.Order.Monoid.Submonoid /-! # Flows and invariant sets This file defines a flow on a topological space `α` by a topological monoid `τ` as a continuous monoid-action of `τ` on `α`. Anticipating the cases where `τ` is one of `ℕ`, `ℤ`, `ℝ⁺`, or `ℝ`, we use additive notation for the monoids, though the definition does not require commutativity. A subset `s` of `α` is invariant under a family of maps `ϕₜ : α → α` if `ϕₜ s ⊆ s` for all `t`. In many cases `ϕ` will be a flow on `α`. For the cases where `ϕ` is a flow by an ordered (additive, commutative) monoid, we additionally define forward invariance, where `t` ranges over those elements which are nonnegative. Additionally, we define such constructions as the (forward) orbit, a semiconjugacy between flows, a factor of a flow, the restriction of a flow onto an invariant subset, and the time-reversal of a flow by a group. -/ open Set Function Filter /-! ### Invariant sets -/ section Invariant variable {τ : Type*} {α : Type*} /-- A set `s ⊆ α` is invariant under `ϕ : τ → α → α` if `ϕ t s ⊆ s` for all `t` in `τ`. -/ def IsInvariant (ϕ : τ → α → α) (s : Set α) : Prop := ∀ t, MapsTo (ϕ t) s s variable (ϕ : τ → α → α) (s : Set α) theorem isInvariant_iff_image : IsInvariant ϕ s ↔ ∀ t, ϕ t '' s ⊆ s := by simp_rw [IsInvariant, mapsTo_iff_image_subset] /-- A set `s ⊆ α` is forward-invariant under `ϕ : τ → α → α` if `ϕ t s ⊆ s` for all `t ≥ 0`. -/ def IsForwardInvariant [Preorder τ] [Zero τ] (ϕ : τ → α → α) (s : Set α) : Prop := ∀ ⦃t⦄, 0 ≤ t → MapsTo (ϕ t) s s @[deprecated (since := "2025-09-25")] alias IsFwInvariant := IsForwardInvariant theorem IsInvariant.isForwardInvariant [Preorder τ] [Zero τ] {ϕ : τ → α → α} {s : Set α} (h : IsInvariant ϕ s) : IsForwardInvariant ϕ s := fun t _ht => h t @[deprecated (since := "2025-09-25")] alias IsInvariant.isFwInvariant := IsInvariant.isForwardInvariant /-- If `τ` is a `CanonicallyOrderedAdd` monoid (e.g., `ℕ` or `ℝ≥0`), then the notions `IsForwardInvariant` and `IsInvariant` are equivalent. -/ theorem IsForwardInvariant.isInvariant [AddMonoid τ] [PartialOrder τ] [CanonicallyOrderedAdd τ] {ϕ : τ → α → α} {s : Set α} (h : IsForwardInvariant ϕ s) : IsInvariant ϕ s := fun t => h (zero_le t) @[deprecated (since := "2025-09-25")] alias IsFwInvariant.isInvariant := IsForwardInvariant.isInvariant /-- If `τ` is a `CanonicallyOrderedAdd` monoid (e.g., `ℕ` or `ℝ≥0`), then the notions `IsForwardInvariant` and `IsInvariant` are equivalent. -/ theorem isForwardInvariant_iff_isInvariant [AddMonoid τ] [PartialOrder τ] [CanonicallyOrderedAdd τ] {ϕ : τ → α → α} {s : Set α} : IsForwardInvariant ϕ s ↔ IsInvariant ϕ s := ⟨IsForwardInvariant.isInvariant, IsInvariant.isForwardInvariant⟩ @[deprecated (since := "2025-09-25")] alias isFwInvariant_iff_isInvariant := isForwardInvariant_iff_isInvariant end Invariant /-! ### Flows -/ /-- A flow on a topological space `α` by an additive topological monoid `τ` is a continuous monoid action of `τ` on `α`. -/ structure Flow (τ : Type*) [TopologicalSpace τ] [AddMonoid τ] [ContinuousAdd τ] (α : Type*) [TopologicalSpace α] where /-- The map `τ → α → α` underlying a flow of `τ` on `α`. -/ toFun : τ → α → α cont' : Continuous (uncurry toFun) map_add' : ∀ t₁ t₂ x, toFun (t₁ + t₂) x = toFun t₁ (toFun t₂ x) map_zero' : ∀ x, toFun 0 x = x namespace Flow variable {τ : Type*} [AddMonoid τ] [TopologicalSpace τ] [ContinuousAdd τ] {α : Type*} [TopologicalSpace α] (ϕ : Flow τ α) instance : Inhabited (Flow τ α) := ⟨{ toFun := fun _ x => x cont' := continuous_snd map_add' := fun _ _ _ => rfl map_zero' := fun _ => rfl }⟩ instance : CoeFun (Flow τ α) fun _ => τ → α → α := ⟨Flow.toFun⟩ @[ext] theorem ext : ∀ {ϕ₁ ϕ₂ : Flow τ α}, (∀ t x, ϕ₁ t x = ϕ₂ t x) → ϕ₁ = ϕ₂ | ⟨f₁, _, _, _⟩, ⟨f₂, _, _, _⟩, h => by congr funext exact h _ _ @[continuity, fun_prop] protected theorem continuous {β : Type*} [TopologicalSpace β] {t : β → τ} (ht : Continuous t) {f : β → α} (hf : Continuous f) : Continuous fun x => ϕ (t x) (f x) := ϕ.cont'.comp (ht.prodMk hf) alias _root_.Continuous.flow := Flow.continuous theorem map_add (t₁ t₂ : τ) (x : α) : ϕ (t₁ + t₂) x = ϕ t₁ (ϕ t₂ x) := ϕ.map_add' _ _ _ @[simp] theorem map_zero : ϕ 0 = id := funext ϕ.map_zero' theorem map_zero_apply (x : α) : ϕ 0 x = x := ϕ.map_zero' x /-- Iterations of a continuous function from a topological space `α` to itself defines a semiflow by `ℕ` on `α`. -/ def fromIter {g : α → α} (h : Continuous g) : Flow ℕ α where toFun n x := g^[n] x cont' := continuous_prod_of_discrete_left.mpr (Continuous.iterate h) map_add' := iterate_add_apply _ map_zero' _x := rfl /-- Restriction of a flow onto an invariant set. -/ def restrict {s : Set α} (h : IsInvariant ϕ s) : Flow τ (↥s) where toFun t := (h t).restrict _ _ _ cont' := (ϕ.continuous continuous_fst continuous_subtype_val.snd').subtype_mk _ map_add' _ _ _ := Subtype.ext (map_add _ _ _ _) map_zero' _ := Subtype.ext (map_zero_apply _ _) @[simp] theorem coe_restrict_apply {s : Set α} (h : IsInvariant ϕ s) (t : τ) (x : s) : restrict ϕ h t x = ϕ t x := rfl /-- Convert a flow to an additive monoid action. -/ def toAddAction : AddAction τ α where vadd := ϕ add_vadd := ϕ.map_add' zero_vadd := ϕ.map_zero' /-- Restrict a flow by `τ` to a flow by an additive submonoid of `τ`. -/ def restrictAddSubmonoid (S : AddSubmonoid τ) : Flow S α where toFun t x := ϕ t x cont' := ϕ.continuous (continuous_subtype_val.comp continuous_fst) continuous_snd map_add' t₁ t₂ x := ϕ.map_add' t₁ t₂ x map_zero' := ϕ.map_zero' theorem restrictAddSubmonoid_apply (S : AddSubmonoid τ) (t : S) (x : α) : restrictAddSubmonoid ϕ S t x = ϕ t x := rfl section Orbit /-- The orbit of a point under a flow. -/ def orbit (x : α) : Set α := @AddAction.orbit _ _ ϕ.toAddAction.toVAdd x theorem orbit_eq_range (x : α) : orbit ϕ x = Set.range (fun t => ϕ t x) := rfl theorem mem_orbit_iff {x₁ x₂ : α} : x₂ ∈ orbit ϕ x₁ ↔ ∃ t : τ, ϕ t x₁ = x₂ := Iff.rfl theorem mem_orbit (x : α) (t : τ) : ϕ t x ∈ orbit ϕ x := @AddAction.mem_orbit _ _ ϕ.toAddAction.toVAdd x t theorem mem_orbit_self (x : α) : x ∈ orbit ϕ x := ϕ.toAddAction.mem_orbit_self x theorem nonempty_orbit (x : α) : Set.Nonempty (orbit ϕ x) := ϕ.toAddAction.nonempty_orbit x theorem mem_orbit_of_mem_orbit {x₁ x₂ : α} (t : τ) (h : x₂ ∈ orbit ϕ x₁) : ϕ t x₂ ∈ orbit ϕ x₁ := ϕ.toAddAction.mem_orbit_of_mem_orbit t h /-- The orbit of a point under a flow `ϕ` is invariant under `ϕ`. -/ theorem isInvariant_orbit (x : α) : IsInvariant ϕ (orbit ϕ x) := fun t _ => ϕ.toAddAction.mem_orbit_of_mem_orbit t theorem orbit_restrict (s : Set α) (hs : IsInvariant ϕ s) (x : s) : orbit (ϕ.restrict hs) x = Subtype.val ⁻¹' orbit ϕ x := Set.ext (fun x => by simp [orbit_eq_range, Subtype.ext_iff]) variable [Preorder τ] [AddLeftMono τ] /-- Restrict a flow by `τ` to a flow by the additive submonoid of nonnegative elements of `τ`. -/ def restrictNonneg : Flow (AddSubmonoid.nonneg τ) α := ϕ.restrictAddSubmonoid (.nonneg τ) /-- The forward orbit of a point under a flow. -/ def forwardOrbit (x : α) : Set α := orbit ϕ.restrictNonneg x theorem forwardOrbit_eq_range_nonneg (x : α) : forwardOrbit ϕ x = Set.range (fun t : {t : τ // 0 ≤ t} => ϕ t x) := rfl /-- The forward orbit of a point under a flow `ϕ` is forward-invariant under `ϕ`. -/ theorem isForwardInvariant_forwardOrbit (x : α) : IsForwardInvariant ϕ (forwardOrbit ϕ x) := fun t h => IsInvariant.isForwardInvariant (isInvariant_orbit ϕ.restrictNonneg x) (t := ⟨t, h⟩) h /-- The forward orbit of a point `x` is contained in the orbit of `x`. -/ theorem forwardOrbit_subset_orbit (x : α) : forwardOrbit ϕ x ⊆ orbit ϕ x := ϕ.toAddAction.orbit_addSubmonoid_subset (AddSubmonoid.nonneg τ) x theorem mem_orbit_of_mem_forwardOrbit {x₁ x₂ : α} (h : x₁ ∈ forwardOrbit ϕ x₂) : x₁ ∈ orbit ϕ x₂ := ϕ.forwardOrbit_subset_orbit x₂ h end Orbit variable {β γ : Type*} [TopologicalSpace β] [TopologicalSpace γ] (ψ : Flow τ β) (χ : Flow τ γ) /-- Given flows `ϕ` by `τ` on `α` and `ψ` by `τ` on `β`, a function `π : α → β` is called a *semiconjugacy* from `ϕ` to `ψ` if `π` is continuous and surjective, and `π ∘ (ϕ t) = (ψ t) ∘ π` for all `t : τ`. -/ structure IsSemiconjugacy (π : α → β) (ϕ : Flow τ α) (ψ : Flow τ β) : Prop where cont : Continuous π surj : Function.Surjective π semiconj : ∀ t, Function.Semiconj π (ϕ t) (ψ t) /-- The composition of semiconjugacies is a semiconjugacy. -/ theorem IsSemiconjugacy.comp {π : α → β} {ρ : β → γ} (h₁ : IsSemiconjugacy π ϕ ψ) (h₂ : IsSemiconjugacy ρ ψ χ) : IsSemiconjugacy (ρ ∘ π) ϕ χ := ⟨h₂.cont.comp h₁.cont, h₂.surj.comp h₁.surj, fun t => (h₂.semiconj t).comp_left (h₁.semiconj t)⟩ /-- The identity is a semiconjugacy from `ϕ` to `ψ` if and only if `ϕ` and `ψ` are equal. -/ theorem isSemiconjugacy_id_iff_eq (ϕ ψ : Flow τ α) : IsSemiconjugacy id ϕ ψ ↔ ϕ = ψ := ⟨fun h => ext h.semiconj, fun h => h.recOn ⟨continuous_id, surjective_id, fun _ => .id_left⟩⟩ /-- A flow `ψ` is called a *factor* of `ϕ` if there exists a semiconjugacy from `ϕ` to `ψ`. -/ def IsFactorOf (ψ : Flow τ β) (ϕ : Flow τ α) : Prop := ∃ π : α → β, IsSemiconjugacy π ϕ ψ theorem IsSemiconjugacy.isFactorOf {π : α → β} (h : IsSemiconjugacy π ϕ ψ) : IsFactorOf ψ ϕ := ⟨π, h⟩ /-- Transitivity of factors of flows. -/ theorem IsFactorOf.trans (h₁ : IsFactorOf ϕ ψ) (h₂ : IsFactorOf ψ χ) : IsFactorOf ϕ χ := h₁.elim fun π hπ => h₂.elim fun ρ hρ => ⟨π ∘ ρ, hρ.comp χ ψ ϕ hπ⟩ /-- Every flow is a factor of itself. -/ theorem IsFactorOf.self : IsFactorOf ϕ ϕ := ⟨id, (isSemiconjugacy_id_iff_eq ϕ ϕ).mpr (by rfl)⟩ end Flow namespace Flow variable {τ : Type*} [AddCommGroup τ] [TopologicalSpace τ] [IsTopologicalAddGroup τ] {α : Type*} [TopologicalSpace α] (ϕ : Flow τ α) theorem isInvariant_iff_image_eq (s : Set α) : IsInvariant ϕ s ↔ ∀ t, ϕ t '' s = s := (isInvariant_iff_image _ _).trans (Iff.intro (fun h t => Subset.antisymm (h t) fun _ hx => ⟨_, h (-t) ⟨_, hx, rfl⟩, by simp [← map_add]⟩) fun h t => by rw [h t]) /-- The time-reversal of a flow `ϕ` by a (commutative, additive) group is defined `ϕ.reverse t x = ϕ (-t) x`. -/ def reverse : Flow τ α where toFun t := ϕ (-t) cont' := ϕ.continuous continuous_fst.neg continuous_snd map_add' _ _ _ := by rw [neg_add, map_add] map_zero' _ := by rw [neg_zero, map_zero_apply] @[continuity, fun_prop] theorem continuous_toFun (t : τ) : Continuous (ϕ.toFun t) := by fun_prop /-- The map `ϕ t` as a homeomorphism. -/ def toHomeomorph (t : τ) : (α ≃ₜ α) where toFun := ϕ t invFun := ϕ (-t) left_inv x := by rw [← map_add, neg_add_cancel, map_zero_apply] right_inv x := by rw [← map_add, add_neg_cancel, map_zero_apply] continuous_toFun := by fun_prop continuous_invFun := by fun_prop theorem image_eq_preimage_symm (t : τ) (s : Set α) : ϕ t '' s = ϕ (-t) ⁻¹' s := (ϕ.toHomeomorph t).toEquiv.image_eq_preimage_symm s end Flow
.lake/packages/mathlib/Mathlib/Dynamics/Transitive.lean
import Mathlib.Dynamics.Minimal /-! # Topologically transitive monoid actions In this file we define an action of a monoid `M` on a topological space `α` to be *topologically transitive* if for any pair of nonempty open sets `U` and `V` in `α` there exists an `m : M` such that `(m • U) ∩ V` is nonempty. We also provide an additive version of this definition and prove basic facts about topologically transitive actions. ## Tags group action, topologically transitive -/ open scoped Pointwise /-- An action of an additive monoid `M` on a topological space `α` is called *topologically transitive* if for any pair of nonempty open sets `U` and `V` in `α` there exists an `m : M` such that `(m +ᵥ U) ∩ V` is nonempty. -/ class AddAction.IsTopologicallyTransitive (M α : Type*) [AddMonoid M] [TopologicalSpace α] [AddAction M α] : Prop where exists_vadd_inter : ∀ {U V : Set α}, IsOpen U → U.Nonempty → IsOpen V → V.Nonempty → ∃ m : M, ((m +ᵥ U) ∩ V).Nonempty /-- An action of a monoid `M` on a topological space `α` is called *topologically transitive* if for any pair of nonempty open sets `U` and `V` in `α` there exists an `m : M` such that `(m • U) ∩ V` is nonempty. -/ @[to_additive] class MulAction.IsTopologicallyTransitive (M α : Type*) [Monoid M] [TopologicalSpace α] [MulAction M α] : Prop where exists_smul_inter : ∀ {U V : Set α}, IsOpen U → U.Nonempty → IsOpen V → V.Nonempty → ∃ m : M, ((m • U) ∩ V).Nonempty open MulAction Set variable (M : Type*) {α : Type*} [TopologicalSpace α] [Monoid M] [MulAction M α] section IsTopologicallyTransitive @[to_additive] theorem MulAction.isTopologicallyTransitive_iff : IsTopologicallyTransitive M α ↔ ∀ {U V : Set α}, IsOpen U → U.Nonempty → IsOpen V → V.Nonempty → ∃ m : M, ((m • U) ∩ V).Nonempty := ⟨fun h ↦ h.1, fun h ↦ ⟨h⟩⟩ /-- An action of a monoid `M` on `α` is topologically transitive if and only if for any nonempty open subset `U` of `α` the union over the elements of `M` of images of `U` is dense in `α`. -/ @[to_additive /-- An action of an additive monoid `M` on `α` is topologically transitive if and only if for any nonempty open subset `U` of `α` the union over the elements of `M` of images of `U` is dense in `α`. -/] theorem MulAction.isTopologicallyTransitive_iff_dense_iUnion : IsTopologicallyTransitive M α ↔ ∀ {U : Set α}, IsOpen U → U.Nonempty → Dense (⋃ m : M, m • U) := by simp only [isTopologicallyTransitive_iff, inter_comm, dense_iff_inter_open, inter_iUnion, nonempty_iUnion] exact ⟨fun h _ h₁ h₂ _ h₃ h₄ ↦ h h₁ h₂ h₃ h₄, fun h _ _ h₁ h₂ h₃ h₄ ↦ h h₁ h₂ _ h₃ h₄⟩ /-- An action of a monoid `M` on `α` is topologically transitive if and only if for any nonempty open subset `U` of `α` the union of the preimages of `U` over the elements of `M` is dense in `α`. -/ @[to_additive /-- An action of an additive monoid `M` on `α` is topologically transitive if and only if for any nonempty open subset `U` of `α` the union of the preimages of `U` over the elements of `M` is dense in `α`. -/] theorem MulAction.isTopologicallyTransitive_iff_dense_iUnion_preimage : IsTopologicallyTransitive M α ↔ ∀ {U : Set α}, IsOpen U → U.Nonempty → Dense (⋃ m : M, (m • ·) ⁻¹' U) := by simp only [dense_iff_inter_open, inter_iUnion, nonempty_iUnion, ← image_inter_nonempty_iff] exact ⟨fun h _ h₁ h₂ _ h₃ h₄ ↦ h.1 h₃ h₄ h₁ h₂, fun h ↦ ⟨fun h₁ h₂ h₃ h₄ ↦ h h₃ h₄ _ h₁ h₂⟩⟩ @[to_additive] theorem IsOpen.dense_iUnion_smul [h : IsTopologicallyTransitive M α] {U : Set α} (hUo : IsOpen U) (hUne : U.Nonempty) : Dense (⋃ m : M, m • U) := (isTopologicallyTransitive_iff_dense_iUnion M).mp h hUo hUne @[to_additive] theorem IsOpen.dense_iUnion_preimage_smul [h : IsTopologicallyTransitive M α] {U : Set α} (hUo : IsOpen U) (hUne : U.Nonempty) : Dense (⋃ m : M, (m • ·) ⁻¹' U) := (isTopologicallyTransitive_iff_dense_iUnion_preimage M).mp h hUo hUne /-- Let `M` be a monoid with a topologically transitive action on `α`. If `U` is a nonempty open subset of `α` and `(m • ·) ⁻¹' U ⊆ U` for all `m : M` then `U` is dense in `α`. -/ @[to_additive /-- Let `M` be an additive monoid with a topologically transitive action on `α`. If `U` is a nonempty open subset of `α` and `(m +ᵥ ·) ⁻¹' U ⊆ U` for all `m : M` then `U` is dense in `α`. -/] theorem IsOpen.dense_of_preimage_smul_invariant [IsTopologicallyTransitive M α] {U : Set α} (hUo : IsOpen U) (hUne : U.Nonempty) (hUinv : ∀ m : M, (m • ·) ⁻¹' U ⊆ U) : Dense U := .mono (by simpa only [iUnion_subset_iff]) (hUo.dense_iUnion_preimage_smul M hUne) /-- An action of a monoid `M` on `α` that is continuous in the second argument is topologically transitive if and only if any nonempty open subset `U` of `α` with `(m • ·) ⁻¹' U ⊆ U` for all `m : M` is dense in `α`. -/ @[to_additive /-- An action of an additive monoid `M` on `α` that is continuous in the second argument is topologically transitive if and only if any nonempty open subset `U` of `α` with `(m +ᵥ ·) ⁻¹' U ⊆ U` for all `m : M` is dense in `α`. -/] theorem MulAction.isTopologicallyTransitive_iff_dense_of_preimage_invariant [h : ContinuousConstSMul M α] : IsTopologicallyTransitive M α ↔ ∀ {U : Set α}, IsOpen U → U.Nonempty → (∀ m : M, (m • ·) ⁻¹' U ⊆ U) → Dense U := by refine ⟨fun _ _ h₀ h₁ h₂ ↦ h₀.dense_of_preimage_smul_invariant M h₁ h₂, fun h₄ ↦ ?_⟩ refine (isTopologicallyTransitive_iff_dense_iUnion_preimage M).mpr ?_ refine fun hU _ ↦ h₄ (isOpen_iUnion fun a ↦ hU.preimage (h.1 a)) ?_ fun b _ ↦ ?_ · exact nonempty_iUnion.mpr ⟨1, by simpa only [one_smul]⟩ · simp only [preimage_iUnion, mem_iUnion, mem_preimage, smul_smul, forall_exists_index] exact fun c hc ↦ ⟨c * b, hc⟩ @[to_additive] instance MulAction.isTopologicallyTransitive_of_isMinimal [IsMinimal M α] : IsTopologicallyTransitive M α := by refine (isTopologicallyTransitive_iff_dense_iUnion_preimage M).mpr fun h hn ↦ ?_ simp only [h.iUnion_preimage_smul M hn, dense_univ] end IsTopologicallyTransitive
.lake/packages/mathlib/Mathlib/Dynamics/OmegaLimit.lean
import Mathlib.Dynamics.Flow import Mathlib.Tactic.Monotonicity /-! # ω-limits For a function `ϕ : τ → α → β` where `β` is a topological space, we define the ω-limit under `ϕ` of a set `s` in `α` with respect to filter `f` on `τ`: an element `y : β` is in the ω-limit of `s` if the forward images of `s` intersect arbitrarily small neighbourhoods of `y` frequently "in the direction of `f`". In practice `ϕ` is often a continuous monoid-act, but the definition requires only that `ϕ` has a coercion to the appropriate function type. In the case where `τ` is `ℕ` or `ℝ` and `f` is `atTop`, we recover the usual definition of the ω-limit set as the set of all `y` such that there exist sequences `(tₙ)`, `(xₙ)` such that `ϕ tₙ xₙ ⟶ y` as `n ⟶ ∞`. ## Notation The `omegaLimit` scope provides the localised notation `ω` for `omegaLimit`, as well as `ω⁺` and `ω⁻` for `omegaLimit atTop` and `omegaLimit atBot` respectively for when the acting monoid is endowed with an order. -/ open Set Function Filter Topology /-! ### Definition and notation -/ section omegaLimit variable {τ : Type*} {α : Type*} {β : Type*} {ι : Type*} /-- The ω-limit of a set `s` under `ϕ` with respect to a filter `f` is `⋂ u ∈ f, cl (ϕ u s)`. -/ def omegaLimit [TopologicalSpace β] (f : Filter τ) (ϕ : τ → α → β) (s : Set α) : Set β := ⋂ u ∈ f, closure (image2 ϕ u s) @[inherit_doc] scoped[omegaLimit] notation "ω" => omegaLimit /-- The ω-limit w.r.t. `Filter.atTop`. -/ scoped[omegaLimit] notation "ω⁺" => omegaLimit Filter.atTop /-- The ω-limit w.r.t. `Filter.atBot`. -/ scoped[omegaLimit] notation "ω⁻" => omegaLimit Filter.atBot variable [TopologicalSpace β] variable (f : Filter τ) (ϕ : τ → α → β) (s s₁ s₂ : Set α) /-! ### Elementary properties -/ open omegaLimit theorem omegaLimit_def : ω f ϕ s = ⋂ u ∈ f, closure (image2 ϕ u s) := rfl theorem omegaLimit_subset_of_tendsto {m : τ → τ} {f₁ f₂ : Filter τ} (hf : Tendsto m f₁ f₂) : ω f₁ (fun t x ↦ ϕ (m t) x) s ⊆ ω f₂ ϕ s := by refine iInter₂_mono' fun u hu ↦ ⟨m ⁻¹' u, tendsto_def.mp hf _ hu, ?_⟩ rw [← image2_image_left] exact closure_mono (image2_subset (image_preimage_subset _ _) Subset.rfl) theorem omegaLimit_mono_left {f₁ f₂ : Filter τ} (hf : f₁ ≤ f₂) : ω f₁ ϕ s ⊆ ω f₂ ϕ s := omegaLimit_subset_of_tendsto ϕ s (tendsto_id'.2 hf) theorem omegaLimit_mono_right {s₁ s₂ : Set α} (hs : s₁ ⊆ s₂) : ω f ϕ s₁ ⊆ ω f ϕ s₂ := iInter₂_mono fun _u _hu ↦ closure_mono (image2_subset Subset.rfl hs) theorem isClosed_omegaLimit : IsClosed (ω f ϕ s) := isClosed_iInter fun _u ↦ isClosed_iInter fun _hu ↦ isClosed_closure theorem mapsTo_omegaLimit' {α' β' : Type*} [TopologicalSpace β'] {f : Filter τ} {ϕ : τ → α → β} {ϕ' : τ → α' → β'} {ga : α → α'} {s' : Set α'} (hs : MapsTo ga s s') {gb : β → β'} (hg : ∀ᶠ t in f, EqOn (gb ∘ ϕ t) (ϕ' t ∘ ga) s) (hgc : Continuous gb) : MapsTo gb (ω f ϕ s) (ω f ϕ' s') := by simp only [omegaLimit_def, mem_iInter, MapsTo] intro y hy u hu refine map_mem_closure hgc (hy _ (inter_mem hu hg)) (forall_mem_image2.2 fun t ht x hx ↦ ?_) calc ϕ' t (ga x) ∈ image2 ϕ' u s' := mem_image2_of_mem ht.1 (hs hx) _ = gb (ϕ t x) := ht.2 hx |>.symm theorem mapsTo_omegaLimit {α' β' : Type*} [TopologicalSpace β'] {f : Filter τ} {ϕ : τ → α → β} {ϕ' : τ → α' → β'} {ga : α → α'} {s' : Set α'} (hs : MapsTo ga s s') {gb : β → β'} (hg : ∀ t x, gb (ϕ t x) = ϕ' t (ga x)) (hgc : Continuous gb) : MapsTo gb (ω f ϕ s) (ω f ϕ' s') := mapsTo_omegaLimit' _ hs (Eventually.of_forall fun t x _hx ↦ hg t x) hgc theorem omegaLimit_image_eq {α' : Type*} (ϕ : τ → α' → β) (f : Filter τ) (g : α → α') : ω f ϕ (g '' s) = ω f (fun t x ↦ ϕ t (g x)) s := by simp only [omegaLimit, image2_image_right] theorem omegaLimit_preimage_subset {α' : Type*} (ϕ : τ → α' → β) (s : Set α') (f : Filter τ) (g : α → α') : ω f (fun t x ↦ ϕ t (g x)) (g ⁻¹' s) ⊆ ω f ϕ s := mapsTo_omegaLimit _ (mapsTo_preimage _ _) (fun _t _x ↦ rfl) continuous_id /-! ### Equivalent definitions of the omega limit The next few lemmas are various versions of the property characterising ω-limits: -/ /-- An element `y` is in the ω-limit set of `s` w.r.t. `f` if the preimages of an arbitrary neighbourhood of `y` frequently (w.r.t. `f`) intersects of `s`. -/ theorem mem_omegaLimit_iff_frequently (y : β) : y ∈ ω f ϕ s ↔ ∀ n ∈ 𝓝 y, ∃ᶠ t in f, (s ∩ ϕ t ⁻¹' n).Nonempty := by simp_rw [frequently_iff, omegaLimit_def, mem_iInter, mem_closure_iff_nhds] constructor · intro h _ hn _ hu rcases h _ hu _ hn with ⟨_, _, _, ht, _, hx, rfl⟩ exact ⟨_, ht, _, hx, by rwa [mem_preimage]⟩ · intro h _ hu _ hn rcases h _ hn hu with ⟨_, ht, _, hx, hϕtx⟩ exact ⟨_, hϕtx, _, ht, _, hx, rfl⟩ /-- An element `y` is in the ω-limit set of `s` w.r.t. `f` if the forward images of `s` frequently (w.r.t. `f`) intersect arbitrary neighbourhoods of `y`. -/ theorem mem_omegaLimit_iff_frequently₂ (y : β) : y ∈ ω f ϕ s ↔ ∀ n ∈ 𝓝 y, ∃ᶠ t in f, (ϕ t '' s ∩ n).Nonempty := by simp_rw [mem_omegaLimit_iff_frequently, image_inter_nonempty_iff] /-- An element `y` is in the ω-limit of `x` w.r.t. `f` if the forward images of `x` frequently (w.r.t. `f`) falls within an arbitrary neighbourhood of `y`. -/ theorem mem_omegaLimit_singleton_iff_map_cluster_point (x : α) (y : β) : y ∈ ω f ϕ {x} ↔ MapClusterPt y f fun t ↦ ϕ t x := by simp_rw [mem_omegaLimit_iff_frequently, mapClusterPt_iff_frequently, singleton_inter_nonempty, mem_preimage] /-! ### Set operations and omega limits -/ theorem omegaLimit_inter : ω f ϕ (s₁ ∩ s₂) ⊆ ω f ϕ s₁ ∩ ω f ϕ s₂ := subset_inter (omegaLimit_mono_right _ _ inter_subset_left) (omegaLimit_mono_right _ _ inter_subset_right) theorem omegaLimit_iInter (p : ι → Set α) : ω f ϕ (⋂ i, p i) ⊆ ⋂ i, ω f ϕ (p i) := subset_iInter fun _i ↦ omegaLimit_mono_right _ _ (iInter_subset _ _) theorem omegaLimit_union : ω f ϕ (s₁ ∪ s₂) = ω f ϕ s₁ ∪ ω f ϕ s₂ := by ext y; constructor · simp only [mem_union, mem_omegaLimit_iff_frequently, union_inter_distrib_right, union_nonempty, frequently_or_distrib] contrapose! simp only [not_frequently, not_nonempty_iff_eq_empty, ← subset_empty_iff] rintro ⟨⟨n₁, hn₁, h₁⟩, ⟨n₂, hn₂, h₂⟩⟩ refine ⟨n₁ ∩ n₂, inter_mem hn₁ hn₂, h₁.mono fun t ↦ ?_, h₂.mono fun t ↦ ?_⟩ exacts [Subset.trans <| inter_subset_inter_right _ <| preimage_mono inter_subset_left, Subset.trans <| inter_subset_inter_right _ <| preimage_mono inter_subset_right] · rintro (hy | hy) exacts [omegaLimit_mono_right _ _ subset_union_left hy, omegaLimit_mono_right _ _ subset_union_right hy] theorem omegaLimit_iUnion (p : ι → Set α) : ⋃ i, ω f ϕ (p i) ⊆ ω f ϕ (⋃ i, p i) := by rw [iUnion_subset_iff] exact fun i ↦ omegaLimit_mono_right _ _ (subset_iUnion _ _) /-! Different expressions for omega limits, useful for rewrites. In particular, one may restrict the intersection to sets in `f` which are subsets of some set `v` also in `f`. -/ theorem omegaLimit_eq_iInter : ω f ϕ s = ⋂ u : ↥f.sets, closure (image2 ϕ u s) := biInter_eq_iInter _ _ theorem omegaLimit_eq_biInter_inter {v : Set τ} (hv : v ∈ f) : ω f ϕ s = ⋂ u ∈ f, closure (image2 ϕ (u ∩ v) s) := Subset.antisymm (iInter₂_mono' fun u hu ↦ ⟨u ∩ v, inter_mem hu hv, Subset.rfl⟩) (iInter₂_mono fun _u _hu ↦ closure_mono <| image2_subset inter_subset_left Subset.rfl) theorem omegaLimit_eq_iInter_inter {v : Set τ} (hv : v ∈ f) : ω f ϕ s = ⋂ u : ↥f.sets, closure (image2 ϕ (u ∩ v) s) := by rw [omegaLimit_eq_biInter_inter _ _ _ hv] apply biInter_eq_iInter theorem omegaLimit_subset_closure_fw_image {u : Set τ} (hu : u ∈ f) : ω f ϕ s ⊆ closure (image2 ϕ u s) := by rw [omegaLimit_eq_iInter] intro _ hx rw [mem_iInter] at hx exact hx ⟨u, hu⟩ -- An instance with better keys instance : Inhabited f.sets := Filter.inhabitedMem /-! ### ω-limits and compactness -/ /-- A set is eventually carried into any open neighbourhood of its ω-limit: if `c` is a compact set such that `closure {ϕ t x | t ∈ v, x ∈ s} ⊆ c` for some `v ∈ f` and `n` is an open neighbourhood of `ω f ϕ s`, then for some `u ∈ f` we have `closure {ϕ t x | t ∈ u, x ∈ s} ⊆ n`. -/ theorem eventually_closure_subset_of_isCompact_absorbing_of_isOpen_of_omegaLimit_subset' {c : Set β} (hc₁ : IsCompact c) (hc₂ : ∃ v ∈ f, closure (image2 ϕ v s) ⊆ c) {n : Set β} (hn₁ : IsOpen n) (hn₂ : ω f ϕ s ⊆ n) : ∃ u ∈ f, closure (image2 ϕ u s) ⊆ n := by rcases hc₂ with ⟨v, hv₁, hv₂⟩ let k := closure (image2 ϕ v s) have hk : IsCompact (k \ n) := (hc₁.of_isClosed_subset isClosed_closure hv₂).diff hn₁ let j u := (closure (image2 ϕ (u ∩ v) s))ᶜ have hj₁ : ∀ u ∈ f, IsOpen (j u) := fun _ _ ↦ isOpen_compl_iff.mpr isClosed_closure have hj₂ : k \ n ⊆ ⋃ u ∈ f, j u := by have : ⋃ u ∈ f, j u = ⋃ u : (↥f.sets), j u := biUnion_eq_iUnion _ _ rw [this, diff_subset_comm, diff_iUnion] rw [omegaLimit_eq_iInter_inter _ _ _ hv₁] at hn₂ simp_rw [j, diff_compl] rw [← inter_iInter] exact Subset.trans inter_subset_right hn₂ rcases hk.elim_finite_subcover_image hj₁ hj₂ with ⟨g, hg₁ : ∀ u ∈ g, u ∈ f, hg₂, hg₃⟩ let w := (⋂ u ∈ g, u) ∩ v have hw₂ : w ∈ f := by simpa [w, *] have hw₃ : k \ n ⊆ (closure (image2 ϕ w s))ᶜ := by apply Subset.trans hg₃ simp only [j, iUnion_subset_iff, compl_subset_compl] intro u hu unfold w gcongr refine iInter_subset_of_subset u (iInter_subset_of_subset hu ?_) all_goals exact Subset.rfl have hw₄ : kᶜ ⊆ (closure (image2 ϕ w s))ᶜ := by simp only [compl_subset_compl] exact closure_mono (image2_subset inter_subset_right Subset.rfl) have hnc : nᶜ ⊆ k \ n ∪ kᶜ := by rw [union_comm, ← inter_subset, diff_eq, inter_comm] have hw : closure (image2 ϕ w s) ⊆ n := compl_subset_compl.mp (Subset.trans hnc (union_subset hw₃ hw₄)) exact ⟨_, hw₂, hw⟩ /-- A set is eventually carried into any open neighbourhood of its ω-limit: if `c` is a compact set such that `closure {ϕ t x | t ∈ v, x ∈ s} ⊆ c` for some `v ∈ f` and `n` is an open neighbourhood of `ω f ϕ s`, then for some `u ∈ f` we have `closure {ϕ t x | t ∈ u, x ∈ s} ⊆ n`. -/ theorem eventually_closure_subset_of_isCompact_absorbing_of_isOpen_of_omegaLimit_subset [T2Space β] {c : Set β} (hc₁ : IsCompact c) (hc₂ : ∀ᶠ t in f, MapsTo (ϕ t) s c) {n : Set β} (hn₁ : IsOpen n) (hn₂ : ω f ϕ s ⊆ n) : ∃ u ∈ f, closure (image2 ϕ u s) ⊆ n := eventually_closure_subset_of_isCompact_absorbing_of_isOpen_of_omegaLimit_subset' f ϕ _ hc₁ ⟨_, hc₂, closure_minimal (image2_subset_iff.2 fun _t ↦ id) hc₁.isClosed⟩ hn₁ hn₂ theorem eventually_mapsTo_of_isCompact_absorbing_of_isOpen_of_omegaLimit_subset [T2Space β] {c : Set β} (hc₁ : IsCompact c) (hc₂ : ∀ᶠ t in f, MapsTo (ϕ t) s c) {n : Set β} (hn₁ : IsOpen n) (hn₂ : ω f ϕ s ⊆ n) : ∀ᶠ t in f, MapsTo (ϕ t) s n := by rcases eventually_closure_subset_of_isCompact_absorbing_of_isOpen_of_omegaLimit_subset f ϕ s hc₁ hc₂ hn₁ hn₂ with ⟨u, hu_mem, hu⟩ refine mem_of_superset hu_mem fun t ht x hx ↦ ?_ exact hu (subset_closure <| mem_image2_of_mem ht hx) theorem eventually_closure_subset_of_isOpen_of_omegaLimit_subset [CompactSpace β] {v : Set β} (hv₁ : IsOpen v) (hv₂ : ω f ϕ s ⊆ v) : ∃ u ∈ f, closure (image2 ϕ u s) ⊆ v := eventually_closure_subset_of_isCompact_absorbing_of_isOpen_of_omegaLimit_subset' _ _ _ isCompact_univ ⟨univ, univ_mem, subset_univ _⟩ hv₁ hv₂ theorem eventually_mapsTo_of_isOpen_of_omegaLimit_subset [CompactSpace β] {v : Set β} (hv₁ : IsOpen v) (hv₂ : ω f ϕ s ⊆ v) : ∀ᶠ t in f, MapsTo (ϕ t) s v := by rcases eventually_closure_subset_of_isOpen_of_omegaLimit_subset f ϕ s hv₁ hv₂ with ⟨u, hu_mem, hu⟩ refine mem_of_superset hu_mem fun t ht x hx ↦ ?_ exact hu (subset_closure <| mem_image2_of_mem ht hx) /-- The ω-limit of a nonempty set w.r.t. a nontrivial filter is nonempty. -/ theorem nonempty_omegaLimit_of_isCompact_absorbing [NeBot f] {c : Set β} (hc₁ : IsCompact c) (hc₂ : ∃ v ∈ f, closure (image2 ϕ v s) ⊆ c) (hs : s.Nonempty) : (ω f ϕ s).Nonempty := by rcases hc₂ with ⟨v, hv₁, hv₂⟩ rw [omegaLimit_eq_iInter_inter _ _ _ hv₁] apply IsCompact.nonempty_iInter_of_directed_nonempty_isCompact_isClosed · rintro ⟨u₁, hu₁⟩ ⟨u₂, hu₂⟩ use ⟨u₁ ∩ u₂, inter_mem hu₁ hu₂⟩ constructor all_goals exact closure_mono (image2_subset (inter_subset_inter_left _ (by simp)) Subset.rfl) · intro u have hn : (image2 ϕ (u ∩ v) s).Nonempty := Nonempty.image2 (Filter.nonempty_of_mem (inter_mem u.prop hv₁)) hs exact hn.mono subset_closure · intro apply hc₁.of_isClosed_subset isClosed_closure calc _ ⊆ closure (image2 ϕ v s) := closure_mono (image2_subset inter_subset_right Subset.rfl) _ ⊆ c := hv₂ · exact fun _ ↦ isClosed_closure theorem nonempty_omegaLimit [CompactSpace β] [NeBot f] (hs : s.Nonempty) : (ω f ϕ s).Nonempty := nonempty_omegaLimit_of_isCompact_absorbing _ _ _ isCompact_univ ⟨univ, univ_mem, subset_univ _⟩ hs end omegaLimit /-! ### ω-limits of flows by a monoid -/ namespace Flow variable {τ : Type*} [TopologicalSpace τ] [AddMonoid τ] [ContinuousAdd τ] {α : Type*} [TopologicalSpace α] (f : Filter τ) (ϕ : Flow τ α) (s : Set α) open omegaLimit theorem isInvariant_omegaLimit (hf : ∀ t, Tendsto (t + ·) f f) : IsInvariant ϕ (ω f ϕ s) := by refine fun t ↦ MapsTo.mono_right ?_ (omegaLimit_subset_of_tendsto ϕ s (hf t)) exact mapsTo_omegaLimit _ (mapsTo_id _) (fun t' x ↦ (ϕ.map_add _ _ _).symm) (continuous_const.flow ϕ continuous_id) theorem omegaLimit_image_subset (t : τ) (ht : Tendsto (· + t) f f) : ω f ϕ (ϕ t '' s) ⊆ ω f ϕ s := by simp only [omegaLimit_image_eq, ← map_add] exact omegaLimit_subset_of_tendsto ϕ s ht end Flow /-! ### ω-limits of flows by a group -/ namespace Flow variable {τ : Type*} [TopologicalSpace τ] [AddCommGroup τ] [IsTopologicalAddGroup τ] {α : Type*} [TopologicalSpace α] (f : Filter τ) (ϕ : Flow τ α) (s : Set α) open omegaLimit /-- the ω-limit of a forward image of `s` is the same as the ω-limit of `s`. -/ @[simp] theorem omegaLimit_image_eq (hf : ∀ t, Tendsto (· + t) f f) (t : τ) : ω f ϕ (ϕ t '' s) = ω f ϕ s := Subset.antisymm (omegaLimit_image_subset _ _ _ _ (hf t)) <| calc ω f ϕ s = ω f ϕ (ϕ (-t) '' (ϕ t '' s)) := by simp [image_image, ← map_add] _ ⊆ ω f ϕ (ϕ t '' s) := omegaLimit_image_subset _ _ _ _ (hf _) theorem omegaLimit_omegaLimit (hf : ∀ t, Tendsto (t + ·) f f) : ω f ϕ (ω f ϕ s) ⊆ ω f ϕ s := by simp only [subset_def, mem_omegaLimit_iff_frequently₂, frequently_iff] intro _ h rintro n hn u hu rcases mem_nhds_iff.mp hn with ⟨o, ho₁, ho₂, ho₃⟩ rcases h o (IsOpen.mem_nhds ho₂ ho₃) hu with ⟨t, _ht₁, ht₂⟩ have l₁ : (ω f ϕ s ∩ o).Nonempty := ht₂.mono (inter_subset_inter_left _ ((isInvariant_iff_image _ _).mp (isInvariant_omegaLimit _ _ _ hf) _)) have l₂ : (closure (image2 ϕ u s) ∩ o).Nonempty := l₁.mono fun b hb ↦ ⟨omegaLimit_subset_closure_fw_image _ _ _ hu hb.1, hb.2⟩ have l₃ : (o ∩ image2 ϕ u s).Nonempty := by rcases l₂ with ⟨b, hb₁, hb₂⟩ exact mem_closure_iff_nhds.mp hb₁ o (IsOpen.mem_nhds ho₂ hb₂) rcases l₃ with ⟨ϕra, ho, ⟨_, hr, _, ha, hϕra⟩⟩ exact ⟨_, hr, ϕra, ⟨_, ha, hϕra⟩, ho₁ ho⟩ end Flow
.lake/packages/mathlib/Mathlib/Dynamics/Minimal.lean
import Mathlib.Topology.Algebra.ConstMulAction /-! # Minimal action of a group In this file we define an action of a monoid `M` on a topological space `α` to be *minimal* if the `M`-orbit of every point `x : α` is dense. We also provide an additive version of this definition and prove some basic facts about minimal actions. ## TODO * Define a minimal set of an action. ## Tags group action, minimal -/ open Pointwise /-- An action of an additive monoid `M` on a topological space is called *minimal* if the `M`-orbit of every point `x : α` is dense. -/ class AddAction.IsMinimal (M α : Type*) [AddMonoid M] [TopologicalSpace α] [AddAction M α] : Prop where dense_orbit : ∀ x : α, Dense (AddAction.orbit M x) /-- An action of a monoid `M` on a topological space is called *minimal* if the `M`-orbit of every point `x : α` is dense. -/ @[to_additive] class MulAction.IsMinimal (M α : Type*) [Monoid M] [TopologicalSpace α] [MulAction M α] : Prop where dense_orbit : ∀ x : α, Dense (MulAction.orbit M x) open MulAction Set variable (M G : Type*) {α : Type*} [Monoid M] [Group G] [TopologicalSpace α] [MulAction M α] [MulAction G α] @[to_additive] theorem MulAction.dense_orbit [IsMinimal M α] (x : α) : Dense (orbit M x) := MulAction.IsMinimal.dense_orbit x @[to_additive] theorem denseRange_smul [IsMinimal M α] (x : α) : DenseRange fun c : M ↦ c • x := MulAction.dense_orbit M x @[to_additive] instance (priority := 100) MulAction.isMinimal_of_pretransitive [IsPretransitive M α] : IsMinimal M α := ⟨fun x ↦ (surjective_smul M x).denseRange⟩ @[to_additive] theorem IsOpen.exists_smul_mem [IsMinimal M α] (x : α) {U : Set α} (hUo : IsOpen U) (hne : U.Nonempty) : ∃ c : M, c • x ∈ U := (denseRange_smul M x).exists_mem_open hUo hne @[to_additive] theorem IsOpen.iUnion_preimage_smul [IsMinimal M α] {U : Set α} (hUo : IsOpen U) (hne : U.Nonempty) : ⋃ c : M, (c • ·) ⁻¹' U = univ := iUnion_eq_univ_iff.2 fun x ↦ hUo.exists_smul_mem M x hne @[to_additive] theorem IsOpen.iUnion_smul [IsMinimal G α] {U : Set α} (hUo : IsOpen U) (hne : U.Nonempty) : ⋃ g : G, g • U = univ := iUnion_eq_univ_iff.2 fun x ↦ let ⟨g, hg⟩ := hUo.exists_smul_mem G x hne ⟨g⁻¹, _, hg, inv_smul_smul _ _⟩ @[to_additive] theorem IsCompact.exists_finite_cover_smul [IsMinimal G α] [ContinuousConstSMul G α] {K U : Set α} (hK : IsCompact K) (hUo : IsOpen U) (hne : U.Nonempty) : ∃ I : Finset G, K ⊆ ⋃ g ∈ I, g • U := (hK.elim_finite_subcover (fun g ↦ g • U) fun _ ↦ hUo.smul _) <| calc K ⊆ univ := subset_univ K _ = ⋃ g : G, g • U := (hUo.iUnion_smul G hne).symm @[to_additive] theorem dense_of_nonempty_smul_invariant [IsMinimal M α] {s : Set α} (hne : s.Nonempty) (hsmul : ∀ c : M, c • s ⊆ s) : Dense s := let ⟨x, hx⟩ := hne (MulAction.dense_orbit M x).mono (range_subset_iff.2 fun c ↦ hsmul c ⟨x, hx, rfl⟩) @[to_additive] theorem eq_empty_or_univ_of_smul_invariant_closed [IsMinimal M α] {s : Set α} (hs : IsClosed s) (hsmul : ∀ c : M, c • s ⊆ s) : s = ∅ ∨ s = univ := s.eq_empty_or_nonempty.imp_right fun hne ↦ hs.closure_eq ▸ (dense_of_nonempty_smul_invariant M hne hsmul).closure_eq @[to_additive] theorem isMinimal_iff_isClosed_smul_invariant [ContinuousConstSMul M α] : IsMinimal M α ↔ ∀ s : Set α, IsClosed s → (∀ c : M, c • s ⊆ s) → s = ∅ ∨ s = univ := by constructor · intro _ _ exact eq_empty_or_univ_of_smul_invariant_closed M refine fun H ↦ ⟨fun _ ↦ dense_iff_closure_eq.2 <| (H _ ?_ ?_).resolve_left ?_⟩ exacts [isClosed_closure, fun _ ↦ smul_closure_orbit_subset _ _, (nonempty_orbit _).closure.ne_empty]
.lake/packages/mathlib/Mathlib/Dynamics/Newton.lean
import Mathlib.Algebra.Polynomial.AlgebraMap import Mathlib.Algebra.Polynomial.Identities import Mathlib.RingTheory.Nilpotent.Lemmas import Mathlib.RingTheory.Polynomial.Nilpotent /-! # Newton-Raphson method Given a single-variable polynomial `P` with derivative `P'`, Newton's method concerns iteration of the rational map: `x ↦ x - P(x) / P'(x)`. Over a field it can serve as a root-finding algorithm. It is also useful tool in certain proofs such as Hensel's lemma and Jordan-Chevalley decomposition. ## Main definitions / results: * `Polynomial.newtonMap`: the map `x ↦ x - P(x) / P'(x)`, where `P'` is the derivative of the polynomial `P`. * `Polynomial.isFixedPt_newtonMap_of_isUnit_iff`: `x` is a fixed point for Newton iteration iff it is a root of `P` (provided `P'(x)` is a unit). * `Polynomial.existsUnique_nilpotent_sub_and_aeval_eq_zero`: if `x` is almost a root of `P` in the sense that `P(x)` is nilpotent (and `P'(x)` is a unit) then we may write `x` as a sum `x = n + r` where `n` is nilpotent and `r` is a root of `P`. This can be used to prove the Jordan-Chevalley decomposition of linear endomorphims. -/ open Set Function noncomputable section namespace Polynomial variable {R S : Type*} [CommRing R] [CommRing S] [Algebra R S] (P : R[X]) {x : S} /-- Given a single-variable polynomial `P` with derivative `P'`, this is the map: `x ↦ x - P(x) / P'(x)`. When `P'(x)` is not a unit we use a junk-value pattern and send `x ↦ x`. -/ def newtonMap (x : S) : S := x - (Ring.inverse <| aeval x (derivative P)) * aeval x P theorem newtonMap_apply : P.newtonMap x = x - (Ring.inverse <| aeval x (derivative P)) * (aeval x P) := rfl variable {P} theorem newtonMap_apply_of_isUnit (h : IsUnit <| aeval x (derivative P)) : P.newtonMap x = x - h.unit⁻¹ * aeval x P := by simp [newtonMap_apply, Ring.inverse, h] theorem newtonMap_apply_of_not_isUnit (h : ¬ (IsUnit <| aeval x (derivative P))) : P.newtonMap x = x := by simp [newtonMap_apply, Ring.inverse, h] theorem isNilpotent_iterate_newtonMap_sub_of_isNilpotent (h : IsNilpotent <| aeval x P) (n : ℕ) : IsNilpotent <| P.newtonMap^[n] x - x := by induction n with | zero => simp | succ n ih => rw [iterate_succ', comp_apply, newtonMap_apply, sub_right_comm] refine (Commute.all _ _).isNilpotent_sub ih <| (Commute.all _ _).isNilpotent_mul_left ?_ simpa using Commute.isNilpotent_add (Commute.all _ _) (isNilpotent_aeval_sub_of_isNilpotent_sub P ih) h theorem isFixedPt_newtonMap_of_aeval_eq_zero (h : aeval x P = 0) : IsFixedPt P.newtonMap x := by rw [IsFixedPt, newtonMap_apply, h, mul_zero, sub_zero] theorem isFixedPt_newtonMap_of_isUnit_iff (h : IsUnit <| aeval x (derivative P)) : IsFixedPt P.newtonMap x ↔ aeval x P = 0 := by rw [IsFixedPt, newtonMap_apply, sub_eq_self, Ring.inverse_mul_eq_iff_eq_mul _ _ _ h, mul_zero] /-- This is really an auxiliary result, en route to `Polynomial.existsUnique_nilpotent_sub_and_aeval_eq_zero`. -/ theorem aeval_pow_two_pow_dvd_aeval_iterate_newtonMap (h : IsNilpotent (aeval x P)) (h' : IsUnit (aeval x <| derivative P)) (n : ℕ) : (aeval x P) ^ (2 ^ n) ∣ aeval (P.newtonMap^[n] x) P := by induction n with | zero => simp | succ n ih => have ⟨d, hd⟩ := binomExpansion (P.map (algebraMap R S)) (P.newtonMap^[n] x) (-Ring.inverse (aeval (P.newtonMap^[n] x) <| derivative P) * aeval (P.newtonMap^[n] x) P) rw [eval_map_algebraMap, eval_map_algebraMap] at hd rw [iterate_succ', comp_apply, newtonMap_apply, sub_eq_add_neg, neg_mul_eq_neg_mul, hd] refine dvd_add ?_ (dvd_mul_of_dvd_right ?_ _) · convert dvd_zero _ have : IsUnit (aeval (P.newtonMap^[n] x) <| derivative P) := isUnit_aeval_of_isUnit_aeval_of_isNilpotent_sub h' <| isNilpotent_iterate_newtonMap_sub_of_isNilpotent h n rw [derivative_map, eval_map_algebraMap, ← mul_assoc, mul_neg, Ring.mul_inverse_cancel _ this, neg_mul, one_mul, add_neg_cancel] · rw [neg_mul, even_two.neg_pow, mul_pow, pow_succ, pow_mul] exact dvd_mul_of_dvd_right (pow_dvd_pow_of_dvd ih 2) _ /-- If `x` is almost a root of `P` in the sense that `P(x)` is nilpotent (and `P'(x)` is a unit) then we may write `x` as a sum `x = n + r` where `n` is nilpotent and `r` is a root of `P`. Moreover, `n` and `r` are unique. This can be used to prove the Jordan-Chevalley decomposition of linear endomorphims. -/ theorem existsUnique_nilpotent_sub_and_aeval_eq_zero (h : IsNilpotent (aeval x P)) (h' : IsUnit (aeval x <| derivative P)) : ∃! r, IsNilpotent (x - r) ∧ aeval r P = 0 := by simp_rw [(neg_sub _ x).symm, isNilpotent_neg_iff] refine existsUnique_of_exists_of_unique ?_ fun r₁ r₂ ⟨hr₁, hr₁'⟩ ⟨hr₂, hr₂'⟩ ↦ ?_ · -- Existence obtain ⟨n, hn⟩ := id h refine ⟨P.newtonMap^[n] x, isNilpotent_iterate_newtonMap_sub_of_isNilpotent h n, ?_⟩ rw [← zero_dvd_iff, ← pow_eq_zero_of_le (n.lt_two_pow_self).le hn] exact aeval_pow_two_pow_dvd_aeval_iterate_newtonMap h h' n · -- Uniqueness have ⟨u, hu⟩ := binomExpansion (P.map (algebraMap R S)) r₁ (r₂ - r₁) suffices IsUnit (aeval r₁ (derivative P) + u * (r₂ - r₁)) by rwa [derivative_map, eval_map_algebraMap, eval_map_algebraMap, eval_map_algebraMap, add_sub_cancel, hr₂', hr₁', zero_add, pow_two, ← mul_assoc, ← add_mul, eq_comm, this.mul_right_eq_zero, sub_eq_zero, eq_comm] at hu have : IsUnit (aeval r₁ (derivative P)) := isUnit_aeval_of_isUnit_aeval_of_isNilpotent_sub h' hr₁ rw [← sub_sub_sub_cancel_right r₂ r₁ x] refine IsNilpotent.isUnit_add_left_of_commute ?_ this (Commute.all _ _) exact (Commute.all _ _).isNilpotent_mul_left <| (Commute.all _ _).isNilpotent_sub hr₂ hr₁ end Polynomial
.lake/packages/mathlib/Mathlib/Dynamics/TopologicalEntropy/Subset.lean
import Mathlib.Dynamics.TopologicalEntropy.NetEntropy /-! # Topological entropy of subsets: monotonicity, closure, union This file contains general results about the topological entropy of various subsets of the same dynamical system `(X, T)`. We prove that: - the topological entropy `CoverEntropy T F` of `F` is monotone in `F`: the larger the subset, the larger its entropy. - the topological entropy of a subset equals the entropy of its closure. - the entropy of the union of two sets is the maximum of their entropies. We generalize the latter property to finite unions. ## Implementation notes Most results are proved using only the definition of the topological entropy by covers. Some lemmas of general interest are also proved for nets. ## TODO One may implement a notion of Hausdorff convergence for subsets using uniform spaces, and then prove the semicontinuity of the topological entropy. It would be a nice generalization of the lemmas on closures. ## Tags closure, entropy, subset, union -/ namespace Dynamics open ExpGrowth Set UniformSpace open scoped SetRel Uniformity variable {X : Type*} /-! ### Monotonicity of entropy as a function of the subset -/ section Subset lemma IsDynCoverOf.monotone_subset {T : X → X} {F G : Set X} (F_G : F ⊆ G) {U : Set (X × X)} {n : ℕ} {s : Set X} (h : IsDynCoverOf T G U n s) : IsDynCoverOf T F U n s := F_G.trans h lemma IsDynNetIn.monotone_subset {T : X → X} {F G : Set X} (F_G : F ⊆ G) {U : Set (X × X)} {n : ℕ} {s : Set X} (h : IsDynNetIn T F U n s) : IsDynNetIn T G U n s := ⟨h.1.trans F_G, h.2⟩ lemma coverMincard_monotone_subset (T : X → X) (U : Set (X × X)) (n : ℕ) : Monotone fun F : Set X ↦ coverMincard T F U n := fun _ _ F_G ↦ biInf_mono fun _ h ↦ h.monotone_subset F_G lemma netMaxcard_monotone_subset (T : X → X) (U : Set (X × X)) (n : ℕ) : Monotone fun F : Set X ↦ netMaxcard T F U n := fun _ _ F_G ↦ biSup_mono fun _ h ↦ h.monotone_subset F_G lemma coverEntropyInfEntourage_monotone (T : X → X) (U : Set (X × X)) : Monotone fun F : Set X ↦ coverEntropyInfEntourage T F U := by refine fun F G F_G ↦ ExpGrowth.expGrowthInf_monotone fun n ↦ ?_ exact ENat.toENNReal_mono (coverMincard_monotone_subset T U n F_G) lemma coverEntropyEntourage_monotone (T : X → X) (U : Set (X × X)) : Monotone fun F : Set X ↦ coverEntropyEntourage T F U := by refine fun F G F_G ↦ ExpGrowth.expGrowthSup_monotone fun n ↦ ?_ exact ENat.toENNReal_mono (coverMincard_monotone_subset T U n F_G) lemma netEntropyInfEntourage_monotone (T : X → X) (U : Set (X × X)) : Monotone fun F : Set X ↦ netEntropyInfEntourage T F U := by refine fun F G F_G ↦ ExpGrowth.expGrowthInf_monotone fun n ↦ ?_ exact ENat.toENNReal_mono (netMaxcard_monotone_subset T U n F_G) lemma netEntropyEntourage_monotone (T : X → X) (U : Set (X × X)) : Monotone fun F : Set X ↦ netEntropyEntourage T F U := by refine fun F G F_G ↦ ExpGrowth.expGrowthSup_monotone fun n ↦ ?_ exact ENat.toENNReal_mono (netMaxcard_monotone_subset T U n F_G) lemma coverEntropyInf_monotone [UniformSpace X] (T : X → X) : Monotone fun F : Set X ↦ coverEntropyInf T F := fun _ _ F_G ↦ iSup₂_mono fun U _ ↦ coverEntropyInfEntourage_monotone T U F_G lemma coverEntropy_monotone [UniformSpace X] (T : X → X) : Monotone fun F : Set X ↦ coverEntropy T F := fun _ _ F_G ↦ iSup₂_mono fun U _ ↦ coverEntropyEntourage_monotone T U F_G end Subset /-! ### Closure -/ section Closure variable [UniformSpace X] {T : X → X} lemma IsDynCoverOf.closure (h : Continuous T) {F : Set X} {U V : Set (X × X)} (V_uni : V ∈ 𝓤 X) {n : ℕ} {s : Set X} (s_cover : IsDynCoverOf T F U n s) : IsDynCoverOf T (closure F) (U ○ V) n s := by rcases (hasBasis_symmetric.mem_iff' V).1 V_uni with ⟨W, ⟨W_uni, W_symm⟩, W_V⟩ refine IsDynCoverOf.of_entourage_subset (SetRel.comp_subset_comp_right W_V) fun x x_clos ↦ ?_ obtain ⟨y, y_x, y_F⟩ := mem_closure_iff_nhds.1 x_clos _ (ball_dynEntourage_mem_nhds h W_uni n x) obtain ⟨z, z_s, y_z⟩ := mem_iUnion₂.1 (s_cover y_F) refine mem_iUnion₂.2 ⟨z, z_s, ?_⟩ rw [mem_ball_symmetry] at y_x exact ball_mono (dynEntourage_comp_subset T U W n) z (mem_ball_comp y_z y_x) lemma coverMincard_closure_le (h : Continuous T) (F : Set X) (U : Set (X × X)) {V : Set (X × X)} (V_uni : V ∈ 𝓤 X) (n : ℕ) : coverMincard T (closure F) (U ○ V) n ≤ coverMincard T F U n := by rcases eq_top_or_lt_top (coverMincard T F U n) with h' | h' · exact h' ▸ le_top obtain ⟨s, s_cover, s_coverMincard⟩ := (coverMincard_finite_iff T F U n).1 h' exact s_coverMincard ▸ (s_cover.closure h V_uni).coverMincard_le_card lemma coverEntropyInfEntourage_closure (h : Continuous T) (F : Set X) (U : Set (X × X)) {V : Set (X × X)} (V_uni : V ∈ 𝓤 X) : coverEntropyInfEntourage T (closure F) (U ○ V) ≤ coverEntropyInfEntourage T F U := expGrowthInf_monotone fun n ↦ ENat.toENNReal_mono (coverMincard_closure_le h F U V_uni n) lemma coverEntropyEntourage_closure (h : Continuous T) (F : Set X) (U : Set (X × X)) {V : Set (X × X)} (V_uni : V ∈ 𝓤 X) : coverEntropyEntourage T (closure F) (U ○ V) ≤ coverEntropyEntourage T F U := expGrowthSup_monotone fun n ↦ ENat.toENNReal_mono (coverMincard_closure_le h F U V_uni n) lemma coverEntropyInf_closure (h : Continuous T) {F : Set X} : coverEntropyInf T (closure F) = coverEntropyInf T F := by refine (iSup₂_le fun U U_uni ↦ ?_).antisymm (coverEntropyInf_monotone T subset_closure) obtain ⟨V, V_uni, V_U⟩ := comp_mem_uniformity_sets U_uni exact le_iSup₂_of_le V V_uni ((coverEntropyInfEntourage_antitone T (closure F) V_U).trans (coverEntropyInfEntourage_closure h F V V_uni)) theorem coverEntropy_closure (h : Continuous T) {F : Set X} : coverEntropy T (closure F) = coverEntropy T F := by refine (iSup₂_le fun U U_uni ↦ ?_).antisymm (coverEntropy_monotone T subset_closure) obtain ⟨V, V_uni, V_U⟩ := comp_mem_uniformity_sets U_uni exact le_iSup₂_of_le V V_uni ((coverEntropyEntourage_antitone T (closure F) V_U).trans (coverEntropyEntourage_closure h F V V_uni)) end Closure /-! ### Finite unions -/ section Union lemma IsDynCoverOf.union {T : X → X} {F G : Set X} {U : Set (X × X)} {n : ℕ} {s t : Set X} (hs : IsDynCoverOf T F U n s) (ht : IsDynCoverOf T G U n t) : IsDynCoverOf T (F ∪ G) U n (s ∪ t) := union_subset (hs.trans (biUnion_subset_biUnion_left subset_union_left)) (ht.trans (biUnion_subset_biUnion_left subset_union_right)) lemma coverMincard_union_le (T : X → X) (F G : Set X) (U : Set (X × X)) (n : ℕ) : coverMincard T (F ∪ G) U n ≤ coverMincard T F U n + coverMincard T G U n := by classical rcases eq_top_or_lt_top (coverMincard T F U n) with hF | hF · rw [hF, top_add]; exact le_top rcases eq_top_or_lt_top (coverMincard T G U n) with hG | hG · rw [hG, add_top]; exact le_top obtain ⟨s, s_cover, s_coverMincard⟩ := (coverMincard_finite_iff T F U n).1 hF obtain ⟨t, t_cover, t_coverMincard⟩ := (coverMincard_finite_iff T G U n).1 hG rw [← s_coverMincard, ← t_coverMincard, ← ENat.coe_add] apply (IsDynCoverOf.coverMincard_le_card _).trans (WithTop.coe_mono (s.card_union_le t)) rw [s.coe_union t] exact s_cover.union t_cover lemma coverEntropyEntourage_union {T : X → X} {F G : Set X} {U : Set (X × X)} : coverEntropyEntourage T (F ∪ G) U = max (coverEntropyEntourage T F U) (coverEntropyEntourage T G U) := by refine le_antisymm ?_ ?_ · apply le_of_le_of_eq (expGrowthSup_monotone fun n ↦ ?_) expGrowthSup_add rw [Pi.add_apply, ← ENat.toENNReal_add] exact ENat.toENNReal_mono (coverMincard_union_le T F G U n) · exact max_le (coverEntropyEntourage_monotone T U subset_union_left) (coverEntropyEntourage_monotone T U subset_union_right) variable {ι : Type*} [UniformSpace X] lemma coverEntropy_union {T : X → X} {F G : Set X} : coverEntropy T (F ∪ G) = max (coverEntropy T F) (coverEntropy T G) := by simp only [coverEntropy, ← iSup_sup_eq] exact biSup_congr fun _ _ ↦ coverEntropyEntourage_union lemma coverEntropyInf_iUnion_le (T : X → X) (F : ι → Set X) : ⨆ i, coverEntropyInf T (F i) ≤ coverEntropyInf T (⋃ i, F i) := iSup_le fun i ↦ coverEntropyInf_monotone T (subset_iUnion F i) lemma coverEntropy_iUnion_le (T : X → X) (F : ι → Set X) : ⨆ i, coverEntropy T (F i) ≤ coverEntropy T (⋃ i, F i) := iSup_le fun i ↦ coverEntropy_monotone T (subset_iUnion F i) lemma coverEntropyInf_biUnion_le (s : Set ι) (T : X → X) (F : ι → Set X) : ⨆ i ∈ s, coverEntropyInf T (F i) ≤ coverEntropyInf T (⋃ i ∈ s, F i) := iSup₂_le fun _ i_s ↦ coverEntropyInf_monotone T (subset_biUnion_of_mem i_s) lemma coverEntropy_biUnion_le (s : Set ι) (T : X → X) (F : ι → Set X) : ⨆ i ∈ s, coverEntropy T (F i) ≤ coverEntropy T (⋃ i ∈ s, F i) := iSup₂_le fun _ i_s ↦ coverEntropy_monotone T (subset_biUnion_of_mem i_s) /-- Topological entropy `CoverEntropy T` as a `SupBotHom` function of the subset. -/ noncomputable def coverEntropy_supBotHom (T : X → X) : SupBotHom (Set X) EReal where toFun := coverEntropy T map_sup' := fun _ _ ↦ coverEntropy_union map_bot' := coverEntropy_empty lemma coverEntropy_iUnion_of_finite [Finite ι] {T : X → X} {F : ι → Set X} : coverEntropy T (⋃ i : ι, F i) = ⨆ i : ι, coverEntropy T (F i) := map_finite_iSup (coverEntropy_supBotHom T) F lemma coverEntropy_biUnion_finset {T : X → X} {F : ι → Set X} {s : Finset ι} : coverEntropy T (⋃ i ∈ s, F i) = ⨆ i ∈ s, coverEntropy T (F i) := by have := map_finset_sup (coverEntropy_supBotHom T) s F rw [s.sup_set_eq_biUnion, s.sup_eq_iSup, coverEntropy_supBotHom, SupBotHom.coe_mk, SupHom.coe_mk] at this rw [this] congr end Union end Dynamics
.lake/packages/mathlib/Mathlib/Dynamics/TopologicalEntropy/Semiconj.lean
import Mathlib.Dynamics.TopologicalEntropy.CoverEntropy /-! # Topological entropy of the image of a set under a semiconjugacy Consider two dynamical systems `(X, S)` and `(Y, T)` together with a semiconjugacy `φ`: ``` X ---S--> X | | φ φ | | v v Y ---T--> Y ``` We relate the topological entropy of a subset `F ⊆ X` with the topological entropy of its image `φ '' F ⊆ Y`. The best-known theorem is that, if all maps are uniformly continuous, then `coverEntropy T (φ '' F) ≤ coverEntropy S F`. This is theorem `coverEntropy_image_le_of_uniformContinuous` herein. We actually prove the much more general statement that `coverEntropy T (φ '' F) = coverEntropy S F` if `X` is endowed with the pullback by `φ` of the uniform structure of `Y`. This more general statement has another direct consequence: if `F` is `S`-invariant, then the topological entropy of the restriction of `S` to `F` is exactly `coverEntropy S F`. This corollary is essential: in most references, the entropy of an invariant subset (or subsystem) `F` is defined as the entropy of the restriction to `F` of the system. We chose instead to give a direct definition of the topological entropy of a subset, so as to avoid working with subtypes. Theorem `coverEntropy_restrict` shows that this choice is coherent with the literature. ## Implementation notes We use only the definition of the topological entropy using covers; the simplest version of `IsDynCoverOf.image` for nets fails. ## Main results - `coverEntropy_image_of_comap`/`coverEntropyInf_image_of_comap`: the entropy of `φ '' F` equals the entropy of `F` if `X` is endowed with the pullback by `φ` of the uniform structure of `Y`. - `coverEntropy_image_le_of_uniformContinuous`/`coverEntropyInf_image_le_of_uniformContinuous`: the entropy of `φ '' F` is lower than the entropy of `F` if `φ` is uniformly continuous. - `coverEntropy_restrict`: the entropy of the restriction of `S` to an invariant set `F` is `coverEntropy S F`. ## Tags entropy, semiconjugacy -/ open Function Prod Set Uniformity UniformSpace open scoped SetRel namespace Dynamics variable {X Y : Type*} {s F : Set X} {V : SetRel Y Y} {S : X → X} {T : Y → Y} {φ : X → Y} {n : ℕ} lemma IsDynCoverOf.image (h : Semiconj φ S T) (h' : IsDynCoverOf S F (map φ φ ⁻¹' V) n s) : IsDynCoverOf T (φ '' F) V n (φ '' s) := by simp only [IsDynCoverOf, image_subset_iff, preimage_iUnion₂, biUnion_image] refine h'.trans (iUnion₂_mono fun i _ ↦ subset_of_eq ?_) rw [← h.preimage_dynEntourage V n, ball_preimage] lemma IsDynCoverOf.preimage (h : Semiconj φ S T) [V.IsSymm] {t : Finset Y} (h' : IsDynCoverOf T (φ '' F) V n t) : ∃ s : Finset X, IsDynCoverOf S F ((map φ φ) ⁻¹' (V ○ V)) n s ∧ s.card ≤ t.card := by classical rcases isEmpty_or_nonempty X with _ | _ · exact ⟨∅, eq_empty_of_isEmpty F ▸ ⟨isDynCoverOf_empty, Finset.card_empty ▸ zero_le t.card⟩⟩ -- If `t` is a dynamical cover of `φ '' F`, then we want to choose one preimage by `φ` for each -- element of `t`. This is complicated by the fact that `t` may not be a subset of `φ '' F`, -- and may not even be in the range of `φ`. Hence, we first modify `t` to make it a subset -- of `φ '' F`. This requires taking larger entourages. obtain ⟨s, s_cover, s_card, s_inter⟩ := h'.nonempty_inter choose! g gs_cover using fun (x : Y) (h : x ∈ s) ↦ nonempty_def.1 (s_inter x h) choose! f f_section using fun (y : Y) (a : y ∈ φ '' F) ↦ a refine ⟨s.image (f ∘ g), ?_, Finset.card_image_le.trans s_card⟩ simp only [IsDynCoverOf, Finset.mem_coe, image_subset_iff, preimage_iUnion₂] at s_cover ⊢ apply s_cover.trans rw [← h.preimage_dynEntourage (V ○ V) n, Finset.set_biUnion_finset_image] refine iUnion₂_mono fun i i_s ↦ ?_ rw [comp_apply, ball_preimage, (f_section (g i) (gs_cover i i_s).2).2] refine preimage_mono fun x x_i ↦ mem_ball_dynEntourage_comp T n x (g i) ⟨i, ?_⟩ replace gs_cover := (gs_cover i i_s).1 rw [mem_ball_symmetry] at x_i gs_cover exact ⟨x_i, gs_cover⟩ lemma le_coverMincard_image (h : Semiconj φ S T) (F : Set X) [V.IsSymm] (n : ℕ) : coverMincard S F ((map φ φ) ⁻¹' (V ○ V)) n ≤ coverMincard T (φ '' F) V n := by rcases eq_top_or_lt_top (coverMincard T (φ '' F) V n) with h' | h' · exact h' ▸ le_top obtain ⟨t, t_cover, t_card⟩ := (coverMincard_finite_iff T (φ '' F) V n).1 h' obtain ⟨s, s_cover, s_card⟩ := t_cover.preimage h rw [← t_card] exact s_cover.coverMincard_le_card.trans (WithTop.coe_le_coe.2 s_card) lemma coverMincard_image_le (h : Semiconj φ S T) (F : Set X) (V : SetRel Y Y) (n : ℕ) : coverMincard T (φ '' F) V n ≤ coverMincard S F ((map φ φ) ⁻¹' V) n := by classical rcases eq_top_or_lt_top (coverMincard S F ((map φ φ) ⁻¹' V) n) with h' | h' · exact h' ▸ le_top obtain ⟨s, s_cover, s_card⟩ := (coverMincard_finite_iff S F ((map φ φ) ⁻¹' V) n).1 h' rw [← s_card] have := s_cover.image h rw [← s.coe_image] at this exact this.coverMincard_le_card.trans (WithTop.coe_le_coe.2 s.card_image_le) open ENNReal EReal ExpGrowth Filter lemma le_coverEntropyEntourage_image (h : Semiconj φ S T) (F : Set X) [V.IsSymm] : coverEntropyEntourage S F ((map φ φ) ⁻¹' (V ○ V)) ≤ coverEntropyEntourage T (φ '' F) V := expGrowthSup_monotone fun n ↦ ENat.toENNReal_mono (le_coverMincard_image h F n) lemma le_coverEntropyInfEntourage_image (h : Semiconj φ S T) (F : Set X) [V.IsSymm] : coverEntropyInfEntourage S F ((map φ φ) ⁻¹' (V ○ V)) ≤ coverEntropyInfEntourage T (φ '' F) V := expGrowthInf_monotone fun n ↦ ENat.toENNReal_mono (le_coverMincard_image h F n) lemma coverEntropyEntourage_image_le (h : Semiconj φ S T) (F : Set X) (V : SetRel Y Y) : coverEntropyEntourage T (φ '' F) V ≤ coverEntropyEntourage S F ((map φ φ) ⁻¹' V) := expGrowthSup_monotone fun n ↦ ENat.toENNReal_mono (coverMincard_image_le h F V n) lemma coverEntropyInfEntourage_image_le (h : Semiconj φ S T) (F : Set X) (V : SetRel Y Y) : coverEntropyInfEntourage T (φ '' F) V ≤ coverEntropyInfEntourage S F ((map φ φ) ⁻¹' V) := expGrowthInf_monotone fun n ↦ ENat.toENNReal_mono (coverMincard_image_le h F V n) /-- The entropy of `φ '' F` equals the entropy of `F` if `X` is endowed with the pullback by `φ` of the uniform structure of `Y`. -/ theorem coverEntropy_image_of_comap (u : UniformSpace Y) {S : X → X} {T : Y → Y} {φ : X → Y} (h : Semiconj φ S T) (F : Set X) : coverEntropy T (φ '' F) = @coverEntropy X (comap φ u) S F := by apply le_antisymm · refine iSup₂_le fun V V_uni ↦ (coverEntropyEntourage_image_le h F V).trans ?_ apply @coverEntropyEntourage_le_coverEntropy X (comap φ u) S F rw [uniformity_comap φ, mem_comap] exact ⟨V, V_uni, Subset.rfl⟩ · refine iSup₂_le fun U U_uni ↦ ?_ simp only [uniformity_comap φ, mem_comap] at U_uni obtain ⟨V, V_uni, V_sub⟩ := U_uni obtain ⟨W, W_uni, W_symm, W_V⟩ := comp_symm_mem_uniformity_sets V_uni apply (coverEntropyEntourage_antitone S F ((preimage_mono W_V).trans V_sub)).trans apply (le_coverEntropyEntourage_image h F).trans exact coverEntropyEntourage_le_coverEntropy T (φ '' F) W_uni /-- The entropy of `φ '' F` equals the entropy of `F` if `X` is endowed with the pullback by `φ` of the uniform structure of `Y`. This version uses a `liminf`. -/ theorem coverEntropyInf_image_of_comap (u : UniformSpace Y) {S : X → X} {T : Y → Y} {φ : X → Y} (h : Semiconj φ S T) (F : Set X) : coverEntropyInf T (φ '' F) = @coverEntropyInf X (comap φ u) S F := by apply le_antisymm · refine iSup₂_le fun V V_uni ↦ (coverEntropyInfEntourage_image_le h F V).trans ?_ apply @coverEntropyInfEntourage_le_coverEntropyInf X (comap φ u) S F rw [uniformity_comap φ, mem_comap] exact ⟨V, V_uni, Subset.rfl⟩ · refine iSup₂_le fun U U_uni ↦ ?_ simp only [uniformity_comap φ, mem_comap] at U_uni obtain ⟨V, V_uni, V_sub⟩ := U_uni obtain ⟨W, W_uni, W_symm, W_V⟩ := comp_symm_mem_uniformity_sets V_uni apply (coverEntropyInfEntourage_antitone S F ((preimage_mono W_V).trans V_sub)).trans apply (le_coverEntropyInfEntourage_image h F).trans exact coverEntropyInfEntourage_le_coverEntropyInf T (φ '' F) W_uni open Subtype lemma coverEntropy_restrict_subset [UniformSpace X] {T : X → X} {F G : Set X} (hF : F ⊆ G) (hG : MapsTo T G G) : coverEntropy (hG.restrict T G G) (val ⁻¹' F) = coverEntropy T F := by rw [← coverEntropy_image_of_comap _ hG.val_restrict_apply (val ⁻¹' F), image_preimage_coe G F, inter_eq_right.2 hF] lemma coverEntropyInf_restrict_subset [UniformSpace X] {T : X → X} {F G : Set X} (hF : F ⊆ G) (hG : MapsTo T G G) : coverEntropyInf (hG.restrict T G G) (val ⁻¹' F) = coverEntropyInf T F := by rw [← coverEntropyInf_image_of_comap _ hG.val_restrict_apply (val ⁻¹' F), image_preimage_coe G F, inter_eq_right.2 hF] /-- The entropy of the restriction of `T` to an invariant set `F` is `coverEntropy S F`. This theorem justifies our definition of `coverEntropy T F`. -/ theorem coverEntropy_restrict [UniformSpace X] {T : X → X} {F : Set X} (h : MapsTo T F F) : coverEntropy (h.restrict T F F) univ = coverEntropy T F := by rw [← coverEntropy_restrict_subset Subset.rfl h, coe_preimage_self F] /-- The entropy of `φ '' F` is lower than entropy of `F` if `φ` is uniformly continuous. -/ theorem coverEntropy_image_le_of_uniformContinuous [UniformSpace X] [UniformSpace Y] {S : X → X} {T : Y → Y} {φ : X → Y} (h : Semiconj φ S T) (h' : UniformContinuous φ) (F : Set X) : coverEntropy T (φ '' F) ≤ coverEntropy S F := by rw [coverEntropy_image_of_comap _ h F] exact coverEntropy_antitone S F (uniformContinuous_iff.1 h') /-- The entropy of `φ '' F` is lower than entropy of `F` if `φ` is uniformly continuous. This version uses a `liminf`. -/ theorem coverEntropyInf_image_le_of_uniformContinuous [UniformSpace X] [UniformSpace Y] {S : X → X} {T : Y → Y} {φ : X → Y} (h : Semiconj φ S T) (h' : UniformContinuous φ) (F : Set X) : coverEntropyInf T (φ '' F) ≤ coverEntropyInf S F := by rw [coverEntropyInf_image_of_comap _ h F] exact coverEntropyInf_antitone S F (uniformContinuous_iff.1 h') lemma coverEntropy_image_le_of_uniformContinuousOn_invariant [UniformSpace X] [UniformSpace Y] {S : X → X} {T : Y → Y} {φ : X → Y} (h : Semiconj φ S T) {F G : Set X} (h' : UniformContinuousOn φ G) (hF : F ⊆ G) (hG : MapsTo S G G) : coverEntropy T (φ '' F) ≤ coverEntropy S F := by rw [← coverEntropy_restrict_subset hF hG] have hφ : Semiconj (G.restrict φ) (hG.restrict S G G) T := by intro x rw [G.restrict_apply, G.restrict_apply, hG.val_restrict_apply, h.eq x] apply (coverEntropy_image_le_of_uniformContinuous hφ (uniformContinuousOn_iff_restrict.1 h') (val ⁻¹' F)).trans_eq' rw [← image_image_val_eq_restrict_image, image_preimage_coe G F, inter_eq_right.2 hF] lemma coverEntropyInf_image_le_of_uniformContinuousOn_invariant [UniformSpace X] [UniformSpace Y] {S : X → X} {T : Y → Y} {φ : X → Y} (h : Semiconj φ S T) {F G : Set X} (h' : UniformContinuousOn φ G) (hF : F ⊆ G) (hG : MapsTo S G G) : coverEntropyInf T (φ '' F) ≤ coverEntropyInf S F := by rw [← coverEntropyInf_restrict_subset hF hG] have hφ : Semiconj (G.restrict φ) (hG.restrict S G G) T := by intro a rw [G.restrict_apply, G.restrict_apply, hG.val_restrict_apply, h.eq a] apply (coverEntropyInf_image_le_of_uniformContinuous hφ (uniformContinuousOn_iff_restrict.1 h') (val ⁻¹' F)).trans_eq' rw [← image_image_val_eq_restrict_image, image_preimage_coe G F, inter_eq_right.2 hF] end Dynamics
.lake/packages/mathlib/Mathlib/Dynamics/TopologicalEntropy/CoverEntropy.lean
import Mathlib.Analysis.Asymptotics.ExpGrowth import Mathlib.Data.ENat.Lattice import Mathlib.Data.Real.ENatENNReal import Mathlib.Dynamics.TopologicalEntropy.DynamicalEntourage /-! # Topological entropy via covers We implement Bowen-Dinaburg's definitions of the topological entropy, via covers. All is stated in the vocabulary of uniform spaces. For compact spaces, the uniform structure is canonical, so the topological entropy depends only on the topological structure. This will give a clean proof that the topological entropy is a topological invariant of the dynamics. A notable choice is that we define the topological entropy of a subset `F` of the whole space. Usually, one defines the entropy of an invariant subset `F` as the entropy of the restriction of the transformation to `F`. We avoid the latter definition as it would involve frequent manipulation of subtypes. Our version directly gives a meaning to the topological entropy of a subsystem, and a single theorem (`subset_restriction_entropy` in `TopologicalEntropy.Semiconj`) will give the equivalence between both versions. Another choice is to give a meaning to the entropy of `∅` (it must be `-∞` to stay coherent) and to keep the possibility for the entropy to be infinite. Hence, the entropy takes values in the extended reals `[-∞, +∞]`. The consequence is that we use `ℕ∞`, `ℝ≥0∞` and `EReal` numbers. ## Main definitions - `IsDynCoverOf`: property that dynamical balls centered on a subset `s` cover a subset `F`. - `coverMincard`: minimal cardinality of a dynamical cover. Takes values in `ℕ∞`. - `coverEntropyInfEntourage`/`coverEntropyEntourage`: exponential growth of `coverMincard`. The former is defined with a `liminf`, the later with a `limsup`. Take values in `EReal`. - `coverEntropyInf`/`coverEntropy`: supremum of `coverEntropyInfEntourage`/`coverEntropyEntourage` over all entourages (or limit as the entourages go to the diagonal). These are Bowen-Dinaburg's versions of the topological entropy with covers. Take values in `EReal`. ## Implementation notes There are two competing definitions of topological entropy in this file: one uses a `liminf`, the other a `limsup`. These two topological entropies are equal as soon as they are applied to an invariant subset by theorem `coverEntropyInf_eq_coverEntropy`. We choose the default definition to be the definition using a `limsup`, and give it the simpler name `coverEntropy` (instead of `coverEntropySup`). Theorems about the topological entropy of invariant subsets will be stated using only `coverEntropy`. ## Main results - `IsDynCoverOf.iterate_le_pow`: given a dynamical cover at time `n`, creates dynamical covers at all iterates `n * m` with controlled cardinality. - `IsDynCoverOf.coverEntropyEntourage_le_log_card_div`: upper bound on `coverEntropyEntourage` given any dynamical cover. - `coverEntropyInf_eq_coverEntropy`: equality between the notions of topological entropy defined with a `liminf` and a `limsup`. ## Tags cover, entropy ## TODO Get versions of the topological entropy on (pseudo-e)metric spaces. -/ open Set Uniformity UniformSpace open scoped SetRel namespace Dynamics variable {X : Type*} /-! ### Dynamical covers -/ /-- Given a subset `F`, an entourage `U` and an integer `n`, a subset `s` is a `(U, n)`- dynamical cover of `F` if any orbit of length `n` in `F` is `U`-shadowed by an orbit of length `n` of a point in `s`. -/ def IsDynCoverOf (T : X → X) (F : Set X) (U : SetRel X X) (n : ℕ) (s : Set X) : Prop := F ⊆ ⋃ x ∈ s, ball x (dynEntourage T U n) lemma IsDynCoverOf.of_le {T : X → X} {F : Set X} {U : SetRel X X} {m n : ℕ} (m_n : m ≤ n) {s : Set X} (h : IsDynCoverOf T F U n s) : IsDynCoverOf T F U m s := h.trans (iUnion₂_mono fun x _ ↦ ball_mono (dynEntourage_antitone T U m_n) x) lemma IsDynCoverOf.of_entourage_subset {T : X → X} {F : Set X} {U V : SetRel X X} (U_V : U ⊆ V) {n : ℕ} {s : Set X} (h : IsDynCoverOf T F U n s) : IsDynCoverOf T F V n s := h.trans (iUnion₂_mono fun x _ ↦ ball_mono (dynEntourage_monotone T n U_V) x) @[simp] lemma isDynCoverOf_empty {T : X → X} {U : SetRel X X} {n : ℕ} {s : Set X} : IsDynCoverOf T ∅ U n s := by simp only [IsDynCoverOf, empty_subset] lemma IsDynCoverOf.nonempty {T : X → X} {F : Set X} (h : F.Nonempty) {U : SetRel X X} {n : ℕ} {s : Set X} (h' : IsDynCoverOf T F U n s) : s.Nonempty := by obtain ⟨x, x_s, _⟩ := nonempty_biUnion.1 (Nonempty.mono h' h) exact nonempty_of_mem x_s lemma isDynCoverOf_zero (T : X → X) (F : Set X) (U : SetRel X X) {s : Set X} (h : s.Nonempty) : IsDynCoverOf T F U 0 s := by simp only [IsDynCoverOf, ball, dynEntourage, not_lt_zero', Prod.map_iterate, iInter_of_empty, iInter_univ, preimage_univ] obtain ⟨x, x_s⟩ := h exact subset_iUnion₂_of_subset x x_s (subset_univ F) lemma isDynCoverOf_univ (T : X → X) (F : Set X) (n : ℕ) {s : Set X} (h : s.Nonempty) : IsDynCoverOf T F univ n s := by simp only [IsDynCoverOf, ball, dynEntourage, Prod.map_iterate, preimage_univ, iInter_univ] obtain ⟨x, x_s⟩ := h exact subset_iUnion₂_of_subset x x_s (subset_univ F) lemma IsDynCoverOf.nonempty_inter {T : X → X} {F : Set X} {U : SetRel X X} {n : ℕ} {s : Finset X} (h : IsDynCoverOf T F U n s) : ∃ t : Finset X, IsDynCoverOf T F U n t ∧ t.card ≤ s.card ∧ ∀ x ∈ t, ((ball x (dynEntourage T U n)) ∩ F).Nonempty := by classical use Finset.filter (fun x : X ↦ ((ball x (dynEntourage T U n)) ∩ F).Nonempty) s simp only [Finset.coe_filter, Finset.mem_filter, and_imp, imp_self, implies_true, and_true] refine ⟨fun y y_F ↦ ?_, Finset.card_mono (s.filter_subset _)⟩ specialize h y_F simp only [mem_iUnion, exists_prop] at h obtain ⟨z, z_s, y_Bz⟩ := h simp only [mem_setOf_eq, mem_iUnion, exists_prop] exact ⟨z, ⟨z_s, nonempty_of_mem ⟨y_Bz, y_F⟩⟩, y_Bz⟩ /-- From a dynamical cover `s` with entourage `U` and time `m`, we construct covers with entourage `U ○ U` and any multiple `m * n` of `m` with controlled cardinality. This lemma is the first step in a submultiplicative-like property of `coverMincard`, with consequences such as explicit bounds for the topological entropy (`coverEntropyInfEntourage_le_card_div`) and an equality between two notions of topological entropy (`coverEntropyInf_eq_coverEntropySup_of_inv`). -/ lemma IsDynCoverOf.iterate_le_pow {T : X → X} {F : Set X} (F_inv : MapsTo T F F) {U : SetRel X X} [U.IsSymm] {m : ℕ} (n : ℕ) {s : Finset X} (h : IsDynCoverOf T F U m s) : ∃ t : Finset X, IsDynCoverOf T F (U ○ U) (m * n) t ∧ t.card ≤ s.card ^ n := by classical -- Deal with the edge cases: `F = ∅` or `m = 0`. rcases F.eq_empty_or_nonempty with rfl | F_nemp · exact ⟨∅, by simp⟩ have _ : Nonempty X := F_nemp.nonempty have s_nemp := h.nonempty F_nemp obtain ⟨x, x_F⟩ := F_nemp rcases m.eq_zero_or_pos with rfl | m_pos · use {x} simp only [zero_mul, Finset.coe_singleton, Finset.card_singleton] exact ⟨isDynCoverOf_zero T F (U ○ U) (singleton_nonempty x), one_le_pow_of_one_le' (Nat.one_le_of_lt (Finset.Nonempty.card_pos s_nemp)) n⟩ -- The proof goes as follows. Given an orbit of length `(m * n)` starting from `y`, each of its -- iterates `y`, `T^[m] y`, `T^[m]^[2] y` ... is `(dynEntourage T U m)`-close to a point of `s`. -- Conversely, given a sequence `t 0`, `t 1`, `t 2` of points in `s`, we choose a point -- `z = dyncover t` such that `z`, `T^[m] z`, `T^[m]^[2] z` ... are `(dynEntourage T U m)`-close -- to `t 0`, `t 1`, `t 2`... Then `y`, `T^[m] y`, `T^[m]^[2] y` ... are -- `(dynEntourage T (U ○ U) m)`-close to `z`, `T^[m] z`, `T^[m]^[2] z`, so that the union of such -- `z` provides the desired cover. Since there are at most `s.card ^ n` sequences of -- length `n` with values in `s`, we get the upper bound we want on the cardinality. -- First step: construct `dyncover`. Given `t 0`, `t 1`, `t 2`, if we cannot find such a point -- `dyncover t`, we use the dummy `x`. have (t : Fin n → s) : ∃ y : X, (⋂ k : Fin n, T^[m * k] ⁻¹' ball (t k) (dynEntourage T U m)) ⊆ ball y (dynEntourage T (U ○ U) (m * n)) := by rcases (⋂ k : Fin n, T^[m * k] ⁻¹' ball (t k) (dynEntourage T U m)).eq_empty_or_nonempty with inter_empt | inter_nemp · exact inter_empt ▸ ⟨x, empty_subset _⟩ · obtain ⟨y, y_int⟩ := inter_nemp refine ⟨y, fun z z_int ↦ ?_⟩ simp only [ball, dynEntourage, Prod.map_iterate, mem_preimage, mem_iInter, Prod.map_apply] at y_int z_int ⊢ intro k k_mn replace k_mn := Nat.div_lt_of_lt_mul k_mn specialize z_int ⟨(k / m), k_mn⟩ (k % m) (Nat.mod_lt k m_pos) specialize y_int ⟨(k / m), k_mn⟩ (k % m) (Nat.mod_lt k m_pos) rw [← Function.iterate_add_apply T (k % m) (m * (k / m)), Nat.mod_add_div k m] at y_int z_int exact mem_comp_of_mem_ball y_int z_int choose! dyncover h_dyncover using this -- The cover we want is the set of all `dyncover t`, that is, `range dyncover`. We need to check -- that it is indeed a `(U ○ U, m * n)` cover, and that its cardinality is at most `card s ^ n`. -- Only the first point requires significant work. let sn := range dyncover refine ⟨sn.toFinset, ?_, ?_⟩ · -- We implement the argument at the beginning: given `y ∈ F`, we extract `t 0`, `t 1`, `t 2` -- such that `y`, `T^[m] y`, `T^[m]^[2] y` ... is `(dynEntourage T U m)`-close to `t 0`, `t 1`, -- `t 2`... Then `dyncover t` is a point of `range dyncover` which satisfies the conclusion -- of the lemma. rw [Finset.coe_nonempty] at s_nemp have _ : Nonempty s := Finset.Nonempty.coe_sort s_nemp intro y y_F have key : ∀ k : Fin n, ∃ z : s, y ∈ T^[m * k] ⁻¹' ball z (dynEntourage T U m) := by intro k have := h (MapsTo.iterate F_inv (m * k) y_F) simp only [mem_iUnion, exists_prop] at this obtain ⟨z, z_s, hz⟩ := this exact ⟨⟨z, z_s⟩, hz⟩ choose! t ht using key simp only [toFinset_range, Finset.coe_image, Finset.coe_univ, image_univ, mem_range, iUnion_exists, iUnion_iUnion_eq', mem_iUnion, sn] use t apply h_dyncover t simp only [mem_iInter, mem_preimage] at ht ⊢ exact ht · rw [toFinset_card] apply (Fintype.card_range_le dyncover).trans simp only [Fintype.card_fun, Fintype.card_coe, Fintype.card_fin, le_refl] lemma exists_isDynCoverOf_of_isCompact_uniformContinuous [UniformSpace X] {T : X → X} {F : Set X} (F_comp : IsCompact F) (h : UniformContinuous T) {U : SetRel X X} (U_uni : U ∈ 𝓤 X) (n : ℕ) : ∃ s : Finset X, IsDynCoverOf T F U n s := by have uni_ite := dynEntourage_mem_uniformity h U_uni n let open_cover := fun x : X ↦ ball x (dynEntourage T U n) obtain ⟨s, _, s_cover⟩ := IsCompact.elim_nhds_subcover F_comp open_cover fun (x : X) _ ↦ ball_mem_nhds x uni_ite exact ⟨s, s_cover⟩ lemma exists_isDynCoverOf_of_isCompact_invariant [UniformSpace X] {T : X → X} {F : Set X} (F_comp : IsCompact F) (F_inv : MapsTo T F F) {U : SetRel X X} (U_uni : U ∈ 𝓤 X) (n : ℕ) : ∃ s : Finset X, IsDynCoverOf T F U n s := by obtain ⟨V, V_uni, V_symm, V_U⟩ := comp_symm_mem_uniformity_sets U_uni obtain ⟨s, _, s_cover⟩ := IsCompact.elim_nhds_subcover F_comp (fun x : X ↦ ball x V) fun (x : X) _ ↦ ball_mem_nhds x V_uni have : IsDynCoverOf T F V 1 s := by simp only [IsDynCoverOf, Finset.mem_coe, dynEntourage_one, s_cover] obtain ⟨t, t_dyncover, t_card⟩ := this.iterate_le_pow F_inv n rw [one_mul n] at t_dyncover exact ⟨t, t_dyncover.of_entourage_subset V_U⟩ /-! ### Minimal cardinality of dynamical covers -/ /-- The smallest cardinality of a `(U, n)`-dynamical cover of `F`. Takes values in `ℕ∞`, and is infinite if and only if `F` admits no finite dynamical cover. -/ noncomputable def coverMincard (T : X → X) (F : Set X) (U : SetRel X X) (n : ℕ) : ℕ∞ := ⨅ (s : Finset X) (_ : IsDynCoverOf T F U n s), (s.card : ℕ∞) lemma IsDynCoverOf.coverMincard_le_card {T : X → X} {F : Set X} {U : SetRel X X} {n : ℕ} {s : Finset X} (h : IsDynCoverOf T F U n s) : coverMincard T F U n ≤ s.card := iInf₂_le s h lemma coverMincard_monotone_time (T : X → X) (F : Set X) (U : SetRel X X) : Monotone fun n : ℕ ↦ coverMincard T F U n := fun _ _ m_n ↦ biInf_mono fun _ h ↦ h.of_le m_n lemma coverMincard_antitone (T : X → X) (F : Set X) (n : ℕ) : Antitone fun U : SetRel X X ↦ coverMincard T F U n := fun _ _ U_V ↦ biInf_mono fun _ h ↦ h.of_entourage_subset U_V lemma coverMincard_finite_iff (T : X → X) (F : Set X) (U : SetRel X X) (n : ℕ) : coverMincard T F U n < ⊤ ↔ ∃ s : Finset X, IsDynCoverOf T F U n s ∧ s.card = coverMincard T F U n := by refine ⟨fun h_fin ↦ ?_, fun ⟨s, _, s_coverMincard⟩ ↦ s_coverMincard ▸ WithTop.coe_lt_top s.card⟩ obtain ⟨k, k_min⟩ := WithTop.ne_top_iff_exists.1 h_fin.ne rw [← k_min] simp only [ENat.some_eq_coe, Nat.cast_inj] have : Nonempty {s : Finset X // IsDynCoverOf T F U n s} := by by_contra h apply ENat.coe_ne_top k rw [← ENat.some_eq_coe, k_min, coverMincard, iInf₂_eq_top] simp only [ENat.coe_ne_top, imp_false] rw [nonempty_subtype, not_exists] at h exact h have key := ciInf_mem fun s : {s : Finset X // IsDynCoverOf T F U n s} ↦ (s.val.card : ℕ∞) rw [coverMincard, iInf_subtype'] at k_min rw [← k_min, mem_range, Subtype.exists] at key simp only [ENat.some_eq_coe, Nat.cast_inj, exists_prop] at key exact key @[simp] lemma coverMincard_empty {T : X → X} {U : SetRel X X} {n : ℕ} : coverMincard T ∅ U n = 0 := (sInf_le (by simp [IsDynCoverOf])).antisymm (zero_le (coverMincard T ∅ U n)) lemma coverMincard_eq_zero_iff (T : X → X) (F : Set X) (U : SetRel X X) (n : ℕ) : coverMincard T F U n = 0 ↔ F = ∅ := by refine ⟨fun h ↦ subset_empty_iff.1 ?_, fun F_empt ↦ by rw [F_empt, coverMincard_empty]⟩ have := coverMincard_finite_iff T F U n rw [h, eq_true ENat.top_pos, true_iff] at this simp only [IsDynCoverOf, Finset.mem_coe, Nat.cast_eq_zero, Finset.card_eq_zero, exists_eq_right, Finset.notMem_empty, iUnion_of_empty, iUnion_empty] at this exact this lemma one_le_coverMincard_iff (T : X → X) (F : Set X) (U : SetRel X X) (n : ℕ) : 1 ≤ coverMincard T F U n ↔ F.Nonempty := by rw [ENat.one_le_iff_ne_zero, nonempty_iff_ne_empty, not_iff_not] exact coverMincard_eq_zero_iff T F U n lemma coverMincard_zero (T : X → X) {F : Set X} (h : F.Nonempty) (U : SetRel X X) : coverMincard T F U 0 = 1 := by apply le_antisymm _ ((one_le_coverMincard_iff T F U 0).2 h) obtain ⟨x, _⟩ := h have := isDynCoverOf_zero T F U (singleton_nonempty x) rw [← Finset.coe_singleton] at this apply this.coverMincard_le_card.trans_eq rw [Finset.card_singleton, Nat.cast_one] lemma coverMincard_univ (T : X → X) {F : Set X} (h : F.Nonempty) (n : ℕ) : coverMincard T F univ n = 1 := by apply le_antisymm _ ((one_le_coverMincard_iff T F univ n).2 h) obtain ⟨x, _⟩ := h have := isDynCoverOf_univ T F n (singleton_nonempty x) rw [← Finset.coe_singleton] at this apply this.coverMincard_le_card.trans_eq rw [Finset.card_singleton, Nat.cast_one] lemma coverMincard_mul_le_pow {T : X → X} {F : Set X} (F_inv : MapsTo T F F) {U : SetRel X X} [U.IsSymm] (m n : ℕ) : coverMincard T F (U ○ U) (m * n) ≤ coverMincard T F U m ^ n := by rcases F.eq_empty_or_nonempty with rfl | F_nonempty · rw [coverMincard_empty]; exact zero_le _ obtain rfl | hn := eq_or_ne n 0 · rw [mul_zero, coverMincard_zero T F_nonempty (U ○ U), pow_zero] rcases eq_top_or_lt_top (coverMincard T F U m) with h | h · simp [*] · obtain ⟨s, s_cover, s_coverMincard⟩ := (coverMincard_finite_iff T F U m).1 h obtain ⟨t, t_cover, t_sn⟩ := s_cover.iterate_le_pow F_inv n rw [← s_coverMincard] exact t_cover.coverMincard_le_card.trans (WithTop.coe_le_coe.2 t_sn) lemma coverMincard_le_pow {T : X → X} {F : Set X} (F_inv : MapsTo T F F) {U : SetRel X X} [U.IsSymm] {m : ℕ} (m_pos : 0 < m) (n : ℕ) : coverMincard T F (U ○ U) n ≤ coverMincard T F U m ^ (n / m + 1) := (coverMincard_monotone_time T F (U ○ U) (Nat.lt_mul_div_succ n m_pos).le).trans (coverMincard_mul_le_pow F_inv m (n / m + 1)) lemma coverMincard_finite_of_isCompact_uniformContinuous [UniformSpace X] {T : X → X} {F : Set X} (F_comp : IsCompact F) (h : UniformContinuous T) {U : SetRel X X} (U_uni : U ∈ 𝓤 X) (n : ℕ) : coverMincard T F U n < ⊤ := by obtain ⟨s, s_cover⟩ := exists_isDynCoverOf_of_isCompact_uniformContinuous F_comp h U_uni n exact s_cover.coverMincard_le_card.trans_lt (WithTop.coe_lt_top s.card) lemma coverMincard_finite_of_isCompact_invariant [UniformSpace X] {T : X → X} {F : Set X} (F_comp : IsCompact F) (F_inv : MapsTo T F F) {U : SetRel X X} (U_uni : U ∈ 𝓤 X) (n : ℕ) : coverMincard T F U n < ⊤ := by obtain ⟨s, s_cover⟩ := exists_isDynCoverOf_of_isCompact_invariant F_comp F_inv U_uni n exact s_cover.coverMincard_le_card.trans_lt (WithTop.coe_lt_top s.card) /-- All dynamical balls of a minimal dynamical cover of `F` intersect `F`. This lemma is the key to relate Bowen-Dinaburg's definition of topological entropy with covers and their definition of topological entropy with nets. -/ lemma nonempty_inter_of_coverMincard {T : X → X} {F : Set X} {U : SetRel X X} {n : ℕ} {s : Finset X} (h : IsDynCoverOf T F U n s) (h' : s.card = coverMincard T F U n) : ∀ x ∈ s, (F ∩ ball x (dynEntourage T U n)).Nonempty := by -- Otherwise, there is a ball which does not intersect `F`. Removing it yields a smaller cover. classical by_contra! hypo obtain ⟨x, x_s, ball_empt⟩ := hypo have smaller_cover : IsDynCoverOf T F U n (s.erase x) := by intro y y_F specialize h y_F simp only [s.mem_coe, mem_iUnion, exists_prop] at h simp only [s.coe_erase, mem_diff, s.mem_coe, mem_singleton_iff, mem_iUnion, exists_prop] obtain ⟨z, z_s, hz⟩ := h refine ⟨z, ⟨z_s, fun z_x ↦ notMem_empty y ?_⟩, hz⟩ rw [← ball_empt] rw [z_x] at hz exact mem_inter y_F hz apply smaller_cover.coverMincard_le_card.not_gt rw [← h'] exact_mod_cast s.card_erase_lt_of_mem x_s /-! ### Cover entropy of entourages -/ open ENNReal EReal ExpGrowth Filter /-- The entropy of an entourage `U`, defined as the exponential rate of growth of the size of the smallest `(U, n)`-refined cover of `F`. Takes values in the space of extended real numbers `[-∞, +∞]`. This first version uses a `limsup`, and is chosen as the default definition. -/ noncomputable def coverEntropyEntourage (T : X → X) (F : Set X) (U : SetRel X X) := expGrowthSup fun n : ℕ ↦ coverMincard T F U n /-- The entropy of an entourage `U`, defined as the exponential rate of growth of the size of the smallest `(U, n)`-refined cover of `F`. Takes values in the space of extended real numbers `[-∞, +∞]`. This second version uses a `liminf`, and is chosen as an alternative definition. -/ noncomputable def coverEntropyInfEntourage (T : X → X) (F : Set X) (U : SetRel X X) := expGrowthInf fun n : ℕ ↦ coverMincard T F U n lemma coverEntropyInfEntourage_antitone (T : X → X) (F : Set X) : Antitone fun U : SetRel X X ↦ coverEntropyInfEntourage T F U := fun _ _ U_V ↦ expGrowthInf_monotone fun n ↦ ENat.toENNReal_mono (coverMincard_antitone T F n U_V) lemma coverEntropyEntourage_antitone (T : X → X) (F : Set X) : Antitone fun U : SetRel X X ↦ coverEntropyEntourage T F U := fun _ _ U_V ↦ expGrowthSup_monotone fun n ↦ ENat.toENNReal_mono (coverMincard_antitone T F n U_V) lemma coverEntropyInfEntourage_le_coverEntropyEntourage (T : X → X) (F : Set X) (U : SetRel X X) : coverEntropyInfEntourage T F U ≤ coverEntropyEntourage T F U := expGrowthInf_le_expGrowthSup @[simp] lemma coverEntropyEntourage_empty {T : X → X} {U : SetRel X X} : coverEntropyEntourage T ∅ U = ⊥ := by simp only [coverEntropyEntourage, coverMincard_empty] rw [ENat.toENNReal_zero, ← Pi.zero_def, expGrowthSup_zero] @[simp] lemma coverEntropyInfEntourage_empty {T : X → X} {U : SetRel X X} : coverEntropyInfEntourage T ∅ U = ⊥ := eq_bot_mono (coverEntropyInfEntourage_le_coverEntropyEntourage T ∅ U) coverEntropyEntourage_empty lemma coverEntropyInfEntourage_nonneg (T : X → X) {F : Set X} (h : F.Nonempty) (U : SetRel X X) : 0 ≤ coverEntropyInfEntourage T F U := by apply Monotone.expGrowthInf_nonneg · exact fun _ _ m_n ↦ ENat.toENNReal_mono (coverMincard_monotone_time T F U m_n) · rw [ne_eq, funext_iff.not, not_forall] use 0 rw [coverMincard_zero T h U, Pi.zero_apply, ENat.toENNReal_one] exact one_ne_zero lemma coverEntropyEntourage_nonneg (T : X → X) {F : Set X} (h : F.Nonempty) (U : SetRel X X) : 0 ≤ coverEntropyEntourage T F U := (coverEntropyInfEntourage_nonneg T h U).trans (coverEntropyInfEntourage_le_coverEntropyEntourage T F U) lemma coverEntropyEntourage_univ (T : X → X) {F : Set X} (h : F.Nonempty) : coverEntropyEntourage T F univ = 0 := by rw [← expGrowthSup_const one_ne_zero one_ne_top, coverEntropyEntourage] simp only [coverMincard_univ T h, ENat.toENNReal_one] lemma coverEntropyInfEntourage_univ (T : X → X) {F : Set X} (h : F.Nonempty) : coverEntropyInfEntourage T F univ = 0 := by rw [← expGrowthInf_const one_ne_zero one_ne_top, coverEntropyInfEntourage] simp only [coverMincard_univ T h, ENat.toENNReal_one] lemma coverEntropyEntourage_le_log_coverMincard_div {T : X → X} {F : Set X} (F_inv : MapsTo T F F) {U : SetRel X X} [U.IsSymm] {n : ℕ} (n_pos : n ≠ 0) : coverEntropyEntourage T F (U ○ U) ≤ log (coverMincard T F U n) / n := by have cv_mono : Monotone fun m ↦ (coverMincard T F (U ○ U) m).toENNReal := fun _ _ k_m ↦ ENat.toENNReal_mono (coverMincard_monotone_time T F (U ○ U) k_m) have h := cv_mono.expGrowthSup_comp_mul n_pos rw [mul_comm, ← div_eq_iff (natCast_ne_bot n) (natCast_ne_top n) (Nat.cast_ne_zero.2 n_pos)] at h rw [coverEntropyEntourage, ← h] apply monotone_div_right_of_nonneg n.cast_nonneg' rw [← expGrowthSup_pow] refine expGrowthSup_monotone fun m ↦ ?_ rw [← ENat.toENNReal_pow] exact ENat.toENNReal_mono (coverMincard_mul_le_pow F_inv n m) lemma IsDynCoverOf.coverEntropyEntourage_le_log_card_div {T : X → X} {F : Set X} (F_inv : MapsTo T F F) {U : SetRel X X} [U.IsSymm] {n : ℕ} (n_pos : n ≠ 0) {s : Finset X} (h : IsDynCoverOf T F U n s) : coverEntropyEntourage T F (U ○ U) ≤ log s.card / n := by apply (coverEntropyEntourage_le_log_coverMincard_div F_inv n_pos).trans apply monotone_div_right_of_nonneg n.cast_nonneg' (log_monotone _) exact_mod_cast coverMincard_le_card h lemma coverEntropyEntourage_le_coverEntropyInfEntourage {T : X → X} {F : Set X} (F_inv : MapsTo T F F) {U : SetRel X X} [U.IsSymm] : coverEntropyEntourage T F (U ○ U) ≤ coverEntropyInfEntourage T F U := by refine (le_liminf_of_le) (eventually_atTop.2 ⟨1, fun m m_pos ↦ ?_⟩) exact coverEntropyEntourage_le_log_coverMincard_div F_inv (Nat.one_le_iff_ne_zero.1 m_pos) lemma coverEntropyEntourage_finite_of_isCompact_invariant [UniformSpace X] {T : X → X} {F : Set X} (F_comp : IsCompact F) (F_inv : MapsTo T F F) {U : SetRel X X} (U_uni : U ∈ 𝓤 X) : coverEntropyEntourage T F U < ⊤ := by obtain ⟨V, V_uni, V_symm, V_U⟩ := comp_symm_mem_uniformity_sets U_uni obtain ⟨s, s_cover⟩ := exists_isDynCoverOf_of_isCompact_invariant F_comp F_inv V_uni 1 apply (coverEntropyEntourage_antitone T F V_U).trans_lt apply (s_cover.coverEntropyEntourage_le_log_card_div F_inv one_ne_zero).trans_lt rw [Nat.cast_one, div_one, log_lt_top_iff, ← ENat.toENNReal_top] exact_mod_cast (ENat.coe_ne_top (Finset.card s)).lt_top /-! ### Cover entropy -/ /-- The entropy of `T` restricted to `F`, obtained by taking the supremum of `coverEntropyEntourage` over entourages. Note that this supremum is approached by taking small entourages. This first version uses a `limsup`, and is chosen as the default definition for topological entropy. -/ noncomputable def coverEntropy [UniformSpace X] (T : X → X) (F : Set X) := ⨆ U ∈ 𝓤 X, coverEntropyEntourage T F U /-- The entropy of `T` restricted to `F`, obtained by taking the supremum of `coverEntropyInfEntourage` over entourages. Note that this supremum is approached by taking small entourages. This second version uses a `liminf`, and is chosen as an alternative definition for topological entropy. -/ noncomputable def coverEntropyInf [UniformSpace X] (T : X → X) (F : Set X) := ⨆ U ∈ 𝓤 X, coverEntropyInfEntourage T F U lemma coverEntropyInf_antitone (T : X → X) (F : Set X) : Antitone fun (u : UniformSpace X) ↦ @coverEntropyInf X u T F := fun _ _ h ↦ iSup₂_mono' fun U U_uni ↦ ⟨U, (le_def.1 h) U U_uni, le_refl _⟩ lemma coverEntropy_antitone (T : X → X) (F : Set X) : Antitone fun (u : UniformSpace X) ↦ @coverEntropy X u T F := fun _ _ h ↦ iSup₂_mono' fun U U_uni ↦ ⟨U, (le_def.1 h) U U_uni, le_refl _⟩ variable [UniformSpace X] lemma coverEntropyEntourage_le_coverEntropy (T : X → X) (F : Set X) {U : SetRel X X} (h : U ∈ 𝓤 X) : coverEntropyEntourage T F U ≤ coverEntropy T F := le_iSup₂ (f := fun (U : SetRel X X) (_ : U ∈ 𝓤 X) ↦ coverEntropyEntourage T F U) U h lemma coverEntropyInfEntourage_le_coverEntropyInf (T : X → X) (F : Set X) {U : SetRel X X} (h : U ∈ 𝓤 X) : coverEntropyInfEntourage T F U ≤ coverEntropyInf T F := le_iSup₂ (f := fun (U : SetRel X X) (_ : U ∈ 𝓤 X) ↦ coverEntropyInfEntourage T F U) U h lemma coverEntropy_eq_iSup_basis {ι : Sort*} {p : ι → Prop} {s : ι → SetRel X X} (h : (𝓤 X).HasBasis p s) (T : X → X) (F : Set X) : coverEntropy T F = ⨆ (i : ι) (_ : p i), coverEntropyEntourage T F (s i) := by refine (iSup₂_le fun U U_uni ↦ ?_).antisymm (iSup₂_mono' fun i h_i ↦ ⟨s i, HasBasis.mem_of_mem h h_i, le_refl _⟩) obtain ⟨i, h_i, si_U⟩ := (HasBasis.mem_iff h).1 U_uni exact (coverEntropyEntourage_antitone T F si_U).trans (le_iSup₂ (f := fun (i : ι) (_ : p i) ↦ coverEntropyEntourage T F (s i)) i h_i) lemma coverEntropyInf_eq_iSup_basis {ι : Sort*} {p : ι → Prop} {s : ι → SetRel X X} (h : (𝓤 X).HasBasis p s) (T : X → X) (F : Set X) : coverEntropyInf T F = ⨆ (i : ι) (_ : p i), coverEntropyInfEntourage T F (s i) := by refine (iSup₂_le fun U U_uni ↦ ?_).antisymm (iSup₂_mono' fun i h_i ↦ ⟨s i, HasBasis.mem_of_mem h h_i, le_refl _⟩) obtain ⟨i, h_i, si_U⟩ := (HasBasis.mem_iff h).1 U_uni exact (coverEntropyInfEntourage_antitone T F si_U).trans (le_iSup₂ (f := fun (i : ι) (_ : p i) ↦ coverEntropyInfEntourage T F (s i)) i h_i) lemma coverEntropyInf_le_coverEntropy (T : X → X) (F : Set X) : coverEntropyInf T F ≤ coverEntropy T F := iSup₂_mono fun (U : SetRel X X) (_ : U ∈ 𝓤 X) ↦ coverEntropyInfEntourage_le_coverEntropyEntourage T F U @[simp] lemma coverEntropy_empty {T : X → X} : coverEntropy T ∅ = ⊥ := by simp only [coverEntropy, coverEntropyEntourage_empty, iSup_bot] @[simp] lemma coverEntropyInf_empty {T : X → X} : coverEntropyInf T ∅ = ⊥ := by simp only [coverEntropyInf, coverEntropyInfEntourage_empty, iSup_bot] lemma coverEntropyInf_nonneg (T : X → X) {F : Set X} (h : F.Nonempty) : 0 ≤ coverEntropyInf T F := (coverEntropyInfEntourage_le_coverEntropyInf T F univ_mem).trans_eq' (coverEntropyInfEntourage_univ T h).symm lemma coverEntropy_nonneg (T : X → X) {F : Set X} (h : F.Nonempty) : 0 ≤ coverEntropy T F := (coverEntropyInf_nonneg T h).trans (coverEntropyInf_le_coverEntropy T F) lemma coverEntropyInf_eq_coverEntropy (T : X → X) {F : Set X} (h : MapsTo T F F) : coverEntropyInf T F = coverEntropy T F := by refine le_antisymm (coverEntropyInf_le_coverEntropy T F) (iSup₂_le fun U U_uni ↦ ?_) obtain ⟨V, V_uni, V_symm, V_U⟩ := comp_symm_mem_uniformity_sets U_uni exact (coverEntropyEntourage_antitone T F V_U).trans <| le_iSup₂_of_le V V_uni <| coverEntropyEntourage_le_coverEntropyInfEntourage h end Dynamics
.lake/packages/mathlib/Mathlib/Dynamics/TopologicalEntropy/NetEntropy.lean
import Mathlib.Dynamics.TopologicalEntropy.CoverEntropy /-! # Topological entropy via nets We implement Bowen-Dinaburg's definitions of the topological entropy, via nets. The major design decisions are the same as in `Mathlib/Dynamics/TopologicalEntropy/CoverEntropy.lean`, and are explained in detail there: use of uniform spaces, definition of the topological entropy of a subset, and values taken in `EReal`. Given a map `T : X → X` and a subset `F ⊆ X`, the topological entropy is loosely defined using nets as the exponential growth (in `n`) of the number of distinguishable orbits of length `n` starting from `F`. More precisely, given an entourage `U`, two orbits of length `n` can be distinguished if there exists some index `k < n` such that `T^[k] x` and `T^[k] y` are far enough (i.e. `(T^[k] x, T^[k] y)` is not in `U`). The maximal number of distinguishable orbits of length `n` is `netMaxcard T F U n`, and its exponential growth `netEntropyEntourage T F U`. This quantity increases when `U` decreases, and a definition of the topological entropy is `⨆ U ∈ 𝓤 X, netEntropyInfEntourage T F U`. The definition of topological entropy using nets coincides with the definition using covers. Instead of defining a new notion of topological entropy, we prove that `coverEntropy` coincides with `⨆ U ∈ 𝓤 X, netEntropyEntourage T F U`. ## Main definitions - `IsDynNetIn`: property that dynamical balls centered on a subset `s` of `F` are disjoint. - `netMaxcard`: maximal cardinality of a dynamical net. Takes values in `ℕ∞`. - `netEntropyInfEntourage`/`netEntropyEntourage`: exponential growth of `netMaxcard`. The former is defined with a `liminf`, the latter with a `limsup`. Take values in `EReal`. ## Implementation notes As when using covers, there are two competing definitions `netEntropyInfEntourage` and `netEntropyEntourage` in this file: one uses a `liminf`, the other a `limsup`. When using covers, we chose the `limsup` definition as the default. ## Main results - `coverEntropy_eq_iSup_netEntropyEntourage`: equality between the notions of topological entropy defined with covers and with nets. Has a variant for `coverEntropyInf`. ## Tags net, entropy ## TODO Get versions of the topological entropy on (pseudo-e)metric spaces. -/ open Set Uniformity UniformSpace open scoped SetRel namespace Dynamics variable {X : Type*} {T : X → X} {U V : SetRel X X} {m n : ℕ} {F s : Set X} {x : X} /-! ### Dynamical nets -/ /-- Given a subset `F`, an entourage `U` and an integer `n`, a subset `s` of `F` is a `(U, n)`-dynamical net of `F` if no two orbits of length `n` of points in `s` shadow each other. -/ def IsDynNetIn (T : X → X) (F : Set X) (U : SetRel X X) (n : ℕ) (s : Set X) : Prop := s ⊆ F ∧ s.PairwiseDisjoint fun x : X ↦ ball x (dynEntourage T U n) lemma IsDynNetIn.of_le (m_n : m ≤ n) (h : IsDynNetIn T F U m s) : IsDynNetIn T F U n s := ⟨h.1, PairwiseDisjoint.mono h.2 fun x ↦ ball_mono (dynEntourage_antitone T U m_n) x⟩ lemma IsDynNetIn.of_entourage_subset (U_V : U ⊆ V) (h : IsDynNetIn T F V n s) : IsDynNetIn T F U n s := ⟨h.1, PairwiseDisjoint.mono h.2 fun x ↦ ball_mono (dynEntourage_monotone T n U_V) x⟩ lemma isDynNetIn_empty : IsDynNetIn T F U n ∅ := ⟨empty_subset F, pairwise_empty _⟩ lemma isDynNetIn_singleton (T : X → X) (U : SetRel X X) (n : ℕ) (h : x ∈ F) : IsDynNetIn T F U n {x} := ⟨singleton_subset_iff.2 h, pairwise_singleton x _⟩ /-- Given an entourage `U` and a time `n`, a dynamical net has a smaller cardinality than a dynamical cover. This lemma is the first of two key results to compare two versions of topological entropy: with cover and with nets, the second being `coverMincard_le_netMaxcard`. -/ lemma IsDynNetIn.card_le_card_of_isDynCoverOf [U.IsSymm] {s t : Finset X} (hs : IsDynNetIn T F U n s) (ht : IsDynCoverOf T F U n t) : s.card ≤ t.card := by have (x : X) (x_s : x ∈ s) : ∃ z ∈ t, x ∈ ball z (dynEntourage T U n) := by specialize ht (hs.1 x_s) simp only [mem_iUnion, exists_prop] at ht exact ht choose! F s_t using this simp only [mem_ball_symmetry] at s_t apply Finset.card_le_card_of_injOn F fun x x_s ↦ (s_t x x_s).1 exact fun x x_s y y_s Fx_Fy ↦ PairwiseDisjoint.elim_set hs.2 x_s y_s (F x) (s_t x x_s).2 (Fx_Fy ▸ (s_t y y_s).2) /-! ### Maximal cardinality of dynamical nets -/ /-- The largest cardinality of a `(U, n)`-dynamical net of `F`. Takes values in `ℕ∞`, and is infinite if and only if `F` admits nets of arbitrarily large size. -/ noncomputable def netMaxcard (T : X → X) (F : Set X) (U : SetRel X X) (n : ℕ) : ℕ∞ := ⨆ (s : Finset X) (_ : IsDynNetIn T F U n s), (s.card : ℕ∞) lemma IsDynNetIn.card_le_netMaxcard {s : Finset X} (h : IsDynNetIn T F U n s) : s.card ≤ netMaxcard T F U n := le_iSup₂ (α := ℕ∞) s h lemma netMaxcard_monotone_time (T : X → X) (F : Set X) (U : SetRel X X) : Monotone fun n : ℕ ↦ netMaxcard T F U n := fun _ _ m_n ↦ biSup_mono fun _ h ↦ h.of_le m_n lemma netMaxcard_antitone (T : X → X) (F : Set X) (n : ℕ) : Antitone fun U : SetRel X X ↦ netMaxcard T F U n := fun _ _ U_V ↦ biSup_mono fun _ h ↦ h.of_entourage_subset U_V lemma netMaxcard_finite_iff (T : X → X) (F : Set X) (U : SetRel X X) (n : ℕ) : netMaxcard T F U n < ⊤ ↔ ∃ s : Finset X, IsDynNetIn T F U n s ∧ (s.card : ℕ∞) = netMaxcard T F U n := by apply Iff.intro <;> intro h · obtain ⟨k, k_max⟩ := WithTop.ne_top_iff_exists.1 h.ne rw [← k_max] simp only [ENat.some_eq_coe, Nat.cast_inj] -- The criterion we want to use is `Nat.sSup_mem`. We rewrite `netMaxcard` with an `sSup`, -- then check its `BddAbove` and `Nonempty` hypotheses. have : netMaxcard T F U n = sSup (WithTop.some '' (Finset.card '' {s : Finset X | IsDynNetIn T F U n s})) := by rw [netMaxcard, ← image_comp, sSup_image] simp only [mem_setOf_eq, ENat.some_eq_coe, Function.comp_apply] rw [this] at k_max have h_bdda : BddAbove (Finset.card '' {s : Finset X | IsDynNetIn T F U n s}) := by refine ⟨k, mem_upperBounds.2 ?_⟩ simp only [mem_image, mem_setOf_eq, forall_exists_index, and_imp, forall_apply_eq_imp_iff₂] intro s h rw [← WithTop.coe_le_coe, k_max] apply le_sSup simp only [ENat.some_eq_coe, mem_image, mem_setOf_eq, Nat.cast_inj, exists_eq_right] exact Filter.frequently_principal.mp fun a ↦ a h rfl have h_nemp : (Finset.card '' {s : Finset X | IsDynNetIn T F U n s}).Nonempty := by refine ⟨0, ?_⟩ simp only [mem_image, mem_setOf_eq, Finset.card_eq_zero, exists_eq_right, Finset.coe_empty] exact isDynNetIn_empty rw [← WithTop.coe_sSup' h_bdda, ENat.some_eq_coe, Nat.cast_inj] at k_max have key := Nat.sSup_mem h_nemp h_bdda rw [← k_max, mem_image] at key simp only [mem_setOf_eq] at key exact key · obtain ⟨s, _, s_card⟩ := h rw [← s_card] exact WithTop.coe_lt_top s.card @[simp] lemma netMaxcard_empty : netMaxcard T ∅ U n = 0 := by rw [netMaxcard, ← bot_eq_zero, iSup₂_eq_bot] intro s s_net replace s_net := subset_empty_iff.1 s_net.1 norm_cast at s_net rw [s_net, Finset.card_empty, CharP.cast_eq_zero, bot_eq_zero'] lemma netMaxcard_eq_zero_iff (T : X → X) (F : Set X) (U : SetRel X X) (n : ℕ) : netMaxcard T F U n = 0 ↔ F = ∅ := by refine ⟨fun h ↦ ?_, fun h ↦ by rw [h, netMaxcard_empty]⟩ rw [eq_empty_iff_forall_notMem] intro x x_F have key := isDynNetIn_singleton T U n x_F rw [← Finset.coe_singleton] at key replace key := key.card_le_netMaxcard rw [Finset.card_singleton, Nat.cast_one, h] at key exact key.not_gt zero_lt_one lemma one_le_netMaxcard_iff (T : X → X) (F : Set X) (U : SetRel X X) (n : ℕ) : 1 ≤ netMaxcard T F U n ↔ F.Nonempty := by rw [ENat.one_le_iff_ne_zero, nonempty_iff_ne_empty] exact not_iff_not.2 (netMaxcard_eq_zero_iff T F U n) lemma netMaxcard_zero (T : X → X) (h : F.Nonempty) (U : SetRel X X) : netMaxcard T F U 0 = 1 := by apply (iSup₂_le _).antisymm ((one_le_netMaxcard_iff T F U 0).2 h) intro s ⟨_, s_net⟩ simp only [ball, dynEntourage_zero, preimage_univ] at s_net norm_cast refine Finset.card_le_one.2 fun x x_s y y_s ↦ ?_ exact PairwiseDisjoint.elim_set s_net x_s y_s x (mem_univ x) (mem_univ x) lemma netMaxcard_univ (T : X → X) (h : F.Nonempty) (n : ℕ) : netMaxcard T F univ n = 1 := by apply (iSup₂_le _).antisymm ((one_le_netMaxcard_iff T F univ n).2 h) intro s ⟨_, s_net⟩ simp only [ball, dynEntourage_univ, preimage_univ] at s_net norm_cast refine Finset.card_le_one.2 fun x x_s y y_s ↦ ?_ exact PairwiseDisjoint.elim_set s_net x_s y_s x (mem_univ x) (mem_univ x) lemma netMaxcard_infinite_iff (T : X → X) (F : Set X) (U : SetRel X X) (n : ℕ) : netMaxcard T F U n = ⊤ ↔ ∀ k : ℕ, ∃ s : Finset X, IsDynNetIn T F U n s ∧ k ≤ s.card := by apply Iff.intro <;> intro h · intro k rw [netMaxcard, iSup_subtype', iSup_eq_top] at h specialize h k (ENat.coe_lt_top k) simp only [Nat.cast_lt, Subtype.exists, exists_prop] at h obtain ⟨s, s_net, s_k⟩ := h exact ⟨s, s_net, s_k.le⟩ · refine WithTop.eq_top_iff_forall_gt.2 fun k ↦ ?_ specialize h (k + 1) obtain ⟨s, s_net, s_card⟩ := h apply s_net.card_le_netMaxcard.trans_lt' rw [ENat.some_eq_coe, Nat.cast_lt] exact (lt_add_one k).trans_le s_card lemma netMaxcard_le_coverMincard (T : X → X) (F : Set X) [U.IsSymm] (n : ℕ) : netMaxcard T F U n ≤ coverMincard T F U n := by rcases eq_top_or_lt_top (coverMincard T F U n) with h | h · exact h ▸ le_top · obtain ⟨t, t_cover, t_mincard⟩ := (coverMincard_finite_iff T F U n).1 h rw [← t_mincard] exact iSup₂_le fun s s_net ↦ Nat.cast_le.2 (s_net.card_le_card_of_isDynCoverOf t_cover) /-- Given an entourage `U` and a time `n`, a minimal dynamical cover by `U ○ U` has a smaller cardinality than a maximal dynamical net by `U`. This lemma is the second of two key results to compare two versions topological entropy: with cover and with nets. -/ lemma coverMincard_le_netMaxcard (T : X → X) (F : Set X) [U.IsRefl] [U.IsSymm] (n : ℕ) : coverMincard T F (U ○ U) n ≤ netMaxcard T F U n := by classical -- WLOG, there exists a maximal dynamical net `s`. rcases eq_top_or_lt_top (netMaxcard T F U n) with h | h · exact h ▸ le_top obtain ⟨s, s_net, s_card⟩ := (netMaxcard_finite_iff T F U n).1 h rw [← s_card] apply IsDynCoverOf.coverMincard_le_card -- We have to check that `s` is a cover for `dynEntourage T F (U ○ U) n`. -- If `s` is not a cover, then we can add to `s` a point `x` which is not covered -- and get a new net. This contradicts the maximality of `s`. by_contra h obtain ⟨x, x_F, x_uncov⟩ := not_subset.1 h simp only [Finset.mem_coe, mem_iUnion, exists_prop, not_exists, not_and] at x_uncov have larger_net : IsDynNetIn T F U n (insert x s) := by refine ⟨insert_subset x_F s_net.1, pairwiseDisjoint_insert.2 ⟨s_net.2, ?_⟩⟩ refine fun y y_s _ ↦ disjoint_left.2 fun z z_x z_y ↦ x_uncov y y_s ?_ exact mem_ball_dynEntourage_comp T n x y (nonempty_of_mem ⟨z_x, z_y⟩) rw [← s.coe_insert x] at larger_net apply larger_net.card_le_netMaxcard.not_gt rw [← s_card, Nat.cast_lt] refine (lt_add_one s.card).trans_eq (s.card_insert_of_notMem fun x_s ↦ ?_).symm exact x_uncov x x_s (ball_mono (dynEntourage_monotone T n SetRel.left_subset_comp) x <| SetRel.rfl (dynEntourage T U n)) /-! ### Net entropy of entourages -/ open ENNReal EReal ExpGrowth Filter /-- The entropy of an entourage `U`, defined as the exponential rate of growth of the size of the largest `(U, n)`-dynamical net of `F`. Takes values in the space of extended real numbers `[-∞,+∞]`. This version uses a `limsup`, and is chosen as the default definition. -/ noncomputable def netEntropyEntourage (T : X → X) (F : Set X) (U : SetRel X X) := expGrowthSup fun n : ℕ ↦ netMaxcard T F U n /-- The entropy of an entourage `U`, defined as the exponential rate of growth of the size of the largest `(U, n)`-dynamical net of `F`. Takes values in the space of extended real numbers `[-∞,+∞]`. This version uses a `liminf`, and is an alternative definition. -/ noncomputable def netEntropyInfEntourage (T : X → X) (F : Set X) (U : SetRel X X) := expGrowthInf fun n : ℕ ↦ netMaxcard T F U n lemma netEntropyInfEntourage_antitone (T : X → X) (F : Set X) : Antitone fun U : SetRel X X ↦ netEntropyInfEntourage T F U := fun _ _ U_V ↦ expGrowthInf_monotone fun n ↦ ENat.toENNReal_mono (netMaxcard_antitone T F n U_V) lemma netEntropyEntourage_antitone (T : X → X) (F : Set X) : Antitone fun U : SetRel X X ↦ netEntropyEntourage T F U := fun _ _ U_V ↦ expGrowthSup_monotone fun n ↦ ENat.toENNReal_mono (netMaxcard_antitone T F n U_V) lemma netEntropyInfEntourage_le_netEntropyEntourage (T : X → X) (F : Set X) (U : SetRel X X) : netEntropyInfEntourage T F U ≤ netEntropyEntourage T F U := expGrowthInf_le_expGrowthSup @[simp] lemma netEntropyEntourage_empty : netEntropyEntourage T ∅ U = ⊥ := by rw [netEntropyEntourage, ← expGrowthSup_zero] congr simp only [netMaxcard_empty, ENat.toENNReal_zero, Pi.zero_def] @[simp] lemma netEntropyInfEntourage_empty : netEntropyInfEntourage T ∅ U = ⊥ := eq_bot_mono (netEntropyInfEntourage_le_netEntropyEntourage T ∅ U) netEntropyEntourage_empty lemma netEntropyInfEntourage_nonneg (T : X → X) (h : F.Nonempty) (U : SetRel X X) : 0 ≤ netEntropyInfEntourage T F U := by apply Monotone.expGrowthInf_nonneg · exact fun _ _ m_n ↦ ENat.toENNReal_mono (netMaxcard_monotone_time T F U m_n) · rw [ne_eq, funext_iff.not, not_forall] use 0 rw [netMaxcard_zero T h U, Pi.zero_apply, ENat.toENNReal_one] exact one_ne_zero lemma netEntropyEntourage_nonneg (T : X → X) (h : F.Nonempty) (U : SetRel X X) : 0 ≤ netEntropyEntourage T F U := (netEntropyInfEntourage_nonneg T h U).trans (netEntropyInfEntourage_le_netEntropyEntourage T F U) lemma netEntropyInfEntourage_univ (T : X → X) {F : Set X} (h : F.Nonempty) : netEntropyInfEntourage T F univ = 0 := by rw [← expGrowthInf_const one_ne_zero one_ne_top, netEntropyInfEntourage] simp only [netMaxcard_univ T h, ENat.toENNReal_one] lemma netEntropyEntourage_univ (T : X → X) {F : Set X} (h : F.Nonempty) : netEntropyEntourage T F univ = 0 := by rw [← expGrowthSup_const one_ne_zero one_ne_top, netEntropyEntourage] simp only [netMaxcard_univ T h, ENat.toENNReal_one] lemma netEntropyInfEntourage_le_coverEntropyInfEntourage (T : X → X) (F : Set X) [U.IsSymm] : netEntropyInfEntourage T F U ≤ coverEntropyInfEntourage T F U := expGrowthInf_monotone fun n ↦ ENat.toENNReal_mono (netMaxcard_le_coverMincard T F n) lemma coverEntropyInfEntourage_le_netEntropyInfEntourage (T : X → X) (F : Set X) [U.IsRefl] [U.IsSymm] : coverEntropyInfEntourage T F (U ○ U) ≤ netEntropyInfEntourage T F U := expGrowthInf_monotone fun n ↦ ENat.toENNReal_mono (coverMincard_le_netMaxcard T F n) lemma netEntropyEntourage_le_coverEntropyEntourage (T : X → X) (F : Set X) [U.IsSymm] : netEntropyEntourage T F U ≤ coverEntropyEntourage T F U := expGrowthSup_monotone fun n ↦ ENat.toENNReal_mono (netMaxcard_le_coverMincard T F n) lemma coverEntropyEntourage_le_netEntropyEntourage (T : X → X) (F : Set X) [U.IsRefl] [U.IsSymm] : coverEntropyEntourage T F (U ○ U) ≤ netEntropyEntourage T F U := expGrowthSup_monotone fun n ↦ ENat.toENNReal_mono (coverMincard_le_netMaxcard T F n) /-! ### Relationship with entropy via covers -/ variable [UniformSpace X] (T : X → X) (F : Set X) /-- Bowen-Dinaburg's definition of topological entropy using nets is `⨆ U ∈ 𝓤 X, netEntropyEntourage T F U`. This quantity is the same as the topological entropy using covers, so there is no need to define a new notion of topological entropy. This version of the theorem relates the `liminf` versions of topological entropy. -/ theorem coverEntropyInf_eq_iSup_netEntropyInfEntourage : coverEntropyInf T F = ⨆ U ∈ 𝓤 X, netEntropyInfEntourage T F U := by apply le_antisymm <;> refine iSup₂_le fun U U_uni ↦ ?_ · obtain ⟨V, V_uni, V_symm, V_U⟩ := comp_symm_mem_uniformity_sets U_uni have := SetRel.id_subset_iff.1 <| refl_le_uniformity V_uni apply (coverEntropyInfEntourage_antitone T F V_U).trans (le_iSup₂_of_le V V_uni _) exact coverEntropyInfEntourage_le_netEntropyInfEntourage T F · apply (netEntropyInfEntourage_antitone T F SetRel.symmetrize_subset_self).trans apply (le_iSup₂ (SetRel.symmetrize U) (symmetrize_mem_uniformity U_uni)).trans' exact netEntropyInfEntourage_le_coverEntropyInfEntourage T F /-- Bowen-Dinaburg's definition of topological entropy using nets is `⨆ U ∈ 𝓤 X, netEntropyEntourage T F U`. This quantity is the same as the topological entropy using covers, so there is no need to define a new notion of topological entropy. This version of the theorem relates the `limsup` versions of topological entropy. -/ theorem coverEntropy_eq_iSup_netEntropyEntourage : coverEntropy T F = ⨆ U ∈ 𝓤 X, netEntropyEntourage T F U := by apply le_antisymm <;> refine iSup₂_le fun U U_uni ↦ ?_ · obtain ⟨V, V_uni, V_symm, V_comp_U⟩ := comp_symm_mem_uniformity_sets U_uni apply (coverEntropyEntourage_antitone T F V_comp_U).trans (le_iSup₂_of_le V V_uni _) have := SetRel.id_subset_iff.1 <| refl_le_uniformity V_uni exact coverEntropyEntourage_le_netEntropyEntourage T F · apply (netEntropyEntourage_antitone T F SetRel.symmetrize_subset_self).trans apply (le_iSup₂ (SetRel.symmetrize U) (symmetrize_mem_uniformity U_uni)).trans' exact netEntropyEntourage_le_coverEntropyEntourage T F lemma coverEntropyInf_eq_iSup_basis_netEntropyInfEntourage {ι : Sort*} {p : ι → Prop} {s : ι → SetRel X X} (h : (𝓤 X).HasBasis p s) (T : X → X) (F : Set X) : coverEntropyInf T F = ⨆ (i : ι) (_ : p i), netEntropyInfEntourage T F (s i) := by rw [coverEntropyInf_eq_iSup_netEntropyInfEntourage T F] apply (iSup₂_mono' fun i h_i ↦ ⟨s i, HasBasis.mem_of_mem h h_i, le_refl _⟩).antisymm' refine iSup₂_le fun U U_uni ↦ ?_ obtain ⟨i, h_i, si_U⟩ := (HasBasis.mem_iff h).1 U_uni apply (netEntropyInfEntourage_antitone T F si_U).trans exact le_iSup₂ (f := fun (i : ι) (_ : p i) ↦ netEntropyInfEntourage T F (s i)) i h_i lemma coverEntropy_eq_iSup_basis_netEntropyEntourage {ι : Sort*} {p : ι → Prop} {s : ι → SetRel X X} (h : (𝓤 X).HasBasis p s) (T : X → X) (F : Set X) : coverEntropy T F = ⨆ (i : ι) (_ : p i), netEntropyEntourage T F (s i) := by rw [coverEntropy_eq_iSup_netEntropyEntourage T F] apply (iSup₂_mono' fun i h_i ↦ ⟨s i, HasBasis.mem_of_mem h h_i, le_refl _⟩).antisymm' refine iSup₂_le fun U U_uni ↦ ?_ obtain ⟨i, h_i, si_U⟩ := (HasBasis.mem_iff h).1 U_uni apply (netEntropyEntourage_antitone T F si_U).trans _ exact le_iSup₂ (f := fun (i : ι) (_ : p i) ↦ netEntropyEntourage T F (s i)) i h_i lemma netEntropyInfEntourage_le_coverEntropyInf (h : U ∈ 𝓤 X) : netEntropyInfEntourage T F U ≤ coverEntropyInf T F := coverEntropyInf_eq_iSup_netEntropyInfEntourage T F ▸ le_iSup₂ (f := fun (U : SetRel X X) (_ : U ∈ 𝓤 X) ↦ netEntropyInfEntourage T F U) U h lemma netEntropyEntourage_le_coverEntropy (h : U ∈ 𝓤 X) : netEntropyEntourage T F U ≤ coverEntropy T F := coverEntropy_eq_iSup_netEntropyEntourage T F ▸ le_iSup₂ (f := fun (U : SetRel X X) (_ : U ∈ 𝓤 X) ↦ netEntropyEntourage T F U) U h end Dynamics
.lake/packages/mathlib/Mathlib/Dynamics/TopologicalEntropy/DynamicalEntourage.lean
import Mathlib.Order.Interval.Finset.Nat import Mathlib.Topology.Constructions.SumProd import Mathlib.Topology.UniformSpace.Basic /-! # Dynamical entourages Bowen-Dinaburg's definition of topological entropy of a transformation `T` in a metric space `(X, d)` relies on the so-called dynamical balls. These balls are sets `B (x, ε, n) = { y | ∀ k < n, d(T^[k] x, T^[k] y) < ε }`. We implement Bowen-Dinaburg's definitions in the more general context of uniform spaces. Dynamical balls are replaced by what we call dynamical entourages. This file collects all general lemmas about these objects. ## Main definitions - `dynEntourage`: dynamical entourage associated with a given transformation `T`, entourage `U` and time `n`. ## Tags entropy ## TODO Add product of entourages. In the context of (pseudo-e)metric spaces, relate the usual definition of dynamical balls with these dynamical entourages. -/ namespace Dynamics open Prod Set UniformSpace open scoped SetRel Topology Uniformity variable {X : Type*} {T : X → X} {U : SetRel X X} {n : ℕ} {x y : X} /-- The dynamical entourage associated to a transformation `T`, entourage `U` and time `n` is the entourage where `x` and `y` are close iff `T^[k] x` and `T^[k] y` are `U`-close for all `k < n`, i.e. iff they are `U`-close up to time `n`. -/ def dynEntourage (T : X → X) (U : SetRel X X) (n : ℕ) : SetRel X X := ⋂ k < n, (map T T)^[k] ⁻¹' U lemma dynEntourage_eq_inter_Ico (T : X → X) (U : SetRel X X) (n : ℕ) : dynEntourage T U n = ⋂ k : Ico 0 n, (map T T)^[k] ⁻¹' U := by simp [dynEntourage] lemma mem_dynEntourage : (x, y) ∈ dynEntourage T U n ↔ ∀ k < n, (T^[k] x, T^[k] y) ∈ U := by simp [dynEntourage] lemma mem_ball_dynEntourage : y ∈ ball x (dynEntourage T U n) ↔ ∀ k < n, T^[k] y ∈ ball (T^[k] x) U := by simp only [ball, mem_preimage, mem_dynEntourage] lemma dynEntourage_mem_uniformity [UniformSpace X] (h : UniformContinuous T) (U_uni : U ∈ 𝓤 X) (n : ℕ) : dynEntourage T U n ∈ 𝓤 X := by rw [dynEntourage_eq_inter_Ico T U n] refine Filter.iInter_mem.2 fun k ↦ ?_ rw [map_iterate T T k] exact uniformContinuous_def.1 (UniformContinuous.iterate T k h) U U_uni lemma ball_dynEntourage_mem_nhds [UniformSpace X] (h : Continuous T) (U_uni : U ∈ 𝓤 X) (n : ℕ) (x : X) : ball x (dynEntourage T U n) ∈ 𝓝 x := by rw [dynEntourage_eq_inter_Ico T U n, ball_iInter, Filter.iInter_mem, Subtype.forall] intro k _ simp only [map_iterate, _root_.ball_preimage] exact (h.iterate k).continuousAt.preimage_mem_nhds (ball_mem_nhds (T^[k] x) U_uni) instance isRefl_dynEntourage [U.IsRefl] : (dynEntourage T U n).IsRefl := by simp [dynEntourage]; infer_instance instance isSymm_dynEntourage [U.IsSymm] : (dynEntourage T U n).IsSymm := by simp [dynEntourage]; infer_instance set_option linter.deprecated false in @[deprecated isRefl_dynEntourage (since := "2025-10-17")] lemma idRel_subset_dynEntourage (T : X → X) {U : Set (X × X)} (h : idRel ⊆ U) (n : ℕ) : idRel ⊆ (dynEntourage T U n) := by simp only [dynEntourage, map_iterate, subset_iInter_iff, idRel_subset, mem_preimage, map_apply] exact fun _ _ _ ↦ h rfl set_option linter.deprecated false in @[deprecated isSymm_dynEntourage (since := "2025-10-17")] lemma _root_.IsSymmetricRel.dynEntourage (T : X → X) {U : Set (X × X)} (h : IsSymmetricRel U) (n : ℕ) : IsSymmetricRel (dynEntourage T U n) := by ext xy simp only [Dynamics.dynEntourage, map_iterate, mem_preimage, mem_iInter] refine forall₂_congr fun k _ ↦ ?_ exact map_apply' _ _ _ ▸ IsSymmetricRel.mk_mem_comm h lemma dynEntourage_comp_subset (T : X → X) (U V : SetRel X X) (n : ℕ) : (dynEntourage T U n) ○ (dynEntourage T V n) ⊆ dynEntourage T (U ○ V) n := by simp only [dynEntourage, map_iterate, subset_iInter_iff] intro k k_n xy xy_comp simp only [SetRel.comp, mem_iInter, mem_preimage, map_apply, mem_setOf_eq] at xy_comp ⊢ rcases xy_comp with ⟨z, hz1, hz2⟩ exact mem_ball_comp (hz1 k k_n) (hz2 k k_n) lemma _root_.isOpen.dynEntourage [TopologicalSpace X] {T : X → X} (T_cont : Continuous T) (U_open : IsOpen U) (n : ℕ) : IsOpen (dynEntourage T U n) := by rw [dynEntourage_eq_inter_Ico T U n] refine isOpen_iInter_of_finite fun k ↦ ?_ exact U_open.preimage ((T_cont.prodMap T_cont).iterate k) lemma dynEntourage_monotone (T : X → X) (n : ℕ) : Monotone (fun U : SetRel X X ↦ dynEntourage T U n) := fun _ _ h ↦ iInter₂_mono fun _ _ ↦ preimage_mono h lemma dynEntourage_antitone (T : X → X) (U : SetRel X X) : Antitone (fun n : ℕ ↦ dynEntourage T U n) := fun m n m_n ↦ iInter₂_mono' fun k k_m ↦ by use k, lt_of_lt_of_le k_m m_n @[simp] lemma dynEntourage_zero : dynEntourage T U 0 = univ := by simp [dynEntourage] @[simp] lemma dynEntourage_one : dynEntourage T U 1 = U := by simp [dynEntourage] @[simp] lemma dynEntourage_univ {T : X → X} {n : ℕ} : dynEntourage T univ n = univ := by simp [dynEntourage] lemma mem_ball_dynEntourage_comp (T : X → X) (n : ℕ) {U : SetRel X X} [U.IsSymm] (x y : X) (h : (ball x (dynEntourage T U n) ∩ ball y (dynEntourage T U n)).Nonempty) : x ∈ ball y (dynEntourage T (U ○ U) n) := by rcases h with ⟨z, z_Bx, z_By⟩ rw [mem_ball_symmetry] at z_Bx exact dynEntourage_comp_subset T U U n (mem_ball_comp z_By z_Bx) lemma _root_.Function.Semiconj.preimage_dynEntourage {Y : Type*} {S : X → X} {T : Y → Y} {φ : X → Y} (h : Function.Semiconj φ S T) (U : Set (Y × Y)) (n : ℕ) : (map φ φ)⁻¹' (dynEntourage T U n) = dynEntourage S ((map φ φ)⁻¹' U) n := by rw [dynEntourage, preimage_iInter₂] refine iInter₂_congr fun k _ ↦ ?_ rw [← preimage_comp, ← preimage_comp, map_iterate S S k, map_iterate T T k, map_comp_map, map_comp_map, (Function.Semiconj.iterate_right h k).comp_eq] end Dynamics
.lake/packages/mathlib/Mathlib/Dynamics/BirkhoffSum/Average.lean
import Mathlib.Dynamics.BirkhoffSum.Basic import Mathlib.Algebra.Module.Basic /-! # Birkhoff average In this file we define `birkhoffAverage f g n x` to be $$ \frac{1}{n}\sum_{k=0}^{n-1}g(f^{[k]}(x)), $$ where `f : α → α` is a self-map on some type `α`, `g : α → M` is a function from `α` to a module over a division semiring `R`, and `R` is used to formalize division by `n` as `(n : R)⁻¹ • _`. While we need an auxiliary division semiring `R` to define `birkhoffAverage`, the definition does not depend on the choice of `R`, see `birkhoffAverage_congr_ring`. -/ open Finset section birkhoffAverage variable (R : Type*) {α M : Type*} [DivisionSemiring R] [AddCommMonoid M] [Module R M] /-- The average value of `g` on the first `n` points of the orbit of `x` under `f`, i.e. the Birkhoff sum `∑ k ∈ Finset.range n, g (f^[k] x)` divided by `n`. This average appears in many ergodic theorems which say that `(birkhoffAverage R f g · x)` converges to the "space average" `⨍ x, g x ∂μ` as `n → ∞`. We use an auxiliary `[DivisionSemiring R]` to define division by `n`. However, the definition does not depend on the choice of `R`, see `birkhoffAverage_congr_ring`. -/ def birkhoffAverage (f : α → α) (g : α → M) (n : ℕ) (x : α) : M := (n : R)⁻¹ • birkhoffSum f g n x theorem birkhoffAverage_zero (f : α → α) (g : α → M) (x : α) : birkhoffAverage R f g 0 x = 0 := by simp [birkhoffAverage] @[simp] theorem birkhoffAverage_zero' (f : α → α) (g : α → M) : birkhoffAverage R f g 0 = 0 := funext <| birkhoffAverage_zero _ _ _ theorem birkhoffAverage_one (f : α → α) (g : α → M) (x : α) : birkhoffAverage R f g 1 x = g x := by simp [birkhoffAverage] @[simp] theorem birkhoffAverage_one' (f : α → α) (g : α → M) : birkhoffAverage R f g 1 = g := funext <| birkhoffAverage_one R f g theorem map_birkhoffAverage (S : Type*) {F N : Type*} [DivisionSemiring S] [AddCommMonoid N] [Module S N] [FunLike F M N] [AddMonoidHomClass F M N] (g' : F) (f : α → α) (g : α → M) (n : ℕ) (x : α) : g' (birkhoffAverage R f g n x) = birkhoffAverage S f (g' ∘ g) n x := by simp only [birkhoffAverage, map_inv_natCast_smul g' R S, map_birkhoffSum] theorem birkhoffAverage_congr_ring (S : Type*) [DivisionSemiring S] [Module S M] (f : α → α) (g : α → M) (n : ℕ) (x : α) : birkhoffAverage R f g n x = birkhoffAverage S f g n x := map_birkhoffAverage R S (AddMonoidHom.id M) f g n x theorem birkhoffAverage_congr_ring' (S : Type*) [DivisionSemiring S] [Module S M] : birkhoffAverage (α := α) (M := M) R = birkhoffAverage S := by ext; apply birkhoffAverage_congr_ring theorem Function.IsFixedPt.birkhoffAverage_eq [CharZero R] {f : α → α} {x : α} (h : IsFixedPt f x) (g : α → M) {n : ℕ} (hn : n ≠ 0) : birkhoffAverage R f g n x = g x := by rw [birkhoffAverage, h.birkhoffSum_eq, ← Nat.cast_smul_eq_nsmul R, inv_smul_smul₀] rwa [Nat.cast_ne_zero] lemma birkhoffAverage_add {f : α → α} {g g' : α → M} : birkhoffAverage R f (g + g') = birkhoffAverage R f g + birkhoffAverage R f g' := by funext _ x simp [birkhoffAverage, birkhoffSum, sum_add_distrib, smul_add] end birkhoffAverage section AddCommGroup variable {R : Type*} {α M : Type*} [DivisionSemiring R] [AddCommGroup M] [Module R M] lemma birkhoffAverage_neg {f : α → α} {g : α → M} : birkhoffAverage R f (-g) = - birkhoffAverage R f g := by funext _ x simp [birkhoffAverage, birkhoffSum] lemma birkhoffAverage_sub {f : α → α} {g g' : α → M} : birkhoffAverage R f (g - g') = birkhoffAverage R f g - birkhoffAverage R f g' := by funext _ x simp [birkhoffAverage, birkhoffSum, smul_sub] /-- Birkhoff average is "almost invariant" under `f`: the difference between `birkhoffAverage R f g n (f x)` and `birkhoffAverage R f g n x` is equal to `(n : R)⁻¹ • (g (f^[n] x) - g x)`. -/ theorem birkhoffAverage_apply_sub_birkhoffAverage (f : α → α) (g : α → M) (n : ℕ) (x : α) : birkhoffAverage R f g n (f x) - birkhoffAverage R f g n x = (n : R)⁻¹ • (g (f^[n] x) - g x) := by simp only [birkhoffAverage, birkhoffSum_apply_sub_birkhoffSum, ← smul_sub] /-- If a function `g` is invariant under a function `f` (i.e., `g ∘ f = g`), then the Birkhoff average of `g` over `f` for `n` iterations is equal to `g`. Requires that `0 < n`. -/ theorem birkhoffAverage_of_comp_eq [CharZero R] {f : α → α} {g : α → M} (h : g ∘ f = g) {n : ℕ} (hn : n ≠ 0) : birkhoffAverage R f g n = g := by funext x suffices (n : R)⁻¹ • n • g x = g x by simpa [birkhoffAverage, birkhoffSum_of_comp_eq h] rw [← Nat.cast_smul_eq_nsmul (R := R), ← mul_smul, inv_mul_cancel₀ (by norm_cast), one_smul] end AddCommGroup
.lake/packages/mathlib/Mathlib/Dynamics/BirkhoffSum/Basic.lean
import Mathlib.Dynamics.FixedPoints.Basic import Mathlib.Algebra.BigOperators.Group.Finset.Basic /-! # Birkhoff sums In this file we define `birkhoffSum f g n x` to be the sum `∑ k ∈ Finset.range n, g (f^[k] x)`. This sum (more precisely, the corresponding average `n⁻¹ • birkhoffSum f g n x`) appears in various ergodic theorems saying that these averages converge to the "space average" `⨍ x, g x ∂μ` in some sense. See also `birkhoffAverage` defined in `Dynamics/BirkhoffSum/Average`. -/ open Finset Function section AddCommMonoid variable {α M : Type*} [AddCommMonoid M] /-- The sum of values of `g` on the first `n` points of the orbit of `x` under `f`. -/ def birkhoffSum (f : α → α) (g : α → M) (n : ℕ) (x : α) : M := ∑ k ∈ range n, g (f^[k] x) theorem birkhoffSum_zero (f : α → α) (g : α → M) (x : α) : birkhoffSum f g 0 x = 0 := sum_range_zero _ @[simp] theorem birkhoffSum_zero' (f : α → α) (g : α → M) : birkhoffSum f g 0 = 0 := funext <| birkhoffSum_zero _ _ theorem birkhoffSum_one (f : α → α) (g : α → M) (x : α) : birkhoffSum f g 1 x = g x := sum_range_one _ @[simp] theorem birkhoffSum_one' (f : α → α) (g : α → M) : birkhoffSum f g 1 = g := funext <| birkhoffSum_one f g theorem birkhoffSum_succ (f : α → α) (g : α → M) (n : ℕ) (x : α) : birkhoffSum f g (n + 1) x = birkhoffSum f g n x + g (f^[n] x) := sum_range_succ _ _ theorem birkhoffSum_succ' (f : α → α) (g : α → M) (n : ℕ) (x : α) : birkhoffSum f g (n + 1) x = g x + birkhoffSum f g n (f x) := (sum_range_succ' _ _).trans (add_comm _ _) theorem birkhoffSum_add (f : α → α) (g : α → M) (m n : ℕ) (x : α) : birkhoffSum f g (m + n) x = birkhoffSum f g m x + birkhoffSum f g n (f^[m] x) := by simp_rw [birkhoffSum, sum_range_add, add_comm m, iterate_add_apply] theorem birkhoffSum_add' (f : α → α) (g g' : α → M) (n : ℕ) (x : α) : birkhoffSum f (g + g') n x = birkhoffSum f g n x + birkhoffSum f g' n x := by simpa [birkhoffSum] using sum_add_distrib theorem Function.IsFixedPt.birkhoffSum_eq {f : α → α} {x : α} (h : IsFixedPt f x) (g : α → M) (n : ℕ) : birkhoffSum f g n x = n • g x := by simp [birkhoffSum, (h.iterate _).eq] theorem map_birkhoffSum {F N : Type*} [AddCommMonoid N] [FunLike F M N] [AddMonoidHomClass F M N] (g' : F) (f : α → α) (g : α → M) (n : ℕ) (x : α) : g' (birkhoffSum f g n x) = birkhoffSum f (g' ∘ g) n x := map_sum g' _ _ /-- If a function `φ` is invariant under a function `f` (i.e., `φ ∘ f = φ`), then the Birkhoff sum of `φ` over `f` for `n` iterations is equal to `n • φ`. -/ theorem birkhoffSum_of_comp_eq {f : α → α} {φ : α → M} (h : φ ∘ f = φ) (n : ℕ) : birkhoffSum f φ n = n • φ := by funext x suffices ∀ k, φ (f^[k] x) = φ x by simp [birkhoffSum, this] intro k exact congrFun (iterate_invariant h k) x end AddCommMonoid section AddCommGroup variable {α G : Type*} [AddCommGroup G] theorem birkhoffSum_neg (f : α → α) (g : α → G) (n : ℕ) (x : α) : birkhoffSum f (-g) n x = -birkhoffSum f g n x := by simp [birkhoffSum] theorem birkhoffSum_sub (f : α → α) (g g' : α → G) (n : ℕ) (x : α) : birkhoffSum f (g - g') n x = birkhoffSum f g n x - birkhoffSum f g' n x := by simp [birkhoffSum] /-- Birkhoff sum is "almost invariant" under `f`: the difference between `birkhoffSum f g n (f x)` and `birkhoffSum f g n x` is equal to `g (f^[n] x) - g x`. -/ theorem birkhoffSum_apply_sub_birkhoffSum (f : α → α) (g : α → G) (n : ℕ) (x : α) : birkhoffSum f g n (f x) - birkhoffSum f g n x = g (f^[n] x) - g x := by rw [← sub_eq_iff_eq_add.2 (birkhoffSum_succ f g n x), ← sub_eq_iff_eq_add.2 (birkhoffSum_succ' f g n x), ← sub_add, ← sub_add, sub_add_comm] end AddCommGroup
.lake/packages/mathlib/Mathlib/Dynamics/BirkhoffSum/QuasiMeasurePreserving.lean
import Mathlib.Dynamics.BirkhoffSum.Average import Mathlib.MeasureTheory.Measure.QuasiMeasurePreserving /-! # Birkhoff sum and average for quasi-measure-preserving maps Given a map `f` and measure `μ`, under the assumption of `QuasiMeasurePreserving f μ μ` we prove: - `birkhoffSum_ae_eq_of_ae_eq`: if observables `φ` and `ψ` are `μ`-a.e. equal then the corresponding `birkhoffSum f` are `μ`-a.e. equal. - `birkhoffAverage_ae_eq_of_ae_eq`: if observables `φ` and `ψ` are `μ`-a.e. equal then the corresponding `birkhoffAverage R f` are `μ`-a.e. equal. -/ namespace MeasureTheory.Measure.QuasiMeasurePreserving open Filter variable {α M : Type*} [MeasurableSpace α] [AddCommMonoid M] variable {f : α → α} {μ : Measure α} {φ ψ : α → M} /-- If observables `φ` and `ψ` are `μ`-a.e. equal then the corresponding `birkhoffSum` are `μ`-a.e. equal. -/ theorem birkhoffSum_ae_eq_of_ae_eq (hf : QuasiMeasurePreserving f μ μ) (hφ : φ =ᵐ[μ] ψ) n : birkhoffSum f φ n =ᵐ[μ] birkhoffSum f ψ n := by apply Eventually.mono _ (fun _ => Finset.sum_congr rfl) apply ae_all_iff.mpr (fun i => ?_) exact (hf.iterate i).ae (hφ.mono (fun _ h _ => h)) /-- If observables `φ` and `ψ` are `μ`-a.e. equal then the corresponding `birkhoffAverage` are `μ`-a.e. equal. -/ theorem birkhoffAverage_ae_eq_of_ae_eq (R : Type*) [DivisionSemiring R] [Module R M] (hf : QuasiMeasurePreserving f μ μ) (hφ : φ =ᵐ[μ] ψ) n : birkhoffAverage R f φ n =ᵐ[μ] birkhoffAverage R f ψ n := EventuallyEq.const_smul (birkhoffSum_ae_eq_of_ae_eq hf hφ n) (n : R)⁻¹ end MeasureTheory.Measure.QuasiMeasurePreserving
.lake/packages/mathlib/Mathlib/Dynamics/BirkhoffSum/NormedSpace.lean
import Mathlib.Analysis.RCLike.Basic import Mathlib.Dynamics.BirkhoffSum.Average /-! # Birkhoff average in a normed space In this file we prove some lemmas about the Birkhoff average (`birkhoffAverage`) of a function which takes values in a normed space over `ℝ` or `ℂ`. At the time of writing, all lemmas in this file are motivated by the proof of the von Neumann Mean Ergodic Theorem, see `LinearIsometry.tendsto_birkhoffAverage_orthogonalProjection`. -/ open Function Set Filter open scoped Topology ENNReal Uniformity section variable {α E : Type*} /-- The Birkhoff averages of a function `g` over the orbit of a fixed point `x` of `f` tend to `g x` as `N → ∞`. In fact, they are equal to `g x` for all `N ≠ 0`, see `Function.IsFixedPt.birkhoffAverage_eq`. TODO: add a version for a periodic orbit. -/ theorem Function.IsFixedPt.tendsto_birkhoffAverage (R : Type*) [DivisionSemiring R] [CharZero R] [AddCommMonoid E] [TopologicalSpace E] [Module R E] {f : α → α} {x : α} (h : f.IsFixedPt x) (g : α → E) : Tendsto (birkhoffAverage R f g · x) atTop (𝓝 (g x)) := tendsto_const_nhds.congr' <| (eventually_ne_atTop 0).mono fun _n hn ↦ (h.birkhoffAverage_eq R g hn).symm variable [NormedAddCommGroup E] theorem dist_birkhoffSum_apply_birkhoffSum (f : α → α) (g : α → E) (n : ℕ) (x : α) : dist (birkhoffSum f g n (f x)) (birkhoffSum f g n x) = dist (g (f^[n] x)) (g x) := by simp only [dist_eq_norm, birkhoffSum_apply_sub_birkhoffSum] theorem dist_birkhoffSum_birkhoffSum_le (f : α → α) (g : α → E) (n : ℕ) (x y : α) : dist (birkhoffSum f g n x) (birkhoffSum f g n y) ≤ ∑ k ∈ Finset.range n, dist (g (f^[k] x)) (g (f^[k] y)) := dist_sum_sum_le _ _ _ variable (𝕜 : Type*) [RCLike 𝕜] [NormedSpace 𝕜 E] theorem dist_birkhoffAverage_birkhoffAverage (f : α → α) (g : α → E) (n : ℕ) (x y : α) : dist (birkhoffAverage 𝕜 f g n x) (birkhoffAverage 𝕜 f g n y) = dist (birkhoffSum f g n x) (birkhoffSum f g n y) / n := by simp [birkhoffAverage, dist_smul₀, div_eq_inv_mul] theorem dist_birkhoffAverage_birkhoffAverage_le (f : α → α) (g : α → E) (n : ℕ) (x y : α) : dist (birkhoffAverage 𝕜 f g n x) (birkhoffAverage 𝕜 f g n y) ≤ (∑ k ∈ Finset.range n, dist (g (f^[k] x)) (g (f^[k] y))) / n := (dist_birkhoffAverage_birkhoffAverage _ _ _ _ _ _).trans_le <| by gcongr; apply dist_birkhoffSum_birkhoffSum_le theorem dist_birkhoffAverage_apply_birkhoffAverage (f : α → α) (g : α → E) (n : ℕ) (x : α) : dist (birkhoffAverage 𝕜 f g n (f x)) (birkhoffAverage 𝕜 f g n x) = dist (g (f^[n] x)) (g x) / n := by simp [dist_birkhoffAverage_birkhoffAverage, dist_birkhoffSum_apply_birkhoffSum] /-- If a function `g` is bounded along the positive orbit of `x` under `f`, then the difference between Birkhoff averages of `g` along the orbit of `f x` and along the orbit of `x` tends to zero. See also `tendsto_birkhoffAverage_apply_sub_birkhoffAverage'`. -/ theorem tendsto_birkhoffAverage_apply_sub_birkhoffAverage {f : α → α} {g : α → E} {x : α} (h : Bornology.IsBounded (range (g <| f^[·] x))) : Tendsto (fun n ↦ birkhoffAverage 𝕜 f g n (f x) - birkhoffAverage 𝕜 f g n x) atTop (𝓝 0) := by rcases Metric.isBounded_range_iff.1 h with ⟨C, hC⟩ have : Tendsto (fun n : ℕ ↦ C / n) atTop (𝓝 0) := tendsto_const_nhds.div_atTop tendsto_natCast_atTop_atTop refine squeeze_zero_norm (fun n ↦ ?_) this rw [← dist_eq_norm, dist_birkhoffAverage_apply_birkhoffAverage] gcongr exact hC n 0 /-- If a function `g` is bounded, then the difference between Birkhoff averages of `g` along the orbit of `f x` and along the orbit of `x` tends to zero. See also `tendsto_birkhoffAverage_apply_sub_birkhoffAverage`. -/ theorem tendsto_birkhoffAverage_apply_sub_birkhoffAverage' {g : α → E} (h : Bornology.IsBounded (range g)) (f : α → α) (x : α) : Tendsto (fun n ↦ birkhoffAverage 𝕜 f g n (f x) - birkhoffAverage 𝕜 f g n x) atTop (𝓝 0) := tendsto_birkhoffAverage_apply_sub_birkhoffAverage _ <| h.subset <| range_comp_subset_range _ _ end variable (𝕜 : Type*) {X E : Type*} [PseudoEMetricSpace X] [RCLike 𝕜] [NormedAddCommGroup E] [NormedSpace 𝕜 E] {f : X → X} {g : X → E} {l : X → E} /-- If `f` is a non-strictly contracting map (i.e., it is Lipschitz with constant `1`) and `g` is a uniformly continuous, then the Birkhoff averages of `g` along orbits of `f` is a uniformly equicontinuous family of functions. -/ theorem uniformEquicontinuous_birkhoffAverage (hf : LipschitzWith 1 f) (hg : UniformContinuous g) : UniformEquicontinuous (birkhoffAverage 𝕜 f g) := by refine Metric.uniformity_basis_dist_le.uniformEquicontinuous_iff_right.2 fun ε hε ↦ ?_ rcases (uniformity_basis_edist_le.uniformContinuous_iff Metric.uniformity_basis_dist_le).1 hg ε hε with ⟨δ, hδ₀, hδε⟩ refine mem_uniformity_edist.2 ⟨δ, hδ₀, fun {x y} h n ↦ ?_⟩ calc dist (birkhoffAverage 𝕜 f g n x) (birkhoffAverage 𝕜 f g n y) ≤ (∑ k ∈ Finset.range n, dist (g (f^[k] x)) (g (f^[k] y))) / n := dist_birkhoffAverage_birkhoffAverage_le .. _ ≤ (∑ _k ∈ Finset.range n, ε) / n := by gcongr refine hδε _ _ ?_ simpa using (hf.iterate _).edist_le_mul_of_le h.le _ = n * ε / n := by simp _ ≤ ε := by rcases eq_or_ne n 0 with hn | hn <;> simp [hn, hε.le, mul_div_cancel_left₀] /-- If `f : X → X` is a non-strictly contracting map (i.e., it is Lipschitz with constant `1`), `g : X → E` is a uniformly continuous, and `l : X → E` is a continuous function, then the set of points `x` such that the Birkhoff average of `g` along the orbit of `x` tends to `l x` is a closed set. -/ theorem isClosed_setOf_tendsto_birkhoffAverage (hf : LipschitzWith 1 f) (hg : UniformContinuous g) (hl : Continuous l) : IsClosed {x | Tendsto (birkhoffAverage 𝕜 f g · x) atTop (𝓝 (l x))} := (uniformEquicontinuous_birkhoffAverage 𝕜 hf hg).equicontinuous.isClosed_setOf_tendsto hl
.lake/packages/mathlib/Mathlib/Dynamics/FixedPoints/Prufer.lean
import Mathlib.Algebra.Group.Action.Pointwise.Set.Basic import Mathlib.Dynamics.FixedPoints.Basic /-! # Results about pointwise operations on sets with iteration. -/ open Pointwise open Set Function /-- Let `n : ℤ` and `s` a subset of a commutative group `G` that is invariant under preimage for the map `x ↦ x^n`. Then `s` is invariant under the pointwise action of the subgroup of elements `g : G` such that `g^(n^j) = 1` for some `j : ℕ`. (This subgroup is called the Prüfer subgroup when `G` is the `Circle` and `n` is prime.) -/ @[to_additive /-- Let `n : ℤ` and `s` a subset of an additive commutative group `G` that is invariant under preimage for the map `x ↦ n • x`. Then `s` is invariant under the pointwise action of the additive subgroup of elements `g : G` such that `(n^j) • g = 0` for some `j : ℕ`. (This additive subgroup is called the Prüfer subgroup when `G` is the `AddCircle` and `n` is prime.) -/] theorem smul_eq_self_of_preimage_zpow_eq_self {G : Type*} [CommGroup G] {n : ℤ} {s : Set G} (hs : (fun x => x ^ n) ⁻¹' s = s) {g : G} {j : ℕ} (hg : g ^ n ^ j = 1) : g • s = s := by suffices ∀ {g' : G} (_ : g' ^ n ^ j = 1), g' • s ⊆ s by refine le_antisymm (this hg) ?_ conv_lhs => rw [← smul_inv_smul g s] replace hg : g⁻¹ ^ n ^ j = 1 := by rw [inv_zpow, hg, inv_one] simpa only [le_eq_subset, smul_set_subset_smul_set_iff] using this hg rw [(IsFixedPt.preimage_iterate hs j : (zpowGroupHom n)^[j] ⁻¹' s = s).symm] rintro g' hg' - ⟨y, hy, rfl⟩ change (zpowGroupHom n)^[j] (g' * y) ∈ s replace hg' : (zpowGroupHom n)^[j] g' = 1 := by simpa [zpowGroupHom] rwa [iterate_map_mul, hg', one_mul]
.lake/packages/mathlib/Mathlib/Dynamics/FixedPoints/Topology.lean
import Mathlib.Dynamics.FixedPoints.Basic import Mathlib.Topology.Separation.Hausdorff /-! # Topological properties of fixed points Currently this file contains two lemmas: - `isFixedPt_of_tendsto_iterate`: if `f^n(x) → y` and `f` is continuous at `y`, then `f y = y`; - `isClosed_fixedPoints`: the set of fixed points of a continuous map is a closed set. ## TODO fixed points, iterates -/ variable {α : Type*} [TopologicalSpace α] [T2Space α] {f : α → α} open Function Filter open Topology /-- If the iterates `f^[n] x` converge to `y` and `f` is continuous at `y`, then `y` is a fixed point for `f`. -/ theorem isFixedPt_of_tendsto_iterate {x y : α} (hy : Tendsto (fun n => f^[n] x) atTop (𝓝 y)) (hf : ContinuousAt f y) : IsFixedPt f y := by refine tendsto_nhds_unique ((tendsto_add_atTop_iff_nat 1).1 ?_) hy simp only [iterate_succ' f] exact hf.tendsto.comp hy /-- The set of fixed points of a continuous map is a closed set. -/ theorem isClosed_fixedPoints (hf : Continuous f) : IsClosed (fixedPoints f) := isClosed_eq hf continuous_id
.lake/packages/mathlib/Mathlib/Dynamics/FixedPoints/Basic.lean
import Mathlib.Algebra.Group.End import Mathlib.Data.Set.Function /-! # Fixed points of a self-map In this file we define * the predicate `IsFixedPt f x := f x = x`; * the set `fixedPoints f` of fixed points of a self-map `f`. We also prove some simple lemmas about `IsFixedPt` and `∘`, `iterate`, and `Semiconj`. ## Tags fixed point -/ open Equiv universe u v variable {α : Type u} {β : Type v} {f fa g : α → α} {x : α} {fb : β → β} {e : Perm α} namespace Function open Function (Commute) /-- Every point is a fixed point of `id`. -/ theorem isFixedPt_id (x : α) : IsFixedPt id x := (rfl :) /-- A function fixes every point iff it is the identity. -/ @[simp] theorem forall_isFixedPt_iff : (∀ x, IsFixedPt f x) ↔ f = id := ⟨funext, fun h ↦ h ▸ isFixedPt_id⟩ namespace IsFixedPt instance decidable [h : DecidableEq α] {f : α → α} {x : α} : Decidable (IsFixedPt f x) := h (f x) x /-- If `x` is a fixed point of `f`, then `f x = x`. This is useful, e.g., for `rw` or `simp`. -/ protected theorem eq (hf : IsFixedPt f x) : f x = x := hf /-- If `x` is a fixed point of `f` and `g`, then it is a fixed point of `f ∘ g`. -/ protected theorem comp (hf : IsFixedPt f x) (hg : IsFixedPt g x) : IsFixedPt (f ∘ g) x := calc f (g x) = f x := congr_arg f hg _ = x := hf /-- If `x` is a fixed point of `f`, then it is a fixed point of `f^[n]`. -/ protected theorem iterate (hf : IsFixedPt f x) (n : ℕ) : IsFixedPt f^[n] x := iterate_fixed hf n /-- If `x` is a fixed point of `f ∘ g` and `g`, then it is a fixed point of `f`. -/ theorem left_of_comp (hfg : IsFixedPt (f ∘ g) x) (hg : IsFixedPt g x) : IsFixedPt f x := calc f x = f (g x) := congr_arg f hg.symm _ = x := hfg /-- If `x` is a fixed point of `f` and `g` is a left inverse of `f`, then `x` is a fixed point of `g`. -/ theorem to_leftInverse (hf : IsFixedPt f x) (h : LeftInverse g f) : IsFixedPt g x := calc g x = g (f x) := congr_arg g hf.symm _ = x := h x /-- If `g` (semi)conjugates `fa` to `fb`, then it sends fixed points of `fa` to fixed points of `fb`. -/ protected theorem map {x : α} (hx : IsFixedPt fa x) {g : α → β} (h : Semiconj g fa fb) : IsFixedPt fb (g x) := calc fb (g x) = g (fa x) := (h.eq x).symm _ = g x := congr_arg g hx protected theorem apply {x : α} (hx : IsFixedPt f x) : IsFixedPt f (f x) := by convert hx theorem preimage_iterate {s : Set α} (h : IsFixedPt (Set.preimage f) s) (n : ℕ) : IsFixedPt (Set.preimage f^[n]) s := by rw [Set.preimage_iterate_eq] exact h.iterate n lemma image_iterate {s : Set α} (h : IsFixedPt (Set.image f) s) (n : ℕ) : IsFixedPt (Set.image f^[n]) s := Set.image_iterate_eq ▸ h.iterate n protected theorem equiv_symm (h : IsFixedPt e x) : IsFixedPt e.symm x := h.to_leftInverse e.leftInverse_symm protected theorem perm_inv (h : IsFixedPt e x) : IsFixedPt (⇑e⁻¹) x := h.equiv_symm protected theorem perm_pow (h : IsFixedPt e x) (n : ℕ) : IsFixedPt (⇑(e ^ n)) x := h.iterate _ protected theorem perm_zpow (h : IsFixedPt e x) : ∀ n : ℤ, IsFixedPt (⇑(e ^ n)) x | Int.ofNat _ => h.perm_pow _ | Int.negSucc n => (h.perm_pow <| n + 1).perm_inv end IsFixedPt @[simp] theorem Injective.isFixedPt_apply_iff (hf : Injective f) {x : α} : IsFixedPt f (f x) ↔ IsFixedPt f x := ⟨fun h => hf h.eq, IsFixedPt.apply⟩ /-- The set of fixed points of a map `f : α → α`. -/ def fixedPoints (f : α → α) : Set α := { x : α | IsFixedPt f x } instance fixedPoints.decidable [DecidableEq α] (f : α → α) (x : α) : Decidable (x ∈ fixedPoints f) := IsFixedPt.decidable @[simp] theorem mem_fixedPoints : x ∈ fixedPoints f ↔ IsFixedPt f x := Iff.rfl theorem mem_fixedPoints_iff {α : Type*} {f : α → α} {x : α} : x ∈ fixedPoints f ↔ f x = x := by rfl @[simp] theorem fixedPoints_id : fixedPoints (@id α) = Set.univ := Set.ext fun _ => by simpa using isFixedPt_id _ theorem fixedPoints_subset_range : fixedPoints f ⊆ Set.range f := fun x hx => ⟨x, hx⟩ /-- If `g` semiconjugates `fa` to `fb`, then it sends fixed points of `fa` to fixed points of `fb`. -/ theorem Semiconj.mapsTo_fixedPoints {g : α → β} (h : Semiconj g fa fb) : Set.MapsTo g (fixedPoints fa) (fixedPoints fb) := fun _ hx => hx.map h /-- Any two maps `f : α → β` and `g : β → α` are inverse of each other on the sets of fixed points of `f ∘ g` and `g ∘ f`, respectively. -/ theorem invOn_fixedPoints_comp (f : α → β) (g : β → α) : Set.InvOn f g (fixedPoints <| f ∘ g) (fixedPoints <| g ∘ f) := ⟨fun _ => id, fun _ => id⟩ /-- Any map `f` sends fixed points of `g ∘ f` to fixed points of `f ∘ g`. -/ theorem mapsTo_fixedPoints_comp (f : α → β) (g : β → α) : Set.MapsTo f (fixedPoints <| g ∘ f) (fixedPoints <| f ∘ g) := fun _ hx => hx.map fun _ => rfl /-- Given two maps `f : α → β` and `g : β → α`, `g` is a bijective map between the fixed points of `f ∘ g` and the fixed points of `g ∘ f`. The inverse map is `f`, see `invOn_fixedPoints_comp`. -/ theorem bijOn_fixedPoints_comp (f : α → β) (g : β → α) : Set.BijOn g (fixedPoints <| f ∘ g) (fixedPoints <| g ∘ f) := (invOn_fixedPoints_comp f g).bijOn (mapsTo_fixedPoints_comp g f) (mapsTo_fixedPoints_comp f g) /-- If self-maps `f` and `g` commute, then they are inverse of each other on the set of fixed points of `f ∘ g`. This is a particular case of `Function.invOn_fixedPoints_comp`. -/ theorem Commute.invOn_fixedPoints_comp (h : Commute f g) : Set.InvOn f g (fixedPoints <| f ∘ g) (fixedPoints <| f ∘ g) := by simpa only [h.comp_eq] using Function.invOn_fixedPoints_comp f g /-- If self-maps `f` and `g` commute, then `f` is bijective on the set of fixed points of `f ∘ g`. This is a particular case of `Function.bijOn_fixedPoints_comp`. -/ theorem Commute.left_bijOn_fixedPoints_comp (h : Commute f g) : Set.BijOn f (fixedPoints <| f ∘ g) (fixedPoints <| f ∘ g) := by simpa only [h.comp_eq] using bijOn_fixedPoints_comp g f /-- If self-maps `f` and `g` commute, then `g` is bijective on the set of fixed points of `f ∘ g`. This is a particular case of `Function.bijOn_fixedPoints_comp`. -/ theorem Commute.right_bijOn_fixedPoints_comp (h : Commute f g) : Set.BijOn g (fixedPoints <| f ∘ g) (fixedPoints <| f ∘ g) := by simpa only [h.comp_eq] using bijOn_fixedPoints_comp f g end Function
.lake/packages/mathlib/Mathlib/Dynamics/Circle/RotationNumber/TranslationNumber.lean
import Mathlib.Analysis.SpecificLimits.Basic import Mathlib.Order.Iterate import Mathlib.Order.SemiconjSup import Mathlib.Topology.Order.MonotoneContinuity import Mathlib.Algebra.CharP.Defs /-! # Translation number of a monotone real map that commutes with `x ↦ x + 1` Let `f : ℝ → ℝ` be a monotone map such that `f (x + 1) = f x + 1` for all `x`. Then the limit $$ \tau(f)=\lim_{n\to\infty}{f^n(x)-x}{n} $$ exists and does not depend on `x`. This number is called the *translation number* of `f`. Different authors use different notation for this number: `τ`, `ρ`, `rot`, etc In this file we define a structure `CircleDeg1Lift` for bundled maps with these properties, define translation number of `f : CircleDeg1Lift`, prove some estimates relating `f^n(x)-x` to `τ(f)`. In case of a continuous map `f` we also prove that `f` admits a point `x` such that `f^n(x)=x+m` if and only if `τ(f)=m/n`. Maps of this type naturally appear as lifts of orientation-preserving circle homeomorphisms. More precisely, let `f` be an orientation-preserving homeomorphism of the circle $S^1=ℝ/ℤ$, and consider a real number `a` such that `⟦a⟧ = f 0`, where `⟦⟧` means the natural projection `ℝ → ℝ/ℤ`. Then there exists a unique continuous function `F : ℝ → ℝ` such that `F 0 = a` and `⟦F x⟧ = f ⟦x⟧` for all `x` (this fact is not formalized yet). This function is strictly monotone, continuous, and satisfies `F (x + 1) = F x + 1`. The number `⟦τ F⟧ : ℝ / ℤ` is called the *rotation number* of `f`. It does not depend on the choice of `a`. ## Main definitions * `CircleDeg1Lift`: a monotone map `f : ℝ → ℝ` such that `f (x + 1) = f x + 1` for all `x`; the type `CircleDeg1Lift` is equipped with `Lattice` and `Monoid` structures; the multiplication is given by composition: `(f * g) x = f (g x)`. * `CircleDeg1Lift.translationNumber`: translation number of `f : CircleDeg1Lift`. ## Main statements We prove the following properties of `CircleDeg1Lift.translationNumber`. * `CircleDeg1Lift.translationNumber_eq_of_dist_bounded`: if the distance between `(f^n) 0` and `(g^n) 0` is bounded from above uniformly in `n : ℕ`, then `f` and `g` have equal translation numbers. * `CircleDeg1Lift.translationNumber_eq_of_semiconjBy`: if two `CircleDeg1Lift` maps `f`, `g` are semiconjugate by a `CircleDeg1Lift` map, then `τ f = τ g`. * `CircleDeg1Lift.translationNumber_units_inv`: if `f` is an invertible `CircleDeg1Lift` map (equivalently, `f` is a lift of an orientation-preserving circle homeomorphism), then the translation number of `f⁻¹` is the negative of the translation number of `f`. * `CircleDeg1Lift.translationNumber_mul_of_commute`: if `f` and `g` commute, then `τ (f * g) = τ f + τ g`. * `CircleDeg1Lift.translationNumber_eq_rat_iff`: the translation number of `f` is equal to a rational number `m / n` if and only if `(f^n) x = x + m` for some `x`. * `CircleDeg1Lift.semiconj_of_bijective_of_translationNumber_eq`: if `f` and `g` are two bijective `CircleDeg1Lift` maps and their translation numbers are equal, then these maps are semiconjugate to each other. * `CircleDeg1Lift.semiconj_of_group_action_of_forall_translationNumber_eq`: let `f₁` and `f₂` be two actions of a group `G` on the circle by degree 1 maps (formally, `f₁` and `f₂` are two homomorphisms from `G →* CircleDeg1Lift`). If the translation numbers of `f₁ g` and `f₂ g` are equal to each other for all `g : G`, then these two actions are semiconjugate by some `F : CircleDeg1Lift`. This is a version of Proposition 5.4 from [Étienne Ghys, Groupes d'homeomorphismes du cercle et cohomologie bornee][ghys87:groupes]. ## Notation We use a local notation `τ` for the translation number of `f : CircleDeg1Lift`. ## Implementation notes We define the translation number of `f : CircleDeg1Lift` to be the limit of the sequence `(f ^ (2 ^ n)) 0 / (2 ^ n)`, then prove that `((f ^ n) x - x) / n` tends to this number for any `x`. This way it is much easier to prove that the limit exists and basic properties of the limit. We define translation number for a wider class of maps `f : ℝ → ℝ` instead of lifts of orientation preserving circle homeomorphisms for two reasons: * non-strictly monotone circle self-maps with discontinuities naturally appear as Poincaré maps for some flows on the two-torus (e.g., one can take a constant flow and glue in a few Cherry cells); * definition and some basic properties still work for this class. ## References * [Étienne Ghys, Groupes d'homeomorphismes du cercle et cohomologie bornee][ghys87:groupes] ## TODO Here are some short-term goals. * Introduce a structure or a typeclass for lifts of circle homeomorphisms. We use `Units CircleDeg1Lift` for now, but it's better to have a dedicated type (or a typeclass?). * Prove that the `SemiconjBy` relation on circle homeomorphisms is an equivalence relation. * Introduce `ConditionallyCompleteLattice` structure, use it in the proof of `CircleDeg1Lift.semiconj_of_group_action_of_forall_translationNumber_eq`. * Prove that the orbits of the irrational rotation are dense in the circle. Deduce that a homeomorphism with an irrational rotation is semiconjugate to the corresponding irrational translation by a continuous `CircleDeg1Lift`. ## Tags circle homeomorphism, rotation number -/ open Filter Set Int Topology open Function hiding Commute /-! ### Definition and monoid structure -/ /-- A lift of a monotone degree one map `S¹ → S¹`. -/ structure CircleDeg1Lift : Type extends ℝ →o ℝ where map_add_one' : ∀ x, toFun (x + 1) = toFun x + 1 namespace CircleDeg1Lift instance : FunLike CircleDeg1Lift ℝ ℝ where coe f := f.toFun coe_injective' | ⟨⟨_, _⟩, _⟩, ⟨⟨_, _⟩, _⟩, rfl => rfl instance : OrderHomClass CircleDeg1Lift ℝ ℝ where map_rel f _ _ h := f.monotone' h @[simp] theorem coe_mk (f h) : ⇑(mk f h) = f := rfl variable (f g : CircleDeg1Lift) @[simp] theorem coe_toOrderHom : ⇑f.toOrderHom = f := rfl protected theorem monotone : Monotone f := f.monotone' @[mono] theorem mono {x y} (h : x ≤ y) : f x ≤ f y := f.monotone h theorem strictMono_iff_injective : StrictMono f ↔ Injective f := f.monotone.strictMono_iff_injective @[simp] theorem map_add_one : ∀ x, f (x + 1) = f x + 1 := f.map_add_one' @[simp] theorem map_one_add (x : ℝ) : f (1 + x) = 1 + f x := by rw [add_comm, map_add_one, add_comm 1] @[ext] theorem ext ⦃f g : CircleDeg1Lift⦄ (h : ∀ x, f x = g x) : f = g := DFunLike.ext f g h instance : Monoid CircleDeg1Lift where mul f g := { toOrderHom := f.1.comp g.1 map_add_one' := fun x => by simp [map_add_one] } one := ⟨.id, fun _ => rfl⟩ mul_one _ := rfl one_mul _ := rfl mul_assoc _ _ _ := DFunLike.coe_injective rfl instance : Inhabited CircleDeg1Lift := ⟨1⟩ @[simp] theorem coe_mul : ⇑(f * g) = f ∘ g := rfl theorem mul_apply (x) : (f * g) x = f (g x) := rfl @[simp] theorem coe_one : ⇑(1 : CircleDeg1Lift) = id := rfl instance unitsHasCoeToFun : CoeFun CircleDeg1Liftˣ fun _ => ℝ → ℝ := ⟨fun f => ⇑(f : CircleDeg1Lift)⟩ @[simp] theorem units_inv_apply_apply (f : CircleDeg1Liftˣ) (x : ℝ) : (f⁻¹ : CircleDeg1Liftˣ) (f x) = x := by simp only [← mul_apply, f.inv_mul, coe_one, id] @[simp] theorem units_apply_inv_apply (f : CircleDeg1Liftˣ) (x : ℝ) : f ((f⁻¹ : CircleDeg1Liftˣ) x) = x := by simp only [← mul_apply, f.mul_inv, coe_one, id] /-- If a lift of a circle map is bijective, then it is an order automorphism of the line. -/ def toOrderIso : CircleDeg1Liftˣ →* ℝ ≃o ℝ where toFun f := { toFun := f invFun := ⇑f⁻¹ left_inv := units_inv_apply_apply f right_inv := units_apply_inv_apply f map_rel_iff' := ⟨fun h => by simpa using mono (↑f⁻¹) h, mono f⟩ } map_one' := rfl map_mul' _ _ := rfl @[simp] theorem coe_toOrderIso (f : CircleDeg1Liftˣ) : ⇑(toOrderIso f) = f := rfl @[simp] theorem coe_toOrderIso_symm (f : CircleDeg1Liftˣ) : ⇑(toOrderIso f).symm = (f⁻¹ : CircleDeg1Liftˣ) := rfl @[simp] theorem coe_toOrderIso_inv (f : CircleDeg1Liftˣ) : ⇑(toOrderIso f)⁻¹ = (f⁻¹ : CircleDeg1Liftˣ) := rfl theorem isUnit_iff_bijective {f : CircleDeg1Lift} : IsUnit f ↔ Bijective f := ⟨fun ⟨u, h⟩ => h ▸ (toOrderIso u).bijective, fun h => Units.isUnit { val := f inv := { toFun := (Equiv.ofBijective f h).symm monotone' := fun x y hxy => (f.strictMono_iff_injective.2 h.1).le_iff_le.1 (by simp only [Equiv.ofBijective_apply_symm_apply f h, hxy]) map_add_one' := fun x => h.1 <| by simp only [Equiv.ofBijective_apply_symm_apply f, f.map_add_one] } val_inv := ext <| Equiv.ofBijective_apply_symm_apply f h inv_val := ext <| Equiv.ofBijective_symm_apply_apply f h }⟩ theorem coe_pow : ∀ n : ℕ, ⇑(f ^ n) = f^[n] | 0 => rfl | n + 1 => by simp [coe_pow n, pow_succ] theorem semiconjBy_iff_semiconj {f g₁ g₂ : CircleDeg1Lift} : SemiconjBy f g₁ g₂ ↔ Semiconj f g₁ g₂ := CircleDeg1Lift.ext_iff theorem commute_iff_commute {f g : CircleDeg1Lift} : Commute f g ↔ Function.Commute f g := CircleDeg1Lift.ext_iff /-! ### Translate by a constant -/ /-- The map `y ↦ x + y` as a `CircleDeg1Lift`. More precisely, we define a homomorphism from `Multiplicative ℝ` to `CircleDeg1Liftˣ`, so the translation by `x` is `translation (Multiplicative.ofAdd x)`. -/ def translate : Multiplicative ℝ →* CircleDeg1Liftˣ := MonoidHom.toHomUnits <| { toFun x := ⟨⟨fun y => x.toAdd + y, add_right_mono⟩, fun _ => (add_assoc ..).symm⟩ map_one' := ext zero_add map_mul' _ _ := ext <| add_assoc _ _ } @[simp] theorem translate_apply (x y : ℝ) : translate (Multiplicative.ofAdd x) y = x + y := rfl @[simp] theorem translate_inv_apply (x y : ℝ) : (translate <| Multiplicative.ofAdd x)⁻¹ y = -x + y := rfl @[simp] theorem translate_zpow (x : ℝ) (n : ℤ) : translate (Multiplicative.ofAdd x) ^ n = translate (Multiplicative.ofAdd <| ↑n * x) := by simp only [← zsmul_eq_mul, ofAdd_zsmul, MonoidHom.map_zpow] @[simp] theorem translate_pow (x : ℝ) (n : ℕ) : translate (Multiplicative.ofAdd x) ^ n = translate (Multiplicative.ofAdd <| ↑n * x) := translate_zpow x n @[simp] theorem translate_iterate (x : ℝ) (n : ℕ) : (translate (Multiplicative.ofAdd x))^[n] = translate (Multiplicative.ofAdd <| ↑n * x) := by rw [← coe_pow, ← Units.val_pow_eq_pow_val, translate_pow] /-! ### Commutativity with integer translations In this section we prove that `f` commutes with translations by an integer number. First we formulate these statements (for a natural or an integer number, addition on the left or on the right, addition or subtraction) using `Function.Commute`, then reformulate as `simp` lemmas `map_int_add` etc. -/ theorem commute_nat_add (n : ℕ) : Function.Commute f (n + ·) := by simpa only [nsmul_one, add_left_iterate] using Function.Commute.iterate_right f.map_one_add n theorem commute_add_nat (n : ℕ) : Function.Commute f (· + n) := by simp only [add_comm _ (n : ℝ), f.commute_nat_add n] theorem commute_sub_nat (n : ℕ) : Function.Commute f (· - n) := by simpa only [sub_eq_add_neg] using (f.commute_add_nat n).inverses_right (Equiv.addRight _).right_inv (Equiv.addRight _).left_inv theorem commute_add_int : ∀ n : ℤ, Function.Commute f (· + n) | (n : ℕ) => f.commute_add_nat n | -[n+1] => by simpa [sub_eq_add_neg] using f.commute_sub_nat (n + 1) theorem commute_int_add (n : ℤ) : Function.Commute f (n + ·) := by simpa only [add_comm _ (n : ℝ)] using f.commute_add_int n theorem commute_sub_int (n : ℤ) : Function.Commute f (· - n) := by simpa only [sub_eq_add_neg] using (f.commute_add_int n).inverses_right (Equiv.addRight _).right_inv (Equiv.addRight _).left_inv @[simp] theorem map_int_add (m : ℤ) (x : ℝ) : f (m + x) = m + f x := f.commute_int_add m x @[simp] theorem map_add_int (x : ℝ) (m : ℤ) : f (x + m) = f x + m := f.commute_add_int m x @[simp] theorem map_sub_int (x : ℝ) (n : ℤ) : f (x - n) = f x - n := f.commute_sub_int n x @[simp] theorem map_add_nat (x : ℝ) (n : ℕ) : f (x + n) = f x + n := f.map_add_int x n @[simp] theorem map_nat_add (n : ℕ) (x : ℝ) : f (n + x) = n + f x := f.map_int_add n x @[simp] theorem map_sub_nat (x : ℝ) (n : ℕ) : f (x - n) = f x - n := f.map_sub_int x n theorem map_int_of_map_zero (n : ℤ) : f n = f 0 + n := by rw [← f.map_add_int, zero_add] @[simp] theorem map_fract_sub_fract_eq (x : ℝ) : f (fract x) - fract x = f x - x := by rw [Int.fract, f.map_sub_int, sub_sub_sub_cancel_right] /-! ### Pointwise order on circle maps -/ /-- Monotone circle maps form a lattice with respect to the pointwise order -/ noncomputable instance : Lattice CircleDeg1Lift where sup f g := { toFun := fun x => max (f x) (g x) monotone' := fun _ _ h => max_le_max (f.mono h) (g.mono h) -- TODO: generalize to `Monotone.max` map_add_one' := fun x => by simp [max_add_add_right] } le f g := ∀ x, f x ≤ g x le_refl f x := le_refl (f x) le_trans _ _ _ h₁₂ h₂₃ x := le_trans (h₁₂ x) (h₂₃ x) le_antisymm _ _ h₁₂ h₂₁ := ext fun x => le_antisymm (h₁₂ x) (h₂₁ x) le_sup_left f g x := le_max_left (f x) (g x) le_sup_right f g x := le_max_right (f x) (g x) sup_le _ _ _ h₁ h₂ x := max_le (h₁ x) (h₂ x) inf f g := { toFun := fun x => min (f x) (g x) monotone' := fun _ _ h => min_le_min (f.mono h) (g.mono h) map_add_one' := fun x => by simp [min_add_add_right] } inf_le_left f g x := min_le_left (f x) (g x) inf_le_right f g x := min_le_right (f x) (g x) le_inf _ _ _ h₂ h₃ x := le_min (h₂ x) (h₃ x) @[simp] theorem sup_apply (x : ℝ) : (f ⊔ g) x = max (f x) (g x) := rfl @[simp] theorem inf_apply (x : ℝ) : (f ⊓ g) x = min (f x) (g x) := rfl theorem iterate_monotone (n : ℕ) : Monotone fun f : CircleDeg1Lift => f^[n] := fun f _ h => f.monotone.iterate_le_of_le h _ theorem iterate_mono {f g : CircleDeg1Lift} (h : f ≤ g) (n : ℕ) : f^[n] ≤ g^[n] := iterate_monotone n h theorem pow_mono {f g : CircleDeg1Lift} (h : f ≤ g) (n : ℕ) : f ^ n ≤ g ^ n := fun x => by simp only [coe_pow, iterate_mono h n x] theorem pow_monotone (n : ℕ) : Monotone fun f : CircleDeg1Lift => f ^ n := fun _ _ h => pow_mono h n /-! ### Estimates on `(f * g) 0` We prove the estimates `f 0 + ⌊g 0⌋ ≤ f (g 0) ≤ f 0 + ⌈g 0⌉` and some corollaries with added/removed floors and ceils. We also prove that for two semiconjugate maps `g₁`, `g₂`, the distance between `g₁ 0` and `g₂ 0` is less than two. -/ theorem map_le_of_map_zero (x : ℝ) : f x ≤ f 0 + ⌈x⌉ := calc f x ≤ f ⌈x⌉ := f.monotone <| le_ceil _ _ = f 0 + ⌈x⌉ := f.map_int_of_map_zero _ theorem map_map_zero_le : f (g 0) ≤ f 0 + ⌈g 0⌉ := f.map_le_of_map_zero (g 0) theorem floor_map_map_zero_le : ⌊f (g 0)⌋ ≤ ⌊f 0⌋ + ⌈g 0⌉ := calc ⌊f (g 0)⌋ ≤ ⌊f 0 + ⌈g 0⌉⌋ := floor_mono <| f.map_map_zero_le g _ = ⌊f 0⌋ + ⌈g 0⌉ := floor_add_intCast _ _ theorem ceil_map_map_zero_le : ⌈f (g 0)⌉ ≤ ⌈f 0⌉ + ⌈g 0⌉ := calc ⌈f (g 0)⌉ ≤ ⌈f 0 + ⌈g 0⌉⌉ := ceil_mono <| f.map_map_zero_le g _ = ⌈f 0⌉ + ⌈g 0⌉ := ceil_add_intCast _ _ theorem map_map_zero_lt : f (g 0) < f 0 + g 0 + 1 := calc f (g 0) ≤ f 0 + ⌈g 0⌉ := f.map_map_zero_le g _ < f 0 + (g 0 + 1) := by gcongr; exact ceil_lt_add_one _ _ = f 0 + g 0 + 1 := (add_assoc _ _ _).symm theorem le_map_of_map_zero (x : ℝ) : f 0 + ⌊x⌋ ≤ f x := calc f 0 + ⌊x⌋ = f ⌊x⌋ := (f.map_int_of_map_zero _).symm _ ≤ f x := f.monotone <| floor_le _ theorem le_map_map_zero : f 0 + ⌊g 0⌋ ≤ f (g 0) := f.le_map_of_map_zero (g 0) theorem le_floor_map_map_zero : ⌊f 0⌋ + ⌊g 0⌋ ≤ ⌊f (g 0)⌋ := calc ⌊f 0⌋ + ⌊g 0⌋ = ⌊f 0 + ⌊g 0⌋⌋ := (floor_add_intCast _ _).symm _ ≤ ⌊f (g 0)⌋ := floor_mono <| f.le_map_map_zero g theorem le_ceil_map_map_zero : ⌈f 0⌉ + ⌊g 0⌋ ≤ ⌈(f * g) 0⌉ := calc ⌈f 0⌉ + ⌊g 0⌋ = ⌈f 0 + ⌊g 0⌋⌉ := (ceil_add_intCast _ _).symm _ ≤ ⌈f (g 0)⌉ := ceil_mono <| f.le_map_map_zero g theorem lt_map_map_zero : f 0 + g 0 - 1 < f (g 0) := calc f 0 + g 0 - 1 = f 0 + (g 0 - 1) := add_sub_assoc _ _ _ _ < f 0 + ⌊g 0⌋ := by gcongr; exact sub_one_lt_floor _ _ ≤ f (g 0) := f.le_map_map_zero g theorem dist_map_map_zero_lt : dist (f 0 + g 0) (f (g 0)) < 1 := by rw [dist_comm, Real.dist_eq, abs_lt, lt_sub_iff_add_lt', sub_lt_iff_lt_add', ← sub_eq_add_neg] exact ⟨f.lt_map_map_zero g, f.map_map_zero_lt g⟩ theorem dist_map_zero_lt_of_semiconj {f g₁ g₂ : CircleDeg1Lift} (h : Function.Semiconj f g₁ g₂) : dist (g₁ 0) (g₂ 0) < 2 := calc dist (g₁ 0) (g₂ 0) ≤ dist (g₁ 0) (f (g₁ 0) - f 0) + dist _ (g₂ 0) := dist_triangle _ _ _ _ = dist (f 0 + g₁ 0) (f (g₁ 0)) + dist (g₂ 0 + f 0) (g₂ (f 0)) := by simp only [h.eq, Real.dist_eq, sub_sub, add_comm (f 0), sub_sub_eq_add_sub, abs_sub_comm (g₂ (f 0))] _ < 1 + 1 := add_lt_add (f.dist_map_map_zero_lt g₁) (g₂.dist_map_map_zero_lt f) _ = 2 := one_add_one_eq_two theorem dist_map_zero_lt_of_semiconjBy {f g₁ g₂ : CircleDeg1Lift} (h : SemiconjBy f g₁ g₂) : dist (g₁ 0) (g₂ 0) < 2 := dist_map_zero_lt_of_semiconj <| semiconjBy_iff_semiconj.1 h /-! ### Limits at infinities and continuity -/ protected theorem tendsto_atBot : Tendsto f atBot atBot := tendsto_atBot_mono f.map_le_of_map_zero <| tendsto_atBot_add_const_left _ _ <| (tendsto_atBot_mono fun x => (ceil_lt_add_one x).le) <| tendsto_atBot_add_const_right _ _ tendsto_id protected theorem tendsto_atTop : Tendsto f atTop atTop := tendsto_atTop_mono f.le_map_of_map_zero <| tendsto_atTop_add_const_left _ _ <| (tendsto_atTop_mono fun x => (sub_one_lt_floor x).le) <| by simpa [sub_eq_add_neg] using tendsto_atTop_add_const_right _ _ tendsto_id theorem continuous_iff_surjective : Continuous f ↔ Function.Surjective f := ⟨fun h => h.surjective f.tendsto_atTop f.tendsto_atBot, f.monotone.continuous_of_surjective⟩ /-! ### Estimates on `(f^n) x` If we know that `f x` is `≤`/`<`/`≥`/`>`/`=` to `x + m`, then we have a similar estimate on `f^[n] x` and `x + n * m`. For `≤`, `≥`, and `=` we formulate both `of` (implication) and `iff` versions because implications work for `n = 0`. For `<` and `>` we formulate only `iff` versions. -/ theorem iterate_le_of_map_le_add_int {x : ℝ} {m : ℤ} (h : f x ≤ x + m) (n : ℕ) : f^[n] x ≤ x + n * m := by simpa only [nsmul_eq_mul, add_right_iterate] using (f.commute_add_int m).iterate_le_of_map_le f.monotone (monotone_id.add_const (m : ℝ)) h n theorem le_iterate_of_add_int_le_map {x : ℝ} {m : ℤ} (h : x + m ≤ f x) (n : ℕ) : x + n * m ≤ f^[n] x := by simpa only [nsmul_eq_mul, add_right_iterate] using (f.commute_add_int m).symm.iterate_le_of_map_le (monotone_id.add_const (m : ℝ)) f.monotone h n theorem iterate_eq_of_map_eq_add_int {x : ℝ} {m : ℤ} (h : f x = x + m) (n : ℕ) : f^[n] x = x + n * m := by simpa only [nsmul_eq_mul, add_right_iterate] using (f.commute_add_int m).iterate_eq_of_map_eq n h theorem iterate_pos_le_iff {x : ℝ} {m : ℤ} {n : ℕ} (hn : 0 < n) : f^[n] x ≤ x + n * m ↔ f x ≤ x + m := by simpa only [nsmul_eq_mul, add_right_iterate] using (f.commute_add_int m).iterate_pos_le_iff_map_le f.monotone (strictMono_id.add_const (m : ℝ)) hn theorem iterate_pos_lt_iff {x : ℝ} {m : ℤ} {n : ℕ} (hn : 0 < n) : f^[n] x < x + n * m ↔ f x < x + m := by simpa only [nsmul_eq_mul, add_right_iterate] using (f.commute_add_int m).iterate_pos_lt_iff_map_lt f.monotone (strictMono_id.add_const (m : ℝ)) hn theorem iterate_pos_eq_iff {x : ℝ} {m : ℤ} {n : ℕ} (hn : 0 < n) : f^[n] x = x + n * m ↔ f x = x + m := by simpa only [nsmul_eq_mul, add_right_iterate] using (f.commute_add_int m).iterate_pos_eq_iff_map_eq f.monotone (strictMono_id.add_const (m : ℝ)) hn theorem le_iterate_pos_iff {x : ℝ} {m : ℤ} {n : ℕ} (hn : 0 < n) : x + n * m ≤ f^[n] x ↔ x + m ≤ f x := by simpa only [not_lt] using not_congr (f.iterate_pos_lt_iff hn) theorem lt_iterate_pos_iff {x : ℝ} {m : ℤ} {n : ℕ} (hn : 0 < n) : x + n * m < f^[n] x ↔ x + m < f x := by simpa only [not_le] using not_congr (f.iterate_pos_le_iff hn) theorem mul_floor_map_zero_le_floor_iterate_zero (n : ℕ) : ↑n * ⌊f 0⌋ ≤ ⌊f^[n] 0⌋ := by rw [le_floor, Int.cast_mul, Int.cast_natCast, ← zero_add ((n : ℝ) * _)] apply le_iterate_of_add_int_le_map simp [floor_le] /-! ### Definition of translation number -/ noncomputable section /-- An auxiliary sequence used to define the translation number. -/ def transnumAuxSeq (n : ℕ) : ℝ := (f ^ (2 ^ n : ℕ)) 0 / 2 ^ n /-- The translation number of a `CircleDeg1Lift`, $τ(f)=\lim_{n→∞}\frac{f^n(x)-x}{n}$. We use an auxiliary sequence `\frac{f^{2^n}(0)}{2^n}` to define `τ(f)` because some proofs are simpler this way. -/ def translationNumber : ℝ := limUnder atTop f.transnumAuxSeq end -- TODO: choose two different symbols for `CircleDeg1Lift.translationNumber` and the future -- `circle_mono_homeo.rotation_number`, then make them `localized notation`s local notation "τ" => translationNumber theorem transnumAuxSeq_def : f.transnumAuxSeq = fun n : ℕ => (f ^ (2 ^ n : ℕ)) 0 / 2 ^ n := rfl theorem translationNumber_eq_of_tendsto_aux {τ' : ℝ} (h : Tendsto f.transnumAuxSeq atTop (𝓝 τ')) : τ f = τ' := h.limUnder_eq theorem translationNumber_eq_of_tendsto₀ {τ' : ℝ} (h : Tendsto (fun n : ℕ => f^[n] 0 / n) atTop (𝓝 τ')) : τ f = τ' := f.translationNumber_eq_of_tendsto_aux <| by simpa [Function.comp_def, transnumAuxSeq_def, coe_pow] using h.comp (tendsto_pow_atTop_atTop_of_one_lt one_lt_two) theorem translationNumber_eq_of_tendsto₀' {τ' : ℝ} (h : Tendsto (fun n : ℕ => f^[n + 1] 0 / (n + 1)) atTop (𝓝 τ')) : τ f = τ' := f.translationNumber_eq_of_tendsto₀ <| (tendsto_add_atTop_iff_nat 1).1 (mod_cast h) theorem transnumAuxSeq_zero : f.transnumAuxSeq 0 = f 0 := by simp [transnumAuxSeq] theorem transnumAuxSeq_dist_lt (n : ℕ) : dist (f.transnumAuxSeq n) (f.transnumAuxSeq (n + 1)) < 1 / 2 / 2 ^ n := by have : 0 < (2 ^ (n + 1) : ℝ) := pow_pos zero_lt_two _ rw [div_div, ← pow_succ', ← abs_of_pos this] calc _ = dist ((f ^ 2 ^ n) 0 + (f ^ 2 ^ n) 0) ((f ^ 2 ^ n) ((f ^ 2 ^ n) 0)) / |2 ^ (n + 1)| := by simp_rw [transnumAuxSeq, Real.dist_eq] rw [← abs_div, sub_div, pow_succ, pow_succ', ← two_mul, mul_div_mul_left _ _ (two_ne_zero' ℝ), pow_mul, sq, mul_apply] _ < _ := by gcongr; exact (f ^ 2 ^ n).dist_map_map_zero_lt (f ^ 2 ^ n) theorem tendsto_translationNumber_aux : Tendsto f.transnumAuxSeq atTop (𝓝 <| τ f) := (cauchySeq_of_le_geometric_two fun n => le_of_lt <| f.transnumAuxSeq_dist_lt n).tendsto_limUnder theorem dist_map_zero_translationNumber_le : dist (f 0) (τ f) ≤ 1 := f.transnumAuxSeq_zero ▸ dist_le_of_le_geometric_two_of_tendsto₀ (fun n => le_of_lt <| f.transnumAuxSeq_dist_lt n) f.tendsto_translationNumber_aux theorem tendsto_translationNumber_of_dist_bounded_aux (x : ℕ → ℝ) (C : ℝ) (H : ∀ n : ℕ, dist ((f ^ n) 0) (x n) ≤ C) : Tendsto (fun n : ℕ => x (2 ^ n) / 2 ^ n) atTop (𝓝 <| τ f) := by apply f.tendsto_translationNumber_aux.congr_dist (squeeze_zero (fun _ => dist_nonneg) _ _) · exact fun n => C / 2 ^ n · intro n have : 0 < (2 ^ n : ℝ) := pow_pos zero_lt_two _ convert (div_le_div_iff_of_pos_right this).2 (H (2 ^ n)) using 1 rw [transnumAuxSeq, Real.dist_eq, ← sub_div, abs_div, abs_of_pos this, Real.dist_eq] · exact mul_zero C ▸ tendsto_const_nhds.mul <| tendsto_inv_atTop_zero.comp <| tendsto_pow_atTop_atTop_of_one_lt one_lt_two theorem translationNumber_eq_of_dist_bounded {f g : CircleDeg1Lift} (C : ℝ) (H : ∀ n : ℕ, dist ((f ^ n) 0) ((g ^ n) 0) ≤ C) : τ f = τ g := Eq.symm <| g.translationNumber_eq_of_tendsto_aux <| f.tendsto_translationNumber_of_dist_bounded_aux (fun n ↦ (g ^ n) 0) C H @[simp] theorem translationNumber_one : τ 1 = 0 := translationNumber_eq_of_tendsto₀ _ <| by simp theorem translationNumber_eq_of_semiconjBy {f g₁ g₂ : CircleDeg1Lift} (H : SemiconjBy f g₁ g₂) : τ g₁ = τ g₂ := translationNumber_eq_of_dist_bounded 2 fun n => le_of_lt <| dist_map_zero_lt_of_semiconjBy <| H.pow_right n theorem translationNumber_eq_of_semiconj {f g₁ g₂ : CircleDeg1Lift} (H : Function.Semiconj f g₁ g₂) : τ g₁ = τ g₂ := translationNumber_eq_of_semiconjBy <| semiconjBy_iff_semiconj.2 H theorem translationNumber_mul_of_commute {f g : CircleDeg1Lift} (h : Commute f g) : τ (f * g) = τ f + τ g := by refine tendsto_nhds_unique ?_ (f.tendsto_translationNumber_aux.add g.tendsto_translationNumber_aux) simp only [transnumAuxSeq, ← add_div] refine (f * g).tendsto_translationNumber_of_dist_bounded_aux (fun n ↦ (f ^ n) 0 + (g ^ n) 0) 1 fun n ↦ ?_ rw [h.mul_pow, dist_comm] exact le_of_lt ((f ^ n).dist_map_map_zero_lt (g ^ n)) @[simp] theorem translationNumber_units_inv (f : CircleDeg1Liftˣ) : τ ↑f⁻¹ = -τ f := eq_neg_iff_add_eq_zero.2 <| by simp [← translationNumber_mul_of_commute (Commute.refl _).units_inv_left] @[simp] theorem translationNumber_pow : ∀ n : ℕ, τ (f ^ n) = n * τ f | 0 => by simp | n + 1 => by rw [pow_succ, translationNumber_mul_of_commute (Commute.pow_self f n), translationNumber_pow n, Nat.cast_add_one, add_mul, one_mul] @[simp] theorem translationNumber_zpow (f : CircleDeg1Liftˣ) : ∀ n : ℤ, τ (f ^ n : Units _) = n * τ f | (n : ℕ) => by simp [translationNumber_pow f n] | -[n+1] => by simp; ring @[simp] theorem translationNumber_conj_eq (f : CircleDeg1Liftˣ) (g : CircleDeg1Lift) : τ (↑f * g * ↑f⁻¹) = τ g := (translationNumber_eq_of_semiconjBy (f.mk_semiconjBy g)).symm @[simp] theorem translationNumber_conj_eq' (f : CircleDeg1Liftˣ) (g : CircleDeg1Lift) : τ (↑f⁻¹ * g * f) = τ g := translationNumber_conj_eq f⁻¹ g theorem dist_pow_map_zero_mul_translationNumber_le (n : ℕ) : dist ((f ^ n) 0) (n * f.translationNumber) ≤ 1 := f.translationNumber_pow n ▸ (f ^ n).dist_map_zero_translationNumber_le theorem tendsto_translation_number₀' : Tendsto (fun n : ℕ => (f ^ (n + 1) : CircleDeg1Lift) 0 / ((n : ℝ) + 1)) atTop (𝓝 <| τ f) := by refine tendsto_iff_dist_tendsto_zero.2 <| squeeze_zero (fun _ => dist_nonneg) (fun n => ?_) ((tendsto_const_div_atTop_nhds_zero_nat 1).comp (tendsto_add_atTop_nat 1)) dsimp have : (0 : ℝ) < n + 1 := n.cast_add_one_pos rw [Real.dist_eq, div_sub' (ne_of_gt this), abs_div, ← Real.dist_eq, abs_of_pos this, Nat.cast_add_one, div_le_div_iff_of_pos_right this, ← Nat.cast_add_one] apply dist_pow_map_zero_mul_translationNumber_le theorem tendsto_translation_number₀ : Tendsto (fun n : ℕ => (f ^ n) 0 / n) atTop (𝓝 <| τ f) := (tendsto_add_atTop_iff_nat 1).1 (mod_cast f.tendsto_translation_number₀') /-- For any `x : ℝ` the sequence $\frac{f^n(x)-x}{n}$ tends to the translation number of `f`. In particular, this limit does not depend on `x`. -/ theorem tendsto_translationNumber (x : ℝ) : Tendsto (fun n : ℕ => ((f ^ n) x - x) / n) atTop (𝓝 <| τ f) := by rw [← translationNumber_conj_eq' (translate <| Multiplicative.ofAdd x)] refine (tendsto_translation_number₀ _).congr fun n ↦ ?_ simp [sub_eq_neg_add, Units.conj_pow'] theorem tendsto_translation_number' (x : ℝ) : Tendsto (fun n : ℕ => ((f ^ (n + 1) : CircleDeg1Lift) x - x) / (n + 1)) atTop (𝓝 <| τ f) := mod_cast (tendsto_add_atTop_iff_nat 1).2 (f.tendsto_translationNumber x) theorem translationNumber_mono : Monotone τ := fun f g h => le_of_tendsto_of_tendsto' f.tendsto_translation_number₀ g.tendsto_translation_number₀ fun n => by gcongr; exact pow_mono h _ _ theorem translationNumber_translate (x : ℝ) : τ (translate <| Multiplicative.ofAdd x) = x := translationNumber_eq_of_tendsto₀' _ <| by simp only [translate_iterate, translate_apply, add_zero, Nat.cast_succ, mul_div_cancel_left₀ (M₀ := ℝ) _ (Nat.cast_add_one_ne_zero _), tendsto_const_nhds] theorem translationNumber_le_of_le_add {z : ℝ} (hz : ∀ x, f x ≤ x + z) : τ f ≤ z := translationNumber_translate z ▸ translationNumber_mono fun x => (hz x).trans_eq (add_comm _ _) theorem le_translationNumber_of_add_le {z : ℝ} (hz : ∀ x, x + z ≤ f x) : z ≤ τ f := translationNumber_translate z ▸ translationNumber_mono fun x => (add_comm _ _).trans_le (hz x) theorem translationNumber_le_of_le_add_int {x : ℝ} {m : ℤ} (h : f x ≤ x + m) : τ f ≤ m := le_of_tendsto' (f.tendsto_translation_number' x) fun n => (div_le_iff₀' (n.cast_add_one_pos : (0 : ℝ) < _)).mpr <| sub_le_iff_le_add'.2 <| (coe_pow f (n + 1)).symm ▸ @Nat.cast_add_one ℝ _ n ▸ f.iterate_le_of_map_le_add_int h (n + 1) theorem translationNumber_le_of_le_add_nat {x : ℝ} {m : ℕ} (h : f x ≤ x + m) : τ f ≤ m := @translationNumber_le_of_le_add_int f x m h theorem le_translationNumber_of_add_int_le {x : ℝ} {m : ℤ} (h : x + m ≤ f x) : ↑m ≤ τ f := ge_of_tendsto' (f.tendsto_translation_number' x) fun n => (le_div_iff₀ (n.cast_add_one_pos : (0 : ℝ) < _)).mpr <| le_sub_iff_add_le'.2 <| by simp only [coe_pow, mul_comm (m : ℝ), ← Nat.cast_add_one, f.le_iterate_of_add_int_le_map h] theorem le_translationNumber_of_add_nat_le {x : ℝ} {m : ℕ} (h : x + m ≤ f x) : ↑m ≤ τ f := @le_translationNumber_of_add_int_le f x m h /-- If `f x - x` is an integer number `m` for some point `x`, then `τ f = m`. On the circle this means that a map with a fixed point has rotation number zero. -/ theorem translationNumber_of_eq_add_int {x : ℝ} {m : ℤ} (h : f x = x + m) : τ f = m := le_antisymm (translationNumber_le_of_le_add_int f <| le_of_eq h) (le_translationNumber_of_add_int_le f <| le_of_eq h.symm) theorem floor_sub_le_translationNumber (x : ℝ) : ↑⌊f x - x⌋ ≤ τ f := le_translationNumber_of_add_int_le f <| le_sub_iff_add_le'.1 (floor_le <| f x - x) theorem translationNumber_le_ceil_sub (x : ℝ) : τ f ≤ ⌈f x - x⌉ := translationNumber_le_of_le_add_int f <| sub_le_iff_le_add'.1 (le_ceil <| f x - x) theorem map_lt_of_translationNumber_lt_int {n : ℤ} (h : τ f < n) (x : ℝ) : f x < x + n := not_le.1 <| mt f.le_translationNumber_of_add_int_le <| not_le.2 h theorem map_lt_of_translationNumber_lt_nat {n : ℕ} (h : τ f < n) (x : ℝ) : f x < x + n := @map_lt_of_translationNumber_lt_int f n h x theorem map_lt_add_floor_translationNumber_add_one (x : ℝ) : f x < x + ⌊τ f⌋ + 1 := by rw [add_assoc] norm_cast refine map_lt_of_translationNumber_lt_int _ ?_ _ push_cast exact lt_floor_add_one _ theorem map_lt_add_translationNumber_add_one (x : ℝ) : f x < x + τ f + 1 := calc f x < x + ⌊τ f⌋ + 1 := f.map_lt_add_floor_translationNumber_add_one x _ ≤ x + τ f + 1 := by gcongr; apply floor_le theorem lt_map_of_int_lt_translationNumber {n : ℤ} (h : ↑n < τ f) (x : ℝ) : x + n < f x := not_le.1 <| mt f.translationNumber_le_of_le_add_int <| not_le.2 h theorem lt_map_of_nat_lt_translationNumber {n : ℕ} (h : ↑n < τ f) (x : ℝ) : x + n < f x := @lt_map_of_int_lt_translationNumber f n h x /-- If `f^n x - x`, `n > 0`, is an integer number `m` for some point `x`, then `τ f = m / n`. On the circle this means that a map with a periodic orbit has a rational rotation number. -/ theorem translationNumber_of_map_pow_eq_add_int {x : ℝ} {n : ℕ} {m : ℤ} (h : (f ^ n) x = x + m) (hn : 0 < n) : τ f = m / n := by have := (f ^ n).translationNumber_of_eq_add_int h rwa [translationNumber_pow, mul_comm, ← eq_div_iff] at this exact Nat.cast_ne_zero.2 (ne_of_gt hn) /-- If a predicate depends only on `f x - x` and holds for all `0 ≤ x ≤ 1`, then it holds for all `x`. -/ theorem forall_map_sub_of_Icc (P : ℝ → Prop) (h : ∀ x ∈ Icc (0 : ℝ) 1, P (f x - x)) (x : ℝ) : P (f x - x) := f.map_fract_sub_fract_eq x ▸ h _ ⟨fract_nonneg _, le_of_lt (fract_lt_one _)⟩ theorem translationNumber_lt_of_forall_lt_add (hf : Continuous f) {z : ℝ} (hz : ∀ x, f x < x + z) : τ f < z := by obtain ⟨x, -, hx⟩ : ∃ x ∈ Icc (0 : ℝ) 1, ∀ y ∈ Icc (0 : ℝ) 1, f y - y ≤ f x - x := isCompact_Icc.exists_isMaxOn (nonempty_Icc.2 zero_le_one) (hf.sub continuous_id).continuousOn refine lt_of_le_of_lt ?_ (sub_lt_iff_lt_add'.2 <| hz x) apply translationNumber_le_of_le_add simp only [← sub_le_iff_le_add'] exact f.forall_map_sub_of_Icc (fun a => a ≤ f x - x) hx theorem lt_translationNumber_of_forall_add_lt (hf : Continuous f) {z : ℝ} (hz : ∀ x, x + z < f x) : z < τ f := by obtain ⟨x, -, hx⟩ : ∃ x ∈ Icc (0 : ℝ) 1, ∀ y ∈ Icc (0 : ℝ) 1, f x - x ≤ f y - y := isCompact_Icc.exists_isMinOn (nonempty_Icc.2 zero_le_one) (hf.sub continuous_id).continuousOn refine lt_of_lt_of_le (lt_sub_iff_add_lt'.2 <| hz x) ?_ apply le_translationNumber_of_add_le simp only [← le_sub_iff_add_le'] exact f.forall_map_sub_of_Icc _ hx /-- If `f` is a continuous monotone map `ℝ → ℝ`, `f (x + 1) = f x + 1`, then there exists `x` such that `f x = x + τ f`. -/ theorem exists_eq_add_translationNumber (hf : Continuous f) : ∃ x, f x = x + τ f := by obtain ⟨a, ha⟩ : ∃ x, f x ≤ x + τ f := by by_contra! H exact lt_irrefl _ (f.lt_translationNumber_of_forall_add_lt hf H) obtain ⟨b, hb⟩ : ∃ x, x + τ f ≤ f x := by by_contra! H exact lt_irrefl _ (f.translationNumber_lt_of_forall_lt_add hf H) exact intermediate_value_univ₂ hf (continuous_id.add continuous_const) ha hb theorem translationNumber_eq_int_iff (hf : Continuous f) {m : ℤ} : τ f = m ↔ ∃ x : ℝ, f x = x + m := by constructor · intro h simp only [← h] exact f.exists_eq_add_translationNumber hf · rintro ⟨x, hx⟩ exact f.translationNumber_of_eq_add_int hx theorem continuous_pow (hf : Continuous f) (n : ℕ) : Continuous (f ^ n : CircleDeg1Lift) := by rw [coe_pow] exact hf.iterate n theorem translationNumber_eq_rat_iff (hf : Continuous f) {m : ℤ} {n : ℕ} (hn : 0 < n) : τ f = m / n ↔ ∃ x, (f ^ n) x = x + m := by rw [eq_div_iff, mul_comm, ← translationNumber_pow] <;> [skip; exact ne_of_gt (Nat.cast_pos.2 hn)] exact (f ^ n).translationNumber_eq_int_iff (f.continuous_pow hf n) /-- Consider two actions `f₁ f₂ : G →* CircleDeg1Lift` of a group on the real line by lifts of orientation-preserving circle homeomorphisms. Suppose that for each `g : G` the homeomorphisms `f₁ g` and `f₂ g` have equal rotation numbers. Then there exists `F : CircleDeg1Lift` such that `F * f₁ g = f₂ g * F` for all `g : G`. This is a version of Proposition 5.4 from [Étienne Ghys, Groupes d'homeomorphismes du cercle et cohomologie bornee][ghys87:groupes]. -/ theorem semiconj_of_group_action_of_forall_translationNumber_eq {G : Type*} [Group G] (f₁ f₂ : G →* CircleDeg1Lift) (h : ∀ g, τ (f₁ g) = τ (f₂ g)) : ∃ F : CircleDeg1Lift, ∀ g, Semiconj F (f₁ g) (f₂ g) := by -- Equality of translation number guarantees that for each `x` -- the set `{f₂ g⁻¹ (f₁ g x) | g : G}` is bounded above. have : ∀ x, BddAbove (range fun g => f₂ g⁻¹ (f₁ g x)) := by refine fun x => ⟨x + 2, ?_⟩ rintro _ ⟨g, rfl⟩ have : τ (f₂ g⁻¹) = -τ (f₂ g) := by rw [← MonoidHom.coe_toHomUnits, MonoidHom.map_inv, translationNumber_units_inv, MonoidHom.coe_toHomUnits] calc f₂ g⁻¹ (f₁ g x) ≤ f₂ g⁻¹ (x + τ (f₁ g) + 1) := mono _ (map_lt_add_translationNumber_add_one _ _).le _ = f₂ g⁻¹ (x + τ (f₂ g)) + 1 := by rw [h, map_add_one] _ ≤ x + τ (f₂ g) + τ (f₂ g⁻¹) + 1 + 1 := by grw [map_lt_add_translationNumber_add_one] _ = x + 2 := by simp [this, add_assoc, one_add_one_eq_two] -- We have a theorem about actions by `OrderIso`, so we introduce auxiliary maps -- to `ℝ ≃o ℝ`. set F₁ := toOrderIso.comp f₁.toHomUnits set F₂ := toOrderIso.comp f₂.toHomUnits have hF₁ : ∀ g, ⇑(F₁ g) = f₁ g := fun _ => rfl have hF₂ : ∀ g, ⇑(F₂ g) = f₂ g := fun _ => rfl -- Now we apply `csSup_div_semiconj` and go back to `f₁` and `f₂`. refine ⟨⟨⟨fun x ↦ ⨆ g', (F₂ g')⁻¹ (F₁ g' x), fun x y hxy => ?_⟩, fun x => ?_⟩, csSup_div_semiconj F₂ F₁ fun x => ?_⟩ <;> simp only [hF₁, hF₂, ← map_inv] · exact ciSup_mono (this y) fun g => mono _ (mono _ hxy) · simp only [map_add_one] exact (Monotone.map_ciSup_of_continuousAt (continuousAt_id.add continuousAt_const) (monotone_id.add_const (1 : ℝ)) (this x)).symm · exact this x /-- If two lifts of circle homeomorphisms have the same translation number, then they are semiconjugate by a `CircleDeg1Lift`. This version uses arguments `f₁ f₂ : CircleDeg1Liftˣ` to assume that `f₁` and `f₂` are homeomorphisms. -/ theorem units_semiconj_of_translationNumber_eq {f₁ f₂ : CircleDeg1Liftˣ} (h : τ f₁ = τ f₂) : ∃ F : CircleDeg1Lift, Semiconj F f₁ f₂ := have : ∀ n : Multiplicative ℤ, τ ((Units.coeHom _).comp (zpowersHom _ f₁) n) = τ ((Units.coeHom _).comp (zpowersHom _ f₂) n) := fun n ↦ by simp [h] (semiconj_of_group_action_of_forall_translationNumber_eq _ _ this).imp fun F hF => by simpa using hF (Multiplicative.ofAdd 1) /-- If two lifts of circle homeomorphisms have the same translation number, then they are semiconjugate by a `CircleDeg1Lift`. This version uses assumptions `IsUnit f₁` and `IsUnit f₂` to assume that `f₁` and `f₂` are homeomorphisms. -/ theorem semiconj_of_isUnit_of_translationNumber_eq {f₁ f₂ : CircleDeg1Lift} (h₁ : IsUnit f₁) (h₂ : IsUnit f₂) (h : τ f₁ = τ f₂) : ∃ F : CircleDeg1Lift, Semiconj F f₁ f₂ := by rcases h₁, h₂ with ⟨⟨f₁, rfl⟩, ⟨f₂, rfl⟩⟩ exact units_semiconj_of_translationNumber_eq h /-- If two lifts of circle homeomorphisms have the same translation number, then they are semiconjugate by a `CircleDeg1Lift`. This version uses assumptions `bijective f₁` and `bijective f₂` to assume that `f₁` and `f₂` are homeomorphisms. -/ theorem semiconj_of_bijective_of_translationNumber_eq {f₁ f₂ : CircleDeg1Lift} (h₁ : Bijective f₁) (h₂ : Bijective f₂) (h : τ f₁ = τ f₂) : ∃ F : CircleDeg1Lift, Semiconj F f₁ f₂ := semiconj_of_isUnit_of_translationNumber_eq (isUnit_iff_bijective.2 h₁) (isUnit_iff_bijective.2 h₂) h end CircleDeg1Lift
.lake/packages/mathlib/Mathlib/Dynamics/Ergodic/MeasurePreserving.lean
import Mathlib.MeasureTheory.Measure.AEMeasurable import Mathlib.Order.Filter.EventuallyConst /-! # Measure-preserving maps We say that `f : α → β` is a measure-preserving map w.r.t. measures `μ : Measure α` and `ν : Measure β` if `f` is measurable and `map f μ = ν`. In this file we define the predicate `MeasureTheory.MeasurePreserving` and prove its basic properties. We use the term "measure preserving" because in many applications `α = β` and `μ = ν`. ## References Partially based on [this](https://www.isa-afp.org/browser_info/current/AFP/Ergodic_Theory/Measure_Preserving_Transformations.html) Isabelle formalization. ## Tags measure-preserving map, measure -/ open MeasureTheory.Measure Function Set open scoped ENNReal variable {α β γ δ : Type*} [MeasurableSpace α] [MeasurableSpace β] [MeasurableSpace γ] [MeasurableSpace δ] namespace MeasureTheory variable {μa : Measure α} {μb : Measure β} {μc : Measure γ} {μd : Measure δ} /-- `f` is a measure-preserving map w.r.t. measures `μa` and `μb` if `f` is measurable and `map f μa = μb`. -/ structure MeasurePreserving (f : α → β) (μa : Measure α := by volume_tac) (μb : Measure β := by volume_tac) : Prop where protected measurable : Measurable f protected map_eq : map f μa = μb protected theorem _root_.Measurable.measurePreserving {f : α → β} (h : Measurable f) (μa : Measure α) : MeasurePreserving f μa (map f μa) := ⟨h, rfl⟩ namespace MeasurePreserving protected theorem id (μ : Measure α) : MeasurePreserving id μ μ := ⟨measurable_id, map_id⟩ protected theorem aemeasurable {f : α → β} (hf : MeasurePreserving f μa μb) : AEMeasurable f μa := hf.1.aemeasurable @[nontriviality] theorem of_isEmpty [IsEmpty β] (f : α → β) (μa : Measure α) (μb : Measure β) : MeasurePreserving f μa μb := ⟨measurable_of_subsingleton_codomain _, Subsingleton.elim _ _⟩ theorem symm (e : α ≃ᵐ β) {μa : Measure α} {μb : Measure β} (h : MeasurePreserving e μa μb) : MeasurePreserving e.symm μb μa := ⟨e.symm.measurable, by rw [← h.map_eq, map_map e.symm.measurable e.measurable, e.symm_comp_self, map_id]⟩ theorem restrict_preimage {f : α → β} (hf : MeasurePreserving f μa μb) {s : Set β} (hs : MeasurableSet s) : MeasurePreserving f (μa.restrict (f ⁻¹' s)) (μb.restrict s) := ⟨hf.measurable, by rw [← hf.map_eq, restrict_map hf.measurable hs]⟩ theorem restrict_preimage_emb {f : α → β} (hf : MeasurePreserving f μa μb) (h₂ : MeasurableEmbedding f) (s : Set β) : MeasurePreserving f (μa.restrict (f ⁻¹' s)) (μb.restrict s) := ⟨hf.measurable, by rw [← hf.map_eq, h₂.restrict_map]⟩ theorem restrict_image_emb {f : α → β} (hf : MeasurePreserving f μa μb) (h₂ : MeasurableEmbedding f) (s : Set α) : MeasurePreserving f (μa.restrict s) (μb.restrict (f '' s)) := by simpa only [Set.preimage_image_eq _ h₂.injective] using hf.restrict_preimage_emb h₂ (f '' s) theorem aemeasurable_comp_iff {f : α → β} (hf : MeasurePreserving f μa μb) (h₂ : MeasurableEmbedding f) {g : β → γ} : AEMeasurable (g ∘ f) μa ↔ AEMeasurable g μb := by rw [← hf.map_eq, h₂.aemeasurable_map_iff] protected theorem quasiMeasurePreserving {f : α → β} (hf : MeasurePreserving f μa μb) : QuasiMeasurePreserving f μa μb := ⟨hf.1, hf.2.absolutelyContinuous⟩ protected theorem comp {g : β → γ} {f : α → β} (hg : MeasurePreserving g μb μc) (hf : MeasurePreserving f μa μb) : MeasurePreserving (g ∘ f) μa μc := ⟨hg.1.comp hf.1, by rw [← map_map hg.1 hf.1, hf.2, hg.2]⟩ /-- An alias of `MeasureTheory.MeasurePreserving.comp` with a convenient defeq and argument order for `MeasurableEquiv` -/ protected theorem trans {e : α ≃ᵐ β} {e' : β ≃ᵐ γ} {μa : Measure α} {μb : Measure β} {μc : Measure γ} (h : MeasurePreserving e μa μb) (h' : MeasurePreserving e' μb μc) : MeasurePreserving (e.trans e') μa μc := h'.comp h protected theorem comp_left_iff {g : α → β} {e : β ≃ᵐ γ} (h : MeasurePreserving e μb μc) : MeasurePreserving (e ∘ g) μa μc ↔ MeasurePreserving g μa μb := by refine ⟨fun hg => ?_, fun hg => h.comp hg⟩ convert (MeasurePreserving.symm e h).comp hg simp [← Function.comp_assoc e.symm e g] protected theorem comp_right_iff {g : α → β} {e : γ ≃ᵐ α} (h : MeasurePreserving e μc μa) : MeasurePreserving (g ∘ e) μc μb ↔ MeasurePreserving g μa μb := by refine ⟨fun hg => ?_, fun hg => hg.comp h⟩ convert hg.comp (MeasurePreserving.symm e h) simp [Function.comp_assoc g e e.symm] protected theorem sigmaFinite {f : α → β} (hf : MeasurePreserving f μa μb) [SigmaFinite μb] : SigmaFinite μa := SigmaFinite.of_map μa hf.aemeasurable (by rwa [hf.map_eq]) protected theorem sfinite {f : α → β} (hf : MeasurePreserving f μa μb) [SFinite μa] : SFinite μb := by rw [← hf.map_eq] infer_instance theorem measure_preimage {f : α → β} (hf : MeasurePreserving f μa μb) {s : Set β} (hs : NullMeasurableSet s μb) : μa (f ⁻¹' s) = μb s := by rw [← hf.map_eq] at hs ⊢ rw [map_apply₀ hf.1.aemeasurable hs] theorem measureReal_preimage {f : α → β} (hf : MeasurePreserving f μa μb) {s : Set β} (hs : NullMeasurableSet s μb) : μa.real (f ⁻¹' s) = μb.real s := by simp [measureReal_def, measure_preimage hf hs] theorem measure_preimage_emb {f : α → β} (hf : MeasurePreserving f μa μb) (hfe : MeasurableEmbedding f) (s : Set β) : μa (f ⁻¹' s) = μb s := by rw [← hf.map_eq, hfe.map_apply] theorem measure_preimage_equiv {f : α ≃ᵐ β} (hf : MeasurePreserving f μa μb) (s : Set β) : μa (f ⁻¹' s) = μb s := measure_preimage_emb hf f.measurableEmbedding s theorem measure_preimage_le {f : α → β} (hf : MeasurePreserving f μa μb) (s : Set β) : μa (f ⁻¹' s) ≤ μb s := by rw [← hf.map_eq] exact le_map_apply hf.aemeasurable _ theorem preimage_null {f : α → β} (hf : MeasurePreserving f μa μb) {s : Set β} (hs : μb s = 0) : μa (f ⁻¹' s) = 0 := hf.quasiMeasurePreserving.preimage_null hs theorem aeconst_comp [MeasurableSingletonClass γ] {f : α → β} (hf : MeasurePreserving f μa μb) {g : β → γ} (hg : NullMeasurable g μb) : Filter.EventuallyConst (g ∘ f) (ae μa) ↔ Filter.EventuallyConst g (ae μb) := exists_congr fun s ↦ and_congr_left fun hs ↦ by simp only [Filter.mem_map, mem_ae_iff, ← hf.measure_preimage (hg hs.measurableSet).compl, preimage_comp, preimage_compl] theorem aeconst_preimage {f : α → β} (hf : MeasurePreserving f μa μb) {s : Set β} (hs : NullMeasurableSet s μb) : Filter.EventuallyConst (f ⁻¹' s) (ae μa) ↔ Filter.EventuallyConst s (ae μb) := aeconst_comp hf hs.mem theorem add_measure {f μa' μb'} (hf : MeasurePreserving f μa μb) (hf' : MeasurePreserving f μa' μb') : MeasurePreserving f (μa + μa') (μb + μb') where measurable := hf.measurable map_eq := by rw [Measure.map_add _ _ hf.measurable, hf.map_eq, hf'.map_eq] theorem smul_measure {R : Type*} [SMul R ℝ≥0∞] [IsScalarTower R ℝ≥0∞ ℝ≥0∞] {f : α → β} (hf : MeasurePreserving f μa μb) (c : R) : MeasurePreserving f (c • μa) (c • μb) where measurable := hf.measurable map_eq := by rw [Measure.map_smul, hf.map_eq] variable {μ : Measure α} {f : α → α} {s : Set α} protected theorem iterate (hf : MeasurePreserving f μ μ) : ∀ n, MeasurePreserving f^[n] μ μ | 0 => .id μ | n + 1 => (MeasurePreserving.iterate hf n).comp hf open scoped symmDiff in lemma measure_symmDiff_preimage_iterate_le (hf : MeasurePreserving f μ μ) (hs : NullMeasurableSet s μ) (n : ℕ) : μ (s ∆ (f^[n] ⁻¹' s)) ≤ n • μ (s ∆ (f ⁻¹' s)) := by induction n with | zero => simp | succ n ih => simp only [add_smul, one_smul] grw [← ih, measure_symmDiff_le s (f^[n] ⁻¹' s) (f^[n+1] ⁻¹' s)] replace hs : NullMeasurableSet (s ∆ (f ⁻¹' s)) μ := hs.symmDiff <| hs.preimage hf.quasiMeasurePreserving rw [iterate_succ', preimage_comp, ← preimage_symmDiff, (hf.iterate n).measure_preimage hs] /-- If `μ univ < n * μ s` and `f` is a map preserving measure `μ`, then for some `x ∈ s` and `0 < m < n`, `f^[m] x ∈ s`. -/ theorem exists_mem_iterate_mem_of_measure_univ_lt_mul_measure (hf : MeasurePreserving f μ μ) (hs : NullMeasurableSet s μ) {n : ℕ} (hvol : μ (Set.univ : Set α) < n * μ s) : ∃ x ∈ s, ∃ m ∈ Set.Ioo 0 n, f^[m] x ∈ s := by have A : ∀ m, NullMeasurableSet (f^[m] ⁻¹' s) μ := fun m ↦ hs.preimage (hf.iterate m).quasiMeasurePreserving have B : ∀ m, μ (f^[m] ⁻¹' s) = μ s := fun m ↦ (hf.iterate m).measure_preimage hs have : μ (univ : Set α) < ∑ m ∈ Finset.range n, μ (f^[m] ⁻¹' s) := by simpa [B] obtain ⟨i, hi, j, hj, hij, x, hxi : f^[i] x ∈ s, hxj : f^[j] x ∈ s⟩ : ∃ i < n, ∃ j < n, i ≠ j ∧ (f^[i] ⁻¹' s ∩ f^[j] ⁻¹' s).Nonempty := by simpa using exists_nonempty_inter_of_measure_univ_lt_sum_measure μ (fun m _ ↦ A m) this wlog hlt : i < j generalizing i j · exact this j hj i hi hij.symm hxj hxi (hij.lt_or_gt.resolve_left hlt) refine ⟨f^[i] x, hxi, j - i, ⟨tsub_pos_of_lt hlt, lt_of_le_of_lt (j.sub_le i) hj⟩, ?_⟩ rwa [← iterate_add_apply, tsub_add_cancel_of_le hlt.le] /-- A self-map preserving a finite measure is conservative: if `μ s ≠ 0`, then at least one point `x ∈ s` comes back to `s` under iterations of `f`. Actually, a.e. point of `s` comes back to `s` infinitely many times, see `MeasureTheory.MeasurePreserving.conservative` and theorems about `MeasureTheory.Conservative`. -/ theorem exists_mem_iterate_mem [IsFiniteMeasure μ] (hf : MeasurePreserving f μ μ) (hs : NullMeasurableSet s μ) (hs' : μ s ≠ 0) : ∃ x ∈ s, ∃ m ≠ 0, f^[m] x ∈ s := by rcases ENNReal.exists_nat_mul_gt hs' (measure_ne_top μ (Set.univ : Set α)) with ⟨N, hN⟩ rcases hf.exists_mem_iterate_mem_of_measure_univ_lt_mul_measure hs hN with ⟨x, hx, m, hm, hmx⟩ exact ⟨x, hx, m, hm.1.ne', hmx⟩ end MeasurePreserving lemma measurePreserving_subtype_coe {s : Set α} (hs : MeasurableSet s) : MeasurePreserving (Subtype.val : s → α) (μa.comap Subtype.val) (μa.restrict s) where measurable := measurable_subtype_coe map_eq := map_comap_subtype_coe hs _ namespace MeasurableEquiv theorem measurePreserving_symm (μ : Measure α) (e : α ≃ᵐ β) : MeasurePreserving e.symm (map e μ) μ := (e.measurable.measurePreserving μ).symm _ end MeasurableEquiv end MeasureTheory
.lake/packages/mathlib/Mathlib/Dynamics/Ergodic/AddCircle.lean
import Mathlib.Algebra.Order.Ring.Abs import Mathlib.Dynamics.FixedPoints.Prufer import Mathlib.Dynamics.Ergodic.Ergodic import Mathlib.MeasureTheory.Covering.DensityTheorem import Mathlib.MeasureTheory.Group.AddCircle import Mathlib.MeasureTheory.Measure.Haar.Unique /-! # Ergodic maps of the additive circle This file contains proofs of ergodicity for maps of the additive circle. ## Main definitions: * `AddCircle.ergodic_zsmul`: given `n : ℤ` such that `1 < |n|`, the self map `y ↦ n • y` on the additive circle is ergodic (w.r.t. the Haar measure). * `AddCircle.ergodic_nsmul`: given `n : ℕ` such that `1 < n`, the self map `y ↦ n • y` on the additive circle is ergodic (w.r.t. the Haar measure). * `AddCircle.ergodic_zsmul_add`: given `n : ℤ` such that `1 < |n|` and `x : AddCircle T`, the self map `y ↦ n • y + x` on the additive circle is ergodic (w.r.t. the Haar measure). * `AddCircle.ergodic_nsmul_add`: given `n : ℕ` such that `1 < n` and `x : AddCircle T`, the self map `y ↦ n • y + x` on the additive circle is ergodic (w.r.t. the Haar measure). -/ open Set Function MeasureTheory MeasureTheory.Measure Filter Metric open scoped MeasureTheory NNReal ENNReal Topology Pointwise namespace AddCircle variable {T : ℝ} [hT : Fact (0 < T)] /-- If a null-measurable subset of the circle is almost invariant under rotation by a family of rational angles with denominators tending to infinity, then it must be almost empty or almost full. -/ theorem ae_empty_or_univ_of_forall_vadd_ae_eq_self {s : Set <| AddCircle T} (hs : NullMeasurableSet s volume) {ι : Type*} {l : Filter ι} [l.NeBot] {u : ι → AddCircle T} (hu₁ : ∀ i, (u i +ᵥ s : Set _) =ᵐ[volume] s) (hu₂ : Tendsto (addOrderOf ∘ u) l atTop) : s =ᵐ[volume] (∅ : Set <| AddCircle T) ∨ s =ᵐ[volume] univ := by /- Sketch of proof: Assume `T = 1` for simplicity and let `μ` be the Haar measure. We may assume `s` has positive measure since otherwise there is nothing to prove. In this case, by Lebesgue's density theorem, there exists a point `d` of positive density. Let `Iⱼ` be the sequence of closed balls about `d` of diameter `1 / nⱼ` where `nⱼ` is the additive order of `uⱼ`. Since `d` has positive density we must have `μ (s ∩ Iⱼ) / μ Iⱼ → 1` along `l`. However since `s` is invariant under the action of `uⱼ` and since `Iⱼ` is a fundamental domain for this action, we must have `μ (s ∩ Iⱼ) = nⱼ * μ s = (μ Iⱼ) * μ s`. We thus have `μ s → 1` and thus `μ s = 1`. -/ set μ := (volume : Measure <| AddCircle T) set n : ι → ℕ := addOrderOf ∘ u have hT₀ : 0 < T := hT.out have hT₁ : ENNReal.ofReal T ≠ 0 := by simpa rw [ae_eq_empty, ae_eq_univ_iff_measure_eq hs, AddCircle.measure_univ] rcases eq_or_ne (μ s) 0 with h | h; · exact Or.inl h right obtain ⟨d, -, hd⟩ : ∃ d, d ∈ s ∧ ∀ {ι'} {l : Filter ι'} (w : ι' → AddCircle T) (δ : ι' → ℝ), Tendsto δ l (𝓝[>] 0) → (∀ᶠ j in l, d ∈ closedBall (w j) (1 * δ j)) → Tendsto (fun j => μ (s ∩ closedBall (w j) (δ j)) / μ (closedBall (w j) (δ j))) l (𝓝 1) := exists_mem_of_measure_ne_zero_of_ae h (IsUnifLocDoublingMeasure.ae_tendsto_measure_inter_div μ s 1) let I : ι → Set (AddCircle T) := fun j => closedBall d (T / (2 * ↑(n j))) replace hd : Tendsto (fun j => μ (s ∩ I j) / μ (I j)) l (𝓝 1) := by let δ : ι → ℝ := fun j => T / (2 * ↑(n j)) have hδ₀ : ∀ᶠ j in l, 0 < δ j := (hu₂.eventually_gt_atTop 0).mono fun j hj => div_pos hT₀ <| by positivity have hδ₁ : Tendsto δ l (𝓝[>] 0) := by refine tendsto_nhdsWithin_iff.mpr ⟨?_, hδ₀⟩ replace hu₂ : Tendsto (fun j => T⁻¹ * 2 * n j) l atTop := (tendsto_natCast_atTop_iff.mpr hu₂).const_mul_atTop (by positivity : 0 < T⁻¹ * 2) convert hu₂.inv_tendsto_atTop ext j simp only [δ, Pi.inv_apply, mul_inv_rev, inv_inv, div_eq_inv_mul, ← mul_assoc] have hw : ∀ᶠ j in l, d ∈ closedBall d (1 * δ j) := hδ₀.mono fun j hj => by simp only [one_mul, mem_closedBall, dist_self] apply hj.le exact hd _ δ hδ₁ hw suffices ∀ᶠ j in l, μ (s ∩ I j) / μ (I j) = μ s / ENNReal.ofReal T by replace hd := hd.congr' this rwa [tendsto_const_nhds_iff, ENNReal.div_eq_one_iff hT₁ ENNReal.ofReal_ne_top] at hd refine (hu₂.eventually_gt_atTop 0).mono fun j hj => ?_ have : addOrderOf (u j) = n j := rfl have huj : IsOfFinAddOrder (u j) := addOrderOf_pos_iff.mp hj have huj' : 1 ≤ (↑(n j) : ℝ) := by norm_cast have hI₀ : μ (I j) ≠ 0 := (measure_closedBall_pos _ d <| by positivity).ne.symm have hI₁ : μ (I j) ≠ ⊤ := measure_ne_top _ _ have hI₂ : μ (I j) * ↑(n j) = ENNReal.ofReal T := by rw [volume_closedBall, mul_div, mul_div_mul_left T _ two_ne_zero, min_eq_right (div_le_self hT₀.le huj'), mul_comm, ← nsmul_eq_mul, ← ENNReal.ofReal_nsmul, nsmul_eq_mul, mul_div_cancel₀] exact Nat.cast_ne_zero.mpr hj.ne' rw [ENNReal.div_eq_div_iff hT₁ ENNReal.ofReal_ne_top hI₀ hI₁, volume_of_add_preimage_eq s _ (u j) d huj (hu₁ j) closedBall_ae_eq_ball, nsmul_eq_mul, ← mul_assoc, this, hI₂] theorem ergodic_zsmul {n : ℤ} (hn : 1 < |n|) : Ergodic fun y : AddCircle T => n • y := { measurePreserving_zsmul volume (abs_pos.mp <| lt_trans zero_lt_one hn) with aeconst_set := fun s hs hs' => by let u : ℕ → AddCircle T := fun j => ↑((↑1 : ℝ) / ↑(n.natAbs ^ j) * T) replace hn : 1 < n.natAbs := by rwa [Int.abs_eq_natAbs, Nat.one_lt_cast] at hn have hu₀ : ∀ j, addOrderOf (u j) = n.natAbs ^ j := fun j => by convert addOrderOf_div_of_gcd_eq_one (p := T) (m := 1) (pow_pos (pos_of_gt hn) j) (gcd_one_left _) norm_cast have hnu : ∀ j, n ^ j • u j = 0 := fun j => by rw [← addOrderOf_dvd_iff_zsmul_eq_zero, hu₀, Int.natCast_pow, Int.natCast_natAbs, ← abs_pow, abs_dvd] have hu₁ : ∀ j, (u j +ᵥ s : Set _) =ᵐ[volume] s := fun j => by rw [vadd_eq_self_of_preimage_zsmul_eq_self hs' (hnu j)] have hu₂ : Tendsto (fun j => addOrderOf <| u j) atTop atTop := by simp_rw [hu₀]; exact tendsto_pow_atTop_atTop_of_one_lt hn rw [eventuallyConst_set'] exact ae_empty_or_univ_of_forall_vadd_ae_eq_self hs.nullMeasurableSet hu₁ hu₂ } theorem ergodic_nsmul {n : ℕ} (hn : 1 < n) : Ergodic fun y : AddCircle T => n • y := ergodic_zsmul (by simp [hn] : 1 < |(n : ℤ)|) theorem ergodic_zsmul_add (x : AddCircle T) {n : ℤ} (h : 1 < |n|) : Ergodic fun y => n • y + x := by set f : AddCircle T → AddCircle T := fun y => n • y + x let e : AddCircle T ≃ᵐ AddCircle T := MeasurableEquiv.addLeft (DivisibleBy.div x <| n - 1) have he : MeasurePreserving e volume volume := measurePreserving_add_left volume (DivisibleBy.div x <| n - 1) suffices e ∘ f ∘ e.symm = fun y => n • y by rw [← he.ergodic_conjugate_iff, this]; exact ergodic_zsmul h replace h : n - 1 ≠ 0 := by rw [← abs_one] at h; rw [sub_ne_zero]; exact ne_of_apply_ne _ (ne_of_gt h) have hnx : n • DivisibleBy.div x (n - 1) = x + DivisibleBy.div x (n - 1) := by conv_rhs => congr; rw [← DivisibleBy.div_cancel x h] rw [sub_smul, one_smul, sub_add_cancel] ext y simp only [f, e, hnx, MeasurableEquiv.coe_addLeft, MeasurableEquiv.symm_addLeft, comp_apply, smul_add, zsmul_neg', neg_smul, neg_add_rev] abel theorem ergodic_nsmul_add (x : AddCircle T) {n : ℕ} (h : 1 < n) : Ergodic fun y => n • y + x := ergodic_zsmul_add x (by simp [h] : 1 < |(n : ℤ)|) end AddCircle
.lake/packages/mathlib/Mathlib/Dynamics/Ergodic/Extreme.lean
import Mathlib.Analysis.Convex.Extreme import Mathlib.Dynamics.Ergodic.Function import Mathlib.Dynamics.Ergodic.RadonNikodym import Mathlib.Probability.ConditionalProbability /-! # Ergodic measures as extreme points In this file we prove that a finite measure `μ` is an ergodic measure for a self-map `f` iff it is an extreme point of the set of invariant measures of `f` with the same total volume. We also specialize this result to probability measures. -/ open Filter Set Function MeasureTheory Measure ProbabilityTheory open scoped NNReal ENNReal Topology variable {X : Type*} {m : MeasurableSpace X} {μ ν : Measure X} {f : X → X} namespace Ergodic /-- Given a constant `c ≠ ∞`, an extreme point of the set of measures that are invariant under `f` and have total mass `c` is an ergodic measure. -/ theorem of_mem_extremePoints_measure_univ_eq {c : ℝ≥0∞} (hc : c ≠ ∞) (h : μ ∈ extremePoints ℝ≥0∞ {ν | MeasurePreserving f ν ν ∧ ν univ = c}) : Ergodic f μ := by have hf : MeasurePreserving f μ μ := h.1.1 rcases eq_or_ne c 0 with rfl | hc₀ · convert zero_measure hf.measurable rw [← measure_univ_eq_zero, h.1.2] · refine ⟨hf, ⟨?_⟩⟩ have : IsFiniteMeasure μ := by constructor rwa [h.1.2, lt_top_iff_ne_top] set S := {ν | MeasurePreserving f ν ν ∧ ν univ = c} have {s : Set X} (hsm : MeasurableSet s) (hfs : f ⁻¹' s = s) (hμs : μ s ≠ 0) : c • μ[|s] ∈ S := by refine ⟨.smul_measure (.smul_measure ?_ _) c, ?_⟩ · convert hf.restrict_preimage hsm exact hfs.symm · rw [Measure.smul_apply, (cond_isProbabilityMeasure hμs).1, smul_eq_mul, mul_one] intro s hsm hfs by_contra H obtain ⟨hs, hs'⟩ : μ s ≠ 0 ∧ μ sᶜ ≠ 0 := by simpa [eventuallyConst_set, ae_iff, and_comm] using H have hcond : c • μ[|s] = μ := by apply h.2 (this hsm hfs hs) (this hsm.compl (by rw [preimage_compl, hfs]) hs') refine ⟨μ s / c, μ sᶜ / c, ENNReal.div_pos hs hc, ENNReal.div_pos hs' hc, ?_, ?_⟩ · rw [← ENNReal.add_div, measure_add_measure_compl hsm, h.1.2, ENNReal.div_self hc₀ hc] · simp [ProbabilityTheory.cond, smul_smul, ← mul_assoc, ENNReal.div_mul_cancel, ENNReal.mul_inv_cancel, *] rw [← hcond] at hs' simp [ProbabilityTheory.cond_apply, hsm] at hs' /-- An extreme point of the set of invariant probability measures is an ergodic measure. -/ theorem of_mem_extremePoints (h : μ ∈ extremePoints ℝ≥0∞ {ν | MeasurePreserving f ν ν ∧ IsProbabilityMeasure ν}) : Ergodic f μ := .of_mem_extremePoints_measure_univ_eq ENNReal.one_ne_top <| by simpa only [isProbabilityMeasure_iff] using h -- TODO: do we need `IsFiniteMeasure ν` here? theorem eq_smul_of_absolutelyContinuous [IsFiniteMeasure μ] [IsFiniteMeasure ν] (hμ : Ergodic f μ) (hfν : MeasurePreserving f ν ν) (hνμ : ν ≪ μ) : ∃ c : ℝ≥0∞, ν = c • μ := by have := hfν.rnDeriv_comp_aeEq hμ.toMeasurePreserving obtain ⟨c, hc⟩ := hμ.ae_eq_const_of_ae_eq_comp₀ (measurable_rnDeriv _ _).nullMeasurable this use c ext s hs calc ν s = ∫⁻ a in s, ν.rnDeriv μ a ∂μ := .symm <| setLIntegral_rnDeriv hνμ _ _ = ∫⁻ _ in s, c ∂μ := lintegral_congr_ae <| hc.filter_mono <| ae_mono restrict_le_self _ = (c • μ) s := by simp theorem eq_of_absolutelyContinuous_measure_univ_eq [IsFiniteMeasure μ] [IsFiniteMeasure ν] (hμ : Ergodic f μ) (hfν : MeasurePreserving f ν ν) (hνμ : ν ≪ μ) (huniv : ν univ = μ univ) : ν = μ := by rcases hμ.eq_smul_of_absolutelyContinuous hfν hνμ with ⟨c, rfl⟩ rcases eq_or_ne μ 0 with rfl | hμ₀ · simp · simp_all [ENNReal.mul_eq_right] theorem eq_of_absolutelyContinuous [IsProbabilityMeasure μ] [IsProbabilityMeasure ν] (hμ : Ergodic f μ) (hfν : MeasurePreserving f ν ν) (hνμ : ν ≪ μ) : ν = μ := eq_of_absolutelyContinuous_measure_univ_eq hμ hfν hνμ <| by simp theorem mem_extremePoints_measure_univ_eq [IsFiniteMeasure μ] (hμ : Ergodic f μ) : μ ∈ extremePoints ℝ≥0∞ {ν | MeasurePreserving f ν ν ∧ ν univ = μ univ} := by rw [mem_extremePoints_iff_left] refine ⟨⟨hμ.toMeasurePreserving, rfl⟩, ?_⟩ rintro ν₁ ⟨hfν₁, hν₁μ⟩ ν₂ ⟨hfν₂, hν₂μ⟩ ⟨a, b, ha, hb, hab, rfl⟩ have : IsFiniteMeasure ν₁ := ⟨by rw [hν₁μ]; apply measure_lt_top⟩ apply hμ.eq_of_absolutelyContinuous_measure_univ_eq hfν₁ (.add_right _ _) hν₁μ apply absolutelyContinuous_smul ha.ne' theorem mem_extremePoints [IsProbabilityMeasure μ] (hμ : Ergodic f μ) : μ ∈ extremePoints ℝ≥0∞ {ν | MeasurePreserving f ν ν ∧ IsProbabilityMeasure ν} := by simpa only [isProbabilityMeasure_iff, measure_univ] using hμ.mem_extremePoints_measure_univ_eq theorem iff_mem_extremePoints_measure_univ_eq [IsFiniteMeasure μ] : Ergodic f μ ↔ μ ∈ extremePoints ℝ≥0∞ {ν | MeasurePreserving f ν ν ∧ ν univ = μ univ} := ⟨mem_extremePoints_measure_univ_eq, of_mem_extremePoints_measure_univ_eq (measure_ne_top _ _)⟩ theorem iff_mem_extremePoints [IsProbabilityMeasure μ] : Ergodic f μ ↔ μ ∈ extremePoints ℝ≥0∞ {ν | MeasurePreserving f ν ν ∧ IsProbabilityMeasure ν} := ⟨mem_extremePoints, of_mem_extremePoints⟩ end Ergodic
.lake/packages/mathlib/Mathlib/Dynamics/Ergodic/RadonNikodym.lean
import Mathlib.Dynamics.Ergodic.MeasurePreserving import Mathlib.MeasureTheory.Measure.Decomposition.RadonNikodym import Mathlib.Topology.Order.CountableSeparating /-! # Radon-Nikodym derivative of invariant measures Given two finite invariant measures of a self-map, we prove that their singular parts, their absolutely continuous parts, and their Radon-Nikodym derivatives are invariant too. For the first two theorems, we only assume that one of the measures is finite and the other is σ-finite. ## TODO It isn't clear if the finiteness assumptions are optimal in this file. We should either weaken them, or describe an example showing that it's impossible. -/ open MeasureTheory Measure Set variable {X : Type*} {m : MeasurableSpace X} {μ ν : Measure X} [IsFiniteMeasure μ] namespace MeasureTheory.MeasurePreserving /-- The singular part of a finite invariant measure of a self-map with respect to a σ-finite invariant measure is an invariant measure. -/ protected theorem singularPart [SigmaFinite ν] {f : X → X} (hfμ : MeasurePreserving f μ μ) (hfν : MeasurePreserving f ν ν) : MeasurePreserving f (μ.singularPart ν) (μ.singularPart ν) := by rcases (μ.mutuallySingular_singularPart ν).symm with ⟨s, hsm, hνs, hμs⟩ convert hfμ.restrict_preimage hsm using 1 · refine singularPart_eq_restrict ?_ (hfν.preimage_null hνs) rw [← mem_ae_iff, ← Filter.eventuallyEq_univ, ae_eq_univ_iff_measure_eq (hfμ.measurable hsm).nullMeasurableSet] calc μ.singularPart ν (f ⁻¹' s) = (ν.withDensity (μ.rnDeriv ν) + μ.singularPart ν) (f ⁻¹' s) := by rw [← hfν.measure_preimage hsm.nullMeasurableSet] at hνs rw [add_apply, withDensity_absolutelyContinuous _ _ hνs, zero_add] _ = (ν.withDensity (μ.rnDeriv ν) + μ.singularPart ν) s := by rw [rnDeriv_add_singularPart, hfμ.measure_preimage hsm.nullMeasurableSet] _ = μ.singularPart ν s := by rw [add_apply, withDensity_absolutelyContinuous _ _ hνs, zero_add] _ = μ.singularPart ν univ := by rw [← measure_add_measure_compl hsm, hμs, add_zero] · exact singularPart_eq_restrict hμs hνs /-- The absolutely continuous part of a finite invariant measure of a self-map with respect to a σ-finite invariant measure is an invariant measure. -/ protected theorem withDensity_rnDeriv [SigmaFinite ν] {f : X → X} (hfμ : MeasurePreserving f μ μ) (hfν : MeasurePreserving f ν ν) : MeasurePreserving f (ν.withDensity (μ.rnDeriv ν)) (ν.withDensity (μ.rnDeriv ν)) := by use hfμ.measurable ext s hs rw [← ENNReal.add_left_inj (measure_ne_top (μ.singularPart ν) s), map_apply hfμ.measurable hs, ← add_apply, rnDeriv_add_singularPart, ← (hfμ.singularPart hfν).measure_preimage hs.nullMeasurableSet, ← add_apply, rnDeriv_add_singularPart, hfμ.measure_preimage hs.nullMeasurableSet] /-- The Radon-Nikodym derivative of a finite invariant measure of a self-map `f` with respect to another finite invariant measure of `f` is a.e. invariant under `f`. -/ theorem rnDeriv_comp_aeEq [IsFiniteMeasure ν] {f : X → X} (hfμ : MeasurePreserving f μ μ) (hfν : MeasurePreserving f ν ν) : μ.rnDeriv ν ∘ f =ᵐ[ν] μ.rnDeriv ν := by wlog hμν : μ ≪ ν generalizing μ · specialize this (hfμ.withDensity_rnDeriv hfν) (withDensity_absolutelyContinuous _ _) refine .trans (.trans ?_ this) (rnDeriv_withDensity ν (measurable_rnDeriv μ ν)) apply hfν.quasiMeasurePreserving.ae_eq_comp exact (rnDeriv_withDensity ν (measurable_rnDeriv μ ν)).symm refine .of_forall_eventually_lt_iff fun c ↦ ?_ set s := {a | μ.rnDeriv ν a < c} have hsm : MeasurableSet s := measurable_rnDeriv _ _ measurableSet_Iio have hμ_diff : μ (f ⁻¹' s \ s) = μ (s \ f ⁻¹' s) := measure_diff_symm (hfμ.measurable hsm).nullMeasurableSet hsm.nullMeasurableSet (hfμ.measure_preimage hsm.nullMeasurableSet) (by finiteness) have hν_diff : ν (f ⁻¹' s \ s) = ν (s \ f ⁻¹' s) := measure_diff_symm (hfν.measurable hsm).nullMeasurableSet hsm.nullMeasurableSet (hfν.measure_preimage hsm.nullMeasurableSet) (by finiteness) suffices f ⁻¹' s =ᵐ[ν] s from this.mem_iff suffices ν (f ⁻¹' s \ s) = 0 from (ae_le_set.mpr this).antisymm (ae_le_set.mpr <| hν_diff ▸ this) contrapose! hμ_diff with h₀ apply ne_of_gt calc μ (s \ f ⁻¹' s) = ∫⁻ a in s \ f ⁻¹' s, μ.rnDeriv ν a ∂ν := (setLIntegral_rnDeriv hμν _).symm _ < ∫⁻ _ in s \ f ⁻¹' s, c ∂ν := by apply setLIntegral_strict_mono (hsm.diff (hfμ.measurable hsm)) (hν_diff ▸ h₀) measurable_const · rw [setLIntegral_rnDeriv hμν] finiteness · exact .of_forall fun x hx ↦ hx.1 _ = ∫⁻ _ in f ⁻¹' s \ s, c ∂ν := by simp [hν_diff] _ ≤ ∫⁻ a in f ⁻¹' s \ s, μ.rnDeriv ν a ∂ν := setLIntegral_mono (by fun_prop) (fun x hx ↦ not_lt.mp hx.2) _ = μ (f ⁻¹' s \ s) := setLIntegral_rnDeriv hμν _ end MeasureTheory.MeasurePreserving
.lake/packages/mathlib/Mathlib/Dynamics/Ergodic/Function.lean
import Mathlib.Dynamics.Ergodic.Ergodic import Mathlib.MeasureTheory.Function.AEEqFun /-! # Functions invariant under (quasi)ergodic map In this file we prove that an a.e. strongly measurable function `g : α → X` that is a.e. invariant under a (quasi)ergodic map is a.e. equal to a constant. We prove several versions of this statement with slightly different measurability assumptions. We also formulate a version for `MeasureTheory.AEEqFun` functions with all a.e. equalities replaced with equalities in the quotient space. -/ open Function Set Filter MeasureTheory Topology TopologicalSpace variable {α X : Type*} [MeasurableSpace α] {μ : MeasureTheory.Measure α} /-- Let `f : α → α` be a (quasi)ergodic map. Let `g : α → X` is a null-measurable function from `α` to a nonempty space with a countable family of measurable sets separating points of a set `s` such that `f x ∈ s` for a.e. `x`. If `g` that is a.e.-invariant under `f`, then `g` is a.e. constant. -/ theorem QuasiErgodic.ae_eq_const_of_ae_eq_comp_of_ae_range₀ [Nonempty X] [MeasurableSpace X] {s : Set X} [MeasurableSpace.CountablySeparated s] {f : α → α} {g : α → X} (h : QuasiErgodic f μ) (hs : ∀ᵐ x ∂μ, g x ∈ s) (hgm : NullMeasurable g μ) (hg_eq : g ∘ f =ᵐ[μ] g) : ∃ c, g =ᵐ[μ] const α c := by refine exists_eventuallyEq_const_of_eventually_mem_of_forall_separating MeasurableSet hs ?_ refine fun U hU ↦ h.ae_mem_or_ae_notMem₀ (s := g ⁻¹' U) (hgm hU) ?_b refine (hg_eq.mono fun x hx ↦ ?_).set_eq rw [← preimage_comp, mem_preimage, mem_preimage, hx] section CountableSeparatingOnUniv variable [Nonempty X] [MeasurableSpace X] [MeasurableSpace.CountablySeparated X] {f : α → α} {g : α → X} /-- Let `f : α → α` be a (pre)ergodic map. Let `g : α → X` be a measurable function from `α` to a nonempty measurable space with a countable family of measurable sets separating the points of `X`. If `g` is invariant under `f`, then `g` is a.e. constant. -/ theorem PreErgodic.ae_eq_const_of_ae_eq_comp (h : PreErgodic f μ) (hgm : Measurable g) (hg_eq : g ∘ f = g) : ∃ c, g =ᵐ[μ] const α c := exists_eventuallyEq_const_of_forall_separating MeasurableSet fun U hU ↦ h.ae_mem_or_ae_notMem (s := g ⁻¹' U) (hgm hU) <| by rw [← preimage_comp, hg_eq] /-- Let `f : α → α` be a quasi-ergodic map. Let `g : α → X` be a null-measurable function from `α` to a nonempty measurable space with a countable family of measurable sets separating the points of `X`. If `g` is a.e.-invariant under `f`, then `g` is a.e. constant. -/ theorem QuasiErgodic.ae_eq_const_of_ae_eq_comp₀ (h : QuasiErgodic f μ) (hgm : NullMeasurable g μ) (hg_eq : g ∘ f =ᵐ[μ] g) : ∃ c, g =ᵐ[μ] const α c := h.ae_eq_const_of_ae_eq_comp_of_ae_range₀ (s := univ) univ_mem hgm hg_eq /-- Let `f : α → α` be an ergodic map. Let `g : α → X` be a null-measurable function from `α` to a nonempty measurable space with a countable family of measurable sets separating the points of `X`. If `g` is a.e.-invariant under `f`, then `g` is a.e. constant. -/ theorem Ergodic.ae_eq_const_of_ae_eq_comp₀ (h : Ergodic f μ) (hgm : NullMeasurable g μ) (hg_eq : g ∘ f =ᵐ[μ] g) : ∃ c, g =ᵐ[μ] const α c := h.quasiErgodic.ae_eq_const_of_ae_eq_comp₀ hgm hg_eq end CountableSeparatingOnUniv variable [TopologicalSpace X] [MetrizableSpace X] [Nonempty X] {f : α → α} namespace QuasiErgodic /-- Let `f : α → α` be a quasi-ergodic map. Let `g : α → X` be an a.e. strongly measurable function from `α` to a nonempty metrizable topological space. If `g` is a.e.-invariant under `f`, then `g` is a.e. constant. -/ theorem ae_eq_const_of_ae_eq_comp_ae {g : α → X} (h : QuasiErgodic f μ) (hgm : AEStronglyMeasurable g μ) (hg_eq : g ∘ f =ᵐ[μ] g) : ∃ c, g =ᵐ[μ] const α c := by borelize X rcases hgm.isSeparable_ae_range with ⟨t, ht, hgt⟩ haveI := ht.secondCountableTopology exact h.ae_eq_const_of_ae_eq_comp_of_ae_range₀ hgt hgm.aemeasurable.nullMeasurable hg_eq theorem eq_const_of_compQuasiMeasurePreserving_eq (h : QuasiErgodic f μ) {g : α →ₘ[μ] X} (hg_eq : g.compQuasiMeasurePreserving f h.1 = g) : ∃ c, g = .const α c := have : g ∘ f =ᵐ[μ] g := (g.coeFn_compQuasiMeasurePreserving h.1).symm.trans (hg_eq.symm ▸ .refl _ _) let ⟨c, hc⟩ := h.ae_eq_const_of_ae_eq_comp_ae g.aestronglyMeasurable this ⟨c, AEEqFun.ext <| hc.trans (AEEqFun.coeFn_const _ _).symm⟩ end QuasiErgodic namespace Ergodic /-- Let `f : α → α` be an ergodic map. Let `g : α → X` be an a.e. strongly measurable function from `α` to a nonempty metrizable topological space. If `g` is a.e.-invariant under `f`, then `g` is a.e. constant. -/ theorem ae_eq_const_of_ae_eq_comp_ae {g : α → X} (h : Ergodic f μ) (hgm : AEStronglyMeasurable g μ) (hg_eq : g ∘ f =ᵐ[μ] g) : ∃ c, g =ᵐ[μ] const α c := h.quasiErgodic.ae_eq_const_of_ae_eq_comp_ae hgm hg_eq theorem eq_const_of_compMeasurePreserving_eq (h : Ergodic f μ) {g : α →ₘ[μ] X} (hg_eq : g.compMeasurePreserving f h.1 = g) : ∃ c, g = .const α c := h.quasiErgodic.eq_const_of_compQuasiMeasurePreserving_eq hg_eq end Ergodic
.lake/packages/mathlib/Mathlib/Dynamics/Ergodic/AddCircleAdd.lean
import Mathlib.Dynamics.Ergodic.Action.OfMinimal import Mathlib.Topology.Instances.AddCircle.DenseSubgroup import Mathlib.MeasureTheory.Integral.IntervalIntegral.Periodic /-! # Ergodicity of an irrational rotation In this file we prove that rotation of `AddCircle p` by `a` is ergodic if and only if `a` has infinite order (in other words, if `a / p` is irrational). -/ open Metric MeasureTheory AddSubgroup open scoped Pointwise namespace AddCircle variable {p : ℝ} [Fact (0 < p)] theorem ergodic_add_left {a : AddCircle p} : Ergodic (a + ·) ↔ addOrderOf a = 0 := by rw [← denseRange_zsmul_iff, ergodic_add_left_iff_denseRange_zsmul] theorem ergodic_add_right {a : AddCircle p} : Ergodic (· + a) ↔ addOrderOf a = 0 := by simp only [add_comm, ← ergodic_add_left] end AddCircle
.lake/packages/mathlib/Mathlib/Dynamics/Ergodic/Ergodic.lean
import Mathlib.Dynamics.Ergodic.MeasurePreserving import Mathlib.MeasureTheory.Measure.Typeclasses.Probability /-! # Ergodic maps and measures Let `f : α → α` be measure preserving with respect to a measure `μ`. We say `f` is ergodic with respect to `μ` (or `μ` is ergodic with respect to `f`) if the only measurable sets `s` such that `f⁻¹' s = s` are either almost empty or full. In this file we define ergodic maps / measures together with quasi-ergodic maps / measures and provide some basic API. Quasi-ergodicity is a weaker condition than ergodicity for which the measure preserving condition is relaxed to quasi-measure-preserving. # Main definitions: * `PreErgodic`: the ergodicity condition without the measure-preserving condition. This exists to share code between the `Ergodic` and `QuasiErgodic` definitions. * `Ergodic`: the definition of ergodic maps / measures. * `QuasiErgodic`: the definition of quasi-ergodic maps / measures. * `Ergodic.quasiErgodic`: an ergodic map / measure is quasi-ergodic. * `QuasiErgodic.ae_empty_or_univ'`: when the map is quasi-measure-preserving, one may relax the strict invariance condition to almost invariance in the ergodicity condition. -/ open Set Function Filter MeasureTheory MeasureTheory.Measure open ENNReal variable {α : Type*} {m : MeasurableSpace α} {s : Set α} /-- A map `f : α → α` is said to be pre-ergodic with respect to a measure `μ` if any measurable strictly invariant set is either almost empty or full. -/ structure PreErgodic (f : α → α) (μ : Measure α := by volume_tac) : Prop where aeconst_set ⦃s : Set α⦄ : MeasurableSet s → f ⁻¹' s = s → EventuallyConst s (ae μ) /-- A map `f : α → α` is said to be ergodic with respect to a measure `μ` if it is measure preserving and pre-ergodic. -/ structure Ergodic (f : α → α) (μ : Measure α := by volume_tac) : Prop extends MeasurePreserving f μ μ, PreErgodic f μ /-- A map `f : α → α` is said to be quasi-ergodic with respect to a measure `μ` if it is quasi-measure-preserving and pre-ergodic. -/ structure QuasiErgodic (f : α → α) (μ : Measure α := by volume_tac) : Prop extends QuasiMeasurePreserving f μ μ, PreErgodic f μ variable {f : α → α} {μ : Measure α} namespace PreErgodic theorem ae_empty_or_univ (hf : PreErgodic f μ) (hs : MeasurableSet s) (hfs : f ⁻¹' s = s) : s =ᵐ[μ] (∅ : Set α) ∨ s =ᵐ[μ] univ := by simpa only [eventuallyConst_set'] using hf.aeconst_set hs hfs theorem measure_self_or_compl_eq_zero (hf : PreErgodic f μ) (hs : MeasurableSet s) (hs' : f ⁻¹' s = s) : μ s = 0 ∨ μ sᶜ = 0 := by simpa using hf.ae_empty_or_univ hs hs' theorem ae_mem_or_ae_notMem (hf : PreErgodic f μ) (hsm : MeasurableSet s) (hs : f ⁻¹' s = s) : (∀ᵐ x ∂μ, x ∈ s) ∨ ∀ᵐ x ∂μ, x ∉ s := eventuallyConst_set.1 <| hf.aeconst_set hsm hs @[deprecated (since := "2025-05-24")] alias ae_mem_or_ae_nmem := ae_mem_or_ae_notMem /-- On a probability space, the (pre)ergodicity condition is a zero one law. -/ theorem prob_eq_zero_or_one [IsProbabilityMeasure μ] (hf : PreErgodic f μ) (hs : MeasurableSet s) (hs' : f ⁻¹' s = s) : μ s = 0 ∨ μ s = 1 := by simpa [hs] using hf.measure_self_or_compl_eq_zero hs hs' theorem of_iterate (n : ℕ) (hf : PreErgodic f^[n] μ) : PreErgodic f μ := ⟨fun _ hs hs' => hf.aeconst_set hs <| IsFixedPt.preimage_iterate hs' n⟩ theorem smul_measure {R : Type*} [SMul R ℝ≥0∞] [IsScalarTower R ℝ≥0∞ ℝ≥0∞] (hf : PreErgodic f μ) (c : R) : PreErgodic f (c • μ) where aeconst_set _s hs hfs := (hf.aeconst_set hs hfs).anti <| ae_smul_measure_le _ theorem zero_measure (f : α → α) : @PreErgodic α m f 0 where aeconst_set _ _ _ := by simp end PreErgodic namespace MeasureTheory.MeasurePreserving variable {β : Type*} {m' : MeasurableSpace β} {μ' : Measure β} {g : α → β} theorem preErgodic_of_preErgodic_conjugate (hg : MeasurePreserving g μ μ') (hf : PreErgodic f μ) {f' : β → β} (h_comm : Semiconj g f f') : PreErgodic f' μ' where aeconst_set s hs₀ hs₁ := by rw [← hg.aeconst_preimage hs₀.nullMeasurableSet] apply hf.aeconst_set (hg.measurable hs₀) rw [← preimage_comp, h_comm.comp_eq, preimage_comp, hs₁] theorem preErgodic_conjugate_iff {e : α ≃ᵐ β} (h : MeasurePreserving e μ μ') : PreErgodic (e ∘ f ∘ e.symm) μ' ↔ PreErgodic f μ := by refine ⟨fun hf => preErgodic_of_preErgodic_conjugate (h.symm e) hf ?_, fun hf => preErgodic_of_preErgodic_conjugate h hf ?_⟩ · simp [Semiconj] · simp [Semiconj] theorem ergodic_conjugate_iff {e : α ≃ᵐ β} (h : MeasurePreserving e μ μ') : Ergodic (e ∘ f ∘ e.symm) μ' ↔ Ergodic f μ := by have : MeasurePreserving (e ∘ f ∘ e.symm) μ' μ' ↔ MeasurePreserving f μ μ := by rw [h.comp_left_iff, (MeasurePreserving.symm e h).comp_right_iff] replace h : PreErgodic (e ∘ f ∘ e.symm) μ' ↔ PreErgodic f μ := h.preErgodic_conjugate_iff exact ⟨fun hf => { this.mp hf.toMeasurePreserving, h.mp hf.toPreErgodic with }, fun hf => { this.mpr hf.toMeasurePreserving, h.mpr hf.toPreErgodic with }⟩ end MeasureTheory.MeasurePreserving namespace QuasiErgodic theorem aeconst_set₀ (hf : QuasiErgodic f μ) (hsm : NullMeasurableSet s μ) (hs : f ⁻¹' s =ᵐ[μ] s) : EventuallyConst s (ae μ) := let ⟨_t, h₀, h₁, h₂⟩ := hf.toQuasiMeasurePreserving.exists_preimage_eq_of_preimage_ae hsm hs (hf.aeconst_set h₀ h₂).congr h₁ /-- For a quasi-ergodic map, sets that are almost invariant (rather than strictly invariant) are still either almost empty or full. -/ theorem ae_empty_or_univ₀ (hf : QuasiErgodic f μ) (hsm : NullMeasurableSet s μ) (hs : f ⁻¹' s =ᵐ[μ] s) : s =ᵐ[μ] (∅ : Set α) ∨ s =ᵐ[μ] univ := eventuallyConst_set'.mp <| hf.aeconst_set₀ hsm hs /-- For a quasi-ergodic map, sets that are almost invariant (rather than strictly invariant) are still either almost empty or full. -/ theorem ae_mem_or_ae_notMem₀ (hf : QuasiErgodic f μ) (hsm : NullMeasurableSet s μ) (hs : f ⁻¹' s =ᵐ[μ] s) : (∀ᵐ x ∂μ, x ∈ s) ∨ ∀ᵐ x ∂μ, x ∉ s := eventuallyConst_set.mp <| hf.aeconst_set₀ hsm hs @[deprecated (since := "2025-05-24")] alias ae_mem_or_ae_nmem₀ := ae_mem_or_ae_notMem₀ theorem smul_measure {R : Type*} [SMul R ℝ≥0∞] [IsScalarTower R ℝ≥0∞ ℝ≥0∞] (hf : QuasiErgodic f μ) (c : R) : QuasiErgodic f (c • μ) := ⟨hf.1.smul_measure _, hf.2.smul_measure _⟩ theorem zero_measure {f : α → α} (hf : Measurable f) : @QuasiErgodic α m f 0 where measurable := hf absolutelyContinuous := by simp toPreErgodic := .zero_measure f end QuasiErgodic namespace Ergodic /-- An ergodic map is quasi-ergodic. -/ theorem quasiErgodic (hf : Ergodic f μ) : QuasiErgodic f μ := { hf.toPreErgodic, hf.toMeasurePreserving.quasiMeasurePreserving with } /-- See also `Ergodic.ae_empty_or_univ_of_preimage_ae_le`. -/ theorem ae_empty_or_univ_of_preimage_ae_le' (hf : Ergodic f μ) (hs : NullMeasurableSet s μ) (hs' : f ⁻¹' s ≤ᵐ[μ] s) (h_fin : μ s ≠ ∞) : s =ᵐ[μ] (∅ : Set α) ∨ s =ᵐ[μ] univ := by refine hf.quasiErgodic.ae_empty_or_univ₀ hs ?_ refine ae_eq_of_ae_subset_of_measure_ge hs' (hf.measure_preimage hs).ge ?_ h_fin exact hs.preimage hf.quasiMeasurePreserving /-- See also `Ergodic.ae_empty_or_univ_of_ae_le_preimage`. -/ theorem ae_empty_or_univ_of_ae_le_preimage' (hf : Ergodic f μ) (hs : NullMeasurableSet s μ) (hs' : s ≤ᵐ[μ] f ⁻¹' s) (h_fin : μ s ≠ ∞) : s =ᵐ[μ] (∅ : Set α) ∨ s =ᵐ[μ] univ := by replace h_fin : μ (f ⁻¹' s) ≠ ∞ := by rwa [hf.measure_preimage hs] refine hf.quasiErgodic.ae_empty_or_univ₀ hs ?_ exact (ae_eq_of_ae_subset_of_measure_ge hs' (hf.measure_preimage hs).le hs h_fin).symm /-- See also `Ergodic.ae_empty_or_univ_of_image_ae_le`. -/ theorem ae_empty_or_univ_of_image_ae_le' (hf : Ergodic f μ) (hs : NullMeasurableSet s μ) (hs' : f '' s ≤ᵐ[μ] s) (h_fin : μ s ≠ ∞) : s =ᵐ[μ] (∅ : Set α) ∨ s =ᵐ[μ] univ := by replace hs' : s ≤ᵐ[μ] f ⁻¹' s := (HasSubset.Subset.eventuallyLE (subset_preimage_image f s)).trans (hf.quasiMeasurePreserving.preimage_mono_ae hs') exact ae_empty_or_univ_of_ae_le_preimage' hf hs hs' h_fin /-- If a measurable equivalence is ergodic, then so is the inverse map. -/ theorem symm {e : α ≃ᵐ α} (he : Ergodic e μ) : Ergodic e.symm μ where toMeasurePreserving := he.toMeasurePreserving.symm aeconst_set s hsm hs := he.aeconst_set hsm <| by conv_lhs => rw [← hs, ← e.image_eq_preimage_symm, e.preimage_image] @[simp] theorem symm_iff {e : α ≃ᵐ α} : Ergodic e.symm μ ↔ Ergodic e μ := ⟨.symm, .symm⟩ theorem smul_measure {R : Type*} [SMul R ℝ≥0∞] [IsScalarTower R ℝ≥0∞ ℝ≥0∞] (hf : Ergodic f μ) (c : R) : Ergodic f (c • μ) := ⟨hf.1.smul_measure _, hf.2.smul_measure _⟩ theorem zero_measure {f : α → α} (hf : Measurable f) : @Ergodic α m f 0 where measurable := hf map_eq := by simp toPreErgodic := .zero_measure f section IsFiniteMeasure variable [IsFiniteMeasure μ] theorem ae_empty_or_univ_of_preimage_ae_le (hf : Ergodic f μ) (hs : NullMeasurableSet s μ) (hs' : f ⁻¹' s ≤ᵐ[μ] s) : s =ᵐ[μ] (∅ : Set α) ∨ s =ᵐ[μ] univ := ae_empty_or_univ_of_preimage_ae_le' hf hs hs' <| measure_ne_top μ s theorem ae_empty_or_univ_of_ae_le_preimage (hf : Ergodic f μ) (hs : NullMeasurableSet s μ) (hs' : s ≤ᵐ[μ] f ⁻¹' s) : s =ᵐ[μ] (∅ : Set α) ∨ s =ᵐ[μ] univ := ae_empty_or_univ_of_ae_le_preimage' hf hs hs' <| measure_ne_top μ s theorem ae_empty_or_univ_of_image_ae_le (hf : Ergodic f μ) (hs : NullMeasurableSet s μ) (hs' : f '' s ≤ᵐ[μ] s) : s =ᵐ[μ] (∅ : Set α) ∨ s =ᵐ[μ] univ := ae_empty_or_univ_of_image_ae_le' hf hs hs' <| measure_ne_top μ s end IsFiniteMeasure end Ergodic
.lake/packages/mathlib/Mathlib/Dynamics/Ergodic/Conservative.lean
import Mathlib.MeasureTheory.Constructions.BorelSpace.Basic import Mathlib.Dynamics.Ergodic.MeasurePreserving import Mathlib.Combinatorics.Pigeonhole /-! # Conservative systems In this file we define `f : α → α` to be a *conservative* system w.r.t. a measure `μ` if `f` is non-singular (`MeasureTheory.QuasiMeasurePreserving`) and for every measurable set `s` of positive measure at least one point `x ∈ s` returns back to `s` after some number of iterations of `f`. There are several properties that look like they are stronger than this one but actually follow from it: * `MeasureTheory.Conservative.frequently_measure_inter_ne_zero`, `MeasureTheory.Conservative.exists_gt_measure_inter_ne_zero`: if `μ s ≠ 0`, then for infinitely many `n`, the measure of `s ∩ f^[n] ⁻¹' s` is positive. * `MeasureTheory.Conservative.measure_mem_forall_ge_image_notMem_eq_zero`, `MeasureTheory.Conservative.ae_mem_imp_frequently_image_mem`: a.e. every point of `s` visits `s` infinitely many times (Poincaré recurrence theorem). We also prove the topological Poincaré recurrence theorem `MeasureTheory.Conservative.ae_frequently_mem_of_mem_nhds`. Let `f : α → α` be a conservative dynamical system on a topological space with second countable topology and measurable open sets. Then almost every point `x : α` is recurrent: it visits every neighborhood `s ∈ 𝓝 x` infinitely many times. ## Tags conservative dynamical system, Poincare recurrence theorem -/ noncomputable section namespace MeasureTheory open Set Filter Finset Function TopologicalSpace Topology variable {α : Type*} [MeasurableSpace α] {f : α → α} {s : Set α} {μ : Measure α} open Measure /-- We say that a non-singular (`MeasureTheory.QuasiMeasurePreserving`) self-map is *conservative* if for any measurable set `s` of positive measure there exists `x ∈ s` such that `x` returns back to `s` under some iteration of `f`. -/ structure Conservative (f : α → α) (μ : Measure α) : Prop extends QuasiMeasurePreserving f μ μ where /-- If `f` is a conservative self-map and `s` is a measurable set of nonzero measure, then there exists a point `x ∈ s` that returns to `s` under a non-zero iteration of `f`. -/ exists_mem_iterate_mem' : ∀ ⦃s⦄, MeasurableSet s → μ s ≠ 0 → ∃ x ∈ s, ∃ m ≠ 0, f^[m] x ∈ s /-- A self-map preserving a finite measure is conservative. -/ protected theorem MeasurePreserving.conservative [IsFiniteMeasure μ] (h : MeasurePreserving f μ μ) : Conservative f μ := ⟨h.quasiMeasurePreserving, fun _ hsm h0 => h.exists_mem_iterate_mem hsm.nullMeasurableSet h0⟩ namespace Conservative /-- The identity map is conservative w.r.t. any measure. -/ protected theorem id (μ : Measure α) : Conservative id μ := { toQuasiMeasurePreserving := QuasiMeasurePreserving.id μ exists_mem_iterate_mem' := fun _ _ h0 => by simpa [exists_ne] using nonempty_of_measure_ne_zero h0 } theorem of_absolutelyContinuous {ν : Measure α} (h : Conservative f μ) (hν : ν ≪ μ) (h' : QuasiMeasurePreserving f ν ν) : Conservative f ν := ⟨h', fun _ hsm h0 ↦ h.exists_mem_iterate_mem' hsm (mt (@hν _) h0)⟩ /-- Restriction of a conservative system to an invariant set is a conservative system, formulated in terms of the restriction of the measure. -/ theorem measureRestrict (h : Conservative f μ) (hs : MapsTo f s s) : Conservative f (μ.restrict s) := .of_absolutelyContinuous h (absolutelyContinuous_of_le restrict_le_self) <| h.toQuasiMeasurePreserving.restrict hs theorem congr_ae {ν : Measure α} (hf : Conservative f μ) (h : ae μ = ae ν) : Conservative f ν := .of_absolutelyContinuous hf h.ge.absolutelyContinuous_of_ae <| hf.toQuasiMeasurePreserving.mono h.ge.absolutelyContinuous_of_ae h.le.absolutelyContinuous_of_ae theorem _root_.MeasureTheory.conservative_congr {ν : Measure α} (h : ae μ = ae ν) : Conservative f μ ↔ Conservative f ν := ⟨(congr_ae · h), (congr_ae · h.symm)⟩ /-- If `f` is a conservative self-map and `s` is a null measurable set of nonzero measure, then there exists a point `x ∈ s` that returns to `s` under a non-zero iteration of `f`. -/ theorem exists_mem_iterate_mem (hf : Conservative f μ) (hsm : NullMeasurableSet s μ) (hs₀ : μ s ≠ 0) : ∃ x ∈ s, ∃ m ≠ 0, f^[m] x ∈ s := by rcases hsm.exists_measurable_subset_ae_eq with ⟨t, hsub, htm, hts⟩ rcases hf.exists_mem_iterate_mem' htm (by rwa [measure_congr hts]) with ⟨x, hxt, m, hm₀, hmt⟩ exact ⟨x, hsub hxt, m, hm₀, hsub hmt⟩ /-- If `f` is a conservative map and `s` is a measurable set of nonzero measure, then for infinitely many values of `m` a positive measure of points `x ∈ s` returns back to `s` after `m` iterations of `f`. -/ theorem frequently_measure_inter_ne_zero (hf : Conservative f μ) (hs : NullMeasurableSet s μ) (h0 : μ s ≠ 0) : ∃ᶠ m in atTop, μ (s ∩ f^[m] ⁻¹' s) ≠ 0 := by set t : ℕ → Set α := fun n ↦ s ∩ f^[n] ⁻¹' s -- Assume that `μ (t n) ≠ 0`, where `t n = s ∩ f^[n] ⁻¹' s`, only for finitely many `n`. by_contra H -- Let `N` be the maximal `n` such that `μ (t n) ≠ 0`. obtain ⟨N, hN, hmax⟩ : ∃ N, μ (t N) ≠ 0 ∧ ∀ n > N, μ (t n) = 0 := by rw [Nat.frequently_atTop_iff_infinite, not_infinite] at H convert exists_max_image _ (·) H ⟨0, by simpa⟩ using 4 rw [gt_iff_lt, ← not_le, not_imp_comm, mem_setOf] have htm {n : ℕ} : NullMeasurableSet (t n) μ := hs.inter <| hs.preimage <| hf.toQuasiMeasurePreserving.iterate n -- Then all `t n`, `n > N`, are null sets, hence `T = t N \ ⋃ n > N, t n` has positive measure. set T := t N \ ⋃ n > N, t n with hT have hμT : μ T ≠ 0 := by rwa [hT, measure_diff_null] exact (measure_biUnion_null_iff {n | N < n}.to_countable).2 hmax have hTm : NullMeasurableSet T μ := htm.diff <| .biUnion {n | N < n}.to_countable fun _ _ ↦ htm -- Take `x ∈ T` and `m ≠ 0` such that `f^[m] x ∈ T`. rcases hf.exists_mem_iterate_mem hTm hμT with ⟨x, hxt, m, hm₀, hmt⟩ -- Then `N + m > N`, `x ∈ s`, and `f^[N + m] x = f^[N] (f^[m] x) ∈ s`. -- This contradicts `x ∈ T ⊆ (⋃ n > N, t n)ᶜ`. refine hxt.2 <| mem_iUnion₂.2 ⟨N + m, ?_, hxt.1.1, ?_⟩ · simpa [pos_iff_ne_zero] · simpa only [iterate_add] using hmt.1.2 /-- If `f` is a conservative map and `s` is a measurable set of nonzero measure, then for an arbitrarily large `m` a positive measure of points `x ∈ s` returns back to `s` after `m` iterations of `f`. -/ theorem exists_gt_measure_inter_ne_zero (hf : Conservative f μ) (hs : NullMeasurableSet s μ) (h0 : μ s ≠ 0) (N : ℕ) : ∃ m > N, μ (s ∩ f^[m] ⁻¹' s) ≠ 0 := let ⟨m, hm, hmN⟩ := ((hf.frequently_measure_inter_ne_zero hs h0).and_eventually (eventually_gt_atTop N)).exists ⟨m, hmN, hm⟩ /-- Poincaré recurrence theorem: given a conservative map `f` and a measurable set `s`, the set of points `x ∈ s` such that `x` does not return to `s` after `≥ n` iterations has measure zero. -/ theorem measure_mem_forall_ge_image_notMem_eq_zero (hf : Conservative f μ) (hs : NullMeasurableSet s μ) (n : ℕ) : μ ({ x ∈ s | ∀ m ≥ n, f^[m] x ∉ s }) = 0 := by by_contra H have : NullMeasurableSet (s ∩ { x | ∀ m ≥ n, f^[m] x ∉ s }) μ := by simp only [setOf_forall, ← compl_setOf] exact hs.inter <| .biInter (to_countable _) fun m _ ↦ (hs.preimage <| hf.toQuasiMeasurePreserving.iterate m).compl rcases (hf.exists_gt_measure_inter_ne_zero this H) n with ⟨m, hmn, hm⟩ rcases nonempty_of_measure_ne_zero hm with ⟨x, ⟨_, hxn⟩, hxm, -⟩ exact hxn m hmn.lt.le hxm @[deprecated (since := "2025-05-23")] alias measure_mem_forall_ge_image_not_mem_eq_zero := measure_mem_forall_ge_image_notMem_eq_zero /-- Poincaré recurrence theorem: given a conservative map `f` and a measurable set `s`, almost every point `x ∈ s` returns back to `s` infinitely many times. -/ theorem ae_mem_imp_frequently_image_mem (hf : Conservative f μ) (hs : NullMeasurableSet s μ) : ∀ᵐ x ∂μ, x ∈ s → ∃ᶠ n in atTop, f^[n] x ∈ s := by simp only [frequently_atTop, @forall_swap (_ ∈ s), ae_all_iff] intro n filter_upwards [ measure_eq_zero_iff_ae_notMem.1 (hf.measure_mem_forall_ge_image_notMem_eq_zero hs n)] simp theorem inter_frequently_image_mem_ae_eq (hf : Conservative f μ) (hs : NullMeasurableSet s μ) : (s ∩ { x | ∃ᶠ n in atTop, f^[n] x ∈ s } : Set α) =ᵐ[μ] s := inter_eventuallyEq_left.2 <| hf.ae_mem_imp_frequently_image_mem hs theorem measure_inter_frequently_image_mem_eq (hf : Conservative f μ) (hs : NullMeasurableSet s μ) : μ (s ∩ { x | ∃ᶠ n in atTop, f^[n] x ∈ s }) = μ s := measure_congr (hf.inter_frequently_image_mem_ae_eq hs) /-- Poincaré recurrence theorem: if `f` is a conservative dynamical system and `s` is a measurable set, then for `μ`-a.e. `x`, if the orbit of `x` visits `s` at least once, then it visits `s` infinitely many times. -/ theorem ae_forall_image_mem_imp_frequently_image_mem (hf : Conservative f μ) (hs : NullMeasurableSet s μ) : ∀ᵐ x ∂μ, ∀ k, f^[k] x ∈ s → ∃ᶠ n in atTop, f^[n] x ∈ s := by refine ae_all_iff.2 fun k => ?_ refine (hf.ae_mem_imp_frequently_image_mem (hs.preimage <| hf.toQuasiMeasurePreserving.iterate k)).mono fun x hx hk => ?_ rw [← map_add_atTop_eq_nat k, frequently_map] refine (hx hk).mono fun n hn => ?_ rwa [add_comm, iterate_add_apply] /-- If `f` is a conservative self-map and `s` is a measurable set of positive measure, then `ae μ`-frequently we have `x ∈ s` and `s` returns to `s` under infinitely many iterations of `f`. -/ theorem frequently_ae_mem_and_frequently_image_mem (hf : Conservative f μ) (hs : NullMeasurableSet s μ) (h0 : μ s ≠ 0) : ∃ᵐ x ∂μ, x ∈ s ∧ ∃ᶠ n in atTop, f^[n] x ∈ s := ((frequently_ae_mem_iff.2 h0).and_eventually (hf.ae_mem_imp_frequently_image_mem hs)).mono fun _ hx => ⟨hx.1, hx.2 hx.1⟩ /-- Poincaré recurrence theorem. Let `f : α → α` be a conservative dynamical system on a topological space with second countable topology and measurable open sets. Then almost every point `x : α` is recurrent: it visits every neighborhood `s ∈ 𝓝 x` infinitely many times. -/ theorem ae_frequently_mem_of_mem_nhds [TopologicalSpace α] [SecondCountableTopology α] [OpensMeasurableSpace α] {f : α → α} {μ : Measure α} (h : Conservative f μ) : ∀ᵐ x ∂μ, ∀ s ∈ 𝓝 x, ∃ᶠ n in atTop, f^[n] x ∈ s := by have : ∀ s ∈ countableBasis α, ∀ᵐ x ∂μ, x ∈ s → ∃ᶠ n in atTop, f^[n] x ∈ s := fun s hs => h.ae_mem_imp_frequently_image_mem (isOpen_of_mem_countableBasis hs).nullMeasurableSet refine ((ae_ball_iff <| countable_countableBasis α).2 this).mono fun x hx s hs => ?_ rcases (isBasis_countableBasis α).mem_nhds_iff.1 hs with ⟨o, hoS, hxo, hos⟩ exact (hx o hoS hxo).mono fun n hn => hos hn /-- Iteration of a conservative system is a conservative system. -/ protected theorem iterate (hf : Conservative f μ) (n : ℕ) : Conservative f^[n] μ := by -- Discharge the trivial case `n = 0` rcases n with - | n · exact Conservative.id μ refine ⟨hf.1.iterate _, fun s hs hs0 => ?_⟩ rcases (hf.frequently_ae_mem_and_frequently_image_mem hs.nullMeasurableSet hs0).exists with ⟨x, _, hx⟩ /- We take a point `x ∈ s` such that `f^[k] x ∈ s` for infinitely many values of `k`, then we choose two of these values `k < l` such that `k ≡ l [MOD (n + 1)]`. Then `f^[k] x ∈ s` and `f^[n + 1]^[(l - k) / (n + 1)] (f^[k] x) = f^[l] x ∈ s`. -/ rw [Nat.frequently_atTop_iff_infinite] at hx rcases Nat.exists_lt_modEq_of_infinite hx n.succ_pos with ⟨k, hk, l, hl, hkl, hn⟩ set m := (l - k) / (n + 1) have : (n + 1) * m = l - k := by apply Nat.mul_div_cancel' exact (Nat.modEq_iff_dvd' hkl.le).1 hn refine ⟨f^[k] x, hk, m, ?_, ?_⟩ · intro hm rw [hm, mul_zero, eq_comm, tsub_eq_zero_iff_le] at this exact this.not_gt hkl · rwa [← iterate_mul, this, ← iterate_add_apply, tsub_add_cancel_of_le] exact hkl.le end Conservative end MeasureTheory