Context
stringlengths
227
76.5k
target
stringlengths
0
11.6k
file_name
stringlengths
21
79
start
int64
14
3.67k
end
int64
16
3.69k
/- Copyright (c) 2022 Violeta Hernández Palacios. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Violeta Hernández Palacios -/ import Mathlib.Algebra.Polynomial.Cardinal import Mathlib.RingTheory.Algebraic.Basic /-! ### Cardinality of algebraic numbers In this file, we prove variants of the following result: the cardinality of algebraic numbers under an R-algebra is at most `#R[X] * ℵ₀`. Although this can be used to prove that real or complex transcendental numbers exist, a more direct proof is given by `Liouville.transcendental`. -/ universe u v open Cardinal Polynomial Set open Cardinal Polynomial namespace Algebraic theorem infinite_of_charZero (R A : Type*) [CommRing R] [Ring A] [Algebra R A] [CharZero A] : { x : A | IsAlgebraic R x }.Infinite := by letI := MulActionWithZero.nontrivial R A exact infinite_of_injective_forall_mem Nat.cast_injective isAlgebraic_nat theorem aleph0_le_cardinalMk_of_charZero (R A : Type*) [CommRing R] [Ring A] [Algebra R A] [CharZero A] : ℵ₀ ≤ #{ x : A // IsAlgebraic R x } := infinite_iff.1 (Set.infinite_coe_iff.2 <| infinite_of_charZero R A) @[deprecated (since := "2024-11-10")] alias aleph0_le_cardinal_mk_of_charZero := aleph0_le_cardinalMk_of_charZero section lift variable (R : Type u) (A : Type v) [CommRing R] [CommRing A] [IsDomain A] [Algebra R A] [NoZeroSMulDivisors R A] theorem cardinalMk_lift_le_mul : Cardinal.lift.{u} #{ x : A // IsAlgebraic R x } ≤ Cardinal.lift.{v} #R[X] * ℵ₀ := by rw [← mk_uLift, ← mk_uLift] choose g hg₁ hg₂ using fun x : { x : A | IsAlgebraic R x } => x.coe_prop refine lift_mk_le_lift_mk_mul_of_lift_mk_preimage_le g fun f => ?_ rw [lift_le_aleph0, le_aleph0_iff_set_countable] suffices MapsTo (↑) (g ⁻¹' {f}) (f.rootSet A) from this.countable_of_injOn Subtype.coe_injective.injOn (f.rootSet_finite A).countable rintro x (rfl : g x = f) exact mem_rootSet.2 ⟨hg₁ x, hg₂ x⟩ @[deprecated (since := "2024-11-10")] alias cardinal_mk_lift_le_mul := cardinalMk_lift_le_mul theorem cardinalMk_lift_le_max : Cardinal.lift.{u} #{ x : A // IsAlgebraic R x } ≤ max (Cardinal.lift.{v} #R) ℵ₀ := (cardinalMk_lift_le_mul R A).trans <| (mul_le_mul_right' (lift_le.2 cardinalMk_le_max) _).trans <| by simp @[deprecated (since := "2024-11-10")] alias cardinal_mk_lift_le_max := cardinalMk_lift_le_max @[simp] theorem cardinalMk_lift_of_infinite [Infinite R] : Cardinal.lift.{u} #{ x : A // IsAlgebraic R x } = Cardinal.lift.{v} #R := ((cardinalMk_lift_le_max R A).trans_eq (max_eq_left <| aleph0_le_mk _)).antisymm <| lift_mk_le'.2 ⟨⟨fun x => ⟨algebraMap R A x, isAlgebraic_algebraMap _⟩, fun _ _ h => FaithfulSMul.algebraMap_injective R A (Subtype.ext_iff.1 h)⟩⟩ @[deprecated (since := "2024-11-10")] alias cardinal_mk_lift_of_infinite := cardinalMk_lift_of_infinite variable [Countable R] @[simp] protected theorem countable : Set.Countable { x : A | IsAlgebraic R x } := by rw [← le_aleph0_iff_set_countable, ← lift_le_aleph0] apply (cardinalMk_lift_le_max R A).trans simp @[simp] theorem cardinalMk_of_countable_of_charZero [CharZero A] : #{ x : A // IsAlgebraic R x } = ℵ₀ := (Algebraic.countable R A).le_aleph0.antisymm (aleph0_le_cardinalMk_of_charZero R A) @[deprecated (since := "2024-11-10")] alias cardinal_mk_of_countable_of_charZero := cardinalMk_of_countable_of_charZero end lift
section NonLift variable (R A : Type u) [CommRing R] [CommRing A] [IsDomain A] [Algebra R A]
Mathlib/Algebra/AlgebraicCard.lean
93
95
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Floris van Doorn -/ import Mathlib.Data.Countable.Small import Mathlib.Data.Fintype.BigOperators import Mathlib.Data.Fintype.Powerset import Mathlib.Data.Nat.Cast.Order.Basic import Mathlib.Data.Set.Countable import Mathlib.Logic.Equiv.Fin.Basic import Mathlib.Logic.Small.Set import Mathlib.Logic.UnivLE import Mathlib.SetTheory.Cardinal.Order /-! # Basic results on cardinal numbers We provide a collection of basic results on cardinal numbers, in particular focussing on finite/countable/small types and sets. ## Main definitions * `Cardinal.powerlt a b` or `a ^< b` is defined as the supremum of `a ^ c` for `c < b`. ## References * <https://en.wikipedia.org/wiki/Cardinal_number> ## Tags cardinal number, cardinal arithmetic, cardinal exponentiation, aleph, Cantor's theorem, König's theorem, Konig's theorem -/ assert_not_exists Field open List (Vector) open Function Order Set noncomputable section universe u v w v' w' variable {α β : Type u} namespace Cardinal /-! ### Lifting cardinals to a higher universe -/ @[simp] lemma mk_preimage_down {s : Set α} : #(ULift.down.{v} ⁻¹' s) = lift.{v} (#s) := by rw [← mk_uLift, Cardinal.eq] constructor let f : ULift.down ⁻¹' s → ULift s := fun x ↦ ULift.up (restrictPreimage s ULift.down x) have : Function.Bijective f := ULift.up_bijective.comp (restrictPreimage_bijective _ (ULift.down_bijective)) exact Equiv.ofBijective f this -- `simp` can't figure out universe levels: normal form is `lift_mk_shrink'`. theorem lift_mk_shrink (α : Type u) [Small.{v} α] : Cardinal.lift.{max u w} #(Shrink.{v} α) = Cardinal.lift.{max v w} #α := lift_mk_eq.2 ⟨(equivShrink α).symm⟩ @[simp] theorem lift_mk_shrink' (α : Type u) [Small.{v} α] : Cardinal.lift.{u} #(Shrink.{v} α) = Cardinal.lift.{v} #α := lift_mk_shrink.{u, v, 0} α @[simp] theorem lift_mk_shrink'' (α : Type max u v) [Small.{v} α] : Cardinal.lift.{u} #(Shrink.{v} α) = #α := by rw [← lift_umax, lift_mk_shrink.{max u v, v, 0} α, ← lift_umax, lift_id] theorem prod_eq_of_fintype {α : Type u} [h : Fintype α] (f : α → Cardinal.{v}) : prod f = Cardinal.lift.{u} (∏ i, f i) := by revert f refine Fintype.induction_empty_option ?_ ?_ ?_ α (h_fintype := h) · intro α β hβ e h f letI := Fintype.ofEquiv β e.symm rw [← e.prod_comp f, ← h] exact mk_congr (e.piCongrLeft _).symm · intro f rw [Fintype.univ_pempty, Finset.prod_empty, lift_one, Cardinal.prod, mk_eq_one] · intro α hα h f rw [Cardinal.prod, mk_congr Equiv.piOptionEquivProd, mk_prod, lift_umax.{v, u}, mk_out, ← Cardinal.prod, lift_prod, Fintype.prod_option, lift_mul, ← h fun a => f (some a)] simp only [lift_id] /-! ### Basic cardinals -/ theorem le_one_iff_subsingleton {α : Type u} : #α ≤ 1 ↔ Subsingleton α := ⟨fun ⟨f⟩ => ⟨fun _ _ => f.injective (Subsingleton.elim _ _)⟩, fun ⟨h⟩ => ⟨fun _ => ULift.up 0, fun _ _ _ => h _ _⟩⟩ @[simp] theorem mk_le_one_iff_set_subsingleton {s : Set α} : #s ≤ 1 ↔ s.Subsingleton := le_one_iff_subsingleton.trans s.subsingleton_coe alias ⟨_, _root_.Set.Subsingleton.cardinalMk_le_one⟩ := mk_le_one_iff_set_subsingleton @[deprecated (since := "2024-11-10")] alias _root_.Set.Subsingleton.cardinal_mk_le_one := Set.Subsingleton.cardinalMk_le_one private theorem cast_succ (n : ℕ) : ((n + 1 : ℕ) : Cardinal.{u}) = n + 1 := by change #(ULift.{u} _) = #(ULift.{u} _) + 1 rw [← mk_option] simp /-! ### Order properties -/ theorem one_lt_iff_nontrivial {α : Type u} : 1 < #α ↔ Nontrivial α := by rw [← not_le, le_one_iff_subsingleton, ← not_nontrivial_iff_subsingleton, Classical.not_not] lemma sInf_eq_zero_iff {s : Set Cardinal} : sInf s = 0 ↔ s = ∅ ∨ ∃ a ∈ s, a = 0 := by refine ⟨fun h ↦ ?_, fun h ↦ ?_⟩ · rcases s.eq_empty_or_nonempty with rfl | hne · exact Or.inl rfl · exact Or.inr ⟨sInf s, csInf_mem hne, h⟩ · rcases h with rfl | ⟨a, ha, rfl⟩ · exact Cardinal.sInf_empty · exact eq_bot_iff.2 (csInf_le' ha) lemma iInf_eq_zero_iff {ι : Sort*} {f : ι → Cardinal} : (⨅ i, f i) = 0 ↔ IsEmpty ι ∨ ∃ i, f i = 0 := by simp [iInf, sInf_eq_zero_iff] /-- A variant of `ciSup_of_empty` but with `0` on the RHS for convenience -/ protected theorem iSup_of_empty {ι} (f : ι → Cardinal) [IsEmpty ι] : iSup f = 0 := ciSup_of_empty f @[simp] theorem lift_sInf (s : Set Cardinal) : lift.{u, v} (sInf s) = sInf (lift.{u, v} '' s) := by rcases eq_empty_or_nonempty s with (rfl | hs) · simp · exact lift_monotone.map_csInf hs @[simp] theorem lift_iInf {ι} (f : ι → Cardinal) : lift.{u, v} (iInf f) = ⨅ i, lift.{u, v} (f i) := by unfold iInf convert lift_sInf (range f) simp_rw [← comp_apply (f := lift), range_comp] end Cardinal /-! ### Small sets of cardinals -/ namespace Cardinal instance small_Iic (a : Cardinal.{u}) : Small.{u} (Iic a) := by rw [← mk_out a] apply @small_of_surjective (Set a.out) (Iic #a.out) _ fun x => ⟨#x, mk_set_le x⟩ rintro ⟨x, hx⟩ simpa using le_mk_iff_exists_set.1 hx instance small_Iio (a : Cardinal.{u}) : Small.{u} (Iio a) := small_subset Iio_subset_Iic_self instance small_Icc (a b : Cardinal.{u}) : Small.{u} (Icc a b) := small_subset Icc_subset_Iic_self instance small_Ico (a b : Cardinal.{u}) : Small.{u} (Ico a b) := small_subset Ico_subset_Iio_self instance small_Ioc (a b : Cardinal.{u}) : Small.{u} (Ioc a b) := small_subset Ioc_subset_Iic_self instance small_Ioo (a b : Cardinal.{u}) : Small.{u} (Ioo a b) := small_subset Ioo_subset_Iio_self /-- A set of cardinals is bounded above iff it's small, i.e. it corresponds to a usual ZFC set. -/ theorem bddAbove_iff_small {s : Set Cardinal.{u}} : BddAbove s ↔ Small.{u} s := ⟨fun ⟨a, ha⟩ => @small_subset _ (Iic a) s (fun _ h => ha h) _, by rintro ⟨ι, ⟨e⟩⟩ use sum.{u, u} fun x ↦ e.symm x intro a ha simpa using le_sum (fun x ↦ e.symm x) (e ⟨a, ha⟩)⟩ theorem bddAbove_of_small (s : Set Cardinal.{u}) [h : Small.{u} s] : BddAbove s := bddAbove_iff_small.2 h theorem bddAbove_range {ι : Type*} [Small.{u} ι] (f : ι → Cardinal.{u}) : BddAbove (Set.range f) := bddAbove_of_small _ theorem bddAbove_image (f : Cardinal.{u} → Cardinal.{max u v}) {s : Set Cardinal.{u}} (hs : BddAbove s) : BddAbove (f '' s) := by rw [bddAbove_iff_small] at hs ⊢ exact small_lift _ theorem bddAbove_range_comp {ι : Type u} {f : ι → Cardinal.{v}} (hf : BddAbove (range f)) (g : Cardinal.{v} → Cardinal.{max v w}) : BddAbove (range (g ∘ f)) := by rw [range_comp] exact bddAbove_image g hf /-- The type of cardinals in universe `u` is not `Small.{u}`. This is a version of the Burali-Forti paradox. -/ theorem _root_.not_small_cardinal : ¬ Small.{u} Cardinal.{max u v} := by intro h have := small_lift.{_, v} Cardinal.{max u v} rw [← small_univ_iff, ← bddAbove_iff_small] at this exact not_bddAbove_univ this instance uncountable : Uncountable Cardinal.{u} := Uncountable.of_not_small not_small_cardinal.{u} /-! ### Bounds on suprema -/ theorem sum_le_iSup_lift {ι : Type u} (f : ι → Cardinal.{max u v}) : sum f ≤ Cardinal.lift #ι * iSup f := by rw [← (iSup f).lift_id, ← lift_umax, lift_umax.{max u v, u}, ← sum_const] exact sum_le_sum _ _ (le_ciSup <| bddAbove_of_small _) theorem sum_le_iSup {ι : Type u} (f : ι → Cardinal.{u}) : sum f ≤ #ι * iSup f := by rw [← lift_id #ι] exact sum_le_iSup_lift f /-- The lift of a supremum is the supremum of the lifts. -/ theorem lift_sSup {s : Set Cardinal} (hs : BddAbove s) : lift.{u} (sSup s) = sSup (lift.{u} '' s) := by apply ((le_csSup_iff' (bddAbove_image.{_,u} _ hs)).2 fun c hc => _).antisymm (csSup_le' _) · intro c hc by_contra h obtain ⟨d, rfl⟩ := Cardinal.mem_range_lift_of_le (not_le.1 h).le simp_rw [lift_le] at h hc rw [csSup_le_iff' hs] at h exact h fun a ha => lift_le.1 <| hc (mem_image_of_mem _ ha) · rintro i ⟨j, hj, rfl⟩ exact lift_le.2 (le_csSup hs hj) /-- The lift of a supremum is the supremum of the lifts. -/ theorem lift_iSup {ι : Type v} {f : ι → Cardinal.{w}} (hf : BddAbove (range f)) : lift.{u} (iSup f) = ⨆ i, lift.{u} (f i) := by rw [iSup, iSup, lift_sSup hf, ← range_comp] simp [Function.comp_def] /-- To prove that the lift of a supremum is bounded by some cardinal `t`, it suffices to show that the lift of each cardinal is bounded by `t`. -/ theorem lift_iSup_le {ι : Type v} {f : ι → Cardinal.{w}} {t : Cardinal} (hf : BddAbove (range f)) (w : ∀ i, lift.{u} (f i) ≤ t) : lift.{u} (iSup f) ≤ t := by rw [lift_iSup hf] exact ciSup_le' w @[simp] theorem lift_iSup_le_iff {ι : Type v} {f : ι → Cardinal.{w}} (hf : BddAbove (range f)) {t : Cardinal} : lift.{u} (iSup f) ≤ t ↔ ∀ i, lift.{u} (f i) ≤ t := by rw [lift_iSup hf] exact ciSup_le_iff' (bddAbove_range_comp.{_,_,u} hf _) /-- To prove an inequality between the lifts to a common universe of two different supremums, it suffices to show that the lift of each cardinal from the smaller supremum if bounded by the lift of some cardinal from the larger supremum. -/ theorem lift_iSup_le_lift_iSup {ι : Type v} {ι' : Type v'} {f : ι → Cardinal.{w}} {f' : ι' → Cardinal.{w'}} (hf : BddAbove (range f)) (hf' : BddAbove (range f')) {g : ι → ι'} (h : ∀ i, lift.{w'} (f i) ≤ lift.{w} (f' (g i))) : lift.{w'} (iSup f) ≤ lift.{w} (iSup f') := by rw [lift_iSup hf, lift_iSup hf'] exact ciSup_mono' (bddAbove_range_comp.{_,_,w} hf' _) fun i => ⟨_, h i⟩ /-- A variant of `lift_iSup_le_lift_iSup` with universes specialized via `w = v` and `w' = v'`. This is sometimes necessary to avoid universe unification issues. -/ theorem lift_iSup_le_lift_iSup' {ι : Type v} {ι' : Type v'} {f : ι → Cardinal.{v}} {f' : ι' → Cardinal.{v'}} (hf : BddAbove (range f)) (hf' : BddAbove (range f')) (g : ι → ι') (h : ∀ i, lift.{v'} (f i) ≤ lift.{v} (f' (g i))) : lift.{v'} (iSup f) ≤ lift.{v} (iSup f') := lift_iSup_le_lift_iSup hf hf' h /-! ### Properties about the cast from `ℕ` -/ theorem mk_finset_of_fintype [Fintype α] : #(Finset α) = 2 ^ Fintype.card α := by simp [Pow.pow] @[norm_cast] theorem nat_succ (n : ℕ) : (n.succ : Cardinal) = succ ↑n := by rw [Nat.cast_succ] refine (add_one_le_succ _).antisymm (succ_le_of_lt ?_) rw [← Nat.cast_succ] exact Nat.cast_lt.2 (Nat.lt_succ_self _) lemma succ_natCast (n : ℕ) : Order.succ (n : Cardinal) = n + 1 := by rw [← Cardinal.nat_succ] norm_cast lemma natCast_add_one_le_iff {n : ℕ} {c : Cardinal} : n + 1 ≤ c ↔ n < c := by rw [← Order.succ_le_iff, Cardinal.succ_natCast] lemma two_le_iff_one_lt {c : Cardinal} : 2 ≤ c ↔ 1 < c := by convert natCast_add_one_le_iff norm_cast @[simp] theorem succ_zero : succ (0 : Cardinal) = 1 := by norm_cast -- This works generally to prove inequalities between numeric cardinals. theorem one_lt_two : (1 : Cardinal) < 2 := by norm_cast theorem exists_finset_le_card (α : Type*) (n : ℕ) (h : n ≤ #α) : ∃ s : Finset α, n ≤ s.card := by obtain hα|hα := finite_or_infinite α · let hα := Fintype.ofFinite α use Finset.univ simpa only [mk_fintype, Nat.cast_le] using h · obtain ⟨s, hs⟩ := Infinite.exists_subset_card_eq α n exact ⟨s, hs.ge⟩ theorem card_le_of {α : Type u} {n : ℕ} (H : ∀ s : Finset α, s.card ≤ n) : #α ≤ n := by contrapose! H apply exists_finset_le_card α (n+1) simpa only [nat_succ, succ_le_iff] using H theorem cantor' (a) {b : Cardinal} (hb : 1 < b) : a < b ^ a := by rw [← succ_le_iff, (by norm_cast : succ (1 : Cardinal) = 2)] at hb exact (cantor a).trans_le (power_le_power_right hb) theorem one_le_iff_pos {c : Cardinal} : 1 ≤ c ↔ 0 < c := by rw [← succ_zero, succ_le_iff] theorem one_le_iff_ne_zero {c : Cardinal} : 1 ≤ c ↔ c ≠ 0 := by rw [one_le_iff_pos, pos_iff_ne_zero] @[simp] theorem lt_one_iff_zero {c : Cardinal} : c < 1 ↔ c = 0 := by simpa using lt_succ_bot_iff (a := c) /-! ### Properties about `aleph0` -/ theorem nat_lt_aleph0 (n : ℕ) : (n : Cardinal.{u}) < ℵ₀ := succ_le_iff.1 (by rw [← nat_succ, ← lift_mk_fin, aleph0, lift_mk_le.{u}] exact ⟨⟨(↑), fun a b => Fin.ext⟩⟩) @[simp] theorem one_lt_aleph0 : 1 < ℵ₀ := by simpa using nat_lt_aleph0 1 @[simp] theorem one_le_aleph0 : 1 ≤ ℵ₀ := one_lt_aleph0.le theorem lt_aleph0 {c : Cardinal} : c < ℵ₀ ↔ ∃ n : ℕ, c = n := ⟨fun h => by rcases lt_lift_iff.1 h with ⟨c, h', rfl⟩ rcases le_mk_iff_exists_set.1 h'.1 with ⟨S, rfl⟩ suffices S.Finite by lift S to Finset ℕ using this simp contrapose! h' haveI := Infinite.to_subtype h' exact ⟨Infinite.natEmbedding S⟩, fun ⟨_, e⟩ => e.symm ▸ nat_lt_aleph0 _⟩ lemma succ_eq_of_lt_aleph0 {c : Cardinal} (h : c < ℵ₀) : Order.succ c = c + 1 := by obtain ⟨n, hn⟩ := Cardinal.lt_aleph0.mp h rw [hn, succ_natCast] theorem aleph0_le {c : Cardinal} : ℵ₀ ≤ c ↔ ∀ n : ℕ, ↑n ≤ c := ⟨fun h _ => (nat_lt_aleph0 _).le.trans h, fun h => le_of_not_lt fun hn => by rcases lt_aleph0.1 hn with ⟨n, rfl⟩ exact (Nat.lt_succ_self _).not_le (Nat.cast_le.1 (h (n + 1)))⟩ theorem isSuccPrelimit_aleph0 : IsSuccPrelimit ℵ₀ := isSuccPrelimit_of_succ_lt fun a ha => by rcases lt_aleph0.1 ha with ⟨n, rfl⟩ rw [← nat_succ] apply nat_lt_aleph0 theorem isSuccLimit_aleph0 : IsSuccLimit ℵ₀ := by rw [Cardinal.isSuccLimit_iff] exact ⟨aleph0_ne_zero, isSuccPrelimit_aleph0⟩ lemma not_isSuccLimit_natCast : (n : ℕ) → ¬ IsSuccLimit (n : Cardinal.{u}) | 0, e => e.1 isMin_bot | Nat.succ n, e => Order.not_isSuccPrelimit_succ _ (nat_succ n ▸ e.2) theorem not_isSuccLimit_of_lt_aleph0 {c : Cardinal} (h : c < ℵ₀) : ¬ IsSuccLimit c := by obtain ⟨n, rfl⟩ := lt_aleph0.1 h exact not_isSuccLimit_natCast n theorem aleph0_le_of_isSuccLimit {c : Cardinal} (h : IsSuccLimit c) : ℵ₀ ≤ c := by contrapose! h exact not_isSuccLimit_of_lt_aleph0 h theorem isStrongLimit_aleph0 : IsStrongLimit ℵ₀ := by refine ⟨aleph0_ne_zero, fun x hx ↦ ?_⟩ obtain ⟨n, rfl⟩ := lt_aleph0.1 hx exact_mod_cast nat_lt_aleph0 _ theorem IsStrongLimit.aleph0_le {c} (H : IsStrongLimit c) : ℵ₀ ≤ c := aleph0_le_of_isSuccLimit H.isSuccLimit lemma exists_eq_natCast_of_iSup_eq {ι : Type u} [Nonempty ι] (f : ι → Cardinal.{v}) (hf : BddAbove (range f)) (n : ℕ) (h : ⨆ i, f i = n) : ∃ i, f i = n := exists_eq_of_iSup_eq_of_not_isSuccLimit.{u, v} f hf (not_isSuccLimit_natCast n) h @[simp] theorem range_natCast : range ((↑) : ℕ → Cardinal) = Iio ℵ₀ := ext fun x => by simp only [mem_Iio, mem_range, eq_comm, lt_aleph0] theorem mk_eq_nat_iff {α : Type u} {n : ℕ} : #α = n ↔ Nonempty (α ≃ Fin n) := by rw [← lift_mk_fin, ← lift_uzero #α, lift_mk_eq'] theorem lt_aleph0_iff_finite {α : Type u} : #α < ℵ₀ ↔ Finite α := by simp only [lt_aleph0, mk_eq_nat_iff, finite_iff_exists_equiv_fin] theorem lt_aleph0_iff_fintype {α : Type u} : #α < ℵ₀ ↔ Nonempty (Fintype α) := lt_aleph0_iff_finite.trans (finite_iff_nonempty_fintype _) theorem lt_aleph0_of_finite (α : Type u) [Finite α] : #α < ℵ₀ := lt_aleph0_iff_finite.2 ‹_› theorem lt_aleph0_iff_set_finite {S : Set α} : #S < ℵ₀ ↔ S.Finite := lt_aleph0_iff_finite.trans finite_coe_iff alias ⟨_, _root_.Set.Finite.lt_aleph0⟩ := lt_aleph0_iff_set_finite @[simp] theorem lt_aleph0_iff_subtype_finite {p : α → Prop} : #{ x // p x } < ℵ₀ ↔ { x | p x }.Finite := lt_aleph0_iff_set_finite theorem mk_le_aleph0_iff : #α ≤ ℵ₀ ↔ Countable α := by rw [countable_iff_nonempty_embedding, aleph0, ← lift_uzero #α, lift_mk_le'] @[simp] theorem mk_le_aleph0 [Countable α] : #α ≤ ℵ₀ := mk_le_aleph0_iff.mpr ‹_› theorem le_aleph0_iff_set_countable {s : Set α} : #s ≤ ℵ₀ ↔ s.Countable := mk_le_aleph0_iff alias ⟨_, _root_.Set.Countable.le_aleph0⟩ := le_aleph0_iff_set_countable @[simp] theorem le_aleph0_iff_subtype_countable {p : α → Prop} : #{ x // p x } ≤ ℵ₀ ↔ { x | p x }.Countable := le_aleph0_iff_set_countable theorem aleph0_lt_mk_iff : ℵ₀ < #α ↔ Uncountable α := by rw [← not_le, ← not_countable_iff, not_iff_not, mk_le_aleph0_iff] @[simp] theorem aleph0_lt_mk [Uncountable α] : ℵ₀ < #α := aleph0_lt_mk_iff.mpr ‹_› instance canLiftCardinalNat : CanLift Cardinal ℕ (↑) fun x => x < ℵ₀ := ⟨fun _ hx => let ⟨n, hn⟩ := lt_aleph0.mp hx ⟨n, hn.symm⟩⟩ theorem add_lt_aleph0 {a b : Cardinal} (ha : a < ℵ₀) (hb : b < ℵ₀) : a + b < ℵ₀ := match a, b, lt_aleph0.1 ha, lt_aleph0.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ => by rw [← Nat.cast_add]; apply nat_lt_aleph0 theorem add_lt_aleph0_iff {a b : Cardinal} : a + b < ℵ₀ ↔ a < ℵ₀ ∧ b < ℵ₀ := ⟨fun h => ⟨(self_le_add_right _ _).trans_lt h, (self_le_add_left _ _).trans_lt h⟩, fun ⟨h1, h2⟩ => add_lt_aleph0 h1 h2⟩ theorem aleph0_le_add_iff {a b : Cardinal} : ℵ₀ ≤ a + b ↔ ℵ₀ ≤ a ∨ ℵ₀ ≤ b := by simp only [← not_lt, add_lt_aleph0_iff, not_and_or] /-- See also `Cardinal.nsmul_lt_aleph0_iff_of_ne_zero` if you already have `n ≠ 0`. -/ theorem nsmul_lt_aleph0_iff {n : ℕ} {a : Cardinal} : n • a < ℵ₀ ↔ n = 0 ∨ a < ℵ₀ := by cases n with | zero => simpa using nat_lt_aleph0 0 | succ n => simp only [Nat.succ_ne_zero, false_or] induction' n with n ih · simp rw [succ_nsmul, add_lt_aleph0_iff, ih, and_self_iff] /-- See also `Cardinal.nsmul_lt_aleph0_iff` for a hypothesis-free version. -/ theorem nsmul_lt_aleph0_iff_of_ne_zero {n : ℕ} {a : Cardinal} (h : n ≠ 0) : n • a < ℵ₀ ↔ a < ℵ₀ := nsmul_lt_aleph0_iff.trans <| or_iff_right h theorem mul_lt_aleph0 {a b : Cardinal} (ha : a < ℵ₀) (hb : b < ℵ₀) : a * b < ℵ₀ := match a, b, lt_aleph0.1 ha, lt_aleph0.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ => by rw [← Nat.cast_mul]; apply nat_lt_aleph0 theorem mul_lt_aleph0_iff {a b : Cardinal} : a * b < ℵ₀ ↔ a = 0 ∨ b = 0 ∨ a < ℵ₀ ∧ b < ℵ₀ := by refine ⟨fun h => ?_, ?_⟩ · by_cases ha : a = 0 · exact Or.inl ha right by_cases hb : b = 0 · exact Or.inl hb right rw [← Ne, ← one_le_iff_ne_zero] at ha hb constructor · rw [← mul_one a] exact (mul_le_mul' le_rfl hb).trans_lt h · rw [← one_mul b] exact (mul_le_mul' ha le_rfl).trans_lt h rintro (rfl | rfl | ⟨ha, hb⟩) <;> simp only [*, mul_lt_aleph0, aleph0_pos, zero_mul, mul_zero] /-- See also `Cardinal.aleph0_le_mul_iff`. -/ theorem aleph0_le_mul_iff {a b : Cardinal} : ℵ₀ ≤ a * b ↔ a ≠ 0 ∧ b ≠ 0 ∧ (ℵ₀ ≤ a ∨ ℵ₀ ≤ b) := by let h := (@mul_lt_aleph0_iff a b).not rwa [not_lt, not_or, not_or, not_and_or, not_lt, not_lt] at h /-- See also `Cardinal.aleph0_le_mul_iff'`. -/ theorem aleph0_le_mul_iff' {a b : Cardinal.{u}} : ℵ₀ ≤ a * b ↔ a ≠ 0 ∧ ℵ₀ ≤ b ∨ ℵ₀ ≤ a ∧ b ≠ 0 := by have : ∀ {a : Cardinal.{u}}, ℵ₀ ≤ a → a ≠ 0 := fun a => ne_bot_of_le_ne_bot aleph0_ne_zero a simp only [aleph0_le_mul_iff, and_or_left, and_iff_right_of_imp this, @and_left_comm (a ≠ 0)] simp only [and_comm, or_comm] theorem mul_lt_aleph0_iff_of_ne_zero {a b : Cardinal} (ha : a ≠ 0) (hb : b ≠ 0) : a * b < ℵ₀ ↔ a < ℵ₀ ∧ b < ℵ₀ := by simp [mul_lt_aleph0_iff, ha, hb] theorem power_lt_aleph0 {a b : Cardinal} (ha : a < ℵ₀) (hb : b < ℵ₀) : a ^ b < ℵ₀ := match a, b, lt_aleph0.1 ha, lt_aleph0.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ => by rw [power_natCast, ← Nat.cast_pow]; apply nat_lt_aleph0 theorem eq_one_iff_unique {α : Type*} : #α = 1 ↔ Subsingleton α ∧ Nonempty α := calc #α = 1 ↔ #α ≤ 1 ∧ 1 ≤ #α := le_antisymm_iff _ ↔ Subsingleton α ∧ Nonempty α := le_one_iff_subsingleton.and (one_le_iff_ne_zero.trans mk_ne_zero_iff) theorem infinite_iff {α : Type u} : Infinite α ↔ ℵ₀ ≤ #α := by rw [← not_lt, lt_aleph0_iff_finite, not_finite_iff_infinite] lemma aleph0_le_mk_iff : ℵ₀ ≤ #α ↔ Infinite α := infinite_iff.symm lemma mk_lt_aleph0_iff : #α < ℵ₀ ↔ Finite α := by simp [← not_le, aleph0_le_mk_iff] @[simp] lemma mk_lt_aleph0 [Finite α] : #α < ℵ₀ := mk_lt_aleph0_iff.2 ‹_› @[simp] theorem aleph0_le_mk (α : Type u) [Infinite α] : ℵ₀ ≤ #α := infinite_iff.1 ‹_› @[simp] theorem mk_eq_aleph0 (α : Type*) [Countable α] [Infinite α] : #α = ℵ₀ := mk_le_aleph0.antisymm <| aleph0_le_mk _ theorem denumerable_iff {α : Type u} : Nonempty (Denumerable α) ↔ #α = ℵ₀ := ⟨fun ⟨h⟩ => mk_congr ((@Denumerable.eqv α h).trans Equiv.ulift.symm), fun h => by obtain ⟨f⟩ := Quotient.exact h exact ⟨Denumerable.mk' <| f.trans Equiv.ulift⟩⟩ theorem mk_denumerable (α : Type u) [Denumerable α] : #α = ℵ₀ := denumerable_iff.1 ⟨‹_›⟩ theorem _root_.Set.countable_infinite_iff_nonempty_denumerable {α : Type*} {s : Set α} : s.Countable ∧ s.Infinite ↔ Nonempty (Denumerable s) := by rw [nonempty_denumerable_iff, ← Set.infinite_coe_iff, countable_coe_iff] @[simp] theorem aleph0_add_aleph0 : ℵ₀ + ℵ₀ = ℵ₀ := mk_denumerable _ theorem aleph0_mul_aleph0 : ℵ₀ * ℵ₀ = ℵ₀ := mk_denumerable _ @[simp] theorem nat_mul_aleph0 {n : ℕ} (hn : n ≠ 0) : ↑n * ℵ₀ = ℵ₀ := le_antisymm (lift_mk_fin n ▸ mk_le_aleph0) <| le_mul_of_one_le_left (zero_le _) <| by rwa [← Nat.cast_one, Nat.cast_le, Nat.one_le_iff_ne_zero] @[simp] theorem aleph0_mul_nat {n : ℕ} (hn : n ≠ 0) : ℵ₀ * n = ℵ₀ := by rw [mul_comm, nat_mul_aleph0 hn] @[simp] theorem ofNat_mul_aleph0 {n : ℕ} [Nat.AtLeastTwo n] : ofNat(n) * ℵ₀ = ℵ₀ := nat_mul_aleph0 (NeZero.ne n) @[simp] theorem aleph0_mul_ofNat {n : ℕ} [Nat.AtLeastTwo n] : ℵ₀ * ofNat(n) = ℵ₀ := aleph0_mul_nat (NeZero.ne n) @[simp] theorem add_le_aleph0 {c₁ c₂ : Cardinal} : c₁ + c₂ ≤ ℵ₀ ↔ c₁ ≤ ℵ₀ ∧ c₂ ≤ ℵ₀ := ⟨fun h => ⟨le_self_add.trans h, le_add_self.trans h⟩, fun h => aleph0_add_aleph0 ▸ add_le_add h.1 h.2⟩ @[simp] theorem aleph0_add_nat (n : ℕ) : ℵ₀ + n = ℵ₀ := (add_le_aleph0.2 ⟨le_rfl, (nat_lt_aleph0 n).le⟩).antisymm le_self_add @[simp] theorem nat_add_aleph0 (n : ℕ) : ↑n + ℵ₀ = ℵ₀ := by rw [add_comm, aleph0_add_nat] @[simp] theorem ofNat_add_aleph0 {n : ℕ} [Nat.AtLeastTwo n] : ofNat(n) + ℵ₀ = ℵ₀ := nat_add_aleph0 n @[simp] theorem aleph0_add_ofNat {n : ℕ} [Nat.AtLeastTwo n] : ℵ₀ + ofNat(n) = ℵ₀ := aleph0_add_nat n theorem exists_nat_eq_of_le_nat {c : Cardinal} {n : ℕ} (h : c ≤ n) : ∃ m, m ≤ n ∧ c = m := by lift c to ℕ using h.trans_lt (nat_lt_aleph0 _) exact ⟨c, mod_cast h, rfl⟩ theorem mk_int : #ℤ = ℵ₀ := mk_denumerable ℤ theorem mk_pnat : #ℕ+ = ℵ₀ := mk_denumerable ℕ+ @[deprecated (since := "2025-04-27")] alias mk_pNat := mk_pnat /-! ### Cardinalities of basic sets and types -/ @[simp] theorem mk_additive : #(Additive α) = #α := rfl @[simp] theorem mk_multiplicative : #(Multiplicative α) = #α := rfl @[to_additive (attr := simp)] theorem mk_mulOpposite : #(MulOpposite α) = #α := mk_congr MulOpposite.opEquiv.symm theorem mk_singleton {α : Type u} (x : α) : #({x} : Set α) = 1 := mk_eq_one _ @[simp] theorem mk_vector (α : Type u) (n : ℕ) : #(List.Vector α n) = #α ^ n := (mk_congr (Equiv.vectorEquivFin α n)).trans <| by simp theorem mk_list_eq_sum_pow (α : Type u) : #(List α) = sum fun n : ℕ => #α ^ n := calc #(List α) = #(Σn, List.Vector α n) := mk_congr (Equiv.sigmaFiberEquiv List.length).symm _ = sum fun n : ℕ => #α ^ n := by simp theorem mk_quot_le {α : Type u} {r : α → α → Prop} : #(Quot r) ≤ #α := mk_le_of_surjective Quot.exists_rep theorem mk_quotient_le {α : Type u} {s : Setoid α} : #(Quotient s) ≤ #α := mk_quot_le theorem mk_subtype_le_of_subset {α : Type u} {p q : α → Prop} (h : ∀ ⦃x⦄, p x → q x) : #(Subtype p) ≤ #(Subtype q) := ⟨Embedding.subtypeMap (Embedding.refl α) h⟩ theorem mk_emptyCollection (α : Type u) : #(∅ : Set α) = 0 := mk_eq_zero _ theorem mk_emptyCollection_iff {α : Type u} {s : Set α} : #s = 0 ↔ s = ∅ := by constructor · intro h rw [mk_eq_zero_iff] at h exact eq_empty_iff_forall_not_mem.2 fun x hx => h.elim' ⟨x, hx⟩ · rintro rfl exact mk_emptyCollection _ @[simp] theorem mk_univ {α : Type u} : #(@univ α) = #α := mk_congr (Equiv.Set.univ α) @[simp] lemma mk_setProd {α β : Type u} (s : Set α) (t : Set β) : #(s ×ˢ t) = #s * #t := by rw [mul_def, mk_congr (Equiv.Set.prod ..)] theorem mk_image_le {α β : Type u} {f : α → β} {s : Set α} : #(f '' s) ≤ #s := mk_le_of_surjective surjective_onto_image lemma mk_image2_le {α β γ : Type u} {f : α → β → γ} {s : Set α} {t : Set β} : #(image2 f s t) ≤ #s * #t := by rw [← image_uncurry_prod, ← mk_setProd] exact mk_image_le theorem mk_image_le_lift {α : Type u} {β : Type v} {f : α → β} {s : Set α} : lift.{u} #(f '' s) ≤ lift.{v} #s := lift_mk_le.{0}.mpr ⟨Embedding.ofSurjective _ surjective_onto_image⟩ theorem mk_range_le {α β : Type u} {f : α → β} : #(range f) ≤ #α := mk_le_of_surjective surjective_onto_range theorem mk_range_le_lift {α : Type u} {β : Type v} {f : α → β} : lift.{u} #(range f) ≤ lift.{v} #α := lift_mk_le.{0}.mpr ⟨Embedding.ofSurjective _ surjective_onto_range⟩ theorem mk_range_eq (f : α → β) (h : Injective f) : #(range f) = #α := mk_congr (Equiv.ofInjective f h).symm theorem mk_range_eq_lift {α : Type u} {β : Type v} {f : α → β} (hf : Injective f) : lift.{max u w} #(range f) = lift.{max v w} #α := lift_mk_eq.{v,u,w}.mpr ⟨(Equiv.ofInjective f hf).symm⟩ theorem mk_range_eq_of_injective {α : Type u} {β : Type v} {f : α → β} (hf : Injective f) : lift.{u} #(range f) = lift.{v} #α := lift_mk_eq'.mpr ⟨(Equiv.ofInjective f hf).symm⟩ lemma lift_mk_le_lift_mk_of_injective {α : Type u} {β : Type v} {f : α → β} (hf : Injective f) : Cardinal.lift.{v} (#α) ≤ Cardinal.lift.{u} (#β) := by rw [← Cardinal.mk_range_eq_of_injective hf] exact Cardinal.lift_le.2 (Cardinal.mk_set_le _) lemma lift_mk_le_lift_mk_of_surjective {α : Type u} {β : Type v} {f : α → β} (hf : Surjective f) : Cardinal.lift.{u} (#β) ≤ Cardinal.lift.{v} (#α) := lift_mk_le_lift_mk_of_injective (injective_surjInv hf) theorem mk_image_eq_of_injOn {α β : Type u} (f : α → β) (s : Set α) (h : InjOn f s) : #(f '' s) = #s := mk_congr (Equiv.Set.imageOfInjOn f s h).symm theorem mk_image_eq_of_injOn_lift {α : Type u} {β : Type v} (f : α → β) (s : Set α) (h : InjOn f s) : lift.{u} #(f '' s) = lift.{v} #s := lift_mk_eq.{v, u, 0}.mpr ⟨(Equiv.Set.imageOfInjOn f s h).symm⟩ theorem mk_image_eq {α β : Type u} {f : α → β} {s : Set α} (hf : Injective f) : #(f '' s) = #s := mk_image_eq_of_injOn _ _ hf.injOn theorem mk_image_eq_lift {α : Type u} {β : Type v} (f : α → β) (s : Set α) (h : Injective f) : lift.{u} #(f '' s) = lift.{v} #s := mk_image_eq_of_injOn_lift _ _ h.injOn @[simp] theorem mk_image_embedding_lift {β : Type v} (f : α ↪ β) (s : Set α) : lift.{u} #(f '' s) = lift.{v} #s := mk_image_eq_lift _ _ f.injective @[simp] theorem mk_image_embedding (f : α ↪ β) (s : Set α) : #(f '' s) = #s := by simpa using mk_image_embedding_lift f s theorem mk_iUnion_le_sum_mk {α ι : Type u} {f : ι → Set α} : #(⋃ i, f i) ≤ sum fun i => #(f i) := calc #(⋃ i, f i) ≤ #(Σi, f i) := mk_le_of_surjective (Set.sigmaToiUnion_surjective f) _ = sum fun i => #(f i) := mk_sigma _ theorem mk_iUnion_le_sum_mk_lift {α : Type u} {ι : Type v} {f : ι → Set α} : lift.{v} #(⋃ i, f i) ≤ sum fun i => #(f i) := calc lift.{v} #(⋃ i, f i) ≤ #(Σi, f i) := mk_le_of_surjective <| ULift.up_surjective.comp (Set.sigmaToiUnion_surjective f) _ = sum fun i => #(f i) := mk_sigma _ theorem mk_iUnion_eq_sum_mk {α ι : Type u} {f : ι → Set α} (h : Pairwise (Disjoint on f)) : #(⋃ i, f i) = sum fun i => #(f i) := calc #(⋃ i, f i) = #(Σi, f i) := mk_congr (Set.unionEqSigmaOfDisjoint h) _ = sum fun i => #(f i) := mk_sigma _ theorem mk_iUnion_eq_sum_mk_lift {α : Type u} {ι : Type v} {f : ι → Set α} (h : Pairwise (Disjoint on f)) : lift.{v} #(⋃ i, f i) = sum fun i => #(f i) := calc lift.{v} #(⋃ i, f i) = #(Σi, f i) := mk_congr <| .trans Equiv.ulift (Set.unionEqSigmaOfDisjoint h) _ = sum fun i => #(f i) := mk_sigma _ theorem mk_iUnion_le {α ι : Type u} (f : ι → Set α) : #(⋃ i, f i) ≤ #ι * ⨆ i, #(f i) := mk_iUnion_le_sum_mk.trans (sum_le_iSup _) theorem mk_iUnion_le_lift {α : Type u} {ι : Type v} (f : ι → Set α) : lift.{v} #(⋃ i, f i) ≤ lift.{u} #ι * ⨆ i, lift.{v} #(f i) := by refine mk_iUnion_le_sum_mk_lift.trans <| Eq.trans_le ?_ (sum_le_iSup_lift _) rw [← lift_sum, lift_id'.{_,u}] theorem mk_sUnion_le {α : Type u} (A : Set (Set α)) : #(⋃₀ A) ≤ #A * ⨆ s : A, #s := by rw [sUnion_eq_iUnion] apply mk_iUnion_le theorem mk_biUnion_le {ι α : Type u} (A : ι → Set α) (s : Set ι) : #(⋃ x ∈ s, A x) ≤ #s * ⨆ x : s, #(A x.1) := by rw [biUnion_eq_iUnion] apply mk_iUnion_le theorem mk_biUnion_le_lift {α : Type u} {ι : Type v} (A : ι → Set α) (s : Set ι) : lift.{v} #(⋃ x ∈ s, A x) ≤ lift.{u} #s * ⨆ x : s, lift.{v} #(A x.1) := by rw [biUnion_eq_iUnion] apply mk_iUnion_le_lift theorem finset_card_lt_aleph0 (s : Finset α) : #(↑s : Set α) < ℵ₀ := lt_aleph0_of_finite _ theorem mk_set_eq_nat_iff_finset {α} {s : Set α} {n : ℕ} : #s = n ↔ ∃ t : Finset α, (t : Set α) = s ∧ t.card = n := by constructor · intro h lift s to Finset α using lt_aleph0_iff_set_finite.1 (h.symm ▸ nat_lt_aleph0 n) simpa using h · rintro ⟨t, rfl, rfl⟩ exact mk_coe_finset theorem mk_eq_nat_iff_finset {n : ℕ} : #α = n ↔ ∃ t : Finset α, (t : Set α) = univ ∧ t.card = n := by rw [← mk_univ, mk_set_eq_nat_iff_finset] theorem mk_eq_nat_iff_fintype {n : ℕ} : #α = n ↔ ∃ h : Fintype α, @Fintype.card α h = n := by rw [mk_eq_nat_iff_finset] constructor · rintro ⟨t, ht, hn⟩ exact ⟨⟨t, eq_univ_iff_forall.1 ht⟩, hn⟩ · rintro ⟨⟨t, ht⟩, hn⟩ exact ⟨t, eq_univ_iff_forall.2 ht, hn⟩ theorem mk_union_add_mk_inter {α : Type u} {S T : Set α} : #(S ∪ T : Set α) + #(S ∩ T : Set α) = #S + #T := by classical exact Quot.sound ⟨Equiv.Set.unionSumInter S T⟩ /-- The cardinality of a union is at most the sum of the cardinalities of the two sets. -/ theorem mk_union_le {α : Type u} (S T : Set α) : #(S ∪ T : Set α) ≤ #S + #T := @mk_union_add_mk_inter α S T ▸ self_le_add_right #(S ∪ T : Set α) #(S ∩ T : Set α) theorem mk_union_of_disjoint {α : Type u} {S T : Set α} (H : Disjoint S T) : #(S ∪ T : Set α) = #S + #T := by classical exact Quot.sound ⟨Equiv.Set.union H⟩ theorem mk_insert {α : Type u} {s : Set α} {a : α} (h : a ∉ s) : #(insert a s : Set α) = #s + 1 := by rw [← union_singleton, mk_union_of_disjoint, mk_singleton] simpa theorem mk_insert_le {α : Type u} {s : Set α} {a : α} : #(insert a s : Set α) ≤ #s + 1 := by by_cases h : a ∈ s · simp only [insert_eq_of_mem h, self_le_add_right] · rw [mk_insert h] theorem mk_sum_compl {α} (s : Set α) : #s + #(sᶜ : Set α) = #α := by classical exact mk_congr (Equiv.Set.sumCompl s) theorem mk_le_mk_of_subset {α} {s t : Set α} (h : s ⊆ t) : #s ≤ #t := ⟨Set.embeddingOfSubset s t h⟩ theorem mk_le_iff_forall_finset_subset_card_le {α : Type u} {n : ℕ} {t : Set α} : #t ≤ n ↔ ∀ s : Finset α, (s : Set α) ⊆ t → s.card ≤ n := by refine ⟨fun H s hs ↦ by simpa using (mk_le_mk_of_subset hs).trans H, fun H ↦ ?_⟩ apply card_le_of (fun s ↦ ?_) classical let u : Finset α := s.image Subtype.val have : u.card = s.card := Finset.card_image_of_injOn Subtype.coe_injective.injOn rw [← this] apply H simp only [u, Finset.coe_image, image_subset_iff, Subtype.coe_preimage_self, subset_univ] theorem mk_subtype_mono {p q : α → Prop} (h : ∀ x, p x → q x) : #{ x // p x } ≤ #{ x // q x } := ⟨embeddingOfSubset _ _ h⟩ theorem le_mk_diff_add_mk (S T : Set α) : #S ≤ #(S \ T : Set α) + #T := (mk_le_mk_of_subset <| subset_diff_union _ _).trans <| mk_union_le _ _ theorem mk_diff_add_mk {S T : Set α} (h : T ⊆ S) : #(S \ T : Set α) + #T = #S := by refine (mk_union_of_disjoint <| ?_).symm.trans <| by rw [diff_union_of_subset h] exact disjoint_sdiff_self_left theorem mk_union_le_aleph0 {α} {P Q : Set α} : #(P ∪ Q : Set α) ≤ ℵ₀ ↔ #P ≤ ℵ₀ ∧ #Q ≤ ℵ₀ := by simp only [le_aleph0_iff_subtype_countable, mem_union, setOf_mem_eq, Set.union_def, ← countable_union] theorem mk_sep (s : Set α) (t : α → Prop) : #({ x ∈ s | t x } : Set α) = #{ x : s | t x.1 } := mk_congr (Equiv.Set.sep s t) theorem mk_preimage_of_injective_lift {α : Type u} {β : Type v} (f : α → β) (s : Set β) (h : Injective f) : lift.{v} #(f ⁻¹' s) ≤ lift.{u} #s := by rw [lift_mk_le.{0}] -- Porting note: Needed to insert `mem_preimage.mp` below use Subtype.coind (fun x => f x.1) fun x => mem_preimage.mp x.2 apply Subtype.coind_injective; exact h.comp Subtype.val_injective theorem mk_preimage_of_subset_range_lift {α : Type u} {β : Type v} (f : α → β) (s : Set β) (h : s ⊆ range f) : lift.{u} #s ≤ lift.{v} #(f ⁻¹' s) := by rw [← image_preimage_eq_iff] at h nth_rewrite 1 [← h] apply mk_image_le_lift theorem mk_preimage_of_injective_of_subset_range_lift {β : Type v} (f : α → β) (s : Set β) (h : Injective f) (h2 : s ⊆ range f) : lift.{v} #(f ⁻¹' s) = lift.{u} #s := le_antisymm (mk_preimage_of_injective_lift f s h) (mk_preimage_of_subset_range_lift f s h2) theorem mk_preimage_of_injective_of_subset_range (f : α → β) (s : Set β) (h : Injective f) (h2 : s ⊆ range f) : #(f ⁻¹' s) = #s := by convert mk_preimage_of_injective_of_subset_range_lift.{u, u} f s h h2 using 1 <;> rw [lift_id] @[simp] theorem mk_preimage_equiv_lift {β : Type v} (f : α ≃ β) (s : Set β) : lift.{v} #(f ⁻¹' s) = lift.{u} #s := by apply mk_preimage_of_injective_of_subset_range_lift _ _ f.injective rw [f.range_eq_univ] exact fun _ _ ↦ ⟨⟩ @[simp] theorem mk_preimage_equiv (f : α ≃ β) (s : Set β) : #(f ⁻¹' s) = #s := by simpa using mk_preimage_equiv_lift f s theorem mk_preimage_of_injective (f : α → β) (s : Set β) (h : Injective f) : #(f ⁻¹' s) ≤ #s := by rw [← lift_id #(↑(f ⁻¹' s)), ← lift_id #(↑s)] exact mk_preimage_of_injective_lift f s h theorem mk_preimage_of_subset_range (f : α → β) (s : Set β) (h : s ⊆ range f) : #s ≤ #(f ⁻¹' s) := by rw [← lift_id #(↑(f ⁻¹' s)), ← lift_id #(↑s)] exact mk_preimage_of_subset_range_lift f s h theorem mk_subset_ge_of_subset_image_lift {α : Type u} {β : Type v} (f : α → β) {s : Set α} {t : Set β} (h : t ⊆ f '' s) : lift.{u} #t ≤ lift.{v} #({ x ∈ s | f x ∈ t } : Set α) := by rw [image_eq_range] at h convert mk_preimage_of_subset_range_lift _ _ h using 1 rw [mk_sep] rfl theorem mk_subset_ge_of_subset_image (f : α → β) {s : Set α} {t : Set β} (h : t ⊆ f '' s) : #t ≤ #({ x ∈ s | f x ∈ t } : Set α) := by rw [image_eq_range] at h convert mk_preimage_of_subset_range _ _ h using 1 rw [mk_sep] rfl theorem le_mk_iff_exists_subset {c : Cardinal} {α : Type u} {s : Set α} : c ≤ #s ↔ ∃ p : Set α, p ⊆ s ∧ #p = c := by rw [le_mk_iff_exists_set, ← Subtype.exists_set_subtype] apply exists_congr; intro t; rw [mk_image_eq]; apply Subtype.val_injective @[simp] theorem mk_range_inl {α : Type u} {β : Type v} : #(range (@Sum.inl α β)) = lift.{v} #α := by rw [← lift_id'.{u, v} #_, (Equiv.Set.rangeInl α β).lift_cardinal_eq, lift_umax.{u, v}] @[simp] theorem mk_range_inr {α : Type u} {β : Type v} : #(range (@Sum.inr α β)) = lift.{u} #β := by rw [← lift_id'.{v, u} #_, (Equiv.Set.rangeInr α β).lift_cardinal_eq, lift_umax.{v, u}] theorem two_le_iff : (2 : Cardinal) ≤ #α ↔ ∃ x y : α, x ≠ y := by rw [← Nat.cast_two, nat_succ, succ_le_iff, Nat.cast_one, one_lt_iff_nontrivial, nontrivial_iff] theorem two_le_iff' (x : α) : (2 : Cardinal) ≤ #α ↔ ∃ y : α, y ≠ x := by rw [two_le_iff, ← nontrivial_iff, nontrivial_iff_exists_ne x] theorem mk_eq_two_iff : #α = 2 ↔ ∃ x y : α, x ≠ y ∧ ({x, y} : Set α) = univ := by classical simp only [← @Nat.cast_two Cardinal, mk_eq_nat_iff_finset, Finset.card_eq_two] constructor · rintro ⟨t, ht, x, y, hne, rfl⟩ exact ⟨x, y, hne, by simpa using ht⟩ · rintro ⟨x, y, hne, h⟩ exact ⟨{x, y}, by simpa using h, x, y, hne, rfl⟩ theorem mk_eq_two_iff' (x : α) : #α = 2 ↔ ∃! y, y ≠ x := by rw [mk_eq_two_iff]; constructor · rintro ⟨a, b, hne, h⟩ simp only [eq_univ_iff_forall, mem_insert_iff, mem_singleton_iff] at h rcases h x with (rfl | rfl) exacts [⟨b, hne.symm, fun z => (h z).resolve_left⟩, ⟨a, hne, fun z => (h z).resolve_right⟩] · rintro ⟨y, hne, hy⟩ exact ⟨x, y, hne.symm, eq_univ_of_forall fun z => or_iff_not_imp_left.2 (hy z)⟩ theorem exists_not_mem_of_length_lt {α : Type*} (l : List α) (h : ↑l.length < #α) : ∃ z : α, z ∉ l := by classical contrapose! h calc #α = #(Set.univ : Set α) := mk_univ.symm _ ≤ #l.toFinset := mk_le_mk_of_subset fun x _ => List.mem_toFinset.mpr (h x) _ = l.toFinset.card := Cardinal.mk_coe_finset _ ≤ l.length := Nat.cast_le.mpr (List.toFinset_card_le l) theorem three_le {α : Type*} (h : 3 ≤ #α) (x : α) (y : α) : ∃ z : α, z ≠ x ∧ z ≠ y := by have : ↑(3 : ℕ) ≤ #α := by simpa using h have : ↑(2 : ℕ) < #α := by rwa [← succ_le_iff, ← Cardinal.nat_succ] have := exists_not_mem_of_length_lt [x, y] this simpa [not_or] using this /-! ### `powerlt` operation -/ /-- The function `a ^< b`, defined as the supremum of `a ^ c` for `c < b`. -/ def powerlt (a b : Cardinal.{u}) : Cardinal.{u} := ⨆ c : Iio b, a ^ (c : Cardinal) @[inherit_doc] infixl:80 " ^< " => powerlt theorem le_powerlt {b c : Cardinal.{u}} (a) (h : c < b) : (a^c) ≤ a ^< b := by refine le_ciSup (f := fun y : Iio b => a ^ (y : Cardinal)) ?_ ⟨c, h⟩ rw [← image_eq_range] exact bddAbove_image.{u, u} _ bddAbove_Iio theorem powerlt_le {a b c : Cardinal.{u}} : a ^< b ≤ c ↔ ∀ x < b, a ^ x ≤ c := by rw [powerlt, ciSup_le_iff'] · simp · rw [← image_eq_range] exact bddAbove_image.{u, u} _ bddAbove_Iio theorem powerlt_le_powerlt_left {a b c : Cardinal} (h : b ≤ c) : a ^< b ≤ a ^< c := powerlt_le.2 fun _ hx => le_powerlt a <| hx.trans_le h theorem powerlt_mono_left (a) : Monotone fun c => a ^< c := fun _ _ => powerlt_le_powerlt_left theorem powerlt_succ {a b : Cardinal} (h : a ≠ 0) : a ^< succ b = a ^ b := (powerlt_le.2 fun _ h' => power_le_power_left h <| le_of_lt_succ h').antisymm <| le_powerlt a (lt_succ b) theorem powerlt_min {a b c : Cardinal} : a ^< min b c = min (a ^< b) (a ^< c) := (powerlt_mono_left a).map_min theorem powerlt_max {a b c : Cardinal} : a ^< max b c = max (a ^< b) (a ^< c) := (powerlt_mono_left a).map_max theorem zero_powerlt {a : Cardinal} (h : a ≠ 0) : 0 ^< a = 1 := by apply (powerlt_le.2 fun c _ => zero_power_le _).antisymm rw [← power_zero] exact le_powerlt 0 (pos_iff_ne_zero.2 h) @[simp] theorem powerlt_zero {a : Cardinal} : a ^< 0 = 0 := by convert Cardinal.iSup_of_empty _ exact Subtype.isEmpty_of_false fun x => mem_Iio.not.mpr (Cardinal.zero_le x).not_lt end Cardinal
Mathlib/SetTheory/Cardinal/Basic.lean
1,514
1,515
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta, Alena Gusakov, Yaël Dillies -/ import Mathlib.Algebra.GeomSum import Mathlib.Data.Finset.Slice import Mathlib.Data.Nat.BitIndices import Mathlib.Order.SupClosed import Mathlib.Order.UpperLower.Closure /-! # Colexigraphic order We define the colex order for finite sets, and give a couple of important lemmas and properties relating to it. The colex ordering likes to avoid large values: If the biggest element of `t` is bigger than all elements of `s`, then `s < t`. In the special case of `ℕ`, it can be thought of as the "binary" ordering. That is, order `s` based on $∑_{i ∈ s} 2^i$. It's defined here on `Finset α` for any linear order `α`. In the context of the Kruskal-Katona theorem, we are interested in how colex behaves for sets of a fixed size. For example, for size 3, the colex order on ℕ starts `012, 013, 023, 123, 014, 024, 124, 034, 134, 234, ...` ## Main statements * Colex order properties - linearity, decidability and so on. * `Finset.Colex.forall_lt_mono`: if `s < t` in colex, and everything in `t` is `< a`, then everything in `s` is `< a`. This confirms the idea that an enumeration under colex will exhaust all sets using elements `< a` before allowing `a` to be included. * `Finset.toColex_image_le_toColex_image`: Strictly monotone functions preserve colex. * `Finset.geomSum_le_geomSum_iff_toColex_le_toColex`: Colex for α = ℕ is the same as binary. This also proves binary expansions are unique. ## See also Related files are: * `Data.List.Lex`: Lexicographic order on lists. * `Data.Pi.Lex`: Lexicographic order on `Πₗ i, α i`. * `Data.PSigma.Order`: Lexicographic order on `Σ' i, α i`. * `Data.Sigma.Order`: Lexicographic order on `Σ i, α i`. * `Data.Prod.Lex`: Lexicographic order on `α × β`. ## TODO * Generalise `Colex.initSeg` so that it applies to `ℕ`. ## References * https://github.com/b-mehta/maths-notes/blob/master/iii/mich/combinatorics.pdf ## Tags colex, colexicographic, binary -/ open Finset Function variable {α β : Type*} namespace Finset /-- Type synonym of `Finset α` equipped with the colexicographic order rather than the inclusion order. -/ @[ext] structure Colex (α) where /-- `toColex` is the "identity" function between `Finset α` and `Finset.Colex α`. -/ toColex :: /-- `ofColex` is the "identity" function between `Finset.Colex α` and `Finset α`. -/ (ofColex : Finset α) -- TODO: Why can't we export? --export Colex (toColex) open Colex instance : Inhabited (Colex α) := ⟨⟨∅⟩⟩ @[simp] lemma toColex_ofColex (s : Colex α) : toColex (ofColex s) = s := rfl lemma ofColex_toColex (s : Finset α) : ofColex (toColex s) = s := rfl lemma toColex_inj {s t : Finset α} : toColex s = toColex t ↔ s = t := by simp @[simp] lemma ofColex_inj {s t : Colex α} : ofColex s = ofColex t ↔ s = t := by cases s; cases t; simp lemma toColex_ne_toColex {s t : Finset α} : toColex s ≠ toColex t ↔ s ≠ t := by simp lemma ofColex_ne_ofColex {s t : Colex α} : ofColex s ≠ ofColex t ↔ s ≠ t := by simp lemma toColex_injective : Injective (toColex : Finset α → Colex α) := fun _ _ ↦ toColex_inj.1 lemma ofColex_injective : Injective (ofColex : Colex α → Finset α) := fun _ _ ↦ ofColex_inj.1 namespace Colex section PartialOrder variable [PartialOrder α] [PartialOrder β] {f : α → β} {𝒜 𝒜₁ 𝒜₂ : Finset (Finset α)} {s t u : Finset α} {a b : α} instance instLE : LE (Colex α) where le s t := ∀ ⦃a⦄, a ∈ ofColex s → a ∉ ofColex t → ∃ b, b ∈ ofColex t ∧ b ∉ ofColex s ∧ a ≤ b -- TODO: This lemma is weirdly useful given how strange its statement is. -- Is there a nicer statement? Should this lemma be made public? private lemma trans_aux (hst : toColex s ≤ toColex t) (htu : toColex t ≤ toColex u) (has : a ∈ s) (hat : a ∉ t) : ∃ b, b ∈ u ∧ b ∉ s ∧ a ≤ b := by
classical let s' : Finset α := {b ∈ s | b ∉ t ∧ a ≤ b} have ⟨b, hb, hbmax⟩ := exists_maximal s' ⟨a, by simp [s', has, hat]⟩ simp only [s', mem_filter, and_imp] at hb hbmax have ⟨c, hct, hcs, hbc⟩ := hst hb.1 hb.2.1 by_cases hcu : c ∈ u · exact ⟨c, hcu, hcs, hb.2.2.trans hbc⟩ have ⟨d, hdu, hdt, hcd⟩ := htu hct hcu have had : a ≤ d := hb.2.2.trans <| hbc.trans hcd refine ⟨d, hdu, fun hds ↦ ?_, had⟩ exact hbmax d hds hdt had <| hbc.trans_lt <| hcd.lt_of_ne <| ne_of_mem_of_not_mem hct hdt private lemma antisymm_aux (hst : toColex s ≤ toColex t) (hts : toColex t ≤ toColex s) : s ⊆ t := by
Mathlib/Combinatorics/Colex.lean
105
117
/- Copyright (c) 2019 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Sébastien Gouëzel, Yury Kudryashov -/ import Mathlib.Analysis.Calculus.FDeriv.Linear import Mathlib.Analysis.Calculus.FDeriv.Comp /-! # Additive operations on derivatives For detailed documentation of the Fréchet derivative, see the module docstring of `Analysis/Calculus/FDeriv/Basic.lean`. This file contains the usual formulas (and existence assertions) for the derivative of * sum of finitely many functions * multiplication of a function by a scalar constant * negative of a function * subtraction of two functions -/ open Filter Asymptotics ContinuousLinearMap noncomputable section section variable {𝕜 : Type*} [NontriviallyNormedField 𝕜] variable {E : Type*} [NormedAddCommGroup E] [NormedSpace 𝕜 E] variable {F : Type*} [NormedAddCommGroup F] [NormedSpace 𝕜 F] variable {f g : E → F} variable {f' g' : E →L[𝕜] F} variable {x : E} variable {s : Set E} variable {L : Filter E} section ConstSMul variable {R : Type*} [Semiring R] [Module R F] [SMulCommClass 𝕜 R F] [ContinuousConstSMul R F] /-! ### Derivative of a function multiplied by a constant -/ @[fun_prop] theorem HasStrictFDerivAt.const_smul (h : HasStrictFDerivAt f f' x) (c : R) : HasStrictFDerivAt (fun x => c • f x) (c • f') x := (c • (1 : F →L[𝕜] F)).hasStrictFDerivAt.comp x h theorem HasFDerivAtFilter.const_smul (h : HasFDerivAtFilter f f' x L) (c : R) : HasFDerivAtFilter (fun x => c • f x) (c • f') x L := (c • (1 : F →L[𝕜] F)).hasFDerivAtFilter.comp x h tendsto_map @[fun_prop] nonrec theorem HasFDerivWithinAt.const_smul (h : HasFDerivWithinAt f f' s x) (c : R) : HasFDerivWithinAt (fun x => c • f x) (c • f') s x := h.const_smul c @[fun_prop] nonrec theorem HasFDerivAt.const_smul (h : HasFDerivAt f f' x) (c : R) : HasFDerivAt (fun x => c • f x) (c • f') x := h.const_smul c @[fun_prop] theorem DifferentiableWithinAt.const_smul (h : DifferentiableWithinAt 𝕜 f s x) (c : R) : DifferentiableWithinAt 𝕜 (fun y => c • f y) s x := (h.hasFDerivWithinAt.const_smul c).differentiableWithinAt @[fun_prop] theorem DifferentiableAt.const_smul (h : DifferentiableAt 𝕜 f x) (c : R) : DifferentiableAt 𝕜 (fun y => c • f y) x := (h.hasFDerivAt.const_smul c).differentiableAt @[fun_prop] theorem DifferentiableOn.const_smul (h : DifferentiableOn 𝕜 f s) (c : R) : DifferentiableOn 𝕜 (fun y => c • f y) s := fun x hx => (h x hx).const_smul c @[fun_prop] theorem Differentiable.const_smul (h : Differentiable 𝕜 f) (c : R) : Differentiable 𝕜 fun y => c • f y := fun x => (h x).const_smul c theorem fderivWithin_const_smul (hxs : UniqueDiffWithinAt 𝕜 s x) (h : DifferentiableWithinAt 𝕜 f s x) (c : R) : fderivWithin 𝕜 (fun y => c • f y) s x = c • fderivWithin 𝕜 f s x := (h.hasFDerivWithinAt.const_smul c).fderivWithin hxs /-- Version of `fderivWithin_const_smul` written with `c • f` instead of `fun y ↦ c • f y`. -/ theorem fderivWithin_const_smul' (hxs : UniqueDiffWithinAt 𝕜 s x) (h : DifferentiableWithinAt 𝕜 f s x) (c : R) : fderivWithin 𝕜 (c • f) s x = c • fderivWithin 𝕜 f s x := fderivWithin_const_smul hxs h c theorem fderiv_const_smul (h : DifferentiableAt 𝕜 f x) (c : R) : fderiv 𝕜 (fun y => c • f y) x = c • fderiv 𝕜 f x := (h.hasFDerivAt.const_smul c).fderiv /-- Version of `fderiv_const_smul` written with `c • f` instead of `fun y ↦ c • f y`. -/ theorem fderiv_const_smul' (h : DifferentiableAt 𝕜 f x) (c : R) : fderiv 𝕜 (c • f) x = c • fderiv 𝕜 f x := (h.hasFDerivAt.const_smul c).fderiv end ConstSMul section Add /-! ### Derivative of the sum of two functions -/ @[fun_prop] nonrec theorem HasStrictFDerivAt.add (hf : HasStrictFDerivAt f f' x) (hg : HasStrictFDerivAt g g' x) : HasStrictFDerivAt (fun y => f y + g y) (f' + g') x := .of_isLittleO <| (hf.isLittleO.add hg.isLittleO).congr_left fun y => by simp only [LinearMap.sub_apply, LinearMap.add_apply, map_sub, map_add, add_apply] abel theorem HasFDerivAtFilter.add (hf : HasFDerivAtFilter f f' x L) (hg : HasFDerivAtFilter g g' x L) : HasFDerivAtFilter (fun y => f y + g y) (f' + g') x L := .of_isLittleO <| (hf.isLittleO.add hg.isLittleO).congr_left fun _ => by simp only [LinearMap.sub_apply, LinearMap.add_apply, map_sub, map_add, add_apply] abel @[fun_prop] nonrec theorem HasFDerivWithinAt.add (hf : HasFDerivWithinAt f f' s x) (hg : HasFDerivWithinAt g g' s x) : HasFDerivWithinAt (fun y => f y + g y) (f' + g') s x := hf.add hg @[fun_prop] nonrec theorem HasFDerivAt.add (hf : HasFDerivAt f f' x) (hg : HasFDerivAt g g' x) : HasFDerivAt (fun x => f x + g x) (f' + g') x := hf.add hg @[fun_prop] theorem DifferentiableWithinAt.add (hf : DifferentiableWithinAt 𝕜 f s x) (hg : DifferentiableWithinAt 𝕜 g s x) : DifferentiableWithinAt 𝕜 (fun y => f y + g y) s x := (hf.hasFDerivWithinAt.add hg.hasFDerivWithinAt).differentiableWithinAt @[simp, fun_prop] theorem DifferentiableAt.add (hf : DifferentiableAt 𝕜 f x) (hg : DifferentiableAt 𝕜 g x) : DifferentiableAt 𝕜 (fun y => f y + g y) x := (hf.hasFDerivAt.add hg.hasFDerivAt).differentiableAt @[fun_prop] theorem DifferentiableOn.add (hf : DifferentiableOn 𝕜 f s) (hg : DifferentiableOn 𝕜 g s) : DifferentiableOn 𝕜 (fun y => f y + g y) s := fun x hx => (hf x hx).add (hg x hx) @[simp, fun_prop] theorem Differentiable.add (hf : Differentiable 𝕜 f) (hg : Differentiable 𝕜 g) : Differentiable 𝕜 fun y => f y + g y := fun x => (hf x).add (hg x) theorem fderivWithin_add (hxs : UniqueDiffWithinAt 𝕜 s x) (hf : DifferentiableWithinAt 𝕜 f s x) (hg : DifferentiableWithinAt 𝕜 g s x) : fderivWithin 𝕜 (fun y => f y + g y) s x = fderivWithin 𝕜 f s x + fderivWithin 𝕜 g s x := (hf.hasFDerivWithinAt.add hg.hasFDerivWithinAt).fderivWithin hxs /-- Version of `fderivWithin_add` where the function is written as `f + g` instead of `fun y ↦ f y + g y`. -/ theorem fderivWithin_add' (hxs : UniqueDiffWithinAt 𝕜 s x) (hf : DifferentiableWithinAt 𝕜 f s x) (hg : DifferentiableWithinAt 𝕜 g s x) : fderivWithin 𝕜 (f + g) s x = fderivWithin 𝕜 f s x + fderivWithin 𝕜 g s x := fderivWithin_add hxs hf hg theorem fderiv_add (hf : DifferentiableAt 𝕜 f x) (hg : DifferentiableAt 𝕜 g x) : fderiv 𝕜 (fun y => f y + g y) x = fderiv 𝕜 f x + fderiv 𝕜 g x := (hf.hasFDerivAt.add hg.hasFDerivAt).fderiv /-- Version of `fderiv_add` where the function is written as `f + g` instead of `fun y ↦ f y + g y`. -/ theorem fderiv_add' (hf : DifferentiableAt 𝕜 f x) (hg : DifferentiableAt 𝕜 g x) : fderiv 𝕜 (f + g) x = fderiv 𝕜 f x + fderiv 𝕜 g x := fderiv_add hf hg @[simp] theorem hasFDerivAtFilter_add_const_iff (c : F) : HasFDerivAtFilter (f · + c) f' x L ↔ HasFDerivAtFilter f f' x L := by simp [hasFDerivAtFilter_iff_isLittleOTVS] alias ⟨_, HasFDerivAtFilter.add_const⟩ := hasFDerivAtFilter_add_const_iff @[simp] theorem hasStrictFDerivAt_add_const_iff (c : F) : HasStrictFDerivAt (f · + c) f' x ↔ HasStrictFDerivAt f f' x := by simp [hasStrictFDerivAt_iff_isLittleO] @[fun_prop] alias ⟨_, HasStrictFDerivAt.add_const⟩ := hasStrictFDerivAt_add_const_iff @[simp] theorem hasFDerivWithinAt_add_const_iff (c : F) : HasFDerivWithinAt (f · + c) f' s x ↔ HasFDerivWithinAt f f' s x := hasFDerivAtFilter_add_const_iff c @[fun_prop] alias ⟨_, HasFDerivWithinAt.add_const⟩ := hasFDerivWithinAt_add_const_iff @[simp] theorem hasFDerivAt_add_const_iff (c : F) : HasFDerivAt (f · + c) f' x ↔ HasFDerivAt f f' x := hasFDerivAtFilter_add_const_iff c @[fun_prop] alias ⟨_, HasFDerivAt.add_const⟩ := hasFDerivAt_add_const_iff @[simp] theorem differentiableWithinAt_add_const_iff (c : F) : DifferentiableWithinAt 𝕜 (fun y => f y + c) s x ↔ DifferentiableWithinAt 𝕜 f s x := exists_congr fun _ ↦ hasFDerivWithinAt_add_const_iff c @[fun_prop] alias ⟨_, DifferentiableWithinAt.add_const⟩ := differentiableWithinAt_add_const_iff @[simp] theorem differentiableAt_add_const_iff (c : F) : DifferentiableAt 𝕜 (fun y => f y + c) x ↔ DifferentiableAt 𝕜 f x := exists_congr fun _ ↦ hasFDerivAt_add_const_iff c @[fun_prop] alias ⟨_, DifferentiableAt.add_const⟩ := differentiableAt_add_const_iff @[simp] theorem differentiableOn_add_const_iff (c : F) : DifferentiableOn 𝕜 (fun y => f y + c) s ↔ DifferentiableOn 𝕜 f s := forall₂_congr fun _ _ ↦ differentiableWithinAt_add_const_iff c @[fun_prop] alias ⟨_, DifferentiableOn.add_const⟩ := differentiableOn_add_const_iff @[simp] theorem differentiable_add_const_iff (c : F) : (Differentiable 𝕜 fun y => f y + c) ↔ Differentiable 𝕜 f := forall_congr' fun _ ↦ differentiableAt_add_const_iff c @[fun_prop] alias ⟨_, Differentiable.add_const⟩ := differentiable_add_const_iff @[simp] theorem fderivWithin_add_const (c : F) : fderivWithin 𝕜 (fun y => f y + c) s x = fderivWithin 𝕜 f s x := by classical simp [fderivWithin] @[simp] theorem fderiv_add_const (c : F) : fderiv 𝕜 (fun y => f y + c) x = fderiv 𝕜 f x := by simp only [← fderivWithin_univ, fderivWithin_add_const] @[simp] theorem hasFDerivAtFilter_const_add_iff (c : F) : HasFDerivAtFilter (c + f ·) f' x L ↔ HasFDerivAtFilter f f' x L := by simpa only [add_comm] using hasFDerivAtFilter_add_const_iff c alias ⟨_, HasFDerivAtFilter.const_add⟩ := hasFDerivAtFilter_const_add_iff @[simp] theorem hasStrictFDerivAt_const_add_iff (c : F) : HasStrictFDerivAt (c + f ·) f' x ↔ HasStrictFDerivAt f f' x := by simpa only [add_comm] using hasStrictFDerivAt_add_const_iff c @[fun_prop] alias ⟨_, HasStrictFDerivAt.const_add⟩ := hasStrictFDerivAt_const_add_iff @[simp] theorem hasFDerivWithinAt_const_add_iff (c : F) : HasFDerivWithinAt (c + f ·) f' s x ↔ HasFDerivWithinAt f f' s x := hasFDerivAtFilter_const_add_iff c @[fun_prop] alias ⟨_, HasFDerivWithinAt.const_add⟩ := hasFDerivWithinAt_const_add_iff @[simp] theorem hasFDerivAt_const_add_iff (c : F) : HasFDerivAt (c + f ·) f' x ↔ HasFDerivAt f f' x := hasFDerivAtFilter_const_add_iff c @[fun_prop] alias ⟨_, HasFDerivAt.const_add⟩ := hasFDerivAt_const_add_iff @[simp] theorem differentiableWithinAt_const_add_iff (c : F) : DifferentiableWithinAt 𝕜 (fun y => c + f y) s x ↔ DifferentiableWithinAt 𝕜 f s x := exists_congr fun _ ↦ hasFDerivWithinAt_const_add_iff c @[fun_prop] alias ⟨_, DifferentiableWithinAt.const_add⟩ := differentiableWithinAt_const_add_iff @[simp] theorem differentiableAt_const_add_iff (c : F) : DifferentiableAt 𝕜 (fun y => c + f y) x ↔ DifferentiableAt 𝕜 f x := exists_congr fun _ ↦ hasFDerivAt_const_add_iff c @[fun_prop] alias ⟨_, DifferentiableAt.const_add⟩ := differentiableAt_const_add_iff @[simp] theorem differentiableOn_const_add_iff (c : F) : DifferentiableOn 𝕜 (fun y => c + f y) s ↔ DifferentiableOn 𝕜 f s := forall₂_congr fun _ _ ↦ differentiableWithinAt_const_add_iff c @[fun_prop] alias ⟨_, DifferentiableOn.const_add⟩ := differentiableOn_const_add_iff @[simp] theorem differentiable_const_add_iff (c : F) : (Differentiable 𝕜 fun y => c + f y) ↔ Differentiable 𝕜 f :=
forall_congr' fun _ ↦ differentiableAt_const_add_iff c @[fun_prop]
Mathlib/Analysis/Calculus/FDeriv/Add.lean
300
302
/- Copyright (c) 2024 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import Mathlib.Algebra.Lie.OfAssociative import Mathlib.LinearAlgebra.Eigenspace.Basic import Mathlib.LinearAlgebra.FreeModule.StrongRankCondition /-! # The Lie algebra `sl₂` and its representations The Lie algebra `sl₂` is the unique simple Lie algebra of minimal rank, 1, and as such occupies a distinguished position in the general theory. This file provides some basic definitions and results about `sl₂`. ## Main definitions: * `IsSl2Triple`: a structure representing a triple of elements in a Lie algebra which satisfy the standard relations for `sl₂`. * `IsSl2Triple.HasPrimitiveVectorWith`: a structure representing a primitive vector in a representation of a Lie algebra relative to a distinguished `sl₂` triple. * `IsSl2Triple.HasPrimitiveVectorWith.exists_nat`: the eigenvalue of a primitive vector must be a natural number if the representation is finite-dimensional. -/ variable (R L M : Type*) [CommRing R] [LieRing L] [LieAlgebra R L] [AddCommGroup M] [Module R M] [LieRingModule L M] [LieModule R L M] open LieModule Set variable {L} in /-- An `sl₂` triple within a Lie ring `L` is a triple of elements `h`, `e`, `f` obeying relations which ensure that the Lie subalgebra they generate is equivalent to `sl₂`. -/ structure IsSl2Triple (h e f : L) : Prop where h_ne_zero : h ≠ 0 lie_e_f : ⁅e, f⁆ = h lie_h_e_nsmul : ⁅h, e⁆ = 2 • e lie_h_f_nsmul : ⁅h, f⁆ = - (2 • f) namespace IsSl2Triple variable {L M} variable {h e f : L} lemma symm (ht : IsSl2Triple h e f) : IsSl2Triple (-h) f e where h_ne_zero := by simpa using ht.h_ne_zero lie_e_f := by rw [← neg_eq_iff_eq_neg, lie_skew, ht.lie_e_f] lie_h_e_nsmul := by rw [neg_lie, neg_eq_iff_eq_neg, ht.lie_h_f_nsmul] lie_h_f_nsmul := by rw [neg_lie, neg_inj, ht.lie_h_e_nsmul] @[simp] lemma symm_iff : IsSl2Triple (-h) f e ↔ IsSl2Triple h e f := ⟨fun t ↦ neg_neg h ▸ t.symm, symm⟩ lemma lie_h_e_smul (t : IsSl2Triple h e f) : ⁅h, e⁆ = (2 : R) • e := by simp [t.lie_h_e_nsmul, two_smul] lemma lie_lie_smul_f (t : IsSl2Triple h e f) : ⁅h, f⁆ = -((2 : R) • f) := by simp [t.lie_h_f_nsmul, two_smul] lemma e_ne_zero (t : IsSl2Triple h e f) : e ≠ 0 := by have := t.h_ne_zero contrapose! this simpa [this] using t.lie_e_f.symm lemma f_ne_zero (t : IsSl2Triple h e f) : f ≠ 0 := by have := t.h_ne_zero contrapose! this simpa [this] using t.lie_e_f.symm variable {R} /-- Given a representation of a Lie algebra with distinguished `sl₂` triple, a vector is said to be primitive if it is a simultaneous eigenvector for the action of both `h`, `e`, and the eigenvalue for `e` is zero. -/ structure HasPrimitiveVectorWith (t : IsSl2Triple h e f) (m : M) (μ : R) : Prop where ne_zero : m ≠ 0 lie_h : ⁅h, m⁆ = μ • m lie_e : ⁅e, m⁆ = 0 /-- Given a representation of a Lie algebra with distinguished `sl₂` triple, a simultaneous eigenvector for the action of both `h` and `e` necessarily has eigenvalue zero for `e`. -/ lemma HasPrimitiveVectorWith.mk' [NoZeroSMulDivisors ℤ M] (t : IsSl2Triple h e f) (m : M) (μ ρ : R) (hm : m ≠ 0) (hm' : ⁅h, m⁆ = μ • m) (he : ⁅e, m⁆ = ρ • m) : HasPrimitiveVectorWith t m μ where ne_zero := hm lie_h := hm' lie_e := by suffices 2 • ⁅e, m⁆ = 0 by simpa using this rw [← nsmul_lie, ← t.lie_h_e_nsmul, lie_lie, hm', lie_smul, he, lie_smul, hm', smul_smul, smul_smul, mul_comm ρ μ, sub_self] namespace HasPrimitiveVectorWith variable {m : M} {μ : R} {t : IsSl2Triple h e f} local notation "ψ" n => ((toEnd R L M f) ^ n) m -- Although this is true by definition, we include this lemma (and the assumption) to mirror the API -- for `lie_h_pow_toEnd_f` and `lie_e_pow_succ_toEnd_f`. set_option linter.unusedVariables false in @[nolint unusedArguments] lemma lie_f_pow_toEnd_f (P : HasPrimitiveVectorWith t m μ) (n : ℕ) : ⁅f, ψ n⁆ = ψ (n + 1) := by simp [pow_succ'] variable (P : HasPrimitiveVectorWith t m μ) include P lemma lie_h_pow_toEnd_f (n : ℕ) : ⁅h, ψ n⁆ = (μ - 2 * n) • ψ n := by
induction n with | zero => simpa using P.lie_h | succ n ih => rw [pow_succ', Module.End.mul_apply, toEnd_apply_apply, Nat.cast_add, Nat.cast_one,
Mathlib/Algebra/Lie/Sl2.lean
112
115
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Mario Carneiro -/ import Mathlib.Algebra.Module.Submodule.Bilinear import Mathlib.Algebra.Module.Equiv.Basic import Mathlib.GroupTheory.Congruence.Hom import Mathlib.Tactic.Abel import Mathlib.Tactic.SuppressCompilation /-! # Tensor product of modules over commutative semirings. This file constructs the tensor product of modules over commutative semirings. Given a semiring `R` and modules over it `M` and `N`, the standard construction of the tensor product is `TensorProduct R M N`. It is also a module over `R`. It comes with a canonical bilinear map `TensorProduct.mk R M N : M →ₗ[R] N →ₗ[R] TensorProduct R M N`. Given any bilinear map `f : M →ₗ[R] N →ₗ[R] P`, there is a unique linear map `TensorProduct.lift f : TensorProduct R M N →ₗ[R] P` whose composition with the canonical bilinear map `TensorProduct.mk` is the given bilinear map `f`. Uniqueness is shown in the theorem `TensorProduct.lift.unique`. ## Notation * This file introduces the notation `M ⊗ N` and `M ⊗[R] N` for the tensor product space `TensorProduct R M N`. * It introduces the notation `m ⊗ₜ n` and `m ⊗ₜ[R] n` for the tensor product of two elements, otherwise written as `TensorProduct.tmul R m n`. ## Tags bilinear, tensor, tensor product -/ suppress_compilation section Semiring variable {R : Type*} [CommSemiring R] variable {R' : Type*} [Monoid R'] variable {R'' : Type*} [Semiring R''] variable {A M N P Q S T : Type*} variable [AddCommMonoid M] [AddCommMonoid N] [AddCommMonoid P] variable [AddCommMonoid Q] [AddCommMonoid S] [AddCommMonoid T] variable [Module R M] [Module R N] [Module R Q] [Module R S] [Module R T] variable [DistribMulAction R' M] variable [Module R'' M] variable (M N) namespace TensorProduct section variable (R) /-- The relation on `FreeAddMonoid (M × N)` that generates a congruence whose quotient is the tensor product. -/ inductive Eqv : FreeAddMonoid (M × N) → FreeAddMonoid (M × N) → Prop | of_zero_left : ∀ n : N, Eqv (.of (0, n)) 0 | of_zero_right : ∀ m : M, Eqv (.of (m, 0)) 0 | of_add_left : ∀ (m₁ m₂ : M) (n : N), Eqv (.of (m₁, n) + .of (m₂, n)) (.of (m₁ + m₂, n)) | of_add_right : ∀ (m : M) (n₁ n₂ : N), Eqv (.of (m, n₁) + .of (m, n₂)) (.of (m, n₁ + n₂)) | of_smul : ∀ (r : R) (m : M) (n : N), Eqv (.of (r • m, n)) (.of (m, r • n)) | add_comm : ∀ x y, Eqv (x + y) (y + x) end end TensorProduct variable (R) in /-- The tensor product of two modules `M` and `N` over the same commutative semiring `R`. The localized notations are `M ⊗ N` and `M ⊗[R] N`, accessed by `open scoped TensorProduct`. -/ def TensorProduct : Type _ := (addConGen (TensorProduct.Eqv R M N)).Quotient set_option quotPrecheck false in @[inherit_doc TensorProduct] scoped[TensorProduct] infixl:100 " ⊗ " => TensorProduct _ @[inherit_doc] scoped[TensorProduct] notation:100 M " ⊗[" R "] " N:100 => TensorProduct R M N namespace TensorProduct section Module protected instance zero : Zero (M ⊗[R] N) := (addConGen (TensorProduct.Eqv R M N)).zero protected instance add : Add (M ⊗[R] N) := (addConGen (TensorProduct.Eqv R M N)).hasAdd instance addZeroClass : AddZeroClass (M ⊗[R] N) := { (addConGen (TensorProduct.Eqv R M N)).addMonoid with /- The `toAdd` field is given explicitly as `TensorProduct.add` for performance reasons. This avoids any need to unfold `Con.addMonoid` when the type checker is checking that instance diagrams commute -/ toAdd := TensorProduct.add _ _ toZero := TensorProduct.zero _ _ } instance addSemigroup : AddSemigroup (M ⊗[R] N) := { (addConGen (TensorProduct.Eqv R M N)).addMonoid with toAdd := TensorProduct.add _ _ } instance addCommSemigroup : AddCommSemigroup (M ⊗[R] N) := { (addConGen (TensorProduct.Eqv R M N)).addMonoid with toAddSemigroup := TensorProduct.addSemigroup _ _ add_comm := fun x y => AddCon.induction_on₂ x y fun _ _ => Quotient.sound' <| AddConGen.Rel.of _ _ <| Eqv.add_comm _ _ } instance : Inhabited (M ⊗[R] N) := ⟨0⟩ variable {M N} variable (R) in /-- The canonical function `M → N → M ⊗ N`. The localized notations are `m ⊗ₜ n` and `m ⊗ₜ[R] n`, accessed by `open scoped TensorProduct`. -/ def tmul (m : M) (n : N) : M ⊗[R] N := AddCon.mk' _ <| FreeAddMonoid.of (m, n) /-- The canonical function `M → N → M ⊗ N`. -/ infixl:100 " ⊗ₜ " => tmul _ /-- The canonical function `M → N → M ⊗ N`. -/ notation:100 x " ⊗ₜ[" R "] " y:100 => tmul R x y @[elab_as_elim, induction_eliminator] protected theorem induction_on {motive : M ⊗[R] N → Prop} (z : M ⊗[R] N) (zero : motive 0) (tmul : ∀ x y, motive <| x ⊗ₜ[R] y) (add : ∀ x y, motive x → motive y → motive (x + y)) : motive z := AddCon.induction_on z fun x => FreeAddMonoid.recOn x zero fun ⟨m, n⟩ y ih => by rw [AddCon.coe_add] exact add _ _ (tmul ..) ih /-- Lift an `R`-balanced map to the tensor product. A map `f : M →+ N →+ P` additive in both components is `R`-balanced, or middle linear with respect to `R`, if scalar multiplication in either argument is equivalent, `f (r • m) n = f m (r • n)`. Note that strictly the first action should be a right-action by `R`, but for now `R` is commutative so it doesn't matter. -/ -- TODO: use this to implement `lift` and `SMul.aux`. For now we do not do this as it causes -- performance issues elsewhere. def liftAddHom (f : M →+ N →+ P) (hf : ∀ (r : R) (m : M) (n : N), f (r • m) n = f m (r • n)) : M ⊗[R] N →+ P := (addConGen (TensorProduct.Eqv R M N)).lift (FreeAddMonoid.lift (fun mn : M × N => f mn.1 mn.2)) <| AddCon.addConGen_le fun x y hxy => match x, y, hxy with | _, _, .of_zero_left n => (AddCon.ker_rel _).2 <| by simp_rw [map_zero, FreeAddMonoid.lift_eval_of, map_zero, AddMonoidHom.zero_apply] | _, _, .of_zero_right m => (AddCon.ker_rel _).2 <| by simp_rw [map_zero, FreeAddMonoid.lift_eval_of, map_zero] | _, _, .of_add_left m₁ m₂ n => (AddCon.ker_rel _).2 <| by simp_rw [map_add, FreeAddMonoid.lift_eval_of, map_add, AddMonoidHom.add_apply] | _, _, .of_add_right m n₁ n₂ => (AddCon.ker_rel _).2 <| by simp_rw [map_add, FreeAddMonoid.lift_eval_of, map_add] | _, _, .of_smul s m n => (AddCon.ker_rel _).2 <| by rw [FreeAddMonoid.lift_eval_of, FreeAddMonoid.lift_eval_of, hf] | _, _, .add_comm x y => (AddCon.ker_rel _).2 <| by simp_rw [map_add, add_comm] @[simp] theorem liftAddHom_tmul (f : M →+ N →+ P) (hf : ∀ (r : R) (m : M) (n : N), f (r • m) n = f m (r • n)) (m : M) (n : N) : liftAddHom f hf (m ⊗ₜ n) = f m n := rfl variable (M) in @[simp] theorem zero_tmul (n : N) : (0 : M) ⊗ₜ[R] n = 0 := Quotient.sound' <| AddConGen.Rel.of _ _ <| Eqv.of_zero_left _ theorem add_tmul (m₁ m₂ : M) (n : N) : (m₁ + m₂) ⊗ₜ n = m₁ ⊗ₜ n + m₂ ⊗ₜ[R] n := Eq.symm <| Quotient.sound' <| AddConGen.Rel.of _ _ <| Eqv.of_add_left _ _ _ variable (N) in @[simp] theorem tmul_zero (m : M) : m ⊗ₜ[R] (0 : N) = 0 := Quotient.sound' <| AddConGen.Rel.of _ _ <| Eqv.of_zero_right _ theorem tmul_add (m : M) (n₁ n₂ : N) : m ⊗ₜ (n₁ + n₂) = m ⊗ₜ n₁ + m ⊗ₜ[R] n₂ := Eq.symm <| Quotient.sound' <| AddConGen.Rel.of _ _ <| Eqv.of_add_right _ _ _ instance uniqueLeft [Subsingleton M] : Unique (M ⊗[R] N) where default := 0 uniq z := z.induction_on rfl (fun x y ↦ by rw [Subsingleton.elim x 0, zero_tmul]) <| by rintro _ _ rfl rfl; apply add_zero instance uniqueRight [Subsingleton N] : Unique (M ⊗[R] N) where default := 0 uniq z := z.induction_on rfl (fun x y ↦ by rw [Subsingleton.elim y 0, tmul_zero]) <| by rintro _ _ rfl rfl; apply add_zero section variable (R R' M N) /-- A typeclass for `SMul` structures which can be moved across a tensor product. This typeclass is generated automatically from an `IsScalarTower` instance, but exists so that we can also add an instance for `AddCommGroup.toIntModule`, allowing `z •` to be moved even if `R` does not support negation. Note that `Module R' (M ⊗[R] N)` is available even without this typeclass on `R'`; it's only needed if `TensorProduct.smul_tmul`, `TensorProduct.smul_tmul'`, or `TensorProduct.tmul_smul` is used. -/ class CompatibleSMul [DistribMulAction R' N] : Prop where smul_tmul : ∀ (r : R') (m : M) (n : N), (r • m) ⊗ₜ n = m ⊗ₜ[R] (r • n) end /-- Note that this provides the default `CompatibleSMul R R M N` instance through `IsScalarTower.left`. -/ instance (priority := 100) CompatibleSMul.isScalarTower [SMul R' R] [IsScalarTower R' R M] [DistribMulAction R' N] [IsScalarTower R' R N] : CompatibleSMul R R' M N := ⟨fun r m n => by conv_lhs => rw [← one_smul R m] conv_rhs => rw [← one_smul R n] rw [← smul_assoc, ← smul_assoc] exact Quotient.sound' <| AddConGen.Rel.of _ _ <| Eqv.of_smul _ _ _⟩ /-- `smul` can be moved from one side of the product to the other . -/ theorem smul_tmul [DistribMulAction R' N] [CompatibleSMul R R' M N] (r : R') (m : M) (n : N) : (r • m) ⊗ₜ n = m ⊗ₜ[R] (r • n) := CompatibleSMul.smul_tmul _ _ _ private def addMonoidWithWrongNSMul : AddMonoid (M ⊗[R] N) := { (addConGen (TensorProduct.Eqv R M N)).addMonoid with } attribute [local instance] addMonoidWithWrongNSMul in /-- Auxiliary function to defining scalar multiplication on tensor product. -/ def SMul.aux {R' : Type*} [SMul R' M] (r : R') : FreeAddMonoid (M × N) →+ M ⊗[R] N := FreeAddMonoid.lift fun p : M × N => (r • p.1) ⊗ₜ p.2 theorem SMul.aux_of {R' : Type*} [SMul R' M] (r : R') (m : M) (n : N) : SMul.aux r (.of (m, n)) = (r • m) ⊗ₜ[R] n := rfl variable [SMulCommClass R R' M] [SMulCommClass R R'' M] /-- Given two modules over a commutative semiring `R`, if one of the factors carries a (distributive) action of a second type of scalars `R'`, which commutes with the action of `R`, then the tensor product (over `R`) carries an action of `R'`. This instance defines this `R'` action in the case that it is the left module which has the `R'` action. Two natural ways in which this situation arises are: * Extension of scalars * A tensor product of a group representation with a module not carrying an action Note that in the special case that `R = R'`, since `R` is commutative, we just get the usual scalar action on a tensor product of two modules. This special case is important enough that, for performance reasons, we define it explicitly below. -/ instance leftHasSMul : SMul R' (M ⊗[R] N) := ⟨fun r => (addConGen (TensorProduct.Eqv R M N)).lift (SMul.aux r : _ →+ M ⊗[R] N) <| AddCon.addConGen_le fun x y hxy => match x, y, hxy with | _, _, .of_zero_left n => (AddCon.ker_rel _).2 <| by simp_rw [map_zero, SMul.aux_of, smul_zero, zero_tmul] | _, _, .of_zero_right m => (AddCon.ker_rel _).2 <| by simp_rw [map_zero, SMul.aux_of, tmul_zero] | _, _, .of_add_left m₁ m₂ n => (AddCon.ker_rel _).2 <| by simp_rw [map_add, SMul.aux_of, smul_add, add_tmul] | _, _, .of_add_right m n₁ n₂ => (AddCon.ker_rel _).2 <| by simp_rw [map_add, SMul.aux_of, tmul_add] | _, _, .of_smul s m n => (AddCon.ker_rel _).2 <| by rw [SMul.aux_of, SMul.aux_of, ← smul_comm, smul_tmul] | _, _, .add_comm x y => (AddCon.ker_rel _).2 <| by simp_rw [map_add, add_comm]⟩ instance : SMul R (M ⊗[R] N) := TensorProduct.leftHasSMul protected theorem smul_zero (r : R') : r • (0 : M ⊗[R] N) = 0 := AddMonoidHom.map_zero _ protected theorem smul_add (r : R') (x y : M ⊗[R] N) : r • (x + y) = r • x + r • y := AddMonoidHom.map_add _ _ _ protected theorem zero_smul (x : M ⊗[R] N) : (0 : R'') • x = 0 := have : ∀ (r : R'') (m : M) (n : N), r • m ⊗ₜ[R] n = (r • m) ⊗ₜ n := fun _ _ _ => rfl x.induction_on (by rw [TensorProduct.smul_zero]) (fun m n => by rw [this, zero_smul, zero_tmul]) fun x y ihx ihy => by rw [TensorProduct.smul_add, ihx, ihy, add_zero] protected theorem one_smul (x : M ⊗[R] N) : (1 : R') • x = x := have : ∀ (r : R') (m : M) (n : N), r • m ⊗ₜ[R] n = (r • m) ⊗ₜ n := fun _ _ _ => rfl x.induction_on (by rw [TensorProduct.smul_zero]) (fun m n => by rw [this, one_smul]) fun x y ihx ihy => by rw [TensorProduct.smul_add, ihx, ihy] protected theorem add_smul (r s : R'') (x : M ⊗[R] N) : (r + s) • x = r • x + s • x := have : ∀ (r : R'') (m : M) (n : N), r • m ⊗ₜ[R] n = (r • m) ⊗ₜ n := fun _ _ _ => rfl x.induction_on (by simp_rw [TensorProduct.smul_zero, add_zero]) (fun m n => by simp_rw [this, add_smul, add_tmul]) fun x y ihx ihy => by simp_rw [TensorProduct.smul_add] rw [ihx, ihy, add_add_add_comm] instance addMonoid : AddMonoid (M ⊗[R] N) := { TensorProduct.addZeroClass _ _ with toAddSemigroup := TensorProduct.addSemigroup _ _ toZero := TensorProduct.zero _ _ nsmul := fun n v => n • v nsmul_zero := by simp [TensorProduct.zero_smul] nsmul_succ := by simp only [TensorProduct.one_smul, TensorProduct.add_smul, add_comm, forall_const] } instance addCommMonoid : AddCommMonoid (M ⊗[R] N) := { TensorProduct.addCommSemigroup _ _ with toAddMonoid := TensorProduct.addMonoid } instance leftDistribMulAction : DistribMulAction R' (M ⊗[R] N) := have : ∀ (r : R') (m : M) (n : N), r • m ⊗ₜ[R] n = (r • m) ⊗ₜ n := fun _ _ _ => rfl { smul_add := fun r x y => TensorProduct.smul_add r x y mul_smul := fun r s x => x.induction_on (by simp_rw [TensorProduct.smul_zero]) (fun m n => by simp_rw [this, mul_smul]) fun x y ihx ihy => by simp_rw [TensorProduct.smul_add] rw [ihx, ihy] one_smul := TensorProduct.one_smul smul_zero := TensorProduct.smul_zero } instance : DistribMulAction R (M ⊗[R] N) := TensorProduct.leftDistribMulAction theorem smul_tmul' (r : R') (m : M) (n : N) : r • m ⊗ₜ[R] n = (r • m) ⊗ₜ n := rfl @[simp] theorem tmul_smul [DistribMulAction R' N] [CompatibleSMul R R' M N] (r : R') (x : M) (y : N) : x ⊗ₜ (r • y) = r • x ⊗ₜ[R] y := (smul_tmul _ _ _).symm theorem smul_tmul_smul (r s : R) (m : M) (n : N) : (r • m) ⊗ₜ[R] (s • n) = (r * s) • m ⊗ₜ[R] n := by simp_rw [smul_tmul, tmul_smul, mul_smul] instance leftModule : Module R'' (M ⊗[R] N) := { add_smul := TensorProduct.add_smul zero_smul := TensorProduct.zero_smul } instance : Module R (M ⊗[R] N) := TensorProduct.leftModule instance [Module R''ᵐᵒᵖ M] [IsCentralScalar R'' M] : IsCentralScalar R'' (M ⊗[R] N) where op_smul_eq_smul r x := x.induction_on (by rw [smul_zero, smul_zero]) (fun x y => by rw [smul_tmul', smul_tmul', op_smul_eq_smul]) fun x y hx hy => by rw [smul_add, smul_add, hx, hy] section -- Like `R'`, `R'₂` provides a `DistribMulAction R'₂ (M ⊗[R] N)` variable {R'₂ : Type*} [Monoid R'₂] [DistribMulAction R'₂ M] variable [SMulCommClass R R'₂ M] /-- `SMulCommClass R' R'₂ M` implies `SMulCommClass R' R'₂ (M ⊗[R] N)` -/ instance smulCommClass_left [SMulCommClass R' R'₂ M] : SMulCommClass R' R'₂ (M ⊗[R] N) where smul_comm r' r'₂ x := TensorProduct.induction_on x (by simp_rw [TensorProduct.smul_zero]) (fun m n => by simp_rw [smul_tmul', smul_comm]) fun x y ihx ihy => by simp_rw [TensorProduct.smul_add]; rw [ihx, ihy] variable [SMul R'₂ R'] /-- `IsScalarTower R'₂ R' M` implies `IsScalarTower R'₂ R' (M ⊗[R] N)` -/ instance isScalarTower_left [IsScalarTower R'₂ R' M] : IsScalarTower R'₂ R' (M ⊗[R] N) := ⟨fun s r x => x.induction_on (by simp) (fun m n => by rw [smul_tmul', smul_tmul', smul_tmul', smul_assoc]) fun x y ihx ihy => by rw [smul_add, smul_add, smul_add, ihx, ihy]⟩ variable [DistribMulAction R'₂ N] [DistribMulAction R' N] variable [CompatibleSMul R R'₂ M N] [CompatibleSMul R R' M N] /-- `IsScalarTower R'₂ R' N` implies `IsScalarTower R'₂ R' (M ⊗[R] N)` -/ instance isScalarTower_right [IsScalarTower R'₂ R' N] : IsScalarTower R'₂ R' (M ⊗[R] N) := ⟨fun s r x => x.induction_on (by simp) (fun m n => by rw [← tmul_smul, ← tmul_smul, ← tmul_smul, smul_assoc]) fun x y ihx ihy => by rw [smul_add, smul_add, smul_add, ihx, ihy]⟩ end /-- A short-cut instance for the common case, where the requirements for the `compatible_smul` instances are sufficient. -/ instance isScalarTower [SMul R' R] [IsScalarTower R' R M] : IsScalarTower R' R (M ⊗[R] N) := TensorProduct.isScalarTower_left -- or right variable (R M N) in /-- The canonical bilinear map `M → N → M ⊗[R] N`. -/ def mk : M →ₗ[R] N →ₗ[R] M ⊗[R] N := LinearMap.mk₂ R (· ⊗ₜ ·) add_tmul (fun c m n => by simp_rw [smul_tmul, tmul_smul]) tmul_add tmul_smul @[simp] theorem mk_apply (m : M) (n : N) : mk R M N m n = m ⊗ₜ n := rfl theorem ite_tmul (x₁ : M) (x₂ : N) (P : Prop) [Decidable P] : (if P then x₁ else 0) ⊗ₜ[R] x₂ = if P then x₁ ⊗ₜ x₂ else 0 := by split_ifs <;> simp theorem tmul_ite (x₁ : M) (x₂ : N) (P : Prop) [Decidable P] : (x₁ ⊗ₜ[R] if P then x₂ else 0) = if P then x₁ ⊗ₜ x₂ else 0 := by split_ifs <;> simp lemma tmul_single {ι : Type*} [DecidableEq ι] {M : ι → Type*} [∀ i, AddCommMonoid (M i)] [∀ i, Module R (M i)] (i : ι) (x : N) (m : M i) (j : ι) : x ⊗ₜ[R] Pi.single i m j = (Pi.single i (x ⊗ₜ[R] m) : ∀ i, N ⊗[R] M i) j := by by_cases h : i = j <;> aesop lemma single_tmul {ι : Type*} [DecidableEq ι] {M : ι → Type*} [∀ i, AddCommMonoid (M i)] [∀ i, Module R (M i)] (i : ι) (x : N) (m : M i) (j : ι) : Pi.single i m j ⊗ₜ[R] x = (Pi.single i (m ⊗ₜ[R] x) : ∀ i, M i ⊗[R] N) j := by by_cases h : i = j <;> aesop section theorem sum_tmul {α : Type*} (s : Finset α) (m : α → M) (n : N) : (∑ a ∈ s, m a) ⊗ₜ[R] n = ∑ a ∈ s, m a ⊗ₜ[R] n := by classical induction s using Finset.induction with | empty => simp | insert _ _ has ih => simp [Finset.sum_insert has, add_tmul, ih] theorem tmul_sum (m : M) {α : Type*} (s : Finset α) (n : α → N) : (m ⊗ₜ[R] ∑ a ∈ s, n a) = ∑ a ∈ s, m ⊗ₜ[R] n a := by classical induction s using Finset.induction with | empty => simp | insert _ _ has ih => simp [Finset.sum_insert has, tmul_add, ih] end variable (R M N) /-- The simple (aka pure) elements span the tensor product. -/ theorem span_tmul_eq_top : Submodule.span R { t : M ⊗[R] N | ∃ m n, m ⊗ₜ n = t } = ⊤ := by ext t; simp only [Submodule.mem_top, iff_true] refine t.induction_on ?_ ?_ ?_ · exact Submodule.zero_mem _ · intro m n apply Submodule.subset_span use m, n · intro t₁ t₂ ht₁ ht₂ exact Submodule.add_mem _ ht₁ ht₂ @[simp] theorem map₂_mk_top_top_eq_top : Submodule.map₂ (mk R M N) ⊤ ⊤ = ⊤ := by rw [← top_le_iff, ← span_tmul_eq_top, Submodule.map₂_eq_span_image2] exact Submodule.span_mono fun _ ⟨m, n, h⟩ => ⟨m, trivial, n, trivial, h⟩ theorem exists_eq_tmul_of_forall (x : TensorProduct R M N) (h : ∀ (m₁ m₂ : M) (n₁ n₂ : N), ∃ m n, m₁ ⊗ₜ n₁ + m₂ ⊗ₜ n₂ = m ⊗ₜ[R] n) : ∃ m n, x = m ⊗ₜ n := by induction x with | zero => use 0, 0 rw [TensorProduct.zero_tmul] | tmul m n => use m, n | add x y h₁ h₂ => obtain ⟨m₁, n₁, rfl⟩ := h₁ obtain ⟨m₂, n₂, rfl⟩ := h₂ apply h end Module variable [Module R P] section UniversalProperty variable {M N} variable (f : M →ₗ[R] N →ₗ[R] P) /-- Auxiliary function to constructing a linear map `M ⊗ N → P` given a bilinear map `M → N → P` with the property that its composition with the canonical bilinear map `M → N → M ⊗ N` is the given bilinear map `M → N → P`. -/ def liftAux : M ⊗[R] N →+ P := liftAddHom (LinearMap.toAddMonoidHom'.comp <| f.toAddMonoidHom) fun r m n => by dsimp; rw [LinearMap.map_smul₂, map_smul] theorem liftAux_tmul (m n) : liftAux f (m ⊗ₜ n) = f m n := rfl variable {f} @[simp] theorem liftAux.smul (r : R) (x) : liftAux f (r • x) = r • liftAux f x := TensorProduct.induction_on x (smul_zero _).symm (fun p q => by simp_rw [← tmul_smul, liftAux_tmul, (f p).map_smul]) fun p q ih1 ih2 => by simp_rw [smul_add, (liftAux f).map_add, ih1, ih2, smul_add] variable (f) in /-- Constructing a linear map `M ⊗ N → P` given a bilinear map `M → N → P` with the property that its composition with the canonical bilinear map `M → N → M ⊗ N` is the given bilinear map `M → N → P`. -/ def lift : M ⊗[R] N →ₗ[R] P := { liftAux f with map_smul' := liftAux.smul } @[simp] theorem lift.tmul (x y) : lift f (x ⊗ₜ y) = f x y := rfl @[simp] theorem lift.tmul' (x y) : (lift f).1 (x ⊗ₜ y) = f x y := rfl theorem ext' {g h : M ⊗[R] N →ₗ[R] P} (H : ∀ x y, g (x ⊗ₜ y) = h (x ⊗ₜ y)) : g = h := LinearMap.ext fun z => TensorProduct.induction_on z (by simp_rw [LinearMap.map_zero]) H fun x y ihx ihy => by rw [g.map_add, h.map_add, ihx, ihy] theorem lift.unique {g : M ⊗[R] N →ₗ[R] P} (H : ∀ x y, g (x ⊗ₜ y) = f x y) : g = lift f := ext' fun m n => by rw [H, lift.tmul] theorem lift_mk : lift (mk R M N) = LinearMap.id := Eq.symm <| lift.unique fun _ _ => rfl theorem lift_compr₂ (g : P →ₗ[R] Q) : lift (f.compr₂ g) = g.comp (lift f) := Eq.symm <| lift.unique fun _ _ => by simp theorem lift_mk_compr₂ (f : M ⊗ N →ₗ[R] P) : lift ((mk R M N).compr₂ f) = f := by rw [lift_compr₂ f, lift_mk, LinearMap.comp_id] /-- This used to be an `@[ext]` lemma, but it fails very slowly when the `ext` tactic tries to apply it in some cases, notably when one wants to show equality of two linear maps. The `@[ext]` attribute is now added locally where it is needed. Using this as the `@[ext]` lemma instead of `TensorProduct.ext'` allows `ext` to apply lemmas specific to `M →ₗ _` and `N →ₗ _`. See note [partially-applied ext lemmas]. -/ theorem ext {g h : M ⊗ N →ₗ[R] P} (H : (mk R M N).compr₂ g = (mk R M N).compr₂ h) : g = h := by rw [← lift_mk_compr₂ g, H, lift_mk_compr₂] attribute [local ext high] ext example : M → N → (M → N → P) → P := fun m => flip fun f => f m variable (R M N P) in /-- Linearly constructing a linear map `M ⊗ N → P` given a bilinear map `M → N → P` with the property that its composition with the canonical bilinear map `M → N → M ⊗ N` is the given bilinear map `M → N → P`. -/ def uncurry : (M →ₗ[R] N →ₗ[R] P) →ₗ[R] M ⊗[R] N →ₗ[R] P := LinearMap.flip <| lift <| LinearMap.lflip.comp (LinearMap.flip LinearMap.id) @[simp] theorem uncurry_apply (f : M →ₗ[R] N →ₗ[R] P) (m : M) (n : N) : uncurry R M N P f (m ⊗ₜ n) = f m n := by rw [uncurry, LinearMap.flip_apply, lift.tmul]; rfl variable (R M N P) /-- A linear equivalence constructing a linear map `M ⊗ N → P` given a bilinear map `M → N → P` with the property that its composition with the canonical bilinear map `M → N → M ⊗ N` is the given bilinear map `M → N → P`. -/ def lift.equiv : (M →ₗ[R] N →ₗ[R] P) ≃ₗ[R] M ⊗[R] N →ₗ[R] P := { uncurry R M N P with invFun := fun f => (mk R M N).compr₂ f left_inv := fun _ => LinearMap.ext₂ fun _ _ => lift.tmul _ _ right_inv := fun _ => ext' fun _ _ => lift.tmul _ _ } @[simp] theorem lift.equiv_apply (f : M →ₗ[R] N →ₗ[R] P) (m : M) (n : N) : lift.equiv R M N P f (m ⊗ₜ n) = f m n := uncurry_apply f m n @[simp] theorem lift.equiv_symm_apply (f : M ⊗[R] N →ₗ[R] P) (m : M) (n : N) : (lift.equiv R M N P).symm f m n = f (m ⊗ₜ n) := rfl /-- Given a linear map `M ⊗ N → P`, compose it with the canonical bilinear map `M → N → M ⊗ N` to form a bilinear map `M → N → P`. -/ def lcurry : (M ⊗[R] N →ₗ[R] P) →ₗ[R] M →ₗ[R] N →ₗ[R] P := (lift.equiv R M N P).symm variable {R M N P} @[simp] theorem lcurry_apply (f : M ⊗[R] N →ₗ[R] P) (m : M) (n : N) : lcurry R M N P f m n = f (m ⊗ₜ n) := rfl /-- Given a linear map `M ⊗ N → P`, compose it with the canonical bilinear map `M → N → M ⊗ N` to form a bilinear map `M → N → P`. -/ def curry (f : M ⊗[R] N →ₗ[R] P) : M →ₗ[R] N →ₗ[R] P := lcurry R M N P f @[simp] theorem curry_apply (f : M ⊗ N →ₗ[R] P) (m : M) (n : N) : curry f m n = f (m ⊗ₜ n) := rfl theorem curry_injective : Function.Injective (curry : (M ⊗[R] N →ₗ[R] P) → M →ₗ[R] N →ₗ[R] P) := fun _ _ H => ext H theorem ext_threefold {g h : (M ⊗[R] N) ⊗[R] P →ₗ[R] Q} (H : ∀ x y z, g (x ⊗ₜ y ⊗ₜ z) = h (x ⊗ₜ y ⊗ₜ z)) : g = h := by ext x y z exact H x y z -- We'll need this one for checking the pentagon identity! theorem ext_fourfold {g h : ((M ⊗[R] N) ⊗[R] P) ⊗[R] Q →ₗ[R] S} (H : ∀ w x y z, g (w ⊗ₜ x ⊗ₜ y ⊗ₜ z) = h (w ⊗ₜ x ⊗ₜ y ⊗ₜ z)) : g = h := by ext w x y z exact H w x y z /-- Two linear maps (M ⊗ N) ⊗ (P ⊗ Q) → S which agree on all elements of the form (m ⊗ₜ n) ⊗ₜ (p ⊗ₜ q) are equal. -/ theorem ext_fourfold' {φ ψ : (M ⊗[R] N) ⊗[R] P ⊗[R] Q →ₗ[R] S} (H : ∀ w x y z, φ (w ⊗ₜ x ⊗ₜ (y ⊗ₜ z)) = ψ (w ⊗ₜ x ⊗ₜ (y ⊗ₜ z))) : φ = ψ := by ext m n p q exact H m n p q end UniversalProperty variable {M N} section variable (R M N) /-- The tensor product of modules is commutative, up to linear equivalence. -/ protected def comm : M ⊗[R] N ≃ₗ[R] N ⊗[R] M := LinearEquiv.ofLinear (lift (mk R N M).flip) (lift (mk R M N).flip) (ext' fun _ _ => rfl) (ext' fun _ _ => rfl) @[simp] theorem comm_tmul (m : M) (n : N) : (TensorProduct.comm R M N) (m ⊗ₜ n) = n ⊗ₜ m := rfl @[simp] theorem comm_symm_tmul (m : M) (n : N) : (TensorProduct.comm R M N).symm (n ⊗ₜ m) = m ⊗ₜ n := rfl lemma lift_comp_comm_eq (f : M →ₗ[R] N →ₗ[R] P) : lift f ∘ₗ TensorProduct.comm R N M = lift f.flip := ext rfl end section CompatibleSMul variable (R A M N) [CommSemiring A] [Module A M] [Module A N] [SMulCommClass R A M] [CompatibleSMul R A M N] /-- If M and N are both R- and A-modules and their actions on them commute, and if the A-action on `M ⊗[R] N` can switch between the two factors, then there is a canonical A-linear map from `M ⊗[A] N` to `M ⊗[R] N`. -/ def mapOfCompatibleSMul : M ⊗[A] N →ₗ[A] M ⊗[R] N := lift { toFun := fun m ↦ { __ := mk R M N m map_smul' := fun _ _ ↦ (smul_tmul _ _ _).symm } map_add' := fun _ _ ↦ LinearMap.ext <| by simp map_smul' := fun _ _ ↦ rfl } @[simp] theorem mapOfCompatibleSMul_tmul (m n) : mapOfCompatibleSMul R A M N (m ⊗ₜ n) = m ⊗ₜ n := rfl theorem mapOfCompatibleSMul_surjective : Function.Surjective (mapOfCompatibleSMul R A M N) := fun x ↦ x.induction_on (⟨0, map_zero _⟩) (fun m n ↦ ⟨_, mapOfCompatibleSMul_tmul ..⟩) fun _ _ ⟨x, hx⟩ ⟨y, hy⟩ ↦ ⟨x + y, by simpa using congr($hx + $hy)⟩ attribute [local instance] SMulCommClass.symm /-- `mapOfCompatibleSMul R A M N` is also R-linear. -/ def mapOfCompatibleSMul' : M ⊗[A] N →ₗ[R] M ⊗[R] N where __ := mapOfCompatibleSMul R A M N map_smul' _ x := x.induction_on (map_zero _) (fun _ _ ↦ by simp [smul_tmul']) fun _ _ h h' ↦ by simpa using congr($h + $h') /-- If the R- and A-actions on M and N satisfy `CompatibleSMul` both ways, then `M ⊗[A] N` is canonically isomorphic to `M ⊗[R] N`. -/ def equivOfCompatibleSMul [CompatibleSMul A R M N] : M ⊗[A] N ≃ₗ[A] M ⊗[R] N where __ := mapOfCompatibleSMul R A M N invFun := mapOfCompatibleSMul A R M N left_inv x := x.induction_on (map_zero _) (fun _ _ ↦ rfl) fun _ _ h h' ↦ by simpa using congr($h + $h') right_inv x := x.induction_on (map_zero _) (fun _ _ ↦ rfl) fun _ _ h h' ↦ by simpa using congr($h + $h') omit [SMulCommClass R A M] end CompatibleSMul open LinearMap /-- The tensor product of a pair of linear maps between modules. -/ def map (f : M →ₗ[R] P) (g : N →ₗ[R] Q) : M ⊗[R] N →ₗ[R] P ⊗[R] Q := lift <| comp (compl₂ (mk _ _ _) g) f @[simp] theorem map_tmul (f : M →ₗ[R] P) (g : N →ₗ[R] Q) (m : M) (n : N) : map f g (m ⊗ₜ n) = f m ⊗ₜ g n := rfl /-- Given linear maps `f : M → P`, `g : N → Q`, if we identify `M ⊗ N` with `N ⊗ M` and `P ⊗ Q` with `Q ⊗ P`, then this lemma states that `f ⊗ g = g ⊗ f`. -/ lemma map_comp_comm_eq (f : M →ₗ[R] P) (g : N →ₗ[R] Q) : map f g ∘ₗ TensorProduct.comm R N M = TensorProduct.comm R Q P ∘ₗ map g f := ext rfl lemma map_comm (f : M →ₗ[R] P) (g : N →ₗ[R] Q) (x : N ⊗[R] M) : map f g (TensorProduct.comm R N M x) = TensorProduct.comm R Q P (map g f x) := DFunLike.congr_fun (map_comp_comm_eq _ _) _ theorem map_range_eq_span_tmul (f : M →ₗ[R] P) (g : N →ₗ[R] Q) : range (map f g) = Submodule.span R { t | ∃ m n, f m ⊗ₜ g n = t } := by simp only [← Submodule.map_top, ← span_tmul_eq_top, Submodule.map_span, Set.mem_image, Set.mem_setOf_eq] congr; ext t constructor · rintro ⟨_, ⟨⟨m, n, rfl⟩, rfl⟩⟩ use m, n simp only [map_tmul] · rintro ⟨m, n, rfl⟩ refine ⟨_, ⟨⟨m, n, rfl⟩, ?_⟩⟩ simp only [map_tmul] /-- Given submodules `p ⊆ P` and `q ⊆ Q`, this is the natural map: `p ⊗ q → P ⊗ Q`. -/ @[simp] def mapIncl (p : Submodule R P) (q : Submodule R Q) : p ⊗[R] q →ₗ[R] P ⊗[R] Q := map p.subtype q.subtype lemma range_mapIncl (p : Submodule R P) (q : Submodule R Q) : LinearMap.range (mapIncl p q) = Submodule.span R (Set.image2 (· ⊗ₜ ·) p q) := by rw [mapIncl, map_range_eq_span_tmul] congr; ext; simp theorem map₂_eq_range_lift_comp_mapIncl (f : P →ₗ[R] Q →ₗ[R] M) (p : Submodule R P) (q : Submodule R Q) : Submodule.map₂ f p q = LinearMap.range (lift f ∘ₗ mapIncl p q) := by simp_rw [LinearMap.range_comp, range_mapIncl, Submodule.map_span, Set.image_image2, Submodule.map₂_eq_span_image2, lift.tmul] section variable {P' Q' : Type*} variable [AddCommMonoid P'] [Module R P'] variable [AddCommMonoid Q'] [Module R Q'] theorem map_comp (f₂ : P →ₗ[R] P') (f₁ : M →ₗ[R] P) (g₂ : Q →ₗ[R] Q') (g₁ : N →ₗ[R] Q) : map (f₂.comp f₁) (g₂.comp g₁) = (map f₂ g₂).comp (map f₁ g₁) := ext' fun _ _ => rfl lemma range_mapIncl_mono {p p' : Submodule R P} {q q' : Submodule R Q} (hp : p ≤ p') (hq : q ≤ q') : LinearMap.range (mapIncl p q) ≤ LinearMap.range (mapIncl p' q') := by simp_rw [range_mapIncl] exact Submodule.span_mono (Set.image2_subset hp hq) theorem lift_comp_map (i : P →ₗ[R] Q →ₗ[R] Q') (f : M →ₗ[R] P) (g : N →ₗ[R] Q) : (lift i).comp (map f g) = lift ((i.comp f).compl₂ g) := ext' fun _ _ => rfl attribute [local ext high] ext @[simp] theorem map_id : map (id : M →ₗ[R] M) (id : N →ₗ[R] N) = .id := by ext simp only [mk_apply, id_coe, compr₂_apply, _root_.id, map_tmul] @[simp] protected theorem map_one : map (1 : M →ₗ[R] M) (1 : N →ₗ[R] N) = 1 := map_id protected theorem map_mul (f₁ f₂ : M →ₗ[R] M) (g₁ g₂ : N →ₗ[R] N) : map (f₁ * f₂) (g₁ * g₂) = map f₁ g₁ * map f₂ g₂ := map_comp f₁ f₂ g₁ g₂ @[simp] protected theorem map_pow (f : M →ₗ[R] M) (g : N →ₗ[R] N) (n : ℕ) : map f g ^ n = map (f ^ n) (g ^ n) := by induction n with | zero => simp only [pow_zero, TensorProduct.map_one] | succ n ih => simp only [pow_succ', ih, TensorProduct.map_mul] theorem map_add_left (f₁ f₂ : M →ₗ[R] P) (g : N →ₗ[R] Q) : map (f₁ + f₂) g = map f₁ g + map f₂ g := by ext simp only [add_tmul, compr₂_apply, mk_apply, map_tmul, add_apply] theorem map_add_right (f : M →ₗ[R] P) (g₁ g₂ : N →ₗ[R] Q) : map f (g₁ + g₂) = map f g₁ + map f g₂ := by ext simp only [tmul_add, compr₂_apply, mk_apply, map_tmul, add_apply] theorem map_smul_left (r : R) (f : M →ₗ[R] P) (g : N →ₗ[R] Q) : map (r • f) g = r • map f g := by ext simp only [smul_tmul, compr₂_apply, mk_apply, map_tmul, smul_apply, tmul_smul] theorem map_smul_right (r : R) (f : M →ₗ[R] P) (g : N →ₗ[R] Q) : map f (r • g) = r • map f g := by ext simp only [smul_tmul, compr₂_apply, mk_apply, map_tmul, smul_apply, tmul_smul] variable (R M N P Q) /-- The tensor product of a pair of linear maps between modules, bilinear in both maps. -/ def mapBilinear : (M →ₗ[R] P) →ₗ[R] (N →ₗ[R] Q) →ₗ[R] M ⊗[R] N →ₗ[R] P ⊗[R] Q := LinearMap.mk₂ R map map_add_left map_smul_left map_add_right map_smul_right /-- The canonical linear map from `P ⊗[R] (M →ₗ[R] Q)` to `(M →ₗ[R] P ⊗[R] Q)` -/ def lTensorHomToHomLTensor : P ⊗[R] (M →ₗ[R] Q) →ₗ[R] M →ₗ[R] P ⊗[R] Q := TensorProduct.lift (llcomp R M Q _ ∘ₗ mk R P Q) /-- The canonical linear map from `(M →ₗ[R] P) ⊗[R] Q` to `(M →ₗ[R] P ⊗[R] Q)` -/ def rTensorHomToHomRTensor : (M →ₗ[R] P) ⊗[R] Q →ₗ[R] M →ₗ[R] P ⊗[R] Q := TensorProduct.lift (llcomp R M P _ ∘ₗ (mk R P Q).flip).flip /-- The linear map from `(M →ₗ P) ⊗ (N →ₗ Q)` to `(M ⊗ N →ₗ P ⊗ Q)` sending `f ⊗ₜ g` to the `TensorProduct.map f g`, the tensor product of the two maps. -/ def homTensorHomMap : (M →ₗ[R] P) ⊗[R] (N →ₗ[R] Q) →ₗ[R] M ⊗[R] N →ₗ[R] P ⊗[R] Q := lift (mapBilinear R M N P Q) variable {R M N P Q} /-- This is a binary version of `TensorProduct.map`: Given a bilinear map `f : M ⟶ P ⟶ Q` and a bilinear map `g : N ⟶ S ⟶ T`, if we think `f` and `g` as linear maps with two inputs, then `map₂ f g` is a bilinear map taking two inputs `M ⊗ N → P ⊗ S → Q ⊗ S` defined by `map₂ f g (m ⊗ n) (p ⊗ s) = f m p ⊗ g n s`. Mathematically, `TensorProduct.map₂` is defined as the composition `M ⊗ N -map→ Hom(P, Q) ⊗ Hom(S, T) -homTensorHomMap→ Hom(P ⊗ S, Q ⊗ T)`. -/ def map₂ (f : M →ₗ[R] P →ₗ[R] Q) (g : N →ₗ[R] S →ₗ[R] T) : M ⊗[R] N →ₗ[R] P ⊗[R] S →ₗ[R] Q ⊗[R] T := homTensorHomMap R _ _ _ _ ∘ₗ map f g @[simp] theorem mapBilinear_apply (f : M →ₗ[R] P) (g : N →ₗ[R] Q) : mapBilinear R M N P Q f g = map f g := rfl @[simp] theorem lTensorHomToHomLTensor_apply (p : P) (f : M →ₗ[R] Q) (m : M) : lTensorHomToHomLTensor R M P Q (p ⊗ₜ f) m = p ⊗ₜ f m := rfl @[simp] theorem rTensorHomToHomRTensor_apply (f : M →ₗ[R] P) (q : Q) (m : M) : rTensorHomToHomRTensor R M P Q (f ⊗ₜ q) m = f m ⊗ₜ q := rfl @[simp] theorem homTensorHomMap_apply (f : M →ₗ[R] P) (g : N →ₗ[R] Q) : homTensorHomMap R M N P Q (f ⊗ₜ g) = map f g := rfl @[simp] theorem map₂_apply_tmul (f : M →ₗ[R] P →ₗ[R] Q) (g : N →ₗ[R] S →ₗ[R] T) (m : M) (n : N) : map₂ f g (m ⊗ₜ n) = map (f m) (g n) := rfl @[simp] theorem map_zero_left (g : N →ₗ[R] Q) : map (0 : M →ₗ[R] P) g = 0 := (mapBilinear R M N P Q).map_zero₂ _ @[simp] theorem map_zero_right (f : M →ₗ[R] P) : map f (0 : N →ₗ[R] Q) = 0 := (mapBilinear R M N P Q _).map_zero end /-- If `M` and `P` are linearly equivalent and `N` and `Q` are linearly equivalent then `M ⊗ N` and `P ⊗ Q` are linearly equivalent. -/ def congr (f : M ≃ₗ[R] P) (g : N ≃ₗ[R] Q) : M ⊗[R] N ≃ₗ[R] P ⊗[R] Q := LinearEquiv.ofLinear (map f g) (map f.symm g.symm) (ext' fun m n => by simp) (ext' fun m n => by simp) @[simp] theorem congr_tmul (f : M ≃ₗ[R] P) (g : N ≃ₗ[R] Q) (m : M) (n : N) : congr f g (m ⊗ₜ n) = f m ⊗ₜ g n := rfl @[simp] theorem congr_symm_tmul (f : M ≃ₗ[R] P) (g : N ≃ₗ[R] Q) (p : P) (q : Q) : (congr f g).symm (p ⊗ₜ q) = f.symm p ⊗ₜ g.symm q := rfl theorem congr_symm (f : M ≃ₗ[R] P) (g : N ≃ₗ[R] Q) : (congr f g).symm = congr f.symm g.symm := rfl @[simp] theorem congr_refl_refl : congr (.refl R M) (.refl R N) = .refl R _ := LinearEquiv.toLinearMap_injective <| ext' fun _ _ ↦ rfl theorem congr_trans (f : M ≃ₗ[R] P) (g : N ≃ₗ[R] Q) (f' : P ≃ₗ[R] S) (g' : Q ≃ₗ[R] T) : congr (f ≪≫ₗ f') (g ≪≫ₗ g') = congr f g ≪≫ₗ congr f' g' := LinearEquiv.toLinearMap_injective <| map_comp _ _ _ _ theorem congr_mul (f : M ≃ₗ[R] M) (g : N ≃ₗ[R] N) (f' : M ≃ₗ[R] M) (g' : N ≃ₗ[R] N) : congr (f * f') (g * g') = congr f g * congr f' g' := congr_trans _ _ _ _ @[simp] theorem congr_pow (f : M ≃ₗ[R] M) (g : N ≃ₗ[R] N) (n : ℕ) : congr f g ^ n = congr (f ^ n) (g ^ n) := by induction n with | zero => exact congr_refl_refl.symm | succ n ih => simp_rw [pow_succ, ih, congr_mul] @[simp] theorem congr_zpow (f : M ≃ₗ[R] M) (g : N ≃ₗ[R] N) (n : ℤ) : congr f g ^ n = congr (f ^ n) (g ^ n) := by cases n with | ofNat n => exact congr_pow _ _ _ | negSucc n => simp_rw [zpow_negSucc, congr_pow]; exact congr_symm _ _ end TensorProduct open scoped TensorProduct variable [Module R P] namespace LinearMap variable {N} /-- `LinearMap.lTensor M f : M ⊗ N →ₗ M ⊗ P` is the natural linear map induced by `f : N →ₗ P`. -/ def lTensor (f : N →ₗ[R] P) : M ⊗[R] N →ₗ[R] M ⊗[R] P := TensorProduct.map id f /-- `LinearMap.rTensor M f : N₁ ⊗ M →ₗ N₂ ⊗ M` is the natural linear map induced by `f : N₁ →ₗ N₂`. -/ def rTensor (f : N →ₗ[R] P) : N ⊗[R] M →ₗ[R] P ⊗[R] M := TensorProduct.map f id variable (g : P →ₗ[R] Q) (f : N →ₗ[R] P) theorem lTensor_def : f.lTensor M = TensorProduct.map LinearMap.id f := rfl theorem rTensor_def : f.rTensor M = TensorProduct.map f LinearMap.id := rfl @[simp] theorem lTensor_tmul (m : M) (n : N) : f.lTensor M (m ⊗ₜ n) = m ⊗ₜ f n := rfl @[simp] theorem rTensor_tmul (m : M) (n : N) : f.rTensor M (n ⊗ₜ m) = f n ⊗ₜ m := rfl @[simp] theorem lTensor_comp_mk (m : M) : f.lTensor M ∘ₗ TensorProduct.mk R M N m = TensorProduct.mk R M P m ∘ₗ f := rfl @[simp] theorem rTensor_comp_flip_mk (m : M) : f.rTensor M ∘ₗ (TensorProduct.mk R N M).flip m = (TensorProduct.mk R P M).flip m ∘ₗ f := rfl lemma comm_comp_rTensor_comp_comm_eq (g : N →ₗ[R] P) : TensorProduct.comm R P Q ∘ₗ rTensor Q g ∘ₗ TensorProduct.comm R Q N = lTensor Q g := TensorProduct.ext rfl lemma comm_comp_lTensor_comp_comm_eq (g : N →ₗ[R] P) : TensorProduct.comm R Q P ∘ₗ lTensor Q g ∘ₗ TensorProduct.comm R N Q = rTensor Q g := TensorProduct.ext rfl /-- Given a linear map `f : N → P`, `f ⊗ M` is injective if and only if `M ⊗ f` is injective. -/ theorem lTensor_inj_iff_rTensor_inj : Function.Injective (lTensor M f) ↔ Function.Injective (rTensor M f) := by simp [← comm_comp_rTensor_comp_comm_eq] /-- Given a linear map `f : N → P`, `f ⊗ M` is surjective if and only if `M ⊗ f` is surjective. -/ theorem lTensor_surj_iff_rTensor_surj : Function.Surjective (lTensor M f) ↔ Function.Surjective (rTensor M f) := by simp [← comm_comp_rTensor_comp_comm_eq] /-- Given a linear map `f : N → P`, `f ⊗ M` is bijective if and only if `M ⊗ f` is bijective. -/ theorem lTensor_bij_iff_rTensor_bij : Function.Bijective (lTensor M f) ↔ Function.Bijective (rTensor M f) := by simp [← comm_comp_rTensor_comp_comm_eq] open TensorProduct attribute [local ext high] TensorProduct.ext /-- `lTensorHom M` is the natural linear map that sends a linear map `f : N →ₗ P` to `M ⊗ f`. See also `Module.End.lTensorAlgHom`. -/ def lTensorHom : (N →ₗ[R] P) →ₗ[R] M ⊗[R] N →ₗ[R] M ⊗[R] P where toFun := lTensor M map_add' f g := by ext x y simp only [compr₂_apply, mk_apply, add_apply, lTensor_tmul, tmul_add] map_smul' r f := by dsimp ext x y simp only [compr₂_apply, mk_apply, tmul_smul, smul_apply, lTensor_tmul] /-- `rTensorHom M` is the natural linear map that sends a linear map `f : N →ₗ P` to `f ⊗ M`. See also `Module.End.rTensorAlgHom`. -/ def rTensorHom : (N →ₗ[R] P) →ₗ[R] N ⊗[R] M →ₗ[R] P ⊗[R] M where toFun f := f.rTensor M map_add' f g := by ext x y simp only [compr₂_apply, mk_apply, add_apply, rTensor_tmul, add_tmul] map_smul' r f := by dsimp ext x y simp only [compr₂_apply, mk_apply, smul_tmul, tmul_smul, smul_apply, rTensor_tmul] @[simp] theorem coe_lTensorHom : (lTensorHom M : (N →ₗ[R] P) → M ⊗[R] N →ₗ[R] M ⊗[R] P) = lTensor M := rfl @[simp] theorem coe_rTensorHom : (rTensorHom M : (N →ₗ[R] P) → N ⊗[R] M →ₗ[R] P ⊗[R] M) = rTensor M := rfl @[simp] theorem lTensor_add (f g : N →ₗ[R] P) : (f + g).lTensor M = f.lTensor M + g.lTensor M := (lTensorHom M).map_add f g @[simp] theorem rTensor_add (f g : N →ₗ[R] P) : (f + g).rTensor M = f.rTensor M + g.rTensor M := (rTensorHom M).map_add f g @[simp] theorem lTensor_zero : lTensor M (0 : N →ₗ[R] P) = 0 := (lTensorHom M).map_zero @[simp] theorem rTensor_zero : rTensor M (0 : N →ₗ[R] P) = 0 := (rTensorHom M).map_zero @[simp] theorem lTensor_smul (r : R) (f : N →ₗ[R] P) : (r • f).lTensor M = r • f.lTensor M := (lTensorHom M).map_smul r f @[simp] theorem rTensor_smul (r : R) (f : N →ₗ[R] P) : (r • f).rTensor M = r • f.rTensor M := (rTensorHom M).map_smul r f theorem lTensor_comp : (g.comp f).lTensor M = (g.lTensor M).comp (f.lTensor M) := by ext m n simp only [compr₂_apply, mk_apply, comp_apply, lTensor_tmul] theorem lTensor_comp_apply (x : M ⊗[R] N) : (g.comp f).lTensor M x = (g.lTensor M) ((f.lTensor M) x) := by rw [lTensor_comp, coe_comp]; rfl theorem rTensor_comp : (g.comp f).rTensor M = (g.rTensor M).comp (f.rTensor M) := by ext m n simp only [compr₂_apply, mk_apply, comp_apply, rTensor_tmul] theorem rTensor_comp_apply (x : N ⊗[R] M) : (g.comp f).rTensor M x = (g.rTensor M) ((f.rTensor M) x) := by rw [rTensor_comp, coe_comp]; rfl theorem lTensor_mul (f g : Module.End R N) : (f * g).lTensor M = f.lTensor M * g.lTensor M := lTensor_comp M f g theorem rTensor_mul (f g : Module.End R N) : (f * g).rTensor M = f.rTensor M * g.rTensor M := rTensor_comp M f g variable (N) @[simp] theorem lTensor_id : (id : N →ₗ[R] N).lTensor M = id := map_id -- `simp` can prove this. theorem lTensor_id_apply (x : M ⊗[R] N) : (LinearMap.id : N →ₗ[R] N).lTensor M x = x := by rw [lTensor_id, id_coe, _root_.id] @[simp] theorem rTensor_id : (id : N →ₗ[R] N).rTensor M = id := map_id -- `simp` can prove this. theorem rTensor_id_apply (x : N ⊗[R] M) : (LinearMap.id : N →ₗ[R] N).rTensor M x = x := by rw [rTensor_id, id_coe, _root_.id] @[simp] theorem lTensor_smul_action (r : R) : (DistribMulAction.toLinearMap R N r).lTensor M = DistribMulAction.toLinearMap R (M ⊗[R] N) r := (lTensor_smul M r LinearMap.id).trans (congrArg _ (lTensor_id M N)) @[simp] theorem rTensor_smul_action (r : R) : (DistribMulAction.toLinearMap R N r).rTensor M = DistribMulAction.toLinearMap R (N ⊗[R] M) r := (rTensor_smul M r LinearMap.id).trans (congrArg _ (rTensor_id M N)) variable {N} @[simp] theorem lTensor_comp_rTensor (f : M →ₗ[R] P) (g : N →ₗ[R] Q) : (g.lTensor P).comp (f.rTensor N) = map f g := by simp only [lTensor, rTensor, ← map_comp, id_comp, comp_id] @[simp] theorem rTensor_comp_lTensor (f : M →ₗ[R] P) (g : N →ₗ[R] Q) : (f.rTensor Q).comp (g.lTensor M) = map f g := by simp only [lTensor, rTensor, ← map_comp, id_comp, comp_id] @[simp] theorem map_comp_rTensor (f : M →ₗ[R] P) (g : N →ₗ[R] Q) (f' : S →ₗ[R] M) : (map f g).comp (f'.rTensor _) = map (f.comp f') g := by simp only [lTensor, rTensor, ← map_comp, id_comp, comp_id] @[simp] theorem map_comp_lTensor (f : M →ₗ[R] P) (g : N →ₗ[R] Q) (g' : S →ₗ[R] N) : (map f g).comp (g'.lTensor _) = map f (g.comp g') := by simp only [lTensor, rTensor, ← map_comp, id_comp, comp_id] @[simp] theorem rTensor_comp_map (f' : P →ₗ[R] S) (f : M →ₗ[R] P) (g : N →ₗ[R] Q) : (f'.rTensor _).comp (map f g) = map (f'.comp f) g := by simp only [lTensor, rTensor, ← map_comp, id_comp, comp_id] @[simp] theorem lTensor_comp_map (g' : Q →ₗ[R] S) (f : M →ₗ[R] P) (g : N →ₗ[R] Q) :
(g'.lTensor _).comp (map f g) = map f (g'.comp g) := by simp only [lTensor, rTensor, ← map_comp, id_comp, comp_id]
Mathlib/LinearAlgebra/TensorProduct/Basic.lean
1,119
1,121
/- Copyright (c) 2023 Dagur Asgeirsson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Dagur Asgeirsson -/ import Mathlib.CategoryTheory.Limits.Preserves.Shapes.Products import Mathlib.CategoryTheory.Limits.Shapes.Pullback.CommSq import Mathlib.CategoryTheory.Sites.EqualizerSheafCondition /-! # Sheaves preserve products We prove that a presheaf which satisfies the sheaf condition with respect to certain presieves preserve "the corresponding products". ## Main results More precisely, given a presheaf `F : Cᵒᵖ ⥤ Type*`, we have: * If `F` satisfies the sheaf condition with respect to the empty sieve on the initial object of `C`, then `F` preserves terminal objects. See `preservesTerminalOfIsSheafForEmpty`. * If `F` furthermore satisfies the sheaf condition with respect to the presieve consisting of the inclusion arrows in a coproduct in `C`, then `F` preserves the corresponding product. See `preservesProductOfIsSheafFor`. * If `F` preserves a product, then it satisfies the sheaf condition with respect to the corresponding presieve of arrows. See `isSheafFor_of_preservesProduct`. -/ universe v u w namespace CategoryTheory.Presieve variable {C : Type u} [Category.{v} C] {I : C} (F : Cᵒᵖ ⥤ Type w) open Limits Opposite variable (hF : (ofArrows (X := I) Empty.elim Empty.instIsEmpty.elim).IsSheafFor F) section Terminal variable (I) in /-- If `F` is a presheaf which satisfies the sheaf condition with respect to the empty presieve on any object, then `F` takes that object to the terminal object. -/ noncomputable def isTerminal_of_isSheafFor_empty_presieve : IsTerminal (F.obj (op I)) := by refine @IsTerminal.ofUnique _ _ _ fun Y ↦ ?_ choose t h using hF (by tauto) (by tauto) exact ⟨⟨fun _ ↦ t⟩, fun a ↦ by ext; exact h.2 _ (by tauto)⟩ include hF in /-- If `F` is a presheaf which satisfies the sheaf condition with respect to the empty presieve on the initial object, then `F` preserves terminal objects. -/ lemma preservesTerminal_of_isSheaf_for_empty (hI : IsInitial I) : PreservesLimit (Functor.empty.{0} Cᵒᵖ) F := have := hI.hasInitial (preservesTerminal_of_iso F ((F.mapIso (terminalIsoIsTerminal (terminalOpOfInitial initialIsInitial)) ≪≫ (F.mapIso (initialIsoIsInitial hI).symm.op) ≪≫ (terminalIsoIsTerminal (isTerminal_of_isSheafFor_empty_presieve I F hF)).symm))) end Terminal section Product variable (hI : IsInitial I) -- This is the data of a particular disjoint coproduct in `C`. variable {α : Type} {X : α → C} (c : Cofan X) (hc : IsColimit c) theorem piComparison_fac : have : HasCoproduct X := ⟨⟨c, hc⟩⟩ piComparison F (fun x ↦ op (X x)) = F.map (opCoproductIsoProduct' hc (productIsProduct _)).inv ≫ Equalizer.Presieve.Arrows.forkMap F X c.inj := by have : HasCoproduct X := ⟨⟨c, hc⟩⟩ dsimp only [Equalizer.Presieve.Arrows.forkMap] have h : Pi.lift (fun i ↦ F.map (c.inj i).op) = F.map (Pi.lift (fun i ↦ (c.inj i).op)) ≫ piComparison F _ := by simp rw [h, ← Category.assoc, ← Functor.map_comp] have hh : Pi.lift (fun i ↦ (c.inj i).op) = (productIsProduct (op <| X ·)).lift c.op := by simp [Pi.lift, productIsProduct] rw [hh, ← desc_op_comp_opCoproductIsoProduct'_hom hc] simp variable [(ofArrows X c.inj).hasPullbacks] include hc in /-- If `F` preserves a particular product, then it `IsSheafFor` the corresponding presieve of arrows. -/ theorem isSheafFor_of_preservesProduct [PreservesLimit (Discrete.functor (fun x ↦ op (X x))) F] : (ofArrows X c.inj).IsSheafFor F := by rw [Equalizer.Presieve.Arrows.sheaf_condition, Limits.Types.type_equalizer_iff_unique] have : HasCoproduct X := ⟨⟨c, hc⟩⟩ have hi : IsIso (piComparison F (fun x ↦ op (X x))) := inferInstance rw [piComparison_fac (hc := hc), isIso_iff_bijective, Function.bijective_iff_existsUnique] at hi intro b _ obtain ⟨t, ht₁, ht₂⟩ := hi b refine ⟨F.map ((opCoproductIsoProduct' hc (productIsProduct _)).inv) t, ht₁, fun y hy ↦ ?_⟩ apply_fun F.map ((opCoproductIsoProduct' hc (productIsProduct _)).hom) using injective_of_mono _ simp [← FunctorToTypes.map_comp_apply, ht₂ (F.map ((opCoproductIsoProduct' hc (productIsProduct _)).hom) y) (by simp [← hy])] variable [HasInitial C] [∀ i, Mono (c.inj i)] (hd : Pairwise fun i j => IsPullback (initial.to _) (initial.to _) (c.inj i) (c.inj j)) include hd hF hI in /-- The two parallel maps in the equalizer diagram for the sheaf condition corresponding to the inclusion maps in a disjoint coproduct are equal. -/ theorem firstMap_eq_secondMap : Equalizer.Presieve.Arrows.firstMap F X c.inj = Equalizer.Presieve.Arrows.secondMap F X c.inj := by ext a ⟨i, j⟩ simp only [Equalizer.Presieve.Arrows.firstMap, Types.pi_lift_π_apply, types_comp_apply, Equalizer.Presieve.Arrows.secondMap] by_cases hi : i = j · rw [hi, Mono.right_cancellation _ _ pullback.condition] · have := preservesTerminal_of_isSheaf_for_empty F hF hI apply_fun (F.mapIso ((hd hi).isoPullback).op ≪≫ F.mapIso (terminalIsoIsTerminal
(terminalOpOfInitial initialIsInitial)).symm ≪≫ (PreservesTerminal.iso F)).hom using injective_of_mono _ ext ⟨i⟩ exact i.elim include hc hd hF hI in /-- If `F` is a presheaf which `IsSheafFor` a presieve of arrows and the empty presieve, then it preserves the product corresponding to the presieve of arrows. -/ lemma preservesProduct_of_isSheafFor (hF' : (ofArrows X c.inj).IsSheafFor F) : PreservesLimit (Discrete.functor (fun x ↦ op (X x))) F := by have : HasCoproduct X := ⟨⟨c, hc⟩⟩ refine @PreservesProduct.of_iso_comparison _ _ _ _ F _ (fun x ↦ op (X x)) _ _ ?_ rw [piComparison_fac (hc := hc)] refine IsIso.comp_isIso' inferInstance ?_
Mathlib/CategoryTheory/Sites/Preserves.lean
129
145
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import Mathlib.Data.Set.Piecewise import Mathlib.Logic.Equiv.Defs import Mathlib.Tactic.Core import Mathlib.Tactic.Attr.Core /-! # Partial equivalences This files defines equivalences between subsets of given types. An element `e` of `PartialEquiv α β` is made of two maps `e.toFun` and `e.invFun` respectively from α to β and from β to α (just like equivs), which are inverse to each other on the subsets `e.source` and `e.target` of respectively α and β. They are designed in particular to define charts on manifolds. The main functionality is `e.trans f`, which composes the two partial equivalences by restricting the source and target to the maximal set where the composition makes sense. As for equivs, we register a coercion to functions and use it in our simp normal form: we write `e x` and `e.symm y` instead of `e.toFun x` and `e.invFun y`. ## Main definitions * `Equiv.toPartialEquiv`: associating a partial equiv to an equiv, with source = target = univ * `PartialEquiv.symm`: the inverse of a partial equivalence * `PartialEquiv.trans`: the composition of two partial equivalences * `PartialEquiv.refl`: the identity partial equivalence * `PartialEquiv.ofSet`: the identity on a set `s` * `EqOnSource`: equivalence relation describing the "right" notion of equality for partial equivalences (see below in implementation notes) ## Implementation notes There are at least three possible implementations of partial equivalences: * equivs on subtypes * pairs of functions taking values in `Option α` and `Option β`, equal to none where the partial equivalence is not defined * pairs of functions defined everywhere, keeping the source and target as additional data Each of these implementations has pros and cons. * When dealing with subtypes, one still need to define additional API for composition and restriction of domains. Checking that one always belongs to the right subtype makes things very tedious, and leads quickly to DTT hell (as the subtype `u ∩ v` is not the "same" as `v ∩ u`, for instance). * With option-valued functions, the composition is very neat (it is just the usual composition, and the domain is restricted automatically). These are implemented in `PEquiv.lean`. For manifolds, where one wants to discuss thoroughly the smoothness of the maps, this creates however a lot of overhead as one would need to extend all classes of smoothness to option-valued maps. * The `PartialEquiv` version as explained above is easier to use for manifolds. The drawback is that there is extra useless data (the values of `toFun` and `invFun` outside of `source` and `target`). In particular, the equality notion between partial equivs is not "the right one", i.e., coinciding source and target and equality there. Moreover, there are no partial equivs in this sense between an empty type and a nonempty type. Since empty types are not that useful, and since one almost never needs to talk about equal partial equivs, this is not an issue in practice. Still, we introduce an equivalence relation `EqOnSource` that captures this right notion of equality, and show that many properties are invariant under this equivalence relation. ### Local coding conventions If a lemma deals with the intersection of a set with either source or target of a `PartialEquiv`, then it should use `e.source ∩ s` or `e.target ∩ t`, not `s ∩ e.source` or `t ∩ e.target`. -/ open Lean Meta Elab Tactic /-! Implementation of the `mfld_set_tac` tactic for working with the domains of partially-defined functions (`PartialEquiv`, `PartialHomeomorph`, etc). This is in a separate file from `Mathlib.Logic.Equiv.MfldSimpsAttr` because attributes need a new file to become functional. -/ /-- Common `@[simps]` configuration options used for manifold-related declarations. -/ def mfld_cfg : Simps.Config where attrs := [`mfld_simps] fullyApplied := false namespace Tactic.MfldSetTac /-- A very basic tactic to show that sets showing up in manifolds coincide or are included in one another. -/ elab (name := mfldSetTac) "mfld_set_tac" : tactic => withMainContext do let g ← getMainGoal let goalTy := (← instantiateMVars (← g.getDecl).type).getAppFnArgs match goalTy with | (``Eq, #[_ty, _e₁, _e₂]) => evalTactic (← `(tactic| ( apply Set.ext; intro my_y constructor <;> · intro h_my_y try simp only [*, mfld_simps] at h_my_y try simp only [*, mfld_simps]))) | (``Subset, #[_ty, _inst, _e₁, _e₂]) => evalTactic (← `(tactic| ( intro my_y h_my_y try simp only [*, mfld_simps] at h_my_y try simp only [*, mfld_simps]))) | _ => throwError "goal should be an equality or an inclusion" attribute [mfld_simps] and_true eq_self_iff_true Function.comp_apply end Tactic.MfldSetTac open Function Set variable {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} /-- Local equivalence between subsets `source` and `target` of `α` and `β` respectively. The (global) maps `toFun : α → β` and `invFun : β → α` map `source` to `target` and conversely, and are inverse to each other there. The values of `toFun` outside of `source` and of `invFun` outside of `target` are irrelevant. -/ structure PartialEquiv (α : Type*) (β : Type*) where /-- The global function which has a partial inverse. Its value outside of the `source` subset is irrelevant. -/ toFun : α → β /-- The partial inverse to `toFun`. Its value outside of the `target` subset is irrelevant. -/ invFun : β → α /-- The domain of the partial equivalence. -/ source : Set α /-- The codomain of the partial equivalence. -/ target : Set β /-- The proposition that elements of `source` are mapped to elements of `target`. -/ map_source' : ∀ ⦃x⦄, x ∈ source → toFun x ∈ target /-- The proposition that elements of `target` are mapped to elements of `source`. -/ map_target' : ∀ ⦃x⦄, x ∈ target → invFun x ∈ source /-- The proposition that `invFun` is a left-inverse of `toFun` on `source`. -/ left_inv' : ∀ ⦃x⦄, x ∈ source → invFun (toFun x) = x /-- The proposition that `invFun` is a right-inverse of `toFun` on `target`. -/ right_inv' : ∀ ⦃x⦄, x ∈ target → toFun (invFun x) = x attribute [coe] PartialEquiv.toFun namespace PartialEquiv variable (e : PartialEquiv α β) (e' : PartialEquiv β γ) instance [Inhabited α] [Inhabited β] : Inhabited (PartialEquiv α β) := ⟨⟨const α default, const β default, ∅, ∅, mapsTo_empty _ _, mapsTo_empty _ _, eqOn_empty _ _, eqOn_empty _ _⟩⟩ /-- The inverse of a partial equivalence -/ @[symm] protected def symm : PartialEquiv β α where toFun := e.invFun invFun := e.toFun source := e.target target := e.source map_source' := e.map_target' map_target' := e.map_source' left_inv' := e.right_inv' right_inv' := e.left_inv' instance : CoeFun (PartialEquiv α β) fun _ => α → β := ⟨PartialEquiv.toFun⟩ /-- See Note [custom simps projection] -/ def Simps.symm_apply (e : PartialEquiv α β) : β → α := e.symm initialize_simps_projections PartialEquiv (toFun → apply, invFun → symm_apply) theorem coe_mk (f : α → β) (g s t ml mr il ir) : (PartialEquiv.mk f g s t ml mr il ir : α → β) = f := rfl @[simp, mfld_simps] theorem coe_symm_mk (f : α → β) (g s t ml mr il ir) : ((PartialEquiv.mk f g s t ml mr il ir).symm : β → α) = g := rfl @[simp, mfld_simps] theorem invFun_as_coe : e.invFun = e.symm := rfl @[simp, mfld_simps] theorem map_source {x : α} (h : x ∈ e.source) : e x ∈ e.target := e.map_source' h /-- Variant of `e.map_source` and `map_source'`, stated for images of subsets of `source`. -/ lemma map_source'' : e '' e.source ⊆ e.target := fun _ ⟨_, hx, hex⟩ ↦ mem_of_eq_of_mem (id hex.symm) (e.map_source' hx) @[simp, mfld_simps] theorem map_target {x : β} (h : x ∈ e.target) : e.symm x ∈ e.source := e.map_target' h @[simp, mfld_simps] theorem left_inv {x : α} (h : x ∈ e.source) : e.symm (e x) = x := e.left_inv' h @[simp, mfld_simps] theorem right_inv {x : β} (h : x ∈ e.target) : e (e.symm x) = x := e.right_inv' h theorem eq_symm_apply {x : α} {y : β} (hx : x ∈ e.source) (hy : y ∈ e.target) : x = e.symm y ↔ e x = y := ⟨fun h => by rw [← e.right_inv hy, h], fun h => by rw [← e.left_inv hx, h]⟩ protected theorem mapsTo : MapsTo e e.source e.target := fun _ => e.map_source theorem symm_mapsTo : MapsTo e.symm e.target e.source := e.symm.mapsTo protected theorem leftInvOn : LeftInvOn e.symm e e.source := fun _ => e.left_inv protected theorem rightInvOn : RightInvOn e.symm e e.target := fun _ => e.right_inv protected theorem invOn : InvOn e.symm e e.source e.target := ⟨e.leftInvOn, e.rightInvOn⟩ protected theorem injOn : InjOn e e.source := e.leftInvOn.injOn protected theorem bijOn : BijOn e e.source e.target := e.invOn.bijOn e.mapsTo e.symm_mapsTo protected theorem surjOn : SurjOn e e.source e.target := e.bijOn.surjOn /-- Interpret an `Equiv` as a `PartialEquiv` by restricting it to `s` in the domain and to `t` in the codomain. -/ @[simps -fullyApplied] def _root_.Equiv.toPartialEquivOfImageEq (e : α ≃ β) (s : Set α) (t : Set β) (h : e '' s = t) : PartialEquiv α β where toFun := e invFun := e.symm source := s target := t map_source' _ hx := h ▸ mem_image_of_mem _ hx map_target' x hx := by subst t rcases hx with ⟨x, hx, rfl⟩ rwa [e.symm_apply_apply] left_inv' x _ := e.symm_apply_apply x right_inv' x _ := e.apply_symm_apply x /-- Associate a `PartialEquiv` to an `Equiv`. -/ @[simps! (config := mfld_cfg)] def _root_.Equiv.toPartialEquiv (e : α ≃ β) : PartialEquiv α β := e.toPartialEquivOfImageEq univ univ <| by rw [image_univ, e.surjective.range_eq] instance inhabitedOfEmpty [IsEmpty α] [IsEmpty β] : Inhabited (PartialEquiv α β) := ⟨((Equiv.equivEmpty α).trans (Equiv.equivEmpty β).symm).toPartialEquiv⟩ /-- Create a copy of a `PartialEquiv` providing better definitional equalities. -/ @[simps -fullyApplied] def copy (e : PartialEquiv α β) (f : α → β) (hf : ⇑e = f) (g : β → α) (hg : ⇑e.symm = g) (s : Set α) (hs : e.source = s) (t : Set β) (ht : e.target = t) : PartialEquiv α β where toFun := f invFun := g source := s target := t map_source' _ := ht ▸ hs ▸ hf ▸ e.map_source map_target' _ := hs ▸ ht ▸ hg ▸ e.map_target left_inv' _ := hs ▸ hf ▸ hg ▸ e.left_inv right_inv' _ := ht ▸ hf ▸ hg ▸ e.right_inv theorem copy_eq (e : PartialEquiv α β) (f : α → β) (hf : ⇑e = f) (g : β → α) (hg : ⇑e.symm = g) (s : Set α) (hs : e.source = s) (t : Set β) (ht : e.target = t) : e.copy f hf g hg s hs t ht = e := by substs f g s t cases e rfl /-- Associate to a `PartialEquiv` an `Equiv` between the source and the target. -/ protected def toEquiv : e.source ≃ e.target where toFun x := ⟨e x, e.map_source x.mem⟩ invFun y := ⟨e.symm y, e.map_target y.mem⟩ left_inv := fun ⟨_, hx⟩ => Subtype.eq <| e.left_inv hx right_inv := fun ⟨_, hy⟩ => Subtype.eq <| e.right_inv hy @[simp, mfld_simps] theorem symm_source : e.symm.source = e.target := rfl @[simp, mfld_simps] theorem symm_target : e.symm.target = e.source := rfl @[simp, mfld_simps] theorem symm_symm : e.symm.symm = e := rfl theorem symm_bijective : Function.Bijective (PartialEquiv.symm : PartialEquiv α β → PartialEquiv β α) := Function.bijective_iff_has_inverse.mpr ⟨_, symm_symm, symm_symm⟩ theorem image_source_eq_target : e '' e.source = e.target := e.bijOn.image_eq theorem forall_mem_target {p : β → Prop} : (∀ y ∈ e.target, p y) ↔ ∀ x ∈ e.source, p (e x) := by rw [← image_source_eq_target, forall_mem_image] theorem exists_mem_target {p : β → Prop} : (∃ y ∈ e.target, p y) ↔ ∃ x ∈ e.source, p (e x) := by rw [← image_source_eq_target, exists_mem_image] /-- We say that `t : Set β` is an image of `s : Set α` under a partial equivalence if any of the following equivalent conditions hold: * `e '' (e.source ∩ s) = e.target ∩ t`; * `e.source ∩ e ⁻¹ t = e.source ∩ s`; * `∀ x ∈ e.source, e x ∈ t ↔ x ∈ s` (this one is used in the definition). -/ def IsImage (s : Set α) (t : Set β) : Prop := ∀ ⦃x⦄, x ∈ e.source → (e x ∈ t ↔ x ∈ s) namespace IsImage variable {e} {s : Set α} {t : Set β} {x : α} theorem apply_mem_iff (h : e.IsImage s t) (hx : x ∈ e.source) : e x ∈ t ↔ x ∈ s := h hx theorem symm_apply_mem_iff (h : e.IsImage s t) : ∀ ⦃y⦄, y ∈ e.target → (e.symm y ∈ s ↔ y ∈ t) := e.forall_mem_target.mpr fun x hx => by rw [e.left_inv hx, h hx] protected theorem symm (h : e.IsImage s t) : e.symm.IsImage t s := h.symm_apply_mem_iff @[simp] theorem symm_iff : e.symm.IsImage t s ↔ e.IsImage s t := ⟨fun h => h.symm, fun h => h.symm⟩ protected theorem mapsTo (h : e.IsImage s t) : MapsTo e (e.source ∩ s) (e.target ∩ t) := fun _ hx => ⟨e.mapsTo hx.1, (h hx.1).2 hx.2⟩ theorem symm_mapsTo (h : e.IsImage s t) : MapsTo e.symm (e.target ∩ t) (e.source ∩ s) := h.symm.mapsTo /-- Restrict a `PartialEquiv` to a pair of corresponding sets. -/ @[simps -fullyApplied] def restr (h : e.IsImage s t) : PartialEquiv α β where toFun := e invFun := e.symm source := e.source ∩ s target := e.target ∩ t map_source' := h.mapsTo map_target' := h.symm_mapsTo left_inv' := e.leftInvOn.mono inter_subset_left right_inv' := e.rightInvOn.mono inter_subset_left theorem image_eq (h : e.IsImage s t) : e '' (e.source ∩ s) = e.target ∩ t := h.restr.image_source_eq_target
theorem symm_image_eq (h : e.IsImage s t) : e.symm '' (e.target ∩ t) = e.source ∩ s := h.symm.image_eq
Mathlib/Logic/Equiv/PartialEquiv.lean
349
350
/- Copyright (c) 2023 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import Mathlib.GroupTheory.CoprodI import Mathlib.GroupTheory.Coprod.Basic import Mathlib.GroupTheory.Complement /-! ## Pushouts of Monoids and Groups This file defines wide pushouts of monoids and groups and proves some properties of the amalgamated product of groups (i.e. the special case where all the maps in the diagram are injective). ## Main definitions - `Monoid.PushoutI`: the pushout of a diagram of monoids indexed by a type `ι` - `Monoid.PushoutI.base`: the map from the amalgamating monoid to the pushout - `Monoid.PushoutI.of`: the map from each Monoid in the family to the pushout - `Monoid.PushoutI.lift`: the universal property used to define homomorphisms out of the pushout. - `Monoid.PushoutI.NormalWord`: a normal form for words in the pushout - `Monoid.PushoutI.of_injective`: if all the maps in the diagram are injective in a pushout of groups then so is `of` - `Monoid.PushoutI.Reduced.eq_empty_of_mem_range`: For any word `w` in the coproduct, if `w` is reduced (i.e none its letters are in the image of the base monoid), and nonempty, then `w` itself is not in the image of the base monoid. ## References * The normal form theorem follows these [notes](https://webspace.maths.qmul.ac.uk/i.m.chiswell/ggt/lecture_notes/lecture2.pdf) from Queen Mary University ## Tags amalgamated product, pushout, group -/ namespace Monoid open CoprodI Subgroup Coprod Function List variable {ι : Type*} {G : ι → Type*} {H : Type*} {K : Type*} [Monoid K] /-- The relation we quotient by to form the pushout -/ def PushoutI.con [∀ i, Monoid (G i)] [Monoid H] (φ : ∀ i, H →* G i) : Con (Coprod (CoprodI G) H) := conGen (fun x y : Coprod (CoprodI G) H => ∃ i x', x = inl (of (φ i x')) ∧ y = inr x') /-- The indexed pushout of monoids, which is the pushout in the category of monoids, or the category of groups. -/ def PushoutI [∀ i, Monoid (G i)] [Monoid H] (φ : ∀ i, H →* G i) : Type _ := (PushoutI.con φ).Quotient namespace PushoutI section Monoid variable [∀ i, Monoid (G i)] [Monoid H] {φ : ∀ i, H →* G i} protected instance mul : Mul (PushoutI φ) := by delta PushoutI; infer_instance protected instance one : One (PushoutI φ) := by delta PushoutI; infer_instance instance monoid : Monoid (PushoutI φ) := { Con.monoid _ with toMul := PushoutI.mul toOne := PushoutI.one } /-- The map from each indexing group into the pushout -/ def of (i : ι) : G i →* PushoutI φ := (Con.mk' _).comp <| inl.comp CoprodI.of variable (φ) in /-- The map from the base monoid into the pushout -/ def base : H →* PushoutI φ := (Con.mk' _).comp inr theorem of_comp_eq_base (i : ι) : (of i).comp (φ i) = (base φ) := by ext x apply (Con.eq _).2 refine ConGen.Rel.of _ _ ?_ simp only [MonoidHom.comp_apply, Set.mem_iUnion, Set.mem_range] exact ⟨_, _, rfl, rfl⟩ variable (φ) in theorem of_apply_eq_base (i : ι) (x : H) : of i (φ i x) = base φ x := by rw [← MonoidHom.comp_apply, of_comp_eq_base] /-- Define a homomorphism out of the pushout of monoids be defining it on each object in the diagram -/ def lift (f : ∀ i, G i →* K) (k : H →* K) (hf : ∀ i, (f i).comp (φ i) = k) : PushoutI φ →* K := Con.lift _ (Coprod.lift (CoprodI.lift f) k) <| by apply Con.conGen_le fun x y => ?_ rintro ⟨i, x', rfl, rfl⟩ simp only [DFunLike.ext_iff, MonoidHom.coe_comp, comp_apply] at hf simp [hf] @[simp] theorem lift_of (f : ∀ i, G i →* K) (k : H →* K) (hf : ∀ i, (f i).comp (φ i) = k) {i : ι} (g : G i) : (lift f k hf) (of i g : PushoutI φ) = f i g := by delta PushoutI lift of simp only [MonoidHom.coe_comp, Con.coe_mk', comp_apply, Con.lift_coe, lift_apply_inl, CoprodI.lift_of] @[simp] theorem lift_base (f : ∀ i, G i →* K) (k : H →* K) (hf : ∀ i, (f i).comp (φ i) = k) (g : H) : (lift f k hf) (base φ g : PushoutI φ) = k g := by delta PushoutI lift base simp only [MonoidHom.coe_comp, Con.coe_mk', comp_apply, Con.lift_coe, lift_apply_inr] -- `ext` attribute should be lower priority then `hom_ext_nonempty` @[ext 1199] theorem hom_ext {f g : PushoutI φ →* K} (h : ∀ i, f.comp (of i : G i →* _) = g.comp (of i : G i →* _)) (hbase : f.comp (base φ) = g.comp (base φ)) : f = g := (MonoidHom.cancel_right Con.mk'_surjective).mp <| Coprod.hom_ext (CoprodI.ext_hom _ _ h) hbase @[ext high] theorem hom_ext_nonempty [hn : Nonempty ι] {f g : PushoutI φ →* K} (h : ∀ i, f.comp (of i : G i →* _) = g.comp (of i : G i →* _)) : f = g := hom_ext h <| by cases hn with | intro i => ext rw [← of_comp_eq_base i, ← MonoidHom.comp_assoc, h, MonoidHom.comp_assoc] /-- The equivalence that is part of the universal property of the pushout. A hom out of the pushout is just a morphism out of all groups in the pushout that satisfies a commutativity condition. -/ @[simps] def homEquiv : (PushoutI φ →* K) ≃ { f : (Π i, G i →* K) × (H →* K) // ∀ i, (f.1 i).comp (φ i) = f.2 } := { toFun := fun f => ⟨(fun i => f.comp (of i), f.comp (base φ)), fun i => by rw [MonoidHom.comp_assoc, of_comp_eq_base]⟩ invFun := fun f => lift f.1.1 f.1.2 f.2, left_inv := fun _ => hom_ext (by simp [DFunLike.ext_iff]) (by simp [DFunLike.ext_iff]) right_inv := fun ⟨⟨_, _⟩, _⟩ => by simp [DFunLike.ext_iff, funext_iff] } /-- The map from the coproduct into the pushout -/ def ofCoprodI : CoprodI G →* PushoutI φ := CoprodI.lift of @[simp] theorem ofCoprodI_of (i : ι) (g : G i) : (ofCoprodI (CoprodI.of g) : PushoutI φ) = of i g := by simp [ofCoprodI] theorem induction_on {motive : PushoutI φ → Prop} (x : PushoutI φ) (of : ∀ (i : ι) (g : G i), motive (of i g)) (base : ∀ h, motive (base φ h)) (mul : ∀ x y, motive x → motive y → motive (x * y)) : motive x := by delta PushoutI PushoutI.of PushoutI.base at * induction x using Con.induction_on with | H x => induction x using Coprod.induction_on with | inl g => induction g using CoprodI.induction_on with | of i g => exact of i g | mul x y ihx ihy => rw [map_mul] exact mul _ _ ihx ihy | one => simpa using base 1 | inr h => exact base h | mul x y ihx ihy => exact mul _ _ ihx ihy end Monoid variable [∀ i, Group (G i)] [Group H] {φ : ∀ i, H →* G i} instance : Group (PushoutI φ) := { Con.group (PushoutI.con φ) with toMonoid := PushoutI.monoid } namespace NormalWord /- In this section we show that there is a normal form for words in the amalgamated product. To have a normal form, we need to pick canonical choice of element of each right coset of the base group. The choice of element in the base group itself is `1`. Given a choice of element of each right coset, given by the type `Transversal φ` we can find a normal form. The normal form for an element is an element of the base group, multiplied by a word in the coproduct, where each letter in the word is the canonical choice of element of its coset. We then show that all groups in the diagram act faithfully on the normal form. This implies that the maps into the coproduct are injective. We demonstrate the action is faithful using the equivalence `equivPair`. We show that `G i` acts faithfully on `Pair d i` and that `Pair d i` is isomorphic to `NormalWord d`. Here, `d` is a `Transversal`. A `Pair d i` is a word in the coproduct, `Coprod G`, the `tail`, and an element of the group `G i`, the `head`. The first letter of the `tail` must not be an element of `G i`. Note that the `head` may be `1` Every letter in the `tail` must be in the transversal given by `d`. We then show that the equivalence between `NormalWord` and `PushoutI`, between the set of normal words and the elements of the amalgamated product. The key to this is the theorem `prod_smul_empty`, which says that going from `NormalWord` to `PushoutI` and back is the identity. This is proven by induction on the word using `consRecOn`. -/ variable (φ) /-- The data we need to pick a normal form for words in the pushout. We need to pick a canonical element of each coset. We also need all the maps in the diagram to be injective -/ structure Transversal : Type _ where /-- All maps in the diagram are injective -/ injective : ∀ i, Injective (φ i) /-- The underlying set, containing exactly one element of each coset of the base group -/ set : ∀ i, Set (G i) /-- The chosen element of the base group itself is the identity -/ one_mem : ∀ i, 1 ∈ set i /-- We have exactly one element of each coset of the base group -/ compl : ∀ i, IsComplement (φ i).range (set i) theorem transversal_nonempty (hφ : ∀ i, Injective (φ i)) : Nonempty (Transversal φ) := by choose t ht using fun i => (φ i).range.exists_isComplement_right 1 apply Nonempty.intro exact { injective := hφ set := t one_mem := fun i => (ht i).2 compl := fun i => (ht i).1 } variable {φ} /-- The normal form for words in the pushout. Every element of the pushout is the product of an element of the base group and a word made up of letters each of which is in the transversal. -/ structure _root_.Monoid.PushoutI.NormalWord (d : Transversal φ) extends CoprodI.Word G where /-- Every `NormalWord` is the product of an element of the base group and a word made up of letters each of which is in the transversal. `head` is that element of the base group. -/ head : H /-- All letter in the word are in the transversal. -/ normalized : ∀ i g, ⟨i, g⟩ ∈ toList → g ∈ d.set i /-- A `Pair d i` is a word in the coproduct, `Coprod G`, the `tail`, and an element of the group `G i`, the `head`. The first letter of the `tail` must not be an element of `G i`. Note that the `head` may be `1` Every letter in the `tail` must be in the transversal given by `d`. Similar to `Monoid.CoprodI.Pair` except every letter must be in the transversal (not including the head letter). -/ structure Pair (d : Transversal φ) (i : ι) extends CoprodI.Word.Pair G i where /-- All letters in the word are in the transversal. -/ normalized : ∀ i g, ⟨i, g⟩ ∈ tail.toList → g ∈ d.set i variable {d : Transversal φ} /-- The empty normalized word, representing the identity element of the group. -/ @[simps!] def empty : NormalWord d := ⟨CoprodI.Word.empty, 1, fun i g => by simp [CoprodI.Word.empty]⟩ instance : Inhabited (NormalWord d) := ⟨NormalWord.empty⟩ instance (i : ι) : Inhabited (Pair d i) := ⟨{ (empty : NormalWord d) with head := 1, tail := _, fstIdx_ne := fun h => by cases h }⟩ @[ext] theorem ext {w₁ w₂ : NormalWord d} (hhead : w₁.head = w₂.head) (hlist : w₁.toList = w₂.toList) : w₁ = w₂ := by rcases w₁ with ⟨⟨_, _, _⟩, _, _⟩ rcases w₂ with ⟨⟨_, _, _⟩, _, _⟩ simp_all open Subgroup.IsComplement instance baseAction : MulAction H (NormalWord d) := { smul := fun h w => { w with head := h * w.head }, one_smul := by simp [instHSMul] mul_smul := by simp [instHSMul, mul_assoc] } theorem base_smul_def' (h : H) (w : NormalWord d) : h • w = { w with head := h * w.head } := rfl /-- Take the product of a normal word as an element of the `PushoutI`. We show that this is bijective, in `NormalWord.equiv`. -/ def prod (w : NormalWord d) : PushoutI φ := base φ w.head * ofCoprodI (w.toWord).prod @[simp] theorem prod_base_smul (h : H) (w : NormalWord d) : (h • w).prod = base φ h * w.prod := by simp only [base_smul_def', prod, map_mul, mul_assoc] @[simp] theorem prod_empty : (empty : NormalWord d).prod = 1 := by simp [prod, empty] /-- A constructor that multiplies a `NormalWord` by an element, with condition to make sure the underlying list does get longer. -/ @[simps!] noncomputable def cons {i} (g : G i) (w : NormalWord d) (hmw : w.fstIdx ≠ some i) (hgr : g ∉ (φ i).range) : NormalWord d := letI n := (d.compl i).equiv (g * (φ i w.head)) letI w' := Word.cons (n.2 : G i) w.toWord hmw (mt (coe_equiv_snd_eq_one_iff_mem _ (d.one_mem _)).1 (mt (mul_mem_cancel_right (by simp)).1 hgr)) { toWord := w' head := (MonoidHom.ofInjective (d.injective i)).symm n.1 normalized := fun i g hg => by simp only [w', Word.cons, mem_cons, Sigma.mk.inj_iff] at hg rcases hg with ⟨rfl, hg | hg⟩ · simp · exact w.normalized _ _ (by assumption) } @[simp] theorem prod_cons {i} (g : G i) (w : NormalWord d) (hmw : w.fstIdx ≠ some i) (hgr : g ∉ (φ i).range) : (cons g w hmw hgr).prod = of i g * w.prod := by simp [prod, cons, ← of_apply_eq_base φ i, equiv_fst_eq_mul_inv, mul_assoc] variable [DecidableEq ι] [∀ i, DecidableEq (G i)] /-- Given a word in `CoprodI`, if every letter is in the transversal and when we multiply by an element of the base group it still has this property, then the element of the base group we multiplied by was one. -/ theorem eq_one_of_smul_normalized (w : CoprodI.Word G) {i : ι} (h : H) (hw : ∀ i g, ⟨i, g⟩ ∈ w.toList → g ∈ d.set i) (hφw : ∀ j g, ⟨j, g⟩ ∈ (CoprodI.of (φ i h) • w).toList → g ∈ d.set j) : h = 1 := by simp only [← (d.compl _).equiv_snd_eq_self_iff_mem (one_mem _)] at hw hφw have hhead : ((d.compl i).equiv (Word.equivPair i w).head).2 = (Word.equivPair i w).head := by rw [Word.equivPair_head] split_ifs with h · rcases h with ⟨_, rfl⟩ exact hw _ _ (List.head_mem _) · rw [equiv_one (d.compl i) (one_mem _) (d.one_mem _)] by_contra hh1 have := hφw i (φ i h * (Word.equivPair i w).head) ?_ · apply hh1 rw [equiv_mul_left_of_mem (d.compl i) ⟨_, rfl⟩, hhead] at this simpa [((injective_iff_map_eq_one' _).1 (d.injective i))] using this · simp only [Word.mem_smul_iff, not_true, false_and, ne_eq, Option.mem_def, mul_right_inj, exists_eq_right', mul_eq_left, exists_prop, true_and, false_or] constructor · intro h apply_fun (d.compl i).equiv at h simp only [Prod.ext_iff, equiv_one (d.compl i) (one_mem _) (d.one_mem _), equiv_mul_left_of_mem (d.compl i) ⟨_, rfl⟩ , hhead, Subtype.ext_iff, Prod.ext_iff, Subgroup.coe_mul] at h rcases h with ⟨h₁, h₂⟩ rw [h₂, equiv_one (d.compl i) (one_mem _) (d.one_mem _)] at h₁ erw [mul_one] at h₁ simp only [((injective_iff_map_eq_one' _).1 (d.injective i))] at h₁ contradiction · rw [Word.equivPair_head] dsimp split_ifs with hep · rcases hep with ⟨hnil, rfl⟩ rw [head?_eq_head hnil] simp_all · push_neg at hep by_cases hw : w.toList = [] · simp [hw, Word.fstIdx] · simp [head?_eq_head hw, Word.fstIdx, hep hw] theorem ext_smul {w₁ w₂ : NormalWord d} (i : ι) (h : CoprodI.of (φ i w₁.head) • w₁.toWord = CoprodI.of (φ i w₂.head) • w₂.toWord) : w₁ = w₂ := by rcases w₁ with ⟨w₁, h₁, hw₁⟩ rcases w₂ with ⟨w₂, h₂, hw₂⟩ dsimp at * rw [smul_eq_iff_eq_inv_smul, ← mul_smul] at h subst h simp only [← map_inv, ← map_mul] at hw₁ have : h₁⁻¹ * h₂ = 1 := eq_one_of_smul_normalized w₂ (h₁⁻¹ * h₂) hw₂ hw₁ rw [inv_mul_eq_one] at this; subst this simp /-- Given a pair `(head, tail)`, we can form a word by prepending `head` to `tail`, but putting head into normal form first, by making sure it is expressed as an element of the base group multiplied by an element of the transversal. -/ noncomputable def rcons (i : ι) (p : Pair d i) : NormalWord d := letI n := (d.compl i).equiv p.head let w := (Word.equivPair i).symm { p.toPair with head := n.2 } { toWord := w head := (MonoidHom.ofInjective (d.injective i)).symm n.1 normalized := fun i g hg => by dsimp [w] at hg rw [Word.equivPair_symm, Word.mem_rcons_iff] at hg rcases hg with hg | ⟨_, rfl, rfl⟩ · exact p.normalized _ _ hg · simp } theorem rcons_injective {i : ι} : Function.Injective (rcons (d := d) i) := by rintro ⟨⟨head₁, tail₁⟩, _⟩ ⟨⟨head₂, tail₂⟩, _⟩ simp only [rcons, NormalWord.mk.injEq, EmbeddingLike.apply_eq_iff_eq, Word.Pair.mk.injEq, Pair.mk.injEq, and_imp] intro h₁ h₂ h₃ subst h₂ rw [← equiv_fst_mul_equiv_snd (d.compl i) head₁, ← equiv_fst_mul_equiv_snd (d.compl i) head₂, h₁, h₃] simp /-- The equivalence between `NormalWord`s and pairs. We can turn a `NormalWord` into a pair by taking the head of the `List` if it is in `G i` and multiplying it by the element of the base group. -/ noncomputable def equivPair (i) : NormalWord d ≃ Pair d i := letI toFun : NormalWord d → Pair d i := fun w => letI p := Word.equivPair i (CoprodI.of (φ i w.head) • w.toWord) { toPair := p normalized := fun j g hg => by dsimp only [p] at hg rw [Word.of_smul_def, ← Word.equivPair_symm, Equiv.apply_symm_apply] at hg dsimp at hg exact w.normalized _ _ (Word.mem_of_mem_equivPair_tail _ hg) } haveI leftInv : Function.LeftInverse (rcons i) toFun := fun w => ext_smul i <| by simp only [toFun, rcons, Word.equivPair_symm, Word.equivPair_smul_same, Word.equivPair_tail_eq_inv_smul, Word.rcons_eq_smul, MonoidHom.apply_ofInjective_symm, equiv_fst_eq_mul_inv, mul_assoc, map_mul, map_inv, mul_smul, inv_smul_smul, smul_inv_smul] { toFun := toFun invFun := rcons i left_inv := leftInv right_inv := fun _ => rcons_injective (leftInv _) } noncomputable instance summandAction (i : ι) : MulAction (G i) (NormalWord d) := { smul := fun g w => (equivPair i).symm { equivPair i w with head := g * (equivPair i w).head } one_smul := fun _ => by dsimp [instHSMul] rw [one_mul] exact (equivPair i).symm_apply_apply _ mul_smul := fun _ _ _ => by dsimp [instHSMul] simp [mul_assoc, Equiv.apply_symm_apply, Function.End.mul_def] } theorem summand_smul_def' {i : ι} (g : G i) (w : NormalWord d) : g • w = (equivPair i).symm { equivPair i w with head := g * (equivPair i w).head } := rfl noncomputable instance mulAction : MulAction (PushoutI φ) (NormalWord d) := MulAction.ofEndHom <| lift (fun _ => MulAction.toEndHom) MulAction.toEndHom <| by intro i simp only [MulAction.toEndHom, DFunLike.ext_iff, MonoidHom.coe_comp, MonoidHom.coe_mk, OneHom.coe_mk, comp_apply] intro h funext w apply NormalWord.ext_smul i simp only [summand_smul_def', equivPair, rcons, Word.equivPair_symm, Equiv.coe_fn_mk, Equiv.coe_fn_symm_mk, Word.equivPair_smul_same, Word.equivPair_tail_eq_inv_smul, Word.rcons_eq_smul, equiv_fst_eq_mul_inv, map_mul, map_inv, mul_smul, inv_smul_smul, smul_inv_smul, base_smul_def', MonoidHom.apply_ofInjective_symm] theorem base_smul_def (h : H) (w : NormalWord d) : base φ h • w = { w with head := h * w.head } := by dsimp [NormalWord.mulAction, instHSMul, SMul.smul] rw [lift_base] rfl theorem summand_smul_def {i : ι} (g : G i) (w : NormalWord d) : of (φ := φ) i g • w = (equivPair i).symm { equivPair i w with head := g * (equivPair i w).head } := by dsimp [NormalWord.mulAction, instHSMul, SMul.smul] rw [lift_of] rfl theorem of_smul_eq_smul {i : ι} (g : G i) (w : NormalWord d) : of (φ := φ) i g • w = g • w := by rw [summand_smul_def, summand_smul_def'] theorem base_smul_eq_smul (h : H) (w : NormalWord d) : base φ h • w = h • w := by rw [base_smul_def, base_smul_def'] /-- Induction principle for `NormalWord`, that corresponds closely to inducting on the underlying list. -/ @[elab_as_elim] noncomputable def consRecOn {motive : NormalWord d → Sort _} (w : NormalWord d) (empty : motive empty) (cons : ∀ (i : ι) (g : G i) (w : NormalWord d) (hmw : w.fstIdx ≠ some i) (_hgn : g ∈ d.set i) (hgr : g ∉ (φ i).range) (_hw1 : w.head = 1), motive w → motive (cons g w hmw hgr)) (base : ∀ (h : H) (w : NormalWord d), w.head = 1 → motive w → motive (base φ h • w)) : motive w := by rcases w with ⟨w, head, h3⟩ convert base head ⟨w, 1, h3⟩ rfl ?_ · simp [base_smul_def] · induction w using Word.consRecOn with | empty => exact empty | cons i g w h1 hg1 ih => convert cons i g ⟨w, 1, fun _ _ h => h3 _ _ (List.mem_cons_of_mem _ h)⟩ h1 (h3 _ _ List.mem_cons_self) ?_ rfl (ih ?_) · ext simp only [Word.cons, Option.mem_def, NormalWord.cons, map_one, mul_one, (equiv_snd_eq_self_iff_mem (d.compl i) (one_mem _)).2 (h3 _ _ List.mem_cons_self)] · apply d.injective i simp only [NormalWord.cons, equiv_fst_eq_mul_inv, MonoidHom.apply_ofInjective_symm, map_one, mul_one, mul_inv_cancel, (equiv_snd_eq_self_iff_mem (d.compl i) (one_mem _)).2 (h3 _ _ List.mem_cons_self)] · rwa [← SetLike.mem_coe, ← coe_equiv_snd_eq_one_iff_mem (d.compl i) (d.one_mem _), (equiv_snd_eq_self_iff_mem (d.compl i) (one_mem _)).2 (h3 _ _ List.mem_cons_self)] theorem cons_eq_smul {i : ι} (g : G i) (w : NormalWord d) (hmw : w.fstIdx ≠ some i) (hgr : g ∉ (φ i).range) : cons g w hmw hgr = of (φ := φ) i g • w := by apply ext_smul i simp only [cons, ne_eq, Word.cons_eq_smul, MonoidHom.apply_ofInjective_symm, equiv_fst_eq_mul_inv, mul_assoc, map_mul, map_inv, mul_smul, inv_smul_smul, summand_smul_def, equivPair, rcons, Word.equivPair_symm, Word.rcons_eq_smul, Equiv.coe_fn_mk, Word.equivPair_tail_eq_inv_smul, Equiv.coe_fn_symm_mk, smul_inv_smul] @[simp] theorem prod_summand_smul {i : ι} (g : G i) (w : NormalWord d) : (g • w).prod = of i g * w.prod := by simp only [prod, summand_smul_def', equivPair, rcons, Word.equivPair_symm, Equiv.coe_fn_mk, Equiv.coe_fn_symm_mk, Word.equivPair_smul_same, Word.equivPair_tail_eq_inv_smul, Word.rcons_eq_smul, ← of_apply_eq_base φ i, MonoidHom.apply_ofInjective_symm, equiv_fst_eq_mul_inv, mul_assoc, map_mul, map_inv, Word.prod_smul, ofCoprodI_of, inv_mul_cancel_left, mul_inv_cancel_left] @[simp] theorem prod_smul (g : PushoutI φ) (w : NormalWord d) : (g • w).prod = g * w.prod := by induction g using PushoutI.induction_on generalizing w with | of i g => rw [of_smul_eq_smul, prod_summand_smul] | base h => rw [base_smul_eq_smul, prod_base_smul] | mul x y ihx ihy => rw [mul_smul, ihx, ihy, mul_assoc] theorem prod_smul_empty (w : NormalWord d) : w.prod • empty = w := by induction w using consRecOn with | empty => simp | cons i g w _ _ _ _ ih => rw [prod_cons, mul_smul, ih, cons_eq_smul] | base h w _ ih => rw [prod_smul, mul_smul, ih] /-- The equivalence between normal forms and elements of the pushout -/ noncomputable def equiv : PushoutI φ ≃ NormalWord d := { toFun := fun g => g • .empty invFun := fun w => w.prod left_inv := fun g => by simp only [prod_smul, prod_empty, mul_one] right_inv := fun w => prod_smul_empty w } theorem prod_injective {ι : Type*} {G : ι → Type*} [(i : ι) → Group (G i)] {φ : (i : ι) → H →* G i} {d : Transversal φ} : Function.Injective (prod : NormalWord d → PushoutI φ) := by letI := Classical.decEq ι letI := fun i => Classical.decEq (G i) classical exact equiv.symm.injective instance : FaithfulSMul (PushoutI φ) (NormalWord d) := ⟨fun h => by simpa using congr_arg prod (h empty)⟩ instance (i : ι) : FaithfulSMul (G i) (NormalWord d) := ⟨by simp [summand_smul_def']⟩ instance : FaithfulSMul H (NormalWord d) := ⟨by simp [base_smul_def']⟩ end NormalWord open NormalWord /-- All maps into the `PushoutI`, or amalgamated product of groups are injective, provided all maps in the diagram are injective. See also `base_injective` -/ theorem of_injective (hφ : ∀ i, Function.Injective (φ i)) (i : ι) : Function.Injective (of (φ := φ) i) := by rcases transversal_nonempty φ hφ with ⟨d⟩ let _ := Classical.decEq ι
let _ := fun i => Classical.decEq (G i) refine Function.Injective.of_comp (f := ((· • ·) : PushoutI φ → NormalWord d → NormalWord d)) ?_ intros _ _ h exact eq_of_smul_eq_smul (fun w : NormalWord d => by simp_all [funext_iff, of_smul_eq_smul]) theorem base_injective (hφ : ∀ i, Function.Injective (φ i)) : Function.Injective (base φ) := by rcases transversal_nonempty φ hφ with ⟨d⟩
Mathlib/GroupTheory/PushoutI.lean
592
601
/- Copyright (c) 2018 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad -/ import Mathlib.Data.Set.BooleanAlgebra import Mathlib.Tactic.AdaptationNote /-! # Relations This file defines bundled relations. A relation between `α` and `β` is a function `α → β → Prop`. Relations are also known as set-valued functions, or partial multifunctions. ## Main declarations * `Rel α β`: Relation between `α` and `β`. * `Rel.inv`: `r.inv` is the `Rel β α` obtained by swapping the arguments of `r`. * `Rel.dom`: Domain of a relation. `x ∈ r.dom` iff there exists `y` such that `r x y`. * `Rel.codom`: Codomain, aka range, of a relation. `y ∈ r.codom` iff there exists `x` such that `r x y`. * `Rel.comp`: Relation composition. Note that the arguments order follows the `CategoryTheory/` one, so `r.comp s x z ↔ ∃ y, r x y ∧ s y z`. * `Rel.image`: Image of a set under a relation. `r.image s` is the set of `f x` over all `x ∈ s`. * `Rel.preimage`: Preimage of a set under a relation. Note that `r.preimage = r.inv.image`. * `Rel.core`: Core of a set. For `s : Set β`, `r.core s` is the set of `x : α` such that all `y` related to `x` are in `s`. * `Rel.restrict_domain`: Domain-restriction of a relation to a subtype. * `Function.graph`: Graph of a function as a relation. ## TODO The `Rel.comp` function uses the notation `r • s`, rather than the more common `r ∘ s` for things named `comp`. This is because the latter is already used for function composition, and causes a clash. A better notation should be found, perhaps a variant of `r ∘r s` or `r; s`. -/ variable {α β γ : Type*} /-- A relation on `α` and `β`, aka a set-valued function, aka a partial multifunction -/ def Rel (α β : Type*) := α → β → Prop -- The `CompleteLattice, Inhabited` instances should be constructed by a deriving handler. -- https://github.com/leanprover-community/mathlib4/issues/380 instance : CompleteLattice (Rel α β) := show CompleteLattice (α → β → Prop) from inferInstance instance : Inhabited (Rel α β) := show Inhabited (α → β → Prop) from inferInstance namespace Rel variable (r : Rel α β) @[ext] theorem ext {r s : Rel α β} : (∀ a, r a = s a) → r = s := funext /-- The inverse relation : `r.inv x y ↔ r y x`. Note that this is *not* a groupoid inverse. -/ def inv : Rel β α := flip r theorem inv_def (x : α) (y : β) : r.inv y x ↔ r x y := Iff.rfl theorem inv_inv : inv (inv r) = r := by ext x y rfl /-- Domain of a relation -/ def dom := { x | ∃ y, r x y } theorem dom_mono {r s : Rel α β} (h : r ≤ s) : dom r ⊆ dom s := fun a ⟨b, hx⟩ => ⟨b, h a b hx⟩ /-- Codomain aka range of a relation -/ def codom := { y | ∃ x, r x y } theorem codom_inv : r.inv.codom = r.dom := by ext x rfl theorem dom_inv : r.inv.dom = r.codom := by ext x rfl /-- Composition of relation; note that it follows the `CategoryTheory/` order of arguments. -/ def comp (r : Rel α β) (s : Rel β γ) : Rel α γ := fun x z => ∃ y, r x y ∧ s y z /-- Local syntax for composition of relations. -/ -- TODO: this could be replaced with `local infixr:90 " ∘ " => Rel.comp`. local infixr:90 " • " => Rel.comp theorem comp_assoc {δ : Type*} (r : Rel α β) (s : Rel β γ) (t : Rel γ δ) : (r • s) • t = r • (s • t) := by unfold comp; ext (x w); constructor · rintro ⟨z, ⟨y, rxy, syz⟩, tzw⟩; exact ⟨y, rxy, z, syz, tzw⟩ · rintro ⟨y, rxy, z, syz, tzw⟩; exact ⟨z, ⟨y, rxy, syz⟩, tzw⟩ @[simp] theorem comp_right_id (r : Rel α β) : r • @Eq β = r := by unfold comp ext y simp @[simp] theorem comp_left_id (r : Rel α β) : @Eq α • r = r := by unfold comp ext x simp @[simp] theorem comp_right_bot (r : Rel α β) : r • (⊥ : Rel β γ) = ⊥ := by ext x y simp [comp, Bot.bot] @[simp] theorem comp_left_bot (r : Rel α β) : (⊥ : Rel γ α) • r = ⊥ := by ext x y simp [comp, Bot.bot] @[simp] theorem comp_right_top (r : Rel α β) : r • (⊤ : Rel β γ) = fun x _ ↦ x ∈ r.dom := by ext x z simp [comp, Top.top, dom] @[simp] theorem comp_left_top (r : Rel α β) : (⊤ : Rel γ α) • r = fun _ y ↦ y ∈ r.codom := by ext x z simp [comp, Top.top, codom] theorem inv_id : inv (@Eq α) = @Eq α := by ext x y constructor <;> apply Eq.symm theorem inv_comp (r : Rel α β) (s : Rel β γ) : inv (r • s) = inv s • inv r := by ext x z simp [comp, inv, flip, and_comm] @[simp] theorem inv_bot : (⊥ : Rel α β).inv = (⊥ : Rel β α) := by simp [Bot.bot, inv, Function.flip_def] @[simp] theorem inv_top : (⊤ : Rel α β).inv = (⊤ : Rel β α) := by simp [Top.top, inv, Function.flip_def] /-- Image of a set under a relation -/ def image (s : Set α) : Set β := { y | ∃ x ∈ s, r x y } theorem mem_image (y : β) (s : Set α) : y ∈ image r s ↔ ∃ x ∈ s, r x y := Iff.rfl open scoped Relator in theorem image_subset : ((· ⊆ ·) ⇒ (· ⊆ ·)) r.image r.image := fun _ _ h _ ⟨x, xs, rxy⟩ => ⟨x, h xs, rxy⟩ theorem image_mono : Monotone r.image := r.image_subset theorem image_inter (s t : Set α) : r.image (s ∩ t) ⊆ r.image s ∩ r.image t := r.image_mono.map_inf_le s t theorem image_union (s t : Set α) : r.image (s ∪ t) = r.image s ∪ r.image t := le_antisymm (fun _y ⟨x, xst, rxy⟩ => xst.elim (fun xs => Or.inl ⟨x, ⟨xs, rxy⟩⟩) fun xt => Or.inr ⟨x, ⟨xt, rxy⟩⟩) (r.image_mono.le_map_sup s t) @[simp] theorem image_id (s : Set α) : image (@Eq α) s = s := by ext x simp [mem_image] theorem image_comp (s : Rel β γ) (t : Set α) : image (r • s) t = image s (image r t) := by ext z; simp only [mem_image]; constructor · rintro ⟨x, xt, y, rxy, syz⟩; exact ⟨y, ⟨x, xt, rxy⟩, syz⟩ · rintro ⟨y, ⟨x, xt, rxy⟩, syz⟩; exact ⟨x, xt, y, rxy, syz⟩ theorem image_univ : r.image Set.univ = r.codom := by ext y simp [mem_image, codom] @[simp] theorem image_empty : r.image ∅ = ∅ := by ext x simp [mem_image] @[simp] theorem image_bot (s : Set α) : (⊥ : Rel α β).image s = ∅ := by rw [Set.eq_empty_iff_forall_not_mem] intro x h simp [mem_image, Bot.bot] at h @[simp] theorem image_top {s : Set α} (h : Set.Nonempty s) : (⊤ : Rel α β).image s = Set.univ := Set.eq_univ_of_forall fun _ ↦ ⟨h.some, by simp [h.some_mem, Top.top]⟩ /-- Preimage of a set under a relation `r`. Same as the image of `s` under `r.inv` -/ def preimage (s : Set β) : Set α := r.inv.image s theorem mem_preimage (x : α) (s : Set β) : x ∈ r.preimage s ↔ ∃ y ∈ s, r x y := Iff.rfl theorem preimage_def (s : Set β) : preimage r s = { x | ∃ y ∈ s, r x y } := Set.ext fun _ => mem_preimage _ _ _ theorem preimage_mono {s t : Set β} (h : s ⊆ t) : r.preimage s ⊆ r.preimage t := image_mono _ h theorem preimage_inter (s t : Set β) : r.preimage (s ∩ t) ⊆ r.preimage s ∩ r.preimage t :=
image_inter _ s t theorem preimage_union (s t : Set β) : r.preimage (s ∪ t) = r.preimage s ∪ r.preimage t :=
Mathlib/Data/Rel.lean
210
212
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import Mathlib.Topology.Algebra.Constructions import Mathlib.Topology.Bases import Mathlib.Algebra.Order.Group.Nat import Mathlib.Topology.UniformSpace.Basic /-! # Theory of Cauchy filters in uniform spaces. Complete uniform spaces. Totally bounded subsets. -/ universe u v open Filter Function TopologicalSpace Topology Set UniformSpace Uniformity variable {α : Type u} {β : Type v} [uniformSpace : UniformSpace α] /-- A filter `f` is Cauchy if for every entourage `r`, there exists an `s ∈ f` such that `s × s ⊆ r`. This is a generalization of Cauchy sequences, because if `a : ℕ → α` then the filter of sets containing cofinitely many of the `a n` is Cauchy iff `a` is a Cauchy sequence. -/ def Cauchy (f : Filter α) := NeBot f ∧ f ×ˢ f ≤ 𝓤 α /-- A set `s` is called *complete*, if any Cauchy filter `f` such that `s ∈ f` has a limit in `s` (formally, it satisfies `f ≤ 𝓝 x` for some `x ∈ s`). -/ def IsComplete (s : Set α) := ∀ f, Cauchy f → f ≤ 𝓟 s → ∃ x ∈ s, f ≤ 𝓝 x theorem Filter.HasBasis.cauchy_iff {ι} {p : ι → Prop} {s : ι → Set (α × α)} (h : (𝓤 α).HasBasis p s) {f : Filter α} : Cauchy f ↔ NeBot f ∧ ∀ i, p i → ∃ t ∈ f, ∀ x ∈ t, ∀ y ∈ t, (x, y) ∈ s i := and_congr Iff.rfl <| (f.basis_sets.prod_self.le_basis_iff h).trans <| by simp only [subset_def, Prod.forall, mem_prod_eq, and_imp, id, forall_mem_comm] theorem cauchy_iff' {f : Filter α} : Cauchy f ↔ NeBot f ∧ ∀ s ∈ 𝓤 α, ∃ t ∈ f, ∀ x ∈ t, ∀ y ∈ t, (x, y) ∈ s := (𝓤 α).basis_sets.cauchy_iff theorem cauchy_iff {f : Filter α} : Cauchy f ↔ NeBot f ∧ ∀ s ∈ 𝓤 α, ∃ t ∈ f, t ×ˢ t ⊆ s := cauchy_iff'.trans <| by simp only [subset_def, Prod.forall, mem_prod_eq, and_imp, id, forall_mem_comm] lemma cauchy_iff_le {l : Filter α} [hl : l.NeBot] : Cauchy l ↔ l ×ˢ l ≤ 𝓤 α := by simp only [Cauchy, hl, true_and] theorem Cauchy.ultrafilter_of {l : Filter α} (h : Cauchy l) : Cauchy (@Ultrafilter.of _ l h.1 : Filter α) := by haveI := h.1 have := Ultrafilter.of_le l exact ⟨Ultrafilter.neBot _, (Filter.prod_mono this this).trans h.2⟩ theorem cauchy_map_iff {l : Filter β} {f : β → α} : Cauchy (l.map f) ↔ NeBot l ∧ Tendsto (fun p : β × β => (f p.1, f p.2)) (l ×ˢ l) (𝓤 α) := by rw [Cauchy, map_neBot_iff, prod_map_map_eq, Tendsto] theorem cauchy_map_iff' {l : Filter β} [hl : NeBot l] {f : β → α} : Cauchy (l.map f) ↔ Tendsto (fun p : β × β => (f p.1, f p.2)) (l ×ˢ l) (𝓤 α) := cauchy_map_iff.trans <| and_iff_right hl theorem Cauchy.mono {f g : Filter α} [hg : NeBot g] (h_c : Cauchy f) (h_le : g ≤ f) : Cauchy g := ⟨hg, le_trans (Filter.prod_mono h_le h_le) h_c.right⟩ theorem Cauchy.mono' {f g : Filter α} (h_c : Cauchy f) (_ : NeBot g) (h_le : g ≤ f) : Cauchy g := h_c.mono h_le theorem cauchy_nhds {a : α} : Cauchy (𝓝 a) := ⟨nhds_neBot, nhds_prod_eq.symm.trans_le (nhds_le_uniformity a)⟩ theorem cauchy_pure {a : α} : Cauchy (pure a) := cauchy_nhds.mono (pure_le_nhds a) theorem Filter.Tendsto.cauchy_map {l : Filter β} [NeBot l] {f : β → α} {a : α} (h : Tendsto f l (𝓝 a)) : Cauchy (map f l) := cauchy_nhds.mono h lemma Cauchy.mono_uniformSpace {u v : UniformSpace β} {F : Filter β} (huv : u ≤ v) (hF : Cauchy (uniformSpace := u) F) : Cauchy (uniformSpace := v) F := ⟨hF.1, hF.2.trans huv⟩ lemma cauchy_inf_uniformSpace {u v : UniformSpace β} {F : Filter β} : Cauchy (uniformSpace := u ⊓ v) F ↔ Cauchy (uniformSpace := u) F ∧ Cauchy (uniformSpace := v) F := by unfold Cauchy rw [inf_uniformity (u := u), le_inf_iff, and_and_left] lemma cauchy_iInf_uniformSpace {ι : Sort*} [Nonempty ι] {u : ι → UniformSpace β} {l : Filter β} : Cauchy (uniformSpace := ⨅ i, u i) l ↔ ∀ i, Cauchy (uniformSpace := u i) l := by unfold Cauchy rw [iInf_uniformity, le_iInf_iff, forall_and, forall_const] lemma cauchy_iInf_uniformSpace' {ι : Sort*} {u : ι → UniformSpace β} {l : Filter β} [l.NeBot] : Cauchy (uniformSpace := ⨅ i, u i) l ↔ ∀ i, Cauchy (uniformSpace := u i) l := by simp_rw [cauchy_iff_le (uniformSpace := _), iInf_uniformity, le_iInf_iff] lemma cauchy_comap_uniformSpace {u : UniformSpace β} {α} {f : α → β} {l : Filter α} : Cauchy (uniformSpace := comap f u) l ↔ Cauchy (map f l) := by simp only [Cauchy, map_neBot_iff, prod_map_map_eq, map_le_iff_le_comap] rfl lemma cauchy_prod_iff [UniformSpace β] {F : Filter (α × β)} : Cauchy F ↔ Cauchy (map Prod.fst F) ∧ Cauchy (map Prod.snd F) := by simp_rw [instUniformSpaceProd, ← cauchy_comap_uniformSpace, ← cauchy_inf_uniformSpace] theorem Cauchy.prod [UniformSpace β] {f : Filter α} {g : Filter β} (hf : Cauchy f) (hg : Cauchy g) : Cauchy (f ×ˢ g) := by have := hf.1; have := hg.1 simpa [cauchy_prod_iff, hf.1] using ⟨hf, hg⟩ /-- The common part of the proofs of `le_nhds_of_cauchy_adhp` and `SequentiallyComplete.le_nhds_of_seq_tendsto_nhds`: if for any entourage `s` one can choose a set `t ∈ f` of diameter `s` such that it contains a point `y` with `(x, y) ∈ s`, then `f` converges to `x`. -/ theorem le_nhds_of_cauchy_adhp_aux {f : Filter α} {x : α} (adhs : ∀ s ∈ 𝓤 α, ∃ t ∈ f, t ×ˢ t ⊆ s ∧ ∃ y, (x, y) ∈ s ∧ y ∈ t) : f ≤ 𝓝 x := by -- Consider a neighborhood `s` of `x` intro s hs -- Take an entourage twice smaller than `s` rcases comp_mem_uniformity_sets (mem_nhds_uniformity_iff_right.1 hs) with ⟨U, U_mem, hU⟩ -- Take a set `t ∈ f`, `t × t ⊆ U`, and a point `y ∈ t` such that `(x, y) ∈ U` rcases adhs U U_mem with ⟨t, t_mem, ht, y, hxy, hy⟩ apply mem_of_superset t_mem -- Given a point `z ∈ t`, we have `(x, y) ∈ U` and `(y, z) ∈ t × t ⊆ U`, hence `z ∈ s` exact fun z hz => hU (prodMk_mem_compRel hxy (ht <| mk_mem_prod hy hz)) rfl /-- If `x` is an adherent (cluster) point for a Cauchy filter `f`, then it is a limit point for `f`. -/ theorem le_nhds_of_cauchy_adhp {f : Filter α} {x : α} (hf : Cauchy f) (adhs : ClusterPt x f) : f ≤ 𝓝 x := le_nhds_of_cauchy_adhp_aux (fun s hs => by obtain ⟨t, t_mem, ht⟩ : ∃ t ∈ f, t ×ˢ t ⊆ s := (cauchy_iff.1 hf).2 s hs use t, t_mem, ht exact forall_mem_nonempty_iff_neBot.2 adhs _ (inter_mem_inf (mem_nhds_left x hs) t_mem)) theorem le_nhds_iff_adhp_of_cauchy {f : Filter α} {x : α} (hf : Cauchy f) : f ≤ 𝓝 x ↔ ClusterPt x f := ⟨fun h => ClusterPt.of_le_nhds' h hf.1, le_nhds_of_cauchy_adhp hf⟩ nonrec theorem Cauchy.map [UniformSpace β] {f : Filter α} {m : α → β} (hf : Cauchy f) (hm : UniformContinuous m) : Cauchy (map m f) := ⟨hf.1.map _, calc map m f ×ˢ map m f = map (Prod.map m m) (f ×ˢ f) := Filter.prod_map_map_eq _ ≤ Filter.map (Prod.map m m) (𝓤 α) := map_mono hf.right _ ≤ 𝓤 β := hm⟩ nonrec theorem Cauchy.comap [UniformSpace β] {f : Filter β} {m : α → β} (hf : Cauchy f) (hm : comap (fun p : α × α => (m p.1, m p.2)) (𝓤 β) ≤ 𝓤 α) [NeBot (comap m f)] : Cauchy (comap m f) := ⟨‹_›, calc comap m f ×ˢ comap m f = comap (Prod.map m m) (f ×ˢ f) := prod_comap_comap_eq _ ≤ comap (Prod.map m m) (𝓤 β) := comap_mono hf.right _ ≤ 𝓤 α := hm⟩ theorem Cauchy.comap' [UniformSpace β] {f : Filter β} {m : α → β} (hf : Cauchy f) (hm : Filter.comap (fun p : α × α => (m p.1, m p.2)) (𝓤 β) ≤ 𝓤 α) (_ : NeBot (Filter.comap m f)) : Cauchy (Filter.comap m f) := hf.comap hm /-- Cauchy sequences. Usually defined on ℕ, but often it is also useful to say that a function defined on ℝ is Cauchy at +∞ to deduce convergence. Therefore, we define it in a type class that is general enough to cover both ℕ and ℝ, which are the main motivating examples. -/ def CauchySeq [Preorder β] (u : β → α) := Cauchy (atTop.map u) theorem CauchySeq.tendsto_uniformity [Preorder β] {u : β → α} (h : CauchySeq u) : Tendsto (Prod.map u u) atTop (𝓤 α) := by simpa only [Tendsto, prod_map_map_eq', prod_atTop_atTop_eq] using h.right theorem CauchySeq.nonempty [Preorder β] {u : β → α} (hu : CauchySeq u) : Nonempty β := @nonempty_of_neBot _ _ <| (map_neBot_iff _).1 hu.1 theorem CauchySeq.mem_entourage {β : Type*} [SemilatticeSup β] {u : β → α} (h : CauchySeq u) {V : Set (α × α)} (hV : V ∈ 𝓤 α) : ∃ k₀, ∀ i j, k₀ ≤ i → k₀ ≤ j → (u i, u j) ∈ V := by haveI := h.nonempty have := h.tendsto_uniformity; rw [← prod_atTop_atTop_eq] at this simpa [MapsTo] using atTop_basis.prod_self.tendsto_left_iff.1 this V hV theorem Filter.Tendsto.cauchySeq [SemilatticeSup β] [Nonempty β] {f : β → α} {x} (hx : Tendsto f atTop (𝓝 x)) : CauchySeq f := hx.cauchy_map theorem cauchySeq_const [SemilatticeSup β] [Nonempty β] (x : α) : CauchySeq fun _ : β => x := tendsto_const_nhds.cauchySeq theorem cauchySeq_iff_tendsto [Nonempty β] [SemilatticeSup β] {u : β → α} : CauchySeq u ↔ Tendsto (Prod.map u u) atTop (𝓤 α) := cauchy_map_iff'.trans <| by simp only [prod_atTop_atTop_eq, Prod.map_def] theorem CauchySeq.comp_tendsto {γ} [Preorder β] [SemilatticeSup γ] [Nonempty γ] {f : β → α} (hf : CauchySeq f) {g : γ → β} (hg : Tendsto g atTop atTop) : CauchySeq (f ∘ g) := ⟨inferInstance, le_trans (prod_le_prod.mpr ⟨Tendsto.comp le_rfl hg, Tendsto.comp le_rfl hg⟩) hf.2⟩ theorem CauchySeq.comp_injective [SemilatticeSup β] [NoMaxOrder β] [Nonempty β] {u : ℕ → α} (hu : CauchySeq u) {f : β → ℕ} (hf : Injective f) : CauchySeq (u ∘ f) := hu.comp_tendsto <| Nat.cofinite_eq_atTop ▸ hf.tendsto_cofinite.mono_left atTop_le_cofinite theorem Function.Bijective.cauchySeq_comp_iff {f : ℕ → ℕ} (hf : Bijective f) (u : ℕ → α) : CauchySeq (u ∘ f) ↔ CauchySeq u := by refine ⟨fun H => ?_, fun H => H.comp_injective hf.injective⟩ lift f to ℕ ≃ ℕ using hf simpa only [Function.comp_def, f.apply_symm_apply] using H.comp_injective f.symm.injective theorem CauchySeq.subseq_subseq_mem {V : ℕ → Set (α × α)} (hV : ∀ n, V n ∈ 𝓤 α) {u : ℕ → α} (hu : CauchySeq u) {f g : ℕ → ℕ} (hf : Tendsto f atTop atTop) (hg : Tendsto g atTop atTop) : ∃ φ : ℕ → ℕ, StrictMono φ ∧ ∀ n, ((u ∘ f ∘ φ) n, (u ∘ g ∘ φ) n) ∈ V n := by rw [cauchySeq_iff_tendsto] at hu exact ((hu.comp <| hf.prod_atTop hg).comp tendsto_atTop_diagonal).subseq_mem hV -- todo: generalize this and other lemmas to a nonempty semilattice theorem cauchySeq_iff' {u : ℕ → α} : CauchySeq u ↔ ∀ V ∈ 𝓤 α, ∀ᶠ k in atTop, k ∈ Prod.map u u ⁻¹' V := cauchySeq_iff_tendsto theorem cauchySeq_iff {u : ℕ → α} : CauchySeq u ↔ ∀ V ∈ 𝓤 α, ∃ N, ∀ k ≥ N, ∀ l ≥ N, (u k, u l) ∈ V := by simp only [cauchySeq_iff', Filter.eventually_atTop_prod_self', mem_preimage, Prod.map_apply] theorem CauchySeq.prodMap {γ δ} [UniformSpace β] [Preorder γ] [Preorder δ] {u : γ → α} {v : δ → β} (hu : CauchySeq u) (hv : CauchySeq v) : CauchySeq (Prod.map u v) := by simpa only [CauchySeq, prod_map_map_eq', prod_atTop_atTop_eq] using hu.prod hv @[deprecated (since := "2025-03-10")] alias CauchySeq.prod_map := CauchySeq.prodMap theorem CauchySeq.prodMk {γ} [UniformSpace β] [Preorder γ] {u : γ → α} {v : γ → β} (hu : CauchySeq u) (hv : CauchySeq v) : CauchySeq fun x => (u x, v x) := haveI := hu.1.of_map (Cauchy.prod hu hv).mono (tendsto_map.prodMk tendsto_map) @[deprecated (since := "2025-03-10")] alias CauchySeq.prod := CauchySeq.prodMk theorem CauchySeq.eventually_eventually [Preorder β] {u : β → α} (hu : CauchySeq u) {V : Set (α × α)} (hV : V ∈ 𝓤 α) : ∀ᶠ k in atTop, ∀ᶠ l in atTop, (u k, u l) ∈ V := eventually_atTop_curry <| hu.tendsto_uniformity hV theorem UniformContinuous.comp_cauchySeq {γ} [UniformSpace β] [Preorder γ] {f : α → β} (hf : UniformContinuous f) {u : γ → α} (hu : CauchySeq u) : CauchySeq (f ∘ u) := hu.map hf theorem CauchySeq.subseq_mem {V : ℕ → Set (α × α)} (hV : ∀ n, V n ∈ 𝓤 α) {u : ℕ → α} (hu : CauchySeq u) : ∃ φ : ℕ → ℕ, StrictMono φ ∧ ∀ n, (u <| φ (n + 1), u <| φ n) ∈ V n := by have : ∀ n, ∃ N, ∀ k ≥ N, ∀ l ≥ k, (u l, u k) ∈ V n := fun n => by rw [cauchySeq_iff] at hu rcases hu _ (hV n) with ⟨N, H⟩ exact ⟨N, fun k hk l hl => H _ (le_trans hk hl) _ hk⟩ obtain ⟨φ : ℕ → ℕ, φ_extr : StrictMono φ, hφ : ∀ n, ∀ l ≥ φ n, (u l, u <| φ n) ∈ V n⟩ := extraction_forall_of_eventually' this exact ⟨φ, φ_extr, fun n => hφ _ _ (φ_extr <| Nat.lt_add_one n).le⟩ theorem Filter.Tendsto.subseq_mem_entourage {V : ℕ → Set (α × α)} (hV : ∀ n, V n ∈ 𝓤 α) {u : ℕ → α} {a : α} (hu : Tendsto u atTop (𝓝 a)) : ∃ φ : ℕ → ℕ, StrictMono φ ∧ (u (φ 0), a) ∈ V 0 ∧ ∀ n, (u <| φ (n + 1), u <| φ n) ∈ V (n + 1) := by rcases mem_atTop_sets.1 (hu (ball_mem_nhds a (symm_le_uniformity <| hV 0))) with ⟨n, hn⟩ rcases (hu.comp (tendsto_add_atTop_nat n)).cauchySeq.subseq_mem fun n => hV (n + 1) with ⟨φ, φ_mono, hφV⟩ exact ⟨fun k => φ k + n, φ_mono.add_const _, hn _ le_add_self, hφV⟩ /-- If a Cauchy sequence has a convergent subsequence, then it converges. -/ theorem tendsto_nhds_of_cauchySeq_of_subseq [Preorder β] {u : β → α} (hu : CauchySeq u) {ι : Type*} {f : ι → β} {p : Filter ι} [NeBot p] (hf : Tendsto f p atTop) {a : α} (ha : Tendsto (u ∘ f) p (𝓝 a)) : Tendsto u atTop (𝓝 a) := le_nhds_of_cauchy_adhp hu (ha.mapClusterPt.of_comp hf) /-- Any shift of a Cauchy sequence is also a Cauchy sequence. -/ theorem cauchySeq_shift {u : ℕ → α} (k : ℕ) : CauchySeq (fun n ↦ u (n + k)) ↔ CauchySeq u := by constructor <;> intro h · rw [cauchySeq_iff] at h ⊢ intro V mV obtain ⟨N, h⟩ := h V mV use N + k intro a ha b hb convert h (a - k) (Nat.le_sub_of_add_le ha) (b - k) (Nat.le_sub_of_add_le hb) <;> omega · exact h.comp_tendsto (tendsto_add_atTop_nat k) theorem Filter.HasBasis.cauchySeq_iff {γ} [Nonempty β] [SemilatticeSup β] {u : β → α} {p : γ → Prop} {s : γ → Set (α × α)} (h : (𝓤 α).HasBasis p s) : CauchySeq u ↔ ∀ i, p i → ∃ N, ∀ m, N ≤ m → ∀ n, N ≤ n → (u m, u n) ∈ s i := by rw [cauchySeq_iff_tendsto, ← prod_atTop_atTop_eq] refine (atTop_basis.prod_self.tendsto_iff h).trans ?_ simp only [exists_prop, true_and, MapsTo, preimage, subset_def, Prod.forall, mem_prod_eq, mem_setOf_eq, mem_Ici, and_imp, Prod.map, @forall_swap (_ ≤ _) β] theorem Filter.HasBasis.cauchySeq_iff' {γ} [Nonempty β] [SemilatticeSup β] {u : β → α} {p : γ → Prop} {s : γ → Set (α × α)} (H : (𝓤 α).HasBasis p s) : CauchySeq u ↔ ∀ i, p i → ∃ N, ∀ n ≥ N, (u n, u N) ∈ s i := by refine H.cauchySeq_iff.trans ⟨fun h i hi => ?_, fun h i hi => ?_⟩ · exact (h i hi).imp fun N hN n hn => hN n hn N le_rfl · rcases comp_symm_of_uniformity (H.mem_of_mem hi) with ⟨t, ht, ht', hts⟩ rcases H.mem_iff.1 ht with ⟨j, hj, hjt⟩ refine (h j hj).imp fun N hN m hm n hn => hts ⟨u N, hjt ?_, ht' <| hjt ?_⟩ exacts [hN m hm, hN n hn] theorem cauchySeq_of_controlled [SemilatticeSup β] [Nonempty β] (U : β → Set (α × α)) (hU : ∀ s ∈ 𝓤 α, ∃ n, U n ⊆ s) {f : β → α} (hf : ∀ ⦃N m n : β⦄, N ≤ m → N ≤ n → (f m, f n) ∈ U N) : CauchySeq f := cauchySeq_iff_tendsto.2 (by intro s hs rw [mem_map, mem_atTop_sets] obtain ⟨N, hN⟩ := hU s hs refine ⟨(N, N), fun mn hmn => ?_⟩ obtain ⟨m, n⟩ := mn exact hN (hf hmn.1 hmn.2)) theorem isComplete_iff_clusterPt {s : Set α} : IsComplete s ↔ ∀ l, Cauchy l → l ≤ 𝓟 s → ∃ x ∈ s, ClusterPt x l := forall₃_congr fun _ hl _ => exists_congr fun _ => and_congr_right fun _ => le_nhds_iff_adhp_of_cauchy hl theorem isComplete_iff_ultrafilter {s : Set α} : IsComplete s ↔ ∀ l : Ultrafilter α, Cauchy (l : Filter α) → ↑l ≤ 𝓟 s → ∃ x ∈ s, ↑l ≤ 𝓝 x := by refine ⟨fun h l => h l, fun H => isComplete_iff_clusterPt.2 fun l hl hls => ?_⟩ haveI := hl.1 rcases H (Ultrafilter.of l) hl.ultrafilter_of ((Ultrafilter.of_le l).trans hls) with ⟨x, hxs, hxl⟩ exact ⟨x, hxs, (ClusterPt.of_le_nhds hxl).mono (Ultrafilter.of_le l)⟩ theorem isComplete_iff_ultrafilter' {s : Set α} : IsComplete s ↔ ∀ l : Ultrafilter α, Cauchy (l : Filter α) → s ∈ l → ∃ x ∈ s, ↑l ≤ 𝓝 x := isComplete_iff_ultrafilter.trans <| by simp only [le_principal_iff, Ultrafilter.mem_coe] protected theorem IsComplete.union {s t : Set α} (hs : IsComplete s) (ht : IsComplete t) : IsComplete (s ∪ t) := by simp only [isComplete_iff_ultrafilter', Ultrafilter.union_mem_iff, or_imp] at * exact fun l hl => ⟨fun hsl => (hs l hl hsl).imp fun x hx => ⟨Or.inl hx.1, hx.2⟩, fun htl => (ht l hl htl).imp fun x hx => ⟨Or.inr hx.1, hx.2⟩⟩ theorem isComplete_iUnion_separated {ι : Sort*} {s : ι → Set α} (hs : ∀ i, IsComplete (s i)) {U : Set (α × α)} (hU : U ∈ 𝓤 α) (hd : ∀ (i j : ι), ∀ x ∈ s i, ∀ y ∈ s j, (x, y) ∈ U → i = j) : IsComplete (⋃ i, s i) := by set S := ⋃ i, s i intro l hl hls rw [le_principal_iff] at hls obtain ⟨hl_ne, hl'⟩ := cauchy_iff.1 hl obtain ⟨t, htS, htl, htU⟩ : ∃ t, t ⊆ S ∧ t ∈ l ∧ t ×ˢ t ⊆ U := by rcases hl' U hU with ⟨t, htl, htU⟩ refine ⟨t ∩ S, inter_subset_right, inter_mem htl hls, Subset.trans ?_ htU⟩ gcongr <;> apply inter_subset_left obtain ⟨i, hi⟩ : ∃ i, t ⊆ s i := by rcases Filter.nonempty_of_mem htl with ⟨x, hx⟩ rcases mem_iUnion.1 (htS hx) with ⟨i, hi⟩ refine ⟨i, fun y hy => ?_⟩ rcases mem_iUnion.1 (htS hy) with ⟨j, hj⟩ rwa [hd i j x hi y hj (htU <| mk_mem_prod hx hy)] rcases hs i l hl (le_principal_iff.2 <| mem_of_superset htl hi) with ⟨x, hxs, hlx⟩ exact ⟨x, mem_iUnion.2 ⟨i, hxs⟩, hlx⟩ /-- A complete space is defined here using uniformities. A uniform space is complete if every Cauchy filter converges. -/ class CompleteSpace (α : Type u) [UniformSpace α] : Prop where /-- In a complete uniform space, every Cauchy filter converges. -/ complete : ∀ {f : Filter α}, Cauchy f → ∃ x, f ≤ 𝓝 x theorem complete_univ {α : Type u} [UniformSpace α] [CompleteSpace α] : IsComplete (univ : Set α) := fun f hf _ => by rcases CompleteSpace.complete hf with ⟨x, hx⟩ exact ⟨x, mem_univ x, hx⟩ instance CompleteSpace.prod [UniformSpace β] [CompleteSpace α] [CompleteSpace β] : CompleteSpace (α × β) where complete hf := let ⟨x1, hx1⟩ := CompleteSpace.complete <| hf.map uniformContinuous_fst let ⟨x2, hx2⟩ := CompleteSpace.complete <| hf.map uniformContinuous_snd ⟨(x1, x2), by rw [nhds_prod_eq, le_prod]; constructor <;> assumption⟩ lemma CompleteSpace.fst_of_prod [UniformSpace β] [CompleteSpace (α × β)] [h : Nonempty β] : CompleteSpace α where complete hf := let ⟨y⟩ := h let ⟨(a, b), hab⟩ := CompleteSpace.complete <| hf.prod <| cauchy_pure (a := y) ⟨a, by simpa only [map_fst_prod, nhds_prod_eq] using map_mono (m := Prod.fst) hab⟩ lemma CompleteSpace.snd_of_prod [UniformSpace β] [CompleteSpace (α × β)] [h : Nonempty α] : CompleteSpace β where complete hf := let ⟨x⟩ := h let ⟨(a, b), hab⟩ := CompleteSpace.complete <| (cauchy_pure (a := x)).prod hf ⟨b, by simpa only [map_snd_prod, nhds_prod_eq] using map_mono (m := Prod.snd) hab⟩ lemma completeSpace_prod_of_nonempty [UniformSpace β] [Nonempty α] [Nonempty β] : CompleteSpace (α × β) ↔ CompleteSpace α ∧ CompleteSpace β := ⟨fun _ ↦ ⟨.fst_of_prod (β := β), .snd_of_prod (α := α)⟩, fun ⟨_, _⟩ ↦ .prod⟩ @[to_additive] instance CompleteSpace.mulOpposite [CompleteSpace α] : CompleteSpace αᵐᵒᵖ where complete hf := MulOpposite.op_surjective.exists.mpr <| let ⟨x, hx⟩ := CompleteSpace.complete (hf.map MulOpposite.uniformContinuous_unop) ⟨x, (map_le_iff_le_comap.mp hx).trans_eq <| MulOpposite.comap_unop_nhds _⟩ /-- If `univ` is complete, the space is a complete space -/ theorem completeSpace_of_isComplete_univ (h : IsComplete (univ : Set α)) : CompleteSpace α := ⟨fun hf => let ⟨x, _, hx⟩ := h _ hf ((@principal_univ α).symm ▸ le_top); ⟨x, hx⟩⟩ theorem completeSpace_iff_isComplete_univ : CompleteSpace α ↔ IsComplete (univ : Set α) := ⟨@complete_univ α _, completeSpace_of_isComplete_univ⟩ theorem completeSpace_iff_ultrafilter : CompleteSpace α ↔ ∀ l : Ultrafilter α, Cauchy (l : Filter α) → ∃ x : α, ↑l ≤ 𝓝 x := by simp [completeSpace_iff_isComplete_univ, isComplete_iff_ultrafilter] theorem cauchy_iff_exists_le_nhds [CompleteSpace α] {l : Filter α} [NeBot l] : Cauchy l ↔ ∃ x, l ≤ 𝓝 x := ⟨CompleteSpace.complete, fun ⟨_, hx⟩ => cauchy_nhds.mono hx⟩ theorem cauchy_map_iff_exists_tendsto [CompleteSpace α] {l : Filter β} {f : β → α} [NeBot l] : Cauchy (l.map f) ↔ ∃ x, Tendsto f l (𝓝 x) := cauchy_iff_exists_le_nhds /-- A Cauchy sequence in a complete space converges -/ theorem cauchySeq_tendsto_of_complete [Preorder β] [CompleteSpace α] {u : β → α} (H : CauchySeq u) : ∃ x, Tendsto u atTop (𝓝 x) := CompleteSpace.complete H /-- If `K` is a complete subset, then any cauchy sequence in `K` converges to a point in `K` -/ theorem cauchySeq_tendsto_of_isComplete [Preorder β] {K : Set α} (h₁ : IsComplete K) {u : β → α} (h₂ : ∀ n, u n ∈ K) (h₃ : CauchySeq u) : ∃ v ∈ K, Tendsto u atTop (𝓝 v) := h₁ _ h₃ <| le_principal_iff.2 <| mem_map_iff_exists_image.2 ⟨univ, univ_mem, by rwa [image_univ, range_subset_iff]⟩ theorem Cauchy.le_nhds_lim [CompleteSpace α] {f : Filter α} (hf : Cauchy f) : haveI := hf.1.nonempty; f ≤ 𝓝 (lim f) := _root_.le_nhds_lim (CompleteSpace.complete hf) theorem CauchySeq.tendsto_limUnder [Preorder β] [CompleteSpace α] {u : β → α} (h : CauchySeq u) : haveI := h.1.nonempty; Tendsto u atTop (𝓝 <| limUnder atTop u) := h.le_nhds_lim theorem IsClosed.isComplete [CompleteSpace α] {s : Set α} (h : IsClosed s) : IsComplete s := fun _ cf fs => let ⟨x, hx⟩ := CompleteSpace.complete cf ⟨x, isClosed_iff_clusterPt.mp h x (cf.left.mono (le_inf hx fs)), hx⟩ /-- A set `s` is totally bounded if for every entourage `d` there is a finite set of points `t` such that every element of `s` is `d`-near to some element of `t`. -/ def TotallyBounded (s : Set α) : Prop := ∀ d ∈ 𝓤 α, ∃ t : Set α, t.Finite ∧ s ⊆ ⋃ y ∈ t, { x | (x, y) ∈ d } theorem TotallyBounded.exists_subset {s : Set α} (hs : TotallyBounded s) {U : Set (α × α)} (hU : U ∈ 𝓤 α) : ∃ t, t ⊆ s ∧ Set.Finite t ∧ s ⊆ ⋃ y ∈ t, { x | (x, y) ∈ U } := by rcases comp_symm_of_uniformity hU with ⟨r, hr, rs, rU⟩ rcases hs r hr with ⟨k, fk, ks⟩ let u := k ∩ { y | ∃ x ∈ s, (x, y) ∈ r } choose f hfs hfr using fun x : u => x.coe_prop.2 refine ⟨range f, ?_, ?_, ?_⟩ · exact range_subset_iff.2 hfs · haveI : Fintype u := (fk.inter_of_left _).fintype exact finite_range f · intro x xs obtain ⟨y, hy, xy⟩ := mem_iUnion₂.1 (ks xs) rw [biUnion_range, mem_iUnion] set z : ↥u := ⟨y, hy, ⟨x, xs, xy⟩⟩ exact ⟨z, rU <| mem_compRel.2 ⟨y, xy, rs (hfr z)⟩⟩ theorem totallyBounded_iff_subset {s : Set α} : TotallyBounded s ↔ ∀ d ∈ 𝓤 α, ∃ t, t ⊆ s ∧ Set.Finite t ∧ s ⊆ ⋃ y ∈ t, { x | (x, y) ∈ d } := ⟨fun H _ hd ↦ H.exists_subset hd, fun H d hd ↦ let ⟨t, _, ht⟩ := H d hd; ⟨t, ht⟩⟩ theorem Filter.HasBasis.totallyBounded_iff {ι} {p : ι → Prop} {U : ι → Set (α × α)} (H : (𝓤 α).HasBasis p U) {s : Set α} : TotallyBounded s ↔ ∀ i, p i → ∃ t : Set α, Set.Finite t ∧ s ⊆ ⋃ y ∈ t, { x | (x, y) ∈ U i } := H.forall_iff fun _ _ hUV h => h.imp fun _ ht => ⟨ht.1, ht.2.trans <| iUnion₂_mono fun _ _ _ hy => hUV hy⟩ theorem totallyBounded_of_forall_symm {s : Set α} (h : ∀ V ∈ 𝓤 α, IsSymmetricRel V → ∃ t : Set α, Set.Finite t ∧ s ⊆ ⋃ y ∈ t, ball y V) : TotallyBounded s := UniformSpace.hasBasis_symmetric.totallyBounded_iff.2 fun V hV => by simpa only [ball_eq_of_symmetry hV.2] using h V hV.1 hV.2 theorem TotallyBounded.subset {s₁ s₂ : Set α} (hs : s₁ ⊆ s₂) (h : TotallyBounded s₂) : TotallyBounded s₁ := fun d hd => let ⟨t, ht₁, ht₂⟩ := h d hd ⟨t, ht₁, Subset.trans hs ht₂⟩ /-- The closure of a totally bounded set is totally bounded. -/ theorem TotallyBounded.closure {s : Set α} (h : TotallyBounded s) : TotallyBounded (closure s) := uniformity_hasBasis_closed.totallyBounded_iff.2 fun V hV => let ⟨t, htf, hst⟩ := h V hV.1 ⟨t, htf, closure_minimal hst <| htf.isClosed_biUnion fun _ _ => hV.2.preimage (.prodMk_left _)⟩ @[simp] lemma totallyBounded_closure {s : Set α} : TotallyBounded (closure s) ↔ TotallyBounded s := ⟨fun h ↦ h.subset subset_closure, TotallyBounded.closure⟩ /-- A finite indexed union is totally bounded if and only if each set of the family is totally bounded. -/ @[simp] lemma totallyBounded_iUnion {ι : Sort*} [Finite ι] {s : ι → Set α} : TotallyBounded (⋃ i, s i) ↔ ∀ i, TotallyBounded (s i) := by refine ⟨fun h i ↦ h.subset (subset_iUnion _ _), fun h U hU ↦ ?_⟩ choose t htf ht using (h · U hU) refine ⟨⋃ i, t i, finite_iUnion htf, ?_⟩ rw [biUnion_iUnion] gcongr; apply ht /-- A union indexed by a finite set is totally bounded if and only if each set of the family is totally bounded. -/ lemma totallyBounded_biUnion {ι : Type*} {I : Set ι} (hI : I.Finite) {s : ι → Set α} : TotallyBounded (⋃ i ∈ I, s i) ↔ ∀ i ∈ I, TotallyBounded (s i) := by have := hI.to_subtype rw [biUnion_eq_iUnion, totallyBounded_iUnion, Subtype.forall] /-- A union of a finite family of sets is totally bounded if and only if each set of the family is totally bounded. -/ lemma totallyBounded_sUnion {S : Set (Set α)} (hS : S.Finite) : TotallyBounded (⋃₀ S) ↔ ∀ s ∈ S, TotallyBounded s := by rw [sUnion_eq_biUnion, totallyBounded_biUnion hS] /-- A finite set is totally bounded. -/ lemma Set.Finite.totallyBounded {s : Set α} (hs : s.Finite) : TotallyBounded s := fun _U hU ↦ ⟨s, hs, fun _x hx ↦ mem_biUnion hx <| refl_mem_uniformity hU⟩ /-- A subsingleton is totally bounded. -/ lemma Set.Subsingleton.totallyBounded {s : Set α} (hs : s.Subsingleton) : TotallyBounded s := hs.finite.totallyBounded @[simp] lemma totallyBounded_singleton (a : α) : TotallyBounded {a} := (finite_singleton a).totallyBounded @[simp] theorem totallyBounded_empty : TotallyBounded (∅ : Set α) := finite_empty.totallyBounded /-- The union of two sets is totally bounded if and only if each of the two sets is totally bounded. -/ @[simp] lemma totallyBounded_union {s t : Set α} : TotallyBounded (s ∪ t) ↔ TotallyBounded s ∧ TotallyBounded t := by rw [union_eq_iUnion, totallyBounded_iUnion] simp [and_comm] /-- The union of two totally bounded sets is totally bounded. -/ protected lemma TotallyBounded.union {s t : Set α} (hs : TotallyBounded s) (ht : TotallyBounded t) : TotallyBounded (s ∪ t) := totallyBounded_union.2 ⟨hs, ht⟩ @[simp] lemma totallyBounded_insert (a : α) {s : Set α} : TotallyBounded (insert a s) ↔ TotallyBounded s := by simp_rw [← singleton_union, totallyBounded_union, totallyBounded_singleton, true_and] protected alias ⟨_, TotallyBounded.insert⟩ := totallyBounded_insert /-- The image of a totally bounded set under a uniformly continuous map is totally bounded. -/ theorem TotallyBounded.image [UniformSpace β] {f : α → β} {s : Set α} (hs : TotallyBounded s) (hf : UniformContinuous f) : TotallyBounded (f '' s) := fun t ht => have : { p : α × α | (f p.1, f p.2) ∈ t } ∈ 𝓤 α := hf ht let ⟨c, hfc, hct⟩ := hs _ this ⟨f '' c, hfc.image f, by simp only [mem_image, iUnion_exists, biUnion_and', iUnion_iUnion_eq_right, image_subset_iff, preimage_iUnion, preimage_setOf_eq] simp? [subset_def] at hct says simp only [mem_setOf_eq, subset_def, mem_iUnion, exists_prop] at hct intro x hx simpa using hct x hx⟩ theorem Ultrafilter.cauchy_of_totallyBounded {s : Set α} (f : Ultrafilter α) (hs : TotallyBounded s) (h : ↑f ≤ 𝓟 s) : Cauchy (f : Filter α) := ⟨f.neBot', fun _ ht => let ⟨t', ht'₁, ht'_symm, ht'_t⟩ := comp_symm_of_uniformity ht let ⟨i, hi, hs_union⟩ := hs t' ht'₁ have : (⋃ y ∈ i, { x | (x, y) ∈ t' }) ∈ f := mem_of_superset (le_principal_iff.mp h) hs_union have : ∃ y ∈ i, { x | (x, y) ∈ t' } ∈ f := (Ultrafilter.finite_biUnion_mem_iff hi).1 this let ⟨y, _, hif⟩ := this have : { x | (x, y) ∈ t' } ×ˢ { x | (x, y) ∈ t' } ⊆ compRel t' t' := fun ⟨_, _⟩ ⟨(h₁ : (_, y) ∈ t'), (h₂ : (_, y) ∈ t')⟩ => ⟨y, h₁, ht'_symm h₂⟩ mem_of_superset (prod_mem_prod hif hif) (Subset.trans this ht'_t)⟩ theorem totallyBounded_iff_filter {s : Set α} : TotallyBounded s ↔ ∀ f, NeBot f → f ≤ 𝓟 s → ∃ c ≤ f, Cauchy c := by constructor · exact fun H f hf hfs => ⟨Ultrafilter.of f, Ultrafilter.of_le f, (Ultrafilter.of f).cauchy_of_totallyBounded H ((Ultrafilter.of_le f).trans hfs)⟩ · intro H d hd contrapose! H with hd_cover set f := ⨅ t : Finset α, 𝓟 (s \ ⋃ y ∈ t, { x | (x, y) ∈ d }) have hb : HasAntitoneBasis f fun t : Finset α ↦ s \ ⋃ y ∈ t, { x | (x, y) ∈ d } := .iInf_principal fun _ _ ↦ diff_subset_diff_right ∘ biUnion_subset_biUnion_left have : Filter.NeBot f := hb.1.neBot_iff.2 fun _ ↦ diff_nonempty.2 <| hd_cover _ (Finset.finite_toSet _) have : f ≤ 𝓟 s := iInf_le_of_le ∅ (by simp) refine ⟨f, ‹_›, ‹_›, fun c hcf hc => ?_⟩ rcases mem_prod_same_iff.1 (hc.2 hd) with ⟨m, hm, hmd⟩ rcases hc.1.nonempty_of_mem hm with ⟨y, hym⟩ have : s \ {x | (x, y) ∈ d} ∈ c := by simpa using hcf (hb.mem {y}) rcases hc.1.nonempty_of_mem (inter_mem hm this) with ⟨z, hzm, -, hyz⟩ exact hyz (hmd ⟨hzm, hym⟩) theorem totallyBounded_iff_ultrafilter {s : Set α} : TotallyBounded s ↔ ∀ f : Ultrafilter α, ↑f ≤ 𝓟 s → Cauchy (f : Filter α) := by refine ⟨fun hs f => f.cauchy_of_totallyBounded hs, fun H => totallyBounded_iff_filter.2 ?_⟩ intro f hf hfs exact ⟨Ultrafilter.of f, Ultrafilter.of_le f, H _ ((Ultrafilter.of_le f).trans hfs)⟩ theorem isCompact_iff_totallyBounded_isComplete {s : Set α} : IsCompact s ↔ TotallyBounded s ∧ IsComplete s := ⟨fun hs => ⟨totallyBounded_iff_ultrafilter.2 fun f hf => let ⟨_, _, fx⟩ := isCompact_iff_ultrafilter_le_nhds.1 hs f hf cauchy_nhds.mono fx, fun f fc fs => let ⟨a, as, fa⟩ := @hs f fc.1 fs ⟨a, as, le_nhds_of_cauchy_adhp fc fa⟩⟩, fun ⟨ht, hc⟩ => isCompact_iff_ultrafilter_le_nhds.2 fun f hf => hc _ (totallyBounded_iff_ultrafilter.1 ht f hf) hf⟩ protected theorem IsCompact.totallyBounded {s : Set α} (h : IsCompact s) : TotallyBounded s := (isCompact_iff_totallyBounded_isComplete.1 h).1 protected theorem IsCompact.isComplete {s : Set α} (h : IsCompact s) : IsComplete s := (isCompact_iff_totallyBounded_isComplete.1 h).2 -- see Note [lower instance priority] instance (priority := 100) complete_of_compact {α : Type u} [UniformSpace α] [CompactSpace α] : CompleteSpace α := ⟨fun hf => by simpa using (isCompact_iff_totallyBounded_isComplete.1 isCompact_univ).2 _ hf⟩ theorem isCompact_of_totallyBounded_isClosed [CompleteSpace α] {s : Set α} (ht : TotallyBounded s) (hc : IsClosed s) : IsCompact s := (@isCompact_iff_totallyBounded_isComplete α _ s).2 ⟨ht, hc.isComplete⟩ /-- Every Cauchy sequence over `ℕ` is totally bounded. -/ theorem CauchySeq.totallyBounded_range {s : ℕ → α} (hs : CauchySeq s) : TotallyBounded (range s) := by intro a ha obtain ⟨n, hn⟩ := cauchySeq_iff.1 hs a ha refine ⟨s '' { k | k ≤ n }, (finite_le_nat _).image _, ?_⟩ rw [range_subset_iff, biUnion_image] intro m rw [mem_iUnion₂] rcases le_total m n with hm | hm exacts [⟨m, hm, refl_mem_uniformity ha⟩, ⟨n, le_refl n, hn m hm n le_rfl⟩] /-- Given a family of points `xs n`, a family of entourages `V n` of the diagonal and a family of natural numbers `u n`, the intersection over `n` of the `V n`-neighborhood of `xs 1, ..., xs (u n)`. Designed to be relatively compact when `V n` tends to the diagonal. -/ def interUnionBalls (xs : ℕ → α) (u : ℕ → ℕ) (V : ℕ → Set (α × α)) : Set α := ⋂ n, ⋃ m ≤ u n, UniformSpace.ball (xs m) (Prod.swap ⁻¹' V n) lemma totallyBounded_interUnionBalls {p : ℕ → Prop} {U : ℕ → Set (α × α)} (H : (uniformity α).HasBasis p U) (xs : ℕ → α) (u : ℕ → ℕ) : TotallyBounded (interUnionBalls xs u U) := by rw [Filter.HasBasis.totallyBounded_iff H] intro i _ have h_subset : interUnionBalls xs u U ⊆ ⋃ m ≤ u i, UniformSpace.ball (xs m) (Prod.swap ⁻¹' U i) := fun x hx ↦ Set.mem_iInter.1 hx i classical refine ⟨Finset.image xs (Finset.range (u i + 1)), Finset.finite_toSet _, fun x hx ↦ ?_⟩ simp only [Finset.coe_image, Finset.coe_range, mem_image, mem_Iio, iUnion_exists, biUnion_and', iUnion_iUnion_eq_right, Nat.lt_succ_iff] exact h_subset hx /-- The construction `interUnionBalls` is used to have a relatively compact set. -/ theorem isCompact_closure_interUnionBalls {p : ℕ → Prop} {U : ℕ → Set (α × α)} (H : (uniformity α).HasBasis p U) [CompleteSpace α] (xs : ℕ → α) (u : ℕ → ℕ) : IsCompact (closure (interUnionBalls xs u U)) := by rw [isCompact_iff_totallyBounded_isComplete] refine ⟨TotallyBounded.closure ?_, isClosed_closure.isComplete⟩ exact totallyBounded_interUnionBalls H xs u /-! ### Sequentially complete space In this section we prove that a uniform space is complete provided that it is sequentially complete (i.e., any Cauchy sequence converges) and its uniformity filter admits a countable generating set. In particular, this applies to (e)metric spaces, see the files `Topology/MetricSpace/EmetricSpace` and `Topology/MetricSpace/Basic`. More precisely, we assume that there is a sequence of entourages `U_n` such that any other entourage includes one of `U_n`. Then any Cauchy filter `f` generates a decreasing sequence of sets `s_n ∈ f` such that `s_n × s_n ⊆ U_n`. Choose a sequence `x_n∈s_n`. It is easy to show that this is a Cauchy sequence. If this sequence converges to some `a`, then `f ≤ 𝓝 a`. -/ namespace SequentiallyComplete variable {f : Filter α} (hf : Cauchy f) {U : ℕ → Set (α × α)} (U_mem : ∀ n, U n ∈ 𝓤 α) open Set Finset noncomputable section /-- An auxiliary sequence of sets approximating a Cauchy filter. -/ def setSeqAux (n : ℕ) : { s : Set α // s ∈ f ∧ s ×ˢ s ⊆ U n } := Classical.indefiniteDescription _ <| (cauchy_iff.1 hf).2 (U n) (U_mem n) /-- Given a Cauchy filter `f` and a sequence `U` of entourages, `set_seq` provides an antitone sequence of sets `s n ∈ f` such that `s n ×ˢ s n ⊆ U`. -/ def setSeq (n : ℕ) : Set α := ⋂ m ∈ Set.Iic n, (setSeqAux hf U_mem m).val theorem setSeq_mem (n : ℕ) : setSeq hf U_mem n ∈ f := (biInter_mem (finite_le_nat n)).2 fun m _ => (setSeqAux hf U_mem m).2.1 theorem setSeq_mono ⦃m n : ℕ⦄ (h : m ≤ n) : setSeq hf U_mem n ⊆ setSeq hf U_mem m := biInter_subset_biInter_left <| Iic_subset_Iic.2 h theorem setSeq_sub_aux (n : ℕ) : setSeq hf U_mem n ⊆ setSeqAux hf U_mem n := biInter_subset_of_mem right_mem_Iic theorem setSeq_prod_subset {N m n} (hm : N ≤ m) (hn : N ≤ n) : setSeq hf U_mem m ×ˢ setSeq hf U_mem n ⊆ U N := fun p hp => by refine (setSeqAux hf U_mem N).2.2 ⟨?_, ?_⟩ <;> apply setSeq_sub_aux · exact setSeq_mono hf U_mem hm hp.1 · exact setSeq_mono hf U_mem hn hp.2 /-- A sequence of points such that `seq n ∈ setSeq n`. Here `setSeq` is an antitone sequence of sets `setSeq n ∈ f` with diameters controlled by a given sequence of entourages. -/ def seq (n : ℕ) : α := (hf.1.nonempty_of_mem (setSeq_mem hf U_mem n)).choose theorem seq_mem (n : ℕ) : seq hf U_mem n ∈ setSeq hf U_mem n := (hf.1.nonempty_of_mem (setSeq_mem hf U_mem n)).choose_spec theorem seq_pair_mem ⦃N m n : ℕ⦄ (hm : N ≤ m) (hn : N ≤ n) : (seq hf U_mem m, seq hf U_mem n) ∈ U N := setSeq_prod_subset hf U_mem hm hn ⟨seq_mem hf U_mem m, seq_mem hf U_mem n⟩ theorem seq_is_cauchySeq (U_le : ∀ s ∈ 𝓤 α, ∃ n, U n ⊆ s) : CauchySeq <| seq hf U_mem := cauchySeq_of_controlled U U_le <| seq_pair_mem hf U_mem /-- If the sequence `SequentiallyComplete.seq` converges to `a`, then `f ≤ 𝓝 a`. -/ theorem le_nhds_of_seq_tendsto_nhds (U_le : ∀ s ∈ 𝓤 α, ∃ n, U n ⊆ s) ⦃a : α⦄ (ha : Tendsto (seq hf U_mem) atTop (𝓝 a)) : f ≤ 𝓝 a := le_nhds_of_cauchy_adhp_aux (fun s hs => by rcases U_le s hs with ⟨m, hm⟩ rcases tendsto_atTop'.1 ha _ (mem_nhds_left a (U_mem m)) with ⟨n, hn⟩ refine ⟨setSeq hf U_mem (max m n), setSeq_mem hf U_mem _, ?_, seq hf U_mem (max m n), ?_, seq_mem hf U_mem _⟩ · have := le_max_left m n exact Set.Subset.trans (setSeq_prod_subset hf U_mem this this) hm · exact hm (hn _ <| le_max_right m n)) end end SequentiallyComplete namespace UniformSpace open SequentiallyComplete variable [IsCountablyGenerated (𝓤 α)] /-- A uniform space is complete provided that (a) its uniformity filter has a countable basis; (b) any sequence satisfying a "controlled" version of the Cauchy condition converges. -/ theorem complete_of_convergent_controlled_sequences (U : ℕ → Set (α × α)) (U_mem : ∀ n, U n ∈ 𝓤 α) (HU : ∀ u : ℕ → α, (∀ N m n, N ≤ m → N ≤ n → (u m, u n) ∈ U N) → ∃ a, Tendsto u atTop (𝓝 a)) : CompleteSpace α := by obtain ⟨U', -, hU'⟩ := (𝓤 α).exists_antitone_seq have Hmem : ∀ n, U n ∩ U' n ∈ 𝓤 α := fun n => inter_mem (U_mem n) (hU'.2 ⟨n, Subset.refl _⟩) refine ⟨fun hf => (HU (seq hf Hmem) fun N m n hm hn => ?_).imp <| le_nhds_of_seq_tendsto_nhds _ _ fun s hs => ?_⟩ · exact inter_subset_left (seq_pair_mem hf Hmem hm hn) · rcases hU'.1 hs with ⟨N, hN⟩ exact ⟨N, Subset.trans inter_subset_right hN⟩ /-- A sequentially complete uniform space with a countable basis of the uniformity filter is complete. -/ theorem complete_of_cauchySeq_tendsto (H' : ∀ u : ℕ → α, CauchySeq u → ∃ a, Tendsto u atTop (𝓝 a)) : CompleteSpace α := let ⟨U', _, hU'⟩ := (𝓤 α).exists_antitone_seq complete_of_convergent_controlled_sequences U' (fun n => hU'.2 ⟨n, Subset.refl _⟩) fun u hu => H' u <| cauchySeq_of_controlled U' (fun _ hs => hU'.1 hs) hu variable (α) -- TODO: move to `Topology.UniformSpace.Basic` instance (priority := 100) firstCountableTopology : FirstCountableTopology α := ⟨fun a => by rw [nhds_eq_comap_uniformity]; infer_instance⟩ /-- A separable uniform space with countably generated uniformity filter is second countable: one obtains a countable basis by taking the balls centered at points in a dense subset, and with rational "radii" from a countable open symmetric antitone basis of `𝓤 α`. We do not register this as an instance, as there is already an instance going in the other direction from second countable spaces to separable spaces, and we want to avoid loops. -/ theorem secondCountable_of_separable [SeparableSpace α] : SecondCountableTopology α := by rcases exists_countable_dense α with ⟨s, hsc, hsd⟩ obtain ⟨t : ℕ → Set (α × α), hto : ∀ i : ℕ, t i ∈ (𝓤 α).sets ∧ IsOpen (t i) ∧ IsSymmetricRel (t i), h_basis : (𝓤 α).HasAntitoneBasis t⟩ := (@uniformity_hasBasis_open_symmetric α _).exists_antitone_subbasis choose ht_mem hto hts using hto refine ⟨⟨⋃ x ∈ s, range fun k => ball x (t k), hsc.biUnion fun x _ => countable_range _, ?_⟩⟩ refine (isTopologicalBasis_of_isOpen_of_nhds ?_ ?_).eq_generateFrom · simp only [mem_iUnion₂, mem_range] rintro _ ⟨x, _, k, rfl⟩ exact isOpen_ball x (hto k) · intro x V hxV hVo simp only [mem_iUnion₂, mem_range, exists_prop]
rcases UniformSpace.mem_nhds_iff.1 (IsOpen.mem_nhds hVo hxV) with ⟨U, hU, hUV⟩ rcases comp_symm_of_uniformity hU with ⟨U', hU', _, hUU'⟩ rcases h_basis.toHasBasis.mem_iff.1 hU' with ⟨k, -, hk⟩ rcases hsd.inter_open_nonempty (ball x <| t k) (isOpen_ball x (hto k)) ⟨x, UniformSpace.mem_ball_self _ (ht_mem k)⟩ with ⟨y, hxy, hys⟩ refine ⟨_, ⟨y, hys, k, rfl⟩, (hts k).subset hxy, fun z hz => ?_⟩ exact hUV (ball_subset_of_comp_subset (hk hxy) hUU' (hk hz)) end UniformSpace
Mathlib/Topology/UniformSpace/Cauchy.lean
808
829
/- Copyright (c) 2018 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis -/ import Mathlib.Algebra.Polynomial.Identities import Mathlib.Analysis.SpecificLimits.Basic import Mathlib.NumberTheory.Padics.PadicIntegers import Mathlib.Topology.Algebra.Polynomial import Mathlib.Topology.MetricSpace.CauSeqFilter /-! # Hensel's lemma on ℤ_p This file proves Hensel's lemma on ℤ_p, roughly following Keith Conrad's writeup: <http://www.math.uconn.edu/~kconrad/blurbs/gradnumthy/hensel.pdf> Hensel's lemma gives a simple condition for the existence of a root of a polynomial. The proof and motivation are described in the paper [R. Y. Lewis, *A formal proof of Hensel's lemma over the p-adic integers*][lewis2019]. ## References * <http://www.math.uconn.edu/~kconrad/blurbs/gradnumthy/hensel.pdf> * [R. Y. Lewis, *A formal proof of Hensel's lemma over the p-adic integers*][lewis2019] * <https://en.wikipedia.org/wiki/Hensel%27s_lemma> ## Tags p-adic, p adic, padic, p-adic integer -/ noncomputable section open Topology -- We begin with some general lemmas that are used below in the computation. theorem padic_polynomial_dist {p : ℕ} [Fact p.Prime] (F : Polynomial ℤ_[p]) (x y : ℤ_[p]) : ‖F.eval x - F.eval y‖ ≤ ‖x - y‖ := let ⟨z, hz⟩ := F.evalSubFactor x y calc ‖F.eval x - F.eval y‖ = ‖z‖ * ‖x - y‖ := by simp [hz] _ ≤ 1 * ‖x - y‖ := by gcongr; apply PadicInt.norm_le_one _ = ‖x - y‖ := by simp open Filter Metric private theorem comp_tendsto_lim {p : ℕ} [Fact p.Prime] {F : Polynomial ℤ_[p]} (ncs : CauSeq ℤ_[p] norm) : Tendsto (fun i => F.eval (ncs i)) atTop (𝓝 (F.eval ncs.lim)) := Filter.Tendsto.comp (@Polynomial.continuousAt _ _ _ _ F _) ncs.tendsto_limit section variable {p : ℕ} [Fact p.Prime] {ncs : CauSeq ℤ_[p] norm} {F : Polynomial ℤ_[p]} {a : ℤ_[p]} (ncs_der_val : ∀ n, ‖F.derivative.eval (ncs n)‖ = ‖F.derivative.eval a‖) private theorem ncs_tendsto_lim : Tendsto (fun i => ‖F.derivative.eval (ncs i)‖) atTop (𝓝 ‖F.derivative.eval ncs.lim‖) := Tendsto.comp (continuous_iff_continuousAt.1 continuous_norm _) (comp_tendsto_lim _) include ncs_der_val private theorem ncs_tendsto_const : Tendsto (fun i => ‖F.derivative.eval (ncs i)‖) atTop (𝓝 ‖F.derivative.eval a‖) := by convert @tendsto_const_nhds ℝ _ ℕ _ _; rw [ncs_der_val] private theorem norm_deriv_eq : ‖F.derivative.eval ncs.lim‖ = ‖F.derivative.eval a‖ := tendsto_nhds_unique ncs_tendsto_lim (ncs_tendsto_const ncs_der_val) end section variable {p : ℕ} [Fact p.Prime] {ncs : CauSeq ℤ_[p] norm} {F : Polynomial ℤ_[p]} (hnorm : Tendsto (fun i => ‖F.eval (ncs i)‖) atTop (𝓝 0)) include hnorm private theorem tendsto_zero_of_norm_tendsto_zero : Tendsto (fun i => F.eval (ncs i)) atTop (𝓝 0) := tendsto_iff_norm_sub_tendsto_zero.2 (by simpa using hnorm) theorem limit_zero_of_norm_tendsto_zero : F.eval ncs.lim = 0 := tendsto_nhds_unique (comp_tendsto_lim _) (tendsto_zero_of_norm_tendsto_zero hnorm) end section Hensel open Nat variable (p : ℕ) [Fact p.Prime] (F : Polynomial ℤ_[p]) (a : ℤ_[p]) /-- `T` is an auxiliary value that is used to control the behavior of the polynomial `F`. -/ private def T_gen : ℝ := ‖F.eval a / ((F.derivative.eval a ^ 2 : ℤ_[p]) : ℚ_[p])‖ local notation "T" => @T_gen p _ F a variable {p F a} private theorem T_def : T = ‖F.eval a‖ / ‖F.derivative.eval a‖ ^ 2 := by simp [T_gen, ← PadicInt.norm_def] private theorem T_nonneg : 0 ≤ T := norm_nonneg _ private theorem T_pow_nonneg (n : ℕ) : 0 ≤ T ^ n := pow_nonneg T_nonneg _ variable (hnorm : ‖F.eval a‖ < ‖F.derivative.eval a‖ ^ 2) include hnorm private theorem deriv_sq_norm_pos : 0 < ‖F.derivative.eval a‖ ^ 2 := lt_of_le_of_lt (norm_nonneg _) hnorm private theorem deriv_sq_norm_ne_zero : ‖F.derivative.eval a‖ ^ 2 ≠ 0 := ne_of_gt (deriv_sq_norm_pos hnorm) private theorem deriv_norm_ne_zero : ‖F.derivative.eval a‖ ≠ 0 := fun h => deriv_sq_norm_ne_zero hnorm (by simp [*, sq]) private theorem deriv_norm_pos : 0 < ‖F.derivative.eval a‖ := lt_of_le_of_ne (norm_nonneg _) (Ne.symm (deriv_norm_ne_zero hnorm)) private theorem deriv_ne_zero : F.derivative.eval a ≠ 0 := mt norm_eq_zero.2 (deriv_norm_ne_zero hnorm) private theorem T_lt_one : T < 1 := by have h := (div_lt_one (deriv_sq_norm_pos hnorm)).2 hnorm rw [T_def]; exact h private theorem T_pow {n : ℕ} (hn : n ≠ 0) : T ^ n < 1 := pow_lt_one₀ T_nonneg (T_lt_one hnorm) hn private theorem T_pow' (n : ℕ) : T ^ 2 ^ n < 1 := T_pow hnorm (pow_ne_zero _ two_ne_zero) /-- We will construct a sequence of elements of ℤ_p satisfying successive values of `ih`. -/ private def ih_gen (n : ℕ) (z : ℤ_[p]) : Prop := ‖F.derivative.eval z‖ = ‖F.derivative.eval a‖ ∧ ‖F.eval z‖ ≤ ‖F.derivative.eval a‖ ^ 2 * T ^ 2 ^ n local notation "ih" => @ih_gen p _ F a private theorem ih_0 : ih 0 a := ⟨rfl, by simp [T_def, mul_div_cancel₀ _ (ne_of_gt (deriv_sq_norm_pos hnorm))]⟩ private theorem calc_norm_le_one {n : ℕ} {z : ℤ_[p]} (hz : ih n z) :
‖(↑(F.eval z) : ℚ_[p]) / ↑(F.derivative.eval z)‖ ≤ 1 := calc
Mathlib/NumberTheory/Padics/Hensel.lean
146
147
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathlib.Data.Ordmap.Invariants /-! # Verification of `Ordnode` This file uses the invariants defined in `Mathlib.Data.Ordmap.Invariants` to construct `Ordset α`, a wrapper around `Ordnode α` which includes the correctness invariant of the type. It exposes parallel operations like `insert` as functions on `Ordset` that do the same thing but bundle the correctness proofs. The advantage is that it is possible to, for example, prove that the result of `find` on `insert` will actually find the element, while `Ordnode` cannot guarantee this if the input tree did not satisfy the type invariants. ## Main definitions * `Ordnode.Valid`: The validity predicate for an `Ordnode` subtree. * `Ordset α`: A well formed set of values of type `α`. ## Implementation notes Because the `Ordnode` file was ported from Haskell, the correctness invariants of some of the functions have not been spelled out, and some theorems like `Ordnode.Valid'.balanceL_aux` show very intricate assumptions on the sizes, which may need to be revised if it turns out some operations violate these assumptions, because there is a decent amount of slop in the actual data structure invariants, so the theorem will go through with multiple choices of assumption. -/ variable {α : Type*} namespace Ordnode section Valid variable [Preorder α] /-- The validity predicate for an `Ordnode` subtree. This asserts that the `size` fields are correct, the tree is balanced, and the elements of the tree are organized according to the ordering. This version of `Valid` also puts all elements in the tree in the interval `(lo, hi)`. -/ structure Valid' (lo : WithBot α) (t : Ordnode α) (hi : WithTop α) : Prop where ord : t.Bounded lo hi sz : t.Sized bal : t.Balanced /-- The validity predicate for an `Ordnode` subtree. This asserts that the `size` fields are correct, the tree is balanced, and the elements of the tree are organized according to the ordering. -/ def Valid (t : Ordnode α) : Prop := Valid' ⊥ t ⊤ theorem Valid'.mono_left {x y : α} (xy : x ≤ y) {t : Ordnode α} {o} (h : Valid' y t o) : Valid' x t o := ⟨h.1.mono_left xy, h.2, h.3⟩ theorem Valid'.mono_right {x y : α} (xy : x ≤ y) {t : Ordnode α} {o} (h : Valid' o t x) : Valid' o t y := ⟨h.1.mono_right xy, h.2, h.3⟩ theorem Valid'.trans_left {t₁ t₂ : Ordnode α} {x : α} {o₁ o₂} (h : Bounded t₁ o₁ x) (H : Valid' x t₂ o₂) : Valid' o₁ t₂ o₂ := ⟨h.trans_left H.1, H.2, H.3⟩ theorem Valid'.trans_right {t₁ t₂ : Ordnode α} {x : α} {o₁ o₂} (H : Valid' o₁ t₁ x) (h : Bounded t₂ x o₂) : Valid' o₁ t₁ o₂ := ⟨H.1.trans_right h, H.2, H.3⟩ theorem Valid'.of_lt {t : Ordnode α} {x : α} {o₁ o₂} (H : Valid' o₁ t o₂) (h₁ : Bounded nil o₁ x) (h₂ : All (· < x) t) : Valid' o₁ t x := ⟨H.1.of_lt h₁ h₂, H.2, H.3⟩ theorem Valid'.of_gt {t : Ordnode α} {x : α} {o₁ o₂} (H : Valid' o₁ t o₂) (h₁ : Bounded nil x o₂) (h₂ : All (· > x) t) : Valid' x t o₂ := ⟨H.1.of_gt h₁ h₂, H.2, H.3⟩ theorem Valid'.valid {t o₁ o₂} (h : @Valid' α _ o₁ t o₂) : Valid t := ⟨h.1.weak, h.2, h.3⟩ theorem valid'_nil {o₁ o₂} (h : Bounded nil o₁ o₂) : Valid' o₁ (@nil α) o₂ := ⟨h, ⟨⟩, ⟨⟩⟩ theorem valid_nil : Valid (@nil α) := valid'_nil ⟨⟩ theorem Valid'.node {s l} {x : α} {r o₁ o₂} (hl : Valid' o₁ l x) (hr : Valid' x r o₂) (H : BalancedSz (size l) (size r)) (hs : s = size l + size r + 1) : Valid' o₁ (@node α s l x r) o₂ := ⟨⟨hl.1, hr.1⟩, ⟨hs, hl.2, hr.2⟩, ⟨H, hl.3, hr.3⟩⟩ theorem Valid'.dual : ∀ {t : Ordnode α} {o₁ o₂}, Valid' o₁ t o₂ → @Valid' αᵒᵈ _ o₂ (dual t) o₁ | .nil, _, _, h => valid'_nil h.1.dual | .node _ l _ r, _, _, ⟨⟨ol, Or⟩, ⟨rfl, sl, sr⟩, ⟨b, bl, br⟩⟩ => let ⟨ol', sl', bl'⟩ := Valid'.dual ⟨ol, sl, bl⟩ let ⟨or', sr', br'⟩ := Valid'.dual ⟨Or, sr, br⟩ ⟨⟨or', ol'⟩, ⟨by simp [size_dual, add_comm], sr', sl'⟩, ⟨by rw [size_dual, size_dual]; exact b.symm, br', bl'⟩⟩ theorem Valid'.dual_iff {t : Ordnode α} {o₁ o₂} : Valid' o₁ t o₂ ↔ @Valid' αᵒᵈ _ o₂ (.dual t) o₁ := ⟨Valid'.dual, fun h => by have := Valid'.dual h; rwa [dual_dual, OrderDual.Preorder.dual_dual] at this⟩ theorem Valid.dual {t : Ordnode α} : Valid t → @Valid αᵒᵈ _ (.dual t) := Valid'.dual theorem Valid.dual_iff {t : Ordnode α} : Valid t ↔ @Valid αᵒᵈ _ (.dual t) := Valid'.dual_iff theorem Valid'.left {s l x r o₁ o₂} (H : Valid' o₁ (@Ordnode.node α s l x r) o₂) : Valid' o₁ l x := ⟨H.1.1, H.2.2.1, H.3.2.1⟩ theorem Valid'.right {s l x r o₁ o₂} (H : Valid' o₁ (@Ordnode.node α s l x r) o₂) : Valid' x r o₂ := ⟨H.1.2, H.2.2.2, H.3.2.2⟩ nonrec theorem Valid.left {s l x r} (H : Valid (@node α s l x r)) : Valid l := H.left.valid nonrec theorem Valid.right {s l x r} (H : Valid (@node α s l x r)) : Valid r := H.right.valid theorem Valid.size_eq {s l x r} (H : Valid (@node α s l x r)) : size (@node α s l x r) = size l + size r + 1 := H.2.1 theorem Valid'.node' {l} {x : α} {r o₁ o₂} (hl : Valid' o₁ l x) (hr : Valid' x r o₂) (H : BalancedSz (size l) (size r)) : Valid' o₁ (@node' α l x r) o₂ := hl.node hr H rfl theorem valid'_singleton {x : α} {o₁ o₂} (h₁ : Bounded nil o₁ x) (h₂ : Bounded nil x o₂) : Valid' o₁ (singleton x : Ordnode α) o₂ := (valid'_nil h₁).node (valid'_nil h₂) (Or.inl zero_le_one) rfl theorem valid_singleton {x : α} : Valid (singleton x : Ordnode α) := valid'_singleton ⟨⟩ ⟨⟩ theorem Valid'.node3L {l} {x : α} {m} {y : α} {r o₁ o₂} (hl : Valid' o₁ l x) (hm : Valid' x m y) (hr : Valid' y r o₂) (H1 : BalancedSz (size l) (size m)) (H2 : BalancedSz (size l + size m + 1) (size r)) : Valid' o₁ (@node3L α l x m y r) o₂ := (hl.node' hm H1).node' hr H2 theorem Valid'.node3R {l} {x : α} {m} {y : α} {r o₁ o₂} (hl : Valid' o₁ l x) (hm : Valid' x m y) (hr : Valid' y r o₂) (H1 : BalancedSz (size l) (size m + size r + 1)) (H2 : BalancedSz (size m) (size r)) : Valid' o₁ (@node3R α l x m y r) o₂ := hl.node' (hm.node' hr H2) H1 theorem Valid'.node4L_lemma₁ {a b c d : ℕ} (lr₂ : 3 * (b + c + 1 + d) ≤ 16 * a + 9) (mr₂ : b + c + 1 ≤ 3 * d) (mm₁ : b ≤ 3 * c) : b < 3 * a + 1 := by omega theorem Valid'.node4L_lemma₂ {b c d : ℕ} (mr₂ : b + c + 1 ≤ 3 * d) : c ≤ 3 * d := by omega theorem Valid'.node4L_lemma₃ {b c d : ℕ} (mr₁ : 2 * d ≤ b + c + 1) (mm₁ : b ≤ 3 * c) : d ≤ 3 * c := by omega theorem Valid'.node4L_lemma₄ {a b c d : ℕ} (lr₁ : 3 * a ≤ b + c + 1 + d) (mr₂ : b + c + 1 ≤ 3 * d) (mm₁ : b ≤ 3 * c) : a + b + 1 ≤ 3 * (c + d + 1) := by omega theorem Valid'.node4L_lemma₅ {a b c d : ℕ} (lr₂ : 3 * (b + c + 1 + d) ≤ 16 * a + 9) (mr₁ : 2 * d ≤ b + c + 1) (mm₂ : c ≤ 3 * b) : c + d + 1 ≤ 3 * (a + b + 1) := by omega theorem Valid'.node4L {l} {x : α} {m} {y : α} {r o₁ o₂} (hl : Valid' o₁ l x) (hm : Valid' x m y) (hr : Valid' (↑y) r o₂) (Hm : 0 < size m) (H : size l = 0 ∧ size m = 1 ∧ size r ≤ 1 ∨ 0 < size l ∧ ratio * size r ≤ size m ∧ delta * size l ≤ size m + size r ∧ 3 * (size m + size r) ≤ 16 * size l + 9 ∧ size m ≤ delta * size r) : Valid' o₁ (@node4L α l x m y r) o₂ := by obtain - | ⟨s, ml, z, mr⟩ := m; · cases Hm suffices BalancedSz (size l) (size ml) ∧ BalancedSz (size mr) (size r) ∧ BalancedSz (size l + size ml + 1) (size mr + size r + 1) from Valid'.node' (hl.node' hm.left this.1) (hm.right.node' hr this.2.1) this.2.2 rcases H with (⟨l0, m1, r0⟩ | ⟨l0, mr₁, lr₁, lr₂, mr₂⟩) · rw [hm.2.size_eq, Nat.succ_inj, add_eq_zero] at m1 rw [l0, m1.1, m1.2]; revert r0; rcases size r with (_ | _ | _) <;> [decide; decide; (intro r0; unfold BalancedSz delta; omega)] · rcases Nat.eq_zero_or_pos (size r) with r0 | r0 · rw [r0] at mr₂; cases not_le_of_lt Hm mr₂ rw [hm.2.size_eq] at lr₁ lr₂ mr₁ mr₂ by_cases mm : size ml + size mr ≤ 1 · have r1 := le_antisymm ((mul_le_mul_left (by decide)).1 (le_trans mr₁ (Nat.succ_le_succ mm) : _ ≤ ratio * 1)) r0 rw [r1, add_assoc] at lr₁ have l1 := le_antisymm ((mul_le_mul_left (by decide)).1 (le_trans lr₁ (add_le_add_right mm 2) : _ ≤ delta * 1)) l0 rw [l1, r1] revert mm; cases size ml <;> cases size mr <;> intro mm · decide · rw [zero_add] at mm; rcases mm with (_ | ⟨⟨⟩⟩) decide · rcases mm with (_ | ⟨⟨⟩⟩); decide · rw [Nat.succ_add] at mm; rcases mm with (_ | ⟨⟨⟩⟩) rcases hm.3.1.resolve_left mm with ⟨mm₁, mm₂⟩ rcases Nat.eq_zero_or_pos (size ml) with ml0 | ml0 · rw [ml0, mul_zero, Nat.le_zero] at mm₂ rw [ml0, mm₂] at mm; cases mm (by decide) have : 2 * size l ≤ size ml + size mr + 1 := by have := Nat.mul_le_mul_left ratio lr₁ rw [mul_left_comm, mul_add] at this have := le_trans this (add_le_add_left mr₁ _) rw [← Nat.succ_mul] at this exact (mul_le_mul_left (by decide)).1 this refine ⟨Or.inr ⟨?_, ?_⟩, Or.inr ⟨?_, ?_⟩, Or.inr ⟨?_, ?_⟩⟩ · refine (mul_le_mul_left (by decide)).1 (le_trans this ?_) rw [two_mul, Nat.succ_le_iff] refine add_lt_add_of_lt_of_le ?_ mm₂ simpa using (mul_lt_mul_right ml0).2 (by decide : 1 < 3) · exact Nat.le_of_lt_succ (Valid'.node4L_lemma₁ lr₂ mr₂ mm₁) · exact Valid'.node4L_lemma₂ mr₂ · exact Valid'.node4L_lemma₃ mr₁ mm₁ · exact Valid'.node4L_lemma₄ lr₁ mr₂ mm₁ · exact Valid'.node4L_lemma₅ lr₂ mr₁ mm₂ theorem Valid'.rotateL_lemma₁ {a b c : ℕ} (H2 : 3 * a ≤ b + c) (hb₂ : c ≤ 3 * b) : a ≤ 3 * b := by omega theorem Valid'.rotateL_lemma₂ {a b c : ℕ} (H3 : 2 * (b + c) ≤ 9 * a + 3) (h : b < 2 * c) : b < 3 * a + 1 := by omega theorem Valid'.rotateL_lemma₃ {a b c : ℕ} (H2 : 3 * a ≤ b + c) (h : b < 2 * c) : a + b < 3 * c := by omega theorem Valid'.rotateL_lemma₄ {a b : ℕ} (H3 : 2 * b ≤ 9 * a + 3) : 3 * b ≤ 16 * a + 9 := by omega theorem Valid'.rotateL {l} {x : α} {r o₁ o₂} (hl : Valid' o₁ l x) (hr : Valid' x r o₂) (H1 : ¬size l + size r ≤ 1) (H2 : delta * size l < size r) (H3 : 2 * size r ≤ 9 * size l + 5 ∨ size r ≤ 3) : Valid' o₁ (@rotateL α l x r) o₂ := by obtain - | ⟨rs, rl, rx, rr⟩ := r; · cases H2 rw [hr.2.size_eq, Nat.lt_succ_iff] at H2 rw [hr.2.size_eq] at H3 replace H3 : 2 * (size rl + size rr) ≤ 9 * size l + 3 ∨ size rl + size rr ≤ 2 := H3.imp (@Nat.le_of_add_le_add_right _ 2 _) Nat.le_of_succ_le_succ have H3_0 : size l = 0 → size rl + size rr ≤ 2 := by intro l0; rw [l0] at H3 exact (or_iff_right_of_imp fun h => (mul_le_mul_left (by decide)).1 (le_trans h (by decide))).1 H3 have H3p : size l > 0 → 2 * (size rl + size rr) ≤ 9 * size l + 3 := fun l0 : 1 ≤ size l => (or_iff_left_of_imp <| by omega).1 H3 have ablem : ∀ {a b : ℕ}, 1 ≤ a → a + b ≤ 2 → b ≤ 1 := by omega have hlp : size l > 0 → ¬size rl + size rr ≤ 1 := fun l0 hb => absurd (le_trans (le_trans (Nat.mul_le_mul_left _ l0) H2) hb) (by decide) rw [Ordnode.rotateL_node]; split_ifs with h · have rr0 : size rr > 0 := (mul_lt_mul_left (by decide)).1 (lt_of_le_of_lt (Nat.zero_le _) h : ratio * 0 < _) suffices BalancedSz (size l) (size rl) ∧ BalancedSz (size l + size rl + 1) (size rr) by exact hl.node3L hr.left hr.right this.1 this.2 rcases Nat.eq_zero_or_pos (size l) with l0 | l0 · rw [l0]; replace H3 := H3_0 l0 have := hr.3.1 rcases Nat.eq_zero_or_pos (size rl) with rl0 | rl0 · rw [rl0] at this ⊢ rw [le_antisymm (balancedSz_zero.1 this.symm) rr0] decide have rr1 : size rr = 1 := le_antisymm (ablem rl0 H3) rr0 rw [add_comm] at H3 rw [rr1, show size rl = 1 from le_antisymm (ablem rr0 H3) rl0] decide replace H3 := H3p l0 rcases hr.3.1.resolve_left (hlp l0) with ⟨_, hb₂⟩ refine ⟨Or.inr ⟨?_, ?_⟩, Or.inr ⟨?_, ?_⟩⟩ · exact Valid'.rotateL_lemma₁ H2 hb₂ · exact Nat.le_of_lt_succ (Valid'.rotateL_lemma₂ H3 h) · exact Valid'.rotateL_lemma₃ H2 h · exact le_trans hb₂ (Nat.mul_le_mul_left _ <| le_trans (Nat.le_add_left _ _) (Nat.le_add_right _ _)) · rcases Nat.eq_zero_or_pos (size rl) with rl0 | rl0 · rw [rl0, not_lt, Nat.le_zero, Nat.mul_eq_zero] at h replace h := h.resolve_left (by decide) rw [rl0, h, Nat.le_zero, Nat.mul_eq_zero] at H2 rw [hr.2.size_eq, rl0, h, H2.resolve_left (by decide)] at H1 cases H1 (by decide) refine hl.node4L hr.left hr.right rl0 ?_ rcases Nat.eq_zero_or_pos (size l) with l0 | l0 · replace H3 := H3_0 l0 rcases Nat.eq_zero_or_pos (size rr) with rr0 | rr0 · have := hr.3.1 rw [rr0] at this exact Or.inl ⟨l0, le_antisymm (balancedSz_zero.1 this) rl0, rr0.symm ▸ zero_le_one⟩ exact Or.inl ⟨l0, le_antisymm (ablem rr0 <| by rwa [add_comm]) rl0, ablem rl0 H3⟩ exact Or.inr ⟨l0, not_lt.1 h, H2, Valid'.rotateL_lemma₄ (H3p l0), (hr.3.1.resolve_left (hlp l0)).1⟩ theorem Valid'.rotateR {l} {x : α} {r o₁ o₂} (hl : Valid' o₁ l x) (hr : Valid' x r o₂) (H1 : ¬size l + size r ≤ 1) (H2 : delta * size r < size l) (H3 : 2 * size l ≤ 9 * size r + 5 ∨ size l ≤ 3) : Valid' o₁ (@rotateR α l x r) o₂ := by refine Valid'.dual_iff.2 ?_ rw [dual_rotateR] refine hr.dual.rotateL hl.dual ?_ ?_ ?_ · rwa [size_dual, size_dual, add_comm] · rwa [size_dual, size_dual] · rwa [size_dual, size_dual] theorem Valid'.balance'_aux {l} {x : α} {r o₁ o₂} (hl : Valid' o₁ l x) (hr : Valid' x r o₂) (H₁ : 2 * @size α r ≤ 9 * size l + 5 ∨ size r ≤ 3) (H₂ : 2 * @size α l ≤ 9 * size r + 5 ∨ size l ≤ 3) : Valid' o₁ (@balance' α l x r) o₂ := by rw [balance']; split_ifs with h h_1 h_2 · exact hl.node' hr (Or.inl h) · exact hl.rotateL hr h h_1 H₁ · exact hl.rotateR hr h h_2 H₂ · exact hl.node' hr (Or.inr ⟨not_lt.1 h_2, not_lt.1 h_1⟩) theorem Valid'.balance'_lemma {α l l' r r'} (H1 : BalancedSz l' r') (H2 : Nat.dist (@size α l) l' ≤ 1 ∧ size r = r' ∨ Nat.dist (size r) r' ≤ 1 ∧ size l = l') : 2 * @size α r ≤ 9 * size l + 5 ∨ size r ≤ 3 := by suffices @size α r ≤ 3 * (size l + 1) by omega rcases H2 with (⟨hl, rfl⟩ | ⟨hr, rfl⟩) <;> rcases H1 with (h | ⟨_, h₂⟩) · exact le_trans (Nat.le_add_left _ _) (le_trans h (Nat.le_add_left _ _)) · exact le_trans h₂ (Nat.mul_le_mul_left _ <| le_trans (Nat.dist_tri_right _ _) (Nat.add_le_add_left hl _)) · exact le_trans (Nat.dist_tri_left' _ _) (le_trans (add_le_add hr (le_trans (Nat.le_add_left _ _) h)) (by omega)) · rw [Nat.mul_succ] exact le_trans (Nat.dist_tri_right' _ _) (add_le_add h₂ (le_trans hr (by decide))) theorem Valid'.balance' {l} {x : α} {r o₁ o₂} (hl : Valid' o₁ l x) (hr : Valid' x r o₂) (H : ∃ l' r', BalancedSz l' r' ∧ (Nat.dist (size l) l' ≤ 1 ∧ size r = r' ∨ Nat.dist (size r) r' ≤ 1 ∧ size l = l')) : Valid' o₁ (@balance' α l x r) o₂ := let ⟨_, _, H1, H2⟩ := H Valid'.balance'_aux hl hr (Valid'.balance'_lemma H1 H2) (Valid'.balance'_lemma H1.symm H2.symm) theorem Valid'.balance {l} {x : α} {r o₁ o₂} (hl : Valid' o₁ l x) (hr : Valid' x r o₂) (H : ∃ l' r', BalancedSz l' r' ∧ (Nat.dist (size l) l' ≤ 1 ∧ size r = r' ∨ Nat.dist (size r) r' ≤ 1 ∧ size l = l')) : Valid' o₁ (@balance α l x r) o₂ := by rw [balance_eq_balance' hl.3 hr.3 hl.2 hr.2]; exact hl.balance' hr H theorem Valid'.balanceL_aux {l} {x : α} {r o₁ o₂} (hl : Valid' o₁ l x) (hr : Valid' x r o₂) (H₁ : size l = 0 → size r ≤ 1) (H₂ : 1 ≤ size l → 1 ≤ size r → size r ≤ delta * size l) (H₃ : 2 * @size α l ≤ 9 * size r + 5 ∨ size l ≤ 3) : Valid' o₁ (@balanceL α l x r) o₂ := by rw [balanceL_eq_balance hl.2 hr.2 H₁ H₂, balance_eq_balance' hl.3 hr.3 hl.2 hr.2] refine hl.balance'_aux hr (Or.inl ?_) H₃ rcases Nat.eq_zero_or_pos (size r) with r0 | r0 · rw [r0]; exact Nat.zero_le _ rcases Nat.eq_zero_or_pos (size l) with l0 | l0 · rw [l0]; exact le_trans (Nat.mul_le_mul_left _ (H₁ l0)) (by decide) replace H₂ : _ ≤ 3 * _ := H₂ l0 r0; omega theorem Valid'.balanceL {l} {x : α} {r o₁ o₂} (hl : Valid' o₁ l x) (hr : Valid' x r o₂) (H : (∃ l', Raised l' (size l) ∧ BalancedSz l' (size r)) ∨ ∃ r', Raised (size r) r' ∧ BalancedSz (size l) r') : Valid' o₁ (@balanceL α l x r) o₂ := by rw [balanceL_eq_balance' hl.3 hr.3 hl.2 hr.2 H] refine hl.balance' hr ?_ rcases H with (⟨l', e, H⟩ | ⟨r', e, H⟩) · exact ⟨_, _, H, Or.inl ⟨e.dist_le', rfl⟩⟩ · exact ⟨_, _, H, Or.inr ⟨e.dist_le, rfl⟩⟩ theorem Valid'.balanceR_aux {l} {x : α} {r o₁ o₂} (hl : Valid' o₁ l x) (hr : Valid' x r o₂) (H₁ : size r = 0 → size l ≤ 1) (H₂ : 1 ≤ size r → 1 ≤ size l → size l ≤ delta * size r) (H₃ : 2 * @size α r ≤ 9 * size l + 5 ∨ size r ≤ 3) : Valid' o₁ (@balanceR α l x r) o₂ := by rw [Valid'.dual_iff, dual_balanceR] have := hr.dual.balanceL_aux hl.dual rw [size_dual, size_dual] at this exact this H₁ H₂ H₃ theorem Valid'.balanceR {l} {x : α} {r o₁ o₂} (hl : Valid' o₁ l x) (hr : Valid' x r o₂) (H : (∃ l', Raised (size l) l' ∧ BalancedSz l' (size r)) ∨ ∃ r', Raised r' (size r) ∧ BalancedSz (size l) r') : Valid' o₁ (@balanceR α l x r) o₂ := by rw [Valid'.dual_iff, dual_balanceR]; exact hr.dual.balanceL hl.dual (balance_sz_dual H) theorem Valid'.eraseMax_aux {s l x r o₁ o₂} (H : Valid' o₁ (.node s l x r) o₂) : Valid' o₁ (@eraseMax α (.node' l x r)) ↑(findMax' x r) ∧ size (.node' l x r) = size (eraseMax (.node' l x r)) + 1 := by have := H.2.eq_node'; rw [this] at H; clear this induction r generalizing l x o₁ with | nil => exact ⟨H.left, rfl⟩ | node rs rl rx rr _ IHrr => have := H.2.2.2.eq_node'; rw [this] at H ⊢ rcases IHrr H.right with ⟨h, e⟩ refine ⟨Valid'.balanceL H.left h (Or.inr ⟨_, Or.inr e, H.3.1⟩), ?_⟩ rw [eraseMax, size_balanceL H.3.2.1 h.3 H.2.2.1 h.2 (Or.inr ⟨_, Or.inr e, H.3.1⟩)] rw [size_node, e]; rfl theorem Valid'.eraseMin_aux {s l} {x : α} {r o₁ o₂} (H : Valid' o₁ (.node s l x r) o₂) : Valid' ↑(findMin' l x) (@eraseMin α (.node' l x r)) o₂ ∧ size (.node' l x r) = size (eraseMin (.node' l x r)) + 1 := by have := H.dual.eraseMax_aux rwa [← dual_node', size_dual, ← dual_eraseMin, size_dual, ← Valid'.dual_iff, findMax'_dual] at this theorem eraseMin.valid : ∀ {t}, @Valid α _ t → Valid (eraseMin t) | nil, _ => valid_nil | node _ l x r, h => by rw [h.2.eq_node']; exact h.eraseMin_aux.1.valid theorem eraseMax.valid {t} (h : @Valid α _ t) : Valid (eraseMax t) := by rw [Valid.dual_iff, dual_eraseMax]; exact eraseMin.valid h.dual theorem Valid'.glue_aux {l r o₁ o₂} (hl : Valid' o₁ l o₂) (hr : Valid' o₁ r o₂) (sep : l.All fun x => r.All fun y => x < y) (bal : BalancedSz (size l) (size r)) : Valid' o₁ (@glue α l r) o₂ ∧ size (glue l r) = size l + size r := by obtain - | ⟨ls, ll, lx, lr⟩ := l; · exact ⟨hr, (zero_add _).symm⟩ obtain - | ⟨rs, rl, rx, rr⟩ := r; · exact ⟨hl, rfl⟩ dsimp [glue]; split_ifs · rw [splitMax_eq] · obtain ⟨v, e⟩ := Valid'.eraseMax_aux hl suffices H : _ by refine ⟨Valid'.balanceR v (hr.of_gt ?_ ?_) H, ?_⟩ · refine findMax'_all (P := fun a : α => Bounded nil (a : WithTop α) o₂) lx lr hl.1.2.to_nil (sep.2.2.imp ?_) exact fun x h => hr.1.2.to_nil.mono_left (le_of_lt h.2.1) · exact @findMax'_all _ (fun a => All (· > a) (.node rs rl rx rr)) lx lr sep.2.1 sep.2.2 · rw [size_balanceR v.3 hr.3 v.2 hr.2 H, add_right_comm, ← e, hl.2.1]; rfl refine Or.inl ⟨_, Or.inr e, ?_⟩ rwa [hl.2.eq_node'] at bal · rw [splitMin_eq] · obtain ⟨v, e⟩ := Valid'.eraseMin_aux hr suffices H : _ by refine ⟨Valid'.balanceL (hl.of_lt ?_ ?_) v H, ?_⟩ · refine @findMin'_all (P := fun a : α => Bounded nil o₁ (a : WithBot α)) _ rl rx (sep.2.1.1.imp ?_) hr.1.1.to_nil exact fun y h => hl.1.1.to_nil.mono_right (le_of_lt h) · exact @findMin'_all _ (fun a => All (· < a) (.node ls ll lx lr)) rl rx (all_iff_forall.2 fun x hx => sep.imp fun y hy => all_iff_forall.1 hy.1 _ hx) (sep.imp fun y hy => hy.2.1) · rw [size_balanceL hl.3 v.3 hl.2 v.2 H, add_assoc, ← e, hr.2.1]; rfl refine Or.inr ⟨_, Or.inr e, ?_⟩ rwa [hr.2.eq_node'] at bal theorem Valid'.glue {l} {x : α} {r o₁ o₂} (hl : Valid' o₁ l x) (hr : Valid' x r o₂) : BalancedSz (size l) (size r) → Valid' o₁ (@glue α l r) o₂ ∧ size (@glue α l r) = size l + size r := Valid'.glue_aux (hl.trans_right hr.1) (hr.trans_left hl.1) (hl.1.to_sep hr.1) theorem Valid'.merge_lemma {a b c : ℕ} (h₁ : 3 * a < b + c + 1) (h₂ : b ≤ 3 * c) : 2 * (a + b) ≤ 9 * c + 5 := by omega theorem Valid'.merge_aux₁ {o₁ o₂ ls ll lx lr rs rl rx rr t} (hl : Valid' o₁ (@Ordnode.node α ls ll lx lr) o₂) (hr : Valid' o₁ (.node rs rl rx rr) o₂) (h : delta * ls < rs) (v : Valid' o₁ t rx) (e : size t = ls + size rl) : Valid' o₁ (.balanceL t rx rr) o₂ ∧ size (.balanceL t rx rr) = ls + rs := by rw [hl.2.1] at e rw [hl.2.1, hr.2.1, delta] at h rcases hr.3.1 with (H | ⟨hr₁, hr₂⟩); · omega suffices H₂ : _ by suffices H₁ : _ by refine ⟨Valid'.balanceL_aux v hr.right H₁ H₂ ?_, ?_⟩ · rw [e]; exact Or.inl (Valid'.merge_lemma h hr₁) · rw [balanceL_eq_balance v.2 hr.2.2.2 H₁ H₂, balance_eq_balance' v.3 hr.3.2.2 v.2 hr.2.2.2, size_balance' v.2 hr.2.2.2, e, hl.2.1, hr.2.1] abel · rw [e, add_right_comm]; rintro ⟨⟩ intro _ _; rw [e]; unfold delta at hr₂ ⊢; omega theorem Valid'.merge_aux {l r o₁ o₂} (hl : Valid' o₁ l o₂) (hr : Valid' o₁ r o₂) (sep : l.All fun x => r.All fun y => x < y) : Valid' o₁ (@merge α l r) o₂ ∧ size (merge l r) = size l + size r := by induction l generalizing o₁ o₂ r with | nil => exact ⟨hr, (zero_add _).symm⟩ | node ls ll lx lr _ IHlr => ?_ induction r generalizing o₁ o₂ with | nil => exact ⟨hl, rfl⟩ | node rs rl rx rr IHrl _ => ?_ rw [merge_node]; split_ifs with h h_1 · obtain ⟨v, e⟩ := IHrl (hl.of_lt hr.1.1.to_nil <| sep.imp fun x h => h.2.1) hr.left (sep.imp fun x h => h.1) exact Valid'.merge_aux₁ hl hr h v e · obtain ⟨v, e⟩ := IHlr hl.right (hr.of_gt hl.1.2.to_nil sep.2.1) sep.2.2 have := Valid'.merge_aux₁ hr.dual hl.dual h_1 v.dual rw [size_dual, add_comm, size_dual, ← dual_balanceR, ← Valid'.dual_iff, size_dual, add_comm rs] at this exact this e · refine Valid'.glue_aux hl hr sep (Or.inr ⟨not_lt.1 h_1, not_lt.1 h⟩) theorem Valid.merge {l r} (hl : Valid l) (hr : Valid r) (sep : l.All fun x => r.All fun y => x < y) : Valid (@merge α l r) := (Valid'.merge_aux hl hr sep).1 theorem insertWith.valid_aux [IsTotal α (· ≤ ·)] [DecidableLE α] (f : α → α) (x : α) (hf : ∀ y, x ≤ y ∧ y ≤ x → x ≤ f y ∧ f y ≤ x) : ∀ {t o₁ o₂}, Valid' o₁ t o₂ → Bounded nil o₁ x → Bounded nil x o₂ → Valid' o₁ (insertWith f x t) o₂ ∧ Raised (size t) (size (insertWith f x t)) | nil, _, _, _, bl, br => ⟨valid'_singleton bl br, Or.inr rfl⟩ | node sz l y r, o₁, o₂, h, bl, br => by rw [insertWith, cmpLE] split_ifs with h_1 h_2 <;> dsimp only · rcases h with ⟨⟨lx, xr⟩, hs, hb⟩ rcases hf _ ⟨h_1, h_2⟩ with ⟨xf, fx⟩ refine ⟨⟨⟨lx.mono_right (le_trans h_2 xf), xr.mono_left (le_trans fx h_1)⟩, hs, hb⟩, Or.inl rfl⟩ · rcases insertWith.valid_aux f x hf h.left bl (lt_of_le_not_le h_1 h_2) with ⟨vl, e⟩ suffices H : _ by refine ⟨vl.balanceL h.right H, ?_⟩ rw [size_balanceL vl.3 h.3.2.2 vl.2 h.2.2.2 H, h.2.size_eq] exact (e.add_right _).add_right _ exact Or.inl ⟨_, e, h.3.1⟩ · have : y < x := lt_of_le_not_le ((total_of (· ≤ ·) _ _).resolve_left h_1) h_1 rcases insertWith.valid_aux f x hf h.right this br with ⟨vr, e⟩ suffices H : _ by refine ⟨h.left.balanceR vr H, ?_⟩ rw [size_balanceR h.3.2.1 vr.3 h.2.2.1 vr.2 H, h.2.size_eq] exact (e.add_left _).add_right _ exact Or.inr ⟨_, e, h.3.1⟩ theorem insertWith.valid [IsTotal α (· ≤ ·)] [DecidableLE α] (f : α → α) (x : α) (hf : ∀ y, x ≤ y ∧ y ≤ x → x ≤ f y ∧ f y ≤ x) {t} (h : Valid t) : Valid (insertWith f x t) := (insertWith.valid_aux _ _ hf h ⟨⟩ ⟨⟩).1 theorem insert_eq_insertWith [DecidableLE α] (x : α) : ∀ t, Ordnode.insert x t = insertWith (fun _ => x) x t | nil => rfl | node _ l y r => by unfold Ordnode.insert insertWith; cases cmpLE x y <;> simp [insert_eq_insertWith] theorem insert.valid [IsTotal α (· ≤ ·)] [DecidableLE α] (x : α) {t} (h : Valid t) : Valid (Ordnode.insert x t) := by rw [insert_eq_insertWith]; exact insertWith.valid _ _ (fun _ _ => ⟨le_rfl, le_rfl⟩) h theorem insert'_eq_insertWith [DecidableLE α] (x : α) : ∀ t, insert' x t = insertWith id x t | nil => rfl | node _ l y r => by unfold insert' insertWith; cases cmpLE x y <;> simp [insert'_eq_insertWith] theorem insert'.valid [IsTotal α (· ≤ ·)] [DecidableLE α] (x : α) {t} (h : Valid t) : Valid (insert' x t) := by rw [insert'_eq_insertWith]; exact insertWith.valid _ _ (fun _ => id) h theorem Valid'.map_aux {β} [Preorder β] {f : α → β} (f_strict_mono : StrictMono f) {t a₁ a₂} (h : Valid' a₁ t a₂) : Valid' (Option.map f a₁) (map f t) (Option.map f a₂) ∧ (map f t).size = t.size := by induction t generalizing a₁ a₂ with | nil => simp only [map, size_nil, and_true]; apply valid'_nil cases a₁; · trivial cases a₂; · trivial simp only [Option.map, Bounded] exact f_strict_mono h.ord | node _ _ _ _ t_ih_l t_ih_r => have t_ih_l' := t_ih_l h.left have t_ih_r' := t_ih_r h.right clear t_ih_l t_ih_r obtain ⟨t_l_valid, t_l_size⟩ := t_ih_l' obtain ⟨t_r_valid, t_r_size⟩ := t_ih_r' simp only [map, size_node, and_true] constructor · exact And.intro t_l_valid.ord t_r_valid.ord · constructor · rw [t_l_size, t_r_size]; exact h.sz.1 · constructor · exact t_l_valid.sz · exact t_r_valid.sz · constructor · rw [t_l_size, t_r_size]; exact h.bal.1 · constructor · exact t_l_valid.bal · exact t_r_valid.bal theorem map.valid {β} [Preorder β] {f : α → β} (f_strict_mono : StrictMono f) {t} (h : Valid t) : Valid (map f t) := (Valid'.map_aux f_strict_mono h).1 theorem Valid'.erase_aux [DecidableLE α] (x : α) {t a₁ a₂} (h : Valid' a₁ t a₂) : Valid' a₁ (erase x t) a₂ ∧ Raised (erase x t).size t.size := by induction t generalizing a₁ a₂ with | nil => simpa [erase, Raised] | node _ t_l t_x t_r t_ih_l t_ih_r => simp only [erase, size_node] have t_ih_l' := t_ih_l h.left have t_ih_r' := t_ih_r h.right clear t_ih_l t_ih_r obtain ⟨t_l_valid, t_l_size⟩ := t_ih_l' obtain ⟨t_r_valid, t_r_size⟩ := t_ih_r' cases cmpLE x t_x <;> rw [h.sz.1] · suffices h_balanceable : _ by constructor · exact Valid'.balanceR t_l_valid h.right h_balanceable · rw [size_balanceR t_l_valid.bal h.right.bal t_l_valid.sz h.right.sz h_balanceable] repeat apply Raised.add_right exact t_l_size left; exists t_l.size; exact And.intro t_l_size h.bal.1 · have h_glue := Valid'.glue h.left h.right h.bal.1 obtain ⟨h_glue_valid, h_glue_sized⟩ := h_glue constructor · exact h_glue_valid · right; rw [h_glue_sized] · suffices h_balanceable : _ by constructor · exact Valid'.balanceL h.left t_r_valid h_balanceable · rw [size_balanceL h.left.bal t_r_valid.bal h.left.sz t_r_valid.sz h_balanceable] apply Raised.add_right apply Raised.add_left exact t_r_size right; exists t_r.size; exact And.intro t_r_size h.bal.1 theorem erase.valid [DecidableLE α] (x : α) {t} (h : Valid t) : Valid (erase x t) := (Valid'.erase_aux x h).1 theorem size_erase_of_mem [DecidableLE α] {x : α} {t a₁ a₂} (h : Valid' a₁ t a₂) (h_mem : x ∈ t) : size (erase x t) = size t - 1 := by induction t generalizing a₁ a₂ with | nil => contradiction | node _ t_l t_x t_r t_ih_l t_ih_r => have t_ih_l' := t_ih_l h.left have t_ih_r' := t_ih_r h.right clear t_ih_l t_ih_r dsimp only [Membership.mem, mem] at h_mem unfold erase revert h_mem; cases cmpLE x t_x <;> intro h_mem <;> dsimp only at h_mem ⊢ · have t_ih_l := t_ih_l' h_mem clear t_ih_l' t_ih_r' have t_l_h := Valid'.erase_aux x h.left obtain ⟨t_l_valid, t_l_size⟩ := t_l_h rw [size_balanceR t_l_valid.bal h.right.bal t_l_valid.sz h.right.sz (Or.inl (Exists.intro t_l.size (And.intro t_l_size h.bal.1)))] rw [t_ih_l, h.sz.1] have h_pos_t_l_size := pos_size_of_mem h.left.sz h_mem revert h_pos_t_l_size; rcases t_l.size with - | t_l_size <;> intro h_pos_t_l_size · cases h_pos_t_l_size · simp [Nat.add_right_comm] · rw [(Valid'.glue h.left h.right h.bal.1).2, h.sz.1]; rfl · have t_ih_r := t_ih_r' h_mem clear t_ih_l' t_ih_r' have t_r_h := Valid'.erase_aux x h.right obtain ⟨t_r_valid, t_r_size⟩ := t_r_h rw [size_balanceL h.left.bal t_r_valid.bal h.left.sz t_r_valid.sz (Or.inr (Exists.intro t_r.size (And.intro t_r_size h.bal.1)))] rw [t_ih_r, h.sz.1] have h_pos_t_r_size := pos_size_of_mem h.right.sz h_mem revert h_pos_t_r_size; rcases t_r.size with - | t_r_size <;> intro h_pos_t_r_size · cases h_pos_t_r_size · simp [Nat.add_assoc] end Valid end Ordnode /-- An `Ordset α` is a finite set of values, represented as a tree. The operations on this type maintain that the tree is balanced and correctly stores subtree sizes at each level. The correctness property of the tree is baked into the type, so all operations on this type are correct by construction. -/ def Ordset (α : Type*) [Preorder α] := { t : Ordnode α // t.Valid } namespace Ordset open Ordnode variable [Preorder α] /-- O(1). The empty set. -/ nonrec def nil : Ordset α := ⟨nil, ⟨⟩, ⟨⟩, ⟨⟩⟩ /-- O(1). Get the size of the set. -/ def size (s : Ordset α) : ℕ := s.1.size /-- O(1). Construct a singleton set containing value `a`. -/ protected def singleton (a : α) : Ordset α := ⟨singleton a, valid_singleton⟩ instance instEmptyCollection : EmptyCollection (Ordset α) := ⟨nil⟩ instance instInhabited : Inhabited (Ordset α) := ⟨nil⟩ instance instSingleton : Singleton α (Ordset α) := ⟨Ordset.singleton⟩ /-- O(1). Is the set empty? -/ def Empty (s : Ordset α) : Prop := s = ∅ theorem empty_iff {s : Ordset α} : s = ∅ ↔ s.1.empty := ⟨fun h => by cases h; exact rfl, fun h => by cases s with | mk s_val _ => cases s_val <;> [rfl; cases h]⟩ instance Empty.instDecidablePred : DecidablePred (@Empty α _) := fun _ => decidable_of_iff' _ empty_iff /-- O(log n). Insert an element into the set, preserving balance and the BST property. If an equivalent element is already in the set, this replaces it. -/ protected def insert [IsTotal α (· ≤ ·)] [DecidableLE α] (x : α) (s : Ordset α) : Ordset α := ⟨Ordnode.insert x s.1, insert.valid _ s.2⟩ instance instInsert [IsTotal α (· ≤ ·)] [DecidableLE α] : Insert α (Ordset α) := ⟨Ordset.insert⟩ /-- O(log n). Insert an element into the set, preserving balance and the BST property. If an equivalent element is already in the set, the set is returned as is. -/ nonrec def insert' [IsTotal α (· ≤ ·)] [DecidableLE α] (x : α) (s : Ordset α) : Ordset α := ⟨insert' x s.1, insert'.valid _ s.2⟩ section variable [DecidableLE α] /-- O(log n). Does the set contain the element `x`? That is, is there an element that is equivalent to `x` in the order? -/ def mem (x : α) (s : Ordset α) : Bool := x ∈ s.val /-- O(log n). Retrieve an element in the set that is equivalent to `x` in the order, if it exists. -/ def find (x : α) (s : Ordset α) : Option α := Ordnode.find x s.val instance instMembership : Membership α (Ordset α) := ⟨fun s x => mem x s⟩ instance mem.decidable (x : α) (s : Ordset α) : Decidable (x ∈ s) := instDecidableEqBool _ _ theorem pos_size_of_mem {x : α} {t : Ordset α} (h_mem : x ∈ t) : 0 < size t := by simp? [Membership.mem, mem] at h_mem says simp only [Membership.mem, mem, Bool.decide_eq_true] at h_mem apply Ordnode.pos_size_of_mem t.property.sz h_mem end /-- O(log n). Remove an element from the set equivalent to `x`. Does nothing if there is no such element. -/ def erase [DecidableLE α] (x : α) (s : Ordset α) : Ordset α := ⟨Ordnode.erase x s.val, Ordnode.erase.valid x s.property⟩ /-- O(n). Map a function across a tree, without changing the structure. -/ def map {β} [Preorder β] (f : α → β) (f_strict_mono : StrictMono f) (s : Ordset α) : Ordset β := ⟨Ordnode.map f s.val, Ordnode.map.valid f_strict_mono s.property⟩ end Ordset
Mathlib/Data/Ordmap/Ordset.lean
797
798
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Simon Hudon, Mario Carneiro -/ import Aesop import Mathlib.Algebra.Group.Defs import Mathlib.Data.Nat.Init import Mathlib.Data.Int.Init import Mathlib.Logic.Function.Iterate import Mathlib.Tactic.SimpRw import Mathlib.Tactic.SplitIfs /-! # Basic lemmas about semigroups, monoids, and groups This file lists various basic lemmas about semigroups, monoids, and groups. Most proofs are one-liners from the corresponding axioms. For the definitions of semigroups, monoids and groups, see `Algebra/Group/Defs.lean`. -/ assert_not_exists MonoidWithZero DenselyOrdered open Function variable {α β G M : Type*} section ite variable [Pow α β] @[to_additive (attr := simp) dite_smul] lemma pow_dite (p : Prop) [Decidable p] (a : α) (b : p → β) (c : ¬ p → β) : a ^ (if h : p then b h else c h) = if h : p then a ^ b h else a ^ c h := by split_ifs <;> rfl @[to_additive (attr := simp) smul_dite] lemma dite_pow (p : Prop) [Decidable p] (a : p → α) (b : ¬ p → α) (c : β) : (if h : p then a h else b h) ^ c = if h : p then a h ^ c else b h ^ c := by split_ifs <;> rfl @[to_additive (attr := simp) ite_smul] lemma pow_ite (p : Prop) [Decidable p] (a : α) (b c : β) : a ^ (if p then b else c) = if p then a ^ b else a ^ c := pow_dite _ _ _ _ @[to_additive (attr := simp) smul_ite] lemma ite_pow (p : Prop) [Decidable p] (a b : α) (c : β) : (if p then a else b) ^ c = if p then a ^ c else b ^ c := dite_pow _ _ _ _ set_option linter.existingAttributeWarning false in attribute [to_additive (attr := simp)] dite_smul smul_dite ite_smul smul_ite end ite section Semigroup variable [Semigroup α] @[to_additive] instance Semigroup.to_isAssociative : Std.Associative (α := α) (· * ·) := ⟨mul_assoc⟩ /-- Composing two multiplications on the left by `y` then `x` is equal to a multiplication on the left by `x * y`. -/ @[to_additive (attr := simp) "Composing two additions on the left by `y` then `x` is equal to an addition on the left by `x + y`."] theorem comp_mul_left (x y : α) : (x * ·) ∘ (y * ·) = (x * y * ·) := by ext z simp [mul_assoc] /-- Composing two multiplications on the right by `y` and `x` is equal to a multiplication on the right by `y * x`. -/ @[to_additive (attr := simp) "Composing two additions on the right by `y` and `x` is equal to an addition on the right by `y + x`."] theorem comp_mul_right (x y : α) : (· * x) ∘ (· * y) = (· * (y * x)) := by ext z simp [mul_assoc] end Semigroup @[to_additive] instance CommMagma.to_isCommutative [CommMagma G] : Std.Commutative (α := G) (· * ·) := ⟨mul_comm⟩ section MulOneClass variable [MulOneClass M] @[to_additive] theorem ite_mul_one {P : Prop} [Decidable P] {a b : M} : ite P (a * b) 1 = ite P a 1 * ite P b 1 := by by_cases h : P <;> simp [h] @[to_additive] theorem ite_one_mul {P : Prop} [Decidable P] {a b : M} : ite P 1 (a * b) = ite P 1 a * ite P 1 b := by by_cases h : P <;> simp [h] @[to_additive] theorem eq_one_iff_eq_one_of_mul_eq_one {a b : M} (h : a * b = 1) : a = 1 ↔ b = 1 := by constructor <;> (rintro rfl; simpa using h) @[to_additive] theorem one_mul_eq_id : ((1 : M) * ·) = id := funext one_mul @[to_additive] theorem mul_one_eq_id : (· * (1 : M)) = id := funext mul_one end MulOneClass section CommSemigroup variable [CommSemigroup G] @[to_additive] theorem mul_left_comm (a b c : G) : a * (b * c) = b * (a * c) := by rw [← mul_assoc, mul_comm a, mul_assoc] @[to_additive] theorem mul_right_comm (a b c : G) : a * b * c = a * c * b := by rw [mul_assoc, mul_comm b, mul_assoc] @[to_additive] theorem mul_mul_mul_comm (a b c d : G) : a * b * (c * d) = a * c * (b * d) := by simp only [mul_left_comm, mul_assoc] @[to_additive] theorem mul_rotate (a b c : G) : a * b * c = b * c * a := by simp only [mul_left_comm, mul_comm] @[to_additive] theorem mul_rotate' (a b c : G) : a * (b * c) = b * (c * a) := by simp only [mul_left_comm, mul_comm] end CommSemigroup attribute [local simp] mul_assoc sub_eq_add_neg section Monoid variable [Monoid M] {a b : M} {m n : ℕ} @[to_additive boole_nsmul] lemma pow_boole (P : Prop) [Decidable P] (a : M) : (a ^ if P then 1 else 0) = if P then a else 1 := by simp only [pow_ite, pow_one, pow_zero] @[to_additive nsmul_add_sub_nsmul] lemma pow_mul_pow_sub (a : M) (h : m ≤ n) : a ^ m * a ^ (n - m) = a ^ n := by rw [← pow_add, Nat.add_comm, Nat.sub_add_cancel h] @[to_additive sub_nsmul_nsmul_add] lemma pow_sub_mul_pow (a : M) (h : m ≤ n) : a ^ (n - m) * a ^ m = a ^ n := by rw [← pow_add, Nat.sub_add_cancel h] @[to_additive sub_one_nsmul_add] lemma mul_pow_sub_one (hn : n ≠ 0) (a : M) : a * a ^ (n - 1) = a ^ n := by rw [← pow_succ', Nat.sub_add_cancel <| Nat.one_le_iff_ne_zero.2 hn] @[to_additive add_sub_one_nsmul] lemma pow_sub_one_mul (hn : n ≠ 0) (a : M) : a ^ (n - 1) * a = a ^ n := by rw [← pow_succ, Nat.sub_add_cancel <| Nat.one_le_iff_ne_zero.2 hn] /-- If `x ^ n = 1`, then `x ^ m` is the same as `x ^ (m % n)` -/ @[to_additive nsmul_eq_mod_nsmul "If `n • x = 0`, then `m • x` is the same as `(m % n) • x`"] lemma pow_eq_pow_mod (m : ℕ) (ha : a ^ n = 1) : a ^ m = a ^ (m % n) := by calc a ^ m = a ^ (m % n + n * (m / n)) := by rw [Nat.mod_add_div] _ = a ^ (m % n) := by simp [pow_add, pow_mul, ha] @[to_additive] lemma pow_mul_pow_eq_one : ∀ n, a * b = 1 → a ^ n * b ^ n = 1 | 0, _ => by simp | n + 1, h => calc a ^ n.succ * b ^ n.succ = a ^ n * a * (b * b ^ n) := by rw [pow_succ, pow_succ'] _ = a ^ n * (a * b) * b ^ n := by simp only [mul_assoc] _ = 1 := by simp [h, pow_mul_pow_eq_one] @[to_additive (attr := simp)] lemma mul_left_iterate (a : M) : ∀ n : ℕ, (a * ·)^[n] = (a ^ n * ·) | 0 => by ext; simp | n + 1 => by ext; simp [pow_succ, mul_left_iterate] @[to_additive (attr := simp)] lemma mul_right_iterate (a : M) : ∀ n : ℕ, (· * a)^[n] = (· * a ^ n) | 0 => by ext; simp | n + 1 => by ext; simp [pow_succ', mul_right_iterate] @[to_additive] lemma mul_left_iterate_apply_one (a : M) : (a * ·)^[n] 1 = a ^ n := by simp [mul_right_iterate] @[to_additive] lemma mul_right_iterate_apply_one (a : M) : (· * a)^[n] 1 = a ^ n := by simp [mul_right_iterate] @[to_additive (attr := simp)] lemma pow_iterate (k : ℕ) : ∀ n : ℕ, (fun x : M ↦ x ^ k)^[n] = (· ^ k ^ n) | 0 => by ext; simp | n + 1 => by ext; simp [pow_iterate, Nat.pow_succ', pow_mul] end Monoid section CommMonoid variable [CommMonoid M] {x y z : M} @[to_additive] theorem inv_unique (hy : x * y = 1) (hz : x * z = 1) : y = z := left_inv_eq_right_inv (Trans.trans (mul_comm _ _) hy) hz @[to_additive nsmul_add] lemma mul_pow (a b : M) : ∀ n, (a * b) ^ n = a ^ n * b ^ n | 0 => by rw [pow_zero, pow_zero, pow_zero, one_mul] | n + 1 => by rw [pow_succ', pow_succ', pow_succ', mul_pow, mul_mul_mul_comm]
end CommMonoid
Mathlib/Algebra/Group/Basic.lean
208
209
/- Copyright (c) 2020 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Floris van Doorn, Yury Kudryashov -/ import Mathlib.Topology.Instances.NNReal.Lemmas import Mathlib.Topology.Order.MonotoneContinuity /-! # Square root of a real number In this file we define * `NNReal.sqrt` to be the square root of a nonnegative real number. * `Real.sqrt` to be the square root of a real number, defined to be zero on negative numbers. Then we prove some basic properties of these functions. ## Implementation notes We define `NNReal.sqrt` as the noncomputable inverse to the function `x ↦ x * x`. We use general theory of inverses of strictly monotone functions to prove that `NNReal.sqrt x` exists. As a side effect, `NNReal.sqrt` is a bundled `OrderIso`, so for `NNReal` numbers we get continuity as well as theorems like `NNReal.sqrt x ≤ y ↔ x ≤ y * y` for free. Then we define `Real.sqrt x` to be `NNReal.sqrt (Real.toNNReal x)`. ## Tags square root -/ open Set Filter open scoped Filter NNReal Topology namespace NNReal variable {x y : ℝ≥0} /-- Square root of a nonnegative real number. -/ -- Porting note (kmill): `pp_nodot` has no effect here -- unless RFC https://github.com/leanprover/lean4/issues/6178 leads to dot notation pp for CoeFun @[pp_nodot] noncomputable def sqrt : ℝ≥0 ≃o ℝ≥0 := OrderIso.symm <| powOrderIso 2 two_ne_zero @[simp] lemma sq_sqrt (x : ℝ≥0) : sqrt x ^ 2 = x := sqrt.symm_apply_apply _ @[simp] lemma sqrt_sq (x : ℝ≥0) : sqrt (x ^ 2) = x := sqrt.apply_symm_apply _ @[simp] lemma mul_self_sqrt (x : ℝ≥0) : sqrt x * sqrt x = x := by rw [← sq, sq_sqrt] @[simp] lemma sqrt_mul_self (x : ℝ≥0) : sqrt (x * x) = x := by rw [← sq, sqrt_sq] lemma sqrt_le_sqrt : sqrt x ≤ sqrt y ↔ x ≤ y := sqrt.le_iff_le lemma sqrt_lt_sqrt : sqrt x < sqrt y ↔ x < y := sqrt.lt_iff_lt lemma sqrt_eq_iff_eq_sq : sqrt x = y ↔ x = y ^ 2 := sqrt.toEquiv.apply_eq_iff_eq_symm_apply lemma sqrt_le_iff_le_sq : sqrt x ≤ y ↔ x ≤ y ^ 2 := sqrt.to_galoisConnection _ _ lemma le_sqrt_iff_sq_le : x ≤ sqrt y ↔ x ^ 2 ≤ y := (sqrt.symm.to_galoisConnection _ _).symm @[simp] lemma sqrt_eq_zero : sqrt x = 0 ↔ x = 0 := by simp [sqrt_eq_iff_eq_sq] @[simp] lemma sqrt_eq_one : sqrt x = 1 ↔ x = 1 := by simp [sqrt_eq_iff_eq_sq] @[simp] lemma sqrt_zero : sqrt 0 = 0 := by simp @[simp] lemma sqrt_one : sqrt 1 = 1 := by simp @[simp] lemma sqrt_le_one : sqrt x ≤ 1 ↔ x ≤ 1 := by rw [← sqrt_one, sqrt_le_sqrt, sqrt_one] @[simp] lemma one_le_sqrt : 1 ≤ sqrt x ↔ 1 ≤ x := by rw [← sqrt_one, sqrt_le_sqrt, sqrt_one] theorem sqrt_mul (x y : ℝ≥0) : sqrt (x * y) = sqrt x * sqrt y := by rw [sqrt_eq_iff_eq_sq, mul_pow, sq_sqrt, sq_sqrt] /-- `NNReal.sqrt` as a `MonoidWithZeroHom`. -/ noncomputable def sqrtHom : ℝ≥0 →*₀ ℝ≥0 := ⟨⟨sqrt, sqrt_zero⟩, sqrt_one, sqrt_mul⟩ theorem sqrt_inv (x : ℝ≥0) : sqrt x⁻¹ = (sqrt x)⁻¹ := map_inv₀ sqrtHom x theorem sqrt_div (x y : ℝ≥0) : sqrt (x / y) = sqrt x / sqrt y := map_div₀ sqrtHom x y @[continuity, fun_prop] theorem continuous_sqrt : Continuous sqrt := sqrt.continuous @[simp] theorem sqrt_pos : 0 < sqrt x ↔ 0 < x := by simp [pos_iff_ne_zero] alias ⟨_, sqrt_pos_of_pos⟩ := sqrt_pos attribute [bound] sqrt_pos_of_pos end NNReal namespace Real /-- The square root of a real number. This returns 0 for negative inputs. This has notation `√x`. Note that `√x⁻¹` is parsed as `√(x⁻¹)`. -/ noncomputable def sqrt (x : ℝ) : ℝ := NNReal.sqrt (Real.toNNReal x) -- TODO: replace this with a typeclass @[inherit_doc] prefix:max "√" => Real.sqrt variable {x y : ℝ} @[simp, norm_cast] theorem coe_sqrt {x : ℝ≥0} : (NNReal.sqrt x : ℝ) = √(x : ℝ) := by rw [Real.sqrt, Real.toNNReal_coe] @[continuity] theorem continuous_sqrt : Continuous (√· : ℝ → ℝ) := NNReal.continuous_coe.comp <| NNReal.continuous_sqrt.comp continuous_real_toNNReal theorem sqrt_eq_zero_of_nonpos (h : x ≤ 0) : sqrt x = 0 := by simp [sqrt, Real.toNNReal_eq_zero.2 h] @[simp] theorem sqrt_nonneg (x : ℝ) : 0 ≤ √x := NNReal.coe_nonneg _ @[simp] theorem mul_self_sqrt (h : 0 ≤ x) : √x * √x = x := by rw [Real.sqrt, ← NNReal.coe_mul, NNReal.mul_self_sqrt, Real.coe_toNNReal _ h] @[simp] theorem sqrt_mul_self (h : 0 ≤ x) : √(x * x) = x := (mul_self_inj_of_nonneg (sqrt_nonneg _) h).1 (mul_self_sqrt (mul_self_nonneg _)) theorem sqrt_eq_cases : √x = y ↔ y * y = x ∧ 0 ≤ y ∨ x < 0 ∧ y = 0 := by constructor · rintro rfl rcases le_or_lt 0 x with hle | hlt · exact Or.inl ⟨mul_self_sqrt hle, sqrt_nonneg x⟩ · exact Or.inr ⟨hlt, sqrt_eq_zero_of_nonpos hlt.le⟩ · rintro (⟨rfl, hy⟩ | ⟨hx, rfl⟩) exacts [sqrt_mul_self hy, sqrt_eq_zero_of_nonpos hx.le] theorem sqrt_eq_iff_mul_self_eq (hx : 0 ≤ x) (hy : 0 ≤ y) : √x = y ↔ x = y * y := ⟨fun h => by rw [← h, mul_self_sqrt hx], fun h => by rw [h, sqrt_mul_self hy]⟩ theorem sqrt_eq_iff_mul_self_eq_of_pos (h : 0 < y) : √x = y ↔ y * y = x := by simp [sqrt_eq_cases, h.ne', h.le] @[simp] theorem sqrt_eq_one : √x = 1 ↔ x = 1 := calc √x = 1 ↔ 1 * 1 = x := sqrt_eq_iff_mul_self_eq_of_pos zero_lt_one _ ↔ x = 1 := by rw [eq_comm, mul_one] @[simp] theorem sq_sqrt (h : 0 ≤ x) : √x ^ 2 = x := by rw [sq, mul_self_sqrt h] @[simp] theorem sqrt_sq (h : 0 ≤ x) : √(x ^ 2) = x := by rw [sq, sqrt_mul_self h] theorem sqrt_eq_iff_eq_sq (hx : 0 ≤ x) (hy : 0 ≤ y) : √x = y ↔ x = y ^ 2 := by rw [sq, sqrt_eq_iff_mul_self_eq hx hy] theorem sqrt_mul_self_eq_abs (x : ℝ) : √(x * x) = |x| := by rw [← abs_mul_abs_self x, sqrt_mul_self (abs_nonneg _)] theorem sqrt_sq_eq_abs (x : ℝ) : √(x ^ 2) = |x| := by rw [sq, sqrt_mul_self_eq_abs] @[simp] theorem sqrt_zero : √0 = 0 := by simp [Real.sqrt] @[simp] theorem sqrt_one : √1 = 1 := by simp [Real.sqrt] @[simp] theorem sqrt_le_sqrt_iff (hy : 0 ≤ y) : √x ≤ √y ↔ x ≤ y := by rw [Real.sqrt, Real.sqrt, NNReal.coe_le_coe, NNReal.sqrt_le_sqrt, toNNReal_le_toNNReal_iff hy] @[simp] theorem sqrt_lt_sqrt_iff (hx : 0 ≤ x) : √x < √y ↔ x < y := lt_iff_lt_of_le_iff_le (sqrt_le_sqrt_iff hx) theorem sqrt_lt_sqrt_iff_of_pos (hy : 0 < y) : √x < √y ↔ x < y := by rw [Real.sqrt, Real.sqrt, NNReal.coe_lt_coe, NNReal.sqrt_lt_sqrt, toNNReal_lt_toNNReal_iff hy] @[gcongr, bound] theorem sqrt_le_sqrt (h : x ≤ y) : √x ≤ √y := by rw [Real.sqrt, Real.sqrt, NNReal.coe_le_coe, NNReal.sqrt_le_sqrt] exact toNNReal_le_toNNReal h @[gcongr, bound] theorem sqrt_lt_sqrt (hx : 0 ≤ x) (h : x < y) : √x < √y := (sqrt_lt_sqrt_iff hx).2 h theorem sqrt_le_left (hy : 0 ≤ y) : √x ≤ y ↔ x ≤ y ^ 2 := by rw [sqrt, ← Real.le_toNNReal_iff_coe_le hy, NNReal.sqrt_le_iff_le_sq, sq, ← Real.toNNReal_mul hy, Real.toNNReal_le_toNNReal_iff (mul_self_nonneg y), sq] theorem sqrt_le_iff : √x ≤ y ↔ 0 ≤ y ∧ x ≤ y ^ 2 := by rw [← and_iff_right_of_imp fun h => (sqrt_nonneg x).trans h, and_congr_right_iff] exact sqrt_le_left theorem sqrt_lt (hx : 0 ≤ x) (hy : 0 ≤ y) : √x < y ↔ x < y ^ 2 := by rw [← sqrt_lt_sqrt_iff hx, sqrt_sq hy] theorem sqrt_lt' (hy : 0 < y) : √x < y ↔ x < y ^ 2 := by
rw [← sqrt_lt_sqrt_iff_of_pos (pow_pos hy _), sqrt_sq hy.le]
Mathlib/Data/Real/Sqrt.lean
208
209
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathlib.Algebra.Ring.Associated import Mathlib.Algebra.Star.Unitary import Mathlib.RingTheory.PrincipalIdealDomain import Mathlib.Tactic.Ring import Mathlib.Algebra.EuclideanDomain.Int /-! # ℤ[√d] The ring of integers adjoined with a square root of `d : ℤ`. After defining the norm, we show that it is a linearly ordered commutative ring, as well as an integral domain. We provide the universal property, that ring homomorphisms `ℤ√d →+* R` correspond to choices of square roots of `d` in `R`. -/ /-- The ring of integers adjoined with a square root of `d`. These have the form `a + b √d` where `a b : ℤ`. The components are called `re` and `im` by analogy to the negative `d` case. -/ @[ext] structure Zsqrtd (d : ℤ) where /-- Component of the integer not multiplied by `√d` -/ re : ℤ /-- Component of the integer multiplied by `√d` -/ im : ℤ deriving DecidableEq @[inherit_doc] prefix:100 "ℤ√" => Zsqrtd namespace Zsqrtd section variable {d : ℤ} /-- Convert an integer to a `ℤ√d` -/ def ofInt (n : ℤ) : ℤ√d := ⟨n, 0⟩ theorem ofInt_re (n : ℤ) : (ofInt n : ℤ√d).re = n := rfl theorem ofInt_im (n : ℤ) : (ofInt n : ℤ√d).im = 0 := rfl /-- The zero of the ring -/ instance : Zero (ℤ√d) := ⟨ofInt 0⟩ @[simp] theorem zero_re : (0 : ℤ√d).re = 0 := rfl @[simp] theorem zero_im : (0 : ℤ√d).im = 0 := rfl instance : Inhabited (ℤ√d) := ⟨0⟩ /-- The one of the ring -/ instance : One (ℤ√d) := ⟨ofInt 1⟩ @[simp] theorem one_re : (1 : ℤ√d).re = 1 := rfl @[simp] theorem one_im : (1 : ℤ√d).im = 0 := rfl /-- The representative of `√d` in the ring -/ def sqrtd : ℤ√d := ⟨0, 1⟩ @[simp] theorem sqrtd_re : (sqrtd : ℤ√d).re = 0 := rfl @[simp] theorem sqrtd_im : (sqrtd : ℤ√d).im = 1 := rfl /-- Addition of elements of `ℤ√d` -/ instance : Add (ℤ√d) := ⟨fun z w => ⟨z.1 + w.1, z.2 + w.2⟩⟩ @[simp] theorem add_def (x y x' y' : ℤ) : (⟨x, y⟩ + ⟨x', y'⟩ : ℤ√d) = ⟨x + x', y + y'⟩ := rfl @[simp] theorem add_re (z w : ℤ√d) : (z + w).re = z.re + w.re := rfl @[simp] theorem add_im (z w : ℤ√d) : (z + w).im = z.im + w.im := rfl /-- Negation in `ℤ√d` -/ instance : Neg (ℤ√d) := ⟨fun z => ⟨-z.1, -z.2⟩⟩ @[simp] theorem neg_re (z : ℤ√d) : (-z).re = -z.re := rfl @[simp] theorem neg_im (z : ℤ√d) : (-z).im = -z.im := rfl /-- Multiplication in `ℤ√d` -/ instance : Mul (ℤ√d) := ⟨fun z w => ⟨z.1 * w.1 + d * z.2 * w.2, z.1 * w.2 + z.2 * w.1⟩⟩ @[simp] theorem mul_re (z w : ℤ√d) : (z * w).re = z.re * w.re + d * z.im * w.im := rfl @[simp] theorem mul_im (z w : ℤ√d) : (z * w).im = z.re * w.im + z.im * w.re := rfl instance addCommGroup : AddCommGroup (ℤ√d) := by refine { add := (· + ·) zero := (0 : ℤ√d) sub := fun a b => a + -b neg := Neg.neg nsmul := @nsmulRec (ℤ√d) ⟨0⟩ ⟨(· + ·)⟩ zsmul := @zsmulRec (ℤ√d) ⟨0⟩ ⟨(· + ·)⟩ ⟨Neg.neg⟩ (@nsmulRec (ℤ√d) ⟨0⟩ ⟨(· + ·)⟩) add_assoc := ?_ zero_add := ?_ add_zero := ?_ neg_add_cancel := ?_ add_comm := ?_ } <;> intros <;> ext <;> simp [add_comm, add_left_comm] @[simp] theorem sub_re (z w : ℤ√d) : (z - w).re = z.re - w.re := rfl @[simp] theorem sub_im (z w : ℤ√d) : (z - w).im = z.im - w.im := rfl instance addGroupWithOne : AddGroupWithOne (ℤ√d) := { Zsqrtd.addCommGroup with natCast := fun n => ofInt n intCast := ofInt one := 1 } instance commRing : CommRing (ℤ√d) := by refine { Zsqrtd.addGroupWithOne with mul := (· * ·) npow := @npowRec (ℤ√d) ⟨1⟩ ⟨(· * ·)⟩, add_comm := ?_ left_distrib := ?_ right_distrib := ?_ zero_mul := ?_ mul_zero := ?_ mul_assoc := ?_ one_mul := ?_ mul_one := ?_ mul_comm := ?_ } <;> intros <;> ext <;> simp <;> ring instance : AddMonoid (ℤ√d) := by infer_instance instance : Monoid (ℤ√d) := by infer_instance instance : CommMonoid (ℤ√d) := by infer_instance instance : CommSemigroup (ℤ√d) := by infer_instance instance : Semigroup (ℤ√d) := by infer_instance instance : AddCommSemigroup (ℤ√d) := by infer_instance instance : AddSemigroup (ℤ√d) := by infer_instance instance : CommSemiring (ℤ√d) := by infer_instance instance : Semiring (ℤ√d) := by infer_instance instance : Ring (ℤ√d) := by infer_instance instance : Distrib (ℤ√d) := by infer_instance /-- Conjugation in `ℤ√d`. The conjugate of `a + b √d` is `a - b √d`. -/ instance : Star (ℤ√d) where star z := ⟨z.1, -z.2⟩ @[simp] theorem star_mk (x y : ℤ) : star (⟨x, y⟩ : ℤ√d) = ⟨x, -y⟩ := rfl @[simp] theorem star_re (z : ℤ√d) : (star z).re = z.re := rfl @[simp] theorem star_im (z : ℤ√d) : (star z).im = -z.im := rfl instance : StarRing (ℤ√d) where star_involutive _ := Zsqrtd.ext rfl (neg_neg _) star_mul a b := by ext <;> simp <;> ring star_add _ _ := Zsqrtd.ext rfl (neg_add _ _) -- Porting note: proof was `by decide` instance nontrivial : Nontrivial (ℤ√d) := ⟨⟨0, 1, Zsqrtd.ext_iff.not.mpr (by simp)⟩⟩ @[simp] theorem natCast_re (n : ℕ) : (n : ℤ√d).re = n := rfl @[simp] theorem ofNat_re (n : ℕ) [n.AtLeastTwo] : (ofNat(n) : ℤ√d).re = n := rfl @[simp] theorem natCast_im (n : ℕ) : (n : ℤ√d).im = 0 := rfl @[simp] theorem ofNat_im (n : ℕ) [n.AtLeastTwo] : (ofNat(n) : ℤ√d).im = 0 := rfl theorem natCast_val (n : ℕ) : (n : ℤ√d) = ⟨n, 0⟩ := rfl @[simp] theorem intCast_re (n : ℤ) : (n : ℤ√d).re = n := by cases n <;> rfl @[simp] theorem intCast_im (n : ℤ) : (n : ℤ√d).im = 0 := by cases n <;> rfl theorem intCast_val (n : ℤ) : (n : ℤ√d) = ⟨n, 0⟩ := by ext <;> simp instance : CharZero (ℤ√d) where cast_injective m n := by simp [Zsqrtd.ext_iff] @[simp] theorem ofInt_eq_intCast (n : ℤ) : (ofInt n : ℤ√d) = n := by ext <;> simp [ofInt_re, ofInt_im] @[simp] theorem nsmul_val (n : ℕ) (x y : ℤ) : (n : ℤ√d) * ⟨x, y⟩ = ⟨n * x, n * y⟩ := by ext <;> simp @[simp] theorem smul_val (n x y : ℤ) : (n : ℤ√d) * ⟨x, y⟩ = ⟨n * x, n * y⟩ := by ext <;> simp theorem smul_re (a : ℤ) (b : ℤ√d) : (↑a * b).re = a * b.re := by simp theorem smul_im (a : ℤ) (b : ℤ√d) : (↑a * b).im = a * b.im := by simp @[simp] theorem muld_val (x y : ℤ) : sqrtd (d := d) * ⟨x, y⟩ = ⟨d * y, x⟩ := by ext <;> simp @[simp] theorem dmuld : sqrtd (d := d) * sqrtd (d := d) = d := by ext <;> simp @[simp] theorem smuld_val (n x y : ℤ) : sqrtd * (n : ℤ√d) * ⟨x, y⟩ = ⟨d * n * y, n * x⟩ := by ext <;> simp theorem decompose {x y : ℤ} : (⟨x, y⟩ : ℤ√d) = x + sqrtd (d := d) * y := by ext <;> simp theorem mul_star {x y : ℤ} : (⟨x, y⟩ * star ⟨x, y⟩ : ℤ√d) = x * x - d * y * y := by ext <;> simp [sub_eq_add_neg, mul_comm] theorem intCast_dvd (z : ℤ) (a : ℤ√d) : ↑z ∣ a ↔ z ∣ a.re ∧ z ∣ a.im := by constructor · rintro ⟨x, rfl⟩ simp only [add_zero, intCast_re, zero_mul, mul_im, dvd_mul_right, and_self_iff, mul_re, mul_zero, intCast_im] · rintro ⟨⟨r, hr⟩, ⟨i, hi⟩⟩ use ⟨r, i⟩ rw [smul_val, Zsqrtd.ext_iff] exact ⟨hr, hi⟩ @[simp, norm_cast] theorem intCast_dvd_intCast (a b : ℤ) : (a : ℤ√d) ∣ b ↔ a ∣ b := by rw [intCast_dvd] constructor · rintro ⟨hre, -⟩ rwa [intCast_re] at hre · rw [intCast_re, intCast_im] exact fun hc => ⟨hc, dvd_zero a⟩ protected theorem eq_of_smul_eq_smul_left {a : ℤ} {b c : ℤ√d} (ha : a ≠ 0) (h : ↑a * b = a * c) : b = c := by rw [Zsqrtd.ext_iff] at h ⊢ apply And.imp _ _ h <;> simpa only [smul_re, smul_im] using mul_left_cancel₀ ha section Gcd theorem gcd_eq_zero_iff (a : ℤ√d) : Int.gcd a.re a.im = 0 ↔ a = 0 := by simp only [Int.gcd_eq_zero_iff, Zsqrtd.ext_iff, eq_self_iff_true, zero_im, zero_re] theorem gcd_pos_iff (a : ℤ√d) : 0 < Int.gcd a.re a.im ↔ a ≠ 0 := pos_iff_ne_zero.trans <| not_congr a.gcd_eq_zero_iff theorem isCoprime_of_dvd_isCoprime {a b : ℤ√d} (hcoprime : IsCoprime a.re a.im) (hdvd : b ∣ a) : IsCoprime b.re b.im := by apply isCoprime_of_dvd · rintro ⟨hre, him⟩ obtain rfl : b = 0 := Zsqrtd.ext hre him rw [zero_dvd_iff] at hdvd simp [hdvd, zero_im, zero_re, not_isCoprime_zero_zero] at hcoprime · rintro z hz - hzdvdu hzdvdv apply hz obtain ⟨ha, hb⟩ : z ∣ a.re ∧ z ∣ a.im := by rw [← intCast_dvd] apply dvd_trans _ hdvd rw [intCast_dvd] exact ⟨hzdvdu, hzdvdv⟩ exact hcoprime.isUnit_of_dvd' ha hb @[deprecated (since := "2025-01-23")] alias coprime_of_dvd_coprime := isCoprime_of_dvd_isCoprime theorem exists_coprime_of_gcd_pos {a : ℤ√d} (hgcd : 0 < Int.gcd a.re a.im) : ∃ b : ℤ√d, a = ((Int.gcd a.re a.im : ℤ) : ℤ√d) * b ∧ IsCoprime b.re b.im := by obtain ⟨re, im, H1, Hre, Him⟩ := Int.exists_gcd_one hgcd rw [mul_comm] at Hre Him refine ⟨⟨re, im⟩, ?_, ?_⟩ · rw [smul_val, ← Hre, ← Him] · rw [Int.isCoprime_iff_gcd_eq_one, H1] end Gcd /-- Read `SqLe a c b d` as `a √c ≤ b √d` -/ def SqLe (a c b d : ℕ) : Prop := c * a * a ≤ d * b * b theorem sqLe_of_le {c d x y z w : ℕ} (xz : z ≤ x) (yw : y ≤ w) (xy : SqLe x c y d) : SqLe z c w d := le_trans (mul_le_mul (Nat.mul_le_mul_left _ xz) xz (Nat.zero_le _) (Nat.zero_le _)) <| le_trans xy (mul_le_mul (Nat.mul_le_mul_left _ yw) yw (Nat.zero_le _) (Nat.zero_le _)) theorem sqLe_add_mixed {c d x y z w : ℕ} (xy : SqLe x c y d) (zw : SqLe z c w d) : c * (x * z) ≤ d * (y * w) := Nat.mul_self_le_mul_self_iff.1 <| by simpa [mul_comm, mul_left_comm] using mul_le_mul xy zw (Nat.zero_le _) (Nat.zero_le _) theorem sqLe_add {c d x y z w : ℕ} (xy : SqLe x c y d) (zw : SqLe z c w d) : SqLe (x + z) c (y + w) d := by have xz := sqLe_add_mixed xy zw simp? [SqLe, mul_assoc] at xy zw says simp only [SqLe, mul_assoc] at xy zw simp [SqLe, mul_add, mul_comm, mul_left_comm, add_le_add, *] theorem sqLe_cancel {c d x y z w : ℕ} (zw : SqLe y d x c) (h : SqLe (x + z) c (y + w) d) : SqLe z c w d := by apply le_of_not_gt intro l refine not_le_of_gt ?_ h simp only [SqLe, mul_add, mul_comm, mul_left_comm, add_assoc, gt_iff_lt] have hm := sqLe_add_mixed zw (le_of_lt l) simp only [SqLe, mul_assoc, gt_iff_lt] at l zw exact lt_of_le_of_lt (add_le_add_right zw _) (add_lt_add_left (add_lt_add_of_le_of_lt hm (add_lt_add_of_le_of_lt hm l)) _) theorem sqLe_smul {c d x y : ℕ} (n : ℕ) (xy : SqLe x c y d) : SqLe (n * x) c (n * y) d := by simpa [SqLe, mul_left_comm, mul_assoc] using Nat.mul_le_mul_left (n * n) xy theorem sqLe_mul {d x y z w : ℕ} : (SqLe x 1 y d → SqLe z 1 w d → SqLe (x * w + y * z) d (x * z + d * y * w) 1) ∧ (SqLe x 1 y d → SqLe w d z 1 → SqLe (x * z + d * y * w) 1 (x * w + y * z) d) ∧ (SqLe y d x 1 → SqLe z 1 w d → SqLe (x * z + d * y * w) 1 (x * w + y * z) d) ∧ (SqLe y d x 1 → SqLe w d z 1 → SqLe (x * w + y * z) d (x * z + d * y * w) 1) := by refine ⟨?_, ?_, ?_, ?_⟩ <;> · intro xy zw have := Int.mul_nonneg (sub_nonneg_of_le (Int.ofNat_le_ofNat_of_le xy)) (sub_nonneg_of_le (Int.ofNat_le_ofNat_of_le zw)) refine Int.le_of_ofNat_le_ofNat (le_of_sub_nonneg ?_) convert this using 1 simp only [one_mul, Int.natCast_add, Int.natCast_mul] ring open Int in /-- "Generalized" `nonneg`. `nonnegg c d x y` means `a √c + b √d ≥ 0`; we are interested in the case `c = 1` but this is more symmetric -/ def Nonnegg (c d : ℕ) : ℤ → ℤ → Prop | (a : ℕ), (b : ℕ) => True | (a : ℕ), -[b+1] => SqLe (b + 1) c a d | -[a+1], (b : ℕ) => SqLe (a + 1) d b c | -[_+1], -[_+1] => False theorem nonnegg_comm {c d : ℕ} {x y : ℤ} : Nonnegg c d x y = Nonnegg d c y x := by cases x <;> cases y <;> rfl theorem nonnegg_neg_pos {c d} : ∀ {a b : ℕ}, Nonnegg c d (-a) b ↔ SqLe a d b c | 0, b => ⟨by simp [SqLe, Nat.zero_le], fun _ => trivial⟩ | a + 1, b => by rfl theorem nonnegg_pos_neg {c d} {a b : ℕ} : Nonnegg c d a (-b) ↔ SqLe b c a d := by rw [nonnegg_comm]; exact nonnegg_neg_pos open Int in theorem nonnegg_cases_right {c d} {a : ℕ} : ∀ {b : ℤ}, (∀ x : ℕ, b = -x → SqLe x c a d) → Nonnegg c d a b | (b : Nat), _ => trivial | -[b+1], h => h (b + 1) rfl theorem nonnegg_cases_left {c d} {b : ℕ} {a : ℤ} (h : ∀ x : ℕ, a = -x → SqLe x d b c) : Nonnegg c d a b :=
cast nonnegg_comm (nonnegg_cases_right h) section Norm /-- The norm of an element of `ℤ[√d]`. -/
Mathlib/NumberTheory/Zsqrtd/Basic.lean
422
426
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Abhimanyu Pallavi Sudhir, Jean Lo, Calle Sönne, Yury Kudryashov -/ import Mathlib.Algebra.Algebra.Rat import Mathlib.Data.Nat.Prime.Int import Mathlib.Data.Rat.Sqrt import Mathlib.Data.Real.Sqrt import Mathlib.RingTheory.Algebraic.Basic import Mathlib.Tactic.IntervalCases /-! # Irrational real numbers In this file we define a predicate `Irrational` on `ℝ`, prove that the `n`-th root of an integer number is irrational if it is not integer, and that `√(q : ℚ)` is irrational if and only if `¬IsSquare q ∧ 0 ≤ q`. We also provide dot-style constructors like `Irrational.add_rat`, `Irrational.rat_sub` etc. With the `Decidable` instances in this file, is possible to prove `Irrational √n` using `decide`, when `n` is a numeric literal or cast; but this only works if you `unseal Nat.sqrt.iter in` before the theorem where you use this proof. -/ open Rat Real /-- A real number is irrational if it is not equal to any rational number. -/ def Irrational (x : ℝ) := x ∉ Set.range ((↑) : ℚ → ℝ) theorem irrational_iff_ne_rational (x : ℝ) : Irrational x ↔ ∀ a b : ℤ, x ≠ a / b := by simp only [Irrational, Rat.forall, cast_mk, not_exists, Set.mem_range, cast_intCast, cast_div, eq_comm] /-- A transcendental real number is irrational. -/ theorem Transcendental.irrational {r : ℝ} (tr : Transcendental ℚ r) : Irrational r := by rintro ⟨a, rfl⟩ exact tr (isAlgebraic_algebraMap a) /-! ### Irrationality of roots of integer and rational numbers -/ /-- If `x^n`, `n > 0`, is integer and is not the `n`-th power of an integer, then `x` is irrational. -/ theorem irrational_nrt_of_notint_nrt {x : ℝ} (n : ℕ) (m : ℤ) (hxr : x ^ n = m) (hv : ¬∃ y : ℤ, x = y) (hnpos : 0 < n) : Irrational x := by rintro ⟨⟨N, D, P, C⟩, rfl⟩ rw [← cast_pow] at hxr have c1 : ((D : ℤ) : ℝ) ≠ 0 := by rw [Int.cast_ne_zero, Int.natCast_ne_zero] exact P have c2 : ((D : ℤ) : ℝ) ^ n ≠ 0 := pow_ne_zero _ c1 rw [mk'_eq_divInt, cast_pow, cast_mk, div_pow, div_eq_iff_mul_eq c2, ← Int.cast_pow, ← Int.cast_pow, ← Int.cast_mul, Int.cast_inj] at hxr have hdivn : (D : ℤ) ^ n ∣ N ^ n := Dvd.intro_left m hxr rw [← Int.dvd_natAbs, ← Int.natCast_pow, Int.natCast_dvd_natCast, Int.natAbs_pow, Nat.pow_dvd_pow_iff hnpos.ne'] at hdivn obtain rfl : D = 1 := by rw [← Nat.gcd_eq_right hdivn, C.gcd_eq_one] refine hv ⟨N, ?_⟩ rw [mk'_eq_divInt, Int.ofNat_one, divInt_one, cast_intCast] /-- If `x^n = m` is an integer and `n` does not divide the `multiplicity p m`, then `x` is irrational. -/ theorem irrational_nrt_of_n_not_dvd_multiplicity {x : ℝ} (n : ℕ) {m : ℤ} (hm : m ≠ 0) (p : ℕ) [hp : Fact p.Prime] (hxr : x ^ n = m) (hv : multiplicity (p : ℤ) m % n ≠ 0) : Irrational x := by rcases Nat.eq_zero_or_pos n with (rfl | hnpos) · rw [eq_comm, pow_zero, ← Int.cast_one, Int.cast_inj] at hxr simp [hxr, multiplicity_of_one_right (mt isUnit_iff_dvd_one.1 (mt Int.natCast_dvd_natCast.1 hp.1.not_dvd_one)), Nat.zero_mod] at hv refine irrational_nrt_of_notint_nrt _ _ hxr ?_ hnpos rintro ⟨y, rfl⟩ rw [← Int.cast_pow, Int.cast_inj] at hxr subst m have : y ≠ 0 := by rintro rfl; rw [zero_pow hnpos.ne'] at hm; exact hm rfl rw [(Int.finiteMultiplicity_iff.2 ⟨by simp [hp.1.ne_one], this⟩).multiplicity_pow (Nat.prime_iff_prime_int.1 hp.1), Nat.mul_mod_right] at hv exact hv rfl theorem irrational_sqrt_of_multiplicity_odd (m : ℤ) (hm : 0 < m) (p : ℕ) [hp : Fact p.Prime] (Hpv : multiplicity (p : ℤ) m % 2 = 1) : Irrational (√m) := @irrational_nrt_of_n_not_dvd_multiplicity _ 2 _ (Ne.symm (ne_of_lt hm)) p hp (sq_sqrt (Int.cast_nonneg.2 <| le_of_lt hm)) (by rw [Hpv]; exact one_ne_zero) @[simp] theorem not_irrational_zero : ¬Irrational 0 := not_not_intro ⟨0, Rat.cast_zero⟩ @[simp] theorem not_irrational_one : ¬Irrational 1 := not_not_intro ⟨1, Rat.cast_one⟩ theorem irrational_sqrt_ratCast_iff_of_nonneg {q : ℚ} (hq : 0 ≤ q) : Irrational (√q) ↔ ¬IsSquare q := by refine Iff.not (?_ : Exists _ ↔ Exists _) constructor · rintro ⟨y, hy⟩ refine ⟨y, Rat.cast_injective (α := ℝ) ?_⟩ rw [Rat.cast_mul, hy, mul_self_sqrt (Rat.cast_nonneg.2 hq)] · rintro ⟨q', rfl⟩ exact ⟨|q'|, mod_cast (sqrt_mul_self_eq_abs q').symm⟩ theorem irrational_sqrt_ratCast_iff {q : ℚ} : Irrational (√q) ↔ ¬IsSquare q ∧ 0 ≤ q := by obtain hq | hq := le_or_lt 0 q · simp_rw [irrational_sqrt_ratCast_iff_of_nonneg hq, and_iff_left hq] · rw [sqrt_eq_zero_of_nonpos (Rat.cast_nonpos.2 hq.le)] simp_rw [not_irrational_zero, false_iff, not_and, not_le, hq, implies_true] theorem irrational_sqrt_intCast_iff_of_nonneg {z : ℤ} (hz : 0 ≤ z) : Irrational (√z) ↔ ¬IsSquare z := by rw [← Rat.isSquare_intCast_iff, ← irrational_sqrt_ratCast_iff_of_nonneg (mod_cast hz), Rat.cast_intCast] theorem irrational_sqrt_intCast_iff {z : ℤ} : Irrational (√z) ↔ ¬IsSquare z ∧ 0 ≤ z := by rw [← Rat.cast_intCast, irrational_sqrt_ratCast_iff, Rat.isSquare_intCast_iff, Int.cast_nonneg] theorem irrational_sqrt_natCast_iff {n : ℕ} : Irrational (√n) ↔ ¬IsSquare n := by rw [← Rat.isSquare_natCast_iff, ← irrational_sqrt_ratCast_iff_of_nonneg n.cast_nonneg, Rat.cast_natCast] theorem irrational_sqrt_ofNat_iff {n : ℕ} [n.AtLeastTwo] : Irrational √(ofNat(n)) ↔ ¬IsSquare ofNat(n) := irrational_sqrt_natCast_iff theorem Nat.Prime.irrational_sqrt {p : ℕ} (hp : Nat.Prime p) : Irrational (√p) := irrational_sqrt_natCast_iff.mpr hp.not_isSquare /-- **Irrationality of the Square Root of 2** -/ theorem irrational_sqrt_two : Irrational (√2) := by simpa using Nat.prime_two.irrational_sqrt /-- This can be used as ```lean unseal Nat.sqrt.iter in example : Irrational √24 := by decide ``` -/ instance {n : ℕ} [n.AtLeastTwo] : Decidable (Irrational √(ofNat(n))) := decidable_of_iff' _ irrational_sqrt_ofNat_iff instance (n : ℕ) : Decidable (Irrational (√n)) := decidable_of_iff' _ irrational_sqrt_natCast_iff instance (z : ℤ) : Decidable (Irrational (√z)) := decidable_of_iff' _ irrational_sqrt_intCast_iff instance (q : ℚ) : Decidable (Irrational (√q)) := decidable_of_iff' _ irrational_sqrt_ratCast_iff /-! ### Dot-style operations on `Irrational` #### Coercion of a rational/integer/natural number is not irrational -/ namespace Irrational variable {x : ℝ} /-! #### Irrational number is not equal to a rational/integer/natural number -/ theorem ne_rat (h : Irrational x) (q : ℚ) : x ≠ q := fun hq => h ⟨q, hq.symm⟩ theorem ne_int (h : Irrational x) (m : ℤ) : x ≠ m := by rw [← Rat.cast_intCast] exact h.ne_rat _ theorem ne_nat (h : Irrational x) (m : ℕ) : x ≠ m := h.ne_int m theorem ne_zero (h : Irrational x) : x ≠ 0 := mod_cast h.ne_nat 0 theorem ne_one (h : Irrational x) : x ≠ 1 := by simpa only [Nat.cast_one] using h.ne_nat 1 @[simp] theorem ne_ofNat (h : Irrational x) (n : ℕ) [n.AtLeastTwo] : x ≠ ofNat(n) := h.ne_nat n end Irrational @[simp] theorem Rat.not_irrational (q : ℚ) : ¬Irrational q := fun h => h ⟨q, rfl⟩ @[simp] theorem Int.not_irrational (m : ℤ) : ¬Irrational m := fun h => h.ne_int m rfl @[simp] theorem Nat.not_irrational (m : ℕ) : ¬Irrational m := fun h => h.ne_nat m rfl @[simp] theorem not_irrational_ofNat (n : ℕ) [n.AtLeastTwo] : ¬Irrational ofNat(n) := n.not_irrational namespace Irrational variable (q : ℚ) {x y : ℝ} /-! #### Addition of rational/integer/natural numbers -/ /-- If `x + y` is irrational, then at least one of `x` and `y` is irrational. -/ theorem add_cases : Irrational (x + y) → Irrational x ∨ Irrational y := by delta Irrational contrapose! rintro ⟨⟨rx, rfl⟩, ⟨ry, rfl⟩⟩ exact ⟨rx + ry, cast_add rx ry⟩ theorem of_ratCast_add (h : Irrational (q + x)) : Irrational x := h.add_cases.resolve_left q.not_irrational @[deprecated (since := "2025-04-01")] alias of_rat_add := of_ratCast_add theorem ratCast_add (h : Irrational x) : Irrational (q + x) := of_ratCast_add (-q) <| by rwa [cast_neg, neg_add_cancel_left] @[deprecated (since := "2025-04-01")] alias rat_add := ratCast_add theorem of_add_ratCast : Irrational (x + q) → Irrational x := add_comm (↑q) x ▸ of_ratCast_add q @[deprecated (since := "2025-04-01")] alias of_add_rat := of_add_ratCast theorem add_ratCast (h : Irrational x) : Irrational (x + q) := add_comm (↑q) x ▸ h.ratCast_add q @[deprecated (since := "2025-04-01")] alias add_rat := add_ratCast theorem of_intCast_add (m : ℤ) (h : Irrational (m + x)) : Irrational x := by rw [← cast_intCast] at h exact h.of_ratCast_add m @[deprecated (since := "2025-04-01")] alias of_int_add := of_intCast_add theorem of_add_intCast (m : ℤ) (h : Irrational (x + m)) : Irrational x := of_intCast_add m <| add_comm x m ▸ h @[deprecated (since := "2025-04-01")] alias of_add_int := of_add_intCast theorem intCast_add (h : Irrational x) (m : ℤ) : Irrational (m + x) := by rw [← cast_intCast] exact h.ratCast_add m @[deprecated (since := "2025-04-01")] alias int_add := intCast_add theorem add_intCast (h : Irrational x) (m : ℤ) : Irrational (x + m) := add_comm (↑m) x ▸ h.intCast_add m @[deprecated (since := "2025-04-01")] alias add_int := add_intCast
theorem of_natCast_add (m : ℕ) (h : Irrational (m + x)) : Irrational x :=
Mathlib/Data/Real/Irrational.lean
250
251
/- Copyright (c) 2021 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import Mathlib.Algebra.Group.Support import Mathlib.Algebra.Order.Monoid.Unbundled.WithTop import Mathlib.Order.WellFoundedSet /-! # Hahn Series If `Γ` is ordered and `R` has zero, then `HahnSeries Γ R` consists of formal series over `Γ` with coefficients in `R`, whose supports are partially well-ordered. With further structure on `R` and `Γ`, we can add further structure on `HahnSeries Γ R`, with the most studied case being when `Γ` is a linearly ordered abelian group and `R` is a field, in which case `HahnSeries Γ R` is a valued field, with value group `Γ`. These generalize Laurent series (with value group `ℤ`), and Laurent series are implemented that way in the file `Mathlib/RingTheory/LaurentSeries.lean`. ## Main Definitions * If `Γ` is ordered and `R` has zero, then `HahnSeries Γ R` consists of formal series over `Γ` with coefficients in `R`, whose supports are partially well-ordered. * `support x` is the subset of `Γ` whose coefficients are nonzero. * `single a r` is the Hahn series which has coefficient `r` at `a` and zero otherwise. * `orderTop x` is a minimal element of `WithTop Γ` where `x` has a nonzero coefficient if `x ≠ 0`, and is `⊤` when `x = 0`. * `order x` is a minimal element of `Γ` where `x` has a nonzero coefficient if `x ≠ 0`, and is zero when `x = 0`. * `map` takes each coefficient of a Hahn series to its target under a zero-preserving map. * `embDomain` preserves coefficients, but embeds the index set `Γ` in a larger poset. ## References - [J. van der Hoeven, *Operators on Generalized Power Series*][van_der_hoeven] -/ open Finset Function noncomputable section /-- If `Γ` is linearly ordered and `R` has zero, then `HahnSeries Γ R` consists of formal series over `Γ` with coefficients in `R`, whose supports are well-founded. -/ @[ext] structure HahnSeries (Γ : Type*) (R : Type*) [PartialOrder Γ] [Zero R] where /-- The coefficient function of a Hahn Series. -/ coeff : Γ → R isPWO_support' : (Function.support coeff).IsPWO variable {Γ Γ' R S : Type*} namespace HahnSeries section Zero variable [PartialOrder Γ] [Zero R] theorem coeff_injective : Injective (coeff : HahnSeries Γ R → Γ → R) := fun _ _ => HahnSeries.ext @[simp] theorem coeff_inj {x y : HahnSeries Γ R} : x.coeff = y.coeff ↔ x = y := coeff_injective.eq_iff /-- The support of a Hahn series is just the set of indices whose coefficients are nonzero. Notably, it is well-founded. -/ nonrec def support (x : HahnSeries Γ R) : Set Γ := support x.coeff @[simp] theorem isPWO_support (x : HahnSeries Γ R) : x.support.IsPWO := x.isPWO_support' @[simp] theorem isWF_support (x : HahnSeries Γ R) : x.support.IsWF := x.isPWO_support.isWF @[simp] theorem mem_support (x : HahnSeries Γ R) (a : Γ) : a ∈ x.support ↔ x.coeff a ≠ 0 := Iff.refl _ instance : Zero (HahnSeries Γ R) := ⟨{ coeff := 0 isPWO_support' := by simp }⟩ instance : Inhabited (HahnSeries Γ R) := ⟨0⟩ instance [Subsingleton R] : Subsingleton (HahnSeries Γ R) := ⟨fun _ _ => HahnSeries.ext (by subsingleton)⟩ @[simp] theorem coeff_zero {a : Γ} : (0 : HahnSeries Γ R).coeff a = 0 := rfl @[deprecated (since := "2025-01-31")] alias zero_coeff := coeff_zero @[simp] theorem coeff_fun_eq_zero_iff {x : HahnSeries Γ R} : x.coeff = 0 ↔ x = 0 := coeff_injective.eq_iff' rfl theorem ne_zero_of_coeff_ne_zero {x : HahnSeries Γ R} {g : Γ} (h : x.coeff g ≠ 0) : x ≠ 0 := mt (fun x0 => (x0.symm ▸ coeff_zero : x.coeff g = 0)) h @[simp] theorem support_zero : support (0 : HahnSeries Γ R) = ∅ := Function.support_zero @[simp] nonrec theorem support_nonempty_iff {x : HahnSeries Γ R} : x.support.Nonempty ↔ x ≠ 0 := by rw [support, support_nonempty_iff, Ne, coeff_fun_eq_zero_iff] @[simp] theorem support_eq_empty_iff {x : HahnSeries Γ R} : x.support = ∅ ↔ x = 0 := Function.support_eq_empty_iff.trans coeff_fun_eq_zero_iff /-- The map of Hahn series induced by applying a zero-preserving map to each coefficient. -/ @[simps] def map [Zero S] (x : HahnSeries Γ R) {F : Type*} [FunLike F R S] [ZeroHomClass F R S] (f : F) : HahnSeries Γ S where coeff g := f (x.coeff g) isPWO_support' := x.isPWO_support.mono <| Function.support_comp_subset (ZeroHomClass.map_zero f) _ @[simp] protected lemma map_zero [Zero S] (f : ZeroHom R S) : (0 : HahnSeries Γ R).map f = 0 := by ext; simp /-- Change a HahnSeries with coefficients in HahnSeries to a HahnSeries on the Lex product. -/ def ofIterate [PartialOrder Γ'] (x : HahnSeries Γ (HahnSeries Γ' R)) : HahnSeries (Γ ×ₗ Γ') R where coeff := fun g => coeff (coeff x g.1) g.2 isPWO_support' := by refine Set.PartiallyWellOrderedOn.subsetProdLex ?_ ?_ · refine Set.IsPWO.mono x.isPWO_support' ?_ simp_rw [Set.image_subset_iff, support_subset_iff, Set.mem_preimage, Function.mem_support] exact fun _ ↦ ne_zero_of_coeff_ne_zero · exact fun a => by simpa [Function.mem_support, ne_eq] using (x.coeff a).isPWO_support' @[simp] lemma mk_eq_zero (f : Γ → R) (h) : HahnSeries.mk f h = 0 ↔ f = 0 := by simp_rw [HahnSeries.ext_iff, funext_iff, coeff_zero, Pi.zero_apply] /-- Change a Hahn series on a lex product to a Hahn series with coefficients in a Hahn series. -/ def toIterate [PartialOrder Γ'] (x : HahnSeries (Γ ×ₗ Γ') R) : HahnSeries Γ (HahnSeries Γ' R) where coeff := fun g => { coeff := fun g' => coeff x (g, g') isPWO_support' := Set.PartiallyWellOrderedOn.fiberProdLex x.isPWO_support' g } isPWO_support' := by have h₁ : (Function.support fun g => HahnSeries.mk (fun g' => x.coeff (g, g')) (Set.PartiallyWellOrderedOn.fiberProdLex x.isPWO_support' g)) = Function.support fun g => fun g' => x.coeff (g, g') := by simp only [Function.support, ne_eq, mk_eq_zero] rw [h₁, Function.support_curry' x.coeff] exact Set.PartiallyWellOrderedOn.imageProdLex x.isPWO_support' /-- The equivalence between iterated Hahn series and Hahn series on the lex product. -/ @[simps] def iterateEquiv [PartialOrder Γ'] : HahnSeries Γ (HahnSeries Γ' R) ≃ HahnSeries (Γ ×ₗ Γ') R where toFun := ofIterate invFun := toIterate left_inv := congrFun rfl right_inv := congrFun rfl open Classical in /-- `single a r` is the Hahn series which has coefficient `r` at `a` and zero otherwise. -/ def single (a : Γ) : ZeroHom R (HahnSeries Γ R) where toFun r := { coeff := Pi.single a r isPWO_support' := (Set.isPWO_singleton a).mono Pi.support_single_subset } map_zero' := HahnSeries.ext (Pi.single_zero _) variable {a b : Γ} {r : R} @[simp] theorem coeff_single_same (a : Γ) (r : R) : (single a r).coeff a = r := by classical exact Pi.single_eq_same (f := fun _ => R) a r @[deprecated (since := "2025-01-31")] alias single_coeff_same := coeff_single_same @[simp] theorem coeff_single_of_ne (h : b ≠ a) : (single a r).coeff b = 0 := by classical exact Pi.single_eq_of_ne (f := fun _ => R) h r @[deprecated (since := "2025-01-31")] alias single_coeff_of_ne := coeff_single_of_ne open Classical in theorem coeff_single : (single a r).coeff b = if b = a then r else 0 := by split_ifs with h <;> simp [h] @[deprecated (since := "2025-01-31")] alias single_coeff := coeff_single @[simp] theorem support_single_of_ne (h : r ≠ 0) : support (single a r) = {a} := by classical exact Pi.support_single_of_ne h theorem support_single_subset : support (single a r) ⊆ {a} := by classical exact Pi.support_single_subset theorem eq_of_mem_support_single {b : Γ} (h : b ∈ support (single a r)) : b = a := support_single_subset h theorem single_eq_zero : single a (0 : R) = 0 := (single a).map_zero theorem single_injective (a : Γ) : Function.Injective (single a : R → HahnSeries Γ R) := fun r s rs => by rw [← coeff_single_same a r, ← coeff_single_same a s, rs] theorem single_ne_zero (h : r ≠ 0) : single a r ≠ 0 := fun con => h (single_injective a (con.trans single_eq_zero.symm)) @[simp] theorem single_eq_zero_iff {a : Γ} {r : R} : single a r = 0 ↔ r = 0 := map_eq_zero_iff _ <| single_injective a @[simp] protected lemma map_single [Zero S] (f : ZeroHom R S) : (single a r).map f = single a (f r) := by ext g by_cases h : g = a <;> simp [h] instance [Nonempty Γ] [Nontrivial R] : Nontrivial (HahnSeries Γ R) := ⟨by obtain ⟨r, s, rs⟩ := exists_pair_ne R inhabit Γ refine ⟨single default r, single default s, fun con => rs ?_⟩ rw [← coeff_single_same (default : Γ) r, con, coeff_single_same]⟩ section Order open Classical in /-- The orderTop of a Hahn series `x` is a minimal element of `WithTop Γ` where `x` has a nonzero coefficient if `x ≠ 0`, and is `⊤` when `x = 0`. -/ def orderTop (x : HahnSeries Γ R) : WithTop Γ := if h : x = 0 then ⊤ else x.isWF_support.min (support_nonempty_iff.2 h) @[simp] theorem orderTop_zero : orderTop (0 : HahnSeries Γ R) = ⊤ := dif_pos rfl @[simp] theorem orderTop_of_Subsingleton [Subsingleton R] {x : HahnSeries Γ R} : x.orderTop = ⊤ := (Subsingleton.eq_zero x) ▸ orderTop_zero theorem orderTop_of_ne {x : HahnSeries Γ R} (hx : x ≠ 0) : orderTop x = x.isWF_support.min (support_nonempty_iff.2 hx) := dif_neg hx @[simp] theorem ne_zero_iff_orderTop {x : HahnSeries Γ R} : x ≠ 0 ↔ orderTop x ≠ ⊤ := by
constructor · exact fun hx => Eq.mpr (congrArg (fun h ↦ h ≠ ⊤) (orderTop_of_ne hx)) WithTop.coe_ne_top · contrapose! simp_all only [orderTop_zero, implies_true]
Mathlib/RingTheory/HahnSeries/Basic.lean
252
256
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Mario Carneiro, Johan Commelin, Amelia Livingston, Anne Baanen -/ import Mathlib.Algebra.Algebra.Tower import Mathlib.Algebra.Field.IsField import Mathlib.Algebra.GroupWithZero.NonZeroDivisors import Mathlib.GroupTheory.MonoidLocalization.MonoidWithZero import Mathlib.RingTheory.Localization.Defs import Mathlib.RingTheory.OreLocalization.Ring /-! # Localizations of commutative rings This file contains various basic results on localizations. We characterize the localization of a commutative ring `R` at a submonoid `M` up to isomorphism; that is, a commutative ring `S` is the localization of `R` at `M` iff we can find a ring homomorphism `f : R →+* S` satisfying 3 properties: 1. For all `y ∈ M`, `f y` is a unit; 2. For all `z : S`, there exists `(x, y) : R × M` such that `z * f y = f x`; 3. For all `x, y : R` such that `f x = f y`, there exists `c ∈ M` such that `x * c = y * c`. (The converse is a consequence of 1.) In the following, let `R, P` be commutative rings, `S, Q` be `R`- and `P`-algebras and `M, T` be submonoids of `R` and `P` respectively, e.g.: ``` variable (R S P Q : Type*) [CommRing R] [CommRing S] [CommRing P] [CommRing Q] variable [Algebra R S] [Algebra P Q] (M : Submonoid R) (T : Submonoid P) ``` ## Main definitions * `IsLocalization.algEquiv`: if `Q` is another localization of `R` at `M`, then `S` and `Q` are isomorphic as `R`-algebras ## Implementation notes In maths it is natural to reason up to isomorphism, but in Lean we cannot naturally `rewrite` one structure with an isomorphic one; one way around this is to isolate a predicate characterizing a structure up to isomorphism, and reason about things that satisfy the predicate. A previous version of this file used a fully bundled type of ring localization maps, then used a type synonym `f.codomain` for `f : LocalizationMap M S` to instantiate the `R`-algebra structure on `S`. This results in defining ad-hoc copies for everything already defined on `S`. By making `IsLocalization` a predicate on the `algebraMap R S`, we can ensure the localization map commutes nicely with other `algebraMap`s. To prove most lemmas about a localization map `algebraMap R S` in this file we invoke the corresponding proof for the underlying `CommMonoid` localization map `IsLocalization.toLocalizationMap M S`, which can be found in `GroupTheory.MonoidLocalization` and the namespace `Submonoid.LocalizationMap`. To reason about the localization as a quotient type, use `mk_eq_of_mk'` and associated lemmas. These show the quotient map `mk : R → M → Localization M` equals the surjection `LocalizationMap.mk'` induced by the map `algebraMap : R →+* Localization M`. The lemma `mk_eq_of_mk'` hence gives you access to the results in the rest of the file, which are about the `LocalizationMap.mk'` induced by any localization map. The proof that "a `CommRing` `K` which is the localization of an integral domain `R` at `R \ {0}` is a field" is a `def` rather than an `instance`, so if you want to reason about a field of fractions `K`, assume `[Field K]` instead of just `[CommRing K]`. ## Tags localization, ring localization, commutative ring localization, characteristic predicate, commutative ring, field of fractions -/ assert_not_exists Ideal open Function namespace Localization open IsLocalization variable {ι : Type*} {R : ι → Type*} [∀ i, CommSemiring (R i)] variable {i : ι} (S : Submonoid (R i)) /-- `IsLocalization.map` applied to a projection homomorphism from a product ring. -/ noncomputable abbrev mapPiEvalRingHom : Localization (S.comap <| Pi.evalRingHom R i) →+* Localization S := map (T := S) _ (Pi.evalRingHom R i) le_rfl open Function in theorem mapPiEvalRingHom_bijective : Bijective (mapPiEvalRingHom S) := by let T := S.comap (Pi.evalRingHom R i) classical refine ⟨fun x₁ x₂ eq ↦ ?_, fun x ↦ ?_⟩ · obtain ⟨r₁, s₁, rfl⟩ := mk'_surjective T x₁ obtain ⟨r₂, s₂, rfl⟩ := mk'_surjective T x₂ simp_rw [map_mk'] at eq rw [IsLocalization.eq] at eq ⊢ obtain ⟨s, hs⟩ := eq refine ⟨⟨update 0 i s, by apply update_self i s.1 0 ▸ s.2⟩, funext fun j ↦ ?_⟩ obtain rfl | ne := eq_or_ne j i · simpa using hs · simp [update_of_ne ne] · obtain ⟨r, s, rfl⟩ := mk'_surjective S x exact ⟨mk' (M := T) _ (update 0 i r) ⟨update 0 i s, by apply update_self i s.1 0 ▸ s.2⟩, by simp [map_mk']⟩ end Localization section CommSemiring variable {R : Type*} [CommSemiring R] {M N : Submonoid R} {S : Type*} [CommSemiring S] variable [Algebra R S] {P : Type*} [CommSemiring P] namespace IsLocalization section IsLocalization variable [IsLocalization M S] variable (M S) in include M in theorem linearMap_compatibleSMul (N₁ N₂) [AddCommMonoid N₁] [AddCommMonoid N₂] [Module R N₁] [Module S N₁] [Module R N₂] [Module S N₂] [IsScalarTower R S N₁] [IsScalarTower R S N₂] : LinearMap.CompatibleSMul N₁ N₂ S R where map_smul f s s' := by obtain ⟨r, m, rfl⟩ := mk'_surjective M s rw [← (map_units S m).smul_left_cancel] simp_rw [algebraMap_smul, ← map_smul, ← smul_assoc, smul_mk'_self, algebraMap_smul, map_smul] variable {g : R →+* P} (hg : ∀ y : M, IsUnit (g y)) variable (M) in include M in -- This is not an instance since the submonoid `M` would become a metavariable in typeclass search. theorem algHom_subsingleton [Algebra R P] : Subsingleton (S →ₐ[R] P) := ⟨fun f g => AlgHom.coe_ringHom_injective <| IsLocalization.ringHom_ext M <| by rw [f.comp_algebraMap, g.comp_algebraMap]⟩ section AlgEquiv variable {Q : Type*} [CommSemiring Q] [Algebra R Q] [IsLocalization M Q] section variable (M S Q) /-- If `S`, `Q` are localizations of `R` at the submonoid `M` respectively, there is an isomorphism of localizations `S ≃ₐ[R] Q`. -/ @[simps!] noncomputable def algEquiv : S ≃ₐ[R] Q := { ringEquivOfRingEquiv S Q (RingEquiv.refl R) M.map_id with commutes' := ringEquivOfRingEquiv_eq _ } end theorem algEquiv_mk' (x : R) (y : M) : algEquiv M S Q (mk' S x y) = mk' Q x y := by simp theorem algEquiv_symm_mk' (x : R) (y : M) : (algEquiv M S Q).symm (mk' Q x y) = mk' S x y := by simp variable (M) in include M in protected lemma bijective (f : S →+* Q) (hf : f.comp (algebraMap R S) = algebraMap R Q) : Function.Bijective f := (show f = IsLocalization.algEquiv M S Q by apply IsLocalization.ringHom_ext M; rw [hf]; ext; simp) ▸ (IsLocalization.algEquiv M S Q).toEquiv.bijective end AlgEquiv section liftAlgHom variable {A : Type*} [CommSemiring A] {R : Type*} [CommSemiring R] [Algebra A R] {M : Submonoid R} {S : Type*} [CommSemiring S] [Algebra A S] [Algebra R S] [IsScalarTower A R S] {P : Type*} [CommSemiring P] [Algebra A P] [IsLocalization M S] {f : R →ₐ[A] P} (hf : ∀ y : M, IsUnit (f y)) (x : S) include hf /-- `AlgHom` version of `IsLocalization.lift`. -/ noncomputable def liftAlgHom : S →ₐ[A] P where __ := lift hf commutes' r := show lift hf (algebraMap A S r) = _ by simp [IsScalarTower.algebraMap_apply A R S] theorem liftAlgHom_toRingHom : (liftAlgHom hf : S →ₐ[A] P).toRingHom = lift hf := rfl @[simp] theorem coe_liftAlgHom : ⇑(liftAlgHom hf : S →ₐ[A] P) = lift hf := rfl theorem liftAlgHom_apply : liftAlgHom hf x = lift hf x := rfl end liftAlgHom section AlgEquivOfAlgEquiv variable {A : Type*} [CommSemiring A] {R : Type*} [CommSemiring R] [Algebra A R] {M : Submonoid R} (S : Type*) [CommSemiring S] [Algebra A S] [Algebra R S] [IsScalarTower A R S] [IsLocalization M S] {P : Type*} [CommSemiring P] [Algebra A P] {T : Submonoid P} (Q : Type*) [CommSemiring Q] [Algebra A Q] [Algebra P Q] [IsScalarTower A P Q] [IsLocalization T Q] (h : R ≃ₐ[A] P) (H : Submonoid.map h M = T) include H /-- If `S`, `Q` are localizations of `R` and `P` at submonoids `M`, `T` respectively, an isomorphism `h : R ≃ₐ[A] P` such that `h(M) = T` induces an isomorphism of localizations `S ≃ₐ[A] Q`. -/ @[simps!] noncomputable def algEquivOfAlgEquiv : S ≃ₐ[A] Q where __ := ringEquivOfRingEquiv S Q h.toRingEquiv H commutes' _ := by dsimp; rw [IsScalarTower.algebraMap_apply A R S, map_eq, RingHom.coe_coe, AlgEquiv.commutes, IsScalarTower.algebraMap_apply A P Q] variable {S Q h} theorem algEquivOfAlgEquiv_eq_map : (algEquivOfAlgEquiv S Q h H : S →+* Q) = map Q (h : R →+* P) (M.le_comap_of_map_le (le_of_eq H)) := rfl theorem algEquivOfAlgEquiv_eq (x : R) : algEquivOfAlgEquiv S Q h H ((algebraMap R S) x) = algebraMap P Q (h x) := by simp set_option linter.docPrime false in theorem algEquivOfAlgEquiv_mk' (x : R) (y : M) : algEquivOfAlgEquiv S Q h H (mk' S x y) = mk' Q (h x) ⟨h y, show h y ∈ T from H ▸ Set.mem_image_of_mem h y.2⟩ := by simp [map_mk'] theorem algEquivOfAlgEquiv_symm : (algEquivOfAlgEquiv S Q h H).symm = algEquivOfAlgEquiv Q S h.symm (show Submonoid.map h.symm T = M by rw [← H, ← Submonoid.map_coe_toMulEquiv, AlgEquiv.symm_toMulEquiv, ← Submonoid.comap_equiv_eq_map_symm, ← Submonoid.map_coe_toMulEquiv, Submonoid.comap_map_eq_of_injective (h : R ≃* P).injective]) := rfl end AlgEquivOfAlgEquiv section at_units variable (R M) /-- The localization at a module of units is isomorphic to the ring. -/ noncomputable def atUnits (H : M ≤ IsUnit.submonoid R) : R ≃ₐ[R] S := by refine AlgEquiv.ofBijective (Algebra.ofId R S) ⟨?_, ?_⟩ · intro x y hxy obtain ⟨c, eq⟩ := (IsLocalization.eq_iff_exists M S).mp hxy obtain ⟨u, hu⟩ := H c.prop rwa [← hu, Units.mul_right_inj] at eq · intro y obtain ⟨⟨x, s⟩, eq⟩ := IsLocalization.surj M y obtain ⟨u, hu⟩ := H s.prop use x * u.inv dsimp [Algebra.ofId, RingHom.toFun_eq_coe, AlgHom.coe_mks] rw [RingHom.map_mul, ← eq, ← hu, mul_assoc, ← RingHom.map_mul] simp end at_units end IsLocalization section variable (M N) theorem isLocalization_of_algEquiv [Algebra R P] [IsLocalization M S] (h : S ≃ₐ[R] P) : IsLocalization M P := by constructor · intro y convert (IsLocalization.map_units S y).map h.toAlgHom.toRingHom.toMonoidHom exact (h.commutes y).symm · intro y obtain ⟨⟨x, s⟩, e⟩ := IsLocalization.surj M (h.symm y) apply_fun (show S → P from h) at e simp only [map_mul, h.apply_symm_apply, h.commutes] at e exact ⟨⟨x, s⟩, e⟩ · intro x y rw [← h.symm.toEquiv.injective.eq_iff, ← IsLocalization.eq_iff_exists M S, ← h.symm.commutes, ← h.symm.commutes] exact id theorem isLocalization_iff_of_algEquiv [Algebra R P] (h : S ≃ₐ[R] P) : IsLocalization M S ↔ IsLocalization M P := ⟨fun _ => isLocalization_of_algEquiv M h, fun _ => isLocalization_of_algEquiv M h.symm⟩ theorem isLocalization_iff_of_ringEquiv (h : S ≃+* P) : IsLocalization M S ↔ haveI := (h.toRingHom.comp <| algebraMap R S).toAlgebra; IsLocalization M P := letI := (h.toRingHom.comp <| algebraMap R S).toAlgebra isLocalization_iff_of_algEquiv M { h with commutes' := fun _ => rfl } variable (S) in /-- If an algebra is simultaneously localizations for two submonoids, then an arbitrary algebra is a localization of one submonoid iff it is a localization of the other. -/ theorem isLocalization_iff_of_isLocalization [IsLocalization M S] [IsLocalization N S] [Algebra R P] : IsLocalization M P ↔ IsLocalization N P := ⟨fun _ ↦ isLocalization_of_algEquiv N (algEquiv M S P), fun _ ↦ isLocalization_of_algEquiv M (algEquiv N S P)⟩ theorem iff_of_le_of_exists_dvd (N : Submonoid R) (h₁ : M ≤ N) (h₂ : ∀ n ∈ N, ∃ m ∈ M, n ∣ m) : IsLocalization M S ↔ IsLocalization N S := have : IsLocalization N (Localization M) := of_le_of_exists_dvd _ _ h₁ h₂ isLocalization_iff_of_isLocalization _ _ (Localization M) end variable (M) /-- If `S₁` is the localization of `R` at `M₁` and `S₂` is the localization of `R` at `M₂`, then every localization `T` of `S₂` at `M₁` is also a localization of `S₁` at `M₂`, in other words `M₁⁻¹M₂⁻¹R` can be identified with `M₂⁻¹M₁⁻¹R`. -/ lemma commutes (S₁ S₂ T : Type*) [CommSemiring S₁] [CommSemiring S₂] [CommSemiring T] [Algebra R S₁] [Algebra R S₂] [Algebra R T] [Algebra S₁ T] [Algebra S₂ T] [IsScalarTower R S₁ T] [IsScalarTower R S₂ T] (M₁ M₂ : Submonoid R) [IsLocalization M₁ S₁] [IsLocalization M₂ S₂] [IsLocalization (Algebra.algebraMapSubmonoid S₂ M₁) T] : IsLocalization (Algebra.algebraMapSubmonoid S₁ M₂) T where map_units' := by rintro ⟨m, ⟨a, ha, rfl⟩⟩ rw [← IsScalarTower.algebraMap_apply, IsScalarTower.algebraMap_apply R S₂ T] exact IsUnit.map _ (IsLocalization.map_units' ⟨a, ha⟩) surj' a := by obtain ⟨⟨y, -, m, hm, rfl⟩, hy⟩ := surj (M := Algebra.algebraMapSubmonoid S₂ M₁) a rw [← IsScalarTower.algebraMap_apply, IsScalarTower.algebraMap_apply R S₁ T] at hy obtain ⟨⟨z, n, hn⟩, hz⟩ := IsLocalization.surj (M := M₂) y have hunit : IsUnit (algebraMap R S₁ m) := map_units' ⟨m, hm⟩ use ⟨algebraMap R S₁ z * hunit.unit⁻¹, ⟨algebraMap R S₁ n, n, hn, rfl⟩⟩ rw [map_mul, ← IsScalarTower.algebraMap_apply, IsScalarTower.algebraMap_apply R S₂ T] conv_rhs => rw [← IsScalarTower.algebraMap_apply] rw [IsScalarTower.algebraMap_apply R S₂ T, ← hz, map_mul, ← hy] convert_to _ = a * (algebraMap S₂ T) ((algebraMap R S₂) n) * (algebraMap S₁ T) (((algebraMap R S₁) m) * hunit.unit⁻¹.val) · rw [map_mul] ring simp exists_of_eq {x y} hxy := by obtain ⟨r, s, d, hr, hs⟩ := IsLocalization.surj₂ M₁ S₁ x y apply_fun (· * algebraMap S₁ T (algebraMap R S₁ d)) at hxy simp_rw [← map_mul, hr, hs, ← IsScalarTower.algebraMap_apply, IsScalarTower.algebraMap_apply R S₂ T] at hxy obtain ⟨⟨-, c, hmc, rfl⟩, hc⟩ := exists_of_eq (M := Algebra.algebraMapSubmonoid S₂ M₁) hxy simp_rw [← map_mul] at hc obtain ⟨a, ha⟩ := IsLocalization.exists_of_eq (M := M₂) hc use ⟨algebraMap R S₁ a, a, a.property, rfl⟩ apply (map_units S₁ d).mul_right_cancel rw [mul_assoc, hr, mul_assoc, hs] apply (map_units S₁ ⟨c, hmc⟩).mul_right_cancel rw [← map_mul, ← map_mul, mul_assoc, mul_comm _ c, ha, map_mul, map_mul] ring end IsLocalization namespace Localization open IsLocalization theorem mk_natCast (m : ℕ) : (mk m 1 : Localization M) = m := by simpa using mk_algebraMap (R := R) (A := ℕ) _ variable [IsLocalization M S] section variable (S) (M) /-- The localization of `R` at `M` as a quotient type is isomorphic to any other localization. -/ @[simps!] noncomputable def algEquiv : Localization M ≃ₐ[R] S := IsLocalization.algEquiv M _ _ /-- The localization of a singleton is a singleton. Cannot be an instance due to metavariables. -/ noncomputable def _root_.IsLocalization.unique (R Rₘ) [CommSemiring R] [CommSemiring Rₘ] (M : Submonoid R) [Subsingleton R] [Algebra R Rₘ] [IsLocalization M Rₘ] : Unique Rₘ := have : Inhabited Rₘ := ⟨1⟩ (algEquiv M Rₘ).symm.injective.unique end nonrec theorem algEquiv_mk' (x : R) (y : M) : algEquiv M S (mk' (Localization M) x y) = mk' S x y := algEquiv_mk' _ _ nonrec theorem algEquiv_symm_mk' (x : R) (y : M) : (algEquiv M S).symm (mk' S x y) = mk' (Localization M) x y := algEquiv_symm_mk' _ _ theorem algEquiv_mk (x y) : algEquiv M S (mk x y) = mk' S x y := by rw [mk_eq_mk', algEquiv_mk'] theorem algEquiv_symm_mk (x : R) (y : M) : (algEquiv M S).symm (mk' S x y) = mk x y := by rw [mk_eq_mk', algEquiv_symm_mk'] lemma coe_algEquiv : (Localization.algEquiv M S : Localization M →+* S) = IsLocalization.map (M := M) (T := M) _ (RingHom.id R) le_rfl := rfl lemma coe_algEquiv_symm : ((Localization.algEquiv M S).symm : S →+* Localization M) = IsLocalization.map (M := M) (T := M) _ (RingHom.id R) le_rfl := rfl end Localization end CommSemiring section CommRing variable {R : Type*} [CommRing R] {M : Submonoid R} (S : Type*) [CommRing S] variable [Algebra R S] {P : Type*} [CommRing P] namespace Localization theorem mk_intCast (m : ℤ) : (mk m 1 : Localization M) = m := by simpa using mk_algebraMap (R := R) (A := ℤ) _ end Localization open IsLocalization /-- If `R` is a field, then localizing at a submonoid not containing `0` adds no new elements. -/ theorem IsField.localization_map_bijective {R Rₘ : Type*} [CommRing R] [CommRing Rₘ] {M : Submonoid R} (hM : (0 : R) ∉ M) (hR : IsField R) [Algebra R Rₘ] [IsLocalization M Rₘ] : Function.Bijective (algebraMap R Rₘ) := by letI := hR.toField replace hM := le_nonZeroDivisors_of_noZeroDivisors hM refine ⟨IsLocalization.injective _ hM, fun x => ?_⟩ obtain ⟨r, ⟨m, hm⟩, rfl⟩ := mk'_surjective M x obtain ⟨n, hn⟩ := hR.mul_inv_cancel (nonZeroDivisors.ne_zero <| hM hm) exact ⟨r * n, by rw [eq_mk'_iff_mul_eq, ← map_mul, mul_assoc, _root_.mul_comm n, hn, mul_one]⟩ /-- If `R` is a field, then localizing at a submonoid not containing `0` adds no new elements. -/ theorem Field.localization_map_bijective {K Kₘ : Type*} [Field K] [CommRing Kₘ] {M : Submonoid K} (hM : (0 : K) ∉ M) [Algebra K Kₘ] [IsLocalization M Kₘ] : Function.Bijective (algebraMap K Kₘ) := (Field.toIsField K).localization_map_bijective hM -- this looks weird due to the `letI` inside the above lemma, but trying to do it the other -- way round causes issues with defeq of instances, so this is actually easier. section Algebra variable {S} {Rₘ Sₘ : Type*} [CommRing Rₘ] [CommRing Sₘ] variable [Algebra R Rₘ] [IsLocalization M Rₘ] variable [Algebra S Sₘ] [i : IsLocalization (Algebra.algebraMapSubmonoid S M) Sₘ] include S section variable (S M) /-- Definition of the natural algebra induced by the localization of an algebra. Given an algebra `R → S`, a submonoid `R` of `M`, and a localization `Rₘ` for `M`, let `Sₘ` be the localization of `S` to the image of `M` under `algebraMap R S`. Then this is the natural algebra structure on `Rₘ → Sₘ`, such that the entire square commutes, where `localization_map.map_comp` gives the commutativity of the underlying maps. This instance can be helpful if you define `Sₘ := Localization (Algebra.algebraMapSubmonoid S M)`, however we will instead use the hypotheses `[Algebra Rₘ Sₘ] [IsScalarTower R Rₘ Sₘ]` in lemmas since the algebra structure may arise in different ways. -/ noncomputable def localizationAlgebra : Algebra Rₘ Sₘ := (map Sₘ (algebraMap R S) (show _ ≤ (Algebra.algebraMapSubmonoid S M).comap _ from M.le_comap_map) : Rₘ →+* Sₘ).toAlgebra end section variable [Algebra Rₘ Sₘ] [Algebra R Sₘ] [IsScalarTower R Rₘ Sₘ] [IsScalarTower R S Sₘ] variable (S Rₘ Sₘ) theorem IsLocalization.map_units_map_submonoid (y : M) : IsUnit (algebraMap R Sₘ y) := by rw [IsScalarTower.algebraMap_apply _ S] exact IsLocalization.map_units Sₘ ⟨algebraMap R S y, Algebra.mem_algebraMapSubmonoid_of_mem y⟩ -- can't be simp, as `S` only appears on the RHS theorem IsLocalization.algebraMap_mk' (x : R) (y : M) : algebraMap Rₘ Sₘ (IsLocalization.mk' Rₘ x y) = IsLocalization.mk' Sₘ (algebraMap R S x) ⟨algebraMap R S y, Algebra.mem_algebraMapSubmonoid_of_mem y⟩ := by rw [IsLocalization.eq_mk'_iff_mul_eq, Subtype.coe_mk, ← IsScalarTower.algebraMap_apply, ← IsScalarTower.algebraMap_apply, IsScalarTower.algebraMap_apply R Rₘ Sₘ, IsScalarTower.algebraMap_apply R Rₘ Sₘ, ← map_mul, mul_comm, IsLocalization.mul_mk'_eq_mk'_of_mul] exact congr_arg (algebraMap Rₘ Sₘ) (IsLocalization.mk'_mul_cancel_left x y) variable (M) /-- If the square below commutes, the bottom map is uniquely specified: ``` R → S ↓ ↓ Rₘ → Sₘ ``` -/ theorem IsLocalization.algebraMap_eq_map_map_submonoid : algebraMap Rₘ Sₘ = map Sₘ (algebraMap R S) (show _ ≤ (Algebra.algebraMapSubmonoid S M).comap _ from M.le_comap_map) := Eq.symm <| IsLocalization.map_unique _ (algebraMap Rₘ Sₘ) fun x => by rw [← IsScalarTower.algebraMap_apply R S Sₘ, ← IsScalarTower.algebraMap_apply R Rₘ Sₘ] /-- If the square below commutes, the bottom map is uniquely specified: ``` R → S ↓ ↓ Rₘ → Sₘ ``` -/ theorem IsLocalization.algebraMap_apply_eq_map_map_submonoid (x) : algebraMap Rₘ Sₘ x = map Sₘ (algebraMap R S) (show _ ≤ (Algebra.algebraMapSubmonoid S M).comap _ from M.le_comap_map) x := DFunLike.congr_fun (IsLocalization.algebraMap_eq_map_map_submonoid _ _ _ _) x theorem IsLocalization.lift_algebraMap_eq_algebraMap : IsLocalization.lift (M := M) (IsLocalization.map_units_map_submonoid S Sₘ) = algebraMap Rₘ Sₘ := IsLocalization.lift_unique _ fun _ => (IsScalarTower.algebraMap_apply _ _ _ _).symm end variable (Rₘ Sₘ) theorem localizationAlgebraMap_def : @algebraMap Rₘ Sₘ _ _ (localizationAlgebra M S) = map Sₘ (algebraMap R S) (show _ ≤ (Algebra.algebraMapSubmonoid S M).comap _ from M.le_comap_map) := rfl /-- Injectivity of the underlying `algebraMap` descends to the algebra induced by localization. -/ theorem localizationAlgebra_injective (hRS : Function.Injective (algebraMap R S)) : Function.Injective (@algebraMap Rₘ Sₘ _ _ (localizationAlgebra M S)) := have : IsLocalization (M.map (algebraMap R S)) Sₘ := i IsLocalization.map_injective_of_injective _ _ _ hRS end Algebra end CommRing
Mathlib/RingTheory/Localization/Basic.lean
1,093
1,095
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Wrenna Robson -/ import Mathlib.Algebra.BigOperators.Group.Finset.Pi import Mathlib.Algebra.Polynomial.FieldDivision import Mathlib.LinearAlgebra.Vandermonde import Mathlib.RingTheory.Polynomial.Basic /-! # Lagrange interpolation ## Main definitions * In everything that follows, `s : Finset ι` is a finite set of indexes, with `v : ι → F` an indexing of the field over some type. We call the image of v on s the interpolation nodes, though strictly unique nodes are only defined when v is injective on s. * `Lagrange.basisDivisor x y`, with `x y : F`. These are the normalised irreducible factors of the Lagrange basis polynomials. They evaluate to `1` at `x` and `0` at `y` when `x` and `y` are distinct. * `Lagrange.basis v i` with `i : ι`: the Lagrange basis polynomial that evaluates to `1` at `v i` and `0` at `v j` for `i ≠ j`. * `Lagrange.interpolate v r` where `r : ι → F` is a function from the fintype to the field: the Lagrange interpolant that evaluates to `r i` at `x i` for all `i : ι`. The `r i` are the _values_ associated with the _nodes_`x i`. -/ open Polynomial section PolynomialDetermination namespace Polynomial variable {R : Type*} [CommRing R] [IsDomain R] {f g : R[X]} section Finset open Function Fintype open scoped Finset variable (s : Finset R) theorem eq_zero_of_degree_lt_of_eval_finset_eq_zero (degree_f_lt : f.degree < #s) (eval_f : ∀ x ∈ s, f.eval x = 0) : f = 0 := by rw [← mem_degreeLT] at degree_f_lt simp_rw [eval_eq_sum_degreeLTEquiv degree_f_lt] at eval_f rw [← degreeLTEquiv_eq_zero_iff_eq_zero degree_f_lt] exact Matrix.eq_zero_of_forall_index_sum_mul_pow_eq_zero (Injective.comp (Embedding.subtype _).inj' (equivFinOfCardEq (card_coe _)).symm.injective) fun _ => eval_f _ (Finset.coe_mem _) theorem eq_of_degree_sub_lt_of_eval_finset_eq (degree_fg_lt : (f - g).degree < #s) (eval_fg : ∀ x ∈ s, f.eval x = g.eval x) : f = g := by rw [← sub_eq_zero] refine eq_zero_of_degree_lt_of_eval_finset_eq_zero _ degree_fg_lt ?_ simp_rw [eval_sub, sub_eq_zero] exact eval_fg theorem eq_of_degrees_lt_of_eval_finset_eq (degree_f_lt : f.degree < #s) (degree_g_lt : g.degree < #s) (eval_fg : ∀ x ∈ s, f.eval x = g.eval x) : f = g := by rw [← mem_degreeLT] at degree_f_lt degree_g_lt refine eq_of_degree_sub_lt_of_eval_finset_eq _ ?_ eval_fg rw [← mem_degreeLT]; exact Submodule.sub_mem _ degree_f_lt degree_g_lt /-- Two polynomials, with the same degree and leading coefficient, which have the same evaluation on a set of distinct values with cardinality equal to the degree, are equal. -/ theorem eq_of_degree_le_of_eval_finset_eq (h_deg_le : f.degree ≤ #s) (h_deg_eq : f.degree = g.degree) (hlc : f.leadingCoeff = g.leadingCoeff) (h_eval : ∀ x ∈ s, f.eval x = g.eval x) : f = g := by rcases eq_or_ne f 0 with rfl | hf · rwa [degree_zero, eq_comm, degree_eq_bot, eq_comm] at h_deg_eq · exact eq_of_degree_sub_lt_of_eval_finset_eq s (lt_of_lt_of_le (degree_sub_lt h_deg_eq hf hlc) h_deg_le) h_eval end Finset section Indexed open Finset variable {ι : Type*} {v : ι → R} (s : Finset ι) theorem eq_zero_of_degree_lt_of_eval_index_eq_zero (hvs : Set.InjOn v s) (degree_f_lt : f.degree < #s) (eval_f : ∀ i ∈ s, f.eval (v i) = 0) : f = 0 := by classical rw [← card_image_of_injOn hvs] at degree_f_lt refine eq_zero_of_degree_lt_of_eval_finset_eq_zero _ degree_f_lt ?_ intro x hx rcases mem_image.mp hx with ⟨_, hj, rfl⟩ exact eval_f _ hj theorem eq_of_degree_sub_lt_of_eval_index_eq (hvs : Set.InjOn v s) (degree_fg_lt : (f - g).degree < #s) (eval_fg : ∀ i ∈ s, f.eval (v i) = g.eval (v i)) : f = g := by rw [← sub_eq_zero] refine eq_zero_of_degree_lt_of_eval_index_eq_zero _ hvs degree_fg_lt ?_ simp_rw [eval_sub, sub_eq_zero] exact eval_fg theorem eq_of_degrees_lt_of_eval_index_eq (hvs : Set.InjOn v s) (degree_f_lt : f.degree < #s) (degree_g_lt : g.degree < #s) (eval_fg : ∀ i ∈ s, f.eval (v i) = g.eval (v i)) : f = g := by refine eq_of_degree_sub_lt_of_eval_index_eq _ hvs ?_ eval_fg rw [← mem_degreeLT] at degree_f_lt degree_g_lt ⊢ exact Submodule.sub_mem _ degree_f_lt degree_g_lt theorem eq_of_degree_le_of_eval_index_eq (hvs : Set.InjOn v s) (h_deg_le : f.degree ≤ #s) (h_deg_eq : f.degree = g.degree) (hlc : f.leadingCoeff = g.leadingCoeff) (h_eval : ∀ i ∈ s, f.eval (v i) = g.eval (v i)) : f = g := by rcases eq_or_ne f 0 with rfl | hf · rwa [degree_zero, eq_comm, degree_eq_bot, eq_comm] at h_deg_eq · exact eq_of_degree_sub_lt_of_eval_index_eq s hvs (lt_of_lt_of_le (degree_sub_lt h_deg_eq hf hlc) h_deg_le) h_eval end Indexed end Polynomial end PolynomialDetermination noncomputable section namespace Lagrange open Polynomial section BasisDivisor variable {F : Type*} [Field F] variable {x y : F} /-- `basisDivisor x y` is the unique linear or constant polynomial such that when evaluated at `x` it gives `1` and `y` it gives `0` (where when `x = y` it is identically `0`). Such polynomials are the building blocks for the Lagrange interpolants. -/ def basisDivisor (x y : F) : F[X] := C (x - y)⁻¹ * (X - C y) theorem basisDivisor_self : basisDivisor x x = 0 := by simp only [basisDivisor, sub_self, inv_zero, map_zero, zero_mul] theorem basisDivisor_inj (hxy : basisDivisor x y = 0) : x = y := by simp_rw [basisDivisor, mul_eq_zero, X_sub_C_ne_zero, or_false, C_eq_zero, inv_eq_zero, sub_eq_zero] at hxy exact hxy @[simp] theorem basisDivisor_eq_zero_iff : basisDivisor x y = 0 ↔ x = y := ⟨basisDivisor_inj, fun H => H ▸ basisDivisor_self⟩ theorem basisDivisor_ne_zero_iff : basisDivisor x y ≠ 0 ↔ x ≠ y := by rw [Ne, basisDivisor_eq_zero_iff] theorem degree_basisDivisor_of_ne (hxy : x ≠ y) : (basisDivisor x y).degree = 1 := by rw [basisDivisor, degree_mul, degree_X_sub_C, degree_C, zero_add] exact inv_ne_zero (sub_ne_zero_of_ne hxy) @[simp] theorem degree_basisDivisor_self : (basisDivisor x x).degree = ⊥ := by rw [basisDivisor_self, degree_zero] theorem natDegree_basisDivisor_self : (basisDivisor x x).natDegree = 0 := by rw [basisDivisor_self, natDegree_zero] theorem natDegree_basisDivisor_of_ne (hxy : x ≠ y) : (basisDivisor x y).natDegree = 1 := natDegree_eq_of_degree_eq_some (degree_basisDivisor_of_ne hxy) @[simp] theorem eval_basisDivisor_right : eval y (basisDivisor x y) = 0 := by simp only [basisDivisor, eval_mul, eval_C, eval_sub, eval_X, sub_self, mul_zero] theorem eval_basisDivisor_left_of_ne (hxy : x ≠ y) : eval x (basisDivisor x y) = 1 := by simp only [basisDivisor, eval_mul, eval_C, eval_sub, eval_X] exact inv_mul_cancel₀ (sub_ne_zero_of_ne hxy) end BasisDivisor section Basis variable {F : Type*} [Field F] {ι : Type*} [DecidableEq ι] variable {s : Finset ι} {v : ι → F} {i j : ι} open Finset /-- Lagrange basis polynomials indexed by `s : Finset ι`, defined at nodes `v i` for a map `v : ι → F`. For `i, j ∈ s`, `basis s v i` evaluates to 0 at `v j` for `i ≠ j`. When `v` is injective on `s`, `basis s v i` evaluates to 1 at `v i`. -/ protected def basis (s : Finset ι) (v : ι → F) (i : ι) : F[X] := ∏ j ∈ s.erase i, basisDivisor (v i) (v j) @[simp] theorem basis_empty : Lagrange.basis ∅ v i = 1 := rfl @[simp] theorem basis_singleton (i : ι) : Lagrange.basis {i} v i = 1 := by rw [Lagrange.basis, erase_singleton, prod_empty] @[simp] theorem basis_pair_left (hij : i ≠ j) : Lagrange.basis {i, j} v i = basisDivisor (v i) (v j) := by simp only [Lagrange.basis, hij, erase_insert_eq_erase, erase_eq_of_not_mem, mem_singleton, not_false_iff, prod_singleton] @[simp] theorem basis_pair_right (hij : i ≠ j) : Lagrange.basis {i, j} v j = basisDivisor (v j) (v i) := by rw [pair_comm] exact basis_pair_left hij.symm theorem basis_ne_zero (hvs : Set.InjOn v s) (hi : i ∈ s) : Lagrange.basis s v i ≠ 0 := by simp_rw [Lagrange.basis, prod_ne_zero_iff, Ne, mem_erase] rintro j ⟨hij, hj⟩ rw [basisDivisor_eq_zero_iff, hvs.eq_iff hi hj] exact hij.symm @[simp] theorem eval_basis_self (hvs : Set.InjOn v s) (hi : i ∈ s) : (Lagrange.basis s v i).eval (v i) = 1 := by rw [Lagrange.basis, eval_prod] refine prod_eq_one fun j H => ?_ rw [eval_basisDivisor_left_of_ne] rcases mem_erase.mp H with ⟨hij, hj⟩ exact mt (hvs hi hj) hij.symm @[simp] theorem eval_basis_of_ne (hij : i ≠ j) (hj : j ∈ s) : (Lagrange.basis s v i).eval (v j) = 0 := by simp_rw [Lagrange.basis, eval_prod, prod_eq_zero_iff] exact ⟨j, ⟨mem_erase.mpr ⟨hij.symm, hj⟩, eval_basisDivisor_right⟩⟩ @[simp] theorem natDegree_basis (hvs : Set.InjOn v s) (hi : i ∈ s) : (Lagrange.basis s v i).natDegree = #s - 1 := by have H : ∀ j, j ∈ s.erase i → basisDivisor (v i) (v j) ≠ 0 := by simp_rw [Ne, mem_erase, basisDivisor_eq_zero_iff] exact fun j ⟨hij₁, hj⟩ hij₂ => hij₁ (hvs hj hi hij₂.symm) rw [← card_erase_of_mem hi, card_eq_sum_ones] convert natDegree_prod _ _ H using 1 refine sum_congr rfl fun j hj => (natDegree_basisDivisor_of_ne ?_).symm rw [Ne, ← basisDivisor_eq_zero_iff] exact H _ hj theorem degree_basis (hvs : Set.InjOn v s) (hi : i ∈ s) : (Lagrange.basis s v i).degree = ↑(#s - 1) := by rw [degree_eq_natDegree (basis_ne_zero hvs hi), natDegree_basis hvs hi] theorem sum_basis (hvs : Set.InjOn v s) (hs : s.Nonempty) : ∑ j ∈ s, Lagrange.basis s v j = 1 := by refine eq_of_degrees_lt_of_eval_index_eq s hvs (lt_of_le_of_lt (degree_sum_le _ _) ?_) ?_ ?_ · rw [Nat.cast_withBot, Finset.sup_lt_iff (WithBot.bot_lt_coe #s)] intro i hi rw [degree_basis hvs hi, Nat.cast_withBot, WithBot.coe_lt_coe] exact Nat.pred_lt (card_ne_zero_of_mem hi) · rw [degree_one, ← WithBot.coe_zero, Nat.cast_withBot, WithBot.coe_lt_coe] exact Nonempty.card_pos hs · intro i hi rw [eval_finset_sum, eval_one, ← add_sum_erase _ _ hi, eval_basis_self hvs hi, add_eq_left] refine sum_eq_zero fun j hj => ?_ rcases mem_erase.mp hj with ⟨hij, _⟩ rw [eval_basis_of_ne hij hi] theorem basisDivisor_add_symm {x y : F} (hxy : x ≠ y) : basisDivisor x y + basisDivisor y x = 1 := by classical rw [← sum_basis Function.injective_id.injOn ⟨x, mem_insert_self _ {y}⟩, sum_insert (not_mem_singleton.mpr hxy), sum_singleton, basis_pair_left hxy, basis_pair_right hxy, id, id] end Basis section Interpolate variable {F : Type*} [Field F] {ι : Type*} [DecidableEq ι] variable {s t : Finset ι} {i j : ι} {v : ι → F} (r r' : ι → F) open Finset /-- Lagrange interpolation: given a finset `s : Finset ι`, a nodal map `v : ι → F` injective on `s` and a value function `r : ι → F`, `interpolate s v r` is the unique polynomial of degree `< #s` that takes value `r i` on `v i` for all `i` in `s`. -/ @[simps] def interpolate (s : Finset ι) (v : ι → F) : (ι → F) →ₗ[F] F[X] where toFun r := ∑ i ∈ s, C (r i) * Lagrange.basis s v i map_add' f g := by simp_rw [← Finset.sum_add_distrib] have h : (fun x => C (f x) * Lagrange.basis s v x + C (g x) * Lagrange.basis s v x) = (fun x => C ((f + g) x) * Lagrange.basis s v x) := by simp_rw [← add_mul, ← C_add, Pi.add_apply] rw [h] map_smul' c f := by simp_rw [Finset.smul_sum, C_mul', smul_smul, Pi.smul_apply, RingHom.id_apply, smul_eq_mul] theorem interpolate_empty : interpolate ∅ v r = 0 := by rw [interpolate_apply, sum_empty] theorem interpolate_singleton : interpolate {i} v r = C (r i) := by rw [interpolate_apply, sum_singleton, basis_singleton, mul_one] theorem interpolate_one (hvs : Set.InjOn v s) (hs : s.Nonempty) : interpolate s v 1 = 1 := by simp_rw [interpolate_apply, Pi.one_apply, map_one, one_mul] exact sum_basis hvs hs theorem eval_interpolate_at_node (hvs : Set.InjOn v s) (hi : i ∈ s) : eval (v i) (interpolate s v r) = r i := by rw [interpolate_apply, eval_finset_sum, ← add_sum_erase _ _ hi] simp_rw [eval_mul, eval_C, eval_basis_self hvs hi, mul_one, add_eq_left] refine sum_eq_zero fun j H => ?_ rw [eval_basis_of_ne (mem_erase.mp H).1 hi, mul_zero] theorem degree_interpolate_le (hvs : Set.InjOn v s) : (interpolate s v r).degree ≤ ↑(#s - 1) := by refine (degree_sum_le _ _).trans ?_ rw [Finset.sup_le_iff] intro i hi rw [degree_mul, degree_basis hvs hi] by_cases hr : r i = 0 · simpa only [hr, map_zero, degree_zero, WithBot.bot_add] using bot_le · rw [degree_C hr, zero_add] theorem degree_interpolate_lt (hvs : Set.InjOn v s) : (interpolate s v r).degree < #s := by rw [Nat.cast_withBot] rcases eq_empty_or_nonempty s with (rfl | h) · rw [interpolate_empty, degree_zero, card_empty] exact WithBot.bot_lt_coe _ · refine lt_of_le_of_lt (degree_interpolate_le _ hvs) ?_ rw [Nat.cast_withBot, WithBot.coe_lt_coe] exact Nat.sub_lt (Nonempty.card_pos h) zero_lt_one theorem degree_interpolate_erase_lt (hvs : Set.InjOn v s) (hi : i ∈ s) : (interpolate (s.erase i) v r).degree < ↑(#s - 1) := by rw [← Finset.card_erase_of_mem hi] exact degree_interpolate_lt _ (Set.InjOn.mono (coe_subset.mpr (erase_subset _ _)) hvs) theorem values_eq_on_of_interpolate_eq (hvs : Set.InjOn v s) (hrr' : interpolate s v r = interpolate s v r') : ∀ i ∈ s, r i = r' i := fun _ hi => by rw [← eval_interpolate_at_node r hvs hi, hrr', eval_interpolate_at_node r' hvs hi] theorem interpolate_eq_of_values_eq_on (hrr' : ∀ i ∈ s, r i = r' i) : interpolate s v r = interpolate s v r' := sum_congr rfl fun i hi => by rw [hrr' _ hi] theorem interpolate_eq_iff_values_eq_on (hvs : Set.InjOn v s) : interpolate s v r = interpolate s v r' ↔ ∀ i ∈ s, r i = r' i := ⟨values_eq_on_of_interpolate_eq _ _ hvs, interpolate_eq_of_values_eq_on _ _⟩ theorem eq_interpolate {f : F[X]} (hvs : Set.InjOn v s) (degree_f_lt : f.degree < #s) : f = interpolate s v fun i => f.eval (v i) := eq_of_degrees_lt_of_eval_index_eq _ hvs degree_f_lt (degree_interpolate_lt _ hvs) fun _ hi => (eval_interpolate_at_node (fun x ↦ eval (v x) f) hvs hi).symm theorem eq_interpolate_of_eval_eq {f : F[X]} (hvs : Set.InjOn v s) (degree_f_lt : f.degree < #s) (eval_f : ∀ i ∈ s, f.eval (v i) = r i) : f = interpolate s v r := by rw [eq_interpolate hvs degree_f_lt] exact interpolate_eq_of_values_eq_on _ _ eval_f /-- This is the characteristic property of the interpolation: the interpolation is the unique polynomial of `degree < Fintype.card ι` which takes the value of the `r i` on the `v i`. -/ theorem eq_interpolate_iff {f : F[X]} (hvs : Set.InjOn v s) : (f.degree < #s ∧ ∀ i ∈ s, eval (v i) f = r i) ↔ f = interpolate s v r := by constructor <;> intro h · exact eq_interpolate_of_eval_eq _ hvs h.1 h.2 · rw [h] exact ⟨degree_interpolate_lt _ hvs, fun _ hi => eval_interpolate_at_node _ hvs hi⟩ /-- Lagrange interpolation induces isomorphism between functions from `s` and polynomials of degree less than `Fintype.card ι`. -/ def funEquivDegreeLT (hvs : Set.InjOn v s) : degreeLT F #s ≃ₗ[F] s → F where toFun f i := f.1.eval (v i) map_add' _ _ := funext fun _ => eval_add map_smul' c f := funext <| by simp invFun r := ⟨interpolate s v fun x => if hx : x ∈ s then r ⟨x, hx⟩ else 0, mem_degreeLT.2 <| degree_interpolate_lt _ hvs⟩ left_inv := by rintro ⟨f, hf⟩ simp only [Subtype.mk_eq_mk, Subtype.coe_mk, dite_eq_ite] rw [mem_degreeLT] at hf conv => rhs; rw [eq_interpolate hvs hf] exact interpolate_eq_of_values_eq_on _ _ fun _ hi => if_pos hi right_inv := by intro f ext ⟨i, hi⟩ simp only [Subtype.coe_mk, eval_interpolate_at_node _ hvs hi] exact dif_pos hi theorem interpolate_eq_sum_interpolate_insert_sdiff (hvt : Set.InjOn v t) (hs : s.Nonempty) (hst : s ⊆ t) : interpolate t v r = ∑ i ∈ s, interpolate (insert i (t \ s)) v r * Lagrange.basis s v i := by symm refine eq_interpolate_of_eval_eq _ hvt (lt_of_le_of_lt (degree_sum_le _ _) ?_) fun i hi => ?_ · simp_rw [Nat.cast_withBot, Finset.sup_lt_iff (WithBot.bot_lt_coe #t), degree_mul] intro i hi have hs : 1 ≤ #s := Nonempty.card_pos ⟨_, hi⟩ have hst' : #s ≤ #t := card_le_card hst have H : #t = 1 + (#t - #s) + (#s - 1) := by rw [add_assoc, tsub_add_tsub_cancel hst' hs, ← add_tsub_assoc_of_le (hs.trans hst'),
Nat.succ_add_sub_one, zero_add] rw [degree_basis (Set.InjOn.mono hst hvt) hi, H, WithBot.coe_add, Nat.cast_withBot, WithBot.add_lt_add_iff_right (@WithBot.coe_ne_bot _ (#s - 1))] convert degree_interpolate_lt _
Mathlib/LinearAlgebra/Lagrange.lean
403
406
/- Copyright (c) 2019 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov, Sébastien Gouëzel, Rémy Degenne -/ import Mathlib.Analysis.Convex.Jensen import Mathlib.Analysis.Convex.Mul import Mathlib.Analysis.Convex.SpecificFunctions.Basic import Mathlib.Analysis.SpecialFunctions.Pow.NNReal /-! # Mean value inequalities In this file we prove several mean inequalities for finite sums. Versions for integrals of some of these inequalities are available in `MeasureTheory.MeanInequalities`. ## Main theorems: generalized mean inequality The inequality says that for two non-negative vectors $w$ and $z$ with $\sum_{i\in s} w_i=1$ and $p ≤ q$ we have $$ \sqrt[p]{\sum_{i\in s} w_i z_i^p} ≤ \sqrt[q]{\sum_{i\in s} w_i z_i^q}. $$ Currently we only prove this inequality for $p=1$. As in the rest of `Mathlib`, we provide different theorems for natural exponents (`pow_arith_mean_le_arith_mean_pow`), integer exponents (`zpow_arith_mean_le_arith_mean_zpow`), and real exponents (`rpow_arith_mean_le_arith_mean_rpow` and `arith_mean_le_rpow_mean`). In the first two cases we prove $$ \left(\sum_{i\in s} w_i z_i\right)^n ≤ \sum_{i\in s} w_i z_i^n $$ in order to avoid using real exponents. For real exponents we prove both this and standard versions. ## TODO - each inequality `A ≤ B` should come with a theorem `A = B ↔ _`; one of the ways to prove them is to define `StrictConvexOn` functions. - generalized mean inequality with any `p ≤ q`, including negative numbers; - prove that the power mean tends to the geometric mean as the exponent tends to zero. -/ universe u v open Finset NNReal ENNReal noncomputable section variable {ι : Type u} (s : Finset ι) namespace Real theorem pow_arith_mean_le_arith_mean_pow (w z : ι → ℝ) (hw : ∀ i ∈ s, 0 ≤ w i) (hw' : ∑ i ∈ s, w i = 1) (hz : ∀ i ∈ s, 0 ≤ z i) (n : ℕ) : (∑ i ∈ s, w i * z i) ^ n ≤ ∑ i ∈ s, w i * z i ^ n := (convexOn_pow n).map_sum_le hw hw' hz theorem pow_arith_mean_le_arith_mean_pow_of_even (w z : ι → ℝ) (hw : ∀ i ∈ s, 0 ≤ w i) (hw' : ∑ i ∈ s, w i = 1) {n : ℕ} (hn : Even n) : (∑ i ∈ s, w i * z i) ^ n ≤ ∑ i ∈ s, w i * z i ^ n := hn.convexOn_pow.map_sum_le hw hw' fun _ _ => Set.mem_univ _ theorem zpow_arith_mean_le_arith_mean_zpow (w z : ι → ℝ) (hw : ∀ i ∈ s, 0 ≤ w i) (hw' : ∑ i ∈ s, w i = 1) (hz : ∀ i ∈ s, 0 < z i) (m : ℤ) : (∑ i ∈ s, w i * z i) ^ m ≤ ∑ i ∈ s, w i * z i ^ m := (convexOn_zpow m).map_sum_le hw hw' hz theorem rpow_arith_mean_le_arith_mean_rpow (w z : ι → ℝ) (hw : ∀ i ∈ s, 0 ≤ w i) (hw' : ∑ i ∈ s, w i = 1) (hz : ∀ i ∈ s, 0 ≤ z i) {p : ℝ} (hp : 1 ≤ p) : (∑ i ∈ s, w i * z i) ^ p ≤ ∑ i ∈ s, w i * z i ^ p := (convexOn_rpow hp).map_sum_le hw hw' hz theorem arith_mean_le_rpow_mean (w z : ι → ℝ) (hw : ∀ i ∈ s, 0 ≤ w i) (hw' : ∑ i ∈ s, w i = 1) (hz : ∀ i ∈ s, 0 ≤ z i) {p : ℝ} (hp : 1 ≤ p) : ∑ i ∈ s, w i * z i ≤ (∑ i ∈ s, w i * z i ^ p) ^ (1 / p) := by have : 0 < p := by positivity rw [← rpow_le_rpow_iff _ _ this, ← rpow_mul, one_div_mul_cancel (ne_of_gt this), rpow_one] · exact rpow_arith_mean_le_arith_mean_rpow s w z hw hw' hz hp all_goals apply_rules [sum_nonneg, rpow_nonneg] intro i hi apply_rules [mul_nonneg, rpow_nonneg, hw i hi, hz i hi] end Real namespace NNReal /-- Weighted generalized mean inequality, version sums over finite sets, with `ℝ≥0`-valued functions and natural exponent. -/ theorem pow_arith_mean_le_arith_mean_pow (w z : ι → ℝ≥0) (hw' : ∑ i ∈ s, w i = 1) (n : ℕ) : (∑ i ∈ s, w i * z i) ^ n ≤ ∑ i ∈ s, w i * z i ^ n := mod_cast Real.pow_arith_mean_le_arith_mean_pow s _ _ (fun i _ => (w i).coe_nonneg) (mod_cast hw') (fun i _ => (z i).coe_nonneg) n /-- Weighted generalized mean inequality, version for sums over finite sets, with `ℝ≥0`-valued functions and real exponents. -/ theorem rpow_arith_mean_le_arith_mean_rpow (w z : ι → ℝ≥0) (hw' : ∑ i ∈ s, w i = 1) {p : ℝ} (hp : 1 ≤ p) : (∑ i ∈ s, w i * z i) ^ p ≤ ∑ i ∈ s, w i * z i ^ p := mod_cast Real.rpow_arith_mean_le_arith_mean_rpow s _ _ (fun i _ => (w i).coe_nonneg) (mod_cast hw') (fun i _ => (z i).coe_nonneg) hp /-- Weighted generalized mean inequality, version for two elements of `ℝ≥0` and real exponents. -/ theorem rpow_arith_mean_le_arith_mean2_rpow (w₁ w₂ z₁ z₂ : ℝ≥0) (hw' : w₁ + w₂ = 1) {p : ℝ} (hp : 1 ≤ p) : (w₁ * z₁ + w₂ * z₂) ^ p ≤ w₁ * z₁ ^ p + w₂ * z₂ ^ p := by have h := rpow_arith_mean_le_arith_mean_rpow univ ![w₁, w₂] ![z₁, z₂] ?_ hp · simpa [Fin.sum_univ_succ] using h · simp [hw', Fin.sum_univ_succ] /-- Unweighted mean inequality, version for two elements of `ℝ≥0` and real exponents. -/ theorem rpow_add_le_mul_rpow_add_rpow (z₁ z₂ : ℝ≥0) {p : ℝ} (hp : 1 ≤ p) : (z₁ + z₂) ^ p ≤ (2 : ℝ≥0) ^ (p - 1) * (z₁ ^ p + z₂ ^ p) := by rcases eq_or_lt_of_le hp with (rfl | h'p) · simp only [rpow_one, sub_self, rpow_zero, one_mul]; rfl convert rpow_arith_mean_le_arith_mean2_rpow (1 / 2) (1 / 2) (2 * z₁) (2 * z₂) (add_halves 1) hp using 1 · simp only [one_div, inv_mul_cancel_left₀, Ne, mul_eq_zero, two_ne_zero, one_ne_zero, not_false_iff] · have A : p - 1 ≠ 0 := ne_of_gt (sub_pos.2 h'p) simp only [mul_rpow, rpow_sub' A, div_eq_inv_mul, rpow_one, mul_one] ring /-- Weighted generalized mean inequality, version for sums over finite sets, with `ℝ≥0`-valued functions and real exponents. -/ theorem arith_mean_le_rpow_mean (w z : ι → ℝ≥0) (hw' : ∑ i ∈ s, w i = 1) {p : ℝ} (hp : 1 ≤ p) : ∑ i ∈ s, w i * z i ≤ (∑ i ∈ s, w i * z i ^ p) ^ (1 / p) := mod_cast Real.arith_mean_le_rpow_mean s _ _ (fun i _ => (w i).coe_nonneg) (mod_cast hw') (fun i _ => (z i).coe_nonneg) hp private theorem add_rpow_le_one_of_add_le_one {p : ℝ} (a b : ℝ≥0) (hab : a + b ≤ 1) (hp1 : 1 ≤ p) : a ^ p + b ^ p ≤ 1 := by have h_le_one : ∀ x : ℝ≥0, x ≤ 1 → x ^ p ≤ x := fun x hx => rpow_le_self_of_le_one hx hp1 have ha : a ≤ 1 := (self_le_add_right a b).trans hab have hb : b ≤ 1 := (self_le_add_left b a).trans hab exact (add_le_add (h_le_one a ha) (h_le_one b hb)).trans hab theorem add_rpow_le_rpow_add {p : ℝ} (a b : ℝ≥0) (hp1 : 1 ≤ p) : a ^ p + b ^ p ≤ (a + b) ^ p := by have hp_pos : 0 < p := by positivity by_cases h_zero : a + b = 0 · simp [add_eq_zero.mp h_zero, hp_pos.ne'] have h_nonzero : ¬(a = 0 ∧ b = 0) := by rwa [add_eq_zero] at h_zero have h_add : a / (a + b) + b / (a + b) = 1 := by rw [div_add_div_same, div_self h_zero] have h := add_rpow_le_one_of_add_le_one (a / (a + b)) (b / (a + b)) h_add.le hp1 rw [div_rpow a (a + b), div_rpow b (a + b)] at h have hab_0 : (a + b) ^ p ≠ 0 := by simp [hp_pos, h_nonzero] have hab_0' : 0 < (a + b) ^ p := zero_lt_iff.mpr hab_0 have h_mul : (a + b) ^ p * (a ^ p / (a + b) ^ p + b ^ p / (a + b) ^ p) ≤ (a + b) ^ p := by nth_rw 4 [← mul_one ((a + b) ^ p)] exact (mul_le_mul_left hab_0').mpr h rwa [div_eq_mul_inv, div_eq_mul_inv, mul_add, mul_comm (a ^ p), mul_comm (b ^ p), ← mul_assoc, ← mul_assoc, mul_inv_cancel₀ hab_0, one_mul, one_mul] at h_mul theorem rpow_add_rpow_le_add {p : ℝ} (a b : ℝ≥0) (hp1 : 1 ≤ p) : (a ^ p + b ^ p) ^ (1 / p) ≤ a + b := by rw [one_div] rw [← @NNReal.le_rpow_inv_iff _ _ p⁻¹ (by simp [lt_of_lt_of_le zero_lt_one hp1])] rw [inv_inv] exact add_rpow_le_rpow_add _ _ hp1 theorem rpow_add_rpow_le {p q : ℝ} (a b : ℝ≥0) (hp_pos : 0 < p) (hpq : p ≤ q) : (a ^ q + b ^ q) ^ (1 / q) ≤ (a ^ p + b ^ p) ^ (1 / p) := by have h_rpow : ∀ a : ℝ≥0, a ^ q = (a ^ p) ^ (q / p) := fun a => by rw [← NNReal.rpow_mul, div_eq_inv_mul, ← mul_assoc, mul_inv_cancel₀ hp_pos.ne.symm, one_mul] have h_rpow_add_rpow_le_add : ((a ^ p) ^ (q / p) + (b ^ p) ^ (q / p)) ^ (1 / (q / p)) ≤ a ^ p + b ^ p := by refine rpow_add_rpow_le_add (a ^ p) (b ^ p) ?_ rwa [one_le_div hp_pos] rw [h_rpow a, h_rpow b, one_div p, NNReal.le_rpow_inv_iff hp_pos, ← NNReal.rpow_mul, mul_comm, mul_one_div] rwa [one_div_div] at h_rpow_add_rpow_le_add theorem rpow_add_le_add_rpow {p : ℝ} (a b : ℝ≥0) (hp : 0 ≤ p) (hp1 : p ≤ 1) : (a + b) ^ p ≤ a ^ p + b ^ p := by rcases hp.eq_or_lt with (rfl | hp_pos) · simp have h := rpow_add_rpow_le a b hp_pos hp1 rw [one_div_one, one_div] at h repeat' rw [NNReal.rpow_one] at h exact (NNReal.le_rpow_inv_iff hp_pos).mp h end NNReal namespace Real lemma add_rpow_le_rpow_add {p : ℝ} {a b : ℝ} (ha : 0 ≤ a) (hb : 0 ≤ b) (hp1 : 1 ≤ p) : a ^ p + b ^ p ≤ (a + b) ^ p := by lift a to NNReal using ha lift b to NNReal using hb exact_mod_cast NNReal.add_rpow_le_rpow_add a b hp1 lemma rpow_add_rpow_le_add {p : ℝ} {a b : ℝ} (ha : 0 ≤ a) (hb : 0 ≤ b) (hp1 : 1 ≤ p) : (a ^ p + b ^ p) ^ (1 / p) ≤ a + b := by lift a to NNReal using ha lift b to NNReal using hb exact_mod_cast NNReal.rpow_add_rpow_le_add a b hp1 lemma rpow_add_rpow_le {p q : ℝ} {a b : ℝ} (ha : 0 ≤ a) (hb : 0 ≤ b) (hp_pos : 0 < p) (hpq : p ≤ q) : (a ^ q + b ^ q) ^ (1 / q) ≤ (a ^ p + b ^ p) ^ (1 / p) := by lift a to NNReal using ha lift b to NNReal using hb exact_mod_cast NNReal.rpow_add_rpow_le a b hp_pos hpq lemma rpow_add_le_add_rpow {p : ℝ} {a b : ℝ} (ha : 0 ≤ a) (hb : 0 ≤ b) (hp : 0 ≤ p) (hp1 : p ≤ 1) : (a + b) ^ p ≤ a ^ p + b ^ p := by lift a to NNReal using ha lift b to NNReal using hb exact_mod_cast NNReal.rpow_add_le_add_rpow a b hp hp1 end Real namespace ENNReal /-- Weighted generalized mean inequality, version for sums over finite sets, with `ℝ≥0∞`-valued functions and real exponents. -/ theorem rpow_arith_mean_le_arith_mean_rpow (w z : ι → ℝ≥0∞) (hw' : ∑ i ∈ s, w i = 1) {p : ℝ} (hp : 1 ≤ p) : (∑ i ∈ s, w i * z i) ^ p ≤ ∑ i ∈ s, w i * z i ^ p := by have hp_pos : 0 < p := by positivity have hp_nonneg : 0 ≤ p := by positivity have hp_not_neg : ¬p < 0 := by simp [hp_nonneg] have h_top_iff_rpow_top : ∀ (i : ι), i ∈ s → (w i * z i = ⊤ ↔ w i * z i ^ p = ⊤) := by simp [ENNReal.mul_eq_top, hp_pos, hp_nonneg, hp_not_neg] refine le_of_top_imp_top_of_toNNReal_le ?_ ?_ · -- first, prove `(∑ i ∈ s, w i * z i) ^ p = ⊤ → ∑ i ∈ s, (w i * z i ^ p) = ⊤` rw [rpow_eq_top_iff, sum_eq_top, sum_eq_top] intro h simp only [and_false, hp_not_neg, false_or] at h
rcases h.left with ⟨a, H, ha⟩ use a, H rwa [← h_top_iff_rpow_top a H] · -- second, suppose both `(∑ i ∈ s, w i * z i) ^ p ≠ ⊤` and `∑ i ∈ s, (w i * z i ^ p) ≠ ⊤`, -- and prove `((∑ i ∈ s, w i * z i) ^ p).toNNReal ≤ (∑ i ∈ s, (w i * z i ^ p)).toNNReal`, -- by using `NNReal.rpow_arith_mean_le_arith_mean_rpow`. intro h_top_rpow_sum _ -- show hypotheses needed to put the `.toNNReal` inside the sums. have h_top : ∀ a : ι, a ∈ s → w a * z a ≠ ⊤ := haveI h_top_sum : ∑ i ∈ s, w i * z i ≠ ⊤ := by intro h rw [h, top_rpow_of_pos hp_pos] at h_top_rpow_sum exact h_top_rpow_sum rfl fun a ha => (lt_top_of_sum_ne_top h_top_sum ha).ne have h_top_rpow : ∀ a : ι, a ∈ s → w a * z a ^ p ≠ ⊤ := by intro i hi specialize h_top i hi rwa [Ne, ← h_top_iff_rpow_top i hi] -- put the `.toNNReal` inside the sums. simp_rw [toNNReal_sum h_top_rpow, toNNReal_rpow, toNNReal_sum h_top, toNNReal_mul, toNNReal_rpow] -- use corresponding nnreal result refine NNReal.rpow_arith_mean_le_arith_mean_rpow s (fun i => (w i).toNNReal) (fun i => (z i).toNNReal) ?_ hp -- verify the hypothesis `∑ i ∈ s, (w i).toNNReal = 1`, using `∑ i ∈ s, w i = 1` . have h_sum_nnreal : ∑ i ∈ s, w i = ↑(∑ i ∈ s, (w i).toNNReal) := by rw [coe_finset_sum] refine sum_congr rfl fun i hi => (coe_toNNReal ?_).symm refine (lt_top_of_sum_ne_top ?_ hi).ne exact hw'.symm ▸ ENNReal.one_ne_top rwa [← coe_inj, ← h_sum_nnreal] /-- Weighted generalized mean inequality, version for two elements of `ℝ≥0∞` and real exponents. -/ theorem rpow_arith_mean_le_arith_mean2_rpow (w₁ w₂ z₁ z₂ : ℝ≥0∞) (hw' : w₁ + w₂ = 1) {p : ℝ} (hp : 1 ≤ p) : (w₁ * z₁ + w₂ * z₂) ^ p ≤ w₁ * z₁ ^ p + w₂ * z₂ ^ p := by have h := rpow_arith_mean_le_arith_mean_rpow univ ![w₁, w₂] ![z₁, z₂] ?_ hp · simpa [Fin.sum_univ_succ] using h · simp [hw', Fin.sum_univ_succ] /-- Unweighted mean inequality, version for two elements of `ℝ≥0∞` and real exponents. -/ theorem rpow_add_le_mul_rpow_add_rpow (z₁ z₂ : ℝ≥0∞) {p : ℝ} (hp : 1 ≤ p) : (z₁ + z₂) ^ p ≤ (2 : ℝ≥0∞) ^ (p - 1) * (z₁ ^ p + z₂ ^ p) := by
Mathlib/Analysis/MeanInequalitiesPow.lean
233
276
/- Copyright (c) 2024 Sophie Morel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sophie Morel -/ import Mathlib.Analysis.NormedSpace.Multilinear.Basic import Mathlib.LinearAlgebra.PiTensorProduct /-! # Projective seminorm on the tensor of a finite family of normed spaces. Let `𝕜` be a nontrivially normed field and `E` be a family of normed `𝕜`-vector spaces `Eᵢ`, indexed by a finite type `ι`. We define a seminorm on `⨂[𝕜] i, Eᵢ`, which we call the "projective seminorm". For `x` an element of `⨂[𝕜] i, Eᵢ`, its projective seminorm is the infimum over all expressions of `x` as `∑ j, ⨂ₜ[𝕜] mⱼ i` (with the `mⱼ` ∈ `Π i, Eᵢ`) of `∑ j, Π i, ‖mⱼ i‖`. In particular, every norm `‖.‖` on `⨂[𝕜] i, Eᵢ` satisfying `‖⨂ₜ[𝕜] i, m i‖ ≤ Π i, ‖m i‖` for every `m` in `Π i, Eᵢ` is bounded above by the projective seminorm. ## Main definitions * `PiTensorProduct.projectiveSeminorm`: The projective seminorm on `⨂[𝕜] i, Eᵢ`. ## Main results * `PiTensorProduct.norm_eval_le_projectiveSeminorm`: If `f` is a continuous multilinear map on `E = Π i, Eᵢ` and `x` is in `⨂[𝕜] i, Eᵢ`, then `‖f.lift x‖ ≤ projectiveSeminorm x * ‖f‖`. ## TODO * If the base field is `ℝ` or `ℂ` (or more generally if the injection of `Eᵢ` into its bidual is an isometry for every `i`), then we have `projectiveSeminorm ⨂ₜ[𝕜] i, mᵢ = Π i, ‖mᵢ‖`. * The functoriality. -/ universe uι u𝕜 uE uF variable {ι : Type uι} [Fintype ι] variable {𝕜 : Type u𝕜} [NontriviallyNormedField 𝕜] variable {E : ι → Type uE} [∀ i, SeminormedAddCommGroup (E i)] open scoped TensorProduct namespace PiTensorProduct /-- A lift of the projective seminorm to `FreeAddMonoid (𝕜 × Π i, Eᵢ)`, useful to prove the properties of `projectiveSeminorm`. -/ def projectiveSeminormAux : FreeAddMonoid (𝕜 × Π i, E i) → ℝ := fun p => (p.toList.map (fun p ↦ ‖p.1‖ * ∏ i, ‖p.2 i‖)).sum theorem projectiveSeminormAux_nonneg (p : FreeAddMonoid (𝕜 × Π i, E i)) :
0 ≤ projectiveSeminormAux p := by simp only [projectiveSeminormAux, Function.comp_apply] refine List.sum_nonneg ?_ intro a simp only [Multiset.map_coe, Multiset.mem_coe, List.mem_map, Prod.exists, forall_exists_index, and_imp] intro x m _ h rw [← h] exact mul_nonneg (norm_nonneg _) (Finset.prod_nonneg (fun _ _ ↦ norm_nonneg _))
Mathlib/Analysis/NormedSpace/PiTensorProduct/ProjectiveSeminorm.lean
55
64
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import Mathlib.MeasureTheory.Measure.Typeclasses.Finite import Mathlib.MeasureTheory.Measure.Typeclasses.NoAtoms import Mathlib.MeasureTheory.Measure.Typeclasses.Probability import Mathlib.MeasureTheory.Measure.Typeclasses.SFinite deprecated_module (since := "2025-04-13")
Mathlib/MeasureTheory/Measure/Typeclasses.lean
167
174
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathlib.Data.Finite.Defs import Mathlib.Data.Finset.BooleanAlgebra import Mathlib.Data.Finset.Image import Mathlib.Data.Fintype.Defs import Mathlib.Data.Fintype.OfMap import Mathlib.Data.Fintype.Sets import Mathlib.Data.List.FinRange /-! # Instances for finite types This file is a collection of basic `Fintype` instances for types such as `Fin`, `Prod` and pi types. -/ assert_not_exists Monoid open Function open Nat universe u v variable {α β γ : Type*} open Finset instance Fin.fintype (n : ℕ) : Fintype (Fin n) := ⟨⟨List.finRange n, List.nodup_finRange n⟩, List.mem_finRange⟩ theorem Fin.univ_def (n : ℕ) : (univ : Finset (Fin n)) = ⟨List.finRange n, List.nodup_finRange n⟩ := rfl theorem Finset.val_univ_fin (n : ℕ) : (Finset.univ : Finset (Fin n)).val = List.finRange n := rfl /-- See also `nonempty_encodable`, `nonempty_denumerable`. -/ theorem nonempty_fintype (α : Type*) [Finite α] : Nonempty (Fintype α) := by rcases Finite.exists_equiv_fin α with ⟨n, ⟨e⟩⟩ exact ⟨.ofEquiv _ e.symm⟩ @[simp] theorem List.toFinset_finRange (n : ℕ) : (List.finRange n).toFinset = Finset.univ := by ext; simp @[simp] theorem Fin.univ_val_map {n : ℕ} (f : Fin n → α) : Finset.univ.val.map f = List.ofFn f := by simp [List.ofFn_eq_map, univ_def] theorem Fin.univ_image_def {n : ℕ} [DecidableEq α] (f : Fin n → α) : Finset.univ.image f = (List.ofFn f).toFinset := by simp [Finset.image] theorem Fin.univ_map_def {n : ℕ} (f : Fin n ↪ α) : Finset.univ.map f = ⟨List.ofFn f, List.nodup_ofFn.mpr f.injective⟩ := by simp [Finset.map] @[simp] theorem Fin.image_succAbove_univ {n : ℕ} (i : Fin (n + 1)) : univ.image i.succAbove = {i}ᶜ := by ext m simp @[simp] theorem Fin.image_succ_univ (n : ℕ) : (univ : Finset (Fin n)).image Fin.succ = {0}ᶜ := by rw [← Fin.succAbove_zero, Fin.image_succAbove_univ] @[simp] theorem Fin.image_castSucc (n : ℕ) : (univ : Finset (Fin n)).image Fin.castSucc = {Fin.last n}ᶜ := by rw [← Fin.succAbove_last, Fin.image_succAbove_univ] /- The following three lemmas use `Finset.cons` instead of `insert` and `Finset.map` instead of `Finset.image` to reduce proof obligations downstream. -/ /-- Embed `Fin n` into `Fin (n + 1)` by prepending zero to the `univ` -/ theorem Fin.univ_succ (n : ℕ) : (univ : Finset (Fin (n + 1))) = Finset.cons 0 (univ.map ⟨Fin.succ, Fin.succ_injective _⟩) (by simp [map_eq_image]) := by simp [map_eq_image] /-- Embed `Fin n` into `Fin (n + 1)` by appending a new `Fin.last n` to the `univ` -/ theorem Fin.univ_castSuccEmb (n : ℕ) : (univ : Finset (Fin (n + 1))) = Finset.cons (Fin.last n) (univ.map Fin.castSuccEmb) (by simp [map_eq_image]) := by simp [map_eq_image] /-- Embed `Fin n` into `Fin (n + 1)` by inserting around a specified pivot `p : Fin (n + 1)` into the `univ` -/ theorem Fin.univ_succAbove (n : ℕ) (p : Fin (n + 1)) : (univ : Finset (Fin (n + 1))) = Finset.cons p (univ.map <| Fin.succAboveEmb p) (by simp) := by simp [map_eq_image] @[simp] theorem Fin.univ_image_get [DecidableEq α] (l : List α) : Finset.univ.image l.get = l.toFinset := by simp [univ_image_def] @[simp] theorem Fin.univ_image_getElem' [DecidableEq β] (l : List α) (f : α → β) : Finset.univ.image (fun i : Fin l.length => f <| l[(i : Nat)]) = (l.map f).toFinset := by simp only [univ_image_def, List.ofFn_getElem_eq_map] theorem Fin.univ_image_get' [DecidableEq β] (l : List α) (f : α → β) : Finset.univ.image (f <| l.get ·) = (l.map f).toFinset := by simp @[instance] def Unique.fintype {α : Type*} [Unique α] : Fintype α := Fintype.ofSubsingleton default /-- Short-circuit instance to decrease search for `Unique.fintype`, since that relies on a subsingleton elimination for `Unique`. -/ instance Fintype.subtypeEq (y : α) : Fintype { x // x = y } := Fintype.subtype {y} (by simp) /-- Short-circuit instance to decrease search for `Unique.fintype`, since that relies on a subsingleton elimination for `Unique`. -/ instance Fintype.subtypeEq' (y : α) : Fintype { x // y = x } := Fintype.subtype {y} (by simp [eq_comm]) theorem Fintype.univ_empty : @univ Empty _ = ∅ := rfl theorem Fintype.univ_pempty : @univ PEmpty _ = ∅ := rfl instance Unit.fintype : Fintype Unit := Fintype.ofSubsingleton () theorem Fintype.univ_unit : @univ Unit _ = {()} := rfl instance PUnit.fintype : Fintype PUnit := Fintype.ofSubsingleton PUnit.unit theorem Fintype.univ_punit : @univ PUnit _ = {PUnit.unit} := rfl @[simp] theorem Fintype.univ_bool : @univ Bool _ = {true, false} := rfl /-- Given that `α × β` is a fintype, `α` is also a fintype. -/ def Fintype.prodLeft {α β} [DecidableEq α] [Fintype (α × β)] [Nonempty β] : Fintype α := ⟨(@univ (α × β) _).image Prod.fst, fun a => by simp⟩ /-- Given that `α × β` is a fintype, `β` is also a fintype. -/ def Fintype.prodRight {α β} [DecidableEq β] [Fintype (α × β)] [Nonempty α] : Fintype β := ⟨(@univ (α × β) _).image Prod.snd, fun b => by simp⟩ instance ULift.fintype (α : Type*) [Fintype α] : Fintype (ULift α) := Fintype.ofEquiv _ Equiv.ulift.symm instance PLift.fintype (α : Type*) [Fintype α] : Fintype (PLift α) := Fintype.ofEquiv _ Equiv.plift.symm instance PLift.fintypeProp (p : Prop) [Decidable p] : Fintype (PLift p) := ⟨if h : p then {⟨h⟩} else ∅, fun ⟨h⟩ => by simp [h]⟩ instance Quotient.fintype [Fintype α] (s : Setoid α) [DecidableRel ((· ≈ ·) : α → α → Prop)] : Fintype (Quotient s) := Fintype.ofSurjective Quotient.mk'' Quotient.mk''_surjective instance PSigma.fintypePropLeft {α : Prop} {β : α → Type*} [Decidable α] [∀ a, Fintype (β a)] : Fintype (Σ'a, β a) := if h : α then Fintype.ofEquiv (β h) ⟨fun x => ⟨h, x⟩, PSigma.snd, fun _ => rfl, fun ⟨_, _⟩ => rfl⟩ else ⟨∅, fun x => (h x.1).elim⟩ instance PSigma.fintypePropRight {α : Type*} {β : α → Prop} [∀ a, Decidable (β a)] [Fintype α] : Fintype (Σ'a, β a) := Fintype.ofEquiv { a // β a } ⟨fun ⟨x, y⟩ => ⟨x, y⟩, fun ⟨x, y⟩ => ⟨x, y⟩, fun ⟨_, _⟩ => rfl, fun ⟨_, _⟩ => rfl⟩ instance PSigma.fintypePropProp {α : Prop} {β : α → Prop} [Decidable α] [∀ a, Decidable (β a)] : Fintype (Σ'a, β a) := if h : ∃ a, β a then ⟨{⟨h.fst, h.snd⟩}, fun ⟨_, _⟩ => by simp⟩ else ⟨∅, fun ⟨x, y⟩ => (h ⟨x, y⟩).elim⟩ instance pfunFintype (p : Prop) [Decidable p] (α : p → Type*) [∀ hp, Fintype (α hp)] : Fintype (∀ hp : p, α hp) := if hp : p then Fintype.ofEquiv (α hp) ⟨fun a _ => a, fun f => f hp, fun _ => rfl, fun _ => rfl⟩ else ⟨singleton fun h => (hp h).elim, fun h => mem_singleton.2 (funext fun x => by contradiction)⟩ section Trunc /-- For `s : Multiset α`, we can lift the existential statement that `∃ x, x ∈ s` to a `Trunc α`. -/ def truncOfMultisetExistsMem {α} (s : Multiset α) : (∃ x, x ∈ s) → Trunc α := Quotient.recOnSubsingleton s fun l h => match l, h with | [], _ => False.elim (by tauto) | a :: _, _ => Trunc.mk a /-- A `Nonempty` `Fintype` constructively contains an element. -/ def truncOfNonemptyFintype (α) [Nonempty α] [Fintype α] : Trunc α := truncOfMultisetExistsMem Finset.univ.val (by simp) /-- By iterating over the elements of a fintype, we can lift an existential statement `∃ a, P a` to `Trunc (Σ' a, P a)`, containing data. -/ def truncSigmaOfExists {α} [Fintype α] {P : α → Prop} [DecidablePred P] (h : ∃ a, P a) : Trunc (Σ'a, P a) := @truncOfNonemptyFintype (Σ'a, P a) ((Exists.elim h) fun a ha => ⟨⟨a, ha⟩⟩) _ end Trunc namespace Multiset variable [Fintype α] [Fintype β] @[simp] theorem count_univ [DecidableEq α] (a : α) : count a Finset.univ.val = 1 := count_eq_one_of_mem Finset.univ.nodup (Finset.mem_univ _) @[simp] theorem map_univ_val_equiv (e : α ≃ β) : map e univ.val = univ.val := by rw [← congr_arg Finset.val (Finset.map_univ_equiv e), Finset.map_val, Equiv.coe_toEmbedding] /-- For functions on finite sets, they are bijections iff they map universes into universes. -/ @[simp] theorem bijective_iff_map_univ_eq_univ (f : α → β) : f.Bijective ↔ map f (Finset.univ : Finset α).val = univ.val := ⟨fun bij ↦ congr_arg (·.val) (map_univ_equiv <| Equiv.ofBijective f bij), fun eq ↦ ⟨ fun a₁ a₂ ↦ inj_on_of_nodup_map (eq.symm ▸ univ.nodup) _ (mem_univ a₁) _ (mem_univ a₂), fun b ↦ have ⟨a, _, h⟩ := mem_map.mp (eq.symm ▸ mem_univ_val b); ⟨a, h⟩⟩⟩ end Multiset /-- Auxiliary definition to show `exists_seq_of_forall_finset_exists`. -/ noncomputable def seqOfForallFinsetExistsAux {α : Type*} [DecidableEq α] (P : α → Prop) (r : α → α → Prop) (h : ∀ s : Finset α, ∃ y, (∀ x ∈ s, P x) → P y ∧ ∀ x ∈ s, r x y) : ℕ → α | n => Classical.choose (h (Finset.image (fun i : Fin n => seqOfForallFinsetExistsAux P r h i) (Finset.univ : Finset (Fin n)))) /-- Induction principle to build a sequence, by adding one point at a time satisfying a given relation with respect to all the previously chosen points. More precisely, Assume that, for any finite set `s`, one can find another point satisfying some relation `r` with respect to all the points in `s`. Then one may construct a function `f : ℕ → α` such that `r (f m) (f n)` holds whenever `m < n`. We also ensure that all constructed points satisfy a given predicate `P`. -/ theorem exists_seq_of_forall_finset_exists {α : Type*} (P : α → Prop) (r : α → α → Prop) (h : ∀ s : Finset α, (∀ x ∈ s, P x) → ∃ y, P y ∧ ∀ x ∈ s, r x y) : ∃ f : ℕ → α, (∀ n, P (f n)) ∧ ∀ m n, m < n → r (f m) (f n) := by classical have : Nonempty α := by rcases h ∅ (by simp) with ⟨y, _⟩ exact ⟨y⟩
choose! F hF using h have h' : ∀ s : Finset α, ∃ y, (∀ x ∈ s, P x) → P y ∧ ∀ x ∈ s, r x y := fun s => ⟨F s, hF s⟩ set f := seqOfForallFinsetExistsAux P r h' with hf
Mathlib/Data/Fintype/Basic.lean
255
257
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import Mathlib.Algebra.Group.Equiv.Basic import Mathlib.Data.ENat.Lattice import Mathlib.Data.Part import Mathlib.Tactic.NormNum /-! # Natural numbers with infinity The natural numbers and an extra `top` element `⊤`. This implementation uses `Part ℕ` as an implementation. Use `ℕ∞` instead unless you care about computability. ## Main definitions The following instances are defined: * `OrderedAddCommMonoid PartENat` * `CanonicallyOrderedAdd PartENat` * `CompleteLinearOrder PartENat` There is no additive analogue of `MonoidWithZero`; if there were then `PartENat` could be an `AddMonoidWithTop`. * `toWithTop` : the map from `PartENat` to `ℕ∞`, with theorems that it plays well with `+` and `≤`. * `withTopAddEquiv : PartENat ≃+ ℕ∞` * `withTopOrderIso : PartENat ≃o ℕ∞` ## Implementation details `PartENat` is defined to be `Part ℕ`. `+` and `≤` are defined on `PartENat`, but there is an issue with `*` because it's not clear what `0 * ⊤` should be. `mul` is hence left undefined. Similarly `⊤ - ⊤` is ambiguous so there is no `-` defined on `PartENat`. Before the `open scoped Classical` line, various proofs are made with decidability assumptions. This can cause issues -- see for example the non-simp lemma `toWithTopZero` proved by `rfl`, followed by `@[simp] lemma toWithTopZero'` whose proof uses `convert`. ## Tags PartENat, ℕ∞ -/ open Part hiding some /-- Type of natural numbers with infinity (`⊤`) -/ def PartENat : Type := Part ℕ namespace PartENat /-- The computable embedding `ℕ → PartENat`. This coincides with the coercion `coe : ℕ → PartENat`, see `PartENat.some_eq_natCast`. -/ @[coe] def some : ℕ → PartENat := Part.some instance : Zero PartENat := ⟨some 0⟩ instance : Inhabited PartENat := ⟨0⟩ instance : One PartENat := ⟨some 1⟩ instance : Add PartENat := ⟨fun x y => ⟨x.Dom ∧ y.Dom, fun h => get x h.1 + get y h.2⟩⟩ instance (n : ℕ) : Decidable (some n).Dom := isTrue trivial @[simp] theorem dom_some (x : ℕ) : (some x).Dom := trivial instance addCommMonoid : AddCommMonoid PartENat where add := (· + ·) zero := 0 add_comm _ _ := Part.ext' and_comm fun _ _ => add_comm _ _ zero_add _ := Part.ext' (iff_of_eq (true_and _)) fun _ _ => zero_add _ add_zero _ := Part.ext' (iff_of_eq (and_true _)) fun _ _ => add_zero _ add_assoc _ _ _ := Part.ext' and_assoc fun _ _ => add_assoc _ _ _ nsmul := nsmulRec instance : AddCommMonoidWithOne PartENat := { PartENat.addCommMonoid with one := 1 natCast := some natCast_zero := rfl natCast_succ := fun _ => Part.ext' (iff_of_eq (true_and _)).symm fun _ _ => rfl } theorem some_eq_natCast (n : ℕ) : some n = n := rfl instance : CharZero PartENat where cast_injective := Part.some_injective /-- Alias of `Nat.cast_inj` specialized to `PartENat` -/ theorem natCast_inj {x y : ℕ} : (x : PartENat) = y ↔ x = y := Nat.cast_inj @[simp] theorem dom_natCast (x : ℕ) : (x : PartENat).Dom := trivial @[simp] theorem dom_ofNat (x : ℕ) [x.AtLeastTwo] : (ofNat(x) : PartENat).Dom := trivial @[simp] theorem dom_zero : (0 : PartENat).Dom := trivial @[simp] theorem dom_one : (1 : PartENat).Dom := trivial instance : CanLift PartENat ℕ (↑) Dom := ⟨fun n hn => ⟨n.get hn, Part.some_get _⟩⟩ instance : LE PartENat := ⟨fun x y => ∃ h : y.Dom → x.Dom, ∀ hy : y.Dom, x.get (h hy) ≤ y.get hy⟩ instance : Top PartENat := ⟨none⟩ instance : Bot PartENat := ⟨0⟩ instance : Max PartENat := ⟨fun x y => ⟨x.Dom ∧ y.Dom, fun h => x.get h.1 ⊔ y.get h.2⟩⟩ theorem le_def (x y : PartENat) : x ≤ y ↔ ∃ h : y.Dom → x.Dom, ∀ hy : y.Dom, x.get (h hy) ≤ y.get hy := Iff.rfl @[elab_as_elim] protected theorem casesOn' {P : PartENat → Prop} : ∀ a : PartENat, P ⊤ → (∀ n : ℕ, P (some n)) → P a := Part.induction_on @[elab_as_elim] protected theorem casesOn {P : PartENat → Prop} : ∀ a : PartENat, P ⊤ → (∀ n : ℕ, P n) → P a := by exact PartENat.casesOn' -- not a simp lemma as we will provide a `LinearOrderedAddCommMonoidWithTop` instance later theorem top_add (x : PartENat) : ⊤ + x = ⊤ := Part.ext' (iff_of_eq (false_and _)) fun h => h.left.elim -- not a simp lemma as we will provide a `LinearOrderedAddCommMonoidWithTop` instance later theorem add_top (x : PartENat) : x + ⊤ = ⊤ := by rw [add_comm, top_add] @[simp] theorem natCast_get {x : PartENat} (h : x.Dom) : (x.get h : PartENat) = x := by exact Part.ext' (iff_of_true trivial h) fun _ _ => rfl @[simp, norm_cast] theorem get_natCast' (x : ℕ) (h : (x : PartENat).Dom) : get (x : PartENat) h = x := by rw [← natCast_inj, natCast_get] theorem get_natCast {x : ℕ} : get (x : PartENat) (dom_natCast x) = x := get_natCast' _ _ theorem coe_add_get {x : ℕ} {y : PartENat} (h : ((x : PartENat) + y).Dom) : get ((x : PartENat) + y) h = x + get y h.2 := by rfl @[simp] theorem get_add {x y : PartENat} (h : (x + y).Dom) : get (x + y) h = x.get h.1 + y.get h.2 := rfl @[simp] theorem get_zero (h : (0 : PartENat).Dom) : (0 : PartENat).get h = 0 := rfl @[simp] theorem get_one (h : (1 : PartENat).Dom) : (1 : PartENat).get h = 1 := rfl @[simp] theorem get_ofNat' (x : ℕ) [x.AtLeastTwo] (h : (ofNat(x) : PartENat).Dom) : Part.get (ofNat(x) : PartENat) h = ofNat(x) := get_natCast' x h nonrec theorem get_eq_iff_eq_some {a : PartENat} {ha : a.Dom} {b : ℕ} : a.get ha = b ↔ a = some b := get_eq_iff_eq_some theorem get_eq_iff_eq_coe {a : PartENat} {ha : a.Dom} {b : ℕ} : a.get ha = b ↔ a = b := by rw [get_eq_iff_eq_some] rfl theorem dom_of_le_of_dom {x y : PartENat} : x ≤ y → y.Dom → x.Dom := fun ⟨h, _⟩ => h theorem dom_of_le_some {x : PartENat} {y : ℕ} (h : x ≤ some y) : x.Dom := dom_of_le_of_dom h trivial theorem dom_of_le_natCast {x : PartENat} {y : ℕ} (h : x ≤ y) : x.Dom := by exact dom_of_le_some h instance decidableLe (x y : PartENat) [Decidable x.Dom] [Decidable y.Dom] : Decidable (x ≤ y) := if hx : x.Dom then decidable_of_decidable_of_iff (le_def x y).symm else if hy : y.Dom then isFalse fun h => hx <| dom_of_le_of_dom h hy else isTrue ⟨fun h => (hy h).elim, fun h => (hy h).elim⟩ instance partialOrder : PartialOrder PartENat where le := (· ≤ ·) le_refl _ := ⟨id, fun _ => le_rfl⟩ le_trans := fun _ _ _ ⟨hxy₁, hxy₂⟩ ⟨hyz₁, hyz₂⟩ => ⟨hxy₁ ∘ hyz₁, fun _ => le_trans (hxy₂ _) (hyz₂ _)⟩ lt_iff_le_not_le _ _ := Iff.rfl le_antisymm := fun _ _ ⟨hxy₁, hxy₂⟩ ⟨hyx₁, hyx₂⟩ => Part.ext' ⟨hyx₁, hxy₁⟩ fun _ _ => le_antisymm (hxy₂ _) (hyx₂ _) theorem lt_def (x y : PartENat) : x < y ↔ ∃ hx : x.Dom, ∀ hy : y.Dom, x.get hx < y.get hy := by rw [lt_iff_le_not_le, le_def, le_def, not_exists] constructor · rintro ⟨⟨hyx, H⟩, h⟩ by_cases hx : x.Dom · use hx intro hy specialize H hy specialize h fun _ => hy rw [not_forall] at h obtain ⟨hx', h⟩ := h rw [not_le] at h exact h · specialize h fun hx' => (hx hx').elim rw [not_forall] at h obtain ⟨hx', h⟩ := h exact (hx hx').elim · rintro ⟨hx, H⟩ exact ⟨⟨fun _ => hx, fun hy => (H hy).le⟩, fun hxy h => not_lt_of_le (h _) (H _)⟩ noncomputable instance isOrderedAddMonoid : IsOrderedAddMonoid PartENat := { add_le_add_left := fun a b ⟨h₁, h₂⟩ c => PartENat.casesOn c (by simp [top_add]) fun c => ⟨fun h => And.intro (dom_natCast _) (h₁ h.2), fun h => by simpa only [coe_add_get] using add_le_add_left (h₂ _) c⟩ } instance semilatticeSup : SemilatticeSup PartENat := { PartENat.partialOrder with sup := (· ⊔ ·) le_sup_left := fun _ _ => ⟨And.left, fun _ => le_sup_left⟩ le_sup_right := fun _ _ => ⟨And.right, fun _ => le_sup_right⟩ sup_le := fun _ _ _ ⟨hx₁, hx₂⟩ ⟨hy₁, hy₂⟩ => ⟨fun hz => ⟨hx₁ hz, hy₁ hz⟩, fun _ => sup_le (hx₂ _) (hy₂ _)⟩ } instance orderBot : OrderBot PartENat where bot := ⊥ bot_le _ := ⟨fun _ => trivial, fun _ => Nat.zero_le _⟩ instance orderTop : OrderTop PartENat where top := ⊤ le_top _ := ⟨fun h => False.elim h, fun hy => False.elim hy⟩ instance : ZeroLEOneClass PartENat where zero_le_one := bot_le /-- Alias of `Nat.cast_le` specialized to `PartENat` -/ theorem coe_le_coe {x y : ℕ} : (x : PartENat) ≤ y ↔ x ≤ y := Nat.cast_le /-- Alias of `Nat.cast_lt` specialized to `PartENat` -/ theorem coe_lt_coe {x y : ℕ} : (x : PartENat) < y ↔ x < y := Nat.cast_lt @[simp] theorem get_le_get {x y : PartENat} {hx : x.Dom} {hy : y.Dom} : x.get hx ≤ y.get hy ↔ x ≤ y := by conv => lhs rw [← coe_le_coe, natCast_get, natCast_get] theorem le_coe_iff (x : PartENat) (n : ℕ) : x ≤ n ↔ ∃ h : x.Dom, x.get h ≤ n := by show (∃ h : True → x.Dom, _) ↔ ∃ h : x.Dom, x.get h ≤ n simp only [forall_prop_of_true, dom_natCast, get_natCast'] theorem lt_coe_iff (x : PartENat) (n : ℕ) : x < n ↔ ∃ h : x.Dom, x.get h < n := by simp only [lt_def, forall_prop_of_true, get_natCast', dom_natCast] theorem coe_le_iff (n : ℕ) (x : PartENat) : (n : PartENat) ≤ x ↔ ∀ h : x.Dom, n ≤ x.get h := by rw [← some_eq_natCast] simp only [le_def, exists_prop_of_true, dom_some, forall_true_iff] rfl theorem coe_lt_iff (n : ℕ) (x : PartENat) : (n : PartENat) < x ↔ ∀ h : x.Dom, n < x.get h := by rw [← some_eq_natCast] simp only [lt_def, exists_prop_of_true, dom_some, forall_true_iff] rfl nonrec theorem eq_zero_iff {x : PartENat} : x = 0 ↔ x ≤ 0 := eq_bot_iff theorem ne_zero_iff {x : PartENat} : x ≠ 0 ↔ ⊥ < x := bot_lt_iff_ne_bot.symm theorem dom_of_lt {x y : PartENat} : x < y → x.Dom := PartENat.casesOn x not_top_lt fun _ _ => dom_natCast _ theorem top_eq_none : (⊤ : PartENat) = Part.none := rfl @[simp] theorem natCast_lt_top (x : ℕ) : (x : PartENat) < ⊤ := Ne.lt_top fun h => absurd (congr_arg Dom h) <| by simp only [dom_natCast]; exact true_ne_false @[simp] theorem zero_lt_top : (0 : PartENat) < ⊤ := natCast_lt_top 0 @[simp] theorem one_lt_top : (1 : PartENat) < ⊤ := natCast_lt_top 1 @[simp] theorem ofNat_lt_top (x : ℕ) [x.AtLeastTwo] : (ofNat(x) : PartENat) < ⊤ := natCast_lt_top x @[simp] theorem natCast_ne_top (x : ℕ) : (x : PartENat) ≠ ⊤ := ne_of_lt (natCast_lt_top x) @[simp] theorem zero_ne_top : (0 : PartENat) ≠ ⊤ := natCast_ne_top 0 @[simp] theorem one_ne_top : (1 : PartENat) ≠ ⊤ := natCast_ne_top 1 @[simp] theorem ofNat_ne_top (x : ℕ) [x.AtLeastTwo] : (ofNat(x) : PartENat) ≠ ⊤ := natCast_ne_top x theorem not_isMax_natCast (x : ℕ) : ¬IsMax (x : PartENat) := not_isMax_of_lt (natCast_lt_top x) theorem ne_top_iff {x : PartENat} : x ≠ ⊤ ↔ ∃ n : ℕ, x = n := by simpa only [← some_eq_natCast] using Part.ne_none_iff theorem ne_top_iff_dom {x : PartENat} : x ≠ ⊤ ↔ x.Dom := by classical exact not_iff_comm.1 Part.eq_none_iff'.symm theorem not_dom_iff_eq_top {x : PartENat} : ¬x.Dom ↔ x = ⊤ := Iff.not_left ne_top_iff_dom.symm theorem ne_top_of_lt {x y : PartENat} (h : x < y) : x ≠ ⊤ := ne_of_lt <| lt_of_lt_of_le h le_top theorem eq_top_iff_forall_lt (x : PartENat) : x = ⊤ ↔ ∀ n : ℕ, (n : PartENat) < x := by constructor · rintro rfl n exact natCast_lt_top _ · contrapose! rw [ne_top_iff] rintro ⟨n, rfl⟩ exact ⟨n, irrefl _⟩ theorem eq_top_iff_forall_le (x : PartENat) : x = ⊤ ↔ ∀ n : ℕ, (n : PartENat) ≤ x := (eq_top_iff_forall_lt x).trans ⟨fun h n => (h n).le, fun h n => lt_of_lt_of_le (coe_lt_coe.mpr n.lt_succ_self) (h (n + 1))⟩ theorem pos_iff_one_le {x : PartENat} : 0 < x ↔ 1 ≤ x := PartENat.casesOn x (by simp only [le_top, natCast_lt_top, ← @Nat.cast_zero PartENat]) fun n => by rw [← Nat.cast_zero, ← Nat.cast_one, PartENat.coe_lt_coe, PartENat.coe_le_coe] rfl instance isTotal : IsTotal PartENat (· ≤ ·) where total x y := PartENat.casesOn (P := fun z => z ≤ y ∨ y ≤ z) x (Or.inr le_top) (PartENat.casesOn y (fun _ => Or.inl le_top) fun x y => (le_total x y).elim (Or.inr ∘ coe_le_coe.2) (Or.inl ∘ coe_le_coe.2)) noncomputable instance linearOrder : LinearOrder PartENat := { PartENat.partialOrder with le_total := IsTotal.total toDecidableLE := Classical.decRel _ max := (· ⊔ ·) max_def a b := congr_fun₂ (@sup_eq_maxDefault PartENat _ (_) _) _ _ } instance boundedOrder : BoundedOrder PartENat := { PartENat.orderTop, PartENat.orderBot with } noncomputable instance lattice : Lattice PartENat := { PartENat.semilatticeSup with inf := min inf_le_left := min_le_left inf_le_right := min_le_right le_inf := fun _ _ _ => le_min } instance : CanonicallyOrderedAdd PartENat := { le_self_add := fun a b => PartENat.casesOn b (le_top.trans_eq (add_top _).symm) fun _ => PartENat.casesOn a (top_add _).ge fun _ => (coe_le_coe.2 le_self_add).trans_eq (Nat.cast_add _ _) exists_add_of_le := fun {a b} => PartENat.casesOn b (fun _ => ⟨⊤, (add_top _).symm⟩) fun b => PartENat.casesOn a (fun h => ((natCast_lt_top _).not_le h).elim) fun a h => ⟨(b - a : ℕ), by rw [← Nat.cast_add, natCast_inj, add_comm, tsub_add_cancel_of_le (coe_le_coe.1 h)]⟩ } theorem eq_natCast_sub_of_add_eq_natCast {x y : PartENat} {n : ℕ} (h : x + y = n) : x = ↑(n - y.get (dom_of_le_natCast ((le_add_left le_rfl).trans_eq h))) := by lift x to ℕ using dom_of_le_natCast ((le_add_right le_rfl).trans_eq h) lift y to ℕ using dom_of_le_natCast ((le_add_left le_rfl).trans_eq h) rw [← Nat.cast_add, natCast_inj] at h rw [get_natCast, natCast_inj, eq_tsub_of_add_eq h] protected theorem add_lt_add_right {x y z : PartENat} (h : x < y) (hz : z ≠ ⊤) : x + z < y + z := by rcases ne_top_iff.mp (ne_top_of_lt h) with ⟨m, rfl⟩ rcases ne_top_iff.mp hz with ⟨k, rfl⟩ induction y using PartENat.casesOn · rw [top_add] exact_mod_cast natCast_lt_top _ norm_cast at h exact_mod_cast add_lt_add_right h _ protected theorem add_lt_add_iff_right {x y z : PartENat} (hz : z ≠ ⊤) : x + z < y + z ↔ x < y := ⟨lt_of_add_lt_add_right, fun h => PartENat.add_lt_add_right h hz⟩ protected theorem add_lt_add_iff_left {x y z : PartENat} (hz : z ≠ ⊤) : z + x < z + y ↔ x < y := by rw [add_comm z, add_comm z, PartENat.add_lt_add_iff_right hz] protected theorem lt_add_iff_pos_right {x y : PartENat} (hx : x ≠ ⊤) : x < x + y ↔ 0 < y := by conv_rhs => rw [← PartENat.add_lt_add_iff_left hx] rw [add_zero] theorem lt_add_one {x : PartENat} (hx : x ≠ ⊤) : x < x + 1 := by rw [PartENat.lt_add_iff_pos_right hx] norm_cast theorem le_of_lt_add_one {x y : PartENat} (h : x < y + 1) : x ≤ y := by induction y using PartENat.casesOn · apply le_top rcases ne_top_iff.mp (ne_top_of_lt h) with ⟨m, rfl⟩ exact_mod_cast Nat.le_of_lt_succ (by norm_cast at h) theorem add_one_le_of_lt {x y : PartENat} (h : x < y) : x + 1 ≤ y := by induction y using PartENat.casesOn · apply le_top rcases ne_top_iff.mp (ne_top_of_lt h) with ⟨m, rfl⟩ exact_mod_cast Nat.succ_le_of_lt (by norm_cast at h) theorem add_one_le_iff_lt {x y : PartENat} (hx : x ≠ ⊤) : x + 1 ≤ y ↔ x < y := by refine ⟨fun h => ?_, add_one_le_of_lt⟩ rcases ne_top_iff.mp hx with ⟨m, rfl⟩ induction y using PartENat.casesOn · apply natCast_lt_top exact_mod_cast Nat.lt_of_succ_le (by norm_cast at h) theorem coe_succ_le_iff {n : ℕ} {e : PartENat} : ↑n.succ ≤ e ↔ ↑n < e := by rw [Nat.succ_eq_add_one n, Nat.cast_add, Nat.cast_one, add_one_le_iff_lt (natCast_ne_top n)] theorem lt_add_one_iff_lt {x y : PartENat} (hx : x ≠ ⊤) : x < y + 1 ↔ x ≤ y := by refine ⟨le_of_lt_add_one, fun h => ?_⟩ rcases ne_top_iff.mp hx with ⟨m, rfl⟩ induction y using PartENat.casesOn · rw [top_add] apply natCast_lt_top exact_mod_cast Nat.lt_succ_of_le (by norm_cast at h) lemma lt_coe_succ_iff_le {x : PartENat} {n : ℕ} (hx : x ≠ ⊤) : x < n.succ ↔ x ≤ n := by rw [Nat.succ_eq_add_one n, Nat.cast_add, Nat.cast_one, lt_add_one_iff_lt hx] theorem add_eq_top_iff {a b : PartENat} : a + b = ⊤ ↔ a = ⊤ ∨ b = ⊤ := by refine PartENat.casesOn a ?_ ?_ <;> refine PartENat.casesOn b ?_ ?_ <;> simp [top_add, add_top] simp only [← Nat.cast_add, PartENat.natCast_ne_top, forall_const, not_false_eq_true] protected theorem add_right_cancel_iff {a b c : PartENat} (hc : c ≠ ⊤) : a + c = b + c ↔ a = b := by rcases ne_top_iff.1 hc with ⟨c, rfl⟩ refine PartENat.casesOn a ?_ ?_ <;> refine PartENat.casesOn b ?_ ?_ <;> simp [add_eq_top_iff, natCast_ne_top, @eq_comm _ (⊤ : PartENat), top_add] simp only [← Nat.cast_add, add_left_cancel_iff, PartENat.natCast_inj, add_comm, forall_const] protected theorem add_left_cancel_iff {a b c : PartENat} (ha : a ≠ ⊤) : a + b = a + c ↔ b = c := by rw [add_comm a, add_comm a, PartENat.add_right_cancel_iff ha] section WithTop /-- Computably converts a `PartENat` to a `ℕ∞`. -/ def toWithTop (x : PartENat) [Decidable x.Dom] : ℕ∞ := x.toOption theorem toWithTop_top : have : Decidable (⊤ : PartENat).Dom := Part.noneDecidable toWithTop ⊤ = ⊤ := rfl @[simp] theorem toWithTop_top' {h : Decidable (⊤ : PartENat).Dom} : toWithTop ⊤ = ⊤ := by convert toWithTop_top theorem toWithTop_zero : have : Decidable (0 : PartENat).Dom := someDecidable 0 toWithTop 0 = 0 := rfl @[simp] theorem toWithTop_zero' {h : Decidable (0 : PartENat).Dom} : toWithTop 0 = 0 := by convert toWithTop_zero theorem toWithTop_one : have : Decidable (1 : PartENat).Dom := someDecidable 1 toWithTop 1 = 1 := rfl @[simp] theorem toWithTop_one' {h : Decidable (1 : PartENat).Dom} : toWithTop 1 = 1 := by convert toWithTop_one theorem toWithTop_some (n : ℕ) : toWithTop (some n) = n := rfl theorem toWithTop_natCast (n : ℕ) {_ : Decidable (n : PartENat).Dom} : toWithTop n = n := by simp only [← toWithTop_some] congr @[simp] theorem toWithTop_natCast' (n : ℕ) {_ : Decidable (n : PartENat).Dom} : toWithTop (n : PartENat) = n := by rw [toWithTop_natCast n] @[simp] theorem toWithTop_ofNat (n : ℕ) [n.AtLeastTwo] {_ : Decidable (OfNat.ofNat n : PartENat).Dom} : toWithTop (ofNat(n) : PartENat) = OfNat.ofNat n := toWithTop_natCast' n @[simp] theorem toWithTop_le {x y : PartENat} [hx : Decidable x.Dom] [hy : Decidable y.Dom] : toWithTop x ≤ toWithTop y ↔ x ≤ y := by induction y using PartENat.casesOn generalizing hy · simp induction x using PartENat.casesOn generalizing hx · simp · simp @[simp] theorem toWithTop_lt {x y : PartENat} [Decidable x.Dom] [Decidable y.Dom] : toWithTop x < toWithTop y ↔ x < y := lt_iff_lt_of_le_iff_le toWithTop_le end WithTop /-- Coercion from `ℕ∞` to `PartENat`. -/ @[coe] def ofENat : ℕ∞ → PartENat := fun x => match x with | Option.none => none | Option.some n => some n instance : Coe ℕ∞ PartENat := ⟨ofENat⟩ example (n : ℕ) : ((n : ℕ∞) : PartENat) = ↑n := rfl @[simp, norm_cast] lemma ofENat_top : ofENat ⊤ = ⊤ := rfl @[simp, norm_cast] lemma ofENat_coe (n : ℕ) : ofENat n = n := rfl @[simp, norm_cast] theorem ofENat_zero : ofENat 0 = 0 := rfl @[simp, norm_cast] theorem ofENat_one : ofENat 1 = 1 := rfl @[simp, norm_cast] theorem ofENat_ofNat (n : Nat) [n.AtLeastTwo] : ofENat ofNat(n) = OfNat.ofNat n := rfl @[simp, norm_cast] theorem toWithTop_ofENat (n : ℕ∞) {_ : Decidable (n : PartENat).Dom} : toWithTop (↑n) = n := by cases n with | top => simp | coe n => simp @[simp, norm_cast] theorem ofENat_toWithTop (x : PartENat) {_ : Decidable (x : PartENat).Dom} : toWithTop x = x := by induction x using PartENat.casesOn <;> simp @[simp, norm_cast] theorem ofENat_le {x y : ℕ∞} : ofENat x ≤ ofENat y ↔ x ≤ y := by classical rw [← toWithTop_le, toWithTop_ofENat, toWithTop_ofENat] @[simp, norm_cast] theorem ofENat_lt {x y : ℕ∞} : ofENat x < ofENat y ↔ x < y := by classical rw [← toWithTop_lt, toWithTop_ofENat, toWithTop_ofENat] section WithTopEquiv open scoped Classical in @[simp] theorem toWithTop_add {x y : PartENat} : toWithTop (x + y) = toWithTop x + toWithTop y := by refine PartENat.casesOn y ?_ ?_ <;> refine PartENat.casesOn x ?_ ?_ <;> simp [add_top, top_add, ← Nat.cast_add, ← ENat.coe_add] open scoped Classical in /-- `Equiv` between `PartENat` and `ℕ∞` (for the order isomorphism see `withTopOrderIso`). -/ @[simps] noncomputable def withTopEquiv : PartENat ≃ ℕ∞ where toFun x := toWithTop x invFun x := ↑x left_inv x := by simp right_inv x := by simp theorem withTopEquiv_top : withTopEquiv ⊤ = ⊤ := by simp theorem withTopEquiv_natCast (n : Nat) : withTopEquiv n = n := by simp theorem withTopEquiv_zero : withTopEquiv 0 = 0 := by simp theorem withTopEquiv_one : withTopEquiv 1 = 1 := by simp theorem withTopEquiv_ofNat (n : Nat) [n.AtLeastTwo] : withTopEquiv ofNat(n) = OfNat.ofNat n := by simp theorem withTopEquiv_le {x y : PartENat} : withTopEquiv x ≤ withTopEquiv y ↔ x ≤ y := by simp theorem withTopEquiv_lt {x y : PartENat} : withTopEquiv x < withTopEquiv y ↔ x < y := by simp theorem withTopEquiv_symm_top : withTopEquiv.symm ⊤ = ⊤ := by simp theorem withTopEquiv_symm_coe (n : Nat) : withTopEquiv.symm n = n := by simp theorem withTopEquiv_symm_zero : withTopEquiv.symm 0 = 0 := by simp theorem withTopEquiv_symm_one : withTopEquiv.symm 1 = 1 := by simp theorem withTopEquiv_symm_ofNat (n : Nat) [n.AtLeastTwo] : withTopEquiv.symm ofNat(n) = OfNat.ofNat n := by simp theorem withTopEquiv_symm_le {x y : ℕ∞} : withTopEquiv.symm x ≤ withTopEquiv.symm y ↔ x ≤ y := by simp theorem withTopEquiv_symm_lt {x y : ℕ∞} : withTopEquiv.symm x < withTopEquiv.symm y ↔ x < y := by simp /-- `toWithTop` induces an order isomorphism between `PartENat` and `ℕ∞`. -/ noncomputable def withTopOrderIso : PartENat ≃o ℕ∞ := { withTopEquiv with map_rel_iff' := @fun _ _ => withTopEquiv_le } /-- `toWithTop` induces an additive monoid isomorphism between `PartENat` and `ℕ∞`. -/ noncomputable def withTopAddEquiv : PartENat ≃+ ℕ∞ := { withTopEquiv with map_add' := fun x y => by simp only [withTopEquiv] exact toWithTop_add } end WithTopEquiv theorem lt_wf : @WellFounded PartENat (· < ·) := by classical change WellFounded fun a b : PartENat => a < b simp_rw [← withTopEquiv_lt] exact InvImage.wf _ wellFounded_lt instance : WellFoundedLT PartENat := ⟨lt_wf⟩ instance wellFoundedRelation : WellFoundedRelation PartENat := ⟨(· < ·), lt_wf⟩ section Find variable (P : ℕ → Prop) [DecidablePred P] /-- The smallest `PartENat` satisfying a (decidable) predicate `P : ℕ → Prop` -/ def find : PartENat := ⟨∃ n, P n, Nat.find⟩ @[simp] theorem find_get (h : (find P).Dom) : (find P).get h = Nat.find h := rfl theorem find_dom (h : ∃ n, P n) : (find P).Dom := h theorem lt_find (n : ℕ) (h : ∀ m ≤ n, ¬P m) : (n : PartENat) < find P := by rw [coe_lt_iff] intro h₁ rw [find_get] have h₂ := @Nat.find_spec P _ h₁ revert h₂ contrapose! exact h _ theorem lt_find_iff (n : ℕ) : (n : PartENat) < find P ↔ ∀ m ≤ n, ¬P m := by refine ⟨?_, lt_find P n⟩ intro h m hm by_cases H : (find P).Dom · apply Nat.find_min H rw [coe_lt_iff] at h specialize h H exact lt_of_le_of_lt hm h · exact not_exists.mp H m theorem find_le (n : ℕ) (h : P n) : find P ≤ n := by rw [le_coe_iff] exact ⟨⟨_, h⟩, @Nat.find_min' P _ _ _ h⟩ theorem find_eq_top_iff : find P = ⊤ ↔ ∀ n, ¬P n := (eq_top_iff_forall_lt _).trans ⟨fun h n => (lt_find_iff P n).mp (h n) _ le_rfl, fun h n => lt_find P n fun _ _ => h _⟩ end Find noncomputable instance : LinearOrderedAddCommMonoidWithTop PartENat := { PartENat.linearOrder, PartENat.isOrderedAddMonoid, PartENat.orderTop with top_add' := top_add } noncomputable instance : CompleteLinearOrder PartENat := { lattice, withTopOrderIso.symm.toGaloisInsertion.liftCompleteLattice, linearOrder, LinearOrder.toBiheytingAlgebra with } end PartENat
Mathlib/Data/Nat/PartENat.lean
749
750
/- Copyright (c) 2019 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton, Kim Morrison -/ import Mathlib.CategoryTheory.Opposites import Mathlib.CategoryTheory.Groupoid /-! # Facts about epimorphisms and monomorphisms. The definitions of `Epi` and `Mono` are in `CategoryTheory.Category`, since they are used by some lemmas for `Iso`, which is used everywhere. -/ universe v₁ v₂ u₁ u₂ namespace CategoryTheory variable {C : Type u₁} [Category.{v₁} C] instance unop_mono_of_epi {A B : Cᵒᵖ} (f : A ⟶ B) [Epi f] : Mono f.unop := ⟨fun _ _ eq => Quiver.Hom.op_inj ((cancel_epi f).1 (Quiver.Hom.unop_inj eq))⟩ instance unop_epi_of_mono {A B : Cᵒᵖ} (f : A ⟶ B) [Mono f] : Epi f.unop := ⟨fun _ _ eq => Quiver.Hom.op_inj ((cancel_mono f).1 (Quiver.Hom.unop_inj eq))⟩ instance op_mono_of_epi {A B : C} (f : A ⟶ B) [Epi f] : Mono f.op := ⟨fun _ _ eq => Quiver.Hom.unop_inj ((cancel_epi f).1 (Quiver.Hom.op_inj eq))⟩ instance op_epi_of_mono {A B : C} (f : A ⟶ B) [Mono f] : Epi f.op := ⟨fun _ _ eq => Quiver.Hom.unop_inj ((cancel_mono f).1 (Quiver.Hom.op_inj eq))⟩ /-- A split monomorphism is a morphism `f : X ⟶ Y` with a given retraction `retraction f : Y ⟶ X` such that `f ≫ retraction f = 𝟙 X`. Every split monomorphism is a monomorphism. -/ @[ext, aesop apply safe (rule_sets := [CategoryTheory])] structure SplitMono {X Y : C} (f : X ⟶ Y) where /-- The map splitting `f` -/ retraction : Y ⟶ X /-- `f` composed with `retraction` is the identity -/ id : f ≫ retraction = 𝟙 X := by aesop_cat attribute [reassoc (attr := simp)] SplitMono.id /-- `IsSplitMono f` is the assertion that `f` admits a retraction -/ class IsSplitMono {X Y : C} (f : X ⟶ Y) : Prop where /-- There is a splitting -/ exists_splitMono : Nonempty (SplitMono f) /-- A composition of `SplitMono` is a `SplitMono`. -/ @[simps] def SplitMono.comp {X Y Z : C} {f : X ⟶ Y} {g : Y ⟶ Z} (smf : SplitMono f) (smg : SplitMono g) : SplitMono (f ≫ g) where retraction := smg.retraction ≫ smf.retraction /-- A constructor for `IsSplitMono f` taking a `SplitMono f` as an argument -/ theorem IsSplitMono.mk' {X Y : C} {f : X ⟶ Y} (sm : SplitMono f) : IsSplitMono f := ⟨Nonempty.intro sm⟩ /-- A split epimorphism is a morphism `f : X ⟶ Y` with a given section `section_ f : Y ⟶ X` such that `section_ f ≫ f = 𝟙 Y`. (Note that `section` is a reserved keyword, so we append an underscore.) Every split epimorphism is an epimorphism. -/ @[ext, aesop apply safe (rule_sets := [CategoryTheory])] structure SplitEpi {X Y : C} (f : X ⟶ Y) where /-- The map splitting `f` -/ section_ : Y ⟶ X /-- `section_` composed with `f` is the identity -/ id : section_ ≫ f = 𝟙 Y := by aesop_cat attribute [reassoc (attr := simp)] SplitEpi.id /-- `IsSplitEpi f` is the assertion that `f` admits a section -/ class IsSplitEpi {X Y : C} (f : X ⟶ Y) : Prop where /-- There is a splitting -/ exists_splitEpi : Nonempty (SplitEpi f) /-- A composition of `SplitEpi` is a split `SplitEpi`. -/ @[simps] def SplitEpi.comp {X Y Z : C} {f : X ⟶ Y} {g : Y ⟶ Z} (sef : SplitEpi f) (seg : SplitEpi g) : SplitEpi (f ≫ g) where section_ := seg.section_ ≫ sef.section_ /-- A constructor for `IsSplitEpi f` taking a `SplitEpi f` as an argument -/ theorem IsSplitEpi.mk' {X Y : C} {f : X ⟶ Y} (se : SplitEpi f) : IsSplitEpi f := ⟨Nonempty.intro se⟩ /-- The chosen retraction of a split monomorphism. -/ noncomputable def retraction {X Y : C} (f : X ⟶ Y) [hf : IsSplitMono f] : Y ⟶ X := hf.exists_splitMono.some.retraction @[reassoc (attr := simp)] theorem IsSplitMono.id {X Y : C} (f : X ⟶ Y) [hf : IsSplitMono f] : f ≫ retraction f = 𝟙 X := hf.exists_splitMono.some.id /-- The retraction of a split monomorphism has an obvious section. -/ def SplitMono.splitEpi {X Y : C} {f : X ⟶ Y} (sm : SplitMono f) : SplitEpi sm.retraction where section_ := f /-- The retraction of a split monomorphism is itself a split epimorphism. -/ instance retraction_isSplitEpi {X Y : C} (f : X ⟶ Y) [IsSplitMono f] : IsSplitEpi (retraction f) := IsSplitEpi.mk' (SplitMono.splitEpi _) /-- A split mono which is epi is an iso. -/ theorem isIso_of_epi_of_isSplitMono {X Y : C} (f : X ⟶ Y) [IsSplitMono f] [Epi f] : IsIso f := ⟨⟨retraction f, ⟨by simp, by simp [← cancel_epi f]⟩⟩⟩ /-- The chosen section of a split epimorphism. (Note that `section` is a reserved keyword, so we append an underscore.) -/ noncomputable def section_ {X Y : C} (f : X ⟶ Y) [hf : IsSplitEpi f] : Y ⟶ X := hf.exists_splitEpi.some.section_ @[reassoc (attr := simp)] theorem IsSplitEpi.id {X Y : C} (f : X ⟶ Y) [hf : IsSplitEpi f] : section_ f ≫ f = 𝟙 Y := hf.exists_splitEpi.some.id /-- The section of a split epimorphism has an obvious retraction. -/ def SplitEpi.splitMono {X Y : C} {f : X ⟶ Y} (se : SplitEpi f) : SplitMono se.section_ where retraction := f /-- The section of a split epimorphism is itself a split monomorphism. -/ instance section_isSplitMono {X Y : C} (f : X ⟶ Y) [IsSplitEpi f] : IsSplitMono (section_ f) := IsSplitMono.mk' (SplitEpi.splitMono _) /-- A split epi which is mono is an iso. -/ theorem isIso_of_mono_of_isSplitEpi {X Y : C} (f : X ⟶ Y) [Mono f] [IsSplitEpi f] : IsIso f := ⟨⟨section_ f, ⟨by simp [← cancel_mono f], by simp⟩⟩⟩ /-- Every iso is a split mono. -/ instance (priority := 100) IsSplitMono.of_iso {X Y : C} (f : X ⟶ Y) [IsIso f] : IsSplitMono f := IsSplitMono.mk' { retraction := inv f } /-- Every iso is a split epi. -/ instance (priority := 100) IsSplitEpi.of_iso {X Y : C} (f : X ⟶ Y) [IsIso f] : IsSplitEpi f := IsSplitEpi.mk' { section_ := inv f } theorem SplitMono.mono {X Y : C} {f : X ⟶ Y} (sm : SplitMono f) : Mono f := { right_cancellation := fun g h w => by replace w := w =≫ sm.retraction; simpa using w } /-- Every split mono is a mono. -/ instance (priority := 100) IsSplitMono.mono {X Y : C} (f : X ⟶ Y) [hf : IsSplitMono f] : Mono f := hf.exists_splitMono.some.mono theorem SplitEpi.epi {X Y : C} {f : X ⟶ Y} (se : SplitEpi f) : Epi f := { left_cancellation := fun g h w => by replace w := se.section_ ≫= w; simpa using w } /-- Every split epi is an epi. -/ instance (priority := 100) IsSplitEpi.epi {X Y : C} (f : X ⟶ Y) [hf : IsSplitEpi f] : Epi f := hf.exists_splitEpi.some.epi instance {X Y Z : C} {f : X ⟶ Y} {g : Y ⟶ Z} [hf : IsSplitMono f] [hg : IsSplitMono g] : IsSplitMono (f ≫ g) := IsSplitMono.mk' <| hf.exists_splitMono.some.comp hg.exists_splitMono.some instance {X Y Z : C} {f : X ⟶ Y} {g : Y ⟶ Z} [hf : IsSplitEpi f] [hg : IsSplitEpi g] :
IsSplitEpi (f ≫ g) := IsSplitEpi.mk' <| hf.exists_splitEpi.some.comp hg.exists_splitEpi.some
Mathlib/CategoryTheory/EpiMono.lean
163
164
/- Copyright (c) 2021 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rémy Degenne, Kexing Ying -/ import Mathlib.Probability.Notation import Mathlib.Probability.Process.Stopping /-! # Martingales A family of functions `f : ι → Ω → E` is a martingale with respect to a filtration `ℱ` if every `f i` is integrable, `f` is adapted with respect to `ℱ` and for all `i ≤ j`, `μ[f j | ℱ i] =ᵐ[μ] f i`. On the other hand, `f : ι → Ω → E` is said to be a supermartingale with respect to the filtration `ℱ` if `f i` is integrable, `f` is adapted with resepct to `ℱ` and for all `i ≤ j`, `μ[f j | ℱ i] ≤ᵐ[μ] f i`. Finally, `f : ι → Ω → E` is said to be a submartingale with respect to the filtration `ℱ` if `f i` is integrable, `f` is adapted with resepct to `ℱ` and for all `i ≤ j`, `f i ≤ᵐ[μ] μ[f j | ℱ i]`. The definitions of filtration and adapted can be found in `Probability.Process.Stopping`. ### Definitions * `MeasureTheory.Martingale f ℱ μ`: `f` is a martingale with respect to filtration `ℱ` and measure `μ`. * `MeasureTheory.Supermartingale f ℱ μ`: `f` is a supermartingale with respect to filtration `ℱ` and measure `μ`. * `MeasureTheory.Submartingale f ℱ μ`: `f` is a submartingale with respect to filtration `ℱ` and measure `μ`. ### Results * `MeasureTheory.martingale_condExp f ℱ μ`: the sequence `fun i => μ[f | ℱ i, ℱ.le i])` is a martingale with respect to `ℱ` and `μ`. -/ open TopologicalSpace Filter open scoped NNReal ENNReal MeasureTheory ProbabilityTheory namespace MeasureTheory variable {Ω E ι : Type*} [Preorder ι] {m0 : MeasurableSpace Ω} {μ : Measure Ω} [NormedAddCommGroup E] [NormedSpace ℝ E] [CompleteSpace E] {f g : ι → Ω → E} {ℱ : Filtration ι m0} /-- A family of functions `f : ι → Ω → E` is a martingale with respect to a filtration `ℱ` if `f` is adapted with respect to `ℱ` and for all `i ≤ j`, `μ[f j | ℱ i] =ᵐ[μ] f i`. -/ def Martingale (f : ι → Ω → E) (ℱ : Filtration ι m0) (μ : Measure Ω) : Prop := Adapted ℱ f ∧ ∀ i j, i ≤ j → μ[f j|ℱ i] =ᵐ[μ] f i /-- A family of integrable functions `f : ι → Ω → E` is a supermartingale with respect to a filtration `ℱ` if `f` is adapted with respect to `ℱ` and for all `i ≤ j`, `μ[f j | ℱ.le i] ≤ᵐ[μ] f i`. -/ def Supermartingale [LE E] (f : ι → Ω → E) (ℱ : Filtration ι m0) (μ : Measure Ω) : Prop := Adapted ℱ f ∧ (∀ i j, i ≤ j → μ[f j|ℱ i] ≤ᵐ[μ] f i) ∧ ∀ i, Integrable (f i) μ /-- A family of integrable functions `f : ι → Ω → E` is a submartingale with respect to a filtration `ℱ` if `f` is adapted with respect to `ℱ` and for all `i ≤ j`, `f i ≤ᵐ[μ] μ[f j | ℱ.le i]`. -/ def Submartingale [LE E] (f : ι → Ω → E) (ℱ : Filtration ι m0) (μ : Measure Ω) : Prop := Adapted ℱ f ∧ (∀ i j, i ≤ j → f i ≤ᵐ[μ] μ[f j|ℱ i]) ∧ ∀ i, Integrable (f i) μ theorem martingale_const (ℱ : Filtration ι m0) (μ : Measure Ω) [IsFiniteMeasure μ] (x : E) : Martingale (fun _ _ => x) ℱ μ := ⟨adapted_const ℱ _, fun i j _ => by rw [condExp_const (ℱ.le _)]⟩ theorem martingale_const_fun [OrderBot ι] (ℱ : Filtration ι m0) (μ : Measure Ω) [IsFiniteMeasure μ] {f : Ω → E} (hf : StronglyMeasurable[ℱ ⊥] f) (hfint : Integrable f μ) : Martingale (fun _ => f) ℱ μ := by refine ⟨fun i => hf.mono <| ℱ.mono bot_le, fun i j _ => ?_⟩ rw [condExp_of_stronglyMeasurable (ℱ.le _) (hf.mono <| ℱ.mono bot_le) hfint] variable (E) in theorem martingale_zero (ℱ : Filtration ι m0) (μ : Measure Ω) : Martingale (0 : ι → Ω → E) ℱ μ := ⟨adapted_zero E ℱ, fun i j _ => by rw [Pi.zero_apply, condExp_zero]; simp⟩ namespace Martingale protected theorem adapted (hf : Martingale f ℱ μ) : Adapted ℱ f := hf.1 protected theorem stronglyMeasurable (hf : Martingale f ℱ μ) (i : ι) : StronglyMeasurable[ℱ i] (f i) := hf.adapted i theorem condExp_ae_eq (hf : Martingale f ℱ μ) {i j : ι} (hij : i ≤ j) : μ[f j|ℱ i] =ᵐ[μ] f i := hf.2 i j hij @[deprecated (since := "2025-01-21")] alias condexp_ae_eq := condExp_ae_eq protected theorem integrable (hf : Martingale f ℱ μ) (i : ι) : Integrable (f i) μ := integrable_condExp.congr (hf.condExp_ae_eq (le_refl i)) theorem setIntegral_eq [SigmaFiniteFiltration μ ℱ] (hf : Martingale f ℱ μ) {i j : ι} (hij : i ≤ j) {s : Set Ω} (hs : MeasurableSet[ℱ i] s) : ∫ ω in s, f i ω ∂μ = ∫ ω in s, f j ω ∂μ := by rw [← setIntegral_condExp (ℱ.le i) (hf.integrable j) hs] refine setIntegral_congr_ae (ℱ.le i s hs) ?_ filter_upwards [hf.2 i j hij] with _ heq _ using heq.symm theorem add (hf : Martingale f ℱ μ) (hg : Martingale g ℱ μ) : Martingale (f + g) ℱ μ := by refine ⟨hf.adapted.add hg.adapted, fun i j hij => ?_⟩ exact (condExp_add (hf.integrable j) (hg.integrable j) _).trans ((hf.2 i j hij).add (hg.2 i j hij)) theorem neg (hf : Martingale f ℱ μ) : Martingale (-f) ℱ μ := ⟨hf.adapted.neg, fun i j hij => (condExp_neg ..).trans (hf.2 i j hij).neg⟩ theorem sub (hf : Martingale f ℱ μ) (hg : Martingale g ℱ μ) : Martingale (f - g) ℱ μ := by rw [sub_eq_add_neg]; exact hf.add hg.neg theorem smul (c : ℝ) (hf : Martingale f ℱ μ) : Martingale (c • f) ℱ μ := by refine ⟨hf.adapted.smul c, fun i j hij => ?_⟩ refine (condExp_smul ..).trans ((hf.2 i j hij).mono fun x hx => ?_) simp only [Pi.smul_apply, hx] theorem supermartingale [Preorder E] (hf : Martingale f ℱ μ) : Supermartingale f ℱ μ := ⟨hf.1, fun i j hij => (hf.2 i j hij).le, fun i => hf.integrable i⟩ theorem submartingale [Preorder E] (hf : Martingale f ℱ μ) : Submartingale f ℱ μ := ⟨hf.1, fun i j hij => (hf.2 i j hij).symm.le, fun i => hf.integrable i⟩ end Martingale theorem martingale_iff [PartialOrder E] : Martingale f ℱ μ ↔ Supermartingale f ℱ μ ∧ Submartingale f ℱ μ :=
⟨fun hf => ⟨hf.supermartingale, hf.submartingale⟩, fun ⟨hf₁, hf₂⟩ => ⟨hf₁.1, fun i j hij => (hf₁.2.1 i j hij).antisymm (hf₂.2.1 i j hij)⟩⟩
Mathlib/Probability/Martingale/Basic.lean
128
129
/- Copyright (c) 2020 Jujian Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jujian Zhang, Johan Commelin -/ import Mathlib.RingTheory.GradedAlgebra.Homogeneous.Ideal import Mathlib.Topology.Category.TopCat.Basic import Mathlib.Topology.Sets.Opens import Mathlib.Data.Set.Subsingleton /-! # Projective spectrum of a graded ring The projective spectrum of a graded commutative ring is the subtype of all homogeneous ideals that are prime and do not contain the irrelevant ideal. It is naturally endowed with a topology: the Zariski topology. ## Notation - `R` is a commutative semiring; - `A` is a commutative ring and an `R`-algebra; - `𝒜 : ℕ → Submodule R A` is the grading of `A`; ## Main definitions * `ProjectiveSpectrum 𝒜`: The projective spectrum of a graded ring `A`, or equivalently, the set of all homogeneous ideals of `A` that is both prime and relevant i.e. not containing irrelevant ideal. Henceforth, we call elements of projective spectrum *relevant homogeneous prime ideals*. * `ProjectiveSpectrum.zeroLocus 𝒜 s`: The zero locus of a subset `s` of `A` is the subset of `ProjectiveSpectrum 𝒜` consisting of all relevant homogeneous prime ideals that contain `s`. * `ProjectiveSpectrum.vanishingIdeal t`: The vanishing ideal of a subset `t` of `ProjectiveSpectrum 𝒜` is the intersection of points in `t` (viewed as relevant homogeneous prime ideals). * `ProjectiveSpectrum.Top`: the topological space of `ProjectiveSpectrum 𝒜` endowed with the Zariski topology. -/ noncomputable section open DirectSum Pointwise SetLike TopCat TopologicalSpace CategoryTheory Opposite variable {R A : Type*} variable [CommSemiring R] [CommRing A] [Algebra R A] variable (𝒜 : ℕ → Submodule R A) [GradedAlgebra 𝒜] /-- The projective spectrum of a graded commutative ring is the subtype of all homogeneous ideals that are prime and do not contain the irrelevant ideal. -/ @[ext] structure ProjectiveSpectrum where asHomogeneousIdeal : HomogeneousIdeal 𝒜 isPrime : asHomogeneousIdeal.toIdeal.IsPrime not_irrelevant_le : ¬HomogeneousIdeal.irrelevant 𝒜 ≤ asHomogeneousIdeal attribute [instance] ProjectiveSpectrum.isPrime namespace ProjectiveSpectrum instance (x : ProjectiveSpectrum 𝒜) : Ideal.IsPrime x.asHomogeneousIdeal.toIdeal := x.isPrime /-- The zero locus of a set `s` of elements of a commutative ring `A` is the set of all relevant homogeneous prime ideals of the ring that contain the set `s`. An element `f` of `A` can be thought of as a dependent function on the projective spectrum of `𝒜`. At a point `x` (a homogeneous prime ideal) the function (i.e., element) `f` takes values in the quotient ring `A` modulo the prime ideal `x`. In this manner, `zeroLocus s` is exactly the subset of `ProjectiveSpectrum 𝒜` where all "functions" in `s` vanish simultaneously. -/ def zeroLocus (s : Set A) : Set (ProjectiveSpectrum 𝒜) := { x | s ⊆ x.asHomogeneousIdeal } @[simp] theorem mem_zeroLocus (x : ProjectiveSpectrum 𝒜) (s : Set A) : x ∈ zeroLocus 𝒜 s ↔ s ⊆ x.asHomogeneousIdeal := Iff.rfl @[simp] theorem zeroLocus_span (s : Set A) : zeroLocus 𝒜 (Ideal.span s) = zeroLocus 𝒜 s := by ext x exact (Submodule.gi _ _).gc s x.asHomogeneousIdeal.toIdeal variable {𝒜} /-- The vanishing ideal of a set `t` of points of the projective spectrum of a commutative ring `R` is the intersection of all the relevant homogeneous prime ideals in the set `t`. An element `f` of `A` can be thought of as a dependent function on the projective spectrum of `𝒜`. At a point `x` (a homogeneous prime ideal) the function (i.e., element) `f` takes values in the quotient ring `A` modulo the prime ideal `x`. In this manner, `vanishingIdeal t` is exactly the ideal of `A` consisting of all "functions" that vanish on all of `t`. -/ def vanishingIdeal (t : Set (ProjectiveSpectrum 𝒜)) : HomogeneousIdeal 𝒜 := ⨅ (x : ProjectiveSpectrum 𝒜) (_ : x ∈ t), x.asHomogeneousIdeal theorem coe_vanishingIdeal (t : Set (ProjectiveSpectrum 𝒜)) : (vanishingIdeal t : Set A) = { f | ∀ x : ProjectiveSpectrum 𝒜, x ∈ t → f ∈ x.asHomogeneousIdeal } := by ext f rw [vanishingIdeal, SetLike.mem_coe, ← HomogeneousIdeal.mem_iff, HomogeneousIdeal.toIdeal_iInf, Submodule.mem_iInf] refine forall_congr' fun x => ?_ rw [HomogeneousIdeal.toIdeal_iInf, Submodule.mem_iInf, HomogeneousIdeal.mem_iff] theorem mem_vanishingIdeal (t : Set (ProjectiveSpectrum 𝒜)) (f : A) : f ∈ vanishingIdeal t ↔ ∀ x : ProjectiveSpectrum 𝒜, x ∈ t → f ∈ x.asHomogeneousIdeal := by rw [← SetLike.mem_coe, coe_vanishingIdeal, Set.mem_setOf_eq] @[simp] theorem vanishingIdeal_singleton (x : ProjectiveSpectrum 𝒜) : vanishingIdeal ({x} : Set (ProjectiveSpectrum 𝒜)) = x.asHomogeneousIdeal := by simp [vanishingIdeal] theorem subset_zeroLocus_iff_le_vanishingIdeal (t : Set (ProjectiveSpectrum 𝒜)) (I : Ideal A) : t ⊆ zeroLocus 𝒜 I ↔ I ≤ (vanishingIdeal t).toIdeal := ⟨fun h _ k => (mem_vanishingIdeal _ _).mpr fun _ j => (mem_zeroLocus _ _ _).mpr (h j) k, fun h => fun x j => (mem_zeroLocus _ _ _).mpr (le_trans h fun _ h => ((mem_vanishingIdeal _ _).mp h) x j)⟩ variable (𝒜) /-- `zeroLocus` and `vanishingIdeal` form a galois connection. -/ theorem gc_ideal : @GaloisConnection (Ideal A) (Set (ProjectiveSpectrum 𝒜))ᵒᵈ _ _ (fun I => zeroLocus 𝒜 I) fun t => (vanishingIdeal t).toIdeal := fun I t => subset_zeroLocus_iff_le_vanishingIdeal t I /-- `zeroLocus` and `vanishingIdeal` form a galois connection. -/ theorem gc_set : @GaloisConnection (Set A) (Set (ProjectiveSpectrum 𝒜))ᵒᵈ _ _ (fun s => zeroLocus 𝒜 s) fun t => vanishingIdeal t := by have ideal_gc : GaloisConnection Ideal.span _ := (Submodule.gi A _).gc simpa [zeroLocus_span, Function.comp_def] using GaloisConnection.compose ideal_gc (gc_ideal 𝒜) theorem gc_homogeneousIdeal : @GaloisConnection (HomogeneousIdeal 𝒜) (Set (ProjectiveSpectrum 𝒜))ᵒᵈ _ _ (fun I => zeroLocus 𝒜 I) fun t => vanishingIdeal t := fun I t => by simpa [show I.toIdeal ≤ (vanishingIdeal t).toIdeal ↔ I ≤ vanishingIdeal t from Iff.rfl] using subset_zeroLocus_iff_le_vanishingIdeal t I.toIdeal theorem subset_zeroLocus_iff_subset_vanishingIdeal (t : Set (ProjectiveSpectrum 𝒜)) (s : Set A) : t ⊆ zeroLocus 𝒜 s ↔ s ⊆ vanishingIdeal t := (gc_set _) s t theorem subset_vanishingIdeal_zeroLocus (s : Set A) : s ⊆ vanishingIdeal (zeroLocus 𝒜 s) :=
(gc_set _).le_u_l s theorem ideal_le_vanishingIdeal_zeroLocus (I : Ideal A) : I ≤ (vanishingIdeal (zeroLocus 𝒜 I)).toIdeal := (gc_ideal _).le_u_l I
Mathlib/AlgebraicGeometry/ProjectiveSpectrum/Topology.lean
144
149
/- Copyright (c) 2021 Luke Kershaw. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Luke Kershaw, Joël Riou -/ import Mathlib.Algebra.Homology.ShortComplex.Basic import Mathlib.CategoryTheory.Limits.Constructions.FiniteProductsOfBinaryProducts import Mathlib.CategoryTheory.Triangulated.TriangleShift /-! # Pretriangulated Categories This file contains the definition of pretriangulated categories and triangulated functors between them. ## Implementation Notes We work under the assumption that pretriangulated categories are preadditive categories, but not necessarily additive categories, as is assumed in some sources. TODO: generalise this to n-angulated categories as in https://arxiv.org/abs/1006.4592 -/ assert_not_exists TwoSidedIdeal noncomputable section open CategoryTheory Preadditive Limits universe v v₀ v₁ v₂ u u₀ u₁ u₂ namespace CategoryTheory open Category Pretriangulated ZeroObject /- We work in a preadditive category `C` equipped with an additive shift. -/ variable (C : Type u) [Category.{v} C] [HasZeroObject C] [HasShift C ℤ] [Preadditive C] /-- A preadditive category `C` with an additive shift, and a class of "distinguished triangles" relative to that shift is called pretriangulated if the following hold: * Any triangle that is isomorphic to a distinguished triangle is also distinguished. * Any triangle of the form `(X,X,0,id,0,0)` is distinguished. * For any morphism `f : X ⟶ Y` there exists a distinguished triangle of the form `(X,Y,Z,f,g,h)`. * The triangle `(X,Y,Z,f,g,h)` is distinguished if and only if `(Y,Z,X⟦1⟧,g,h,-f⟦1⟧)` is. * Given a diagram: ``` f g h X ───> Y ───> Z ───> X⟦1⟧ │ │ │ │a │b │a⟦1⟧' V V V X' ───> Y' ───> Z' ───> X'⟦1⟧ f' g' h' ``` where the left square commutes, and whose rows are distinguished triangles, there exists a morphism `c : Z ⟶ Z'` such that `(a,b,c)` is a triangle morphism. -/ @[stacks 0145] class Pretriangulated [∀ n : ℤ, Functor.Additive (shiftFunctor C n)] where /-- a class of triangle which are called `distinguished` -/ distinguishedTriangles : Set (Triangle C) /-- a triangle that is isomorphic to a distinguished triangle is distinguished -/ isomorphic_distinguished : ∀ T₁ ∈ distinguishedTriangles, ∀ (T₂) (_ : T₂ ≅ T₁), T₂ ∈ distinguishedTriangles /-- obvious triangles `X ⟶ X ⟶ 0 ⟶ X⟦1⟧` are distinguished -/ contractible_distinguished : ∀ X : C, contractibleTriangle X ∈ distinguishedTriangles /-- any morphism `X ⟶ Y` is part of a distinguished triangle `X ⟶ Y ⟶ Z ⟶ X⟦1⟧` -/ distinguished_cocone_triangle : ∀ {X Y : C} (f : X ⟶ Y), ∃ (Z : C) (g : Y ⟶ Z) (h : Z ⟶ X⟦(1 : ℤ)⟧), Triangle.mk f g h ∈ distinguishedTriangles /-- a triangle is distinguished iff it is so after rotating it -/ rotate_distinguished_triangle : ∀ T : Triangle C, T ∈ distinguishedTriangles ↔ T.rotate ∈ distinguishedTriangles /-- given two distinguished triangle, a commutative square can be extended as morphism of triangles -/ complete_distinguished_triangle_morphism : ∀ (T₁ T₂ : Triangle C) (_ : T₁ ∈ distinguishedTriangles) (_ : T₂ ∈ distinguishedTriangles) (a : T₁.obj₁ ⟶ T₂.obj₁) (b : T₁.obj₂ ⟶ T₂.obj₂) (_ : T₁.mor₁ ≫ b = a ≫ T₂.mor₁), ∃ c : T₁.obj₃ ⟶ T₂.obj₃, T₁.mor₂ ≫ c = b ≫ T₂.mor₂ ∧ T₁.mor₃ ≫ a⟦1⟧' = c ≫ T₂.mor₃ namespace Pretriangulated variable [∀ n : ℤ, Functor.Additive (CategoryTheory.shiftFunctor C n)] [hC : Pretriangulated C] -- Porting note: increased the priority so that we can write `T ∈ distTriang C`, and -- not just `T ∈ (distTriang C)` /-- distinguished triangles in a pretriangulated category -/ notation:60 "distTriang " C => @distinguishedTriangles C _ _ _ _ _ _ variable {C} lemma distinguished_iff_of_iso {T₁ T₂ : Triangle C} (e : T₁ ≅ T₂) : (T₁ ∈ distTriang C) ↔ T₂ ∈ distTriang C := ⟨fun hT₁ => isomorphic_distinguished _ hT₁ _ e.symm, fun hT₂ => isomorphic_distinguished _ hT₂ _ e⟩ /-- Given any distinguished triangle `T`, then we know `T.rotate` is also distinguished. -/ theorem rot_of_distTriang (T : Triangle C) (H : T ∈ distTriang C) : T.rotate ∈ distTriang C := (rotate_distinguished_triangle T).mp H /-- Given any distinguished triangle `T`, then we know `T.inv_rotate` is also distinguished. -/ theorem inv_rot_of_distTriang (T : Triangle C) (H : T ∈ distTriang C) : T.invRotate ∈ distTriang C := (rotate_distinguished_triangle T.invRotate).mpr (isomorphic_distinguished T H T.invRotate.rotate (invRotCompRot.app T)) /-- Given any distinguished triangle ``` f g h X ───> Y ───> Z ───> X⟦1⟧ ``` the composition `f ≫ g = 0`. -/ @[reassoc, stacks 0146] theorem comp_distTriang_mor_zero₁₂ (T) (H : T ∈ (distTriang C)) : T.mor₁ ≫ T.mor₂ = 0 := by obtain ⟨c, hc⟩ := complete_distinguished_triangle_morphism _ _ (contractible_distinguished T.obj₁) H (𝟙 T.obj₁) T.mor₁ rfl simpa only [contractibleTriangle_mor₂, zero_comp] using hc.left.symm /-- Given any distinguished triangle ``` f g h X ───> Y ───> Z ───> X⟦1⟧ ``` the composition `g ≫ h = 0`. -/ @[reassoc, stacks 0146] theorem comp_distTriang_mor_zero₂₃ (T : Triangle C) (H : T ∈ distTriang C) : T.mor₂ ≫ T.mor₃ = 0 := comp_distTriang_mor_zero₁₂ T.rotate (rot_of_distTriang T H) /-- Given any distinguished triangle ``` f g h X ───> Y ───> Z ───> X⟦1⟧ ``` the composition `h ≫ f⟦1⟧ = 0`. -/ @[reassoc, stacks 0146] theorem comp_distTriang_mor_zero₃₁ (T : Triangle C) (H : T ∈ distTriang C) : T.mor₃ ≫ T.mor₁⟦1⟧' = 0 := by have H₂ := rot_of_distTriang T.rotate (rot_of_distTriang T H) simpa using comp_distTriang_mor_zero₁₂ T.rotate.rotate H₂ /-- The short complex `T.obj₁ ⟶ T.obj₂ ⟶ T.obj₃` attached to a distinguished triangle. -/ @[simps] def shortComplexOfDistTriangle (T : Triangle C) (hT : T ∈ distTriang C) : ShortComplex C := ShortComplex.mk T.mor₁ T.mor₂ (comp_distTriang_mor_zero₁₂ _ hT) /-- The isomorphism between the short complex attached to two isomorphic distinguished triangles. -/ @[simps!] def shortComplexOfDistTriangleIsoOfIso {T T' : Triangle C} (e : T ≅ T') (hT : T ∈ distTriang C) : shortComplexOfDistTriangle T hT ≅ shortComplexOfDistTriangle T' (isomorphic_distinguished _ hT _ e.symm) := ShortComplex.isoMk (Triangle.π₁.mapIso e) (Triangle.π₂.mapIso e) (Triangle.π₃.mapIso e) /-- Any morphism `Y ⟶ Z` is part of a distinguished triangle `X ⟶ Y ⟶ Z ⟶ X⟦1⟧` -/ lemma distinguished_cocone_triangle₁ {Y Z : C} (g : Y ⟶ Z) : ∃ (X : C) (f : X ⟶ Y) (h : Z ⟶ X⟦(1 : ℤ)⟧), Triangle.mk f g h ∈ distTriang C := by obtain ⟨X', f', g', mem⟩ := distinguished_cocone_triangle g exact ⟨_, _, _, inv_rot_of_distTriang _ mem⟩ /-- Any morphism `Z ⟶ X⟦1⟧` is part of a distinguished triangle `X ⟶ Y ⟶ Z ⟶ X⟦1⟧` -/ lemma distinguished_cocone_triangle₂ {Z X : C} (h : Z ⟶ X⟦(1 : ℤ)⟧) : ∃ (Y : C) (f : X ⟶ Y) (g : Y ⟶ Z), Triangle.mk f g h ∈ distTriang C := by obtain ⟨Y', f', g', mem⟩ := distinguished_cocone_triangle h let T' := (Triangle.mk h f' g').invRotate.invRotate refine ⟨T'.obj₂, ((shiftEquiv C (1 : ℤ)).unitIso.app X).hom ≫ T'.mor₁, T'.mor₂, isomorphic_distinguished _ (inv_rot_of_distTriang _ (inv_rot_of_distTriang _ mem)) _ ?_⟩ exact Triangle.isoMk _ _ ((shiftEquiv C (1 : ℤ)).unitIso.app X) (Iso.refl _) (Iso.refl _) (by aesop_cat) (by aesop_cat) (by dsimp; simp only [shift_shiftFunctorCompIsoId_inv_app, id_comp]) /-- A commutative square involving the morphisms `mor₂` of two distinguished triangles can be extended as morphism of triangles -/ lemma complete_distinguished_triangle_morphism₁ (T₁ T₂ : Triangle C) (hT₁ : T₁ ∈ distTriang C) (hT₂ : T₂ ∈ distTriang C) (b : T₁.obj₂ ⟶ T₂.obj₂) (c : T₁.obj₃ ⟶ T₂.obj₃) (comm : T₁.mor₂ ≫ c = b ≫ T₂.mor₂) : ∃ (a : T₁.obj₁ ⟶ T₂.obj₁), T₁.mor₁ ≫ b = a ≫ T₂.mor₁ ∧ T₁.mor₃ ≫ a⟦(1 : ℤ)⟧' = c ≫ T₂.mor₃ := by obtain ⟨a, ⟨ha₁, ha₂⟩⟩ := complete_distinguished_triangle_morphism _ _ (rot_of_distTriang _ hT₁) (rot_of_distTriang _ hT₂) b c comm refine ⟨(shiftFunctor C (1 : ℤ)).preimage a, ⟨?_, ?_⟩⟩ · apply (shiftFunctor C (1 : ℤ)).map_injective dsimp at ha₂ rw [neg_comp, comp_neg, neg_inj] at ha₂ simpa only [Functor.map_comp, Functor.map_preimage] using ha₂ · simpa only [Functor.map_preimage] using ha₁ /-- A commutative square involving the morphisms `mor₃` of two distinguished triangles can be extended as morphism of triangles -/ lemma complete_distinguished_triangle_morphism₂ (T₁ T₂ : Triangle C) (hT₁ : T₁ ∈ distTriang C) (hT₂ : T₂ ∈ distTriang C) (a : T₁.obj₁ ⟶ T₂.obj₁) (c : T₁.obj₃ ⟶ T₂.obj₃) (comm : T₁.mor₃ ≫ a⟦(1 : ℤ)⟧' = c ≫ T₂.mor₃) : ∃ (b : T₁.obj₂ ⟶ T₂.obj₂), T₁.mor₁ ≫ b = a ≫ T₂.mor₁ ∧ T₁.mor₂ ≫ c = b ≫ T₂.mor₂ := by obtain ⟨a, ⟨ha₁, ha₂⟩⟩ := complete_distinguished_triangle_morphism _ _ (inv_rot_of_distTriang _ hT₁) (inv_rot_of_distTriang _ hT₂) (c⟦(-1 : ℤ)⟧') a (by dsimp simp only [neg_comp, comp_neg, ← Functor.map_comp_assoc, ← comm, Functor.map_comp, shift_shift_neg', Functor.id_obj, assoc, Iso.inv_hom_id_app, comp_id]) refine ⟨a, ⟨ha₁, ?_⟩⟩ dsimp only [Triangle.invRotate, Triangle.mk] at ha₂ rw [← cancel_mono ((shiftEquiv C (1 : ℤ)).counitIso.inv.app T₂.obj₃), assoc, assoc, ← ha₂] simp only [shiftEquiv'_counitIso, shift_neg_shift', assoc, Iso.inv_hom_id_app_assoc] /-- Obvious triangles `0 ⟶ X ⟶ X ⟶ 0⟦1⟧` are distinguished -/ lemma contractible_distinguished₁ (X : C) : Triangle.mk (0 : 0 ⟶ X) (𝟙 X) 0 ∈ distTriang C := by refine isomorphic_distinguished _ (inv_rot_of_distTriang _ (contractible_distinguished X)) _ ?_ exact Triangle.isoMk _ _ (Functor.mapZeroObject _).symm (Iso.refl _) (Iso.refl _) (by simp) (by simp) (by simp) /-- Obvious triangles `X ⟶ 0 ⟶ X⟦1⟧ ⟶ X⟦1⟧` are distinguished -/ lemma contractible_distinguished₂ (X : C) : Triangle.mk (0 : X ⟶ 0) 0 (𝟙 (X⟦1⟧)) ∈ distTriang C := by refine isomorphic_distinguished _ (inv_rot_of_distTriang _ (contractible_distinguished₁ (X⟦(1 : ℤ)⟧))) _ ?_ exact Triangle.isoMk _ _ ((shiftEquiv C (1 : ℤ)).unitIso.app X) (Iso.refl _) (Iso.refl _) (by simp) (by simp) (by dsimp; simp only [shift_shiftFunctorCompIsoId_inv_app, id_comp]) namespace Triangle variable (T : Triangle C) (hT : T ∈ distTriang C) include hT lemma yoneda_exact₂ {X : C} (f : T.obj₂ ⟶ X) (hf : T.mor₁ ≫ f = 0) : ∃ (g : T.obj₃ ⟶ X), f = T.mor₂ ≫ g := by obtain ⟨g, ⟨hg₁, _⟩⟩ := complete_distinguished_triangle_morphism T _ hT (contractible_distinguished₁ X) 0 f (by aesop_cat) exact ⟨g, by simpa using hg₁.symm⟩ lemma yoneda_exact₃ {X : C} (f : T.obj₃ ⟶ X) (hf : T.mor₂ ≫ f = 0) : ∃ (g : T.obj₁⟦(1 : ℤ)⟧ ⟶ X), f = T.mor₃ ≫ g := yoneda_exact₂ _ (rot_of_distTriang _ hT) f hf lemma coyoneda_exact₂ {X : C} (f : X ⟶ T.obj₂) (hf : f ≫ T.mor₂ = 0) : ∃ (g : X ⟶ T.obj₁), f = g ≫ T.mor₁ := by obtain ⟨a, ⟨ha₁, _⟩⟩ := complete_distinguished_triangle_morphism₁ _ T (contractible_distinguished X) hT f 0 (by aesop_cat) exact ⟨a, by simpa using ha₁⟩ lemma coyoneda_exact₁ {X : C} (f : X ⟶ T.obj₁⟦(1 : ℤ)⟧) (hf : f ≫ T.mor₁⟦1⟧' = 0) : ∃ (g : X ⟶ T.obj₃), f = g ≫ T.mor₃ := coyoneda_exact₂ _ (rot_of_distTriang _ (rot_of_distTriang _ hT)) f (by aesop_cat) lemma coyoneda_exact₃ {X : C} (f : X ⟶ T.obj₃) (hf : f ≫ T.mor₃ = 0) : ∃ (g : X ⟶ T.obj₂), f = g ≫ T.mor₂ := coyoneda_exact₂ _ (rot_of_distTriang _ hT) f hf lemma mor₃_eq_zero_iff_epi₂ : T.mor₃ = 0 ↔ Epi T.mor₂ := by constructor · intro h rw [epi_iff_cancel_zero] intro X g hg obtain ⟨f, rfl⟩ := yoneda_exact₃ T hT g hg rw [h, zero_comp] · intro rw [← cancel_epi T.mor₂, comp_distTriang_mor_zero₂₃ _ hT, comp_zero] lemma mor₂_eq_zero_iff_epi₁ : T.mor₂ = 0 ↔ Epi T.mor₁ := by have h := mor₃_eq_zero_iff_epi₂ _ (inv_rot_of_distTriang _ hT) dsimp at h rw [← h, IsIso.comp_right_eq_zero] lemma mor₁_eq_zero_iff_epi₃ : T.mor₁ = 0 ↔ Epi T.mor₃ := by have h := mor₃_eq_zero_iff_epi₂ _ (rot_of_distTriang _ hT) dsimp at h rw [← h, neg_eq_zero] constructor · intro h simp only [h, Functor.map_zero] · intro h rw [← (CategoryTheory.shiftFunctor C (1 : ℤ)).map_eq_zero_iff, h] lemma mor₃_eq_zero_of_epi₂ (h : Epi T.mor₂) : T.mor₃ = 0 := (T.mor₃_eq_zero_iff_epi₂ hT).2 h lemma mor₂_eq_zero_of_epi₁ (h : Epi T.mor₁) : T.mor₂ = 0 := (T.mor₂_eq_zero_iff_epi₁ hT).2 h lemma mor₁_eq_zero_of_epi₃ (h : Epi T.mor₃) : T.mor₁ = 0 := (T.mor₁_eq_zero_iff_epi₃ hT).2 h lemma epi₂ (h : T.mor₃ = 0) : Epi T.mor₂ := (T.mor₃_eq_zero_iff_epi₂ hT).1 h lemma epi₁ (h : T.mor₂ = 0) : Epi T.mor₁ := (T.mor₂_eq_zero_iff_epi₁ hT).1 h lemma epi₃ (h : T.mor₁ = 0) : Epi T.mor₃ := (T.mor₁_eq_zero_iff_epi₃ hT).1 h lemma mor₁_eq_zero_iff_mono₂ : T.mor₁ = 0 ↔ Mono T.mor₂ := by constructor · intro h rw [mono_iff_cancel_zero] intro X g hg obtain ⟨f, rfl⟩ := coyoneda_exact₂ T hT g hg rw [h, comp_zero] · intro rw [← cancel_mono T.mor₂, comp_distTriang_mor_zero₁₂ _ hT, zero_comp] lemma mor₂_eq_zero_iff_mono₃ : T.mor₂ = 0 ↔ Mono T.mor₃ := mor₁_eq_zero_iff_mono₂ _ (rot_of_distTriang _ hT) lemma mor₃_eq_zero_iff_mono₁ : T.mor₃ = 0 ↔ Mono T.mor₁ := by have h := mor₁_eq_zero_iff_mono₂ _ (inv_rot_of_distTriang _ hT) dsimp at h rw [← h, neg_eq_zero, IsIso.comp_right_eq_zero] constructor · intro h simp only [h, Functor.map_zero] · intro h rw [← (CategoryTheory.shiftFunctor C (-1 : ℤ)).map_eq_zero_iff, h] lemma mor₁_eq_zero_of_mono₂ (h : Mono T.mor₂) : T.mor₁ = 0 := (T.mor₁_eq_zero_iff_mono₂ hT).2 h lemma mor₂_eq_zero_of_mono₃ (h : Mono T.mor₃) : T.mor₂ = 0 := (T.mor₂_eq_zero_iff_mono₃ hT).2 h lemma mor₃_eq_zero_of_mono₁ (h : Mono T.mor₁) : T.mor₃ = 0 := (T.mor₃_eq_zero_iff_mono₁ hT).2 h lemma mono₂ (h : T.mor₁ = 0) : Mono T.mor₂ := (T.mor₁_eq_zero_iff_mono₂ hT).1 h lemma mono₃ (h : T.mor₂ = 0) : Mono T.mor₃ := (T.mor₂_eq_zero_iff_mono₃ hT).1 h lemma mono₁ (h : T.mor₃ = 0) : Mono T.mor₁ := (T.mor₃_eq_zero_iff_mono₁ hT).1 h lemma isZero₂_iff : IsZero T.obj₂ ↔ (T.mor₁ = 0 ∧ T.mor₂ = 0) := by constructor · intro h exact ⟨h.eq_of_tgt _ _, h.eq_of_src _ _⟩ · intro ⟨h₁, h₂⟩ obtain ⟨f, hf⟩ := coyoneda_exact₂ T hT (𝟙 _) (by rw [h₂, comp_zero]) rw [IsZero.iff_id_eq_zero, hf, h₁, comp_zero] lemma isZero₁_iff : IsZero T.obj₁ ↔ (T.mor₁ = 0 ∧ T.mor₃ = 0) := by refine (isZero₂_iff _ (inv_rot_of_distTriang _ hT)).trans ?_ dsimp simp only [neg_eq_zero, IsIso.comp_right_eq_zero, Functor.map_eq_zero_iff] tauto lemma isZero₃_iff : IsZero T.obj₃ ↔ (T.mor₂ = 0 ∧ T.mor₃ = 0) := by refine (isZero₂_iff _ (rot_of_distTriang _ hT)).trans ?_ dsimp tauto lemma isZero₁_of_isZero₂₃ (h₂ : IsZero T.obj₂) (h₃ : IsZero T.obj₃) : IsZero T.obj₁ := by rw [T.isZero₁_iff hT] exact ⟨h₂.eq_of_tgt _ _, h₃.eq_of_src _ _⟩ lemma isZero₂_of_isZero₁₃ (h₁ : IsZero T.obj₁) (h₃ : IsZero T.obj₃) : IsZero T.obj₂ := by rw [T.isZero₂_iff hT] exact ⟨h₁.eq_of_src _ _, h₃.eq_of_tgt _ _⟩ lemma isZero₃_of_isZero₁₂ (h₁ : IsZero T.obj₁) (h₂ : IsZero T.obj₂) : IsZero T.obj₃ := isZero₂_of_isZero₁₃ _ (rot_of_distTriang _ hT) h₂ (by dsimp simp only [IsZero.iff_id_eq_zero] at h₁ ⊢ rw [← Functor.map_id, h₁, Functor.map_zero]) lemma isZero₁_iff_isIso₂ : IsZero T.obj₁ ↔ IsIso T.mor₂ := by rw [T.isZero₁_iff hT] constructor · intro ⟨h₁, h₃⟩ have := T.epi₂ hT h₃ obtain ⟨f, hf⟩ := yoneda_exact₂ T hT (𝟙 _) (by rw [h₁, zero_comp]) exact ⟨f, hf.symm, by rw [← cancel_epi T.mor₂, comp_id, ← reassoc_of% hf]⟩ · intro rw [T.mor₁_eq_zero_iff_mono₂ hT, T.mor₃_eq_zero_iff_epi₂ hT] constructor <;> infer_instance lemma isZero₂_iff_isIso₃ : IsZero T.obj₂ ↔ IsIso T.mor₃ := isZero₁_iff_isIso₂ _ (rot_of_distTriang _ hT) lemma isZero₃_iff_isIso₁ : IsZero T.obj₃ ↔ IsIso T.mor₁ := by refine Iff.trans ?_ (Triangle.isZero₁_iff_isIso₂ _ (inv_rot_of_distTriang _ hT)) dsimp simp only [IsZero.iff_id_eq_zero, ← Functor.map_id, Functor.map_eq_zero_iff] lemma isZero₁_of_isIso₂ (h : IsIso T.mor₂) : IsZero T.obj₁ := (T.isZero₁_iff_isIso₂ hT).2 h lemma isZero₂_of_isIso₃ (h : IsIso T.mor₃) : IsZero T.obj₂ := (T.isZero₂_iff_isIso₃ hT).2 h lemma isZero₃_of_isIso₁ (h : IsIso T.mor₁) : IsZero T.obj₃ := (T.isZero₃_iff_isIso₁ hT).2 h lemma shift_distinguished (n : ℤ) : (CategoryTheory.shiftFunctor (Triangle C) n).obj T ∈ distTriang C := by revert T hT let H : ℤ → Prop := fun n => ∀ (T : Triangle C) (_ : T ∈ distTriang C), (Triangle.shiftFunctor C n).obj T ∈ distTriang C change H n have H_zero : H 0 := fun T hT => isomorphic_distinguished _ hT _ ((Triangle.shiftFunctorZero C).app T) have H_one : H 1 := fun T hT => isomorphic_distinguished _ (rot_of_distTriang _ (rot_of_distTriang _ (rot_of_distTriang _ hT))) _ ((rotateRotateRotateIso C).symm.app T) have H_neg_one : H (-1) := fun T hT => isomorphic_distinguished _ (inv_rot_of_distTriang _ (inv_rot_of_distTriang _ (inv_rot_of_distTriang _ hT))) _ ((invRotateInvRotateInvRotateIso C).symm.app T) have H_add : ∀ {a b c : ℤ}, H a → H b → a + b = c → H c := fun {a b c} ha hb hc T hT => isomorphic_distinguished _ (hb _ (ha _ hT)) _ ((Triangle.shiftFunctorAdd' C _ _ _ hc).app T) obtain (n|n) := n · induction n with | zero => exact H_zero | succ n hn => exact H_add hn H_one rfl · induction n with | zero => exact H_neg_one | succ n hn => exact H_add hn H_neg_one rfl end Triangle instance : SplitEpiCategory C where isSplitEpi_of_epi f hf := by obtain ⟨Z, g, h, hT⟩ := distinguished_cocone_triangle f obtain ⟨r, hr⟩ := Triangle.coyoneda_exact₂ _ hT (𝟙 _) (by rw [Triangle.mor₂_eq_zero_of_epi₁ _ hT hf, comp_zero]) exact ⟨r, hr.symm⟩ instance : SplitMonoCategory C where isSplitMono_of_mono f hf := by obtain ⟨X, g, h, hT⟩ := distinguished_cocone_triangle₁ f obtain ⟨r, hr⟩ := Triangle.yoneda_exact₂ _ hT (𝟙 _) (by rw [Triangle.mor₁_eq_zero_of_mono₂ _ hT hf, zero_comp]) exact ⟨r, hr.symm⟩ lemma isIso₂_of_isIso₁₃ {T T' : Triangle C} (φ : T ⟶ T') (hT : T ∈ distTriang C) (hT' : T' ∈ distTriang C) (h₁ : IsIso φ.hom₁) (h₃ : IsIso φ.hom₃) : IsIso φ.hom₂ := by have : Mono φ.hom₂ := by rw [mono_iff_cancel_zero] intro A f hf obtain ⟨g, rfl⟩ := Triangle.coyoneda_exact₂ _ hT f (by rw [← cancel_mono φ.hom₃, assoc, φ.comm₂, reassoc_of% hf, zero_comp, zero_comp]) rw [assoc] at hf obtain ⟨h, hh⟩ := Triangle.coyoneda_exact₂ T'.invRotate (inv_rot_of_distTriang _ hT') (g ≫ φ.hom₁) (by dsimp; rw [assoc, ← φ.comm₁, hf]) obtain ⟨k, rfl⟩ : ∃ (k : A ⟶ T.invRotate.obj₁), k ≫ T.invRotate.mor₁ = g := by refine ⟨h ≫ inv (φ.hom₃⟦(-1 : ℤ)⟧'), ?_⟩ have eq := ((invRotate C).map φ).comm₁ dsimp only [invRotate] at eq rw [← cancel_mono φ.hom₁, assoc, assoc, eq, IsIso.inv_hom_id_assoc, hh] erw [assoc, comp_distTriang_mor_zero₁₂ _ (inv_rot_of_distTriang _ hT), comp_zero] refine isIso_of_yoneda_map_bijective _ (fun A => ⟨?_, ?_⟩) · intro f₁ f₂ h simpa only [← cancel_mono φ.hom₂] using h · intro y₂ obtain ⟨x₃, hx₃⟩ : ∃ (x₃ : A ⟶ T.obj₃), x₃ ≫ φ.hom₃ = y₂ ≫ T'.mor₂ := ⟨y₂ ≫ T'.mor₂ ≫ inv φ.hom₃, by simp⟩ obtain ⟨x₂, hx₂⟩ := Triangle.coyoneda_exact₃ _ hT x₃ (by rw [← cancel_mono (φ.hom₁⟦(1 : ℤ)⟧'), assoc, zero_comp, φ.comm₃, reassoc_of% hx₃, comp_distTriang_mor_zero₂₃ _ hT', comp_zero]) obtain ⟨y₁, hy₁⟩ := Triangle.coyoneda_exact₂ _ hT' (y₂ - x₂ ≫ φ.hom₂) (by rw [sub_comp, assoc, ← φ.comm₂, ← reassoc_of% hx₂, hx₃, sub_self]) obtain ⟨x₁, hx₁⟩ : ∃ (x₁ : A ⟶ T.obj₁), x₁ ≫ φ.hom₁ = y₁ := ⟨y₁ ≫ inv φ.hom₁, by simp⟩ refine ⟨x₂ + x₁ ≫ T.mor₁, ?_⟩ dsimp rw [add_comp, assoc, φ.comm₁, reassoc_of% hx₁, ← hy₁, add_sub_cancel] lemma isIso₃_of_isIso₁₂ {T T' : Triangle C} (φ : T ⟶ T') (hT : T ∈ distTriang C) (hT' : T' ∈ distTriang C) (h₁ : IsIso φ.hom₁) (h₂ : IsIso φ.hom₂) : IsIso φ.hom₃ := isIso₂_of_isIso₁₃ ((rotate C).map φ) (rot_of_distTriang _ hT) (rot_of_distTriang _ hT') h₂ (by dsimp; infer_instance) lemma isIso₁_of_isIso₂₃ {T T' : Triangle C} (φ : T ⟶ T') (hT : T ∈ distTriang C) (hT' : T' ∈ distTriang C) (h₂ : IsIso φ.hom₂) (h₃ : IsIso φ.hom₃) : IsIso φ.hom₁ := isIso₂_of_isIso₁₃ ((invRotate C).map φ) (inv_rot_of_distTriang _ hT) (inv_rot_of_distTriang _ hT') (by dsimp; infer_instance) (by dsimp; infer_instance) /-- Given a distinguished triangle `T` such that `T.mor₃ = 0` and the datum of morphisms `inr : T.obj₃ ⟶ T.obj₂` and `fst : T.obj₂ ⟶ T.obj₁` satisfying suitable relations, this is the binary biproduct data expressing that `T.obj₂` identifies to the binary biproduct of `T.obj₁` and `T.obj₃`. See also `exists_iso_binaryBiproduct_of_distTriang`. -/ @[simps] def binaryBiproductData (T : Triangle C) (hT : T ∈ distTriang C) (hT₀ : T.mor₃ = 0) (inr : T.obj₃ ⟶ T.obj₂) (inr_snd : inr ≫ T.mor₂ = 𝟙 _) (fst : T.obj₂ ⟶ T.obj₁)
(total : fst ≫ T.mor₁ + T.mor₂ ≫ inr = 𝟙 T.obj₂) : BinaryBiproductData T.obj₁ T.obj₃ := by have : Mono T.mor₁ := T.mono₁ hT hT₀ have eq : fst ≫ T.mor₁ = 𝟙 T.obj₂ - T.mor₂ ≫ inr := by rw [← total, add_sub_cancel_right]
Mathlib/CategoryTheory/Triangulated/Pretriangulated.lean
470
473
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Kim Morrison -/ import Mathlib.Algebra.Group.Indicator import Mathlib.Algebra.Group.InjSurj import Mathlib.Data.Set.Finite.Basic import Mathlib.Tactic.FastInstance import Mathlib.Algebra.Group.Equiv.Defs /-! # Type of functions with finite support For any type `α` and any type `M` with zero, we define the type `Finsupp α M` (notation: `α →₀ M`) of finitely supported functions from `α` to `M`, i.e. the functions which are zero everywhere on `α` except on a finite set. Functions with finite support are used (at least) in the following parts of the library: * `MonoidAlgebra R M` and `AddMonoidAlgebra R M` are defined as `M →₀ R`; * polynomials and multivariate polynomials are defined as `AddMonoidAlgebra`s, hence they use `Finsupp` under the hood; * the linear combination of a family of vectors `v i` with coefficients `f i` (as used, e.g., to define linearly independent family `LinearIndependent`) is defined as a map `Finsupp.linearCombination : (ι → M) → (ι →₀ R) →ₗ[R] M`. Some other constructions are naturally equivalent to `α →₀ M` with some `α` and `M` but are defined in a different way in the library: * `Multiset α ≃+ α →₀ ℕ`; * `FreeAbelianGroup α ≃+ α →₀ ℤ`. Most of the theory assumes that the range is a commutative additive monoid. This gives us the big sum operator as a powerful way to construct `Finsupp` elements, which is defined in `Mathlib.Algebra.BigOperators.Finsupp.Basic`. Many constructions based on `α →₀ M` are `def`s rather than `abbrev`s to avoid reusing unwanted type class instances. E.g., `MonoidAlgebra`, `AddMonoidAlgebra`, and types based on these two have non-pointwise multiplication. ## Main declarations * `Finsupp`: The type of finitely supported functions from `α` to `β`. * `Finsupp.onFinset`: The restriction of a function to a `Finset` as a `Finsupp`. * `Finsupp.mapRange`: Composition of a `ZeroHom` with a `Finsupp`. * `Finsupp.embDomain`: Maps the domain of a `Finsupp` by an embedding. * `Finsupp.zipWith`: Postcomposition of two `Finsupp`s with a function `f` such that `f 0 0 = 0`. ## Notations This file adds `α →₀ M` as a global notation for `Finsupp α M`. We also use the following convention for `Type*` variables in this file * `α`, `β`, `γ`: types with no additional structure that appear as the first argument to `Finsupp` somewhere in the statement; * `ι` : an auxiliary index type; * `M`, `M'`, `N`, `P`: types with `Zero` or `(Add)(Comm)Monoid` structure; `M` is also used for a (semi)module over a (semi)ring. * `G`, `H`: groups (commutative or not, multiplicative or additive); * `R`, `S`: (semi)rings. ## Implementation notes This file is a `noncomputable theory` and uses classical logic throughout. ## TODO * Expand the list of definitions and important lemmas to the module docstring. -/ assert_not_exists CompleteLattice Submonoid noncomputable section open Finset Function variable {α β γ ι M M' N P G H R S : Type*} /-- `Finsupp α M`, denoted `α →₀ M`, is the type of functions `f : α → M` such that `f x = 0` for all but finitely many `x`. -/ structure Finsupp (α : Type*) (M : Type*) [Zero M] where /-- The support of a finitely supported function (aka `Finsupp`). -/ support : Finset α /-- The underlying function of a bundled finitely supported function (aka `Finsupp`). -/ toFun : α → M /-- The witness that the support of a `Finsupp` is indeed the exact locus where its underlying function is nonzero. -/ mem_support_toFun : ∀ a, a ∈ support ↔ toFun a ≠ 0 @[inherit_doc] infixr:25 " →₀ " => Finsupp namespace Finsupp /-! ### Basic declarations about `Finsupp` -/ section Basic variable [Zero M] instance instFunLike : FunLike (α →₀ M) α M := ⟨toFun, by rintro ⟨s, f, hf⟩ ⟨t, g, hg⟩ (rfl : f = g) congr ext a exact (hf _).trans (hg _).symm⟩ @[ext] theorem ext {f g : α →₀ M} (h : ∀ a, f a = g a) : f = g := DFunLike.ext _ _ h lemma ne_iff {f g : α →₀ M} : f ≠ g ↔ ∃ a, f a ≠ g a := DFunLike.ne_iff @[simp, norm_cast] theorem coe_mk (f : α → M) (s : Finset α) (h : ∀ a, a ∈ s ↔ f a ≠ 0) : ⇑(⟨s, f, h⟩ : α →₀ M) = f := rfl instance instZero : Zero (α →₀ M) := ⟨⟨∅, 0, fun _ => ⟨fun h ↦ (not_mem_empty _ h).elim, fun H => (H rfl).elim⟩⟩⟩ @[simp, norm_cast] lemma coe_zero : ⇑(0 : α →₀ M) = 0 := rfl theorem zero_apply {a : α} : (0 : α →₀ M) a = 0 := rfl @[simp] theorem support_zero : (0 : α →₀ M).support = ∅ := rfl instance instInhabited : Inhabited (α →₀ M) := ⟨0⟩ @[simp] theorem mem_support_iff {f : α →₀ M} : ∀ {a : α}, a ∈ f.support ↔ f a ≠ 0 := @(f.mem_support_toFun) @[simp, norm_cast] theorem fun_support_eq (f : α →₀ M) : Function.support f = f.support := Set.ext fun _x => mem_support_iff.symm theorem not_mem_support_iff {f : α →₀ M} {a} : a ∉ f.support ↔ f a = 0 := not_iff_comm.1 mem_support_iff.symm @[simp, norm_cast] theorem coe_eq_zero {f : α →₀ M} : (f : α → M) = 0 ↔ f = 0 := by rw [← coe_zero, DFunLike.coe_fn_eq] theorem ext_iff' {f g : α →₀ M} : f = g ↔ f.support = g.support ∧ ∀ x ∈ f.support, f x = g x := ⟨fun h => h ▸ ⟨rfl, fun _ _ => rfl⟩, fun ⟨h₁, h₂⟩ => ext fun a => by classical exact if h : a ∈ f.support then h₂ a h else by have hf : f a = 0 := not_mem_support_iff.1 h have hg : g a = 0 := by rwa [h₁, not_mem_support_iff] at h rw [hf, hg]⟩ @[simp] theorem support_eq_empty {f : α →₀ M} : f.support = ∅ ↔ f = 0 := mod_cast @Function.support_eq_empty_iff _ _ _ f theorem support_nonempty_iff {f : α →₀ M} : f.support.Nonempty ↔ f ≠ 0 := by simp only [Finsupp.support_eq_empty, Finset.nonempty_iff_ne_empty, Ne] theorem card_support_eq_zero {f : α →₀ M} : #f.support = 0 ↔ f = 0 := by simp instance instDecidableEq [DecidableEq α] [DecidableEq M] : DecidableEq (α →₀ M) := fun f g => decidable_of_iff (f.support = g.support ∧ ∀ a ∈ f.support, f a = g a) ext_iff'.symm theorem finite_support (f : α →₀ M) : Set.Finite (Function.support f) := f.fun_support_eq.symm ▸ f.support.finite_toSet theorem support_subset_iff {s : Set α} {f : α →₀ M} : ↑f.support ⊆ s ↔ ∀ a ∉ s, f a = 0 := by simp only [Set.subset_def, mem_coe, mem_support_iff]; exact forall_congr' fun a => not_imp_comm /-- Given `Finite α`, `equivFunOnFinite` is the `Equiv` between `α →₀ β` and `α → β`. (All functions on a finite type are finitely supported.) -/ @[simps] def equivFunOnFinite [Finite α] : (α →₀ M) ≃ (α → M) where toFun := (⇑) invFun f := mk (Function.support f).toFinite.toFinset f fun _a => Set.Finite.mem_toFinset _ left_inv _f := ext fun _x => rfl right_inv _f := rfl @[simp] theorem equivFunOnFinite_symm_coe {α} [Finite α] (f : α →₀ M) : equivFunOnFinite.symm f = f := equivFunOnFinite.symm_apply_apply f @[simp] lemma coe_equivFunOnFinite_symm {α} [Finite α] (f : α → M) : ⇑(equivFunOnFinite.symm f) = f := rfl /-- If `α` has a unique term, the type of finitely supported functions `α →₀ β` is equivalent to `β`. -/ @[simps!] noncomputable def _root_.Equiv.finsuppUnique {ι : Type*} [Unique ι] : (ι →₀ M) ≃ M := Finsupp.equivFunOnFinite.trans (Equiv.funUnique ι M) @[ext] theorem unique_ext [Unique α] {f g : α →₀ M} (h : f default = g default) : f = g := ext fun a => by rwa [Unique.eq_default a] end Basic /-! ### Declarations about `onFinset` -/ section OnFinset variable [Zero M] /-- `Finsupp.onFinset s f hf` is the finsupp function representing `f` restricted to the finset `s`. The function must be `0` outside of `s`. Use this when the set needs to be filtered anyways, otherwise a better set representation is often available. -/ def onFinset (s : Finset α) (f : α → M) (hf : ∀ a, f a ≠ 0 → a ∈ s) : α →₀ M where support := haveI := Classical.decEq M {a ∈ s | f a ≠ 0} toFun := f mem_support_toFun := by classical simpa @[simp, norm_cast] lemma coe_onFinset (s : Finset α) (f : α → M) (hf) : onFinset s f hf = f := rfl @[simp] theorem onFinset_apply {s : Finset α} {f : α → M} {hf a} : (onFinset s f hf : α →₀ M) a = f a := rfl @[simp] theorem support_onFinset_subset {s : Finset α} {f : α → M} {hf} : (onFinset s f hf).support ⊆ s := by classical convert filter_subset (f · ≠ 0) s theorem mem_support_onFinset {s : Finset α} {f : α → M} (hf : ∀ a : α, f a ≠ 0 → a ∈ s) {a : α} : a ∈ (Finsupp.onFinset s f hf).support ↔ f a ≠ 0 := by rw [Finsupp.mem_support_iff, Finsupp.onFinset_apply] theorem support_onFinset [DecidableEq M] {s : Finset α} {f : α → M} (hf : ∀ a : α, f a ≠ 0 → a ∈ s) : (Finsupp.onFinset s f hf).support = {a ∈ s | f a ≠ 0} := by dsimp [onFinset]; congr end OnFinset section OfSupportFinite variable [Zero M] /-- The natural `Finsupp` induced by the function `f` given that it has finite support. -/ noncomputable def ofSupportFinite (f : α → M) (hf : (Function.support f).Finite) : α →₀ M where support := hf.toFinset toFun := f mem_support_toFun _ := hf.mem_toFinset theorem ofSupportFinite_coe {f : α → M} {hf : (Function.support f).Finite} : (ofSupportFinite f hf : α → M) = f := rfl instance instCanLift : CanLift (α → M) (α →₀ M) (⇑) fun f => (Function.support f).Finite where prf f hf := ⟨ofSupportFinite f hf, rfl⟩ end OfSupportFinite /-! ### Declarations about `mapRange` -/ section MapRange variable [Zero M] [Zero N] [Zero P] /-- The composition of `f : M → N` and `g : α →₀ M` is `mapRange f hf g : α →₀ N`, which is well-defined when `f 0 = 0`. This preserves the structure on `f`, and exists in various bundled forms for when `f` is itself bundled (defined in `Mathlib/Data/Finsupp/Basic.lean`): * `Finsupp.mapRange.equiv` * `Finsupp.mapRange.zeroHom` * `Finsupp.mapRange.addMonoidHom` * `Finsupp.mapRange.addEquiv` * `Finsupp.mapRange.linearMap` * `Finsupp.mapRange.linearEquiv` -/ def mapRange (f : M → N) (hf : f 0 = 0) (g : α →₀ M) : α →₀ N := onFinset g.support (f ∘ g) fun a => by rw [mem_support_iff, not_imp_not]; exact fun H => (congr_arg f H).trans hf @[simp] theorem mapRange_apply {f : M → N} {hf : f 0 = 0} {g : α →₀ M} {a : α} : mapRange f hf g a = f (g a) := rfl @[simp] theorem mapRange_zero {f : M → N} {hf : f 0 = 0} : mapRange f hf (0 : α →₀ M) = 0 := ext fun _ => by simp only [hf, zero_apply, mapRange_apply] @[simp] theorem mapRange_id (g : α →₀ M) : mapRange id rfl g = g := ext fun _ => rfl theorem mapRange_comp (f : N → P) (hf : f 0 = 0) (f₂ : M → N) (hf₂ : f₂ 0 = 0) (h : (f ∘ f₂) 0 = 0) (g : α →₀ M) : mapRange (f ∘ f₂) h g = mapRange f hf (mapRange f₂ hf₂ g) := ext fun _ => rfl @[simp] lemma mapRange_mapRange (e₁ : N → P) (e₂ : M → N) (he₁ he₂) (f : α →₀ M) : mapRange e₁ he₁ (mapRange e₂ he₂ f) = mapRange (e₁ ∘ e₂) (by simp [*]) f := ext fun _ ↦ rfl theorem support_mapRange {f : M → N} {hf : f 0 = 0} {g : α →₀ M} : (mapRange f hf g).support ⊆ g.support := support_onFinset_subset theorem support_mapRange_of_injective {e : M → N} (he0 : e 0 = 0) (f : ι →₀ M) (he : Function.Injective e) : (Finsupp.mapRange e he0 f).support = f.support := by ext simp only [Finsupp.mem_support_iff, Ne, Finsupp.mapRange_apply] exact he.ne_iff' he0 lemma range_mapRange (e : M → N) (he₀ : e 0 = 0) : Set.range (Finsupp.mapRange (α := α) e he₀) = {g | ∀ i, g i ∈ Set.range e} := by ext g simp only [Set.mem_range, Set.mem_setOf] constructor · rintro ⟨g, rfl⟩ i simp · intro h classical choose f h using h use onFinset g.support (Set.indicator g.support f) (by aesop) ext i simp only [mapRange_apply, onFinset_apply, Set.indicator_apply] split_ifs <;> simp_all /-- `Finsupp.mapRange` of a injective function is injective. -/ lemma mapRange_injective (e : M → N) (he₀ : e 0 = 0) (he : Injective e) : Injective (Finsupp.mapRange (α := α) e he₀) := by intro a b h rw [Finsupp.ext_iff] at h ⊢ simpa only [mapRange_apply, he.eq_iff] using h /-- `Finsupp.mapRange` of a surjective function is surjective. -/ lemma mapRange_surjective (e : M → N) (he₀ : e 0 = 0) (he : Surjective e) : Surjective (Finsupp.mapRange (α := α) e he₀) := by rw [← Set.range_eq_univ, range_mapRange, he.range_eq] simp end MapRange /-! ### Declarations about `embDomain` -/ section EmbDomain variable [Zero M] [Zero N] /-- Given `f : α ↪ β` and `v : α →₀ M`, `Finsupp.embDomain f v : β →₀ M` is the finitely supported function whose value at `f a : β` is `v a`. For a `b : β` outside the range of `f`, it is zero. -/ def embDomain (f : α ↪ β) (v : α →₀ M) : β →₀ M where support := v.support.map f toFun a₂ := haveI := Classical.decEq β if h : a₂ ∈ v.support.map f then v (v.support.choose (fun a₁ => f a₁ = a₂) (by rcases Finset.mem_map.1 h with ⟨a, ha, rfl⟩ exact ExistsUnique.intro a ⟨ha, rfl⟩ fun b ⟨_, hb⟩ => f.injective hb)) else 0 mem_support_toFun a₂ := by dsimp split_ifs with h · simp only [h, true_iff, Ne] rw [← not_mem_support_iff, not_not] classical apply Finset.choose_mem · simp only [h, Ne, ne_self_iff_false, not_true_eq_false] @[simp] theorem support_embDomain (f : α ↪ β) (v : α →₀ M) : (embDomain f v).support = v.support.map f := rfl @[simp] theorem embDomain_zero (f : α ↪ β) : (embDomain f 0 : β →₀ M) = 0 := rfl @[simp] theorem embDomain_apply (f : α ↪ β) (v : α →₀ M) (a : α) : embDomain f v (f a) = v a := by classical simp_rw [embDomain, coe_mk, mem_map'] split_ifs with h · refine congr_arg (v : α → M) (f.inj' ?_) exact Finset.choose_property (fun a₁ => f a₁ = f a) _ _ · exact (not_mem_support_iff.1 h).symm theorem embDomain_notin_range (f : α ↪ β) (v : α →₀ M) (a : β) (h : a ∉ Set.range f) : embDomain f v a = 0 := by classical refine dif_neg (mt (fun h => ?_) h) rcases Finset.mem_map.1 h with ⟨a, _h, rfl⟩ exact Set.mem_range_self a theorem embDomain_injective (f : α ↪ β) : Function.Injective (embDomain f : (α →₀ M) → β →₀ M) := fun l₁ l₂ h => ext fun a => by simpa only [embDomain_apply] using DFunLike.ext_iff.1 h (f a) @[simp] theorem embDomain_inj {f : α ↪ β} {l₁ l₂ : α →₀ M} : embDomain f l₁ = embDomain f l₂ ↔ l₁ = l₂ := (embDomain_injective f).eq_iff @[simp] theorem embDomain_eq_zero {f : α ↪ β} {l : α →₀ M} : embDomain f l = 0 ↔ l = 0 := (embDomain_injective f).eq_iff' <| embDomain_zero f theorem embDomain_mapRange (f : α ↪ β) (g : M → N) (p : α →₀ M) (hg : g 0 = 0) : embDomain f (mapRange g hg p) = mapRange g hg (embDomain f p) := by ext a by_cases h : a ∈ Set.range f · rcases h with ⟨a', rfl⟩ rw [mapRange_apply, embDomain_apply, embDomain_apply, mapRange_apply] · rw [mapRange_apply, embDomain_notin_range, embDomain_notin_range, ← hg] <;> assumption end EmbDomain /-! ### Declarations about `zipWith` -/ section ZipWith variable [Zero M] [Zero N] [Zero P] /-- Given finitely supported functions `g₁ : α →₀ M` and `g₂ : α →₀ N` and function `f : M → N → P`, `Finsupp.zipWith f hf g₁ g₂` is the finitely supported function `α →₀ P` satisfying `zipWith f hf g₁ g₂ a = f (g₁ a) (g₂ a)`, which is well-defined when `f 0 0 = 0`. -/ def zipWith (f : M → N → P) (hf : f 0 0 = 0) (g₁ : α →₀ M) (g₂ : α →₀ N) : α →₀ P := onFinset (haveI := Classical.decEq α; g₁.support ∪ g₂.support) (fun a => f (g₁ a) (g₂ a)) fun a (H : f _ _ ≠ 0) => by classical rw [mem_union, mem_support_iff, mem_support_iff, ← not_and_or] rintro ⟨h₁, h₂⟩; rw [h₁, h₂] at H; exact H hf @[simp] theorem zipWith_apply {f : M → N → P} {hf : f 0 0 = 0} {g₁ : α →₀ M} {g₂ : α →₀ N} {a : α} : zipWith f hf g₁ g₂ a = f (g₁ a) (g₂ a) := rfl theorem support_zipWith [D : DecidableEq α] {f : M → N → P} {hf : f 0 0 = 0} {g₁ : α →₀ M} {g₂ : α →₀ N} : (zipWith f hf g₁ g₂).support ⊆ g₁.support ∪ g₂.support := by convert support_onFinset_subset end ZipWith /-! ### Additive monoid structure on `α →₀ M` -/ section AddZeroClass variable [AddZeroClass M] instance instAdd : Add (α →₀ M) := ⟨zipWith (· + ·) (add_zero 0)⟩ @[simp, norm_cast] lemma coe_add (f g : α →₀ M) : ⇑(f + g) = f + g := rfl theorem add_apply (g₁ g₂ : α →₀ M) (a : α) : (g₁ + g₂) a = g₁ a + g₂ a := rfl theorem support_add [DecidableEq α] {g₁ g₂ : α →₀ M} : (g₁ + g₂).support ⊆ g₁.support ∪ g₂.support := support_zipWith theorem support_add_eq [DecidableEq α] {g₁ g₂ : α →₀ M} (h : Disjoint g₁.support g₂.support) : (g₁ + g₂).support = g₁.support ∪ g₂.support := le_antisymm support_zipWith fun a ha => (Finset.mem_union.1 ha).elim (fun ha => by have : a ∉ g₂.support := disjoint_left.1 h ha simp only [mem_support_iff, not_not] at *; simpa only [add_apply, this, add_zero] ) fun ha => by have : a ∉ g₁.support := disjoint_right.1 h ha simp only [mem_support_iff, not_not] at *; simpa only [add_apply, this, zero_add]
instance instAddZeroClass : AddZeroClass (α →₀ M) := fast_instance% DFunLike.coe_injective.addZeroClass _ coe_zero coe_add
Mathlib/Data/Finsupp/Defs.lean
491
493
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Julian Kuelshammer -/ import Mathlib.Algebra.CharP.Defs import Mathlib.Algebra.Group.Commute.Basic import Mathlib.Algebra.Group.Pointwise.Set.Finite import Mathlib.Algebra.Group.Subgroup.Finite import Mathlib.Algebra.Module.NatInt import Mathlib.Algebra.Order.Group.Action import Mathlib.Algebra.Order.Ring.Abs import Mathlib.Data.Int.ModEq import Mathlib.Dynamics.PeriodicPts.Lemmas import Mathlib.GroupTheory.Index import Mathlib.NumberTheory.Divisors import Mathlib.Order.Interval.Set.Infinite /-! # Order of an element This file defines the order of an element of a finite group. For a finite group `G` the order of `x ∈ G` is the minimal `n ≥ 1` such that `x ^ n = 1`. ## Main definitions * `IsOfFinOrder` is a predicate on an element `x` of a monoid `G` saying that `x` is of finite order. * `IsOfFinAddOrder` is the additive analogue of `IsOfFinOrder`. * `orderOf x` defines the order of an element `x` of a monoid `G`, by convention its value is `0` if `x` has infinite order. * `addOrderOf` is the additive analogue of `orderOf`. ## Tags order of an element -/ assert_not_exists Field open Function Fintype Nat Pointwise Subgroup Submonoid open scoped Finset variable {G H A α β : Type*} section Monoid variable [Monoid G] {a b x y : G} {n m : ℕ} section IsOfFinOrder -- Porting note (https://github.com/leanprover-community/mathlib4/issues/12129): additional beta reduction needed @[to_additive] theorem isPeriodicPt_mul_iff_pow_eq_one (x : G) : IsPeriodicPt (x * ·) n 1 ↔ x ^ n = 1 := by rw [IsPeriodicPt, IsFixedPt, mul_left_iterate]; beta_reduce; rw [mul_one] /-- `IsOfFinOrder` is a predicate on an element `x` of a monoid to be of finite order, i.e. there exists `n ≥ 1` such that `x ^ n = 1`. -/ @[to_additive "`IsOfFinAddOrder` is a predicate on an element `a` of an additive monoid to be of finite order, i.e. there exists `n ≥ 1` such that `n • a = 0`."] def IsOfFinOrder (x : G) : Prop := (1 : G) ∈ periodicPts (x * ·) theorem isOfFinAddOrder_ofMul_iff : IsOfFinAddOrder (Additive.ofMul x) ↔ IsOfFinOrder x := Iff.rfl theorem isOfFinOrder_ofAdd_iff {α : Type*} [AddMonoid α] {x : α} : IsOfFinOrder (Multiplicative.ofAdd x) ↔ IsOfFinAddOrder x := Iff.rfl @[to_additive] theorem isOfFinOrder_iff_pow_eq_one : IsOfFinOrder x ↔ ∃ n, 0 < n ∧ x ^ n = 1 := by simp [IsOfFinOrder, mem_periodicPts, isPeriodicPt_mul_iff_pow_eq_one] @[to_additive] alias ⟨IsOfFinOrder.exists_pow_eq_one, _⟩ := isOfFinOrder_iff_pow_eq_one @[to_additive] lemma isOfFinOrder_iff_zpow_eq_one {G} [DivisionMonoid G] {x : G} : IsOfFinOrder x ↔ ∃ (n : ℤ), n ≠ 0 ∧ x ^ n = 1 := by rw [isOfFinOrder_iff_pow_eq_one] refine ⟨fun ⟨n, hn, hn'⟩ ↦ ⟨n, Int.natCast_ne_zero_iff_pos.mpr hn, zpow_natCast x n ▸ hn'⟩, fun ⟨n, hn, hn'⟩ ↦ ⟨n.natAbs, Int.natAbs_pos.mpr hn, ?_⟩⟩ rcases (Int.natAbs_eq_iff (a := n)).mp rfl with h | h · rwa [h, zpow_natCast] at hn' · rwa [h, zpow_neg, inv_eq_one, zpow_natCast] at hn' /-- See also `injective_pow_iff_not_isOfFinOrder`. -/ @[to_additive "See also `injective_nsmul_iff_not_isOfFinAddOrder`."] theorem not_isOfFinOrder_of_injective_pow {x : G} (h : Injective fun n : ℕ => x ^ n) : ¬IsOfFinOrder x := by simp_rw [isOfFinOrder_iff_pow_eq_one, not_exists, not_and] intro n hn_pos hnx rw [← pow_zero x] at hnx rw [h hnx] at hn_pos exact irrefl 0 hn_pos /-- 1 is of finite order in any monoid. -/ @[to_additive (attr := simp) "0 is of finite order in any additive monoid."] theorem IsOfFinOrder.one : IsOfFinOrder (1 : G) := isOfFinOrder_iff_pow_eq_one.mpr ⟨1, Nat.one_pos, one_pow 1⟩ @[to_additive] lemma IsOfFinOrder.pow {n : ℕ} : IsOfFinOrder a → IsOfFinOrder (a ^ n) := by simp_rw [isOfFinOrder_iff_pow_eq_one] rintro ⟨m, hm, ha⟩ exact ⟨m, hm, by simp [pow_right_comm _ n, ha]⟩ @[to_additive] lemma IsOfFinOrder.of_pow {n : ℕ} (h : IsOfFinOrder (a ^ n)) (hn : n ≠ 0) : IsOfFinOrder a := by rw [isOfFinOrder_iff_pow_eq_one] at * rcases h with ⟨m, hm, ha⟩ exact ⟨n * m, mul_pos hn.bot_lt hm, by rwa [pow_mul]⟩ @[to_additive (attr := simp)] lemma isOfFinOrder_pow {n : ℕ} : IsOfFinOrder (a ^ n) ↔ IsOfFinOrder a ∨ n = 0 := by rcases Decidable.eq_or_ne n 0 with rfl | hn · simp · exact ⟨fun h ↦ .inl <| h.of_pow hn, fun h ↦ (h.resolve_right hn).pow⟩ /-- Elements of finite order are of finite order in submonoids. -/ @[to_additive "Elements of finite order are of finite order in submonoids."] theorem Submonoid.isOfFinOrder_coe {H : Submonoid G} {x : H} : IsOfFinOrder (x : G) ↔ IsOfFinOrder x := by rw [isOfFinOrder_iff_pow_eq_one, isOfFinOrder_iff_pow_eq_one] norm_cast theorem IsConj.isOfFinOrder (h : IsConj x y) : IsOfFinOrder x → IsOfFinOrder y := by simp_rw [isOfFinOrder_iff_pow_eq_one] rintro ⟨n, n_gt_0, eq'⟩ exact ⟨n, n_gt_0, by rw [← isConj_one_right, ← eq']; exact h.pow n⟩ /-- The image of an element of finite order has finite order. -/ @[to_additive "The image of an element of finite additive order has finite additive order."] theorem MonoidHom.isOfFinOrder [Monoid H] (f : G →* H) {x : G} (h : IsOfFinOrder x) : IsOfFinOrder <| f x := isOfFinOrder_iff_pow_eq_one.mpr <| by obtain ⟨n, npos, hn⟩ := h.exists_pow_eq_one exact ⟨n, npos, by rw [← f.map_pow, hn, f.map_one]⟩ /-- If a direct product has finite order then so does each component. -/ @[to_additive "If a direct product has finite additive order then so does each component."] theorem IsOfFinOrder.apply {η : Type*} {Gs : η → Type*} [∀ i, Monoid (Gs i)] {x : ∀ i, Gs i} (h : IsOfFinOrder x) : ∀ i, IsOfFinOrder (x i) := by obtain ⟨n, npos, hn⟩ := h.exists_pow_eq_one exact fun _ => isOfFinOrder_iff_pow_eq_one.mpr ⟨n, npos, (congr_fun hn.symm _).symm⟩ /-- The submonoid generated by an element is a group if that element has finite order. -/ @[to_additive "The additive submonoid generated by an element is an additive group if that element has finite order."] noncomputable abbrev IsOfFinOrder.groupPowers (hx : IsOfFinOrder x) : Group (Submonoid.powers x) := by obtain ⟨hpos, hx⟩ := hx.exists_pow_eq_one.choose_spec exact Submonoid.groupPowers hpos hx end IsOfFinOrder /-- `orderOf x` is the order of the element `x`, i.e. the `n ≥ 1`, s.t. `x ^ n = 1` if it exists. Otherwise, i.e. if `x` is of infinite order, then `orderOf x` is `0` by convention. -/ @[to_additive "`addOrderOf a` is the order of the element `a`, i.e. the `n ≥ 1`, s.t. `n • a = 0` if it exists. Otherwise, i.e. if `a` is of infinite order, then `addOrderOf a` is `0` by convention."] noncomputable def orderOf (x : G) : ℕ := minimalPeriod (x * ·) 1 @[simp] theorem addOrderOf_ofMul_eq_orderOf (x : G) : addOrderOf (Additive.ofMul x) = orderOf x := rfl @[simp] lemma orderOf_ofAdd_eq_addOrderOf {α : Type*} [AddMonoid α] (a : α) : orderOf (Multiplicative.ofAdd a) = addOrderOf a := rfl @[to_additive] protected lemma IsOfFinOrder.orderOf_pos (h : IsOfFinOrder x) : 0 < orderOf x := minimalPeriod_pos_of_mem_periodicPts h @[to_additive addOrderOf_nsmul_eq_zero] theorem pow_orderOf_eq_one (x : G) : x ^ orderOf x = 1 := by convert Eq.trans _ (isPeriodicPt_minimalPeriod (x * ·) 1) -- Porting note (https://github.com/leanprover-community/mathlib4/issues/12129): additional beta reduction needed in the middle of the rewrite rw [orderOf, mul_left_iterate]; beta_reduce; rw [mul_one] @[to_additive] theorem orderOf_eq_zero (h : ¬IsOfFinOrder x) : orderOf x = 0 := by rwa [orderOf, minimalPeriod, dif_neg] @[to_additive] theorem orderOf_eq_zero_iff : orderOf x = 0 ↔ ¬IsOfFinOrder x := ⟨fun h H ↦ H.orderOf_pos.ne' h, orderOf_eq_zero⟩ @[to_additive] theorem orderOf_eq_zero_iff' : orderOf x = 0 ↔ ∀ n : ℕ, 0 < n → x ^ n ≠ 1 := by simp_rw [orderOf_eq_zero_iff, isOfFinOrder_iff_pow_eq_one, not_exists, not_and] @[to_additive] theorem orderOf_eq_iff {n} (h : 0 < n) : orderOf x = n ↔ x ^ n = 1 ∧ ∀ m, m < n → 0 < m → x ^ m ≠ 1 := by simp_rw [Ne, ← isPeriodicPt_mul_iff_pow_eq_one, orderOf, minimalPeriod] split_ifs with h1 · classical rw [find_eq_iff] simp only [h, true_and] push_neg rfl · rw [iff_false_left h.ne] rintro ⟨h', -⟩ exact h1 ⟨n, h, h'⟩ /-- A group element has finite order iff its order is positive. -/ @[to_additive "A group element has finite additive order iff its order is positive."] theorem orderOf_pos_iff : 0 < orderOf x ↔ IsOfFinOrder x := by rw [iff_not_comm.mp orderOf_eq_zero_iff, pos_iff_ne_zero] @[to_additive] theorem IsOfFinOrder.mono [Monoid β] {y : β} (hx : IsOfFinOrder x) (h : orderOf y ∣ orderOf x) : IsOfFinOrder y := by rw [← orderOf_pos_iff] at hx ⊢; exact Nat.pos_of_dvd_of_pos h hx @[to_additive] theorem pow_ne_one_of_lt_orderOf (n0 : n ≠ 0) (h : n < orderOf x) : x ^ n ≠ 1 := fun j => not_isPeriodicPt_of_pos_of_lt_minimalPeriod n0 h ((isPeriodicPt_mul_iff_pow_eq_one x).mpr j) @[to_additive] theorem orderOf_le_of_pow_eq_one (hn : 0 < n) (h : x ^ n = 1) : orderOf x ≤ n := IsPeriodicPt.minimalPeriod_le hn (by rwa [isPeriodicPt_mul_iff_pow_eq_one]) @[to_additive (attr := simp)] theorem orderOf_one : orderOf (1 : G) = 1 := by rw [orderOf, ← minimalPeriod_id (x := (1 : G)), ← one_mul_eq_id] @[to_additive (attr := simp) AddMonoid.addOrderOf_eq_one_iff] theorem orderOf_eq_one_iff : orderOf x = 1 ↔ x = 1 := by rw [orderOf, minimalPeriod_eq_one_iff_isFixedPt, IsFixedPt, mul_one] @[to_additive (attr := simp) mod_addOrderOf_nsmul] lemma pow_mod_orderOf (x : G) (n : ℕ) : x ^ (n % orderOf x) = x ^ n := calc x ^ (n % orderOf x) = x ^ (n % orderOf x + orderOf x * (n / orderOf x)) := by simp [pow_add, pow_mul, pow_orderOf_eq_one] _ = x ^ n := by rw [Nat.mod_add_div] @[to_additive] theorem orderOf_dvd_of_pow_eq_one (h : x ^ n = 1) : orderOf x ∣ n := IsPeriodicPt.minimalPeriod_dvd ((isPeriodicPt_mul_iff_pow_eq_one _).mpr h) @[to_additive] theorem orderOf_dvd_iff_pow_eq_one {n : ℕ} : orderOf x ∣ n ↔ x ^ n = 1 := ⟨fun h => by rw [← pow_mod_orderOf, Nat.mod_eq_zero_of_dvd h, _root_.pow_zero], orderOf_dvd_of_pow_eq_one⟩ @[to_additive addOrderOf_smul_dvd] theorem orderOf_pow_dvd (n : ℕ) : orderOf (x ^ n) ∣ orderOf x := by rw [orderOf_dvd_iff_pow_eq_one, pow_right_comm, pow_orderOf_eq_one, one_pow] @[to_additive] lemma pow_injOn_Iio_orderOf : (Set.Iio <| orderOf x).InjOn (x ^ ·) := by simpa only [mul_left_iterate, mul_one] using iterate_injOn_Iio_minimalPeriod (f := (x * ·)) (x := 1) @[to_additive] protected lemma IsOfFinOrder.mem_powers_iff_mem_range_orderOf [DecidableEq G] (hx : IsOfFinOrder x) : y ∈ Submonoid.powers x ↔ y ∈ (Finset.range (orderOf x)).image (x ^ ·) := Finset.mem_range_iff_mem_finset_range_of_mod_eq' hx.orderOf_pos <| pow_mod_orderOf _ @[to_additive] protected lemma IsOfFinOrder.powers_eq_image_range_orderOf [DecidableEq G] (hx : IsOfFinOrder x) : (Submonoid.powers x : Set G) = (Finset.range (orderOf x)).image (x ^ ·) := Set.ext fun _ ↦ hx.mem_powers_iff_mem_range_orderOf @[to_additive] theorem pow_eq_one_iff_modEq : x ^ n = 1 ↔ n ≡ 0 [MOD orderOf x] := by rw [modEq_zero_iff_dvd, orderOf_dvd_iff_pow_eq_one] @[to_additive] theorem orderOf_map_dvd {H : Type*} [Monoid H] (ψ : G →* H) (x : G) : orderOf (ψ x) ∣ orderOf x := by apply orderOf_dvd_of_pow_eq_one rw [← map_pow, pow_orderOf_eq_one] apply map_one @[to_additive] theorem exists_pow_eq_self_of_coprime (h : n.Coprime (orderOf x)) : ∃ m : ℕ, (x ^ n) ^ m = x := by by_cases h0 : orderOf x = 0 · rw [h0, coprime_zero_right] at h exact ⟨1, by rw [h, pow_one, pow_one]⟩ by_cases h1 : orderOf x = 1 · exact ⟨0, by rw [orderOf_eq_one_iff.mp h1, one_pow, one_pow]⟩ obtain ⟨m, h⟩ := exists_mul_emod_eq_one_of_coprime h (one_lt_iff_ne_zero_and_ne_one.mpr ⟨h0, h1⟩) exact ⟨m, by rw [← pow_mul, ← pow_mod_orderOf, h, pow_one]⟩ /-- If `x^n = 1`, but `x^(n/p) ≠ 1` for all prime factors `p` of `n`, then `x` has order `n` in `G`. -/ @[to_additive addOrderOf_eq_of_nsmul_and_div_prime_nsmul "If `n * x = 0`, but `n/p * x ≠ 0` for all prime factors `p` of `n`, then `x` has order `n` in `G`."] theorem orderOf_eq_of_pow_and_pow_div_prime (hn : 0 < n) (hx : x ^ n = 1) (hd : ∀ p : ℕ, p.Prime → p ∣ n → x ^ (n / p) ≠ 1) : orderOf x = n := by -- Let `a` be `n/(orderOf x)`, and show `a = 1` obtain ⟨a, ha⟩ := exists_eq_mul_right_of_dvd (orderOf_dvd_of_pow_eq_one hx) suffices a = 1 by simp [this, ha] -- Assume `a` is not one... by_contra h have a_min_fac_dvd_p_sub_one : a.minFac ∣ n := by obtain ⟨b, hb⟩ : ∃ b : ℕ, a = b * a.minFac := exists_eq_mul_left_of_dvd a.minFac_dvd rw [hb, ← mul_assoc] at ha exact Dvd.intro_left (orderOf x * b) ha.symm -- Use the minimum prime factor of `a` as `p`. refine hd a.minFac (Nat.minFac_prime h) a_min_fac_dvd_p_sub_one ?_ rw [← orderOf_dvd_iff_pow_eq_one, Nat.dvd_div_iff_mul_dvd a_min_fac_dvd_p_sub_one, ha, mul_comm, Nat.mul_dvd_mul_iff_left (IsOfFinOrder.orderOf_pos _)] · exact Nat.minFac_dvd a
· rw [isOfFinOrder_iff_pow_eq_one] exact Exists.intro n (id ⟨hn, hx⟩)
Mathlib/GroupTheory/OrderOfElement.lean
308
309
/- Copyright (c) 2022 Xavier Roblot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alex J. Best, Xavier Roblot -/ import Mathlib.Algebra.Algebra.Hom.Rat import Mathlib.Analysis.Complex.Polynomial.Basic import Mathlib.NumberTheory.NumberField.Norm import Mathlib.RingTheory.RootsOfUnity.PrimitiveRoots import Mathlib.Topology.Instances.Complex /-! # Embeddings of number fields This file defines the embeddings of a number field into an algebraic closed field. ## Main Definitions and Results * `NumberField.Embeddings.range_eval_eq_rootSet_minpoly`: let `x ∈ K` with `K` number field and let `A` be an algebraic closed field of char. 0, then the images of `x` by the embeddings of `K` in `A` are exactly the roots in `A` of the minimal polynomial of `x` over `ℚ`. * `NumberField.Embeddings.pow_eq_one_of_norm_eq_one`: an algebraic integer whose conjugates are all of norm one is a root of unity. * `NumberField.InfinitePlace`: the type of infinite places of a number field `K`. * `NumberField.InfinitePlace.mk_eq_iff`: two complex embeddings define the same infinite place iff they are equal or complex conjugates. * `NumberField.InfinitePlace.prod_eq_abs_norm`: the infinite part of the product formula, that is for `x ∈ K`, we have `Π_w ‖x‖_w = |norm(x)|` where the product is over the infinite place `w` and `‖·‖_w` is the normalized absolute value for `w`. ## Tags number field, embeddings, places, infinite places -/ open scoped Finset namespace NumberField.Embeddings section Fintype open Module variable (K : Type*) [Field K] [NumberField K] variable (A : Type*) [Field A] [CharZero A] /-- There are finitely many embeddings of a number field. -/ noncomputable instance : Fintype (K →+* A) := Fintype.ofEquiv (K →ₐ[ℚ] A) RingHom.equivRatAlgHom.symm variable [IsAlgClosed A] /-- The number of embeddings of a number field is equal to its finrank. -/ theorem card : Fintype.card (K →+* A) = finrank ℚ K := by rw [Fintype.ofEquiv_card RingHom.equivRatAlgHom.symm, AlgHom.card] instance : Nonempty (K →+* A) := by rw [← Fintype.card_pos_iff, NumberField.Embeddings.card K A] exact Module.finrank_pos end Fintype section Roots open Set Polynomial variable (K A : Type*) [Field K] [NumberField K] [Field A] [Algebra ℚ A] [IsAlgClosed A] (x : K) /-- Let `A` be an algebraically closed field and let `x ∈ K`, with `K` a number field. The images of `x` by the embeddings of `K` in `A` are exactly the roots in `A` of the minimal polynomial of `x` over `ℚ`. -/ theorem range_eval_eq_rootSet_minpoly : (range fun φ : K →+* A => φ x) = (minpoly ℚ x).rootSet A := by convert (NumberField.isAlgebraic K).range_eval_eq_rootSet_minpoly A x using 1 ext a exact ⟨fun ⟨φ, hφ⟩ => ⟨φ.toRatAlgHom, hφ⟩, fun ⟨φ, hφ⟩ => ⟨φ.toRingHom, hφ⟩⟩ end Roots section Bounded open Module Polynomial Set variable {K : Type*} [Field K] [NumberField K] variable {A : Type*} [NormedField A] [IsAlgClosed A] [NormedAlgebra ℚ A] theorem coeff_bdd_of_norm_le {B : ℝ} {x : K} (h : ∀ φ : K →+* A, ‖φ x‖ ≤ B) (i : ℕ) : ‖(minpoly ℚ x).coeff i‖ ≤ max B 1 ^ finrank ℚ K * (finrank ℚ K).choose (finrank ℚ K / 2) := by have hx := Algebra.IsSeparable.isIntegral ℚ x rw [← norm_algebraMap' A, ← coeff_map (algebraMap ℚ A)] refine coeff_bdd_of_roots_le _ (minpoly.monic hx) (IsAlgClosed.splits_codomain _) (minpoly.natDegree_le x) (fun z hz => ?_) i classical rw [← Multiset.mem_toFinset] at hz obtain ⟨φ, rfl⟩ := (range_eval_eq_rootSet_minpoly K A x).symm.subset hz exact h φ variable (K A) /-- Let `B` be a real number. The set of algebraic integers in `K` whose conjugates are all smaller in norm than `B` is finite. -/ theorem finite_of_norm_le (B : ℝ) : {x : K | IsIntegral ℤ x ∧ ∀ φ : K →+* A, ‖φ x‖ ≤ B}.Finite := by classical let C := Nat.ceil (max B 1 ^ finrank ℚ K * (finrank ℚ K).choose (finrank ℚ K / 2)) have := bUnion_roots_finite (algebraMap ℤ K) (finrank ℚ K) (finite_Icc (-C : ℤ) C) refine this.subset fun x hx => ?_; simp_rw [mem_iUnion] have h_map_ℚ_minpoly := minpoly.isIntegrallyClosed_eq_field_fractions' ℚ hx.1 refine ⟨_, ⟨?_, fun i => ?_⟩, mem_rootSet.2 ⟨minpoly.ne_zero hx.1, minpoly.aeval ℤ x⟩⟩ · rw [← (minpoly.monic hx.1).natDegree_map (algebraMap ℤ ℚ), ← h_map_ℚ_minpoly] exact minpoly.natDegree_le x rw [mem_Icc, ← abs_le, ← @Int.cast_le ℝ] refine (Eq.trans_le ?_ <| coeff_bdd_of_norm_le hx.2 i).trans (Nat.le_ceil _) rw [h_map_ℚ_minpoly, coeff_map, eq_intCast, Int.norm_cast_rat, Int.norm_eq_abs, Int.cast_abs] /-- An algebraic integer whose conjugates are all of norm one is a root of unity. -/ theorem pow_eq_one_of_norm_eq_one {x : K} (hxi : IsIntegral ℤ x) (hx : ∀ φ : K →+* A, ‖φ x‖ = 1) : ∃ (n : ℕ) (_ : 0 < n), x ^ n = 1 := by obtain ⟨a, -, b, -, habne, h⟩ := @Set.Infinite.exists_ne_map_eq_of_mapsTo _ _ _ _ (x ^ · : ℕ → K) Set.infinite_univ (by exact fun a _ => ⟨hxi.pow a, fun φ => by simp [hx φ]⟩) (finite_of_norm_le K A (1 : ℝ)) wlog hlt : b < a · exact this K A hxi hx b a habne.symm h.symm (habne.lt_or_lt.resolve_right hlt) refine ⟨a - b, tsub_pos_of_lt hlt, ?_⟩ rw [← Nat.sub_add_cancel hlt.le, pow_add, mul_left_eq_self₀] at h refine h.resolve_right fun hp => ?_ specialize hx (IsAlgClosed.lift (R := ℚ)).toRingHom rw [pow_eq_zero hp, map_zero, norm_zero] at hx; norm_num at hx end Bounded end NumberField.Embeddings section Place variable {K : Type*} [Field K] {A : Type*} [NormedDivisionRing A] [Nontrivial A] (φ : K →+* A) /-- An embedding into a normed division ring defines a place of `K` -/ def NumberField.place : AbsoluteValue K ℝ := (IsAbsoluteValue.toAbsoluteValue (norm : A → ℝ)).comp φ.injective @[simp] theorem NumberField.place_apply (x : K) : (NumberField.place φ) x = norm (φ x) := rfl end Place namespace NumberField.ComplexEmbedding open Complex NumberField open scoped ComplexConjugate variable {K : Type*} [Field K] {k : Type*} [Field k] variable (K) in /-- A (random) lift of the complex embedding `φ : k →+* ℂ` to an extension `K` of `k`. -/ noncomputable def lift [Algebra k K] [Algebra.IsAlgebraic k K] (φ : k →+* ℂ) : K →+* ℂ := by letI := φ.toAlgebra exact (IsAlgClosed.lift (R := k)).toRingHom @[simp] theorem lift_comp_algebraMap [Algebra k K] [Algebra.IsAlgebraic k K] (φ : k →+* ℂ) : (lift K φ).comp (algebraMap k K) = φ := by unfold lift letI := φ.toAlgebra rw [AlgHom.toRingHom_eq_coe, AlgHom.comp_algebraMap_of_tower, RingHom.algebraMap_toAlgebra'] @[simp] theorem lift_algebraMap_apply [Algebra k K] [Algebra.IsAlgebraic k K] (φ : k →+* ℂ) (x : k) : lift K φ (algebraMap k K x) = φ x := RingHom.congr_fun (lift_comp_algebraMap φ) x /-- The conjugate of a complex embedding as a complex embedding. -/ abbrev conjugate (φ : K →+* ℂ) : K →+* ℂ := star φ @[simp] theorem conjugate_coe_eq (φ : K →+* ℂ) (x : K) : (conjugate φ) x = conj (φ x) := rfl theorem place_conjugate (φ : K →+* ℂ) : place (conjugate φ) = place φ := by ext; simp only [place_apply, norm_conj, conjugate_coe_eq] /-- An embedding into `ℂ` is real if it is fixed by complex conjugation. -/ abbrev IsReal (φ : K →+* ℂ) : Prop := IsSelfAdjoint φ theorem isReal_iff {φ : K →+* ℂ} : IsReal φ ↔ conjugate φ = φ := isSelfAdjoint_iff theorem isReal_conjugate_iff {φ : K →+* ℂ} : IsReal (conjugate φ) ↔ IsReal φ := IsSelfAdjoint.star_iff /-- A real embedding as a ring homomorphism from `K` to `ℝ` . -/ def IsReal.embedding {φ : K →+* ℂ} (hφ : IsReal φ) : K →+* ℝ where toFun x := (φ x).re map_one' := by simp only [map_one, one_re] map_mul' := by simp only [Complex.conj_eq_iff_im.mp (RingHom.congr_fun hφ _), map_mul, mul_re, mul_zero, tsub_zero, eq_self_iff_true, forall_const] map_zero' := by simp only [map_zero, zero_re] map_add' := by simp only [map_add, add_re, eq_self_iff_true, forall_const] @[simp] theorem IsReal.coe_embedding_apply {φ : K →+* ℂ} (hφ : IsReal φ) (x : K) : (hφ.embedding x : ℂ) = φ x := by apply Complex.ext · rfl · rw [ofReal_im, eq_comm, ← Complex.conj_eq_iff_im] exact RingHom.congr_fun hφ x lemma IsReal.comp (f : k →+* K) {φ : K →+* ℂ} (hφ : IsReal φ) : IsReal (φ.comp f) := by ext1 x; simpa using RingHom.congr_fun hφ (f x) lemma isReal_comp_iff {f : k ≃+* K} {φ : K →+* ℂ} : IsReal (φ.comp (f : k →+* K)) ↔ IsReal φ := ⟨fun H ↦ by convert H.comp f.symm.toRingHom; ext1; simp, IsReal.comp _⟩ lemma exists_comp_symm_eq_of_comp_eq [Algebra k K] [IsGalois k K] (φ ψ : K →+* ℂ) (h : φ.comp (algebraMap k K) = ψ.comp (algebraMap k K)) : ∃ σ : K ≃ₐ[k] K, φ.comp σ.symm = ψ := by letI := (φ.comp (algebraMap k K)).toAlgebra letI := φ.toAlgebra have : IsScalarTower k K ℂ := IsScalarTower.of_algebraMap_eq' rfl let ψ' : K →ₐ[k] ℂ := { ψ with commutes' := fun r ↦ (RingHom.congr_fun h r).symm } use (AlgHom.restrictNormal' ψ' K).symm ext1 x exact AlgHom.restrictNormal_commutes ψ' K x variable [Algebra k K] (φ : K →+* ℂ) (σ : K ≃ₐ[k] K) /-- `IsConj φ σ` states that `σ : K ≃ₐ[k] K` is the conjugation under the embedding `φ : K →+* ℂ`. -/ def IsConj : Prop := conjugate φ = φ.comp σ variable {φ σ} lemma IsConj.eq (h : IsConj φ σ) (x) : φ (σ x) = star (φ x) := RingHom.congr_fun h.symm x lemma IsConj.ext {σ₁ σ₂ : K ≃ₐ[k] K} (h₁ : IsConj φ σ₁) (h₂ : IsConj φ σ₂) : σ₁ = σ₂ := AlgEquiv.ext fun x ↦ φ.injective ((h₁.eq x).trans (h₂.eq x).symm) lemma IsConj.ext_iff {σ₁ σ₂ : K ≃ₐ[k] K} (h₁ : IsConj φ σ₁) : σ₁ = σ₂ ↔ IsConj φ σ₂ := ⟨fun e ↦ e ▸ h₁, h₁.ext⟩ lemma IsConj.isReal_comp (h : IsConj φ σ) : IsReal (φ.comp (algebraMap k K)) := by ext1 x simp only [conjugate_coe_eq, RingHom.coe_comp, Function.comp_apply, ← h.eq, starRingEnd_apply, AlgEquiv.commutes] lemma isConj_one_iff : IsConj φ (1 : K ≃ₐ[k] K) ↔ IsReal φ := Iff.rfl alias ⟨_, IsReal.isConjGal_one⟩ := ComplexEmbedding.isConj_one_iff lemma IsConj.symm (hσ : IsConj φ σ) : IsConj φ σ.symm := RingHom.ext fun x ↦ by simpa using congr_arg star (hσ.eq (σ.symm x)) lemma isConj_symm : IsConj φ σ.symm ↔ IsConj φ σ := ⟨IsConj.symm, IsConj.symm⟩ end NumberField.ComplexEmbedding section InfinitePlace open NumberField variable {k : Type*} [Field k] (K : Type*) [Field K] {F : Type*} [Field F] /-- An infinite place of a number field `K` is a place associated to a complex embedding. -/ def NumberField.InfinitePlace := { w : AbsoluteValue K ℝ // ∃ φ : K →+* ℂ, place φ = w } instance [NumberField K] : Nonempty (NumberField.InfinitePlace K) := Set.instNonemptyRange _ variable {K} /-- Return the infinite place defined by a complex embedding `φ`. -/ noncomputable def NumberField.InfinitePlace.mk (φ : K →+* ℂ) : NumberField.InfinitePlace K := ⟨place φ, ⟨φ, rfl⟩⟩ namespace NumberField.InfinitePlace open NumberField instance {K : Type*} [Field K] : FunLike (InfinitePlace K) K ℝ where coe w x := w.1 x coe_injective' _ _ h := Subtype.eq (AbsoluteValue.ext fun x => congr_fun h x) lemma coe_apply {K : Type*} [Field K] (v : InfinitePlace K) (x : K) : v x = v.1 x := rfl @[ext] lemma ext {K : Type*} [Field K] (v₁ v₂ : InfinitePlace K) (h : ∀ k, v₁ k = v₂ k) : v₁ = v₂ := Subtype.ext <| AbsoluteValue.ext h instance : MonoidWithZeroHomClass (InfinitePlace K) K ℝ where map_mul w _ _ := w.1.map_mul _ _ map_one w := w.1.map_one map_zero w := w.1.map_zero instance : NonnegHomClass (InfinitePlace K) K ℝ where apply_nonneg w _ := w.1.nonneg _ @[simp] theorem apply (φ : K →+* ℂ) (x : K) : (mk φ) x = ‖φ x‖ := rfl /-- For an infinite place `w`, return an embedding `φ` such that `w = infinite_place φ` . -/ noncomputable def embedding (w : InfinitePlace K) : K →+* ℂ := w.2.choose @[simp] theorem mk_embedding (w : InfinitePlace K) : mk (embedding w) = w := Subtype.ext w.2.choose_spec @[simp] theorem mk_conjugate_eq (φ : K →+* ℂ) : mk (ComplexEmbedding.conjugate φ) = mk φ := by refine DFunLike.ext _ _ (fun x => ?_) rw [apply, apply, ComplexEmbedding.conjugate_coe_eq, Complex.norm_conj] theorem norm_embedding_eq (w : InfinitePlace K) (x : K) : ‖(embedding w) x‖ = w x := by nth_rewrite 2 [← mk_embedding w] rfl theorem eq_iff_eq (x : K) (r : ℝ) : (∀ w : InfinitePlace K, w x = r) ↔ ∀ φ : K →+* ℂ, ‖φ x‖ = r := ⟨fun hw φ => hw (mk φ), by rintro hφ ⟨w, ⟨φ, rfl⟩⟩; exact hφ φ⟩ theorem le_iff_le (x : K) (r : ℝ) : (∀ w : InfinitePlace K, w x ≤ r) ↔ ∀ φ : K →+* ℂ, ‖φ x‖ ≤ r := ⟨fun hw φ => hw (mk φ), by rintro hφ ⟨w, ⟨φ, rfl⟩⟩; exact hφ φ⟩ theorem pos_iff {w : InfinitePlace K} {x : K} : 0 < w x ↔ x ≠ 0 := AbsoluteValue.pos_iff w.1 @[simp] theorem mk_eq_iff {φ ψ : K →+* ℂ} : mk φ = mk ψ ↔ φ = ψ ∨ ComplexEmbedding.conjugate φ = ψ := by constructor · -- We prove that the map ψ ∘ φ⁻¹ between φ(K) and ℂ is uniform continuous, thus it is either the -- inclusion or the complex conjugation using `Complex.uniformContinuous_ringHom_eq_id_or_conj` intro h₀ obtain ⟨j, hiφ⟩ := (φ.injective).hasLeftInverse let ι := RingEquiv.ofLeftInverse hiφ have hlip : LipschitzWith 1 (RingHom.comp ψ ι.symm.toRingHom) := by change LipschitzWith 1 (ψ ∘ ι.symm) apply LipschitzWith.of_dist_le_mul intro x y rw [NNReal.coe_one, one_mul, NormedField.dist_eq, Function.comp_apply, Function.comp_apply, ← map_sub, ← map_sub] apply le_of_eq suffices ‖φ (ι.symm (x - y))‖ = ‖ψ (ι.symm (x - y))‖ by rw [← this, ← RingEquiv.ofLeftInverse_apply hiφ _, RingEquiv.apply_symm_apply ι _] rfl exact congrFun (congrArg (↑) h₀) _ cases Complex.uniformContinuous_ringHom_eq_id_or_conj φ.fieldRange hlip.uniformContinuous with | inl h => left; ext1 x conv_rhs => rw [← hiφ x] exact (congrFun h (ι x)).symm | inr h => right; ext1 x conv_rhs => rw [← hiφ x] exact (congrFun h (ι x)).symm · rintro (⟨h⟩ | ⟨h⟩) · exact congr_arg mk h · rw [← mk_conjugate_eq] exact congr_arg mk h /-- An infinite place is real if it is defined by a real embedding. -/ def IsReal (w : InfinitePlace K) : Prop := ∃ φ : K →+* ℂ, ComplexEmbedding.IsReal φ ∧ mk φ = w /-- An infinite place is complex if it is defined by a complex (ie. not real) embedding. -/ def IsComplex (w : InfinitePlace K) : Prop := ∃ φ : K →+* ℂ, ¬ComplexEmbedding.IsReal φ ∧ mk φ = w theorem embedding_mk_eq (φ : K →+* ℂ) : embedding (mk φ) = φ ∨ embedding (mk φ) = ComplexEmbedding.conjugate φ := by rw [@eq_comm _ _ φ, @eq_comm _ _ (ComplexEmbedding.conjugate φ), ← mk_eq_iff, mk_embedding] @[simp] theorem embedding_mk_eq_of_isReal {φ : K →+* ℂ} (h : ComplexEmbedding.IsReal φ) : embedding (mk φ) = φ := by have := embedding_mk_eq φ rwa [ComplexEmbedding.isReal_iff.mp h, or_self] at this theorem isReal_iff {w : InfinitePlace K} : IsReal w ↔ ComplexEmbedding.IsReal (embedding w) := by refine ⟨?_, fun h => ⟨embedding w, h, mk_embedding w⟩⟩ rintro ⟨φ, ⟨hφ, rfl⟩⟩ rwa [embedding_mk_eq_of_isReal hφ] theorem isComplex_iff {w : InfinitePlace K} : IsComplex w ↔ ¬ComplexEmbedding.IsReal (embedding w) := by refine ⟨?_, fun h => ⟨embedding w, h, mk_embedding w⟩⟩ rintro ⟨φ, ⟨hφ, rfl⟩⟩ contrapose! hφ cases mk_eq_iff.mp (mk_embedding (mk φ)) with | inl h => rwa [h] at hφ | inr h => rwa [← ComplexEmbedding.isReal_conjugate_iff, h] at hφ @[simp] theorem conjugate_embedding_eq_of_isReal {w : InfinitePlace K} (h : IsReal w) : ComplexEmbedding.conjugate (embedding w) = embedding w := ComplexEmbedding.isReal_iff.mpr (isReal_iff.mp h) @[simp] theorem not_isReal_iff_isComplex {w : InfinitePlace K} : ¬IsReal w ↔ IsComplex w := by rw [isComplex_iff, isReal_iff] @[simp] theorem not_isComplex_iff_isReal {w : InfinitePlace K} : ¬IsComplex w ↔ IsReal w := by rw [isComplex_iff, isReal_iff, not_not] theorem isReal_or_isComplex (w : InfinitePlace K) : IsReal w ∨ IsComplex w := by rw [← not_isReal_iff_isComplex]; exact em _ theorem ne_of_isReal_isComplex {w w' : InfinitePlace K} (h : IsReal w) (h' : IsComplex w') : w ≠ w' := fun h_eq ↦ not_isReal_iff_isComplex.mpr h' (h_eq ▸ h) variable (K) in theorem disjoint_isReal_isComplex : Disjoint {(w : InfinitePlace K) | IsReal w} {(w : InfinitePlace K) | IsComplex w} := Set.disjoint_iff.2 <| fun _ hw ↦ not_isReal_iff_isComplex.2 hw.2 hw.1 /-- The real embedding associated to a real infinite place. -/ noncomputable def embedding_of_isReal {w : InfinitePlace K} (hw : IsReal w) : K →+* ℝ := ComplexEmbedding.IsReal.embedding (isReal_iff.mp hw) @[simp] theorem embedding_of_isReal_apply {w : InfinitePlace K} (hw : IsReal w) (x : K) : ((embedding_of_isReal hw) x : ℂ) = (embedding w) x := ComplexEmbedding.IsReal.coe_embedding_apply (isReal_iff.mp hw) x theorem norm_embedding_of_isReal {w : InfinitePlace K} (hw : IsReal w) (x : K) : ‖embedding_of_isReal hw x‖ = w x := by rw [← norm_embedding_eq, ← embedding_of_isReal_apply hw, Complex.norm_real] @[simp] theorem isReal_of_mk_isReal {φ : K →+* ℂ} (h : IsReal (mk φ)) : ComplexEmbedding.IsReal φ := by contrapose! h rw [not_isReal_iff_isComplex] exact ⟨φ, h, rfl⟩ lemma isReal_mk_iff {φ : K →+* ℂ} : IsReal (mk φ) ↔ ComplexEmbedding.IsReal φ := ⟨isReal_of_mk_isReal, fun H ↦ ⟨_, H, rfl⟩⟩ lemma isComplex_mk_iff {φ : K →+* ℂ} : IsComplex (mk φ) ↔ ¬ ComplexEmbedding.IsReal φ := not_isReal_iff_isComplex.symm.trans isReal_mk_iff.not @[simp] theorem not_isReal_of_mk_isComplex {φ : K →+* ℂ} (h : IsComplex (mk φ)) : ¬ ComplexEmbedding.IsReal φ := by rwa [← isComplex_mk_iff] open scoped Classical in /-- The multiplicity of an infinite place, that is the number of distinct complex embeddings that define it, see `card_filter_mk_eq`. -/ noncomputable def mult (w : InfinitePlace K) : ℕ := if (IsReal w) then 1 else 2 @[simp] theorem mult_isReal (w : {w : InfinitePlace K // IsReal w}) : mult w.1 = 1 := by rw [mult, if_pos w.prop] @[simp] theorem mult_isComplex (w : {w : InfinitePlace K // IsComplex w}) : mult w.1 = 2 := by rw [mult, if_neg (not_isReal_iff_isComplex.mpr w.prop)] theorem mult_pos {w : InfinitePlace K} : 0 < mult w := by rw [mult] split_ifs <;> norm_num @[simp] theorem mult_ne_zero {w : InfinitePlace K} : mult w ≠ 0 := ne_of_gt mult_pos theorem mult_coe_ne_zero {w : InfinitePlace K} : (mult w : ℝ) ≠ 0 := Nat.cast_ne_zero.mpr mult_ne_zero theorem one_le_mult {w : InfinitePlace K} : (1 : ℝ) ≤ mult w := by rw [← Nat.cast_one, Nat.cast_le] exact mult_pos open scoped Classical in theorem card_filter_mk_eq [NumberField K] (w : InfinitePlace K) : #{φ | mk φ = w} = mult w := by conv_lhs => congr; congr; ext rw [← mk_embedding w, mk_eq_iff, ComplexEmbedding.conjugate, star_involutive.eq_iff] simp_rw [Finset.filter_or, Finset.filter_eq' _ (embedding w), Finset.filter_eq' _ (ComplexEmbedding.conjugate (embedding w)), Finset.mem_univ, ite_true, mult] split_ifs with hw · rw [ComplexEmbedding.isReal_iff.mp (isReal_iff.mp hw), Finset.union_idempotent, Finset.card_singleton] · refine Finset.card_pair ?_ rwa [Ne, eq_comm, ← ComplexEmbedding.isReal_iff, ← isReal_iff] open scoped Classical in noncomputable instance NumberField.InfinitePlace.fintype [NumberField K] : Fintype (InfinitePlace K) := Set.fintypeRange _ open scoped Classical in @[to_additive] theorem prod_eq_prod_mul_prod {α : Type*} [CommMonoid α] [NumberField K] (f : InfinitePlace K → α) : ∏ w, f w = (∏ w : {w // IsReal w}, f w.1) * (∏ w : {w // IsComplex w}, f w.1) := by rw [← Equiv.prod_comp (Equiv.subtypeEquivRight (fun _ ↦ not_isReal_iff_isComplex))] simp [Fintype.prod_subtype_mul_prod_subtype] theorem sum_mult_eq [NumberField K] : ∑ w : InfinitePlace K, mult w = Module.finrank ℚ K := by classical rw [← Embeddings.card K ℂ, Fintype.card, Finset.card_eq_sum_ones, ← Finset.univ.sum_fiberwise (fun φ => InfinitePlace.mk φ)] exact Finset.sum_congr rfl (fun _ _ => by rw [Finset.sum_const, smul_eq_mul, mul_one, card_filter_mk_eq]) /-- The map from real embeddings to real infinite places as an equiv -/ noncomputable def mkReal : { φ : K →+* ℂ // ComplexEmbedding.IsReal φ } ≃ { w : InfinitePlace K // IsReal w } := by refine (Equiv.ofBijective (fun φ => ⟨mk φ, ?_⟩) ⟨fun φ ψ h => ?_, fun w => ?_⟩) · exact ⟨φ, φ.prop, rfl⟩ · rwa [Subtype.mk.injEq, mk_eq_iff, ComplexEmbedding.isReal_iff.mp φ.prop, or_self, ← Subtype.ext_iff] at h · exact ⟨⟨embedding w, isReal_iff.mp w.prop⟩, by simp⟩ /-- The map from nonreal embeddings to complex infinite places -/ noncomputable def mkComplex : { φ : K →+* ℂ // ¬ComplexEmbedding.IsReal φ } → { w : InfinitePlace K // IsComplex w } := Subtype.map mk fun φ hφ => ⟨φ, hφ, rfl⟩ @[simp] theorem mkReal_coe (φ : { φ : K →+* ℂ // ComplexEmbedding.IsReal φ }) : (mkReal φ : InfinitePlace K) = mk (φ : K →+* ℂ) := rfl @[simp] theorem mkComplex_coe (φ : { φ : K →+* ℂ // ¬ComplexEmbedding.IsReal φ }) : (mkComplex φ : InfinitePlace K) = mk (φ : K →+* ℂ) := rfl section NumberField variable [NumberField K] /-- The infinite part of the product formula : for `x ∈ K`, we have `Π_w ‖x‖_w = |norm(x)|` where `‖·‖_w` is the normalized absolute value for `w`. -/ theorem prod_eq_abs_norm (x : K) : ∏ w : InfinitePlace K, w x ^ mult w = abs (Algebra.norm ℚ x) := by classical convert (congr_arg (‖·‖) (@Algebra.norm_eq_prod_embeddings ℚ _ _ _ _ ℂ _ _ _ _ _ x)).symm · rw [norm_prod, ← Fintype.prod_equiv RingHom.equivRatAlgHom (fun f => ‖f x‖) (fun φ => ‖φ x‖) fun _ => by simp [RingHom.equivRatAlgHom_apply]] rw [← Finset.prod_fiberwise Finset.univ mk (fun φ => ‖φ x‖)] have (w : InfinitePlace K) (φ) (hφ : φ ∈ ({φ | mk φ = w} : Finset _)) : ‖φ x‖ = w x := by rw [← (Finset.mem_filter.mp hφ).2, apply] simp_rw [Finset.prod_congr rfl (this _), Finset.prod_const, card_filter_mk_eq] · rw [eq_ratCast, Rat.cast_abs, ← Real.norm_eq_abs, ← Complex.norm_real, Complex.ofReal_ratCast] theorem one_le_of_lt_one {w : InfinitePlace K} {a : (𝓞 K)} (ha : a ≠ 0) (h : ∀ ⦃z⦄, z ≠ w → z a < 1) : 1 ≤ w a := by suffices (1 : ℝ) ≤ |Algebra.norm ℚ (a : K)| by contrapose! this rw [← InfinitePlace.prod_eq_abs_norm, ← Finset.prod_const_one] refine Finset.prod_lt_prod_of_nonempty (fun _ _ ↦ ?_) (fun z _ ↦ ?_) Finset.univ_nonempty · exact pow_pos (pos_iff.mpr ((Subalgebra.coe_eq_zero _).not.mpr ha)) _ · refine pow_lt_one₀ (apply_nonneg _ _) ?_ (by rw [mult]; split_ifs <;> norm_num) by_cases hz : z = w · rwa [hz] · exact h hz rw [← Algebra.coe_norm_int, ← Int.cast_one, ← Int.cast_abs, Rat.cast_intCast, Int.cast_le] exact Int.one_le_abs (Algebra.norm_ne_zero_iff.mpr ha) open scoped IntermediateField in theorem _root_.NumberField.is_primitive_element_of_infinitePlace_lt {x : 𝓞 K} {w : InfinitePlace K} (h₁ : x ≠ 0) (h₂ : ∀ ⦃w'⦄, w' ≠ w → w' x < 1) (h₃ : IsReal w ∨ |(w.embedding x).re| < 1) : ℚ⟮(x : K)⟯ = ⊤ := by rw [Field.primitive_element_iff_algHom_eq_of_eval ℚ ℂ ?_ _ w.embedding.toRatAlgHom] · intro ψ hψ have h : 1 ≤ w x := one_le_of_lt_one h₁ h₂ have main : w = InfinitePlace.mk ψ.toRingHom := by simp at hψ rw [← norm_embedding_eq, hψ] at h contrapose! h exact h₂ h.symm rw [(mk_embedding w).symm, mk_eq_iff] at main cases h₃ with | inl hw => rw [conjugate_embedding_eq_of_isReal hw, or_self] at main exact congr_arg RingHom.toRatAlgHom main | inr hw => refine congr_arg RingHom.toRatAlgHom (main.resolve_right fun h' ↦ hw.not_le ?_) have : (embedding w x).im = 0 := by rw [← Complex.conj_eq_iff_im] have := RingHom.congr_fun h' x simp at this rw [this] exact hψ.symm rwa [← norm_embedding_eq, ← Complex.re_add_im (embedding w x), this, Complex.ofReal_zero, zero_mul, add_zero, Complex.norm_real] at h · exact fun x ↦ IsAlgClosed.splits_codomain (minpoly ℚ x) theorem _root_.NumberField.adjoin_eq_top_of_infinitePlace_lt {x : 𝓞 K} {w : InfinitePlace K} (h₁ : x ≠ 0) (h₂ : ∀ ⦃w'⦄, w' ≠ w → w' x < 1) (h₃ : IsReal w ∨ |(w.embedding x).re| < 1) : Algebra.adjoin ℚ {(x : K)} = ⊤ := by rw [← IntermediateField.adjoin_simple_toSubalgebra_of_integral (IsIntegral.of_finite ℚ _)] exact congr_arg IntermediateField.toSubalgebra <| NumberField.is_primitive_element_of_infinitePlace_lt h₁ h₂ h₃ end NumberField open Fintype Module variable (K) section NumberField variable [NumberField K] open scoped Classical in /-- The number of infinite real places of the number field `K`. -/ noncomputable abbrev nrRealPlaces := card { w : InfinitePlace K // IsReal w } @[deprecated (since := "2024-10-24")] alias NrRealPlaces := nrRealPlaces open scoped Classical in /-- The number of infinite complex places of the number field `K`. -/ noncomputable abbrev nrComplexPlaces := card { w : InfinitePlace K // IsComplex w } @[deprecated (since := "2024-10-24")] alias NrComplexPlaces := nrComplexPlaces open scoped Classical in theorem card_real_embeddings : card { φ : K →+* ℂ // ComplexEmbedding.IsReal φ } = nrRealPlaces K := Fintype.card_congr mkReal theorem card_eq_nrRealPlaces_add_nrComplexPlaces : Fintype.card (InfinitePlace K) = nrRealPlaces K + nrComplexPlaces K := by classical convert Fintype.card_subtype_or_disjoint (IsReal (K := K)) (IsComplex (K := K)) (disjoint_isReal_isComplex K) using 1 exact (Fintype.card_of_subtype _ (fun w ↦ ⟨fun _ ↦ isReal_or_isComplex w, fun _ ↦ by simp⟩)).symm open scoped Classical in theorem card_complex_embeddings : card { φ : K →+* ℂ // ¬ComplexEmbedding.IsReal φ } = 2 * nrComplexPlaces K := by suffices ∀ w : { w : InfinitePlace K // IsComplex w }, #{φ : {φ //¬ ComplexEmbedding.IsReal φ} | mkComplex φ = w} = 2 by rw [Fintype.card, Finset.card_eq_sum_ones, ← Finset.sum_fiberwise _ (fun φ => mkComplex φ)] simp_rw [Finset.sum_const, this, smul_eq_mul, mul_one, Fintype.card, Finset.card_eq_sum_ones, Finset.mul_sum, Finset.sum_const, smul_eq_mul, mul_one] rintro ⟨w, hw⟩ convert card_filter_mk_eq w · rw [← Fintype.card_subtype, ← Fintype.card_subtype] refine Fintype.card_congr (Equiv.ofBijective ?_ ⟨fun _ _ h => ?_, fun ⟨φ, hφ⟩ => ?_⟩) · exact fun ⟨φ, hφ⟩ => ⟨φ.val, by rwa [Subtype.ext_iff] at hφ⟩ · rwa [Subtype.mk_eq_mk, ← Subtype.ext_iff, ← Subtype.ext_iff] at h · refine ⟨⟨⟨φ, not_isReal_of_mk_isComplex (hφ.symm ▸ hw)⟩, ?_⟩, rfl⟩ rwa [Subtype.ext_iff, mkComplex_coe] · simp_rw [mult, not_isReal_iff_isComplex.mpr hw, ite_false] theorem card_add_two_mul_card_eq_rank : nrRealPlaces K + 2 * nrComplexPlaces K = finrank ℚ K := by classical rw [← card_real_embeddings, ← card_complex_embeddings, Fintype.card_subtype_compl, ← Embeddings.card K ℂ, Nat.add_sub_of_le] exact Fintype.card_subtype_le _ variable {K} theorem nrComplexPlaces_eq_zero_of_finrank_eq_one (h : finrank ℚ K = 1) : nrComplexPlaces K = 0 := by linarith [card_add_two_mul_card_eq_rank K] theorem nrRealPlaces_eq_one_of_finrank_eq_one (h : finrank ℚ K = 1) : nrRealPlaces K = 1 := by have := card_add_two_mul_card_eq_rank K rwa [nrComplexPlaces_eq_zero_of_finrank_eq_one h, h, mul_zero, add_zero] at this theorem nrRealPlaces_pos_of_odd_finrank (h : Odd (finrank ℚ K)) : 0 < nrRealPlaces K := by refine Nat.pos_of_ne_zero ?_ by_contra hc refine (Nat.not_odd_iff_even.mpr ?_) h rw [← card_add_two_mul_card_eq_rank, hc, zero_add] exact even_two_mul (nrComplexPlaces K) /-- The restriction of an infinite place along an embedding. -/ def comap (w : InfinitePlace K) (f : k →+* K) : InfinitePlace k := ⟨w.1.comp f.injective, w.embedding.comp f, by { ext x; show _ = w.1 (f x); rw [← w.2.choose_spec]; rfl }⟩ end NumberField variable {K} @[simp] lemma comap_mk (φ : K →+* ℂ) (f : k →+* K) : (mk φ).comap f = mk (φ.comp f) := rfl lemma comap_id (w : InfinitePlace K) : w.comap (RingHom.id K) = w := rfl lemma comap_comp (w : InfinitePlace K) (f : F →+* K) (g : k →+* F) : w.comap (f.comp g) = (w.comap f).comap g := rfl lemma comap_mk_lift [Algebra k K] [Algebra.IsAlgebraic k K] (φ : k →+* ℂ) : (mk (ComplexEmbedding.lift K φ)).comap (algebraMap k K) = mk φ := by simp lemma IsReal.comap (f : k →+* K) {w : InfinitePlace K} (hφ : IsReal w) : IsReal (w.comap f) := by rw [← mk_embedding w, comap_mk, isReal_mk_iff] rw [← mk_embedding w, isReal_mk_iff] at hφ exact hφ.comp f lemma isReal_comap_iff (f : k ≃+* K) {w : InfinitePlace K} : IsReal (w.comap (f : k →+* K)) ↔ IsReal w := by rw [← mk_embedding w, comap_mk, isReal_mk_iff, isReal_mk_iff, ComplexEmbedding.isReal_comp_iff] lemma comap_surjective [Algebra k K] [Algebra.IsAlgebraic k K] : Function.Surjective (comap · (algebraMap k K)) := fun w ↦ ⟨(mk (ComplexEmbedding.lift K w.embedding)), by simp⟩ lemma mult_comap_le (f : k →+* K) (w : InfinitePlace K) : mult (w.comap f) ≤ mult w := by rw [mult, mult] split_ifs with h₁ h₂ h₂ pick_goal 3 · exact (h₁ (h₂.comap _)).elim all_goals decide variable [Algebra k K] (σ : K ≃ₐ[k] K) (w : InfinitePlace K) variable (k K) lemma card_mono [NumberField k] [NumberField K] : card (InfinitePlace k) ≤ card (InfinitePlace K) := have := Module.Finite.of_restrictScalars_finite ℚ k K Fintype.card_le_of_surjective _ comap_surjective variable {k K} /-- The action of the galois group on infinite places. -/ @[simps! smul_coe_apply] instance : MulAction (K ≃ₐ[k] K) (InfinitePlace K) where smul := fun σ w ↦ w.comap σ.symm one_smul := fun _ ↦ rfl mul_smul := fun _ _ _ ↦ rfl lemma smul_eq_comap : σ • w = w.comap σ.symm := rfl @[simp] lemma smul_apply (x) : (σ • w) x = w (σ.symm x) := rfl @[simp] lemma smul_mk (φ : K →+* ℂ) : σ • mk φ = mk (φ.comp σ.symm) := rfl lemma comap_smul {f : F →+* K} : (σ • w).comap f = w.comap (RingHom.comp σ.symm f) := rfl variable {σ w} lemma isReal_smul_iff : IsReal (σ • w) ↔ IsReal w := isReal_comap_iff (f := σ.symm.toRingEquiv) lemma isComplex_smul_iff : IsComplex (σ • w) ↔ IsComplex w := by rw [← not_isReal_iff_isComplex, ← not_isReal_iff_isComplex, isReal_smul_iff] lemma ComplexEmbedding.exists_comp_symm_eq_of_comp_eq [IsGalois k K] (φ ψ : K →+* ℂ) (h : φ.comp (algebraMap k K) = ψ.comp (algebraMap k K)) : ∃ σ : K ≃ₐ[k] K, φ.comp σ.symm = ψ := by letI := (φ.comp (algebraMap k K)).toAlgebra letI := φ.toAlgebra have : IsScalarTower k K ℂ := IsScalarTower.of_algebraMap_eq' rfl let ψ' : K →ₐ[k] ℂ := { ψ with commutes' := fun r ↦ (RingHom.congr_fun h r).symm } use (AlgHom.restrictNormal' ψ' K).symm ext1 x exact AlgHom.restrictNormal_commutes ψ' K x lemma exists_smul_eq_of_comap_eq [IsGalois k K] {w w' : InfinitePlace K} (h : w.comap (algebraMap k K) = w'.comap (algebraMap k K)) : ∃ σ : K ≃ₐ[k] K, σ • w = w' := by rw [← mk_embedding w, ← mk_embedding w', comap_mk, comap_mk, mk_eq_iff] at h cases h with | inl h => obtain ⟨σ, hσ⟩ := ComplexEmbedding.exists_comp_symm_eq_of_comp_eq w.embedding w'.embedding h use σ rw [← mk_embedding w, ← mk_embedding w', smul_mk, hσ] | inr h => obtain ⟨σ, hσ⟩ := ComplexEmbedding.exists_comp_symm_eq_of_comp_eq ((starRingEnd ℂ).comp (embedding w)) w'.embedding h use σ rw [← mk_embedding w, ← mk_embedding w', smul_mk, mk_eq_iff] exact Or.inr hσ lemma mem_orbit_iff [IsGalois k K] {w w' : InfinitePlace K} : w' ∈ MulAction.orbit (K ≃ₐ[k] K) w ↔ w.comap (algebraMap k K) = w'.comap (algebraMap k K) := by refine ⟨?_, exists_smul_eq_of_comap_eq⟩ rintro ⟨σ, rfl : σ • w = w'⟩ rw [← mk_embedding w, comap_mk, smul_mk, comap_mk] congr 1; ext1; simp /-- The orbits of infinite places under the action of the galois group are indexed by the infinite places of the base field. -/ noncomputable def orbitRelEquiv [IsGalois k K] : Quotient (MulAction.orbitRel (K ≃ₐ[k] K) (InfinitePlace K)) ≃ InfinitePlace k := by refine Equiv.ofBijective (Quotient.lift (comap · (algebraMap k K)) fun _ _ e ↦ (mem_orbit_iff.mp e).symm) ⟨?_, ?_⟩ · rintro ⟨w⟩ ⟨w'⟩ e exact Quotient.sound (mem_orbit_iff.mpr e.symm) · intro w obtain ⟨w', hw⟩ := comap_surjective (K := K) w exact ⟨⟦w'⟧, hw⟩ lemma orbitRelEquiv_apply_mk'' [IsGalois k K] (w : InfinitePlace K) : orbitRelEquiv (Quotient.mk'' w) = comap w (algebraMap k K) := rfl variable (k w) /-- An infinite place is unramified in a field extension if the restriction has the same multiplicity. -/ def IsUnramified : Prop := mult (w.comap (algebraMap k K)) = mult w variable {k} lemma isUnramified_self : IsUnramified K w := rfl variable {w} lemma IsUnramified.eq (h : IsUnramified k w) : mult (w.comap (algebraMap k K)) = mult w := h lemma isUnramified_iff_mult_le : IsUnramified k w ↔ mult w ≤ mult (w.comap (algebraMap k K)) := by rw [IsUnramified, le_antisymm_iff, and_iff_right] exact mult_comap_le _ _ variable [Algebra k F] lemma IsUnramified.comap_algHom {w : InfinitePlace F} (h : IsUnramified k w) (f : K →ₐ[k] F) : IsUnramified k (w.comap (f : K →+* F)) := by rw [InfinitePlace.isUnramified_iff_mult_le, ← InfinitePlace.comap_comp, f.comp_algebraMap, h.eq] exact InfinitePlace.mult_comap_le _ _ variable (K) variable [Algebra K F] [IsScalarTower k K F] lemma IsUnramified.of_restrictScalars {w : InfinitePlace F} (h : IsUnramified k w) : IsUnramified K w := by rw [InfinitePlace.isUnramified_iff_mult_le, ← h.eq, IsScalarTower.algebraMap_eq k K F, InfinitePlace.comap_comp] exact InfinitePlace.mult_comap_le _ _ lemma IsUnramified.comap {w : InfinitePlace F} (h : IsUnramified k w) : IsUnramified k (w.comap (algebraMap K F)) := h.comap_algHom (IsScalarTower.toAlgHom k K F) variable {K} lemma not_isUnramified_iff : ¬ IsUnramified k w ↔ IsComplex w ∧ IsReal (w.comap (algebraMap k K)) := by rw [IsUnramified, mult, mult, ← not_isReal_iff_isComplex] split_ifs with h₁ h₂ h₂ <;> simp only [not_true_eq_false, false_iff, and_self, forall_true_left, IsEmpty.forall_iff, not_and, OfNat.one_ne_ofNat, not_false_eq_true, true_iff, OfNat.ofNat_ne_one, h₁, h₂] exact h₁ (h₂.comap _) lemma isUnramified_iff : IsUnramified k w ↔ IsReal w ∨ IsComplex (w.comap (algebraMap k K)) := by rw [← not_iff_not, not_isUnramified_iff, not_or, not_isReal_iff_isComplex, not_isComplex_iff_isReal] variable (k) lemma IsReal.isUnramified (h : IsReal w) : IsUnramified k w := isUnramified_iff.mpr (Or.inl h) variable {k} lemma _root_.NumberField.ComplexEmbedding.IsConj.isUnramified_mk_iff {φ : K →+* ℂ} (h : ComplexEmbedding.IsConj φ σ) : IsUnramified k (mk φ) ↔ σ = 1 := by rw [h.ext_iff, ComplexEmbedding.isConj_one_iff, ← not_iff_not, not_isUnramified_iff, ← not_isReal_iff_isComplex, comap_mk, isReal_mk_iff, isReal_mk_iff, eq_true h.isReal_comp, and_true] lemma isUnramified_mk_iff_forall_isConj [IsGalois k K] {φ : K →+* ℂ} : IsUnramified k (mk φ) ↔ ∀ σ : K ≃ₐ[k] K, ComplexEmbedding.IsConj φ σ → σ = 1 := by refine ⟨fun H σ hσ ↦ hσ.isUnramified_mk_iff.mp H, fun H ↦ ?_⟩ by_contra hφ rw [not_isUnramified_iff] at hφ rw [comap_mk, isReal_mk_iff, ← not_isReal_iff_isComplex, isReal_mk_iff, ← ComplexEmbedding.isConj_one_iff (k := k)] at hφ letI := (φ.comp (algebraMap k K)).toAlgebra letI := φ.toAlgebra have : IsScalarTower k K ℂ := IsScalarTower.of_algebraMap_eq' rfl let φ' : K →ₐ[k] ℂ := { star φ with commutes' := fun r ↦ by simpa using RingHom.congr_fun hφ.2 r } have : ComplexEmbedding.IsConj φ (AlgHom.restrictNormal' φ' K) := (RingHom.ext <| AlgHom.restrictNormal_commutes φ' K).symm exact hφ.1 (H _ this ▸ this) local notation "Stab" => MulAction.stabilizer (K ≃ₐ[k] K) lemma mem_stabilizer_mk_iff (φ : K →+* ℂ) (σ : K ≃ₐ[k] K) : σ ∈ Stab (mk φ) ↔ σ = 1 ∨ ComplexEmbedding.IsConj φ σ := by simp only [MulAction.mem_stabilizer_iff, smul_mk, mk_eq_iff] rw [← ComplexEmbedding.isConj_symm, ComplexEmbedding.conjugate, star_eq_iff_star_eq] refine or_congr ⟨fun H ↦ ?_, fun H ↦ H ▸ rfl⟩ Iff.rfl exact congr_arg AlgEquiv.symm (AlgEquiv.ext (g := AlgEquiv.refl) fun x ↦ φ.injective (RingHom.congr_fun H x)) lemma IsUnramified.stabilizer_eq_bot (h : IsUnramified k w) : Stab w = ⊥ := by rw [eq_bot_iff, ← mk_embedding w, SetLike.le_def] simp only [mem_stabilizer_mk_iff, Subgroup.mem_bot, forall_eq_or_imp, true_and] exact fun σ hσ ↦ hσ.isUnramified_mk_iff.mp ((mk_embedding w).symm ▸ h) lemma _root_.NumberField.ComplexEmbedding.IsConj.coe_stabilzer_mk {φ : K →+* ℂ} (h : ComplexEmbedding.IsConj φ σ) : (Stab (mk φ) : Set (K ≃ₐ[k] K)) = {1, σ} := by ext rw [SetLike.mem_coe, mem_stabilizer_mk_iff, Set.mem_insert_iff, Set.mem_singleton_iff, ← h.ext_iff, eq_comm (a := σ)] variable (k w) lemma nat_card_stabilizer_eq_one_or_two : Nat.card (Stab w) = 1 ∨ Nat.card (Stab w) = 2 := by classical rw [← SetLike.coe_sort_coe, ← mk_embedding w] by_cases h : ∃ σ, ComplexEmbedding.IsConj (k := k) (embedding w) σ · obtain ⟨σ, hσ⟩ := h simp only [hσ.coe_stabilzer_mk, Nat.card_eq_fintype_card, card_ofFinset, Set.toFinset_singleton] by_cases 1 = σ · left; simp [*] · right; simp [*] · push_neg at h left trans Nat.card ({1} : Set (K ≃ₐ[k] K)) · congr with x simp only [SetLike.mem_coe, mem_stabilizer_mk_iff, Set.mem_singleton_iff, or_iff_left_iff_imp, h x, IsEmpty.forall_iff] · simp variable {k w} lemma isUnramified_iff_stabilizer_eq_bot [IsGalois k K] : IsUnramified k w ↔ Stab w = ⊥ := by rw [← mk_embedding w, isUnramified_mk_iff_forall_isConj] simp only [eq_bot_iff, SetLike.le_def, mem_stabilizer_mk_iff, Subgroup.mem_bot, forall_eq_or_imp, true_and] lemma isUnramified_iff_card_stabilizer_eq_one [IsGalois k K] : IsUnramified k w ↔ Nat.card (Stab w) = 1 := by rw [isUnramified_iff_stabilizer_eq_bot, Subgroup.card_eq_one] lemma not_isUnramified_iff_card_stabilizer_eq_two [IsGalois k K] : ¬ IsUnramified k w ↔ Nat.card (Stab w) = 2 := by rw [isUnramified_iff_card_stabilizer_eq_one] obtain (e|e) := nat_card_stabilizer_eq_one_or_two k w <;> rw [e] <;> decide open scoped Classical in lemma card_stabilizer [IsGalois k K] : Nat.card (Stab w) = if IsUnramified k w then 1 else 2 := by split · rwa [← isUnramified_iff_card_stabilizer_eq_one] · rwa [← not_isUnramified_iff_card_stabilizer_eq_two] lemma even_nat_card_aut_of_not_isUnramified [IsGalois k K] (hw : ¬ IsUnramified k w) : Even (Nat.card <| K ≃ₐ[k] K) := by by_cases H : Finite (K ≃ₐ[k] K)
· cases nonempty_fintype (K ≃ₐ[k] K) rw [even_iff_two_dvd, ← not_isUnramified_iff_card_stabilizer_eq_two.mp hw] exact Subgroup.card_subgroup_dvd_card (Stab w) · convert Even.zero by_contra e exact H (Nat.finite_of_card_ne_zero e)
Mathlib/NumberTheory/NumberField/Embeddings.lean
948
953
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import Mathlib.Algebra.CharP.Basic import Mathlib.Algebra.Module.End import Mathlib.Algebra.Ring.Prod import Mathlib.Data.Fintype.Units import Mathlib.GroupTheory.GroupAction.SubMulAction import Mathlib.GroupTheory.OrderOfElement import Mathlib.Tactic.FinCases /-! # Integers mod `n` Definition of the integers mod n, and the field structure on the integers mod p. ## Definitions * `ZMod n`, which is for integers modulo a nat `n : ℕ` * `val a` is defined as a natural number: - for `a : ZMod 0` it is the absolute value of `a` - for `a : ZMod n` with `0 < n` it is the least natural number in the equivalence class * A coercion `cast` is defined from `ZMod n` into any ring. This is a ring hom if the ring has characteristic dividing `n` -/ assert_not_exists Field Submodule TwoSidedIdeal open Function ZMod namespace ZMod /-- For non-zero `n : ℕ`, the ring `Fin n` is equivalent to `ZMod n`. -/ def finEquiv : ∀ (n : ℕ) [NeZero n], Fin n ≃+* ZMod n | 0, h => (h.ne _ rfl).elim | _ + 1, _ => .refl _ instance charZero : CharZero (ZMod 0) := inferInstanceAs (CharZero ℤ) /-- `val a` is a natural number defined as: - for `a : ZMod 0` it is the absolute value of `a` - for `a : ZMod n` with `0 < n` it is the least natural number in the equivalence class See `ZMod.valMinAbs` for a variant that takes values in the integers. -/ def val : ∀ {n : ℕ}, ZMod n → ℕ | 0 => Int.natAbs | n + 1 => ((↑) : Fin (n + 1) → ℕ) theorem val_lt {n : ℕ} [NeZero n] (a : ZMod n) : a.val < n := by cases n · cases NeZero.ne 0 rfl exact Fin.is_lt a theorem val_le {n : ℕ} [NeZero n] (a : ZMod n) : a.val ≤ n := a.val_lt.le @[simp] theorem val_zero : ∀ {n}, (0 : ZMod n).val = 0 | 0 => rfl | _ + 1 => rfl @[simp] theorem val_one' : (1 : ZMod 0).val = 1 := rfl @[simp] theorem val_neg' {n : ZMod 0} : (-n).val = n.val := Int.natAbs_neg n @[simp] theorem val_mul' {m n : ZMod 0} : (m * n).val = m.val * n.val := Int.natAbs_mul m n @[simp] theorem val_natCast (n a : ℕ) : (a : ZMod n).val = a % n := by cases n · rw [Nat.mod_zero] exact Int.natAbs_natCast a · apply Fin.val_natCast lemma val_natCast_of_lt {n a : ℕ} (h : a < n) : (a : ZMod n).val = a := by rwa [val_natCast, Nat.mod_eq_of_lt] lemma val_ofNat (n a : ℕ) [a.AtLeastTwo] : (ofNat(a) : ZMod n).val = ofNat(a) % n := val_natCast .. lemma val_ofNat_of_lt {n a : ℕ} [a.AtLeastTwo] (han : a < n) : (ofNat(a) : ZMod n).val = ofNat(a) := val_natCast_of_lt han theorem val_unit' {n : ZMod 0} : IsUnit n ↔ n.val = 1 := by simp only [val] rw [Int.isUnit_iff, Int.natAbs_eq_iff, Nat.cast_one] lemma eq_one_of_isUnit_natCast {n : ℕ} (h : IsUnit (n : ZMod 0)) : n = 1 := by rw [← Nat.mod_zero n, ← val_natCast, val_unit'.mp h] instance charP (n : ℕ) : CharP (ZMod n) n where cast_eq_zero_iff := by intro k rcases n with - | n · simp [zero_dvd_iff, Int.natCast_eq_zero] · exact Fin.natCast_eq_zero @[simp] theorem addOrderOf_one (n : ℕ) : addOrderOf (1 : ZMod n) = n := CharP.eq _ (CharP.addOrderOf_one _) (ZMod.charP n) /-- This lemma works in the case in which `ZMod n` is not infinite, i.e. `n ≠ 0`. The version where `a ≠ 0` is `addOrderOf_coe'`. -/ @[simp] theorem addOrderOf_coe (a : ℕ) {n : ℕ} (n0 : n ≠ 0) : addOrderOf (a : ZMod n) = n / n.gcd a := by rcases a with - | a · simp only [Nat.cast_zero, addOrderOf_zero, Nat.gcd_zero_right, Nat.pos_of_ne_zero n0, Nat.div_self] rw [← Nat.smul_one_eq_cast, addOrderOf_nsmul' _ a.succ_ne_zero, ZMod.addOrderOf_one] /-- This lemma works in the case in which `a ≠ 0`. The version where `ZMod n` is not infinite, i.e. `n ≠ 0`, is `addOrderOf_coe`. -/ @[simp] theorem addOrderOf_coe' {a : ℕ} (n : ℕ) (a0 : a ≠ 0) : addOrderOf (a : ZMod n) = n / n.gcd a := by rw [← Nat.smul_one_eq_cast, addOrderOf_nsmul' _ a0, ZMod.addOrderOf_one] /-- We have that `ringChar (ZMod n) = n`. -/ theorem ringChar_zmod_n (n : ℕ) : ringChar (ZMod n) = n := by rw [ringChar.eq_iff] exact ZMod.charP n theorem natCast_self (n : ℕ) : (n : ZMod n) = 0 := CharP.cast_eq_zero (ZMod n) n @[simp] theorem natCast_self' (n : ℕ) : (n + 1 : ZMod (n + 1)) = 0 := by rw [← Nat.cast_add_one, natCast_self (n + 1)] section UniversalProperty variable {n : ℕ} {R : Type*} section variable [AddGroupWithOne R] /-- Cast an integer modulo `n` to another semiring. This function is a morphism if the characteristic of `R` divides `n`. See `ZMod.castHom` for a bundled version. -/ def cast : ∀ {n : ℕ}, ZMod n → R | 0 => Int.cast | _ + 1 => fun i => i.val @[simp] theorem cast_zero : (cast (0 : ZMod n) : R) = 0 := by delta ZMod.cast cases n · exact Int.cast_zero · simp theorem cast_eq_val [NeZero n] (a : ZMod n) : (cast a : R) = a.val := by cases n · cases NeZero.ne 0 rfl rfl variable {S : Type*} [AddGroupWithOne S] @[simp] theorem _root_.Prod.fst_zmod_cast (a : ZMod n) : (cast a : R × S).fst = cast a := by cases n · rfl · simp [ZMod.cast] @[simp] theorem _root_.Prod.snd_zmod_cast (a : ZMod n) : (cast a : R × S).snd = cast a := by cases n · rfl · simp [ZMod.cast] end /-- So-named because the coercion is `Nat.cast` into `ZMod`. For `Nat.cast` into an arbitrary ring, see `ZMod.natCast_val`. -/ theorem natCast_zmod_val {n : ℕ} [NeZero n] (a : ZMod n) : (a.val : ZMod n) = a := by cases n · cases NeZero.ne 0 rfl · apply Fin.cast_val_eq_self theorem natCast_rightInverse [NeZero n] : Function.RightInverse val ((↑) : ℕ → ZMod n) := natCast_zmod_val theorem natCast_zmod_surjective [NeZero n] : Function.Surjective ((↑) : ℕ → ZMod n) := natCast_rightInverse.surjective /-- So-named because the outer coercion is `Int.cast` into `ZMod`. For `Int.cast` into an arbitrary ring, see `ZMod.intCast_cast`. -/ @[norm_cast] theorem intCast_zmod_cast (a : ZMod n) : ((cast a : ℤ) : ZMod n) = a := by cases n · simp [ZMod.cast, ZMod] · dsimp [ZMod.cast] rw [Int.cast_natCast, natCast_zmod_val] theorem intCast_rightInverse : Function.RightInverse (cast : ZMod n → ℤ) ((↑) : ℤ → ZMod n) := intCast_zmod_cast theorem intCast_surjective : Function.Surjective ((↑) : ℤ → ZMod n) := intCast_rightInverse.surjective lemma «forall» {P : ZMod n → Prop} : (∀ x, P x) ↔ ∀ x : ℤ, P x := intCast_surjective.forall lemma «exists» {P : ZMod n → Prop} : (∃ x, P x) ↔ ∃ x : ℤ, P x := intCast_surjective.exists theorem cast_id : ∀ (n) (i : ZMod n), (ZMod.cast i : ZMod n) = i | 0, _ => Int.cast_id | _ + 1, i => natCast_zmod_val i @[simp] theorem cast_id' : (ZMod.cast : ZMod n → ZMod n) = id := funext (cast_id n) variable (R) [Ring R] /-- The coercions are respectively `Nat.cast` and `ZMod.cast`. -/ @[simp] theorem natCast_comp_val [NeZero n] : ((↑) : ℕ → R) ∘ (val : ZMod n → ℕ) = cast := by cases n · cases NeZero.ne 0 rfl rfl /-- The coercions are respectively `Int.cast`, `ZMod.cast`, and `ZMod.cast`. -/ @[simp] theorem intCast_comp_cast : ((↑) : ℤ → R) ∘ (cast : ZMod n → ℤ) = cast := by cases n · exact congr_arg (Int.cast ∘ ·) ZMod.cast_id' · ext simp [ZMod, ZMod.cast] variable {R} @[simp] theorem natCast_val [NeZero n] (i : ZMod n) : (i.val : R) = cast i := congr_fun (natCast_comp_val R) i @[simp] theorem intCast_cast (i : ZMod n) : ((cast i : ℤ) : R) = cast i := congr_fun (intCast_comp_cast R) i theorem cast_add_eq_ite {n : ℕ} (a b : ZMod n) : (cast (a + b) : ℤ) = if (n : ℤ) ≤ cast a + cast b then (cast a + cast b - n : ℤ) else cast a + cast b := by rcases n with - | n · simp; rfl change Fin (n + 1) at a b change ((((a + b) : Fin (n + 1)) : ℕ) : ℤ) = if ((n + 1 : ℕ) : ℤ) ≤ (a : ℕ) + b then _ else _ simp only [Fin.val_add_eq_ite, Int.natCast_succ, Int.ofNat_le] norm_cast split_ifs with h · rw [Nat.cast_sub h] congr · rfl section CharDvd /-! If the characteristic of `R` divides `n`, then `cast` is a homomorphism. -/ variable {m : ℕ} [CharP R m] @[simp] theorem cast_one (h : m ∣ n) : (cast (1 : ZMod n) : R) = 1 := by rcases n with - | n · exact Int.cast_one show ((1 % (n + 1) : ℕ) : R) = 1 cases n · rw [Nat.dvd_one] at h subst m subsingleton [CharP.CharOne.subsingleton] rw [Nat.mod_eq_of_lt] · exact Nat.cast_one exact Nat.lt_of_sub_eq_succ rfl theorem cast_add (h : m ∣ n) (a b : ZMod n) : (cast (a + b : ZMod n) : R) = cast a + cast b := by cases n · apply Int.cast_add symm dsimp [ZMod, ZMod.cast, ZMod.val] rw [← Nat.cast_add, Fin.val_add, ← sub_eq_zero, ← Nat.cast_sub (Nat.mod_le _ _), @CharP.cast_eq_zero_iff R _ m] exact h.trans (Nat.dvd_sub_mod _) theorem cast_mul (h : m ∣ n) (a b : ZMod n) : (cast (a * b : ZMod n) : R) = cast a * cast b := by cases n · apply Int.cast_mul symm dsimp [ZMod, ZMod.cast, ZMod.val] rw [← Nat.cast_mul, Fin.val_mul, ← sub_eq_zero, ← Nat.cast_sub (Nat.mod_le _ _), @CharP.cast_eq_zero_iff R _ m] exact h.trans (Nat.dvd_sub_mod _) /-- The canonical ring homomorphism from `ZMod n` to a ring of characteristic dividing `n`. See also `ZMod.lift` for a generalized version working in `AddGroup`s. -/ def castHom (h : m ∣ n) (R : Type*) [Ring R] [CharP R m] : ZMod n →+* R where toFun := cast map_zero' := cast_zero map_one' := cast_one h map_add' := cast_add h map_mul' := cast_mul h @[simp] theorem castHom_apply {h : m ∣ n} (i : ZMod n) : castHom h R i = cast i := rfl @[simp] theorem cast_sub (h : m ∣ n) (a b : ZMod n) : (cast (a - b : ZMod n) : R) = cast a - cast b := (castHom h R).map_sub a b @[simp] theorem cast_neg (h : m ∣ n) (a : ZMod n) : (cast (-a : ZMod n) : R) = -(cast a) := (castHom h R).map_neg a @[simp] theorem cast_pow (h : m ∣ n) (a : ZMod n) (k : ℕ) : (cast (a ^ k : ZMod n) : R) = (cast a) ^ k := (castHom h R).map_pow a k @[simp, norm_cast] theorem cast_natCast (h : m ∣ n) (k : ℕ) : (cast (k : ZMod n) : R) = k := map_natCast (castHom h R) k @[simp, norm_cast] theorem cast_intCast (h : m ∣ n) (k : ℤ) : (cast (k : ZMod n) : R) = k := map_intCast (castHom h R) k end CharDvd section CharEq /-! Some specialised simp lemmas which apply when `R` has characteristic `n`. -/ variable [CharP R n] @[simp] theorem cast_one' : (cast (1 : ZMod n) : R) = 1 := cast_one dvd_rfl @[simp] theorem cast_add' (a b : ZMod n) : (cast (a + b : ZMod n) : R) = cast a + cast b := cast_add dvd_rfl a b @[simp] theorem cast_mul' (a b : ZMod n) : (cast (a * b : ZMod n) : R) = cast a * cast b := cast_mul dvd_rfl a b @[simp] theorem cast_sub' (a b : ZMod n) : (cast (a - b : ZMod n) : R) = cast a - cast b := cast_sub dvd_rfl a b @[simp] theorem cast_pow' (a : ZMod n) (k : ℕ) : (cast (a ^ k : ZMod n) : R) = (cast a : R) ^ k := cast_pow dvd_rfl a k @[simp, norm_cast] theorem cast_natCast' (k : ℕ) : (cast (k : ZMod n) : R) = k := cast_natCast dvd_rfl k @[simp, norm_cast] theorem cast_intCast' (k : ℤ) : (cast (k : ZMod n) : R) = k := cast_intCast dvd_rfl k variable (R) theorem castHom_injective : Function.Injective (ZMod.castHom (dvd_refl n) R) := by rw [injective_iff_map_eq_zero] intro x obtain ⟨k, rfl⟩ := ZMod.intCast_surjective x rw [map_intCast, CharP.intCast_eq_zero_iff R n, CharP.intCast_eq_zero_iff (ZMod n) n] exact id theorem castHom_bijective [Fintype R] (h : Fintype.card R = n) : Function.Bijective (ZMod.castHom (dvd_refl n) R) := by haveI : NeZero n := ⟨by intro hn rw [hn] at h exact (Fintype.card_eq_zero_iff.mp h).elim' 0⟩ rw [Fintype.bijective_iff_injective_and_card, ZMod.card, h, eq_self_iff_true, and_true] apply ZMod.castHom_injective /-- The unique ring isomorphism between `ZMod n` and a ring `R` of characteristic `n` and cardinality `n`. -/ noncomputable def ringEquiv [Fintype R] (h : Fintype.card R = n) : ZMod n ≃+* R := RingEquiv.ofBijective _ (ZMod.castHom_bijective R h) /-- The unique ring isomorphism between `ZMod p` and a ring `R` of cardinality a prime `p`. If you need any property of this isomorphism, first of all use `ringEquivOfPrime_eq_ringEquiv` below (after `have : CharP R p := ...`) and deduce it by the results about `ZMod.ringEquiv`. -/ noncomputable def ringEquivOfPrime [Fintype R] {p : ℕ} (hp : p.Prime) (hR : Fintype.card R = p) : ZMod p ≃+* R := have : Nontrivial R := Fintype.one_lt_card_iff_nontrivial.1 (hR ▸ hp.one_lt) -- The following line exists as `charP_of_card_eq_prime` in `Mathlib.Algebra.CharP.CharAndCard`. have : CharP R p := (CharP.charP_iff_prime_eq_zero hp).2 (hR ▸ Nat.cast_card_eq_zero R) ZMod.ringEquiv R hR @[simp] lemma ringEquivOfPrime_eq_ringEquiv [Fintype R] {p : ℕ} [CharP R p] (hp : p.Prime) (hR : Fintype.card R = p) : ringEquivOfPrime R hp hR = ringEquiv R hR := rfl /-- The identity between `ZMod m` and `ZMod n` when `m = n`, as a ring isomorphism. -/ def ringEquivCongr {m n : ℕ} (h : m = n) : ZMod m ≃+* ZMod n := by rcases m with - | m <;> rcases n with - | n · exact RingEquiv.refl _ · exfalso exact n.succ_ne_zero h.symm · exfalso exact m.succ_ne_zero h · exact { finCongr h with map_mul' := fun a b => by dsimp [ZMod] ext rw [Fin.coe_cast, Fin.coe_mul, Fin.coe_mul, Fin.coe_cast, Fin.coe_cast, ← h] map_add' := fun a b => by dsimp [ZMod] ext rw [Fin.coe_cast, Fin.val_add, Fin.val_add, Fin.coe_cast, Fin.coe_cast, ← h] } @[simp] lemma ringEquivCongr_refl (a : ℕ) : ringEquivCongr (rfl : a = a) = .refl _ := by cases a <;> rfl lemma ringEquivCongr_refl_apply {a : ℕ} (x : ZMod a) : ringEquivCongr rfl x = x := by rw [ringEquivCongr_refl] rfl lemma ringEquivCongr_symm {a b : ℕ} (hab : a = b) : (ringEquivCongr hab).symm = ringEquivCongr hab.symm := by subst hab cases a <;> rfl lemma ringEquivCongr_trans {a b c : ℕ} (hab : a = b) (hbc : b = c) : (ringEquivCongr hab).trans (ringEquivCongr hbc) = ringEquivCongr (hab.trans hbc) := by subst hab hbc cases a <;> rfl lemma ringEquivCongr_ringEquivCongr_apply {a b c : ℕ} (hab : a = b) (hbc : b = c) (x : ZMod a) : ringEquivCongr hbc (ringEquivCongr hab x) = ringEquivCongr (hab.trans hbc) x := by rw [← ringEquivCongr_trans hab hbc] rfl lemma ringEquivCongr_val {a b : ℕ} (h : a = b) (x : ZMod a) : ZMod.val ((ZMod.ringEquivCongr h) x) = ZMod.val x := by subst h cases a <;> rfl lemma ringEquivCongr_intCast {a b : ℕ} (h : a = b) (z : ℤ) : ZMod.ringEquivCongr h z = z := by subst h cases a <;> rfl end CharEq end UniversalProperty variable {m n : ℕ} @[simp] theorem val_eq_zero : ∀ {n : ℕ} (a : ZMod n), a.val = 0 ↔ a = 0 | 0, _ => Int.natAbs_eq_zero | n + 1, a => by rw [Fin.ext_iff] exact Iff.rfl theorem intCast_eq_intCast_iff (a b : ℤ) (c : ℕ) : (a : ZMod c) = (b : ZMod c) ↔ a ≡ b [ZMOD c] := CharP.intCast_eq_intCast (ZMod c) c theorem intCast_eq_intCast_iff' (a b : ℤ) (c : ℕ) : (a : ZMod c) = (b : ZMod c) ↔ a % c = b % c := ZMod.intCast_eq_intCast_iff a b c theorem val_intCast {n : ℕ} (a : ℤ) [NeZero n] : ↑(a : ZMod n).val = a % n := by have hle : (0 : ℤ) ≤ ↑(a : ZMod n).val := Int.natCast_nonneg _ have hlt : ↑(a : ZMod n).val < (n : ℤ) := Int.ofNat_lt.mpr (ZMod.val_lt a) refine (Int.emod_eq_of_lt hle hlt).symm.trans ?_ rw [← ZMod.intCast_eq_intCast_iff', Int.cast_natCast, ZMod.natCast_val, ZMod.cast_id] theorem natCast_eq_natCast_iff (a b c : ℕ) : (a : ZMod c) = (b : ZMod c) ↔ a ≡ b [MOD c] := by simpa [Int.natCast_modEq_iff] using ZMod.intCast_eq_intCast_iff a b c theorem natCast_eq_natCast_iff' (a b c : ℕ) : (a : ZMod c) = (b : ZMod c) ↔ a % c = b % c := ZMod.natCast_eq_natCast_iff a b c theorem intCast_zmod_eq_zero_iff_dvd (a : ℤ) (b : ℕ) : (a : ZMod b) = 0 ↔ (b : ℤ) ∣ a := by rw [← Int.cast_zero, ZMod.intCast_eq_intCast_iff, Int.modEq_zero_iff_dvd] theorem intCast_eq_intCast_iff_dvd_sub (a b : ℤ) (c : ℕ) : (a : ZMod c) = ↑b ↔ ↑c ∣ b - a := by rw [ZMod.intCast_eq_intCast_iff, Int.modEq_iff_dvd] theorem natCast_zmod_eq_zero_iff_dvd (a b : ℕ) : (a : ZMod b) = 0 ↔ b ∣ a := by rw [← Nat.cast_zero, ZMod.natCast_eq_natCast_iff, Nat.modEq_zero_iff_dvd] theorem coe_intCast (a : ℤ) : cast (a : ZMod n) = a % n := by cases n · rw [Int.ofNat_zero, Int.emod_zero, Int.cast_id]; rfl · rw [← val_intCast, val]; rfl lemma intCast_cast_add (x y : ZMod n) : (cast (x + y) : ℤ) = (cast x + cast y) % n := by rw [← ZMod.coe_intCast, Int.cast_add, ZMod.intCast_zmod_cast, ZMod.intCast_zmod_cast] lemma intCast_cast_mul (x y : ZMod n) : (cast (x * y) : ℤ) = cast x * cast y % n := by rw [← ZMod.coe_intCast, Int.cast_mul, ZMod.intCast_zmod_cast, ZMod.intCast_zmod_cast] lemma intCast_cast_sub (x y : ZMod n) : (cast (x - y) : ℤ) = (cast x - cast y) % n := by rw [← ZMod.coe_intCast, Int.cast_sub, ZMod.intCast_zmod_cast, ZMod.intCast_zmod_cast] lemma intCast_cast_neg (x : ZMod n) : (cast (-x) : ℤ) = -cast x % n := by rw [← ZMod.coe_intCast, Int.cast_neg, ZMod.intCast_zmod_cast] @[simp] theorem val_neg_one (n : ℕ) : (-1 : ZMod n.succ).val = n := by dsimp [val, Fin.coe_neg] cases n · simp [Nat.mod_one] · dsimp [ZMod, ZMod.cast] rw [Fin.coe_neg_one] /-- `-1 : ZMod n` lifts to `n - 1 : R`. This avoids the characteristic assumption in `cast_neg`. -/ theorem cast_neg_one {R : Type*} [Ring R] (n : ℕ) : cast (-1 : ZMod n) = (n - 1 : R) := by rcases n with - | n · dsimp [ZMod, ZMod.cast]; simp · rw [← natCast_val, val_neg_one, Nat.cast_succ, add_sub_cancel_right] theorem cast_sub_one {R : Type*} [Ring R] {n : ℕ} (k : ZMod n) : (cast (k - 1 : ZMod n) : R) = (if k = 0 then (n : R) else cast k) - 1 := by split_ifs with hk · rw [hk, zero_sub, ZMod.cast_neg_one] · cases n · dsimp [ZMod, ZMod.cast] rw [Int.cast_sub, Int.cast_one] · dsimp [ZMod, ZMod.cast, ZMod.val] rw [Fin.coe_sub_one, if_neg] · rw [Nat.cast_sub, Nat.cast_one] rwa [Fin.ext_iff, Fin.val_zero, ← Ne, ← Nat.one_le_iff_ne_zero] at hk · exact hk theorem natCast_eq_iff (p : ℕ) (n : ℕ) (z : ZMod p) [NeZero p] : ↑n = z ↔ ∃ k, n = z.val + p * k := by constructor · rintro rfl refine ⟨n / p, ?_⟩ rw [val_natCast, Nat.mod_add_div] · rintro ⟨k, rfl⟩ rw [Nat.cast_add, natCast_zmod_val, Nat.cast_mul, natCast_self, zero_mul, add_zero] theorem intCast_eq_iff (p : ℕ) (n : ℤ) (z : ZMod p) [NeZero p] : ↑n = z ↔ ∃ k, n = z.val + p * k := by constructor · rintro rfl refine ⟨n / p, ?_⟩ rw [val_intCast, Int.emod_add_ediv] · rintro ⟨k, rfl⟩ rw [Int.cast_add, Int.cast_mul, Int.cast_natCast, Int.cast_natCast, natCast_val, ZMod.natCast_self, zero_mul, add_zero, cast_id] @[push_cast, simp] theorem intCast_mod (a : ℤ) (b : ℕ) : ((a % b : ℤ) : ZMod b) = (a : ZMod b) := by rw [ZMod.intCast_eq_intCast_iff] apply Int.mod_modEq theorem ker_intCastAddHom (n : ℕ) : (Int.castAddHom (ZMod n)).ker = AddSubgroup.zmultiples (n : ℤ) := by ext rw [Int.mem_zmultiples_iff, AddMonoidHom.mem_ker, Int.coe_castAddHom, intCast_zmod_eq_zero_iff_dvd] theorem cast_injective_of_le {m n : ℕ} [nzm : NeZero m] (h : m ≤ n) : Function.Injective (@cast (ZMod n) _ m) := by cases m with | zero => cases nzm; simp_all | succ m => rintro ⟨x, hx⟩ ⟨y, hy⟩ f simp only [cast, val, natCast_eq_natCast_iff', Nat.mod_eq_of_lt (hx.trans_le h), Nat.mod_eq_of_lt (hy.trans_le h)] at f apply Fin.ext exact f theorem cast_zmod_eq_zero_iff_of_le {m n : ℕ} [NeZero m] (h : m ≤ n) (a : ZMod m) : (cast a : ZMod n) = 0 ↔ a = 0 := by rw [← ZMod.cast_zero (n := m)] exact Injective.eq_iff' (cast_injective_of_le h) rfl @[simp] theorem natCast_toNat (p : ℕ) : ∀ {z : ℤ} (_h : 0 ≤ z), (z.toNat : ZMod p) = z | (n : ℕ), _h => by simp only [Int.cast_natCast, Int.toNat_natCast] | Int.negSucc n, h => by simp at h theorem val_injective (n : ℕ) [NeZero n] : Function.Injective (val : ZMod n → ℕ) := by cases n · cases NeZero.ne 0 rfl intro a b h dsimp [ZMod] ext exact h theorem val_one_eq_one_mod (n : ℕ) : (1 : ZMod n).val = 1 % n := by rw [← Nat.cast_one, val_natCast] theorem val_two_eq_two_mod (n : ℕ) : (2 : ZMod n).val = 2 % n := by rw [← Nat.cast_two, val_natCast] theorem val_one (n : ℕ) [Fact (1 < n)] : (1 : ZMod n).val = 1 := by rw [val_one_eq_one_mod] exact Nat.mod_eq_of_lt Fact.out lemma val_one'' : ∀ {n}, n ≠ 1 → (1 : ZMod n).val = 1 | 0, _ => rfl | 1, hn => by cases hn rfl | n + 2, _ => haveI : Fact (1 < n + 2) := ⟨by simp⟩ ZMod.val_one _ theorem val_add {n : ℕ} [NeZero n] (a b : ZMod n) : (a + b).val = (a.val + b.val) % n := by cases n · cases NeZero.ne 0 rfl · apply Fin.val_add theorem val_add_of_lt {n : ℕ} {a b : ZMod n} (h : a.val + b.val < n) : (a + b).val = a.val + b.val := by have : NeZero n := by constructor; rintro rfl; simp at h rw [ZMod.val_add, Nat.mod_eq_of_lt h] theorem val_add_val_of_le {n : ℕ} [NeZero n] {a b : ZMod n} (h : n ≤ a.val + b.val) : a.val + b.val = (a + b).val + n := by rw [val_add, Nat.add_mod_add_of_le_add_mod, Nat.mod_eq_of_lt (val_lt _), Nat.mod_eq_of_lt (val_lt _)] rwa [Nat.mod_eq_of_lt (val_lt _), Nat.mod_eq_of_lt (val_lt _)] theorem val_add_of_le {n : ℕ} [NeZero n] {a b : ZMod n} (h : n ≤ a.val + b.val) : (a + b).val = a.val + b.val - n := by rw [val_add_val_of_le h] exact eq_tsub_of_add_eq rfl theorem val_add_le {n : ℕ} (a b : ZMod n) : (a + b).val ≤ a.val + b.val := by cases n · simpa [ZMod.val] using Int.natAbs_add_le _ _ · simpa [ZMod.val_add] using Nat.mod_le _ _ theorem val_mul {n : ℕ} (a b : ZMod n) : (a * b).val = a.val * b.val % n := by cases n · rw [Nat.mod_zero] apply Int.natAbs_mul · apply Fin.val_mul theorem val_mul_le {n : ℕ} (a b : ZMod n) : (a * b).val ≤ a.val * b.val := by rw [val_mul] apply Nat.mod_le theorem val_mul_of_lt {n : ℕ} {a b : ZMod n} (h : a.val * b.val < n) : (a * b).val = a.val * b.val := by rw [val_mul] apply Nat.mod_eq_of_lt h theorem val_mul_iff_lt {n : ℕ} [NeZero n] (a b : ZMod n) : (a * b).val = a.val * b.val ↔ a.val * b.val < n := by constructor <;> intro h · rw [← h]; apply ZMod.val_lt · apply ZMod.val_mul_of_lt h instance nontrivial (n : ℕ) [Fact (1 < n)] : Nontrivial (ZMod n) := ⟨⟨0, 1, fun h => zero_ne_one <| calc 0 = (0 : ZMod n).val := by rw [val_zero] _ = (1 : ZMod n).val := congr_arg ZMod.val h _ = 1 := val_one n ⟩⟩ instance nontrivial' : Nontrivial (ZMod 0) := by delta ZMod; infer_instance lemma one_eq_zero_iff {n : ℕ} : (1 : ZMod n) = 0 ↔ n = 1 := by rw [← Nat.cast_one, natCast_zmod_eq_zero_iff_dvd, Nat.dvd_one] /-- The inversion on `ZMod n`. It is setup in such a way that `a * a⁻¹` is equal to `gcd a.val n`. In particular, if `a` is coprime to `n`, and hence a unit, `a * a⁻¹ = 1`. -/ def inv : ∀ n : ℕ, ZMod n → ZMod n | 0, i => Int.sign i | n + 1, i => Nat.gcdA i.val (n + 1) instance (n : ℕ) : Inv (ZMod n) := ⟨inv n⟩ theorem inv_zero : ∀ n : ℕ, (0 : ZMod n)⁻¹ = 0
| 0 => Int.sign_zero | n + 1 => show (Nat.gcdA _ (n + 1) : ZMod (n + 1)) = 0 by rw [val_zero] unfold Nat.gcdA Nat.xgcd Nat.xgcdAux
Mathlib/Data/ZMod/Basic.lean
699
703
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Yury Kudryashov -/ import Mathlib.Topology.Order.LeftRight import Mathlib.Topology.Separation.Hausdorff /-! # Order-closed topologies In this file we introduce 3 typeclass mixins that relate topology and order structures: - `ClosedIicTopology` says that all the intervals $(-∞, a]$ (formally, `Set.Iic a`) are closed sets; - `ClosedIciTopology` says that all the intervals $[a, +∞)$ (formally, `Set.Ici a`) are closed sets; - `OrderClosedTopology` says that the set of points `(x, y)` such that `x ≤ y` is closed in the product topology. The last predicate implies the first two. We prove many basic properties of such topologies. ## Main statements This file contains the proofs of the following facts. For exact requirements (`OrderClosedTopology` vs `ClosedIciTopology` vs `ClosedIicTopology, `Preorder` vs `PartialOrder` vs `LinearOrder` etc) see their statements. ### Open / closed sets * `isOpen_lt` : if `f` and `g` are continuous functions, then `{x | f x < g x}` is open; * `isOpen_Iio`, `isOpen_Ioi`, `isOpen_Ioo` : open intervals are open; * `isClosed_le` : if `f` and `g` are continuous functions, then `{x | f x ≤ g x}` is closed; * `isClosed_Iic`, `isClosed_Ici`, `isClosed_Icc` : closed intervals are closed; * `frontier_le_subset_eq`, `frontier_lt_subset_eq` : frontiers of both `{x | f x ≤ g x}` and `{x | f x < g x}` are included by `{x | f x = g x}`; ### Convergence and inequalities * `le_of_tendsto_of_tendsto` : if `f` converges to `a`, `g` converges to `b`, and eventually `f x ≤ g x`, then `a ≤ b` * `le_of_tendsto`, `ge_of_tendsto` : if `f` converges to `a` and eventually `f x ≤ b` (resp., `b ≤ f x`), then `a ≤ b` (resp., `b ≤ a`); we also provide primed versions that assume the inequalities to hold for all `x`. ### Min, max, `sSup` and `sInf` * `Continuous.min`, `Continuous.max`: pointwise `min`/`max` of two continuous functions is continuous. * `Tendsto.min`, `Tendsto.max` : if `f` tends to `a` and `g` tends to `b`, then their pointwise `min`/`max` tend to `min a b` and `max a b`, respectively. -/ open Set Filter open OrderDual (toDual) open scoped Topology universe u v w variable {α : Type u} {β : Type v} {γ : Type w} /-- If `α` is a topological space and a preorder, `ClosedIicTopology α` means that `Iic a` is closed for all `a : α`. -/ class ClosedIicTopology (α : Type*) [TopologicalSpace α] [Preorder α] : Prop where /-- For any `a`, the set `(-∞, a]` is closed. -/ isClosed_Iic (a : α) : IsClosed (Iic a) /-- If `α` is a topological space and a preorder, `ClosedIciTopology α` means that `Ici a` is closed for all `a : α`. -/ class ClosedIciTopology (α : Type*) [TopologicalSpace α] [Preorder α] : Prop where /-- For any `a`, the set `[a, +∞)` is closed. -/ isClosed_Ici (a : α) : IsClosed (Ici a) /-- A topology on a set which is both a topological space and a preorder is _order-closed_ if the set of points `(x, y)` with `x ≤ y` is closed in the product space. We introduce this as a mixin. This property is satisfied for the order topology on a linear order, but it can be satisfied more generally, and suffices to derive many interesting properties relating order and topology. -/ class OrderClosedTopology (α : Type*) [TopologicalSpace α] [Preorder α] : Prop where /-- The set `{ (x, y) | x ≤ y }` is a closed set. -/ isClosed_le' : IsClosed { p : α × α | p.1 ≤ p.2 } instance [TopologicalSpace α] [h : FirstCountableTopology α] : FirstCountableTopology αᵒᵈ := h instance [TopologicalSpace α] [h : SecondCountableTopology α] : SecondCountableTopology αᵒᵈ := h theorem Dense.orderDual [TopologicalSpace α] {s : Set α} (hs : Dense s) : Dense (OrderDual.ofDual ⁻¹' s) := hs section General variable [TopologicalSpace α] [Preorder α] {s : Set α} protected lemma BddAbove.of_closure : BddAbove (closure s) → BddAbove s := BddAbove.mono subset_closure protected lemma BddBelow.of_closure : BddBelow (closure s) → BddBelow s := BddBelow.mono subset_closure end General section ClosedIicTopology section Preorder variable [TopologicalSpace α] [Preorder α] [ClosedIicTopology α] {f : β → α} {a b : α} {s : Set α} theorem isClosed_Iic : IsClosed (Iic a) := ClosedIicTopology.isClosed_Iic a instance : ClosedIciTopology αᵒᵈ where isClosed_Ici _ := isClosed_Iic (α := α) @[simp] theorem closure_Iic (a : α) : closure (Iic a) = Iic a := isClosed_Iic.closure_eq theorem le_of_tendsto_of_frequently {x : Filter β} (lim : Tendsto f x (𝓝 a)) (h : ∃ᶠ c in x, f c ≤ b) : a ≤ b := isClosed_Iic.mem_of_frequently_of_tendsto h lim theorem le_of_tendsto {x : Filter β} [NeBot x] (lim : Tendsto f x (𝓝 a)) (h : ∀ᶠ c in x, f c ≤ b) : a ≤ b := isClosed_Iic.mem_of_tendsto lim h theorem le_of_tendsto' {x : Filter β} [NeBot x] (lim : Tendsto f x (𝓝 a)) (h : ∀ c, f c ≤ b) : a ≤ b := le_of_tendsto lim (Eventually.of_forall h) @[simp] lemma upperBounds_closure (s : Set α) : upperBounds (closure s : Set α) = upperBounds s := ext fun a ↦ by simp_rw [mem_upperBounds_iff_subset_Iic, isClosed_Iic.closure_subset_iff] @[simp] lemma bddAbove_closure : BddAbove (closure s) ↔ BddAbove s := by simp_rw [BddAbove, upperBounds_closure] protected alias ⟨_, BddAbove.closure⟩ := bddAbove_closure @[simp] theorem disjoint_nhds_atBot_iff : Disjoint (𝓝 a) atBot ↔ ¬IsBot a := by constructor · intro hd hbot rw [hbot.atBot_eq, disjoint_principal_right] at hd exact mem_of_mem_nhds hd le_rfl · simp only [IsBot, not_forall] rintro ⟨b, hb⟩ refine disjoint_of_disjoint_of_mem disjoint_compl_left ?_ (Iic_mem_atBot b) exact isClosed_Iic.isOpen_compl.mem_nhds hb theorem IsLUB.range_of_tendsto {F : Filter β} [F.NeBot] (hle : ∀ i, f i ≤ a) (hlim : Tendsto f F (𝓝 a)) : IsLUB (range f) a := ⟨forall_mem_range.mpr hle, fun _c hc ↦ le_of_tendsto' hlim fun i ↦ hc <| mem_range_self i⟩ end Preorder section NoBotOrder variable [Preorder α] [NoBotOrder α] [TopologicalSpace α] [ClosedIicTopology α] {a : α} {l : Filter β} [NeBot l] {f : β → α} theorem disjoint_nhds_atBot (a : α) : Disjoint (𝓝 a) atBot := by simp @[simp] theorem inf_nhds_atBot (a : α) : 𝓝 a ⊓ atBot = ⊥ := (disjoint_nhds_atBot a).eq_bot theorem not_tendsto_nhds_of_tendsto_atBot (hf : Tendsto f l atBot) (a : α) : ¬Tendsto f l (𝓝 a) := hf.not_tendsto (disjoint_nhds_atBot a).symm theorem not_tendsto_atBot_of_tendsto_nhds (hf : Tendsto f l (𝓝 a)) : ¬Tendsto f l atBot := hf.not_tendsto (disjoint_nhds_atBot a) end NoBotOrder theorem iSup_eq_of_forall_le_of_tendsto {ι : Type*} {F : Filter ι} [Filter.NeBot F] [ConditionallyCompleteLattice α] [TopologicalSpace α] [ClosedIicTopology α] {a : α} {f : ι → α} (hle : ∀ i, f i ≤ a) (hlim : Filter.Tendsto f F (𝓝 a)) : ⨆ i, f i = a := have := F.nonempty_of_neBot (IsLUB.range_of_tendsto hle hlim).ciSup_eq theorem iUnion_Iic_eq_Iio_of_lt_of_tendsto {ι : Type*} {F : Filter ι} [F.NeBot] [ConditionallyCompleteLinearOrder α] [TopologicalSpace α] [ClosedIicTopology α] {a : α} {f : ι → α} (hlt : ∀ i, f i < a) (hlim : Tendsto f F (𝓝 a)) : ⋃ i : ι, Iic (f i) = Iio a := by have obs : a ∉ range f := by rw [mem_range] rintro ⟨i, rfl⟩ exact (hlt i).false rw [← biUnion_range, (IsLUB.range_of_tendsto (le_of_lt <| hlt ·) hlim).biUnion_Iic_eq_Iio obs] section LinearOrder variable [TopologicalSpace α] [LinearOrder α] [ClosedIicTopology α] [TopologicalSpace β] {a b c : α} {f : α → β} theorem isOpen_Ioi : IsOpen (Ioi a) := by rw [← compl_Iic] exact isClosed_Iic.isOpen_compl @[simp] theorem interior_Ioi : interior (Ioi a) = Ioi a := isOpen_Ioi.interior_eq theorem Ioi_mem_nhds (h : a < b) : Ioi a ∈ 𝓝 b := IsOpen.mem_nhds isOpen_Ioi h theorem eventually_gt_nhds (hab : b < a) : ∀ᶠ x in 𝓝 a, b < x := Ioi_mem_nhds hab theorem Ici_mem_nhds (h : a < b) : Ici a ∈ 𝓝 b := mem_of_superset (Ioi_mem_nhds h) Ioi_subset_Ici_self theorem eventually_ge_nhds (hab : b < a) : ∀ᶠ x in 𝓝 a, b ≤ x := Ici_mem_nhds hab theorem Filter.Tendsto.eventually_const_lt {l : Filter γ} {f : γ → α} {u v : α} (hv : u < v) (h : Filter.Tendsto f l (𝓝 v)) : ∀ᶠ a in l, u < f a := h.eventually <| eventually_gt_nhds hv @[deprecated (since := "2024-11-17")] alias eventually_gt_of_tendsto_gt := Filter.Tendsto.eventually_const_lt theorem Filter.Tendsto.eventually_const_le {l : Filter γ} {f : γ → α} {u v : α} (hv : u < v) (h : Tendsto f l (𝓝 v)) : ∀ᶠ a in l, u ≤ f a := h.eventually <| eventually_ge_nhds hv @[deprecated (since := "2024-11-17")] alias eventually_ge_of_tendsto_gt := Filter.Tendsto.eventually_const_le protected theorem Dense.exists_gt [NoMaxOrder α] {s : Set α} (hs : Dense s) (x : α) : ∃ y ∈ s, x < y := hs.exists_mem_open isOpen_Ioi (exists_gt x) protected theorem Dense.exists_ge [NoMaxOrder α] {s : Set α} (hs : Dense s) (x : α) : ∃ y ∈ s, x ≤ y := (hs.exists_gt x).imp fun _ h ↦ ⟨h.1, h.2.le⟩ theorem Dense.exists_ge' {s : Set α} (hs : Dense s) (htop : ∀ x, IsTop x → x ∈ s) (x : α) : ∃ y ∈ s, x ≤ y := by by_cases hx : IsTop x · exact ⟨x, htop x hx, le_rfl⟩ · simp only [IsTop, not_forall, not_le] at hx rcases hs.exists_mem_open isOpen_Ioi hx with ⟨y, hys, hy : x < y⟩ exact ⟨y, hys, hy.le⟩ /-! ### Left neighborhoods on a `ClosedIicTopology` Limits to the left of real functions are defined in terms of neighborhoods to the left, either open or closed, i.e., members of `𝓝[<] a` and `𝓝[≤] a`. Here we prove that all left-neighborhoods of a point are equal, and we prove other useful characterizations which require the stronger hypothesis `OrderTopology α` in another file. -/ /-! #### Point excluded -/ theorem Ioo_mem_nhdsLT (H : a < b) : Ioo a b ∈ 𝓝[<] b := by simpa only [← Iio_inter_Ioi] using inter_mem_nhdsWithin _ (Ioi_mem_nhds H) @[deprecated (since := "2024-12-21")] alias Ioo_mem_nhdsWithin_Iio' := Ioo_mem_nhdsLT theorem Ioo_mem_nhdsLT_of_mem (H : b ∈ Ioc a c) : Ioo a c ∈ 𝓝[<] b := mem_of_superset (Ioo_mem_nhdsLT H.1) <| Ioo_subset_Ioo_right H.2 @[deprecated (since := "2024-12-21")] alias Ioo_mem_nhdsWithin_Iio := Ioo_mem_nhdsLT_of_mem protected theorem CovBy.nhdsLT (h : a ⋖ b) : 𝓝[<] b = ⊥ := empty_mem_iff_bot.mp <| h.Ioo_eq ▸ Ioo_mem_nhdsLT h.1 @[deprecated (since := "2024-12-21")] protected alias CovBy.nhdsWithin_Iio := CovBy.nhdsLT protected theorem PredOrder.nhdsLT [PredOrder α] : 𝓝[<] a = ⊥ := by if h : IsMin a then simp [h.Iio_eq] else exact (Order.pred_covBy_of_not_isMin h).nhdsLT @[deprecated (since := "2024-12-21")] protected alias PredOrder.nhdsWithin_Iio := PredOrder.nhdsLT theorem PredOrder.nhdsGT_eq_nhdsNE [PredOrder α] (a : α) : 𝓝[>] a = 𝓝[≠] a := by rw [← nhdsLT_sup_nhdsGT, PredOrder.nhdsLT, bot_sup_eq] theorem PredOrder.nhdsGE_eq_nhds [PredOrder α] (a : α) : 𝓝[≥] a = 𝓝 a := by rw [← nhdsLT_sup_nhdsGE, PredOrder.nhdsLT, bot_sup_eq] theorem Ico_mem_nhdsLT_of_mem (H : b ∈ Ioc a c) : Ico a c ∈ 𝓝[<] b := mem_of_superset (Ioo_mem_nhdsLT_of_mem H) Ioo_subset_Ico_self @[deprecated (since := "2024-12-21")] alias Ico_mem_nhdsWithin_Iio := Ico_mem_nhdsLT_of_mem theorem Ico_mem_nhdsLT (H : a < b) : Ico a b ∈ 𝓝[<] b := Ico_mem_nhdsLT_of_mem ⟨H, le_rfl⟩ @[deprecated (since := "2024-12-21")] alias Ico_mem_nhdsWithin_Iio' := Ico_mem_nhdsLT theorem Ioc_mem_nhdsLT_of_mem (H : b ∈ Ioc a c) : Ioc a c ∈ 𝓝[<] b := mem_of_superset (Ioo_mem_nhdsLT_of_mem H) Ioo_subset_Ioc_self @[deprecated (since := "2024-12-21")] alias Ioc_mem_nhdsWithin_Iio := Ioc_mem_nhdsLT_of_mem theorem Ioc_mem_nhdsLT (H : a < b) : Ioc a b ∈ 𝓝[<] b := Ioc_mem_nhdsLT_of_mem ⟨H, le_rfl⟩ @[deprecated (since := "2024-12-21")] alias Ioc_mem_nhdsWithin_Iio' := Ioc_mem_nhdsLT theorem Icc_mem_nhdsLT_of_mem (H : b ∈ Ioc a c) : Icc a c ∈ 𝓝[<] b := mem_of_superset (Ioo_mem_nhdsLT_of_mem H) Ioo_subset_Icc_self @[deprecated (since := "2024-12-21")] alias Icc_mem_nhdsWithin_Iio := Icc_mem_nhdsLT_of_mem theorem Icc_mem_nhdsLT (H : a < b) : Icc a b ∈ 𝓝[<] b := Icc_mem_nhdsLT_of_mem ⟨H, le_rfl⟩ @[deprecated (since := "2024-12-21")] alias Icc_mem_nhdsWithin_Iio' := Icc_mem_nhdsLT @[simp] theorem nhdsWithin_Ico_eq_nhdsLT (h : a < b) : 𝓝[Ico a b] b = 𝓝[<] b := nhdsWithin_inter_of_mem <| nhdsWithin_le_nhds <| Ici_mem_nhds h @[deprecated (since := "2024-12-21")] alias nhdsWithin_Ico_eq_nhdsWithin_Iio := nhdsWithin_Ico_eq_nhdsLT @[simp] theorem nhdsWithin_Ioo_eq_nhdsLT (h : a < b) : 𝓝[Ioo a b] b = 𝓝[<] b := nhdsWithin_inter_of_mem <| nhdsWithin_le_nhds <| Ioi_mem_nhds h @[deprecated (since := "2024-12-21")] alias nhdsWithin_Ioo_eq_nhdsWithin_Iio := nhdsWithin_Ioo_eq_nhdsLT @[simp] theorem continuousWithinAt_Ico_iff_Iio (h : a < b) : ContinuousWithinAt f (Ico a b) b ↔ ContinuousWithinAt f (Iio b) b := by simp only [ContinuousWithinAt, nhdsWithin_Ico_eq_nhdsLT h] @[simp] theorem continuousWithinAt_Ioo_iff_Iio (h : a < b) : ContinuousWithinAt f (Ioo a b) b ↔ ContinuousWithinAt f (Iio b) b := by simp only [ContinuousWithinAt, nhdsWithin_Ioo_eq_nhdsLT h] /-! #### Point included -/ protected theorem CovBy.nhdsLE (H : a ⋖ b) : 𝓝[≤] b = pure b := by rw [← Iio_insert, nhdsWithin_insert, H.nhdsLT, sup_bot_eq] @[deprecated (since := "2024-12-21")] protected alias CovBy.nhdsWithin_Iic := CovBy.nhdsLE protected theorem PredOrder.nhdsLE [PredOrder α] : 𝓝[≤] b = pure b := by rw [← Iio_insert, nhdsWithin_insert, PredOrder.nhdsLT, sup_bot_eq] @[deprecated (since := "2024-12-21")] protected alias PredOrder.nhdsWithin_Iic := PredOrder.nhdsLE theorem Ioc_mem_nhdsLE (H : a < b) : Ioc a b ∈ 𝓝[≤] b := inter_mem (nhdsWithin_le_nhds <| Ioi_mem_nhds H) self_mem_nhdsWithin @[deprecated (since := "2024-12-21")] alias Ioc_mem_nhdsWithin_Iic' := Ioc_mem_nhdsLE theorem Ioo_mem_nhdsLE_of_mem (H : b ∈ Ioo a c) : Ioo a c ∈ 𝓝[≤] b := mem_of_superset (Ioc_mem_nhdsLE H.1) <| Ioc_subset_Ioo_right H.2 @[deprecated (since := "2024-12-21")] alias Ioo_mem_nhdsWithin_Iic := Ioo_mem_nhdsLE_of_mem theorem Ico_mem_nhdsLE_of_mem (H : b ∈ Ioo a c) : Ico a c ∈ 𝓝[≤] b := mem_of_superset (Ioo_mem_nhdsLE_of_mem H) Ioo_subset_Ico_self @[deprecated (since := "2024-12-22")] alias Ico_mem_nhdsWithin_Iic := Ico_mem_nhdsLE_of_mem theorem Ioc_mem_nhdsLE_of_mem (H : b ∈ Ioc a c) : Ioc a c ∈ 𝓝[≤] b := mem_of_superset (Ioc_mem_nhdsLE H.1) <| Ioc_subset_Ioc_right H.2 @[deprecated (since := "2024-12-22")] alias Ioc_mem_nhdsWithin_Iic := Ioc_mem_nhdsLE_of_mem theorem Icc_mem_nhdsLE_of_mem (H : b ∈ Ioc a c) : Icc a c ∈ 𝓝[≤] b := mem_of_superset (Ioc_mem_nhdsLE_of_mem H) Ioc_subset_Icc_self @[deprecated (since := "2024-12-22")] alias Icc_mem_nhdsWithin_Iic := Icc_mem_nhdsLE_of_mem theorem Icc_mem_nhdsLE (H : a < b) : Icc a b ∈ 𝓝[≤] b := Icc_mem_nhdsLE_of_mem ⟨H, le_rfl⟩ @[deprecated (since := "2024-12-22")] alias Icc_mem_nhdsWithin_Iic' := Icc_mem_nhdsLE @[simp] theorem nhdsWithin_Icc_eq_nhdsLE (h : a < b) : 𝓝[Icc a b] b = 𝓝[≤] b := nhdsWithin_inter_of_mem <| nhdsWithin_le_nhds <| Ici_mem_nhds h @[deprecated (since := "2024-12-22")] alias nhdsWithin_Icc_eq_nhdsWithin_Iic := nhdsWithin_Icc_eq_nhdsLE @[simp] theorem nhdsWithin_Ioc_eq_nhdsLE (h : a < b) : 𝓝[Ioc a b] b = 𝓝[≤] b := nhdsWithin_inter_of_mem <| nhdsWithin_le_nhds <| Ioi_mem_nhds h @[deprecated (since := "2024-12-22")] alias nhdsWithin_Ioc_eq_nhdsWithin_Iic := nhdsWithin_Ioc_eq_nhdsLE @[simp] theorem continuousWithinAt_Icc_iff_Iic (h : a < b) : ContinuousWithinAt f (Icc a b) b ↔ ContinuousWithinAt f (Iic b) b := by simp only [ContinuousWithinAt, nhdsWithin_Icc_eq_nhdsLE h] @[simp] theorem continuousWithinAt_Ioc_iff_Iic (h : a < b) : ContinuousWithinAt f (Ioc a b) b ↔ ContinuousWithinAt f (Iic b) b := by simp only [ContinuousWithinAt, nhdsWithin_Ioc_eq_nhdsLE h] end LinearOrder end ClosedIicTopology section ClosedIciTopology section Preorder variable [TopologicalSpace α] [Preorder α] [ClosedIciTopology α] {f : β → α} {a b : α} {s : Set α} theorem isClosed_Ici {a : α} : IsClosed (Ici a) := ClosedIciTopology.isClosed_Ici a instance : ClosedIicTopology αᵒᵈ where isClosed_Iic _ := isClosed_Ici (α := α) @[simp] theorem closure_Ici (a : α) : closure (Ici a) = Ici a := isClosed_Ici.closure_eq lemma ge_of_tendsto_of_frequently {x : Filter β} (lim : Tendsto f x (𝓝 a)) (h : ∃ᶠ c in x, b ≤ f c) : b ≤ a := isClosed_Ici.mem_of_frequently_of_tendsto h lim theorem ge_of_tendsto {x : Filter β} [NeBot x] (lim : Tendsto f x (𝓝 a)) (h : ∀ᶠ c in x, b ≤ f c) : b ≤ a := isClosed_Ici.mem_of_tendsto lim h theorem ge_of_tendsto' {x : Filter β} [NeBot x] (lim : Tendsto f x (𝓝 a)) (h : ∀ c, b ≤ f c) : b ≤ a := ge_of_tendsto lim (Eventually.of_forall h) @[simp] lemma lowerBounds_closure (s : Set α) : lowerBounds (closure s : Set α) = lowerBounds s := ext fun a ↦ by simp_rw [mem_lowerBounds_iff_subset_Ici, isClosed_Ici.closure_subset_iff] @[simp] lemma bddBelow_closure : BddBelow (closure s) ↔ BddBelow s := by simp_rw [BddBelow, lowerBounds_closure] protected alias ⟨_, BddBelow.closure⟩ := bddBelow_closure @[simp] theorem disjoint_nhds_atTop_iff : Disjoint (𝓝 a) atTop ↔ ¬IsTop a := disjoint_nhds_atBot_iff (α := αᵒᵈ) theorem IsGLB.range_of_tendsto {F : Filter β} [F.NeBot] (hle : ∀ i, a ≤ f i) (hlim : Tendsto f F (𝓝 a)) : IsGLB (range f) a := IsLUB.range_of_tendsto (α := αᵒᵈ) hle hlim end Preorder section NoTopOrder variable [Preorder α] [NoTopOrder α] [TopologicalSpace α] [ClosedIciTopology α] {a : α} {l : Filter β} [NeBot l] {f : β → α} theorem disjoint_nhds_atTop (a : α) : Disjoint (𝓝 a) atTop := disjoint_nhds_atBot (toDual a) @[simp] theorem inf_nhds_atTop (a : α) : 𝓝 a ⊓ atTop = ⊥ := (disjoint_nhds_atTop a).eq_bot theorem not_tendsto_nhds_of_tendsto_atTop (hf : Tendsto f l atTop) (a : α) : ¬Tendsto f l (𝓝 a) := hf.not_tendsto (disjoint_nhds_atTop a).symm theorem not_tendsto_atTop_of_tendsto_nhds (hf : Tendsto f l (𝓝 a)) : ¬Tendsto f l atTop := hf.not_tendsto (disjoint_nhds_atTop a) end NoTopOrder theorem iInf_eq_of_forall_le_of_tendsto {ι : Type*} {F : Filter ι} [F.NeBot] [ConditionallyCompleteLattice α] [TopologicalSpace α] [ClosedIciTopology α] {a : α} {f : ι → α} (hle : ∀ i, a ≤ f i) (hlim : Tendsto f F (𝓝 a)) : ⨅ i, f i = a := iSup_eq_of_forall_le_of_tendsto (α := αᵒᵈ) hle hlim theorem iUnion_Ici_eq_Ioi_of_lt_of_tendsto {ι : Type*} {F : Filter ι} [F.NeBot] [ConditionallyCompleteLinearOrder α] [TopologicalSpace α] [ClosedIciTopology α] {a : α} {f : ι → α} (hlt : ∀ i, a < f i) (hlim : Tendsto f F (𝓝 a)) : ⋃ i : ι, Ici (f i) = Ioi a := iUnion_Iic_eq_Iio_of_lt_of_tendsto (α := αᵒᵈ) hlt hlim section LinearOrder variable [TopologicalSpace α] [LinearOrder α] [ClosedIciTopology α] [TopologicalSpace β] {a b c : α} {f : α → β} theorem isOpen_Iio : IsOpen (Iio a) := isOpen_Ioi (α := αᵒᵈ) @[simp] theorem interior_Iio : interior (Iio a) = Iio a := isOpen_Iio.interior_eq theorem Iio_mem_nhds (h : a < b) : Iio b ∈ 𝓝 a := isOpen_Iio.mem_nhds h theorem eventually_lt_nhds (hab : a < b) : ∀ᶠ x in 𝓝 a, x < b := Iio_mem_nhds hab theorem Iic_mem_nhds (h : a < b) : Iic b ∈ 𝓝 a := mem_of_superset (Iio_mem_nhds h) Iio_subset_Iic_self theorem eventually_le_nhds (hab : a < b) : ∀ᶠ x in 𝓝 a, x ≤ b := Iic_mem_nhds hab theorem Filter.Tendsto.eventually_lt_const {l : Filter γ} {f : γ → α} {u v : α} (hv : v < u) (h : Filter.Tendsto f l (𝓝 v)) : ∀ᶠ a in l, f a < u := h.eventually <| eventually_lt_nhds hv @[deprecated (since := "2024-11-17")] alias eventually_lt_of_tendsto_lt := Filter.Tendsto.eventually_lt_const theorem Filter.Tendsto.eventually_le_const {l : Filter γ} {f : γ → α} {u v : α} (hv : v < u) (h : Tendsto f l (𝓝 v)) : ∀ᶠ a in l, f a ≤ u := h.eventually <| eventually_le_nhds hv @[deprecated (since := "2024-11-17")] alias eventually_le_of_tendsto_lt := Filter.Tendsto.eventually_le_const protected theorem Dense.exists_lt [NoMinOrder α] {s : Set α} (hs : Dense s) (x : α) : ∃ y ∈ s, y < x := hs.orderDual.exists_gt x protected theorem Dense.exists_le [NoMinOrder α] {s : Set α} (hs : Dense s) (x : α) : ∃ y ∈ s, y ≤ x := hs.orderDual.exists_ge x theorem Dense.exists_le' {s : Set α} (hs : Dense s) (hbot : ∀ x, IsBot x → x ∈ s) (x : α) : ∃ y ∈ s, y ≤ x := hs.orderDual.exists_ge' hbot x /-! ### Right neighborhoods on a `ClosedIciTopology` Limits to the right of real functions are defined in terms of neighborhoods to the right, either open or closed, i.e., members of `𝓝[>] a` and `𝓝[≥] a`. Here we prove that all right-neighborhoods of a point are equal, and we prove other useful characterizations which require the stronger hypothesis `OrderTopology α` in another file. -/ /-! #### Point excluded -/ theorem Ioo_mem_nhdsGT_of_mem (H : b ∈ Ico a c) : Ioo a c ∈ 𝓝[>] b := mem_nhdsWithin.2 ⟨Iio c, isOpen_Iio, H.2, by rw [inter_comm, Ioi_inter_Iio]; exact Ioo_subset_Ioo_left H.1⟩ @[deprecated (since := "2024-12-22")] alias Ioo_mem_nhdsWithin_Ioi := Ioo_mem_nhdsGT_of_mem theorem Ioo_mem_nhdsGT (H : a < b) : Ioo a b ∈ 𝓝[>] a := Ioo_mem_nhdsGT_of_mem ⟨le_rfl, H⟩ @[deprecated (since := "2024-12-22")] alias Ioo_mem_nhdsWithin_Ioi' := Ioo_mem_nhdsGT protected theorem CovBy.nhdsGT (h : a ⋖ b) : 𝓝[>] a = ⊥ := h.toDual.nhdsLT @[deprecated (since := "2024-12-22")] alias CovBy.nhdsWithin_Ioi := CovBy.nhdsGT
protected theorem SuccOrder.nhdsGT [SuccOrder α] : 𝓝[>] a = ⊥ := PredOrder.nhdsLT (α := αᵒᵈ)
Mathlib/Topology/Order/OrderClosed.lean
560
562
/- Copyright (c) 2023 Claus Clausen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Claus Clausen, Patrick Massot -/ import Mathlib.Probability.Notation import Mathlib.Probability.CDF import Mathlib.Probability.Distributions.Gamma /-! # Exponential distributions over ℝ Define the Exponential measure over the reals. ## Main definitions * `exponentialPDFReal`: the function `r x ↦ r * exp (-(r * x)` for `0 ≤ x` or `0` else, which is the probability density function of a exponential distribution with rate `r` (when `hr : 0 < r`). * `exponentialPDF`: `ℝ≥0∞`-valued pdf, `exponentialPDF r = ENNReal.ofReal (exponentialPDFReal r)`. * `expMeasure`: an exponential measure on `ℝ`, parametrized by its rate `r`. * `exponentialCDFReal`: the CDF given by the definition of CDF in `ProbabilityTheory.CDF` applied to the exponential measure. ## Main results * `exponentialCDFReal_eq`: Proof that the `exponentialCDFReal` given by the definition equals the known function given as `r x ↦ 1 - exp (- (r * x))` for `0 ≤ x` or `0` else. -/ open scoped ENNReal NNReal open MeasureTheory Real Set Filter Topology namespace ProbabilityTheory section ExponentialPDF /-- The pdf of the exponential distribution depending on its rate -/ noncomputable def exponentialPDFReal (r x : ℝ) : ℝ := gammaPDFReal 1 r x /-- The pdf of the exponential distribution, as a function valued in `ℝ≥0∞` -/ noncomputable def exponentialPDF (r x : ℝ) : ℝ≥0∞ := ENNReal.ofReal (exponentialPDFReal r x)
lemma exponentialPDF_eq (r x : ℝ) : exponentialPDF r x = ENNReal.ofReal (if 0 ≤ x then r * exp (-(r * x)) else 0) := by rw [exponentialPDF, exponentialPDFReal, gammaPDFReal] simp only [rpow_one, Gamma_one, div_one, sub_self, rpow_zero, mul_one]
Mathlib/Probability/Distributions/Exponential.lean
47
50
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen, Eric Wieser -/ import Mathlib.Algebra.Group.Fin.Tuple import Mathlib.Data.Matrix.RowCol import Mathlib.Data.Fin.VecNotation import Mathlib.Tactic.FinCases import Mathlib.Algebra.BigOperators.Fin /-! # Matrix and vector notation This file includes `simp` lemmas for applying operations in `Data.Matrix.Basic` to values built out of the matrix notation `![a, b] = vecCons a (vecCons b vecEmpty)` defined in `Data.Fin.VecNotation`. This also provides the new notation `!![a, b; c, d] = Matrix.of ![![a, b], ![c, d]]`. This notation also works for empty matrices; `!![,,,] : Matrix (Fin 0) (Fin 3)` and `!![;;;] : Matrix (Fin 3) (Fin 0)`. ## Implementation notes The `simp` lemmas require that one of the arguments is of the form `vecCons _ _`. This ensures `simp` works with entries only when (some) entries are already given. In other words, this notation will only appear in the output of `simp` if it already appears in the input. ## Notations This file provide notation `!![a, b; c, d]` for matrices, which corresponds to `Matrix.of ![![a, b], ![c, d]]`. ## Examples Examples of usage can be found in the `MathlibTest/matrix.lean` file. -/ namespace Matrix universe u uₘ uₙ uₒ variable {α : Type u} {o n m : ℕ} {m' : Type uₘ} {n' : Type uₙ} {o' : Type uₒ} open Matrix section toExpr open Lean Qq open Qq in /-- `Matrix.mkLiteralQ !![a, b; c, d]` produces the term `q(!![$a, $b; $c, $d])`. -/ def mkLiteralQ {u : Level} {α : Q(Type u)} {m n : Nat} (elems : Matrix (Fin m) (Fin n) Q($α)) : Q(Matrix (Fin $m) (Fin $n) $α) := let elems := PiFin.mkLiteralQ (α := q(Fin $n → $α)) fun i => PiFin.mkLiteralQ fun j => elems i j q(Matrix.of $elems) /-- Matrices can be reflected whenever their entries can. We insert a `Matrix.of` to prevent immediate decay to a function. -/ protected instance toExpr [ToLevel.{u}] [ToLevel.{uₘ}] [ToLevel.{uₙ}] [Lean.ToExpr α] [Lean.ToExpr m'] [Lean.ToExpr n'] [Lean.ToExpr (m' → n' → α)] : Lean.ToExpr (Matrix m' n' α) := have eα : Q(Type $(toLevel.{u})) := toTypeExpr α have em' : Q(Type $(toLevel.{uₘ})) := toTypeExpr m' have en' : Q(Type $(toLevel.{uₙ})) := toTypeExpr n' { toTypeExpr := q(Matrix $eα $em' $en') toExpr := fun M => have eM : Q($em' → $en' → $eα) := toExpr (show m' → n' → α from M) q(Matrix.of $eM) } end toExpr section Parser open Lean Meta Elab Term Macro TSyntax PrettyPrinter.Delaborator SubExpr /-- Notation for m×n matrices, aka `Matrix (Fin m) (Fin n) α`. For instance: * `!![a, b, c; d, e, f]` is the matrix with two rows and three columns, of type `Matrix (Fin 2) (Fin 3) α` * `!![a, b, c]` is a row vector of type `Matrix (Fin 1) (Fin 3) α` (see also `Matrix.row`). * `!![a; b; c]` is a column vector of type `Matrix (Fin 3) (Fin 1) α` (see also `Matrix.col`). This notation implements some special cases: * `![,,]`, with `n` `,`s, is a term of type `Matrix (Fin 0) (Fin n) α` * `![;;]`, with `m` `;`s, is a term of type `Matrix (Fin m) (Fin 0) α` * `![]` is the 0×0 matrix Note that vector notation is provided elsewhere (by `Matrix.vecNotation`) as `![a, b, c]`. Under the hood, `!![a, b, c; d, e, f]` is syntax for `Matrix.of ![![a, b, c], ![d, e, f]]`. -/ syntax (name := matrixNotation) "!![" ppRealGroup(sepBy1(ppGroup(term,+,?), ";", "; ", allowTrailingSep)) "]" : term @[inherit_doc matrixNotation] syntax (name := matrixNotationRx0) "!![" ";"+ "]" : term @[inherit_doc matrixNotation] syntax (name := matrixNotation0xC) "!![" ","* "]" : term macro_rules | `(!![$[$[$rows],*];*]) => do let m := rows.size let n := if h : 0 < m then rows[0].size else 0 let rowVecs ← rows.mapM fun row : Array Term => do unless row.size = n do Macro.throwErrorAt (mkNullNode row) s!"\ Rows must be of equal length; this row has {row.size} items, \ the previous rows have {n}" `(![$row,*]) `(@Matrix.of (Fin $(quote m)) (Fin $(quote n)) _ ![$rowVecs,*]) | `(!![$[;%$semicolons]*]) => do let emptyVec ← `(![]) let emptyVecs := semicolons.map (fun _ => emptyVec) `(@Matrix.of (Fin $(quote semicolons.size)) (Fin 0) _ ![$emptyVecs,*]) | `(!![$[,%$commas]*]) => `(@Matrix.of (Fin 0) (Fin $(quote commas.size)) _ ![]) /-- Delaborator for the `!![]` notation. -/ @[app_delab DFunLike.coe] def delabMatrixNotation : Delab := whenNotPPOption getPPExplicit <| whenPPOption getPPNotation <| withOverApp 6 do let mkApp3 (.const ``Matrix.of _) (.app (.const ``Fin _) em) (.app (.const ``Fin _) en) _ := (← getExpr).appFn!.appArg! | failure let some m ← withNatValue em (pure ∘ some) | failure let some n ← withNatValue en (pure ∘ some) | failure withAppArg do if m = 0 then guard <| (← getExpr).isAppOfArity ``vecEmpty 1 let commas := .replicate n (mkAtom ",") `(!![$[,%$commas]*]) else if n = 0 then let `(![$[![]%$evecs],*]) ← delab | failure `(!![$[;%$evecs]*]) else let `(![$[![$[$melems],*]],*]) ← delab | failure `(!![$[$[$melems],*];*]) end Parser variable (a b : ℕ) /-- Use `![...]` notation for displaying a `Fin`-indexed matrix, for example: ``` #eval !![1, 2; 3, 4] + !![3, 4; 5, 6] -- !![4, 6; 8, 10] ``` -/ instance repr [Repr α] : Repr (Matrix (Fin m) (Fin n) α) where reprPrec f _p := (Std.Format.bracket "!![" · "]") <| (Std.Format.joinSep · (";" ++ Std.Format.line)) <| (List.finRange m).map fun i => Std.Format.fill <| -- wrap line in a single place rather than all at once (Std.Format.joinSep · ("," ++ Std.Format.line)) <| (List.finRange n).map fun j => _root_.repr (f i j) @[simp] theorem cons_val' (v : n' → α) (B : Fin m → n' → α) (i j) : vecCons v B i j = vecCons (v j) (fun i => B i j) i := by refine Fin.cases ?_ ?_ i <;> simp @[simp] theorem head_val' (B : Fin m.succ → n' → α) (j : n') : (vecHead fun i => B i j) = vecHead B j := rfl @[simp] theorem tail_val' (B : Fin m.succ → n' → α) (j : n') : (vecTail fun i => B i j) = fun i => vecTail B i j := rfl section DotProduct variable [AddCommMonoid α] [Mul α] @[simp] theorem dotProduct_empty (v w : Fin 0 → α) : dotProduct v w = 0 := Finset.sum_empty @[simp] theorem cons_dotProduct (x : α) (v : Fin n → α) (w : Fin n.succ → α) : dotProduct (vecCons x v) w = x * vecHead w + dotProduct v (vecTail w) := by simp [dotProduct, Fin.sum_univ_succ, vecHead, vecTail] @[simp] theorem dotProduct_cons (v : Fin n.succ → α) (x : α) (w : Fin n → α) : dotProduct v (vecCons x w) = vecHead v * x + dotProduct (vecTail v) w := by simp [dotProduct, Fin.sum_univ_succ, vecHead, vecTail] theorem cons_dotProduct_cons (x : α) (v : Fin n → α) (y : α) (w : Fin n → α) : dotProduct (vecCons x v) (vecCons y w) = x * y + dotProduct v w := by simp end DotProduct section ColRow variable {ι : Type*} @[simp] theorem replicateCol_empty (v : Fin 0 → α) : replicateCol ι v = vecEmpty := empty_eq _ @[deprecated (since := "2025-03-20")] alias col_empty := replicateCol_empty @[simp] theorem replicateCol_cons (x : α) (u : Fin m → α) : replicateCol ι (vecCons x u) = of (vecCons (fun _ => x) (replicateCol ι u)) := by ext i j refine Fin.cases ?_ ?_ i <;> simp [vecHead, vecTail] @[deprecated (since := "2025-03-20")] alias col_cons := replicateCol_cons @[simp] theorem replicateRow_empty : replicateRow ι (vecEmpty : Fin 0 → α) = of fun _ => vecEmpty := rfl @[deprecated (since := "2025-03-20")] alias row_empty := replicateRow_empty @[simp] theorem replicateRow_cons (x : α) (u : Fin m → α) : replicateRow ι (vecCons x u) = of fun _ => vecCons x u := rfl @[deprecated (since := "2025-03-20")] alias row_cons := replicateRow_cons end ColRow section Transpose @[simp] theorem transpose_empty_rows (A : Matrix m' (Fin 0) α) : Aᵀ = of ![] := empty_eq _ @[simp] theorem transpose_empty_cols (A : Matrix (Fin 0) m' α) : Aᵀ = of fun _ => ![] := funext fun _ => empty_eq _ @[simp] theorem cons_transpose (v : n' → α) (A : Matrix (Fin m) n' α) : (of (vecCons v A))ᵀ = of fun i => vecCons (v i) (Aᵀ i) := by ext i j refine Fin.cases ?_ ?_ j <;> simp @[simp] theorem head_transpose (A : Matrix m' (Fin n.succ) α) : vecHead (of.symm Aᵀ) = vecHead ∘ of.symm A := rfl @[simp] theorem tail_transpose (A : Matrix m' (Fin n.succ) α) : vecTail (of.symm Aᵀ) = (vecTail ∘ A)ᵀ := by ext i j rfl end Transpose section Mul variable [NonUnitalNonAssocSemiring α] @[simp] theorem empty_mul [Fintype n'] (A : Matrix (Fin 0) n' α) (B : Matrix n' o' α) : A * B = of ![] := empty_eq _ @[simp] theorem empty_mul_empty (A : Matrix m' (Fin 0) α) (B : Matrix (Fin 0) o' α) : A * B = 0 := rfl @[simp] theorem mul_empty [Fintype n'] (A : Matrix m' n' α) (B : Matrix n' (Fin 0) α) : A * B = of fun _ => ![] := funext fun _ => empty_eq _ theorem mul_val_succ [Fintype n'] (A : Matrix (Fin m.succ) n' α) (B : Matrix n' o' α) (i : Fin m) (j : o') : (A * B) i.succ j = (of (vecTail (of.symm A)) * B) i j := rfl @[simp] theorem cons_mul [Fintype n'] (v : n' → α) (A : Fin m → n' → α) (B : Matrix n' o' α) : of (vecCons v A) * B = of (vecCons (v ᵥ* B) (of.symm (of A * B))) := by ext i j refine Fin.cases ?_ ?_ i · rfl simp [mul_val_succ] end Mul section VecMul variable [NonUnitalNonAssocSemiring α] @[simp] theorem empty_vecMul (v : Fin 0 → α) (B : Matrix (Fin 0) o' α) : v ᵥ* B = 0 := rfl @[simp] theorem vecMul_empty [Fintype n'] (v : n' → α) (B : Matrix n' (Fin 0) α) : v ᵥ* B = ![] := empty_eq _ @[simp] theorem cons_vecMul (x : α) (v : Fin n → α) (B : Fin n.succ → o' → α) : vecCons x v ᵥ* of B = x • vecHead B + v ᵥ* of (vecTail B) := by ext i simp [vecMul] @[simp] theorem vecMul_cons (v : Fin n.succ → α) (w : o' → α) (B : Fin n → o' → α) : v ᵥ* of (vecCons w B) = vecHead v • w + vecTail v ᵥ* of B := by ext i simp [vecMul] theorem cons_vecMul_cons (x : α) (v : Fin n → α) (w : o' → α) (B : Fin n → o' → α) : vecCons x v ᵥ* of (vecCons w B) = x • w + v ᵥ* of B := by simp end VecMul section MulVec variable [NonUnitalNonAssocSemiring α] @[simp] theorem empty_mulVec [Fintype n'] (A : Matrix (Fin 0) n' α) (v : n' → α) : A *ᵥ v = ![] := empty_eq _ @[simp] theorem mulVec_empty (A : Matrix m' (Fin 0) α) (v : Fin 0 → α) : A *ᵥ v = 0 := rfl @[simp] theorem cons_mulVec [Fintype n'] (v : n' → α) (A : Fin m → n' → α) (w : n' → α) : (of <| vecCons v A) *ᵥ w = vecCons (dotProduct v w) (of A *ᵥ w) := by ext i refine Fin.cases ?_ ?_ i <;> simp [mulVec] @[simp] theorem mulVec_cons {α} [NonUnitalCommSemiring α] (A : m' → Fin n.succ → α) (x : α) (v : Fin n → α) : (of A) *ᵥ (vecCons x v) = x • vecHead ∘ A + (of (vecTail ∘ A)) *ᵥ v := by ext i simp [mulVec, mul_comm] end MulVec section VecMulVec variable [NonUnitalNonAssocSemiring α] @[simp] theorem empty_vecMulVec (v : Fin 0 → α) (w : n' → α) : vecMulVec v w = ![] := empty_eq _ @[simp] theorem vecMulVec_empty (v : m' → α) (w : Fin 0 → α) : vecMulVec v w = of fun _ => ![] := funext fun _ => empty_eq _ @[simp] theorem cons_vecMulVec (x : α) (v : Fin m → α) (w : n' → α) : vecMulVec (vecCons x v) w = vecCons (x • w) (vecMulVec v w) := by ext i refine Fin.cases ?_ ?_ i <;> simp [vecMulVec] @[simp] theorem vecMulVec_cons (v : m' → α) (x : α) (w : Fin n → α) : vecMulVec v (vecCons x w) = of fun i => v i • vecCons x w := rfl end VecMulVec section SMul variable [NonUnitalNonAssocSemiring α] theorem smul_mat_empty {m' : Type*} (x : α) (A : Fin 0 → m' → α) : x • A = ![] := empty_eq _ theorem smul_mat_cons (x : α) (v : n' → α) (A : Fin m → n' → α) : x • vecCons v A = vecCons (x • v) (x • A) := by ext i refine Fin.cases ?_ ?_ i <;> simp end SMul section Submatrix @[simp] theorem submatrix_empty (A : Matrix m' n' α) (row : Fin 0 → m') (col : o' → n') : submatrix A row col = ![] := empty_eq _ @[simp] theorem submatrix_cons_row (A : Matrix m' n' α) (i : m') (row : Fin m → m') (col : o' → n') : submatrix A (vecCons i row) col = vecCons (fun j => A i (col j)) (submatrix A row col) := by ext i j refine Fin.cases ?_ ?_ i <;> simp [submatrix] /-- Updating a row then removing it is the same as removing it. -/ @[simp] theorem submatrix_updateRow_succAbove (A : Matrix (Fin m.succ) n' α) (v : n' → α) (f : o' → n') (i : Fin m.succ) : (A.updateRow i v).submatrix i.succAbove f = A.submatrix i.succAbove f := ext fun r s => (congr_fun (updateRow_ne (Fin.succAbove_ne i r) : _ = A _) (f s) :) /-- Updating a column then removing it is the same as removing it. -/ @[simp] theorem submatrix_updateCol_succAbove (A : Matrix m' (Fin n.succ) α) (v : m' → α) (f : o' → m') (i : Fin n.succ) : (A.updateCol i v).submatrix f i.succAbove = A.submatrix f i.succAbove := ext fun _r s => updateCol_ne (Fin.succAbove_ne i s) @[deprecated (since := "2024-12-11")] alias submatrix_updateColumn_succAbove := submatrix_updateCol_succAbove end Submatrix section Vec2AndVec3 section One variable [Zero α] [One α] theorem one_fin_two : (1 : Matrix (Fin 2) (Fin 2) α) = !![1, 0; 0, 1] := by ext i j fin_cases i <;> fin_cases j <;> rfl theorem one_fin_three : (1 : Matrix (Fin 3) (Fin 3) α) = !![1, 0, 0; 0, 1, 0; 0, 0, 1] := by ext i j fin_cases i <;> fin_cases j <;> rfl end One section AddMonoidWithOne variable [AddMonoidWithOne α] theorem natCast_fin_two (n : ℕ) : (n : Matrix (Fin 2) (Fin 2) α) = !![↑n, 0; 0, ↑n] := by ext i j fin_cases i <;> fin_cases j <;> rfl theorem natCast_fin_three (n : ℕ) : (n : Matrix (Fin 3) (Fin 3) α) = !![↑n, 0, 0; 0, ↑n, 0; 0, 0, ↑n] := by ext i j fin_cases i <;> fin_cases j <;> rfl theorem ofNat_fin_two (n : ℕ) [n.AtLeastTwo] : (ofNat(n) : Matrix (Fin 2) (Fin 2) α) = !![ofNat(n), 0; 0, ofNat(n)] := natCast_fin_two _ theorem ofNat_fin_three (n : ℕ) [n.AtLeastTwo] : (ofNat(n) : Matrix (Fin 3) (Fin 3) α) = !![ofNat(n), 0, 0; 0, ofNat(n), 0; 0, 0, ofNat(n)] := natCast_fin_three _ end AddMonoidWithOne theorem eta_fin_two (A : Matrix (Fin 2) (Fin 2) α) : A = !![A 0 0, A 0 1; A 1 0, A 1 1] := by ext i j fin_cases i <;> fin_cases j <;> rfl theorem eta_fin_three (A : Matrix (Fin 3) (Fin 3) α) : A = !![A 0 0, A 0 1, A 0 2; A 1 0, A 1 1, A 1 2; A 2 0, A 2 1, A 2 2] := by ext i j fin_cases i <;> fin_cases j <;> rfl theorem mul_fin_two [AddCommMonoid α] [Mul α] (a₁₁ a₁₂ a₂₁ a₂₂ b₁₁ b₁₂ b₂₁ b₂₂ : α) : !![a₁₁, a₁₂; a₂₁, a₂₂] * !![b₁₁, b₁₂; b₂₁, b₂₂] = !![a₁₁ * b₁₁ + a₁₂ * b₂₁, a₁₁ * b₁₂ + a₁₂ * b₂₂; a₂₁ * b₁₁ + a₂₂ * b₂₁, a₂₁ * b₁₂ + a₂₂ * b₂₂] := by ext i j fin_cases i <;> fin_cases j <;> simp [Matrix.mul_apply, dotProduct, Fin.sum_univ_succ] theorem mul_fin_three [AddCommMonoid α] [Mul α] (a₁₁ a₁₂ a₁₃ a₂₁ a₂₂ a₂₃ a₃₁ a₃₂ a₃₃ b₁₁ b₁₂ b₁₃ b₂₁ b₂₂ b₂₃ b₃₁ b₃₂ b₃₃ : α) : !![a₁₁, a₁₂, a₁₃; a₂₁, a₂₂, a₂₃; a₃₁, a₃₂, a₃₃] * !![b₁₁, b₁₂, b₁₃; b₂₁, b₂₂, b₂₃; b₃₁, b₃₂, b₃₃] = !![a₁₁*b₁₁ + a₁₂*b₂₁ + a₁₃*b₃₁, a₁₁*b₁₂ + a₁₂*b₂₂ + a₁₃*b₃₂, a₁₁*b₁₃ + a₁₂*b₂₃ + a₁₃*b₃₃; a₂₁*b₁₁ + a₂₂*b₂₁ + a₂₃*b₃₁, a₂₁*b₁₂ + a₂₂*b₂₂ + a₂₃*b₃₂, a₂₁*b₁₃ + a₂₂*b₂₃ + a₂₃*b₃₃; a₃₁*b₁₁ + a₃₂*b₂₁ + a₃₃*b₃₁, a₃₁*b₁₂ + a₃₂*b₂₂ + a₃₃*b₃₂, a₃₁*b₁₃ + a₃₂*b₂₃ + a₃₃*b₃₃] := by ext i j fin_cases i <;> fin_cases j <;> simp [Matrix.mul_apply, dotProduct, Fin.sum_univ_succ, ← add_assoc] theorem vec2_eq {a₀ a₁ b₀ b₁ : α} (h₀ : a₀ = b₀) (h₁ : a₁ = b₁) : ![a₀, a₁] = ![b₀, b₁] := by subst_vars rfl theorem vec3_eq {a₀ a₁ a₂ b₀ b₁ b₂ : α} (h₀ : a₀ = b₀) (h₁ : a₁ = b₁) (h₂ : a₂ = b₂) : ![a₀, a₁, a₂] = ![b₀, b₁, b₂] := by subst_vars rfl theorem vec2_add [Add α] (a₀ a₁ b₀ b₁ : α) : ![a₀, a₁] + ![b₀, b₁] = ![a₀ + b₀, a₁ + b₁] := by rw [cons_add_cons, cons_add_cons, empty_add_empty] theorem vec3_add [Add α] (a₀ a₁ a₂ b₀ b₁ b₂ : α) : ![a₀, a₁, a₂] + ![b₀, b₁, b₂] = ![a₀ + b₀, a₁ + b₁, a₂ + b₂] := by rw [cons_add_cons, cons_add_cons, cons_add_cons, empty_add_empty] theorem smul_vec2 {R : Type*} [SMul R α] (x : R) (a₀ a₁ : α) : x • ![a₀, a₁] = ![x • a₀, x • a₁] := by rw [smul_cons, smul_cons, smul_empty] theorem smul_vec3 {R : Type*} [SMul R α] (x : R) (a₀ a₁ a₂ : α) : x • ![a₀, a₁, a₂] = ![x • a₀, x • a₁, x • a₂] := by rw [smul_cons, smul_cons, smul_cons, smul_empty]
variable [AddCommMonoid α] [Mul α] theorem vec2_dotProduct' {a₀ a₁ b₀ b₁ : α} : ![a₀, a₁] ⬝ᵥ ![b₀, b₁] = a₀ * b₀ + a₁ * b₁ := by
Mathlib/Data/Matrix/Notation.lean
504
507
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathlib.Algebra.Order.Ring.Nat import Mathlib.Logic.Encodable.Pi import Mathlib.Logic.Function.Iterate /-! # The primitive recursive functions The primitive recursive functions are the least collection of functions `ℕ → ℕ` which are closed under projections (using the `pair` pairing function), composition, zero, successor, and primitive recursion (i.e. `Nat.rec` where the motive is `C n := ℕ`). We can extend this definition to a large class of basic types by using canonical encodings of types as natural numbers (Gödel numbering), which we implement through the type class `Encodable`. (More precisely, we need that the composition of encode with decode yields a primitive recursive function, so we have the `Primcodable` type class for this.) In the above, the pairing function is primitive recursive by definition. This deviates from the textbook definition of primitive recursive functions, which instead work with *`n`-ary* functions. We formalize the textbook definition in `Nat.Primrec'`. `Nat.Primrec'.prim_iff` then proves it is equivalent to our chosen formulation. For more discussionn of this and other design choices in this formalization, see [carneiro2019]. ## Main definitions - `Nat.Primrec f`: `f` is primitive recursive, for functions `f : ℕ → ℕ` - `Primrec f`: `f` is primitive recursive, for functions between `Primcodable` types - `Primcodable α`: well-behaved encoding of `α` into `ℕ`, i.e. one such that roundtripping through the encoding functions adds no computational power ## References * [Mario Carneiro, *Formalizing computability theory via partial recursive functions*][carneiro2019] -/ open List (Vector) open Denumerable Encodable Function namespace Nat /-- Calls the given function on a pair of entries `n`, encoded via the pairing function. -/ @[simp, reducible] def unpaired {α} (f : ℕ → ℕ → α) (n : ℕ) : α := f n.unpair.1 n.unpair.2 /-- The primitive recursive functions `ℕ → ℕ`. -/ protected inductive Primrec : (ℕ → ℕ) → Prop | zero : Nat.Primrec fun _ => 0 | protected succ : Nat.Primrec succ | left : Nat.Primrec fun n => n.unpair.1 | right : Nat.Primrec fun n => n.unpair.2 | pair {f g} : Nat.Primrec f → Nat.Primrec g → Nat.Primrec fun n => pair (f n) (g n) | comp {f g} : Nat.Primrec f → Nat.Primrec g → Nat.Primrec fun n => f (g n) | prec {f g} : Nat.Primrec f → Nat.Primrec g → Nat.Primrec (unpaired fun z n => n.rec (f z) fun y IH => g <| pair z <| pair y IH) namespace Primrec theorem of_eq {f g : ℕ → ℕ} (hf : Nat.Primrec f) (H : ∀ n, f n = g n) : Nat.Primrec g := (funext H : f = g) ▸ hf theorem const : ∀ n : ℕ, Nat.Primrec fun _ => n | 0 => zero | n + 1 => Primrec.succ.comp (const n) protected theorem id : Nat.Primrec id := (left.pair right).of_eq fun n => by simp theorem prec1 {f} (m : ℕ) (hf : Nat.Primrec f) : Nat.Primrec fun n => n.rec m fun y IH => f <| Nat.pair y IH := ((prec (const m) (hf.comp right)).comp (zero.pair Primrec.id)).of_eq fun n => by simp theorem casesOn1 {f} (m : ℕ) (hf : Nat.Primrec f) : Nat.Primrec (Nat.casesOn · m f) := (prec1 m (hf.comp left)).of_eq <| by simp -- Porting note: `Nat.Primrec.casesOn` is already declared as a recursor. theorem casesOn' {f g} (hf : Nat.Primrec f) (hg : Nat.Primrec g) : Nat.Primrec (unpaired fun z n => n.casesOn (f z) fun y => g <| Nat.pair z y) := (prec hf (hg.comp (pair left (left.comp right)))).of_eq fun n => by simp protected theorem swap : Nat.Primrec (unpaired (swap Nat.pair)) := (pair right left).of_eq fun n => by simp theorem swap' {f} (hf : Nat.Primrec (unpaired f)) : Nat.Primrec (unpaired (swap f)) := (hf.comp .swap).of_eq fun n => by simp theorem pred : Nat.Primrec pred := (casesOn1 0 Primrec.id).of_eq fun n => by cases n <;> simp [*] theorem add : Nat.Primrec (unpaired (· + ·)) := (prec .id ((Primrec.succ.comp right).comp right)).of_eq fun p => by simp; induction p.unpair.2 <;> simp [*, Nat.add_assoc] theorem sub : Nat.Primrec (unpaired (· - ·)) := (prec .id ((pred.comp right).comp right)).of_eq fun p => by simp; induction p.unpair.2 <;> simp [*, Nat.sub_add_eq] theorem mul : Nat.Primrec (unpaired (· * ·)) := (prec zero (add.comp (pair left (right.comp right)))).of_eq fun p => by simp; induction p.unpair.2 <;> simp [*, mul_succ, add_comm _ (unpair p).fst] theorem pow : Nat.Primrec (unpaired (· ^ ·)) := (prec (const 1) (mul.comp (pair (right.comp right) left))).of_eq fun p => by simp; induction p.unpair.2 <;> simp [*, Nat.pow_succ] end Primrec end Nat /-- A `Primcodable` type is, essentially, an `Encodable` type for which the encode/decode functions are primitive recursive. However, such a definition is circular. Instead, we ask that the composition of `decode : ℕ → Option α` with `encode : Option α → ℕ` is primitive recursive. Said composition is the identity function, restricted to the image of `encode`. Thus, in a way, the added requirement ensures that no predicates can be smuggled in through a cunning choice of the subset of `ℕ` into which the type is encoded. -/ class Primcodable (α : Type*) extends Encodable α where -- Porting note: was `prim [] `. -- This means that `prim` does not take the type explicitly in Lean 4 prim : Nat.Primrec fun n => Encodable.encode (decode n) namespace Primcodable open Nat.Primrec instance (priority := 10) ofDenumerable (α) [Denumerable α] : Primcodable α := ⟨Nat.Primrec.succ.of_eq <| by simp⟩ /-- Builds a `Primcodable` instance from an equivalence to a `Primcodable` type. -/ def ofEquiv (α) {β} [Primcodable α] (e : β ≃ α) : Primcodable β := { __ := Encodable.ofEquiv α e prim := (@Primcodable.prim α _).of_eq fun n => by rw [decode_ofEquiv] cases (@decode α _ n) <;> simp [encode_ofEquiv] } instance empty : Primcodable Empty := ⟨zero⟩ instance unit : Primcodable PUnit := ⟨(casesOn1 1 zero).of_eq fun n => by cases n <;> simp⟩ instance option {α : Type*} [h : Primcodable α] : Primcodable (Option α) := ⟨(casesOn1 1 ((casesOn1 0 (.comp .succ .succ)).comp (@Primcodable.prim α _))).of_eq fun n => by cases n with | zero => rfl | succ n => rw [decode_option_succ] cases H : @decode α _ n <;> simp [H]⟩ instance bool : Primcodable Bool := ⟨(casesOn1 1 (casesOn1 2 zero)).of_eq fun n => match n with | 0 => rfl | 1 => rfl | (n + 2) => by rw [decode_ge_two] <;> simp⟩ end Primcodable /-- `Primrec f` means `f` is primitive recursive (after encoding its input and output as natural numbers). -/ def Primrec {α β} [Primcodable α] [Primcodable β] (f : α → β) : Prop := Nat.Primrec fun n => encode ((@decode α _ n).map f) namespace Primrec variable {α : Type*} {β : Type*} {σ : Type*} variable [Primcodable α] [Primcodable β] [Primcodable σ] open Nat.Primrec protected theorem encode : Primrec (@encode α _) := (@Primcodable.prim α _).of_eq fun n => by cases @decode α _ n <;> rfl protected theorem decode : Primrec (@decode α _) := Nat.Primrec.succ.comp (@Primcodable.prim α _) theorem dom_denumerable {α β} [Denumerable α] [Primcodable β] {f : α → β} : Primrec f ↔ Nat.Primrec fun n => encode (f (ofNat α n)) := ⟨fun h => (pred.comp h).of_eq fun n => by simp, fun h => (Nat.Primrec.succ.comp h).of_eq fun n => by simp⟩ theorem nat_iff {f : ℕ → ℕ} : Primrec f ↔ Nat.Primrec f := dom_denumerable theorem encdec : Primrec fun n => encode (@decode α _ n) := nat_iff.2 Primcodable.prim theorem option_some : Primrec (@some α) := ((casesOn1 0 (Nat.Primrec.succ.comp .succ)).comp (@Primcodable.prim α _)).of_eq fun n => by cases @decode α _ n <;> simp theorem of_eq {f g : α → σ} (hf : Primrec f) (H : ∀ n, f n = g n) : Primrec g := (funext H : f = g) ▸ hf theorem const (x : σ) : Primrec fun _ : α => x := ((casesOn1 0 (.const (encode x).succ)).comp (@Primcodable.prim α _)).of_eq fun n => by cases @decode α _ n <;> rfl protected theorem id : Primrec (@id α) := (@Primcodable.prim α).of_eq <| by simp theorem comp {f : β → σ} {g : α → β} (hf : Primrec f) (hg : Primrec g) : Primrec fun a => f (g a) := ((casesOn1 0 (.comp hf (pred.comp hg))).comp (@Primcodable.prim α _)).of_eq fun n => by cases @decode α _ n <;> simp [encodek] theorem succ : Primrec Nat.succ := nat_iff.2 Nat.Primrec.succ theorem pred : Primrec Nat.pred := nat_iff.2 Nat.Primrec.pred theorem encode_iff {f : α → σ} : (Primrec fun a => encode (f a)) ↔ Primrec f := ⟨fun h => Nat.Primrec.of_eq h fun n => by cases @decode α _ n <;> rfl, Primrec.encode.comp⟩ theorem ofNat_iff {α β} [Denumerable α] [Primcodable β] {f : α → β} : Primrec f ↔ Primrec fun n => f (ofNat α n) := dom_denumerable.trans <| nat_iff.symm.trans encode_iff protected theorem ofNat (α) [Denumerable α] : Primrec (ofNat α) := ofNat_iff.1 Primrec.id theorem option_some_iff {f : α → σ} : (Primrec fun a => some (f a)) ↔ Primrec f := ⟨fun h => encode_iff.1 <| pred.comp <| encode_iff.2 h, option_some.comp⟩ theorem of_equiv {β} {e : β ≃ α} : haveI := Primcodable.ofEquiv α e Primrec e := letI : Primcodable β := Primcodable.ofEquiv α e encode_iff.1 Primrec.encode theorem of_equiv_symm {β} {e : β ≃ α} : haveI := Primcodable.ofEquiv α e Primrec e.symm := letI := Primcodable.ofEquiv α e encode_iff.1 (show Primrec fun a => encode (e (e.symm a)) by simp [Primrec.encode]) theorem of_equiv_iff {β} (e : β ≃ α) {f : σ → β} : haveI := Primcodable.ofEquiv α e (Primrec fun a => e (f a)) ↔ Primrec f := letI := Primcodable.ofEquiv α e ⟨fun h => (of_equiv_symm.comp h).of_eq fun a => by simp, of_equiv.comp⟩ theorem of_equiv_symm_iff {β} (e : β ≃ α) {f : σ → α} : haveI := Primcodable.ofEquiv α e (Primrec fun a => e.symm (f a)) ↔ Primrec f := letI := Primcodable.ofEquiv α e ⟨fun h => (of_equiv.comp h).of_eq fun a => by simp, of_equiv_symm.comp⟩ end Primrec namespace Primcodable open Nat.Primrec instance prod {α β} [Primcodable α] [Primcodable β] : Primcodable (α × β) := ⟨((casesOn' zero ((casesOn' zero .succ).comp (pair right ((@Primcodable.prim β).comp left)))).comp (pair right ((@Primcodable.prim α).comp left))).of_eq fun n => by simp only [Nat.unpaired, Nat.unpair_pair, decode_prod_val] cases @decode α _ n.unpair.1; · simp cases @decode β _ n.unpair.2 <;> simp⟩ end Primcodable namespace Primrec variable {α : Type*} [Primcodable α] open Nat.Primrec theorem fst {α β} [Primcodable α] [Primcodable β] : Primrec (@Prod.fst α β) := ((casesOn' zero ((casesOn' zero (Nat.Primrec.succ.comp left)).comp (pair right ((@Primcodable.prim β).comp left)))).comp (pair right ((@Primcodable.prim α).comp left))).of_eq fun n => by simp only [Nat.unpaired, Nat.unpair_pair, decode_prod_val] cases @decode α _ n.unpair.1 <;> simp cases @decode β _ n.unpair.2 <;> simp theorem snd {α β} [Primcodable α] [Primcodable β] : Primrec (@Prod.snd α β) := ((casesOn' zero ((casesOn' zero (Nat.Primrec.succ.comp right)).comp (pair right ((@Primcodable.prim β).comp left)))).comp (pair right ((@Primcodable.prim α).comp left))).of_eq fun n => by simp only [Nat.unpaired, Nat.unpair_pair, decode_prod_val] cases @decode α _ n.unpair.1 <;> simp cases @decode β _ n.unpair.2 <;> simp theorem pair {α β γ} [Primcodable α] [Primcodable β] [Primcodable γ] {f : α → β} {g : α → γ} (hf : Primrec f) (hg : Primrec g) : Primrec fun a => (f a, g a) := ((casesOn1 0 (Nat.Primrec.succ.comp <| .pair (Nat.Primrec.pred.comp hf) (Nat.Primrec.pred.comp hg))).comp (@Primcodable.prim α _)).of_eq fun n => by cases @decode α _ n <;> simp [encodek] theorem unpair : Primrec Nat.unpair := (pair (nat_iff.2 .left) (nat_iff.2 .right)).of_eq fun n => by simp theorem list_getElem?₁ : ∀ l : List α, Primrec (l[·]? : ℕ → Option α) | [] => dom_denumerable.2 zero | a :: l => dom_denumerable.2 <| (casesOn1 (encode a).succ <| dom_denumerable.1 <| list_getElem?₁ l).of_eq fun n => by cases n <;> simp @[deprecated (since := "2025-02-14")] alias list_get?₁ := list_getElem?₁ end Primrec /-- `Primrec₂ f` means `f` is a binary primitive recursive function. This is technically unnecessary since we can always curry all the arguments together, but there are enough natural two-arg functions that it is convenient to express this directly. -/ def Primrec₂ {α β σ} [Primcodable α] [Primcodable β] [Primcodable σ] (f : α → β → σ) := Primrec fun p : α × β => f p.1 p.2 /-- `PrimrecPred p` means `p : α → Prop` is a (decidable) primitive recursive predicate, which is to say that `decide ∘ p : α → Bool` is primitive recursive. -/ def PrimrecPred {α} [Primcodable α] (p : α → Prop) [DecidablePred p] := Primrec fun a => decide (p a) /-- `PrimrecRel p` means `p : α → β → Prop` is a (decidable) primitive recursive relation, which is to say that `decide ∘ p : α → β → Bool` is primitive recursive. -/ def PrimrecRel {α β} [Primcodable α] [Primcodable β] (s : α → β → Prop) [∀ a b, Decidable (s a b)] := Primrec₂ fun a b => decide (s a b) namespace Primrec₂ variable {α : Type*} {β : Type*} {σ : Type*} variable [Primcodable α] [Primcodable β] [Primcodable σ] theorem mk {f : α → β → σ} (hf : Primrec fun p : α × β => f p.1 p.2) : Primrec₂ f := hf theorem of_eq {f g : α → β → σ} (hg : Primrec₂ f) (H : ∀ a b, f a b = g a b) : Primrec₂ g := (by funext a b; apply H : f = g) ▸ hg theorem const (x : σ) : Primrec₂ fun (_ : α) (_ : β) => x := Primrec.const _ protected theorem pair : Primrec₂ (@Prod.mk α β) := Primrec.pair .fst .snd theorem left : Primrec₂ fun (a : α) (_ : β) => a := .fst theorem right : Primrec₂ fun (_ : α) (b : β) => b := .snd theorem natPair : Primrec₂ Nat.pair := by simp [Primrec₂, Primrec]; constructor theorem unpaired {f : ℕ → ℕ → α} : Primrec (Nat.unpaired f) ↔ Primrec₂ f := ⟨fun h => by simpa using h.comp natPair, fun h => h.comp Primrec.unpair⟩ theorem unpaired' {f : ℕ → ℕ → ℕ} : Nat.Primrec (Nat.unpaired f) ↔ Primrec₂ f := Primrec.nat_iff.symm.trans unpaired theorem encode_iff {f : α → β → σ} : (Primrec₂ fun a b => encode (f a b)) ↔ Primrec₂ f := Primrec.encode_iff theorem option_some_iff {f : α → β → σ} : (Primrec₂ fun a b => some (f a b)) ↔ Primrec₂ f := Primrec.option_some_iff theorem ofNat_iff {α β σ} [Denumerable α] [Denumerable β] [Primcodable σ] {f : α → β → σ} : Primrec₂ f ↔ Primrec₂ fun m n : ℕ => f (ofNat α m) (ofNat β n) := (Primrec.ofNat_iff.trans <| by simp).trans unpaired theorem uncurry {f : α → β → σ} : Primrec (Function.uncurry f) ↔ Primrec₂ f := by rw [show Function.uncurry f = fun p : α × β => f p.1 p.2 from funext fun ⟨a, b⟩ => rfl]; rfl theorem curry {f : α × β → σ} : Primrec₂ (Function.curry f) ↔ Primrec f := by rw [← uncurry, Function.uncurry_curry] end Primrec₂ section Comp variable {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {σ : Type*} variable [Primcodable α] [Primcodable β] [Primcodable γ] [Primcodable δ] [Primcodable σ] theorem Primrec.comp₂ {f : γ → σ} {g : α → β → γ} (hf : Primrec f) (hg : Primrec₂ g) : Primrec₂ fun a b => f (g a b) := hf.comp hg theorem Primrec₂.comp {f : β → γ → σ} {g : α → β} {h : α → γ} (hf : Primrec₂ f) (hg : Primrec g) (hh : Primrec h) : Primrec fun a => f (g a) (h a) := Primrec.comp hf (hg.pair hh) theorem Primrec₂.comp₂ {f : γ → δ → σ} {g : α → β → γ} {h : α → β → δ} (hf : Primrec₂ f) (hg : Primrec₂ g) (hh : Primrec₂ h) : Primrec₂ fun a b => f (g a b) (h a b) := hf.comp hg hh theorem PrimrecPred.comp {p : β → Prop} [DecidablePred p] {f : α → β} : PrimrecPred p → Primrec f → PrimrecPred fun a => p (f a) := Primrec.comp theorem PrimrecRel.comp {R : β → γ → Prop} [∀ a b, Decidable (R a b)] {f : α → β} {g : α → γ} : PrimrecRel R → Primrec f → Primrec g → PrimrecPred fun a => R (f a) (g a) := Primrec₂.comp theorem PrimrecRel.comp₂ {R : γ → δ → Prop} [∀ a b, Decidable (R a b)] {f : α → β → γ} {g : α → β → δ} : PrimrecRel R → Primrec₂ f → Primrec₂ g → PrimrecRel fun a b => R (f a b) (g a b) := PrimrecRel.comp end Comp theorem PrimrecPred.of_eq {α} [Primcodable α] {p q : α → Prop} [DecidablePred p] [DecidablePred q] (hp : PrimrecPred p) (H : ∀ a, p a ↔ q a) : PrimrecPred q := Primrec.of_eq hp fun a => Bool.decide_congr (H a) theorem PrimrecRel.of_eq {α β} [Primcodable α] [Primcodable β] {r s : α → β → Prop} [∀ a b, Decidable (r a b)] [∀ a b, Decidable (s a b)] (hr : PrimrecRel r) (H : ∀ a b, r a b ↔ s a b) : PrimrecRel s := Primrec₂.of_eq hr fun a b => Bool.decide_congr (H a b) namespace Primrec₂ variable {α : Type*} {β : Type*} {σ : Type*} variable [Primcodable α] [Primcodable β] [Primcodable σ] open Nat.Primrec theorem swap {f : α → β → σ} (h : Primrec₂ f) : Primrec₂ (swap f) := h.comp₂ Primrec₂.right Primrec₂.left theorem nat_iff {f : α → β → σ} : Primrec₂ f ↔ Nat.Primrec (.unpaired fun m n => encode <| (@decode α _ m).bind fun a => (@decode β _ n).map (f a)) := by have : ∀ (a : Option α) (b : Option β), Option.map (fun p : α × β => f p.1 p.2) (Option.bind a fun a : α => Option.map (Prod.mk a) b) = Option.bind a fun a => Option.map (f a) b := fun a b => by cases a <;> cases b <;> rfl simp [Primrec₂, Primrec, this] theorem nat_iff' {f : α → β → σ} : Primrec₂ f ↔ Primrec₂ fun m n : ℕ => (@decode α _ m).bind fun a => Option.map (f a) (@decode β _ n) := nat_iff.trans <| unpaired'.trans encode_iff end Primrec₂ namespace Primrec variable {α : Type*} {β : Type*} {σ : Type*} variable [Primcodable α] [Primcodable β] [Primcodable σ] theorem to₂ {f : α × β → σ} (hf : Primrec f) : Primrec₂ fun a b => f (a, b) := hf.of_eq fun _ => rfl theorem nat_rec {f : α → β} {g : α → ℕ × β → β} (hf : Primrec f) (hg : Primrec₂ g) : Primrec₂ fun a (n : ℕ) => n.rec (motive := fun _ => β) (f a) fun n IH => g a (n, IH) := Primrec₂.nat_iff.2 <| ((Nat.Primrec.casesOn' .zero <| (Nat.Primrec.prec hf <| .comp hg <| Nat.Primrec.left.pair <| (Nat.Primrec.left.comp .right).pair <| Nat.Primrec.pred.comp <| Nat.Primrec.right.comp .right).comp <| Nat.Primrec.right.pair <| Nat.Primrec.right.comp Nat.Primrec.left).comp <| Nat.Primrec.id.pair <| (@Primcodable.prim α).comp Nat.Primrec.left).of_eq fun n => by simp only [Nat.unpaired, id_eq, Nat.unpair_pair, decode_prod_val, decode_nat, Option.some_bind, Option.map_map, Option.map_some'] rcases @decode α _ n.unpair.1 with - | a; · rfl simp only [Nat.pred_eq_sub_one, encode_some, Nat.succ_eq_add_one, encodek, Option.map_some', Option.some_bind, Option.map_map] induction' n.unpair.2 with m <;> simp [encodek] simp [*, encodek] theorem nat_rec' {f : α → ℕ} {g : α → β} {h : α → ℕ × β → β} (hf : Primrec f) (hg : Primrec g) (hh : Primrec₂ h) : Primrec fun a => (f a).rec (motive := fun _ => β) (g a) fun n IH => h a (n, IH) := (nat_rec hg hh).comp .id hf theorem nat_rec₁ {f : ℕ → α → α} (a : α) (hf : Primrec₂ f) : Primrec (Nat.rec a f) := nat_rec' .id (const a) <| comp₂ hf Primrec₂.right theorem nat_casesOn' {f : α → β} {g : α → ℕ → β} (hf : Primrec f) (hg : Primrec₂ g) : Primrec₂ fun a (n : ℕ) => (n.casesOn (f a) (g a) : β) := nat_rec hf <| hg.comp₂ Primrec₂.left <| comp₂ fst Primrec₂.right theorem nat_casesOn {f : α → ℕ} {g : α → β} {h : α → ℕ → β} (hf : Primrec f) (hg : Primrec g) (hh : Primrec₂ h) : Primrec fun a => ((f a).casesOn (g a) (h a) : β) := (nat_casesOn' hg hh).comp .id hf theorem nat_casesOn₁ {f : ℕ → α} (a : α) (hf : Primrec f) : Primrec (fun (n : ℕ) => (n.casesOn a f : α)) := nat_casesOn .id (const a) (comp₂ hf .right) theorem nat_iterate {f : α → ℕ} {g : α → β} {h : α → β → β} (hf : Primrec f) (hg : Primrec g) (hh : Primrec₂ h) : Primrec fun a => (h a)^[f a] (g a) := (nat_rec' hf hg (hh.comp₂ Primrec₂.left <| snd.comp₂ Primrec₂.right)).of_eq fun a => by induction f a <;> simp [*, -Function.iterate_succ, Function.iterate_succ'] theorem option_casesOn {o : α → Option β} {f : α → σ} {g : α → β → σ} (ho : Primrec o) (hf : Primrec f) (hg : Primrec₂ g) : @Primrec _ σ _ _ fun a => Option.casesOn (o a) (f a) (g a) := encode_iff.1 <| (nat_casesOn (encode_iff.2 ho) (encode_iff.2 hf) <| pred.comp₂ <| Primrec₂.encode_iff.2 <| (Primrec₂.nat_iff'.1 hg).comp₂ ((@Primrec.encode α _).comp fst).to₂ Primrec₂.right).of_eq fun a => by rcases o a with - | b <;> simp [encodek] theorem option_bind {f : α → Option β} {g : α → β → Option σ} (hf : Primrec f) (hg : Primrec₂ g) : Primrec fun a => (f a).bind (g a) := (option_casesOn hf (const none) hg).of_eq fun a => by cases f a <;> rfl theorem option_bind₁ {f : α → Option σ} (hf : Primrec f) : Primrec fun o => Option.bind o f := option_bind .id (hf.comp snd).to₂ theorem option_map {f : α → Option β} {g : α → β → σ} (hf : Primrec f) (hg : Primrec₂ g) : Primrec fun a => (f a).map (g a) := (option_bind hf (option_some.comp₂ hg)).of_eq fun x => by cases f x <;> rfl theorem option_map₁ {f : α → σ} (hf : Primrec f) : Primrec (Option.map f) := option_map .id (hf.comp snd).to₂ theorem option_iget [Inhabited α] : Primrec (@Option.iget α _) := (option_casesOn .id (const <| @default α _) .right).of_eq fun o => by cases o <;> rfl theorem option_isSome : Primrec (@Option.isSome α) := (option_casesOn .id (const false) (const true).to₂).of_eq fun o => by cases o <;> rfl theorem option_getD : Primrec₂ (@Option.getD α) := Primrec.of_eq (option_casesOn Primrec₂.left Primrec₂.right .right) fun ⟨o, a⟩ => by cases o <;> rfl theorem bind_decode_iff {f : α → β → Option σ} : (Primrec₂ fun a n => (@decode β _ n).bind (f a)) ↔ Primrec₂ f := ⟨fun h => by simpa [encodek] using h.comp fst ((@Primrec.encode β _).comp snd), fun h => option_bind (Primrec.decode.comp snd) <| h.comp (fst.comp fst) snd⟩ theorem map_decode_iff {f : α → β → σ} : (Primrec₂ fun a n => (@decode β _ n).map (f a)) ↔ Primrec₂ f := by simp only [Option.map_eq_bind] exact bind_decode_iff.trans Primrec₂.option_some_iff theorem nat_add : Primrec₂ ((· + ·) : ℕ → ℕ → ℕ) := Primrec₂.unpaired'.1 Nat.Primrec.add theorem nat_sub : Primrec₂ ((· - ·) : ℕ → ℕ → ℕ) := Primrec₂.unpaired'.1 Nat.Primrec.sub theorem nat_mul : Primrec₂ ((· * ·) : ℕ → ℕ → ℕ) := Primrec₂.unpaired'.1 Nat.Primrec.mul theorem cond {c : α → Bool} {f : α → σ} {g : α → σ} (hc : Primrec c) (hf : Primrec f) (hg : Primrec g) : Primrec fun a => bif (c a) then (f a) else (g a) := (nat_casesOn (encode_iff.2 hc) hg (hf.comp fst).to₂).of_eq fun a => by cases c a <;> rfl theorem ite {c : α → Prop} [DecidablePred c] {f : α → σ} {g : α → σ} (hc : PrimrecPred c) (hf : Primrec f) (hg : Primrec g) : Primrec fun a => if c a then f a else g a := by simpa [Bool.cond_decide] using cond hc hf hg theorem nat_le : PrimrecRel ((· ≤ ·) : ℕ → ℕ → Prop) := (nat_casesOn nat_sub (const true) (const false).to₂).of_eq fun p => by dsimp [swap] rcases e : p.1 - p.2 with - | n · simp [Nat.sub_eq_zero_iff_le.1 e] · simp [not_le.2 (Nat.lt_of_sub_eq_succ e)] theorem nat_min : Primrec₂ (@min ℕ _) := ite nat_le fst snd theorem nat_max : Primrec₂ (@max ℕ _) := ite (nat_le.comp fst snd) snd fst theorem dom_bool (f : Bool → α) : Primrec f := (cond .id (const (f true)) (const (f false))).of_eq fun b => by cases b <;> rfl theorem dom_bool₂ (f : Bool → Bool → α) : Primrec₂ f := (cond fst ((dom_bool (f true)).comp snd) ((dom_bool (f false)).comp snd)).of_eq fun ⟨a, b⟩ => by cases a <;> rfl protected theorem not : Primrec not := dom_bool _ protected theorem and : Primrec₂ and := dom_bool₂ _ protected theorem or : Primrec₂ or := dom_bool₂ _ theorem _root_.PrimrecPred.not {p : α → Prop} [DecidablePred p] (hp : PrimrecPred p) : PrimrecPred fun a => ¬p a := (Primrec.not.comp hp).of_eq fun n => by simp theorem _root_.PrimrecPred.and {p q : α → Prop} [DecidablePred p] [DecidablePred q] (hp : PrimrecPred p) (hq : PrimrecPred q) : PrimrecPred fun a => p a ∧ q a := (Primrec.and.comp hp hq).of_eq fun n => by simp theorem _root_.PrimrecPred.or {p q : α → Prop} [DecidablePred p] [DecidablePred q] (hp : PrimrecPred p) (hq : PrimrecPred q) : PrimrecPred fun a => p a ∨ q a := (Primrec.or.comp hp hq).of_eq fun n => by simp protected theorem beq [DecidableEq α] : Primrec₂ (@BEq.beq α _) := have : PrimrecRel fun a b : ℕ => a = b := (PrimrecPred.and nat_le nat_le.swap).of_eq fun a => by simp [le_antisymm_iff] (this.comp₂ (Primrec.encode.comp₂ Primrec₂.left) (Primrec.encode.comp₂ Primrec₂.right)).of_eq fun _ _ => encode_injective.eq_iff protected theorem eq [DecidableEq α] : PrimrecRel (@Eq α) := Primrec.beq theorem nat_lt : PrimrecRel ((· < ·) : ℕ → ℕ → Prop) := (nat_le.comp snd fst).not.of_eq fun p => by simp theorem option_guard {p : α → β → Prop} [∀ a b, Decidable (p a b)] (hp : PrimrecRel p) {f : α → β} (hf : Primrec f) : Primrec fun a => Option.guard (p a) (f a) := ite (hp.comp Primrec.id hf) (option_some_iff.2 hf) (const none) theorem option_orElse : Primrec₂ ((· <|> ·) : Option α → Option α → Option α) := (option_casesOn fst snd (fst.comp fst).to₂).of_eq fun ⟨o₁, o₂⟩ => by cases o₁ <;> cases o₂ <;> rfl protected theorem decode₂ : Primrec (decode₂ α) := option_bind .decode <| option_guard (Primrec.beq.comp₂ (by exact encode_iff.mpr snd) (by exact fst.comp fst)) snd theorem list_findIdx₁ {p : α → β → Bool} (hp : Primrec₂ p) : ∀ l : List β, Primrec fun a => l.findIdx (p a) | [] => const 0 | a :: l => (cond (hp.comp .id (const a)) (const 0) (succ.comp (list_findIdx₁ hp l))).of_eq fun n => by simp [List.findIdx_cons] theorem list_idxOf₁ [DecidableEq α] (l : List α) : Primrec fun a => l.idxOf a := list_findIdx₁ (.swap .beq) l @[deprecated (since := "2025-01-30")] alias list_indexOf₁ := list_idxOf₁ theorem dom_fintype [Finite α] (f : α → σ) : Primrec f := let ⟨l, _, m⟩ := Finite.exists_univ_list α option_some_iff.1 <| by haveI := decidableEqOfEncodable α refine ((list_getElem?₁ (l.map f)).comp (list_idxOf₁ l)).of_eq fun a => ?_ rw [List.getElem?_map, List.getElem?_idxOf (m a), Option.map_some'] -- Porting note: These are new lemmas -- I added it because it actually simplified the proofs -- and because I couldn't understand the original proof /-- A function is `PrimrecBounded` if its size is bounded by a primitive recursive function -/ def PrimrecBounded (f : α → β) : Prop := ∃ g : α → ℕ, Primrec g ∧ ∀ x, encode (f x) ≤ g x theorem nat_findGreatest {f : α → ℕ} {p : α → ℕ → Prop} [∀ x n, Decidable (p x n)] (hf : Primrec f) (hp : PrimrecRel p) : Primrec fun x => (f x).findGreatest (p x) := (nat_rec' (h := fun x nih => if p x (nih.1 + 1) then nih.1 + 1 else nih.2) hf (const 0) (ite (hp.comp fst (snd |> fst.comp |> succ.comp)) (snd |> fst.comp |> succ.comp) (snd.comp snd))).of_eq fun x => by induction f x <;> simp [Nat.findGreatest, *] /-- To show a function `f : α → ℕ` is primitive recursive, it is enough to show that the function is bounded by a primitive recursive function and that its graph is primitive recursive -/ theorem of_graph {f : α → ℕ} (h₁ : PrimrecBounded f) (h₂ : PrimrecRel fun a b => f a = b) : Primrec f := by rcases h₁ with ⟨g, pg, hg : ∀ x, f x ≤ g x⟩ refine (nat_findGreatest pg h₂).of_eq fun n => ?_ exact (Nat.findGreatest_spec (P := fun b => f n = b) (hg n) rfl).symm -- We show that division is primitive recursive by showing that the graph is theorem nat_div : Primrec₂ ((· / ·) : ℕ → ℕ → ℕ) := by refine of_graph ⟨_, fst, fun p => Nat.div_le_self _ _⟩ ?_ have : PrimrecRel fun (a : ℕ × ℕ) (b : ℕ) => (a.2 = 0 ∧ b = 0) ∨ (0 < a.2 ∧ b * a.2 ≤ a.1 ∧ a.1 < (b + 1) * a.2) := PrimrecPred.or (.and (const 0 |> Primrec.eq.comp (fst |> snd.comp)) (const 0 |> Primrec.eq.comp snd)) (.and (nat_lt.comp (const 0) (fst |> snd.comp)) <| .and (nat_le.comp (nat_mul.comp snd (fst |> snd.comp)) (fst |> fst.comp)) (nat_lt.comp (fst.comp fst) (nat_mul.comp (Primrec.succ.comp snd) (snd.comp fst)))) refine this.of_eq ?_ rintro ⟨a, k⟩ q if H : k = 0 then simp [H, eq_comm] else have : q * k ≤ a ∧ a < (q + 1) * k ↔ q = a / k := by rw [le_antisymm_iff, ← (@Nat.lt_succ _ q), Nat.le_div_iff_mul_le (Nat.pos_of_ne_zero H), Nat.div_lt_iff_lt_mul (Nat.pos_of_ne_zero H)] simpa [H, zero_lt_iff, eq_comm (b := q)] theorem nat_mod : Primrec₂ ((· % ·) : ℕ → ℕ → ℕ) := (nat_sub.comp fst (nat_mul.comp snd nat_div)).to₂.of_eq fun m n => by apply Nat.sub_eq_of_eq_add simp [add_comm (m % n), Nat.div_add_mod] theorem nat_bodd : Primrec Nat.bodd := (Primrec.beq.comp (nat_mod.comp .id (const 2)) (const 1)).of_eq fun n => by cases H : n.bodd <;> simp [Nat.mod_two_of_bodd, H] theorem nat_div2 : Primrec Nat.div2 := (nat_div.comp .id (const 2)).of_eq fun n => n.div2_val.symm theorem nat_double : Primrec (fun n : ℕ => 2 * n) := nat_mul.comp (const _) Primrec.id theorem nat_double_succ : Primrec (fun n : ℕ => 2 * n + 1) := nat_double |> Primrec.succ.comp end Primrec section variable {α : Type*} {β : Type*} {σ : Type*} variable [Primcodable α] [Primcodable β] [Primcodable σ] variable (H : Nat.Primrec fun n => Encodable.encode (@decode (List β) _ n)) open Primrec private def prim : Primcodable (List β) := ⟨H⟩ private theorem list_casesOn' {f : α → List β} {g : α → σ} {h : α → β × List β → σ} (hf : haveI := prim H; Primrec f) (hg : Primrec g) (hh : haveI := prim H; Primrec₂ h) : @Primrec _ σ _ _ fun a => List.casesOn (f a) (g a) fun b l => h a (b, l) := letI := prim H have : @Primrec _ (Option σ) _ _ fun a => (@decode (Option (β × List β)) _ (encode (f a))).map fun o => Option.casesOn o (g a) (h a) := ((@map_decode_iff _ (Option (β × List β)) _ _ _ _ _).2 <| to₂ <| option_casesOn snd (hg.comp fst) (hh.comp₂ (fst.comp₂ Primrec₂.left) Primrec₂.right)).comp .id (encode_iff.2 hf) option_some_iff.1 <| this.of_eq fun a => by rcases f a with - | ⟨b, l⟩ <;> simp [encodek] private theorem list_foldl' {f : α → List β} {g : α → σ} {h : α → σ × β → σ} (hf : haveI := prim H; Primrec f) (hg : Primrec g) (hh : haveI := prim H; Primrec₂ h) : Primrec fun a => (f a).foldl (fun s b => h a (s, b)) (g a) := by letI := prim H let G (a : α) (IH : σ × List β) : σ × List β := List.casesOn IH.2 IH fun b l => (h a (IH.1, b), l) have hG : Primrec₂ G := list_casesOn' H (snd.comp snd) snd <| to₂ <| pair (hh.comp (fst.comp fst) <| pair ((fst.comp snd).comp fst) (fst.comp snd)) (snd.comp snd) let F := fun (a : α) (n : ℕ) => (G a)^[n] (g a, f a) have hF : Primrec fun a => (F a (encode (f a))).1 := (fst.comp <| nat_iterate (encode_iff.2 hf) (pair hg hf) <| hG) suffices ∀ a n, F a n = (((f a).take n).foldl (fun s b => h a (s, b)) (g a), (f a).drop n) by refine hF.of_eq fun a => ?_ rw [this, List.take_of_length_le (length_le_encode _)] introv dsimp only [F] generalize f a = l generalize g a = x induction n generalizing l x with | zero => rfl | succ n IH => simp only [iterate_succ, comp_apply] rcases l with - | ⟨b, l⟩ <;> simp [G, IH] private theorem list_cons' : (haveI := prim H; Primrec₂ (@List.cons β)) := letI := prim H encode_iff.1 (succ.comp <| Primrec₂.natPair.comp (encode_iff.2 fst) (encode_iff.2 snd)) private theorem list_reverse' : haveI := prim H Primrec (@List.reverse β) := letI := prim H (list_foldl' H .id (const []) <| to₂ <| ((list_cons' H).comp snd fst).comp snd).of_eq (suffices ∀ l r, List.foldl (fun (s : List β) (b : β) => b :: s) r l = List.reverseAux l r from fun l => this l [] fun l => by induction l <;> simp [*, List.reverseAux])
end namespace Primcodable variable {α : Type*} {β : Type*} variable [Primcodable α] [Primcodable β]
Mathlib/Computability/Primrec.lean
782
787
/- Copyright (c) 2021 Kalle Kytölä. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kalle Kytölä -/ import Mathlib.Topology.MetricSpace.HausdorffDistance /-! # Thickenings in pseudo-metric spaces ## Main definitions * `Metric.thickening δ s`, the open thickening by radius `δ` of a set `s` in a pseudo emetric space. * `Metric.cthickening δ s`, the closed thickening by radius `δ` of a set `s` in a pseudo emetric space. ## Main results * `Disjoint.exists_thickenings`: two disjoint sets admit disjoint thickenings * `Disjoint.exists_cthickenings`: two disjoint sets admit disjoint closed thickenings * `IsCompact.exists_cthickening_subset_open`: if `s` is compact, `t` is open and `s ⊆ t`, some `cthickening` of `s` is contained in `t`. * `Metric.hasBasis_nhdsSet_cthickening`: the `cthickening`s of a compact set `K` form a basis of the neighbourhoods of `K` * `Metric.closure_eq_iInter_cthickening'`: the closure of a set equals the intersection of its closed thickenings of positive radii accumulating at zero. The same holds for open thickenings. * `IsCompact.cthickening_eq_biUnion_closedBall`: if `s` is compact, `cthickening δ s` is the union of `closedBall`s of radius `δ` around `x : E`. -/ noncomputable section open NNReal ENNReal Topology Set Filter Bornology universe u v w variable {ι : Sort*} {α : Type u} namespace Metric section Thickening variable [PseudoEMetricSpace α] {δ : ℝ} {s : Set α} {x : α} open EMetric /-- The (open) `δ`-thickening `Metric.thickening δ E` of a subset `E` in a pseudo emetric space consists of those points that are at distance less than `δ` from some point of `E`. -/ def thickening (δ : ℝ) (E : Set α) : Set α := { x : α | infEdist x E < ENNReal.ofReal δ } theorem mem_thickening_iff_infEdist_lt : x ∈ thickening δ s ↔ infEdist x s < ENNReal.ofReal δ := Iff.rfl /-- An exterior point of a subset `E` (i.e., a point outside the closure of `E`) is not in the (open) `δ`-thickening of `E` for small enough positive `δ`. -/ lemma eventually_not_mem_thickening_of_infEdist_pos {E : Set α} {x : α} (h : x ∉ closure E) : ∀ᶠ δ in 𝓝 (0 : ℝ), x ∉ Metric.thickening δ E := by obtain ⟨ε, ⟨ε_pos, ε_lt⟩⟩ := exists_real_pos_lt_infEdist_of_not_mem_closure h filter_upwards [eventually_lt_nhds ε_pos] with δ hδ simp only [thickening, mem_setOf_eq, not_lt] exact (ENNReal.ofReal_le_ofReal hδ.le).trans ε_lt.le /-- The (open) thickening equals the preimage of an open interval under `EMetric.infEdist`. -/ theorem thickening_eq_preimage_infEdist (δ : ℝ) (E : Set α) : thickening δ E = (infEdist · E) ⁻¹' Iio (ENNReal.ofReal δ) := rfl /-- The (open) thickening is an open set. -/ theorem isOpen_thickening {δ : ℝ} {E : Set α} : IsOpen (thickening δ E) := Continuous.isOpen_preimage continuous_infEdist _ isOpen_Iio /-- The (open) thickening of the empty set is empty. -/ @[simp] theorem thickening_empty (δ : ℝ) : thickening δ (∅ : Set α) = ∅ := by simp only [thickening, setOf_false, infEdist_empty, not_top_lt] theorem thickening_of_nonpos (hδ : δ ≤ 0) (s : Set α) : thickening δ s = ∅ := eq_empty_of_forall_not_mem fun _ => ((ENNReal.ofReal_of_nonpos hδ).trans_le bot_le).not_lt /-- The (open) thickening `Metric.thickening δ E` of a fixed subset `E` is an increasing function of the thickening radius `δ`. -/ @[gcongr] theorem thickening_mono {δ₁ δ₂ : ℝ} (hle : δ₁ ≤ δ₂) (E : Set α) : thickening δ₁ E ⊆ thickening δ₂ E := preimage_mono (Iio_subset_Iio (ENNReal.ofReal_le_ofReal hle)) /-- The (open) thickening `Metric.thickening δ E` with a fixed thickening radius `δ` is an increasing function of the subset `E`. -/ theorem thickening_subset_of_subset (δ : ℝ) {E₁ E₂ : Set α} (h : E₁ ⊆ E₂) : thickening δ E₁ ⊆ thickening δ E₂ := fun _ hx => lt_of_le_of_lt (infEdist_anti h) hx theorem mem_thickening_iff_exists_edist_lt {δ : ℝ} (E : Set α) (x : α) : x ∈ thickening δ E ↔ ∃ z ∈ E, edist x z < ENNReal.ofReal δ := infEdist_lt_iff /-- The frontier of the (open) thickening of a set is contained in an `EMetric.infEdist` level set. -/ theorem frontier_thickening_subset (E : Set α) {δ : ℝ} : frontier (thickening δ E) ⊆ { x : α | infEdist x E = ENNReal.ofReal δ } := frontier_lt_subset_eq continuous_infEdist continuous_const open scoped Function in -- required for scoped `on` notation theorem frontier_thickening_disjoint (A : Set α) : Pairwise (Disjoint on fun r : ℝ => frontier (thickening r A)) := by refine (pairwise_disjoint_on _).2 fun r₁ r₂ hr => ?_ rcases le_total r₁ 0 with h₁ | h₁ · simp [thickening_of_nonpos h₁] refine ((disjoint_singleton.2 fun h => hr.ne ?_).preimage _).mono (frontier_thickening_subset _) (frontier_thickening_subset _) apply_fun ENNReal.toReal at h rwa [ENNReal.toReal_ofReal h₁, ENNReal.toReal_ofReal (h₁.trans hr.le)] at h /-- Any set is contained in the complement of the δ-thickening of the complement of its δ-thickening. -/ lemma subset_compl_thickening_compl_thickening_self (δ : ℝ) (E : Set α) : E ⊆ (thickening δ (thickening δ E)ᶜ)ᶜ := by intro x x_in_E simp only [thickening, mem_compl_iff, mem_setOf_eq, not_lt] apply EMetric.le_infEdist.mpr fun y hy ↦ ?_ simp only [mem_compl_iff, mem_setOf_eq, not_lt] at hy simpa only [edist_comm] using le_trans hy <| EMetric.infEdist_le_edist_of_mem x_in_E /-- The δ-thickening of the complement of the δ-thickening of a set is contained in the complement of the set. -/ lemma thickening_compl_thickening_self_subset_compl (δ : ℝ) (E : Set α) : thickening δ (thickening δ E)ᶜ ⊆ Eᶜ := by apply compl_subset_compl.mp simpa only [compl_compl] using subset_compl_thickening_compl_thickening_self δ E variable {X : Type u} [PseudoMetricSpace X] theorem mem_thickening_iff_infDist_lt {E : Set X} {x : X} (h : E.Nonempty) : x ∈ thickening δ E ↔ infDist x E < δ := lt_ofReal_iff_toReal_lt (infEdist_ne_top h) /-- A point in a metric space belongs to the (open) `δ`-thickening of a subset `E` if and only if it is at distance less than `δ` from some point of `E`. -/ theorem mem_thickening_iff {E : Set X} {x : X} : x ∈ thickening δ E ↔ ∃ z ∈ E, dist x z < δ := by have key_iff : ∀ z : X, edist x z < ENNReal.ofReal δ ↔ dist x z < δ := fun z ↦ by rw [dist_edist, lt_ofReal_iff_toReal_lt (edist_ne_top _ _)] simp_rw [mem_thickening_iff_exists_edist_lt, key_iff] @[simp] theorem thickening_singleton (δ : ℝ) (x : X) : thickening δ ({x} : Set X) = ball x δ := by ext simp [mem_thickening_iff] theorem ball_subset_thickening {x : X} {E : Set X} (hx : x ∈ E) (δ : ℝ) : ball x δ ⊆ thickening δ E := Subset.trans (by simp [Subset.rfl]) (thickening_subset_of_subset δ <| singleton_subset_iff.mpr hx) /-- The (open) `δ`-thickening `Metric.thickening δ E` of a subset `E` in a metric space equals the union of balls of radius `δ` centered at points of `E`. -/ theorem thickening_eq_biUnion_ball {δ : ℝ} {E : Set X} : thickening δ E = ⋃ x ∈ E, ball x δ := by ext x simp only [mem_iUnion₂, exists_prop] exact mem_thickening_iff protected theorem _root_.Bornology.IsBounded.thickening {δ : ℝ} {E : Set X} (h : IsBounded E) : IsBounded (thickening δ E) := by rcases E.eq_empty_or_nonempty with rfl | ⟨x, hx⟩ · simp · refine (isBounded_iff_subset_closedBall x).2 ⟨δ + diam E, fun y hy ↦ ?_⟩ calc dist y x ≤ infDist y E + diam E := dist_le_infDist_add_diam (x := y) h hx _ ≤ δ + diam E := add_le_add_right ((mem_thickening_iff_infDist_lt ⟨x, hx⟩).1 hy).le _ end Thickening section Cthickening variable [PseudoEMetricSpace α] {δ ε : ℝ} {s t : Set α} {x : α} open EMetric /-- The closed `δ`-thickening `Metric.cthickening δ E` of a subset `E` in a pseudo emetric space consists of those points that are at infimum distance at most `δ` from `E`. -/ def cthickening (δ : ℝ) (E : Set α) : Set α := { x : α | infEdist x E ≤ ENNReal.ofReal δ } @[simp] theorem mem_cthickening_iff : x ∈ cthickening δ s ↔ infEdist x s ≤ ENNReal.ofReal δ := Iff.rfl /-- An exterior point of a subset `E` (i.e., a point outside the closure of `E`) is not in the closed `δ`-thickening of `E` for small enough positive `δ`. -/ lemma eventually_not_mem_cthickening_of_infEdist_pos {E : Set α} {x : α} (h : x ∉ closure E) : ∀ᶠ δ in 𝓝 (0 : ℝ), x ∉ Metric.cthickening δ E := by obtain ⟨ε, ⟨ε_pos, ε_lt⟩⟩ := exists_real_pos_lt_infEdist_of_not_mem_closure h filter_upwards [eventually_lt_nhds ε_pos] with δ hδ simp only [cthickening, mem_setOf_eq, not_le] exact ((ofReal_lt_ofReal_iff ε_pos).mpr hδ).trans ε_lt theorem mem_cthickening_of_edist_le (x y : α) (δ : ℝ) (E : Set α) (h : y ∈ E) (h' : edist x y ≤ ENNReal.ofReal δ) : x ∈ cthickening δ E := (infEdist_le_edist_of_mem h).trans h' theorem mem_cthickening_of_dist_le {α : Type*} [PseudoMetricSpace α] (x y : α) (δ : ℝ) (E : Set α) (h : y ∈ E) (h' : dist x y ≤ δ) : x ∈ cthickening δ E := by apply mem_cthickening_of_edist_le x y δ E h rw [edist_dist] exact ENNReal.ofReal_le_ofReal h' theorem cthickening_eq_preimage_infEdist (δ : ℝ) (E : Set α) : cthickening δ E = (fun x => infEdist x E) ⁻¹' Iic (ENNReal.ofReal δ) := rfl /-- The closed thickening is a closed set. -/ theorem isClosed_cthickening {δ : ℝ} {E : Set α} : IsClosed (cthickening δ E) := IsClosed.preimage continuous_infEdist isClosed_Iic /-- The closed thickening of the empty set is empty. -/ @[simp] theorem cthickening_empty (δ : ℝ) : cthickening δ (∅ : Set α) = ∅ := by simp only [cthickening, ENNReal.ofReal_ne_top, setOf_false, infEdist_empty, top_le_iff] theorem cthickening_of_nonpos {δ : ℝ} (hδ : δ ≤ 0) (E : Set α) : cthickening δ E = closure E := by ext x simp [mem_closure_iff_infEdist_zero, cthickening, ENNReal.ofReal_eq_zero.2 hδ] /-- The closed thickening with radius zero is the closure of the set. -/ @[simp] theorem cthickening_zero (E : Set α) : cthickening 0 E = closure E := cthickening_of_nonpos le_rfl E theorem cthickening_max_zero (δ : ℝ) (E : Set α) : cthickening (max 0 δ) E = cthickening δ E := by cases le_total δ 0 <;> simp [cthickening_of_nonpos, *] /-- The closed thickening `Metric.cthickening δ E` of a fixed subset `E` is an increasing function of the thickening radius `δ`. -/ theorem cthickening_mono {δ₁ δ₂ : ℝ} (hle : δ₁ ≤ δ₂) (E : Set α) : cthickening δ₁ E ⊆ cthickening δ₂ E := preimage_mono (Iic_subset_Iic.mpr (ENNReal.ofReal_le_ofReal hle)) @[simp] theorem cthickening_singleton {α : Type*} [PseudoMetricSpace α] (x : α) {δ : ℝ} (hδ : 0 ≤ δ) : cthickening δ ({x} : Set α) = closedBall x δ := by ext y simp [cthickening, edist_dist, ENNReal.ofReal_le_ofReal_iff hδ] theorem closedBall_subset_cthickening_singleton {α : Type*} [PseudoMetricSpace α] (x : α) (δ : ℝ) : closedBall x δ ⊆ cthickening δ ({x} : Set α) := by rcases lt_or_le δ 0 with (hδ | hδ) · simp only [closedBall_eq_empty.mpr hδ, empty_subset] · simp only [cthickening_singleton x hδ, Subset.rfl] /-- The closed thickening `Metric.cthickening δ E` with a fixed thickening radius `δ` is an increasing function of the subset `E`. -/ theorem cthickening_subset_of_subset (δ : ℝ) {E₁ E₂ : Set α} (h : E₁ ⊆ E₂) : cthickening δ E₁ ⊆ cthickening δ E₂ := fun _ hx => le_trans (infEdist_anti h) hx theorem cthickening_subset_thickening {δ₁ : ℝ≥0} {δ₂ : ℝ} (hlt : (δ₁ : ℝ) < δ₂) (E : Set α) : cthickening δ₁ E ⊆ thickening δ₂ E := fun _ hx => hx.out.trans_lt ((ENNReal.ofReal_lt_ofReal_iff (lt_of_le_of_lt δ₁.prop hlt)).mpr hlt) /-- The closed thickening `Metric.cthickening δ₁ E` is contained in the open thickening `Metric.thickening δ₂ E` if the radius of the latter is positive and larger. -/ theorem cthickening_subset_thickening' {δ₁ δ₂ : ℝ} (δ₂_pos : 0 < δ₂) (hlt : δ₁ < δ₂) (E : Set α) : cthickening δ₁ E ⊆ thickening δ₂ E := fun _ hx => lt_of_le_of_lt hx.out ((ENNReal.ofReal_lt_ofReal_iff δ₂_pos).mpr hlt) /-- The open thickening `Metric.thickening δ E` is contained in the closed thickening `Metric.cthickening δ E` with the same radius. -/ theorem thickening_subset_cthickening (δ : ℝ) (E : Set α) : thickening δ E ⊆ cthickening δ E := by intro x hx rw [thickening, mem_setOf_eq] at hx exact hx.le theorem thickening_subset_cthickening_of_le {δ₁ δ₂ : ℝ} (hle : δ₁ ≤ δ₂) (E : Set α) : thickening δ₁ E ⊆ cthickening δ₂ E := (thickening_subset_cthickening δ₁ E).trans (cthickening_mono hle E) theorem _root_.Bornology.IsBounded.cthickening {α : Type*} [PseudoMetricSpace α] {δ : ℝ} {E : Set α} (h : IsBounded E) : IsBounded (cthickening δ E) := by have : IsBounded (thickening (max (δ + 1) 1) E) := h.thickening apply this.subset exact cthickening_subset_thickening' (zero_lt_one.trans_le (le_max_right _ _)) ((lt_add_one _).trans_le (le_max_left _ _)) _ protected theorem _root_.IsCompact.cthickening {α : Type*} [PseudoMetricSpace α] [ProperSpace α] {s : Set α} (hs : IsCompact s) {r : ℝ} : IsCompact (cthickening r s) := isCompact_of_isClosed_isBounded isClosed_cthickening hs.isBounded.cthickening theorem thickening_subset_interior_cthickening (δ : ℝ) (E : Set α) : thickening δ E ⊆ interior (cthickening δ E) := (subset_interior_iff_isOpen.mpr isOpen_thickening).trans (interior_mono (thickening_subset_cthickening δ E)) theorem closure_thickening_subset_cthickening (δ : ℝ) (E : Set α) : closure (thickening δ E) ⊆ cthickening δ E := (closure_mono (thickening_subset_cthickening δ E)).trans isClosed_cthickening.closure_subset /-- The closed thickening of a set contains the closure of the set. -/ theorem closure_subset_cthickening (δ : ℝ) (E : Set α) : closure E ⊆ cthickening δ E := by rw [← cthickening_of_nonpos (min_le_right δ 0)] exact cthickening_mono (min_le_left δ 0) E /-- The (open) thickening of a set contains the closure of the set. -/ theorem closure_subset_thickening {δ : ℝ} (δ_pos : 0 < δ) (E : Set α) : closure E ⊆ thickening δ E := by rw [← cthickening_zero] exact cthickening_subset_thickening' δ_pos δ_pos E /-- A set is contained in its own (open) thickening. -/ theorem self_subset_thickening {δ : ℝ} (δ_pos : 0 < δ) (E : Set α) : E ⊆ thickening δ E := (@subset_closure _ _ E).trans (closure_subset_thickening δ_pos E) /-- A set is contained in its own closed thickening. -/ theorem self_subset_cthickening {δ : ℝ} (E : Set α) : E ⊆ cthickening δ E := subset_closure.trans (closure_subset_cthickening δ E) theorem thickening_mem_nhdsSet (E : Set α) {δ : ℝ} (hδ : 0 < δ) : thickening δ E ∈ 𝓝ˢ E := isOpen_thickening.mem_nhdsSet.2 <| self_subset_thickening hδ E theorem cthickening_mem_nhdsSet (E : Set α) {δ : ℝ} (hδ : 0 < δ) : cthickening δ E ∈ 𝓝ˢ E := mem_of_superset (thickening_mem_nhdsSet E hδ) (thickening_subset_cthickening _ _) @[simp] theorem thickening_union (δ : ℝ) (s t : Set α) : thickening δ (s ∪ t) = thickening δ s ∪ thickening δ t := by simp_rw [thickening, infEdist_union, min_lt_iff, setOf_or] @[simp] theorem cthickening_union (δ : ℝ) (s t : Set α) : cthickening δ (s ∪ t) = cthickening δ s ∪ cthickening δ t := by simp_rw [cthickening, infEdist_union, min_le_iff, setOf_or] @[simp] theorem thickening_iUnion (δ : ℝ) (f : ι → Set α) : thickening δ (⋃ i, f i) = ⋃ i, thickening δ (f i) := by simp_rw [thickening, infEdist_iUnion, iInf_lt_iff, setOf_exists] lemma thickening_biUnion {ι : Type*} (δ : ℝ) (f : ι → Set α) (I : Set ι) : thickening δ (⋃ i ∈ I, f i) = ⋃ i ∈ I, thickening δ (f i) := by simp only [thickening_iUnion] theorem ediam_cthickening_le (ε : ℝ≥0) : EMetric.diam (cthickening ε s) ≤ EMetric.diam s + 2 * ε := by refine diam_le fun x hx y hy => ENNReal.le_of_forall_pos_le_add fun δ hδ _ => ?_ rw [mem_cthickening_iff, ENNReal.ofReal_coe_nnreal] at hx hy have hε : (ε : ℝ≥0∞) < ε + δ := ENNReal.coe_lt_coe.2 (lt_add_of_pos_right _ hδ) replace hx := hx.trans_lt hε obtain ⟨x', hx', hxx'⟩ := infEdist_lt_iff.mp hx calc edist x y ≤ edist x x' + edist y x' := edist_triangle_right _ _ _ _ ≤ ε + δ + (infEdist y s + EMetric.diam s) := add_le_add hxx'.le (edist_le_infEdist_add_ediam hx') _ ≤ ε + δ + (ε + EMetric.diam s) := add_le_add_left (add_le_add_right hy _) _ _ = _ := by rw [two_mul]; ac_rfl theorem ediam_thickening_le (ε : ℝ≥0) : EMetric.diam (thickening ε s) ≤ EMetric.diam s + 2 * ε := (EMetric.diam_mono <| thickening_subset_cthickening _ _).trans <| ediam_cthickening_le _ theorem diam_cthickening_le {α : Type*} [PseudoMetricSpace α] (s : Set α) (hε : 0 ≤ ε) : diam (cthickening ε s) ≤ diam s + 2 * ε := by lift ε to ℝ≥0 using hε refine (toReal_le_add' (ediam_cthickening_le _) ?_ ?_).trans_eq ?_ · exact fun h ↦ top_unique <| h ▸ EMetric.diam_mono (self_subset_cthickening _) · simp [mul_eq_top] · simp [diam] theorem diam_thickening_le {α : Type*} [PseudoMetricSpace α] (s : Set α) (hε : 0 ≤ ε) : diam (thickening ε s) ≤ diam s + 2 * ε := by by_cases hs : IsBounded s · exact (diam_mono (thickening_subset_cthickening _ _) hs.cthickening).trans (diam_cthickening_le _ hε) obtain rfl | hε := hε.eq_or_lt · simp [thickening_of_nonpos, diam_nonneg] · rw [diam_eq_zero_of_unbounded (mt (IsBounded.subset · <| self_subset_thickening hε _) hs)] positivity @[simp] theorem thickening_closure : thickening δ (closure s) = thickening δ s := by simp_rw [thickening, infEdist_closure] @[simp] theorem cthickening_closure : cthickening δ (closure s) = cthickening δ s := by simp_rw [cthickening, infEdist_closure] open ENNReal theorem _root_.Disjoint.exists_thickenings (hst : Disjoint s t) (hs : IsCompact s) (ht : IsClosed t) : ∃ δ, 0 < δ ∧ Disjoint (thickening δ s) (thickening δ t) := by obtain ⟨r, hr, h⟩ := exists_pos_forall_lt_edist hs ht hst refine ⟨r / 2, half_pos (NNReal.coe_pos.2 hr), ?_⟩ rw [disjoint_iff_inf_le] rintro z ⟨hzs, hzt⟩ rw [mem_thickening_iff_exists_edist_lt] at hzs hzt rw [← NNReal.coe_two, ← NNReal.coe_div, ENNReal.ofReal_coe_nnreal] at hzs hzt obtain ⟨x, hx, hzx⟩ := hzs obtain ⟨y, hy, hzy⟩ := hzt refine (h x hx y hy).not_le ?_ calc edist x y ≤ edist z x + edist z y := edist_triangle_left _ _ _ _ ≤ ↑(r / 2) + ↑(r / 2) := add_le_add hzx.le hzy.le _ = r := by rw [← ENNReal.coe_add, add_halves] theorem _root_.Disjoint.exists_cthickenings (hst : Disjoint s t) (hs : IsCompact s) (ht : IsClosed t) : ∃ δ, 0 < δ ∧ Disjoint (cthickening δ s) (cthickening δ t) := by obtain ⟨δ, hδ, h⟩ := hst.exists_thickenings hs ht refine ⟨δ / 2, half_pos hδ, h.mono ?_ ?_⟩ <;> exact cthickening_subset_thickening' hδ (half_lt_self hδ) _ /-- If `s` is compact, `t` is open and `s ⊆ t`, some `cthickening` of `s` is contained in `t`. -/ theorem _root_.IsCompact.exists_cthickening_subset_open (hs : IsCompact s) (ht : IsOpen t) (hst : s ⊆ t) : ∃ δ, 0 < δ ∧ cthickening δ s ⊆ t := (hst.disjoint_compl_right.exists_cthickenings hs ht.isClosed_compl).imp fun _ h => ⟨h.1, disjoint_compl_right_iff_subset.1 <| h.2.mono_right <| self_subset_cthickening _⟩ theorem _root_.IsCompact.exists_isCompact_cthickening [LocallyCompactSpace α] (hs : IsCompact s) : ∃ δ, 0 < δ ∧ IsCompact (cthickening δ s) := by rcases exists_compact_superset hs with ⟨K, K_compact, hK⟩ rcases hs.exists_cthickening_subset_open isOpen_interior hK with ⟨δ, δpos, hδ⟩ refine ⟨δ, δpos, ?_⟩ exact K_compact.of_isClosed_subset isClosed_cthickening (hδ.trans interior_subset) theorem _root_.IsCompact.exists_thickening_subset_open (hs : IsCompact s) (ht : IsOpen t) (hst : s ⊆ t) : ∃ δ, 0 < δ ∧ thickening δ s ⊆ t := let ⟨δ, h₀, hδ⟩ := hs.exists_cthickening_subset_open ht hst ⟨δ, h₀, (thickening_subset_cthickening _ _).trans hδ⟩ theorem hasBasis_nhdsSet_thickening {K : Set α} (hK : IsCompact K) : (𝓝ˢ K).HasBasis (fun δ : ℝ => 0 < δ) fun δ => thickening δ K := (hasBasis_nhdsSet K).to_hasBasis' (fun _U hU => hK.exists_thickening_subset_open hU.1 hU.2) fun _ => thickening_mem_nhdsSet K theorem hasBasis_nhdsSet_cthickening {K : Set α} (hK : IsCompact K) : (𝓝ˢ K).HasBasis (fun δ : ℝ => 0 < δ) fun δ => cthickening δ K := (hasBasis_nhdsSet K).to_hasBasis' (fun _U hU => hK.exists_cthickening_subset_open hU.1 hU.2) fun _ => cthickening_mem_nhdsSet K theorem cthickening_eq_iInter_cthickening' {δ : ℝ} (s : Set ℝ) (hsδ : s ⊆ Ioi δ) (hs : ∀ ε, δ < ε → (s ∩ Ioc δ ε).Nonempty) (E : Set α) : cthickening δ E = ⋂ ε ∈ s, cthickening ε E := by apply Subset.antisymm · exact subset_iInter₂ fun _ hε => cthickening_mono (le_of_lt (hsδ hε)) E · unfold cthickening intro x hx simp only [mem_iInter, mem_setOf_eq] at * apply ENNReal.le_of_forall_pos_le_add intro η η_pos _ rcases hs (δ + η) (lt_add_of_pos_right _ (NNReal.coe_pos.mpr η_pos)) with ⟨ε, ⟨hsε, hε⟩⟩ apply ((hx ε hsε).trans (ENNReal.ofReal_le_ofReal hε.2)).trans rw [ENNReal.coe_nnreal_eq η] exact ENNReal.ofReal_add_le theorem cthickening_eq_iInter_cthickening {δ : ℝ} (E : Set α) : cthickening δ E = ⋂ (ε : ℝ) (_ : δ < ε), cthickening ε E := by apply cthickening_eq_iInter_cthickening' (Ioi δ) rfl.subset simp_rw [inter_eq_right.mpr Ioc_subset_Ioi_self] exact fun _ hε => nonempty_Ioc.mpr hε theorem cthickening_eq_iInter_thickening' {δ : ℝ} (δ_nn : 0 ≤ δ) (s : Set ℝ) (hsδ : s ⊆ Ioi δ) (hs : ∀ ε, δ < ε → (s ∩ Ioc δ ε).Nonempty) (E : Set α) : cthickening δ E = ⋂ ε ∈ s, thickening ε E := by refine (subset_iInter₂ fun ε hε => ?_).antisymm ?_ · obtain ⟨ε', -, hε'⟩ := hs ε (hsδ hε) have ss := cthickening_subset_thickening' (lt_of_le_of_lt δ_nn hε'.1) hε'.1 E exact ss.trans (thickening_mono hε'.2 E) · rw [cthickening_eq_iInter_cthickening' s hsδ hs E] exact iInter₂_mono fun ε _ => thickening_subset_cthickening ε E theorem cthickening_eq_iInter_thickening {δ : ℝ} (δ_nn : 0 ≤ δ) (E : Set α) : cthickening δ E = ⋂ (ε : ℝ) (_ : δ < ε), thickening ε E := by apply cthickening_eq_iInter_thickening' δ_nn (Ioi δ) rfl.subset simp_rw [inter_eq_right.mpr Ioc_subset_Ioi_self] exact fun _ hε => nonempty_Ioc.mpr hε theorem cthickening_eq_iInter_thickening'' (δ : ℝ) (E : Set α) : cthickening δ E = ⋂ (ε : ℝ) (_ : max 0 δ < ε), thickening ε E := by rw [← cthickening_max_zero, cthickening_eq_iInter_thickening] exact le_max_left _ _ /-- The closure of a set equals the intersection of its closed thickenings of positive radii accumulating at zero. -/ theorem closure_eq_iInter_cthickening' (E : Set α) (s : Set ℝ) (hs : ∀ ε, 0 < ε → (s ∩ Ioc 0 ε).Nonempty) : closure E = ⋂ δ ∈ s, cthickening δ E := by by_cases hs₀ : s ⊆ Ioi 0 · rw [← cthickening_zero] apply cthickening_eq_iInter_cthickening' _ hs₀ hs obtain ⟨δ, hδs, δ_nonpos⟩ := not_subset.mp hs₀ rw [Set.mem_Ioi, not_lt] at δ_nonpos apply Subset.antisymm · exact subset_iInter₂ fun ε _ => closure_subset_cthickening ε E · rw [← cthickening_of_nonpos δ_nonpos E] exact biInter_subset_of_mem hδs /-- The closure of a set equals the intersection of its closed thickenings of positive radii. -/ theorem closure_eq_iInter_cthickening (E : Set α) : closure E = ⋂ (δ : ℝ) (_ : 0 < δ), cthickening δ E := by rw [← cthickening_zero] exact cthickening_eq_iInter_cthickening E /-- The closure of a set equals the intersection of its open thickenings of positive radii accumulating at zero. -/ theorem closure_eq_iInter_thickening' (E : Set α) (s : Set ℝ) (hs₀ : s ⊆ Ioi 0) (hs : ∀ ε, 0 < ε → (s ∩ Ioc 0 ε).Nonempty) : closure E = ⋂ δ ∈ s, thickening δ E := by rw [← cthickening_zero] apply cthickening_eq_iInter_thickening' le_rfl _ hs₀ hs /-- The closure of a set equals the intersection of its (open) thickenings of positive radii. -/ theorem closure_eq_iInter_thickening (E : Set α) : closure E = ⋂ (δ : ℝ) (_ : 0 < δ), thickening δ E := by rw [← cthickening_zero] exact cthickening_eq_iInter_thickening rfl.ge E /-- The frontier of the closed thickening of a set is contained in an `EMetric.infEdist` level set. -/ theorem frontier_cthickening_subset (E : Set α) {δ : ℝ} : frontier (cthickening δ E) ⊆ { x : α | infEdist x E = ENNReal.ofReal δ } := frontier_le_subset_eq continuous_infEdist continuous_const
/-- The closed ball of radius `δ` centered at a point of `E` is included in the closed thickening of `E`. -/ theorem closedBall_subset_cthickening {α : Type*} [PseudoMetricSpace α] {x : α} {E : Set α} (hx : x ∈ E) (δ : ℝ) : closedBall x δ ⊆ cthickening δ E := by refine (closedBall_subset_cthickening_singleton _ _).trans (cthickening_subset_of_subset _ ?_) simpa using hx theorem cthickening_subset_iUnion_closedBall_of_lt {α : Type*} [PseudoMetricSpace α] (E : Set α) {δ δ' : ℝ} (hδ₀ : 0 < δ') (hδδ' : δ < δ') : cthickening δ E ⊆ ⋃ x ∈ E, closedBall x δ' := by
Mathlib/Topology/MetricSpace/Thickening.lean
517
525
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Johan Commelin, Mario Carneiro -/ import Mathlib.Algebra.Algebra.Subalgebra.Lattice import Mathlib.Algebra.Algebra.Tower import Mathlib.Algebra.GroupWithZero.Divisibility import Mathlib.Algebra.MonoidAlgebra.Basic import Mathlib.Algebra.MonoidAlgebra.Support import Mathlib.Algebra.Regular.Pow import Mathlib.Data.Finsupp.Antidiagonal import Mathlib.Order.SymmDiff /-! # Multivariate polynomials This file defines polynomial rings over a base ring (or even semiring), with variables from a general type `σ` (which could be infinite). ## Important definitions Let `R` be a commutative ring (or a semiring) and let `σ` be an arbitrary type. This file creates the type `MvPolynomial σ R`, which mathematicians might denote $R[X_i : i \in σ]$. It is the type of multivariate (a.k.a. multivariable) polynomials, with variables corresponding to the terms in `σ`, and coefficients in `R`. ### Notation In the definitions below, we use the following notation: + `σ : Type*` (indexing the variables) + `R : Type*` `[CommSemiring R]` (the coefficients) + `s : σ →₀ ℕ`, a function from `σ` to `ℕ` which is zero away from a finite set. This will give rise to a monomial in `MvPolynomial σ R` which mathematicians might call `X^s` + `a : R` + `i : σ`, with corresponding monomial `X i`, often denoted `X_i` by mathematicians + `p : MvPolynomial σ R` ### Definitions * `MvPolynomial σ R` : the type of polynomials with variables of type `σ` and coefficients in the commutative semiring `R` * `monomial s a` : the monomial which mathematically would be denoted `a * X^s` * `C a` : the constant polynomial with value `a` * `X i` : the degree one monomial corresponding to i; mathematically this might be denoted `Xᵢ`. * `coeff s p` : the coefficient of `s` in `p`. ## Implementation notes Recall that if `Y` has a zero, then `X →₀ Y` is the type of functions from `X` to `Y` with finite support, i.e. such that only finitely many elements of `X` get sent to non-zero terms in `Y`. The definition of `MvPolynomial σ R` is `(σ →₀ ℕ) →₀ R`; here `σ →₀ ℕ` denotes the space of all monomials in the variables, and the function to `R` sends a monomial to its coefficient in the polynomial being represented. ## Tags polynomial, multivariate polynomial, multivariable polynomial -/ noncomputable section open Set Function Finsupp AddMonoidAlgebra open scoped Pointwise universe u v w x variable {R : Type u} {S₁ : Type v} {S₂ : Type w} {S₃ : Type x} /-- Multivariate polynomial, where `σ` is the index set of the variables and `R` is the coefficient ring -/ def MvPolynomial (σ : Type*) (R : Type*) [CommSemiring R] := AddMonoidAlgebra R (σ →₀ ℕ) namespace MvPolynomial -- Porting note: because of `MvPolynomial.C` and `MvPolynomial.X` this linter throws -- tons of warnings in this file, and it's easier to just disable them globally in the file variable {σ : Type*} {a a' a₁ a₂ : R} {e : ℕ} {n m : σ} {s : σ →₀ ℕ} section CommSemiring section Instances instance decidableEqMvPolynomial [CommSemiring R] [DecidableEq σ] [DecidableEq R] : DecidableEq (MvPolynomial σ R) := Finsupp.instDecidableEq instance commSemiring [CommSemiring R] : CommSemiring (MvPolynomial σ R) := AddMonoidAlgebra.commSemiring instance inhabited [CommSemiring R] : Inhabited (MvPolynomial σ R) := ⟨0⟩ instance distribuMulAction [Monoid R] [CommSemiring S₁] [DistribMulAction R S₁] : DistribMulAction R (MvPolynomial σ S₁) := AddMonoidAlgebra.distribMulAction instance smulZeroClass [CommSemiring S₁] [SMulZeroClass R S₁] : SMulZeroClass R (MvPolynomial σ S₁) := AddMonoidAlgebra.smulZeroClass instance faithfulSMul [CommSemiring S₁] [SMulZeroClass R S₁] [FaithfulSMul R S₁] : FaithfulSMul R (MvPolynomial σ S₁) := AddMonoidAlgebra.faithfulSMul instance module [Semiring R] [CommSemiring S₁] [Module R S₁] : Module R (MvPolynomial σ S₁) := AddMonoidAlgebra.module instance isScalarTower [CommSemiring S₂] [SMul R S₁] [SMulZeroClass R S₂] [SMulZeroClass S₁ S₂] [IsScalarTower R S₁ S₂] : IsScalarTower R S₁ (MvPolynomial σ S₂) := AddMonoidAlgebra.isScalarTower instance smulCommClass [CommSemiring S₂] [SMulZeroClass R S₂] [SMulZeroClass S₁ S₂] [SMulCommClass R S₁ S₂] : SMulCommClass R S₁ (MvPolynomial σ S₂) := AddMonoidAlgebra.smulCommClass instance isCentralScalar [CommSemiring S₁] [SMulZeroClass R S₁] [SMulZeroClass Rᵐᵒᵖ S₁] [IsCentralScalar R S₁] : IsCentralScalar R (MvPolynomial σ S₁) := AddMonoidAlgebra.isCentralScalar instance algebra [CommSemiring R] [CommSemiring S₁] [Algebra R S₁] : Algebra R (MvPolynomial σ S₁) := AddMonoidAlgebra.algebra instance isScalarTower_right [CommSemiring S₁] [DistribSMul R S₁] [IsScalarTower R S₁ S₁] : IsScalarTower R (MvPolynomial σ S₁) (MvPolynomial σ S₁) := AddMonoidAlgebra.isScalarTower_self _ instance smulCommClass_right [CommSemiring S₁] [DistribSMul R S₁] [SMulCommClass R S₁ S₁] : SMulCommClass R (MvPolynomial σ S₁) (MvPolynomial σ S₁) := AddMonoidAlgebra.smulCommClass_self _ /-- If `R` is a subsingleton, then `MvPolynomial σ R` has a unique element -/ instance unique [CommSemiring R] [Subsingleton R] : Unique (MvPolynomial σ R) := AddMonoidAlgebra.unique end Instances variable [CommSemiring R] [CommSemiring S₁] {p q : MvPolynomial σ R} /-- `monomial s a` is the monomial with coefficient `a` and exponents given by `s` -/ def monomial (s : σ →₀ ℕ) : R →ₗ[R] MvPolynomial σ R := AddMonoidAlgebra.lsingle s theorem one_def : (1 : MvPolynomial σ R) = monomial 0 1 := rfl theorem single_eq_monomial (s : σ →₀ ℕ) (a : R) : Finsupp.single s a = monomial s a := rfl theorem mul_def : p * q = p.sum fun m a => q.sum fun n b => monomial (m + n) (a * b) := AddMonoidAlgebra.mul_def /-- `C a` is the constant polynomial with value `a` -/ def C : R →+* MvPolynomial σ R := { singleZeroRingHom with toFun := monomial 0 } variable (R σ) @[simp] theorem algebraMap_eq : algebraMap R (MvPolynomial σ R) = C := rfl variable {R σ} /-- `X n` is the degree `1` monomial $X_n$. -/ def X (n : σ) : MvPolynomial σ R := monomial (Finsupp.single n 1) 1 theorem monomial_left_injective {r : R} (hr : r ≠ 0) : Function.Injective fun s : σ →₀ ℕ => monomial s r := Finsupp.single_left_injective hr @[simp] theorem monomial_left_inj {s t : σ →₀ ℕ} {r : R} (hr : r ≠ 0) : monomial s r = monomial t r ↔ s = t := Finsupp.single_left_inj hr theorem C_apply : (C a : MvPolynomial σ R) = monomial 0 a := rfl @[simp] theorem C_0 : C 0 = (0 : MvPolynomial σ R) := map_zero _ @[simp] theorem C_1 : C 1 = (1 : MvPolynomial σ R) := rfl theorem C_mul_monomial : C a * monomial s a' = monomial s (a * a') := by -- Porting note: this `show` feels like defeq abuse, but I can't find the appropriate lemmas show AddMonoidAlgebra.single _ _ * AddMonoidAlgebra.single _ _ = AddMonoidAlgebra.single _ _ simp [C_apply, single_mul_single] @[simp] theorem C_add : (C (a + a') : MvPolynomial σ R) = C a + C a' := Finsupp.single_add _ _ _ @[simp] theorem C_mul : (C (a * a') : MvPolynomial σ R) = C a * C a' := C_mul_monomial.symm @[simp] theorem C_pow (a : R) (n : ℕ) : (C (a ^ n) : MvPolynomial σ R) = C a ^ n := map_pow _ _ _ theorem C_injective (σ : Type*) (R : Type*) [CommSemiring R] : Function.Injective (C : R → MvPolynomial σ R) := Finsupp.single_injective _ theorem C_surjective {R : Type*} [CommSemiring R] (σ : Type*) [IsEmpty σ] : Function.Surjective (C : R → MvPolynomial σ R) := by refine fun p => ⟨p.toFun 0, Finsupp.ext fun a => ?_⟩ simp only [C_apply, ← single_eq_monomial, (Finsupp.ext isEmptyElim (α := σ) : a = 0), single_eq_same] rfl @[simp] theorem C_inj {σ : Type*} (R : Type*) [CommSemiring R] (r s : R) : (C r : MvPolynomial σ R) = C s ↔ r = s := (C_injective σ R).eq_iff @[simp] lemma C_eq_zero : (C a : MvPolynomial σ R) = 0 ↔ a = 0 := by rw [← map_zero C, C_inj] lemma C_ne_zero : (C a : MvPolynomial σ R) ≠ 0 ↔ a ≠ 0 := C_eq_zero.ne instance nontrivial_of_nontrivial (σ : Type*) (R : Type*) [CommSemiring R] [Nontrivial R] : Nontrivial (MvPolynomial σ R) := inferInstanceAs (Nontrivial <| AddMonoidAlgebra R (σ →₀ ℕ)) instance infinite_of_infinite (σ : Type*) (R : Type*) [CommSemiring R] [Infinite R] : Infinite (MvPolynomial σ R) := Infinite.of_injective C (C_injective _ _) instance infinite_of_nonempty (σ : Type*) (R : Type*) [Nonempty σ] [CommSemiring R] [Nontrivial R] : Infinite (MvPolynomial σ R) := Infinite.of_injective ((fun s : σ →₀ ℕ => monomial s 1) ∘ Finsupp.single (Classical.arbitrary σ)) <| (monomial_left_injective one_ne_zero).comp (Finsupp.single_injective _) theorem C_eq_coe_nat (n : ℕ) : (C ↑n : MvPolynomial σ R) = n := by induction n <;> simp [*] theorem C_mul' : MvPolynomial.C a * p = a • p := (Algebra.smul_def a p).symm theorem smul_eq_C_mul (p : MvPolynomial σ R) (a : R) : a • p = C a * p := C_mul'.symm theorem C_eq_smul_one : (C a : MvPolynomial σ R) = a • (1 : MvPolynomial σ R) := by rw [← C_mul', mul_one] theorem smul_monomial {S₁ : Type*} [SMulZeroClass S₁ R] (r : S₁) : r • monomial s a = monomial s (r • a) := Finsupp.smul_single _ _ _ theorem X_injective [Nontrivial R] : Function.Injective (X : σ → MvPolynomial σ R) := (monomial_left_injective one_ne_zero).comp (Finsupp.single_left_injective one_ne_zero) @[simp] theorem X_inj [Nontrivial R] (m n : σ) : X m = (X n : MvPolynomial σ R) ↔ m = n := X_injective.eq_iff theorem monomial_pow : monomial s a ^ e = monomial (e • s) (a ^ e) := AddMonoidAlgebra.single_pow e @[simp] theorem monomial_mul {s s' : σ →₀ ℕ} {a b : R} : monomial s a * monomial s' b = monomial (s + s') (a * b) := AddMonoidAlgebra.single_mul_single variable (σ R) /-- `fun s ↦ monomial s 1` as a homomorphism. -/ def monomialOneHom : Multiplicative (σ →₀ ℕ) →* MvPolynomial σ R := AddMonoidAlgebra.of _ _ variable {σ R} @[simp] theorem monomialOneHom_apply : monomialOneHom R σ s = (monomial s 1 : MvPolynomial σ R) := rfl theorem X_pow_eq_monomial : X n ^ e = monomial (Finsupp.single n e) (1 : R) := by simp [X, monomial_pow] theorem monomial_add_single : monomial (s + Finsupp.single n e) a = monomial s a * X n ^ e := by rw [X_pow_eq_monomial, monomial_mul, mul_one] theorem monomial_single_add : monomial (Finsupp.single n e + s) a = X n ^ e * monomial s a := by rw [X_pow_eq_monomial, monomial_mul, one_mul] theorem C_mul_X_pow_eq_monomial {s : σ} {a : R} {n : ℕ} : C a * X s ^ n = monomial (Finsupp.single s n) a := by rw [← zero_add (Finsupp.single s n), monomial_add_single, C_apply] theorem C_mul_X_eq_monomial {s : σ} {a : R} : C a * X s = monomial (Finsupp.single s 1) a := by rw [← C_mul_X_pow_eq_monomial, pow_one] @[simp] theorem monomial_zero {s : σ →₀ ℕ} : monomial s (0 : R) = 0 := Finsupp.single_zero _ @[simp] theorem monomial_zero' : (monomial (0 : σ →₀ ℕ) : R → MvPolynomial σ R) = C := rfl @[simp] theorem monomial_eq_zero {s : σ →₀ ℕ} {b : R} : monomial s b = 0 ↔ b = 0 := Finsupp.single_eq_zero @[simp] theorem sum_monomial_eq {A : Type*} [AddCommMonoid A] {u : σ →₀ ℕ} {r : R} {b : (σ →₀ ℕ) → R → A} (w : b u 0 = 0) : sum (monomial u r) b = b u r := Finsupp.sum_single_index w @[simp] theorem sum_C {A : Type*} [AddCommMonoid A] {b : (σ →₀ ℕ) → R → A} (w : b 0 0 = 0) : sum (C a) b = b 0 a := sum_monomial_eq w theorem monomial_sum_one {α : Type*} (s : Finset α) (f : α → σ →₀ ℕ) : (monomial (∑ i ∈ s, f i) 1 : MvPolynomial σ R) = ∏ i ∈ s, monomial (f i) 1 := map_prod (monomialOneHom R σ) (fun i => Multiplicative.ofAdd (f i)) s theorem monomial_sum_index {α : Type*} (s : Finset α) (f : α → σ →₀ ℕ) (a : R) : monomial (∑ i ∈ s, f i) a = C a * ∏ i ∈ s, monomial (f i) 1 := by rw [← monomial_sum_one, C_mul', ← (monomial _).map_smul, smul_eq_mul, mul_one] theorem monomial_finsupp_sum_index {α β : Type*} [Zero β] (f : α →₀ β) (g : α → β → σ →₀ ℕ) (a : R) : monomial (f.sum g) a = C a * f.prod fun a b => monomial (g a b) 1 := monomial_sum_index _ _ _ theorem monomial_eq_monomial_iff {α : Type*} (a₁ a₂ : α →₀ ℕ) (b₁ b₂ : R) : monomial a₁ b₁ = monomial a₂ b₂ ↔ a₁ = a₂ ∧ b₁ = b₂ ∨ b₁ = 0 ∧ b₂ = 0 := Finsupp.single_eq_single_iff _ _ _ _ theorem monomial_eq : monomial s a = C a * (s.prod fun n e => X n ^ e : MvPolynomial σ R) := by simp only [X_pow_eq_monomial, ← monomial_finsupp_sum_index, Finsupp.sum_single] @[simp] lemma prod_X_pow_eq_monomial : ∏ x ∈ s.support, X x ^ s x = monomial s (1 : R) := by simp only [monomial_eq, map_one, one_mul, Finsupp.prod] @[elab_as_elim] theorem induction_on_monomial {motive : MvPolynomial σ R → Prop} (C : ∀ a, motive (C a)) (mul_X : ∀ p n, motive p → motive (p * X n)) : ∀ s a, motive (monomial s a) := by intro s a apply @Finsupp.induction σ ℕ _ _ s · show motive (monomial 0 a) exact C a · intro n e p _hpn _he ih have : ∀ e : ℕ, motive (monomial p a * X n ^ e) := by intro e induction e with | zero => simp [ih] | succ e e_ih => simp [ih, pow_succ, (mul_assoc _ _ _).symm, mul_X, e_ih] simp [add_comm, monomial_add_single, this] /-- Analog of `Polynomial.induction_on'`. To prove something about mv_polynomials, it suffices to show the condition is closed under taking sums, and it holds for monomials. -/ @[elab_as_elim] theorem induction_on' {P : MvPolynomial σ R → Prop} (p : MvPolynomial σ R) (monomial : ∀ (u : σ →₀ ℕ) (a : R), P (monomial u a)) (add : ∀ p q : MvPolynomial σ R, P p → P q → P (p + q)) : P p := Finsupp.induction p (suffices P (MvPolynomial.monomial 0 0) by rwa [monomial_zero] at this show P (MvPolynomial.monomial 0 0) from monomial 0 0) fun _ _ _ _ha _hb hPf => add _ _ (monomial _ _) hPf /-- Similar to `MvPolynomial.induction_on` but only a weak form of `h_add` is required. In particular, this version only requires us to show that `motive` is closed under addition of nontrivial monomials not present in the support. -/ @[elab_as_elim] theorem monomial_add_induction_on {motive : MvPolynomial σ R → Prop} (p : MvPolynomial σ R) (C : ∀ a, motive (C a)) (monomial_add : ∀ (a : σ →₀ ℕ) (b : R) (f : MvPolynomial σ R), a ∉ f.support → b ≠ 0 → motive f → motive ((monomial a b) + f)) : motive p := Finsupp.induction p (C_0.rec <| C 0) monomial_add @[deprecated (since := "2025-03-11")] alias induction_on''' := monomial_add_induction_on /-- Similar to `MvPolynomial.induction_on` but only a yet weaker form of `h_add` is required. In particular, this version only requires us to show that `motive` is closed under addition of monomials not present in the support for which `motive` is already known to hold. -/ theorem induction_on'' {motive : MvPolynomial σ R → Prop} (p : MvPolynomial σ R) (C : ∀ a, motive (C a)) (monomial_add : ∀ (a : σ →₀ ℕ) (b : R) (f : MvPolynomial σ R), a ∉ f.support → b ≠ 0 → motive f → motive (monomial a b) → motive ((monomial a b) + f)) (mul_X : ∀ (p : MvPolynomial σ R) (n : σ), motive p → motive (p * MvPolynomial.X n)) : motive p := monomial_add_induction_on p C fun a b f ha hb hf => monomial_add a b f ha hb hf <| induction_on_monomial C mul_X a b /-- Analog of `Polynomial.induction_on`. If a property holds for any constant polynomial and is preserved under addition and multiplication by variables then it holds for all multivariate polynomials. -/ @[recursor 5] theorem induction_on {motive : MvPolynomial σ R → Prop} (p : MvPolynomial σ R) (C : ∀ a, motive (C a)) (add : ∀ p q, motive p → motive q → motive (p + q)) (mul_X : ∀ p n, motive p → motive (p * X n)) : motive p := induction_on'' p C (fun a b f _ha _hb hf hm => add (monomial a b) f hm hf) mul_X theorem ringHom_ext {A : Type*} [Semiring A] {f g : MvPolynomial σ R →+* A} (hC : ∀ r, f (C r) = g (C r)) (hX : ∀ i, f (X i) = g (X i)) : f = g := by refine AddMonoidAlgebra.ringHom_ext' ?_ ?_ -- Porting note (https://github.com/leanprover-community/mathlib4/issues/11041): this has high priority, but Lean still chooses `RingHom.ext`, why? -- probably because of the type synonym · ext x exact hC _ · apply Finsupp.mulHom_ext'; intros x -- Porting note (https://github.com/leanprover-community/mathlib4/issues/11041): `Finsupp.mulHom_ext'` needs to have increased priority apply MonoidHom.ext_mnat exact hX _ /-- See note [partially-applied ext lemmas]. -/ @[ext 1100] theorem ringHom_ext' {A : Type*} [Semiring A] {f g : MvPolynomial σ R →+* A} (hC : f.comp C = g.comp C) (hX : ∀ i, f (X i) = g (X i)) : f = g := ringHom_ext (RingHom.ext_iff.1 hC) hX theorem hom_eq_hom [Semiring S₂] (f g : MvPolynomial σ R →+* S₂) (hC : f.comp C = g.comp C) (hX : ∀ n : σ, f (X n) = g (X n)) (p : MvPolynomial σ R) : f p = g p := RingHom.congr_fun (ringHom_ext' hC hX) p theorem is_id (f : MvPolynomial σ R →+* MvPolynomial σ R) (hC : f.comp C = C) (hX : ∀ n : σ, f (X n) = X n) (p : MvPolynomial σ R) : f p = p := hom_eq_hom f (RingHom.id _) hC hX p @[ext 1100] theorem algHom_ext' {A B : Type*} [CommSemiring A] [CommSemiring B] [Algebra R A] [Algebra R B] {f g : MvPolynomial σ A →ₐ[R] B} (h₁ : f.comp (IsScalarTower.toAlgHom R A (MvPolynomial σ A)) = g.comp (IsScalarTower.toAlgHom R A (MvPolynomial σ A))) (h₂ : ∀ i, f (X i) = g (X i)) : f = g := AlgHom.coe_ringHom_injective (MvPolynomial.ringHom_ext' (congr_arg AlgHom.toRingHom h₁) h₂) @[ext 1200] theorem algHom_ext {A : Type*} [Semiring A] [Algebra R A] {f g : MvPolynomial σ R →ₐ[R] A} (hf : ∀ i : σ, f (X i) = g (X i)) : f = g := AddMonoidAlgebra.algHom_ext' (mulHom_ext' fun X : σ => MonoidHom.ext_mnat (hf X)) @[simp] theorem algHom_C {A : Type*} [Semiring A] [Algebra R A] (f : MvPolynomial σ R →ₐ[R] A) (r : R) : f (C r) = algebraMap R A r := f.commutes r @[simp] theorem adjoin_range_X : Algebra.adjoin R (range (X : σ → MvPolynomial σ R)) = ⊤ := by set S := Algebra.adjoin R (range (X : σ → MvPolynomial σ R)) refine top_unique fun p hp => ?_; clear hp induction p using MvPolynomial.induction_on with | C => exact S.algebraMap_mem _ | add p q hp hq => exact S.add_mem hp hq | mul_X p i hp => exact S.mul_mem hp (Algebra.subset_adjoin <| mem_range_self _) @[ext] theorem linearMap_ext {M : Type*} [AddCommMonoid M] [Module R M] {f g : MvPolynomial σ R →ₗ[R] M} (h : ∀ s, f ∘ₗ monomial s = g ∘ₗ monomial s) : f = g := Finsupp.lhom_ext' h section Support /-- The finite set of all `m : σ →₀ ℕ` such that `X^m` has a non-zero coefficient. -/ def support (p : MvPolynomial σ R) : Finset (σ →₀ ℕ) := Finsupp.support p theorem finsupp_support_eq_support (p : MvPolynomial σ R) : Finsupp.support p = p.support := rfl theorem support_monomial [h : Decidable (a = 0)] : (monomial s a).support = if a = 0 then ∅ else {s} := by rw [← Subsingleton.elim (Classical.decEq R a 0) h] rfl theorem support_monomial_subset : (monomial s a).support ⊆ {s} := support_single_subset theorem support_add [DecidableEq σ] : (p + q).support ⊆ p.support ∪ q.support := Finsupp.support_add theorem support_X [Nontrivial R] : (X n : MvPolynomial σ R).support = {Finsupp.single n 1} := by classical rw [X, support_monomial, if_neg]; exact one_ne_zero theorem support_X_pow [Nontrivial R] (s : σ) (n : ℕ) : (X s ^ n : MvPolynomial σ R).support = {Finsupp.single s n} := by classical rw [X_pow_eq_monomial, support_monomial, if_neg (one_ne_zero' R)] @[simp] theorem support_zero : (0 : MvPolynomial σ R).support = ∅ := rfl theorem support_smul {S₁ : Type*} [SMulZeroClass S₁ R] {a : S₁} {f : MvPolynomial σ R} : (a • f).support ⊆ f.support := Finsupp.support_smul theorem support_sum {α : Type*} [DecidableEq σ] {s : Finset α} {f : α → MvPolynomial σ R} : (∑ x ∈ s, f x).support ⊆ s.biUnion fun x => (f x).support := Finsupp.support_finset_sum end Support section Coeff /-- The coefficient of the monomial `m` in the multi-variable polynomial `p`. -/ def coeff (m : σ →₀ ℕ) (p : MvPolynomial σ R) : R := @DFunLike.coe ((σ →₀ ℕ) →₀ R) _ _ _ p m @[simp] theorem mem_support_iff {p : MvPolynomial σ R} {m : σ →₀ ℕ} : m ∈ p.support ↔ p.coeff m ≠ 0 := by simp [support, coeff] theorem not_mem_support_iff {p : MvPolynomial σ R} {m : σ →₀ ℕ} : m ∉ p.support ↔ p.coeff m = 0 := by simp theorem sum_def {A} [AddCommMonoid A] {p : MvPolynomial σ R} {b : (σ →₀ ℕ) → R → A} : p.sum b = ∑ m ∈ p.support, b m (p.coeff m) := by simp [support, Finsupp.sum, coeff] theorem support_mul [DecidableEq σ] (p q : MvPolynomial σ R) : (p * q).support ⊆ p.support + q.support := AddMonoidAlgebra.support_mul p q @[ext] theorem ext (p q : MvPolynomial σ R) : (∀ m, coeff m p = coeff m q) → p = q := Finsupp.ext @[simp] theorem coeff_add (m : σ →₀ ℕ) (p q : MvPolynomial σ R) : coeff m (p + q) = coeff m p + coeff m q := add_apply p q m @[simp] theorem coeff_smul {S₁ : Type*} [SMulZeroClass S₁ R] (m : σ →₀ ℕ) (C : S₁) (p : MvPolynomial σ R) : coeff m (C • p) = C • coeff m p := smul_apply C p m @[simp] theorem coeff_zero (m : σ →₀ ℕ) : coeff m (0 : MvPolynomial σ R) = 0 := rfl @[simp] theorem coeff_zero_X (i : σ) : coeff 0 (X i : MvPolynomial σ R) = 0 := single_eq_of_ne fun h => by cases Finsupp.single_eq_zero.1 h /-- `MvPolynomial.coeff m` but promoted to an `AddMonoidHom`. -/ @[simps] def coeffAddMonoidHom (m : σ →₀ ℕ) : MvPolynomial σ R →+ R where toFun := coeff m map_zero' := coeff_zero m map_add' := coeff_add m variable (R) in /-- `MvPolynomial.coeff m` but promoted to a `LinearMap`. -/ @[simps] def lcoeff (m : σ →₀ ℕ) : MvPolynomial σ R →ₗ[R] R where toFun := coeff m map_add' := coeff_add m map_smul' := coeff_smul m theorem coeff_sum {X : Type*} (s : Finset X) (f : X → MvPolynomial σ R) (m : σ →₀ ℕ) : coeff m (∑ x ∈ s, f x) = ∑ x ∈ s, coeff m (f x) := map_sum (@coeffAddMonoidHom R σ _ _) _ s theorem monic_monomial_eq (m) : monomial m (1 : R) = (m.prod fun n e => X n ^ e : MvPolynomial σ R) := by simp [monomial_eq] @[simp] theorem coeff_monomial [DecidableEq σ] (m n) (a) : coeff m (monomial n a : MvPolynomial σ R) = if n = m then a else 0 := Finsupp.single_apply @[simp] theorem coeff_C [DecidableEq σ] (m) (a) : coeff m (C a : MvPolynomial σ R) = if 0 = m then a else 0 := Finsupp.single_apply lemma eq_C_of_isEmpty [IsEmpty σ] (p : MvPolynomial σ R) : p = C (p.coeff 0) := by obtain ⟨x, rfl⟩ := C_surjective σ p simp theorem coeff_one [DecidableEq σ] (m) : coeff m (1 : MvPolynomial σ R) = if 0 = m then 1 else 0 := coeff_C m 1 @[simp] theorem coeff_zero_C (a) : coeff 0 (C a : MvPolynomial σ R) = a := single_eq_same @[simp] theorem coeff_zero_one : coeff 0 (1 : MvPolynomial σ R) = 1 := coeff_zero_C 1 theorem coeff_X_pow [DecidableEq σ] (i : σ) (m) (k : ℕ) : coeff m (X i ^ k : MvPolynomial σ R) = if Finsupp.single i k = m then 1 else 0 := by have := coeff_monomial m (Finsupp.single i k) (1 : R) rwa [@monomial_eq _ _ (1 : R) (Finsupp.single i k) _, C_1, one_mul, Finsupp.prod_single_index] at this exact pow_zero _ theorem coeff_X' [DecidableEq σ] (i : σ) (m) : coeff m (X i : MvPolynomial σ R) = if Finsupp.single i 1 = m then 1 else 0 := by rw [← coeff_X_pow, pow_one] @[simp] theorem coeff_X (i : σ) : coeff (Finsupp.single i 1) (X i : MvPolynomial σ R) = 1 := by classical rw [coeff_X', if_pos rfl] @[simp] theorem coeff_C_mul (m) (a : R) (p : MvPolynomial σ R) : coeff m (C a * p) = a * coeff m p := by classical rw [mul_def, sum_C] · simp +contextual [sum_def, coeff_sum] simp theorem coeff_mul [DecidableEq σ] (p q : MvPolynomial σ R) (n : σ →₀ ℕ) : coeff n (p * q) = ∑ x ∈ Finset.antidiagonal n, coeff x.1 p * coeff x.2 q := AddMonoidAlgebra.mul_apply_antidiagonal p q _ _ Finset.mem_antidiagonal @[simp] theorem coeff_mul_monomial (m) (s : σ →₀ ℕ) (r : R) (p : MvPolynomial σ R) : coeff (m + s) (p * monomial s r) = coeff m p * r := AddMonoidAlgebra.mul_single_apply_aux p _ _ _ _ fun _a _ => add_left_inj _ @[simp] theorem coeff_monomial_mul (m) (s : σ →₀ ℕ) (r : R) (p : MvPolynomial σ R) : coeff (s + m) (monomial s r * p) = r * coeff m p := AddMonoidAlgebra.single_mul_apply_aux p _ _ _ _ fun _a _ => add_right_inj _ @[simp] theorem coeff_mul_X (m) (s : σ) (p : MvPolynomial σ R) : coeff (m + Finsupp.single s 1) (p * X s) = coeff m p := (coeff_mul_monomial _ _ _ _).trans (mul_one _) @[simp] theorem coeff_X_mul (m) (s : σ) (p : MvPolynomial σ R) : coeff (Finsupp.single s 1 + m) (X s * p) = coeff m p := (coeff_monomial_mul _ _ _ _).trans (one_mul _) lemma coeff_single_X_pow [DecidableEq σ] (s s' : σ) (n n' : ℕ) : (X (R := R) s ^ n).coeff (Finsupp.single s' n') = if s = s' ∧ n = n' ∨ n = 0 ∧ n' = 0 then 1 else 0 := by simp only [coeff_X_pow, single_eq_single_iff] @[simp] lemma coeff_single_X [DecidableEq σ] (s s' : σ) (n : ℕ) : (X s).coeff (R := R) (Finsupp.single s' n) = if n = 1 ∧ s = s' then 1 else 0 := by simpa [eq_comm, and_comm] using coeff_single_X_pow s s' 1 n @[simp] theorem support_mul_X (s : σ) (p : MvPolynomial σ R) : (p * X s).support = p.support.map (addRightEmbedding (Finsupp.single s 1)) := AddMonoidAlgebra.support_mul_single p _ (by simp) _ @[simp] theorem support_X_mul (s : σ) (p : MvPolynomial σ R) : (X s * p).support = p.support.map (addLeftEmbedding (Finsupp.single s 1)) := AddMonoidAlgebra.support_single_mul p _ (by simp) _ @[simp] theorem support_smul_eq {S₁ : Type*} [Semiring S₁] [Module S₁ R] [NoZeroSMulDivisors S₁ R] {a : S₁} (h : a ≠ 0) (p : MvPolynomial σ R) : (a • p).support = p.support := Finsupp.support_smul_eq h theorem support_sdiff_support_subset_support_add [DecidableEq σ] (p q : MvPolynomial σ R) : p.support \ q.support ⊆ (p + q).support := by intro m hm simp only [Classical.not_not, mem_support_iff, Finset.mem_sdiff, Ne] at hm simp [hm.2, hm.1] open scoped symmDiff in theorem support_symmDiff_support_subset_support_add [DecidableEq σ] (p q : MvPolynomial σ R) : p.support ∆ q.support ⊆ (p + q).support := by rw [symmDiff_def, Finset.sup_eq_union] apply Finset.union_subset · exact support_sdiff_support_subset_support_add p q · rw [add_comm] exact support_sdiff_support_subset_support_add q p theorem coeff_mul_monomial' (m) (s : σ →₀ ℕ) (r : R) (p : MvPolynomial σ R) : coeff m (p * monomial s r) = if s ≤ m then coeff (m - s) p * r else 0 := by classical split_ifs with h · conv_rhs => rw [← coeff_mul_monomial _ s] congr with t rw [tsub_add_cancel_of_le h] · contrapose! h rw [← mem_support_iff] at h obtain ⟨j, -, rfl⟩ : ∃ j ∈ support p, j + s = m := by simpa [Finset.mem_add] using Finset.add_subset_add_left support_monomial_subset <| support_mul _ _ h exact le_add_left le_rfl theorem coeff_monomial_mul' (m) (s : σ →₀ ℕ) (r : R) (p : MvPolynomial σ R) : coeff m (monomial s r * p) = if s ≤ m then r * coeff (m - s) p else 0 := by -- note that if we allow `R` to be non-commutative we will have to duplicate the proof above. rw [mul_comm, mul_comm r] exact coeff_mul_monomial' _ _ _ _ theorem coeff_mul_X' [DecidableEq σ] (m) (s : σ) (p : MvPolynomial σ R) : coeff m (p * X s) = if s ∈ m.support then coeff (m - Finsupp.single s 1) p else 0 := by refine (coeff_mul_monomial' _ _ _ _).trans ?_ simp_rw [Finsupp.single_le_iff, Finsupp.mem_support_iff, Nat.succ_le_iff, pos_iff_ne_zero, mul_one] theorem coeff_X_mul' [DecidableEq σ] (m) (s : σ) (p : MvPolynomial σ R) : coeff m (X s * p) = if s ∈ m.support then coeff (m - Finsupp.single s 1) p else 0 := by refine (coeff_monomial_mul' _ _ _ _).trans ?_ simp_rw [Finsupp.single_le_iff, Finsupp.mem_support_iff, Nat.succ_le_iff, pos_iff_ne_zero, one_mul] theorem eq_zero_iff {p : MvPolynomial σ R} : p = 0 ↔ ∀ d, coeff d p = 0 := by rw [MvPolynomial.ext_iff] simp only [coeff_zero] theorem ne_zero_iff {p : MvPolynomial σ R} : p ≠ 0 ↔ ∃ d, coeff d p ≠ 0 := by rw [Ne, eq_zero_iff] push_neg rfl @[simp] theorem X_ne_zero [Nontrivial R] (s : σ) : X (R := R) s ≠ 0 := by rw [ne_zero_iff] use Finsupp.single s 1 simp only [coeff_X, ne_eq, one_ne_zero, not_false_eq_true] @[simp] theorem support_eq_empty {p : MvPolynomial σ R} : p.support = ∅ ↔ p = 0 := Finsupp.support_eq_empty @[simp] lemma support_nonempty {p : MvPolynomial σ R} : p.support.Nonempty ↔ p ≠ 0 := by rw [Finset.nonempty_iff_ne_empty, ne_eq, support_eq_empty] theorem exists_coeff_ne_zero {p : MvPolynomial σ R} (h : p ≠ 0) : ∃ d, coeff d p ≠ 0 := ne_zero_iff.mp h theorem C_dvd_iff_dvd_coeff (r : R) (φ : MvPolynomial σ R) : C r ∣ φ ↔ ∀ i, r ∣ φ.coeff i := by constructor · rintro ⟨φ, rfl⟩ c rw [coeff_C_mul] apply dvd_mul_right · intro h choose C hc using h classical let c' : (σ →₀ ℕ) → R := fun i => if i ∈ φ.support then C i else 0 let ψ : MvPolynomial σ R := ∑ i ∈ φ.support, monomial i (c' i) use ψ apply MvPolynomial.ext intro i simp only [ψ, c', coeff_C_mul, coeff_sum, coeff_monomial, Finset.sum_ite_eq'] split_ifs with hi · rw [hc] · rw [not_mem_support_iff] at hi rwa [mul_zero] @[simp] lemma isRegular_X : IsRegular (X n : MvPolynomial σ R) := by suffices IsLeftRegular (X n : MvPolynomial σ R) from ⟨this, this.right_of_commute <| Commute.all _⟩ intro P Q (hPQ : (X n) * P = (X n) * Q) ext i rw [← coeff_X_mul i n P, hPQ, coeff_X_mul i n Q] @[simp] lemma isRegular_X_pow (k : ℕ) : IsRegular (X n ^ k : MvPolynomial σ R) := isRegular_X.pow k @[simp] lemma isRegular_prod_X (s : Finset σ) : IsRegular (∏ n ∈ s, X n : MvPolynomial σ R) := IsRegular.prod fun _ _ ↦ isRegular_X /-- The finset of nonzero coefficients of a multivariate polynomial. -/ def coeffs (p : MvPolynomial σ R) : Finset R := letI := Classical.decEq R Finset.image p.coeff p.support @[simp] lemma coeffs_zero : coeffs (0 : MvPolynomial σ R) = ∅ := rfl lemma coeffs_one : coeffs (1 : MvPolynomial σ R) ⊆ {1} := by classical rw [coeffs, Finset.image_subset_iff] simp_all [coeff_one] @[nontriviality] lemma coeffs_eq_empty_of_subsingleton [Subsingleton R] (p : MvPolynomial σ R) : p.coeffs = ∅ := by simpa [coeffs] using Subsingleton.eq_zero p @[simp] lemma coeffs_one_of_nontrivial [Nontrivial R] : coeffs (1 : MvPolynomial σ R) = {1} := by apply Finset.Subset.antisymm coeffs_one simp only [coeffs, Finset.singleton_subset_iff, Finset.mem_image] exact ⟨0, by simp⟩ lemma mem_coeffs_iff {p : MvPolynomial σ R} {c : R} : c ∈ p.coeffs ↔ ∃ n ∈ p.support, c = p.coeff n := by simp [coeffs, eq_comm, (Finset.mem_image)] lemma coeff_mem_coeffs {p : MvPolynomial σ R} (m : σ →₀ ℕ) (h : p.coeff m ≠ 0) : p.coeff m ∈ p.coeffs := letI := Classical.decEq R Finset.mem_image_of_mem p.coeff (mem_support_iff.mpr h) lemma zero_not_mem_coeffs (p : MvPolynomial σ R) : 0 ∉ p.coeffs := by intro hz obtain ⟨n, hnsupp, hn⟩ := mem_coeffs_iff.mp hz exact (mem_support_iff.mp hnsupp) hn.symm end Coeff section ConstantCoeff /-- `constantCoeff p` returns the constant term of the polynomial `p`, defined as `coeff 0 p`. This is a ring homomorphism. -/ def constantCoeff : MvPolynomial σ R →+* R where toFun := coeff 0 map_one' := by simp [AddMonoidAlgebra.one_def] map_mul' := by classical simp [coeff_mul, Finsupp.support_single_ne_zero] map_zero' := coeff_zero _ map_add' := coeff_add _ theorem constantCoeff_eq : (constantCoeff : MvPolynomial σ R → R) = coeff 0 := rfl variable (σ) in @[simp] theorem constantCoeff_C (r : R) : constantCoeff (C r : MvPolynomial σ R) = r := by classical simp [constantCoeff_eq] variable (R) in @[simp] theorem constantCoeff_X (i : σ) : constantCoeff (X i : MvPolynomial σ R) = 0 := by simp [constantCoeff_eq] @[simp] theorem constantCoeff_smul {R : Type*} [SMulZeroClass R S₁] (a : R) (f : MvPolynomial σ S₁) : constantCoeff (a • f) = a • constantCoeff f := rfl theorem constantCoeff_monomial [DecidableEq σ] (d : σ →₀ ℕ) (r : R) : constantCoeff (monomial d r) = if d = 0 then r else 0 := by rw [constantCoeff_eq, coeff_monomial] variable (σ R) @[simp] theorem constantCoeff_comp_C : constantCoeff.comp (C : R →+* MvPolynomial σ R) = RingHom.id R := by ext x exact constantCoeff_C σ x theorem constantCoeff_comp_algebraMap : constantCoeff.comp (algebraMap R (MvPolynomial σ R)) = RingHom.id R := constantCoeff_comp_C _ _ end ConstantCoeff section AsSum @[simp] theorem support_sum_monomial_coeff (p : MvPolynomial σ R) : (∑ v ∈ p.support, monomial v (coeff v p)) = p := Finsupp.sum_single p theorem as_sum (p : MvPolynomial σ R) : p = ∑ v ∈ p.support, monomial v (coeff v p) := (support_sum_monomial_coeff p).symm end AsSum section coeffsIn variable {R S σ : Type*} [CommSemiring R] [CommSemiring S] section Module variable [Module R S] {M N : Submodule R S} {p : MvPolynomial σ S} {s : σ} {i : σ →₀ ℕ} {x : S} {n : ℕ} variable (σ M) in /-- The `R`-submodule of multivariate polynomials whose coefficients lie in a `R`-submodule `M`. -/ @[simps] def coeffsIn : Submodule R (MvPolynomial σ S) where carrier := {p | ∀ i, p.coeff i ∈ M} add_mem' := by simp+contextual [add_mem] zero_mem' := by simp smul_mem' := by simp+contextual [Submodule.smul_mem] lemma mem_coeffsIn : p ∈ coeffsIn σ M ↔ ∀ i, p.coeff i ∈ M := .rfl @[simp] lemma monomial_mem_coeffsIn : monomial i x ∈ coeffsIn σ M ↔ x ∈ M := by classical simp only [mem_coeffsIn, coeff_monomial] exact ⟨fun h ↦ by simpa using h i, fun hs j ↦ by split <;> simp [hs]⟩ @[simp] lemma C_mem_coeffsIn : C x ∈ coeffsIn σ M ↔ x ∈ M := by simpa using monomial_mem_coeffsIn (i := 0) @[simp] lemma one_coeffsIn : 1 ∈ coeffsIn σ M ↔ 1 ∈ M := by simpa using C_mem_coeffsIn (x := (1 : S)) @[simp] lemma mul_monomial_mem_coeffsIn : p * monomial i 1 ∈ coeffsIn σ M ↔ p ∈ coeffsIn σ M := by classical simp only [mem_coeffsIn, coeff_mul_monomial', Finsupp.mem_support_iff] constructor · rintro hp j simpa using hp (j + i) · rintro hp i split <;> simp [hp] @[simp] lemma monomial_mul_mem_coeffsIn : monomial i 1 * p ∈ coeffsIn σ M ↔ p ∈ coeffsIn σ M := by simp [mul_comm] @[simp] lemma mul_X_mem_coeffsIn : p * X s ∈ coeffsIn σ M ↔ p ∈ coeffsIn σ M := by simpa [-mul_monomial_mem_coeffsIn] using mul_monomial_mem_coeffsIn (i := .single s 1) @[simp] lemma X_mul_mem_coeffsIn : X s * p ∈ coeffsIn σ M ↔ p ∈ coeffsIn σ M := by simp [mul_comm] variable (M) in lemma coeffsIn_eq_span_monomial : coeffsIn σ M = .span R {monomial i m | (m ∈ M) (i : σ →₀ ℕ)} := by classical refine le_antisymm ?_ <| Submodule.span_le.2 ?_ · rintro p hp rw [p.as_sum] exact sum_mem fun i hi ↦ Submodule.subset_span ⟨_, hp i, _, rfl⟩ · rintro _ ⟨m, hm, s, n, rfl⟩ i simp [coeff_X_pow] split <;> simp [hm] lemma coeffsIn_le {N : Submodule R (MvPolynomial σ S)} : coeffsIn σ M ≤ N ↔ ∀ m ∈ M, ∀ i, monomial i m ∈ N := by simp [coeffsIn_eq_span_monomial, Submodule.span_le, Set.subset_def, forall_swap (α := MvPolynomial σ S)] end Module section Algebra variable [Algebra R S] {M : Submodule R S} lemma coeffsIn_mul (M N : Submodule R S) : coeffsIn σ (M * N) = coeffsIn σ M * coeffsIn σ N := by classical refine le_antisymm (coeffsIn_le.2 ?_) ?_ · intros r hr s induction hr using Submodule.mul_induction_on' with | mem_mul_mem m hm n hn => rw [← add_zero s, ← monomial_mul] apply Submodule.mul_mem_mul <;> simpa | add x _ y _ hx hy => simpa [map_add] using add_mem hx hy · rw [Submodule.mul_le] intros x hx y hy k rw [MvPolynomial.coeff_mul] exact sum_mem fun c hc ↦ Submodule.mul_mem_mul (hx _) (hy _) lemma coeffsIn_pow : ∀ {n}, n ≠ 0 → ∀ M : Submodule R S, coeffsIn σ (M ^ n) = coeffsIn σ M ^ n | 1, _, M => by simp | n + 2, _, M => by rw [pow_succ, coeffsIn_mul, coeffsIn_pow, ← pow_succ]; exact n.succ_ne_zero lemma le_coeffsIn_pow : ∀ {n}, coeffsIn σ M ^ n ≤ coeffsIn σ (M ^ n) | 0 => by simpa using ⟨1, map_one _⟩ | n + 1 => (coeffsIn_pow n.succ_ne_zero _).ge end Algebra end coeffsIn end CommSemiring end MvPolynomial
Mathlib/Algebra/MvPolynomial/Basic.lean
1,742
1,765
/- Copyright (c) 2024 Judith Ludwig, Christian Merten. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Judith Ludwig, Christian Merten -/ import Mathlib.RingTheory.AdicCompletion.Basic import Mathlib.RingTheory.AdicCompletion.Algebra import Mathlib.Algebra.DirectSum.Basic /-! # Functoriality of adic completions In this file we establish functorial properties of the adic completion. ## Main definitions - `AdicCauchySequence.map I f`: the linear map on `I`-adic cauchy sequences induced by `f` - `AdicCompletion.map I f`: the linear map on `I`-adic completions induced by `f` ## Main results - `sumEquivOfFintype`: adic completion commutes with finite sums - `piEquivOfFintype`: adic completion commutes with finite products -/ suppress_compilation variable {R : Type*} [CommRing R] (I : Ideal R) variable {M : Type*} [AddCommGroup M] [Module R M] variable {N : Type*} [AddCommGroup N] [Module R N] variable {P : Type*} [AddCommGroup P] [Module R P] variable {T : Type*} [AddCommGroup T] [Module (AdicCompletion I R) T] namespace LinearMap /-- `R`-linear version of `reduceModIdeal`. -/ private def reduceModIdealAux (f : M →ₗ[R] N) : M ⧸ (I • ⊤ : Submodule R M) →ₗ[R] N ⧸ (I • ⊤ : Submodule R N) := Submodule.mapQ (I • ⊤ : Submodule R M) (I • ⊤ : Submodule R N) f (fun x hx ↦ by refine Submodule.smul_induction_on hx (fun r hr x _ ↦ ?_) (fun x y hx hy ↦ ?_) · simp [Submodule.smul_mem_smul hr Submodule.mem_top] · simp [Submodule.add_mem _ hx hy]) @[local simp] private theorem reduceModIdealAux_apply (f : M →ₗ[R] N) (x : M) : (f.reduceModIdealAux I) (Submodule.Quotient.mk (p := (I • ⊤ : Submodule R M)) x) = Submodule.Quotient.mk (p := (I • ⊤ : Submodule R N)) (f x) := rfl /-- The induced linear map on the quotients mod `I • ⊤`. -/ def reduceModIdeal (f : M →ₗ[R] N) : M ⧸ (I • ⊤ : Submodule R M) →ₗ[R ⧸ I] N ⧸ (I • ⊤ : Submodule R N) where toFun := f.reduceModIdealAux I map_add' := by simp map_smul' r x := by refine Quotient.inductionOn' r (fun r ↦ ?_) refine Quotient.inductionOn' x (fun x ↦ ?_) simp only [Submodule.Quotient.mk''_eq_mk, Ideal.Quotient.mk_eq_mk, Module.Quotient.mk_smul_mk, Submodule.Quotient.mk_smul, LinearMapClass.map_smul, reduceModIdealAux_apply, RingHomCompTriple.comp_apply] @[simp] theorem reduceModIdeal_apply (f : M →ₗ[R] N) (x : M) : (f.reduceModIdeal I) (Submodule.Quotient.mk (p := (I • ⊤ : Submodule R M)) x) = Submodule.Quotient.mk (p := (I • ⊤ : Submodule R N)) (f x) := rfl end LinearMap namespace AdicCompletion open LinearMap theorem transitionMap_comp_reduceModIdeal (f : M →ₗ[R] N) {m n : ℕ} (hmn : m ≤ n) : transitionMap I N hmn ∘ₗ f.reduceModIdeal (I ^ n) = (f.reduceModIdeal (I ^ m) : _ →ₗ[R] _) ∘ₗ transitionMap I M hmn := by ext x simp namespace AdicCauchySequence /-- A linear map induces a linear map on adic cauchy sequences. -/ @[simps] def map (f : M →ₗ[R] N) : AdicCauchySequence I M →ₗ[R] AdicCauchySequence I N where toFun a := ⟨fun n ↦ f (a n), fun {m n} hmn ↦ by have hm : Submodule.map f (I ^ m • ⊤ : Submodule R M) ≤ (I ^ m • ⊤ : Submodule R N) := by rw [Submodule.map_smul''] exact smul_mono_right _ le_top apply SModEq.mono hm apply SModEq.map (a.property hmn) f⟩ map_add' a b := by ext n; simp map_smul' r a := by ext n; simp variable (M) in @[simp] theorem map_id : map I (LinearMap.id (M := M)) = LinearMap.id := rfl theorem map_comp (f : M →ₗ[R] N) (g : N →ₗ[R] P) : map I g ∘ₗ map I f = map I (g ∘ₗ f) := rfl theorem map_comp_apply (f : M →ₗ[R] N) (g : N →ₗ[R] P) (a : AdicCauchySequence I M) : map I g (map I f a) = map I (g ∘ₗ f) a := rfl @[simp] theorem map_zero : map I (0 : M →ₗ[R] N) = 0 := rfl end AdicCauchySequence /-- `R`-linear version of `adicCompletion`. -/ private def adicCompletionAux (f : M →ₗ[R] N) : AdicCompletion I M →ₗ[R] AdicCompletion I N := AdicCompletion.lift I (fun n ↦ reduceModIdeal (I ^ n) f ∘ₗ AdicCompletion.eval I M n) (fun {m n} hmn ↦ by rw [← comp_assoc, AdicCompletion.transitionMap_comp_reduceModIdeal, comp_assoc, transitionMap_comp_eval]) @[local simp] private theorem adicCompletionAux_val_apply (f : M →ₗ[R] N) {n : ℕ} (x : AdicCompletion I M) : (adicCompletionAux I f x).val n = f.reduceModIdeal (I ^ n) (x.val n) := rfl /-- A linear map induces a map on adic completions. -/ def map (f : M →ₗ[R] N) : AdicCompletion I M →ₗ[AdicCompletion I R] AdicCompletion I N where toFun := adicCompletionAux I f map_add' := by simp map_smul' r x := by ext n simp only [adicCompletionAux_val_apply, smul_eval, smul_eq_mul, RingHom.id_apply] rw [val_smul_eq_evalₐ_smul, val_smul_eq_evalₐ_smul, map_smul] @[simp] theorem map_val_apply (f : M →ₗ[R] N) {n : ℕ} (x : AdicCompletion I M) : (map I f x).val n = f.reduceModIdeal (I ^ n) (x.val n) := rfl /-- Equality of maps out of an adic completion can be checked on Cauchy sequences. -/ theorem map_ext {N} {f g : AdicCompletion I M → N} (h : ∀ (a : AdicCauchySequence I M), f (AdicCompletion.mk I M a) = g (AdicCompletion.mk I M a)) : f = g := by ext x apply induction_on I M x h /-- Equality of linear maps out of an adic completion can be checked on Cauchy sequences. -/ @[ext] theorem map_ext' {f g : AdicCompletion I M →ₗ[AdicCompletion I R] T} (h : ∀ (a : AdicCauchySequence I M), f (AdicCompletion.mk I M a) = g (AdicCompletion.mk I M a)) : f = g := by ext x apply induction_on I M x h /-- Equality of linear maps out of an adic completion can be checked on Cauchy sequences. -/ @[ext] theorem map_ext'' {f g : AdicCompletion I M →ₗ[R] N} (h : f.comp (AdicCompletion.mk I M) = g.comp (AdicCompletion.mk I M)) : f = g := by ext x apply induction_on I M x (fun a ↦ LinearMap.ext_iff.mp h a) variable (M) in @[simp] theorem map_id : map I (LinearMap.id (M := M)) = LinearMap.id (R := AdicCompletion I R) (M := AdicCompletion I M) := by ext a n simp theorem map_comp (f : M →ₗ[R] N) (g : N →ₗ[R] P) : map I g ∘ₗ map I f = map I (g ∘ₗ f) := by ext simp theorem map_comp_apply (f : M →ₗ[R] N) (g : N →ₗ[R] P) (x : AdicCompletion I M) : map I g (map I f x) = map I (g ∘ₗ f) x := by show (map I g ∘ₗ map I f) x = map I (g ∘ₗ f) x rw [map_comp] @[simp] theorem map_mk (f : M →ₗ[R] N) (a : AdicCauchySequence I M) : map I f (AdicCompletion.mk I M a) = AdicCompletion.mk I N (AdicCauchySequence.map I f a) := rfl @[simp] theorem map_zero : map I (0 : M →ₗ[R] N) = 0 := by ext simp /-- A linear equiv induces a linear equiv on adic completions. -/ def congr (f : M ≃ₗ[R] N) : AdicCompletion I M ≃ₗ[AdicCompletion I R] AdicCompletion I N := LinearEquiv.ofLinear (map I f) (map I f.symm) (by simp [map_comp]) (by simp [map_comp]) @[simp] theorem congr_apply (f : M ≃ₗ[R] N) (x : AdicCompletion I M) : congr I f x = map I f x := rfl @[simp] theorem congr_symm_apply (f : M ≃ₗ[R] N) (x : AdicCompletion I N) : (congr I f).symm x = map I f.symm x := rfl section Families /-! ### Adic completion in families In this section we consider a family `M : ι → Type*` of `R`-modules. Purely from the formal properties of adic completions we obtain two canonical maps - `AdicCompleiton I (∀ j, M j) →ₗ[R] ∀ j, AdicCompletion I (M j)` - `(⨁ j, (AdicCompletion I (M j))) →ₗ[R] AdicCompletion I (⨁ j, M j)` If `ι` is finite, both are isomorphisms and, modulo the equivalence `⨁ j, (AdicCompletion I (M j)` and `∀ j, AdicCompletion I (M j)`, inverse to each other. -/ variable {ι : Type*} (M : ι → Type*) [∀ i, AddCommGroup (M i)] [∀ i, Module R (M i)] section Pi /-- The canonical map from the adic completion of the product to the product of the adic completions. -/ @[simps!] def pi : AdicCompletion I (∀ j, M j) →ₗ[AdicCompletion I R] ∀ j, AdicCompletion I (M j) := LinearMap.pi (fun j ↦ map I (LinearMap.proj j)) end Pi section Sum open DirectSum /-- The canonical map from the sum of the adic completions to the adic completion of the sum. -/ def sum [DecidableEq ι] : (⨁ j, (AdicCompletion I (M j))) →ₗ[AdicCompletion I R] AdicCompletion I (⨁ j, M j) := toModule (AdicCompletion I R) ι (AdicCompletion I (⨁ j, M j)) (fun j ↦ map I (lof R ι M j)) @[simp] theorem sum_lof [DecidableEq ι] (j : ι) (x : AdicCompletion I (M j)) : sum I M ((DirectSum.lof (AdicCompletion I R) ι (fun i ↦ AdicCompletion I (M i)) j) x) = map I (lof R ι M j) x := by simp [sum] @[simp] theorem sum_of [DecidableEq ι] (j : ι) (x : AdicCompletion I (M j)) : sum I M ((DirectSum.of (fun i ↦ AdicCompletion I (M i)) j) x) = map I (lof R ι M j) x := by rw [← lof_eq_of R] apply sum_lof variable [Fintype ι] /-- If `ι` is finite, we use the equivalence of sum and product to obtain an inverse for `AdicCompletion.sum` from `AdicCompletion.pi`. -/ def sumInv : AdicCompletion I (⨁ j, M j) →ₗ[AdicCompletion I R] (⨁ j, (AdicCompletion I (M j))) := letI f := map I (linearEquivFunOnFintype R ι M) letI g := linearEquivFunOnFintype (AdicCompletion I R) ι (fun j ↦ AdicCompletion I (M j)) g.symm.toLinearMap ∘ₗ pi I M ∘ₗ f @[simp] theorem component_sumInv (x : AdicCompletion I (⨁ j, M j)) (j : ι) : component (AdicCompletion I R) ι _ j (sumInv I M x) = map I (component R ι _ j) x := by apply induction_on I _ x (fun x ↦ ?_)
rfl @[simp] theorem sumInv_apply (x : AdicCompletion I (⨁ j, M j)) (j : ι) : (sumInv I M x) j = map I (component R ι _ j) x := by
Mathlib/RingTheory/AdicCompletion/Functoriality.lean
279
283
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Jeremy Avigad -/ import Mathlib.Data.Set.Finite.Basic import Mathlib.Data.Set.Finite.Range import Mathlib.Data.Set.Lattice import Mathlib.Topology.Defs.Filter /-! # Openness and closedness of a set This file provides lemmas relating to the predicates `IsOpen` and `IsClosed` of a set endowed with a topology. ## Implementation notes Topology in mathlib heavily uses filters (even more than in Bourbaki). See explanations in <https://leanprover-community.github.io/theories/topology.html>. ## References * [N. Bourbaki, *General Topology*][bourbaki1966] * [I. M. James, *Topologies and Uniformities*][james1999] ## Tags topological space -/ open Set Filter Topology universe u v /-- A constructor for topologies by specifying the closed sets, and showing that they satisfy the appropriate conditions. -/ def TopologicalSpace.ofClosed {X : Type u} (T : Set (Set X)) (empty_mem : ∅ ∈ T) (sInter_mem : ∀ A, A ⊆ T → ⋂₀ A ∈ T) (union_mem : ∀ A, A ∈ T → ∀ B, B ∈ T → A ∪ B ∈ T) : TopologicalSpace X where IsOpen X := Xᶜ ∈ T isOpen_univ := by simp [empty_mem] isOpen_inter s t hs ht := by simpa only [compl_inter] using union_mem sᶜ hs tᶜ ht isOpen_sUnion s hs := by simp only [Set.compl_sUnion] exact sInter_mem (compl '' s) fun z ⟨y, hy, hz⟩ => hz ▸ hs y hy section TopologicalSpace variable {X : Type u} {ι : Sort v} {α : Type*} {x : X} {s s₁ s₂ t : Set X} {p p₁ p₂ : X → Prop} lemma isOpen_mk {p h₁ h₂ h₃} : IsOpen[⟨p, h₁, h₂, h₃⟩] s ↔ p s := Iff.rfl @[ext (iff := false)] protected theorem TopologicalSpace.ext : ∀ {f g : TopologicalSpace X}, IsOpen[f] = IsOpen[g] → f = g | ⟨_, _, _, _⟩, ⟨_, _, _, _⟩, rfl => rfl protected theorem TopologicalSpace.ext_iff {t t' : TopologicalSpace X} : t = t' ↔ ∀ s, IsOpen[t] s ↔ IsOpen[t'] s := ⟨fun h _ => h ▸ Iff.rfl, fun h => by ext; exact h _⟩ theorem isOpen_fold {t : TopologicalSpace X} : t.IsOpen s = IsOpen[t] s := rfl variable [TopologicalSpace X] theorem isOpen_iUnion {f : ι → Set X} (h : ∀ i, IsOpen (f i)) : IsOpen (⋃ i, f i) := isOpen_sUnion (forall_mem_range.2 h) theorem isOpen_biUnion {s : Set α} {f : α → Set X} (h : ∀ i ∈ s, IsOpen (f i)) : IsOpen (⋃ i ∈ s, f i) := isOpen_iUnion fun i => isOpen_iUnion fun hi => h i hi theorem IsOpen.union (h₁ : IsOpen s₁) (h₂ : IsOpen s₂) : IsOpen (s₁ ∪ s₂) := by rw [union_eq_iUnion]; exact isOpen_iUnion (Bool.forall_bool.2 ⟨h₂, h₁⟩) lemma isOpen_iff_of_cover {f : α → Set X} (ho : ∀ i, IsOpen (f i)) (hU : (⋃ i, f i) = univ) : IsOpen s ↔ ∀ i, IsOpen (f i ∩ s) := by refine ⟨fun h i ↦ (ho i).inter h, fun h ↦ ?_⟩ rw [← s.inter_univ, inter_comm, ← hU, iUnion_inter] exact isOpen_iUnion fun i ↦ h i @[simp] theorem isOpen_empty : IsOpen (∅ : Set X) := by rw [← sUnion_empty]; exact isOpen_sUnion fun a => False.elim theorem Set.Finite.isOpen_sInter {s : Set (Set X)} (hs : s.Finite) (h : ∀ t ∈ s, IsOpen t) : IsOpen (⋂₀ s) := by induction s, hs using Set.Finite.induction_on with | empty => rw [sInter_empty]; exact isOpen_univ | insert _ _ ih => simp only [sInter_insert, forall_mem_insert] at h ⊢ exact h.1.inter (ih h.2) theorem Set.Finite.isOpen_biInter {s : Set α} {f : α → Set X} (hs : s.Finite) (h : ∀ i ∈ s, IsOpen (f i)) : IsOpen (⋂ i ∈ s, f i) := sInter_image f s ▸ (hs.image _).isOpen_sInter (forall_mem_image.2 h) theorem isOpen_iInter_of_finite [Finite ι] {s : ι → Set X} (h : ∀ i, IsOpen (s i)) : IsOpen (⋂ i, s i) := (finite_range _).isOpen_sInter (forall_mem_range.2 h) theorem isOpen_biInter_finset {s : Finset α} {f : α → Set X} (h : ∀ i ∈ s, IsOpen (f i)) : IsOpen (⋂ i ∈ s, f i) := s.finite_toSet.isOpen_biInter h @[simp] theorem isOpen_const {p : Prop} : IsOpen { _x : X | p } := by by_cases p <;> simp [*] theorem IsOpen.and : IsOpen { x | p₁ x } → IsOpen { x | p₂ x } → IsOpen { x | p₁ x ∧ p₂ x } := IsOpen.inter @[simp] theorem isOpen_compl_iff : IsOpen sᶜ ↔ IsClosed s := ⟨fun h => ⟨h⟩, fun h => h.isOpen_compl⟩ theorem TopologicalSpace.ext_iff_isClosed {X} {t₁ t₂ : TopologicalSpace X} : t₁ = t₂ ↔ ∀ s, IsClosed[t₁] s ↔ IsClosed[t₂] s := by rw [TopologicalSpace.ext_iff, compl_surjective.forall] simp only [@isOpen_compl_iff _ _ t₁, @isOpen_compl_iff _ _ t₂] alias ⟨_, TopologicalSpace.ext_isClosed⟩ := TopologicalSpace.ext_iff_isClosed theorem isClosed_const {p : Prop} : IsClosed { _x : X | p } := ⟨isOpen_const (p := ¬p)⟩ @[simp] theorem isClosed_empty : IsClosed (∅ : Set X) := isClosed_const @[simp] theorem isClosed_univ : IsClosed (univ : Set X) := isClosed_const lemma IsOpen.isLocallyClosed (hs : IsOpen s) : IsLocallyClosed s := ⟨_, _, hs, isClosed_univ, (inter_univ _).symm⟩ lemma IsClosed.isLocallyClosed (hs : IsClosed s) : IsLocallyClosed s := ⟨_, _, isOpen_univ, hs, (univ_inter _).symm⟩ theorem IsClosed.union : IsClosed s₁ → IsClosed s₂ → IsClosed (s₁ ∪ s₂) := by simpa only [← isOpen_compl_iff, compl_union] using IsOpen.inter theorem isClosed_sInter {s : Set (Set X)} : (∀ t ∈ s, IsClosed t) → IsClosed (⋂₀ s) := by simpa only [← isOpen_compl_iff, compl_sInter, sUnion_image] using isOpen_biUnion theorem isClosed_iInter {f : ι → Set X} (h : ∀ i, IsClosed (f i)) : IsClosed (⋂ i, f i) := isClosed_sInter <| forall_mem_range.2 h theorem isClosed_biInter {s : Set α} {f : α → Set X} (h : ∀ i ∈ s, IsClosed (f i)) : IsClosed (⋂ i ∈ s, f i) := isClosed_iInter fun i => isClosed_iInter <| h i @[simp] theorem isClosed_compl_iff {s : Set X} : IsClosed sᶜ ↔ IsOpen s := by rw [← isOpen_compl_iff, compl_compl] alias ⟨_, IsOpen.isClosed_compl⟩ := isClosed_compl_iff theorem IsOpen.sdiff (h₁ : IsOpen s) (h₂ : IsClosed t) : IsOpen (s \ t) := IsOpen.inter h₁ h₂.isOpen_compl theorem IsClosed.inter (h₁ : IsClosed s₁) (h₂ : IsClosed s₂) : IsClosed (s₁ ∩ s₂) := by rw [← isOpen_compl_iff] at * rw [compl_inter] exact IsOpen.union h₁ h₂ theorem IsClosed.sdiff (h₁ : IsClosed s) (h₂ : IsOpen t) : IsClosed (s \ t) := IsClosed.inter h₁ (isClosed_compl_iff.mpr h₂) theorem Set.Finite.isClosed_biUnion {s : Set α} {f : α → Set X} (hs : s.Finite) (h : ∀ i ∈ s, IsClosed (f i)) : IsClosed (⋃ i ∈ s, f i) := by simp only [← isOpen_compl_iff, compl_iUnion] at * exact hs.isOpen_biInter h lemma isClosed_biUnion_finset {s : Finset α} {f : α → Set X} (h : ∀ i ∈ s, IsClosed (f i)) : IsClosed (⋃ i ∈ s, f i) := s.finite_toSet.isClosed_biUnion h theorem isClosed_iUnion_of_finite [Finite ι] {s : ι → Set X} (h : ∀ i, IsClosed (s i)) : IsClosed (⋃ i, s i) := by simp only [← isOpen_compl_iff, compl_iUnion] at * exact isOpen_iInter_of_finite h theorem isClosed_imp {p q : X → Prop} (hp : IsOpen { x | p x }) (hq : IsClosed { x | q x }) : IsClosed { x | p x → q x } := by simpa only [imp_iff_not_or] using hp.isClosed_compl.union hq theorem IsClosed.not : IsClosed { a | p a } → IsOpen { a | ¬p a } := isOpen_compl_iff.mpr /-! ### Limits of filters in topological spaces In this section we define functions that return a limit of a filter (or of a function along a filter), if it exists, and a random point otherwise. These functions are rarely used in Mathlib, most of the theorems are written using `Filter.Tendsto`. One of the reasons is that `Filter.limUnder f g = x` is not equivalent to `Filter.Tendsto g f (𝓝 x)` unless the codomain is a Hausdorff space and `g` has a limit along `f`. -/ section lim /-- If a filter `f` is majorated by some `𝓝 x`, then it is majorated by `𝓝 (Filter.lim f)`. We formulate this lemma with a `[Nonempty X]` argument of `lim` derived from `h` to make it useful for types without a `[Nonempty X]` instance. Because of the built-in proof irrelevance, Lean will unify this instance with any other instance. -/ theorem le_nhds_lim {f : Filter X} (h : ∃ x, f ≤ 𝓝 x) : f ≤ 𝓝 (@lim _ _ (nonempty_of_exists h) f) := Classical.epsilon_spec h /-- If `g` tends to some `𝓝 x` along `f`, then it tends to `𝓝 (Filter.limUnder f g)`. We formulate this lemma with a `[Nonempty X]` argument of `lim` derived from `h` to make it useful for types without a `[Nonempty X]` instance. Because of the built-in proof irrelevance, Lean will unify this instance with any other instance. -/ theorem tendsto_nhds_limUnder {f : Filter α} {g : α → X} (h : ∃ x, Tendsto g f (𝓝 x)) : Tendsto g f (𝓝 (@limUnder _ _ _ (nonempty_of_exists h) f g)) := le_nhds_lim h theorem limUnder_of_not_tendsto [hX : Nonempty X] {f : Filter α} {g : α → X} (h : ¬ ∃ x, Tendsto g f (𝓝 x)) : limUnder f g = Classical.choice hX := by simp_rw [Tendsto] at h simp_rw [limUnder, lim, Classical.epsilon, Classical.strongIndefiniteDescription, dif_neg h] end lim end TopologicalSpace
Mathlib/Topology/Basic.lean
551
552
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jeremy Avigad, Minchao Wu, Mario Carneiro -/ import Mathlib.Data.Finset.Attach import Mathlib.Data.Finset.Disjoint import Mathlib.Data.Finset.Erase import Mathlib.Data.Finset.Filter import Mathlib.Data.Finset.Range import Mathlib.Data.Finset.SDiff import Mathlib.Data.Multiset.Basic import Mathlib.Logic.Equiv.Set import Mathlib.Order.Directed import Mathlib.Order.Interval.Set.Defs import Mathlib.Data.Set.SymmDiff /-! # Basic lemmas on finite sets This file contains lemmas on the interaction of various definitions on the `Finset` type. For an explanation of `Finset` design decisions, please see `Mathlib/Data/Finset/Defs.lean`. ## Main declarations ### Main definitions * `Finset.choose`: Given a proof `h` of existence and uniqueness of a certain element satisfying a predicate, `choose s h` returns the element of `s` satisfying that predicate. ### Equivalences between finsets * The `Mathlib/Logic/Equiv/Defs.lean` file describes a general type of equivalence, so look in there for any lemmas. There is some API for rewriting sums and products from `s` to `t` given that `s ≃ t`. TODO: examples ## Tags finite sets, finset -/ -- Assert that we define `Finset` without the material on `List.sublists`. -- Note that we cannot use `List.sublists` itself as that is defined very early. assert_not_exists List.sublistsLen Multiset.powerset CompleteLattice Monoid open Multiset Subtype Function universe u variable {α : Type*} {β : Type*} {γ : Type*} namespace Finset -- TODO: these should be global attributes, but this will require fixing other files attribute [local trans] Subset.trans Superset.trans set_option linter.deprecated false in @[deprecated "Deprecated without replacement." (since := "2025-02-07")] theorem sizeOf_lt_sizeOf_of_mem [SizeOf α] {x : α} {s : Finset α} (hx : x ∈ s) : SizeOf.sizeOf x < SizeOf.sizeOf s := by cases s dsimp [SizeOf.sizeOf, SizeOf.sizeOf, Multiset.sizeOf] rw [Nat.add_comm] refine lt_trans ?_ (Nat.lt_succ_self _) exact Multiset.sizeOf_lt_sizeOf_of_mem hx /-! ### Lattice structure -/ section Lattice variable [DecidableEq α] {s s₁ s₂ t t₁ t₂ u v : Finset α} {a b : α} /-! #### union -/ @[simp] theorem disjUnion_eq_union (s t h) : @disjUnion α s t h = s ∪ t := ext fun a => by simp @[simp] theorem disjoint_union_left : Disjoint (s ∪ t) u ↔ Disjoint s u ∧ Disjoint t u := by simp only [disjoint_left, mem_union, or_imp, forall_and] @[simp] theorem disjoint_union_right : Disjoint s (t ∪ u) ↔ Disjoint s t ∧ Disjoint s u := by simp only [disjoint_right, mem_union, or_imp, forall_and] /-! #### inter -/ theorem not_disjoint_iff_nonempty_inter : ¬Disjoint s t ↔ (s ∩ t).Nonempty := not_disjoint_iff.trans <| by simp [Finset.Nonempty] alias ⟨_, Nonempty.not_disjoint⟩ := not_disjoint_iff_nonempty_inter theorem disjoint_or_nonempty_inter (s t : Finset α) : Disjoint s t ∨ (s ∩ t).Nonempty := by rw [← not_disjoint_iff_nonempty_inter] exact em _ omit [DecidableEq α] in theorem disjoint_of_subset_iff_left_eq_empty (h : s ⊆ t) : Disjoint s t ↔ s = ∅ := disjoint_of_le_iff_left_eq_bot h lemma pairwiseDisjoint_iff {ι : Type*} {s : Set ι} {f : ι → Finset α} : s.PairwiseDisjoint f ↔ ∀ ⦃i⦄, i ∈ s → ∀ ⦃j⦄, j ∈ s → (f i ∩ f j).Nonempty → i = j := by simp [Set.PairwiseDisjoint, Set.Pairwise, Function.onFun, not_imp_comm (a := _ = _), not_disjoint_iff_nonempty_inter] end Lattice instance isDirected_le : IsDirected (Finset α) (· ≤ ·) := by classical infer_instance instance isDirected_subset : IsDirected (Finset α) (· ⊆ ·) := isDirected_le /-! ### erase -/ section Erase variable [DecidableEq α] {s t u v : Finset α} {a b : α} @[simp] theorem erase_empty (a : α) : erase ∅ a = ∅ := rfl protected lemma Nontrivial.erase_nonempty (hs : s.Nontrivial) : (s.erase a).Nonempty := (hs.exists_ne a).imp <| by aesop @[simp] lemma erase_nonempty (ha : a ∈ s) : (s.erase a).Nonempty ↔ s.Nontrivial := by simp only [Finset.Nonempty, mem_erase, and_comm (b := _ ∈ _)] refine ⟨?_, fun hs ↦ hs.exists_ne a⟩ rintro ⟨b, hb, hba⟩ exact ⟨_, hb, _, ha, hba⟩ @[simp] theorem erase_singleton (a : α) : ({a} : Finset α).erase a = ∅ := by ext x simp @[simp] theorem erase_insert_eq_erase (s : Finset α) (a : α) : (insert a s).erase a = s.erase a := ext fun x => by simp +contextual only [mem_erase, mem_insert, and_congr_right_iff, false_or, iff_self, imp_true_iff] theorem erase_insert {a : α} {s : Finset α} (h : a ∉ s) : erase (insert a s) a = s := by rw [erase_insert_eq_erase, erase_eq_of_not_mem h] theorem erase_insert_of_ne {a b : α} {s : Finset α} (h : a ≠ b) : erase (insert a s) b = insert a (erase s b) := ext fun x => by have : x ≠ b ∧ x = a ↔ x = a := and_iff_right_of_imp fun hx => hx.symm ▸ h simp only [mem_erase, mem_insert, and_or_left, this] theorem erase_cons_of_ne {a b : α} {s : Finset α} (ha : a ∉ s) (hb : a ≠ b) : erase (cons a s ha) b = cons a (erase s b) fun h => ha <| erase_subset _ _ h := by simp only [cons_eq_insert, erase_insert_of_ne hb] @[simp] theorem insert_erase (h : a ∈ s) : insert a (erase s a) = s := ext fun x => by simp only [mem_insert, mem_erase, or_and_left, dec_em, true_and] apply or_iff_right_of_imp rintro rfl exact h lemma erase_eq_iff_eq_insert (hs : a ∈ s) (ht : a ∉ t) : erase s a = t ↔ s = insert a t := by aesop lemma insert_erase_invOn : Set.InvOn (insert a) (fun s ↦ erase s a) {s : Finset α | a ∈ s} {s : Finset α | a ∉ s} := ⟨fun _s ↦ insert_erase, fun _s ↦ erase_insert⟩ theorem erase_ssubset {a : α} {s : Finset α} (h : a ∈ s) : s.erase a ⊂ s := calc s.erase a ⊂ insert a (s.erase a) := ssubset_insert <| not_mem_erase _ _ _ = _ := insert_erase h theorem ssubset_iff_exists_subset_erase {s t : Finset α} : s ⊂ t ↔ ∃ a ∈ t, s ⊆ t.erase a := by refine ⟨fun h => ?_, fun ⟨a, ha, h⟩ => ssubset_of_subset_of_ssubset h <| erase_ssubset ha⟩ obtain ⟨a, ht, hs⟩ := not_subset.1 h.2 exact ⟨a, ht, subset_erase.2 ⟨h.1, hs⟩⟩ theorem erase_ssubset_insert (s : Finset α) (a : α) : s.erase a ⊂ insert a s := ssubset_iff_exists_subset_erase.2 ⟨a, mem_insert_self _ _, erase_subset_erase _ <| subset_insert _ _⟩ theorem erase_cons {s : Finset α} {a : α} (h : a ∉ s) : (s.cons a h).erase a = s := by rw [cons_eq_insert, erase_insert_eq_erase, erase_eq_of_not_mem h] theorem subset_insert_iff {a : α} {s t : Finset α} : s ⊆ insert a t ↔ erase s a ⊆ t := by simp only [subset_iff, or_iff_not_imp_left, mem_erase, mem_insert, and_imp] exact forall_congr' fun x => forall_swap theorem erase_insert_subset (a : α) (s : Finset α) : erase (insert a s) a ⊆ s := subset_insert_iff.1 <| Subset.rfl theorem insert_erase_subset (a : α) (s : Finset α) : s ⊆ insert a (erase s a) := subset_insert_iff.2 <| Subset.rfl theorem subset_insert_iff_of_not_mem (h : a ∉ s) : s ⊆ insert a t ↔ s ⊆ t := by rw [subset_insert_iff, erase_eq_of_not_mem h] theorem erase_subset_iff_of_mem (h : a ∈ t) : s.erase a ⊆ t ↔ s ⊆ t := by rw [← subset_insert_iff, insert_eq_of_mem h] theorem erase_injOn' (a : α) : { s : Finset α | a ∈ s }.InjOn fun s => erase s a := fun s hs t ht (h : s.erase a = _) => by rw [← insert_erase hs, ← insert_erase ht, h] end Erase lemma Nontrivial.exists_cons_eq {s : Finset α} (hs : s.Nontrivial) : ∃ t a ha b hb hab, (cons b t hb).cons a (mem_cons.not.2 <| not_or_intro hab ha) = s := by classical obtain ⟨a, ha, b, hb, hab⟩ := hs have : b ∈ s.erase a := mem_erase.2 ⟨hab.symm, hb⟩ refine ⟨(s.erase a).erase b, a, ?_, b, ?_, ?_, ?_⟩ <;> simp [insert_erase this, insert_erase ha, *] /-! ### sdiff -/ section Sdiff variable [DecidableEq α] {s t u v : Finset α} {a b : α} lemma erase_sdiff_erase (hab : a ≠ b) (hb : b ∈ s) : s.erase a \ s.erase b = {b} := by ext; aesop -- TODO: Do we want to delete this lemma and `Finset.disjUnion_singleton`, -- or instead add `Finset.union_singleton`/`Finset.singleton_union`? theorem sdiff_singleton_eq_erase (a : α) (s : Finset α) : s \ {a} = erase s a := by ext rw [mem_erase, mem_sdiff, mem_singleton, and_comm] -- This lemma matches `Finset.insert_eq` in functionality. theorem erase_eq (s : Finset α) (a : α) : s.erase a = s \ {a} := (sdiff_singleton_eq_erase _ _).symm theorem disjoint_erase_comm : Disjoint (s.erase a) t ↔ Disjoint s (t.erase a) := by simp_rw [erase_eq, disjoint_sdiff_comm] lemma disjoint_insert_erase (ha : a ∉ t) : Disjoint (s.erase a) (insert a t) ↔ Disjoint s t := by rw [disjoint_erase_comm, erase_insert ha] lemma disjoint_erase_insert (ha : a ∉ s) : Disjoint (insert a s) (t.erase a) ↔ Disjoint s t := by rw [← disjoint_erase_comm, erase_insert ha] theorem disjoint_of_erase_left (ha : a ∉ t) (hst : Disjoint (s.erase a) t) : Disjoint s t := by rw [← erase_insert ha, ← disjoint_erase_comm, disjoint_insert_right] exact ⟨not_mem_erase _ _, hst⟩ theorem disjoint_of_erase_right (ha : a ∉ s) (hst : Disjoint s (t.erase a)) : Disjoint s t := by rw [← erase_insert ha, disjoint_erase_comm, disjoint_insert_left] exact ⟨not_mem_erase _ _, hst⟩ theorem inter_erase (a : α) (s t : Finset α) : s ∩ t.erase a = (s ∩ t).erase a := by simp only [erase_eq, inter_sdiff_assoc] @[simp] theorem erase_inter (a : α) (s t : Finset α) : s.erase a ∩ t = (s ∩ t).erase a := by simpa only [inter_comm t] using inter_erase a t s theorem erase_sdiff_comm (s t : Finset α) (a : α) : s.erase a \ t = (s \ t).erase a := by simp_rw [erase_eq, sdiff_right_comm] theorem erase_inter_comm (s t : Finset α) (a : α) : s.erase a ∩ t = s ∩ t.erase a := by rw [erase_inter, inter_erase] theorem erase_union_distrib (s t : Finset α) (a : α) : (s ∪ t).erase a = s.erase a ∪ t.erase a := by simp_rw [erase_eq, union_sdiff_distrib] theorem insert_inter_distrib (s t : Finset α) (a : α) : insert a (s ∩ t) = insert a s ∩ insert a t := by simp_rw [insert_eq, union_inter_distrib_left] theorem erase_sdiff_distrib (s t : Finset α) (a : α) : (s \ t).erase a = s.erase a \ t.erase a := by simp_rw [erase_eq, sdiff_sdiff, sup_sdiff_eq_sup le_rfl, sup_comm] theorem erase_union_of_mem (ha : a ∈ t) (s : Finset α) : s.erase a ∪ t = s ∪ t := by rw [← insert_erase (mem_union_right s ha), erase_union_distrib, ← union_insert, insert_erase ha] theorem union_erase_of_mem (ha : a ∈ s) (t : Finset α) : s ∪ t.erase a = s ∪ t := by rw [← insert_erase (mem_union_left t ha), erase_union_distrib, ← insert_union, insert_erase ha] theorem sdiff_union_erase_cancel (hts : t ⊆ s) (ha : a ∈ t) : s \ t ∪ t.erase a = s.erase a := by simp_rw [erase_eq, sdiff_union_sdiff_cancel hts (singleton_subset_iff.2 ha)] theorem sdiff_insert (s t : Finset α) (x : α) : s \ insert x t = (s \ t).erase x := by simp_rw [← sdiff_singleton_eq_erase, insert_eq, sdiff_sdiff_left', sdiff_union_distrib, inter_comm] theorem sdiff_insert_insert_of_mem_of_not_mem {s t : Finset α} {x : α} (hxs : x ∈ s) (hxt : x ∉ t) : insert x (s \ insert x t) = s \ t := by rw [sdiff_insert, insert_erase (mem_sdiff.mpr ⟨hxs, hxt⟩)] theorem sdiff_erase (h : a ∈ s) : s \ t.erase a = insert a (s \ t) := by rw [← sdiff_singleton_eq_erase, sdiff_sdiff_eq_sdiff_union (singleton_subset_iff.2 h), insert_eq, union_comm] theorem sdiff_erase_self (ha : a ∈ s) : s \ s.erase a = {a} := by rw [sdiff_erase ha, Finset.sdiff_self, insert_empty_eq] theorem erase_eq_empty_iff (s : Finset α) (a : α) : s.erase a = ∅ ↔ s = ∅ ∨ s = {a} := by rw [← sdiff_singleton_eq_erase, sdiff_eq_empty_iff_subset, subset_singleton_iff] --TODO@Yaël: Kill lemmas duplicate with `BooleanAlgebra` theorem sdiff_disjoint : Disjoint (t \ s) s := disjoint_left.2 fun _a ha => (mem_sdiff.1 ha).2 theorem disjoint_sdiff : Disjoint s (t \ s) := sdiff_disjoint.symm theorem disjoint_sdiff_inter (s t : Finset α) : Disjoint (s \ t) (s ∩ t) := disjoint_of_subset_right inter_subset_right sdiff_disjoint end Sdiff /-! ### attach -/ @[simp] theorem attach_empty : attach (∅ : Finset α) = ∅ := rfl @[simp] theorem attach_nonempty_iff {s : Finset α} : s.attach.Nonempty ↔ s.Nonempty := by simp [Finset.Nonempty] @[aesop safe apply (rule_sets := [finsetNonempty])] protected alias ⟨_, Nonempty.attach⟩ := attach_nonempty_iff @[simp] theorem attach_eq_empty_iff {s : Finset α} : s.attach = ∅ ↔ s = ∅ := by simp [eq_empty_iff_forall_not_mem] /-! ### filter -/ section Filter variable (p q : α → Prop) [DecidablePred p] [DecidablePred q] {s t : Finset α} theorem filter_singleton (a : α) : filter p {a} = if p a then {a} else ∅ := by classical ext x simp only [mem_singleton, forall_eq, mem_filter] split_ifs with h <;> by_cases h' : x = a <;> simp [h, h'] theorem filter_cons_of_pos (a : α) (s : Finset α) (ha : a ∉ s) (hp : p a) : filter p (cons a s ha) = cons a (filter p s) ((mem_of_mem_filter _).mt ha) := eq_of_veq <| Multiset.filter_cons_of_pos s.val hp theorem filter_cons_of_neg (a : α) (s : Finset α) (ha : a ∉ s) (hp : ¬p a) : filter p (cons a s ha) = filter p s := eq_of_veq <| Multiset.filter_cons_of_neg s.val hp theorem disjoint_filter {s : Finset α} {p q : α → Prop} [DecidablePred p] [DecidablePred q] : Disjoint (s.filter p) (s.filter q) ↔ ∀ x ∈ s, p x → ¬q x := by constructor <;> simp +contextual [disjoint_left] theorem disjoint_filter_filter' (s t : Finset α) {p q : α → Prop} [DecidablePred p] [DecidablePred q] (h : Disjoint p q) : Disjoint (s.filter p) (t.filter q) := by simp_rw [disjoint_left, mem_filter] rintro a ⟨_, hp⟩ ⟨_, hq⟩ rw [Pi.disjoint_iff] at h simpa [hp, hq] using h a theorem disjoint_filter_filter_neg (s t : Finset α) (p : α → Prop) [DecidablePred p] [∀ x, Decidable (¬p x)] : Disjoint (s.filter p) (t.filter fun a => ¬p a) := disjoint_filter_filter' s t disjoint_compl_right theorem filter_disj_union (s : Finset α) (t : Finset α) (h : Disjoint s t) : filter p (disjUnion s t h) = (filter p s).disjUnion (filter p t) (disjoint_filter_filter h) := eq_of_veq <| Multiset.filter_add _ _ _ theorem filter_cons {a : α} (s : Finset α) (ha : a ∉ s) : filter p (cons a s ha) = if p a then cons a (filter p s) ((mem_of_mem_filter _).mt ha) else filter p s := by split_ifs with h · rw [filter_cons_of_pos _ _ _ ha h] · rw [filter_cons_of_neg _ _ _ ha h] section variable [DecidableEq α] theorem filter_union (s₁ s₂ : Finset α) : (s₁ ∪ s₂).filter p = s₁.filter p ∪ s₂.filter p := ext fun _ => by simp only [mem_filter, mem_union, or_and_right] theorem filter_union_right (s : Finset α) : s.filter p ∪ s.filter q = s.filter fun x => p x ∨ q x := ext fun x => by simp [mem_filter, mem_union, ← and_or_left] theorem filter_mem_eq_inter {s t : Finset α} [∀ i, Decidable (i ∈ t)] : (s.filter fun i => i ∈ t) = s ∩ t := ext fun i => by simp [mem_filter, mem_inter] theorem filter_inter_distrib (s t : Finset α) : (s ∩ t).filter p = s.filter p ∩ t.filter p := by ext simp [mem_filter, mem_inter, and_assoc] theorem filter_inter (s t : Finset α) : filter p s ∩ t = filter p (s ∩ t) := by ext simp only [mem_inter, mem_filter, and_right_comm] theorem inter_filter (s t : Finset α) : s ∩ filter p t = filter p (s ∩ t) := by rw [inter_comm, filter_inter, inter_comm] theorem filter_insert (a : α) (s : Finset α) : filter p (insert a s) = if p a then insert a (filter p s) else filter p s := by ext x split_ifs with h <;> by_cases h' : x = a <;> simp [h, h'] theorem filter_erase (a : α) (s : Finset α) : filter p (erase s a) = erase (filter p s) a := by ext x simp only [and_assoc, mem_filter, iff_self, mem_erase] theorem filter_or (s : Finset α) : (s.filter fun a => p a ∨ q a) = s.filter p ∪ s.filter q := ext fun _ => by simp [mem_filter, mem_union, and_or_left] theorem filter_and (s : Finset α) : (s.filter fun a => p a ∧ q a) = s.filter p ∩ s.filter q := ext fun _ => by simp [mem_filter, mem_inter, and_comm, and_left_comm, and_self_iff, and_assoc] theorem filter_not (s : Finset α) : (s.filter fun a => ¬p a) = s \ s.filter p := ext fun a => by simp only [Bool.decide_coe, Bool.not_eq_true', mem_filter, and_comm, mem_sdiff, not_and_or, Bool.not_eq_true, and_or_left, and_not_self, or_false] lemma filter_and_not (s : Finset α) (p q : α → Prop) [DecidablePred p] [DecidablePred q] : s.filter (fun a ↦ p a ∧ ¬ q a) = s.filter p \ s.filter q := by rw [filter_and, filter_not, ← inter_sdiff_assoc, inter_eq_left.2 (filter_subset _ _)] theorem sdiff_eq_filter (s₁ s₂ : Finset α) : s₁ \ s₂ = filter (· ∉ s₂) s₁ := ext fun _ => by simp [mem_sdiff, mem_filter] theorem subset_union_elim {s : Finset α} {t₁ t₂ : Set α} (h : ↑s ⊆ t₁ ∪ t₂) : ∃ s₁ s₂ : Finset α, s₁ ∪ s₂ = s ∧ ↑s₁ ⊆ t₁ ∧ ↑s₂ ⊆ t₂ \ t₁ := by classical refine ⟨s.filter (· ∈ t₁), s.filter (· ∉ t₁), ?_, ?_, ?_⟩ · simp [filter_union_right, em] · intro x simp · intro x simp only [not_not, coe_filter, Set.mem_setOf_eq, Set.mem_diff, and_imp] intro hx hx₂ exact ⟨Or.resolve_left (h hx) hx₂, hx₂⟩ -- This is not a good simp lemma, as it would prevent `Finset.mem_filter` from firing -- on, e.g. `x ∈ s.filter (Eq b)`. /-- After filtering out everything that does not equal a given value, at most that value remains. This is equivalent to `filter_eq'` with the equality the other way. -/ theorem filter_eq [DecidableEq β] (s : Finset β) (b : β) : s.filter (Eq b) = ite (b ∈ s) {b} ∅ := by split_ifs with h · ext simp only [mem_filter, mem_singleton, decide_eq_true_eq] refine ⟨fun h => h.2.symm, ?_⟩ rintro rfl exact ⟨h, rfl⟩ · ext simp only [mem_filter, not_and, iff_false, not_mem_empty, decide_eq_true_eq] rintro m rfl exact h m /-- After filtering out everything that does not equal a given value, at most that value remains. This is equivalent to `filter_eq` with the equality the other way. -/ theorem filter_eq' [DecidableEq β] (s : Finset β) (b : β) : (s.filter fun a => a = b) = ite (b ∈ s) {b} ∅ := _root_.trans (filter_congr fun _ _ => by simp_rw [@eq_comm _ b]) (filter_eq s b) theorem filter_ne [DecidableEq β] (s : Finset β) (b : β) : (s.filter fun a => b ≠ a) = s.erase b := by ext simp only [mem_filter, mem_erase, Ne, decide_not, Bool.not_eq_true', decide_eq_false_iff_not] tauto theorem filter_ne' [DecidableEq β] (s : Finset β) (b : β) : (s.filter fun a => a ≠ b) = s.erase b := _root_.trans (filter_congr fun _ _ => by simp_rw [@ne_comm _ b]) (filter_ne s b) theorem filter_union_filter_of_codisjoint (s : Finset α) (h : Codisjoint p q) : s.filter p ∪ s.filter q = s := (filter_or _ _ _).symm.trans <| filter_true_of_mem fun x _ => h.top_le x trivial theorem filter_union_filter_neg_eq [∀ x, Decidable (¬p x)] (s : Finset α) : (s.filter p ∪ s.filter fun a => ¬p a) = s := filter_union_filter_of_codisjoint _ _ _ <| @codisjoint_hnot_right _ _ p end end Filter /-! ### range -/ section Range open Nat variable {n m l : ℕ} @[simp] theorem range_filter_eq {n m : ℕ} : (range n).filter (· = m) = if m < n then {m} else ∅ := by convert filter_eq (range n) m using 2 · ext rw [eq_comm] · simp end Range end Finset /-! ### dedup on list and multiset -/ namespace Multiset variable [DecidableEq α] {s t : Multiset α} @[simp] theorem toFinset_add (s t : Multiset α) : toFinset (s + t) = toFinset s ∪ toFinset t := Finset.ext <| by simp @[simp] theorem toFinset_inter (s t : Multiset α) : toFinset (s ∩ t) = toFinset s ∩ toFinset t := Finset.ext <| by simp @[simp] theorem toFinset_union (s t : Multiset α) : (s ∪ t).toFinset = s.toFinset ∪ t.toFinset := by ext; simp @[simp] theorem toFinset_eq_empty {m : Multiset α} : m.toFinset = ∅ ↔ m = 0 := Finset.val_inj.symm.trans Multiset.dedup_eq_zero @[simp] theorem toFinset_nonempty : s.toFinset.Nonempty ↔ s ≠ 0 := by simp only [toFinset_eq_empty, Ne, Finset.nonempty_iff_ne_empty] @[aesop safe apply (rule_sets := [finsetNonempty])] protected alias ⟨_, Aesop.toFinset_nonempty_of_ne⟩ := toFinset_nonempty @[simp] theorem toFinset_filter (s : Multiset α) (p : α → Prop) [DecidablePred p] : Multiset.toFinset (s.filter p) = s.toFinset.filter p := by ext; simp end Multiset namespace List variable [DecidableEq α] {l l' : List α} {a : α} {f : α → β} {s : Finset α} {t : Set β} {t' : Finset β} @[simp] theorem toFinset_union (l l' : List α) : (l ∪ l').toFinset = l.toFinset ∪ l'.toFinset := by ext simp @[simp] theorem toFinset_inter (l l' : List α) : (l ∩ l').toFinset = l.toFinset ∩ l'.toFinset := by ext simp @[aesop safe apply (rule_sets := [finsetNonempty])] alias ⟨_, Aesop.toFinset_nonempty_of_ne⟩ := toFinset_nonempty_iff @[simp] theorem toFinset_filter (s : List α) (p : α → Bool) : (s.filter p).toFinset = s.toFinset.filter (p ·) := by ext; simp [List.mem_filter] end List namespace Finset section ToList @[simp] theorem toList_eq_nil {s : Finset α} : s.toList = [] ↔ s = ∅ := Multiset.toList_eq_nil.trans val_eq_zero theorem empty_toList {s : Finset α} : s.toList.isEmpty ↔ s = ∅ := by simp @[simp] theorem toList_empty : (∅ : Finset α).toList = [] := toList_eq_nil.mpr rfl theorem Nonempty.toList_ne_nil {s : Finset α} (hs : s.Nonempty) : s.toList ≠ [] := mt toList_eq_nil.mp hs.ne_empty theorem Nonempty.not_empty_toList {s : Finset α} (hs : s.Nonempty) : ¬s.toList.isEmpty := mt empty_toList.mp hs.ne_empty end ToList /-! ### choose -/ section Choose variable (p : α → Prop) [DecidablePred p] (l : Finset α) /-- Given a finset `l` and a predicate `p`, associate to a proof that there is a unique element of `l` satisfying `p` this unique element, as an element of the corresponding subtype. -/ def chooseX (hp : ∃! a, a ∈ l ∧ p a) : { a // a ∈ l ∧ p a } := Multiset.chooseX p l.val hp /-- Given a finset `l` and a predicate `p`, associate to a proof that there is a unique element of `l` satisfying `p` this unique element, as an element of the ambient type. -/ def choose (hp : ∃! a, a ∈ l ∧ p a) : α := chooseX p l hp theorem choose_spec (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l ∧ p (choose p l hp) := (chooseX p l hp).property theorem choose_mem (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l := (choose_spec _ _ _).1 theorem choose_property (hp : ∃! a, a ∈ l ∧ p a) : p (choose p l hp) := (choose_spec _ _ _).2 end Choose end Finset namespace Equiv variable [DecidableEq α] {s t : Finset α} open Finset /-- The disjoint union of finsets is a sum -/ def Finset.union (s t : Finset α) (h : Disjoint s t) : s ⊕ t ≃ (s ∪ t : Finset α) := Equiv.setCongr (coe_union _ _) |>.trans (Equiv.Set.union (disjoint_coe.mpr h)) |>.symm @[simp] theorem Finset.union_symm_inl (h : Disjoint s t) (x : s) : Equiv.Finset.union s t h (Sum.inl x) = ⟨x, Finset.mem_union.mpr <| Or.inl x.2⟩ := rfl @[simp] theorem Finset.union_symm_inr (h : Disjoint s t) (y : t) : Equiv.Finset.union s t h (Sum.inr y) = ⟨y, Finset.mem_union.mpr <| Or.inr y.2⟩ := rfl /-- The type of dependent functions on the disjoint union of finsets `s ∪ t` is equivalent to the type of pairs of functions on `s` and on `t`. This is similar to `Equiv.sumPiEquivProdPi`. -/ def piFinsetUnion {ι} [DecidableEq ι] (α : ι → Type*) {s t : Finset ι} (h : Disjoint s t) : ((∀ i : s, α i) × ∀ i : t, α i) ≃ ∀ i : (s ∪ t : Finset ι), α i := let e := Equiv.Finset.union s t h sumPiEquivProdPi (fun b ↦ α (e b)) |>.symm.trans (.piCongrLeft (fun i : ↥(s ∪ t) ↦ α i) e) /-- A finset is equivalent to its coercion as a set. -/ def _root_.Finset.equivToSet (s : Finset α) : s ≃ s.toSet where toFun a := ⟨a.1, mem_coe.2 a.2⟩ invFun a := ⟨a.1, mem_coe.1 a.2⟩ left_inv := fun _ ↦ rfl right_inv := fun _ ↦ rfl end Equiv namespace Multiset variable [DecidableEq α] @[simp] lemma toFinset_replicate (n : ℕ) (a : α) : (replicate n a).toFinset = if n = 0 then ∅ else {a} := by ext x simp only [mem_toFinset, Finset.mem_singleton, mem_replicate] split_ifs with hn <;> simp [hn] end Multiset
Mathlib/Data/Finset/Basic.lean
1,172
1,173
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Mario Carneiro, Johannes Hölzl -/ import Mathlib.Algebra.Order.Group.Defs import Mathlib.Algebra.Order.Group.Unbundled.Abs import Mathlib.Algebra.Order.Monoid.Unbundled.Pow /-! # Absolute values in ordered groups The absolute value of an element in a group which is also a lattice is its supremum with its negation. This generalizes the usual absolute value on real numbers (`|x| = max x (-x)`). ## Notations - `|a|`: The *absolute value* of an element `a` of an additive lattice ordered group - `|a|ₘ`: The *absolute value* of an element `a` of a multiplicative lattice ordered group -/ open Function variable {G : Type*} section LinearOrderedCommGroup variable [CommGroup G] [LinearOrder G] [IsOrderedMonoid G] {a b c : G} @[to_additive] lemma mabs_pow (n : ℕ) (a : G) : |a ^ n|ₘ = |a|ₘ ^ n := by obtain ha | ha := le_total a 1 · rw [mabs_of_le_one ha, ← mabs_inv, ← inv_pow, mabs_of_one_le] exact one_le_pow_of_one_le' (one_le_inv'.2 ha) n · rw [mabs_of_one_le ha, mabs_of_one_le (one_le_pow_of_one_le' ha n)] @[to_additive] private lemma mabs_mul_eq_mul_mabs_le (hab : a ≤ b) : |a * b|ₘ = |a|ₘ * |b|ₘ ↔ 1 ≤ a ∧ 1 ≤ b ∨ a ≤ 1 ∧ b ≤ 1 := by obtain ha | ha := le_or_lt 1 a <;> obtain hb | hb := le_or_lt 1 b · simp [ha, hb, mabs_of_one_le, one_le_mul ha hb] · exact (lt_irrefl (1 : G) <| ha.trans_lt <| hab.trans_lt hb).elim swap · simp [ha.le, hb.le, mabs_of_le_one, mul_le_one', mul_comm] have : (|a * b|ₘ = a⁻¹ * b ↔ b ≤ 1) ↔ (|a * b|ₘ = |a|ₘ * |b|ₘ ↔ 1 ≤ a ∧ 1 ≤ b ∨ a ≤ 1 ∧ b ≤ 1) := by simp [ha.le, ha.not_le, hb, mabs_of_le_one, mabs_of_one_le] refine this.mp ⟨fun h ↦ ?_, fun h ↦ by simp only [h.antisymm hb, mabs_of_lt_one ha, mul_one]⟩ obtain ab | ab := le_or_lt (a * b) 1 · refine (eq_one_of_inv_eq' ?_).le rwa [mabs_of_le_one ab, mul_inv_rev, mul_comm, mul_right_inj] at h · rw [mabs_of_one_lt ab, mul_left_inj] at h rw [eq_one_of_inv_eq' h.symm] at ha cases ha.false @[to_additive] lemma mabs_mul_eq_mul_mabs_iff (a b : G) : |a * b|ₘ = |a|ₘ * |b|ₘ ↔ 1 ≤ a ∧ 1 ≤ b ∨ a ≤ 1 ∧ b ≤ 1 := by obtain ab | ab := le_total a b · exact mabs_mul_eq_mul_mabs_le ab · simpa only [mul_comm, and_comm] using mabs_mul_eq_mul_mabs_le ab @[to_additive] theorem mabs_le : |a|ₘ ≤ b ↔ b⁻¹ ≤ a ∧ a ≤ b := by rw [mabs_le', and_comm, inv_le'] @[to_additive] theorem le_mabs' : a ≤ |b|ₘ ↔ b ≤ a⁻¹ ∨ a ≤ b := by rw [le_mabs, or_comm, le_inv'] @[to_additive] theorem inv_le_of_mabs_le (h : |a|ₘ ≤ b) : b⁻¹ ≤ a := (mabs_le.mp h).1 @[to_additive] theorem le_of_mabs_le (h : |a|ₘ ≤ b) : a ≤ b := (mabs_le.mp h).2 /-- The **triangle inequality** in `LinearOrderedCommGroup`s. -/ @[to_additive "The **triangle inequality** in `LinearOrderedAddCommGroup`s."] theorem mabs_mul (a b : G) : |a * b|ₘ ≤ |a|ₘ * |b|ₘ := by rw [mabs_le, mul_inv] constructor <;> gcongr <;> apply_rules [inv_mabs_le, le_mabs_self] @[to_additive] theorem mabs_mul' (a b : G) : |a|ₘ ≤ |b|ₘ * |b * a|ₘ := by simpa using mabs_mul b⁻¹ (b * a) @[to_additive] theorem mabs_div (a b : G) : |a / b|ₘ ≤ |a|ₘ * |b|ₘ := by rw [div_eq_mul_inv, ← mabs_inv b] exact mabs_mul a _ @[to_additive] theorem mabs_div_le_iff : |a / b|ₘ ≤ c ↔ a / b ≤ c ∧ b / a ≤ c := by rw [mabs_le, inv_le_div_iff_le_mul, div_le_iff_le_mul', and_comm, div_le_iff_le_mul'] @[to_additive] theorem mabs_div_lt_iff : |a / b|ₘ < c ↔ a / b < c ∧ b / a < c := by rw [mabs_lt, inv_lt_div_iff_lt_mul', div_lt_iff_lt_mul', and_comm, div_lt_iff_lt_mul'] @[to_additive] theorem div_le_of_mabs_div_le_left (h : |a / b|ₘ ≤ c) : b / c ≤ a := div_le_comm.1 <| (mabs_div_le_iff.1 h).2 @[to_additive] theorem div_le_of_mabs_div_le_right (h : |a / b|ₘ ≤ c) : a / c ≤ b := div_le_of_mabs_div_le_left (mabs_div_comm a b ▸ h) @[to_additive] theorem div_lt_of_mabs_div_lt_left (h : |a / b|ₘ < c) : b / c < a := div_lt_comm.1 <| (mabs_div_lt_iff.1 h).2 @[to_additive] theorem div_lt_of_mabs_div_lt_right (h : |a / b|ₘ < c) : a / c < b := div_lt_of_mabs_div_lt_left (mabs_div_comm a b ▸ h) @[to_additive] theorem mabs_div_mabs_le_mabs_div (a b : G) : |a|ₘ / |b|ₘ ≤ |a / b|ₘ := div_le_iff_le_mul.2 <| calc |a|ₘ = |a / b * b|ₘ := by rw [div_mul_cancel] _ ≤ |a / b|ₘ * |b|ₘ := mabs_mul _ _ @[to_additive] theorem mabs_mabs_div_mabs_le_mabs_div (a b : G) : |(|a|ₘ / |b|ₘ)|ₘ ≤ |a / b|ₘ := mabs_div_le_iff.2 ⟨mabs_div_mabs_le_mabs_div _ _, by rw [mabs_div_comm]; apply mabs_div_mabs_le_mabs_div⟩ /-- `|a / b|ₘ ≤ n` if `1 ≤ a ≤ n` and `1 ≤ b ≤ n`. -/ @[to_additive "`|a - b| ≤ n` if `0 ≤ a ≤ n` and `0 ≤ b ≤ n`."] theorem mabs_div_le_of_one_le_of_le {a b n : G} (one_le_a : 1 ≤ a) (a_le_n : a ≤ n) (one_le_b : 1 ≤ b) (b_le_n : b ≤ n) : |a / b|ₘ ≤ n := by rw [mabs_div_le_iff, div_le_iff_le_mul, div_le_iff_le_mul] exact ⟨le_mul_of_le_of_one_le a_le_n one_le_b, le_mul_of_le_of_one_le b_le_n one_le_a⟩ /-- `|a - b| < n` if `0 ≤ a < n` and `0 ≤ b < n`. -/ @[to_additive "`|a / b|ₘ < n` if `1 ≤ a < n` and `1 ≤ b < n`."] theorem mabs_div_lt_of_one_le_of_lt {a b n : G} (one_le_a : 1 ≤ a) (a_lt_n : a < n) (one_le_b : 1 ≤ b) (b_lt_n : b < n) : |a / b|ₘ < n := by rw [mabs_div_lt_iff, div_lt_iff_lt_mul, div_lt_iff_lt_mul] exact ⟨lt_mul_of_lt_of_one_le a_lt_n one_le_b, lt_mul_of_lt_of_one_le b_lt_n one_le_a⟩ @[to_additive] theorem mabs_eq (hb : 1 ≤ b) : |a|ₘ = b ↔ a = b ∨ a = b⁻¹ := by refine ⟨eq_or_eq_inv_of_mabs_eq, ?_⟩ rintro (rfl | rfl) <;> simp only [mabs_inv, mabs_of_one_le hb] @[to_additive] theorem mabs_le_max_mabs_mabs (hab : a ≤ b) (hbc : b ≤ c) : |b|ₘ ≤ max |a|ₘ |c|ₘ := mabs_le'.2 ⟨by simp [hbc.trans (le_mabs_self c)], by simp [(inv_le_inv_iff.mpr hab).trans (inv_le_mabs a)]⟩ omit [IsOrderedMonoid G] in @[to_additive] theorem min_mabs_mabs_le_mabs_max : min |a|ₘ |b|ₘ ≤ |max a b|ₘ := (le_total a b).elim (fun h => (min_le_right _ _).trans_eq <| congr_arg _ (max_eq_right h).symm) fun h => (min_le_left _ _).trans_eq <| congr_arg _ (max_eq_left h).symm omit [IsOrderedMonoid G] in @[to_additive] theorem min_mabs_mabs_le_mabs_min : min |a|ₘ |b|ₘ ≤ |min a b|ₘ := (le_total a b).elim (fun h => (min_le_left _ _).trans_eq <| congr_arg _ (min_eq_left h).symm) fun h => (min_le_right _ _).trans_eq <| congr_arg _ (min_eq_right h).symm omit [IsOrderedMonoid G] in @[to_additive] theorem mabs_max_le_max_mabs_mabs : |max a b|ₘ ≤ max |a|ₘ |b|ₘ := (le_total a b).elim (fun h => (congr_arg _ <| max_eq_right h).trans_le <| le_max_right _ _) fun h => (congr_arg _ <| max_eq_left h).trans_le <| le_max_left _ _ omit [IsOrderedMonoid G] in @[to_additive] theorem mabs_min_le_max_mabs_mabs : |min a b|ₘ ≤ max |a|ₘ |b|ₘ := (le_total a b).elim (fun h => (congr_arg _ <| min_eq_left h).trans_le <| le_max_left _ _) fun h => (congr_arg _ <| min_eq_right h).trans_le <| le_max_right _ _ @[to_additive] theorem eq_of_mabs_div_eq_one {a b : G} (h : |a / b|ₘ = 1) : a = b := div_eq_one.1 <| mabs_eq_one.1 h @[to_additive] theorem mabs_div_le (a b c : G) : |a / c|ₘ ≤ |a / b|ₘ * |b / c|ₘ := calc |a / c|ₘ = |a / b * (b / c)|ₘ := by rw [div_mul_div_cancel] _ ≤ |a / b|ₘ * |b / c|ₘ := mabs_mul _ _ @[to_additive] theorem mabs_mul_three (a b c : G) : |a * b * c|ₘ ≤ |a|ₘ * |b|ₘ * |c|ₘ := (mabs_mul _ _).trans (mul_le_mul_right' (mabs_mul _ _) _) @[to_additive] theorem mabs_div_le_of_le_of_le {a b lb ub : G} (hal : lb ≤ a) (hau : a ≤ ub) (hbl : lb ≤ b) (hbu : b ≤ ub) : |a / b|ₘ ≤ ub / lb := mabs_div_le_iff.2 ⟨div_le_div'' hau hbl, div_le_div'' hbu hal⟩ @[deprecated (since := "2025-03-02")] alias dist_bdd_within_interval := abs_sub_le_of_le_of_le @[to_additive] theorem eq_of_mabs_div_le_one (h : |a / b|ₘ ≤ 1) : a = b := eq_of_mabs_div_eq_one (le_antisymm h (one_le_mabs (a / b))) @[to_additive] lemma eq_of_mabs_div_lt_all {x y : G} (h : ∀ ε > 1, |x / y|ₘ < ε) : x = y := eq_of_mabs_div_le_one <| forall_lt_iff_le'.mp h @[to_additive] lemma eq_of_mabs_div_le_all [DenselyOrdered G] {x y : G} (h : ∀ ε > 1, |x / y|ₘ ≤ ε) : x = y := eq_of_mabs_div_le_one <| forall_gt_imp_ge_iff_le_of_dense.mp h @[to_additive] theorem mabs_div_le_one : |a / b|ₘ ≤ 1 ↔ a = b := ⟨eq_of_mabs_div_le_one, by rintro rfl; rw [div_self', mabs_one]⟩ @[to_additive] theorem mabs_div_pos : 1 < |a / b|ₘ ↔ a ≠ b := not_le.symm.trans mabs_div_le_one.not @[to_additive (attr := simp)] theorem mabs_eq_self : |a|ₘ = a ↔ 1 ≤ a := by rw [mabs_eq_max_inv, max_eq_left_iff, inv_le_self_iff] @[to_additive (attr := simp)] theorem mabs_eq_inv_self : |a|ₘ = a⁻¹ ↔ a ≤ 1 := by rw [mabs_eq_max_inv, max_eq_right_iff, le_inv_self_iff] /-- For an element `a` of a multiplicative linear ordered group, either `|a|ₘ = a` and `1 ≤ a`, or `|a|ₘ = a⁻¹` and `a < 1`. -/ @[to_additive "For an element `a` of an additive linear ordered group, either `|a| = a` and `0 ≤ a`, or `|a| = -a` and `a < 0`. Use cases on this lemma to automate linarith in inequalities"] theorem mabs_cases (a : G) : |a|ₘ = a ∧ 1 ≤ a ∨ |a|ₘ = a⁻¹ ∧ a < 1 := by cases le_or_lt 1 a <;> simp [*, le_of_lt] @[to_additive (attr := simp)] theorem max_one_mul_max_inv_one_eq_mabs_self (a : G) : max a 1 * max a⁻¹ 1 = |a|ₘ := by symm rcases le_total 1 a with (ha | ha) <;> simp [ha] end LinearOrderedCommGroup section LinearOrderedAddCommGroup variable [AddCommGroup G] [LinearOrder G] [IsOrderedAddMonoid G] {a b c : G} @[to_additive] theorem apply_abs_le_mul_of_one_le' {H : Type*} [MulOneClass H] [LE H] [MulLeftMono H] [MulRightMono H] {f : G → H} {a : G} (h₁ : 1 ≤ f a) (h₂ : 1 ≤ f (-a)) : f |a| ≤ f a * f (-a) := (le_total a 0).rec (fun ha => (abs_of_nonpos ha).symm ▸ le_mul_of_one_le_left' h₁) fun ha => (abs_of_nonneg ha).symm ▸ le_mul_of_one_le_right' h₂ @[to_additive] theorem apply_abs_le_mul_of_one_le {H : Type*} [MulOneClass H] [LE H] [MulLeftMono H] [MulRightMono H] {f : G → H} (h : ∀ x, 1 ≤ f x) (a : G) : f |a| ≤ f a * f (-a) := apply_abs_le_mul_of_one_le' (h _) (h _) end LinearOrderedAddCommGroup
Mathlib/Algebra/Order/Group/Abs.lean
292
292
/- Copyright (c) 2021 Chris Birkbeck. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Birkbeck -/ import Mathlib.Algebra.Group.Subgroup.Pointwise import Mathlib.GroupTheory.Coset.Basic /-! # Double cosets This file defines double cosets for two subgroups `H K` of a group `G` and the quotient of `G` by the double coset relation, i.e. `H \ G / K`. We also prove that `G` can be written as a disjoint union of the double cosets and that if one of `H` or `K` is the trivial group (i.e. `⊥` ) then this is the usual left or right quotient of a group by a subgroup. ## Main definitions * `rel`: The double coset relation defined by two subgroups `H K` of `G`. * `Doset.quotient`: The quotient of `G` by the double coset relation, i.e, `H \ G / K`. -/ assert_not_exists MonoidWithZero variable {G : Type*} [Group G] {α : Type*} [Mul α] open MulOpposite open scoped Pointwise namespace Doset /-- The double coset as an element of `Set α` corresponding to `s a t` -/ def doset (a : α) (s t : Set α) : Set α := s * {a} * t lemma doset_eq_image2 (a : α) (s t : Set α) : doset a s t = Set.image2 (· * a * ·) s t := by simp_rw [doset, Set.mul_singleton, ← Set.image2_mul, Set.image2_image_left] theorem mem_doset {s t : Set α} {a b : α} : b ∈ doset a s t ↔ ∃ x ∈ s, ∃ y ∈ t, b = x * a * y := by simp only [doset_eq_image2, Set.mem_image2, eq_comm] theorem mem_doset_self (H K : Subgroup G) (a : G) : a ∈ doset a H K := mem_doset.mpr ⟨1, H.one_mem, 1, K.one_mem, (one_mul a).symm.trans (mul_one (1 * a)).symm⟩ theorem doset_eq_of_mem {H K : Subgroup G} {a b : G} (hb : b ∈ doset a H K) : doset b H K = doset a H K := by obtain ⟨h, hh, k, hk, rfl⟩ := mem_doset.1 hb rw [doset, doset, ← Set.singleton_mul_singleton, ← Set.singleton_mul_singleton, mul_assoc, mul_assoc, Subgroup.singleton_mul_subgroup hk, ← mul_assoc, ← mul_assoc, Subgroup.subgroup_mul_singleton hh] theorem mem_doset_of_not_disjoint {H K : Subgroup G} {a b : G} (h : ¬Disjoint (doset a H K) (doset b H K)) : b ∈ doset a H K := by rw [Set.not_disjoint_iff] at h simp only [mem_doset] at * obtain ⟨x, ⟨l, hl, r, hr, hrx⟩, y, hy, ⟨r', hr', rfl⟩⟩ := h refine ⟨y⁻¹ * l, H.mul_mem (H.inv_mem hy) hl, r * r'⁻¹, K.mul_mem hr (K.inv_mem hr'), ?_⟩ rwa [mul_assoc, mul_assoc, eq_inv_mul_iff_mul_eq, ← mul_assoc, ← mul_assoc, eq_mul_inv_iff_mul_eq] theorem eq_of_not_disjoint {H K : Subgroup G} {a b : G} (h : ¬Disjoint (doset a H K) (doset b H K)) : doset a H K = doset b H K := by rw [disjoint_comm] at h have ha : a ∈ doset b H K := mem_doset_of_not_disjoint h apply doset_eq_of_mem ha /-- The setoid defined by the double_coset relation -/ def setoid (H K : Set G) : Setoid G := Setoid.ker fun x => doset x H K /-- Quotient of `G` by the double coset relation, i.e. `H \ G / K` -/ def Quotient (H K : Set G) : Type _ := _root_.Quotient (setoid H K) theorem rel_iff {H K : Subgroup G} {x y : G} : setoid ↑H ↑K x y ↔ ∃ a ∈ H, ∃ b ∈ K, y = a * x * b := Iff.trans ⟨fun (hxy : doset x H K = doset y H K) => hxy ▸ mem_doset_self H K y, fun hxy => (doset_eq_of_mem hxy).symm⟩ mem_doset theorem bot_rel_eq_leftRel (H : Subgroup G) : ⇑(setoid ↑(⊥ : Subgroup G) ↑H) = ⇑(QuotientGroup.leftRel H) := by ext a b rw [rel_iff, QuotientGroup.leftRel_apply] constructor · rintro ⟨a, rfl : a = 1, b, hb, rfl⟩ rwa [one_mul, inv_mul_cancel_left] · rintro (h : a⁻¹ * b ∈ H) exact ⟨1, rfl, a⁻¹ * b, h, by rw [one_mul, mul_inv_cancel_left]⟩ theorem rel_bot_eq_right_group_rel (H : Subgroup G) : ⇑(setoid ↑H ↑(⊥ : Subgroup G)) = ⇑(QuotientGroup.rightRel H) := by ext a b rw [rel_iff, QuotientGroup.rightRel_apply] constructor · rintro ⟨b, hb, a, rfl : a = 1, rfl⟩ rwa [mul_one, mul_inv_cancel_right] · rintro (h : b * a⁻¹ ∈ H) exact ⟨b * a⁻¹, h, 1, rfl, by rw [mul_one, inv_mul_cancel_right]⟩ /-- Create a doset out of an element of `H \ G / K` -/ def quotToDoset (H K : Subgroup G) (q : Quotient (H : Set G) K) : Set G := doset q.out H K /-- Map from `G` to `H \ G / K` -/ abbrev mk (H K : Subgroup G) (a : G) : Quotient (H : Set G) K := Quotient.mk'' a instance (H K : Subgroup G) : Inhabited (Quotient (H : Set G) K) := ⟨mk H K (1 : G)⟩ theorem eq (H K : Subgroup G) (a b : G) : mk H K a = mk H K b ↔ ∃ h ∈ H, ∃ k ∈ K, b = h * a * k := by rw [Quotient.eq''] apply rel_iff theorem out_eq' (H K : Subgroup G) (q : Quotient ↑H ↑K) : mk H K q.out = q := Quotient.out_eq' q theorem mk_out_eq_mul (H K : Subgroup G) (g : G) : ∃ h k : G, h ∈ H ∧ k ∈ K ∧ (mk H K g : Quotient ↑H ↑K).out = h * g * k := by have := eq H K (mk H K g : Quotient ↑H ↑K).out g rw [out_eq'] at this obtain ⟨h, h_h, k, hk, T⟩ := this.1 rfl refine ⟨h⁻¹, k⁻¹, H.inv_mem h_h, K.inv_mem hk, eq_mul_inv_of_mul_eq (eq_inv_mul_of_mul_eq ?_)⟩ rw [← mul_assoc, ← T] theorem mk_eq_of_doset_eq {H K : Subgroup G} {a b : G} (h : doset a H K = doset b H K) : mk H K a = mk H K b := by rw [eq] exact mem_doset.mp (h.symm ▸ mem_doset_self H K b) theorem disjoint_out {H K : Subgroup G} {a b : Quotient H K} : a ≠ b → Disjoint (doset a.out H K) (doset b.out (H : Set G) K) := by contrapose! intro h simpa [out_eq'] using mk_eq_of_doset_eq (eq_of_not_disjoint h) theorem union_quotToDoset (H K : Subgroup G) : ⋃ q, quotToDoset H K q = Set.univ := by ext x simp only [Set.mem_iUnion, quotToDoset, mem_doset, SetLike.mem_coe, exists_prop, Set.mem_univ, iff_true] use mk H K x obtain ⟨h, k, h3, h4, h5⟩ := mk_out_eq_mul H K x refine ⟨h⁻¹, H.inv_mem h3, k⁻¹, K.inv_mem h4, ?_⟩ simp only [h5, Subgroup.coe_mk, ← mul_assoc, one_mul, inv_mul_cancel, mul_inv_cancel_right] theorem doset_union_rightCoset (H K : Subgroup G) (a : G) : ⋃ k : K, op (a * k) • ↑H = doset a H K := by ext x simp only [mem_rightCoset_iff, exists_prop, mul_inv_rev, Set.mem_iUnion, mem_doset, Subgroup.mem_carrier, SetLike.mem_coe] constructor · rintro ⟨y, h_h⟩ refine ⟨x * (y⁻¹ * a⁻¹), h_h, y, y.2, ?_⟩ simp only [← mul_assoc, Subgroup.coe_mk, inv_mul_cancel_right, InvMemClass.coe_inv] · rintro ⟨x, hx, y, hy, hxy⟩ refine ⟨⟨y, hy⟩, ?_⟩ simp only [hxy, ← mul_assoc, hx, mul_inv_cancel_right, Subgroup.coe_mk] theorem doset_union_leftCoset (H K : Subgroup G) (a : G) : ⋃ h : H, (h * a : G) • ↑K = doset a H K := by ext x simp only [mem_leftCoset_iff, mul_inv_rev, Set.mem_iUnion, mem_doset] constructor · rintro ⟨y, h_h⟩ refine ⟨y, y.2, a⁻¹ * y⁻¹ * x, h_h, ?_⟩ simp only [← mul_assoc, one_mul, mul_inv_cancel, mul_inv_cancel_right, InvMemClass.coe_inv] · rintro ⟨x, hx, y, hy, hxy⟩ refine ⟨⟨x, hx⟩, ?_⟩ simp only [hxy, ← mul_assoc, hy, one_mul, inv_mul_cancel, Subgroup.coe_mk, inv_mul_cancel_right] theorem left_bot_eq_left_quot (H : Subgroup G) : Quotient (⊥ : Subgroup G) (H : Set G) = (G ⧸ H) := by unfold Quotient congr ext simp_rw [← bot_rel_eq_leftRel H] theorem right_bot_eq_right_quot (H : Subgroup G) : Quotient (H : Set G) (⊥ : Subgroup G) = _root_.Quotient (QuotientGroup.rightRel H) := by unfold Quotient congr ext simp_rw [← rel_bot_eq_right_group_rel H]
end Doset
Mathlib/GroupTheory/DoubleCoset.lean
186
196
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import Mathlib.Control.Functor import Mathlib.Tactic.Common /-! # Functors with two arguments This file defines bifunctors. A bifunctor is a function `F : Type* → Type* → Type*` along with a bimap which turns `F α β`into `F α' β'` given two functions `α → α'` and `β → β'`. It further * respects the identity: `bimap id id = id` * composes in the obvious way: `(bimap f' g') ∘ (bimap f g) = bimap (f' ∘ f) (g' ∘ g)` ## Main declarations * `Bifunctor`: A typeclass for the bare bimap of a bifunctor. * `LawfulBifunctor`: A typeclass asserting this bimap respects the bifunctor laws. -/ universe u₀ u₁ u₂ v₀ v₁ v₂ open Function /-- Lawless bifunctor. This typeclass only holds the data for the bimap. -/ class Bifunctor (F : Type u₀ → Type u₁ → Type u₂) where bimap : ∀ {α α' β β'}, (α → α') → (β → β') → F α β → F α' β' export Bifunctor (bimap) /-- Bifunctor. This typeclass asserts that a lawless `Bifunctor` is lawful. -/ class LawfulBifunctor (F : Type u₀ → Type u₁ → Type u₂) [Bifunctor F] : Prop where id_bimap : ∀ {α β} (x : F α β), bimap id id x = x bimap_bimap : ∀ {α₀ α₁ α₂ β₀ β₁ β₂} (f : α₀ → α₁) (f' : α₁ → α₂) (g : β₀ → β₁) (g' : β₁ → β₂) (x : F α₀ β₀), bimap f' g' (bimap f g x) = bimap (f' ∘ f) (g' ∘ g) x export LawfulBifunctor (id_bimap bimap_bimap) attribute [higher_order bimap_id_id] id_bimap attribute [higher_order bimap_comp_bimap] bimap_bimap export LawfulBifunctor (bimap_id_id bimap_comp_bimap) variable {F : Type u₀ → Type u₁ → Type u₂} [Bifunctor F] namespace Bifunctor /-- Left map of a bifunctor. -/ abbrev fst {α α' β} (f : α → α') : F α β → F α' β := bimap f id /-- Right map of a bifunctor. -/ abbrev snd {α β β'} (f : β → β') : F α β → F α β' := bimap id f variable [LawfulBifunctor F] @[higher_order fst_id] theorem id_fst : ∀ {α β} (x : F α β), fst id x = x := @id_bimap _ _ _ @[higher_order snd_id] theorem id_snd : ∀ {α β} (x : F α β), snd id x = x := @id_bimap _ _ _ @[higher_order fst_comp_fst] theorem comp_fst {α₀ α₁ α₂ β} (f : α₀ → α₁) (f' : α₁ → α₂) (x : F α₀ β) : fst f' (fst f x) = fst (f' ∘ f) x := by simp [fst, bimap_bimap] @[higher_order fst_comp_snd] theorem fst_snd {α₀ α₁ β₀ β₁} (f : α₀ → α₁) (f' : β₀ → β₁) (x : F α₀ β₀) : fst f (snd f' x) = bimap f f' x := by simp [fst, bimap_bimap] @[higher_order snd_comp_fst] theorem snd_fst {α₀ α₁ β₀ β₁} (f : α₀ → α₁) (f' : β₀ → β₁) (x : F α₀ β₀) : snd f' (fst f x) = bimap f f' x := by simp [snd, bimap_bimap] @[higher_order snd_comp_snd]
theorem comp_snd {α β₀ β₁ β₂} (g : β₀ → β₁) (g' : β₁ → β₂) (x : F α β₀) : snd g' (snd g x) = snd (g' ∘ g) x := by simp [snd, bimap_bimap]
Mathlib/Control/Bifunctor.lean
86
87
/- Copyright (c) 2024 Dagur Asgeirsson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Dagur Asgeirsson -/ import Mathlib.Topology.Category.CompHausLike.Limits import Mathlib.Topology.Category.LightProfinite.Basic /-! # Explicit limits and colimits This file applies the general API for explicit limits and colimits in `CompHausLike P` (see the file `Mathlib.Topology.Category.CompHausLike.Limits`) to the special case of `LightProfinite`. -/ namespace LightProfinite universe u w open CategoryTheory Limits CompHausLike instance : HasExplicitPullbacks (fun Y ↦ TotallyDisconnectedSpace Y ∧ SecondCountableTopology Y) where hasProp _ _ := { hasProp := ⟨show TotallyDisconnectedSpace {_xy : _ | _} from inferInstance, show SecondCountableTopology {_xy : _ | _} from inferInstance⟩ } instance : HasExplicitFiniteCoproducts.{w, u} (fun Y ↦ TotallyDisconnectedSpace Y ∧ SecondCountableTopology Y) where hasProp _ := { hasProp := ⟨show TotallyDisconnectedSpace (Σ (_a : _), _) from inferInstance, show SecondCountableTopology (Σ (_a : _), _) from inferInstance⟩ } /-- A one-element space is terminal in `Profinite` -/ abbrev isTerminalPUnit : IsTerminal (LightProfinite.of PUnit.{u + 1}) := CompHausLike.isTerminalPUnit example : FinitaryExtensive LightProfinite.{u} := inferInstance noncomputable example : PreservesFiniteCoproducts lightProfiniteToCompHaus.{u} := inferInstance end LightProfinite
Mathlib/Topology/Category/LightProfinite/Limits.lean
220
224
/- Copyright (c) 2022 Riccardo Brasca. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Riccardo Brasca -/ import Mathlib.NumberTheory.Cyclotomic.Discriminant import Mathlib.RingTheory.Polynomial.Eisenstein.IsIntegral import Mathlib.RingTheory.Ideal.Norm.AbsNorm import Mathlib.RingTheory.Prime /-! # Ring of integers of `p ^ n`-th cyclotomic fields We gather results about cyclotomic extensions of `ℚ`. In particular, we compute the ring of integers of a `p ^ n`-th cyclotomic extension of `ℚ`. ## Main results * `IsCyclotomicExtension.Rat.isIntegralClosure_adjoin_singleton_of_prime_pow`: if `K` is a `p ^ k`-th cyclotomic extension of `ℚ`, then `(adjoin ℤ {ζ})` is the integral closure of `ℤ` in `K`. * `IsCyclotomicExtension.Rat.cyclotomicRing_isIntegralClosure_of_prime_pow`: the integral closure of `ℤ` inside `CyclotomicField (p ^ k) ℚ` is `CyclotomicRing (p ^ k) ℤ ℚ`. * `IsCyclotomicExtension.Rat.absdiscr_prime_pow` and related results: the absolute discriminant of cyclotomic fields. -/ universe u open Algebra IsCyclotomicExtension Polynomial NumberField open scoped Cyclotomic Nat variable {p : ℕ+} {k : ℕ} {K : Type u} [Field K] {ζ : K} [hp : Fact (p : ℕ).Prime] namespace IsCyclotomicExtension.Rat variable [CharZero K] /-- The discriminant of the power basis given by `ζ - 1`. -/ theorem discr_prime_pow_ne_two' [IsCyclotomicExtension {p ^ (k + 1)} ℚ K] (hζ : IsPrimitiveRoot ζ ↑(p ^ (k + 1))) (hk : p ^ (k + 1) ≠ 2) : discr ℚ (hζ.subOnePowerBasis ℚ).basis = (-1) ^ ((p ^ (k + 1) : ℕ).totient / 2) * p ^ ((p : ℕ) ^ k * ((p - 1) * (k + 1) - 1)) := by rw [← discr_prime_pow_ne_two hζ (cyclotomic.irreducible_rat (p ^ (k + 1)).pos) hk] exact hζ.discr_zeta_eq_discr_zeta_sub_one.symm theorem discr_odd_prime' [IsCyclotomicExtension {p} ℚ K] (hζ : IsPrimitiveRoot ζ p) (hodd : p ≠ 2) : discr ℚ (hζ.subOnePowerBasis ℚ).basis = (-1) ^ (((p : ℕ) - 1) / 2) * p ^ ((p : ℕ) - 2) := by rw [← discr_odd_prime hζ (cyclotomic.irreducible_rat hp.out.pos) hodd] exact hζ.discr_zeta_eq_discr_zeta_sub_one.symm /-- The discriminant of the power basis given by `ζ - 1`. Beware that in the cases `p ^ k = 1` and `p ^ k = 2` the formula uses `1 / 2 = 0` and `0 - 1 = 0`. It is useful only to have a uniform result. See also `IsCyclotomicExtension.Rat.discr_prime_pow_eq_unit_mul_pow'`. -/ theorem discr_prime_pow' [IsCyclotomicExtension {p ^ k} ℚ K] (hζ : IsPrimitiveRoot ζ ↑(p ^ k)) : discr ℚ (hζ.subOnePowerBasis ℚ).basis = (-1) ^ ((p ^ k : ℕ).totient / 2) * p ^ ((p : ℕ) ^ (k - 1) * ((p - 1) * k - 1)) := by rw [← discr_prime_pow hζ (cyclotomic.irreducible_rat (p ^ k).pos)] exact hζ.discr_zeta_eq_discr_zeta_sub_one.symm /-- If `p` is a prime and `IsCyclotomicExtension {p ^ k} K L`, then there are `u : ℤˣ` and `n : ℕ` such that the discriminant of the power basis given by `ζ - 1` is `u * p ^ n`. Often this is enough and less cumbersome to use than `IsCyclotomicExtension.Rat.discr_prime_pow'`. -/ theorem discr_prime_pow_eq_unit_mul_pow' [IsCyclotomicExtension {p ^ k} ℚ K] (hζ : IsPrimitiveRoot ζ ↑(p ^ k)) : ∃ (u : ℤˣ) (n : ℕ), discr ℚ (hζ.subOnePowerBasis ℚ).basis = u * p ^ n := by rw [hζ.discr_zeta_eq_discr_zeta_sub_one.symm] exact discr_prime_pow_eq_unit_mul_pow hζ (cyclotomic.irreducible_rat (p ^ k).pos) /-- If `K` is a `p ^ k`-th cyclotomic extension of `ℚ`, then `(adjoin ℤ {ζ})` is the integral closure of `ℤ` in `K`. -/ theorem isIntegralClosure_adjoin_singleton_of_prime_pow [hcycl : IsCyclotomicExtension {p ^ k} ℚ K] (hζ : IsPrimitiveRoot ζ ↑(p ^ k)) : IsIntegralClosure (adjoin ℤ ({ζ} : Set K)) ℤ K := by refine ⟨Subtype.val_injective, @fun x => ⟨fun h => ⟨⟨x, ?_⟩, rfl⟩, ?_⟩⟩ swap · rintro ⟨y, rfl⟩ exact IsIntegral.algebraMap ((le_integralClosure_iff_isIntegral.1 (adjoin_le_integralClosure (hζ.isIntegral (p ^ k).pos))).isIntegral _) let B := hζ.subOnePowerBasis ℚ have hint : IsIntegral ℤ B.gen := (hζ.isIntegral (p ^ k).pos).sub isIntegral_one -- Porting note: the following `letI` was not needed because the locale `cyclotomic` set it -- as instances. letI := IsCyclotomicExtension.finiteDimensional {p ^ k} ℚ K have H := discr_mul_isIntegral_mem_adjoin ℚ hint h obtain ⟨u, n, hun⟩ := discr_prime_pow_eq_unit_mul_pow' hζ rw [hun] at H replace H := Subalgebra.smul_mem _ H u.inv rw [← smul_assoc, ← smul_mul_assoc, Units.inv_eq_val_inv, zsmul_eq_mul, ← Int.cast_mul, Units.inv_mul, Int.cast_one, one_mul, smul_def, map_pow] at H cases k · haveI : IsCyclotomicExtension {1} ℚ K := by simpa using hcycl have : x ∈ (⊥ : Subalgebra ℚ K) := by rw [singleton_one ℚ K] exact mem_top obtain ⟨y, rfl⟩ := mem_bot.1 this replace h := (isIntegral_algebraMap_iff (algebraMap ℚ K).injective).1 h obtain ⟨z, hz⟩ := IsIntegrallyClosed.isIntegral_iff.1 h rw [← hz, ← IsScalarTower.algebraMap_apply] exact Subalgebra.algebraMap_mem _ _ · have hmin : (minpoly ℤ B.gen).IsEisensteinAt (Submodule.span ℤ {((p : ℕ) : ℤ)}) := by have h₁ := minpoly.isIntegrallyClosed_eq_field_fractions' ℚ hint have h₂ := hζ.minpoly_sub_one_eq_cyclotomic_comp (cyclotomic.irreducible_rat (p ^ _).pos) rw [IsPrimitiveRoot.subOnePowerBasis_gen] at h₁ rw [h₁, ← map_cyclotomic_int, show Int.castRingHom ℚ = algebraMap ℤ ℚ by rfl, show X + 1 = map (algebraMap ℤ ℚ) (X + 1) by simp, ← map_comp] at h₂ rw [IsPrimitiveRoot.subOnePowerBasis_gen, map_injective (algebraMap ℤ ℚ) (algebraMap ℤ ℚ).injective_int h₂] exact cyclotomic_prime_pow_comp_X_add_one_isEisensteinAt p _ refine adjoin_le ?_ (mem_adjoin_of_smul_prime_pow_smul_of_minpoly_isEisensteinAt (n := n) (Nat.prime_iff_prime_int.1 hp.out) hint h (by simpa using H) hmin) simp only [Set.singleton_subset_iff, SetLike.mem_coe] exact Subalgebra.sub_mem _ (self_mem_adjoin_singleton ℤ _) (Subalgebra.one_mem _) theorem isIntegralClosure_adjoin_singleton_of_prime [hcycl : IsCyclotomicExtension {p} ℚ K] (hζ : IsPrimitiveRoot ζ ↑p) : IsIntegralClosure (adjoin ℤ ({ζ} : Set K)) ℤ K := by rw [← pow_one p] at hζ hcycl exact isIntegralClosure_adjoin_singleton_of_prime_pow hζ /-- The integral closure of `ℤ` inside `CyclotomicField (p ^ k) ℚ` is `CyclotomicRing (p ^ k) ℤ ℚ`. -/ theorem cyclotomicRing_isIntegralClosure_of_prime_pow : IsIntegralClosure (CyclotomicRing (p ^ k) ℤ ℚ) ℤ (CyclotomicField (p ^ k) ℚ) := by have hζ := zeta_spec (p ^ k) ℚ (CyclotomicField (p ^ k) ℚ) refine ⟨IsFractionRing.injective _ _, @fun x => ⟨fun h => ⟨⟨x, ?_⟩, rfl⟩, ?_⟩⟩ · obtain ⟨y, rfl⟩ := (isIntegralClosure_adjoin_singleton_of_prime_pow hζ).isIntegral_iff.1 h refine adjoin_mono ?_ y.2 simp only [PNat.pow_coe, Set.singleton_subset_iff, Set.mem_setOf_eq] exact hζ.pow_eq_one · rintro ⟨y, rfl⟩ exact IsIntegral.algebraMap ((IsCyclotomicExtension.integral {p ^ k} ℤ _).isIntegral _) theorem cyclotomicRing_isIntegralClosure_of_prime : IsIntegralClosure (CyclotomicRing p ℤ ℚ) ℤ (CyclotomicField p ℚ) := by rw [← pow_one p] exact cyclotomicRing_isIntegralClosure_of_prime_pow end IsCyclotomicExtension.Rat section PowerBasis open IsCyclotomicExtension.Rat namespace IsPrimitiveRoot section CharZero variable [CharZero K] /-- The algebra isomorphism `adjoin ℤ {ζ} ≃ₐ[ℤ] (𝓞 K)`, where `ζ` is a primitive `p ^ k`-th root of unity and `K` is a `p ^ k`-th cyclotomic extension of `ℚ`. -/ @[simps!] noncomputable def _root_.IsPrimitiveRoot.adjoinEquivRingOfIntegers [IsCyclotomicExtension {p ^ k} ℚ K] (hζ : IsPrimitiveRoot ζ ↑(p ^ k)) : adjoin ℤ ({ζ} : Set K) ≃ₐ[ℤ] 𝓞 K := let _ := isIntegralClosure_adjoin_singleton_of_prime_pow hζ IsIntegralClosure.equiv ℤ (adjoin ℤ ({ζ} : Set K)) K (𝓞 K) /-- The ring of integers of a `p ^ k`-th cyclotomic extension of `ℚ` is a cyclotomic extension. -/ instance IsCyclotomicExtension.ringOfIntegers [IsCyclotomicExtension {p ^ k} ℚ K] : IsCyclotomicExtension {p ^ k} ℤ (𝓞 K) := let _ := (zeta_spec (p ^ k) ℚ K).adjoin_isCyclotomicExtension ℤ IsCyclotomicExtension.equiv _ ℤ _ (zeta_spec (p ^ k) ℚ K).adjoinEquivRingOfIntegers /-- The integral `PowerBasis` of `𝓞 K` given by a primitive root of unity, where `K` is a `p ^ k` cyclotomic extension of `ℚ`. -/ noncomputable def integralPowerBasis [IsCyclotomicExtension {p ^ k} ℚ K] (hζ : IsPrimitiveRoot ζ ↑(p ^ k)) : PowerBasis ℤ (𝓞 K) := (Algebra.adjoin.powerBasis' (hζ.isIntegral (p ^ k).pos)).map hζ.adjoinEquivRingOfIntegers /-- Abbreviation to see a primitive root of unity as a member of the ring of integers. -/ abbrev toInteger {k : ℕ+} (hζ : IsPrimitiveRoot ζ k) : 𝓞 K := ⟨ζ, hζ.isIntegral k.pos⟩ end CharZero lemma coe_toInteger {k : ℕ+} (hζ : IsPrimitiveRoot ζ k) : hζ.toInteger.1 = ζ := rfl /-- `𝓞 K ⧸ Ideal.span {ζ - 1}` is finite. -/ lemma finite_quotient_toInteger_sub_one [NumberField K] {k : ℕ+} (hk : 1 < k) (hζ : IsPrimitiveRoot ζ k) : Finite (𝓞 K ⧸ Ideal.span {hζ.toInteger - 1}) := by refine Ideal.finiteQuotientOfFreeOfNeBot _ (fun h ↦ ?_) simp only [Ideal.span_singleton_eq_bot, sub_eq_zero, ← Subtype.coe_inj] at h exact hζ.ne_one hk (RingOfIntegers.ext_iff.1 h) /-- We have that `𝓞 K ⧸ Ideal.span {ζ - 1}` has cardinality equal to the norm of `ζ - 1`. See the results below to compute this norm in various cases. -/ lemma card_quotient_toInteger_sub_one [NumberField K] {k : ℕ+} (hζ : IsPrimitiveRoot ζ k) : Nat.card (𝓞 K ⧸ Ideal.span {hζ.toInteger - 1}) = (Algebra.norm ℤ (hζ.toInteger - 1)).natAbs := by rw [← Submodule.cardQuot_apply, ← Ideal.absNorm_apply, Ideal.absNorm_span_singleton] lemma toInteger_isPrimitiveRoot {k : ℕ+} (hζ : IsPrimitiveRoot ζ k) : IsPrimitiveRoot hζ.toInteger k := IsPrimitiveRoot.of_map_of_injective (by exact hζ) RingOfIntegers.coe_injective variable [CharZero K] @[simp] theorem integralPowerBasis_gen [hcycl : IsCyclotomicExtension {p ^ k} ℚ K] (hζ : IsPrimitiveRoot ζ ↑(p ^ k)) : hζ.integralPowerBasis.gen = hζ.toInteger := Subtype.ext <| show algebraMap _ K hζ.integralPowerBasis.gen = _ by rw [integralPowerBasis, PowerBasis.map_gen, adjoin.powerBasis'_gen] simp only [adjoinEquivRingOfIntegers_apply, IsIntegralClosure.algebraMap_lift] rfl #adaptation_note /-- https://github.com/leanprover/lean4/pull/5338 We name `hcycl` so it can be used as a named argument, but since https://github.com/leanprover/lean4/pull/5338, this is considered unused, so we need to disable the linter. -/ set_option linter.unusedVariables false in @[simp] theorem integralPowerBasis_dim [hcycl : IsCyclotomicExtension {p ^ k} ℚ K] (hζ : IsPrimitiveRoot ζ ↑(p ^ k)) : hζ.integralPowerBasis.dim = φ (p ^ k) := by simp [integralPowerBasis, ← cyclotomic_eq_minpoly hζ, natDegree_cyclotomic] /-- The algebra isomorphism `adjoin ℤ {ζ} ≃ₐ[ℤ] (𝓞 K)`, where `ζ` is a primitive `p`-th root of unity and `K` is a `p`-th cyclotomic extension of `ℚ`. -/ @[simps!] noncomputable def _root_.IsPrimitiveRoot.adjoinEquivRingOfIntegers' [hcycl : IsCyclotomicExtension {p} ℚ K] (hζ : IsPrimitiveRoot ζ p) : adjoin ℤ ({ζ} : Set K) ≃ₐ[ℤ] 𝓞 K := have : IsCyclotomicExtension {p ^ 1} ℚ K := by convert hcycl; rw [pow_one] adjoinEquivRingOfIntegers (p := p) (k := 1) (ζ := ζ) (by rwa [pow_one]) /-- The ring of integers of a `p`-th cyclotomic extension of `ℚ` is a cyclotomic extension. -/ instance _root_.IsCyclotomicExtension.ring_of_integers' [IsCyclotomicExtension {p} ℚ K] : IsCyclotomicExtension {p} ℤ (𝓞 K) := let _ := (zeta_spec p ℚ K).adjoin_isCyclotomicExtension ℤ IsCyclotomicExtension.equiv _ ℤ _ (zeta_spec p ℚ K).adjoinEquivRingOfIntegers' /-- The integral `PowerBasis` of `𝓞 K` given by a primitive root of unity, where `K` is a `p`-th cyclotomic extension of `ℚ`. -/ noncomputable def integralPowerBasis' [hcycl : IsCyclotomicExtension {p} ℚ K] (hζ : IsPrimitiveRoot ζ p) : PowerBasis ℤ (𝓞 K) := have : IsCyclotomicExtension {p ^ 1} ℚ K := by convert hcycl; rw [pow_one] integralPowerBasis (p := p) (k := 1) (ζ := ζ) (by rwa [pow_one]) @[simp] theorem integralPowerBasis'_gen [hcycl : IsCyclotomicExtension {p} ℚ K] (hζ : IsPrimitiveRoot ζ p) : hζ.integralPowerBasis'.gen = hζ.toInteger := integralPowerBasis_gen (hcycl := by rwa [pow_one]) (by rwa [pow_one]) @[simp] theorem power_basis_int'_dim [hcycl : IsCyclotomicExtension {p} ℚ K] (hζ : IsPrimitiveRoot ζ p) : hζ.integralPowerBasis'.dim = φ p := by rw [integralPowerBasis', integralPowerBasis_dim (hcycl := by rwa [pow_one]) (by rwa [pow_one]), pow_one] /-- The integral `PowerBasis` of `𝓞 K` given by `ζ - 1`, where `K` is a `p ^ k` cyclotomic extension of `ℚ`. -/ noncomputable def subOneIntegralPowerBasis [IsCyclotomicExtension {p ^ k} ℚ K] (hζ : IsPrimitiveRoot ζ ↑(p ^ k)) : PowerBasis ℤ (𝓞 K) := PowerBasis.ofGenMemAdjoin' hζ.integralPowerBasis (RingOfIntegers.isIntegral _) (by simp only [integralPowerBasis_gen, toInteger] convert Subalgebra.add_mem _ (self_mem_adjoin_singleton ℤ (⟨ζ - 1, _⟩ : 𝓞 K)) (Subalgebra.one_mem _) · simp · exact Subalgebra.sub_mem _ (hζ.isIntegral (by simp)) (Subalgebra.one_mem _)) @[simp] theorem subOneIntegralPowerBasis_gen [IsCyclotomicExtension {p ^ k} ℚ K] (hζ : IsPrimitiveRoot ζ ↑(p ^ k)) : hζ.subOneIntegralPowerBasis.gen = ⟨ζ - 1, Subalgebra.sub_mem _ (hζ.isIntegral (p ^ k).pos) (Subalgebra.one_mem _)⟩ := by simp [subOneIntegralPowerBasis] /-- The integral `PowerBasis` of `𝓞 K` given by `ζ - 1`, where `K` is a `p`-th cyclotomic extension of `ℚ`. -/ noncomputable def subOneIntegralPowerBasis' [IsCyclotomicExtension {p} ℚ K] (hζ : IsPrimitiveRoot ζ p) : PowerBasis ℤ (𝓞 K) := have : IsCyclotomicExtension {p ^ 1} ℚ K := by rwa [pow_one] subOneIntegralPowerBasis (p := p) (k := 1) (ζ := ζ) (by rwa [pow_one]) @[simp, nolint unusedHavesSuffices] theorem subOneIntegralPowerBasis'_gen [IsCyclotomicExtension {p} ℚ K] (hζ : IsPrimitiveRoot ζ p) : hζ.subOneIntegralPowerBasis'.gen = hζ.toInteger - 1 := -- The `unusedHavesSuffices` linter incorrectly thinks this `have` is unnecessary. have : IsCyclotomicExtension {p ^ 1} ℚ K := by rwa [pow_one] subOneIntegralPowerBasis_gen (by rwa [pow_one]) /-- `ζ - 1` is prime if `p ≠ 2` and `ζ` is a primitive `p ^ (k + 1)`-th root of unity. See `zeta_sub_one_prime` for a general statement. -/ theorem zeta_sub_one_prime_of_ne_two [IsCyclotomicExtension {p ^ (k + 1)} ℚ K] (hζ : IsPrimitiveRoot ζ ↑(p ^ (k + 1))) (hodd : p ≠ 2) : Prime (hζ.toInteger - 1) := by letI := IsCyclotomicExtension.numberField {p ^ (k + 1)} ℚ K refine Ideal.prime_of_irreducible_absNorm_span (fun h ↦ ?_) ?_
· apply hζ.pow_ne_one_of_pos_of_lt zero_lt_one (one_lt_pow₀ hp.out.one_lt (by simp)) rw [sub_eq_zero] at h simpa using congrArg (algebraMap _ K) h rw [Nat.irreducible_iff_prime, Ideal.absNorm_span_singleton, ← Nat.prime_iff,
Mathlib/NumberTheory/Cyclotomic/Rat.lean
295
298
/- Copyright (c) 2023 David Kurniadi Angdinata. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: David Kurniadi Angdinata -/ import Mathlib.Algebra.Polynomial.Bivariate import Mathlib.AlgebraicGeometry.EllipticCurve.Weierstrass import Mathlib.AlgebraicGeometry.EllipticCurve.VariableChange /-! # Affine coordinates for Weierstrass curves This file defines the type of points on a Weierstrass curve as an inductive, consisting of the point at infinity and affine points satisfying a Weierstrass equation with a nonsingular condition. This file also defines the negation and addition operations of the group law for this type, and proves that they respect the Weierstrass equation and the nonsingular condition. The fact that they form an abelian group is proven in `Mathlib/AlgebraicGeometry/EllipticCurve/Group.lean`. ## Mathematical background Let `W` be a Weierstrass curve over a field `F` with coefficients `aᵢ`. An *affine point* on `W` is a tuple `(x, y)` of elements in `R` satisfying the *Weierstrass equation* `W(X, Y) = 0` in *affine coordinates*, where `W(X, Y) := Y² + a₁XY + a₃Y - (X³ + a₂X² + a₄X + a₆)`. It is *nonsingular* if its partial derivatives `W_X(x, y)` and `W_Y(x, y)` do not vanish simultaneously. The nonsingular affine points on `W` can be given negation and addition operations defined by a secant-and-tangent process. * Given a nonsingular affine point `P`, its *negation* `-P` is defined to be the unique third nonsingular point of intersection between `W` and the vertical line through `P`. Explicitly, if `P` is `(x, y)`, then `-P` is `(x, -y - a₁x - a₃)`. * Given two nonsingular affine points `P` and `Q`, their *addition* `P + Q` is defined to be the negation of the unique third nonsingular point of intersection between `W` and the line `L` through `P` and `Q`. Explicitly, let `P` be `(x₁, y₁)` and let `Q` be `(x₂, y₂)`. * If `x₁ = x₂` and `y₁ = -y₂ - a₁x₂ - a₃`, then `L` is vertical. * If `x₁ = x₂` and `y₁ ≠ -y₂ - a₁x₂ - a₃`, then `L` is the tangent of `W` at `P = Q`, and has slope `ℓ := (3x₁² + 2a₂x₁ + a₄ - a₁y₁) / (2y₁ + a₁x₁ + a₃)`. * Otherwise `x₁ ≠ x₂`, then `L` is the secant of `W` through `P` and `Q`, and has slope `ℓ := (y₁ - y₂) / (x₁ - x₂)`. In the last two cases, the `X`-coordinate of `P + Q` is then the unique third solution of the equation obtained by substituting the line `Y = ℓ(X - x₁) + y₁` into the Weierstrass equation, and can be written down explicitly as `x := ℓ² + a₁ℓ - a₂ - x₁ - x₂` by inspecting the coefficients of `X²`. The `Y`-coordinate of `P + Q`, after applying the final negation that maps `Y` to `-Y - a₁X - a₃`, is precisely `y := -(ℓ(x - x₁) + y₁) - a₁x - a₃`. The type of nonsingular points `W⟮F⟯` in affine coordinates is an inductive, consisting of the unique point at infinity `𝓞` and nonsingular affine points `(x, y)`. Then `W⟮F⟯` can be endowed with a group law, with `𝓞` as the identity nonsingular point, which is uniquely determined by these formulae. ## Main definitions * `WeierstrassCurve.Affine.Equation`: the Weierstrass equation of an affine Weierstrass curve. * `WeierstrassCurve.Affine.Nonsingular`: the nonsingular condition on an affine Weierstrass curve. * `WeierstrassCurve.Affine.Point`: a nonsingular rational point on an affine Weierstrass curve. * `WeierstrassCurve.Affine.Point.neg`: the negation operation on an affine Weierstrass curve. * `WeierstrassCurve.Affine.Point.add`: the addition operation on an affine Weierstrass curve. ## Main statements * `WeierstrassCurve.Affine.equation_neg`: negation preserves the Weierstrass equation. * `WeierstrassCurve.Affine.equation_add`: addition preserves the Weierstrass equation. * `WeierstrassCurve.Affine.nonsingular_neg`: negation preserves the nonsingular condition. * `WeierstrassCurve.Affine.nonsingular_add`: addition preserves the nonsingular condition. * `WeierstrassCurve.Affine.nonsingular_of_Δ_ne_zero`: an affine Weierstrass curve is nonsingular at every point if its discriminant is non-zero. * `WeierstrassCurve.Affine.nonsingular`: an affine elliptic curve is nonsingular at every point. ## Notations * `W⟮K⟯`: the group of nonsingular rational points on `W` base changed to `K`. ## References [J Silverman, *The Arithmetic of Elliptic Curves*][silverman2009] ## Tags elliptic curve, rational point, affine coordinates -/ open Polynomial open scoped Polynomial.Bivariate local macro "C_simp" : tactic => `(tactic| simp only [map_ofNat, C_0, C_1, C_neg, C_add, C_sub, C_mul, C_pow]) local macro "derivative_simp" : tactic => `(tactic| simp only [derivative_C, derivative_X, derivative_X_pow, derivative_neg, derivative_add, derivative_sub, derivative_mul, derivative_sq]) local macro "eval_simp" : tactic => `(tactic| simp only [eval_C, eval_X, eval_neg, eval_add, eval_sub, eval_mul, eval_pow, evalEval]) local macro "map_simp" : tactic => `(tactic| simp only [map_ofNat, map_neg, map_add, map_sub, map_mul, map_pow, map_div₀, Polynomial.map_ofNat, map_C, map_X, Polynomial.map_neg, Polynomial.map_add, Polynomial.map_sub, Polynomial.map_mul, Polynomial.map_pow, Polynomial.map_div, coe_mapRingHom, WeierstrassCurve.map]) universe r s u v w /-! ## Weierstrass curves -/ namespace WeierstrassCurve variable {R : Type r} {S : Type s} {A F : Type u} {B K : Type v} {L : Type w} variable (R) in /-- An abbreviation for a Weierstrass curve in affine coordinates. -/ abbrev Affine : Type r := WeierstrassCurve R /-- The conversion from a Weierstrass curve to affine coordinates. -/ abbrev toAffine (W : WeierstrassCurve R) : Affine R := W namespace Affine variable [CommRing R] [CommRing S] [CommRing A] [CommRing B] [Field F] [Field K] [Field L] {W' : Affine R} {W : Affine F} section Equation /-! ### Weierstrass equations -/ variable (W') in /-- The polynomial `W(X, Y) := Y² + a₁XY + a₃Y - (X³ + a₂X² + a₄X + a₆)` associated to a Weierstrass curve `W` over a ring `R` in affine coordinates. For ease of polynomial manipulation, this is represented as a term of type `R[X][X]`, where the inner variable represents `X` and the outer variable represents `Y`. For clarity, the alternative notations `Y` and `R[X][Y]` are provided in the `Polynomial.Bivariate` scope to represent the outer variable and the bivariate polynomial ring `R[X][X]` respectively. -/ noncomputable def polynomial : R[X][Y] := Y ^ 2 + C (C W'.a₁ * X + C W'.a₃) * Y - C (X ^ 3 + C W'.a₂ * X ^ 2 + C W'.a₄ * X + C W'.a₆) lemma polynomial_eq : W'.polynomial = Cubic.toPoly ⟨0, 1, Cubic.toPoly ⟨0, 0, W'.a₁, W'.a₃⟩, Cubic.toPoly ⟨-1, -W'.a₂, -W'.a₄, -W'.a₆⟩⟩ := by simp only [polynomial, Cubic.toPoly] C_simp ring1 lemma polynomial_ne_zero [Nontrivial R] : W'.polynomial ≠ 0 := by rw [polynomial_eq] exact Cubic.ne_zero_of_b_ne_zero one_ne_zero @[simp] lemma degree_polynomial [Nontrivial R] : W'.polynomial.degree = 2 := by rw [polynomial_eq] exact Cubic.degree_of_b_ne_zero' one_ne_zero @[simp] lemma natDegree_polynomial [Nontrivial R] : W'.polynomial.natDegree = 2 := by rw [polynomial_eq] exact Cubic.natDegree_of_b_ne_zero' one_ne_zero lemma monic_polynomial : W'.polynomial.Monic := by nontriviality R simpa only [polynomial_eq] using Cubic.monic_of_b_eq_one' lemma irreducible_polynomial [IsDomain R] : Irreducible W'.polynomial := by by_contra h rcases (monic_polynomial.not_irreducible_iff_exists_add_mul_eq_coeff natDegree_polynomial).mp h with ⟨f, g, h0, h1⟩ simp only [polynomial_eq, Cubic.coeff_eq_c, Cubic.coeff_eq_d] at h0 h1 apply_fun degree at h0 h1 rw [Cubic.degree_of_a_ne_zero' <| neg_ne_zero.mpr <| one_ne_zero' R, degree_mul] at h0 apply (h1.symm.le.trans Cubic.degree_of_b_eq_zero').not_lt rcases Nat.WithBot.add_eq_three_iff.mp h0.symm with h | h | h | h iterate 2 rw [degree_add_eq_right_of_degree_lt] <;> simp only [h] <;> decide iterate 2 rw [degree_add_eq_left_of_degree_lt] <;> simp only [h] <;> decide lemma evalEval_polynomial (x y : R) : W'.polynomial.evalEval x y = y ^ 2 + W'.a₁ * x * y + W'.a₃ * y - (x ^ 3 + W'.a₂ * x ^ 2 + W'.a₄ * x + W'.a₆) := by simp only [polynomial] eval_simp rw [add_mul, ← add_assoc] @[simp] lemma evalEval_polynomial_zero : W'.polynomial.evalEval 0 0 = -W'.a₆ := by simp only [evalEval_polynomial, zero_add, zero_sub, mul_zero, zero_pow <| Nat.succ_ne_zero _] variable (W') in /-- The proposition that an affine point `(x, y)` lies in a Weierstrass curve `W`. In other words, it satisfies the Weierstrass equation `W(X, Y) = 0`. -/ def Equation (x y : R) : Prop := W'.polynomial.evalEval x y = 0 lemma equation_iff' (x y : R) : W'.Equation x y ↔ y ^ 2 + W'.a₁ * x * y + W'.a₃ * y - (x ^ 3 + W'.a₂ * x ^ 2 + W'.a₄ * x + W'.a₆) = 0 := by rw [Equation, evalEval_polynomial] lemma equation_iff (x y : R) : W'.Equation x y ↔ y ^ 2 + W'.a₁ * x * y + W'.a₃ * y = x ^ 3 + W'.a₂ * x ^ 2 + W'.a₄ * x + W'.a₆ := by rw [equation_iff', sub_eq_zero] @[simp] lemma equation_zero : W'.Equation 0 0 ↔ W'.a₆ = 0 := by rw [Equation, evalEval_polynomial_zero, neg_eq_zero] lemma equation_iff_variableChange (x y : R) : W'.Equation x y ↔ (VariableChange.mk 1 x 0 y • W').toAffine.Equation 0 0 := by rw [equation_iff', ← neg_eq_zero, equation_zero, variableChange_a₆, inv_one, Units.val_one] congr! 1 ring1 end Equation section Nonsingular /-! ### Nonsingular Weierstrass equations -/ variable (W') in /-- The partial derivative `W_X(X, Y)` with respect to `X` of the polynomial `W(X, Y)` associated to a Weierstrass curve `W` in affine coordinates. -/ -- TODO: define this in terms of `Polynomial.derivative`. noncomputable def polynomialX : R[X][Y] := C (C W'.a₁) * Y - C (C 3 * X ^ 2 + C (2 * W'.a₂) * X + C W'.a₄) lemma evalEval_polynomialX (x y : R) : W'.polynomialX.evalEval x y = W'.a₁ * y - (3 * x ^ 2 + 2 * W'.a₂ * x + W'.a₄) := by simp only [polynomialX] eval_simp @[simp] lemma evalEval_polynomialX_zero : W'.polynomialX.evalEval 0 0 = -W'.a₄ := by simp only [evalEval_polynomialX, zero_add, zero_sub, mul_zero, zero_pow <| Nat.succ_ne_zero _] variable (W') in /-- The partial derivative `W_Y(X, Y)` with respect to `Y` of the polynomial `W(X, Y)` associated to a Weierstrass curve `W` in affine coordinates. -/ -- TODO: define this in terms of `Polynomial.derivative`. noncomputable def polynomialY : R[X][Y] := C (C 2) * Y + C (C W'.a₁ * X + C W'.a₃) lemma evalEval_polynomialY (x y : R) : W'.polynomialY.evalEval x y = 2 * y + W'.a₁ * x + W'.a₃ := by simp only [polynomialY] eval_simp rw [← add_assoc] @[simp] lemma evalEval_polynomialY_zero : W'.polynomialY.evalEval 0 0 = W'.a₃ := by simp only [evalEval_polynomialY, zero_add, mul_zero] variable (W') in /-- The proposition that an affine point `(x, y)` on a Weierstrass curve `W` is nonsingular. In other words, either `W_X(x, y) ≠ 0` or `W_Y(x, y) ≠ 0`. Note that this definition is only mathematically accurate for fields. -/ -- TODO: generalise this definition to be mathematically accurate for a larger class of rings. def Nonsingular (x y : R) : Prop := W'.Equation x y ∧ (W'.polynomialX.evalEval x y ≠ 0 ∨ W'.polynomialY.evalEval x y ≠ 0) lemma nonsingular_iff' (x y : R) : W'.Nonsingular x y ↔ W'.Equation x y ∧ (W'.a₁ * y - (3 * x ^ 2 + 2 * W'.a₂ * x + W'.a₄) ≠ 0 ∨ 2 * y + W'.a₁ * x + W'.a₃ ≠ 0) := by rw [Nonsingular, equation_iff', evalEval_polynomialX, evalEval_polynomialY] lemma nonsingular_iff (x y : R) : W'.Nonsingular x y ↔ W'.Equation x y ∧ (W'.a₁ * y ≠ 3 * x ^ 2 + 2 * W'.a₂ * x + W'.a₄ ∨ y ≠ -y - W'.a₁ * x - W'.a₃) := by rw [nonsingular_iff', sub_ne_zero, ← sub_ne_zero (a := y)] congr! 3 ring1 @[simp] lemma nonsingular_zero : W'.Nonsingular 0 0 ↔ W'.a₆ = 0 ∧ (W'.a₃ ≠ 0 ∨ W'.a₄ ≠ 0) := by rw [Nonsingular, equation_zero, evalEval_polynomialX_zero, neg_ne_zero, evalEval_polynomialY_zero, or_comm] lemma nonsingular_iff_variableChange (x y : R) : W'.Nonsingular x y ↔ (VariableChange.mk 1 x 0 y • W').toAffine.Nonsingular 0 0 := by rw [nonsingular_iff', equation_iff_variableChange, equation_zero, ← neg_ne_zero, or_comm, nonsingular_zero, variableChange_a₃, variableChange_a₄, inv_one, Units.val_one] simp only [variableChange_def] congr! 3 <;> ring1 private lemma equation_zero_iff_nonsingular_zero_of_Δ_ne_zero (hΔ : W'.Δ ≠ 0) : W'.Equation 0 0 ↔ W'.Nonsingular 0 0 := by simp only [equation_zero, nonsingular_zero, iff_self_and] contrapose! hΔ simp only [b₂, b₄, b₆, b₈, Δ, hΔ] ring1 /-- A Weierstrass curve is nonsingular at every point if its discriminant is non-zero. -/ lemma equation_iff_nonsingular_of_Δ_ne_zero {x y : R} (hΔ : W'.Δ ≠ 0) : W'.Equation x y ↔ W'.Nonsingular x y := by rw [equation_iff_variableChange, nonsingular_iff_variableChange, equation_zero_iff_nonsingular_zero_of_Δ_ne_zero <| by rwa [variableChange_Δ, inv_one, Units.val_one, one_pow, one_mul]] /-- An elliptic curve is nonsingular at every point. -/ lemma equation_iff_nonsingular [Nontrivial R] [W'.IsElliptic] {x y : R} : W'.toAffine.Equation x y ↔ W'.toAffine.Nonsingular x y := W'.toAffine.equation_iff_nonsingular_of_Δ_ne_zero <| W'.coe_Δ' ▸ W'.Δ'.ne_zero @[deprecated (since := "2025-03-01")] alias nonsingular_zero_of_Δ_ne_zero := equation_iff_nonsingular_of_Δ_ne_zero @[deprecated (since := "2025-03-01")] alias nonsingular_of_Δ_ne_zero := equation_iff_nonsingular_of_Δ_ne_zero @[deprecated (since := "2025-03-01")] alias nonsingular := equation_iff_nonsingular end Nonsingular section Ring /-! ### Group operation polynomials over a ring -/ variable (W') in /-- The negation polynomial `-Y - a₁X - a₃` associated to the negation of a nonsingular affine point on a Weierstrass curve. -/ noncomputable def negPolynomial : R[X][Y] := -(Y : R[X][Y]) - C (C W'.a₁ * X + C W'.a₃) lemma Y_sub_polynomialY : Y - W'.polynomialY = W'.negPolynomial := by rw [polynomialY, negPolynomial] C_simp ring1 lemma Y_sub_negPolynomial : Y - W'.negPolynomial = W'.polynomialY := by rw [← Y_sub_polynomialY, sub_sub_cancel] variable (W') in /-- The `Y`-coordinate of `-(x, y)` for a nonsingular affine point `(x, y)` on a Weierstrass curve `W`. This depends on `W`, and has argument order: `x`, `y`. -/ @[simp] def negY (x y : R) : R := -y - W'.a₁ * x - W'.a₃ lemma negY_negY (x y : R) : W'.negY x (W'.negY x y) = y := by simp only [negY] ring1 lemma evalEval_negPolynomial (x y : R) : W'.negPolynomial.evalEval x y = W'.negY x y := by rw [negY, sub_sub, negPolynomial] eval_simp @[deprecated (since := "2025-03-05")] alias eval_negPolynomial := evalEval_negPolynomial /-- The line polynomial `ℓ(X - x) + y` associated to the line `Y = ℓ(X - x) + y` that passes through a nonsingular affine point `(x, y)` on a Weierstrass curve `W` with a slope of `ℓ`. This does not depend on `W`, and has argument order: `x`, `y`, `ℓ`. -/ noncomputable def linePolynomial (x y ℓ : R) : R[X] := C ℓ * (X - C x) + C y variable (W') in /-- The addition polynomial obtained by substituting the line `Y = ℓ(X - x) + y` into the polynomial `W(X, Y)` associated to a Weierstrass curve `W`. If such a line intersects `W` at another nonsingular affine point `(x', y')` on `W`, then the roots of this polynomial are precisely `x`, `x'`, and the `X`-coordinate of the addition of `(x, y)` and `(x', y')`. This depends on `W`, and has argument order: `x`, `y`, `ℓ`. -/ noncomputable def addPolynomial (x y ℓ : R) : R[X] := W'.polynomial.eval <| linePolynomial x y ℓ lemma C_addPolynomial (x y ℓ : R) : C (W'.addPolynomial x y ℓ) = (Y - C (linePolynomial x y ℓ)) * (W'.negPolynomial - C (linePolynomial x y ℓ)) + W'.polynomial := by rw [addPolynomial, linePolynomial, polynomial, negPolynomial] eval_simp C_simp ring1 lemma addPolynomial_eq (x y ℓ : R) : W'.addPolynomial x y ℓ = -Cubic.toPoly ⟨1, -ℓ ^ 2 - W'.a₁ * ℓ + W'.a₂, 2 * x * ℓ ^ 2 + (W'.a₁ * x - 2 * y - W'.a₃) * ℓ + (-W'.a₁ * y + W'.a₄), -x ^ 2 * ℓ ^ 2 + (2 * x * y + W'.a₃ * x) * ℓ - (y ^ 2 + W'.a₃ * y - W'.a₆)⟩ := by rw [addPolynomial, linePolynomial, polynomial, Cubic.toPoly] eval_simp C_simp ring1 variable (W') in /-- The `X`-coordinate of `(x₁, y₁) + (x₂, y₂)` for two nonsingular affine points `(x₁, y₁)` and `(x₂, y₂)` on a Weierstrass curve `W`, where the line through them has a slope of `ℓ`. This depends on `W`, and has argument order: `x₁`, `x₂`, `ℓ`. -/ @[simp] def addX (x₁ x₂ ℓ : R) : R := ℓ ^ 2 + W'.a₁ * ℓ - W'.a₂ - x₁ - x₂ variable (W') in /-- The `Y`-coordinate of `-((x₁, y₁) + (x₂, y₂))` for two nonsingular affine points `(x₁, y₁)` and `(x₂, y₂)` on a Weierstrass curve `W`, where the line through them has a slope of `ℓ`. This depends on `W`, and has argument order: `x₁`, `x₂`, `y₁`, `ℓ`. -/ @[simp] def negAddY (x₁ x₂ y₁ ℓ : R) : R := ℓ * (W'.addX x₁ x₂ ℓ - x₁) + y₁ variable (W') in /-- The `Y`-coordinate of `(x₁, y₁) + (x₂, y₂)` for two nonsingular affine points `(x₁, y₁)` and `(x₂, y₂)` on a Weierstrass curve `W`, where the line through them has a slope of `ℓ`. This depends on `W`, and has argument order: `x₁`, `x₂`, `y₁`, `ℓ`. -/ @[simp] def addY (x₁ x₂ y₁ ℓ : R) : R := W'.negY (W'.addX x₁ x₂ ℓ) (W'.negAddY x₁ x₂ y₁ ℓ) lemma equation_neg (x y : R) : W'.Equation x (W'.negY x y) ↔ W'.Equation x y := by rw [equation_iff, equation_iff, negY] congr! 1 ring1 @[deprecated (since := "2025-02-01")] alias equation_neg_of := equation_neg @[deprecated (since := "2025-02-01")] alias equation_neg_iff := equation_neg lemma nonsingular_neg (x y : R) : W'.Nonsingular x (W'.negY x y) ↔ W'.Nonsingular x y := by rw [nonsingular_iff, equation_neg, ← negY, negY_negY, ← @ne_comm _ y, nonsingular_iff] exact and_congr_right' <| (iff_congr not_and_or.symm not_and_or.symm).mpr <| not_congr <| and_congr_left fun h => by rw [← h] @[deprecated (since := "2025-02-01")] alias nonsingular_neg_of := nonsingular_neg @[deprecated (since := "2025-02-01")] alias nonsingular_neg_iff := nonsingular_neg lemma equation_add_iff (x₁ x₂ y₁ ℓ : R) : W'.Equation (W'.addX x₁ x₂ ℓ) (W'.negAddY x₁ x₂ y₁ ℓ) ↔ (W'.addPolynomial x₁ y₁ ℓ).eval (W'.addX x₁ x₂ ℓ) = 0 := by rw [Equation, negAddY, addPolynomial, linePolynomial, polynomial] eval_simp lemma nonsingular_negAdd_of_eval_derivative_ne_zero {x₁ x₂ y₁ ℓ : R} (hx' : W'.Equation (W'.addX x₁ x₂ ℓ) (W'.negAddY x₁ x₂ y₁ ℓ)) (hx : (W'.addPolynomial x₁ y₁ ℓ).derivative.eval (W'.addX x₁ x₂ ℓ) ≠ 0) : W'.Nonsingular (W'.addX x₁ x₂ ℓ) (W'.negAddY x₁ x₂ y₁ ℓ) := by rw [Nonsingular, and_iff_right hx', negAddY, polynomialX, polynomialY] eval_simp contrapose! hx rw [addPolynomial, linePolynomial, polynomial] eval_simp derivative_simp simp only [zero_add, add_zero, sub_zero, zero_mul, mul_one] eval_simp linear_combination (norm := (norm_num1; ring1)) hx.left + ℓ * hx.right end Ring section Field /-! ### Group operation polynomials over a field -/ open Classical in variable (W) in /-- The slope of the line through two nonsingular affine points `(x₁, y₁)` and `(x₂, y₂)` on a Weierstrass curve `W`. If `x₁ ≠ x₂`, then this line is the secant of `W` through `(x₁, y₁)` and `(x₂, y₂)`, and has slope `(y₁ - y₂) / (x₁ - x₂)`. Otherwise, if `y₁ ≠ -y₁ - a₁x₁ - a₃`, then this line is the tangent of `W` at `(x₁, y₁) = (x₂, y₂)`, and has slope `(3x₁² + 2a₂x₁ + a₄ - a₁y₁) / (2y₁ + a₁x₁ + a₃)`. Otherwise, this line is vertical, in which case this returns the value `0`. This depends on `W`, and has argument order: `x₁`, `x₂`, `y₁`, `y₂`. -/ noncomputable def slope (x₁ x₂ y₁ y₂ : F) : F := if x₁ = x₂ then if y₁ = W.negY x₂ y₂ then 0 else (3 * x₁ ^ 2 + 2 * W.a₂ * x₁ + W.a₄ - W.a₁ * y₁) / (y₁ - W.negY x₁ y₁) else (y₁ - y₂) / (x₁ - x₂) @[simp] lemma slope_of_Y_eq {x₁ x₂ y₁ y₂ : F} (hx : x₁ = x₂) (hy : y₁ = W.negY x₂ y₂) : W.slope x₁ x₂ y₁ y₂ = 0 := by rw [slope, if_pos hx, if_pos hy] @[simp] lemma slope_of_Y_ne {x₁ x₂ y₁ y₂ : F} (hx : x₁ = x₂) (hy : y₁ ≠ W.negY x₂ y₂) : W.slope x₁ x₂ y₁ y₂ = (3 * x₁ ^ 2 + 2 * W.a₂ * x₁ + W.a₄ - W.a₁ * y₁) / (y₁ - W.negY x₁ y₁) := by rw [slope, if_pos hx, if_neg hy] @[simp] lemma slope_of_X_ne {x₁ x₂ y₁ y₂ : F} (hx : x₁ ≠ x₂) : W.slope x₁ x₂ y₁ y₂ = (y₁ - y₂) / (x₁ - x₂) := by rw [slope, if_neg hx] lemma slope_of_Y_ne_eq_evalEval {x₁ x₂ y₁ y₂ : F} (hx : x₁ = x₂) (hy : y₁ ≠ W.negY x₂ y₂) : W.slope x₁ x₂ y₁ y₂ = -W.polynomialX.evalEval x₁ y₁ / W.polynomialY.evalEval x₁ y₁ := by rw [slope_of_Y_ne hx hy, evalEval_polynomialX, neg_sub] congr 1 rw [negY, evalEval_polynomialY] ring1 @[deprecated (since := "2025-03-05")] alias slope_of_Y_ne_eq_eval := slope_of_Y_ne_eq_evalEval lemma Y_eq_of_X_eq {x₁ x₂ y₁ y₂ : F} (h₁ : W.Equation x₁ y₁) (h₂ : W.Equation x₂ y₂) (hx : x₁ = x₂) : y₁ = y₂ ∨ y₁ = W.negY x₂ y₂ := by rw [equation_iff] at h₁ h₂ rw [← sub_eq_zero, ← sub_eq_zero (a := y₁), ← mul_eq_zero, negY] linear_combination (norm := (rw [hx]; ring1)) h₁ - h₂ lemma Y_eq_of_Y_ne {x₁ x₂ y₁ y₂ : F} (h₁ : W.Equation x₁ y₁) (h₂ : W.Equation x₂ y₂) (hx : x₁ = x₂) (hy : y₁ ≠ W.negY x₂ y₂) : y₁ = y₂ := (Y_eq_of_X_eq h₁ h₂ hx).resolve_right hy lemma addPolynomial_slope {x₁ x₂ y₁ y₂ : F} (h₁ : W.Equation x₁ y₁) (h₂ : W.Equation x₂ y₂) (hxy : ¬(x₁ = x₂ ∧ y₁ = W.negY x₂ y₂)) : W.addPolynomial x₁ y₁ (W.slope x₁ x₂ y₁ y₂) = -((X - C x₁) * (X - C x₂) * (X - C (W.addX x₁ x₂ <| W.slope x₁ x₂ y₁ y₂))) := by rw [addPolynomial_eq, neg_inj, Cubic.prod_X_sub_C_eq, Cubic.toPoly_injective] by_cases hx : x₁ = x₂ · have hy : y₁ ≠ W.negY x₂ y₂ := fun h => hxy ⟨hx, h⟩ rcases hx, Y_eq_of_Y_ne h₁ h₂ hx hy with ⟨rfl, rfl⟩ rw [equation_iff] at h₁ h₂ rw [slope_of_Y_ne rfl hy] rw [negY, ← sub_ne_zero] at hy ext · rfl · simp only [addX] ring1 · field_simp [hy] ring1 · linear_combination (norm := (field_simp [hy]; ring1)) -h₁ · rw [equation_iff] at h₁ h₂ rw [slope_of_X_ne hx] rw [← sub_eq_zero] at hx ext · rfl · simp only [addX] ring1 · apply mul_right_injective₀ hx linear_combination (norm := (field_simp [hx]; ring1)) h₂ - h₁ · apply mul_right_injective₀ hx linear_combination (norm := (field_simp [hx]; ring1)) x₂ * h₁ - x₁ * h₂ /-- The negated addition of two affine points in `W` on a sloped line lies in `W`. -/ lemma equation_negAdd {x₁ x₂ y₁ y₂ : F} (h₁ : W.Equation x₁ y₁) (h₂ : W.Equation x₂ y₂) (hxy : ¬(x₁ = x₂ ∧ y₁ = W.negY x₂ y₂)) : W.Equation (W.addX x₁ x₂ <| W.slope x₁ x₂ y₁ y₂) (W.negAddY x₁ x₂ y₁ <| W.slope x₁ x₂ y₁ y₂) := by rw [equation_add_iff, addPolynomial_slope h₁ h₂ hxy] eval_simp rw [neg_eq_zero, sub_self, mul_zero] /-- The addition of two affine points in `W` on a sloped line lies in `W`. -/ lemma equation_add {x₁ x₂ y₁ y₂ : F} (h₁ : W.Equation x₁ y₁) (h₂ : W.Equation x₂ y₂) (hxy : ¬(x₁ = x₂ ∧ y₁ = W.negY x₂ y₂)) : W.Equation (W.addX x₁ x₂ <| W.slope x₁ x₂ y₁ y₂) (W.addY x₁ x₂ y₁ <| W.slope x₁ x₂ y₁ y₂) := (equation_neg ..).mpr <| equation_negAdd h₁ h₂ hxy lemma C_addPolynomial_slope {x₁ x₂ y₁ y₂ : F} (h₁ : W.Equation x₁ y₁) (h₂ : W.Equation x₂ y₂) (hxy : ¬(x₁ = x₂ ∧ y₁ = W.negY x₂ y₂)) : C (W.addPolynomial x₁ y₁ <| W.slope x₁ x₂ y₁ y₂) = -(C (X - C x₁) * C (X - C x₂) * C (X - C (W.addX x₁ x₂ <| W.slope x₁ x₂ y₁ y₂))) := by rw [addPolynomial_slope h₁ h₂ hxy] map_simp lemma derivative_addPolynomial_slope {x₁ x₂ y₁ y₂ : F} (h₁ : W.Equation x₁ y₁) (h₂ : W.Equation x₂ y₂) (hxy : ¬(x₁ = x₂ ∧ y₁ = W.negY x₂ y₂)) : derivative (W.addPolynomial x₁ y₁ <| W.slope x₁ x₂ y₁ y₂) = -((X - C x₁) * (X - C x₂) + (X - C x₁) * (X - C (W.addX x₁ x₂ <| W.slope x₁ x₂ y₁ y₂)) + (X - C x₂) * (X - C (W.addX x₁ x₂ <| W.slope x₁ x₂ y₁ y₂))) := by rw [addPolynomial_slope h₁ h₂ hxy] derivative_simp ring1 /-- The negated addition of two nonsingular affine points in `W` on a sloped line is nonsingular. -/ lemma nonsingular_negAdd {x₁ x₂ y₁ y₂ : F} (h₁ : W.Nonsingular x₁ y₁) (h₂ : W.Nonsingular x₂ y₂) (hxy : ¬(x₁ = x₂ ∧ y₁ = W.negY x₂ y₂)) : W.Nonsingular (W.addX x₁ x₂ <| W.slope x₁ x₂ y₁ y₂) (W.negAddY x₁ x₂ y₁ <| W.slope x₁ x₂ y₁ y₂) := by by_cases hx₁ : W.addX x₁ x₂ (W.slope x₁ x₂ y₁ y₂) = x₁ · rwa [negAddY, hx₁, sub_self, mul_zero, zero_add] · by_cases hx₂ : W.addX x₁ x₂ (W.slope x₁ x₂ y₁ y₂) = x₂ · by_cases hx : x₁ = x₂ · subst hx contradiction · rwa [negAddY, ← neg_sub, mul_neg, hx₂, slope_of_X_ne hx, div_mul_cancel₀ _ <| sub_ne_zero_of_ne hx, neg_sub, sub_add_cancel] · apply nonsingular_negAdd_of_eval_derivative_ne_zero <| equation_negAdd h₁.left h₂.left hxy rw [derivative_addPolynomial_slope h₁.left h₂.left hxy] eval_simp simp only [neg_ne_zero, sub_self, mul_zero, add_zero] exact mul_ne_zero (sub_ne_zero_of_ne hx₁) (sub_ne_zero_of_ne hx₂) /-- The addition of two nonsingular affine points in `W` on a sloped line is nonsingular. -/ lemma nonsingular_add {x₁ x₂ y₁ y₂ : F} (h₁ : W.Nonsingular x₁ y₁) (h₂ : W.Nonsingular x₂ y₂) (hxy : ¬(x₁ = x₂ ∧ y₁ = W.negY x₂ y₂)) : W.Nonsingular (W.addX x₁ x₂ <| W.slope x₁ x₂ y₁ y₂) (W.addY x₁ x₂ y₁ <| W.slope x₁ x₂ y₁ y₂) := (nonsingular_neg ..).mpr <| nonsingular_negAdd h₁ h₂ hxy /-- The formula `x(P₁ + P₂) = x(P₁ - P₂) - ψ(P₁)ψ(P₂) / (x(P₂) - x(P₁))²`, where `ψ(x,y) = 2y + a₁x + a₃`. -/ lemma addX_eq_addX_negY_sub {x₁ x₂ : F} (y₁ y₂ : F) (hx : x₁ ≠ x₂) : W.addX x₁ x₂ (W.slope x₁ x₂ y₁ y₂) = W.addX x₁ x₂ (W.slope x₁ x₂ y₁ <| W.negY x₂ y₂) - (y₁ - W.negY x₁ y₁) * (y₂ - W.negY x₂ y₂) / (x₂ - x₁) ^ 2 := by simp_rw [slope_of_X_ne hx, addX, negY, ← neg_sub x₁, neg_sq] field_simp [sub_ne_zero.mpr hx] ring1 /-- The formula `y(P₁)(x(P₂) - x(P₃)) + y(P₂)(x(P₃) - x(P₁)) + y(P₃)(x(P₁) - x(P₂)) = 0`, assuming that `P₁ + P₂ + P₃ = O`. -/ lemma cyclic_sum_Y_mul_X_sub_X {x₁ x₂ : F} (y₁ y₂ : F) (hx : x₁ ≠ x₂) : let x₃ := W.addX x₁ x₂ (W.slope x₁ x₂ y₁ y₂) y₁ * (x₂ - x₃) + y₂ * (x₃ - x₁) + W.negAddY x₁ x₂ y₁ (W.slope x₁ x₂ y₁ y₂) * (x₁ - x₂) = 0 := by simp_rw [slope_of_X_ne hx, negAddY, addX] field_simp [sub_ne_zero.mpr hx] ring1 /-- The formula `ψ(P₁ + P₂) = (ψ(P₂)(x(P₁) - x(P₃)) - ψ(P₁)(x(P₂) - x(P₃))) / (x(P₂) - x(P₁))`, where `ψ(x,y) = 2y + a₁x + a₃`. -/ lemma addY_sub_negY_addY {x₁ x₂ : F} (y₁ y₂ : F) (hx : x₁ ≠ x₂) : let x₃ := W.addX x₁ x₂ (W.slope x₁ x₂ y₁ y₂) let y₃ := W.addY x₁ x₂ y₁ (W.slope x₁ x₂ y₁ y₂) y₃ - W.negY x₃ y₃ = ((y₂ - W.negY x₂ y₂) * (x₁ - x₃) - (y₁ - W.negY x₁ y₁) * (x₂ - x₃)) / (x₂ - x₁) := by simp_rw [addY, negY, eq_div_iff (sub_ne_zero.mpr hx.symm)] linear_combination (norm := ring1) 2 * cyclic_sum_Y_mul_X_sub_X y₁ y₂ hx end Field section Group /-! ### Nonsingular points -/ variable (W') in /-- A nonsingular point on a Weierstrass curve `W` in affine coordinates. This is either the unique point at infinity `WeierstrassCurve.Affine.Point.zero` or a nonsingular affine point `WeierstrassCurve.Affine.Point.some (x, y)` satisfying the Weierstrass equation of `W`. -/ inductive Point | zero | some {x y : R} (h : W'.Nonsingular x y) /-- For an algebraic extension `S` of a ring `R`, the type of nonsingular `S`-points on a Weierstrass curve `W` over `R` in affine coordinates. -/ scoped notation3:max W' "⟮" S "⟯" => Affine.Point <| baseChange W' S namespace Point /-! ### Group operations -/ instance : Inhabited W'.Point := ⟨.zero⟩ instance : Zero W'.Point := ⟨.zero⟩ lemma zero_def : 0 = (.zero : W'.Point) := rfl lemma some_ne_zero {x y : R} (h : W'.Nonsingular x y) : Point.some h ≠ 0 := by rintro (_ | _) /-- The negation of a nonsingular point on a Weierstrass curve in affine coordinates. Given a nonsingular point `P` in affine coordinates, use `-P` instead of `neg P`. -/ def neg : W'.Point → W'.Point | 0 => 0 | some h => some <| (nonsingular_neg ..).mpr h instance : Neg W'.Point := ⟨neg⟩ lemma neg_def (P : W'.Point) : -P = P.neg := rfl @[simp] lemma neg_zero : (-0 : W'.Point) = 0 := rfl @[simp] lemma neg_some {x y : R} (h : W'.Nonsingular x y) : -some h = some ((nonsingular_neg ..).mpr h) := rfl instance : InvolutiveNeg W'.Point where neg_neg := by rintro (_ | _) · rfl · simp only [neg_some, negY_negY] open Classical in /-- The addition of two nonsingular points on a Weierstrass curve in affine coordinates. Given two nonsingular points `P` and `Q` in affine coordinates, use `P + Q` instead of `add P Q`. -/ noncomputable def add : W.Point → W.Point → W.Point | 0, P => P | P, 0 => P | @some _ _ _ x₁ y₁ h₁, @some _ _ _ x₂ y₂ h₂ => if hxy : x₁ = x₂ ∧ y₁ = W.negY x₂ y₂ then 0 else some <| nonsingular_add h₁ h₂ hxy noncomputable instance : Add W.Point := ⟨add⟩ noncomputable instance : AddZeroClass W.Point := ⟨by rintro (_ | _) <;> rfl, by rintro (_ | _) <;> rfl⟩ lemma add_def (P Q : W.Point) : P + Q = P.add Q := rfl lemma add_some {x₁ x₂ y₁ y₂ : F} (hxy : ¬(x₁ = x₂ ∧ y₁ = W.negY x₂ y₂)) {h₁ : W.Nonsingular x₁ y₁} {h₂ : W.Nonsingular x₂ y₂} : some h₁ + some h₂ = some (nonsingular_add h₁ h₂ hxy) := by simp only [add_def, add, dif_neg hxy] @[deprecated (since := "2025-02-28")] alias add_of_imp := add_some @[simp] lemma add_of_Y_eq {x₁ x₂ y₁ y₂ : F} {h₁ : W.Nonsingular x₁ y₁} {h₂ : W.Nonsingular x₂ y₂} (hx : x₁ = x₂) (hy : y₁ = W.negY x₂ y₂) : some h₁ + some h₂ = 0 := by simpa only [add_def, add] using dif_pos ⟨hx, hy⟩ @[simp] lemma add_self_of_Y_eq {x₁ y₁ : F} {h₁ : W.Nonsingular x₁ y₁} (hy : y₁ = W.negY x₁ y₁) : some h₁ + some h₁ = 0 := add_of_Y_eq rfl hy @[simp] lemma add_of_Y_ne {x₁ x₂ y₁ y₂ : F} {h₁ : W.Nonsingular x₁ y₁} {h₂ : W.Nonsingular x₂ y₂} (hy : y₁ ≠ W.negY x₂ y₂) : some h₁ + some h₂ = some (nonsingular_add h₁ h₂ fun hxy => hy hxy.right) := add_some fun hxy => hy hxy.right lemma add_of_Y_ne' {x₁ x₂ y₁ y₂ : F} {h₁ : W.Nonsingular x₁ y₁} {h₂ : W.Nonsingular x₂ y₂} (hy : y₁ ≠ W.negY x₂ y₂) : some h₁ + some h₂ = -some (nonsingular_negAdd h₁ h₂ fun hxy => hy hxy.right) := add_of_Y_ne hy @[simp] lemma add_self_of_Y_ne {x₁ y₁ : F} {h₁ : W.Nonsingular x₁ y₁} (hy : y₁ ≠ W.negY x₁ y₁) : some h₁ + some h₁ = some (nonsingular_add h₁ h₁ fun hxy => hy hxy.right) := add_of_Y_ne hy lemma add_self_of_Y_ne' {x₁ y₁ : F} {h₁ : W.Nonsingular x₁ y₁} (hy : y₁ ≠ W.negY x₁ y₁) : some h₁ + some h₁ = -some (nonsingular_negAdd h₁ h₁ fun hxy => hy hxy.right) := add_of_Y_ne hy @[simp] lemma add_of_X_ne {x₁ x₂ y₁ y₂ : F} {h₁ : W.Nonsingular x₁ y₁} {h₂ : W.Nonsingular x₂ y₂} (hx : x₁ ≠ x₂) : some h₁ + some h₂ = some (nonsingular_add h₁ h₂ fun hxy => hx hxy.left) := add_some fun hxy => hx hxy.left lemma add_of_X_ne' {x₁ x₂ y₁ y₂ : F} {h₁ : W.Nonsingular x₁ y₁} {h₂ : W.Nonsingular x₂ y₂} (hx : x₁ ≠ x₂) : some h₁ + some h₂ = -some (nonsingular_negAdd h₁ h₂ fun hxy => hx hxy.left) := add_of_X_ne hx end Point end Group section Map /-! ### Maps across ring homomorphisms -/ variable (f : R →+* S) (x y x₁ y₁ x₂ y₂ ℓ : R) lemma map_polynomial : (W'.map f).toAffine.polynomial = W'.polynomial.map (mapRingHom f) := by simp only [polynomial] map_simp lemma evalEval_baseChange_polynomial : (W'.baseChange R[X][Y]).toAffine.polynomial.evalEval (C X) Y = W'.polynomial := by rw [map_polynomial, evalEval, eval_map, eval_C_X_eval₂_map_C_X] @[deprecated (since := "2025-03-05")] alias evalEval_baseChange_polynomial_X_Y := evalEval_baseChange_polynomial variable {x y} in lemma Equation.map {x y : R} (h : W'.Equation x y) : (W'.map f).toAffine.Equation (f x) (f y) := by rw [Equation, map_polynomial, map_mapRingHom_evalEval, h, map_zero] variable {f} in lemma map_equation (hf : Function.Injective f) : (W'.map f).toAffine.Equation (f x) (f y) ↔ W'.Equation x y := by simp only [Equation, map_polynomial, map_mapRingHom_evalEval, map_eq_zero_iff f hf] lemma map_polynomialX : (W'.map f).toAffine.polynomialX = W'.polynomialX.map (mapRingHom f) := by simp only [polynomialX] map_simp lemma map_polynomialY : (W'.map f).toAffine.polynomialY = W'.polynomialY.map (mapRingHom f) := by simp only [polynomialY] map_simp variable {f} in lemma map_nonsingular (hf : Function.Injective f) : (W'.map f).toAffine.Nonsingular (f x) (f y) ↔ W'.Nonsingular x y := by simp only [Nonsingular, evalEval, map_equation _ _ hf, map_polynomialX, map_polynomialY, map_mapRingHom_evalEval, map_ne_zero_iff f hf] lemma map_negPolynomial : (W'.map f).toAffine.negPolynomial = W'.negPolynomial.map (mapRingHom f) := by simp only [negPolynomial] map_simp lemma map_negY : (W'.map f).toAffine.negY (f x) (f y) = f (W'.negY x y) := by simp only [negY] map_simp lemma map_linePolynomial : linePolynomial (f x) (f y) (f ℓ) = (linePolynomial x y ℓ).map f := by simp only [linePolynomial] map_simp lemma map_addPolynomial : (W'.map f).toAffine.addPolynomial (f x) (f y) (f ℓ) = (W'.addPolynomial x y ℓ).map f := by rw [addPolynomial, map_polynomial, eval_map, linePolynomial, addPolynomial, ← coe_mapRingHom, ← eval₂_hom, linePolynomial] map_simp lemma map_addX : (W'.map f).toAffine.addX (f x₁) (f x₂) (f ℓ) = f (W'.addX x₁ x₂ ℓ) := by simp only [addX] map_simp lemma map_negAddY : (W'.map f).toAffine.negAddY (f x₁) (f x₂) (f y₁) (f ℓ) = f (W'.negAddY x₁ x₂ y₁ ℓ) := by simp only [negAddY, map_addX] map_simp lemma map_addY : (W'.map f).toAffine.addY (f x₁) (f x₂) (f y₁) (f ℓ) = f (W'.toAffine.addY x₁ x₂ y₁ ℓ) := by simp only [addY, map_negAddY, map_addX, map_negY] lemma map_slope (f : F →+* K) (x₁ x₂ y₁ y₂ : F) : (W.map f).toAffine.slope (f x₁) (f x₂) (f y₁) (f y₂) = f (W.slope x₁ x₂ y₁ y₂) := by by_cases hx : x₁ = x₂ · by_cases hy : y₁ = W.negY x₂ y₂ · rw [slope_of_Y_eq (congr_arg f hx) <| by rw [hy, map_negY], slope_of_Y_eq hx hy, map_zero] · rw [slope_of_Y_ne (congr_arg f hx) <| map_negY f x₂ y₂ ▸ fun h => hy <| f.injective h, map_negY, slope_of_Y_ne hx hy] map_simp · rw [slope_of_X_ne fun h => hx <| f.injective h, slope_of_X_ne hx] map_simp end Map section BaseChange /-! ### Base changes across algebra homomorphisms -/ variable [Algebra R S] [Algebra R A] [Algebra S A] [IsScalarTower R S A] [Algebra R B] [Algebra S B] [IsScalarTower R S B] (f : A →ₐ[S] B) (x y x₁ y₁ x₂ y₂ ℓ : A) lemma baseChange_polynomial : (W'.baseChange B).toAffine.polynomial = (W'.baseChange A).toAffine.polynomial.map (mapRingHom f) := by rw [← map_polynomial, map_baseChange] variable {x y} in lemma Equation.baseChange (h : (W'.baseChange A).toAffine.Equation x y) : (W'.baseChange B).toAffine.Equation (f x) (f y) := by convert Equation.map f.toRingHom h using 1 rw [AlgHom.toRingHom_eq_coe, map_baseChange] variable {f} in lemma baseChange_equation (hf : Function.Injective f) : (W'.baseChange B).toAffine.Equation (f x) (f y) ↔ (W'.baseChange A).toAffine.Equation x y := by rw [← map_equation _ _ hf, AlgHom.toRingHom_eq_coe, map_baseChange, RingHom.coe_coe] lemma baseChange_polynomialX : (W'.baseChange B).toAffine.polynomialX = (W'.baseChange A).toAffine.polynomialX.map (mapRingHom f) := by rw [← map_polynomialX, map_baseChange] lemma baseChange_polynomialY : (W'.baseChange B).toAffine.polynomialY = (W'.baseChange A).toAffine.polynomialY.map (mapRingHom f) := by rw [← map_polynomialY, map_baseChange] variable {f} in lemma baseChange_nonsingular (hf : Function.Injective f) : (W'.baseChange B).toAffine.Nonsingular (f x) (f y) ↔ (W'.baseChange A).toAffine.Nonsingular x y := by
rw [← map_nonsingular _ _ hf, AlgHom.toRingHom_eq_coe, map_baseChange, RingHom.coe_coe] lemma baseChange_negPolynomial : (W'.baseChange B).toAffine.negPolynomial =
Mathlib/AlgebraicGeometry/EllipticCurve/Affine.lean
855
857
/- Copyright (c) 2023 Michael Stoll. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Michael Geißer, Michael Stoll -/ import Mathlib.Data.ZMod.Basic import Mathlib.NumberTheory.DiophantineApproximation.Basic import Mathlib.NumberTheory.Zsqrtd.Basic import Mathlib.Tactic.Qify /-! # Pell's Equation *Pell's Equation* is the equation $x^2 - d y^2 = 1$, where $d$ is a positive integer that is not a square, and one is interested in solutions in integers $x$ and $y$. In this file, we aim at providing all of the essential theory of Pell's Equation for general $d$ (as opposed to the contents of `NumberTheory.PellMatiyasevic`, which is specific to the case $d = a^2 - 1$ for some $a > 1$). We begin by defining a type `Pell.Solution₁ d` for solutions of the equation, show that it has a natural structure as an abelian group, and prove some basic properties. We then prove the following **Theorem.** Let $d$ be a positive integer that is not a square. Then the equation $x^2 - d y^2 = 1$ has a nontrivial (i.e., with $y \ne 0$) solution in integers. See `Pell.exists_of_not_isSquare` and `Pell.Solution₁.exists_nontrivial_of_not_isSquare`. We then define the *fundamental solution* to be the solution with smallest $x$ among all solutions satisfying $x > 1$ and $y > 0$. We show that every solution is a power (in the sense of the group structure mentioned above) of the fundamental solution up to a (common) sign, see `Pell.IsFundamental.eq_zpow_or_neg_zpow`, and that a (positive) solution has this property if and only if it is fundamental, see `Pell.pos_generator_iff_fundamental`. ## References * [K. Ireland, M. Rosen, *A classical introduction to modern number theory* (Section 17.5)][IrelandRosen1990] ## Tags Pell's equation ## TODO * Extend to `x ^ 2 - d * y ^ 2 = -1` and further generalizations. * Connect solutions to the continued fraction expansion of `√d`. -/ namespace Pell /-! ### Group structure of the solution set We define a structure of a commutative multiplicative group with distributive negation on the set of all solutions to the Pell equation `x^2 - d*y^2 = 1`. The type of such solutions is `Pell.Solution₁ d`. It corresponds to a pair of integers `x` and `y` and a proof that `(x, y)` is indeed a solution. The multiplication is given by `(x, y) * (x', y') = (x*y' + d*y*y', x*y' + y*x')`. This is obtained by mapping `(x, y)` to `x + y*√d` and multiplying the results. In fact, we define `Pell.Solution₁ d` to be `↥(unitary (ℤ√d))` and transport the "commutative group with distributive negation" structure from `↥(unitary (ℤ√d))`. We then set up an API for `Pell.Solution₁ d`. -/ open CharZero Zsqrtd /-- An element of `ℤ√d` has norm one (i.e., `a.re^2 - d*a.im^2 = 1`) if and only if it is contained in the submonoid of unitary elements. TODO: merge this result with `Pell.isPell_iff_mem_unitary`. -/ theorem is_pell_solution_iff_mem_unitary {d : ℤ} {a : ℤ√d} : a.re ^ 2 - d * a.im ^ 2 = 1 ↔ a ∈ unitary (ℤ√d) := by rw [← norm_eq_one_iff_mem_unitary, norm_def, sq, sq, ← mul_assoc] -- We use `solution₁ d` to allow for a more general structure `solution d m` that -- encodes solutions to `x^2 - d*y^2 = m` to be added later. /-- `Pell.Solution₁ d` is the type of solutions to the Pell equation `x^2 - d*y^2 = 1`. We define this in terms of elements of `ℤ√d` of norm one. -/ def Solution₁ (d : ℤ) : Type := ↥(unitary (ℤ√d)) namespace Solution₁ variable {d : ℤ} instance instCommGroup : CommGroup (Solution₁ d) := inferInstanceAs (CommGroup (unitary (ℤ√d))) instance instHasDistribNeg : HasDistribNeg (Solution₁ d) := inferInstanceAs (HasDistribNeg (unitary (ℤ√d))) instance instInhabited : Inhabited (Solution₁ d) := inferInstanceAs (Inhabited (unitary (ℤ√d))) instance : Coe (Solution₁ d) (ℤ√d) where coe := Subtype.val /-- The `x` component of a solution to the Pell equation `x^2 - d*y^2 = 1` -/ protected def x (a : Solution₁ d) : ℤ := (a : ℤ√d).re /-- The `y` component of a solution to the Pell equation `x^2 - d*y^2 = 1` -/ protected def y (a : Solution₁ d) : ℤ := (a : ℤ√d).im /-- The proof that `a` is a solution to the Pell equation `x^2 - d*y^2 = 1` -/ theorem prop (a : Solution₁ d) : a.x ^ 2 - d * a.y ^ 2 = 1 := is_pell_solution_iff_mem_unitary.mpr a.property /-- An alternative form of the equation, suitable for rewriting `x^2`. -/ theorem prop_x (a : Solution₁ d) : a.x ^ 2 = 1 + d * a.y ^ 2 := by rw [← a.prop]; ring /-- An alternative form of the equation, suitable for rewriting `d * y^2`. -/ theorem prop_y (a : Solution₁ d) : d * a.y ^ 2 = a.x ^ 2 - 1 := by rw [← a.prop]; ring /-- Two solutions are equal if their `x` and `y` components are equal. -/ @[ext] theorem ext {a b : Solution₁ d} (hx : a.x = b.x) (hy : a.y = b.y) : a = b := Subtype.ext <| Zsqrtd.ext hx hy /-- Construct a solution from `x`, `y` and a proof that the equation is satisfied. -/ def mk (x y : ℤ) (prop : x ^ 2 - d * y ^ 2 = 1) : Solution₁ d where val := ⟨x, y⟩ property := is_pell_solution_iff_mem_unitary.mp prop @[simp] theorem x_mk (x y : ℤ) (prop : x ^ 2 - d * y ^ 2 = 1) : (mk x y prop).x = x := rfl @[simp] theorem y_mk (x y : ℤ) (prop : x ^ 2 - d * y ^ 2 = 1) : (mk x y prop).y = y := rfl @[simp] theorem coe_mk (x y : ℤ) (prop : x ^ 2 - d * y ^ 2 = 1) : (↑(mk x y prop) : ℤ√d) = ⟨x, y⟩ := Zsqrtd.ext (x_mk x y prop) (y_mk x y prop) @[simp] theorem x_one : (1 : Solution₁ d).x = 1 := rfl @[simp] theorem y_one : (1 : Solution₁ d).y = 0 := rfl @[simp] theorem x_mul (a b : Solution₁ d) : (a * b).x = a.x * b.x + d * (a.y * b.y) := by rw [← mul_assoc] rfl @[simp] theorem y_mul (a b : Solution₁ d) : (a * b).y = a.x * b.y + a.y * b.x := rfl @[simp] theorem x_inv (a : Solution₁ d) : a⁻¹.x = a.x := rfl @[simp] theorem y_inv (a : Solution₁ d) : a⁻¹.y = -a.y := rfl @[simp] theorem x_neg (a : Solution₁ d) : (-a).x = -a.x := rfl @[simp] theorem y_neg (a : Solution₁ d) : (-a).y = -a.y := rfl /-- When `d` is negative, then `x` or `y` must be zero in a solution. -/ theorem eq_zero_of_d_neg (h₀ : d < 0) (a : Solution₁ d) : a.x = 0 ∨ a.y = 0 := by have h := a.prop contrapose! h have h1 := sq_pos_of_ne_zero h.1 have h2 := sq_pos_of_ne_zero h.2 nlinarith /-- A solution has `x ≠ 0`. -/ theorem x_ne_zero (h₀ : 0 ≤ d) (a : Solution₁ d) : a.x ≠ 0 := by intro hx have h : 0 ≤ d * a.y ^ 2 := mul_nonneg h₀ (sq_nonneg _) rw [a.prop_y, hx, sq, zero_mul, zero_sub] at h exact not_le.mpr (neg_one_lt_zero : (-1 : ℤ) < 0) h /-- A solution with `x > 1` must have `y ≠ 0`. -/ theorem y_ne_zero_of_one_lt_x {a : Solution₁ d} (ha : 1 < a.x) : a.y ≠ 0 := by intro hy have prop := a.prop rw [hy, sq (0 : ℤ), zero_mul, mul_zero, sub_zero] at prop exact lt_irrefl _ (((one_lt_sq_iff₀ <| zero_le_one.trans ha.le).mpr ha).trans_eq prop) /-- If a solution has `x > 1`, then `d` is positive. -/ theorem d_pos_of_one_lt_x {a : Solution₁ d} (ha : 1 < a.x) : 0 < d := by refine pos_of_mul_pos_left ?_ (sq_nonneg a.y) rw [a.prop_y, sub_pos] exact one_lt_pow₀ ha two_ne_zero /-- If a solution has `x > 1`, then `d` is not a square. -/ theorem d_nonsquare_of_one_lt_x {a : Solution₁ d} (ha : 1 < a.x) : ¬IsSquare d := by have hp := a.prop rintro ⟨b, rfl⟩ simp_rw [← sq, ← mul_pow, sq_sub_sq, Int.mul_eq_one_iff_eq_one_or_neg_one] at hp omega /-- A solution with `x = 1` is trivial. -/ theorem eq_one_of_x_eq_one (h₀ : d ≠ 0) {a : Solution₁ d} (ha : a.x = 1) : a = 1 := by have prop := a.prop_y rw [ha, one_pow, sub_self, mul_eq_zero, or_iff_right h₀, sq_eq_zero_iff] at prop exact ext ha prop /-- A solution is `1` or `-1` if and only if `y = 0`. -/ theorem eq_one_or_neg_one_iff_y_eq_zero {a : Solution₁ d} : a = 1 ∨ a = -1 ↔ a.y = 0 := by refine ⟨fun H => H.elim (fun h => by simp [h]) fun h => by simp [h], fun H => ?_⟩ have prop := a.prop rw [H, sq (0 : ℤ), mul_zero, mul_zero, sub_zero, sq_eq_one_iff] at prop exact prop.imp (fun h => ext h H) fun h => ext h H /-- The set of solutions with `x > 0` is closed under multiplication. -/ theorem x_mul_pos {a b : Solution₁ d} (ha : 0 < a.x) (hb : 0 < b.x) : 0 < (a * b).x := by simp only [x_mul] refine neg_lt_iff_pos_add'.mp (abs_lt.mp ?_).1 rw [← abs_of_pos ha, ← abs_of_pos hb, ← abs_mul, ← sq_lt_sq, mul_pow a.x, a.prop_x, b.prop_x, ← sub_pos] ring_nf rcases le_or_lt 0 d with h | h · positivity · rw [(eq_zero_of_d_neg h a).resolve_left ha.ne', (eq_zero_of_d_neg h b).resolve_left hb.ne'] simp /-- The set of solutions with `x` and `y` positive is closed under multiplication. -/ theorem y_mul_pos {a b : Solution₁ d} (hax : 0 < a.x) (hay : 0 < a.y) (hbx : 0 < b.x) (hby : 0 < b.y) : 0 < (a * b).y := by simp only [y_mul] positivity /-- If `(x, y)` is a solution with `x` positive, then all its powers with natural exponents have positive `x`. -/ theorem x_pow_pos {a : Solution₁ d} (hax : 0 < a.x) (n : ℕ) : 0 < (a ^ n).x := by induction n with | zero => simp only [pow_zero, x_one, zero_lt_one] | succ n ih => rw [pow_succ]; exact x_mul_pos ih hax /-- If `(x, y)` is a solution with `x` and `y` positive, then all its powers with positive natural exponents have positive `y`. -/ theorem y_pow_succ_pos {a : Solution₁ d} (hax : 0 < a.x) (hay : 0 < a.y) (n : ℕ) : 0 < (a ^ n.succ).y := by induction n with | zero => simp only [pow_one, hay] | succ n ih => rw [pow_succ']; exact y_mul_pos hax hay (x_pow_pos hax _) ih /-- If `(x, y)` is a solution with `x` and `y` positive, then all its powers with positive exponents have positive `y`. -/
theorem y_zpow_pos {a : Solution₁ d} (hax : 0 < a.x) (hay : 0 < a.y) {n : ℤ} (hn : 0 < n) : 0 < (a ^ n).y := by lift n to ℕ using hn.le norm_cast at hn ⊢ rw [← Nat.succ_pred_eq_of_pos hn] exact y_pow_succ_pos hax hay _ /-- If `(x, y)` is a solution with `x` positive, then all its powers have positive `x`. -/ theorem x_zpow_pos {a : Solution₁ d} (hax : 0 < a.x) (n : ℤ) : 0 < (a ^ n).x := by cases n with | ofNat n => rw [Int.ofNat_eq_coe, zpow_natCast] exact x_pow_pos hax n | negSucc n =>
Mathlib/NumberTheory/Pell.lean
264
277
/- Copyright (c) 2021 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import Mathlib.Algebra.Ring.Divisibility.Lemmas import Mathlib.Algebra.Lie.Nilpotent import Mathlib.Algebra.Lie.Engel import Mathlib.LinearAlgebra.Eigenspace.Pi import Mathlib.RingTheory.Artinian.Module import Mathlib.LinearAlgebra.Trace import Mathlib.LinearAlgebra.FreeModule.PID /-! # Weight spaces of Lie modules of nilpotent Lie algebras Just as a key tool when studying the behaviour of a linear operator is to decompose the space on which it acts into a sum of (generalised) eigenspaces, a key tool when studying a representation `M` of Lie algebra `L` is to decompose `M` into a sum of simultaneous eigenspaces of `x` as `x` ranges over `L`. These simultaneous generalised eigenspaces are known as the weight spaces of `M`. When `L` is nilpotent, it follows from the binomial theorem that weight spaces are Lie submodules. Basic definitions and properties of the above ideas are provided in this file. ## Main definitions * `LieModule.genWeightSpaceOf` * `LieModule.genWeightSpace` * `LieModule.Weight` * `LieModule.posFittingCompOf` * `LieModule.posFittingComp` * `LieModule.iSup_ucs_eq_genWeightSpace_zero` * `LieModule.iInf_lowerCentralSeries_eq_posFittingComp` * `LieModule.isCompl_genWeightSpace_zero_posFittingComp` * `LieModule.iSupIndep_genWeightSpace` * `LieModule.iSup_genWeightSpace_eq_top` ## References * [N. Bourbaki, *Lie Groups and Lie Algebras, Chapters 7--9*](bourbaki1975b) ## Tags lie character, eigenvalue, eigenspace, weight, weight vector, root, root vector -/ variable {K R L M : Type*} [CommRing R] [LieRing L] [LieAlgebra R L] [AddCommGroup M] [Module R M] [LieRingModule L M] [LieModule R L M] namespace LieModule open Set Function TensorProduct LieModule variable (M) in /-- If `M` is a representation of a Lie algebra `L` and `χ : L → R` is a family of scalars, then `weightSpace M χ` is the intersection of the `χ x`-eigenspaces of the action of `x` on `M` as `x` ranges over `L`. -/ def weightSpace (χ : L → R) : LieSubmodule R L M where __ := ⨅ x : L, (toEnd R L M x).eigenspace (χ x) lie_mem {x m} hm := by simp_all [smul_comm (χ x)] lemma mem_weightSpace (χ : L → R) (m : M) : m ∈ weightSpace M χ ↔ ∀ x, ⁅x, m⁆ = χ x • m := by simp [weightSpace] section notation_genWeightSpaceOf /-- Until we define `LieModule.genWeightSpaceOf`, it is useful to have some notation as follows: -/ local notation3 "𝕎("M", " χ", " x")" => (toEnd R L M x).maxGenEigenspace χ /-- See also `bourbaki1975b` Chapter VII §1.1, Proposition 2 (ii). -/ protected theorem weight_vector_multiplication (M₁ M₂ M₃ : Type*) [AddCommGroup M₁] [Module R M₁] [LieRingModule L M₁] [LieModule R L M₁] [AddCommGroup M₂] [Module R M₂] [LieRingModule L M₂] [LieModule R L M₂] [AddCommGroup M₃] [Module R M₃] [LieRingModule L M₃] [LieModule R L M₃] (g : M₁ ⊗[R] M₂ →ₗ⁅R,L⁆ M₃) (χ₁ χ₂ : R) (x : L) : LinearMap.range ((g : M₁ ⊗[R] M₂ →ₗ[R] M₃).comp (mapIncl 𝕎(M₁, χ₁, x) 𝕎(M₂, χ₂, x))) ≤ 𝕎(M₃, χ₁ + χ₂, x) := by -- Unpack the statement of the goal. intro m₃ simp only [TensorProduct.mapIncl, LinearMap.mem_range, LinearMap.coe_comp, LieModuleHom.coe_toLinearMap, Function.comp_apply, Pi.add_apply, exists_imp, Module.End.mem_maxGenEigenspace] rintro t rfl -- Set up some notation. let F : Module.End R M₃ := toEnd R L M₃ x - (χ₁ + χ₂) • ↑1 -- The goal is linear in `t` so use induction to reduce to the case that `t` is a pure tensor. refine t.induction_on ?_ ?_ ?_ · use 0; simp only [LinearMap.map_zero, LieModuleHom.map_zero] swap · rintro t₁ t₂ ⟨k₁, hk₁⟩ ⟨k₂, hk₂⟩; use max k₁ k₂ simp only [LieModuleHom.map_add, LinearMap.map_add, Module.End.pow_map_zero_of_le (le_max_left k₁ k₂) hk₁, Module.End.pow_map_zero_of_le (le_max_right k₁ k₂) hk₂, add_zero] -- Now the main argument: pure tensors. rintro ⟨m₁, hm₁⟩ ⟨m₂, hm₂⟩ change ∃ k, (F ^ k) ((g : M₁ ⊗[R] M₂ →ₗ[R] M₃) (m₁ ⊗ₜ m₂)) = (0 : M₃) -- Eliminate `g` from the picture. let f₁ : Module.End R (M₁ ⊗[R] M₂) := (toEnd R L M₁ x - χ₁ • ↑1).rTensor M₂ let f₂ : Module.End R (M₁ ⊗[R] M₂) := (toEnd R L M₂ x - χ₂ • ↑1).lTensor M₁ have h_comm_square : F ∘ₗ ↑g = (g : M₁ ⊗[R] M₂ →ₗ[R] M₃).comp (f₁ + f₂) := by ext m₁ m₂ simp only [f₁, f₂, F, ← g.map_lie x (m₁ ⊗ₜ m₂), add_smul, sub_tmul, tmul_sub, smul_tmul, lie_tmul_right, tmul_smul, toEnd_apply_apply, LieModuleHom.map_smul, Module.End.one_apply, LieModuleHom.coe_toLinearMap, LinearMap.smul_apply, Function.comp_apply, LinearMap.coe_comp, LinearMap.rTensor_tmul, LieModuleHom.map_add, LinearMap.add_apply, LieModuleHom.map_sub, LinearMap.sub_apply, LinearMap.lTensor_tmul, AlgebraTensorModule.curry_apply, TensorProduct.curry_apply, LinearMap.toFun_eq_coe, LinearMap.coe_restrictScalars] abel rsuffices ⟨k, hk⟩ : ∃ k : ℕ, ((f₁ + f₂) ^ k) (m₁ ⊗ₜ m₂) = 0 · use k change (F ^ k) (g.toLinearMap (m₁ ⊗ₜ[R] m₂)) = 0 rw [← LinearMap.comp_apply, Module.End.commute_pow_left_of_commute h_comm_square, LinearMap.comp_apply, hk, LinearMap.map_zero] -- Unpack the information we have about `m₁`, `m₂`. simp only [Module.End.mem_maxGenEigenspace] at hm₁ hm₂ obtain ⟨k₁, hk₁⟩ := hm₁ obtain ⟨k₂, hk₂⟩ := hm₂ have hf₁ : (f₁ ^ k₁) (m₁ ⊗ₜ m₂) = 0 := by simp only [f₁, hk₁, zero_tmul, LinearMap.rTensor_tmul, LinearMap.rTensor_pow] have hf₂ : (f₂ ^ k₂) (m₁ ⊗ₜ m₂) = 0 := by simp only [f₂, hk₂, tmul_zero, LinearMap.lTensor_tmul, LinearMap.lTensor_pow] -- It's now just an application of the binomial theorem. use k₁ + k₂ - 1 have hf_comm : Commute f₁ f₂ := by ext m₁ m₂ simp only [f₁, f₂, Module.End.mul_apply, LinearMap.rTensor_tmul, LinearMap.lTensor_tmul, AlgebraTensorModule.curry_apply, LinearMap.toFun_eq_coe, LinearMap.lTensor_tmul, TensorProduct.curry_apply, LinearMap.coe_restrictScalars] rw [hf_comm.add_pow'] simp only [TensorProduct.mapIncl, Submodule.subtype_apply, Finset.sum_apply, Submodule.coe_mk, LinearMap.coeFn_sum, TensorProduct.map_tmul, LinearMap.smul_apply] -- The required sum is zero because each individual term is zero. apply Finset.sum_eq_zero rintro ⟨i, j⟩ hij -- Eliminate the binomial coefficients from the picture. suffices (f₁ ^ i * f₂ ^ j) (m₁ ⊗ₜ m₂) = 0 by rw [this]; apply smul_zero -- Finish off with appropriate case analysis. rcases Nat.le_or_le_of_add_eq_add_pred (Finset.mem_antidiagonal.mp hij) with hi | hj · rw [(hf_comm.pow_pow i j).eq, Module.End.mul_apply, Module.End.pow_map_zero_of_le hi hf₁, LinearMap.map_zero] · rw [Module.End.mul_apply, Module.End.pow_map_zero_of_le hj hf₂, LinearMap.map_zero] lemma lie_mem_maxGenEigenspace_toEnd {χ₁ χ₂ : R} {x y : L} {m : M} (hy : y ∈ 𝕎(L, χ₁, x)) (hm : m ∈ 𝕎(M, χ₂, x)) : ⁅y, m⁆ ∈ 𝕎(M, χ₁ + χ₂, x) := by apply LieModule.weight_vector_multiplication L M M (toModuleHom R L M) χ₁ χ₂ simp only [LieModuleHom.coe_toLinearMap, Function.comp_apply, LinearMap.coe_comp, TensorProduct.mapIncl, LinearMap.mem_range] use ⟨y, hy⟩ ⊗ₜ ⟨m, hm⟩ simp only [Submodule.subtype_apply, toModuleHom_apply, TensorProduct.map_tmul] variable (M) /-- If `M` is a representation of a nilpotent Lie algebra `L`, `χ` is a scalar, and `x : L`, then `genWeightSpaceOf M χ x` is the maximal generalized `χ`-eigenspace of the action of `x` on `M`. It is a Lie submodule because `L` is nilpotent. -/ def genWeightSpaceOf [LieRing.IsNilpotent L] (χ : R) (x : L) : LieSubmodule R L M := { 𝕎(M, χ, x) with lie_mem := by intro y m hm simp only [AddSubsemigroup.mem_carrier, AddSubmonoid.mem_toSubsemigroup, Submodule.mem_toAddSubmonoid] at hm ⊢ rw [← zero_add χ] exact lie_mem_maxGenEigenspace_toEnd (by simp) hm } end notation_genWeightSpaceOf variable (M) variable [LieRing.IsNilpotent L] theorem mem_genWeightSpaceOf (χ : R) (x : L) (m : M) : m ∈ genWeightSpaceOf M χ x ↔ ∃ k : ℕ, ((toEnd R L M x - χ • ↑1) ^ k) m = 0 := by simp [genWeightSpaceOf] theorem coe_genWeightSpaceOf_zero (x : L) : ↑(genWeightSpaceOf M (0 : R) x) = ⨆ k, LinearMap.ker (toEnd R L M x ^ k) := by simp [genWeightSpaceOf, ← Module.End.iSup_genEigenspace_eq] /-- If `M` is a representation of a nilpotent Lie algebra `L` and `χ : L → R` is a family of scalars, then `genWeightSpace M χ` is the intersection of the maximal generalized `χ x`-eigenspaces of the action of `x` on `M` as `x` ranges over `L`. It is a Lie submodule because `L` is nilpotent. -/ def genWeightSpace (χ : L → R) : LieSubmodule R L M := ⨅ x, genWeightSpaceOf M (χ x) x theorem mem_genWeightSpace (χ : L → R) (m : M) : m ∈ genWeightSpace M χ ↔ ∀ x, ∃ k : ℕ, ((toEnd R L M x - χ x • ↑1) ^ k) m = 0 := by simp [genWeightSpace, mem_genWeightSpaceOf] lemma genWeightSpace_le_genWeightSpaceOf (x : L) (χ : L → R) : genWeightSpace M χ ≤ genWeightSpaceOf M (χ x) x := iInf_le _ x lemma weightSpace_le_genWeightSpace (χ : L → R) : weightSpace M χ ≤ genWeightSpace M χ := by apply le_iInf intro x rw [← (LieSubmodule.toSubmodule_orderEmbedding R L M).le_iff_le] apply (iInf_le _ x).trans exact ((toEnd R L M x).genEigenspace (χ x)).monotone le_top variable (R L) in /-- A weight of a Lie module is a map `L → R` such that the corresponding weight space is non-trivial. -/ structure Weight where /-- The family of eigenvalues corresponding to a weight. -/ toFun : L → R genWeightSpace_ne_bot' : genWeightSpace M toFun ≠ ⊥ namespace Weight instance instFunLike : FunLike (Weight R L M) L R where coe χ := χ.1 coe_injective' χ₁ χ₂ h := by cases χ₁; cases χ₂; simp_all @[simp] lemma coe_weight_mk (χ : L → R) (h) : (↑(⟨χ, h⟩ : Weight R L M) : L → R) = χ := rfl lemma genWeightSpace_ne_bot (χ : Weight R L M) : genWeightSpace M χ ≠ ⊥ := χ.genWeightSpace_ne_bot' variable {M} @[ext] lemma ext {χ₁ χ₂ : Weight R L M} (h : ∀ x, χ₁ x = χ₂ x) : χ₁ = χ₂ := by obtain ⟨f₁, _⟩ := χ₁; obtain ⟨f₂, _⟩ := χ₂; aesop lemma ext_iff' {χ₁ χ₂ : Weight R L M} : (χ₁ : L → R) = χ₂ ↔ χ₁ = χ₂ := by simp lemma exists_ne_zero (χ : Weight R L M) : ∃ x ∈ genWeightSpace M χ, x ≠ 0 := by simpa [LieSubmodule.eq_bot_iff] using χ.genWeightSpace_ne_bot instance [Subsingleton M] : IsEmpty (Weight R L M) := ⟨fun h ↦ h.2 (Subsingleton.elim _ _)⟩ instance [Nontrivial (genWeightSpace M (0 : L → R))] : Zero (Weight R L M) := ⟨0, fun e ↦ not_nontrivial (⊥ : LieSubmodule R L M) (e ▸ ‹_›)⟩ @[simp] lemma coe_zero [Nontrivial (genWeightSpace M (0 : L → R))] : ((0 : Weight R L M) : L → R) = 0 := rfl lemma zero_apply [Nontrivial (genWeightSpace M (0 : L → R))] (x) : (0 : Weight R L M) x = 0 := rfl /-- The proposition that a weight of a Lie module is zero. We make this definition because we cannot define a `Zero (Weight R L M)` instance since the weight space of the zero function can be trivial. -/ def IsZero (χ : Weight R L M) := (χ : L → R) = 0 @[simp] lemma IsZero.eq {χ : Weight R L M} (hχ : χ.IsZero) : (χ : L → R) = 0 := hχ @[simp] lemma coe_eq_zero_iff (χ : Weight R L M) : (χ : L → R) = 0 ↔ χ.IsZero := Iff.rfl lemma isZero_iff_eq_zero [Nontrivial (genWeightSpace M (0 : L → R))] {χ : Weight R L M} : χ.IsZero ↔ χ = 0 := Weight.ext_iff' (χ₂ := 0) lemma isZero_zero [Nontrivial (genWeightSpace M (0 : L → R))] : IsZero (0 : Weight R L M) := rfl /-- The proposition that a weight of a Lie module is non-zero. -/ abbrev IsNonZero (χ : Weight R L M) := ¬ IsZero (χ : Weight R L M) lemma isNonZero_iff_ne_zero [Nontrivial (genWeightSpace M (0 : L → R))] {χ : Weight R L M} : χ.IsNonZero ↔ χ ≠ 0 := isZero_iff_eq_zero.not noncomputable instance : DecidablePred (IsNonZero (R := R) (L := L) (M := M)) := Classical.decPred _ variable (R L M) in /-- The set of weights is equivalent to a subtype. -/ def equivSetOf : Weight R L M ≃ {χ : L → R | genWeightSpace M χ ≠ ⊥} where toFun w := ⟨w.1, w.2⟩ invFun w := ⟨w.1, w.2⟩ left_inv w := by simp right_inv w := by simp lemma genWeightSpaceOf_ne_bot (χ : Weight R L M) (x : L) : genWeightSpaceOf M (χ x) x ≠ ⊥ := by have : ⨅ x, genWeightSpaceOf M (χ x) x ≠ ⊥ := χ.genWeightSpace_ne_bot contrapose! this rw [eq_bot_iff] exact le_of_le_of_eq (iInf_le _ _) this lemma hasEigenvalueAt (χ : Weight R L M) (x : L) : (toEnd R L M x).HasEigenvalue (χ x) := by obtain ⟨k : ℕ, hk : (toEnd R L M x).genEigenspace (χ x) k ≠ ⊥⟩ := by simpa [genWeightSpaceOf, ← Module.End.iSup_genEigenspace_eq] using χ.genWeightSpaceOf_ne_bot x exact Module.End.hasEigenvalue_of_hasGenEigenvalue hk lemma apply_eq_zero_of_isNilpotent [NoZeroSMulDivisors R M] [IsReduced R] (x : L) (h : _root_.IsNilpotent (toEnd R L M x)) (χ : Weight R L M) : χ x = 0 := ((χ.hasEigenvalueAt x).isNilpotent_of_isNilpotent h).eq_zero end Weight /-- See also the more useful form `LieModule.zero_genWeightSpace_eq_top_of_nilpotent`. -/ @[simp] theorem zero_genWeightSpace_eq_top_of_nilpotent' [IsNilpotent L M] : genWeightSpace M (0 : L → R) = ⊤ := by ext simp [genWeightSpace, genWeightSpaceOf] theorem coe_genWeightSpace_of_top (χ : L → R) : (genWeightSpace M (χ ∘ (⊤ : LieSubalgebra R L).incl) : Submodule R M) = genWeightSpace M χ := by ext m simp only [mem_genWeightSpace, LieSubmodule.mem_toSubmodule, Subtype.forall] apply forall_congr' simp @[simp] theorem zero_genWeightSpace_eq_top_of_nilpotent [IsNilpotent L M] : genWeightSpace M (0 : (⊤ : LieSubalgebra R L) → R) = ⊤ := by ext m simp only [mem_genWeightSpace, Pi.zero_apply, zero_smul, sub_zero, Subtype.forall, forall_true_left, LieSubalgebra.toEnd_mk, LieSubalgebra.mem_top, LieSubmodule.mem_top, iff_true] intro x obtain ⟨k, hk⟩ := exists_forall_pow_toEnd_eq_zero R L M exact ⟨k, by simp [hk x]⟩ theorem exists_genWeightSpace_le_ker_of_isNoetherian [IsNoetherian R M] (χ : L → R) (x : L) : ∃ k : ℕ, genWeightSpace M χ ≤ LinearMap.ker ((toEnd R L M x - algebraMap R _ (χ x)) ^ k) := by use (toEnd R L M x).maxGenEigenspaceIndex (χ x) intro m hm replace hm : m ∈ (toEnd R L M x).maxGenEigenspace (χ x) := genWeightSpace_le_genWeightSpaceOf M x χ hm rwa [Module.End.maxGenEigenspace_eq, Module.End.genEigenspace_nat] at hm variable (R) in theorem exists_genWeightSpace_zero_le_ker_of_isNoetherian [IsNoetherian R M] (x : L) : ∃ k : ℕ, genWeightSpace M (0 : L → R) ≤ LinearMap.ker (toEnd R L M x ^ k) := by simpa using exists_genWeightSpace_le_ker_of_isNoetherian M (0 : L → R) x lemma isNilpotent_toEnd_sub_algebraMap [IsNoetherian R M] (χ : L → R) (x : L) : _root_.IsNilpotent <| toEnd R L (genWeightSpace M χ) x - algebraMap R _ (χ x) := by have : toEnd R L (genWeightSpace M χ) x - algebraMap R _ (χ x) = (toEnd R L M x - algebraMap R _ (χ x)).restrict (fun m hm ↦ sub_mem (LieSubmodule.lie_mem _ hm) (Submodule.smul_mem _ _ hm)) := by rfl obtain ⟨k, hk⟩ := exists_genWeightSpace_le_ker_of_isNoetherian M χ x use k ext ⟨m, hm⟩ simp only [this, Module.End.pow_restrict _, LinearMap.zero_apply, ZeroMemClass.coe_zero, ZeroMemClass.coe_eq_zero] exact ZeroMemClass.coe_eq_zero.mp (hk hm) /-- A (nilpotent) Lie algebra acts nilpotently on the zero weight space of a Noetherian Lie module. -/ theorem isNilpotent_toEnd_genWeightSpace_zero [IsNoetherian R M] (x : L) : _root_.IsNilpotent <| toEnd R L (genWeightSpace M (0 : L → R)) x := by simpa using isNilpotent_toEnd_sub_algebraMap M (0 : L → R) x /-- By Engel's theorem, the zero weight space of a Noetherian Lie module is nilpotent. -/ instance [IsNoetherian R M] : IsNilpotent L (genWeightSpace M (0 : L → R)) := isNilpotent_iff_forall'.mpr <| isNilpotent_toEnd_genWeightSpace_zero M variable (R L) @[simp] lemma genWeightSpace_zero_normalizer_eq_self : (genWeightSpace M (0 : L → R)).normalizer = genWeightSpace M 0 := by refine le_antisymm ?_ (LieSubmodule.le_normalizer _) intro m hm rw [LieSubmodule.mem_normalizer] at hm simp only [mem_genWeightSpace, Pi.zero_apply, zero_smul, sub_zero] at hm ⊢ intro y obtain ⟨k, hk⟩ := hm y y use k + 1 simpa [pow_succ, Module.End.mul_eq_comp] lemma iSup_ucs_le_genWeightSpace_zero : ⨆ k, (⊥ : LieSubmodule R L M).ucs k ≤ genWeightSpace M (0 : L → R) := by simpa using LieSubmodule.ucs_le_of_normalizer_eq_self (genWeightSpace_zero_normalizer_eq_self R L M) /-- See also `LieModule.iInf_lowerCentralSeries_eq_posFittingComp`. -/ lemma iSup_ucs_eq_genWeightSpace_zero [IsNoetherian R M] : ⨆ k, (⊥ : LieSubmodule R L M).ucs k = genWeightSpace M (0 : L → R) := by obtain ⟨k, hk⟩ := (LieSubmodule.isNilpotent_iff_exists_self_le_ucs <| genWeightSpace M (0 : L → R)).mp inferInstance refine le_antisymm (iSup_ucs_le_genWeightSpace_zero R L M) (le_trans hk ?_) exact le_iSup (fun k ↦ (⊥ : LieSubmodule R L M).ucs k) k variable {L} /-- If `M` is a representation of a nilpotent Lie algebra `L`, and `x : L`, then `posFittingCompOf R M x` is the infimum of the decreasing system `range φₓ ⊇ range φₓ² ⊇ range φₓ³ ⊇ ⋯` where `φₓ : End R M := toEnd R L M x`. We call this the "positive Fitting component" because with appropriate assumptions (e.g., `R` is a field and `M` is finite-dimensional) `φₓ` induces the so-called Fitting decomposition: `M = M₀ ⊕ M₁` where `M₀ = genWeightSpaceOf M 0 x` and `M₁ = posFittingCompOf R M x`. It is a Lie submodule because `L` is nilpotent. -/ def posFittingCompOf (x : L) : LieSubmodule R L M := { toSubmodule := ⨅ k, LinearMap.range (toEnd R L M x ^ k) lie_mem := by set φ := toEnd R L M x intros y m hm simp only [AddSubsemigroup.mem_carrier, AddSubmonoid.mem_toSubsemigroup, Submodule.mem_toAddSubmonoid, Submodule.mem_iInf, LinearMap.mem_range] at hm ⊢ intro k obtain ⟨N, hN⟩ := LieAlgebra.nilpotent_ad_of_nilpotent_algebra R L obtain ⟨m, rfl⟩ := hm (N + k) let f₁ : Module.End R (L ⊗[R] M) := (LieAlgebra.ad R L x).rTensor M let f₂ : Module.End R (L ⊗[R] M) := φ.lTensor L replace hN : f₁ ^ N = 0 := by ext; simp [f₁, hN] have h₁ : Commute f₁ f₂ := by ext; simp [f₁, f₂] have h₂ : φ ∘ₗ toModuleHom R L M = toModuleHom R L M ∘ₗ (f₁ + f₂) := by ext; simp [φ, f₁, f₂] obtain ⟨q, hq⟩ := h₁.add_pow_dvd_pow_of_pow_eq_zero_right (N + k).le_succ hN use toModuleHom R L M (q (y ⊗ₜ m)) change (φ ^ k).comp ((toModuleHom R L M : L ⊗[R] M →ₗ[R] M)) _ = _ simp [φ, f₁, f₂, Module.End.commute_pow_left_of_commute h₂, LinearMap.comp_apply (g := (f₁ + f₂) ^ k), ← LinearMap.comp_apply (g := q), ← Module.End.mul_eq_comp, ← hq] } variable {M} in lemma mem_posFittingCompOf (x : L) (m : M) : m ∈ posFittingCompOf R M x ↔ ∀ (k : ℕ), ∃ n, (toEnd R L M x ^ k) n = m := by simp [posFittingCompOf] @[simp] lemma posFittingCompOf_le_lowerCentralSeries (x : L) (k : ℕ) : posFittingCompOf R M x ≤ lowerCentralSeries R L M k := by suffices ∀ m l, (toEnd R L M x ^ l) m ∈ lowerCentralSeries R L M l by intro m hm obtain ⟨n, rfl⟩ := (mem_posFittingCompOf R x m).mp hm k exact this n k intro m l induction l with | zero => simp | succ l ih => simp only [lowerCentralSeries_succ, pow_succ', Module.End.mul_apply] exact LieSubmodule.lie_mem_lie (LieSubmodule.mem_top x) ih @[simp] lemma posFittingCompOf_eq_bot_of_isNilpotent [IsNilpotent L M] (x : L) : posFittingCompOf R M x = ⊥ := by simp_rw [eq_bot_iff, ← iInf_lowerCentralSeries_eq_bot_of_isNilpotent, le_iInf_iff,
posFittingCompOf_le_lowerCentralSeries, forall_const] variable (L)
Mathlib/Algebra/Lie/Weights/Basic.lean
443
445
/- Copyright (c) 2019 Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard -/ import Mathlib.Data.EReal.Basic deprecated_module (since := "2025-04-13")
Mathlib/Data/Real/EReal.lean
1,627
1,631
/- Copyright (c) 2023 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import Mathlib.Analysis.Calculus.Deriv.Comp import Mathlib.Analysis.Calculus.Deriv.Add import Mathlib.Analysis.Calculus.Deriv.Mul import Mathlib.Analysis.Calculus.Deriv.Slope /-! # Line derivatives We define the line derivative of a function `f : E → F`, at a point `x : E` along a vector `v : E`, as the element `f' : F` such that `f (x + t • v) = f x + t • f' + o (t)` as `t` tends to `0` in the scalar field `𝕜`, if it exists. It is denoted by `lineDeriv 𝕜 f x v`. This notion is generally less well behaved than the full Fréchet derivative (for instance, the composition of functions which are line-differentiable is not line-differentiable in general). The Fréchet derivative should therefore be favored over this one in general, although the line derivative may sometimes prove handy. The line derivative in direction `v` is also called the Gateaux derivative in direction `v`, although the term "Gateaux derivative" is sometimes reserved for the situation where there is such a derivative in all directions, for the map `v ↦ lineDeriv 𝕜 f x v` (which doesn't have to be linear in general). ## Main definition and results We mimic the definitions and statements for the Fréchet derivative and the one-dimensional derivative. We define in particular the following objects: * `LineDifferentiableWithinAt 𝕜 f s x v` * `LineDifferentiableAt 𝕜 f x v` * `HasLineDerivWithinAt 𝕜 f f' s x v` * `HasLineDerivAt 𝕜 f s x v` * `lineDerivWithin 𝕜 f s x v` * `lineDeriv 𝕜 f x v` and develop about them a basic API inspired by the one for the Fréchet derivative. We depart from the Fréchet derivative in two places, as the dependence of the following predicates on the direction would make them barely usable: * We do not define an analogue of the predicate `UniqueDiffOn`; * We do not define `LineDifferentiableOn` nor `LineDifferentiable`. -/ noncomputable section open scoped Topology Filter ENNReal NNReal open Filter Asymptotics Set variable {𝕜 : Type*} [NontriviallyNormedField 𝕜] variable {F : Type*} [NormedAddCommGroup F] [NormedSpace 𝕜 F] section Module /-! Results that do not rely on a topological structure on `E` -/ variable (𝕜) variable {E : Type*} [AddCommGroup E] [Module 𝕜 E] /-- `f` has the derivative `f'` at the point `x` along the direction `v` in the set `s`. That is, `f (x + t v) = f x + t • f' + o (t)` when `t` tends to `0` and `x + t v ∈ s`. Note that this definition is less well behaved than the total Fréchet derivative, which should generally be favored over this one. -/ def HasLineDerivWithinAt (f : E → F) (f' : F) (s : Set E) (x : E) (v : E) := HasDerivWithinAt (fun t ↦ f (x + t • v)) f' ((fun t ↦ x + t • v) ⁻¹' s) (0 : 𝕜) /-- `f` has the derivative `f'` at the point `x` along the direction `v`. That is, `f (x + t v) = f x + t • f' + o (t)` when `t` tends to `0`. Note that this definition is less well behaved than the total Fréchet derivative, which should generally be favored over this one. -/ def HasLineDerivAt (f : E → F) (f' : F) (x : E) (v : E) := HasDerivAt (fun t ↦ f (x + t • v)) f' (0 : 𝕜) /-- `f` is line-differentiable at the point `x` in the direction `v` in the set `s` if there exists `f'` such that `f (x + t v) = f x + t • f' + o (t)` when `t` tends to `0` and `x + t v ∈ s`. -/ def LineDifferentiableWithinAt (f : E → F) (s : Set E) (x : E) (v : E) : Prop := DifferentiableWithinAt 𝕜 (fun t ↦ f (x + t • v)) ((fun t ↦ x + t • v) ⁻¹' s) (0 : 𝕜) /-- `f` is line-differentiable at the point `x` in the direction `v` if there exists `f'` such that `f (x + t v) = f x + t • f' + o (t)` when `t` tends to `0`. -/ def LineDifferentiableAt (f : E → F) (x : E) (v : E) : Prop := DifferentiableAt 𝕜 (fun t ↦ f (x + t • v)) (0 : 𝕜) /-- Line derivative of `f` at the point `x` in the direction `v` within the set `s`, if it exists. Zero otherwise. If the line derivative exists (i.e., `∃ f', HasLineDerivWithinAt 𝕜 f f' s x v`), then `f (x + t v) = f x + t lineDerivWithin 𝕜 f s x v + o (t)` when `t` tends to `0` and `x + t v ∈ s`. -/ def lineDerivWithin (f : E → F) (s : Set E) (x : E) (v : E) : F := derivWithin (fun t ↦ f (x + t • v)) ((fun t ↦ x + t • v) ⁻¹' s) (0 : 𝕜) /-- Line derivative of `f` at the point `x` in the direction `v`, if it exists. Zero otherwise. If the line derivative exists (i.e., `∃ f', HasLineDerivAt 𝕜 f f' x v`), then `f (x + t v) = f x + t lineDeriv 𝕜 f x v + o (t)` when `t` tends to `0`. -/ def lineDeriv (f : E → F) (x : E) (v : E) : F := deriv (fun t ↦ f (x + t • v)) (0 : 𝕜) variable {𝕜} variable {f f₁ : E → F} {f' f₀' f₁' : F} {s t : Set E} {x v : E} lemma HasLineDerivWithinAt.mono (hf : HasLineDerivWithinAt 𝕜 f f' s x v) (hst : t ⊆ s) : HasLineDerivWithinAt 𝕜 f f' t x v := HasDerivWithinAt.mono hf (preimage_mono hst) lemma HasLineDerivAt.hasLineDerivWithinAt (hf : HasLineDerivAt 𝕜 f f' x v) (s : Set E) : HasLineDerivWithinAt 𝕜 f f' s x v := HasDerivAt.hasDerivWithinAt hf lemma HasLineDerivWithinAt.lineDifferentiableWithinAt (hf : HasLineDerivWithinAt 𝕜 f f' s x v) : LineDifferentiableWithinAt 𝕜 f s x v := HasDerivWithinAt.differentiableWithinAt hf theorem HasLineDerivAt.lineDifferentiableAt (hf : HasLineDerivAt 𝕜 f f' x v) : LineDifferentiableAt 𝕜 f x v := HasDerivAt.differentiableAt hf theorem LineDifferentiableWithinAt.hasLineDerivWithinAt (h : LineDifferentiableWithinAt 𝕜 f s x v) : HasLineDerivWithinAt 𝕜 f (lineDerivWithin 𝕜 f s x v) s x v := DifferentiableWithinAt.hasDerivWithinAt h theorem LineDifferentiableAt.hasLineDerivAt (h : LineDifferentiableAt 𝕜 f x v) : HasLineDerivAt 𝕜 f (lineDeriv 𝕜 f x v) x v := DifferentiableAt.hasDerivAt h @[simp] lemma hasLineDerivWithinAt_univ : HasLineDerivWithinAt 𝕜 f f' univ x v ↔ HasLineDerivAt 𝕜 f f' x v := by simp only [HasLineDerivWithinAt, HasLineDerivAt, preimage_univ, hasDerivWithinAt_univ] theorem lineDerivWithin_zero_of_not_lineDifferentiableWithinAt (h : ¬LineDifferentiableWithinAt 𝕜 f s x v) : lineDerivWithin 𝕜 f s x v = 0 := derivWithin_zero_of_not_differentiableWithinAt h theorem lineDeriv_zero_of_not_lineDifferentiableAt (h : ¬LineDifferentiableAt 𝕜 f x v) : lineDeriv 𝕜 f x v = 0 := deriv_zero_of_not_differentiableAt h theorem hasLineDerivAt_iff_isLittleO_nhds_zero : HasLineDerivAt 𝕜 f f' x v ↔ (fun t : 𝕜 => f (x + t • v) - f x - t • f') =o[𝓝 0] fun t => t := by simp only [HasLineDerivAt, hasDerivAt_iff_isLittleO_nhds_zero, zero_add, zero_smul, add_zero] theorem HasLineDerivAt.unique (h₀ : HasLineDerivAt 𝕜 f f₀' x v) (h₁ : HasLineDerivAt 𝕜 f f₁' x v) : f₀' = f₁' := HasDerivAt.unique h₀ h₁ protected theorem HasLineDerivAt.lineDeriv (h : HasLineDerivAt 𝕜 f f' x v) : lineDeriv 𝕜 f x v = f' := by rw [h.unique h.lineDifferentiableAt.hasLineDerivAt] theorem lineDifferentiableWithinAt_univ : LineDifferentiableWithinAt 𝕜 f univ x v ↔ LineDifferentiableAt 𝕜 f x v := by simp only [LineDifferentiableWithinAt, LineDifferentiableAt, preimage_univ, differentiableWithinAt_univ] theorem LineDifferentiableAt.lineDifferentiableWithinAt (h : LineDifferentiableAt 𝕜 f x v) : LineDifferentiableWithinAt 𝕜 f s x v := (differentiableWithinAt_univ.2 h).mono (subset_univ _) @[simp] theorem lineDerivWithin_univ : lineDerivWithin 𝕜 f univ x v = lineDeriv 𝕜 f x v := by simp [lineDerivWithin, lineDeriv] theorem LineDifferentiableWithinAt.mono (h : LineDifferentiableWithinAt 𝕜 f t x v) (st : s ⊆ t) : LineDifferentiableWithinAt 𝕜 f s x v := (h.hasLineDerivWithinAt.mono st).lineDifferentiableWithinAt theorem HasLineDerivWithinAt.congr_mono (h : HasLineDerivWithinAt 𝕜 f f' s x v) (ht : EqOn f₁ f t) (hx : f₁ x = f x) (h₁ : t ⊆ s) : HasLineDerivWithinAt 𝕜 f₁ f' t x v := HasDerivWithinAt.congr_mono h (fun _ hy ↦ ht hy) (by simpa using hx) (preimage_mono h₁) theorem HasLineDerivWithinAt.congr (h : HasLineDerivWithinAt 𝕜 f f' s x v) (hs : EqOn f₁ f s) (hx : f₁ x = f x) : HasLineDerivWithinAt 𝕜 f₁ f' s x v := h.congr_mono hs hx (Subset.refl _) theorem HasLineDerivWithinAt.congr' (h : HasLineDerivWithinAt 𝕜 f f' s x v) (hs : EqOn f₁ f s) (hx : x ∈ s) : HasLineDerivWithinAt 𝕜 f₁ f' s x v := h.congr hs (hs hx) theorem LineDifferentiableWithinAt.congr_mono (h : LineDifferentiableWithinAt 𝕜 f s x v) (ht : EqOn f₁ f t) (hx : f₁ x = f x) (h₁ : t ⊆ s) : LineDifferentiableWithinAt 𝕜 f₁ t x v := (HasLineDerivWithinAt.congr_mono h.hasLineDerivWithinAt ht hx h₁).differentiableWithinAt theorem LineDifferentiableWithinAt.congr (h : LineDifferentiableWithinAt 𝕜 f s x v) (ht : ∀ x ∈ s, f₁ x = f x) (hx : f₁ x = f x) : LineDifferentiableWithinAt 𝕜 f₁ s x v := LineDifferentiableWithinAt.congr_mono h ht hx (Subset.refl _) theorem lineDerivWithin_congr (hs : EqOn f₁ f s) (hx : f₁ x = f x) : lineDerivWithin 𝕜 f₁ s x v = lineDerivWithin 𝕜 f s x v := derivWithin_congr (fun _ hy ↦ hs hy) (by simpa using hx) theorem lineDerivWithin_congr' (hs : EqOn f₁ f s) (hx : x ∈ s) : lineDerivWithin 𝕜 f₁ s x v = lineDerivWithin 𝕜 f s x v := lineDerivWithin_congr hs (hs hx) theorem hasLineDerivAt_iff_tendsto_slope_zero : HasLineDerivAt 𝕜 f f' x v ↔ Tendsto (fun (t : 𝕜) ↦ t⁻¹ • (f (x + t • v) - f x)) (𝓝[≠] 0) (𝓝 f') := by simp only [HasLineDerivAt, hasDerivAt_iff_tendsto_slope_zero, zero_add, zero_smul, add_zero] alias ⟨HasLineDerivAt.tendsto_slope_zero, _⟩ := hasLineDerivAt_iff_tendsto_slope_zero theorem HasLineDerivAt.tendsto_slope_zero_right [Preorder 𝕜] (h : HasLineDerivAt 𝕜 f f' x v) : Tendsto (fun (t : 𝕜) ↦ t⁻¹ • (f (x + t • v) - f x)) (𝓝[>] 0) (𝓝 f') := h.tendsto_slope_zero.mono_left (nhdsGT_le_nhdsNE 0) theorem HasLineDerivAt.tendsto_slope_zero_left [Preorder 𝕜] (h : HasLineDerivAt 𝕜 f f' x v) : Tendsto (fun (t : 𝕜) ↦ t⁻¹ • (f (x + t • v) - f x)) (𝓝[<] 0) (𝓝 f') := h.tendsto_slope_zero.mono_left (nhdsLT_le_nhdsNE 0) theorem HasLineDerivWithinAt.hasLineDerivAt' (h : HasLineDerivWithinAt 𝕜 f f' s x v) (hs : ∀ᶠ t : 𝕜 in 𝓝 0, x + t • v ∈ s) : HasLineDerivAt 𝕜 f f' x v := h.hasDerivAt hs end Module section NormedSpace /-! Results that need a normed space structure on `E` -/ variable {E : Type*} [NormedAddCommGroup E] [NormedSpace 𝕜 E] {f f₀ f₁ : E → F} {f' : F} {s t : Set E} {x v : E} {L : E →L[𝕜] F} theorem HasLineDerivWithinAt.mono_of_mem_nhdsWithin (h : HasLineDerivWithinAt 𝕜 f f' t x v) (hst : t ∈ 𝓝[s] x) : HasLineDerivWithinAt 𝕜 f f' s x v := by apply HasDerivWithinAt.mono_of_mem_nhdsWithin h apply ContinuousWithinAt.preimage_mem_nhdsWithin'' _ hst (by simp) apply Continuous.continuousWithinAt; fun_prop @[deprecated (since := "2024-10-31")] alias HasLineDerivWithinAt.mono_of_mem := HasLineDerivWithinAt.mono_of_mem_nhdsWithin theorem HasLineDerivWithinAt.hasLineDerivAt (h : HasLineDerivWithinAt 𝕜 f f' s x v) (hs : s ∈ 𝓝 x) : HasLineDerivAt 𝕜 f f' x v := h.hasLineDerivAt' <| (Continuous.tendsto' (by fun_prop) 0 _ (by simp)).eventually hs theorem LineDifferentiableWithinAt.lineDifferentiableAt (h : LineDifferentiableWithinAt 𝕜 f s x v) (hs : s ∈ 𝓝 x) : LineDifferentiableAt 𝕜 f x v := (h.hasLineDerivWithinAt.hasLineDerivAt hs).lineDifferentiableAt lemma HasFDerivWithinAt.hasLineDerivWithinAt (hf : HasFDerivWithinAt f L s x) (v : E) : HasLineDerivWithinAt 𝕜 f (L v) s x v := by let F := fun (t : 𝕜) ↦ x + t • v rw [show x = F (0 : 𝕜) by simp [F]] at hf have A : HasDerivWithinAt F (0 + (1 : 𝕜) • v) (F ⁻¹' s) 0 := ((hasDerivAt_const (0 : 𝕜) x).add ((hasDerivAt_id' (0 : 𝕜)).smul_const v)).hasDerivWithinAt simp only [one_smul, zero_add] at A exact hf.comp_hasDerivWithinAt (x := (0 : 𝕜)) A (mapsTo_preimage F s) lemma HasFDerivAt.hasLineDerivAt (hf : HasFDerivAt f L x) (v : E) : HasLineDerivAt 𝕜 f (L v) x v := by rw [← hasLineDerivWithinAt_univ] exact hf.hasFDerivWithinAt.hasLineDerivWithinAt v lemma DifferentiableAt.lineDeriv_eq_fderiv (hf : DifferentiableAt 𝕜 f x) : lineDeriv 𝕜 f x v = fderiv 𝕜 f x v :=
(hf.hasFDerivAt.hasLineDerivAt v).lineDeriv theorem LineDifferentiableWithinAt.mono_of_mem_nhdsWithin (h : LineDifferentiableWithinAt 𝕜 f s x v) (hst : s ∈ 𝓝[t] x) : LineDifferentiableWithinAt 𝕜 f t x v := (h.hasLineDerivWithinAt.mono_of_mem_nhdsWithin hst).lineDifferentiableWithinAt
Mathlib/Analysis/Calculus/LineDeriv/Basic.lean
275
279
/- Copyright (c) 2020 Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kyle Miller -/ import Mathlib.Algebra.Group.Action.Pi import Mathlib.Data.Finset.Prod import Mathlib.Data.SetLike.Basic import Mathlib.Data.Sym.Basic import Mathlib.Data.Sym.Sym2.Init /-! # The symmetric square This file defines the symmetric square, which is `α × α` modulo swapping. This is also known as the type of unordered pairs. More generally, the symmetric square is the second symmetric power (see `Data.Sym.Basic`). The equivalence is `Sym2.equivSym`. From the point of view that an unordered pair is equivalent to a multiset of cardinality two (see `Sym2.equivMultiset`), there is a `Mem` instance `Sym2.Mem`, which is a `Prop`-valued membership test. Given `h : a ∈ z` for `z : Sym2 α`, then `Mem.other h` is the other element of the pair, defined using `Classical.choice`. If `α` has decidable equality, then `h.other'` computably gives the other element. The universal property of `Sym2` is provided as `Sym2.lift`, which states that functions from `Sym2 α` are equivalent to symmetric two-argument functions from `α`. Recall that an undirected graph (allowing self loops, but no multiple edges) is equivalent to a symmetric relation on the vertex type `α`. Given a symmetric relation on `α`, the corresponding edge set is constructed by `Sym2.fromRel` which is a special case of `Sym2.lift`. ## Notation The element `Sym2.mk (a, b)` can be written as `s(a, b)` for short. ## Tags symmetric square, unordered pairs, symmetric powers -/ assert_not_exists MonoidWithZero open List (Vector) open Finset Function Sym universe u variable {α β γ : Type*} namespace Sym2 /-- This is the relation capturing the notion of pairs equivalent up to permutations. -/ @[aesop (rule_sets := [Sym2]) [safe [constructors, cases], norm]] inductive Rel (α : Type u) : α × α → α × α → Prop | refl (x y : α) : Rel _ (x, y) (x, y) | swap (x y : α) : Rel _ (x, y) (y, x) attribute [refl] Rel.refl @[symm] theorem Rel.symm {x y : α × α} : Rel α x y → Rel α y x := by aesop (rule_sets := [Sym2]) @[trans] theorem Rel.trans {x y z : α × α} (a : Rel α x y) (b : Rel α y z) : Rel α x z := by aesop (rule_sets := [Sym2]) theorem Rel.is_equivalence : Equivalence (Rel α) := { refl := fun (x, y) ↦ Rel.refl x y, symm := Rel.symm, trans := Rel.trans } /-- One can use `attribute [local instance] Sym2.Rel.setoid` to temporarily make `Quotient` functionality work for `α × α`. -/ def Rel.setoid (α : Type u) : Setoid (α × α) := ⟨Rel α, Rel.is_equivalence⟩ @[simp] theorem rel_iff' {p q : α × α} : Rel α p q ↔ p = q ∨ p = q.swap := by aesop (rule_sets := [Sym2]) theorem rel_iff {x y z w : α} : Rel α (x, y) (z, w) ↔ x = z ∧ y = w ∨ x = w ∧ y = z := by simp end Sym2 /-- `Sym2 α` is the symmetric square of `α`, which, in other words, is the type of unordered pairs. It is equivalent in a natural way to multisets of cardinality 2 (see `Sym2.equivMultiset`). -/ abbrev Sym2 (α : Type u) := Quot (Sym2.Rel α) /-- Constructor for `Sym2`. This is the quotient map `α × α → Sym2 α`. -/ protected abbrev Sym2.mk {α : Type*} (p : α × α) : Sym2 α := Quot.mk (Sym2.Rel α) p /-- `s(x, y)` is an unordered pair, which is to say a pair modulo the action of the symmetric group. It is equal to `Sym2.mk (x, y)`. -/ notation3 "s(" x ", " y ")" => Sym2.mk (x, y) namespace Sym2 protected theorem sound {p p' : α × α} (h : Sym2.Rel α p p') : Sym2.mk p = Sym2.mk p' := Quot.sound h protected theorem exact {p p' : α × α} (h : Sym2.mk p = Sym2.mk p') : Sym2.Rel α p p' := Quotient.exact (s := Sym2.Rel.setoid α) h @[simp] protected theorem eq {p p' : α × α} : Sym2.mk p = Sym2.mk p' ↔ Sym2.Rel α p p' := Quotient.eq' (s₁ := Sym2.Rel.setoid α) @[elab_as_elim, cases_eliminator, induction_eliminator] protected theorem ind {f : Sym2 α → Prop} (h : ∀ x y, f s(x, y)) : ∀ i, f i := Quot.ind <| Prod.rec <| h @[elab_as_elim] protected theorem inductionOn {f : Sym2 α → Prop} (i : Sym2 α) (hf : ∀ x y, f s(x, y)) : f i := i.ind hf @[elab_as_elim] protected theorem inductionOn₂ {f : Sym2 α → Sym2 β → Prop} (i : Sym2 α) (j : Sym2 β) (hf : ∀ a₁ a₂ b₁ b₂, f s(a₁, a₂) s(b₁, b₂)) : f i j := Quot.induction_on₂ i j <| by intro ⟨a₁, a₂⟩ ⟨b₁, b₂⟩ exact hf _ _ _ _ /-- Dependent recursion principal for `Sym2`. See `Quot.rec`. -/ @[elab_as_elim] protected def rec {motive : Sym2 α → Sort*} (f : (p : α × α) → motive (Sym2.mk p)) (h : (p q : α × α) → (h : Sym2.Rel α p q) → Eq.ndrec (f p) (Sym2.sound h) = f q) (z : Sym2 α) : motive z := Quot.rec f h z /-- Dependent recursion principal for `Sym2` when the target is a `Subsingleton` type. See `Quot.recOnSubsingleton`. -/ @[elab_as_elim] protected abbrev recOnSubsingleton {motive : Sym2 α → Sort*} [(p : α × α) → Subsingleton (motive (Sym2.mk p))] (z : Sym2 α) (f : (p : α × α) → motive (Sym2.mk p)) : motive z := Quot.recOnSubsingleton z f protected theorem «exists» {α : Sort _} {f : Sym2 α → Prop} : (∃ x : Sym2 α, f x) ↔ ∃ x y, f s(x, y) := Quot.mk_surjective.exists.trans Prod.exists protected theorem «forall» {α : Sort _} {f : Sym2 α → Prop} : (∀ x : Sym2 α, f x) ↔ ∀ x y, f s(x, y) := Quot.mk_surjective.forall.trans Prod.forall theorem eq_swap {a b : α} : s(a, b) = s(b, a) := Quot.sound (Rel.swap _ _) @[simp] theorem mk_prod_swap_eq {p : α × α} : Sym2.mk p.swap = Sym2.mk p := by cases p exact eq_swap theorem congr_right {a b c : α} : s(a, b) = s(a, c) ↔ b = c := by simp +contextual theorem congr_left {a b c : α} : s(b, a) = s(c, a) ↔ b = c := by simp +contextual theorem eq_iff {x y z w : α} : s(x, y) = s(z, w) ↔ x = z ∧ y = w ∨ x = w ∧ y = z := by simp theorem mk_eq_mk_iff {p q : α × α} : Sym2.mk p = Sym2.mk q ↔ p = q ∨ p = q.swap := by cases p cases q simp only [eq_iff, Prod.mk_inj, Prod.swap_prod_mk] /-- The universal property of `Sym2`; symmetric functions of two arguments are equivalent to functions from `Sym2`. Note that when `β` is `Prop`, it can sometimes be more convenient to use `Sym2.fromRel` instead. -/ def lift : { f : α → α → β // ∀ a₁ a₂, f a₁ a₂ = f a₂ a₁ } ≃ (Sym2 α → β) where toFun f := Quot.lift (uncurry ↑f) <| by rintro _ _ ⟨⟩ exacts [rfl, f.prop _ _] invFun F := ⟨curry (F ∘ Sym2.mk), fun _ _ => congr_arg F eq_swap⟩ left_inv _ := Subtype.ext rfl right_inv _ := funext <| Sym2.ind fun _ _ => rfl @[simp] theorem lift_mk (f : { f : α → α → β // ∀ a₁ a₂, f a₁ a₂ = f a₂ a₁ }) (a₁ a₂ : α) : lift f s(a₁, a₂) = (f : α → α → β) a₁ a₂ := rfl @[simp] theorem coe_lift_symm_apply (F : Sym2 α → β) (a₁ a₂ : α) : (lift.symm F : α → α → β) a₁ a₂ = F s(a₁, a₂) := rfl /-- A two-argument version of `Sym2.lift`. -/ def lift₂ : { f : α → α → β → β → γ // ∀ a₁ a₂ b₁ b₂, f a₁ a₂ b₁ b₂ = f a₂ a₁ b₁ b₂ ∧ f a₁ a₂ b₁ b₂ = f a₁ a₂ b₂ b₁ } ≃ (Sym2 α → Sym2 β → γ) where toFun f := Quotient.lift₂ (s₁ := Sym2.Rel.setoid α) (s₂ := Sym2.Rel.setoid β) (fun (a : α × α) (b : β × β) => f.1 a.1 a.2 b.1 b.2) (by rintro _ _ _ _ ⟨⟩ ⟨⟩ exacts [rfl, (f.2 _ _ _ _).2, (f.2 _ _ _ _).1, (f.2 _ _ _ _).1.trans (f.2 _ _ _ _).2]) invFun F := ⟨fun a₁ a₂ b₁ b₂ => F s(a₁, a₂) s(b₁, b₂), fun a₁ a₂ b₁ b₂ => by constructor exacts [congr_arg₂ F eq_swap rfl, congr_arg₂ F rfl eq_swap]⟩ left_inv _ := Subtype.ext rfl right_inv _ := funext₂ fun a b => Sym2.inductionOn₂ a b fun _ _ _ _ => rfl @[simp] theorem lift₂_mk (f : { f : α → α → β → β → γ // ∀ a₁ a₂ b₁ b₂, f a₁ a₂ b₁ b₂ = f a₂ a₁ b₁ b₂ ∧ f a₁ a₂ b₁ b₂ = f a₁ a₂ b₂ b₁ }) (a₁ a₂ : α) (b₁ b₂ : β) : lift₂ f s(a₁, a₂) s(b₁, b₂) = (f : α → α → β → β → γ) a₁ a₂ b₁ b₂ := rfl @[simp] theorem coe_lift₂_symm_apply (F : Sym2 α → Sym2 β → γ) (a₁ a₂ : α) (b₁ b₂ : β) : (lift₂.symm F : α → α → β → β → γ) a₁ a₂ b₁ b₂ = F s(a₁, a₂) s(b₁, b₂) := rfl /-- The functor `Sym2` is functorial, and this function constructs the induced maps. -/ def map (f : α → β) : Sym2 α → Sym2 β := Quot.map (Prod.map f f) (by intro _ _ h; cases h <;> constructor) @[simp] theorem map_id : map (@id α) = id := by ext ⟨⟨x, y⟩⟩ rfl theorem map_comp {g : β → γ} {f : α → β} : Sym2.map (g ∘ f) = Sym2.map g ∘ Sym2.map f := by ext ⟨⟨x, y⟩⟩ rfl theorem map_map {g : β → γ} {f : α → β} (x : Sym2 α) : map g (map f x) = map (g ∘ f) x := by induction x; aesop @[simp] theorem map_pair_eq (f : α → β) (x y : α) : map f s(x, y) = s(f x, f y) := rfl theorem map.injective {f : α → β} (hinj : Injective f) : Injective (map f) := by intro z z' refine Sym2.inductionOn₂ z z' (fun x y x' y' => ?_) simp [hinj.eq_iff] /-- `mk a` as an embedding. This is the symmetric version of `Function.Embedding.sectL`. -/ @[simps] def mkEmbedding (a : α) : α ↪ Sym2 α where toFun b := s(a, b) inj' b₁ b₁ h := by simp only [Sym2.eq, Sym2.rel_iff', Prod.mk.injEq, true_and, Prod.swap_prod_mk] at h obtain rfl | ⟨rfl, rfl⟩ := h <;> rfl /-- `Sym2.map` as an embedding. -/ @[simps] def _root_.Function.Embedding.sym2Map (f : α ↪ β) : Sym2 α ↪ Sym2 β where toFun := map f
inj' := map.injective f.injective lemma lift_comp_map {g : γ → α} (f : {f : α → α → β // ∀ a₁ a₂, f a₁ a₂ = f a₂ a₁}) :
Mathlib/Data/Sym/Sym2.lean
270
272
/- Copyright (c) 2022 Wrenna Robson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Wrenna Robson -/ import Mathlib.Topology.MetricSpace.Basic /-! # Infimum separation This file defines the extended infimum separation of a set. This is approximately dual to the diameter of a set, but where the extended diameter of a set is the supremum of the extended distance between elements of the set, the extended infimum separation is the infimum of the (extended) distance between *distinct* elements in the set. We also define the infimum separation as the cast of the extended infimum separation to the reals. This is the infimum of the distance between distinct elements of the set when in a pseudometric space. All lemmas and definitions are in the `Set` namespace to give access to dot notation. ## Main definitions * `Set.einfsep`: Extended infimum separation of a set. * `Set.infsep`: Infimum separation of a set (when in a pseudometric space). -/ variable {α β : Type*} namespace Set section Einfsep open ENNReal open Function /-- The "extended infimum separation" of a set with an edist function. -/ noncomputable def einfsep [EDist α] (s : Set α) : ℝ≥0∞ := ⨅ (x ∈ s) (y ∈ s) (_ : x ≠ y), edist x y section EDist variable [EDist α] {x y : α} {s t : Set α} theorem le_einfsep_iff {d} : d ≤ s.einfsep ↔ ∀ x ∈ s, ∀ y ∈ s, x ≠ y → d ≤ edist x y := by simp_rw [einfsep, le_iInf_iff] theorem einfsep_zero : s.einfsep = 0 ↔ ∀ C > 0, ∃ x ∈ s, ∃ y ∈ s, x ≠ y ∧ edist x y < C := by simp_rw [einfsep, ← _root_.bot_eq_zero, iInf_eq_bot, iInf_lt_iff, exists_prop] theorem einfsep_pos : 0 < s.einfsep ↔ ∃ C > 0, ∀ x ∈ s, ∀ y ∈ s, x ≠ y → C ≤ edist x y := by rw [pos_iff_ne_zero, Ne, einfsep_zero] simp only [not_forall, not_exists, not_lt, exists_prop, not_and] theorem einfsep_top : s.einfsep = ∞ ↔ ∀ x ∈ s, ∀ y ∈ s, x ≠ y → edist x y = ∞ := by simp_rw [einfsep, iInf_eq_top] theorem einfsep_lt_top : s.einfsep < ∞ ↔ ∃ x ∈ s, ∃ y ∈ s, x ≠ y ∧ edist x y < ∞ := by simp_rw [einfsep, iInf_lt_iff, exists_prop] theorem einfsep_ne_top : s.einfsep ≠ ∞ ↔ ∃ x ∈ s, ∃ y ∈ s, x ≠ y ∧ edist x y ≠ ∞ := by simp_rw [← lt_top_iff_ne_top, einfsep_lt_top] theorem einfsep_lt_iff {d} : s.einfsep < d ↔ ∃ x ∈ s, ∃ y ∈ s, x ≠ y ∧ edist x y < d := by simp_rw [einfsep, iInf_lt_iff, exists_prop]
theorem nontrivial_of_einfsep_lt_top (hs : s.einfsep < ∞) : s.Nontrivial := by rcases einfsep_lt_top.1 hs with ⟨_, hx, _, hy, hxy, _⟩ exact ⟨_, hx, _, hy, hxy⟩
Mathlib/Topology/MetricSpace/Infsep.lean
74
76
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Kevin Kappelmann -/ import Mathlib.Algebra.Order.Floor.Defs import Mathlib.Algebra.Order.Floor.Ring import Mathlib.Algebra.Order.Floor.Semiring deprecated_module (since := "2025-04-13")
Mathlib/Algebra/Order/Floor.lean
958
960
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen, Filippo A. E. Nuccio -/ import Mathlib.Algebra.EuclideanDomain.Basic import Mathlib.RingTheory.FractionalIdeal.Basic import Mathlib.RingTheory.IntegralClosure.IsIntegral.Basic import Mathlib.RingTheory.LocalRing.Basic import Mathlib.RingTheory.PrincipalIdealDomain import Mathlib.Tactic.FieldSimp /-! # More operations on fractional ideals ## Main definitions * `map` is the pushforward of a fractional ideal along an algebra morphism Let `K` be the localization of `R` at `R⁰ = R \ {0}` (i.e. the field of fractions). * `FractionalIdeal R⁰ K` is the type of fractional ideals in the field of fractions * `Div (FractionalIdeal R⁰ K)` instance: the ideal quotient `I / J` (typically written $I : J$, but a `:` operator cannot be defined) ## Main statement * `isNoetherian` states that every fractional ideal of a noetherian integral domain is noetherian ## References * https://en.wikipedia.org/wiki/Fractional_ideal ## Tags fractional ideal, fractional ideals, invertible ideal -/ open IsLocalization Pointwise nonZeroDivisors namespace FractionalIdeal open Set Submodule variable {R : Type*} [CommRing R] {S : Submonoid R} {P : Type*} [CommRing P] variable [Algebra R P] section variable {P' : Type*} [CommRing P'] [Algebra R P'] variable {P'' : Type*} [CommRing P''] [Algebra R P''] theorem _root_.IsFractional.map (g : P →ₐ[R] P') {I : Submodule R P} : IsFractional S I → IsFractional S (Submodule.map g.toLinearMap I) | ⟨a, a_nonzero, hI⟩ => ⟨a, a_nonzero, fun b hb => by obtain ⟨b', b'_mem, hb'⟩ := Submodule.mem_map.mp hb rw [AlgHom.toLinearMap_apply] at hb' obtain ⟨x, hx⟩ := hI b' b'_mem use x rw [← g.commutes, hx, map_smul, hb']⟩ /-- `I.map g` is the pushforward of the fractional ideal `I` along the algebra morphism `g` -/ def map (g : P →ₐ[R] P') : FractionalIdeal S P → FractionalIdeal S P' := fun I => ⟨Submodule.map g.toLinearMap I, I.isFractional.map g⟩ @[simp, norm_cast] theorem coe_map (g : P →ₐ[R] P') (I : FractionalIdeal S P) : ↑(map g I) = Submodule.map g.toLinearMap I := rfl @[simp] theorem mem_map {I : FractionalIdeal S P} {g : P →ₐ[R] P'} {y : P'} : y ∈ I.map g ↔ ∃ x, x ∈ I ∧ g x = y := Submodule.mem_map variable (I J : FractionalIdeal S P) (g : P →ₐ[R] P') @[simp] theorem map_id : I.map (AlgHom.id _ _) = I := coeToSubmodule_injective (Submodule.map_id (I : Submodule R P)) @[simp] theorem map_comp (g' : P' →ₐ[R] P'') : I.map (g'.comp g) = (I.map g).map g' := coeToSubmodule_injective (Submodule.map_comp g.toLinearMap g'.toLinearMap I) @[simp, norm_cast] theorem map_coeIdeal (I : Ideal R) : (I : FractionalIdeal S P).map g = I := by ext x simp only [mem_coeIdeal] constructor · rintro ⟨_, ⟨y, hy, rfl⟩, rfl⟩ exact ⟨y, hy, (g.commutes y).symm⟩ · rintro ⟨y, hy, rfl⟩ exact ⟨_, ⟨y, hy, rfl⟩, g.commutes y⟩ @[simp] protected theorem map_one : (1 : FractionalIdeal S P).map g = 1 := map_coeIdeal g ⊤ @[simp] protected theorem map_zero : (0 : FractionalIdeal S P).map g = 0 := map_coeIdeal g 0 @[simp] protected theorem map_add : (I + J).map g = I.map g + J.map g := coeToSubmodule_injective (Submodule.map_sup _ _ _) @[simp] protected theorem map_mul : (I * J).map g = I.map g * J.map g := by simp only [mul_def] exact coeToSubmodule_injective (Submodule.map_mul _ _ _) @[simp] theorem map_map_symm (g : P ≃ₐ[R] P') : (I.map (g : P →ₐ[R] P')).map (g.symm : P' →ₐ[R] P) = I := by rw [← map_comp, g.symm_comp, map_id] @[simp] theorem map_symm_map (I : FractionalIdeal S P') (g : P ≃ₐ[R] P') : (I.map (g.symm : P' →ₐ[R] P)).map (g : P →ₐ[R] P') = I := by rw [← map_comp, g.comp_symm, map_id] theorem map_mem_map {f : P →ₐ[R] P'} (h : Function.Injective f) {x : P} {I : FractionalIdeal S P} : f x ∈ map f I ↔ x ∈ I := mem_map.trans ⟨fun ⟨_, hx', x'_eq⟩ => h x'_eq ▸ hx', fun h => ⟨x, h, rfl⟩⟩ theorem map_injective (f : P →ₐ[R] P') (h : Function.Injective f) : Function.Injective (map f : FractionalIdeal S P → FractionalIdeal S P') := fun _ _ hIJ => ext fun _ => (map_mem_map h).symm.trans (hIJ.symm ▸ map_mem_map h) /-- If `g` is an equivalence, `map g` is an isomorphism -/ def mapEquiv (g : P ≃ₐ[R] P') : FractionalIdeal S P ≃+* FractionalIdeal S P' where toFun := map g invFun := map g.symm map_add' I J := FractionalIdeal.map_add I J _ map_mul' I J := FractionalIdeal.map_mul I J _ left_inv I := by rw [← map_comp, AlgEquiv.symm_comp, map_id] right_inv I := by rw [← map_comp, AlgEquiv.comp_symm, map_id] @[simp] theorem coeFun_mapEquiv (g : P ≃ₐ[R] P') : (mapEquiv g : FractionalIdeal S P → FractionalIdeal S P') = map g := rfl @[simp] theorem mapEquiv_apply (g : P ≃ₐ[R] P') (I : FractionalIdeal S P) : mapEquiv g I = map (↑g) I := rfl @[simp] theorem mapEquiv_symm (g : P ≃ₐ[R] P') : ((mapEquiv g).symm : FractionalIdeal S P' ≃+* _) = mapEquiv g.symm := rfl @[simp] theorem mapEquiv_refl : mapEquiv AlgEquiv.refl = RingEquiv.refl (FractionalIdeal S P) := RingEquiv.ext fun x => by simp theorem isFractional_span_iff {s : Set P} : IsFractional S (span R s) ↔ ∃ a ∈ S, ∀ b : P, b ∈ s → IsInteger R (a • b) := ⟨fun ⟨a, a_mem, h⟩ => ⟨a, a_mem, fun b hb => h b (subset_span hb)⟩, fun ⟨a, a_mem, h⟩ => ⟨a, a_mem, fun _ hb => span_induction (hx := hb) h (by rw [smul_zero] exact isInteger_zero) (fun x y _ _ hx hy => by rw [smul_add] exact isInteger_add hx hy) fun s x _ hx => by rw [smul_comm] exact isInteger_smul hx⟩⟩ theorem isFractional_of_fg [IsLocalization S P] {I : Submodule R P} (hI : I.FG) : IsFractional S I := by rcases hI with ⟨I, rfl⟩ rcases exist_integer_multiples_of_finset S I with ⟨⟨s, hs1⟩, hs⟩ rw [isFractional_span_iff] exact ⟨s, hs1, hs⟩ theorem mem_span_mul_finite_of_mem_mul {I J : FractionalIdeal S P} {x : P} (hx : x ∈ I * J) : ∃ T T' : Finset P, (T : Set P) ⊆ I ∧ (T' : Set P) ⊆ J ∧ x ∈ span R (T * T' : Set P) := Submodule.mem_span_mul_finite_of_mem_mul (by simpa using mem_coe.mpr hx) variable (S) in theorem coeIdeal_fg (inj : Function.Injective (algebraMap R P)) (I : Ideal R) : FG ((I : FractionalIdeal S P) : Submodule R P) ↔ I.FG := coeSubmodule_fg _ inj _ theorem fg_unit (I : (FractionalIdeal S P)ˣ) : FG (I : Submodule R P) := Submodule.fg_unit <| Units.map (coeSubmoduleHom S P).toMonoidHom I theorem fg_of_isUnit (I : FractionalIdeal S P) (h : IsUnit I) : FG (I : Submodule R P) := fg_unit h.unit theorem _root_.Ideal.fg_of_isUnit (inj : Function.Injective (algebraMap R P)) (I : Ideal R) (h : IsUnit (I : FractionalIdeal S P)) : I.FG := by rw [← coeIdeal_fg S inj I] exact FractionalIdeal.fg_of_isUnit (R := R) I h variable (S P P') variable [IsLocalization S P] [IsLocalization S P'] /-- `canonicalEquiv f f'` is the canonical equivalence between the fractional ideals in `P` and in `P'`, which are both localizations of `R` at `S`. -/ noncomputable irreducible_def canonicalEquiv : FractionalIdeal S P ≃+* FractionalIdeal S P' := mapEquiv { ringEquivOfRingEquiv P P' (RingEquiv.refl R) (show S.map _ = S by rw [RingEquiv.toMonoidHom_refl, Submonoid.map_id]) with commutes' := fun _ => ringEquivOfRingEquiv_eq _ _ } @[simp] theorem mem_canonicalEquiv_apply {I : FractionalIdeal S P} {x : P'} : x ∈ canonicalEquiv S P P' I ↔ ∃ y ∈ I, IsLocalization.map P' (RingHom.id R) (fun y (hy : y ∈ S) => show RingHom.id R y ∈ S from hy) (y : P) = x := by rw [canonicalEquiv, mapEquiv_apply, mem_map] exact ⟨fun ⟨y, mem, Eq⟩ => ⟨y, mem, Eq⟩, fun ⟨y, mem, Eq⟩ => ⟨y, mem, Eq⟩⟩ @[simp] theorem canonicalEquiv_symm : (canonicalEquiv S P P').symm = canonicalEquiv S P' P := RingEquiv.ext fun I => SetLike.ext_iff.mpr fun x => by rw [mem_canonicalEquiv_apply, canonicalEquiv, mapEquiv_symm, mapEquiv_apply, mem_map] exact ⟨fun ⟨y, mem, Eq⟩ => ⟨y, mem, Eq⟩, fun ⟨y, mem, Eq⟩ => ⟨y, mem, Eq⟩⟩ theorem canonicalEquiv_flip (I) : canonicalEquiv S P P' (canonicalEquiv S P' P I) = I := by rw [← canonicalEquiv_symm, RingEquiv.symm_apply_apply] @[simp] theorem canonicalEquiv_canonicalEquiv (P'' : Type*) [CommRing P''] [Algebra R P''] [IsLocalization S P''] (I : FractionalIdeal S P) : canonicalEquiv S P' P'' (canonicalEquiv S P P' I) = canonicalEquiv S P P'' I := by ext simp only [IsLocalization.map_map, RingHomInvPair.comp_eq₂, mem_canonicalEquiv_apply, exists_prop, exists_exists_and_eq_and] theorem canonicalEquiv_trans_canonicalEquiv (P'' : Type*) [CommRing P''] [Algebra R P''] [IsLocalization S P''] : (canonicalEquiv S P P').trans (canonicalEquiv S P' P'') = canonicalEquiv S P P'' := RingEquiv.ext (canonicalEquiv_canonicalEquiv S P P' P'') @[simp] theorem canonicalEquiv_coeIdeal (I : Ideal R) : canonicalEquiv S P P' I = I := by ext simp [IsLocalization.map_eq] @[simp] theorem canonicalEquiv_self : canonicalEquiv S P P = RingEquiv.refl _ := by rw [← canonicalEquiv_trans_canonicalEquiv S P P] convert (canonicalEquiv S P P).symm_trans_self exact (canonicalEquiv_symm S P P).symm end section IsFractionRing /-! ### `IsFractionRing` section This section concerns fractional ideals in the field of fractions, i.e. the type `FractionalIdeal R⁰ K` where `IsFractionRing R K`. -/ variable {K K' : Type*} [Field K] [Field K'] variable [Algebra R K] [IsFractionRing R K] [Algebra R K'] [IsFractionRing R K'] variable {I J : FractionalIdeal R⁰ K} (h : K →ₐ[R] K') /-- Nonzero fractional ideals contain a nonzero integer. -/ theorem exists_ne_zero_mem_isInteger [Nontrivial R] (hI : I ≠ 0) : ∃ x, x ≠ 0 ∧ algebraMap R K x ∈ I := by obtain ⟨y : K, y_mem, y_not_mem⟩ := SetLike.exists_of_lt (by simpa only using bot_lt_iff_ne_bot.mpr hI) have y_ne_zero : y ≠ 0 := by simpa using y_not_mem obtain ⟨z, ⟨x, hx⟩⟩ := exists_integer_multiple R⁰ y refine ⟨x, ?_, ?_⟩ · rw [Ne, ← @IsFractionRing.to_map_eq_zero_iff R _ K, hx, Algebra.smul_def] exact mul_ne_zero (IsFractionRing.to_map_ne_zero_of_mem_nonZeroDivisors z.2) y_ne_zero · rw [hx] exact smul_mem _ _ y_mem theorem map_ne_zero [Nontrivial R] (hI : I ≠ 0) : I.map h ≠ 0 := by obtain ⟨x, x_ne_zero, hx⟩ := exists_ne_zero_mem_isInteger hI contrapose! x_ne_zero with map_eq_zero refine IsFractionRing.to_map_eq_zero_iff.mp (eq_zero_iff.mp map_eq_zero _ (mem_map.mpr ?_)) exact ⟨algebraMap R K x, hx, h.commutes x⟩ @[simp] theorem map_eq_zero_iff [Nontrivial R] : I.map h = 0 ↔ I = 0 := ⟨not_imp_not.mp (map_ne_zero _), fun hI => hI.symm ▸ FractionalIdeal.map_zero h⟩ theorem coeIdeal_injective : Function.Injective (fun (I : Ideal R) ↦ (I : FractionalIdeal R⁰ K)) := coeIdeal_injective' le_rfl theorem coeIdeal_inj {I J : Ideal R} : (I : FractionalIdeal R⁰ K) = (J : FractionalIdeal R⁰ K) ↔ I = J := coeIdeal_inj' le_rfl @[simp] theorem coeIdeal_eq_zero {I : Ideal R} : (I : FractionalIdeal R⁰ K) = 0 ↔ I = ⊥ := coeIdeal_eq_zero' le_rfl theorem coeIdeal_ne_zero {I : Ideal R} : (I : FractionalIdeal R⁰ K) ≠ 0 ↔ I ≠ ⊥ := coeIdeal_ne_zero' le_rfl @[simp] theorem coeIdeal_eq_one {I : Ideal R} : (I : FractionalIdeal R⁰ K) = 1 ↔ I = 1 := by simpa only [Ideal.one_eq_top] using coeIdeal_inj theorem coeIdeal_ne_one {I : Ideal R} : (I : FractionalIdeal R⁰ K) ≠ 1 ↔ I ≠ 1 := not_iff_not.mpr coeIdeal_eq_one theorem num_eq_zero_iff [Nontrivial R] {I : FractionalIdeal R⁰ K} : I.num = 0 ↔ I = 0 := ⟨fun h ↦ zero_of_num_eq_bot zero_not_mem_nonZeroDivisors h, fun h ↦ h ▸ num_zero_eq (IsFractionRing.injective R K)⟩ end IsFractionRing section Quotient /-! ### `quotient` section This section defines the ideal quotient of fractional ideals. In this section we need that each non-zero `y : R` has an inverse in the localization, i.e. that the localization is a field. We satisfy this assumption by taking `S = nonZeroDivisors R`, `R`'s localization at which is a field because `R` is a domain. -/ variable {R₁ : Type*} [CommRing R₁] {K : Type*} [Field K] variable [Algebra R₁ K] instance : Nontrivial (FractionalIdeal R₁⁰ K) := ⟨⟨0, 1, fun h => have this : (1 : K) ∈ (0 : FractionalIdeal R₁⁰ K) := by rw [← (algebraMap R₁ K).map_one] simpa only [h] using coe_mem_one R₁⁰ 1 one_ne_zero ((mem_zero_iff _).mp this)⟩⟩ theorem ne_zero_of_mul_eq_one (I J : FractionalIdeal R₁⁰ K) (h : I * J = 1) : I ≠ 0 := fun hI => zero_ne_one' (FractionalIdeal R₁⁰ K) (by convert h simp [hI]) variable [IsFractionRing R₁ K] [IsDomain R₁] theorem _root_.IsFractional.div_of_nonzero {I J : Submodule R₁ K} : IsFractional R₁⁰ I → IsFractional R₁⁰ J → J ≠ 0 → IsFractional R₁⁰ (I / J) | ⟨aI, haI, hI⟩, ⟨aJ, haJ, hJ⟩, h => by obtain ⟨y, mem_J, not_mem_zero⟩ := SetLike.exists_of_lt (show 0 < J by simpa only using bot_lt_iff_ne_bot.mpr h) obtain ⟨y', hy'⟩ := hJ y mem_J use aI * y' constructor · apply (nonZeroDivisors R₁).mul_mem haI (mem_nonZeroDivisors_iff_ne_zero.mpr _) intro y'_eq_zero have : algebraMap R₁ K aJ * y = 0 := by rw [← Algebra.smul_def, ← hy', y'_eq_zero, RingHom.map_zero] have y_zero := (mul_eq_zero.mp this).resolve_left (mt ((injective_iff_map_eq_zero (algebraMap R₁ K)).1 (IsFractionRing.injective _ _) _) (mem_nonZeroDivisors_iff_ne_zero.mp haJ)) apply not_mem_zero simpa intro b hb convert hI _ (hb _ (Submodule.smul_mem _ aJ mem_J)) using 1 rw [← hy', mul_comm b, ← Algebra.smul_def, mul_smul] theorem fractional_div_of_nonzero {I J : FractionalIdeal R₁⁰ K} (h : J ≠ 0) : IsFractional R₁⁰ (I / J : Submodule R₁ K) := I.isFractional.div_of_nonzero J.isFractional fun H => h <| coeToSubmodule_injective <| H.trans coe_zero.symm open Classical in noncomputable instance : Div (FractionalIdeal R₁⁰ K) := ⟨fun I J => if h : J = 0 then 0 else ⟨I / J, fractional_div_of_nonzero h⟩⟩ variable {I J : FractionalIdeal R₁⁰ K} @[simp] theorem div_zero {I : FractionalIdeal R₁⁰ K} : I / 0 = 0 := dif_pos rfl theorem div_nonzero {I J : FractionalIdeal R₁⁰ K} (h : J ≠ 0) : I / J = ⟨I / J, fractional_div_of_nonzero h⟩ := dif_neg h @[simp] theorem coe_div {I J : FractionalIdeal R₁⁰ K} (hJ : J ≠ 0) : (↑(I / J) : Submodule R₁ K) = ↑I / (↑J : Submodule R₁ K) := congr_arg _ (dif_neg hJ) theorem mem_div_iff_of_nonzero {I J : FractionalIdeal R₁⁰ K} (h : J ≠ 0) {x} : x ∈ I / J ↔ ∀ y ∈ J, x * y ∈ I := by rw [div_nonzero h] exact Submodule.mem_div_iff_forall_mul_mem theorem mul_one_div_le_one {I : FractionalIdeal R₁⁰ K} : I * (1 / I) ≤ 1 := by by_cases hI : I = 0 · rw [hI, div_zero, mul_zero] exact zero_le 1 · rw [← coe_le_coe, coe_mul, coe_div hI, coe_one] apply Submodule.mul_one_div_le_one theorem le_self_mul_one_div {I : FractionalIdeal R₁⁰ K} (hI : I ≤ (1 : FractionalIdeal R₁⁰ K)) : I ≤ I * (1 / I) := by by_cases hI_nz : I = 0 · rw [hI_nz, div_zero, mul_zero] · rw [← coe_le_coe, coe_mul, coe_div hI_nz, coe_one] rw [← coe_le_coe, coe_one] at hI exact Submodule.le_self_mul_one_div hI theorem le_div_iff_of_nonzero {I J J' : FractionalIdeal R₁⁰ K} (hJ' : J' ≠ 0) : I ≤ J / J' ↔ ∀ x ∈ I, ∀ y ∈ J', x * y ∈ J := ⟨fun h _ hx => (mem_div_iff_of_nonzero hJ').mp (h hx), fun h x hx => (mem_div_iff_of_nonzero hJ').mpr (h x hx)⟩ theorem le_div_iff_mul_le {I J J' : FractionalIdeal R₁⁰ K} (hJ' : J' ≠ 0) : I ≤ J / J' ↔ I * J' ≤ J := by rw [div_nonzero hJ'] -- Porting note: this used to be { convert; rw }, flipped the order. rw [← coe_le_coe (I := I * J') (J := J), coe_mul] exact Submodule.le_div_iff_mul_le @[simp] theorem div_one {I : FractionalIdeal R₁⁰ K} : I / 1 = I := by rw [div_nonzero (one_ne_zero' (FractionalIdeal R₁⁰ K))] ext constructor <;> intro h · simpa using mem_div_iff_forall_mul_mem.mp h 1 ((algebraMap R₁ K).map_one ▸ coe_mem_one R₁⁰ 1) · apply mem_div_iff_forall_mul_mem.mpr rintro y ⟨y', _, rfl⟩ -- Porting note: this used to be { convert; rw }, flipped the order. rw [mul_comm, Algebra.linearMap_apply, ← Algebra.smul_def] exact Submodule.smul_mem _ y' h theorem eq_one_div_of_mul_eq_one_right (I J : FractionalIdeal R₁⁰ K) (h : I * J = 1) : J = 1 / I := by have hI : I ≠ 0 := ne_zero_of_mul_eq_one I J h suffices h' : I * (1 / I) = 1 from congr_arg Units.inv <| @Units.ext _ _ (Units.mkOfMulEqOne _ _ h) (Units.mkOfMulEqOne _ _ h') rfl apply le_antisymm · apply mul_le.mpr _ intro x hx y hy rw [mul_comm] exact (mem_div_iff_of_nonzero hI).mp hy x hx rw [← h] apply mul_left_mono I apply (le_div_iff_of_nonzero hI).mpr _ intro y hy x hx rw [mul_comm] exact mul_mem_mul hy hx theorem mul_div_self_cancel_iff {I : FractionalIdeal R₁⁰ K} : I * (1 / I) = 1 ↔ ∃ J, I * J = 1 := ⟨fun h => ⟨1 / I, h⟩, fun ⟨J, hJ⟩ => by rwa [← eq_one_div_of_mul_eq_one_right I J hJ]⟩ variable {K' : Type*} [Field K'] [Algebra R₁ K'] [IsFractionRing R₁ K'] @[simp] protected theorem map_div (I J : FractionalIdeal R₁⁰ K) (h : K ≃ₐ[R₁] K') : (I / J).map (h : K →ₐ[R₁] K') = I.map h / J.map h := by by_cases H : J = 0 · rw [H, div_zero, FractionalIdeal.map_zero, div_zero] · -- Porting note: `simp` wouldn't apply these lemmas so do them manually using `rw` rw [← coeToSubmodule_inj, div_nonzero H, div_nonzero (map_ne_zero _ H)] simp [Submodule.map_div] -- Porting note: doesn't need to be @[simp] because this follows from `map_one` and `map_div` theorem map_one_div (I : FractionalIdeal R₁⁰ K) (h : K ≃ₐ[R₁] K') : (1 / I).map (h : K →ₐ[R₁] K') = 1 / I.map h := by rw [FractionalIdeal.map_div, FractionalIdeal.map_one] end Quotient section Field variable {R₁ K L : Type*} [CommRing R₁] [Field K] [Field L] variable [Algebra R₁ K] [IsFractionRing R₁ K] [Algebra K L] [IsFractionRing K L] theorem eq_zero_or_one (I : FractionalIdeal K⁰ L) : I = 0 ∨ I = 1 := by rw [or_iff_not_imp_left] intro hI simp_rw [@SetLike.ext_iff _ _ _ I 1, mem_one_iff] intro x constructor · intro x_mem obtain ⟨n, d, rfl⟩ := IsLocalization.mk'_surjective K⁰ x refine ⟨n / d, ?_⟩ rw [map_div₀, IsFractionRing.mk'_eq_div] · rintro ⟨x, rfl⟩ obtain ⟨y, y_ne, y_mem⟩ := exists_ne_zero_mem_isInteger hI rw [← div_mul_cancel₀ x y_ne, RingHom.map_mul, ← Algebra.smul_def] exact smul_mem (M := L) I (x / y) y_mem theorem eq_zero_or_one_of_isField (hF : IsField R₁) (I : FractionalIdeal R₁⁰ K) : I = 0 ∨ I = 1 := letI : Field R₁ := hF.toField eq_zero_or_one I end Field section PrincipalIdeal variable {R₁ : Type*} [CommRing R₁] {K : Type*} [Field K] variable [Algebra R₁ K] [IsFractionRing R₁ K] variable (R₁) /-- `FractionalIdeal.span_finset R₁ s f` is the fractional ideal of `R₁` generated by `f '' s`. -/ -- Porting note: `@[simps]` generated a `Subtype.val` coercion instead of a -- `FractionalIdeal.coeToSubmodule` coercion def spanFinset {ι : Type*} (s : Finset ι) (f : ι → K) : FractionalIdeal R₁⁰ K := ⟨Submodule.span R₁ (f '' s), by obtain ⟨a', ha'⟩ := IsLocalization.exist_integer_multiples R₁⁰ s f refine ⟨a', a'.2, fun x hx => Submodule.span_induction ?_ ?_ ?_ ?_ hx⟩ · rintro _ ⟨i, hi, rfl⟩ exact ha' i hi · rw [smul_zero] exact IsLocalization.isInteger_zero · intro x y _ _ hx hy rw [smul_add] exact IsLocalization.isInteger_add hx hy · intro c x _ hx rw [smul_comm] exact IsLocalization.isInteger_smul hx⟩ @[simp] lemma spanFinset_coe {ι : Type*} (s : Finset ι) (f : ι → K) : (spanFinset R₁ s f : Submodule R₁ K) = Submodule.span R₁ (f '' s) := rfl variable {R₁} @[simp] theorem spanFinset_eq_zero {ι : Type*} {s : Finset ι} {f : ι → K} : spanFinset R₁ s f = 0 ↔ ∀ j ∈ s, f j = 0 := by simp only [← coeToSubmodule_inj, spanFinset_coe, coe_zero, Submodule.span_eq_bot, Set.mem_image, Finset.mem_coe, forall_exists_index, and_imp, forall_apply_eq_imp_iff₂] theorem spanFinset_ne_zero {ι : Type*} {s : Finset ι} {f : ι → K} : spanFinset R₁ s f ≠ 0 ↔ ∃ j ∈ s, f j ≠ 0 := by simp open Submodule.IsPrincipal variable [IsLocalization S P] theorem isFractional_span_singleton (x : P) : IsFractional S (span R {x} : Submodule R P) := let ⟨a, ha⟩ := exists_integer_multiple S x isFractional_span_iff.mpr ⟨a, a.2, fun _ hx' => (Set.mem_singleton_iff.mp hx').symm ▸ ha⟩ variable (S) /-- `spanSingleton x` is the fractional ideal generated by `x` if `0 ∉ S` -/ irreducible_def spanSingleton (x : P) : FractionalIdeal S P := ⟨span R {x}, isFractional_span_singleton x⟩ -- local attribute [semireducible] span_singleton @[simp] theorem coe_spanSingleton (x : P) : (spanSingleton S x : Submodule R P) = span R {x} := by rw [spanSingleton] rfl @[simp] theorem mem_spanSingleton {x y : P} : x ∈ spanSingleton S y ↔ ∃ z : R, z • y = x := by rw [spanSingleton] exact Submodule.mem_span_singleton theorem mem_spanSingleton_self (x : P) : x ∈ spanSingleton S x := (mem_spanSingleton S).mpr ⟨1, one_smul _ _⟩ variable (P) in /-- A version of `FractionalIdeal.den_mul_self_eq_num` in terms of fractional ideals. -/ theorem den_mul_self_eq_num' (I : FractionalIdeal S P) : spanSingleton S (algebraMap R P I.den) * I = I.num := by apply coeToSubmodule_injective dsimp only rw [coe_mul, ← smul_eq_mul, coe_spanSingleton, smul_eq_mul, Submodule.span_singleton_mul] convert I.den_mul_self_eq_num using 1 ext rw [mem_smul_pointwise_iff_exists, mem_smul_pointwise_iff_exists] simp [smul_eq_mul, Algebra.smul_def, Submonoid.smul_def] variable {S} @[simp] theorem spanSingleton_le_iff_mem {x : P} {I : FractionalIdeal S P} : spanSingleton S x ≤ I ↔ x ∈ I := by rw [← coe_le_coe, coe_spanSingleton, Submodule.span_singleton_le_iff_mem, mem_coe] theorem spanSingleton_eq_spanSingleton [NoZeroSMulDivisors R P] {x y : P} : spanSingleton S x = spanSingleton S y ↔ ∃ z : Rˣ, z • x = y := by rw [← Submodule.span_singleton_eq_span_singleton, spanSingleton, spanSingleton] exact Subtype.mk_eq_mk theorem eq_spanSingleton_of_principal (I : FractionalIdeal S P) [IsPrincipal (I : Submodule R P)] : I = spanSingleton S (generator (I : Submodule R P)) := by -- Porting note: this used to be `coeToSubmodule_injective (span_singleton_generator ↑I).symm` -- but Lean 4 struggled to unify everything. Turned it into an explicit `rw`. rw [spanSingleton, ← coeToSubmodule_inj, coe_mk, span_singleton_generator] theorem isPrincipal_iff (I : FractionalIdeal S P) : IsPrincipal (I : Submodule R P) ↔ ∃ x, I = spanSingleton S x := ⟨fun _ => ⟨generator (I : Submodule R P), eq_spanSingleton_of_principal I⟩, fun ⟨x, hx⟩ => { principal := ⟨x, Eq.trans (congr_arg _ hx) (coe_spanSingleton _ x)⟩ }⟩ @[simp] theorem spanSingleton_zero : spanSingleton S (0 : P) = 0 := by ext simp [Submodule.mem_span_singleton, eq_comm] theorem spanSingleton_eq_zero_iff {y : P} : spanSingleton S y = 0 ↔ y = 0 := ⟨fun h => span_eq_bot.mp (by simpa using congr_arg Subtype.val h : span R {y} = ⊥) y (mem_singleton y), fun h => by simp [h]⟩ theorem spanSingleton_ne_zero_iff {y : P} : spanSingleton S y ≠ 0 ↔ y ≠ 0 := not_congr spanSingleton_eq_zero_iff @[simp] theorem spanSingleton_one : spanSingleton S (1 : P) = 1 := by ext refine (mem_spanSingleton S).trans ((exists_congr ?_).trans (mem_one_iff S).symm) intro x' rw [Algebra.smul_def, mul_one] @[simp] theorem spanSingleton_mul_spanSingleton (x y : P) : spanSingleton S x * spanSingleton S y = spanSingleton S (x * y) := by apply coeToSubmodule_injective simp only [coe_mul, coe_spanSingleton, span_mul_span, singleton_mul_singleton] @[simp] theorem spanSingleton_pow (x : P) (n : ℕ) : spanSingleton S x ^ n = spanSingleton S (x ^ n) := by induction' n with n hn · rw [pow_zero, pow_zero, spanSingleton_one] · rw [pow_succ, hn, spanSingleton_mul_spanSingleton, pow_succ] @[simp] theorem coeIdeal_span_singleton (x : R) : (↑(Ideal.span {x} : Ideal R) : FractionalIdeal S P) = spanSingleton S (algebraMap R P x) := by ext y refine (mem_coeIdeal S).trans (Iff.trans ?_ (mem_spanSingleton S).symm) constructor · rintro ⟨y', hy', rfl⟩ obtain ⟨x', rfl⟩ := Submodule.mem_span_singleton.mp hy' use x' rw [smul_eq_mul, RingHom.map_mul, Algebra.smul_def] · rintro ⟨y', rfl⟩ refine ⟨y' * x, Submodule.mem_span_singleton.mpr ⟨y', rfl⟩, ?_⟩ rw [RingHom.map_mul, Algebra.smul_def] @[simp] theorem canonicalEquiv_spanSingleton {P'} [CommRing P'] [Algebra R P'] [IsLocalization S P'] (x : P) : canonicalEquiv S P P' (spanSingleton S x) = spanSingleton S (IsLocalization.map P' (RingHom.id R) (fun y (hy : y ∈ S) => show RingHom.id R y ∈ S from hy) x) := by apply SetLike.ext_iff.mpr intro y constructor <;> intro h · rw [mem_spanSingleton] obtain ⟨x', hx', rfl⟩ := (mem_canonicalEquiv_apply _ _ _).mp h obtain ⟨z, rfl⟩ := (mem_spanSingleton _).mp hx' use z rw [IsLocalization.map_smul, RingHom.id_apply] · rw [mem_canonicalEquiv_apply] obtain ⟨z, rfl⟩ := (mem_spanSingleton _).mp h use z • x use (mem_spanSingleton _).mpr ⟨z, rfl⟩ simp [IsLocalization.map_smul] theorem mem_singleton_mul {x y : P} {I : FractionalIdeal S P} : y ∈ spanSingleton S x * I ↔ ∃ y' ∈ I, y = x * y' := by constructor · intro h refine FractionalIdeal.mul_induction_on h ?_ ?_ · intro x' hx' y' hy' obtain ⟨a, ha⟩ := (mem_spanSingleton S).mp hx' use a • y', Submodule.smul_mem (I : Submodule R P) a hy' rw [← ha, Algebra.mul_smul_comm, Algebra.smul_mul_assoc] · rintro _ _ ⟨y, hy, rfl⟩ ⟨y', hy', rfl⟩ exact ⟨y + y', Submodule.add_mem (I : Submodule R P) hy hy', (mul_add _ _ _).symm⟩ · rintro ⟨y', hy', rfl⟩ exact mul_mem_mul ((mem_spanSingleton S).mpr ⟨1, one_smul _ _⟩) hy' variable (K) in theorem mk'_mul_coeIdeal_eq_coeIdeal {I J : Ideal R₁} {x y : R₁} (hy : y ∈ R₁⁰) : spanSingleton R₁⁰ (IsLocalization.mk' K x ⟨y, hy⟩) * I = (J : FractionalIdeal R₁⁰ K) ↔ Ideal.span {x} * I = Ideal.span {y} * J := by have : spanSingleton R₁⁰ (IsLocalization.mk' _ (1 : R₁) ⟨y, hy⟩) * spanSingleton R₁⁰ (algebraMap R₁ K y) = 1 := by rw [spanSingleton_mul_spanSingleton, mul_comm, ← IsLocalization.mk'_eq_mul_mk'_one, IsLocalization.mk'_self, spanSingleton_one] let y' : (FractionalIdeal R₁⁰ K)ˣ := Units.mkOfMulEqOne _ _ this have coe_y' : ↑y' = spanSingleton R₁⁰ (IsLocalization.mk' K (1 : R₁) ⟨y, hy⟩) := rfl refine Iff.trans ?_ (y'.mul_right_inj.trans coeIdeal_inj) rw [coe_y', coeIdeal_mul, coeIdeal_span_singleton, coeIdeal_mul, coeIdeal_span_singleton, ← mul_assoc, spanSingleton_mul_spanSingleton, ← mul_assoc, spanSingleton_mul_spanSingleton, mul_comm (mk' _ _ _), ← IsLocalization.mk'_eq_mul_mk'_one, mul_comm (mk' _ _ _), ← IsLocalization.mk'_eq_mul_mk'_one, IsLocalization.mk'_self, spanSingleton_one, one_mul] theorem spanSingleton_mul_coeIdeal_eq_coeIdeal {I J : Ideal R₁} {z : K} : spanSingleton R₁⁰ z * (I : FractionalIdeal R₁⁰ K) = J ↔ Ideal.span {((IsLocalization.sec R₁⁰ z).1 : R₁)} * I = Ideal.span {((IsLocalization.sec R₁⁰ z).2 : R₁)} * J := by rw [← mk'_mul_coeIdeal_eq_coeIdeal K (IsLocalization.sec R₁⁰ z).2.prop, IsLocalization.mk'_sec K z] variable [IsDomain R₁] theorem one_div_spanSingleton (x : K) : 1 / spanSingleton R₁⁰ x = spanSingleton R₁⁰ x⁻¹ := by classical exact if h : x = 0 then by simp [h] else (eq_one_div_of_mul_eq_one_right _ _ (by simp [h])).symm @[simp] theorem div_spanSingleton (J : FractionalIdeal R₁⁰ K) (d : K) : J / spanSingleton R₁⁰ d = spanSingleton R₁⁰ d⁻¹ * J := by rw [← one_div_spanSingleton] by_cases hd : d = 0 · simp only [hd, spanSingleton_zero, div_zero, zero_mul] have h_spand : spanSingleton R₁⁰ d ≠ 0 := mt spanSingleton_eq_zero_iff.mp hd apply le_antisymm · intro x hx dsimp only [val_eq_coe] at hx ⊢ -- Porting note: get rid of the partially applied `coe`s rw [coe_div h_spand, Submodule.mem_div_iff_forall_mul_mem] at hx specialize hx d (mem_spanSingleton_self R₁⁰ d) have h_xd : x = d⁻¹ * (x * d) := by field_simp rw [coe_mul, one_div_spanSingleton, h_xd] exact Submodule.mul_mem_mul (mem_spanSingleton_self R₁⁰ _) hx
· rw [le_div_iff_mul_le h_spand, mul_assoc, mul_left_comm, one_div_spanSingleton, spanSingleton_mul_spanSingleton, inv_mul_cancel₀ hd, spanSingleton_one, mul_one] theorem exists_eq_spanSingleton_mul (I : FractionalIdeal R₁⁰ K) : ∃ (a : R₁) (aI : Ideal R₁), a ≠ 0 ∧ I = spanSingleton R₁⁰ (algebraMap R₁ K a)⁻¹ * aI := by obtain ⟨a_inv, nonzero, ha⟩ := I.isFractional have nonzero := mem_nonZeroDivisors_iff_ne_zero.mp nonzero have map_a_nonzero : algebraMap R₁ K a_inv ≠ 0 := mt IsFractionRing.to_map_eq_zero_iff.mp nonzero refine ⟨a_inv, Submodule.comap (Algebra.linearMap R₁ K) ↑(spanSingleton R₁⁰ (algebraMap R₁ K a_inv) * I), nonzero, ext fun x => Iff.trans ⟨?_, ?_⟩ mem_singleton_mul.symm⟩ · intro hx obtain ⟨x', hx'⟩ := ha x hx rw [Algebra.smul_def] at hx' refine ⟨algebraMap R₁ K x', (mem_coeIdeal _).mpr ⟨x', mem_singleton_mul.mpr ?_, rfl⟩, ?_⟩ · exact ⟨x, hx, hx'⟩ · rw [hx', ← mul_assoc, inv_mul_cancel₀ map_a_nonzero, one_mul]
Mathlib/RingTheory/FractionalIdeal/Operations.lean
737
755
/- Copyright (c) 2021 Aaron Anderson, Jesse Michael Han, Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson, Jesse Michael Han, Floris van Doorn -/ import Mathlib.Data.Finset.Basic import Mathlib.ModelTheory.Syntax import Mathlib.Data.List.ProdSigma /-! # Basics on First-Order Semantics This file defines the interpretations of first-order terms, formulas, sentences, and theories in a style inspired by the [Flypitch project](https://flypitch.github.io/). ## Main Definitions - `FirstOrder.Language.Term.realize` is defined so that `t.realize v` is the term `t` evaluated at variables `v`. - `FirstOrder.Language.BoundedFormula.Realize` is defined so that `φ.Realize v xs` is the bounded formula `φ` evaluated at tuples of variables `v` and `xs`. - `FirstOrder.Language.Formula.Realize` is defined so that `φ.Realize v` is the formula `φ` evaluated at variables `v`. - `FirstOrder.Language.Sentence.Realize` is defined so that `φ.Realize M` is the sentence `φ` evaluated in the structure `M`. Also denoted `M ⊨ φ`. - `FirstOrder.Language.Theory.Model` is defined so that `T.Model M` is true if and only if every sentence of `T` is realized in `M`. Also denoted `T ⊨ φ`. ## Main Results - Several results in this file show that syntactic constructions such as `relabel`, `castLE`, `liftAt`, `subst`, and the actions of language maps commute with realization of terms, formulas, sentences, and theories. ## Implementation Notes - Formulas use a modified version of de Bruijn variables. Specifically, a `L.BoundedFormula α n` is a formula with some variables indexed by a type `α`, which cannot be quantified over, and some indexed by `Fin n`, which can. For any `φ : L.BoundedFormula α (n + 1)`, we define the formula `∀' φ : L.BoundedFormula α n` by universally quantifying over the variable indexed by `n : Fin (n + 1)`. ## References For the Flypitch project: - [J. Han, F. van Doorn, *A formal proof of the independence of the continuum hypothesis*] [flypitch_cpp] - [J. Han, F. van Doorn, *A formalization of forcing and the unprovability of the continuum hypothesis*][flypitch_itp] -/ universe u v w u' v' namespace FirstOrder namespace Language variable {L : Language.{u, v}} {L' : Language} variable {M : Type w} {N P : Type*} [L.Structure M] [L.Structure N] [L.Structure P] variable {α : Type u'} {β : Type v'} {γ : Type*} open FirstOrder Cardinal open Structure Cardinal Fin namespace Term /-- A term `t` with variables indexed by `α` can be evaluated by giving a value to each variable. -/ def realize (v : α → M) : ∀ _t : L.Term α, M | var k => v k | func f ts => funMap f fun i => (ts i).realize v @[simp] theorem realize_var (v : α → M) (k) : realize v (var k : L.Term α) = v k := rfl @[simp] theorem realize_func (v : α → M) {n} (f : L.Functions n) (ts) : realize v (func f ts : L.Term α) = funMap f fun i => (ts i).realize v := rfl @[simp] theorem realize_relabel {t : L.Term α} {g : α → β} {v : β → M} : (t.relabel g).realize v = t.realize (v ∘ g) := by induction t with | var => rfl | func f ts ih => simp [ih] @[simp] theorem realize_liftAt {n n' m : ℕ} {t : L.Term (α ⊕ (Fin n))} {v : α ⊕ (Fin (n + n')) → M} : (t.liftAt n' m).realize v = t.realize (v ∘ Sum.map id fun i : Fin _ => if ↑i < m then Fin.castAdd n' i else Fin.addNat i n') := realize_relabel @[simp] theorem realize_constants {c : L.Constants} {v : α → M} : c.term.realize v = c := funMap_eq_coe_constants @[simp] theorem realize_functions_apply₁ {f : L.Functions 1} {t : L.Term α} {v : α → M} : (f.apply₁ t).realize v = funMap f ![t.realize v] := by rw [Functions.apply₁, Term.realize] refine congr rfl (funext fun i => ?_) simp only [Matrix.cons_val_fin_one] @[simp] theorem realize_functions_apply₂ {f : L.Functions 2} {t₁ t₂ : L.Term α} {v : α → M} : (f.apply₂ t₁ t₂).realize v = funMap f ![t₁.realize v, t₂.realize v] := by rw [Functions.apply₂, Term.realize] refine congr rfl (funext (Fin.cases ?_ ?_)) · simp only [Matrix.cons_val_zero] · simp only [Matrix.cons_val_succ, Matrix.cons_val_fin_one, forall_const] theorem realize_con {A : Set M} {a : A} {v : α → M} : (L.con a).term.realize v = a := rfl @[simp] theorem realize_subst {t : L.Term α} {tf : α → L.Term β} {v : β → M} : (t.subst tf).realize v = t.realize fun a => (tf a).realize v := by induction t with | var => rfl | func _ _ ih => simp [ih] theorem realize_restrictVar [DecidableEq α] {t : L.Term α} {f : t.varFinset → β} {v : β → M} (v' : α → M) (hv' : ∀ a, v (f a) = v' a) : (t.restrictVar f).realize v = t.realize v' := by induction t with | var => simp [restrictVar, hv'] | func _ _ ih => exact congr rfl (funext fun i => ih i ((by simp [Function.comp_apply, hv']))) /-- A special case of `realize_restrictVar`, included because we can add the `simp` attribute to it -/ @[simp] theorem realize_restrictVar' [DecidableEq α] {t : L.Term α} {s : Set α} (h : ↑t.varFinset ⊆ s) {v : α → M} : (t.restrictVar (Set.inclusion h)).realize (v ∘ (↑)) = t.realize v := realize_restrictVar _ (by simp) theorem realize_restrictVarLeft [DecidableEq α] {γ : Type*} {t : L.Term (α ⊕ γ)} {f : t.varFinsetLeft → β} {xs : β ⊕ γ → M} (xs' : α → M) (hxs' : ∀ a, xs (Sum.inl (f a)) = xs' a) : (t.restrictVarLeft f).realize xs = t.realize (Sum.elim xs' (xs ∘ Sum.inr)) := by induction t with | var a => cases a <;> simp [restrictVarLeft, hxs'] | func _ _ ih => exact congr rfl (funext fun i => ih i (by simp [hxs'])) /-- A special case of `realize_restrictVarLeft`, included because we can add the `simp` attribute to it -/ @[simp] theorem realize_restrictVarLeft' [DecidableEq α] {γ : Type*} {t : L.Term (α ⊕ γ)} {s : Set α} (h : ↑t.varFinsetLeft ⊆ s) {v : α → M} {xs : γ → M} : (t.restrictVarLeft (Set.inclusion h)).realize (Sum.elim (v ∘ (↑)) xs) = t.realize (Sum.elim v xs) := realize_restrictVarLeft _ (by simp) @[simp] theorem realize_constantsToVars [L[[α]].Structure M] [(lhomWithConstants L α).IsExpansionOn M] {t : L[[α]].Term β} {v : β → M} : t.constantsToVars.realize (Sum.elim (fun a => ↑(L.con a)) v) = t.realize v := by induction t with | var => simp | @func n f ts ih => cases n · cases f · simp only [realize, ih, constantsOn, constantsOnFunc, constantsToVars] -- Porting note: below lemma does not work with simp for some reason rw [withConstants_funMap_sumInl] · simp only [realize, constantsToVars, Sum.elim_inl, funMap_eq_coe_constants] rfl · obtain - | f := f · simp only [realize, ih, constantsOn, constantsOnFunc, constantsToVars] -- Porting note: below lemma does not work with simp for some reason rw [withConstants_funMap_sumInl] · exact isEmptyElim f @[simp] theorem realize_varsToConstants [L[[α]].Structure M] [(lhomWithConstants L α).IsExpansionOn M] {t : L.Term (α ⊕ β)} {v : β → M} : t.varsToConstants.realize v = t.realize (Sum.elim (fun a => ↑(L.con a)) v) := by induction t with | var ab => rcases ab with a | b <;> simp [Language.con] | func f ts ih => simp only [realize, constantsOn, constantsOnFunc, ih, varsToConstants] -- Porting note: below lemma does not work with simp for some reason rw [withConstants_funMap_sumInl] theorem realize_constantsVarsEquivLeft [L[[α]].Structure M] [(lhomWithConstants L α).IsExpansionOn M] {n} {t : L[[α]].Term (β ⊕ (Fin n))} {v : β → M} {xs : Fin n → M} : (constantsVarsEquivLeft t).realize (Sum.elim (Sum.elim (fun a => ↑(L.con a)) v) xs) = t.realize (Sum.elim v xs) := by simp only [constantsVarsEquivLeft, realize_relabel, Equiv.coe_trans, Function.comp_apply, constantsVarsEquiv_apply, relabelEquiv_symm_apply] refine _root_.trans ?_ realize_constantsToVars rcongr x rcases x with (a | (b | i)) <;> simp end Term namespace LHom @[simp] theorem realize_onTerm [L'.Structure M] (φ : L →ᴸ L') [φ.IsExpansionOn M] (t : L.Term α) (v : α → M) : (φ.onTerm t).realize v = t.realize v := by induction t with | var => rfl | func f ts ih => simp only [Term.realize, LHom.onTerm, LHom.map_onFunction, ih] end LHom @[simp] theorem HomClass.realize_term {F : Type*} [FunLike F M N] [HomClass L F M N] (g : F) {t : L.Term α} {v : α → M} : t.realize (g ∘ v) = g (t.realize v) := by induction t · rfl · rw [Term.realize, Term.realize, HomClass.map_fun] refine congr rfl ?_ ext x simp [*] variable {n : ℕ} namespace BoundedFormula open Term /-- A bounded formula can be evaluated as true or false by giving values to each free variable. -/ def Realize : ∀ {l} (_f : L.BoundedFormula α l) (_v : α → M) (_xs : Fin l → M), Prop | _, falsum, _v, _xs => False | _, equal t₁ t₂, v, xs => t₁.realize (Sum.elim v xs) = t₂.realize (Sum.elim v xs) | _, rel R ts, v, xs => RelMap R fun i => (ts i).realize (Sum.elim v xs) | _, imp f₁ f₂, v, xs => Realize f₁ v xs → Realize f₂ v xs | _, all f, v, xs => ∀ x : M, Realize f v (snoc xs x) variable {l : ℕ} {φ ψ : L.BoundedFormula α l} {θ : L.BoundedFormula α l.succ} variable {v : α → M} {xs : Fin l → M} @[simp] theorem realize_bot : (⊥ : L.BoundedFormula α l).Realize v xs ↔ False := Iff.rfl @[simp] theorem realize_not : φ.not.Realize v xs ↔ ¬φ.Realize v xs := Iff.rfl @[simp] theorem realize_bdEqual (t₁ t₂ : L.Term (α ⊕ (Fin l))) : (t₁.bdEqual t₂).Realize v xs ↔ t₁.realize (Sum.elim v xs) = t₂.realize (Sum.elim v xs) := Iff.rfl @[simp] theorem realize_top : (⊤ : L.BoundedFormula α l).Realize v xs ↔ True := by simp [Top.top] @[simp] theorem realize_inf : (φ ⊓ ψ).Realize v xs ↔ φ.Realize v xs ∧ ψ.Realize v xs := by simp [Inf.inf, Realize] @[simp] theorem realize_foldr_inf (l : List (L.BoundedFormula α n)) (v : α → M) (xs : Fin n → M) : (l.foldr (· ⊓ ·) ⊤).Realize v xs ↔ ∀ φ ∈ l, BoundedFormula.Realize φ v xs := by induction' l with φ l ih · simp · simp [ih] @[simp] theorem realize_imp : (φ.imp ψ).Realize v xs ↔ φ.Realize v xs → ψ.Realize v xs := by simp only [Realize] @[simp] theorem realize_rel {k : ℕ} {R : L.Relations k} {ts : Fin k → L.Term _} : (R.boundedFormula ts).Realize v xs ↔ RelMap R fun i => (ts i).realize (Sum.elim v xs) := Iff.rfl @[simp] theorem realize_rel₁ {R : L.Relations 1} {t : L.Term _} : (R.boundedFormula₁ t).Realize v xs ↔ RelMap R ![t.realize (Sum.elim v xs)] := by rw [Relations.boundedFormula₁, realize_rel, iff_eq_eq] refine congr rfl (funext fun _ => ?_) simp only [Matrix.cons_val_fin_one] @[simp] theorem realize_rel₂ {R : L.Relations 2} {t₁ t₂ : L.Term _} : (R.boundedFormula₂ t₁ t₂).Realize v xs ↔ RelMap R ![t₁.realize (Sum.elim v xs), t₂.realize (Sum.elim v xs)] := by rw [Relations.boundedFormula₂, realize_rel, iff_eq_eq] refine congr rfl (funext (Fin.cases ?_ ?_)) · simp only [Matrix.cons_val_zero] · simp only [Matrix.cons_val_succ, Matrix.cons_val_fin_one, forall_const] @[simp] theorem realize_sup : (φ ⊔ ψ).Realize v xs ↔ φ.Realize v xs ∨ ψ.Realize v xs := by simp only [realize, max, realize_not, eq_iff_iff] tauto @[simp] theorem realize_foldr_sup (l : List (L.BoundedFormula α n)) (v : α → M) (xs : Fin n → M) : (l.foldr (· ⊔ ·) ⊥).Realize v xs ↔ ∃ φ ∈ l, BoundedFormula.Realize φ v xs := by induction' l with φ l ih · simp · simp_rw [List.foldr_cons, realize_sup, ih, List.mem_cons, or_and_right, exists_or, exists_eq_left] @[simp] theorem realize_all : (all θ).Realize v xs ↔ ∀ a : M, θ.Realize v (Fin.snoc xs a) := Iff.rfl @[simp] theorem realize_ex : θ.ex.Realize v xs ↔ ∃ a : M, θ.Realize v (Fin.snoc xs a) := by rw [BoundedFormula.ex, realize_not, realize_all, not_forall] simp_rw [realize_not, Classical.not_not] @[simp] theorem realize_iff : (φ.iff ψ).Realize v xs ↔ (φ.Realize v xs ↔ ψ.Realize v xs) := by simp only [BoundedFormula.iff, realize_inf, realize_imp, and_imp, ← iff_def] theorem realize_castLE_of_eq {m n : ℕ} (h : m = n) {h' : m ≤ n} {φ : L.BoundedFormula α m} {v : α → M} {xs : Fin n → M} : (φ.castLE h').Realize v xs ↔ φ.Realize v (xs ∘ Fin.cast h) := by subst h simp only [castLE_rfl, cast_refl, OrderIso.coe_refl, Function.comp_id] theorem realize_mapTermRel_id [L'.Structure M] {ft : ∀ n, L.Term (α ⊕ (Fin n)) → L'.Term (β ⊕ (Fin n))} {fr : ∀ n, L.Relations n → L'.Relations n} {n} {φ : L.BoundedFormula α n} {v : α → M} {v' : β → M} {xs : Fin n → M} (h1 : ∀ (n) (t : L.Term (α ⊕ (Fin n))) (xs : Fin n → M), (ft n t).realize (Sum.elim v' xs) = t.realize (Sum.elim v xs)) (h2 : ∀ (n) (R : L.Relations n) (x : Fin n → M), RelMap (fr n R) x = RelMap R x) : (φ.mapTermRel ft fr fun _ => id).Realize v' xs ↔ φ.Realize v xs := by induction φ with | falsum => rfl | equal => simp [mapTermRel, Realize, h1] | rel => simp [mapTermRel, Realize, h1, h2] | imp _ _ ih1 ih2 => simp [mapTermRel, Realize, ih1, ih2] | all _ ih => simp only [mapTermRel, Realize, ih, id] theorem realize_mapTermRel_add_castLe [L'.Structure M] {k : ℕ} {ft : ∀ n, L.Term (α ⊕ (Fin n)) → L'.Term (β ⊕ (Fin (k + n)))} {fr : ∀ n, L.Relations n → L'.Relations n} {n} {φ : L.BoundedFormula α n} (v : ∀ {n}, (Fin (k + n) → M) → α → M) {v' : β → M} (xs : Fin (k + n) → M) (h1 : ∀ (n) (t : L.Term (α ⊕ (Fin n))) (xs' : Fin (k + n) → M), (ft n t).realize (Sum.elim v' xs') = t.realize (Sum.elim (v xs') (xs' ∘ Fin.natAdd _))) (h2 : ∀ (n) (R : L.Relations n) (x : Fin n → M), RelMap (fr n R) x = RelMap R x) (hv : ∀ (n) (xs : Fin (k + n) → M) (x : M), @v (n + 1) (snoc xs x : Fin _ → M) = v xs) : (φ.mapTermRel ft fr fun _ => castLE (add_assoc _ _ _).symm.le).Realize v' xs ↔ φ.Realize (v xs) (xs ∘ Fin.natAdd _) := by induction φ with | falsum => rfl | equal => simp [mapTermRel, Realize, h1] | rel => simp [mapTermRel, Realize, h1, h2] | imp _ _ ih1 ih2 => simp [mapTermRel, Realize, ih1, ih2] | all _ ih => simp [mapTermRel, Realize, ih, hv] @[simp] theorem realize_relabel {m n : ℕ} {φ : L.BoundedFormula α n} {g : α → β ⊕ (Fin m)} {v : β → M} {xs : Fin (m + n) → M} : (φ.relabel g).Realize v xs ↔ φ.Realize (Sum.elim v (xs ∘ Fin.castAdd n) ∘ g) (xs ∘ Fin.natAdd m) := by apply realize_mapTermRel_add_castLe <;> simp theorem realize_liftAt {n n' m : ℕ} {φ : L.BoundedFormula α n} {v : α → M} {xs : Fin (n + n') → M} (hmn : m + n' ≤ n + 1) : (φ.liftAt n' m).Realize v xs ↔ φ.Realize v (xs ∘ fun i => if ↑i < m then Fin.castAdd n' i else Fin.addNat i n') := by rw [liftAt] induction φ with | falsum => simp [mapTermRel, Realize] | equal => simp [mapTermRel, Realize, realize_rel, realize_liftAt, Sum.elim_comp_map] | rel => simp [mapTermRel, Realize, realize_rel, realize_liftAt, Sum.elim_comp_map] | imp _ _ ih1 ih2 => simp only [mapTermRel, Realize, ih1 hmn, ih2 hmn] | @all k _ ih3 => have h : k + 1 + n' = k + n' + 1 := by rw [add_assoc, add_comm 1 n', ← add_assoc] simp only [mapTermRel, Realize, realize_castLE_of_eq h, ih3 (hmn.trans k.succ.le_succ)] refine forall_congr' fun x => iff_eq_eq.mpr (congr rfl (funext (Fin.lastCases ?_ fun i => ?_))) · simp only [Function.comp_apply, val_last, snoc_last] refine (congr rfl (Fin.ext ?_)).trans (snoc_last _ _) split_ifs <;> dsimp; omega · simp only [Function.comp_apply, Fin.snoc_castSucc] refine (congr rfl (Fin.ext ?_)).trans (snoc_castSucc _ _ _) simp only [coe_castSucc, coe_cast] split_ifs <;> simp theorem realize_liftAt_one {n m : ℕ} {φ : L.BoundedFormula α n} {v : α → M} {xs : Fin (n + 1) → M} (hmn : m ≤ n) : (φ.liftAt 1 m).Realize v xs ↔ φ.Realize v (xs ∘ fun i => if ↑i < m then castSucc i else i.succ) := by simp [realize_liftAt (add_le_add_right hmn 1), castSucc] @[simp] theorem realize_liftAt_one_self {n : ℕ} {φ : L.BoundedFormula α n} {v : α → M} {xs : Fin (n + 1) → M} : (φ.liftAt 1 n).Realize v xs ↔ φ.Realize v (xs ∘ castSucc) := by rw [realize_liftAt_one (refl n), iff_eq_eq] refine congr rfl (congr rfl (funext fun i => ?_)) rw [if_pos i.is_lt] @[simp] theorem realize_subst {φ : L.BoundedFormula α n} {tf : α → L.Term β} {v : β → M} {xs : Fin n → M} : (φ.subst tf).Realize v xs ↔ φ.Realize (fun a => (tf a).realize v) xs := realize_mapTermRel_id (fun n t x => by rw [Term.realize_subst] rcongr a cases a · simp only [Sum.elim_inl, Function.comp_apply, Term.realize_relabel, Sum.elim_comp_inl] · rfl) (by simp) theorem realize_restrictFreeVar [DecidableEq α] {n : ℕ} {φ : L.BoundedFormula α n} {f : φ.freeVarFinset → β} {v : β → M} {xs : Fin n → M} (v' : α → M) (hv' : ∀ a, v (f a) = v' a) : (φ.restrictFreeVar f).Realize v xs ↔ φ.Realize v' xs := by induction φ with | falsum => rfl | equal => simp only [Realize, restrictFreeVar, freeVarFinset.eq_2] rw [realize_restrictVarLeft v' (by simp [hv']), realize_restrictVarLeft v' (by simp [hv'])] simp [Function.comp_apply] | rel => simp only [Realize, freeVarFinset.eq_3, Finset.biUnion_val, restrictFreeVar] congr! rw [realize_restrictVarLeft v' (by simp [hv'])] simp [Function.comp_apply] | imp _ _ ih1 ih2 => simp only [Realize, restrictFreeVar, freeVarFinset.eq_4] rw [ih1, ih2] <;> simp [hv'] | all _ ih3 => simp only [restrictFreeVar, Realize] refine forall_congr' (fun _ => ?_) rw [ih3]; simp [hv'] /-- A special case of `realize_restrictFreeVar`, included because we can add the `simp` attribute to it -/ @[simp] theorem realize_restrictFreeVar' [DecidableEq α] {n : ℕ} {φ : L.BoundedFormula α n} {s : Set α} (h : ↑φ.freeVarFinset ⊆ s) {v : α → M} {xs : Fin n → M} : (φ.restrictFreeVar (Set.inclusion h)).Realize (v ∘ (↑)) xs ↔ φ.Realize v xs := realize_restrictFreeVar _ (by simp) theorem realize_constantsVarsEquiv [L[[α]].Structure M] [(lhomWithConstants L α).IsExpansionOn M] {n} {φ : L[[α]].BoundedFormula β n} {v : β → M} {xs : Fin n → M} : (constantsVarsEquiv φ).Realize (Sum.elim (fun a => ↑(L.con a)) v) xs ↔ φ.Realize v xs := by refine realize_mapTermRel_id (fun n t xs => realize_constantsVarsEquivLeft) fun n R xs => ?_ -- This used to be `rw`, but we need `erw` after https://github.com/leanprover/lean4/pull/2644 erw [← (lhomWithConstants L α).map_onRelation (Equiv.sumEmpty (L.Relations n) ((constantsOn α).Relations n) R) xs] rcongr obtain - | R := R · simp · exact isEmptyElim R @[simp] theorem realize_relabelEquiv {g : α ≃ β} {k} {φ : L.BoundedFormula α k} {v : β → M} {xs : Fin k → M} : (relabelEquiv g φ).Realize v xs ↔ φ.Realize (v ∘ g) xs := by simp only [relabelEquiv, mapTermRelEquiv_apply, Equiv.coe_refl] refine realize_mapTermRel_id (fun n t xs => ?_) fun _ _ _ => rfl simp only [relabelEquiv_apply, Term.realize_relabel] refine congr (congr rfl ?_) rfl ext (i | i) <;> rfl variable [Nonempty M] theorem realize_all_liftAt_one_self {n : ℕ} {φ : L.BoundedFormula α n} {v : α → M} {xs : Fin n → M} : (φ.liftAt 1 n).all.Realize v xs ↔ φ.Realize v xs := by inhabit M simp only [realize_all, realize_liftAt_one_self] refine ⟨fun h => ?_, fun h a => ?_⟩ · refine (congr rfl (funext fun i => ?_)).mp (h default) simp · refine (congr rfl (funext fun i => ?_)).mp h simp end BoundedFormula namespace LHom open BoundedFormula @[simp] theorem realize_onBoundedFormula [L'.Structure M] (φ : L →ᴸ L') [φ.IsExpansionOn M] {n : ℕ} (ψ : L.BoundedFormula α n) {v : α → M} {xs : Fin n → M} : (φ.onBoundedFormula ψ).Realize v xs ↔ ψ.Realize v xs := by induction ψ with | falsum => rfl | equal => simp only [onBoundedFormula, realize_bdEqual, realize_onTerm]; rfl | rel => simp only [onBoundedFormula, realize_rel, LHom.map_onRelation, Function.comp_apply, realize_onTerm] rfl | imp _ _ ih1 ih2 => simp only [onBoundedFormula, ih1, ih2, realize_imp] | all _ ih3 => simp only [onBoundedFormula, ih3, realize_all] end LHom namespace Formula /-- A formula can be evaluated as true or false by giving values to each free variable. -/ nonrec def Realize (φ : L.Formula α) (v : α → M) : Prop := φ.Realize v default variable {φ ψ : L.Formula α} {v : α → M} @[simp] theorem realize_not : φ.not.Realize v ↔ ¬φ.Realize v := Iff.rfl @[simp] theorem realize_bot : (⊥ : L.Formula α).Realize v ↔ False := Iff.rfl @[simp] theorem realize_top : (⊤ : L.Formula α).Realize v ↔ True := BoundedFormula.realize_top @[simp] theorem realize_inf : (φ ⊓ ψ).Realize v ↔ φ.Realize v ∧ ψ.Realize v := BoundedFormula.realize_inf @[simp] theorem realize_imp : (φ.imp ψ).Realize v ↔ φ.Realize v → ψ.Realize v := BoundedFormula.realize_imp @[simp] theorem realize_rel {k : ℕ} {R : L.Relations k} {ts : Fin k → L.Term α} : (R.formula ts).Realize v ↔ RelMap R fun i => (ts i).realize v := BoundedFormula.realize_rel.trans (by simp) @[simp] theorem realize_rel₁ {R : L.Relations 1} {t : L.Term _} : (R.formula₁ t).Realize v ↔ RelMap R ![t.realize v] := by rw [Relations.formula₁, realize_rel, iff_eq_eq] refine congr rfl (funext fun _ => ?_) simp only [Matrix.cons_val_fin_one] @[simp] theorem realize_rel₂ {R : L.Relations 2} {t₁ t₂ : L.Term _} : (R.formula₂ t₁ t₂).Realize v ↔ RelMap R ![t₁.realize v, t₂.realize v] := by rw [Relations.formula₂, realize_rel, iff_eq_eq] refine congr rfl (funext (Fin.cases ?_ ?_)) · simp only [Matrix.cons_val_zero] · simp only [Matrix.cons_val_succ, Matrix.cons_val_fin_one, forall_const] @[simp] theorem realize_sup : (φ ⊔ ψ).Realize v ↔ φ.Realize v ∨ ψ.Realize v := BoundedFormula.realize_sup @[simp] theorem realize_iff : (φ.iff ψ).Realize v ↔ (φ.Realize v ↔ ψ.Realize v) := BoundedFormula.realize_iff @[simp] theorem realize_relabel {φ : L.Formula α} {g : α → β} {v : β → M} : (φ.relabel g).Realize v ↔ φ.Realize (v ∘ g) := by rw [Realize, Realize, relabel, BoundedFormula.realize_relabel, iff_eq_eq, Fin.castAdd_zero] exact congr rfl (funext finZeroElim) theorem realize_relabel_sumInr (φ : L.Formula (Fin n)) {v : Empty → M} {x : Fin n → M} : (BoundedFormula.relabel Sum.inr φ).Realize v x ↔ φ.Realize x := by rw [BoundedFormula.realize_relabel, Formula.Realize, Sum.elim_comp_inr, Fin.castAdd_zero, cast_refl, Function.comp_id, Subsingleton.elim (x ∘ (natAdd n : Fin 0 → Fin n)) default] @[deprecated (since := "2025-02-21")] alias realize_relabel_sum_inr := realize_relabel_sumInr @[simp] theorem realize_equal {t₁ t₂ : L.Term α} {x : α → M} : (t₁.equal t₂).Realize x ↔ t₁.realize x = t₂.realize x := by simp [Term.equal, Realize] @[simp] theorem realize_graph {f : L.Functions n} {x : Fin n → M} {y : M} : (Formula.graph f).Realize (Fin.cons y x : _ → M) ↔ funMap f x = y := by simp only [Formula.graph, Term.realize, realize_equal, Fin.cons_zero, Fin.cons_succ] rw [eq_comm] theorem boundedFormula_realize_eq_realize (φ : L.Formula α) (x : α → M) (y : Fin 0 → M) : BoundedFormula.Realize φ x y ↔ φ.Realize x := by rw [Formula.Realize, iff_iff_eq] congr ext i; exact Fin.elim0 i end Formula @[simp] theorem LHom.realize_onFormula [L'.Structure M] (φ : L →ᴸ L') [φ.IsExpansionOn M] (ψ : L.Formula α) {v : α → M} : (φ.onFormula ψ).Realize v ↔ ψ.Realize v := φ.realize_onBoundedFormula ψ @[simp] theorem LHom.setOf_realize_onFormula [L'.Structure M] (φ : L →ᴸ L') [φ.IsExpansionOn M] (ψ : L.Formula α) : (setOf (φ.onFormula ψ).Realize : Set (α → M)) = setOf ψ.Realize := by ext simp variable (M) /-- A sentence can be evaluated as true or false in a structure. -/ nonrec def Sentence.Realize (φ : L.Sentence) : Prop := φ.Realize (default : _ → M) -- input using \|= or \vDash, but not using \models @[inherit_doc Sentence.Realize] infixl:51 " ⊨ " => Sentence.Realize @[simp] theorem Sentence.realize_not {φ : L.Sentence} : M ⊨ φ.not ↔ ¬M ⊨ φ := Iff.rfl namespace Formula @[simp] theorem realize_equivSentence_symm_con [L[[α]].Structure M] [(L.lhomWithConstants α).IsExpansionOn M] (φ : L[[α]].Sentence) : ((equivSentence.symm φ).Realize fun a => (L.con a : M)) ↔ φ.Realize M := by simp only [equivSentence, _root_.Equiv.symm_symm, Equiv.coe_trans, Realize, BoundedFormula.realize_relabelEquiv, Function.comp] refine _root_.trans ?_ BoundedFormula.realize_constantsVarsEquiv rw [iff_iff_eq] congr with (_ | a) · simp · cases a @[simp] theorem realize_equivSentence [L[[α]].Structure M] [(L.lhomWithConstants α).IsExpansionOn M] (φ : L.Formula α) : (equivSentence φ).Realize M ↔ φ.Realize fun a => (L.con a : M) := by rw [← realize_equivSentence_symm_con M (equivSentence φ), _root_.Equiv.symm_apply_apply] theorem realize_equivSentence_symm (φ : L[[α]].Sentence) (v : α → M) : (equivSentence.symm φ).Realize v ↔ @Sentence.Realize _ M (@Language.withConstantsStructure L M _ α (constantsOn.structure v)) φ := letI := constantsOn.structure v realize_equivSentence_symm_con M φ end Formula @[simp] theorem LHom.realize_onSentence [L'.Structure M] (φ : L →ᴸ L') [φ.IsExpansionOn M] (ψ : L.Sentence) : M ⊨ φ.onSentence ψ ↔ M ⊨ ψ := φ.realize_onFormula ψ variable (L) /-- The complete theory of a structure `M` is the set of all sentences `M` satisfies. -/ def completeTheory : L.Theory := { φ | M ⊨ φ } variable (N) /-- Two structures are elementarily equivalent when they satisfy the same sentences. -/ def ElementarilyEquivalent : Prop := L.completeTheory M = L.completeTheory N @[inherit_doc FirstOrder.Language.ElementarilyEquivalent] scoped[FirstOrder] notation:25 A " ≅[" L "] " B:50 => FirstOrder.Language.ElementarilyEquivalent L A B variable {L} {M} {N} @[simp] theorem mem_completeTheory {φ : Sentence L} : φ ∈ L.completeTheory M ↔ M ⊨ φ := Iff.rfl theorem elementarilyEquivalent_iff : M ≅[L] N ↔ ∀ φ : L.Sentence, M ⊨ φ ↔ N ⊨ φ := by simp only [ElementarilyEquivalent, Set.ext_iff, completeTheory, Set.mem_setOf_eq] variable (M) /-- A model of a theory is a structure in which every sentence is realized as true. -/ class Theory.Model (T : L.Theory) : Prop where realize_of_mem : ∀ φ ∈ T, M ⊨ φ -- input using \|= or \vDash, but not using \models @[inherit_doc Theory.Model] infixl:51 " ⊨ " => Theory.Model variable {M} (T : L.Theory) @[simp default - 10] theorem Theory.model_iff : M ⊨ T ↔ ∀ φ ∈ T, M ⊨ φ := ⟨fun h => h.realize_of_mem, fun h => ⟨h⟩⟩ theorem Theory.realize_sentence_of_mem [M ⊨ T] {φ : L.Sentence} (h : φ ∈ T) : M ⊨ φ := Theory.Model.realize_of_mem φ h @[simp] theorem LHom.onTheory_model [L'.Structure M] (φ : L →ᴸ L') [φ.IsExpansionOn M] (T : L.Theory) : M ⊨ φ.onTheory T ↔ M ⊨ T := by simp [Theory.model_iff, LHom.onTheory] variable {T} instance model_empty : M ⊨ (∅ : L.Theory) := ⟨fun φ hφ => (Set.not_mem_empty φ hφ).elim⟩ namespace Theory theorem Model.mono {T' : L.Theory} (_h : M ⊨ T') (hs : T ⊆ T') : M ⊨ T := ⟨fun _φ hφ => T'.realize_sentence_of_mem (hs hφ)⟩ theorem Model.union {T' : L.Theory} (h : M ⊨ T) (h' : M ⊨ T') : M ⊨ T ∪ T' := by simp only [model_iff, Set.mem_union] at * exact fun φ hφ => hφ.elim (h _) (h' _) @[simp] theorem model_union_iff {T' : L.Theory} : M ⊨ T ∪ T' ↔ M ⊨ T ∧ M ⊨ T' := ⟨fun h => ⟨h.mono Set.subset_union_left, h.mono Set.subset_union_right⟩, fun h => h.1.union h.2⟩ @[simp] theorem model_singleton_iff {φ : L.Sentence} : M ⊨ ({φ} : L.Theory) ↔ M ⊨ φ := by simp theorem model_insert_iff {φ : L.Sentence} : M ⊨ insert φ T ↔ M ⊨ φ ∧ M ⊨ T := by rw [Set.insert_eq, model_union_iff, model_singleton_iff] theorem model_iff_subset_completeTheory : M ⊨ T ↔ T ⊆ L.completeTheory M := T.model_iff theorem completeTheory.subset [MT : M ⊨ T] : T ⊆ L.completeTheory M := model_iff_subset_completeTheory.1 MT end Theory instance model_completeTheory : M ⊨ L.completeTheory M := Theory.model_iff_subset_completeTheory.2 (subset_refl _) variable (M N) theorem realize_iff_of_model_completeTheory [N ⊨ L.completeTheory M] (φ : L.Sentence) : N ⊨ φ ↔ M ⊨ φ := by refine ⟨fun h => ?_, (L.completeTheory M).realize_sentence_of_mem⟩ contrapose! h rw [← Sentence.realize_not] at * exact (L.completeTheory M).realize_sentence_of_mem (mem_completeTheory.2 h) variable {M N} namespace BoundedFormula @[simp] theorem realize_alls {φ : L.BoundedFormula α n} {v : α → M} : φ.alls.Realize v ↔ ∀ xs : Fin n → M, φ.Realize v xs := by induction' n with n ih · exact Unique.forall_iff.symm · simp only [alls, ih, Realize] exact ⟨fun h xs => Fin.snoc_init_self xs ▸ h _ _, fun h xs x => h (Fin.snoc xs x)⟩ @[simp] theorem realize_exs {φ : L.BoundedFormula α n} {v : α → M} : φ.exs.Realize v ↔ ∃ xs : Fin n → M, φ.Realize v xs := by induction' n with n ih · exact Unique.exists_iff.symm · simp only [BoundedFormula.exs, ih, realize_ex] constructor · rintro ⟨xs, x, h⟩ exact ⟨_, h⟩ · rintro ⟨xs, h⟩ rw [← Fin.snoc_init_self xs] at h exact ⟨_, _, h⟩ @[simp] theorem _root_.FirstOrder.Language.Formula.realize_iAlls [Finite β] {φ : L.Formula (α ⊕ β)} {v : α → M} : (φ.iAlls β).Realize v ↔ ∀ (i : β → M), φ.Realize (fun a => Sum.elim v i a) := by let e := Classical.choice (Classical.choose_spec (Finite.exists_equiv_fin β)) rw [Formula.iAlls] simp only [Nat.add_zero, realize_alls, realize_relabel, Function.comp_def, castAdd_zero, finCongr_refl, OrderIso.refl_apply, Sum.elim_map, id_eq] refine Equiv.forall_congr ?_ ?_ · exact ⟨fun v => v ∘ e, fun v => v ∘ e.symm, fun _ => by simp [Function.comp_def], fun _ => by simp [Function.comp_def]⟩ · intro x rw [Formula.Realize, iff_iff_eq] congr funext i exact i.elim0 @[simp] theorem realize_iAlls [Finite β] {φ : L.Formula (α ⊕ β)} {v : α → M} {v' : Fin 0 → M} : BoundedFormula.Realize (φ.iAlls β) v v' ↔ ∀ (i : β → M), φ.Realize (fun a => Sum.elim v i a) := by rw [← Formula.realize_iAlls, iff_iff_eq]; congr; simp [eq_iff_true_of_subsingleton] @[simp] theorem _root_.FirstOrder.Language.Formula.realize_iExs [Finite γ] {φ : L.Formula (α ⊕ γ)} {v : α → M} : (φ.iExs γ).Realize v ↔ ∃ (i : γ → M), φ.Realize (Sum.elim v i) := by let e := Classical.choice (Classical.choose_spec (Finite.exists_equiv_fin γ)) rw [Formula.iExs] simp only [Nat.add_zero, realize_exs, realize_relabel, Function.comp_def, castAdd_zero, finCongr_refl, OrderIso.refl_apply, Sum.elim_map, id_eq] refine Equiv.exists_congr ?_ ?_ · exact ⟨fun v => v ∘ e, fun v => v ∘ e.symm, fun _ => by simp [Function.comp_def], fun _ => by simp [Function.comp_def]⟩ · intro x rw [Formula.Realize, iff_iff_eq] congr funext i exact i.elim0 @[simp] theorem realize_iExs [Finite γ] {φ : L.Formula (α ⊕ γ)} {v : α → M} {v' : Fin 0 → M} : BoundedFormula.Realize (φ.iExs γ) v v' ↔ ∃ (i : γ → M), φ.Realize (Sum.elim v i) := by rw [← Formula.realize_iExs, iff_iff_eq]; congr; simp [eq_iff_true_of_subsingleton] @[simp] theorem realize_toFormula (φ : L.BoundedFormula α n) (v : α ⊕ (Fin n) → M) : φ.toFormula.Realize v ↔ φ.Realize (v ∘ Sum.inl) (v ∘ Sum.inr) := by induction φ with | falsum => rfl | equal => simp [BoundedFormula.Realize] | rel => simp [BoundedFormula.Realize] | imp _ _ ih1 ih2 => rw [toFormula, Formula.Realize, realize_imp, ← Formula.Realize, ih1, ← Formula.Realize, ih2, realize_imp] | all _ ih3 => rw [toFormula, Formula.Realize, realize_all, realize_all] refine forall_congr' fun a => ?_ have h := ih3 (Sum.elim (v ∘ Sum.inl) (snoc (v ∘ Sum.inr) a)) simp only [Sum.elim_comp_inl, Sum.elim_comp_inr] at h rw [← h, realize_relabel, Formula.Realize, iff_iff_eq] simp only [Function.comp_def] congr with x · rcases x with _ | x · simp · refine Fin.lastCases ?_ ?_ x · rw [Sum.elim_inr, Sum.elim_inr, finSumFinEquiv_symm_last, Sum.map_inr, Sum.elim_inr] simp [Fin.snoc] · simp only [castSucc, Function.comp_apply, Sum.elim_inr, finSumFinEquiv_symm_apply_castAdd, Sum.map_inl, Sum.elim_inl] rw [← castSucc] simp · exact Fin.elim0 x @[simp] theorem realize_iSup [Finite β] {f : β → L.BoundedFormula α n} {v : α → M} {v' : Fin n → M} : (iSup f).Realize v v' ↔ ∃ b, (f b).Realize v v' := by simp only [iSup, realize_foldr_sup, List.mem_map, Finset.mem_toList, Finset.mem_univ, true_and, exists_exists_eq_and] @[simp] theorem realize_iInf [Finite β] {f : β → L.BoundedFormula α n} {v : α → M} {v' : Fin n → M} : (iInf f).Realize v v' ↔ ∀ b, (f b).Realize v v' := by simp only [iInf, realize_foldr_inf, List.mem_map, Finset.mem_toList, Finset.mem_univ, true_and, forall_exists_index, forall_apply_eq_imp_iff] @[simp] theorem _root_.FirstOrder.Language.Formula.realize_iExsUnique [Finite γ] {φ : L.Formula (α ⊕ γ)} {v : α → M} : (φ.iExsUnique γ).Realize v ↔ ∃! (i : γ → M), φ.Realize (Sum.elim v i) := by rw [Formula.iExsUnique, ExistsUnique] simp only [Formula.realize_iExs, Formula.realize_inf, Formula.realize_iAlls, Formula.realize_imp, Formula.realize_relabel] simp only [Formula.Realize, Function.comp_def, Term.equal, Term.relabel, realize_iInf, realize_bdEqual, Term.realize_var, Sum.elim_inl, Sum.elim_inr, funext_iff] refine exists_congr (fun i => and_congr_right' (forall_congr' (fun y => ?_))) rw [iff_iff_eq]; congr with x cases x <;> simp @[simp] theorem realize_iExsUnique [Finite γ] {φ : L.Formula (α ⊕ γ)} {v : α → M} {v' : Fin 0 → M} : BoundedFormula.Realize (φ.iExsUnique γ) v v' ↔ ∃! (i : γ → M), φ.Realize (Sum.elim v i) := by rw [← Formula.realize_iExsUnique, iff_iff_eq]; congr; simp [eq_iff_true_of_subsingleton] end BoundedFormula namespace StrongHomClass variable {F : Type*} [EquivLike F M N] [StrongHomClass L F M N] (g : F) @[simp] theorem realize_boundedFormula (φ : L.BoundedFormula α n) {v : α → M} {xs : Fin n → M} : φ.Realize (g ∘ v) (g ∘ xs) ↔ φ.Realize v xs := by induction φ with | falsum => rfl | equal => simp only [BoundedFormula.Realize, ← Sum.comp_elim, HomClass.realize_term, EmbeddingLike.apply_eq_iff_eq g] | rel => simp only [BoundedFormula.Realize, ← Sum.comp_elim, HomClass.realize_term] exact StrongHomClass.map_rel g _ _ | imp _ _ ih1 ih2 => rw [BoundedFormula.Realize, ih1, ih2, BoundedFormula.Realize] | all _ ih3 => rw [BoundedFormula.Realize, BoundedFormula.Realize] constructor · intro h a have h' := h (g a) rw [← Fin.comp_snoc, ih3] at h' exact h' · intro h a have h' := h (EquivLike.inv g a) rw [← ih3, Fin.comp_snoc, EquivLike.apply_inv_apply g] at h' exact h' @[simp] theorem realize_formula (φ : L.Formula α) {v : α → M} : φ.Realize (g ∘ v) ↔ φ.Realize v := by rw [Formula.Realize, Formula.Realize, ← realize_boundedFormula g φ, iff_eq_eq, Unique.eq_default (g ∘ default)] include g theorem realize_sentence (φ : L.Sentence) : M ⊨ φ ↔ N ⊨ φ := by rw [Sentence.Realize, Sentence.Realize, ← realize_formula g, Unique.eq_default (g ∘ default)] theorem theory_model [M ⊨ T] : N ⊨ T := ⟨fun φ hφ => (realize_sentence g φ).1 (Theory.realize_sentence_of_mem T hφ)⟩ theorem elementarilyEquivalent : M ≅[L] N := elementarilyEquivalent_iff.2 (realize_sentence g) end StrongHomClass namespace Relations open BoundedFormula variable {r : L.Relations 2} @[simp] theorem realize_reflexive : M ⊨ r.reflexive ↔ Reflexive fun x y : M => RelMap r ![x, y] := forall_congr' fun _ => realize_rel₂ @[simp] theorem realize_irreflexive : M ⊨ r.irreflexive ↔ Irreflexive fun x y : M => RelMap r ![x, y] := forall_congr' fun _ => not_congr realize_rel₂ @[simp] theorem realize_symmetric : M ⊨ r.symmetric ↔ Symmetric fun x y : M => RelMap r ![x, y] := forall_congr' fun _ => forall_congr' fun _ => imp_congr realize_rel₂ realize_rel₂ @[simp] theorem realize_antisymmetric : M ⊨ r.antisymmetric ↔ AntiSymmetric fun x y : M => RelMap r ![x, y] := forall_congr' fun _ => forall_congr' fun _ => imp_congr realize_rel₂ (imp_congr realize_rel₂ Iff.rfl) @[simp] theorem realize_transitive : M ⊨ r.transitive ↔ Transitive fun x y : M => RelMap r ![x, y] := forall_congr' fun _ => forall_congr' fun _ => forall_congr' fun _ => imp_congr realize_rel₂ (imp_congr realize_rel₂ realize_rel₂) @[simp] theorem realize_total : M ⊨ r.total ↔ Total fun x y : M => RelMap r ![x, y] := forall_congr' fun _ => forall_congr' fun _ => realize_sup.trans (or_congr realize_rel₂ realize_rel₂) end Relations section Cardinality variable (L) @[simp] theorem Sentence.realize_cardGe (n) : M ⊨ Sentence.cardGe L n ↔ ↑n ≤ #M := by rw [← lift_mk_fin, ← lift_le.{0}, lift_lift, lift_mk_le, Sentence.cardGe, Sentence.Realize, BoundedFormula.realize_exs] simp_rw [BoundedFormula.realize_foldr_inf] simp only [Function.comp_apply, List.mem_map, Prod.exists, Ne, List.mem_product, List.mem_finRange, forall_exists_index, and_imp, List.mem_filter, true_and] refine ⟨?_, fun xs => ⟨xs.some, ?_⟩⟩ · rintro ⟨xs, h⟩ refine ⟨⟨xs, fun i j ij => ?_⟩⟩ contrapose! ij have hij := h _ i j (by simpa using ij) rfl simp only [BoundedFormula.realize_not, Term.realize, BoundedFormula.realize_bdEqual, Sum.elim_inr] at hij exact hij · rintro _ i j ij rfl simpa using ij @[simp] theorem model_infiniteTheory_iff : M ⊨ L.infiniteTheory ↔ Infinite M := by simp [infiniteTheory, infinite_iff, aleph0_le] instance model_infiniteTheory [h : Infinite M] : M ⊨ L.infiniteTheory := L.model_infiniteTheory_iff.2 h @[simp] theorem model_nonemptyTheory_iff : M ⊨ L.nonemptyTheory ↔ Nonempty M := by simp only [nonemptyTheory, Theory.model_iff, Set.mem_singleton_iff, forall_eq, Sentence.realize_cardGe, Nat.cast_one, one_le_iff_ne_zero, mk_ne_zero_iff] instance model_nonempty [h : Nonempty M] : M ⊨ L.nonemptyTheory := L.model_nonemptyTheory_iff.2 h theorem model_distinctConstantsTheory {M : Type w} [L[[α]].Structure M] (s : Set α) : M ⊨ L.distinctConstantsTheory s ↔ Set.InjOn (fun i : α => (L.con i : M)) s := by simp only [distinctConstantsTheory, Theory.model_iff, Set.mem_image, Set.mem_inter, Set.mem_prod, Set.mem_compl, Prod.exists, forall_exists_index, and_imp] refine ⟨fun h a as b bs ab => ?_, ?_⟩ · contrapose! ab have h' := h _ a b ⟨⟨as, bs⟩, ab⟩ rfl simp only [Sentence.Realize, Formula.realize_not, Formula.realize_equal, Term.realize_constants] at h' exact h' · rintro h φ a b ⟨⟨as, bs⟩, ab⟩ rfl simp only [Sentence.Realize, Formula.realize_not, Formula.realize_equal, Term.realize_constants] exact fun contra => ab (h as bs contra) theorem card_le_of_model_distinctConstantsTheory (s : Set α) (M : Type w) [L[[α]].Structure M] [h : M ⊨ L.distinctConstantsTheory s] : Cardinal.lift.{w} #s ≤ Cardinal.lift.{u'} #M := lift_mk_le'.2 ⟨⟨_, Set.injOn_iff_injective.1 ((L.model_distinctConstantsTheory s).1 h)⟩⟩ end Cardinality namespace ElementarilyEquivalent @[symm] nonrec theorem symm (h : M ≅[L] N) : N ≅[L] M := h.symm @[trans] nonrec theorem trans (MN : M ≅[L] N) (NP : N ≅[L] P) : M ≅[L] P := MN.trans NP theorem completeTheory_eq (h : M ≅[L] N) : L.completeTheory M = L.completeTheory N := h theorem realize_sentence (h : M ≅[L] N) (φ : L.Sentence) : M ⊨ φ ↔ N ⊨ φ := (elementarilyEquivalent_iff.1 h) φ theorem theory_model_iff (h : M ≅[L] N) : M ⊨ T ↔ N ⊨ T := by rw [Theory.model_iff_subset_completeTheory, Theory.model_iff_subset_completeTheory, h.completeTheory_eq] theorem theory_model [MT : M ⊨ T] (h : M ≅[L] N) : N ⊨ T := h.theory_model_iff.1 MT theorem nonempty_iff (h : M ≅[L] N) : Nonempty M ↔ Nonempty N := (model_nonemptyTheory_iff L).symm.trans (h.theory_model_iff.trans (model_nonemptyTheory_iff L)) theorem nonempty [Mn : Nonempty M] (h : M ≅[L] N) : Nonempty N := h.nonempty_iff.1 Mn theorem infinite_iff (h : M ≅[L] N) : Infinite M ↔ Infinite N := (model_infiniteTheory_iff L).symm.trans (h.theory_model_iff.trans (model_infiniteTheory_iff L)) theorem infinite [Mi : Infinite M] (h : M ≅[L] N) : Infinite N := h.infinite_iff.1 Mi end ElementarilyEquivalent end Language end FirstOrder
Mathlib/ModelTheory/Semantics.lean
1,128
1,130
/- Copyright (c) 2020 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import Mathlib.Algebra.BigOperators.Fin import Mathlib.Logic.Encodable.Pi import Mathlib.MeasureTheory.Group.Measure import Mathlib.MeasureTheory.MeasurableSpace.Pi import Mathlib.MeasureTheory.Measure.Prod import Mathlib.Topology.Constructions /-! # Indexed product measures In this file we define and prove properties about finite products of measures (and at some point, countable products of measures). ## Main definition * `MeasureTheory.Measure.pi`: The product of finitely many σ-finite measures. Given `μ : (i : ι) → Measure (α i)` for `[Fintype ι]` it has type `Measure ((i : ι) → α i)`. To apply Fubini's theorem or Tonelli's theorem along some subset, we recommend using the marginal construction `MeasureTheory.lmarginal` and (todo) `MeasureTheory.marginal`. This allows you to apply the theorems without any bookkeeping with measurable equivalences. ## Implementation Notes We define `MeasureTheory.OuterMeasure.pi`, the product of finitely many outer measures, as the maximal outer measure `n` with the property that `n (pi univ s) ≤ ∏ i, m i (s i)`, where `pi univ s` is the product of the sets `{s i | i : ι}`. We then show that this induces a product of measures, called `MeasureTheory.Measure.pi`. For a collection of σ-finite measures `μ` and a collection of measurable sets `s` we show that `Measure.pi μ (pi univ s) = ∏ i, m i (s i)`. To do this, we follow the following steps: * We know that there is some ordering on `ι`, given by an element of `[Countable ι]`. * Using this, we have an equivalence `MeasurableEquiv.piMeasurableEquivTProd` between `∀ ι, α i` and an iterated product of `α i`, called `List.tprod α l` for some list `l`. * On this iterated product we can easily define a product measure `MeasureTheory.Measure.tprod` by iterating `MeasureTheory.Measure.prod` * Using the previous two steps we construct `MeasureTheory.Measure.pi'` on `(i : ι) → α i` for countable `ι`. * We know that `MeasureTheory.Measure.pi'` sends products of sets to products of measures, and since `MeasureTheory.Measure.pi` is the maximal such measure (or at least, it comes from an outer measure which is the maximal such outer measure), we get the same rule for `MeasureTheory.Measure.pi`. ## Tags finitary product measure -/ noncomputable section open Function Set MeasureTheory.OuterMeasure Filter MeasurableSpace Encodable open scoped Topology ENNReal universe u v variable {ι ι' : Type*} {α : ι → Type*} namespace MeasureTheory variable [Fintype ι] {m : ∀ i, OuterMeasure (α i)} /-- An upper bound for the measure in a finite product space. It is defined to by taking the image of the set under all projections, and taking the product of the measures of these images. For measurable boxes it is equal to the correct measure. -/ @[simp] def piPremeasure (m : ∀ i, OuterMeasure (α i)) (s : Set (∀ i, α i)) : ℝ≥0∞ := ∏ i, m i (eval i '' s) theorem piPremeasure_pi {s : ∀ i, Set (α i)} (hs : (pi univ s).Nonempty) : piPremeasure m (pi univ s) = ∏ i, m i (s i) := by simp [hs, piPremeasure] theorem piPremeasure_pi' {s : ∀ i, Set (α i)} : piPremeasure m (pi univ s) = ∏ i, m i (s i) := by cases isEmpty_or_nonempty ι · simp [piPremeasure] rcases (pi univ s).eq_empty_or_nonempty with h | h · rcases univ_pi_eq_empty_iff.mp h with ⟨i, hi⟩ have : ∃ i, m i (s i) = 0 := ⟨i, by simp [hi]⟩ simpa [h, Finset.card_univ, zero_pow Fintype.card_ne_zero, @eq_comm _ (0 : ℝ≥0∞), Finset.prod_eq_zero_iff, piPremeasure] · simp [h, piPremeasure] theorem piPremeasure_pi_mono {s t : Set (∀ i, α i)} (h : s ⊆ t) : piPremeasure m s ≤ piPremeasure m t := Finset.prod_le_prod' fun _ _ => measure_mono (image_subset _ h) theorem piPremeasure_pi_eval {s : Set (∀ i, α i)} : piPremeasure m (pi univ fun i => eval i '' s) = piPremeasure m s := by simp only [eval, piPremeasure_pi']; rfl namespace OuterMeasure /-- `OuterMeasure.pi m` is the finite product of the outer measures `{m i | i : ι}`. It is defined to be the maximal outer measure `n` with the property that `n (pi univ s) ≤ ∏ i, m i (s i)`, where `pi univ s` is the product of the sets `{s i | i : ι}`. -/ protected def pi (m : ∀ i, OuterMeasure (α i)) : OuterMeasure (∀ i, α i) := boundedBy (piPremeasure m) theorem pi_pi_le (m : ∀ i, OuterMeasure (α i)) (s : ∀ i, Set (α i)) : OuterMeasure.pi m (pi univ s) ≤ ∏ i, m i (s i) := by rcases (pi univ s).eq_empty_or_nonempty with h | h · simp [h] exact (boundedBy_le _).trans_eq (piPremeasure_pi h) theorem le_pi {m : ∀ i, OuterMeasure (α i)} {n : OuterMeasure (∀ i, α i)} : n ≤ OuterMeasure.pi m ↔ ∀ s : ∀ i, Set (α i), (pi univ s).Nonempty → n (pi univ s) ≤ ∏ i, m i (s i) := by rw [OuterMeasure.pi, le_boundedBy']; constructor · intro h s hs; refine (h _ hs).trans_eq (piPremeasure_pi hs) · intro h s hs; refine le_trans (n.mono <| subset_pi_eval_image univ s) (h _ ?_) simp [univ_pi_nonempty_iff, hs] end OuterMeasure namespace Measure variable [∀ i, MeasurableSpace (α i)] (μ : ∀ i, Measure (α i)) section Tprod open List variable {δ : Type*} {X : δ → Type*} [∀ i, MeasurableSpace (X i)] -- for some reason the equation compiler doesn't like this definition /-- A product of measures in `tprod α l`. -/ protected def tprod (l : List δ) (μ : ∀ i, Measure (X i)) : Measure (TProd X l) := by induction' l with i l ih · exact dirac PUnit.unit · exact (μ i).prod (α := X i) ih @[simp] theorem tprod_nil (μ : ∀ i, Measure (X i)) : Measure.tprod [] μ = dirac PUnit.unit := rfl @[simp] theorem tprod_cons (i : δ) (l : List δ) (μ : ∀ i, Measure (X i)) : Measure.tprod (i :: l) μ = (μ i).prod (Measure.tprod l μ) := rfl instance sigmaFinite_tprod (l : List δ) (μ : ∀ i, Measure (X i)) [∀ i, SigmaFinite (μ i)] : SigmaFinite (Measure.tprod l μ) := by induction l with | nil => rw [tprod_nil]; infer_instance | cons i l ih => rw [tprod_cons]; exact @prod.instSigmaFinite _ _ _ _ _ _ _ ih theorem tprod_tprod (l : List δ) (μ : ∀ i, Measure (X i)) [∀ i, SigmaFinite (μ i)] (s : ∀ i, Set (X i)) : Measure.tprod l μ (Set.tprod l s) = (l.map fun i => (μ i) (s i)).prod := by induction l with | nil => simp | cons a l ih => rw [tprod_cons, Set.tprod] dsimp only [foldr_cons, map_cons, prod_cons] rw [prod_prod, ih] end Tprod section Encodable open List MeasurableEquiv variable [Encodable ι] open scoped Classical in /-- The product measure on an encodable finite type, defined by mapping `Measure.tprod` along the equivalence `MeasurableEquiv.piMeasurableEquivTProd`. The definition `MeasureTheory.Measure.pi` should be used instead of this one. -/ def pi' : Measure (∀ i, α i) := Measure.map (TProd.elim' mem_sortedUniv) (Measure.tprod (sortedUniv ι) μ) theorem pi'_pi [∀ i, SigmaFinite (μ i)] (s : ∀ i, Set (α i)) : pi' μ (pi univ s) = ∏ i, μ i (s i) := by classical rw [pi'] rw [← MeasurableEquiv.piMeasurableEquivTProd_symm_apply, MeasurableEquiv.map_apply, MeasurableEquiv.piMeasurableEquivTProd_symm_apply, elim_preimage_pi, tprod_tprod _ μ, ← List.prod_toFinset, sortedUniv_toFinset] <;> exact sortedUniv_nodup ι end Encodable theorem pi_caratheodory : MeasurableSpace.pi ≤ (OuterMeasure.pi fun i => (μ i).toOuterMeasure).caratheodory := by refine iSup_le ?_ intro i s hs rw [MeasurableSpace.comap] at hs rcases hs with ⟨s, hs, rfl⟩ apply boundedBy_caratheodory intro t simp_rw [piPremeasure] refine Finset.prod_add_prod_le' (Finset.mem_univ i) ?_ ?_ ?_ · simp [image_inter_preimage, image_diff_preimage, measure_inter_add_diff _ hs, le_refl] · rintro j - _; gcongr; apply inter_subset_left · rintro j - _; gcongr; apply diff_subset /-- `Measure.pi μ` is the finite product of the measures `{μ i | i : ι}`. It is defined to be measure corresponding to `MeasureTheory.OuterMeasure.pi`. -/ protected irreducible_def pi : Measure (∀ i, α i) := toMeasure (OuterMeasure.pi fun i => (μ i).toOuterMeasure) (pi_caratheodory μ) instance _root_.MeasureTheory.MeasureSpace.pi {α : ι → Type*} [∀ i, MeasureSpace (α i)] : MeasureSpace (∀ i, α i) := ⟨Measure.pi fun _ => volume⟩ theorem pi_pi_aux [∀ i, SigmaFinite (μ i)] (s : ∀ i, Set (α i)) (hs : ∀ i, MeasurableSet (s i)) : Measure.pi μ (pi univ s) = ∏ i, μ i (s i) := by refine le_antisymm ?_ ?_ · rw [Measure.pi, toMeasure_apply _ _ (MeasurableSet.pi countable_univ fun i _ => hs i)] apply OuterMeasure.pi_pi_le · haveI : Encodable ι := Fintype.toEncodable ι simp_rw [← pi'_pi μ s, Measure.pi, toMeasure_apply _ _ (MeasurableSet.pi countable_univ fun i _ => hs i)] suffices (pi' μ).toOuterMeasure ≤ OuterMeasure.pi fun i => (μ i).toOuterMeasure by exact this _ clear hs s rw [OuterMeasure.le_pi] intro s _ exact (pi'_pi μ s).le variable {μ} /-- `Measure.pi μ` has finite spanning sets in rectangles of finite spanning sets. -/ def FiniteSpanningSetsIn.pi {C : ∀ i, Set (Set (α i))} (hμ : ∀ i, (μ i).FiniteSpanningSetsIn (C i)) : (Measure.pi μ).FiniteSpanningSetsIn (pi univ '' pi univ C) := by haveI := fun i => (hμ i).sigmaFinite haveI := Fintype.toEncodable ι refine ⟨fun n => Set.pi univ fun i => (hμ i).set ((@decode (ι → ℕ) _ n).iget i), fun n => ?_, fun n => ?_, ?_⟩ <;> -- TODO (kmill) If this let comes before the refine, while the noncomputability checker -- correctly sees this definition is computable, the Lean VM fails to see the binding is -- computationally irrelevant. The `noncomputable section` doesn't help because all it does -- is insert `noncomputable` for you when necessary. let e : ℕ → ι → ℕ := fun n => (@decode (ι → ℕ) _ n).iget · refine mem_image_of_mem _ fun i _ => (hμ i).set_mem _ · calc Measure.pi μ (Set.pi univ fun i => (hμ i).set (e n i)) ≤ Measure.pi μ (Set.pi univ fun i => toMeasurable (μ i) ((hμ i).set (e n i))) := measure_mono (pi_mono fun i _ => subset_toMeasurable _ _) _ = ∏ i, μ i (toMeasurable (μ i) ((hμ i).set (e n i))) := (pi_pi_aux μ _ fun i => measurableSet_toMeasurable _ _) _ = ∏ i, μ i ((hμ i).set (e n i)) := by simp only [measure_toMeasurable] _ < ∞ := ENNReal.prod_lt_top fun i _ => (hμ i).finite _ · simp_rw [(surjective_decode_iget (ι → ℕ)).iUnion_comp fun x => Set.pi univ fun i => (hμ i).set (x i), iUnion_univ_pi fun i => (hμ i).set, (hμ _).spanning, Set.pi_univ] /-- A measure on a finite product space equals the product measure if they are equal on rectangles with as sides sets that generate the corresponding σ-algebras. -/ theorem pi_eq_generateFrom {C : ∀ i, Set (Set (α i))} (hC : ∀ i, generateFrom (C i) = by apply_assumption) (h2C : ∀ i, IsPiSystem (C i)) (h3C : ∀ i, (μ i).FiniteSpanningSetsIn (C i)) {μν : Measure (∀ i, α i)} (h₁ : ∀ s : ∀ i, Set (α i), (∀ i, s i ∈ C i) → μν (pi univ s) = ∏ i, μ i (s i)) : Measure.pi μ = μν := by have h4C : ∀ (i) (s : Set (α i)), s ∈ C i → MeasurableSet s := by intro i s hs; rw [← hC]; exact measurableSet_generateFrom hs refine (FiniteSpanningSetsIn.pi h3C).ext (generateFrom_eq_pi hC fun i => (h3C i).isCountablySpanning).symm (IsPiSystem.pi h2C) ?_ rintro _ ⟨s, hs, rfl⟩ rw [mem_univ_pi] at hs haveI := fun i => (h3C i).sigmaFinite simp_rw [h₁ s hs, pi_pi_aux μ s fun i => h4C i _ (hs i)] variable [∀ i, SigmaFinite (μ i)] /-- A measure on a finite product space equals the product measure if they are equal on rectangles. -/ theorem pi_eq {μ' : Measure (∀ i, α i)} (h : ∀ s : ∀ i, Set (α i), (∀ i, MeasurableSet (s i)) → μ' (pi univ s) = ∏ i, μ i (s i)) : Measure.pi μ = μ' := pi_eq_generateFrom (fun _ => generateFrom_measurableSet) (fun _ => isPiSystem_measurableSet) (fun i => (μ i).toFiniteSpanningSetsIn) h variable (μ) theorem pi'_eq_pi [Encodable ι] : pi' μ = Measure.pi μ := Eq.symm <| pi_eq fun s _ => pi'_pi μ s @[simp] theorem pi_pi (s : ∀ i, Set (α i)) : Measure.pi μ (pi univ s) = ∏ i, μ i (s i) := by haveI : Encodable ι := Fintype.toEncodable ι rw [← pi'_eq_pi, pi'_pi] nonrec theorem pi_univ : Measure.pi μ univ = ∏ i, μ i univ := by rw [← pi_univ, pi_pi μ] theorem pi_ball [∀ i, MetricSpace (α i)] (x : ∀ i, α i) {r : ℝ} (hr : 0 < r) : Measure.pi μ (Metric.ball x r) = ∏ i, μ i (Metric.ball (x i) r) := by rw [ball_pi _ hr, pi_pi] theorem pi_closedBall [∀ i, MetricSpace (α i)] (x : ∀ i, α i) {r : ℝ} (hr : 0 ≤ r) : Measure.pi μ (Metric.closedBall x r) = ∏ i, μ i (Metric.closedBall (x i) r) := by rw [closedBall_pi _ hr, pi_pi] instance pi.sigmaFinite : SigmaFinite (Measure.pi μ) := (FiniteSpanningSetsIn.pi fun i => (μ i).toFiniteSpanningSetsIn).sigmaFinite instance {α : ι → Type*} [∀ i, MeasureSpace (α i)] [∀ i, SigmaFinite (volume : Measure (α i))] : SigmaFinite (volume : Measure (∀ i, α i)) := pi.sigmaFinite _ instance pi.instIsFiniteMeasure [∀ i, IsFiniteMeasure (μ i)] : IsFiniteMeasure (Measure.pi μ) := ⟨Measure.pi_univ μ ▸ ENNReal.prod_lt_top (fun i _ ↦ measure_lt_top (μ i) _)⟩ instance {α : ι → Type*} [∀ i, MeasureSpace (α i)] [∀ i, IsFiniteMeasure (volume : Measure (α i))] : IsFiniteMeasure (volume : Measure (∀ i, α i)) := pi.instIsFiniteMeasure _ instance pi.instIsProbabilityMeasure [∀ i, IsProbabilityMeasure (μ i)] : IsProbabilityMeasure (Measure.pi μ) := ⟨by simp only [Measure.pi_univ, measure_univ, Finset.prod_const_one]⟩ instance {α : ι → Type*} [∀ i, MeasureSpace (α i)] [∀ i, IsProbabilityMeasure (volume : Measure (α i))] : IsProbabilityMeasure (volume : Measure (∀ i, α i)) := pi.instIsProbabilityMeasure _ theorem pi_of_empty {α : Type*} [Fintype α] [IsEmpty α] {β : α → Type*} {m : ∀ a, MeasurableSpace (β a)} (μ : ∀ a : α, Measure (β a)) (x : ∀ a, β a := isEmptyElim) : Measure.pi μ = dirac x := by haveI : ∀ a, SigmaFinite (μ a) := isEmptyElim refine pi_eq fun s _ => ?_ rw [Fintype.prod_empty, dirac_apply_of_mem] exact isEmptyElim (α := α) lemma volume_pi_eq_dirac {ι : Type*} [Fintype ι] [IsEmpty ι] {α : ι → Type*} [∀ i, MeasureSpace (α i)] (x : ∀ a, α a := isEmptyElim) : (volume : Measure (∀ i, α i)) = Measure.dirac x := Measure.pi_of_empty _ _ @[simp] theorem pi_empty_univ {α : Type*} [Fintype α] [IsEmpty α] {β : α → Type*} {m : ∀ α, MeasurableSpace (β α)} (μ : ∀ a : α, Measure (β a)) : Measure.pi μ (Set.univ) = 1 := by rw [pi_of_empty, measure_univ] theorem pi_eval_preimage_null {i : ι} {s : Set (α i)} (hs : μ i s = 0) : Measure.pi μ (eval i ⁻¹' s) = 0 := by classical -- WLOG, `s` is measurable rcases exists_measurable_superset_of_null hs with ⟨t, hst, _, hμt⟩ suffices Measure.pi μ (eval i ⁻¹' t) = 0 from measure_mono_null (preimage_mono hst) this -- Now rewrite it as `Set.pi`, and apply `pi_pi` rw [← univ_pi_update_univ, pi_pi] apply Finset.prod_eq_zero (Finset.mem_univ i) simp [hμt] theorem pi_hyperplane (i : ι) [NoAtoms (μ i)] (x : α i) : Measure.pi μ { f : ∀ i, α i | f i = x } = 0 := show Measure.pi μ (eval i ⁻¹' {x}) = 0 from pi_eval_preimage_null _ (measure_singleton x) theorem ae_eval_ne (i : ι) [NoAtoms (μ i)] (x : α i) : ∀ᵐ y : ∀ i, α i ∂Measure.pi μ, y i ≠ x := compl_mem_ae_iff.2 (pi_hyperplane μ i x) theorem restrict_pi_pi (s : (i : ι) → Set (α i)) : (Measure.pi μ).restrict (Set.univ.pi fun i ↦ s i) = .pi (fun i ↦ (μ i).restrict (s i)) := by refine (pi_eq fun _ h ↦ ?_).symm simp_rw [restrict_apply (MeasurableSet.univ_pi h), restrict_apply (h _), ← Set.pi_inter_distrib, pi_pi] variable {μ} theorem tendsto_eval_ae_ae {i : ι} : Tendsto (eval i) (ae (Measure.pi μ)) (ae (μ i)) := fun _ hs => pi_eval_preimage_null μ hs theorem ae_pi_le_pi : ae (Measure.pi μ) ≤ Filter.pi fun i => ae (μ i) := le_iInf fun _ => tendsto_eval_ae_ae.le_comap theorem ae_eq_pi {β : ι → Type*} {f f' : ∀ i, α i → β i} (h : ∀ i, f i =ᵐ[μ i] f' i) : (fun (x : ∀ i, α i) i => f i (x i)) =ᵐ[Measure.pi μ] fun x i => f' i (x i) := (eventually_all.2 fun i => tendsto_eval_ae_ae.eventually (h i)).mono fun _ hx => funext hx theorem ae_le_pi {β : ι → Type*} [∀ i, Preorder (β i)] {f f' : ∀ i, α i → β i} (h : ∀ i, f i ≤ᵐ[μ i] f' i) : (fun (x : ∀ i, α i) i => f i (x i)) ≤ᵐ[Measure.pi μ] fun x i => f' i (x i) := (eventually_all.2 fun i => tendsto_eval_ae_ae.eventually (h i)).mono fun _ hx => hx theorem ae_le_set_pi {I : Set ι} {s t : ∀ i, Set (α i)} (h : ∀ i ∈ I, s i ≤ᵐ[μ i] t i) : Set.pi I s ≤ᵐ[Measure.pi μ] Set.pi I t := ((eventually_all_finite I.toFinite).2 fun i hi => tendsto_eval_ae_ae.eventually (h i hi)).mono fun _ hst hx i hi => hst i hi <| hx i hi theorem ae_eq_set_pi {I : Set ι} {s t : ∀ i, Set (α i)} (h : ∀ i ∈ I, s i =ᵐ[μ i] t i) : Set.pi I s =ᵐ[Measure.pi μ] Set.pi I t := (ae_le_set_pi fun i hi => (h i hi).le).antisymm (ae_le_set_pi fun i hi => (h i hi).symm.le) lemma pi_map_piCongrLeft [hι' : Fintype ι'] (e : ι ≃ ι') {β : ι' → Type*} [∀ i, MeasurableSpace (β i)] (μ : (i : ι') → Measure (β i)) [∀ i, SigmaFinite (μ i)] : (Measure.pi fun i ↦ μ (e i)).map (MeasurableEquiv.piCongrLeft (fun i ↦ β i) e) = Measure.pi μ := by let e_meas : ((b : ι) → β (e b)) ≃ᵐ ((a : ι') → β a) := MeasurableEquiv.piCongrLeft (fun i ↦ β i) e refine Measure.pi_eq (fun s _ ↦ ?_) |>.symm rw [e_meas.measurableEmbedding.map_apply] let s' : (i : ι) → Set (β (e i)) := fun i ↦ s (e i) have : e_meas ⁻¹' pi univ s = pi univ s' := by ext x simp only [mem_preimage, Set.mem_pi, mem_univ, forall_true_left, s'] refine (e.forall_congr ?_).symm intro i rw [MeasurableEquiv.piCongrLeft_apply_apply e x i] rw [this, pi_pi, Finset.prod_equiv e.symm] · simp only [Finset.mem_univ, implies_true] intro i _ simp only [s'] congr all_goals rw [e.apply_symm_apply] lemma pi_map_piOptionEquivProd {β : Option ι → Type*} [∀ i, MeasurableSpace (β i)] (μ : (i : Option ι) → Measure (β i)) [∀ (i : Option ι), SigmaFinite (μ i)] : ((Measure.pi fun i ↦ μ (some i)).prod (μ none)).map (MeasurableEquiv.piOptionEquivProd β).symm = Measure.pi μ := by refine pi_eq (fun s _ ↦ ?_) |>.symm let e_meas : ((i : ι) → β (some i)) × β none ≃ᵐ ((i : Option ι) → β i) := MeasurableEquiv.piOptionEquivProd β |>.symm have me := MeasurableEquiv.measurableEmbedding e_meas have : e_meas ⁻¹' pi univ s = (pi univ (fun i ↦ s (some i))) ×ˢ (s none) := by ext x simp only [mem_preimage, Set.mem_pi, mem_univ, forall_true_left, mem_prod] refine ⟨by tauto, fun _ i ↦ ?_⟩ rcases i <;> tauto simp only [e_meas, me.map_apply, univ_option, le_eq_subset, Finset.prod_insertNone, this, prod_prod, pi_pi, mul_comm] section Intervals variable [∀ i, PartialOrder (α i)] [∀ i, NoAtoms (μ i)] theorem pi_Iio_ae_eq_pi_Iic {s : Set ι} {f : ∀ i, α i} : (pi s fun i => Iio (f i)) =ᵐ[Measure.pi μ] pi s fun i => Iic (f i) := ae_eq_set_pi fun _ _ => Iio_ae_eq_Iic theorem pi_Ioi_ae_eq_pi_Ici {s : Set ι} {f : ∀ i, α i} : (pi s fun i => Ioi (f i)) =ᵐ[Measure.pi μ] pi s fun i => Ici (f i) := ae_eq_set_pi fun _ _ => Ioi_ae_eq_Ici theorem univ_pi_Iio_ae_eq_Iic {f : ∀ i, α i} : (pi univ fun i => Iio (f i)) =ᵐ[Measure.pi μ] Iic f := by rw [← pi_univ_Iic]; exact pi_Iio_ae_eq_pi_Iic theorem univ_pi_Ioi_ae_eq_Ici {f : ∀ i, α i} : (pi univ fun i => Ioi (f i)) =ᵐ[Measure.pi μ] Ici f := by rw [← pi_univ_Ici]; exact pi_Ioi_ae_eq_pi_Ici theorem pi_Ioo_ae_eq_pi_Icc {s : Set ι} {f g : ∀ i, α i} : (pi s fun i => Ioo (f i) (g i)) =ᵐ[Measure.pi μ] pi s fun i => Icc (f i) (g i) := ae_eq_set_pi fun _ _ => Ioo_ae_eq_Icc theorem pi_Ioo_ae_eq_pi_Ioc {s : Set ι} {f g : ∀ i, α i} : (pi s fun i => Ioo (f i) (g i)) =ᵐ[Measure.pi μ] pi s fun i => Ioc (f i) (g i) := ae_eq_set_pi fun _ _ => Ioo_ae_eq_Ioc theorem univ_pi_Ioo_ae_eq_Icc {f g : ∀ i, α i} : (pi univ fun i => Ioo (f i) (g i)) =ᵐ[Measure.pi μ] Icc f g := by rw [← pi_univ_Icc]; exact pi_Ioo_ae_eq_pi_Icc theorem pi_Ioc_ae_eq_pi_Icc {s : Set ι} {f g : ∀ i, α i} : (pi s fun i => Ioc (f i) (g i)) =ᵐ[Measure.pi μ] pi s fun i => Icc (f i) (g i) := ae_eq_set_pi fun _ _ => Ioc_ae_eq_Icc theorem univ_pi_Ioc_ae_eq_Icc {f g : ∀ i, α i} : (pi univ fun i => Ioc (f i) (g i)) =ᵐ[Measure.pi μ] Icc f g := by rw [← pi_univ_Icc]; exact pi_Ioc_ae_eq_pi_Icc theorem pi_Ico_ae_eq_pi_Icc {s : Set ι} {f g : ∀ i, α i} : (pi s fun i => Ico (f i) (g i)) =ᵐ[Measure.pi μ] pi s fun i => Icc (f i) (g i) := ae_eq_set_pi fun _ _ => Ico_ae_eq_Icc theorem univ_pi_Ico_ae_eq_Icc {f g : ∀ i, α i} : (pi univ fun i => Ico (f i) (g i)) =ᵐ[Measure.pi μ] Icc f g := by rw [← pi_univ_Icc]; exact pi_Ico_ae_eq_pi_Icc end Intervals /-- If one of the measures `μ i` has no atoms, them `Measure.pi µ` has no atoms. The instance below assumes that all `μ i` have no atoms. -/ theorem pi_noAtoms (i : ι) [NoAtoms (μ i)] : NoAtoms (Measure.pi μ) := ⟨fun x => flip measure_mono_null (pi_hyperplane μ i (x i)) (singleton_subset_iff.2 rfl)⟩ instance pi_noAtoms' [h : Nonempty ι] [∀ i, NoAtoms (μ i)] : NoAtoms (Measure.pi μ) := h.elim fun i => pi_noAtoms i instance {α : ι → Type*} [Nonempty ι] [∀ i, MeasureSpace (α i)] [∀ i, SigmaFinite (volume : Measure (α i))] [∀ i, NoAtoms (volume : Measure (α i))] : NoAtoms (volume : Measure (∀ i, α i)) := pi_noAtoms' instance pi.isLocallyFiniteMeasure [∀ i, TopologicalSpace (α i)] [∀ i, IsLocallyFiniteMeasure (μ i)] : IsLocallyFiniteMeasure (Measure.pi μ) := by refine ⟨fun x => ?_⟩ choose s hxs ho hμ using fun i => (μ i).exists_isOpen_measure_lt_top (x i) refine ⟨pi univ s, set_pi_mem_nhds finite_univ fun i _ => IsOpen.mem_nhds (ho i) (hxs i), ?_⟩ rw [pi_pi] exact ENNReal.prod_lt_top fun i _ => hμ i instance {X : ι → Type*} [∀ i, TopologicalSpace (X i)] [∀ i, MeasureSpace (X i)] [∀ i, SigmaFinite (volume : Measure (X i))] [∀ i, IsLocallyFiniteMeasure (volume : Measure (X i))] : IsLocallyFiniteMeasure (volume : Measure (∀ i, X i)) := pi.isLocallyFiniteMeasure variable (μ) @[to_additive] instance pi.isMulLeftInvariant [∀ i, Group (α i)] [∀ i, MeasurableMul (α i)] [∀ i, IsMulLeftInvariant (μ i)] : IsMulLeftInvariant (Measure.pi μ) := by refine ⟨fun v => (pi_eq fun s hs => ?_).symm⟩ rw [map_apply (measurable_const_mul _) (MeasurableSet.univ_pi hs), show (v * ·) ⁻¹' univ.pi s = univ.pi fun i => (v i * ·) ⁻¹' s i by rfl, pi_pi] simp_rw [measure_preimage_mul] @[to_additive] instance {G : ι → Type*} [∀ i, Group (G i)] [∀ i, MeasureSpace (G i)] [∀ i, MeasurableMul (G i)] [∀ i, SigmaFinite (volume : Measure (G i))] [∀ i, IsMulLeftInvariant (volume : Measure (G i))] : IsMulLeftInvariant (volume : Measure (∀ i, G i)) := pi.isMulLeftInvariant _ @[to_additive] instance pi.isMulRightInvariant [∀ i, Group (α i)] [∀ i, MeasurableMul (α i)] [∀ i, IsMulRightInvariant (μ i)] : IsMulRightInvariant (Measure.pi μ) := by refine ⟨fun v => (pi_eq fun s hs => ?_).symm⟩ rw [map_apply (measurable_mul_const _) (MeasurableSet.univ_pi hs), show (· * v) ⁻¹' univ.pi s = univ.pi fun i => (· * v i) ⁻¹' s i by rfl, pi_pi] simp_rw [measure_preimage_mul_right] @[to_additive] instance {G : ι → Type*} [∀ i, Group (G i)] [∀ i, MeasureSpace (G i)] [∀ i, MeasurableMul (G i)] [∀ i, SigmaFinite (volume : Measure (G i))] [∀ i, IsMulRightInvariant (volume : Measure (G i))] : IsMulRightInvariant (volume : Measure (∀ i, G i)) := pi.isMulRightInvariant _ @[to_additive] instance pi.isInvInvariant [∀ i, Group (α i)] [∀ i, MeasurableInv (α i)] [∀ i, IsInvInvariant (μ i)] : IsInvInvariant (Measure.pi μ) := by refine ⟨(Measure.pi_eq fun s hs => ?_).symm⟩ have A : Inv.inv ⁻¹' pi univ s = Set.pi univ fun i => Inv.inv ⁻¹' s i := by ext; simp simp_rw [Measure.inv, Measure.map_apply measurable_inv (MeasurableSet.univ_pi hs), A, pi_pi, measure_preimage_inv] @[to_additive] instance {G : ι → Type*} [∀ i, Group (G i)] [∀ i, MeasureSpace (G i)] [∀ i, MeasurableInv (G i)] [∀ i, SigmaFinite (volume : Measure (G i))] [∀ i, IsInvInvariant (volume : Measure (G i))] : IsInvInvariant (volume : Measure (∀ i, G i)) := pi.isInvInvariant _ instance pi.isOpenPosMeasure [∀ i, TopologicalSpace (α i)] [∀ i, IsOpenPosMeasure (μ i)] : IsOpenPosMeasure (MeasureTheory.Measure.pi μ) := by constructor rintro U U_open ⟨a, ha⟩ obtain ⟨s, ⟨hs, hsU⟩⟩ := isOpen_pi_iff'.1 U_open a ha refine ne_of_gt (lt_of_lt_of_le ?_ (measure_mono hsU)) simp only [pi_pi] rw [CanonicallyOrderedAdd.prod_pos] intro i _ apply (hs i).1.measure_pos (μ i) ⟨a i, (hs i).2⟩ instance {X : ι → Type*} [∀ i, TopologicalSpace (X i)] [∀ i, MeasureSpace (X i)] [∀ i, IsOpenPosMeasure (volume : Measure (X i))] [∀ i, SigmaFinite (volume : Measure (X i))] : IsOpenPosMeasure (volume : Measure (∀ i, X i)) := pi.isOpenPosMeasure _ instance pi.isFiniteMeasureOnCompacts [∀ i, TopologicalSpace (α i)] [∀ i, IsFiniteMeasureOnCompacts (μ i)] : IsFiniteMeasureOnCompacts (MeasureTheory.Measure.pi μ) := by constructor intro K hK suffices Measure.pi μ (Set.univ.pi fun j => Function.eval j '' K) < ⊤ by exact lt_of_le_of_lt (measure_mono (univ.subset_pi_eval_image K)) this rw [Measure.pi_pi] refine WithTop.prod_lt_top ?_ exact fun i _ => IsCompact.measure_lt_top (IsCompact.image hK (continuous_apply i)) instance {X : ι → Type*} [∀ i, MeasureSpace (X i)] [∀ i, TopologicalSpace (X i)] [∀ i, SigmaFinite (volume : Measure (X i))] [∀ i, IsFiniteMeasureOnCompacts (volume : Measure (X i))] : IsFiniteMeasureOnCompacts (volume : Measure (∀ i, X i)) := pi.isFiniteMeasureOnCompacts _ @[to_additive] instance pi.isHaarMeasure [∀ i, Group (α i)] [∀ i, TopologicalSpace (α i)] [∀ i, IsHaarMeasure (μ i)] [∀ i, MeasurableMul (α i)] : IsHaarMeasure (Measure.pi μ) where @[to_additive] instance {G : ι → Type*} [∀ i, Group (G i)] [∀ i, MeasureSpace (G i)] [∀ i, MeasurableMul (G i)] [∀ i, TopologicalSpace (G i)] [∀ i, SigmaFinite (volume : Measure (G i))] [∀ i, IsHaarMeasure (volume : Measure (G i))] : IsHaarMeasure (volume : Measure (∀ i, G i)) := pi.isHaarMeasure _ end Measure theorem volume_pi [∀ i, MeasureSpace (α i)] : (volume : Measure (∀ i, α i)) = Measure.pi fun _ => volume := rfl theorem volume_pi_pi [∀ i, MeasureSpace (α i)] [∀ i, SigmaFinite (volume : Measure (α i))] (s : ∀ i, Set (α i)) : volume (pi univ s) = ∏ i, volume (s i) := Measure.pi_pi (fun _ => volume) s theorem volume_pi_ball [∀ i, MeasureSpace (α i)] [∀ i, SigmaFinite (volume : Measure (α i))] [∀ i, MetricSpace (α i)] (x : ∀ i, α i) {r : ℝ} (hr : 0 < r) : volume (Metric.ball x r) = ∏ i, volume (Metric.ball (x i) r) := Measure.pi_ball _ _ hr theorem volume_pi_closedBall [∀ i, MeasureSpace (α i)] [∀ i, SigmaFinite (volume : Measure (α i))] [∀ i, MetricSpace (α i)] (x : ∀ i, α i) {r : ℝ} (hr : 0 ≤ r) : volume (Metric.closedBall x r) = ∏ i, volume (Metric.closedBall (x i) r) := Measure.pi_closedBall _ _ hr open Measure /-- We intentionally restrict this only to the nondependent function space, since type-class inference cannot find an instance for `ι → ℝ` when this is stated for dependent function spaces. -/ @[to_additive "We intentionally restrict this only to the nondependent function space, since type-class inference cannot find an instance for `ι → ℝ` when this is stated for dependent function spaces."] instance Pi.isMulLeftInvariant_volume {α} [Group α] [MeasureSpace α] [SigmaFinite (volume : Measure α)] [MeasurableMul α] [IsMulLeftInvariant (volume : Measure α)] : IsMulLeftInvariant (volume : Measure (ι → α)) := pi.isMulLeftInvariant _ /-- We intentionally restrict this only to the nondependent function space, since type-class inference cannot find an instance for `ι → ℝ` when this is stated for dependent function spaces. -/ @[to_additive "We intentionally restrict this only to the nondependent function space, since type-class inference cannot find an instance for `ι → ℝ` when this is stated for dependent function spaces."] instance Pi.isInvInvariant_volume {α} [Group α] [MeasureSpace α] [SigmaFinite (volume : Measure α)] [MeasurableInv α] [IsInvInvariant (volume : Measure α)] : IsInvInvariant (volume : Measure (ι → α)) := pi.isInvInvariant _ /-! ### Measure preserving equivalences In this section we prove that some measurable equivalences (e.g., between `Fin 1 → α` and `α` or between `Fin 2 → α` and `α × α`) preserve measure or volume. These lemmas can be used to prove that measures of corresponding sets (images or preimages) have equal measures and functions `f ∘ e` and `f` have equal integrals, see lemmas in the `MeasureTheory.measurePreserving` prefix. -/ section MeasurePreserving variable {m : ∀ i, MeasurableSpace (α i)} (μ : ∀ i, Measure (α i)) [∀ i, SigmaFinite (μ i)] variable [Fintype ι'] theorem measurePreserving_piEquivPiSubtypeProd (p : ι → Prop) [DecidablePred p] : MeasurePreserving (MeasurableEquiv.piEquivPiSubtypeProd α p) (Measure.pi μ) ((Measure.pi fun i : Subtype p => μ i).prod (Measure.pi fun i => μ i)) := by set e := (MeasurableEquiv.piEquivPiSubtypeProd α p).symm refine MeasurePreserving.symm e ?_ refine ⟨e.measurable, (pi_eq fun s _ => ?_).symm⟩ have : e ⁻¹' pi univ s = (pi univ fun i : { i // p i } => s i) ×ˢ pi univ fun i : { i // ¬p i } => s i := Equiv.preimage_piEquivPiSubtypeProd_symm_pi p s rw [e.map_apply, this, prod_prod, pi_pi, pi_pi] exact Fintype.prod_subtype_mul_prod_subtype p fun i => μ i (s i) theorem volume_preserving_piEquivPiSubtypeProd (α : ι → Type*) [∀ i, MeasureSpace (α i)] [∀ i, SigmaFinite (volume : Measure (α i))] (p : ι → Prop) [DecidablePred p] : MeasurePreserving (MeasurableEquiv.piEquivPiSubtypeProd α p) := measurePreserving_piEquivPiSubtypeProd (fun _ => volume) p theorem measurePreserving_piCongrLeft (f : ι' ≃ ι) : MeasurePreserving (MeasurableEquiv.piCongrLeft α f) (Measure.pi fun i' => μ (f i')) (Measure.pi μ) where measurable := (MeasurableEquiv.piCongrLeft α f).measurable map_eq := by refine (pi_eq fun s _ => ?_).symm rw [MeasurableEquiv.map_apply, MeasurableEquiv.coe_piCongrLeft f, Equiv.piCongrLeft_preimage_univ_pi, pi_pi _ _, f.prod_comp (fun i => μ i (s i))] theorem volume_measurePreserving_piCongrLeft (α : ι → Type*) (f : ι' ≃ ι) [∀ i, MeasureSpace (α i)] [∀ i, SigmaFinite (volume : Measure (α i))] : MeasurePreserving (MeasurableEquiv.piCongrLeft α f) volume volume := measurePreserving_piCongrLeft (fun _ ↦ volume) f theorem measurePreserving_arrowProdEquivProdArrow (α β γ : Type*) [MeasurableSpace α] [MeasurableSpace β] [Fintype γ] (μ : γ → Measure α) (ν : γ → Measure β) [∀ i, SigmaFinite (μ i)] [∀ i, SigmaFinite (ν i)] : MeasurePreserving (MeasurableEquiv.arrowProdEquivProdArrow α β γ) (.pi fun i ↦ (μ i).prod (ν i)) ((Measure.pi fun i ↦ μ i).prod (Measure.pi fun i ↦ ν i)) where measurable := (MeasurableEquiv.arrowProdEquivProdArrow α β γ).measurable map_eq := by refine (FiniteSpanningSetsIn.ext ?_ (isPiSystem_pi.prod isPiSystem_pi) ((FiniteSpanningSetsIn.pi fun i ↦ (μ i).toFiniteSpanningSetsIn).prod (FiniteSpanningSetsIn.pi (fun i ↦ (ν i).toFiniteSpanningSetsIn))) ?_).symm · refine (generateFrom_eq_prod generateFrom_pi generateFrom_pi ?_ ?_).symm · exact (FiniteSpanningSetsIn.pi (fun i ↦ (μ i).toFiniteSpanningSetsIn)).isCountablySpanning · exact (FiniteSpanningSetsIn.pi (fun i ↦ (ν i).toFiniteSpanningSetsIn)).isCountablySpanning · rintro _ ⟨s, ⟨s, _, rfl⟩, ⟨_, ⟨t, _, rfl⟩, rfl⟩⟩ rw [MeasurableEquiv.map_apply, MeasurableEquiv.arrowProdEquivProdArrow, MeasurableEquiv.coe_mk] rw [show Equiv.arrowProdEquivProdArrow γ _ _ ⁻¹' (univ.pi s ×ˢ univ.pi t) = (univ.pi fun i ↦ s i ×ˢ t i) by ext; simp [Set.mem_pi, forall_and]] simp_rw [pi_pi, prod_prod, pi_pi, Finset.prod_mul_distrib] theorem volume_measurePreserving_arrowProdEquivProdArrow (α β γ : Type*) [MeasureSpace α] [MeasureSpace β] [Fintype γ] [SigmaFinite (volume : Measure α)] [SigmaFinite (volume : Measure β)] : MeasurePreserving (MeasurableEquiv.arrowProdEquivProdArrow α β γ) := measurePreserving_arrowProdEquivProdArrow α β γ (fun _ ↦ volume) (fun _ ↦ volume) theorem measurePreserving_sumPiEquivProdPi_symm {X : ι ⊕ ι' → Type*} {m : ∀ i, MeasurableSpace (X i)} (μ : ∀ i, Measure (X i)) [∀ i, SigmaFinite (μ i)] : MeasurePreserving (MeasurableEquiv.sumPiEquivProdPi X).symm ((Measure.pi fun i => μ (.inl i)).prod (Measure.pi fun i => μ (.inr i))) (Measure.pi μ) where measurable := (MeasurableEquiv.sumPiEquivProdPi X).symm.measurable map_eq := by refine (pi_eq fun s _ => ?_).symm simp_rw [MeasurableEquiv.map_apply, MeasurableEquiv.coe_sumPiEquivProdPi_symm, Equiv.sumPiEquivProdPi_symm_preimage_univ_pi, Measure.prod_prod, Measure.pi_pi, Fintype.prod_sum_type] theorem volume_measurePreserving_sumPiEquivProdPi_symm (X : ι ⊕ ι' → Type*) [∀ i, MeasureSpace (X i)] [∀ i, SigmaFinite (volume : Measure (X i))] : MeasurePreserving (MeasurableEquiv.sumPiEquivProdPi X).symm volume volume := measurePreserving_sumPiEquivProdPi_symm (fun _ ↦ volume) theorem measurePreserving_sumPiEquivProdPi {X : ι ⊕ ι' → Type*} {_m : ∀ i, MeasurableSpace (X i)} (μ : ∀ i, Measure (X i)) [∀ i, SigmaFinite (μ i)] : MeasurePreserving (MeasurableEquiv.sumPiEquivProdPi X) (Measure.pi μ) ((Measure.pi fun i => μ (.inl i)).prod (Measure.pi fun i => μ (.inr i))) := measurePreserving_sumPiEquivProdPi_symm μ |>.symm theorem volume_measurePreserving_sumPiEquivProdPi (X : ι ⊕ ι' → Type*) [∀ i, MeasureSpace (X i)] [∀ i, SigmaFinite (volume : Measure (X i))] : MeasurePreserving (MeasurableEquiv.sumPiEquivProdPi X) volume volume := measurePreserving_sumPiEquivProdPi (fun _ ↦ volume) theorem measurePreserving_piFinSuccAbove {n : ℕ} {α : Fin (n + 1) → Type u} {m : ∀ i, MeasurableSpace (α i)} (μ : ∀ i, Measure (α i)) [∀ i, SigmaFinite (μ i)] (i : Fin (n + 1)) : MeasurePreserving (MeasurableEquiv.piFinSuccAbove α i) (Measure.pi μ) ((μ i).prod <| Measure.pi fun j => μ (i.succAbove j)) := by set e := (MeasurableEquiv.piFinSuccAbove α i).symm refine MeasurePreserving.symm e ?_ refine ⟨e.measurable, (pi_eq fun s _ => ?_).symm⟩ rw [e.map_apply, i.prod_univ_succAbove _, ← pi_pi, ← prod_prod] congr 1 with ⟨x, f⟩ simp [e, i.forall_iff_succAbove] theorem volume_preserving_piFinSuccAbove {n : ℕ} (α : Fin (n + 1) → Type u) [∀ i, MeasureSpace (α i)] [∀ i, SigmaFinite (volume : Measure (α i))] (i : Fin (n + 1)) : MeasurePreserving (MeasurableEquiv.piFinSuccAbove α i) := measurePreserving_piFinSuccAbove (fun _ => volume) i theorem measurePreserving_piUnique {X : ι → Type*} [Unique ι] {m : ∀ i, MeasurableSpace (X i)} (μ : ∀ i, Measure (X i)) : MeasurePreserving (MeasurableEquiv.piUnique X) (Measure.pi μ) (μ default) where measurable := (MeasurableEquiv.piUnique X).measurable map_eq := by set e := MeasurableEquiv.piUnique X have : (piPremeasure fun i => (μ i).toOuterMeasure) = Measure.map e.symm (μ default) := by ext1 s rw [piPremeasure, Fintype.prod_unique, e.symm.map_apply, coe_toOuterMeasure] congr 1; exact e.toEquiv.image_eq_preimage s simp_rw [Measure.pi, OuterMeasure.pi, this, ← coe_toOuterMeasure, boundedBy_eq_self, toOuterMeasure_toMeasure, MeasurableEquiv.map_map_symm] theorem volume_preserving_piUnique (X : ι → Type*) [Unique ι] [∀ i, MeasureSpace (X i)] : MeasurePreserving (MeasurableEquiv.piUnique X) volume volume := measurePreserving_piUnique _ theorem measurePreserving_funUnique {β : Type u} {_m : MeasurableSpace β} (μ : Measure β) (α : Type v) [Unique α] : MeasurePreserving (MeasurableEquiv.funUnique α β) (Measure.pi fun _ : α => μ) μ := measurePreserving_piUnique _ theorem volume_preserving_funUnique (α : Type u) (β : Type v) [Unique α] [MeasureSpace β] : MeasurePreserving (MeasurableEquiv.funUnique α β) volume volume := measurePreserving_funUnique volume α theorem measurePreserving_piFinTwo {α : Fin 2 → Type u} {m : ∀ i, MeasurableSpace (α i)} (μ : ∀ i, Measure (α i)) [∀ i, SigmaFinite (μ i)] : MeasurePreserving (MeasurableEquiv.piFinTwo α) (Measure.pi μ) ((μ 0).prod (μ 1)) := by refine ⟨MeasurableEquiv.measurable _, (Measure.prod_eq fun s t _ _ => ?_).symm⟩ rw [MeasurableEquiv.map_apply, MeasurableEquiv.piFinTwo_apply, Fin.preimage_apply_01_prod, Measure.pi_pi, Fin.prod_univ_two] rfl theorem volume_preserving_piFinTwo (α : Fin 2 → Type u) [∀ i, MeasureSpace (α i)] [∀ i, SigmaFinite (volume : Measure (α i))] : MeasurePreserving (MeasurableEquiv.piFinTwo α) volume volume := measurePreserving_piFinTwo _ theorem measurePreserving_finTwoArrow_vec {α : Type u} {_ : MeasurableSpace α} (μ ν : Measure α) [SigmaFinite μ] [SigmaFinite ν] : MeasurePreserving MeasurableEquiv.finTwoArrow (Measure.pi ![μ, ν]) (μ.prod ν) := haveI : ∀ i, SigmaFinite (![μ, ν] i) := Fin.forall_fin_two.2 ⟨‹_›, ‹_›⟩ measurePreserving_piFinTwo _ theorem measurePreserving_finTwoArrow {α : Type u} {m : MeasurableSpace α} (μ : Measure α) [SigmaFinite μ] : MeasurePreserving MeasurableEquiv.finTwoArrow (Measure.pi fun _ => μ) (μ.prod μ) := by simpa only [Matrix.vec_single_eq_const, Matrix.vecCons_const] using measurePreserving_finTwoArrow_vec μ μ theorem volume_preserving_finTwoArrow (α : Type u) [MeasureSpace α] [SigmaFinite (volume : Measure α)] : MeasurePreserving (@MeasurableEquiv.finTwoArrow α _) volume volume := measurePreserving_finTwoArrow volume theorem measurePreserving_pi_empty {ι : Type u} {α : ι → Type v} [Fintype ι] [IsEmpty ι] {m : ∀ i, MeasurableSpace (α i)} (μ : ∀ i, Measure (α i)) : MeasurePreserving (MeasurableEquiv.ofUniqueOfUnique (∀ i, α i) Unit) (Measure.pi μ) (Measure.dirac ()) := by set e := MeasurableEquiv.ofUniqueOfUnique (∀ i, α i) Unit refine ⟨e.measurable, ?_⟩ rw [Measure.pi_of_empty, Measure.map_dirac e.measurable] theorem volume_preserving_pi_empty {ι : Type u} (α : ι → Type v) [Fintype ι] [IsEmpty ι] [∀ i, MeasureSpace (α i)] : MeasurePreserving (MeasurableEquiv.ofUniqueOfUnique (∀ i, α i) Unit) volume volume := measurePreserving_pi_empty fun _ => volume theorem measurePreserving_piFinsetUnion {ι : Type*} {α : ι → Type*} {_ : ∀ i, MeasurableSpace (α i)} [DecidableEq ι] {s t : Finset ι} (h : Disjoint s t) (μ : ∀ i, Measure (α i)) [∀ i, SigmaFinite (μ i)] : MeasurePreserving (MeasurableEquiv.piFinsetUnion α h) ((Measure.pi fun i : s ↦ μ i).prod (Measure.pi fun i : t ↦ μ i)) (Measure.pi fun i : ↥(s ∪ t) ↦ μ i) := let e := Equiv.Finset.union s t h measurePreserving_piCongrLeft (fun i : ↥(s ∪ t) ↦ μ i) e |>.comp <| measurePreserving_sumPiEquivProdPi_symm fun b ↦ μ (e b) theorem volume_preserving_piFinsetUnion {ι : Type*} [DecidableEq ι] (α : ι → Type*) {s t : Finset ι} (h : Disjoint s t) [∀ i, MeasureSpace (α i)] [∀ i, SigmaFinite (volume : Measure (α i))] : MeasurePreserving (MeasurableEquiv.piFinsetUnion α h) volume volume := measurePreserving_piFinsetUnion h (fun _ ↦ volume) theorem measurePreserving_pi {ι : Type*} [Fintype ι] {α : ι → Type v} {β : ι → Type*} [∀ i, MeasurableSpace (α i)] [∀ i, MeasurableSpace (β i)] (μ : (i : ι) → Measure (α i)) (ν : (i : ι) → Measure (β i)) {f : (i : ι) → (α i) → (β i)} [∀ i, SigmaFinite (ν i)] (hf : ∀ i, MeasurePreserving (f i) (μ i) (ν i)) : MeasurePreserving (fun a i ↦ f i (a i)) (Measure.pi μ) (Measure.pi ν) where measurable := measurable_pi_iff.mpr <| fun i ↦ (hf i).measurable.comp (measurable_pi_apply i) map_eq := by haveI : ∀ i, SigmaFinite (μ i) := fun i ↦ (hf i).sigmaFinite refine (Measure.pi_eq fun s hs ↦ ?_).symm rw [Measure.map_apply, Set.preimage_pi, Measure.pi_pi] · simp_rw [← MeasurePreserving.measure_preimage (hf _) (hs _).nullMeasurableSet] · exact measurable_pi_iff.mpr <| fun i ↦ (hf i).measurable.comp (measurable_pi_apply i) · exact MeasurableSet.univ_pi hs theorem volume_preserving_pi {α' β' : ι → Type*} [∀ i, MeasureSpace (α' i)] [∀ i, MeasureSpace (β' i)] [∀ i, SigmaFinite (volume : Measure (β' i))] {f : (i : ι) → (α' i) → (β' i)} (hf : ∀ i, MeasurePreserving (f i)) : MeasurePreserving (fun (a : (i : ι) → α' i) (i : ι) ↦ (f i) (a i)) := measurePreserving_pi _ _ hf /-- The measurable equiv `(α₁ → β₁) ≃ᵐ (α₂ → β₂)` induced by `α₁ ≃ α₂` and `β₁ ≃ᵐ β₂` is measure preserving. -/ theorem measurePreserving_arrowCongr' {α₁ β₁ α₂ β₂ : Type*} [Fintype α₁] [Fintype α₂] [MeasurableSpace β₁] [MeasurableSpace β₂] (μ : α₁ → Measure β₁) (ν : α₂ → Measure β₂) [∀ i, SigmaFinite (ν i)] (eα : α₁ ≃ α₂) (eβ : β₁ ≃ᵐ β₂) (hm : ∀ i, MeasurePreserving eβ (μ i) (ν (eα i))) : MeasurePreserving (MeasurableEquiv.arrowCongr' eα eβ) (Measure.pi fun i ↦ μ i) (Measure.pi fun i ↦ ν i) := by classical convert (measurePreserving_piCongrLeft (fun i : α₂ ↦ ν i) eα).comp (measurePreserving_pi μ (fun i : α₁ ↦ ν (eα i)) hm) simp only [MeasurableEquiv.arrowCongr', Equiv.arrowCongr', Equiv.arrowCongr, EquivLike.coe_coe, comp_def, MeasurableEquiv.coe_mk, Equiv.coe_fn_mk, MeasurableEquiv.piCongrLeft, Equiv.piCongrLeft, Equiv.symm_symm, Equiv.piCongrLeft', eq_rec_constant, Equiv.coe_fn_symm_mk] /-- The measurable equiv `(α₁ → β₁) ≃ᵐ (α₂ → β₂)` induced by `α₁ ≃ α₂` and `β₁ ≃ᵐ β₂` is volume preserving. -/ theorem volume_preserving_arrowCongr' {α₁ β₁ α₂ β₂ : Type*} [Fintype α₁] [Fintype α₂] [MeasureSpace β₁] [MeasureSpace β₂] [SigmaFinite (volume : Measure β₂)] (hα : α₁ ≃ α₂) (hβ : β₁ ≃ᵐ β₂) (hm : MeasurePreserving hβ) : MeasurePreserving (MeasurableEquiv.arrowCongr' hα hβ) := measurePreserving_arrowCongr' (fun _ ↦ volume) (fun _ ↦ volume) hα hβ (fun _ ↦ hm) end MeasurePreserving end MeasureTheory
Mathlib/MeasureTheory/Constructions/Pi.lean
909
915
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import Mathlib.Algebra.GroupWithZero.Divisibility import Mathlib.Algebra.Ring.Rat import Mathlib.Algebra.Ring.Int.Parity import Mathlib.Data.PNat.Defs /-! # Further lemmas for the Rational Numbers -/ namespace Rat theorem num_dvd (a) {b : ℤ} (b0 : b ≠ 0) : (a /. b).num ∣ a := by rcases e : a /. b with ⟨n, d, h, c⟩ rw [Rat.mk'_eq_divInt, divInt_eq_iff b0 (mod_cast h)] at e refine Int.natAbs_dvd.1 <| Int.dvd_natAbs.1 <| Int.natCast_dvd_natCast.2 <| c.dvd_of_dvd_mul_right ?_ have := congr_arg Int.natAbs e simp only [Int.natAbs_mul, Int.natAbs_natCast] at this; simp [this] theorem den_dvd (a b : ℤ) : ((a /. b).den : ℤ) ∣ b := by by_cases b0 : b = 0; · simp [b0] rcases e : a /. b with ⟨n, d, h, c⟩ rw [mk'_eq_divInt, divInt_eq_iff b0 (ne_of_gt (Int.natCast_pos.2 (Nat.pos_of_ne_zero h)))] at e refine Int.dvd_natAbs.1 <| Int.natCast_dvd_natCast.2 <| c.symm.dvd_of_dvd_mul_left ?_ rw [← Int.natAbs_mul, ← Int.natCast_dvd_natCast, Int.dvd_natAbs, ← e]; simp theorem num_den_mk {q : ℚ} {n d : ℤ} (hd : d ≠ 0) (qdf : q = n /. d) : ∃ c : ℤ, n = c * q.num ∧ d = c * q.den := by obtain rfl | hn := eq_or_ne n 0 · simp [qdf] have : q.num * d = n * ↑q.den := by refine (divInt_eq_iff ?_ hd).mp ?_ · exact Int.natCast_ne_zero.mpr (Rat.den_nz _) · rwa [num_divInt_den] have hqdn : q.num ∣ n := by rw [qdf] exact Rat.num_dvd _ hd refine ⟨n / q.num, ?_, ?_⟩ · rw [Int.ediv_mul_cancel hqdn] · refine Int.eq_mul_div_of_mul_eq_mul_of_dvd_left ?_ hqdn this rw [qdf] exact Rat.num_ne_zero.2 ((divInt_ne_zero hd).mpr hn) theorem num_mk (n d : ℤ) : (n /. d).num = d.sign * n / n.gcd d := by have (m : ℕ) : Int.natAbs (m + 1) = m + 1 := by rw [← Nat.cast_one, ← Nat.cast_add, Int.natAbs_cast] rcases d with ((_ | _) | _) <;> rw [← Int.tdiv_eq_ediv_of_dvd] <;> simp [divInt, mkRat, Rat.normalize, Nat.succPNat, Int.sign, Int.gcd, Int.zero_ediv, Int.ofNat_dvd_left, Nat.gcd_dvd_left, this] theorem den_mk (n d : ℤ) : (n /. d).den = if d = 0 then 1 else d.natAbs / n.gcd d := by have (m : ℕ) : Int.natAbs (m + 1) = m + 1 := by rw [← Nat.cast_one, ← Nat.cast_add, Int.natAbs_cast] rcases d with ((_ | _) | _) <;> simp [divInt, mkRat, Rat.normalize, Nat.succPNat, Int.sign, Int.gcd, if_neg (Nat.cast_add_one_ne_zero _), this] theorem add_den_dvd_lcm (q₁ q₂ : ℚ) : (q₁ + q₂).den ∣ q₁.den.lcm q₂.den := by rw [add_def, normalize_eq, Nat.div_dvd_iff_dvd_mul (Nat.gcd_dvd_right _ _) (Nat.gcd_ne_zero_right (by simp)), ← Nat.gcd_mul_lcm, mul_dvd_mul_iff_right (Nat.lcm_ne_zero (by simp) (by simp)), Nat.dvd_gcd_iff] refine ⟨?_, dvd_mul_right _ _⟩ rw [← Int.natCast_dvd_natCast, Int.dvd_natAbs] apply Int.dvd_add <;> apply dvd_mul_of_dvd_right <;> rw [Int.natCast_dvd_natCast] <;> [exact Nat.gcd_dvd_right _ _; exact Nat.gcd_dvd_left _ _] theorem add_den_dvd (q₁ q₂ : ℚ) : (q₁ + q₂).den ∣ q₁.den * q₂.den := by rw [add_def, normalize_eq] apply Nat.div_dvd_of_dvd apply Nat.gcd_dvd_right theorem mul_den_dvd (q₁ q₂ : ℚ) : (q₁ * q₂).den ∣ q₁.den * q₂.den := by rw [mul_def, normalize_eq] apply Nat.div_dvd_of_dvd apply Nat.gcd_dvd_right theorem mul_num (q₁ q₂ : ℚ) : (q₁ * q₂).num = q₁.num * q₂.num / Nat.gcd (q₁.num * q₂.num).natAbs (q₁.den * q₂.den) := by rw [mul_def, normalize_eq] theorem mul_den (q₁ q₂ : ℚ) : (q₁ * q₂).den = q₁.den * q₂.den / Nat.gcd (q₁.num * q₂.num).natAbs (q₁.den * q₂.den) := by rw [mul_def, normalize_eq] theorem mul_self_num (q : ℚ) : (q * q).num = q.num * q.num := by rw [mul_num, Int.natAbs_mul, Nat.Coprime.gcd_eq_one, Int.ofNat_one, Int.ediv_one] exact (q.reduced.mul_right q.reduced).mul (q.reduced.mul_right q.reduced) theorem mul_self_den (q : ℚ) : (q * q).den = q.den * q.den := by rw [Rat.mul_den, Int.natAbs_mul, Nat.Coprime.gcd_eq_one, Nat.div_one] exact (q.reduced.mul_right q.reduced).mul (q.reduced.mul_right q.reduced) theorem add_num_den (q r : ℚ) : q + r = (q.num * r.den + q.den * r.num : ℤ) /. (↑q.den * ↑r.den : ℤ) := by have hqd : (q.den : ℤ) ≠ 0 := Int.natCast_ne_zero_iff_pos.2 q.den_pos have hrd : (r.den : ℤ) ≠ 0 := Int.natCast_ne_zero_iff_pos.2 r.den_pos conv_lhs => rw [← num_divInt_den q, ← num_divInt_den r, divInt_add_divInt _ _ hqd hrd] rw [mul_comm r.num q.den] theorem isSquare_iff {q : ℚ} : IsSquare q ↔ IsSquare q.num ∧ IsSquare q.den := by constructor · rintro ⟨qr, rfl⟩ rw [Rat.mul_self_num, mul_self_den] simp only [IsSquare.mul_self, and_self] · rintro ⟨⟨nr, hnr⟩, ⟨dr, hdr⟩⟩ refine ⟨nr / dr, ?_⟩ rw [div_mul_div_comm, ← Int.cast_mul, ← Nat.cast_mul, ← hnr, ← hdr, num_div_den] @[norm_cast, simp] theorem isSquare_natCast_iff {n : ℕ} : IsSquare (n : ℚ) ↔ IsSquare n := by simp_rw [isSquare_iff, num_natCast, den_natCast, IsSquare.one, and_true, Int.isSquare_natCast_iff] @[norm_cast, simp] theorem isSquare_intCast_iff {z : ℤ} : IsSquare (z : ℚ) ↔ IsSquare z := by simp_rw [isSquare_iff, intCast_num, intCast_den, IsSquare.one, and_true] @[simp] theorem isSquare_ofNat_iff {n : ℕ} : IsSquare (ofNat(n) : ℚ) ↔ IsSquare (OfNat.ofNat n : ℕ) := isSquare_natCast_iff section Casts theorem exists_eq_mul_div_num_and_eq_mul_div_den (n : ℤ) {d : ℤ} (d_ne_zero : d ≠ 0) : ∃ c : ℤ, n = c * ((n : ℚ) / d).num ∧ (d : ℤ) = c * ((n : ℚ) / d).den := haveI : (n : ℚ) / d = Rat.divInt n d := by rw [← Rat.divInt_eq_div] Rat.num_den_mk d_ne_zero this theorem mul_num_den' (q r : ℚ) : (q * r).num * q.den * r.den = q.num * r.num * (q * r).den := by let s := q.num * r.num /. (q.den * r.den : ℤ) have hs : (q.den * r.den : ℤ) ≠ 0 := Int.natCast_ne_zero_iff_pos.mpr (Nat.mul_pos q.pos r.pos) obtain ⟨c, ⟨c_mul_num, c_mul_den⟩⟩ := exists_eq_mul_div_num_and_eq_mul_div_den (q.num * r.num) hs rw [c_mul_num, mul_assoc, mul_comm] nth_rw 1 [c_mul_den] rw [Int.mul_assoc, Int.mul_assoc, mul_eq_mul_left_iff, or_iff_not_imp_right] intro have h : _ = s := divInt_mul_divInt q.num r.num (mod_cast q.den_ne_zero) (mod_cast r.den_ne_zero) rw [num_divInt_den, num_divInt_den] at h rw [h, mul_comm, ← Rat.eq_iff_mul_eq_mul, ← divInt_eq_div] theorem add_num_den' (q r : ℚ) : (q + r).num * q.den * r.den = (q.num * r.den + r.num * q.den) * (q + r).den := by let s := divInt (q.num * r.den + r.num * q.den) (q.den * r.den : ℤ) have hs : (q.den * r.den : ℤ) ≠ 0 := Int.natCast_ne_zero_iff_pos.mpr (Nat.mul_pos q.pos r.pos) obtain ⟨c, ⟨c_mul_num, c_mul_den⟩⟩ := exists_eq_mul_div_num_and_eq_mul_div_den (q.num * r.den + r.num * q.den) hs rw [c_mul_num, mul_assoc, mul_comm] nth_rw 1 [c_mul_den] repeat rw [Int.mul_assoc] apply mul_eq_mul_left_iff.2 rw [or_iff_not_imp_right] intro have h : _ = s := divInt_add_divInt q.num r.num (mod_cast q.den_ne_zero) (mod_cast r.den_ne_zero) rw [num_divInt_den, num_divInt_den] at h rw [h] rw [mul_comm] apply Rat.eq_iff_mul_eq_mul.mp rw [← divInt_eq_div] theorem substr_num_den' (q r : ℚ) : (q - r).num * q.den * r.den = (q.num * r.den - r.num * q.den) * (q - r).den := by rw [sub_eq_add_neg, sub_eq_add_neg, ← neg_mul, ← num_neg_eq_neg_num, ← den_neg_eq_den r, add_num_den' q (-r)] end Casts protected theorem inv_neg (q : ℚ) : (-q)⁻¹ = -q⁻¹ := by rw [← num_divInt_den q] simp only [Rat.neg_divInt, Rat.inv_divInt', eq_self_iff_true, Rat.divInt_neg] theorem num_div_eq_of_coprime {a b : ℤ} (hb0 : 0 < b) (h : Nat.Coprime a.natAbs b.natAbs) : (a / b : ℚ).num = a := by lift b to ℕ using hb0.le simp only [Int.natAbs_natCast, Int.ofNat_pos] at h hb0 rw [← Rat.divInt_eq_div, ← mk_eq_divInt _ _ hb0.ne' h] theorem den_div_eq_of_coprime {a b : ℤ} (hb0 : 0 < b) (h : Nat.Coprime a.natAbs b.natAbs) : ((a / b : ℚ).den : ℤ) = b := by lift b to ℕ using hb0.le simp only [Int.natAbs_natCast, Int.ofNat_pos] at h hb0 rw [← Rat.divInt_eq_div, ← mk_eq_divInt _ _ hb0.ne' h] theorem div_int_inj {a b c d : ℤ} (hb0 : 0 < b) (hd0 : 0 < d) (h1 : Nat.Coprime a.natAbs b.natAbs) (h2 : Nat.Coprime c.natAbs d.natAbs) (h : (a : ℚ) / b = (c : ℚ) / d) : a = c ∧ b = d := by apply And.intro · rw [← num_div_eq_of_coprime hb0 h1, h, num_div_eq_of_coprime hd0 h2] · rw [← den_div_eq_of_coprime hb0 h1, h, den_div_eq_of_coprime hd0 h2] @[norm_cast] theorem intCast_div_self (n : ℤ) : ((n / n : ℤ) : ℚ) = n / n := by by_cases hn : n = 0 · subst hn simp only [Int.cast_zero, Int.zero_tdiv, zero_div, Int.ediv_zero] · have : (n : ℚ) ≠ 0 := by rwa [← coe_int_inj] at hn simp only [Int.ediv_self hn, Int.cast_one, Ne, not_false_iff, div_self this] @[norm_cast] theorem natCast_div_self (n : ℕ) : ((n / n : ℕ) : ℚ) = n / n := intCast_div_self n theorem intCast_div (a b : ℤ) (h : b ∣ a) : ((a / b : ℤ) : ℚ) = a / b := by rcases h with ⟨c, rfl⟩ rw [mul_comm b, Int.mul_ediv_assoc c (dvd_refl b), Int.cast_mul, intCast_div_self, Int.cast_mul, mul_div_assoc] theorem natCast_div (a b : ℕ) (h : b ∣ a) : ((a / b : ℕ) : ℚ) = a / b := intCast_div a b (Int.ofNat_dvd.mpr h) theorem den_div_intCast_eq_one_iff (m n : ℤ) (hn : n ≠ 0) : ((m : ℚ) / n).den = 1 ↔ n ∣ m := by replace hn : (n : ℚ) ≠ 0 := num_ne_zero.mp hn constructor · rw [Rat.den_eq_one_iff, eq_div_iff hn] exact mod_cast (Dvd.intro_left _) · exact (intCast_div _ _ · ▸ rfl) theorem den_div_natCast_eq_one_iff (m n : ℕ) (hn : n ≠ 0) : ((m : ℚ) / n).den = 1 ↔ n ∣ m := (den_div_intCast_eq_one_iff m n (Int.ofNat_ne_zero.mpr hn)).trans Int.ofNat_dvd theorem inv_intCast_num_of_pos {a : ℤ} (ha0 : 0 < a) : (a : ℚ)⁻¹.num = 1 := by rw [← ofInt_eq_cast, ofInt, mk_eq_divInt, Rat.inv_divInt', divInt_eq_div, Nat.cast_one] apply num_div_eq_of_coprime ha0 rw [Int.natAbs_one] exact Nat.coprime_one_left _ theorem inv_natCast_num_of_pos {a : ℕ} (ha0 : 0 < a) : (a : ℚ)⁻¹.num = 1 := inv_intCast_num_of_pos (mod_cast ha0 : 0 < (a : ℤ)) theorem inv_intCast_den_of_pos {a : ℤ} (ha0 : 0 < a) : ((a : ℚ)⁻¹.den : ℤ) = a := by rw [← ofInt_eq_cast, ofInt, mk_eq_divInt, Rat.inv_divInt', divInt_eq_div, Nat.cast_one] apply den_div_eq_of_coprime ha0 rw [Int.natAbs_one] exact Nat.coprime_one_left _ theorem inv_natCast_den_of_pos {a : ℕ} (ha0 : 0 < a) : (a : ℚ)⁻¹.den = a := by rw [← Int.ofNat_inj, ← Int.cast_natCast a, inv_intCast_den_of_pos] rwa [Int.natCast_pos] @[simp] theorem inv_intCast_num (a : ℤ) : (a : ℚ)⁻¹.num = Int.sign a := by rcases lt_trichotomy a 0 with lt | rfl | gt · obtain ⟨a, rfl⟩ : ∃ b, -b = a := ⟨-a, a.neg_neg⟩ simp at lt simp [Rat.inv_neg, inv_intCast_num_of_pos lt, Int.sign_eq_one_iff_pos.mpr lt] · simp · simp [inv_intCast_num_of_pos gt, Int.sign_eq_one_iff_pos.mpr gt] @[simp] theorem inv_natCast_num (a : ℕ) : (a : ℚ)⁻¹.num = Int.sign a := inv_intCast_num a @[simp] theorem inv_ofNat_num (a : ℕ) [a.AtLeastTwo] : (ofNat(a) : ℚ)⁻¹.num = 1 := inv_natCast_num_of_pos (Nat.pos_of_neZero a) @[simp] theorem inv_intCast_den (a : ℤ) : (a : ℚ)⁻¹.den = if a = 0 then 1 else a.natAbs := by rw [← Int.ofNat_inj] rcases lt_trichotomy a 0 with lt | rfl | gt · obtain ⟨a, rfl⟩ : ∃ b, -b = a := ⟨-a, a.neg_neg⟩ simp at lt rw [if_neg (by omega)] simp only [Int.cast_neg, Rat.inv_neg, neg_den, inv_intCast_den_of_pos lt, Int.natAbs_neg] exact Int.eq_natAbs_of_nonneg (by omega) · simp · rw [if_neg (by omega)] simp only [inv_intCast_den_of_pos gt] exact Int.eq_natAbs_of_nonneg (by omega) @[simp] theorem inv_natCast_den (a : ℕ) : (a : ℚ)⁻¹.den = if a = 0 then 1 else a := by simpa [-inv_intCast_den, ofInt_eq_cast] using inv_intCast_den a @[simp] theorem inv_ofNat_den (a : ℕ) [a.AtLeastTwo] : (ofNat(a) : ℚ)⁻¹.den = OfNat.ofNat a := inv_natCast_den_of_pos (Nat.pos_of_neZero a) protected theorem «forall» {p : ℚ → Prop} : (∀ r, p r) ↔ ∀ a b : ℤ, p (a / b) := ⟨fun h _ _ => h _, fun h q => by have := h q.num q.den rwa [Int.cast_natCast, num_div_den q] at this⟩ protected theorem «exists» {p : ℚ → Prop} : (∃ r, p r) ↔ ∃ a b : ℤ, p (a / b) := ⟨fun ⟨r, hr⟩ => ⟨r.num, r.den, by convert hr; convert num_div_den r⟩, fun ⟨_, _, h⟩ => ⟨_, h⟩⟩ /-! ### Denominator as `ℕ+` -/ section PNatDen /-- Denominator as `ℕ+`. -/ def pnatDen (x : ℚ) : ℕ+ := ⟨x.den, x.pos⟩ @[simp] theorem coe_pnatDen (x : ℚ) : (x.pnatDen : ℕ) = x.den := rfl theorem pnatDen_eq_iff_den_eq {x : ℚ} {n : ℕ+} : x.pnatDen = n ↔ x.den = ↑n :=
Subtype.ext_iff
Mathlib/Data/Rat/Lemmas.lean
316
317
/- Copyright (c) 2019 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen, Lu-Ming Zhang -/ import Mathlib.Data.Matrix.Invertible import Mathlib.Data.Matrix.Kronecker import Mathlib.LinearAlgebra.FiniteDimensional.Basic import Mathlib.LinearAlgebra.Matrix.Adjugate import Mathlib.LinearAlgebra.Matrix.SemiringInverse import Mathlib.LinearAlgebra.Matrix.ToLin import Mathlib.LinearAlgebra.Matrix.Trace /-! # Nonsingular inverses In this file, we define an inverse for square matrices of invertible determinant. For matrices that are not square or not of full rank, there is a more general notion of pseudoinverses which we do not consider here. The definition of inverse used in this file is the adjugate divided by the determinant. We show that dividing the adjugate by `det A` (if possible), giving a matrix `A⁻¹` (`nonsing_inv`), will result in a multiplicative inverse to `A`. Note that there are at least three different inverses in mathlib: * `A⁻¹` (`Inv.inv`): alone, this satisfies no properties, although it is usually used in conjunction with `Group` or `GroupWithZero`. On matrices, this is defined to be zero when no inverse exists. * `⅟A` (`invOf`): this is only available in the presence of `[Invertible A]`, which guarantees an inverse exists. * `Ring.inverse A`: this is defined on any `MonoidWithZero`, and just like `⁻¹` on matrices, is defined to be zero when no inverse exists. We start by working with `Invertible`, and show the main results: * `Matrix.invertibleOfDetInvertible` * `Matrix.detInvertibleOfInvertible` * `Matrix.isUnit_iff_isUnit_det` * `Matrix.mul_eq_one_comm` After this we define `Matrix.inv` and show it matches `⅟A` and `Ring.inverse A`. The rest of the results in the file are then about `A⁻¹` ## References * https://en.wikipedia.org/wiki/Cramer's_rule#Finding_inverse_matrix ## Tags matrix inverse, cramer, cramer's rule, adjugate -/ namespace Matrix universe u u' v variable {l : Type*} {m : Type u} {n : Type u'} {α : Type v} open Matrix Equiv Equiv.Perm Finset /-! ### Matrices are `Invertible` iff their determinants are -/ section Invertible variable [Fintype n] [DecidableEq n] [CommRing α] variable (A : Matrix n n α) (B : Matrix n n α) /-- If `A.det` has a constructive inverse, produce one for `A`. -/ def invertibleOfDetInvertible [Invertible A.det] : Invertible A where invOf := ⅟ A.det • A.adjugate mul_invOf_self := by rw [mul_smul_comm, mul_adjugate, smul_smul, invOf_mul_self, one_smul] invOf_mul_self := by rw [smul_mul_assoc, adjugate_mul, smul_smul, invOf_mul_self, one_smul] theorem invOf_eq [Invertible A.det] [Invertible A] : ⅟ A = ⅟ A.det • A.adjugate := by letI := invertibleOfDetInvertible A convert (rfl : ⅟ A = _) /-- `A.det` is invertible if `A` has a left inverse. -/ def detInvertibleOfLeftInverse (h : B * A = 1) : Invertible A.det where invOf := B.det mul_invOf_self := by rw [mul_comm, ← det_mul, h, det_one] invOf_mul_self := by rw [← det_mul, h, det_one] /-- `A.det` is invertible if `A` has a right inverse. -/ def detInvertibleOfRightInverse (h : A * B = 1) : Invertible A.det where invOf := B.det mul_invOf_self := by rw [← det_mul, h, det_one] invOf_mul_self := by rw [mul_comm, ← det_mul, h, det_one] /-- If `A` has a constructive inverse, produce one for `A.det`. -/ def detInvertibleOfInvertible [Invertible A] : Invertible A.det := detInvertibleOfLeftInverse A (⅟ A) (invOf_mul_self _) theorem det_invOf [Invertible A] [Invertible A.det] : (⅟ A).det = ⅟ A.det := by letI := detInvertibleOfInvertible A convert (rfl : _ = ⅟ A.det) /-- Together `Matrix.detInvertibleOfInvertible` and `Matrix.invertibleOfDetInvertible` form an equivalence, although both sides of the equiv are subsingleton anyway. -/ @[simps] def invertibleEquivDetInvertible : Invertible A ≃ Invertible A.det where toFun := @detInvertibleOfInvertible _ _ _ _ _ A invFun := @invertibleOfDetInvertible _ _ _ _ _ A left_inv _ := Subsingleton.elim _ _ right_inv _ := Subsingleton.elim _ _ /-- Given a proof that `A.det` has a constructive inverse, lift `A` to `(Matrix n n α)ˣ` -/ def unitOfDetInvertible [Invertible A.det] : (Matrix n n α)ˣ := @unitOfInvertible _ _ A (invertibleOfDetInvertible A) /-- When lowered to a prop, `Matrix.invertibleEquivDetInvertible` forms an `iff`. -/ theorem isUnit_iff_isUnit_det : IsUnit A ↔ IsUnit A.det := by simp only [← nonempty_invertible_iff_isUnit, (invertibleEquivDetInvertible A).nonempty_congr] @[simp] theorem isUnits_det_units (A : (Matrix n n α)ˣ) : IsUnit (A : Matrix n n α).det := isUnit_iff_isUnit_det _ |>.mp A.isUnit /-! #### Variants of the statements above with `IsUnit` -/ theorem isUnit_det_of_invertible [Invertible A] : IsUnit A.det := @isUnit_of_invertible _ _ _ (detInvertibleOfInvertible A) variable {A B} theorem isUnit_det_of_left_inverse (h : B * A = 1) : IsUnit A.det := @isUnit_of_invertible _ _ _ (detInvertibleOfLeftInverse _ _ h) theorem isUnit_det_of_right_inverse (h : A * B = 1) : IsUnit A.det := @isUnit_of_invertible _ _ _ (detInvertibleOfRightInverse _ _ h) theorem det_ne_zero_of_left_inverse [Nontrivial α] (h : B * A = 1) : A.det ≠ 0 := (isUnit_det_of_left_inverse h).ne_zero theorem det_ne_zero_of_right_inverse [Nontrivial α] (h : A * B = 1) : A.det ≠ 0 := (isUnit_det_of_right_inverse h).ne_zero end Invertible section Inv variable [Fintype n] [DecidableEq n] [CommRing α] variable (A : Matrix n n α) (B : Matrix n n α) theorem isUnit_det_transpose (h : IsUnit A.det) : IsUnit Aᵀ.det := by rw [det_transpose] exact h /-! ### A noncomputable `Inv` instance -/ /-- The inverse of a square matrix, when it is invertible (and zero otherwise). -/ noncomputable instance inv : Inv (Matrix n n α) := ⟨fun A => Ring.inverse A.det • A.adjugate⟩ theorem inv_def (A : Matrix n n α) : A⁻¹ = Ring.inverse A.det • A.adjugate := rfl theorem nonsing_inv_apply_not_isUnit (h : ¬IsUnit A.det) : A⁻¹ = 0 := by rw [inv_def, Ring.inverse_non_unit _ h, zero_smul] theorem nonsing_inv_apply (h : IsUnit A.det) : A⁻¹ = (↑h.unit⁻¹ : α) • A.adjugate := by rw [inv_def, ← Ring.inverse_unit h.unit, IsUnit.unit_spec] /-- The nonsingular inverse is the same as `invOf` when `A` is invertible. -/ @[simp] theorem invOf_eq_nonsing_inv [Invertible A] : ⅟ A = A⁻¹ := by letI := detInvertibleOfInvertible A rw [inv_def, Ring.inverse_invertible, invOf_eq] /-- Coercing the result of `Units.instInv` is the same as coercing first and applying the nonsingular inverse. -/ @[simp, norm_cast] theorem coe_units_inv (A : (Matrix n n α)ˣ) : ↑A⁻¹ = (A⁻¹ : Matrix n n α) := by letI := A.invertible rw [← invOf_eq_nonsing_inv, invOf_units] /-- The nonsingular inverse is the same as the general `Ring.inverse`. -/ theorem nonsing_inv_eq_ringInverse : A⁻¹ = Ring.inverse A := by by_cases h_det : IsUnit A.det · cases (A.isUnit_iff_isUnit_det.mpr h_det).nonempty_invertible rw [← invOf_eq_nonsing_inv, Ring.inverse_invertible] · have h := mt A.isUnit_iff_isUnit_det.mp h_det rw [Ring.inverse_non_unit _ h, nonsing_inv_apply_not_isUnit A h_det] @[deprecated (since := "2025-04-22")] alias nonsing_inv_eq_ring_inverse := nonsing_inv_eq_ringInverse theorem transpose_nonsing_inv : A⁻¹ᵀ = Aᵀ⁻¹ := by rw [inv_def, inv_def, transpose_smul, det_transpose, adjugate_transpose] theorem conjTranspose_nonsing_inv [StarRing α] : A⁻¹ᴴ = Aᴴ⁻¹ := by rw [inv_def, inv_def, conjTranspose_smul, det_conjTranspose, adjugate_conjTranspose, Ring.inverse_star] /-- The `nonsing_inv` of `A` is a right inverse. -/ @[simp] theorem mul_nonsing_inv (h : IsUnit A.det) : A * A⁻¹ = 1 := by cases (A.isUnit_iff_isUnit_det.mpr h).nonempty_invertible rw [← invOf_eq_nonsing_inv, mul_invOf_self] /-- The `nonsing_inv` of `A` is a left inverse. -/ @[simp] theorem nonsing_inv_mul (h : IsUnit A.det) : A⁻¹ * A = 1 := by cases (A.isUnit_iff_isUnit_det.mpr h).nonempty_invertible rw [← invOf_eq_nonsing_inv, invOf_mul_self] instance [Invertible A] : Invertible A⁻¹ := by rw [← invOf_eq_nonsing_inv] infer_instance @[simp] theorem inv_inv_of_invertible [Invertible A] : A⁻¹⁻¹ = A := by simp only [← invOf_eq_nonsing_inv, invOf_invOf] @[simp] theorem mul_nonsing_inv_cancel_right (B : Matrix m n α) (h : IsUnit A.det) : B * A * A⁻¹ = B := by simp [Matrix.mul_assoc, mul_nonsing_inv A h] @[simp] theorem mul_nonsing_inv_cancel_left (B : Matrix n m α) (h : IsUnit A.det) : A * (A⁻¹ * B) = B := by simp [← Matrix.mul_assoc, mul_nonsing_inv A h] @[simp] theorem nonsing_inv_mul_cancel_right (B : Matrix m n α) (h : IsUnit A.det) : B * A⁻¹ * A = B := by simp [Matrix.mul_assoc, nonsing_inv_mul A h] @[simp] theorem nonsing_inv_mul_cancel_left (B : Matrix n m α) (h : IsUnit A.det) : A⁻¹ * (A * B) = B := by simp [← Matrix.mul_assoc, nonsing_inv_mul A h] @[simp] theorem mul_inv_of_invertible [Invertible A] : A * A⁻¹ = 1 := mul_nonsing_inv A (isUnit_det_of_invertible A) @[simp] theorem inv_mul_of_invertible [Invertible A] : A⁻¹ * A = 1 := nonsing_inv_mul A (isUnit_det_of_invertible A) @[simp] theorem mul_inv_cancel_right_of_invertible (B : Matrix m n α) [Invertible A] : B * A * A⁻¹ = B := mul_nonsing_inv_cancel_right A B (isUnit_det_of_invertible A) @[simp] theorem mul_inv_cancel_left_of_invertible (B : Matrix n m α) [Invertible A] : A * (A⁻¹ * B) = B := mul_nonsing_inv_cancel_left A B (isUnit_det_of_invertible A) @[simp] theorem inv_mul_cancel_right_of_invertible (B : Matrix m n α) [Invertible A] : B * A⁻¹ * A = B := nonsing_inv_mul_cancel_right A B (isUnit_det_of_invertible A) @[simp] theorem inv_mul_cancel_left_of_invertible (B : Matrix n m α) [Invertible A] : A⁻¹ * (A * B) = B := nonsing_inv_mul_cancel_left A B (isUnit_det_of_invertible A) theorem inv_mul_eq_iff_eq_mul_of_invertible (A B C : Matrix n n α) [Invertible A] : A⁻¹ * B = C ↔ B = A * C := ⟨fun h => by rw [← h, mul_inv_cancel_left_of_invertible], fun h => by rw [h, inv_mul_cancel_left_of_invertible]⟩ theorem mul_inv_eq_iff_eq_mul_of_invertible (A B C : Matrix n n α) [Invertible A] : B * A⁻¹ = C ↔ B = C * A := ⟨fun h => by rw [← h, inv_mul_cancel_right_of_invertible], fun h => by rw [h, mul_inv_cancel_right_of_invertible]⟩ lemma inv_mulVec_eq_vec {A : Matrix n n α} [Invertible A] {u v : n → α} (hM : u = A.mulVec v) : A⁻¹.mulVec u = v := by rw [hM, Matrix.mulVec_mulVec, Matrix.inv_mul_of_invertible, Matrix.one_mulVec] lemma mul_right_injective_of_invertible [Invertible A] : Function.Injective (fun (x : Matrix n m α) => A * x) := fun _ _ h => by simpa only [inv_mul_cancel_left_of_invertible] using congr_arg (A⁻¹ * ·) h lemma mul_left_injective_of_invertible [Invertible A] : Function.Injective (fun (x : Matrix m n α) => x * A) := fun a x hax => by simpa only [mul_inv_cancel_right_of_invertible] using congr_arg (· * A⁻¹) hax lemma mul_right_inj_of_invertible [Invertible A] {x y : Matrix n m α} : A * x = A * y ↔ x = y := (mul_right_injective_of_invertible A).eq_iff lemma mul_left_inj_of_invertible [Invertible A] {x y : Matrix m n α} : x * A = y * A ↔ x = y := (mul_left_injective_of_invertible A).eq_iff end Inv section InjectiveMul variable [Fintype n] [Fintype m] [DecidableEq m] [CommRing α] lemma mul_left_injective_of_inv (A : Matrix m n α) (B : Matrix n m α) (h : A * B = 1) : Function.Injective (fun x : Matrix l m α => x * A) := fun _ _ g => by simpa only [Matrix.mul_assoc, Matrix.mul_one, h] using congr_arg (· * B) g lemma mul_right_injective_of_inv (A : Matrix m n α) (B : Matrix n m α) (h : A * B = 1) : Function.Injective (fun x : Matrix m l α => B * x) := fun _ _ g => by simpa only [← Matrix.mul_assoc, Matrix.one_mul, h] using congr_arg (A * ·) g end InjectiveMul section vecMul section Semiring variable {R : Type*} [Semiring R] theorem vecMul_surjective_iff_exists_left_inverse [DecidableEq n] [Fintype m] [Finite n] {A : Matrix m n R} : Function.Surjective A.vecMul ↔ ∃ B : Matrix n m R, B * A = 1 := by cases nonempty_fintype n refine ⟨fun h ↦ ?_, fun ⟨B, hBA⟩ y ↦ ⟨y ᵥ* B, by simp [hBA]⟩⟩ choose rows hrows using (h <| Pi.single · 1) refine ⟨Matrix.of rows, Matrix.ext fun i j => ?_⟩ rw [mul_apply_eq_vecMul, one_eq_pi_single, ← hrows] rfl theorem mulVec_surjective_iff_exists_right_inverse [DecidableEq m] [Finite m] [Fintype n] {A : Matrix m n R} : Function.Surjective A.mulVec ↔ ∃ B : Matrix n m R, A * B = 1 := by cases nonempty_fintype m refine ⟨fun h ↦ ?_, fun ⟨B, hBA⟩ y ↦ ⟨B *ᵥ y, by simp [hBA]⟩⟩ choose cols hcols using (h <| Pi.single · 1) refine ⟨(Matrix.of cols)ᵀ, Matrix.ext fun i j ↦ ?_⟩ rw [one_eq_pi_single, Pi.single_comm, ← hcols j] rfl end Semiring variable [DecidableEq m] {R K : Type*} [CommRing R] [Field K] [Fintype m] theorem vecMul_surjective_iff_isUnit {A : Matrix m m R} : Function.Surjective A.vecMul ↔ IsUnit A := by rw [vecMul_surjective_iff_exists_left_inverse, exists_left_inverse_iff_isUnit] theorem mulVec_surjective_iff_isUnit {A : Matrix m m R} : Function.Surjective A.mulVec ↔ IsUnit A := by rw [mulVec_surjective_iff_exists_right_inverse, exists_right_inverse_iff_isUnit] theorem vecMul_injective_iff_isUnit {A : Matrix m m K} : Function.Injective A.vecMul ↔ IsUnit A := by refine ⟨fun h ↦ ?_, fun h ↦ ?_⟩ · rw [← vecMul_surjective_iff_isUnit] exact LinearMap.surjective_of_injective (f := A.vecMulLinear) h change Function.Injective A.vecMulLinear rw [← LinearMap.ker_eq_bot, LinearMap.ker_eq_bot'] intro c hc replace h := h.invertible simpa using congr_arg A⁻¹.vecMulLinear hc theorem mulVec_injective_iff_isUnit {A : Matrix m m K} : Function.Injective A.mulVec ↔ IsUnit A := by rw [← isUnit_transpose, ← vecMul_injective_iff_isUnit] simp_rw [vecMul_transpose] theorem linearIndependent_rows_iff_isUnit {A : Matrix m m K} : LinearIndependent K A.row ↔ IsUnit A := by rw [← col_transpose, ← mulVec_injective_iff, ← coe_mulVecLin, mulVecLin_transpose, ← vecMul_injective_iff_isUnit, coe_vecMulLinear] theorem linearIndependent_cols_iff_isUnit {A : Matrix m m K} : LinearIndependent K A.col ↔ IsUnit A := by rw [← row_transpose, linearIndependent_rows_iff_isUnit, isUnit_transpose] theorem vecMul_surjective_of_invertible (A : Matrix m m R) [Invertible A] : Function.Surjective A.vecMul := vecMul_surjective_iff_isUnit.2 <| isUnit_of_invertible A theorem mulVec_surjective_of_invertible (A : Matrix m m R) [Invertible A] : Function.Surjective A.mulVec := mulVec_surjective_iff_isUnit.2 <| isUnit_of_invertible A theorem vecMul_injective_of_invertible (A : Matrix m m K) [Invertible A] : Function.Injective A.vecMul := vecMul_injective_iff_isUnit.2 <| isUnit_of_invertible A theorem mulVec_injective_of_invertible (A : Matrix m m K) [Invertible A] : Function.Injective A.mulVec := mulVec_injective_iff_isUnit.2 <| isUnit_of_invertible A theorem linearIndependent_rows_of_invertible (A : Matrix m m K) [Invertible A] : LinearIndependent K A.row := linearIndependent_rows_iff_isUnit.2 <| isUnit_of_invertible A theorem linearIndependent_cols_of_invertible (A : Matrix m m K) [Invertible A] : LinearIndependent K A.col := linearIndependent_cols_iff_isUnit.2 <| isUnit_of_invertible A end vecMul variable [Fintype n] [DecidableEq n] [CommRing α] variable (A : Matrix n n α) (B : Matrix n n α) theorem nonsing_inv_cancel_or_zero : A⁻¹ * A = 1 ∧ A * A⁻¹ = 1 ∨ A⁻¹ = 0 := by by_cases h : IsUnit A.det · exact Or.inl ⟨nonsing_inv_mul _ h, mul_nonsing_inv _ h⟩ · exact Or.inr (nonsing_inv_apply_not_isUnit _ h) theorem det_nonsing_inv_mul_det (h : IsUnit A.det) : A⁻¹.det * A.det = 1 := by rw [← det_mul, A.nonsing_inv_mul h, det_one] @[simp] theorem det_nonsing_inv : A⁻¹.det = Ring.inverse A.det := by by_cases h : IsUnit A.det · cases h.nonempty_invertible letI := invertibleOfDetInvertible A rw [Ring.inverse_invertible, ← invOf_eq_nonsing_inv, det_invOf] cases isEmpty_or_nonempty n · rw [det_isEmpty, det_isEmpty, Ring.inverse_one] · rw [Ring.inverse_non_unit _ h, nonsing_inv_apply_not_isUnit _ h, det_zero ‹_›] theorem isUnit_nonsing_inv_det (h : IsUnit A.det) : IsUnit A⁻¹.det := isUnit_of_mul_eq_one _ _ (A.det_nonsing_inv_mul_det h) @[simp] theorem nonsing_inv_nonsing_inv (h : IsUnit A.det) : A⁻¹⁻¹ = A := calc A⁻¹⁻¹ = 1 * A⁻¹⁻¹ := by rw [Matrix.one_mul] _ = A * A⁻¹ * A⁻¹⁻¹ := by rw [A.mul_nonsing_inv h] _ = A := by rw [Matrix.mul_assoc, A⁻¹.mul_nonsing_inv (A.isUnit_nonsing_inv_det h), Matrix.mul_one] theorem isUnit_nonsing_inv_det_iff {A : Matrix n n α} : IsUnit A⁻¹.det ↔ IsUnit A.det := by rw [Matrix.det_nonsing_inv, isUnit_ringInverse] @[simp] theorem isUnit_nonsing_inv_iff {A : Matrix n n α} : IsUnit A⁻¹ ↔ IsUnit A := by simp_rw [isUnit_iff_isUnit_det, isUnit_nonsing_inv_det_iff] -- `IsUnit.invertible` lifts the proposition `IsUnit A` to a constructive inverse of `A`. /-- A version of `Matrix.invertibleOfDetInvertible` with the inverse defeq to `A⁻¹` that is therefore noncomputable. -/ noncomputable def invertibleOfIsUnitDet (h : IsUnit A.det) : Invertible A := ⟨A⁻¹, nonsing_inv_mul A h, mul_nonsing_inv A h⟩ /-- A version of `Matrix.unitOfDetInvertible` with the inverse defeq to `A⁻¹` that is therefore noncomputable. -/ noncomputable def nonsingInvUnit (h : IsUnit A.det) : (Matrix n n α)ˣ := @unitOfInvertible _ _ _ (invertibleOfIsUnitDet A h) theorem unitOfDetInvertible_eq_nonsingInvUnit [Invertible A.det] : unitOfDetInvertible A = nonsingInvUnit A (isUnit_of_invertible _) := by ext rfl variable {A} {B} /-- If matrix A is left invertible, then its inverse equals its left inverse. -/ theorem inv_eq_left_inv (h : B * A = 1) : A⁻¹ = B := letI := invertibleOfLeftInverse _ _ h invOf_eq_nonsing_inv A ▸ invOf_eq_left_inv h /-- If matrix A is right invertible, then its inverse equals its right inverse. -/ theorem inv_eq_right_inv (h : A * B = 1) : A⁻¹ = B := inv_eq_left_inv (mul_eq_one_comm.2 h) section InvEqInv variable {C : Matrix n n α} /-- The left inverse of matrix A is unique when existing. -/ theorem left_inv_eq_left_inv (h : B * A = 1) (g : C * A = 1) : B = C := by rw [← inv_eq_left_inv h, ← inv_eq_left_inv g] /-- The right inverse of matrix A is unique when existing. -/ theorem right_inv_eq_right_inv (h : A * B = 1) (g : A * C = 1) : B = C := by rw [← inv_eq_right_inv h, ← inv_eq_right_inv g] /-- The right inverse of matrix A equals the left inverse of A when they exist. -/ theorem right_inv_eq_left_inv (h : A * B = 1) (g : C * A = 1) : B = C := by rw [← inv_eq_right_inv h, ← inv_eq_left_inv g] theorem inv_inj (h : A⁻¹ = B⁻¹) (h' : IsUnit A.det) : A = B := by refine left_inv_eq_left_inv (mul_nonsing_inv _ h') ?_ rw [h] refine mul_nonsing_inv _ ?_ rwa [← isUnit_nonsing_inv_det_iff, ← h, isUnit_nonsing_inv_det_iff] end InvEqInv variable (A) @[simp] theorem inv_zero : (0 : Matrix n n α)⁻¹ = 0 := by rcases subsingleton_or_nontrivial α with ht | ht · simp [eq_iff_true_of_subsingleton] rcases (Fintype.card n).zero_le.eq_or_lt with hc | hc · rw [eq_comm, Fintype.card_eq_zero_iff] at hc haveI := hc ext i exact (IsEmpty.false i).elim · have hn : Nonempty n := Fintype.card_pos_iff.mp hc refine nonsing_inv_apply_not_isUnit _ ?_ simp [hn] noncomputable instance : InvOneClass (Matrix n n α) := { Matrix.one, Matrix.inv with inv_one := inv_eq_left_inv (by simp) } theorem inv_smul (k : α) [Invertible k] (h : IsUnit A.det) : (k • A)⁻¹ = ⅟ k • A⁻¹ := inv_eq_left_inv (by simp [h, smul_smul]) theorem inv_smul' (k : αˣ) (h : IsUnit A.det) : (k • A)⁻¹ = k⁻¹ • A⁻¹ := inv_eq_left_inv (by simp [h, smul_smul]) theorem inv_adjugate (A : Matrix n n α) (h : IsUnit A.det) : (adjugate A)⁻¹ = h.unit⁻¹ • A := by refine inv_eq_left_inv ?_ rw [smul_mul, mul_adjugate, Units.smul_def, smul_smul, h.val_inv_mul, one_smul] section Diagonal /-- `diagonal v` is invertible if `v` is -/ def diagonalInvertible {α} [NonAssocSemiring α] (v : n → α) [Invertible v] : Invertible (diagonal v) := Invertible.map (diagonalRingHom n α) v theorem invOf_diagonal_eq {α} [Semiring α] (v : n → α) [Invertible v] [Invertible (diagonal v)] : ⅟ (diagonal v) = diagonal (⅟ v) := by rw [@Invertible.congr _ _ _ _ _ (diagonalInvertible v) rfl] rfl /-- `v` is invertible if `diagonal v` is -/ def invertibleOfDiagonalInvertible (v : n → α) [Invertible (diagonal v)] : Invertible v where invOf := diag (⅟ (diagonal v)) invOf_mul_self := funext fun i => by letI : Invertible (diagonal v).det := detInvertibleOfInvertible _ rw [invOf_eq, diag_smul, adjugate_diagonal, diag_diagonal] dsimp rw [mul_assoc, prod_erase_mul _ _ (Finset.mem_univ _), ← det_diagonal] exact mul_invOf_self _ mul_invOf_self := funext fun i => by letI : Invertible (diagonal v).det := detInvertibleOfInvertible _ rw [invOf_eq, diag_smul, adjugate_diagonal, diag_diagonal] dsimp rw [mul_left_comm, mul_prod_erase _ _ (Finset.mem_univ _), ← det_diagonal] exact mul_invOf_self _ /-- Together `Matrix.diagonalInvertible` and `Matrix.invertibleOfDiagonalInvertible` form an equivalence, although both sides of the equiv are subsingleton anyway. -/ @[simps] def diagonalInvertibleEquivInvertible (v : n → α) : Invertible (diagonal v) ≃ Invertible v where toFun := @invertibleOfDiagonalInvertible _ _ _ _ _ _ invFun := @diagonalInvertible _ _ _ _ _ _ left_inv _ := Subsingleton.elim _ _ right_inv _ := Subsingleton.elim _ _
/-- When lowered to a prop, `Matrix.diagonalInvertibleEquivInvertible` forms an `iff`. -/
Mathlib/LinearAlgebra/Matrix/NonsingularInverse.lean
551
552
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import Mathlib.Topology.Algebra.Constructions import Mathlib.Topology.Bases import Mathlib.Algebra.Order.Group.Nat import Mathlib.Topology.UniformSpace.Basic /-! # Theory of Cauchy filters in uniform spaces. Complete uniform spaces. Totally bounded subsets. -/ universe u v open Filter Function TopologicalSpace Topology Set UniformSpace Uniformity variable {α : Type u} {β : Type v} [uniformSpace : UniformSpace α] /-- A filter `f` is Cauchy if for every entourage `r`, there exists an `s ∈ f` such that `s × s ⊆ r`. This is a generalization of Cauchy sequences, because if `a : ℕ → α` then the filter of sets containing cofinitely many of the `a n` is Cauchy iff `a` is a Cauchy sequence. -/ def Cauchy (f : Filter α) := NeBot f ∧ f ×ˢ f ≤ 𝓤 α /-- A set `s` is called *complete*, if any Cauchy filter `f` such that `s ∈ f` has a limit in `s` (formally, it satisfies `f ≤ 𝓝 x` for some `x ∈ s`). -/ def IsComplete (s : Set α) := ∀ f, Cauchy f → f ≤ 𝓟 s → ∃ x ∈ s, f ≤ 𝓝 x theorem Filter.HasBasis.cauchy_iff {ι} {p : ι → Prop} {s : ι → Set (α × α)} (h : (𝓤 α).HasBasis p s) {f : Filter α} : Cauchy f ↔ NeBot f ∧ ∀ i, p i → ∃ t ∈ f, ∀ x ∈ t, ∀ y ∈ t, (x, y) ∈ s i := and_congr Iff.rfl <| (f.basis_sets.prod_self.le_basis_iff h).trans <| by simp only [subset_def, Prod.forall, mem_prod_eq, and_imp, id, forall_mem_comm] theorem cauchy_iff' {f : Filter α} : Cauchy f ↔ NeBot f ∧ ∀ s ∈ 𝓤 α, ∃ t ∈ f, ∀ x ∈ t, ∀ y ∈ t, (x, y) ∈ s := (𝓤 α).basis_sets.cauchy_iff theorem cauchy_iff {f : Filter α} : Cauchy f ↔ NeBot f ∧ ∀ s ∈ 𝓤 α, ∃ t ∈ f, t ×ˢ t ⊆ s := cauchy_iff'.trans <| by simp only [subset_def, Prod.forall, mem_prod_eq, and_imp, id, forall_mem_comm] lemma cauchy_iff_le {l : Filter α} [hl : l.NeBot] : Cauchy l ↔ l ×ˢ l ≤ 𝓤 α := by simp only [Cauchy, hl, true_and] theorem Cauchy.ultrafilter_of {l : Filter α} (h : Cauchy l) : Cauchy (@Ultrafilter.of _ l h.1 : Filter α) := by haveI := h.1 have := Ultrafilter.of_le l exact ⟨Ultrafilter.neBot _, (Filter.prod_mono this this).trans h.2⟩ theorem cauchy_map_iff {l : Filter β} {f : β → α} : Cauchy (l.map f) ↔ NeBot l ∧ Tendsto (fun p : β × β => (f p.1, f p.2)) (l ×ˢ l) (𝓤 α) := by rw [Cauchy, map_neBot_iff, prod_map_map_eq, Tendsto] theorem cauchy_map_iff' {l : Filter β} [hl : NeBot l] {f : β → α} : Cauchy (l.map f) ↔ Tendsto (fun p : β × β => (f p.1, f p.2)) (l ×ˢ l) (𝓤 α) := cauchy_map_iff.trans <| and_iff_right hl theorem Cauchy.mono {f g : Filter α} [hg : NeBot g] (h_c : Cauchy f) (h_le : g ≤ f) : Cauchy g := ⟨hg, le_trans (Filter.prod_mono h_le h_le) h_c.right⟩ theorem Cauchy.mono' {f g : Filter α} (h_c : Cauchy f) (_ : NeBot g) (h_le : g ≤ f) : Cauchy g := h_c.mono h_le theorem cauchy_nhds {a : α} : Cauchy (𝓝 a) := ⟨nhds_neBot, nhds_prod_eq.symm.trans_le (nhds_le_uniformity a)⟩ theorem cauchy_pure {a : α} : Cauchy (pure a) := cauchy_nhds.mono (pure_le_nhds a) theorem Filter.Tendsto.cauchy_map {l : Filter β} [NeBot l] {f : β → α} {a : α} (h : Tendsto f l (𝓝 a)) : Cauchy (map f l) := cauchy_nhds.mono h lemma Cauchy.mono_uniformSpace {u v : UniformSpace β} {F : Filter β} (huv : u ≤ v) (hF : Cauchy (uniformSpace := u) F) : Cauchy (uniformSpace := v) F := ⟨hF.1, hF.2.trans huv⟩ lemma cauchy_inf_uniformSpace {u v : UniformSpace β} {F : Filter β} : Cauchy (uniformSpace := u ⊓ v) F ↔ Cauchy (uniformSpace := u) F ∧ Cauchy (uniformSpace := v) F := by unfold Cauchy rw [inf_uniformity (u := u), le_inf_iff, and_and_left] lemma cauchy_iInf_uniformSpace {ι : Sort*} [Nonempty ι] {u : ι → UniformSpace β} {l : Filter β} : Cauchy (uniformSpace := ⨅ i, u i) l ↔ ∀ i, Cauchy (uniformSpace := u i) l := by unfold Cauchy rw [iInf_uniformity, le_iInf_iff, forall_and, forall_const] lemma cauchy_iInf_uniformSpace' {ι : Sort*} {u : ι → UniformSpace β} {l : Filter β} [l.NeBot] : Cauchy (uniformSpace := ⨅ i, u i) l ↔ ∀ i, Cauchy (uniformSpace := u i) l := by simp_rw [cauchy_iff_le (uniformSpace := _), iInf_uniformity, le_iInf_iff] lemma cauchy_comap_uniformSpace {u : UniformSpace β} {α} {f : α → β} {l : Filter α} : Cauchy (uniformSpace := comap f u) l ↔ Cauchy (map f l) := by simp only [Cauchy, map_neBot_iff, prod_map_map_eq, map_le_iff_le_comap] rfl lemma cauchy_prod_iff [UniformSpace β] {F : Filter (α × β)} : Cauchy F ↔ Cauchy (map Prod.fst F) ∧ Cauchy (map Prod.snd F) := by simp_rw [instUniformSpaceProd, ← cauchy_comap_uniformSpace, ← cauchy_inf_uniformSpace] theorem Cauchy.prod [UniformSpace β] {f : Filter α} {g : Filter β} (hf : Cauchy f) (hg : Cauchy g) : Cauchy (f ×ˢ g) := by have := hf.1; have := hg.1 simpa [cauchy_prod_iff, hf.1] using ⟨hf, hg⟩ /-- The common part of the proofs of `le_nhds_of_cauchy_adhp` and `SequentiallyComplete.le_nhds_of_seq_tendsto_nhds`: if for any entourage `s` one can choose a set `t ∈ f` of diameter `s` such that it contains a point `y` with `(x, y) ∈ s`, then `f` converges to `x`. -/ theorem le_nhds_of_cauchy_adhp_aux {f : Filter α} {x : α} (adhs : ∀ s ∈ 𝓤 α, ∃ t ∈ f, t ×ˢ t ⊆ s ∧ ∃ y, (x, y) ∈ s ∧ y ∈ t) : f ≤ 𝓝 x := by -- Consider a neighborhood `s` of `x` intro s hs -- Take an entourage twice smaller than `s` rcases comp_mem_uniformity_sets (mem_nhds_uniformity_iff_right.1 hs) with ⟨U, U_mem, hU⟩ -- Take a set `t ∈ f`, `t × t ⊆ U`, and a point `y ∈ t` such that `(x, y) ∈ U` rcases adhs U U_mem with ⟨t, t_mem, ht, y, hxy, hy⟩ apply mem_of_superset t_mem -- Given a point `z ∈ t`, we have `(x, y) ∈ U` and `(y, z) ∈ t × t ⊆ U`, hence `z ∈ s` exact fun z hz => hU (prodMk_mem_compRel hxy (ht <| mk_mem_prod hy hz)) rfl /-- If `x` is an adherent (cluster) point for a Cauchy filter `f`, then it is a limit point for `f`. -/ theorem le_nhds_of_cauchy_adhp {f : Filter α} {x : α} (hf : Cauchy f) (adhs : ClusterPt x f) : f ≤ 𝓝 x := le_nhds_of_cauchy_adhp_aux (fun s hs => by obtain ⟨t, t_mem, ht⟩ : ∃ t ∈ f, t ×ˢ t ⊆ s := (cauchy_iff.1 hf).2 s hs use t, t_mem, ht exact forall_mem_nonempty_iff_neBot.2 adhs _ (inter_mem_inf (mem_nhds_left x hs) t_mem)) theorem le_nhds_iff_adhp_of_cauchy {f : Filter α} {x : α} (hf : Cauchy f) : f ≤ 𝓝 x ↔ ClusterPt x f := ⟨fun h => ClusterPt.of_le_nhds' h hf.1, le_nhds_of_cauchy_adhp hf⟩ nonrec theorem Cauchy.map [UniformSpace β] {f : Filter α} {m : α → β} (hf : Cauchy f) (hm : UniformContinuous m) : Cauchy (map m f) := ⟨hf.1.map _, calc map m f ×ˢ map m f = map (Prod.map m m) (f ×ˢ f) := Filter.prod_map_map_eq _ ≤ Filter.map (Prod.map m m) (𝓤 α) := map_mono hf.right _ ≤ 𝓤 β := hm⟩ nonrec theorem Cauchy.comap [UniformSpace β] {f : Filter β} {m : α → β} (hf : Cauchy f) (hm : comap (fun p : α × α => (m p.1, m p.2)) (𝓤 β) ≤ 𝓤 α) [NeBot (comap m f)] : Cauchy (comap m f) := ⟨‹_›, calc comap m f ×ˢ comap m f = comap (Prod.map m m) (f ×ˢ f) := prod_comap_comap_eq _ ≤ comap (Prod.map m m) (𝓤 β) := comap_mono hf.right _ ≤ 𝓤 α := hm⟩ theorem Cauchy.comap' [UniformSpace β] {f : Filter β} {m : α → β} (hf : Cauchy f) (hm : Filter.comap (fun p : α × α => (m p.1, m p.2)) (𝓤 β) ≤ 𝓤 α) (_ : NeBot (Filter.comap m f)) : Cauchy (Filter.comap m f) := hf.comap hm /-- Cauchy sequences. Usually defined on ℕ, but often it is also useful to say that a function defined on ℝ is Cauchy at +∞ to deduce convergence. Therefore, we define it in a type class that is general enough to cover both ℕ and ℝ, which are the main motivating examples. -/ def CauchySeq [Preorder β] (u : β → α) := Cauchy (atTop.map u) theorem CauchySeq.tendsto_uniformity [Preorder β] {u : β → α} (h : CauchySeq u) : Tendsto (Prod.map u u) atTop (𝓤 α) := by simpa only [Tendsto, prod_map_map_eq', prod_atTop_atTop_eq] using h.right theorem CauchySeq.nonempty [Preorder β] {u : β → α} (hu : CauchySeq u) : Nonempty β := @nonempty_of_neBot _ _ <| (map_neBot_iff _).1 hu.1 theorem CauchySeq.mem_entourage {β : Type*} [SemilatticeSup β] {u : β → α} (h : CauchySeq u) {V : Set (α × α)} (hV : V ∈ 𝓤 α) : ∃ k₀, ∀ i j, k₀ ≤ i → k₀ ≤ j → (u i, u j) ∈ V := by haveI := h.nonempty have := h.tendsto_uniformity; rw [← prod_atTop_atTop_eq] at this simpa [MapsTo] using atTop_basis.prod_self.tendsto_left_iff.1 this V hV theorem Filter.Tendsto.cauchySeq [SemilatticeSup β] [Nonempty β] {f : β → α} {x} (hx : Tendsto f atTop (𝓝 x)) : CauchySeq f := hx.cauchy_map theorem cauchySeq_const [SemilatticeSup β] [Nonempty β] (x : α) : CauchySeq fun _ : β => x := tendsto_const_nhds.cauchySeq theorem cauchySeq_iff_tendsto [Nonempty β] [SemilatticeSup β] {u : β → α} : CauchySeq u ↔ Tendsto (Prod.map u u) atTop (𝓤 α) := cauchy_map_iff'.trans <| by simp only [prod_atTop_atTop_eq, Prod.map_def] theorem CauchySeq.comp_tendsto {γ} [Preorder β] [SemilatticeSup γ] [Nonempty γ] {f : β → α} (hf : CauchySeq f) {g : γ → β} (hg : Tendsto g atTop atTop) : CauchySeq (f ∘ g) := ⟨inferInstance, le_trans (prod_le_prod.mpr ⟨Tendsto.comp le_rfl hg, Tendsto.comp le_rfl hg⟩) hf.2⟩ theorem CauchySeq.comp_injective [SemilatticeSup β] [NoMaxOrder β] [Nonempty β] {u : ℕ → α} (hu : CauchySeq u) {f : β → ℕ} (hf : Injective f) : CauchySeq (u ∘ f) := hu.comp_tendsto <| Nat.cofinite_eq_atTop ▸ hf.tendsto_cofinite.mono_left atTop_le_cofinite theorem Function.Bijective.cauchySeq_comp_iff {f : ℕ → ℕ} (hf : Bijective f) (u : ℕ → α) : CauchySeq (u ∘ f) ↔ CauchySeq u := by refine ⟨fun H => ?_, fun H => H.comp_injective hf.injective⟩ lift f to ℕ ≃ ℕ using hf
simpa only [Function.comp_def, f.apply_symm_apply] using H.comp_injective f.symm.injective theorem CauchySeq.subseq_subseq_mem {V : ℕ → Set (α × α)} (hV : ∀ n, V n ∈ 𝓤 α) {u : ℕ → α} (hu : CauchySeq u) {f g : ℕ → ℕ} (hf : Tendsto f atTop atTop) (hg : Tendsto g atTop atTop) : ∃ φ : ℕ → ℕ, StrictMono φ ∧ ∀ n, ((u ∘ f ∘ φ) n, (u ∘ g ∘ φ) n) ∈ V n := by
Mathlib/Topology/UniformSpace/Cauchy.lean
211
215
/- Copyright (c) 2023 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import Mathlib.Algebra.Algebra.Defs import Mathlib.Algebra.Order.Module.Defs /-! # Ordered algebras This file proves properties of algebras where both rings are ordered compatibly. ## TODO `positivity` extension for `algebraMap` -/ variable {α β : Type*} [CommSemiring α] [PartialOrder α] section OrderedSemiring variable (β) variable [Semiring β] [PartialOrder β] [IsOrderedRing β] [Algebra α β] [SMulPosMono α β] {a : α}
@[mono] lemma algebraMap_mono : Monotone (algebraMap α β) := fun a₁ a₂ ha ↦ by simpa only [Algebra.algebraMap_eq_smul_one] using smul_le_smul_of_nonneg_right ha zero_le_one
Mathlib/Algebra/Order/Module/Algebra.lean
25
27
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Aurélien Saue, Anne Baanen -/ import Mathlib.Tactic.NormNum.Inv import Mathlib.Tactic.NormNum.Pow import Mathlib.Util.AtomM /-! # `ring` tactic A tactic for solving equations in commutative (semi)rings, where the exponents can also contain variables. Based on <http://www.cs.ru.nl/~freek/courses/tt-2014/read/10.1.1.61.3041.pdf> . More precisely, expressions of the following form are supported: - constants (non-negative integers) - variables - coefficients (any rational number, embedded into the (semi)ring) - addition of expressions - multiplication of expressions (`a * b`) - scalar multiplication of expressions (`n • a`; the multiplier must have type `ℕ`) - exponentiation of expressions (the exponent must have type `ℕ`) - subtraction and negation of expressions (if the base is a full ring) The extension to exponents means that something like `2 * 2^n * b = b * 2^(n+1)` can be proved, even though it is not strictly speaking an equation in the language of commutative rings. ## Implementation notes The basic approach to prove equalities is to normalise both sides and check for equality. The normalisation is guided by building a value in the type `ExSum` at the meta level, together with a proof (at the base level) that the original value is equal to the normalised version. The outline of the file: - Define a mutual inductive family of types `ExSum`, `ExProd`, `ExBase`, which can represent expressions with `+`, `*`, `^` and rational numerals. The mutual induction ensures that associativity and distributivity are applied, by restricting which kinds of subexpressions appear as arguments to the various operators. - Represent addition, multiplication and exponentiation in the `ExSum` type, thus allowing us to map expressions to `ExSum` (the `eval` function drives this). We apply associativity and distributivity of the operators here (helped by `Ex*` types) and commutativity as well (by sorting the subterms; unfortunately not helped by anything). Any expression not of the above formats is treated as an atom (the same as a variable). There are some details we glossed over which make the plan more complicated: - The order on atoms is not initially obvious. We construct a list containing them in order of initial appearance in the expression, then use the index into the list as a key to order on. - For `pow`, the exponent must be a natural number, while the base can be any semiring `α`. We swap out operations for the base ring `α` with those for the exponent ring `ℕ` as soon as we deal with exponents. ## Caveats and future work The normalized form of an expression is the one that is useful for the tactic, but not as nice to read. To remedy this, the user-facing normalization calls `ringNFCore`. Subtraction cancels out identical terms, but division does not. That is: `a - a = 0 := by ring` solves the goal, but `a / a := 1 by ring` doesn't. Note that `0 / 0` is generally defined to be `0`, so division cancelling out is not true in general. Multiplication of powers can be simplified a little bit further: `2 ^ n * 2 ^ n = 4 ^ n := by ring` could be implemented in a similar way that `2 * a + 2 * a = 4 * a := by ring` already works. This feature wasn't needed yet, so it's not implemented yet. ## Tags ring, semiring, exponent, power -/ assert_not_exists OrderedAddCommMonoid namespace Mathlib.Tactic namespace Ring open Mathlib.Meta Qq NormNum Lean.Meta AtomM attribute [local instance] monadLiftOptionMetaM open Lean (MetaM Expr mkRawNatLit) /-- A shortcut instance for `CommSemiring ℕ` used by ring. -/ def instCommSemiringNat : CommSemiring ℕ := inferInstance /-- A typed expression of type `CommSemiring ℕ` used when we are working on ring subexpressions of type `ℕ`. -/ def sℕ : Q(CommSemiring ℕ) := q(instCommSemiringNat) mutual /-- The base `e` of a normalized exponent expression. -/ inductive ExBase : ∀ {u : Lean.Level} {α : Q(Type u)}, Q(CommSemiring $α) → (e : Q($α)) → Type /-- An atomic expression `e` with id `id`. Atomic expressions are those which `ring` cannot parse any further. For instance, `a + (a % b)` has `a` and `(a % b)` as atoms. The `ring1` tactic does not normalize the subexpressions in atoms, but `ring_nf` does. Atoms in fact represent equivalence classes of expressions, modulo definitional equality. The field `index : ℕ` should be a unique number for each class, while `value : expr` contains a representative of this class. The function `resolve_atom` determines the appropriate atom for a given expression. -/ | atom {sα} {e} (id : ℕ) : ExBase sα e /-- A sum of monomials. -/ | sum {sα} {e} (_ : ExSum sα e) : ExBase sα e /-- A monomial, which is a product of powers of `ExBase` expressions, terminated by a (nonzero) constant coefficient. -/ inductive ExProd : ∀ {u : Lean.Level} {α : Q(Type u)}, Q(CommSemiring $α) → (e : Q($α)) → Type /-- A coefficient `value`, which must not be `0`. `e` is a raw rat cast. If `value` is not an integer, then `hyp` should be a proof of `(value.den : α) ≠ 0`. -/ | const {sα} {e} (value : ℚ) (hyp : Option Expr := none) : ExProd sα e /-- A product `x ^ e * b` is a monomial if `b` is a monomial. Here `x` is an `ExBase` and `e` is an `ExProd` representing a monomial expression in `ℕ` (it is a monomial instead of a polynomial because we eagerly normalize `x ^ (a + b) = x ^ a * x ^ b`.) -/ | mul {u : Lean.Level} {α : Q(Type u)} {sα} {x : Q($α)} {e : Q(ℕ)} {b : Q($α)} : ExBase sα x → ExProd sℕ e → ExProd sα b → ExProd sα q($x ^ $e * $b) /-- A polynomial expression, which is a sum of monomials. -/ inductive ExSum : ∀ {u : Lean.Level} {α : Q(Type u)}, Q(CommSemiring $α) → (e : Q($α)) → Type /-- Zero is a polynomial. `e` is the expression `0`. -/ | zero {u : Lean.Level} {α : Q(Type u)} {sα : Q(CommSemiring $α)} : ExSum sα q(0 : $α) /-- A sum `a + b` is a polynomial if `a` is a monomial and `b` is another polynomial. -/ | add {u : Lean.Level} {α : Q(Type u)} {sα : Q(CommSemiring $α)} {a b : Q($α)} : ExProd sα a → ExSum sα b → ExSum sα q($a + $b) end mutual -- partial only to speed up compilation /-- Equality test for expressions. This is not a `BEq` instance because it is heterogeneous. -/ partial def ExBase.eq {u : Lean.Level} {α : Q(Type u)} {sα : Q(CommSemiring $α)} {a b : Q($α)} : ExBase sα a → ExBase sα b → Bool | .atom i, .atom j => i == j | .sum a, .sum b => a.eq b | _, _ => false @[inherit_doc ExBase.eq] partial def ExProd.eq {u : Lean.Level} {α : Q(Type u)} {sα : Q(CommSemiring $α)} {a b : Q($α)} : ExProd sα a → ExProd sα b → Bool | .const i _, .const j _ => i == j | .mul a₁ a₂ a₃, .mul b₁ b₂ b₃ => a₁.eq b₁ && a₂.eq b₂ && a₃.eq b₃ | _, _ => false @[inherit_doc ExBase.eq] partial def ExSum.eq {u : Lean.Level} {α : Q(Type u)} {sα : Q(CommSemiring $α)} {a b : Q($α)} : ExSum sα a → ExSum sα b → Bool | .zero, .zero => true | .add a₁ a₂, .add b₁ b₂ => a₁.eq b₁ && a₂.eq b₂ | _, _ => false end mutual -- partial only to speed up compilation /-- A total order on normalized expressions. This is not an `Ord` instance because it is heterogeneous. -/ partial def ExBase.cmp {u : Lean.Level} {α : Q(Type u)} {sα : Q(CommSemiring $α)} {a b : Q($α)} : ExBase sα a → ExBase sα b → Ordering | .atom i, .atom j => compare i j | .sum a, .sum b => a.cmp b | .atom .., .sum .. => .lt | .sum .., .atom .. => .gt @[inherit_doc ExBase.cmp] partial def ExProd.cmp {u : Lean.Level} {α : Q(Type u)} {sα : Q(CommSemiring $α)} {a b : Q($α)} : ExProd sα a → ExProd sα b → Ordering | .const i _, .const j _ => compare i j | .mul a₁ a₂ a₃, .mul b₁ b₂ b₃ => (a₁.cmp b₁).then (a₂.cmp b₂) |>.then (a₃.cmp b₃) | .const _ _, .mul .. => .lt | .mul .., .const _ _ => .gt @[inherit_doc ExBase.cmp] partial def ExSum.cmp {u : Lean.Level} {α : Q(Type u)} {sα : Q(CommSemiring $α)} {a b : Q($α)} : ExSum sα a → ExSum sα b → Ordering | .zero, .zero => .eq | .add a₁ a₂, .add b₁ b₂ => (a₁.cmp b₁).then (a₂.cmp b₂) | .zero, .add .. => .lt | .add .., .zero => .gt end variable {u : Lean.Level} {α : Q(Type u)} {sα : Q(CommSemiring $α)} instance : Inhabited (Σ e, (ExBase sα) e) := ⟨default, .atom 0⟩ instance : Inhabited (Σ e, (ExSum sα) e) := ⟨_, .zero⟩ instance : Inhabited (Σ e, (ExProd sα) e) := ⟨default, .const 0 none⟩ mutual /-- Converts `ExBase sα` to `ExBase sβ`, assuming `sα` and `sβ` are defeq. -/ partial def ExBase.cast {v : Lean.Level} {β : Q(Type v)} {sβ : Q(CommSemiring $β)} {a : Q($α)} : ExBase sα a → Σ a, ExBase sβ a | .atom i => ⟨a, .atom i⟩ | .sum a => let ⟨_, vb⟩ := a.cast; ⟨_, .sum vb⟩ /-- Converts `ExProd sα` to `ExProd sβ`, assuming `sα` and `sβ` are defeq. -/ partial def ExProd.cast {v : Lean.Level} {β : Q(Type v)} {sβ : Q(CommSemiring $β)} {a : Q($α)} : ExProd sα a → Σ a, ExProd sβ a | .const i h => ⟨a, .const i h⟩ | .mul a₁ a₂ a₃ => ⟨_, .mul a₁.cast.2 a₂ a₃.cast.2⟩ /-- Converts `ExSum sα` to `ExSum sβ`, assuming `sα` and `sβ` are defeq. -/ partial def ExSum.cast {v : Lean.Level} {β : Q(Type v)} {sβ : Q(CommSemiring $β)} {a : Q($α)} : ExSum sα a → Σ a, ExSum sβ a | .zero => ⟨_, .zero⟩ | .add a₁ a₂ => ⟨_, .add a₁.cast.2 a₂.cast.2⟩ end variable {u : Lean.Level} /-- The result of evaluating an (unnormalized) expression `e` into the type family `E` (one of `ExSum`, `ExProd`, `ExBase`) is a (normalized) element `e'` and a representation `E e'` for it, and a proof of `e = e'`. -/ structure Result {α : Q(Type u)} (E : Q($α) → Type) (e : Q($α)) where /-- The normalized result. -/ expr : Q($α) /-- The data associated to the normalization. -/ val : E expr /-- A proof that the original expression is equal to the normalized result. -/ proof : Q($e = $expr) instance {α : Q(Type u)} {E : Q($α) → Type} {e : Q($α)} [Inhabited (Σ e, E e)] : Inhabited (Result E e) := let ⟨e', v⟩ : Σ e, E e := default; ⟨e', v, default⟩ variable {α : Q(Type u)} (sα : Q(CommSemiring $α)) {R : Type*} [CommSemiring R] /-- Constructs the expression corresponding to `.const n`. (The `.const` constructor does not check that the expression is correct.) -/ def ExProd.mkNat (n : ℕ) : (e : Q($α)) × ExProd sα e := let lit : Q(ℕ) := mkRawNatLit n ⟨q(($lit).rawCast : $α), .const n none⟩ /-- Constructs the expression corresponding to `.const (-n)`. (The `.const` constructor does not check that the expression is correct.) -/ def ExProd.mkNegNat (_ : Q(Ring $α)) (n : ℕ) : (e : Q($α)) × ExProd sα e := let lit : Q(ℕ) := mkRawNatLit n ⟨q((Int.negOfNat $lit).rawCast : $α), .const (-n) none⟩ /-- Constructs the expression corresponding to `.const q h` for `q = n / d` and `h` a proof that `(d : α) ≠ 0`. (The `.const` constructor does not check that the expression is correct.) -/ def ExProd.mkRat (_ : Q(DivisionRing $α)) (q : ℚ) (n : Q(ℤ)) (d : Q(ℕ)) (h : Expr) : (e : Q($α)) × ExProd sα e := ⟨q(Rat.rawCast $n $d : $α), .const q h⟩ section /-- Embed an exponent (an `ExBase, ExProd` pair) as an `ExProd` by multiplying by 1. -/ def ExBase.toProd {α : Q(Type u)} {sα : Q(CommSemiring $α)} {a : Q($α)} {b : Q(ℕ)} (va : ExBase sα a) (vb : ExProd sℕ b) : ExProd sα q($a ^ $b * (nat_lit 1).rawCast) := .mul va vb (.const 1 none) /-- Embed `ExProd` in `ExSum` by adding 0. -/ def ExProd.toSum {sα : Q(CommSemiring $α)} {e : Q($α)} (v : ExProd sα e) : ExSum sα q($e + 0) := .add v .zero /-- Get the leading coefficient of an `ExProd`. -/ def ExProd.coeff {sα : Q(CommSemiring $α)} {e : Q($α)} : ExProd sα e → ℚ | .const q _ => q | .mul _ _ v => v.coeff end /-- Two monomials are said to "overlap" if they differ by a constant factor, in which case the constants just add. When this happens, the constant may be either zero (if the monomials cancel) or nonzero (if they add up); the zero case is handled specially. -/ inductive Overlap (e : Q($α)) where /-- The expression `e` (the sum of monomials) is equal to `0`. -/ | zero (_ : Q(IsNat $e (nat_lit 0))) /-- The expression `e` (the sum of monomials) is equal to another monomial (with nonzero leading coefficient). -/ | nonzero (_ : Result (ExProd sα) e) variable {a a' a₁ a₂ a₃ b b' b₁ b₂ b₃ c c₁ c₂ : R} theorem add_overlap_pf (x : R) (e) (pq_pf : a + b = c) : x ^ e * a + x ^ e * b = x ^ e * c := by subst_vars; simp [mul_add] theorem add_overlap_pf_zero (x : R) (e) : IsNat (a + b) (nat_lit 0) → IsNat (x ^ e * a + x ^ e * b) (nat_lit 0) | ⟨h⟩ => ⟨by simp [h, ← mul_add]⟩ -- TODO: decide if this is a good idea globally in -- https://leanprover.zulipchat.com/#narrow/stream/270676-lean4/topic/.60MonadLift.20Option.20.28OptionT.20m.29.60/near/469097834 private local instance {m} [Pure m] : MonadLift Option (OptionT m) where monadLift f := .mk <| pure f /-- Given monomials `va, vb`, attempts to add them together to get another monomial. If the monomials are not compatible, returns `none`. For example, `xy + 2xy = 3xy` is a `.nonzero` overlap, while `xy + xz` returns `none` and `xy + -xy = 0` is a `.zero` overlap. -/ def evalAddOverlap {a b : Q($α)} (va : ExProd sα a) (vb : ExProd sα b) : OptionT Lean.Core.CoreM (Overlap sα q($a + $b)) := do Lean.Core.checkSystem decl_name%.toString match va, vb with | .const za ha, .const zb hb => do let ra := Result.ofRawRat za a ha; let rb := Result.ofRawRat zb b hb let res ← NormNum.evalAdd.core q($a + $b) q(HAdd.hAdd) a b ra rb match res with | .isNat _ (.lit (.natVal 0)) p => pure <| .zero p | rc => let ⟨zc, hc⟩ ← rc.toRatNZ let ⟨c, pc⟩ := rc.toRawEq pure <| .nonzero ⟨c, .const zc hc, pc⟩ | .mul (x := a₁) (e := a₂) va₁ va₂ va₃, .mul vb₁ vb₂ vb₃ => do guard (va₁.eq vb₁ && va₂.eq vb₂) match ← evalAddOverlap va₃ vb₃ with | .zero p => pure <| .zero (q(add_overlap_pf_zero $a₁ $a₂ $p) : Expr) | .nonzero ⟨_, vc, p⟩ => pure <| .nonzero ⟨_, .mul va₁ va₂ vc, (q(add_overlap_pf $a₁ $a₂ $p) : Expr)⟩ | _, _ => OptionT.fail theorem add_pf_zero_add (b : R) : 0 + b = b := by simp theorem add_pf_add_zero (a : R) : a + 0 = a := by simp theorem add_pf_add_overlap (_ : a₁ + b₁ = c₁) (_ : a₂ + b₂ = c₂) : (a₁ + a₂ : R) + (b₁ + b₂) = c₁ + c₂ := by subst_vars; simp [add_assoc, add_left_comm] theorem add_pf_add_overlap_zero (h : IsNat (a₁ + b₁) (nat_lit 0)) (h₄ : a₂ + b₂ = c) : (a₁ + a₂ : R) + (b₁ + b₂) = c := by subst_vars; rw [add_add_add_comm, h.1, Nat.cast_zero, add_pf_zero_add] theorem add_pf_add_lt (a₁ : R) (_ : a₂ + b = c) : (a₁ + a₂) + b = a₁ + c := by simp [*, add_assoc] theorem add_pf_add_gt (b₁ : R) (_ : a + b₂ = c) : a + (b₁ + b₂) = b₁ + c := by subst_vars; simp [add_left_comm] /-- Adds two polynomials `va, vb` together to get a normalized result polynomial. * `0 + b = b` * `a + 0 = a` * `a * x + a * y = a * (x + y)` (for `x`, `y` coefficients; uses `evalAddOverlap`) * `(a₁ + a₂) + (b₁ + b₂) = a₁ + (a₂ + (b₁ + b₂))` (if `a₁.lt b₁`) * `(a₁ + a₂) + (b₁ + b₂) = b₁ + ((a₁ + a₂) + b₂)` (if not `a₁.lt b₁`) -/ partial def evalAdd {a b : Q($α)} (va : ExSum sα a) (vb : ExSum sα b) : Lean.Core.CoreM <| Result (ExSum sα) q($a + $b) := do Lean.Core.checkSystem decl_name%.toString match va, vb with | .zero, vb => return ⟨b, vb, q(add_pf_zero_add $b)⟩ | va, .zero => return ⟨a, va, q(add_pf_add_zero $a)⟩ | .add (a := a₁) (b := _a₂) va₁ va₂, .add (a := b₁) (b := _b₂) vb₁ vb₂ => match ← (evalAddOverlap sα va₁ vb₁).run with | some (.nonzero ⟨_, vc₁, pc₁⟩) => let ⟨_, vc₂, pc₂⟩ ← evalAdd va₂ vb₂ return ⟨_, .add vc₁ vc₂, q(add_pf_add_overlap $pc₁ $pc₂)⟩ | some (.zero pc₁) => let ⟨c₂, vc₂, pc₂⟩ ← evalAdd va₂ vb₂ return ⟨c₂, vc₂, q(add_pf_add_overlap_zero $pc₁ $pc₂)⟩ | none => if let .lt := va₁.cmp vb₁ then let ⟨_c, vc, (pc : Q($_a₂ + ($b₁ + $_b₂) = $_c))⟩ ← evalAdd va₂ vb return ⟨_, .add va₁ vc, q(add_pf_add_lt $a₁ $pc)⟩ else let ⟨_c, vc, (pc : Q($a₁ + $_a₂ + $_b₂ = $_c))⟩ ← evalAdd va vb₂ return ⟨_, .add vb₁ vc, q(add_pf_add_gt $b₁ $pc)⟩ theorem one_mul (a : R) : (nat_lit 1).rawCast * a = a := by simp [Nat.rawCast] theorem mul_one (a : R) : a * (nat_lit 1).rawCast = a := by simp [Nat.rawCast] theorem mul_pf_left (a₁ : R) (a₂) (_ : a₃ * b = c) : (a₁ ^ a₂ * a₃ : R) * b = a₁ ^ a₂ * c := by subst_vars; rw [mul_assoc] theorem mul_pf_right (b₁ : R) (b₂) (_ : a * b₃ = c) : a * (b₁ ^ b₂ * b₃) = b₁ ^ b₂ * c := by subst_vars; rw [mul_left_comm] theorem mul_pp_pf_overlap {ea eb e : ℕ} (x : R) (_ : ea + eb = e) (_ : a₂ * b₂ = c) : (x ^ ea * a₂ : R) * (x ^ eb * b₂) = x ^ e * c := by subst_vars; simp [pow_add, mul_mul_mul_comm] /-- Multiplies two monomials `va, vb` together to get a normalized result monomial. * `x * y = (x * y)` (for `x`, `y` coefficients) * `x * (b₁ * b₂) = b₁ * (b₂ * x)` (for `x` coefficient) * `(a₁ * a₂) * y = a₁ * (a₂ * y)` (for `y` coefficient) * `(x ^ ea * a₂) * (x ^ eb * b₂) = x ^ (ea + eb) * (a₂ * b₂)` (if `ea` and `eb` are identical except coefficient) * `(a₁ * a₂) * (b₁ * b₂) = a₁ * (a₂ * (b₁ * b₂))` (if `a₁.lt b₁`) * `(a₁ * a₂) * (b₁ * b₂) = b₁ * ((a₁ * a₂) * b₂)` (if not `a₁.lt b₁`) -/ partial def evalMulProd {a b : Q($α)} (va : ExProd sα a) (vb : ExProd sα b) : Lean.Core.CoreM <| Result (ExProd sα) q($a * $b) := do Lean.Core.checkSystem decl_name%.toString match va, vb with | .const za ha, .const zb hb => if za = 1 then return ⟨b, .const zb hb, (q(one_mul $b) : Expr)⟩ else if zb = 1 then return ⟨a, .const za ha, (q(mul_one $a) : Expr)⟩ else let ra := Result.ofRawRat za a ha; let rb := Result.ofRawRat zb b hb let rc := (NormNum.evalMul.core q($a * $b) q(HMul.hMul) _ _ q(CommSemiring.toSemiring) ra rb).get! let ⟨zc, hc⟩ := rc.toRatNZ.get! let ⟨c, pc⟩ := rc.toRawEq return ⟨c, .const zc hc, pc⟩ | .mul (x := a₁) (e := a₂) va₁ va₂ va₃, .const _ _ => let ⟨_, vc, pc⟩ ← evalMulProd va₃ vb return ⟨_, .mul va₁ va₂ vc, (q(mul_pf_left $a₁ $a₂ $pc) : Expr)⟩ | .const _ _, .mul (x := b₁) (e := b₂) vb₁ vb₂ vb₃ => let ⟨_, vc, pc⟩ ← evalMulProd va vb₃ return ⟨_, .mul vb₁ vb₂ vc, (q(mul_pf_right $b₁ $b₂ $pc) : Expr)⟩ | .mul (x := xa) (e := ea) vxa vea va₂, .mul (x := xb) (e := eb) vxb veb vb₂ => do if vxa.eq vxb then if let some (.nonzero ⟨_, ve, pe⟩) ← (evalAddOverlap sℕ vea veb).run then let ⟨_, vc, pc⟩ ← evalMulProd va₂ vb₂ return ⟨_, .mul vxa ve vc, (q(mul_pp_pf_overlap $xa $pe $pc) : Expr)⟩ if let .lt := (vxa.cmp vxb).then (vea.cmp veb) then let ⟨_, vc, pc⟩ ← evalMulProd va₂ vb return ⟨_, .mul vxa vea vc, (q(mul_pf_left $xa $ea $pc) : Expr)⟩ else let ⟨_, vc, pc⟩ ← evalMulProd va vb₂ return ⟨_, .mul vxb veb vc, (q(mul_pf_right $xb $eb $pc) : Expr)⟩ theorem mul_zero (a : R) : a * 0 = 0 := by simp theorem mul_add {d : R} (_ : (a : R) * b₁ = c₁) (_ : a * b₂ = c₂) (_ : c₁ + 0 + c₂ = d) : a * (b₁ + b₂) = d := by subst_vars; simp [_root_.mul_add] /-- Multiplies a monomial `va` to a polynomial `vb` to get a normalized result polynomial. * `a * 0 = 0` * `a * (b₁ + b₂) = (a * b₁) + (a * b₂)` -/ def evalMul₁ {a b : Q($α)} (va : ExProd sα a) (vb : ExSum sα b) : Lean.Core.CoreM <| Result (ExSum sα) q($a * $b) := do match vb with | .zero => return ⟨_, .zero, q(mul_zero $a)⟩ | .add vb₁ vb₂ => let ⟨_, vc₁, pc₁⟩ ← evalMulProd sα va vb₁ let ⟨_, vc₂, pc₂⟩ ← evalMul₁ va vb₂ let ⟨_, vd, pd⟩ ← evalAdd sα vc₁.toSum vc₂ return ⟨_, vd, q(mul_add $pc₁ $pc₂ $pd)⟩ theorem zero_mul (b : R) : 0 * b = 0 := by simp theorem add_mul {d : R} (_ : (a₁ : R) * b = c₁) (_ : a₂ * b = c₂) (_ : c₁ + c₂ = d) : (a₁ + a₂) * b = d := by subst_vars; simp [_root_.add_mul] /-- Multiplies two polynomials `va, vb` together to get a normalized result polynomial. * `0 * b = 0` * `(a₁ + a₂) * b = (a₁ * b) + (a₂ * b)` -/ def evalMul {a b : Q($α)} (va : ExSum sα a) (vb : ExSum sα b) : Lean.Core.CoreM <| Result (ExSum sα) q($a * $b) := do match va with | .zero => return ⟨_, .zero, q(zero_mul $b)⟩ | .add va₁ va₂ => let ⟨_, vc₁, pc₁⟩ ← evalMul₁ sα va₁ vb let ⟨_, vc₂, pc₂⟩ ← evalMul va₂ vb let ⟨_, vd, pd⟩ ← evalAdd sα vc₁ vc₂ return ⟨_, vd, q(add_mul $pc₁ $pc₂ $pd)⟩ theorem natCast_nat (n) : ((Nat.rawCast n : ℕ) : R) = Nat.rawCast n := by simp theorem natCast_mul {a₁ a₃ : ℕ} (a₂) (_ : ((a₁ : ℕ) : R) = b₁) (_ : ((a₃ : ℕ) : R) = b₃) : ((a₁ ^ a₂ * a₃ : ℕ) : R) = b₁ ^ a₂ * b₃ := by subst_vars; simp theorem natCast_zero : ((0 : ℕ) : R) = 0 := Nat.cast_zero theorem natCast_add {a₁ a₂ : ℕ} (_ : ((a₁ : ℕ) : R) = b₁) (_ : ((a₂ : ℕ) : R) = b₂) : ((a₁ + a₂ : ℕ) : R) = b₁ + b₂ := by subst_vars; simp mutual /-- Applies `Nat.cast` to a nat polynomial to produce a polynomial in `α`. * An atom `e` causes `↑e` to be allocated as a new atom. * A sum delegates to `ExSum.evalNatCast`. -/ partial def ExBase.evalNatCast {a : Q(ℕ)} (va : ExBase sℕ a) : AtomM (Result (ExBase sα) q($a)) := match va with | .atom _ => do let (i, ⟨b', _⟩) ← addAtomQ q($a) pure ⟨b', ExBase.atom i, q(Eq.refl $b')⟩ | .sum va => do let ⟨_, vc, p⟩ ← va.evalNatCast pure ⟨_, .sum vc, p⟩ /-- Applies `Nat.cast` to a nat monomial to produce a monomial in `α`. * `↑c = c` if `c` is a numeric literal * `↑(a ^ n * b) = ↑a ^ n * ↑b` -/ partial def ExProd.evalNatCast {a : Q(ℕ)} (va : ExProd sℕ a) : AtomM (Result (ExProd sα) q($a)) := match va with | .const c hc => have n : Q(ℕ) := a.appArg! pure ⟨q(Nat.rawCast $n), .const c hc, (q(natCast_nat (R := $α) $n) : Expr)⟩ | .mul (e := a₂) va₁ va₂ va₃ => do let ⟨_, vb₁, pb₁⟩ ← va₁.evalNatCast let ⟨_, vb₃, pb₃⟩ ← va₃.evalNatCast pure ⟨_, .mul vb₁ va₂ vb₃, q(natCast_mul $a₂ $pb₁ $pb₃)⟩ /-- Applies `Nat.cast` to a nat polynomial to produce a polynomial in `α`. * `↑0 = 0` * `↑(a + b) = ↑a + ↑b` -/ partial def ExSum.evalNatCast {a : Q(ℕ)} (va : ExSum sℕ a) : AtomM (Result (ExSum sα) q($a)) := match va with | .zero => pure ⟨_, .zero, q(natCast_zero (R := $α))⟩ | .add va₁ va₂ => do let ⟨_, vb₁, pb₁⟩ ← va₁.evalNatCast let ⟨_, vb₂, pb₂⟩ ← va₂.evalNatCast pure ⟨_, .add vb₁ vb₂, q(natCast_add $pb₁ $pb₂)⟩ end theorem smul_nat {a b c : ℕ} (_ : (a * b : ℕ) = c) : a • b = c := by subst_vars; simp theorem smul_eq_cast {a : ℕ} (_ : ((a : ℕ) : R) = a') (_ : a' * b = c) : a • b = c := by subst_vars; simp /-- Constructs the scalar multiplication `n • a`, where both `n : ℕ` and `a : α` are normalized polynomial expressions. * `a • b = a * b` if `α = ℕ` * `a • b = ↑a * b` otherwise -/ def evalNSMul {a : Q(ℕ)} {b : Q($α)} (va : ExSum sℕ a) (vb : ExSum sα b) : AtomM (Result (ExSum sα) q($a • $b)) := do if ← isDefEq sα sℕ then let ⟨_, va'⟩ := va.cast have _b : Q(ℕ) := b let ⟨(_c : Q(ℕ)), vc, (pc : Q($a * $_b = $_c))⟩ ← evalMul sα va' vb pure ⟨_, vc, (q(smul_nat $pc) : Expr)⟩ else let ⟨_, va', pa'⟩ ← va.evalNatCast sα let ⟨_, vc, pc⟩ ← evalMul sα va' vb pure ⟨_, vc, (q(smul_eq_cast $pa' $pc) : Expr)⟩ theorem neg_one_mul {R} [Ring R] {a b : R} (_ : (Int.negOfNat (nat_lit 1)).rawCast * a = b) : -a = b := by subst_vars; simp [Int.negOfNat] theorem neg_mul {R} [Ring R] (a₁ : R) (a₂) {a₃ b : R} (_ : -a₃ = b) : -(a₁ ^ a₂ * a₃) = a₁ ^ a₂ * b := by subst_vars; simp /-- Negates a monomial `va` to get another monomial. * `-c = (-c)` (for `c` coefficient) * `-(a₁ * a₂) = a₁ * -a₂` -/ def evalNegProd {a : Q($α)} (rα : Q(Ring $α)) (va : ExProd sα a) : Lean.Core.CoreM <| Result (ExProd sα) q(-$a) := do Lean.Core.checkSystem decl_name%.toString match va with | .const za ha => let lit : Q(ℕ) := mkRawNatLit 1 let ⟨m1, _⟩ := ExProd.mkNegNat sα rα 1 let rm := Result.isNegNat rα lit (q(IsInt.of_raw $α (.negOfNat $lit)) : Expr) let ra := Result.ofRawRat za a ha let rb := (NormNum.evalMul.core q($m1 * $a) q(HMul.hMul) _ _ q(CommSemiring.toSemiring) rm ra).get! let ⟨zb, hb⟩ := rb.toRatNZ.get! let ⟨b, (pb : Q((Int.negOfNat (nat_lit 1)).rawCast * $a = $b))⟩ := rb.toRawEq return ⟨b, .const zb hb, (q(neg_one_mul (R := $α) $pb) : Expr)⟩ | .mul (x := a₁) (e := a₂) va₁ va₂ va₃ => let ⟨_, vb, pb⟩ ← evalNegProd rα va₃ return ⟨_, .mul va₁ va₂ vb, (q(neg_mul $a₁ $a₂ $pb) : Expr)⟩ theorem neg_zero {R} [Ring R] : -(0 : R) = 0 := by simp theorem neg_add {R} [Ring R] {a₁ a₂ b₁ b₂ : R} (_ : -a₁ = b₁) (_ : -a₂ = b₂) : -(a₁ + a₂) = b₁ + b₂ := by subst_vars; simp [add_comm] /-- Negates a polynomial `va` to get another polynomial. * `-0 = 0` (for `c` coefficient) * `-(a₁ + a₂) = -a₁ + -a₂` -/ def evalNeg {a : Q($α)} (rα : Q(Ring $α)) (va : ExSum sα a) : Lean.Core.CoreM <| Result (ExSum sα) q(-$a) := do match va with | .zero => return ⟨_, .zero, (q(neg_zero (R := $α)) : Expr)⟩ | .add va₁ va₂ => let ⟨_, vb₁, pb₁⟩ ← evalNegProd sα rα va₁ let ⟨_, vb₂, pb₂⟩ ← evalNeg rα va₂ return ⟨_, .add vb₁ vb₂, (q(neg_add $pb₁ $pb₂) : Expr)⟩ theorem sub_pf {R} [Ring R] {a b c d : R} (_ : -b = c) (_ : a + c = d) : a - b = d := by subst_vars; simp [sub_eq_add_neg] /-- Subtracts two polynomials `va, vb` to get a normalized result polynomial. * `a - b = a + -b` -/ def evalSub {α : Q(Type u)} (sα : Q(CommSemiring $α)) {a b : Q($α)} (rα : Q(Ring $α)) (va : ExSum sα a) (vb : ExSum sα b) : Lean.Core.CoreM <| Result (ExSum sα) q($a - $b) := do let ⟨_c, vc, pc⟩ ← evalNeg sα rα vb let ⟨d, vd, (pd : Q($a + $_c = $d))⟩ ← evalAdd sα va vc return ⟨d, vd, (q(sub_pf $pc $pd) : Expr)⟩ theorem pow_prod_atom (a : R) (b) : a ^ b = (a + 0) ^ b * (nat_lit 1).rawCast := by simp /-- The fallback case for exponentiating polynomials is to use `ExBase.toProd` to just build an exponent expression. (This has a slightly different normalization than `evalPowAtom` because the input types are different.) * `x ^ e = (x + 0) ^ e * 1` -/ def evalPowProdAtom {a : Q($α)} {b : Q(ℕ)} (va : ExProd sα a) (vb : ExProd sℕ b) : Result (ExProd sα) q($a ^ $b) := ⟨_, (ExBase.sum va.toSum).toProd vb, q(pow_prod_atom $a $b)⟩ theorem pow_atom (a : R) (b) : a ^ b = a ^ b * (nat_lit 1).rawCast + 0 := by simp /-- The fallback case for exponentiating polynomials is to use `ExBase.toProd` to just build an exponent expression. * `x ^ e = x ^ e * 1 + 0` -/ def evalPowAtom {a : Q($α)} {b : Q(ℕ)} (va : ExBase sα a) (vb : ExProd sℕ b) : Result (ExSum sα) q($a ^ $b) := ⟨_, (va.toProd vb).toSum, q(pow_atom $a $b)⟩ theorem const_pos (n : ℕ) (h : Nat.ble 1 n = true) : 0 < (n.rawCast : ℕ) := Nat.le_of_ble_eq_true h theorem mul_exp_pos {a₁ a₂ : ℕ} (n) (h₁ : 0 < a₁) (h₂ : 0 < a₂) : 0 < a₁ ^ n * a₂ := Nat.mul_pos (Nat.pow_pos h₁) h₂ theorem add_pos_left {a₁ : ℕ} (a₂) (h : 0 < a₁) : 0 < a₁ + a₂ := Nat.lt_of_lt_of_le h (Nat.le_add_right ..) theorem add_pos_right {a₂ : ℕ} (a₁) (h : 0 < a₂) : 0 < a₁ + a₂ := Nat.lt_of_lt_of_le h (Nat.le_add_left ..) mutual /-- Attempts to prove that a polynomial expression in `ℕ` is positive. * Atoms are not (necessarily) positive * Sums defer to `ExSum.evalPos` -/ partial def ExBase.evalPos {a : Q(ℕ)} (va : ExBase sℕ a) : Option Q(0 < $a) := match va with | .atom _ => none | .sum va => va.evalPos /-- Attempts to prove that a monomial expression in `ℕ` is positive. * `0 < c` (where `c` is a numeral) is true by the normalization invariant (`c` is not zero) * `0 < x ^ e * b` if `0 < x` and `0 < b` -/ partial def ExProd.evalPos {a : Q(ℕ)} (va : ExProd sℕ a) : Option Q(0 < $a) := match va with | .const _ _ => -- it must be positive because it is a nonzero nat literal have lit : Q(ℕ) := a.appArg! haveI : $a =Q Nat.rawCast $lit := ⟨⟩ haveI p : Nat.ble 1 $lit =Q true := ⟨⟩ some q(const_pos $lit $p) | .mul (e := ea₁) vxa₁ _ va₂ => do let pa₁ ← vxa₁.evalPos let pa₂ ← va₂.evalPos some q(mul_exp_pos $ea₁ $pa₁ $pa₂) /-- Attempts to prove that a polynomial expression in `ℕ` is positive. * `0 < 0` fails * `0 < a + b` if `0 < a` or `0 < b` -/ partial def ExSum.evalPos {a : Q(ℕ)} (va : ExSum sℕ a) : Option Q(0 < $a) := match va with | .zero => none | .add (a := a₁) (b := a₂) va₁ va₂ => do match va₁.evalPos with | some p => some q(add_pos_left $a₂ $p) | none => let p ← va₂.evalPos; some q(add_pos_right $a₁ $p) end theorem pow_one (a : R) : a ^ nat_lit 1 = a := by simp theorem pow_bit0 {k : ℕ} (_ : (a : R) ^ k = b) (_ : b * b = c) : a ^ (Nat.mul (nat_lit 2) k) = c := by subst_vars; simp [Nat.succ_mul, pow_add] theorem pow_bit1 {k : ℕ} {d : R} (_ : (a : R) ^ k = b) (_ : b * b = c) (_ : c * a = d) : a ^ (Nat.add (Nat.mul (nat_lit 2) k) (nat_lit 1)) = d := by subst_vars; simp [Nat.succ_mul, pow_add] /-- The main case of exponentiation of ring expressions is when `va` is a polynomial and `n` is a nonzero literal expression, like `(x + y)^5`. In this case we work out the polynomial completely into a sum of monomials. * `x ^ 1 = x` * `x ^ (2*n) = x ^ n * x ^ n` * `x ^ (2*n+1) = x ^ n * x ^ n * x` -/ partial def evalPowNat {a : Q($α)} (va : ExSum sα a) (n : Q(ℕ)) : Lean.Core.CoreM <| Result (ExSum sα) q($a ^ $n) := do let nn := n.natLit! if nn = 1 then return ⟨_, va, (q(pow_one $a) : Expr)⟩ else let nm := nn >>> 1 have m : Q(ℕ) := mkRawNatLit nm if nn &&& 1 = 0 then let ⟨_, vb, pb⟩ ← evalPowNat va m let ⟨_, vc, pc⟩ ← evalMul sα vb vb return ⟨_, vc, (q(pow_bit0 $pb $pc) : Expr)⟩ else let ⟨_, vb, pb⟩ ← evalPowNat va m let ⟨_, vc, pc⟩ ← evalMul sα vb vb let ⟨_, vd, pd⟩ ← evalMul sα vc va return ⟨_, vd, (q(pow_bit1 $pb $pc $pd) : Expr)⟩ theorem one_pow (b : ℕ) : ((nat_lit 1).rawCast : R) ^ b = (nat_lit 1).rawCast := by simp theorem mul_pow {ea₁ b c₁ : ℕ} {xa₁ : R} (_ : ea₁ * b = c₁) (_ : a₂ ^ b = c₂) : (xa₁ ^ ea₁ * a₂ : R) ^ b = xa₁ ^ c₁ * c₂ := by subst_vars; simp [_root_.mul_pow, pow_mul] /-- There are several special cases when exponentiating monomials: * `1 ^ n = 1` * `x ^ y = (x ^ y)` when `x` and `y` are constants * `(a * b) ^ e = a ^ e * b ^ e` In all other cases we use `evalPowProdAtom`. -/ def evalPowProd {a : Q($α)} {b : Q(ℕ)} (va : ExProd sα a) (vb : ExProd sℕ b) : Lean.Core.CoreM <| Result (ExProd sα) q($a ^ $b) := do Lean.Core.checkSystem decl_name%.toString let res : OptionT Lean.Core.CoreM (Result (ExProd sα) q($a ^ $b)) := do match va, vb with | .const 1, _ => return ⟨_, va, (q(one_pow (R := $α) $b) : Expr)⟩ | .const za ha, .const zb hb => assert! 0 ≤ zb let ra := Result.ofRawRat za a ha have lit : Q(ℕ) := b.appArg! let rb := (q(IsNat.of_raw ℕ $lit) : Expr) let rc ← NormNum.evalPow.core q($a ^ $b) q(HPow.hPow) q($a) q($b) lit rb q(CommSemiring.toSemiring) ra let ⟨zc, hc⟩ ← rc.toRatNZ let ⟨c, pc⟩ := rc.toRawEq return ⟨c, .const zc hc, pc⟩ | .mul vxa₁ vea₁ va₂, vb => let ⟨_, vc₁, pc₁⟩ ← evalMulProd sℕ vea₁ vb let ⟨_, vc₂, pc₂⟩ ← evalPowProd va₂ vb return ⟨_, .mul vxa₁ vc₁ vc₂, q(mul_pow $pc₁ $pc₂)⟩ | _, _ => OptionT.fail return (← res.run).getD (evalPowProdAtom sα va vb) /-- The result of `extractCoeff` is a numeral and a proof that the original expression factors by this numeral. -/ structure ExtractCoeff (e : Q(ℕ)) where /-- A raw natural number literal. -/ k : Q(ℕ) /-- The result of extracting the coefficient is a monic monomial. -/ e' : Q(ℕ) /-- `e'` is a monomial. -/ ve' : ExProd sℕ e' /-- The proof that `e` splits into the coefficient `k` and the monic monomial `e'`. -/ p : Q($e = $e' * $k) theorem coeff_one (k : ℕ) : k.rawCast = (nat_lit 1).rawCast * k := by simp theorem coeff_mul {a₃ c₂ k : ℕ} (a₁ a₂ : ℕ) (_ : a₃ = c₂ * k) : a₁ ^ a₂ * a₃ = (a₁ ^ a₂ * c₂) * k := by subst_vars; rw [mul_assoc] /-- Given a monomial expression `va`, splits off the leading coefficient `k` and the remainder `e'`, stored in the `ExtractCoeff` structure. * `c = 1 * c` (if `c` is a constant) * `a * b = (a * b') * k` if `b = b' * k` -/ def extractCoeff {a : Q(ℕ)} (va : ExProd sℕ a) : ExtractCoeff a := match va with | .const _ _ => have k : Q(ℕ) := a.appArg! ⟨k, q((nat_lit 1).rawCast), .const 1, (q(coeff_one $k) : Expr)⟩ | .mul (x := a₁) (e := a₂) va₁ va₂ va₃ => let ⟨k, _, vc, pc⟩ := extractCoeff va₃ ⟨k, _, .mul va₁ va₂ vc, q(coeff_mul $a₁ $a₂ $pc)⟩ theorem pow_one_cast (a : R) : a ^ (nat_lit 1).rawCast = a := by simp theorem zero_pow {b : ℕ} (_ : 0 < b) : (0 : R) ^ b = 0 := match b with | b+1 => by simp [pow_succ] theorem single_pow {b : ℕ} (_ : (a : R) ^ b = c) : (a + 0) ^ b = c + 0 := by simp [*] theorem pow_nat {b c k : ℕ} {d e : R} (_ : b = c * k) (_ : a ^ c = d) (_ : d ^ k = e) : (a : R) ^ b = e := by subst_vars; simp [pow_mul] /-- Exponentiates a polynomial `va` by a monomial `vb`, including several special cases. * `a ^ 1 = a` * `0 ^ e = 0` if `0 < e` * `(a + 0) ^ b = a ^ b` computed using `evalPowProd` * `a ^ b = (a ^ b') ^ k` if `b = b' * k` and `k > 1` Otherwise `a ^ b` is just encoded as `a ^ b * 1 + 0` using `evalPowAtom`. -/ partial def evalPow₁ {a : Q($α)} {b : Q(ℕ)} (va : ExSum sα a) (vb : ExProd sℕ b) : Lean.Core.CoreM <| Result (ExSum sα) q($a ^ $b) := do match va, vb with | va, .const 1 => haveI : $b =Q Nat.rawCast (nat_lit 1) := ⟨⟩ return ⟨_, va, q(pow_one_cast $a)⟩ | .zero, vb => match vb.evalPos with | some p => return ⟨_, .zero, q(zero_pow (R := $α) $p)⟩ | none => return evalPowAtom sα (.sum .zero) vb | ExSum.add va .zero, vb => -- TODO: using `.add` here takes a while to compile? let ⟨_, vc, pc⟩ ← evalPowProd sα va vb return ⟨_, vc.toSum, q(single_pow $pc)⟩ | va, vb => if vb.coeff > 1 then let ⟨k, _, vc, pc⟩ := extractCoeff vb let ⟨_, vd, pd⟩ ← evalPow₁ va vc let ⟨_, ve, pe⟩ ← evalPowNat sα vd k return ⟨_, ve, q(pow_nat $pc $pd $pe)⟩ else return evalPowAtom sα (.sum va) vb theorem pow_zero (a : R) : a ^ 0 = (nat_lit 1).rawCast + 0 := by simp theorem pow_add {b₁ b₂ : ℕ} {d : R} (_ : a ^ b₁ = c₁) (_ : a ^ b₂ = c₂) (_ : c₁ * c₂ = d) : (a : R) ^ (b₁ + b₂) = d := by subst_vars; simp [_root_.pow_add] /-- Exponentiates two polynomials `va, vb`. * `a ^ 0 = 1` * `a ^ (b₁ + b₂) = a ^ b₁ * a ^ b₂` -/ def evalPow {a : Q($α)} {b : Q(ℕ)} (va : ExSum sα a) (vb : ExSum sℕ b) : Lean.Core.CoreM <| Result (ExSum sα) q($a ^ $b) := do match vb with | .zero => return ⟨_, (ExProd.mkNat sα 1).2.toSum, q(pow_zero $a)⟩ | .add vb₁ vb₂ => let ⟨_, vc₁, pc₁⟩ ← evalPow₁ sα va vb₁ let ⟨_, vc₂, pc₂⟩ ← evalPow va vb₂ let ⟨_, vd, pd⟩ ← evalMul sα vc₁ vc₂ return ⟨_, vd, q(pow_add $pc₁ $pc₂ $pd)⟩ /-- This cache contains data required by the `ring` tactic during execution. -/ structure Cache {α : Q(Type u)} (sα : Q(CommSemiring $α)) where /-- A ring instance on `α`, if available. -/ rα : Option Q(Ring $α) /-- A division ring instance on `α`, if available. -/ dα : Option Q(DivisionRing $α) /-- A characteristic zero ring instance on `α`, if available. -/ czα : Option Q(CharZero $α) /-- Create a new cache for `α` by doing the necessary instance searches. -/
def mkCache {α : Q(Type u)} (sα : Q(CommSemiring $α)) : MetaM (Cache sα) := return {
Mathlib/Tactic/Ring/Basic.lean
900
901
/- Copyright (c) 2020 Kim Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kim Morrison -/ import Mathlib.AlgebraicGeometry.Spec import Mathlib.Algebra.Category.Ring.Constructions import Mathlib.CategoryTheory.Elementwise /-! # The category of schemes A scheme is a locally ringed space such that every point is contained in some open set where there is an isomorphism of presheaves between the restriction to that open set, and the structure sheaf of `Spec R`, for some commutative ring `R`. A morphism of schemes is just a morphism of the underlying locally ringed spaces. -/ -- Explicit universe annotations were used in this file to improve performance https://github.com/leanprover-community/mathlib4/issues/12737 universe u noncomputable section open TopologicalSpace open CategoryTheory open TopCat open Opposite namespace AlgebraicGeometry /-- We define `Scheme` as an `X : LocallyRingedSpace`, along with a proof that every point has an open neighbourhood `U` so that the restriction of `X` to `U` is isomorphic, as a locally ringed space, to `Spec.toLocallyRingedSpace.obj (op R)` for some `R : CommRingCat`. -/ structure Scheme extends LocallyRingedSpace where local_affine : ∀ x : toLocallyRingedSpace, ∃ (U : OpenNhds x) (R : CommRingCat), Nonempty (toLocallyRingedSpace.restrict U.isOpenEmbedding ≅ Spec.toLocallyRingedSpace.obj (op R)) namespace Scheme instance : CoeSort Scheme Type* where coe X := X.carrier /-- The type of open sets of a scheme. -/ abbrev Opens (X : Scheme) : Type* := TopologicalSpace.Opens X /-- A morphism between schemes is a morphism between the underlying locally ringed spaces. -/ structure Hom (X Y : Scheme) extends toLRSHom' : X.toLocallyRingedSpace.Hom Y.toLocallyRingedSpace where /-- Cast a morphism of schemes into morphisms of local ringed spaces. -/ abbrev Hom.toLRSHom {X Y : Scheme.{u}} (f : X.Hom Y) : X.toLocallyRingedSpace ⟶ Y.toLocallyRingedSpace := f.toLRSHom' /-- See Note [custom simps projection] -/ def Hom.Simps.toLRSHom {X Y : Scheme.{u}} (f : X.Hom Y) : X.toLocallyRingedSpace ⟶ Y.toLocallyRingedSpace := f.toLRSHom initialize_simps_projections Hom (toLRSHom' → toLRSHom) /-- Schemes are a full subcategory of locally ringed spaces. -/ instance : Category Scheme where Hom := Hom id X := Hom.mk (𝟙 X.toLocallyRingedSpace) comp f g := Hom.mk (f.toLRSHom ≫ g.toLRSHom) /-- `f ⁻¹ᵁ U` is notation for `(Opens.map f.base).obj U`, the preimage of an open set `U` under `f`. -/ scoped[AlgebraicGeometry] notation3:90 f:91 " ⁻¹ᵁ " U:90 => @Prefunctor.obj (Scheme.Opens _) _ (Scheme.Opens _) _ (Opens.map (f : Scheme.Hom _ _).base).toPrefunctor U /-- `Γ(X, U)` is notation for `X.presheaf.obj (op U)`. -/ scoped[AlgebraicGeometry] notation3 "Γ(" X ", " U ")" => (PresheafedSpace.presheaf (SheafedSpace.toPresheafedSpace (LocallyRingedSpace.toSheafedSpace (Scheme.toLocallyRingedSpace X)))).obj (op (α := Scheme.Opens _) U) instance {X : Scheme.{u}} : Subsingleton Γ(X, ⊥) := CommRingCat.subsingleton_of_isTerminal X.sheaf.isTerminalOfEmpty @[continuity, fun_prop] lemma Hom.continuous {X Y : Scheme} (f : X.Hom Y) : Continuous f.base := f.base.hom.2 /-- The structure sheaf of a scheme. -/ protected abbrev sheaf (X : Scheme) := X.toSheafedSpace.sheaf namespace Hom variable {X Y : Scheme.{u}} (f : Hom X Y) {U U' : Y.Opens} {V V' : X.Opens} /-- Given a morphism of schemes `f : X ⟶ Y`, and open `U ⊆ Y`, this is the induced map `Γ(Y, U) ⟶ Γ(X, f ⁻¹ᵁ U)`. -/ abbrev app (U : Y.Opens) : Γ(Y, U) ⟶ Γ(X, f ⁻¹ᵁ U) := f.c.app (op U) /-- Given a morphism of schemes `f : X ⟶ Y`, this is the induced map `Γ(Y, ⊤) ⟶ Γ(X, ⊤)`. -/ abbrev appTop : Γ(Y, ⊤) ⟶ Γ(X, ⊤) := f.app ⊤ @[reassoc] lemma naturality (i : op U' ⟶ op U) : Y.presheaf.map i ≫ f.app U = f.app U' ≫ X.presheaf.map ((Opens.map f.base).map i.unop).op := f.c.naturality i /-- Given a morphism of schemes `f : X ⟶ Y`, and open sets `U ⊆ Y`, `V ⊆ f ⁻¹' U`, this is the induced map `Γ(Y, U) ⟶ Γ(X, V)`. -/ def appLE (U : Y.Opens) (V : X.Opens) (e : V ≤ f ⁻¹ᵁ U) : Γ(Y, U) ⟶ Γ(X, V) := f.app U ≫ X.presheaf.map (homOfLE e).op @[reassoc (attr := simp)] lemma appLE_map (e : V ≤ f ⁻¹ᵁ U) (i : op V ⟶ op V') : f.appLE U V e ≫ X.presheaf.map i = f.appLE U V' (i.unop.le.trans e) := by rw [Hom.appLE, Category.assoc, ← Functor.map_comp] rfl @[reassoc] lemma appLE_map' (e : V ≤ f ⁻¹ᵁ U) (i : V = V') : f.appLE U V' (i ▸ e) ≫ X.presheaf.map (eqToHom i).op = f.appLE U V e := appLE_map _ _ _ @[reassoc (attr := simp)] lemma map_appLE (e : V ≤ f ⁻¹ᵁ U) (i : op U' ⟶ op U) : Y.presheaf.map i ≫ f.appLE U V e = f.appLE U' V (e.trans ((Opens.map f.base).map i.unop).le) := by rw [Hom.appLE, f.naturality_assoc, ← Functor.map_comp] rfl @[reassoc] lemma map_appLE' (e : V ≤ f ⁻¹ᵁ U) (i : U' = U) : Y.presheaf.map (eqToHom i).op ≫ f.appLE U' V (i ▸ e) = f.appLE U V e := map_appLE _ _ _ lemma app_eq_appLE {U : Y.Opens} : f.app U = f.appLE U _ le_rfl := by simp [Hom.appLE] lemma appLE_eq_app {U : Y.Opens} : f.appLE U (f ⁻¹ᵁ U) le_rfl = f.app U := (app_eq_appLE f).symm lemma appLE_congr (e : V ≤ f ⁻¹ᵁ U) (e₁ : U = U') (e₂ : V = V') (P : ∀ {R S : CommRingCat.{u}} (_ : R ⟶ S), Prop) : P (f.appLE U V e) ↔ P (f.appLE U' V' (e₁ ▸ e₂ ▸ e)) := by subst e₁; subst e₂; rfl /-- A morphism of schemes `f : X ⟶ Y` induces a local ring homomorphism from `Y.presheaf.stalk (f x)` to `X.presheaf.stalk x` for any `x : X`. -/ def stalkMap (x : X) : Y.presheaf.stalk (f.base x) ⟶ X.presheaf.stalk x := f.toLRSHom.stalkMap x @[ext (iff := false)] protected lemma ext {f g : X ⟶ Y} (h_base : f.base = g.base) (h_app : ∀ U, f.app U ≫ X.presheaf.map (eqToHom congr((Opens.map $h_base.symm).obj U)).op = g.app U) : f = g := by cases f; cases g; congr 1 exact LocallyRingedSpace.Hom.ext' <| SheafedSpace.ext _ _ h_base (TopCat.Presheaf.ext fun U ↦ by simpa using h_app U) /-- An alternative ext lemma for scheme morphisms. -/ protected lemma ext' {f g : X ⟶ Y} (h : f.toLRSHom = g.toLRSHom) : f = g := by cases f; cases g; congr 1 lemma preimage_iSup {ι} (U : ι → Opens Y) : f ⁻¹ᵁ iSup U = ⨆ i, f ⁻¹ᵁ U i := Opens.ext (by simp) lemma preimage_iSup_eq_top {ι} {U : ι → Opens Y} (hU : iSup U = ⊤) : ⨆ i, f ⁻¹ᵁ U i = ⊤ := f.preimage_iSup U ▸ hU ▸ rfl lemma preimage_le_preimage_of_le {U U' : Y.Opens} (hUU' : U ≤ U') : f ⁻¹ᵁ U ≤ f ⁻¹ᵁ U' := fun _ ha ↦ hUU' ha end Hom @[simp] lemma preimage_comp {X Y Z : Scheme.{u}} (f : X ⟶ Y) (g : Y ⟶ Z) (U) : (f ≫ g) ⁻¹ᵁ U = f ⁻¹ᵁ g ⁻¹ᵁ U := rfl /-- The forgetful functor from `Scheme` to `LocallyRingedSpace`. -/ @[simps!] def forgetToLocallyRingedSpace : Scheme ⥤ LocallyRingedSpace where obj := toLocallyRingedSpace map := Hom.toLRSHom /-- The forget functor `Scheme ⥤ LocallyRingedSpace` is fully faithful. -/ @[simps preimage_toLRSHom] def fullyFaithfulForgetToLocallyRingedSpace : forgetToLocallyRingedSpace.FullyFaithful where preimage := Hom.mk instance : forgetToLocallyRingedSpace.Full := fullyFaithfulForgetToLocallyRingedSpace.full instance : forgetToLocallyRingedSpace.Faithful := fullyFaithfulForgetToLocallyRingedSpace.faithful /-- The forgetful functor from `Scheme` to `TopCat`. -/ @[simps!] def forgetToTop : Scheme ⥤ TopCat := Scheme.forgetToLocallyRingedSpace ⋙ LocallyRingedSpace.forgetToTop
/-- An isomorphism of schemes induces a homeomorphism of the underlying topological spaces. -/ noncomputable def homeoOfIso {X Y : Scheme.{u}} (e : X ≅ Y) : X ≃ₜ Y := TopCat.homeoOfIso (forgetToTop.mapIso e) @[simp]
Mathlib/AlgebraicGeometry/Scheme.lean
219
224
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import Mathlib.Algebra.CharP.Basic import Mathlib.Algebra.Module.End import Mathlib.Algebra.Ring.Prod import Mathlib.Data.Fintype.Units import Mathlib.GroupTheory.GroupAction.SubMulAction import Mathlib.GroupTheory.OrderOfElement import Mathlib.Tactic.FinCases /-! # Integers mod `n` Definition of the integers mod n, and the field structure on the integers mod p. ## Definitions * `ZMod n`, which is for integers modulo a nat `n : ℕ` * `val a` is defined as a natural number: - for `a : ZMod 0` it is the absolute value of `a` - for `a : ZMod n` with `0 < n` it is the least natural number in the equivalence class * A coercion `cast` is defined from `ZMod n` into any ring. This is a ring hom if the ring has characteristic dividing `n` -/ assert_not_exists Field Submodule TwoSidedIdeal open Function ZMod namespace ZMod /-- For non-zero `n : ℕ`, the ring `Fin n` is equivalent to `ZMod n`. -/ def finEquiv : ∀ (n : ℕ) [NeZero n], Fin n ≃+* ZMod n | 0, h => (h.ne _ rfl).elim | _ + 1, _ => .refl _ instance charZero : CharZero (ZMod 0) := inferInstanceAs (CharZero ℤ) /-- `val a` is a natural number defined as: - for `a : ZMod 0` it is the absolute value of `a` - for `a : ZMod n` with `0 < n` it is the least natural number in the equivalence class See `ZMod.valMinAbs` for a variant that takes values in the integers. -/ def val : ∀ {n : ℕ}, ZMod n → ℕ | 0 => Int.natAbs | n + 1 => ((↑) : Fin (n + 1) → ℕ) theorem val_lt {n : ℕ} [NeZero n] (a : ZMod n) : a.val < n := by cases n · cases NeZero.ne 0 rfl exact Fin.is_lt a theorem val_le {n : ℕ} [NeZero n] (a : ZMod n) : a.val ≤ n := a.val_lt.le @[simp] theorem val_zero : ∀ {n}, (0 : ZMod n).val = 0 | 0 => rfl | _ + 1 => rfl @[simp] theorem val_one' : (1 : ZMod 0).val = 1 := rfl @[simp] theorem val_neg' {n : ZMod 0} : (-n).val = n.val := Int.natAbs_neg n @[simp] theorem val_mul' {m n : ZMod 0} : (m * n).val = m.val * n.val := Int.natAbs_mul m n @[simp] theorem val_natCast (n a : ℕ) : (a : ZMod n).val = a % n := by cases n · rw [Nat.mod_zero] exact Int.natAbs_natCast a · apply Fin.val_natCast lemma val_natCast_of_lt {n a : ℕ} (h : a < n) : (a : ZMod n).val = a := by rwa [val_natCast, Nat.mod_eq_of_lt] lemma val_ofNat (n a : ℕ) [a.AtLeastTwo] : (ofNat(a) : ZMod n).val = ofNat(a) % n := val_natCast .. lemma val_ofNat_of_lt {n a : ℕ} [a.AtLeastTwo] (han : a < n) : (ofNat(a) : ZMod n).val = ofNat(a) := val_natCast_of_lt han theorem val_unit' {n : ZMod 0} : IsUnit n ↔ n.val = 1 := by simp only [val] rw [Int.isUnit_iff, Int.natAbs_eq_iff, Nat.cast_one] lemma eq_one_of_isUnit_natCast {n : ℕ} (h : IsUnit (n : ZMod 0)) : n = 1 := by rw [← Nat.mod_zero n, ← val_natCast, val_unit'.mp h] instance charP (n : ℕ) : CharP (ZMod n) n where cast_eq_zero_iff := by intro k rcases n with - | n · simp [zero_dvd_iff, Int.natCast_eq_zero] · exact Fin.natCast_eq_zero @[simp] theorem addOrderOf_one (n : ℕ) : addOrderOf (1 : ZMod n) = n := CharP.eq _ (CharP.addOrderOf_one _) (ZMod.charP n) /-- This lemma works in the case in which `ZMod n` is not infinite, i.e. `n ≠ 0`. The version where `a ≠ 0` is `addOrderOf_coe'`. -/ @[simp] theorem addOrderOf_coe (a : ℕ) {n : ℕ} (n0 : n ≠ 0) : addOrderOf (a : ZMod n) = n / n.gcd a := by rcases a with - | a · simp only [Nat.cast_zero, addOrderOf_zero, Nat.gcd_zero_right, Nat.pos_of_ne_zero n0, Nat.div_self] rw [← Nat.smul_one_eq_cast, addOrderOf_nsmul' _ a.succ_ne_zero, ZMod.addOrderOf_one] /-- This lemma works in the case in which `a ≠ 0`. The version where `ZMod n` is not infinite, i.e. `n ≠ 0`, is `addOrderOf_coe`. -/ @[simp] theorem addOrderOf_coe' {a : ℕ} (n : ℕ) (a0 : a ≠ 0) : addOrderOf (a : ZMod n) = n / n.gcd a := by rw [← Nat.smul_one_eq_cast, addOrderOf_nsmul' _ a0, ZMod.addOrderOf_one] /-- We have that `ringChar (ZMod n) = n`. -/ theorem ringChar_zmod_n (n : ℕ) : ringChar (ZMod n) = n := by rw [ringChar.eq_iff] exact ZMod.charP n theorem natCast_self (n : ℕ) : (n : ZMod n) = 0 := CharP.cast_eq_zero (ZMod n) n @[simp] theorem natCast_self' (n : ℕ) : (n + 1 : ZMod (n + 1)) = 0 := by rw [← Nat.cast_add_one, natCast_self (n + 1)] section UniversalProperty variable {n : ℕ} {R : Type*} section variable [AddGroupWithOne R] /-- Cast an integer modulo `n` to another semiring. This function is a morphism if the characteristic of `R` divides `n`. See `ZMod.castHom` for a bundled version. -/ def cast : ∀ {n : ℕ}, ZMod n → R | 0 => Int.cast | _ + 1 => fun i => i.val @[simp] theorem cast_zero : (cast (0 : ZMod n) : R) = 0 := by delta ZMod.cast cases n · exact Int.cast_zero · simp theorem cast_eq_val [NeZero n] (a : ZMod n) : (cast a : R) = a.val := by cases n · cases NeZero.ne 0 rfl rfl variable {S : Type*} [AddGroupWithOne S] @[simp] theorem _root_.Prod.fst_zmod_cast (a : ZMod n) : (cast a : R × S).fst = cast a := by cases n · rfl · simp [ZMod.cast] @[simp] theorem _root_.Prod.snd_zmod_cast (a : ZMod n) : (cast a : R × S).snd = cast a := by cases n · rfl · simp [ZMod.cast] end /-- So-named because the coercion is `Nat.cast` into `ZMod`. For `Nat.cast` into an arbitrary ring, see `ZMod.natCast_val`. -/ theorem natCast_zmod_val {n : ℕ} [NeZero n] (a : ZMod n) : (a.val : ZMod n) = a := by cases n · cases NeZero.ne 0 rfl · apply Fin.cast_val_eq_self theorem natCast_rightInverse [NeZero n] : Function.RightInverse val ((↑) : ℕ → ZMod n) := natCast_zmod_val theorem natCast_zmod_surjective [NeZero n] : Function.Surjective ((↑) : ℕ → ZMod n) := natCast_rightInverse.surjective /-- So-named because the outer coercion is `Int.cast` into `ZMod`. For `Int.cast` into an arbitrary ring, see `ZMod.intCast_cast`. -/ @[norm_cast] theorem intCast_zmod_cast (a : ZMod n) : ((cast a : ℤ) : ZMod n) = a := by cases n · simp [ZMod.cast, ZMod] · dsimp [ZMod.cast] rw [Int.cast_natCast, natCast_zmod_val] theorem intCast_rightInverse : Function.RightInverse (cast : ZMod n → ℤ) ((↑) : ℤ → ZMod n) := intCast_zmod_cast theorem intCast_surjective : Function.Surjective ((↑) : ℤ → ZMod n) := intCast_rightInverse.surjective lemma «forall» {P : ZMod n → Prop} : (∀ x, P x) ↔ ∀ x : ℤ, P x := intCast_surjective.forall lemma «exists» {P : ZMod n → Prop} : (∃ x, P x) ↔ ∃ x : ℤ, P x := intCast_surjective.exists theorem cast_id : ∀ (n) (i : ZMod n), (ZMod.cast i : ZMod n) = i | 0, _ => Int.cast_id | _ + 1, i => natCast_zmod_val i @[simp] theorem cast_id' : (ZMod.cast : ZMod n → ZMod n) = id := funext (cast_id n) variable (R) [Ring R] /-- The coercions are respectively `Nat.cast` and `ZMod.cast`. -/ @[simp] theorem natCast_comp_val [NeZero n] : ((↑) : ℕ → R) ∘ (val : ZMod n → ℕ) = cast := by cases n · cases NeZero.ne 0 rfl rfl /-- The coercions are respectively `Int.cast`, `ZMod.cast`, and `ZMod.cast`. -/ @[simp] theorem intCast_comp_cast : ((↑) : ℤ → R) ∘ (cast : ZMod n → ℤ) = cast := by cases n · exact congr_arg (Int.cast ∘ ·) ZMod.cast_id' · ext simp [ZMod, ZMod.cast] variable {R} @[simp] theorem natCast_val [NeZero n] (i : ZMod n) : (i.val : R) = cast i := congr_fun (natCast_comp_val R) i @[simp] theorem intCast_cast (i : ZMod n) : ((cast i : ℤ) : R) = cast i := congr_fun (intCast_comp_cast R) i theorem cast_add_eq_ite {n : ℕ} (a b : ZMod n) : (cast (a + b) : ℤ) = if (n : ℤ) ≤ cast a + cast b then (cast a + cast b - n : ℤ) else cast a + cast b := by rcases n with - | n · simp; rfl change Fin (n + 1) at a b change ((((a + b) : Fin (n + 1)) : ℕ) : ℤ) = if ((n + 1 : ℕ) : ℤ) ≤ (a : ℕ) + b then _ else _ simp only [Fin.val_add_eq_ite, Int.natCast_succ, Int.ofNat_le] norm_cast split_ifs with h · rw [Nat.cast_sub h] congr · rfl section CharDvd /-! If the characteristic of `R` divides `n`, then `cast` is a homomorphism. -/ variable {m : ℕ} [CharP R m] @[simp] theorem cast_one (h : m ∣ n) : (cast (1 : ZMod n) : R) = 1 := by rcases n with - | n · exact Int.cast_one show ((1 % (n + 1) : ℕ) : R) = 1 cases n · rw [Nat.dvd_one] at h subst m subsingleton [CharP.CharOne.subsingleton] rw [Nat.mod_eq_of_lt] · exact Nat.cast_one exact Nat.lt_of_sub_eq_succ rfl theorem cast_add (h : m ∣ n) (a b : ZMod n) : (cast (a + b : ZMod n) : R) = cast a + cast b := by cases n · apply Int.cast_add symm dsimp [ZMod, ZMod.cast, ZMod.val] rw [← Nat.cast_add, Fin.val_add, ← sub_eq_zero, ← Nat.cast_sub (Nat.mod_le _ _), @CharP.cast_eq_zero_iff R _ m] exact h.trans (Nat.dvd_sub_mod _) theorem cast_mul (h : m ∣ n) (a b : ZMod n) : (cast (a * b : ZMod n) : R) = cast a * cast b := by cases n · apply Int.cast_mul symm dsimp [ZMod, ZMod.cast, ZMod.val] rw [← Nat.cast_mul, Fin.val_mul, ← sub_eq_zero, ← Nat.cast_sub (Nat.mod_le _ _), @CharP.cast_eq_zero_iff R _ m] exact h.trans (Nat.dvd_sub_mod _) /-- The canonical ring homomorphism from `ZMod n` to a ring of characteristic dividing `n`. See also `ZMod.lift` for a generalized version working in `AddGroup`s. -/ def castHom (h : m ∣ n) (R : Type*) [Ring R] [CharP R m] : ZMod n →+* R where toFun := cast map_zero' := cast_zero map_one' := cast_one h map_add' := cast_add h map_mul' := cast_mul h @[simp] theorem castHom_apply {h : m ∣ n} (i : ZMod n) : castHom h R i = cast i := rfl @[simp] theorem cast_sub (h : m ∣ n) (a b : ZMod n) : (cast (a - b : ZMod n) : R) = cast a - cast b := (castHom h R).map_sub a b @[simp] theorem cast_neg (h : m ∣ n) (a : ZMod n) : (cast (-a : ZMod n) : R) = -(cast a) := (castHom h R).map_neg a @[simp] theorem cast_pow (h : m ∣ n) (a : ZMod n) (k : ℕ) : (cast (a ^ k : ZMod n) : R) = (cast a) ^ k := (castHom h R).map_pow a k @[simp, norm_cast] theorem cast_natCast (h : m ∣ n) (k : ℕ) : (cast (k : ZMod n) : R) = k := map_natCast (castHom h R) k @[simp, norm_cast] theorem cast_intCast (h : m ∣ n) (k : ℤ) : (cast (k : ZMod n) : R) = k := map_intCast (castHom h R) k end CharDvd section CharEq /-! Some specialised simp lemmas which apply when `R` has characteristic `n`. -/ variable [CharP R n] @[simp] theorem cast_one' : (cast (1 : ZMod n) : R) = 1 := cast_one dvd_rfl @[simp] theorem cast_add' (a b : ZMod n) : (cast (a + b : ZMod n) : R) = cast a + cast b := cast_add dvd_rfl a b @[simp] theorem cast_mul' (a b : ZMod n) : (cast (a * b : ZMod n) : R) = cast a * cast b := cast_mul dvd_rfl a b @[simp] theorem cast_sub' (a b : ZMod n) : (cast (a - b : ZMod n) : R) = cast a - cast b := cast_sub dvd_rfl a b @[simp] theorem cast_pow' (a : ZMod n) (k : ℕ) : (cast (a ^ k : ZMod n) : R) = (cast a : R) ^ k := cast_pow dvd_rfl a k @[simp, norm_cast] theorem cast_natCast' (k : ℕ) : (cast (k : ZMod n) : R) = k := cast_natCast dvd_rfl k @[simp, norm_cast] theorem cast_intCast' (k : ℤ) : (cast (k : ZMod n) : R) = k := cast_intCast dvd_rfl k variable (R) theorem castHom_injective : Function.Injective (ZMod.castHom (dvd_refl n) R) := by rw [injective_iff_map_eq_zero] intro x obtain ⟨k, rfl⟩ := ZMod.intCast_surjective x rw [map_intCast, CharP.intCast_eq_zero_iff R n, CharP.intCast_eq_zero_iff (ZMod n) n] exact id theorem castHom_bijective [Fintype R] (h : Fintype.card R = n) : Function.Bijective (ZMod.castHom (dvd_refl n) R) := by haveI : NeZero n := ⟨by intro hn rw [hn] at h exact (Fintype.card_eq_zero_iff.mp h).elim' 0⟩ rw [Fintype.bijective_iff_injective_and_card, ZMod.card, h, eq_self_iff_true, and_true] apply ZMod.castHom_injective /-- The unique ring isomorphism between `ZMod n` and a ring `R` of characteristic `n` and cardinality `n`. -/ noncomputable def ringEquiv [Fintype R] (h : Fintype.card R = n) : ZMod n ≃+* R := RingEquiv.ofBijective _ (ZMod.castHom_bijective R h) /-- The unique ring isomorphism between `ZMod p` and a ring `R` of cardinality a prime `p`. If you need any property of this isomorphism, first of all use `ringEquivOfPrime_eq_ringEquiv` below (after `have : CharP R p := ...`) and deduce it by the results about `ZMod.ringEquiv`. -/ noncomputable def ringEquivOfPrime [Fintype R] {p : ℕ} (hp : p.Prime) (hR : Fintype.card R = p) : ZMod p ≃+* R := have : Nontrivial R := Fintype.one_lt_card_iff_nontrivial.1 (hR ▸ hp.one_lt) -- The following line exists as `charP_of_card_eq_prime` in `Mathlib.Algebra.CharP.CharAndCard`. have : CharP R p := (CharP.charP_iff_prime_eq_zero hp).2 (hR ▸ Nat.cast_card_eq_zero R) ZMod.ringEquiv R hR @[simp] lemma ringEquivOfPrime_eq_ringEquiv [Fintype R] {p : ℕ} [CharP R p] (hp : p.Prime) (hR : Fintype.card R = p) : ringEquivOfPrime R hp hR = ringEquiv R hR := rfl /-- The identity between `ZMod m` and `ZMod n` when `m = n`, as a ring isomorphism. -/ def ringEquivCongr {m n : ℕ} (h : m = n) : ZMod m ≃+* ZMod n := by rcases m with - | m <;> rcases n with - | n · exact RingEquiv.refl _ · exfalso exact n.succ_ne_zero h.symm · exfalso exact m.succ_ne_zero h · exact { finCongr h with map_mul' := fun a b => by dsimp [ZMod] ext rw [Fin.coe_cast, Fin.coe_mul, Fin.coe_mul, Fin.coe_cast, Fin.coe_cast, ← h] map_add' := fun a b => by dsimp [ZMod] ext rw [Fin.coe_cast, Fin.val_add, Fin.val_add, Fin.coe_cast, Fin.coe_cast, ← h] } @[simp] lemma ringEquivCongr_refl (a : ℕ) : ringEquivCongr (rfl : a = a) = .refl _ := by cases a <;> rfl lemma ringEquivCongr_refl_apply {a : ℕ} (x : ZMod a) : ringEquivCongr rfl x = x := by rw [ringEquivCongr_refl] rfl lemma ringEquivCongr_symm {a b : ℕ} (hab : a = b) : (ringEquivCongr hab).symm = ringEquivCongr hab.symm := by subst hab cases a <;> rfl lemma ringEquivCongr_trans {a b c : ℕ} (hab : a = b) (hbc : b = c) : (ringEquivCongr hab).trans (ringEquivCongr hbc) = ringEquivCongr (hab.trans hbc) := by subst hab hbc cases a <;> rfl lemma ringEquivCongr_ringEquivCongr_apply {a b c : ℕ} (hab : a = b) (hbc : b = c) (x : ZMod a) : ringEquivCongr hbc (ringEquivCongr hab x) = ringEquivCongr (hab.trans hbc) x := by rw [← ringEquivCongr_trans hab hbc] rfl lemma ringEquivCongr_val {a b : ℕ} (h : a = b) (x : ZMod a) : ZMod.val ((ZMod.ringEquivCongr h) x) = ZMod.val x := by subst h cases a <;> rfl lemma ringEquivCongr_intCast {a b : ℕ} (h : a = b) (z : ℤ) : ZMod.ringEquivCongr h z = z := by subst h cases a <;> rfl end CharEq end UniversalProperty variable {m n : ℕ} @[simp] theorem val_eq_zero : ∀ {n : ℕ} (a : ZMod n), a.val = 0 ↔ a = 0 | 0, _ => Int.natAbs_eq_zero | n + 1, a => by rw [Fin.ext_iff] exact Iff.rfl theorem intCast_eq_intCast_iff (a b : ℤ) (c : ℕ) : (a : ZMod c) = (b : ZMod c) ↔ a ≡ b [ZMOD c] := CharP.intCast_eq_intCast (ZMod c) c theorem intCast_eq_intCast_iff' (a b : ℤ) (c : ℕ) : (a : ZMod c) = (b : ZMod c) ↔ a % c = b % c := ZMod.intCast_eq_intCast_iff a b c theorem val_intCast {n : ℕ} (a : ℤ) [NeZero n] : ↑(a : ZMod n).val = a % n := by have hle : (0 : ℤ) ≤ ↑(a : ZMod n).val := Int.natCast_nonneg _ have hlt : ↑(a : ZMod n).val < (n : ℤ) := Int.ofNat_lt.mpr (ZMod.val_lt a) refine (Int.emod_eq_of_lt hle hlt).symm.trans ?_ rw [← ZMod.intCast_eq_intCast_iff', Int.cast_natCast, ZMod.natCast_val, ZMod.cast_id] theorem natCast_eq_natCast_iff (a b c : ℕ) : (a : ZMod c) = (b : ZMod c) ↔ a ≡ b [MOD c] := by simpa [Int.natCast_modEq_iff] using ZMod.intCast_eq_intCast_iff a b c theorem natCast_eq_natCast_iff' (a b c : ℕ) : (a : ZMod c) = (b : ZMod c) ↔ a % c = b % c := ZMod.natCast_eq_natCast_iff a b c theorem intCast_zmod_eq_zero_iff_dvd (a : ℤ) (b : ℕ) : (a : ZMod b) = 0 ↔ (b : ℤ) ∣ a := by rw [← Int.cast_zero, ZMod.intCast_eq_intCast_iff, Int.modEq_zero_iff_dvd] theorem intCast_eq_intCast_iff_dvd_sub (a b : ℤ) (c : ℕ) : (a : ZMod c) = ↑b ↔ ↑c ∣ b - a := by rw [ZMod.intCast_eq_intCast_iff, Int.modEq_iff_dvd] theorem natCast_zmod_eq_zero_iff_dvd (a b : ℕ) : (a : ZMod b) = 0 ↔ b ∣ a := by rw [← Nat.cast_zero, ZMod.natCast_eq_natCast_iff, Nat.modEq_zero_iff_dvd] theorem coe_intCast (a : ℤ) : cast (a : ZMod n) = a % n := by cases n · rw [Int.ofNat_zero, Int.emod_zero, Int.cast_id]; rfl · rw [← val_intCast, val]; rfl lemma intCast_cast_add (x y : ZMod n) : (cast (x + y) : ℤ) = (cast x + cast y) % n := by rw [← ZMod.coe_intCast, Int.cast_add, ZMod.intCast_zmod_cast, ZMod.intCast_zmod_cast] lemma intCast_cast_mul (x y : ZMod n) : (cast (x * y) : ℤ) = cast x * cast y % n := by rw [← ZMod.coe_intCast, Int.cast_mul, ZMod.intCast_zmod_cast, ZMod.intCast_zmod_cast] lemma intCast_cast_sub (x y : ZMod n) : (cast (x - y) : ℤ) = (cast x - cast y) % n := by rw [← ZMod.coe_intCast, Int.cast_sub, ZMod.intCast_zmod_cast, ZMod.intCast_zmod_cast] lemma intCast_cast_neg (x : ZMod n) : (cast (-x) : ℤ) = -cast x % n := by rw [← ZMod.coe_intCast, Int.cast_neg, ZMod.intCast_zmod_cast] @[simp] theorem val_neg_one (n : ℕ) : (-1 : ZMod n.succ).val = n := by dsimp [val, Fin.coe_neg] cases n · simp [Nat.mod_one] · dsimp [ZMod, ZMod.cast] rw [Fin.coe_neg_one] /-- `-1 : ZMod n` lifts to `n - 1 : R`. This avoids the characteristic assumption in `cast_neg`. -/ theorem cast_neg_one {R : Type*} [Ring R] (n : ℕ) : cast (-1 : ZMod n) = (n - 1 : R) := by rcases n with - | n · dsimp [ZMod, ZMod.cast]; simp · rw [← natCast_val, val_neg_one, Nat.cast_succ, add_sub_cancel_right] theorem cast_sub_one {R : Type*} [Ring R] {n : ℕ} (k : ZMod n) : (cast (k - 1 : ZMod n) : R) = (if k = 0 then (n : R) else cast k) - 1 := by split_ifs with hk · rw [hk, zero_sub, ZMod.cast_neg_one] · cases n · dsimp [ZMod, ZMod.cast] rw [Int.cast_sub, Int.cast_one] · dsimp [ZMod, ZMod.cast, ZMod.val] rw [Fin.coe_sub_one, if_neg] · rw [Nat.cast_sub, Nat.cast_one] rwa [Fin.ext_iff, Fin.val_zero, ← Ne, ← Nat.one_le_iff_ne_zero] at hk · exact hk theorem natCast_eq_iff (p : ℕ) (n : ℕ) (z : ZMod p) [NeZero p] : ↑n = z ↔ ∃ k, n = z.val + p * k := by constructor · rintro rfl refine ⟨n / p, ?_⟩ rw [val_natCast, Nat.mod_add_div] · rintro ⟨k, rfl⟩ rw [Nat.cast_add, natCast_zmod_val, Nat.cast_mul, natCast_self, zero_mul, add_zero] theorem intCast_eq_iff (p : ℕ) (n : ℤ) (z : ZMod p) [NeZero p] : ↑n = z ↔ ∃ k, n = z.val + p * k := by constructor · rintro rfl refine ⟨n / p, ?_⟩ rw [val_intCast, Int.emod_add_ediv] · rintro ⟨k, rfl⟩ rw [Int.cast_add, Int.cast_mul, Int.cast_natCast, Int.cast_natCast, natCast_val, ZMod.natCast_self, zero_mul, add_zero, cast_id] @[push_cast, simp] theorem intCast_mod (a : ℤ) (b : ℕ) : ((a % b : ℤ) : ZMod b) = (a : ZMod b) := by rw [ZMod.intCast_eq_intCast_iff] apply Int.mod_modEq theorem ker_intCastAddHom (n : ℕ) : (Int.castAddHom (ZMod n)).ker = AddSubgroup.zmultiples (n : ℤ) := by ext rw [Int.mem_zmultiples_iff, AddMonoidHom.mem_ker, Int.coe_castAddHom, intCast_zmod_eq_zero_iff_dvd] theorem cast_injective_of_le {m n : ℕ} [nzm : NeZero m] (h : m ≤ n) : Function.Injective (@cast (ZMod n) _ m) := by cases m with | zero => cases nzm; simp_all | succ m => rintro ⟨x, hx⟩ ⟨y, hy⟩ f simp only [cast, val, natCast_eq_natCast_iff', Nat.mod_eq_of_lt (hx.trans_le h), Nat.mod_eq_of_lt (hy.trans_le h)] at f apply Fin.ext exact f theorem cast_zmod_eq_zero_iff_of_le {m n : ℕ} [NeZero m] (h : m ≤ n) (a : ZMod m) : (cast a : ZMod n) = 0 ↔ a = 0 := by rw [← ZMod.cast_zero (n := m)] exact Injective.eq_iff' (cast_injective_of_le h) rfl @[simp] theorem natCast_toNat (p : ℕ) : ∀ {z : ℤ} (_h : 0 ≤ z), (z.toNat : ZMod p) = z | (n : ℕ), _h => by simp only [Int.cast_natCast, Int.toNat_natCast] | Int.negSucc n, h => by simp at h theorem val_injective (n : ℕ) [NeZero n] : Function.Injective (val : ZMod n → ℕ) := by cases n · cases NeZero.ne 0 rfl intro a b h dsimp [ZMod] ext exact h theorem val_one_eq_one_mod (n : ℕ) : (1 : ZMod n).val = 1 % n := by rw [← Nat.cast_one, val_natCast] theorem val_two_eq_two_mod (n : ℕ) : (2 : ZMod n).val = 2 % n := by rw [← Nat.cast_two, val_natCast] theorem val_one (n : ℕ) [Fact (1 < n)] : (1 : ZMod n).val = 1 := by rw [val_one_eq_one_mod] exact Nat.mod_eq_of_lt Fact.out lemma val_one'' : ∀ {n}, n ≠ 1 → (1 : ZMod n).val = 1 | 0, _ => rfl | 1, hn => by cases hn rfl | n + 2, _ => haveI : Fact (1 < n + 2) := ⟨by simp⟩ ZMod.val_one _
theorem val_add {n : ℕ} [NeZero n] (a b : ZMod n) : (a + b).val = (a.val + b.val) % n := by cases n · cases NeZero.ne 0 rfl · apply Fin.val_add
Mathlib/Data/ZMod/Basic.lean
626
629
/- Copyright (c) 2019 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner, Sébastien Gouëzel -/ import Mathlib.Analysis.Calculus.FDeriv.Basic import Mathlib.Analysis.NormedSpace.OperatorNorm.NormedSpace /-! # One-dimensional derivatives This file defines the derivative of a function `f : 𝕜 → F` where `𝕜` is a normed field and `F` is a normed space over this field. The derivative of such a function `f` at a point `x` is given by an element `f' : F`. The theory is developed analogously to the [Fréchet derivatives](./fderiv.html). We first introduce predicates defined in terms of the corresponding predicates for Fréchet derivatives: - `HasDerivAtFilter f f' x L` states that the function `f` has the derivative `f'` at the point `x` as `x` goes along the filter `L`. - `HasDerivWithinAt f f' s x` states that the function `f` has the derivative `f'` at the point `x` within the subset `s`. - `HasDerivAt f f' x` states that the function `f` has the derivative `f'` at the point `x`. - `HasStrictDerivAt f f' x` states that the function `f` has the derivative `f'` at the point `x` in the sense of strict differentiability, i.e., `f y - f z = (y - z) • f' + o (y - z)` as `y, z → x`. For the last two notions we also define a functional version: - `derivWithin f s x` is a derivative of `f` at `x` within `s`. If the derivative does not exist, then `derivWithin f s x` equals zero. - `deriv f x` is a derivative of `f` at `x`. If the derivative does not exist, then `deriv f x` equals zero. The theorems `fderivWithin_derivWithin` and `fderiv_deriv` show that the one-dimensional derivatives coincide with the general Fréchet derivatives. We also show the existence and compute the derivatives of: - constants - the identity function - linear maps (in `Linear.lean`) - addition (in `Add.lean`) - sum of finitely many functions (in `Add.lean`) - negation (in `Add.lean`) - subtraction (in `Add.lean`) - star (in `Star.lean`) - multiplication of two functions in `𝕜 → 𝕜` (in `Mul.lean`) - multiplication of a function in `𝕜 → 𝕜` and of a function in `𝕜 → E` (in `Mul.lean`) - powers of a function (in `Pow.lean` and `ZPow.lean`) - inverse `x → x⁻¹` (in `Inv.lean`) - division (in `Inv.lean`) - composition of a function in `𝕜 → F` with a function in `𝕜 → 𝕜` (in `Comp.lean`) - composition of a function in `F → E` with a function in `𝕜 → F` (in `Comp.lean`) - inverse function (assuming that it exists; the inverse function theorem is in `Inverse.lean`) - polynomials (in `Polynomial.lean`) For most binary operations we also define `const_op` and `op_const` theorems for the cases when the first or second argument is a constant. This makes writing chains of `HasDerivAt`'s easier, and they more frequently lead to the desired result. We set up the simplifier so that it can compute the derivative of simple functions. For instance, ```lean example (x : ℝ) : deriv (fun x ↦ cos (sin x) * exp x) x = (cos (sin x) - sin (sin x) * cos x) * exp x := by simp; ring ``` The relationship between the derivative of a function and its definition from a standard undergraduate course as the limit of the slope `(f y - f x) / (y - x)` as `y` tends to `𝓝[≠] x` is developed in the file `Slope.lean`. ## Implementation notes Most of the theorems are direct restatements of the corresponding theorems for Fréchet derivatives. The strategy to construct simp lemmas that give the simplifier the possibility to compute derivatives is the same as the one for differentiability statements, as explained in `FDeriv/Basic.lean`. See the explanations there. -/ universe u v w noncomputable section open scoped Topology ENNReal NNReal open Filter Asymptotics Set open ContinuousLinearMap (smulRight smulRight_one_eq_iff) section TVS variable {𝕜 : Type u} [NontriviallyNormedField 𝕜] variable {F : Type v} [AddCommGroup F] [Module 𝕜 F] [TopologicalSpace F] section variable [ContinuousSMul 𝕜 F] /-- `f` has the derivative `f'` at the point `x` as `x` goes along the filter `L`. That is, `f x' = f x + (x' - x) • f' + o(x' - x)` where `x'` converges along the filter `L`. -/ def HasDerivAtFilter (f : 𝕜 → F) (f' : F) (x : 𝕜) (L : Filter 𝕜) := HasFDerivAtFilter f (smulRight (1 : 𝕜 →L[𝕜] 𝕜) f') x L /-- `f` has the derivative `f'` at the point `x` within the subset `s`. That is, `f x' = f x + (x' - x) • f' + o(x' - x)` where `x'` converges to `x` inside `s`. -/ def HasDerivWithinAt (f : 𝕜 → F) (f' : F) (s : Set 𝕜) (x : 𝕜) := HasDerivAtFilter f f' x (𝓝[s] x) /-- `f` has the derivative `f'` at the point `x`. That is, `f x' = f x + (x' - x) • f' + o(x' - x)` where `x'` converges to `x`. -/ def HasDerivAt (f : 𝕜 → F) (f' : F) (x : 𝕜) := HasDerivAtFilter f f' x (𝓝 x) /-- `f` has the derivative `f'` at the point `x` in the sense of strict differentiability. That is, `f y - f z = (y - z) • f' + o(y - z)` as `y, z → x`. -/ def HasStrictDerivAt (f : 𝕜 → F) (f' : F) (x : 𝕜) := HasStrictFDerivAt f (smulRight (1 : 𝕜 →L[𝕜] 𝕜) f') x end /-- Derivative of `f` at the point `x` within the set `s`, if it exists. Zero otherwise. If the derivative exists (i.e., `∃ f', HasDerivWithinAt f f' s x`), then `f x' = f x + (x' - x) • derivWithin f s x + o(x' - x)` where `x'` converges to `x` inside `s`. -/ def derivWithin (f : 𝕜 → F) (s : Set 𝕜) (x : 𝕜) := fderivWithin 𝕜 f s x 1 /-- Derivative of `f` at the point `x`, if it exists. Zero otherwise. If the derivative exists (i.e., `∃ f', HasDerivAt f f' x`), then `f x' = f x + (x' - x) • deriv f x + o(x' - x)` where `x'` converges to `x`. -/ def deriv (f : 𝕜 → F) (x : 𝕜) := fderiv 𝕜 f x 1 variable {f f₀ f₁ : 𝕜 → F} variable {f' f₀' f₁' g' : F} variable {x : 𝕜} variable {s t : Set 𝕜} variable {L L₁ L₂ : Filter 𝕜} section variable [ContinuousSMul 𝕜 F] /-- Expressing `HasFDerivAtFilter f f' x L` in terms of `HasDerivAtFilter` -/ theorem hasFDerivAtFilter_iff_hasDerivAtFilter {f' : 𝕜 →L[𝕜] F} : HasFDerivAtFilter f f' x L ↔ HasDerivAtFilter f (f' 1) x L := by simp [HasDerivAtFilter] theorem HasFDerivAtFilter.hasDerivAtFilter {f' : 𝕜 →L[𝕜] F} : HasFDerivAtFilter f f' x L → HasDerivAtFilter f (f' 1) x L := hasFDerivAtFilter_iff_hasDerivAtFilter.mp /-- Expressing `HasFDerivWithinAt f f' s x` in terms of `HasDerivWithinAt` -/ theorem hasFDerivWithinAt_iff_hasDerivWithinAt {f' : 𝕜 →L[𝕜] F} : HasFDerivWithinAt f f' s x ↔ HasDerivWithinAt f (f' 1) s x := hasFDerivAtFilter_iff_hasDerivAtFilter /-- Expressing `HasDerivWithinAt f f' s x` in terms of `HasFDerivWithinAt` -/ theorem hasDerivWithinAt_iff_hasFDerivWithinAt {f' : F} : HasDerivWithinAt f f' s x ↔ HasFDerivWithinAt f (smulRight (1 : 𝕜 →L[𝕜] 𝕜) f') s x := Iff.rfl theorem HasFDerivWithinAt.hasDerivWithinAt {f' : 𝕜 →L[𝕜] F} : HasFDerivWithinAt f f' s x → HasDerivWithinAt f (f' 1) s x := hasFDerivWithinAt_iff_hasDerivWithinAt.mp theorem HasDerivWithinAt.hasFDerivWithinAt {f' : F} : HasDerivWithinAt f f' s x → HasFDerivWithinAt f (smulRight (1 : 𝕜 →L[𝕜] 𝕜) f') s x := hasDerivWithinAt_iff_hasFDerivWithinAt.mp /-- Expressing `HasFDerivAt f f' x` in terms of `HasDerivAt` -/ theorem hasFDerivAt_iff_hasDerivAt {f' : 𝕜 →L[𝕜] F} : HasFDerivAt f f' x ↔ HasDerivAt f (f' 1) x := hasFDerivAtFilter_iff_hasDerivAtFilter theorem HasFDerivAt.hasDerivAt {f' : 𝕜 →L[𝕜] F} : HasFDerivAt f f' x → HasDerivAt f (f' 1) x := hasFDerivAt_iff_hasDerivAt.mp theorem hasStrictFDerivAt_iff_hasStrictDerivAt {f' : 𝕜 →L[𝕜] F} : HasStrictFDerivAt f f' x ↔ HasStrictDerivAt f (f' 1) x := by simp [HasStrictDerivAt, HasStrictFDerivAt] protected theorem HasStrictFDerivAt.hasStrictDerivAt {f' : 𝕜 →L[𝕜] F} : HasStrictFDerivAt f f' x → HasStrictDerivAt f (f' 1) x := hasStrictFDerivAt_iff_hasStrictDerivAt.mp theorem hasStrictDerivAt_iff_hasStrictFDerivAt : HasStrictDerivAt f f' x ↔ HasStrictFDerivAt f (smulRight (1 : 𝕜 →L[𝕜] 𝕜) f') x := Iff.rfl alias ⟨HasStrictDerivAt.hasStrictFDerivAt, _⟩ := hasStrictDerivAt_iff_hasStrictFDerivAt /-- Expressing `HasDerivAt f f' x` in terms of `HasFDerivAt` -/ theorem hasDerivAt_iff_hasFDerivAt {f' : F} : HasDerivAt f f' x ↔ HasFDerivAt f (smulRight (1 : 𝕜 →L[𝕜] 𝕜) f') x := Iff.rfl alias ⟨HasDerivAt.hasFDerivAt, _⟩ := hasDerivAt_iff_hasFDerivAt end theorem derivWithin_zero_of_not_differentiableWithinAt (h : ¬DifferentiableWithinAt 𝕜 f s x) : derivWithin f s x = 0 := by unfold derivWithin rw [fderivWithin_zero_of_not_differentiableWithinAt h] simp theorem differentiableWithinAt_of_derivWithin_ne_zero (h : derivWithin f s x ≠ 0) : DifferentiableWithinAt 𝕜 f s x := not_imp_comm.1 derivWithin_zero_of_not_differentiableWithinAt h end TVS variable {𝕜 : Type u} [NontriviallyNormedField 𝕜] variable {F : Type v} [NormedAddCommGroup F] [NormedSpace 𝕜 F] variable {f f₀ f₁ : 𝕜 → F} variable {f' f₀' f₁' g' : F} variable {x : 𝕜} variable {s t : Set 𝕜} variable {L L₁ L₂ : Filter 𝕜} theorem derivWithin_zero_of_not_accPt (h : ¬AccPt x (𝓟 s)) : derivWithin f s x = 0 := by rw [derivWithin, fderivWithin_zero_of_not_accPt h, ContinuousLinearMap.zero_apply] theorem derivWithin_zero_of_not_uniqueDiffWithinAt (h : ¬UniqueDiffWithinAt 𝕜 s x) : derivWithin f s x = 0 := derivWithin_zero_of_not_accPt <| mt AccPt.uniqueDiffWithinAt h set_option linter.deprecated false in @[deprecated derivWithin_zero_of_not_accPt (since := "2025-04-20")] theorem derivWithin_zero_of_isolated (h : 𝓝[s \ {x}] x = ⊥) : derivWithin f s x = 0 := by rw [derivWithin, fderivWithin_zero_of_isolated h, ContinuousLinearMap.zero_apply] theorem derivWithin_zero_of_nmem_closure (h : x ∉ closure s) : derivWithin f s x = 0 := by rw [derivWithin, fderivWithin_zero_of_nmem_closure h, ContinuousLinearMap.zero_apply] theorem deriv_zero_of_not_differentiableAt (h : ¬DifferentiableAt 𝕜 f x) : deriv f x = 0 := by unfold deriv rw [fderiv_zero_of_not_differentiableAt h] simp theorem differentiableAt_of_deriv_ne_zero (h : deriv f x ≠ 0) : DifferentiableAt 𝕜 f x := not_imp_comm.1 deriv_zero_of_not_differentiableAt h theorem UniqueDiffWithinAt.eq_deriv (s : Set 𝕜) (H : UniqueDiffWithinAt 𝕜 s x) (h : HasDerivWithinAt f f' s x) (h₁ : HasDerivWithinAt f f₁' s x) : f' = f₁' := smulRight_one_eq_iff.mp <| UniqueDiffWithinAt.eq H h h₁ theorem hasDerivAtFilter_iff_isLittleO : HasDerivAtFilter f f' x L ↔ (fun x' : 𝕜 => f x' - f x - (x' - x) • f') =o[L] fun x' => x' - x := hasFDerivAtFilter_iff_isLittleO .. theorem hasDerivAtFilter_iff_tendsto : HasDerivAtFilter f f' x L ↔ Tendsto (fun x' : 𝕜 => ‖x' - x‖⁻¹ * ‖f x' - f x - (x' - x) • f'‖) L (𝓝 0) := hasFDerivAtFilter_iff_tendsto theorem hasDerivWithinAt_iff_isLittleO : HasDerivWithinAt f f' s x ↔ (fun x' : 𝕜 => f x' - f x - (x' - x) • f') =o[𝓝[s] x] fun x' => x' - x := hasFDerivAtFilter_iff_isLittleO .. theorem hasDerivWithinAt_iff_tendsto : HasDerivWithinAt f f' s x ↔ Tendsto (fun x' => ‖x' - x‖⁻¹ * ‖f x' - f x - (x' - x) • f'‖) (𝓝[s] x) (𝓝 0) := hasFDerivAtFilter_iff_tendsto theorem hasDerivAt_iff_isLittleO : HasDerivAt f f' x ↔ (fun x' : 𝕜 => f x' - f x - (x' - x) • f') =o[𝓝 x] fun x' => x' - x := hasFDerivAtFilter_iff_isLittleO .. theorem hasDerivAt_iff_tendsto : HasDerivAt f f' x ↔ Tendsto (fun x' => ‖x' - x‖⁻¹ * ‖f x' - f x - (x' - x) • f'‖) (𝓝 x) (𝓝 0) := hasFDerivAtFilter_iff_tendsto theorem HasDerivAtFilter.isBigO_sub (h : HasDerivAtFilter f f' x L) : (fun x' => f x' - f x) =O[L] fun x' => x' - x := HasFDerivAtFilter.isBigO_sub h nonrec theorem HasDerivAtFilter.isBigO_sub_rev (hf : HasDerivAtFilter f f' x L) (hf' : f' ≠ 0) : (fun x' => x' - x) =O[L] fun x' => f x' - f x := suffices AntilipschitzWith ‖f'‖₊⁻¹ (smulRight (1 : 𝕜 →L[𝕜] 𝕜) f') from hf.isBigO_sub_rev this AddMonoidHomClass.antilipschitz_of_bound (smulRight (1 : 𝕜 →L[𝕜] 𝕜) f') fun x => by simp [norm_smul, ← div_eq_inv_mul, mul_div_cancel_right₀ _ (mt norm_eq_zero.1 hf')] theorem HasStrictDerivAt.hasDerivAt (h : HasStrictDerivAt f f' x) : HasDerivAt f f' x := h.hasFDerivAt theorem hasDerivWithinAt_congr_set' {s t : Set 𝕜} (y : 𝕜) (h : s =ᶠ[𝓝[{y}ᶜ] x] t) : HasDerivWithinAt f f' s x ↔ HasDerivWithinAt f f' t x := hasFDerivWithinAt_congr_set' y h theorem hasDerivWithinAt_congr_set {s t : Set 𝕜} (h : s =ᶠ[𝓝 x] t) : HasDerivWithinAt f f' s x ↔ HasDerivWithinAt f f' t x := hasFDerivWithinAt_congr_set h alias ⟨HasDerivWithinAt.congr_set, _⟩ := hasDerivWithinAt_congr_set @[simp] theorem hasDerivWithinAt_diff_singleton : HasDerivWithinAt f f' (s \ {x}) x ↔ HasDerivWithinAt f f' s x := hasFDerivWithinAt_diff_singleton _ @[simp] theorem hasDerivWithinAt_Ioi_iff_Ici [PartialOrder 𝕜] : HasDerivWithinAt f f' (Ioi x) x ↔ HasDerivWithinAt f f' (Ici x) x := by rw [← Ici_diff_left, hasDerivWithinAt_diff_singleton] alias ⟨HasDerivWithinAt.Ici_of_Ioi, HasDerivWithinAt.Ioi_of_Ici⟩ := hasDerivWithinAt_Ioi_iff_Ici @[simp] theorem hasDerivWithinAt_Iio_iff_Iic [PartialOrder 𝕜] : HasDerivWithinAt f f' (Iio x) x ↔ HasDerivWithinAt f f' (Iic x) x := by rw [← Iic_diff_right, hasDerivWithinAt_diff_singleton] alias ⟨HasDerivWithinAt.Iic_of_Iio, HasDerivWithinAt.Iio_of_Iic⟩ := hasDerivWithinAt_Iio_iff_Iic theorem HasDerivWithinAt.Ioi_iff_Ioo [LinearOrder 𝕜] [OrderClosedTopology 𝕜] {x y : 𝕜} (h : x < y) : HasDerivWithinAt f f' (Ioo x y) x ↔ HasDerivWithinAt f f' (Ioi x) x := hasFDerivWithinAt_inter <| Iio_mem_nhds h alias ⟨HasDerivWithinAt.Ioi_of_Ioo, HasDerivWithinAt.Ioo_of_Ioi⟩ := HasDerivWithinAt.Ioi_iff_Ioo theorem hasDerivAt_iff_isLittleO_nhds_zero : HasDerivAt f f' x ↔ (fun h => f (x + h) - f x - h • f') =o[𝓝 0] fun h => h := hasFDerivAt_iff_isLittleO_nhds_zero theorem HasDerivAtFilter.mono (h : HasDerivAtFilter f f' x L₂) (hst : L₁ ≤ L₂) : HasDerivAtFilter f f' x L₁ := HasFDerivAtFilter.mono h hst theorem HasDerivWithinAt.mono (h : HasDerivWithinAt f f' t x) (hst : s ⊆ t) : HasDerivWithinAt f f' s x := HasFDerivWithinAt.mono h hst theorem HasDerivWithinAt.mono_of_mem_nhdsWithin (h : HasDerivWithinAt f f' t x) (hst : t ∈ 𝓝[s] x) : HasDerivWithinAt f f' s x := HasFDerivWithinAt.mono_of_mem_nhdsWithin h hst @[deprecated (since := "2024-10-31")] alias HasDerivWithinAt.mono_of_mem := HasDerivWithinAt.mono_of_mem_nhdsWithin theorem HasDerivAt.hasDerivAtFilter (h : HasDerivAt f f' x) (hL : L ≤ 𝓝 x) : HasDerivAtFilter f f' x L := HasFDerivAt.hasFDerivAtFilter h hL theorem HasDerivAt.hasDerivWithinAt (h : HasDerivAt f f' x) : HasDerivWithinAt f f' s x := HasFDerivAt.hasFDerivWithinAt h theorem HasDerivWithinAt.differentiableWithinAt (h : HasDerivWithinAt f f' s x) : DifferentiableWithinAt 𝕜 f s x := HasFDerivWithinAt.differentiableWithinAt h theorem HasDerivAt.differentiableAt (h : HasDerivAt f f' x) : DifferentiableAt 𝕜 f x := HasFDerivAt.differentiableAt h @[simp] theorem hasDerivWithinAt_univ : HasDerivWithinAt f f' univ x ↔ HasDerivAt f f' x := hasFDerivWithinAt_univ theorem HasDerivAt.unique (h₀ : HasDerivAt f f₀' x) (h₁ : HasDerivAt f f₁' x) : f₀' = f₁' := smulRight_one_eq_iff.mp <| h₀.hasFDerivAt.unique h₁ theorem hasDerivWithinAt_inter' (h : t ∈ 𝓝[s] x) : HasDerivWithinAt f f' (s ∩ t) x ↔ HasDerivWithinAt f f' s x := hasFDerivWithinAt_inter' h theorem hasDerivWithinAt_inter (h : t ∈ 𝓝 x) : HasDerivWithinAt f f' (s ∩ t) x ↔ HasDerivWithinAt f f' s x := hasFDerivWithinAt_inter h theorem HasDerivWithinAt.union (hs : HasDerivWithinAt f f' s x) (ht : HasDerivWithinAt f f' t x) : HasDerivWithinAt f f' (s ∪ t) x := hs.hasFDerivWithinAt.union ht.hasFDerivWithinAt theorem HasDerivWithinAt.hasDerivAt (h : HasDerivWithinAt f f' s x) (hs : s ∈ 𝓝 x) : HasDerivAt f f' x := HasFDerivWithinAt.hasFDerivAt h hs theorem DifferentiableWithinAt.hasDerivWithinAt (h : DifferentiableWithinAt 𝕜 f s x) : HasDerivWithinAt f (derivWithin f s x) s x := h.hasFDerivWithinAt.hasDerivWithinAt theorem DifferentiableAt.hasDerivAt (h : DifferentiableAt 𝕜 f x) : HasDerivAt f (deriv f x) x := h.hasFDerivAt.hasDerivAt @[simp] theorem hasDerivAt_deriv_iff : HasDerivAt f (deriv f x) x ↔ DifferentiableAt 𝕜 f x := ⟨fun h => h.differentiableAt, fun h => h.hasDerivAt⟩ @[simp] theorem hasDerivWithinAt_derivWithin_iff : HasDerivWithinAt f (derivWithin f s x) s x ↔ DifferentiableWithinAt 𝕜 f s x := ⟨fun h => h.differentiableWithinAt, fun h => h.hasDerivWithinAt⟩ theorem DifferentiableOn.hasDerivAt (h : DifferentiableOn 𝕜 f s) (hs : s ∈ 𝓝 x) : HasDerivAt f (deriv f x) x := (h.hasFDerivAt hs).hasDerivAt theorem HasDerivAt.deriv (h : HasDerivAt f f' x) : deriv f x = f' := h.differentiableAt.hasDerivAt.unique h theorem deriv_eq {f' : 𝕜 → F} (h : ∀ x, HasDerivAt f (f' x) x) : deriv f = f' := funext fun x => (h x).deriv theorem HasDerivWithinAt.derivWithin (h : HasDerivWithinAt f f' s x) (hxs : UniqueDiffWithinAt 𝕜 s x) : derivWithin f s x = f' := hxs.eq_deriv _ h.differentiableWithinAt.hasDerivWithinAt h theorem fderivWithin_derivWithin : (fderivWithin 𝕜 f s x : 𝕜 → F) 1 = derivWithin f s x := rfl theorem derivWithin_fderivWithin : smulRight (1 : 𝕜 →L[𝕜] 𝕜) (derivWithin f s x) = fderivWithin 𝕜 f s x := by simp [derivWithin] theorem norm_derivWithin_eq_norm_fderivWithin : ‖derivWithin f s x‖ = ‖fderivWithin 𝕜 f s x‖ := by simp [← derivWithin_fderivWithin] theorem fderiv_deriv : (fderiv 𝕜 f x : 𝕜 → F) 1 = deriv f x := rfl @[simp] theorem fderiv_eq_smul_deriv (y : 𝕜) : (fderiv 𝕜 f x : 𝕜 → F) y = y • deriv f x := by rw [← fderiv_deriv, ← ContinuousLinearMap.map_smul] simp only [smul_eq_mul, mul_one] theorem deriv_fderiv : smulRight (1 : 𝕜 →L[𝕜] 𝕜) (deriv f x) = fderiv 𝕜 f x := by simp only [deriv, ContinuousLinearMap.smulRight_one_one] lemma fderiv_eq_deriv_mul {f : 𝕜 → 𝕜} {x y : 𝕜} : (fderiv 𝕜 f x : 𝕜 → 𝕜) y = (deriv f x) * y := by simp [mul_comm] theorem norm_deriv_eq_norm_fderiv : ‖deriv f x‖ = ‖fderiv 𝕜 f x‖ := by simp [← deriv_fderiv] theorem DifferentiableAt.derivWithin (h : DifferentiableAt 𝕜 f x) (hxs : UniqueDiffWithinAt 𝕜 s x) : derivWithin f s x = deriv f x := by unfold _root_.derivWithin deriv rw [h.fderivWithin hxs] theorem HasDerivWithinAt.deriv_eq_zero (hd : HasDerivWithinAt f 0 s x) (H : UniqueDiffWithinAt 𝕜 s x) : deriv f x = 0 := (em' (DifferentiableAt 𝕜 f x)).elim deriv_zero_of_not_differentiableAt fun h => H.eq_deriv _ h.hasDerivAt.hasDerivWithinAt hd theorem derivWithin_of_mem_nhdsWithin (st : t ∈ 𝓝[s] x) (ht : UniqueDiffWithinAt 𝕜 s x) (h : DifferentiableWithinAt 𝕜 f t x) : derivWithin f s x = derivWithin f t x := ((DifferentiableWithinAt.hasDerivWithinAt h).mono_of_mem_nhdsWithin st).derivWithin ht @[deprecated (since := "2024-10-31")] alias derivWithin_of_mem := derivWithin_of_mem_nhdsWithin theorem derivWithin_subset (st : s ⊆ t) (ht : UniqueDiffWithinAt 𝕜 s x) (h : DifferentiableWithinAt 𝕜 f t x) : derivWithin f s x = derivWithin f t x := ((DifferentiableWithinAt.hasDerivWithinAt h).mono st).derivWithin ht theorem derivWithin_congr_set' (y : 𝕜) (h : s =ᶠ[𝓝[{y}ᶜ] x] t) : derivWithin f s x = derivWithin f t x := by simp only [derivWithin, fderivWithin_congr_set' y h] theorem derivWithin_congr_set (h : s =ᶠ[𝓝 x] t) : derivWithin f s x = derivWithin f t x := by simp only [derivWithin, fderivWithin_congr_set h] @[simp] theorem derivWithin_univ : derivWithin f univ = deriv f := by ext unfold derivWithin deriv rw [fderivWithin_univ] theorem derivWithin_inter (ht : t ∈ 𝓝 x) : derivWithin f (s ∩ t) x = derivWithin f s x := by unfold derivWithin rw [fderivWithin_inter ht] theorem derivWithin_of_mem_nhds (h : s ∈ 𝓝 x) : derivWithin f s x = deriv f x := by simp only [derivWithin, deriv, fderivWithin_of_mem_nhds h] theorem derivWithin_of_isOpen (hs : IsOpen s) (hx : x ∈ s) : derivWithin f s x = deriv f x := derivWithin_of_mem_nhds (hs.mem_nhds hx) lemma deriv_eqOn {f' : 𝕜 → F} (hs : IsOpen s) (hf' : ∀ x ∈ s, HasDerivWithinAt f (f' x) s x) : s.EqOn (deriv f) f' := fun x hx ↦ by rw [← derivWithin_of_isOpen hs hx, (hf' _ hx).derivWithin <| hs.uniqueDiffWithinAt hx] theorem deriv_mem_iff {f : 𝕜 → F} {s : Set F} {x : 𝕜} : deriv f x ∈ s ↔ DifferentiableAt 𝕜 f x ∧ deriv f x ∈ s ∨ ¬DifferentiableAt 𝕜 f x ∧ (0 : F) ∈ s := by by_cases hx : DifferentiableAt 𝕜 f x <;> simp [deriv_zero_of_not_differentiableAt, *] theorem derivWithin_mem_iff {f : 𝕜 → F} {t : Set 𝕜} {s : Set F} {x : 𝕜} : derivWithin f t x ∈ s ↔ DifferentiableWithinAt 𝕜 f t x ∧ derivWithin f t x ∈ s ∨ ¬DifferentiableWithinAt 𝕜 f t x ∧ (0 : F) ∈ s := by by_cases hx : DifferentiableWithinAt 𝕜 f t x <;> simp [derivWithin_zero_of_not_differentiableWithinAt, *] theorem differentiableWithinAt_Ioi_iff_Ici [PartialOrder 𝕜] : DifferentiableWithinAt 𝕜 f (Ioi x) x ↔ DifferentiableWithinAt 𝕜 f (Ici x) x := ⟨fun h => h.hasDerivWithinAt.Ici_of_Ioi.differentiableWithinAt, fun h => h.hasDerivWithinAt.Ioi_of_Ici.differentiableWithinAt⟩ -- Golfed while splitting the file theorem derivWithin_Ioi_eq_Ici {E : Type*} [NormedAddCommGroup E] [NormedSpace ℝ E] (f : ℝ → E) (x : ℝ) : derivWithin f (Ioi x) x = derivWithin f (Ici x) x := by by_cases H : DifferentiableWithinAt ℝ f (Ioi x) x · have A := H.hasDerivWithinAt.Ici_of_Ioi have B := (differentiableWithinAt_Ioi_iff_Ici.1 H).hasDerivWithinAt simpa using (uniqueDiffOn_Ici x).eq left_mem_Ici A B · rw [derivWithin_zero_of_not_differentiableWithinAt H, derivWithin_zero_of_not_differentiableWithinAt] rwa [differentiableWithinAt_Ioi_iff_Ici] at H section congr /-! ### Congruence properties of derivatives -/ theorem Filter.EventuallyEq.hasDerivAtFilter_iff (h₀ : f₀ =ᶠ[L] f₁) (hx : f₀ x = f₁ x) (h₁ : f₀' = f₁') : HasDerivAtFilter f₀ f₀' x L ↔ HasDerivAtFilter f₁ f₁' x L := h₀.hasFDerivAtFilter_iff hx (by simp [h₁]) theorem HasDerivAtFilter.congr_of_eventuallyEq (h : HasDerivAtFilter f f' x L) (hL : f₁ =ᶠ[L] f) (hx : f₁ x = f x) : HasDerivAtFilter f₁ f' x L := by rwa [hL.hasDerivAtFilter_iff hx rfl] theorem HasDerivWithinAt.congr_mono (h : HasDerivWithinAt f f' s x) (ht : ∀ x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (h₁ : t ⊆ s) : HasDerivWithinAt f₁ f' t x := HasFDerivWithinAt.congr_mono h ht hx h₁ theorem HasDerivWithinAt.congr (h : HasDerivWithinAt f f' s x) (hs : ∀ x ∈ s, f₁ x = f x) (hx : f₁ x = f x) : HasDerivWithinAt f₁ f' s x := h.congr_mono hs hx (Subset.refl _) theorem HasDerivWithinAt.congr_of_mem (h : HasDerivWithinAt f f' s x) (hs : ∀ x ∈ s, f₁ x = f x) (hx : x ∈ s) : HasDerivWithinAt f₁ f' s x := h.congr hs (hs _ hx) theorem HasDerivWithinAt.congr_of_eventuallyEq (h : HasDerivWithinAt f f' s x) (h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : HasDerivWithinAt f₁ f' s x :=
HasDerivAtFilter.congr_of_eventuallyEq h h₁ hx theorem Filter.EventuallyEq.hasDerivWithinAt_iff (h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : HasDerivWithinAt f₁ f' s x ↔ HasDerivWithinAt f f' s x := ⟨fun h' ↦ h'.congr_of_eventuallyEq h₁.symm hx.symm, fun h' ↦ h'.congr_of_eventuallyEq h₁ hx⟩
Mathlib/Analysis/Calculus/Deriv/Basic.lean
546
551
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Johannes Hölzl -/ import Mathlib.MeasureTheory.Integral.Lebesgue.Basic import Mathlib.MeasureTheory.Integral.Lebesgue.Countable import Mathlib.MeasureTheory.Integral.Lebesgue.MeasurePreserving import Mathlib.MeasureTheory.Integral.Lebesgue.Norm deprecated_module (since := "2025-04-13")
Mathlib/MeasureTheory/Integral/Lebesgue.lean
1,620
1,623
/- Copyright (c) 2023 Peter Nelson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Peter Nelson -/ import Mathlib.SetTheory.Cardinal.Finite import Mathlib.Data.Set.Finite.Powerset /-! # Noncomputable Set Cardinality We define the cardinality of set `s` as a term `Set.encard s : ℕ∞` and a term `Set.ncard s : ℕ`. The latter takes the junk value of zero if `s` is infinite. Both functions are noncomputable, and are defined in terms of `ENat.card` (which takes a type as its argument); this file can be seen as an API for the same function in the special case where the type is a coercion of a `Set`, allowing for smoother interactions with the `Set` API. `Set.encard` never takes junk values, so is more mathematically natural than `Set.ncard`, even though it takes values in a less convenient type. It is probably the right choice in settings where one is concerned with the cardinalities of sets that may or may not be infinite. `Set.ncard` has a nicer codomain, but when using it, `Set.Finite` hypotheses are normally needed to make sure its values are meaningful. More generally, `Set.ncard` is intended to be used over the obvious alternative `Finset.card` when finiteness is 'propositional' rather than 'structural'. When working with sets that are finite by virtue of their definition, then `Finset.card` probably makes more sense. One setting where `Set.ncard` works nicely is in a type `α` with `[Finite α]`, where every set is automatically finite. In this setting, we use default arguments and a simple tactic so that finiteness goals are discharged automatically in `Set.ncard` theorems. ## Main Definitions * `Set.encard s` is the cardinality of the set `s` as an extended natural number, with value `⊤` if `s` is infinite. * `Set.ncard s` is the cardinality of the set `s` as a natural number, provided `s` is Finite. If `s` is Infinite, then `Set.ncard s = 0`. * `toFinite_tac` is a tactic that tries to synthesize a `Set.Finite s` argument with `Set.toFinite`. This will work for `s : Set α` where there is a `Finite α` instance. ## Implementation Notes The theorems in this file are very similar to those in `Data.Finset.Card`, but with `Set` operations instead of `Finset`. We first prove all the theorems for `Set.encard`, and then derive most of the `Set.ncard` results as a consequence. Things are done this way to avoid reliance on the `Finset` API for theorems about infinite sets, and to allow for a refactor that removes or modifies `Set.ncard` in the future. Nearly all the theorems for `Set.ncard` require finiteness of one or more of their arguments. We provide this assumption with a default argument of the form `(hs : s.Finite := by toFinite_tac)`, where `toFinite_tac` will find an `s.Finite` term in the cases where `s` is a set in a `Finite` type. Often, where there are two set arguments `s` and `t`, the finiteness of one follows from the other in the context of the theorem, in which case we only include the ones that are needed, and derive the other inside the proof. A few of the theorems, such as `ncard_union_le` do not require finiteness arguments; they are true by coincidence due to junk values. -/ namespace Set variable {α β : Type*} {s t : Set α} /-- The cardinality of a set as a term in `ℕ∞` -/ noncomputable def encard (s : Set α) : ℕ∞ := ENat.card s @[simp] theorem encard_univ_coe (s : Set α) : encard (univ : Set s) = encard s := by rw [encard, encard, ENat.card_congr (Equiv.Set.univ ↑s)] theorem encard_univ (α : Type*) : encard (univ : Set α) = ENat.card α := by rw [encard, ENat.card_congr (Equiv.Set.univ α)] theorem Finite.encard_eq_coe_toFinset_card (h : s.Finite) : s.encard = h.toFinset.card := by have := h.fintype rw [encard, ENat.card_eq_coe_fintype_card, toFinite_toFinset, toFinset_card] theorem encard_eq_coe_toFinset_card (s : Set α) [Fintype s] : encard s = s.toFinset.card := by have h := toFinite s rw [h.encard_eq_coe_toFinset_card, toFinite_toFinset] @[simp] theorem toENat_cardinalMk (s : Set α) : (Cardinal.mk s).toENat = s.encard := rfl theorem toENat_cardinalMk_subtype (P : α → Prop) : (Cardinal.mk {x // P x}).toENat = {x | P x}.encard := rfl @[simp] theorem coe_fintypeCard (s : Set α) [Fintype s] : Fintype.card s = s.encard := by simp [encard_eq_coe_toFinset_card] @[simp, norm_cast] theorem encard_coe_eq_coe_finsetCard (s : Finset α) : encard (s : Set α) = s.card := by rw [Finite.encard_eq_coe_toFinset_card (Finset.finite_toSet s)]; simp @[simp] theorem Infinite.encard_eq {s : Set α} (h : s.Infinite) : s.encard = ⊤ := by have := h.to_subtype rw [encard, ENat.card_eq_top_of_infinite] @[simp] theorem encard_eq_zero : s.encard = 0 ↔ s = ∅ := by rw [encard, ENat.card_eq_zero_iff_empty, isEmpty_subtype, eq_empty_iff_forall_not_mem] @[simp] theorem encard_empty : (∅ : Set α).encard = 0 := by rw [encard_eq_zero] theorem nonempty_of_encard_ne_zero (h : s.encard ≠ 0) : s.Nonempty := by rwa [nonempty_iff_ne_empty, Ne, ← encard_eq_zero] theorem encard_ne_zero : s.encard ≠ 0 ↔ s.Nonempty := by rw [ne_eq, encard_eq_zero, nonempty_iff_ne_empty] @[simp] theorem encard_pos : 0 < s.encard ↔ s.Nonempty := by rw [pos_iff_ne_zero, encard_ne_zero] protected alias ⟨_, Nonempty.encard_pos⟩ := encard_pos @[simp] theorem encard_singleton (e : α) : ({e} : Set α).encard = 1 := by rw [encard, ENat.card_eq_coe_fintype_card, Fintype.card_ofSubsingleton, Nat.cast_one] theorem encard_union_eq (h : Disjoint s t) : (s ∪ t).encard = s.encard + t.encard := by classical simp [encard, ENat.card_congr (Equiv.Set.union h)] theorem encard_insert_of_not_mem {a : α} (has : a ∉ s) : (insert a s).encard = s.encard + 1 := by rw [← union_singleton, encard_union_eq (by simpa), encard_singleton] theorem Finite.encard_lt_top (h : s.Finite) : s.encard < ⊤ := by induction s, h using Set.Finite.induction_on with | empty => simp | insert hat _ ht' => rw [encard_insert_of_not_mem hat] exact lt_tsub_iff_right.1 ht' theorem Finite.encard_eq_coe (h : s.Finite) : s.encard = ENat.toNat s.encard := (ENat.coe_toNat h.encard_lt_top.ne).symm theorem Finite.exists_encard_eq_coe (h : s.Finite) : ∃ (n : ℕ), s.encard = n := ⟨_, h.encard_eq_coe⟩ @[simp] theorem encard_lt_top_iff : s.encard < ⊤ ↔ s.Finite := ⟨fun h ↦ by_contra fun h' ↦ h.ne (Infinite.encard_eq h'), Finite.encard_lt_top⟩ @[simp] theorem encard_eq_top_iff : s.encard = ⊤ ↔ s.Infinite := by rw [← not_iff_not, ← Ne, ← lt_top_iff_ne_top, encard_lt_top_iff, not_infinite] alias ⟨_, encard_eq_top⟩ := encard_eq_top_iff theorem encard_ne_top_iff : s.encard ≠ ⊤ ↔ s.Finite := by simp theorem finite_of_encard_le_coe {k : ℕ} (h : s.encard ≤ k) : s.Finite := by rw [← encard_lt_top_iff]; exact h.trans_lt (WithTop.coe_lt_top _) theorem finite_of_encard_eq_coe {k : ℕ} (h : s.encard = k) : s.Finite := finite_of_encard_le_coe h.le theorem encard_le_coe_iff {k : ℕ} : s.encard ≤ k ↔ s.Finite ∧ ∃ (n₀ : ℕ), s.encard = n₀ ∧ n₀ ≤ k := ⟨fun h ↦ ⟨finite_of_encard_le_coe h, by rwa [ENat.le_coe_iff] at h⟩, fun ⟨_,⟨n₀,hs, hle⟩⟩ ↦ by rwa [hs, Nat.cast_le]⟩ @[simp] theorem encard_prod : (s ×ˢ t).encard = s.encard * t.encard := by simp [Set.encard, ENat.card_congr (Equiv.Set.prod ..)] section Lattice theorem encard_le_encard (h : s ⊆ t) : s.encard ≤ t.encard := by rw [← union_diff_cancel h, encard_union_eq disjoint_sdiff_right]; exact le_self_add @[deprecated (since := "2025-01-05")] alias encard_le_card := encard_le_encard theorem encard_mono {α : Type*} : Monotone (encard : Set α → ℕ∞) := fun _ _ ↦ encard_le_encard theorem encard_diff_add_encard_of_subset (h : s ⊆ t) : (t \ s).encard + s.encard = t.encard := by rw [← encard_union_eq disjoint_sdiff_left, diff_union_self, union_eq_self_of_subset_right h] @[simp] theorem one_le_encard_iff_nonempty : 1 ≤ s.encard ↔ s.Nonempty := by rw [nonempty_iff_ne_empty, Ne, ← encard_eq_zero, ENat.one_le_iff_ne_zero] theorem encard_diff_add_encard_inter (s t : Set α) : (s \ t).encard + (s ∩ t).encard = s.encard := by rw [← encard_union_eq (disjoint_of_subset_right inter_subset_right disjoint_sdiff_left), diff_union_inter] theorem encard_union_add_encard_inter (s t : Set α) : (s ∪ t).encard + (s ∩ t).encard = s.encard + t.encard := by rw [← diff_union_self, encard_union_eq disjoint_sdiff_left, add_right_comm, encard_diff_add_encard_inter] theorem encard_eq_encard_iff_encard_diff_eq_encard_diff (h : (s ∩ t).Finite) : s.encard = t.encard ↔ (s \ t).encard = (t \ s).encard := by rw [← encard_diff_add_encard_inter s t, ← encard_diff_add_encard_inter t s, inter_comm t s, WithTop.add_right_inj h.encard_lt_top.ne] theorem encard_le_encard_iff_encard_diff_le_encard_diff (h : (s ∩ t).Finite) : s.encard ≤ t.encard ↔ (s \ t).encard ≤ (t \ s).encard := by rw [← encard_diff_add_encard_inter s t, ← encard_diff_add_encard_inter t s, inter_comm t s, WithTop.add_le_add_iff_right h.encard_lt_top.ne] theorem encard_lt_encard_iff_encard_diff_lt_encard_diff (h : (s ∩ t).Finite) : s.encard < t.encard ↔ (s \ t).encard < (t \ s).encard := by rw [← encard_diff_add_encard_inter s t, ← encard_diff_add_encard_inter t s, inter_comm t s, WithTop.add_lt_add_iff_right h.encard_lt_top.ne] theorem encard_union_le (s t : Set α) : (s ∪ t).encard ≤ s.encard + t.encard := by rw [← encard_union_add_encard_inter]; exact le_self_add theorem finite_iff_finite_of_encard_eq_encard (h : s.encard = t.encard) : s.Finite ↔ t.Finite := by rw [← encard_lt_top_iff, ← encard_lt_top_iff, h] theorem infinite_iff_infinite_of_encard_eq_encard (h : s.encard = t.encard) : s.Infinite ↔ t.Infinite := by rw [← encard_eq_top_iff, h, encard_eq_top_iff] theorem Finite.finite_of_encard_le {s : Set α} {t : Set β} (hs : s.Finite) (h : t.encard ≤ s.encard) : t.Finite := encard_lt_top_iff.1 (h.trans_lt hs.encard_lt_top) lemma Finite.eq_of_subset_of_encard_le' (ht : t.Finite) (hst : s ⊆ t) (hts : t.encard ≤ s.encard) : s = t := by rw [← zero_add (a := encard s), ← encard_diff_add_encard_of_subset hst] at hts have hdiff := WithTop.le_of_add_le_add_right (ht.subset hst).encard_lt_top.ne hts rw [nonpos_iff_eq_zero, encard_eq_zero, diff_eq_empty] at hdiff exact hst.antisymm hdiff theorem Finite.eq_of_subset_of_encard_le (hs : s.Finite) (hst : s ⊆ t) (hts : t.encard ≤ s.encard) : s = t := (hs.finite_of_encard_le hts).eq_of_subset_of_encard_le' hst hts theorem Finite.encard_lt_encard (hs : s.Finite) (h : s ⊂ t) : s.encard < t.encard := (encard_mono h.subset).lt_of_ne fun he ↦ h.ne (hs.eq_of_subset_of_encard_le h.subset he.symm.le) theorem encard_strictMono [Finite α] : StrictMono (encard : Set α → ℕ∞) := fun _ _ h ↦ (toFinite _).encard_lt_encard h theorem encard_diff_add_encard (s t : Set α) : (s \ t).encard + t.encard = (s ∪ t).encard := by rw [← encard_union_eq disjoint_sdiff_left, diff_union_self] theorem encard_le_encard_diff_add_encard (s t : Set α) : s.encard ≤ (s \ t).encard + t.encard := (encard_mono subset_union_left).trans_eq (encard_diff_add_encard _ _).symm theorem tsub_encard_le_encard_diff (s t : Set α) : s.encard - t.encard ≤ (s \ t).encard := by rw [tsub_le_iff_left, add_comm]; apply encard_le_encard_diff_add_encard theorem encard_add_encard_compl (s : Set α) : s.encard + sᶜ.encard = (univ : Set α).encard := by rw [← encard_union_eq disjoint_compl_right, union_compl_self] end Lattice section InsertErase variable {a b : α} theorem encard_insert_le (s : Set α) (x : α) : (insert x s).encard ≤ s.encard + 1 := by rw [← union_singleton, ← encard_singleton x]; apply encard_union_le theorem encard_singleton_inter (s : Set α) (x : α) : ({x} ∩ s).encard ≤ 1 := by rw [← encard_singleton x]; exact encard_le_encard inter_subset_left theorem encard_diff_singleton_add_one (h : a ∈ s) : (s \ {a}).encard + 1 = s.encard := by rw [← encard_insert_of_not_mem (fun h ↦ h.2 rfl), insert_diff_singleton, insert_eq_of_mem h] theorem encard_diff_singleton_of_mem (h : a ∈ s) : (s \ {a}).encard = s.encard - 1 := by rw [← encard_diff_singleton_add_one h, ← WithTop.add_right_inj WithTop.one_ne_top, tsub_add_cancel_of_le (self_le_add_left _ _)] theorem encard_tsub_one_le_encard_diff_singleton (s : Set α) (x : α) : s.encard - 1 ≤ (s \ {x}).encard := by rw [← encard_singleton x]; apply tsub_encard_le_encard_diff theorem encard_exchange (ha : a ∉ s) (hb : b ∈ s) : (insert a (s \ {b})).encard = s.encard := by rw [encard_insert_of_not_mem, encard_diff_singleton_add_one hb] simp_all only [not_true, mem_diff, mem_singleton_iff, false_and, not_false_eq_true] theorem encard_exchange' (ha : a ∉ s) (hb : b ∈ s) : (insert a s \ {b}).encard = s.encard := by rw [← insert_diff_singleton_comm (by rintro rfl; exact ha hb), encard_exchange ha hb] theorem encard_eq_add_one_iff {k : ℕ∞} : s.encard = k + 1 ↔ (∃ a t, ¬a ∈ t ∧ insert a t = s ∧ t.encard = k) := by refine ⟨fun h ↦ ?_, ?_⟩ · obtain ⟨a, ha⟩ := nonempty_of_encard_ne_zero (s := s) (by simp [h]) refine ⟨a, s \ {a}, fun h ↦ h.2 rfl, by rwa [insert_diff_singleton, insert_eq_of_mem], ?_⟩ rw [← WithTop.add_right_inj WithTop.one_ne_top, ← h, encard_diff_singleton_add_one ha] rintro ⟨a, t, h, rfl, rfl⟩ rw [encard_insert_of_not_mem h] /-- Every set is either empty, infinite, or can have its `encard` reduced by a removal. Intended for well-founded induction on the value of `encard`. -/ theorem eq_empty_or_encard_eq_top_or_encard_diff_singleton_lt (s : Set α) : s = ∅ ∨ s.encard = ⊤ ∨ ∃ a ∈ s, (s \ {a}).encard < s.encard := by refine s.eq_empty_or_nonempty.elim Or.inl (Or.inr ∘ fun ⟨a,ha⟩ ↦ (s.finite_or_infinite.elim (fun hfin ↦ Or.inr ⟨a, ha, ?_⟩) (Or.inl ∘ Infinite.encard_eq))) rw [← encard_diff_singleton_add_one ha]; nth_rw 1 [← add_zero (encard _)] exact WithTop.add_lt_add_left hfin.diff.encard_lt_top.ne zero_lt_one end InsertErase section SmallSets theorem encard_pair {x y : α} (hne : x ≠ y) : ({x, y} : Set α).encard = 2 := by rw [encard_insert_of_not_mem (by simpa), ← one_add_one_eq_two, WithTop.add_right_inj WithTop.one_ne_top, encard_singleton] theorem encard_eq_one : s.encard = 1 ↔ ∃ x, s = {x} := by refine ⟨fun h ↦ ?_, fun ⟨x, hx⟩ ↦ by rw [hx, encard_singleton]⟩ obtain ⟨x, hx⟩ := nonempty_of_encard_ne_zero (s := s) (by rw [h]; simp) exact ⟨x, ((finite_singleton x).eq_of_subset_of_encard_le (by simpa) (by simp [h])).symm⟩ theorem encard_le_one_iff_eq : s.encard ≤ 1 ↔ s = ∅ ∨ ∃ x, s = {x} := by rw [le_iff_lt_or_eq, lt_iff_not_le, ENat.one_le_iff_ne_zero, not_not, encard_eq_zero, encard_eq_one] theorem encard_le_one_iff : s.encard ≤ 1 ↔ ∀ a b, a ∈ s → b ∈ s → a = b := by rw [encard_le_one_iff_eq, or_iff_not_imp_left, ← Ne, ← nonempty_iff_ne_empty] refine ⟨fun h a b has hbs ↦ ?_, fun h ⟨x, hx⟩ ↦ ⟨x, ((singleton_subset_iff.2 hx).antisymm' (fun y hy ↦ h _ _ hy hx))⟩⟩ obtain ⟨x, rfl⟩ := h ⟨_, has⟩ rw [(has : a = x), (hbs : b = x)] theorem encard_le_one_iff_subsingleton : s.encard ≤ 1 ↔ s.Subsingleton := by rw [encard_le_one_iff, Set.Subsingleton] tauto theorem one_lt_encard_iff_nontrivial : 1 < s.encard ↔ s.Nontrivial := by rw [← not_iff_not, not_lt, Set.not_nontrivial_iff, ← encard_le_one_iff_subsingleton] theorem one_lt_encard_iff : 1 < s.encard ↔ ∃ a b, a ∈ s ∧ b ∈ s ∧ a ≠ b := by rw [← not_iff_not, not_exists, not_lt, encard_le_one_iff]; aesop theorem exists_ne_of_one_lt_encard (h : 1 < s.encard) (a : α) : ∃ b ∈ s, b ≠ a := by by_contra! h' obtain ⟨b, b', hb, hb', hne⟩ := one_lt_encard_iff.1 h apply hne rw [h' b hb, h' b' hb'] theorem encard_eq_two : s.encard = 2 ↔ ∃ x y, x ≠ y ∧ s = {x, y} := by refine ⟨fun h ↦ ?_, fun ⟨x, y, hne, hs⟩ ↦ by rw [hs, encard_pair hne]⟩ obtain ⟨x, hx⟩ := nonempty_of_encard_ne_zero (s := s) (by rw [h]; simp) rw [← insert_eq_of_mem hx, ← insert_diff_singleton, encard_insert_of_not_mem (fun h ↦ h.2 rfl), ← one_add_one_eq_two, WithTop.add_right_inj (WithTop.one_ne_top), encard_eq_one] at h obtain ⟨y, h⟩ := h refine ⟨x, y, by rintro rfl; exact (h.symm.subset rfl).2 rfl, ?_⟩ rw [← h, insert_diff_singleton, insert_eq_of_mem hx] theorem encard_eq_three {α : Type u_1} {s : Set α} : encard s = 3 ↔ ∃ x y z, x ≠ y ∧ x ≠ z ∧ y ≠ z ∧ s = {x, y, z} := by refine ⟨fun h ↦ ?_, fun ⟨x, y, z, hxy, hyz, hxz, hs⟩ ↦ ?_⟩ · obtain ⟨x, hx⟩ := nonempty_of_encard_ne_zero (s := s) (by rw [h]; simp) rw [← insert_eq_of_mem hx, ← insert_diff_singleton, encard_insert_of_not_mem (fun h ↦ h.2 rfl), (by exact rfl : (3 : ℕ∞) = 2 + 1), WithTop.add_right_inj WithTop.one_ne_top, encard_eq_two] at h obtain ⟨y, z, hne, hs⟩ := h refine ⟨x, y, z, ?_, ?_, hne, ?_⟩ · rintro rfl; exact (hs.symm.subset (Or.inl rfl)).2 rfl · rintro rfl; exact (hs.symm.subset (Or.inr rfl)).2 rfl rw [← hs, insert_diff_singleton, insert_eq_of_mem hx] rw [hs, encard_insert_of_not_mem, encard_insert_of_not_mem, encard_singleton] <;> aesop theorem Nat.encard_range (k : ℕ) : {i | i < k}.encard = k := by convert encard_coe_eq_coe_finsetCard (Finset.range k) using 1 · rw [Finset.coe_range, Iio_def] rw [Finset.card_range] end SmallSets theorem Finite.eq_insert_of_subset_of_encard_eq_succ (hs : s.Finite) (h : s ⊆ t) (hst : t.encard = s.encard + 1) : ∃ a, t = insert a s := by rw [← encard_diff_add_encard_of_subset h, add_comm, WithTop.add_left_inj hs.encard_lt_top.ne, encard_eq_one] at hst obtain ⟨x, hx⟩ := hst; use x; rw [← diff_union_of_subset h, hx, singleton_union] theorem exists_subset_encard_eq {k : ℕ∞} (hk : k ≤ s.encard) : ∃ t, t ⊆ s ∧ t.encard = k := by revert hk refine ENat.nat_induction k (fun _ ↦ ⟨∅, empty_subset _, by simp⟩) (fun n IH hle ↦ ?_) ?_ · obtain ⟨t₀, ht₀s, ht₀⟩ := IH (le_trans (by simp) hle) simp only [Nat.cast_succ] at * have hne : t₀ ≠ s := by rintro rfl; rw [ht₀, ← Nat.cast_one, ← Nat.cast_add, Nat.cast_le] at hle; simp at hle obtain ⟨x, hx⟩ := exists_of_ssubset (ht₀s.ssubset_of_ne hne) exact ⟨insert x t₀, insert_subset hx.1 ht₀s, by rw [encard_insert_of_not_mem hx.2, ht₀]⟩ simp only [top_le_iff, encard_eq_top_iff] exact fun _ hi ↦ ⟨s, Subset.rfl, hi⟩ theorem exists_superset_subset_encard_eq {k : ℕ∞} (hst : s ⊆ t) (hsk : s.encard ≤ k) (hkt : k ≤ t.encard) : ∃ r, s ⊆ r ∧ r ⊆ t ∧ r.encard = k := by obtain (hs | hs) := eq_or_ne s.encard ⊤ · rw [hs, top_le_iff] at hsk; subst hsk; exact ⟨s, Subset.rfl, hst, hs⟩ obtain ⟨k, rfl⟩ := exists_add_of_le hsk obtain ⟨k', hk'⟩ := exists_add_of_le hkt have hk : k ≤ encard (t \ s) := by rw [← encard_diff_add_encard_of_subset hst, add_comm] at hkt exact WithTop.le_of_add_le_add_right hs hkt obtain ⟨r', hr', rfl⟩ := exists_subset_encard_eq hk refine ⟨s ∪ r', subset_union_left, union_subset hst (hr'.trans diff_subset), ?_⟩ rw [encard_union_eq (disjoint_of_subset_right hr' disjoint_sdiff_right)] section Function variable {s : Set α} {t : Set β} {f : α → β} theorem InjOn.encard_image (h : InjOn f s) : (f '' s).encard = s.encard := by rw [encard, ENat.card_image_of_injOn h, encard] theorem encard_congr (e : s ≃ t) : s.encard = t.encard := by rw [← encard_univ_coe, ← encard_univ_coe t, encard_univ, encard_univ, ENat.card_congr e] theorem _root_.Function.Injective.encard_image (hf : f.Injective) (s : Set α) : (f '' s).encard = s.encard := hf.injOn.encard_image theorem _root_.Function.Embedding.encard_le (e : s ↪ t) : s.encard ≤ t.encard := by rw [← encard_univ_coe, ← e.injective.encard_image, ← Subtype.coe_injective.encard_image] exact encard_mono (by simp) theorem encard_image_le (f : α → β) (s : Set α) : (f '' s).encard ≤ s.encard := by obtain (h | h) := isEmpty_or_nonempty α · rw [s.eq_empty_of_isEmpty]; simp rw [← (f.invFunOn_injOn_image s).encard_image] apply encard_le_encard exact f.invFunOn_image_image_subset s theorem Finite.injOn_of_encard_image_eq (hs : s.Finite) (h : (f '' s).encard = s.encard) : InjOn f s := by obtain (h' | hne) := isEmpty_or_nonempty α · rw [s.eq_empty_of_isEmpty]; simp rw [← (f.invFunOn_injOn_image s).encard_image] at h rw [injOn_iff_invFunOn_image_image_eq_self] exact hs.eq_of_subset_of_encard_le' (f.invFunOn_image_image_subset s) h.symm.le theorem encard_preimage_of_injective_subset_range (hf : f.Injective) (ht : t ⊆ range f) : (f ⁻¹' t).encard = t.encard := by rw [← hf.encard_image, image_preimage_eq_inter_range, inter_eq_self_of_subset_left ht] lemma encard_preimage_of_bijective (hf : f.Bijective) (t : Set β) : (f ⁻¹' t).encard = t.encard := encard_preimage_of_injective_subset_range hf.injective (by simp [hf.surjective.range_eq]) theorem encard_le_encard_of_injOn (hf : MapsTo f s t) (f_inj : InjOn f s) : s.encard ≤ t.encard := by rw [← f_inj.encard_image]; apply encard_le_encard; rintro _ ⟨x, hx, rfl⟩; exact hf hx theorem Finite.exists_injOn_of_encard_le [Nonempty β] {s : Set α} {t : Set β} (hs : s.Finite) (hle : s.encard ≤ t.encard) : ∃ (f : α → β), s ⊆ f ⁻¹' t ∧ InjOn f s := by classical obtain (rfl | h | ⟨a, has, -⟩) := s.eq_empty_or_encard_eq_top_or_encard_diff_singleton_lt · simp · exact (encard_ne_top_iff.mpr hs h).elim obtain ⟨b, hbt⟩ := encard_pos.1 ((encard_pos.2 ⟨_, has⟩).trans_le hle) have hle' : (s \ {a}).encard ≤ (t \ {b}).encard := by rwa [← WithTop.add_le_add_iff_right WithTop.one_ne_top, encard_diff_singleton_add_one has, encard_diff_singleton_add_one hbt] obtain ⟨f₀, hf₀s, hinj⟩ := exists_injOn_of_encard_le hs.diff hle' simp only [preimage_diff, subset_def, mem_diff, mem_singleton_iff, mem_preimage, and_imp] at hf₀s use Function.update f₀ a b rw [← insert_eq_of_mem has, ← insert_diff_singleton, injOn_insert (fun h ↦ h.2 rfl)] simp only [mem_diff, mem_singleton_iff, not_true, and_false, insert_diff_singleton, subset_def, mem_insert_iff, mem_preimage, ne_eq, Function.update_apply, forall_eq_or_imp, ite_true, and_imp, mem_image, ite_eq_left_iff, not_exists, not_and, not_forall, exists_prop, and_iff_right hbt] refine ⟨?_, ?_, fun x hxs hxa ↦ ⟨hxa, (hf₀s x hxs hxa).2⟩⟩ · rintro x hx; split_ifs with h · assumption · exact (hf₀s x hx h).1 exact InjOn.congr hinj (fun x ⟨_, hxa⟩ ↦ by rwa [Function.update_of_ne]) termination_by encard s theorem Finite.exists_bijOn_of_encard_eq [Nonempty β] (hs : s.Finite) (h : s.encard = t.encard) : ∃ (f : α → β), BijOn f s t := by obtain ⟨f, hf, hinj⟩ := hs.exists_injOn_of_encard_le h.le; use f convert hinj.bijOn_image rw [(hs.image f).eq_of_subset_of_encard_le (image_subset_iff.mpr hf) (h.symm.trans hinj.encard_image.symm).le] end Function section ncard open Nat /-- A tactic (for use in default params) that applies `Set.toFinite` to synthesize a `Set.Finite` term. -/ syntax "toFinite_tac" : tactic macro_rules | `(tactic| toFinite_tac) => `(tactic| apply Set.toFinite) /-- A tactic useful for transferring proofs for `encard` to their corresponding `card` statements -/ syntax "to_encard_tac" : tactic macro_rules | `(tactic| to_encard_tac) => `(tactic| simp only [← Nat.cast_le (α := ℕ∞), ← Nat.cast_inj (R := ℕ∞), Nat.cast_add, Nat.cast_one]) /-- The cardinality of `s : Set α` . Has the junk value `0` if `s` is infinite -/ noncomputable def ncard (s : Set α) : ℕ := ENat.toNat s.encard theorem ncard_def (s : Set α) : s.ncard = ENat.toNat s.encard := rfl theorem Finite.cast_ncard_eq (hs : s.Finite) : s.ncard = s.encard := by rwa [ncard, ENat.coe_toNat_eq_self, ne_eq, encard_eq_top_iff, Set.Infinite, not_not] lemma ncard_le_encard (s : Set α) : s.ncard ≤ s.encard := ENat.coe_toNat_le_self _ theorem Nat.card_coe_set_eq (s : Set α) : Nat.card s = s.ncard := by obtain (h | h) := s.finite_or_infinite · have := h.fintype
rw [ncard, h.encard_eq_coe_toFinset_card, Nat.card_eq_fintype_card, toFinite_toFinset, toFinset_card, ENat.toNat_coe] have := infinite_coe_iff.2 h rw [ncard, h.encard_eq, Nat.card_eq_zero_of_infinite, ENat.toNat_top]
Mathlib/Data/Set/Card.lean
510
513
/- Copyright (c) 2020 Nicolò Cavalleri. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nicolò Cavalleri, Andrew Yang -/ import Mathlib.Algebra.Polynomial.AlgebraMap import Mathlib.Algebra.Polynomial.Derivative /-! # Derivations This file defines derivation. A derivation `D` from the `R`-algebra `A` to the `A`-module `M` is an `R`-linear map that satisfy the Leibniz rule `D (a * b) = a * D b + D a * b`. ## Main results - `Derivation`: The type of `R`-derivations from `A` to `M`. This has an `A`-module structure. - `Derivation.llcomp`: We may compose linear maps and derivations to obtain a derivation, and the composition is bilinear. See `RingTheory.Derivation.Lie` for - `derivation.lie_algebra`: The `R`-derivations from `A` to `A` form a lie algebra over `R`. and `RingTheory.Derivation.ToSquareZero` for - `derivationToSquareZeroEquivLift`: The `R`-derivations from `A` into a square-zero ideal `I` of `B` corresponds to the lifts `A →ₐ[R] B` of the map `A →ₐ[R] B ⧸ I`. ## Future project - Generalize derivations into bimodules. -/ open Algebra /-- `D : Derivation R A M` is an `R`-linear map from `A` to `M` that satisfies the `leibniz` equality. We also require that `D 1 = 0`. See `Derivation.mk'` for a constructor that deduces this assumption from the Leibniz rule when `M` is cancellative. TODO: update this when bimodules are defined. -/ structure Derivation (R : Type*) (A : Type*) (M : Type*) [CommSemiring R] [CommSemiring A] [AddCommMonoid M] [Algebra R A] [Module A M] [Module R M] extends A →ₗ[R] M where protected map_one_eq_zero' : toLinearMap 1 = 0 protected leibniz' (a b : A) : toLinearMap (a * b) = a • toLinearMap b + b • toLinearMap a /-- The `LinearMap` underlying a `Derivation`. -/ add_decl_doc Derivation.toLinearMap namespace Derivation section variable {R : Type*} {A : Type*} {B : Type*} {M : Type*} variable [CommSemiring R] [CommSemiring A] [CommSemiring B] [AddCommMonoid M] variable [Algebra R A] [Algebra R B] variable [Module A M] [Module B M] [Module R M] variable (D : Derivation R A M) {D1 D2 : Derivation R A M} (r : R) (a b : A) instance : FunLike (Derivation R A M) A M where coe D := D.toFun coe_injective' D1 D2 h := by cases D1; cases D2; congr; exact DFunLike.coe_injective h instance : AddMonoidHomClass (Derivation R A M) A M where map_add D := D.toLinearMap.map_add' map_zero D := D.toLinearMap.map_zero -- Not a simp lemma because it can be proved via `coeFn_coe` + `toLinearMap_eq_coe` theorem toFun_eq_coe : D.toFun = ⇑D := rfl /-- See Note [custom simps projection] -/ def Simps.apply (D : Derivation R A M) : A → M := D initialize_simps_projections Derivation (toFun → apply) attribute [coe] toLinearMap instance hasCoeToLinearMap : Coe (Derivation R A M) (A →ₗ[R] M) := ⟨fun D => D.toLinearMap⟩ @[simp] theorem mk_coe (f : A →ₗ[R] M) (h₁ h₂) : ((⟨f, h₁, h₂⟩ : Derivation R A M) : A → M) = f := rfl @[simp, norm_cast] theorem coeFn_coe (f : Derivation R A M) : ⇑(f : A →ₗ[R] M) = f := rfl theorem coe_injective : @Function.Injective (Derivation R A M) (A → M) DFunLike.coe := DFunLike.coe_injective @[ext] theorem ext (H : ∀ a, D1 a = D2 a) : D1 = D2 := DFunLike.ext _ _ H theorem congr_fun (h : D1 = D2) (a : A) : D1 a = D2 a := DFunLike.congr_fun h a protected theorem map_add : D (a + b) = D a + D b := map_add D a b protected theorem map_zero : D 0 = 0 := map_zero D @[simp] theorem map_smul : D (r • a) = r • D a := D.toLinearMap.map_smul r a @[simp] theorem leibniz : D (a * b) = a • D b + b • D a := D.leibniz' _ _ @[simp] theorem map_smul_of_tower {S : Type*} [SMul S A] [SMul S M] [LinearMap.CompatibleSMul A M S R] (D : Derivation R A M) (r : S) (a : A) : D (r • a) = r • D a := D.toLinearMap.map_smul_of_tower r a @[simp] theorem map_one_eq_zero : D 1 = 0 := D.map_one_eq_zero' @[simp] theorem map_algebraMap : D (algebraMap R A r) = 0 := by rw [← mul_one r, RingHom.map_mul, RingHom.map_one, ← smul_def, map_smul, map_one_eq_zero, smul_zero] @[simp] theorem map_natCast (n : ℕ) : D (n : A) = 0 := by rw [← nsmul_one, D.map_smul_of_tower n, map_one_eq_zero, smul_zero] @[simp] theorem leibniz_pow (n : ℕ) : D (a ^ n) = n • a ^ (n - 1) • D a := by induction' n with n ihn · rw [pow_zero, map_one_eq_zero, zero_smul] · rcases (zero_le n).eq_or_lt with (rfl | hpos) · simp · have : a * a ^ (n - 1) = a ^ n := by rw [← pow_succ', Nat.sub_add_cancel hpos] simp only [pow_succ', leibniz, ihn, smul_comm a n (_ : M), smul_smul a, add_smul, this, Nat.succ_eq_add_one, Nat.add_succ_sub_one, add_zero, one_nsmul] open Polynomial in @[simp] theorem map_aeval (P : R[X]) (x : A) : D (aeval x P) = aeval x (derivative P) • D x := by induction P using Polynomial.induction_on · simp · simp [add_smul, *] · simp [mul_smul, ← Nat.cast_smul_eq_nsmul A] theorem eqOn_adjoin {s : Set A} (h : Set.EqOn D1 D2 s) : Set.EqOn D1 D2 (adjoin R s) := fun _ hx => Algebra.adjoin_induction (hx := hx) h (fun r => (D1.map_algebraMap r).trans (D2.map_algebraMap r).symm) (fun x y _ _ hx hy => by simp only [map_add, *]) fun x y _ _ hx hy => by simp only [leibniz, *] /-- If adjoin of a set is the whole algebra, then any two derivations equal on this set are equal on the whole algebra. -/ theorem ext_of_adjoin_eq_top (s : Set A) (hs : adjoin R s = ⊤) (h : Set.EqOn D1 D2 s) : D1 = D2 := ext fun _ => eqOn_adjoin h <| hs.symm ▸ trivial -- Data typeclasses instance : Zero (Derivation R A M) := ⟨{ toLinearMap := 0 map_one_eq_zero' := rfl leibniz' := fun a b => by simp only [add_zero, LinearMap.zero_apply, smul_zero] }⟩ @[simp] theorem coe_zero : ⇑(0 : Derivation R A M) = 0 := rfl @[simp] theorem coe_zero_linearMap : ↑(0 : Derivation R A M) = (0 : A →ₗ[R] M) := rfl
theorem zero_apply (a : A) : (0 : Derivation R A M) a = 0 := rfl
Mathlib/RingTheory/Derivation/Basic.lean
177
179
/- Copyright (c) 2022 Andrew Yang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andrew Yang, Joël Riou -/ import Mathlib.CategoryTheory.Sites.Subsheaf import Mathlib.CategoryTheory.Sites.CompatibleSheafification import Mathlib.CategoryTheory.Sites.LocallyInjective /-! # Locally surjective morphisms ## Main definitions - `IsLocallySurjective` : A morphism of presheaves valued in a concrete category is locally surjective with respect to a Grothendieck topology if every section in the target is locally in the set-theoretic image, i.e. the image sheaf coincides with the target. ## Main results - `Presheaf.isLocallySurjective_toSheafify`: `toSheafify` is locally surjective. - `Sheaf.isLocallySurjective_iff_epi`: a morphism of sheaves of types is locally surjective iff it is epi -/ universe v u w v' u' w' open Opposite CategoryTheory CategoryTheory.GrothendieckTopology namespace CategoryTheory variable {C : Type u} [Category.{v} C] (J : GrothendieckTopology C) variable {A : Type u'} [Category.{v'} A] {FA : A → A → Type*} {CA : A → Type w'} variable [∀ X Y, FunLike (FA X Y) (CA X) (CA Y)] [ConcreteCategory.{w'} A FA] namespace Presheaf /-- Given `f : F ⟶ G`, a morphism between presieves, and `s : G.obj (op U)`, this is the sieve of `U` consisting of the `i : V ⟶ U` such that `s` restricted along `i` is in the image of `f`. -/ @[simps -isSimp] def imageSieve {F G : Cᵒᵖ ⥤ A} (f : F ⟶ G) {U : C} (s : ToType (G.obj (op U))) : Sieve U where arrows V i := ∃ t : ToType (F.obj (op V)), f.app _ t = G.map i.op s downward_closed := by rintro V W i ⟨t, ht⟩ j refine ⟨F.map j.op t, ?_⟩ rw [op_comp, G.map_comp, ConcreteCategory.comp_apply, ← ht, NatTrans.naturality_apply f] theorem imageSieve_eq_sieveOfSection {F G : Cᵒᵖ ⥤ A} (f : F ⟶ G) {U : C} (s : ToType (G.obj (op U))) : imageSieve f s = (Subpresheaf.range (whiskerRight f (forget A))).sieveOfSection s := rfl attribute [local instance] Types.instFunLike Types.instConcreteCategory in theorem imageSieve_whisker_forget {F G : Cᵒᵖ ⥤ A} (f : F ⟶ G) {U : C} (s : ToType (G.obj (op U))) : imageSieve (whiskerRight f (forget A)) s = imageSieve f s := rfl theorem imageSieve_app {F G : Cᵒᵖ ⥤ A} (f : F ⟶ G) {U : C} (s : ToType (F.obj (op U))) : imageSieve f (f.app _ s) = ⊤ := by ext V i simp only [Sieve.top_apply, iff_true, imageSieve_apply] exact ⟨F.map i.op s, NatTrans.naturality_apply f i.op s⟩ /-- If a morphism `g : V ⟶ U.unop` belongs to the sieve `imageSieve f s g`, then this is choice of a preimage of `G.map g.op s` in `F.obj (op V)`, see `app_localPreimage`. -/ noncomputable def localPreimage {F G : Cᵒᵖ ⥤ A} (f : F ⟶ G) {U : Cᵒᵖ} (s : ToType (G.obj U)) {V : C} (g : V ⟶ U.unop) (hg : imageSieve f s g) : ToType (F.obj (op V)) := hg.choose @[simp] lemma app_localPreimage {F G : Cᵒᵖ ⥤ A} (f : F ⟶ G) {U : Cᵒᵖ} (s : ToType (G.obj U)) {V : C} (g : V ⟶ U.unop) (hg : imageSieve f s g) : f.app _ (localPreimage f s g hg) = G.map g.op s := hg.choose_spec /-- A morphism of presheaves `f : F ⟶ G` is locally surjective with respect to a grothendieck topology if every section of `G` is locally in the image of `f`. -/ class IsLocallySurjective {F G : Cᵒᵖ ⥤ A} (f : F ⟶ G) : Prop where imageSieve_mem {U : C} (s : ToType (G.obj (op U))) : imageSieve f s ∈ J U lemma imageSieve_mem {F G : Cᵒᵖ ⥤ A} (f : F ⟶ G) [IsLocallySurjective J f] {U : Cᵒᵖ} (s : ToType (G.obj U)) : imageSieve f s ∈ J U.unop := IsLocallySurjective.imageSieve_mem _ attribute [local instance] Types.instFunLike Types.instConcreteCategory in instance {F G : Cᵒᵖ ⥤ A} (f : F ⟶ G) [IsLocallySurjective J f] : IsLocallySurjective J (whiskerRight f (forget A)) where imageSieve_mem s := imageSieve_mem J f s theorem isLocallySurjective_iff_range_sheafify_eq_top {F G : Cᵒᵖ ⥤ A} (f : F ⟶ G) : IsLocallySurjective J f ↔ (Subpresheaf.range (whiskerRight f (forget A))).sheafify J = ⊤ := by simp only [Subpresheaf.ext_iff, funext_iff, Set.ext_iff, Subpresheaf.top_obj, Set.top_eq_univ, Set.mem_univ, iff_true] exact ⟨fun H _ => H.imageSieve_mem, fun H => ⟨H _⟩⟩ @[deprecated (since := "2025-01-26")] alias isLocallySurjective_iff_imagePresheaf_sheafify_eq_top := isLocallySurjective_iff_range_sheafify_eq_top attribute [local instance] Types.instFunLike Types.instConcreteCategory in theorem isLocallySurjective_iff_range_sheafify_eq_top' {F G : Cᵒᵖ ⥤ Type w} (f : F ⟶ G) : IsLocallySurjective J f ↔ (Subpresheaf.range f).sheafify J = ⊤ := by apply isLocallySurjective_iff_range_sheafify_eq_top @[deprecated (since := "2025-01-26")] alias isLocallySurjective_iff_imagePresheaf_sheafify_eq_top' := isLocallySurjective_iff_range_sheafify_eq_top' attribute [local instance] Types.instFunLike Types.instConcreteCategory in theorem isLocallySurjective_iff_whisker_forget {F G : Cᵒᵖ ⥤ A} (f : F ⟶ G) : IsLocallySurjective J f ↔ IsLocallySurjective J (whiskerRight f (forget A)) := by simp only [isLocallySurjective_iff_range_sheafify_eq_top] rfl theorem isLocallySurjective_of_surjective {F G : Cᵒᵖ ⥤ A} (f : F ⟶ G) (H : ∀ U, Function.Surjective (f.app U)) : IsLocallySurjective J f where imageSieve_mem {U} s := by obtain ⟨t, rfl⟩ := H _ s rw [imageSieve_app] exact J.top_mem _ instance isLocallySurjective_of_iso {F G : Cᵒᵖ ⥤ A} (f : F ⟶ G) [IsIso f] : IsLocallySurjective J f := by apply isLocallySurjective_of_surjective intro U apply Function.Bijective.surjective rw [← isIso_iff_bijective, ← ConcreteCategory.forget_map_eq_coe] infer_instance instance isLocallySurjective_comp {F₁ F₂ F₃ : Cᵒᵖ ⥤ A} (f₁ : F₁ ⟶ F₂) (f₂ : F₂ ⟶ F₃) [IsLocallySurjective J f₁] [IsLocallySurjective J f₂] : IsLocallySurjective J (f₁ ≫ f₂) where imageSieve_mem s := by have : (Sieve.bind (imageSieve f₂ s) fun _ _ h => imageSieve f₁ h.choose) ≤ imageSieve (f₁ ≫ f₂) s := by rintro V i ⟨W, i, j, H, ⟨t', ht'⟩, rfl⟩ refine ⟨t', ?_⟩ rw [op_comp, F₃.map_comp, NatTrans.comp_app, ConcreteCategory.comp_apply, ConcreteCategory.comp_apply, ht', NatTrans.naturality_apply, H.choose_spec] apply J.superset_covering this apply J.bind_covering · apply imageSieve_mem · intros; apply imageSieve_mem lemma isLocallySurjective_of_isLocallySurjective {F₁ F₂ F₃ : Cᵒᵖ ⥤ A} (f₁ : F₁ ⟶ F₂) (f₂ : F₂ ⟶ F₃) [IsLocallySurjective J (f₁ ≫ f₂)] : IsLocallySurjective J f₂ where imageSieve_mem {X} x := by refine J.superset_covering ?_ (imageSieve_mem J (f₁ ≫ f₂) x) intro Y g hg exact ⟨f₁.app _ (localPreimage (f₁ ≫ f₂) x g hg), by simpa using app_localPreimage (f₁ ≫ f₂) x g hg⟩ lemma isLocallySurjective_of_isLocallySurjective_fac {F₁ F₂ F₃ : Cᵒᵖ ⥤ A} {f₁ : F₁ ⟶ F₂} {f₂ : F₂ ⟶ F₃} {f₃ : F₁ ⟶ F₃} (fac : f₁ ≫ f₂ = f₃) [IsLocallySurjective J f₃] : IsLocallySurjective J f₂ := by subst fac exact isLocallySurjective_of_isLocallySurjective J f₁ f₂ lemma isLocallySurjective_iff_of_fac {F₁ F₂ F₃ : Cᵒᵖ ⥤ A} {f₁ : F₁ ⟶ F₂} {f₂ : F₂ ⟶ F₃} {f₃ : F₁ ⟶ F₃} (fac : f₁ ≫ f₂ = f₃) [IsLocallySurjective J f₁] : IsLocallySurjective J f₃ ↔ IsLocallySurjective J f₂ := by constructor · intro exact isLocallySurjective_of_isLocallySurjective_fac J fac · intro rw [← fac] infer_instance lemma comp_isLocallySurjective_iff {F₁ F₂ F₃ : Cᵒᵖ ⥤ A} (f₁ : F₁ ⟶ F₂) (f₂ : F₂ ⟶ F₃) [IsLocallySurjective J f₁] : IsLocallySurjective J (f₁ ≫ f₂) ↔ IsLocallySurjective J f₂ := isLocallySurjective_iff_of_fac J rfl variable {J} in lemma isLocallySurjective_of_le {K : GrothendieckTopology C} (hJK : J ≤ K) {F G : Cᵒᵖ ⥤ A} (f : F ⟶ G) (h : IsLocallySurjective J f) : IsLocallySurjective K f where imageSieve_mem s := by apply hJK; exact h.1 _ lemma isLocallyInjective_of_isLocallyInjective_of_isLocallySurjective {F₁ F₂ F₃ : Cᵒᵖ ⥤ A} (f₁ : F₁ ⟶ F₂) (f₂ : F₂ ⟶ F₃) [IsLocallyInjective J (f₁ ≫ f₂)] [IsLocallySurjective J f₁] : IsLocallyInjective J f₂ where equalizerSieve_mem {X} x₁ x₂ h := by let S := imageSieve f₁ x₁ ⊓ imageSieve f₁ x₂ have hS : S ∈ J X.unop := by apply J.intersection_covering all_goals apply imageSieve_mem let T : ∀ ⦃Y : C⦄ (f : Y ⟶ X.unop) (_ : S f), Sieve Y := fun Y f hf => equalizerSieve (localPreimage f₁ x₁ f hf.1) (localPreimage f₁ x₂ f hf.2) refine J.superset_covering ?_ (J.transitive hS (Sieve.bind S.1 T) ?_) · rintro Y f ⟨Z, a, g, hg, ha, rfl⟩ simpa using congr_arg (f₁.app _) ha · intro Y f hf apply J.superset_covering (Sieve.le_pullback_bind _ _ _ hf) apply equalizerSieve_mem J (f₁ ≫ f₂) dsimp rw [ConcreteCategory.comp_apply, ConcreteCategory.comp_apply, app_localPreimage, app_localPreimage, NatTrans.naturality_apply, NatTrans.naturality_apply, h] lemma isLocallyInjective_of_isLocallyInjective_of_isLocallySurjective_fac {F₁ F₂ F₃ : Cᵒᵖ ⥤ A} {f₁ : F₁ ⟶ F₂} {f₂ : F₂ ⟶ F₃} (f₃ : F₁ ⟶ F₃) (fac : f₁ ≫ f₂ = f₃) [IsLocallyInjective J f₃] [IsLocallySurjective J f₁] : IsLocallyInjective J f₂ := by subst fac exact isLocallyInjective_of_isLocallyInjective_of_isLocallySurjective J f₁ f₂ lemma isLocallySurjective_of_isLocallySurjective_of_isLocallyInjective {F₁ F₂ F₃ : Cᵒᵖ ⥤ A} (f₁ : F₁ ⟶ F₂) (f₂ : F₂ ⟶ F₃) [IsLocallySurjective J (f₁ ≫ f₂)] [IsLocallyInjective J f₂] : IsLocallySurjective J f₁ where imageSieve_mem {X} x := by let S := imageSieve (f₁ ≫ f₂) (f₂.app _ x) let T : ∀ ⦃Y : C⦄ (f : Y ⟶ X) (_ : S f), Sieve Y := fun Y f hf => equalizerSieve (f₁.app _ (localPreimage (f₁ ≫ f₂) (f₂.app _ x) f hf)) (F₂.map f.op x) refine J.superset_covering ?_ (J.transitive (imageSieve_mem J (f₁ ≫ f₂) (f₂.app _ x)) (Sieve.bind S.1 T) ?_) · rintro Y _ ⟨Z, a, g, hg, ha, rfl⟩ exact ⟨F₁.map a.op (localPreimage (f₁ ≫ f₂) _ _ hg), by simpa using ha⟩ · intro Y f hf apply J.superset_covering (Sieve.le_pullback_bind _ _ _ hf) apply equalizerSieve_mem J f₂ rw [NatTrans.naturality_apply, ← app_localPreimage (f₁ ≫ f₂) _ _ hf, NatTrans.comp_app, ConcreteCategory.comp_apply] lemma isLocallySurjective_of_isLocallySurjective_of_isLocallyInjective_fac {F₁ F₂ F₃ : Cᵒᵖ ⥤ A} {f₁ : F₁ ⟶ F₂} {f₂ : F₂ ⟶ F₃} (f₃ : F₁ ⟶ F₃) (fac : f₁ ≫ f₂ = f₃) [IsLocallySurjective J f₃] [IsLocallyInjective J f₂] : IsLocallySurjective J f₁ := by subst fac exact isLocallySurjective_of_isLocallySurjective_of_isLocallyInjective J f₁ f₂ lemma comp_isLocallyInjective_iff {F₁ F₂ F₃ : Cᵒᵖ ⥤ A} (f₁ : F₁ ⟶ F₂) (f₂ : F₂ ⟶ F₃) [IsLocallyInjective J f₁] [IsLocallySurjective J f₁] : IsLocallyInjective J (f₁ ≫ f₂) ↔ IsLocallyInjective J f₂ := by constructor · intro exact isLocallyInjective_of_isLocallyInjective_of_isLocallySurjective J f₁ f₂ · intro infer_instance lemma isLocallySurjective_comp_iff {F₁ F₂ F₃ : Cᵒᵖ ⥤ A} (f₁ : F₁ ⟶ F₂) (f₂ : F₂ ⟶ F₃)
[IsLocallyInjective J f₂] [IsLocallySurjective J f₂] : IsLocallySurjective J (f₁ ≫ f₂) ↔ IsLocallySurjective J f₁ := by constructor · intro exact isLocallySurjective_of_isLocallySurjective_of_isLocallyInjective J f₁ f₂ · intro infer_instance attribute [local instance] Types.instFunLike Types.instConcreteCategory in
Mathlib/CategoryTheory/Sites/LocallySurjective.lean
253
261
/- Copyright (c) 2019 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import Mathlib.Topology.Constructions import Mathlib.Order.Filter.ListTraverse import Mathlib.Tactic.AdaptationNote import Mathlib.Topology.Algebra.Monoid.Defs /-! # Topology on lists and vectors -/ open TopologicalSpace Set Filter open Topology Filter variable {α : Type*} {β : Type*} [TopologicalSpace α] [TopologicalSpace β] instance : TopologicalSpace (List α) := TopologicalSpace.mkOfNhds (traverse nhds) theorem nhds_list (as : List α) : 𝓝 as = traverse 𝓝 as := by refine nhds_mkOfNhds _ _ ?_ ?_ · intro l induction l with | nil => exact le_rfl | cons a l ih => suffices List.cons <$> pure a <*> pure l ≤ List.cons <$> 𝓝 a <*> traverse 𝓝 l by simpa only [functor_norm] using this exact Filter.seq_mono (Filter.map_mono <| pure_le_nhds a) ih · intro l s hs rcases (mem_traverse_iff _ _).1 hs with ⟨u, hu, hus⟩ clear as hs have : ∃ v : List (Set α), l.Forall₂ (fun a s => IsOpen s ∧ a ∈ s) v ∧ sequence v ⊆ s := by induction hu generalizing s with | nil => exists [] simp only [List.forall₂_nil_left_iff, exists_eq_left] exact ⟨trivial, hus⟩ | cons ht _ ih => rcases mem_nhds_iff.1 ht with ⟨u, hut, hu⟩ rcases ih _ Subset.rfl with ⟨v, hv, hvss⟩ exact ⟨u::v, List.Forall₂.cons hu hv, Subset.trans (Set.seq_mono (Set.image_subset _ hut) hvss) hus⟩ rcases this with ⟨v, hv, hvs⟩ have : sequence v ∈ traverse 𝓝 l := mem_traverse _ _ <| hv.imp fun a s ⟨hs, ha⟩ => IsOpen.mem_nhds hs ha refine mem_of_superset this fun u hu ↦ ?_ have hu := (List.mem_traverse _ _).1 hu have : List.Forall₂ (fun a s => IsOpen s ∧ a ∈ s) u v := by refine List.Forall₂.flip ?_ replace hv := hv.flip simp only [List.forall₂_and_left, Function.flip_def] at hv ⊢ exact ⟨hv.1, hu.flip⟩ refine mem_of_superset ?_ hvs exact mem_traverse _ _ (this.imp fun a s ⟨hs, ha⟩ => IsOpen.mem_nhds hs ha) @[simp] theorem nhds_nil : 𝓝 ([] : List α) = pure [] := by rw [nhds_list, List.traverse_nil _] theorem nhds_cons (a : α) (l : List α) : 𝓝 (a::l) = List.cons <$> 𝓝 a <*> 𝓝 l := by rw [nhds_list, List.traverse_cons _, ← nhds_list] theorem List.tendsto_cons {a : α} {l : List α} : Tendsto (fun p : α × List α => List.cons p.1 p.2) (𝓝 a ×ˢ 𝓝 l) (𝓝 (a::l)) := by rw [nhds_cons, Tendsto, Filter.map_prod]; exact le_rfl theorem Filter.Tendsto.cons {α : Type*} {f : α → β} {g : α → List β} {a : Filter α} {b : β} {l : List β} (hf : Tendsto f a (𝓝 b)) (hg : Tendsto g a (𝓝 l)) : Tendsto (fun a => List.cons (f a) (g a)) a (𝓝 (b::l)) := List.tendsto_cons.comp (Tendsto.prodMk hf hg) namespace List theorem tendsto_cons_iff {β : Type*} {f : List α → β} {b : Filter β} {a : α} {l : List α} : Tendsto f (𝓝 (a::l)) b ↔ Tendsto (fun p : α × List α => f (p.1::p.2)) (𝓝 a ×ˢ 𝓝 l) b := by have : 𝓝 (a::l) = (𝓝 a ×ˢ 𝓝 l).map fun p : α × List α => p.1::p.2 := by simp only [nhds_cons, Filter.prod_eq, (Filter.map_def _ _).symm, (Filter.seq_eq_filter_seq _ _).symm] simp [-Filter.map_def, Function.comp_def, functor_norm] rw [this, Filter.tendsto_map'_iff]; rfl theorem continuous_cons : Continuous fun x : α × List α => (x.1::x.2 : List α) := continuous_iff_continuousAt.mpr fun ⟨_x, _y⟩ => continuousAt_fst.cons continuousAt_snd theorem tendsto_nhds {β : Type*} {f : List α → β} {r : List α → Filter β} (h_nil : Tendsto f (pure []) (r [])) (h_cons : ∀ l a, Tendsto f (𝓝 l) (r l) → Tendsto (fun p : α × List α => f (p.1::p.2)) (𝓝 a ×ˢ 𝓝 l) (r (a::l))) : ∀ l, Tendsto f (𝓝 l) (r l) | [] => by rwa [nhds_nil] | a::l => by rw [tendsto_cons_iff]; exact h_cons l a (@tendsto_nhds _ _ _ h_nil h_cons l) instance [DiscreteTopology α] : DiscreteTopology (List α) := by rw [discreteTopology_iff_nhds]; intro l; induction l <;> simp [*, nhds_cons] theorem continuousAt_length : ∀ l : List α, ContinuousAt List.length l := by simp only [ContinuousAt, nhds_discrete] refine tendsto_nhds ?_ ?_ · exact tendsto_pure_pure _ _ · intro l a ih dsimp only [List.length] refine Tendsto.comp (tendsto_pure_pure (fun x => x + 1) _) ?_ exact Tendsto.comp ih tendsto_snd /-- Continuity of `insertIdx` in terms of `Tendsto`. -/ theorem tendsto_insertIdx' {a : α} : ∀ {n : ℕ} {l : List α}, Tendsto (fun p : α × List α => p.2.insertIdx n p.1) (𝓝 a ×ˢ 𝓝 l) (𝓝 (l.insertIdx n a)) | 0, _ => tendsto_cons | n + 1, [] => by simp | n + 1, a'::l => by have : 𝓝 a ×ˢ 𝓝 (a'::l) = (𝓝 a ×ˢ (𝓝 a' ×ˢ 𝓝 l)).map fun p : α × α × List α => (p.1, p.2.1::p.2.2) := by simp only [nhds_cons, Filter.prod_eq, ← Filter.map_def, ← Filter.seq_eq_filter_seq] simp [-Filter.map_def, Function.comp_def, functor_norm] rw [this, tendsto_map'_iff] exact (tendsto_fst.comp tendsto_snd).cons ((@tendsto_insertIdx' _ n l).comp <| tendsto_fst.prodMk <| tendsto_snd.comp tendsto_snd) theorem tendsto_insertIdx {β} {n : ℕ} {a : α} {l : List α} {f : β → α} {g : β → List α} {b : Filter β} (hf : Tendsto f b (𝓝 a)) (hg : Tendsto g b (𝓝 l)) : Tendsto (fun b : β => (g b).insertIdx n (f b)) b (𝓝 (l.insertIdx n a)) := tendsto_insertIdx'.comp (hf.prodMk hg) theorem continuous_insertIdx {n : ℕ} : Continuous fun p : α × List α => p.2.insertIdx n p.1 := continuous_iff_continuousAt.mpr fun ⟨a, l⟩ => by rw [ContinuousAt, nhds_prod_eq]; exact tendsto_insertIdx' theorem tendsto_eraseIdx : ∀ {n : ℕ} {l : List α}, Tendsto (eraseIdx · n) (𝓝 l) (𝓝 (eraseIdx l n)) | _, [] => by rw [nhds_nil]; exact tendsto_pure_nhds _ _ | 0, a::l => by rw [tendsto_cons_iff]; exact tendsto_snd | n + 1, a::l => by rw [tendsto_cons_iff] dsimp [eraseIdx] exact tendsto_fst.cons ((@tendsto_eraseIdx n l).comp tendsto_snd) theorem continuous_eraseIdx {n : ℕ} : Continuous fun l : List α => eraseIdx l n := continuous_iff_continuousAt.mpr fun _a => tendsto_eraseIdx @[to_additive] theorem tendsto_prod [MulOneClass α] [ContinuousMul α] {l : List α} : Tendsto List.prod (𝓝 l) (𝓝 l.prod) := by induction l with | nil => simp +contextual [nhds_nil, mem_of_mem_nhds, tendsto_pure_left] | cons x l ih => simp_rw [tendsto_cons_iff, prod_cons] have := continuous_iff_continuousAt.mp continuous_mul (x, l.prod) rw [ContinuousAt, nhds_prod_eq] at this exact this.comp (tendsto_id.prodMap ih) @[to_additive] theorem continuous_prod [MulOneClass α] [ContinuousMul α] : Continuous (prod : List α → α) := continuous_iff_continuousAt.mpr fun _l => tendsto_prod end List namespace List.Vector open List instance (n : ℕ) : TopologicalSpace (Vector α n) := by unfold Vector; infer_instance theorem tendsto_cons {n : ℕ} {a : α} {l : Vector α n} : Tendsto (fun p : α × Vector α n => p.1 ::ᵥ p.2) (𝓝 a ×ˢ 𝓝 l) (𝓝 (a ::ᵥ l)) := by rw [tendsto_subtype_rng, Vector.cons_val] exact tendsto_fst.cons (Tendsto.comp continuousAt_subtype_val tendsto_snd) theorem tendsto_insertIdx {n : ℕ} {i : Fin (n + 1)} {a : α} : ∀ {l : Vector α n}, Tendsto (fun p : α × Vector α n => insertIdx p.1 i p.2) (𝓝 a ×ˢ 𝓝 l) (𝓝 (insertIdx a i l)) | ⟨l, hl⟩ => by rw [insertIdx, tendsto_subtype_rng] simp only [insertIdx_val] exact List.tendsto_insertIdx tendsto_fst (Tendsto.comp continuousAt_subtype_val tendsto_snd : _) /-- Continuity of `Vector.insertIdx`. -/ theorem continuous_insertIdx' {n : ℕ} {i : Fin (n + 1)} : Continuous fun p : α × Vector α n => Vector.insertIdx p.1 i p.2 := continuous_iff_continuousAt.mpr fun ⟨a, l⟩ => by rw [ContinuousAt, nhds_prod_eq]; exact tendsto_insertIdx theorem continuous_insertIdx {n : ℕ} {i : Fin (n + 1)} {f : β → α} {g : β → Vector α n} (hf : Continuous f) (hg : Continuous g) : Continuous fun b => Vector.insertIdx (f b) i (g b) := continuous_insertIdx'.comp (hf.prodMk hg) theorem continuousAt_eraseIdx {n : ℕ} {i : Fin (n + 1)} : ∀ {l : Vector α (n + 1)}, ContinuousAt (Vector.eraseIdx i) l | ⟨l, hl⟩ => by rw [ContinuousAt, Vector.eraseIdx, tendsto_subtype_rng] simp only [Vector.eraseIdx_val] exact Tendsto.comp List.tendsto_eraseIdx continuousAt_subtype_val
theorem continuous_eraseIdx {n : ℕ} {i : Fin (n + 1)} : Continuous (Vector.eraseIdx i : Vector α (n + 1) → Vector α n) := continuous_iff_continuousAt.mpr fun ⟨_a, _l⟩ => continuousAt_eraseIdx end List.Vector
Mathlib/Topology/List.lean
206
212
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathlib.Data.WSeq.Basic import Mathlib.Data.WSeq.Defs import Mathlib.Data.WSeq.Productive import Mathlib.Data.WSeq.Relation deprecated_module (since := "2025-04-13")
Mathlib/Data/Seq/WSeq.lean
663
663
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Abhimanyu Pallavi Sudhir, Jean Lo, Calle Sönne, Sébastien Gouëzel, Rémy Degenne, David Loeffler -/ import Mathlib.Analysis.SpecialFunctions.Pow.Complex import Qq /-! # Power function on `ℝ` We construct the power functions `x ^ y`, where `x` and `y` are real numbers. -/ noncomputable section open Real ComplexConjugate Finset Set /- ## Definitions -/ namespace Real variable {x y z : ℝ} /-- The real power function `x ^ y`, defined as the real part of the complex power function. For `x > 0`, it is equal to `exp (y log x)`. For `x = 0`, one sets `0 ^ 0=1` and `0 ^ y=0` for `y ≠ 0`. For `x < 0`, the definition is somewhat arbitrary as it depends on the choice of a complex determination of the logarithm. With our conventions, it is equal to `exp (y log x) cos (π y)`. -/ noncomputable def rpow (x y : ℝ) := ((x : ℂ) ^ (y : ℂ)).re noncomputable instance : Pow ℝ ℝ := ⟨rpow⟩ @[simp] theorem rpow_eq_pow (x y : ℝ) : rpow x y = x ^ y := rfl theorem rpow_def (x y : ℝ) : x ^ y = ((x : ℂ) ^ (y : ℂ)).re := rfl theorem rpow_def_of_nonneg {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : x ^ y = if x = 0 then if y = 0 then 1 else 0 else exp (log x * y) := by simp only [rpow_def, Complex.cpow_def]; split_ifs <;> simp_all [(Complex.ofReal_log hx).symm, -Complex.ofReal_mul, (Complex.ofReal_mul _ _).symm, Complex.exp_ofReal_re, Complex.ofReal_eq_zero] theorem rpow_def_of_pos {x : ℝ} (hx : 0 < x) (y : ℝ) : x ^ y = exp (log x * y) := by rw [rpow_def_of_nonneg (le_of_lt hx), if_neg (ne_of_gt hx)] theorem exp_mul (x y : ℝ) : exp (x * y) = exp x ^ y := by rw [rpow_def_of_pos (exp_pos _), log_exp] @[simp, norm_cast] theorem rpow_intCast (x : ℝ) (n : ℤ) : x ^ (n : ℝ) = x ^ n := by simp only [rpow_def, ← Complex.ofReal_zpow, Complex.cpow_intCast, Complex.ofReal_intCast, Complex.ofReal_re] @[simp, norm_cast] theorem rpow_natCast (x : ℝ) (n : ℕ) : x ^ (n : ℝ) = x ^ n := by simpa using rpow_intCast x n @[simp] theorem exp_one_rpow (x : ℝ) : exp 1 ^ x = exp x := by rw [← exp_mul, one_mul] @[simp] lemma exp_one_pow (n : ℕ) : exp 1 ^ n = exp n := by rw [← rpow_natCast, exp_one_rpow] theorem rpow_eq_zero_iff_of_nonneg (hx : 0 ≤ x) : x ^ y = 0 ↔ x = 0 ∧ y ≠ 0 := by simp only [rpow_def_of_nonneg hx] split_ifs <;> simp [*, exp_ne_zero] @[simp] lemma rpow_eq_zero (hx : 0 ≤ x) (hy : y ≠ 0) : x ^ y = 0 ↔ x = 0 := by simp [rpow_eq_zero_iff_of_nonneg, *] @[simp] lemma rpow_ne_zero (hx : 0 ≤ x) (hy : y ≠ 0) : x ^ y ≠ 0 ↔ x ≠ 0 := Real.rpow_eq_zero hx hy |>.not open Real theorem rpow_def_of_neg {x : ℝ} (hx : x < 0) (y : ℝ) : x ^ y = exp (log x * y) * cos (y * π) := by rw [rpow_def, Complex.cpow_def, if_neg] · have : Complex.log x * y = ↑(log (-x) * y) + ↑(y * π) * Complex.I := by simp only [Complex.log, Complex.norm_real, norm_eq_abs, abs_of_neg hx, log_neg_eq_log, Complex.arg_ofReal_of_neg hx, Complex.ofReal_mul] ring rw [this, Complex.exp_add_mul_I, ← Complex.ofReal_exp, ← Complex.ofReal_cos, ← Complex.ofReal_sin, mul_add, ← Complex.ofReal_mul, ← mul_assoc, ← Complex.ofReal_mul, Complex.add_re, Complex.ofReal_re, Complex.mul_re, Complex.I_re, Complex.ofReal_im, Real.log_neg_eq_log] ring · rw [Complex.ofReal_eq_zero] exact ne_of_lt hx theorem rpow_def_of_nonpos {x : ℝ} (hx : x ≤ 0) (y : ℝ) : x ^ y = if x = 0 then if y = 0 then 1 else 0 else exp (log x * y) * cos (y * π) := by split_ifs with h <;> simp [rpow_def, *]; exact rpow_def_of_neg (lt_of_le_of_ne hx h) _ @[bound] theorem rpow_pos_of_pos {x : ℝ} (hx : 0 < x) (y : ℝ) : 0 < x ^ y := by rw [rpow_def_of_pos hx]; apply exp_pos @[simp] theorem rpow_zero (x : ℝ) : x ^ (0 : ℝ) = 1 := by simp [rpow_def] theorem rpow_zero_pos (x : ℝ) : 0 < x ^ (0 : ℝ) := by simp @[simp] theorem zero_rpow {x : ℝ} (h : x ≠ 0) : (0 : ℝ) ^ x = 0 := by simp [rpow_def, *] theorem zero_rpow_eq_iff {x : ℝ} {a : ℝ} : 0 ^ x = a ↔ x ≠ 0 ∧ a = 0 ∨ x = 0 ∧ a = 1 := by constructor · intro hyp simp only [rpow_def, Complex.ofReal_zero] at hyp by_cases h : x = 0 · subst h simp only [Complex.one_re, Complex.ofReal_zero, Complex.cpow_zero] at hyp exact Or.inr ⟨rfl, hyp.symm⟩ · rw [Complex.zero_cpow (Complex.ofReal_ne_zero.mpr h)] at hyp exact Or.inl ⟨h, hyp.symm⟩ · rintro (⟨h, rfl⟩ | ⟨rfl, rfl⟩) · exact zero_rpow h · exact rpow_zero _ theorem eq_zero_rpow_iff {x : ℝ} {a : ℝ} : a = 0 ^ x ↔ x ≠ 0 ∧ a = 0 ∨ x = 0 ∧ a = 1 := by rw [← zero_rpow_eq_iff, eq_comm] @[simp] theorem rpow_one (x : ℝ) : x ^ (1 : ℝ) = x := by simp [rpow_def] @[simp] theorem one_rpow (x : ℝ) : (1 : ℝ) ^ x = 1 := by simp [rpow_def] theorem zero_rpow_le_one (x : ℝ) : (0 : ℝ) ^ x ≤ 1 := by by_cases h : x = 0 <;> simp [h, zero_le_one] theorem zero_rpow_nonneg (x : ℝ) : 0 ≤ (0 : ℝ) ^ x := by by_cases h : x = 0 <;> simp [h, zero_le_one] @[bound] theorem rpow_nonneg {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : 0 ≤ x ^ y := by rw [rpow_def_of_nonneg hx]; split_ifs <;> simp only [zero_le_one, le_refl, le_of_lt (exp_pos _)] theorem abs_rpow_of_nonneg {x y : ℝ} (hx_nonneg : 0 ≤ x) : |x ^ y| = |x| ^ y := by have h_rpow_nonneg : 0 ≤ x ^ y := Real.rpow_nonneg hx_nonneg _ rw [abs_eq_self.mpr hx_nonneg, abs_eq_self.mpr h_rpow_nonneg] @[bound] theorem abs_rpow_le_abs_rpow (x y : ℝ) : |x ^ y| ≤ |x| ^ y := by rcases le_or_lt 0 x with hx | hx · rw [abs_rpow_of_nonneg hx] · rw [abs_of_neg hx, rpow_def_of_neg hx, rpow_def_of_pos (neg_pos.2 hx), log_neg_eq_log, abs_mul, abs_of_pos (exp_pos _)] exact mul_le_of_le_one_right (exp_pos _).le (abs_cos_le_one _) theorem abs_rpow_le_exp_log_mul (x y : ℝ) : |x ^ y| ≤ exp (log x * y) := by refine (abs_rpow_le_abs_rpow x y).trans ?_ by_cases hx : x = 0 · by_cases hy : y = 0 <;> simp [hx, hy, zero_le_one] · rw [rpow_def_of_pos (abs_pos.2 hx), log_abs] lemma rpow_inv_log (hx₀ : 0 < x) (hx₁ : x ≠ 1) : x ^ (log x)⁻¹ = exp 1 := by rw [rpow_def_of_pos hx₀, mul_inv_cancel₀] exact log_ne_zero.2 ⟨hx₀.ne', hx₁, (hx₀.trans' <| by norm_num).ne'⟩ /-- See `Real.rpow_inv_log` for the equality when `x ≠ 1` is strictly positive. -/ lemma rpow_inv_log_le_exp_one : x ^ (log x)⁻¹ ≤ exp 1 := by calc _ ≤ |x ^ (log x)⁻¹| := le_abs_self _ _ ≤ |x| ^ (log x)⁻¹ := abs_rpow_le_abs_rpow .. rw [← log_abs] obtain hx | hx := (abs_nonneg x).eq_or_gt · simp [hx] · rw [rpow_def_of_pos hx] gcongr exact mul_inv_le_one theorem norm_rpow_of_nonneg {x y : ℝ} (hx_nonneg : 0 ≤ x) : ‖x ^ y‖ = ‖x‖ ^ y := by simp_rw [Real.norm_eq_abs] exact abs_rpow_of_nonneg hx_nonneg variable {w x y z : ℝ} theorem rpow_add (hx : 0 < x) (y z : ℝ) : x ^ (y + z) = x ^ y * x ^ z := by simp only [rpow_def_of_pos hx, mul_add, exp_add] theorem rpow_add' (hx : 0 ≤ x) (h : y + z ≠ 0) : x ^ (y + z) = x ^ y * x ^ z := by rcases hx.eq_or_lt with (rfl | pos) · rw [zero_rpow h, zero_eq_mul] have : y ≠ 0 ∨ z ≠ 0 := not_and_or.1 fun ⟨hy, hz⟩ => h <| hy.symm ▸ hz.symm ▸ zero_add 0 exact this.imp zero_rpow zero_rpow · exact rpow_add pos _ _ /-- Variant of `Real.rpow_add'` that avoids having to prove `y + z = w` twice. -/ lemma rpow_of_add_eq (hx : 0 ≤ x) (hw : w ≠ 0) (h : y + z = w) : x ^ w = x ^ y * x ^ z := by rw [← h, rpow_add' hx]; rwa [h] theorem rpow_add_of_nonneg (hx : 0 ≤ x) (hy : 0 ≤ y) (hz : 0 ≤ z) : x ^ (y + z) = x ^ y * x ^ z := by rcases hy.eq_or_lt with (rfl | hy) · rw [zero_add, rpow_zero, one_mul] exact rpow_add' hx (ne_of_gt <| add_pos_of_pos_of_nonneg hy hz) /-- For `0 ≤ x`, the only problematic case in the equality `x ^ y * x ^ z = x ^ (y + z)` is for `x = 0` and `y + z = 0`, where the right hand side is `1` while the left hand side can vanish. The inequality is always true, though, and given in this lemma. -/ theorem le_rpow_add {x : ℝ} (hx : 0 ≤ x) (y z : ℝ) : x ^ y * x ^ z ≤ x ^ (y + z) := by rcases le_iff_eq_or_lt.1 hx with (H | pos) · by_cases h : y + z = 0 · simp only [H.symm, h, rpow_zero] calc (0 : ℝ) ^ y * 0 ^ z ≤ 1 * 1 := mul_le_mul (zero_rpow_le_one y) (zero_rpow_le_one z) (zero_rpow_nonneg z) zero_le_one _ = 1 := by simp · simp [rpow_add', ← H, h] · simp [rpow_add pos] theorem rpow_sum_of_pos {ι : Type*} {a : ℝ} (ha : 0 < a) (f : ι → ℝ) (s : Finset ι) : (a ^ ∑ x ∈ s, f x) = ∏ x ∈ s, a ^ f x := map_sum (⟨⟨fun (x : ℝ) => (a ^ x : ℝ), rpow_zero a⟩, rpow_add ha⟩ : ℝ →+ (Additive ℝ)) f s theorem rpow_sum_of_nonneg {ι : Type*} {a : ℝ} (ha : 0 ≤ a) {s : Finset ι} {f : ι → ℝ} (h : ∀ x ∈ s, 0 ≤ f x) : (a ^ ∑ x ∈ s, f x) = ∏ x ∈ s, a ^ f x := by induction' s using Finset.cons_induction with i s hi ihs · rw [sum_empty, Finset.prod_empty, rpow_zero] · rw [forall_mem_cons] at h rw [sum_cons, prod_cons, ← ihs h.2, rpow_add_of_nonneg ha h.1 (sum_nonneg h.2)] theorem rpow_neg {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : x ^ (-y) = (x ^ y)⁻¹ := by simp only [rpow_def_of_nonneg hx]; split_ifs <;> simp_all [exp_neg] theorem rpow_sub {x : ℝ} (hx : 0 < x) (y z : ℝ) : x ^ (y - z) = x ^ y / x ^ z := by simp only [sub_eq_add_neg, rpow_add hx, rpow_neg (le_of_lt hx), div_eq_mul_inv] theorem rpow_sub' {x : ℝ} (hx : 0 ≤ x) {y z : ℝ} (h : y - z ≠ 0) : x ^ (y - z) = x ^ y / x ^ z := by simp only [sub_eq_add_neg] at h ⊢ simp only [rpow_add' hx h, rpow_neg hx, div_eq_mul_inv] protected theorem _root_.HasCompactSupport.rpow_const {α : Type*} [TopologicalSpace α] {f : α → ℝ} (hf : HasCompactSupport f) {r : ℝ} (hr : r ≠ 0) : HasCompactSupport (fun x ↦ f x ^ r) := hf.comp_left (g := (· ^ r)) (Real.zero_rpow hr) end Real /-! ## Comparing real and complex powers -/ namespace Complex theorem ofReal_cpow {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : ((x ^ y : ℝ) : ℂ) = (x : ℂ) ^ (y : ℂ) := by simp only [Real.rpow_def_of_nonneg hx, Complex.cpow_def, ofReal_eq_zero]; split_ifs <;> simp [Complex.ofReal_log hx] theorem ofReal_cpow_of_nonpos {x : ℝ} (hx : x ≤ 0) (y : ℂ) : (x : ℂ) ^ y = (-x : ℂ) ^ y * exp (π * I * y) := by rcases hx.eq_or_lt with (rfl | hlt) · rcases eq_or_ne y 0 with (rfl | hy) <;> simp [*] have hne : (x : ℂ) ≠ 0 := ofReal_ne_zero.mpr hlt.ne rw [cpow_def_of_ne_zero hne, cpow_def_of_ne_zero (neg_ne_zero.2 hne), ← exp_add, ← add_mul, log, log, norm_neg, arg_ofReal_of_neg hlt, ← ofReal_neg, arg_ofReal_of_nonneg (neg_nonneg.2 hx), ofReal_zero, zero_mul, add_zero] lemma cpow_ofReal (x : ℂ) (y : ℝ) : x ^ (y : ℂ) = ↑(‖x‖ ^ y) * (Real.cos (arg x * y) + Real.sin (arg x * y) * I) := by rcases eq_or_ne x 0 with rfl | hx · simp [ofReal_cpow le_rfl] · rw [cpow_def_of_ne_zero hx, exp_eq_exp_re_mul_sin_add_cos, mul_comm (log x)] norm_cast rw [re_ofReal_mul, im_ofReal_mul, log_re, log_im, mul_comm y, mul_comm y, Real.exp_mul, Real.exp_log] rwa [norm_pos_iff] lemma cpow_ofReal_re (x : ℂ) (y : ℝ) : (x ^ (y : ℂ)).re = ‖x‖ ^ y * Real.cos (arg x * y) := by rw [cpow_ofReal]; generalize arg x * y = z; simp [Real.cos] lemma cpow_ofReal_im (x : ℂ) (y : ℝ) : (x ^ (y : ℂ)).im = ‖x‖ ^ y * Real.sin (arg x * y) := by rw [cpow_ofReal]; generalize arg x * y = z; simp [Real.sin] theorem norm_cpow_of_ne_zero {z : ℂ} (hz : z ≠ 0) (w : ℂ) : ‖z ^ w‖ = ‖z‖ ^ w.re / Real.exp (arg z * im w) := by rw [cpow_def_of_ne_zero hz, norm_exp, mul_re, log_re, log_im, Real.exp_sub, Real.rpow_def_of_pos (norm_pos_iff.mpr hz)] theorem norm_cpow_of_imp {z w : ℂ} (h : z = 0 → w.re = 0 → w = 0) : ‖z ^ w‖ = ‖z‖ ^ w.re / Real.exp (arg z * im w) := by rcases ne_or_eq z 0 with (hz | rfl) <;> [exact norm_cpow_of_ne_zero hz w; rw [norm_zero]] rcases eq_or_ne w.re 0 with hw | hw · simp [hw, h rfl hw] · rw [Real.zero_rpow hw, zero_div, zero_cpow, norm_zero] exact ne_of_apply_ne re hw theorem norm_cpow_le (z w : ℂ) : ‖z ^ w‖ ≤ ‖z‖ ^ w.re / Real.exp (arg z * im w) := by by_cases h : z = 0 → w.re = 0 → w = 0 · exact (norm_cpow_of_imp h).le · push_neg at h simp [h] @[simp] theorem norm_cpow_real (x : ℂ) (y : ℝ) : ‖x ^ (y : ℂ)‖ = ‖x‖ ^ y := by rw [norm_cpow_of_imp] <;> simp @[simp] theorem norm_cpow_inv_nat (x : ℂ) (n : ℕ) : ‖x ^ (n⁻¹ : ℂ)‖ = ‖x‖ ^ (n⁻¹ : ℝ) := by rw [← norm_cpow_real]; simp theorem norm_cpow_eq_rpow_re_of_pos {x : ℝ} (hx : 0 < x) (y : ℂ) : ‖(x : ℂ) ^ y‖ = x ^ y.re := by rw [norm_cpow_of_ne_zero (ofReal_ne_zero.mpr hx.ne'), arg_ofReal_of_nonneg hx.le, zero_mul, Real.exp_zero, div_one, Complex.norm_of_nonneg hx.le] theorem norm_cpow_eq_rpow_re_of_nonneg {x : ℝ} (hx : 0 ≤ x) {y : ℂ} (hy : re y ≠ 0) : ‖(x : ℂ) ^ y‖ = x ^ re y := by rw [norm_cpow_of_imp] <;> simp [*, arg_ofReal_of_nonneg, abs_of_nonneg] @[deprecated (since := "2025-02-17")] alias abs_cpow_of_ne_zero := norm_cpow_of_ne_zero @[deprecated (since := "2025-02-17")] alias abs_cpow_of_imp := norm_cpow_of_imp @[deprecated (since := "2025-02-17")] alias abs_cpow_le := norm_cpow_le @[deprecated (since := "2025-02-17")] alias abs_cpow_real := norm_cpow_real @[deprecated (since := "2025-02-17")] alias abs_cpow_inv_nat := norm_cpow_inv_nat @[deprecated (since := "2025-02-17")] alias abs_cpow_eq_rpow_re_of_pos := norm_cpow_eq_rpow_re_of_pos @[deprecated (since := "2025-02-17")] alias abs_cpow_eq_rpow_re_of_nonneg := norm_cpow_eq_rpow_re_of_nonneg open Filter in lemma norm_ofReal_cpow_eventually_eq_atTop (c : ℂ) : (fun t : ℝ ↦ ‖(t : ℂ) ^ c‖) =ᶠ[atTop] fun t ↦ t ^ c.re := by filter_upwards [eventually_gt_atTop 0] with t ht rw [norm_cpow_eq_rpow_re_of_pos ht] lemma norm_natCast_cpow_of_re_ne_zero (n : ℕ) {s : ℂ} (hs : s.re ≠ 0) : ‖(n : ℂ) ^ s‖ = (n : ℝ) ^ (s.re) := by rw [← ofReal_natCast, norm_cpow_eq_rpow_re_of_nonneg n.cast_nonneg hs] lemma norm_natCast_cpow_of_pos {n : ℕ} (hn : 0 < n) (s : ℂ) : ‖(n : ℂ) ^ s‖ = (n : ℝ) ^ (s.re) := by rw [← ofReal_natCast, norm_cpow_eq_rpow_re_of_pos (Nat.cast_pos.mpr hn) _] lemma norm_natCast_cpow_pos_of_pos {n : ℕ} (hn : 0 < n) (s : ℂ) : 0 < ‖(n : ℂ) ^ s‖ := (norm_natCast_cpow_of_pos hn _).symm ▸ Real.rpow_pos_of_pos (Nat.cast_pos.mpr hn) _ theorem cpow_mul_ofReal_nonneg {x : ℝ} (hx : 0 ≤ x) (y : ℝ) (z : ℂ) : (x : ℂ) ^ (↑y * z) = (↑(x ^ y) : ℂ) ^ z := by rw [cpow_mul, ofReal_cpow hx] · rw [← ofReal_log hx, ← ofReal_mul, ofReal_im, neg_lt_zero]; exact Real.pi_pos · rw [← ofReal_log hx, ← ofReal_mul, ofReal_im]; exact Real.pi_pos.le end Complex /-! ### Positivity extension -/ namespace Mathlib.Meta.Positivity open Lean Meta Qq /-- Extension for the `positivity` tactic: exponentiation by a real number is positive (namely 1) when the exponent is zero. The other cases are done in `evalRpow`. -/ @[positivity (_ : ℝ) ^ (0 : ℝ)] def evalRpowZero : PositivityExt where eval {u α} _ _ e := do match u, α, e with | 0, ~q(ℝ), ~q($a ^ (0 : ℝ)) => assertInstancesCommute pure (.positive q(Real.rpow_zero_pos $a)) | _, _, _ => throwError "not Real.rpow" /-- Extension for the `positivity` tactic: exponentiation by a real number is nonnegative when the base is nonnegative and positive when the base is positive. -/ @[positivity (_ : ℝ) ^ (_ : ℝ)] def evalRpow : PositivityExt where eval {u α} _zα _pα e := do match u, α, e with | 0, ~q(ℝ), ~q($a ^ ($b : ℝ)) => let ra ← core q(inferInstance) q(inferInstance) a assertInstancesCommute match ra with | .positive pa => pure (.positive q(Real.rpow_pos_of_pos $pa $b)) | .nonnegative pa => pure (.nonnegative q(Real.rpow_nonneg $pa $b)) | _ => pure .none | _, _, _ => throwError "not Real.rpow" end Mathlib.Meta.Positivity /-! ## Further algebraic properties of `rpow` -/ namespace Real variable {x y z : ℝ} {n : ℕ} theorem rpow_mul {x : ℝ} (hx : 0 ≤ x) (y z : ℝ) : x ^ (y * z) = (x ^ y) ^ z := by rw [← Complex.ofReal_inj, Complex.ofReal_cpow (rpow_nonneg hx _), Complex.ofReal_cpow hx, Complex.ofReal_mul, Complex.cpow_mul, Complex.ofReal_cpow hx] <;> simp only [(Complex.ofReal_mul _ _).symm, (Complex.ofReal_log hx).symm, Complex.ofReal_im, neg_lt_zero, pi_pos, le_of_lt pi_pos] lemma rpow_pow_comm {x : ℝ} (hx : 0 ≤ x) (y : ℝ) (n : ℕ) : (x ^ y) ^ n = (x ^ n) ^ y := by simp_rw [← rpow_natCast, ← rpow_mul hx, mul_comm y] lemma rpow_zpow_comm {x : ℝ} (hx : 0 ≤ x) (y : ℝ) (n : ℤ) : (x ^ y) ^ n = (x ^ n) ^ y := by simp_rw [← rpow_intCast, ← rpow_mul hx, mul_comm y] lemma rpow_add_intCast {x : ℝ} (hx : x ≠ 0) (y : ℝ) (n : ℤ) : x ^ (y + n) = x ^ y * x ^ n := by rw [rpow_def, rpow_def, Complex.ofReal_add, Complex.cpow_add _ _ (Complex.ofReal_ne_zero.mpr hx), Complex.ofReal_intCast, Complex.cpow_intCast, ← Complex.ofReal_zpow, mul_comm, Complex.re_ofReal_mul, mul_comm] lemma rpow_add_natCast {x : ℝ} (hx : x ≠ 0) (y : ℝ) (n : ℕ) : x ^ (y + n) = x ^ y * x ^ n := by simpa using rpow_add_intCast hx y n lemma rpow_sub_intCast {x : ℝ} (hx : x ≠ 0) (y : ℝ) (n : ℕ) : x ^ (y - n) = x ^ y / x ^ n := by simpa using rpow_add_intCast hx y (-n) lemma rpow_sub_natCast {x : ℝ} (hx : x ≠ 0) (y : ℝ) (n : ℕ) : x ^ (y - n) = x ^ y / x ^ n := by simpa using rpow_sub_intCast hx y n lemma rpow_add_intCast' (hx : 0 ≤ x) {n : ℤ} (h : y + n ≠ 0) : x ^ (y + n) = x ^ y * x ^ n := by rw [rpow_add' hx h, rpow_intCast] lemma rpow_add_natCast' (hx : 0 ≤ x) (h : y + n ≠ 0) : x ^ (y + n) = x ^ y * x ^ n := by rw [rpow_add' hx h, rpow_natCast] lemma rpow_sub_intCast' (hx : 0 ≤ x) {n : ℤ} (h : y - n ≠ 0) : x ^ (y - n) = x ^ y / x ^ n := by rw [rpow_sub' hx h, rpow_intCast] lemma rpow_sub_natCast' (hx : 0 ≤ x) (h : y - n ≠ 0) : x ^ (y - n) = x ^ y / x ^ n := by rw [rpow_sub' hx h, rpow_natCast] theorem rpow_add_one {x : ℝ} (hx : x ≠ 0) (y : ℝ) : x ^ (y + 1) = x ^ y * x := by simpa using rpow_add_natCast hx y 1 theorem rpow_sub_one {x : ℝ} (hx : x ≠ 0) (y : ℝ) : x ^ (y - 1) = x ^ y / x := by simpa using rpow_sub_natCast hx y 1 lemma rpow_add_one' (hx : 0 ≤ x) (h : y + 1 ≠ 0) : x ^ (y + 1) = x ^ y * x := by rw [rpow_add' hx h, rpow_one] lemma rpow_one_add' (hx : 0 ≤ x) (h : 1 + y ≠ 0) : x ^ (1 + y) = x * x ^ y := by rw [rpow_add' hx h, rpow_one] lemma rpow_sub_one' (hx : 0 ≤ x) (h : y - 1 ≠ 0) : x ^ (y - 1) = x ^ y / x := by rw [rpow_sub' hx h, rpow_one] lemma rpow_one_sub' (hx : 0 ≤ x) (h : 1 - y ≠ 0) : x ^ (1 - y) = x / x ^ y := by rw [rpow_sub' hx h, rpow_one] @[simp] theorem rpow_two (x : ℝ) : x ^ (2 : ℝ) = x ^ 2 := by rw [← rpow_natCast] simp only [Nat.cast_ofNat] theorem rpow_neg_one (x : ℝ) : x ^ (-1 : ℝ) = x⁻¹ := by suffices H : x ^ ((-1 : ℤ) : ℝ) = x⁻¹ by rwa [Int.cast_neg, Int.cast_one] at H simp only [rpow_intCast, zpow_one, zpow_neg] theorem mul_rpow (hx : 0 ≤ x) (hy : 0 ≤ y) : (x * y) ^ z = x ^ z * y ^ z := by iterate 2 rw [Real.rpow_def_of_nonneg]; split_ifs with h_ifs <;> simp_all · rw [log_mul ‹_› ‹_›, add_mul, exp_add, rpow_def_of_pos (hy.lt_of_ne' ‹_›)] all_goals positivity theorem inv_rpow (hx : 0 ≤ x) (y : ℝ) : x⁻¹ ^ y = (x ^ y)⁻¹ := by simp only [← rpow_neg_one, ← rpow_mul hx, mul_comm] theorem div_rpow (hx : 0 ≤ x) (hy : 0 ≤ y) (z : ℝ) : (x / y) ^ z = x ^ z / y ^ z := by simp only [div_eq_mul_inv, mul_rpow hx (inv_nonneg.2 hy), inv_rpow hy] theorem log_rpow {x : ℝ} (hx : 0 < x) (y : ℝ) : log (x ^ y) = y * log x := by apply exp_injective rw [exp_log (rpow_pos_of_pos hx y), ← exp_log hx, mul_comm, rpow_def_of_pos (exp_pos (log x)) y] theorem mul_log_eq_log_iff {x y z : ℝ} (hx : 0 < x) (hz : 0 < z) : y * log x = log z ↔ x ^ y = z := ⟨fun h ↦ log_injOn_pos (rpow_pos_of_pos hx _) hz <| log_rpow hx _ |>.trans h, by rintro rfl; rw [log_rpow hx]⟩ @[simp] lemma rpow_rpow_inv (hx : 0 ≤ x) (hy : y ≠ 0) : (x ^ y) ^ y⁻¹ = x := by rw [← rpow_mul hx, mul_inv_cancel₀ hy, rpow_one] @[simp] lemma rpow_inv_rpow (hx : 0 ≤ x) (hy : y ≠ 0) : (x ^ y⁻¹) ^ y = x := by rw [← rpow_mul hx, inv_mul_cancel₀ hy, rpow_one] theorem pow_rpow_inv_natCast (hx : 0 ≤ x) (hn : n ≠ 0) : (x ^ n) ^ (n⁻¹ : ℝ) = x := by have hn0 : (n : ℝ) ≠ 0 := Nat.cast_ne_zero.2 hn rw [← rpow_natCast, ← rpow_mul hx, mul_inv_cancel₀ hn0, rpow_one] theorem rpow_inv_natCast_pow (hx : 0 ≤ x) (hn : n ≠ 0) : (x ^ (n⁻¹ : ℝ)) ^ n = x := by have hn0 : (n : ℝ) ≠ 0 := Nat.cast_ne_zero.2 hn rw [← rpow_natCast, ← rpow_mul hx, inv_mul_cancel₀ hn0, rpow_one] lemma rpow_natCast_mul (hx : 0 ≤ x) (n : ℕ) (z : ℝ) : x ^ (n * z) = (x ^ n) ^ z := by rw [rpow_mul hx, rpow_natCast] lemma rpow_mul_natCast (hx : 0 ≤ x) (y : ℝ) (n : ℕ) : x ^ (y * n) = (x ^ y) ^ n := by rw [rpow_mul hx, rpow_natCast] lemma rpow_intCast_mul (hx : 0 ≤ x) (n : ℤ) (z : ℝ) : x ^ (n * z) = (x ^ n) ^ z := by rw [rpow_mul hx, rpow_intCast] lemma rpow_mul_intCast (hx : 0 ≤ x) (y : ℝ) (n : ℤ) : x ^ (y * n) = (x ^ y) ^ n := by rw [rpow_mul hx, rpow_intCast] /-! Note: lemmas about `(∏ i ∈ s, f i ^ r)` such as `Real.finset_prod_rpow` are proved in `Mathlib/Analysis/SpecialFunctions/Pow/NNReal.lean` instead. -/ /-! ## Order and monotonicity -/ @[gcongr, bound] theorem rpow_lt_rpow (hx : 0 ≤ x) (hxy : x < y) (hz : 0 < z) : x ^ z < y ^ z := by rw [le_iff_eq_or_lt] at hx; rcases hx with hx | hx · rw [← hx, zero_rpow (ne_of_gt hz)] exact rpow_pos_of_pos (by rwa [← hx] at hxy) _ · rw [rpow_def_of_pos hx, rpow_def_of_pos (lt_trans hx hxy), exp_lt_exp] exact mul_lt_mul_of_pos_right (log_lt_log hx hxy) hz theorem strictMonoOn_rpow_Ici_of_exponent_pos {r : ℝ} (hr : 0 < r) : StrictMonoOn (fun (x : ℝ) => x ^ r) (Set.Ici 0) := fun _ ha _ _ hab => rpow_lt_rpow ha hab hr @[gcongr, bound] theorem rpow_le_rpow {x y z : ℝ} (h : 0 ≤ x) (h₁ : x ≤ y) (h₂ : 0 ≤ z) : x ^ z ≤ y ^ z := by rcases eq_or_lt_of_le h₁ with (rfl | h₁'); · rfl rcases eq_or_lt_of_le h₂ with (rfl | h₂'); · simp exact le_of_lt (rpow_lt_rpow h h₁' h₂') theorem monotoneOn_rpow_Ici_of_exponent_nonneg {r : ℝ} (hr : 0 ≤ r) : MonotoneOn (fun (x : ℝ) => x ^ r) (Set.Ici 0) := fun _ ha _ _ hab => rpow_le_rpow ha hab hr lemma rpow_lt_rpow_of_neg (hx : 0 < x) (hxy : x < y) (hz : z < 0) : y ^ z < x ^ z := by have := hx.trans hxy rw [← inv_lt_inv₀, ← rpow_neg, ← rpow_neg] on_goal 1 => refine rpow_lt_rpow ?_ hxy (neg_pos.2 hz) all_goals positivity lemma rpow_le_rpow_of_nonpos (hx : 0 < x) (hxy : x ≤ y) (hz : z ≤ 0) : y ^ z ≤ x ^ z := by have := hx.trans_le hxy rw [← inv_le_inv₀, ← rpow_neg, ← rpow_neg] on_goal 1 => refine rpow_le_rpow ?_ hxy (neg_nonneg.2 hz) all_goals positivity theorem rpow_lt_rpow_iff (hx : 0 ≤ x) (hy : 0 ≤ y) (hz : 0 < z) : x ^ z < y ^ z ↔ x < y := ⟨lt_imp_lt_of_le_imp_le fun h => rpow_le_rpow hy h (le_of_lt hz), fun h => rpow_lt_rpow hx h hz⟩ theorem rpow_le_rpow_iff (hx : 0 ≤ x) (hy : 0 ≤ y) (hz : 0 < z) : x ^ z ≤ y ^ z ↔ x ≤ y := le_iff_le_iff_lt_iff_lt.2 <| rpow_lt_rpow_iff hy hx hz lemma rpow_lt_rpow_iff_of_neg (hx : 0 < x) (hy : 0 < y) (hz : z < 0) : x ^ z < y ^ z ↔ y < x := ⟨lt_imp_lt_of_le_imp_le fun h ↦ rpow_le_rpow_of_nonpos hx h hz.le, fun h ↦ rpow_lt_rpow_of_neg hy h hz⟩ lemma rpow_le_rpow_iff_of_neg (hx : 0 < x) (hy : 0 < y) (hz : z < 0) : x ^ z ≤ y ^ z ↔ y ≤ x := le_iff_le_iff_lt_iff_lt.2 <| rpow_lt_rpow_iff_of_neg hy hx hz lemma le_rpow_inv_iff_of_pos (hx : 0 ≤ x) (hy : 0 ≤ y) (hz : 0 < z) : x ≤ y ^ z⁻¹ ↔ x ^ z ≤ y := by rw [← rpow_le_rpow_iff hx _ hz, rpow_inv_rpow] <;> positivity lemma rpow_inv_le_iff_of_pos (hx : 0 ≤ x) (hy : 0 ≤ y) (hz : 0 < z) : x ^ z⁻¹ ≤ y ↔ x ≤ y ^ z := by rw [← rpow_le_rpow_iff _ hy hz, rpow_inv_rpow] <;> positivity lemma lt_rpow_inv_iff_of_pos (hx : 0 ≤ x) (hy : 0 ≤ y) (hz : 0 < z) : x < y ^ z⁻¹ ↔ x ^ z < y := lt_iff_lt_of_le_iff_le <| rpow_inv_le_iff_of_pos hy hx hz lemma rpow_inv_lt_iff_of_pos (hx : 0 ≤ x) (hy : 0 ≤ y) (hz : 0 < z) : x ^ z⁻¹ < y ↔ x < y ^ z := lt_iff_lt_of_le_iff_le <| le_rpow_inv_iff_of_pos hy hx hz theorem le_rpow_inv_iff_of_neg (hx : 0 < x) (hy : 0 < y) (hz : z < 0) : x ≤ y ^ z⁻¹ ↔ y ≤ x ^ z := by rw [← rpow_le_rpow_iff_of_neg _ hx hz, rpow_inv_rpow _ hz.ne] <;> positivity theorem lt_rpow_inv_iff_of_neg (hx : 0 < x) (hy : 0 < y) (hz : z < 0) : x < y ^ z⁻¹ ↔ y < x ^ z := by rw [← rpow_lt_rpow_iff_of_neg _ hx hz, rpow_inv_rpow _ hz.ne] <;> positivity theorem rpow_inv_lt_iff_of_neg (hx : 0 < x) (hy : 0 < y) (hz : z < 0) : x ^ z⁻¹ < y ↔ y ^ z < x := by rw [← rpow_lt_rpow_iff_of_neg hy _ hz, rpow_inv_rpow _ hz.ne] <;> positivity theorem rpow_inv_le_iff_of_neg (hx : 0 < x) (hy : 0 < y) (hz : z < 0) : x ^ z⁻¹ ≤ y ↔ y ^ z ≤ x := by rw [← rpow_le_rpow_iff_of_neg hy _ hz, rpow_inv_rpow _ hz.ne] <;> positivity theorem rpow_lt_rpow_of_exponent_lt (hx : 1 < x) (hyz : y < z) : x ^ y < x ^ z := by repeat' rw [rpow_def_of_pos (lt_trans zero_lt_one hx)] rw [exp_lt_exp]; exact mul_lt_mul_of_pos_left hyz (log_pos hx) @[gcongr] theorem rpow_le_rpow_of_exponent_le (hx : 1 ≤ x) (hyz : y ≤ z) : x ^ y ≤ x ^ z := by repeat' rw [rpow_def_of_pos (lt_of_lt_of_le zero_lt_one hx)] rw [exp_le_exp]; exact mul_le_mul_of_nonneg_left hyz (log_nonneg hx) theorem rpow_lt_rpow_of_exponent_neg {x y z : ℝ} (hy : 0 < y) (hxy : y < x) (hz : z < 0) : x ^ z < y ^ z := by have hx : 0 < x := hy.trans hxy rw [← neg_neg z, Real.rpow_neg (le_of_lt hx) (-z), Real.rpow_neg (le_of_lt hy) (-z), inv_lt_inv₀ (rpow_pos_of_pos hx _) (rpow_pos_of_pos hy _)] exact Real.rpow_lt_rpow (by positivity) hxy <| neg_pos_of_neg hz theorem strictAntiOn_rpow_Ioi_of_exponent_neg {r : ℝ} (hr : r < 0) : StrictAntiOn (fun (x : ℝ) => x ^ r) (Set.Ioi 0) := fun _ ha _ _ hab => rpow_lt_rpow_of_exponent_neg ha hab hr theorem rpow_le_rpow_of_exponent_nonpos {x y : ℝ} (hy : 0 < y) (hxy : y ≤ x) (hz : z ≤ 0) : x ^ z ≤ y ^ z := by rcases ne_or_eq z 0 with hz_zero | rfl case inl => rcases ne_or_eq x y with hxy' | rfl case inl => exact le_of_lt <| rpow_lt_rpow_of_exponent_neg hy (Ne.lt_of_le (id (Ne.symm hxy')) hxy) (Ne.lt_of_le hz_zero hz) case inr => simp case inr => simp theorem antitoneOn_rpow_Ioi_of_exponent_nonpos {r : ℝ} (hr : r ≤ 0) : AntitoneOn (fun (x : ℝ) => x ^ r) (Set.Ioi 0) := fun _ ha _ _ hab => rpow_le_rpow_of_exponent_nonpos ha hab hr @[simp] theorem rpow_le_rpow_left_iff (hx : 1 < x) : x ^ y ≤ x ^ z ↔ y ≤ z := by have x_pos : 0 < x := lt_trans zero_lt_one hx rw [← log_le_log_iff (rpow_pos_of_pos x_pos y) (rpow_pos_of_pos x_pos z), log_rpow x_pos, log_rpow x_pos, mul_le_mul_right (log_pos hx)] @[simp] theorem rpow_lt_rpow_left_iff (hx : 1 < x) : x ^ y < x ^ z ↔ y < z := by rw [lt_iff_not_le, rpow_le_rpow_left_iff hx, lt_iff_not_le] theorem rpow_lt_rpow_of_exponent_gt (hx0 : 0 < x) (hx1 : x < 1) (hyz : z < y) : x ^ y < x ^ z := by repeat' rw [rpow_def_of_pos hx0] rw [exp_lt_exp]; exact mul_lt_mul_of_neg_left hyz (log_neg hx0 hx1) theorem rpow_le_rpow_of_exponent_ge (hx0 : 0 < x) (hx1 : x ≤ 1) (hyz : z ≤ y) : x ^ y ≤ x ^ z := by repeat' rw [rpow_def_of_pos hx0] rw [exp_le_exp]; exact mul_le_mul_of_nonpos_left hyz (log_nonpos (le_of_lt hx0) hx1) @[simp] theorem rpow_le_rpow_left_iff_of_base_lt_one (hx0 : 0 < x) (hx1 : x < 1) : x ^ y ≤ x ^ z ↔ z ≤ y := by rw [← log_le_log_iff (rpow_pos_of_pos hx0 y) (rpow_pos_of_pos hx0 z), log_rpow hx0, log_rpow hx0, mul_le_mul_right_of_neg (log_neg hx0 hx1)] @[simp] theorem rpow_lt_rpow_left_iff_of_base_lt_one (hx0 : 0 < x) (hx1 : x < 1) : x ^ y < x ^ z ↔ z < y := by rw [lt_iff_not_le, rpow_le_rpow_left_iff_of_base_lt_one hx0 hx1, lt_iff_not_le] theorem rpow_lt_one {x z : ℝ} (hx1 : 0 ≤ x) (hx2 : x < 1) (hz : 0 < z) : x ^ z < 1 := by rw [← one_rpow z] exact rpow_lt_rpow hx1 hx2 hz theorem rpow_le_one {x z : ℝ} (hx1 : 0 ≤ x) (hx2 : x ≤ 1) (hz : 0 ≤ z) : x ^ z ≤ 1 := by rw [← one_rpow z] exact rpow_le_rpow hx1 hx2 hz theorem rpow_lt_one_of_one_lt_of_neg {x z : ℝ} (hx : 1 < x) (hz : z < 0) : x ^ z < 1 := by convert rpow_lt_rpow_of_exponent_lt hx hz exact (rpow_zero x).symm theorem rpow_le_one_of_one_le_of_nonpos {x z : ℝ} (hx : 1 ≤ x) (hz : z ≤ 0) : x ^ z ≤ 1 := by convert rpow_le_rpow_of_exponent_le hx hz exact (rpow_zero x).symm theorem one_lt_rpow {x z : ℝ} (hx : 1 < x) (hz : 0 < z) : 1 < x ^ z := by rw [← one_rpow z] exact rpow_lt_rpow zero_le_one hx hz theorem one_le_rpow {x z : ℝ} (hx : 1 ≤ x) (hz : 0 ≤ z) : 1 ≤ x ^ z := by rw [← one_rpow z] exact rpow_le_rpow zero_le_one hx hz theorem one_lt_rpow_of_pos_of_lt_one_of_neg (hx1 : 0 < x) (hx2 : x < 1) (hz : z < 0) : 1 < x ^ z := by convert rpow_lt_rpow_of_exponent_gt hx1 hx2 hz exact (rpow_zero x).symm theorem one_le_rpow_of_pos_of_le_one_of_nonpos (hx1 : 0 < x) (hx2 : x ≤ 1) (hz : z ≤ 0) : 1 ≤ x ^ z := by convert rpow_le_rpow_of_exponent_ge hx1 hx2 hz exact (rpow_zero x).symm theorem rpow_lt_one_iff_of_pos (hx : 0 < x) : x ^ y < 1 ↔ 1 < x ∧ y < 0 ∨ x < 1 ∧ 0 < y := by rw [rpow_def_of_pos hx, exp_lt_one_iff, mul_neg_iff, log_pos_iff hx.le, log_neg_iff hx] theorem rpow_lt_one_iff (hx : 0 ≤ x) : x ^ y < 1 ↔ x = 0 ∧ y ≠ 0 ∨ 1 < x ∧ y < 0 ∨ x < 1 ∧ 0 < y := by rcases hx.eq_or_lt with (rfl | hx) · rcases _root_.em (y = 0) with (rfl | hy) <;> simp [*, lt_irrefl, zero_lt_one] · simp [rpow_lt_one_iff_of_pos hx, hx.ne.symm] theorem rpow_lt_one_iff' {x y : ℝ} (hx : 0 ≤ x) (hy : 0 < y) : x ^ y < 1 ↔ x < 1 := by rw [← Real.rpow_lt_rpow_iff hx zero_le_one hy, Real.one_rpow] theorem one_lt_rpow_iff_of_pos (hx : 0 < x) : 1 < x ^ y ↔ 1 < x ∧ 0 < y ∨ x < 1 ∧ y < 0 := by rw [rpow_def_of_pos hx, one_lt_exp_iff, mul_pos_iff, log_pos_iff hx.le, log_neg_iff hx] theorem one_lt_rpow_iff (hx : 0 ≤ x) : 1 < x ^ y ↔ 1 < x ∧ 0 < y ∨ 0 < x ∧ x < 1 ∧ y < 0 := by rcases hx.eq_or_lt with (rfl | hx) · rcases _root_.em (y = 0) with (rfl | hy) <;> simp [*, lt_irrefl, (zero_lt_one' ℝ).not_lt] · simp [one_lt_rpow_iff_of_pos hx, hx] /-- This is a more general but less convenient version of `rpow_le_rpow_of_exponent_ge`. This version allows `x = 0`, so it explicitly forbids `x = y = 0`, `z ≠ 0`. -/ theorem rpow_le_rpow_of_exponent_ge_of_imp (hx0 : 0 ≤ x) (hx1 : x ≤ 1) (hyz : z ≤ y) (h : x = 0 → y = 0 → z = 0) : x ^ y ≤ x ^ z := by rcases eq_or_lt_of_le hx0 with (rfl | hx0') · rcases eq_or_ne y 0 with rfl | hy0 · rw [h rfl rfl] · rw [zero_rpow hy0] apply zero_rpow_nonneg · exact rpow_le_rpow_of_exponent_ge hx0' hx1 hyz /-- This version of `rpow_le_rpow_of_exponent_ge` allows `x = 0` but requires `0 ≤ z`. See also `rpow_le_rpow_of_exponent_ge_of_imp` for the most general version. -/ theorem rpow_le_rpow_of_exponent_ge' (hx0 : 0 ≤ x) (hx1 : x ≤ 1) (hz : 0 ≤ z) (hyz : z ≤ y) : x ^ y ≤ x ^ z := rpow_le_rpow_of_exponent_ge_of_imp hx0 hx1 hyz fun _ hy ↦ le_antisymm (hyz.trans_eq hy) hz lemma rpow_max {x y p : ℝ} (hx : 0 ≤ x) (hy : 0 ≤ y) (hp : 0 ≤ p) : (max x y) ^ p = max (x ^ p) (y ^ p) := by rcases le_total x y with hxy | hxy · rw [max_eq_right hxy, max_eq_right (rpow_le_rpow hx hxy hp)] · rw [max_eq_left hxy, max_eq_left (rpow_le_rpow hy hxy hp)] theorem self_le_rpow_of_le_one (h₁ : 0 ≤ x) (h₂ : x ≤ 1) (h₃ : y ≤ 1) : x ≤ x ^ y := by simpa only [rpow_one] using rpow_le_rpow_of_exponent_ge_of_imp h₁ h₂ h₃ fun _ ↦ (absurd · one_ne_zero) theorem self_le_rpow_of_one_le (h₁ : 1 ≤ x) (h₂ : 1 ≤ y) : x ≤ x ^ y := by simpa only [rpow_one] using rpow_le_rpow_of_exponent_le h₁ h₂ theorem rpow_le_self_of_le_one (h₁ : 0 ≤ x) (h₂ : x ≤ 1) (h₃ : 1 ≤ y) : x ^ y ≤ x := by simpa only [rpow_one] using rpow_le_rpow_of_exponent_ge_of_imp h₁ h₂ h₃ fun _ ↦ (absurd · (one_pos.trans_le h₃).ne') theorem rpow_le_self_of_one_le (h₁ : 1 ≤ x) (h₂ : y ≤ 1) : x ^ y ≤ x := by simpa only [rpow_one] using rpow_le_rpow_of_exponent_le h₁ h₂ theorem self_lt_rpow_of_lt_one (h₁ : 0 < x) (h₂ : x < 1) (h₃ : y < 1) : x < x ^ y := by simpa only [rpow_one] using rpow_lt_rpow_of_exponent_gt h₁ h₂ h₃ theorem self_lt_rpow_of_one_lt (h₁ : 1 < x) (h₂ : 1 < y) : x < x ^ y := by simpa only [rpow_one] using rpow_lt_rpow_of_exponent_lt h₁ h₂ theorem rpow_lt_self_of_lt_one (h₁ : 0 < x) (h₂ : x < 1) (h₃ : 1 < y) : x ^ y < x := by simpa only [rpow_one] using rpow_lt_rpow_of_exponent_gt h₁ h₂ h₃ theorem rpow_lt_self_of_one_lt (h₁ : 1 < x) (h₂ : y < 1) : x ^ y < x := by simpa only [rpow_one] using rpow_lt_rpow_of_exponent_lt h₁ h₂ theorem rpow_left_injOn {x : ℝ} (hx : x ≠ 0) : InjOn (fun y : ℝ => y ^ x) { y : ℝ | 0 ≤ y } := by rintro y hy z hz (hyz : y ^ x = z ^ x) rw [← rpow_one y, ← rpow_one z, ← mul_inv_cancel₀ hx, rpow_mul hy, rpow_mul hz, hyz] lemma rpow_left_inj (hx : 0 ≤ x) (hy : 0 ≤ y) (hz : z ≠ 0) : x ^ z = y ^ z ↔ x = y := (rpow_left_injOn hz).eq_iff hx hy lemma rpow_inv_eq (hx : 0 ≤ x) (hy : 0 ≤ y) (hz : z ≠ 0) : x ^ z⁻¹ = y ↔ x = y ^ z := by rw [← rpow_left_inj _ hy hz, rpow_inv_rpow hx hz]; positivity lemma eq_rpow_inv (hx : 0 ≤ x) (hy : 0 ≤ y) (hz : z ≠ 0) : x = y ^ z⁻¹ ↔ x ^ z = y := by rw [← rpow_left_inj hx _ hz, rpow_inv_rpow hy hz]; positivity theorem le_rpow_iff_log_le (hx : 0 < x) (hy : 0 < y) : x ≤ y ^ z ↔ log x ≤ z * log y := by rw [← log_le_log_iff hx (rpow_pos_of_pos hy z), log_rpow hy] lemma le_pow_iff_log_le (hx : 0 < x) (hy : 0 < y) : x ≤ y ^ n ↔ log x ≤ n * log y := rpow_natCast _ _ ▸ le_rpow_iff_log_le hx hy lemma le_zpow_iff_log_le {n : ℤ} (hx : 0 < x) (hy : 0 < y) : x ≤ y ^ n ↔ log x ≤ n * log y := rpow_intCast _ _ ▸ le_rpow_iff_log_le hx hy lemma le_rpow_of_log_le (hy : 0 < y) (h : log x ≤ z * log y) : x ≤ y ^ z := by obtain hx | hx := le_or_lt x 0 · exact hx.trans (rpow_pos_of_pos hy _).le · exact (le_rpow_iff_log_le hx hy).2 h lemma le_pow_of_log_le (hy : 0 < y) (h : log x ≤ n * log y) : x ≤ y ^ n := rpow_natCast _ _ ▸ le_rpow_of_log_le hy h lemma le_zpow_of_log_le {n : ℤ} (hy : 0 < y) (h : log x ≤ n * log y) : x ≤ y ^ n := rpow_intCast _ _ ▸ le_rpow_of_log_le hy h theorem lt_rpow_iff_log_lt (hx : 0 < x) (hy : 0 < y) : x < y ^ z ↔ log x < z * log y := by rw [← log_lt_log_iff hx (rpow_pos_of_pos hy z), log_rpow hy] lemma lt_pow_iff_log_lt (hx : 0 < x) (hy : 0 < y) : x < y ^ n ↔ log x < n * log y := rpow_natCast _ _ ▸ lt_rpow_iff_log_lt hx hy lemma lt_zpow_iff_log_lt {n : ℤ} (hx : 0 < x) (hy : 0 < y) : x < y ^ n ↔ log x < n * log y := rpow_intCast _ _ ▸ lt_rpow_iff_log_lt hx hy lemma lt_rpow_of_log_lt (hy : 0 < y) (h : log x < z * log y) : x < y ^ z := by obtain hx | hx := le_or_lt x 0 · exact hx.trans_lt (rpow_pos_of_pos hy _) · exact (lt_rpow_iff_log_lt hx hy).2 h lemma lt_pow_of_log_lt (hy : 0 < y) (h : log x < n * log y) : x < y ^ n := rpow_natCast _ _ ▸ lt_rpow_of_log_lt hy h lemma lt_zpow_of_log_lt {n : ℤ} (hy : 0 < y) (h : log x < n * log y) : x < y ^ n := rpow_intCast _ _ ▸ lt_rpow_of_log_lt hy h lemma rpow_le_iff_le_log (hx : 0 < x) (hy : 0 < y) : x ^ z ≤ y ↔ z * log x ≤ log y := by rw [← log_le_log_iff (rpow_pos_of_pos hx _) hy, log_rpow hx] lemma pow_le_iff_le_log (hx : 0 < x) (hy : 0 < y) : x ^ n ≤ y ↔ n * log x ≤ log y := by rw [← rpow_le_iff_le_log hx hy, rpow_natCast] lemma zpow_le_iff_le_log {n : ℤ} (hx : 0 < x) (hy : 0 < y) : x ^ n ≤ y ↔ n * log x ≤ log y := by rw [← rpow_le_iff_le_log hx hy, rpow_intCast] lemma le_log_of_rpow_le (hx : 0 < x) (h : x ^ z ≤ y) : z * log x ≤ log y := log_rpow hx _ ▸ log_le_log (by positivity) h
lemma le_log_of_pow_le (hx : 0 < x) (h : x ^ n ≤ y) : n * log x ≤ log y := le_log_of_rpow_le hx (rpow_natCast _ _ ▸ h) lemma le_log_of_zpow_le {n : ℤ} (hx : 0 < x) (h : x ^ n ≤ y) : n * log x ≤ log y := le_log_of_rpow_le hx (rpow_intCast _ _ ▸ h) lemma rpow_le_of_le_log (hy : 0 < y) (h : log x ≤ z * log y) : x ≤ y ^ z := by
Mathlib/Analysis/SpecialFunctions/Pow/Real.lean
821
827
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Kevin Kappelmann -/ import Mathlib.Algebra.Order.Floor.Defs import Mathlib.Algebra.Order.Floor.Ring import Mathlib.Algebra.Order.Floor.Semiring deprecated_module (since := "2025-04-13")
Mathlib/Algebra/Order/Floor.lean
1,136
1,140
/- Copyright (c) 2022 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import Mathlib.Analysis.Asymptotics.Lemmas import Mathlib.Analysis.Normed.Module.Basic /-! # Asymptotic equivalence up to a constant In this file we define `Asymptotics.IsTheta l f g` (notation: `f =Θ[l] g`) as `f =O[l] g ∧ g =O[l] f`, then prove basic properties of this equivalence relation. -/ open Filter open Topology namespace Asymptotics variable {α : Type*} {β : Type*} {E : Type*} {F : Type*} {G : Type*} {E' : Type*} {F' : Type*} {G' : Type*} {E'' : Type*} {F'' : Type*} {G'' : Type*} {R : Type*} {R' : Type*} {𝕜 : Type*} {𝕜' : Type*} variable [Norm E] [Norm F] [Norm G] variable [SeminormedAddCommGroup E'] [SeminormedAddCommGroup F'] [SeminormedAddCommGroup G'] [NormedAddCommGroup E''] [NormedAddCommGroup F''] [NormedAddCommGroup G''] [SeminormedRing R] [SeminormedRing R'] variable [NormedField 𝕜] [NormedField 𝕜'] variable {c c' c₁ c₂ : ℝ} {f : α → E} {g : α → F} {k : α → G} variable {f' : α → E'} {g' : α → F'} {k' : α → G'} variable {f'' : α → E''} {g'' : α → F''} variable {l l' : Filter α} /-- We say that `f` is `Θ(g)` along a filter `l` (notation: `f =Θ[l] g`) if `f =O[l] g` and `g =O[l] f`. -/ def IsTheta (l : Filter α) (f : α → E) (g : α → F) : Prop := IsBigO l f g ∧ IsBigO l g f @[inherit_doc] notation:100 f " =Θ[" l "] " g:100 => IsTheta l f g theorem IsBigO.antisymm (h₁ : f =O[l] g) (h₂ : g =O[l] f) : f =Θ[l] g := ⟨h₁, h₂⟩ lemma IsTheta.isBigO (h : f =Θ[l] g) : f =O[l] g := h.1 lemma IsTheta.isBigO_symm (h : f =Θ[l] g) : g =O[l] f := h.2 @[refl] theorem isTheta_refl (f : α → E) (l : Filter α) : f =Θ[l] f := ⟨isBigO_refl _ _, isBigO_refl _ _⟩ theorem isTheta_rfl : f =Θ[l] f := isTheta_refl _ _ @[symm] nonrec theorem IsTheta.symm (h : f =Θ[l] g) : g =Θ[l] f := h.symm theorem isTheta_comm : f =Θ[l] g ↔ g =Θ[l] f := ⟨fun h ↦ h.symm, fun h ↦ h.symm⟩ @[trans] theorem IsTheta.trans {f : α → E} {g : α → F'} {k : α → G} (h₁ : f =Θ[l] g) (h₂ : g =Θ[l] k) : f =Θ[l] k := ⟨h₁.1.trans h₂.1, h₂.2.trans h₁.2⟩ instance : Trans (α := α → E) (β := α → F') (γ := α → G) (IsTheta l) (IsTheta l) (IsTheta l) := ⟨IsTheta.trans⟩ @[trans] theorem IsBigO.trans_isTheta {f : α → E} {g : α → F'} {k : α → G} (h₁ : f =O[l] g) (h₂ : g =Θ[l] k) : f =O[l] k := h₁.trans h₂.1 instance : Trans (α := α → E) (β := α → F') (γ := α → G) (IsBigO l) (IsTheta l) (IsBigO l) := ⟨IsBigO.trans_isTheta⟩ @[trans] theorem IsTheta.trans_isBigO {f : α → E} {g : α → F'} {k : α → G} (h₁ : f =Θ[l] g) (h₂ : g =O[l] k) : f =O[l] k := h₁.1.trans h₂ instance : Trans (α := α → E) (β := α → F') (γ := α → G) (IsTheta l) (IsBigO l) (IsBigO l) := ⟨IsTheta.trans_isBigO⟩ @[trans] theorem IsLittleO.trans_isTheta {f : α → E} {g : α → F} {k : α → G'} (h₁ : f =o[l] g) (h₂ : g =Θ[l] k) : f =o[l] k := h₁.trans_isBigO h₂.1 instance : Trans (α := α → E) (β := α → F') (γ := α → G') (IsLittleO l) (IsTheta l) (IsLittleO l) := ⟨IsLittleO.trans_isTheta⟩ @[trans] theorem IsTheta.trans_isLittleO {f : α → E} {g : α → F'} {k : α → G} (h₁ : f =Θ[l] g) (h₂ : g =o[l] k) : f =o[l] k := h₁.1.trans_isLittleO h₂ instance : Trans (α := α → E) (β := α → F') (γ := α → G) (IsTheta l) (IsLittleO l) (IsLittleO l) := ⟨IsTheta.trans_isLittleO⟩ @[trans] theorem IsTheta.trans_eventuallyEq {f : α → E} {g₁ g₂ : α → F} (h : f =Θ[l] g₁) (hg : g₁ =ᶠ[l] g₂) : f =Θ[l] g₂ := ⟨h.1.trans_eventuallyEq hg, hg.symm.trans_isBigO h.2⟩ instance : Trans (α := α → E) (β := α → F) (γ := α → F) (IsTheta l) (EventuallyEq l) (IsTheta l) := ⟨IsTheta.trans_eventuallyEq⟩ @[trans] theorem _root_.Filter.EventuallyEq.trans_isTheta {f₁ f₂ : α → E} {g : α → F} (hf : f₁ =ᶠ[l] f₂) (h : f₂ =Θ[l] g) : f₁ =Θ[l] g := ⟨hf.trans_isBigO h.1, h.2.trans_eventuallyEq hf.symm⟩ instance : Trans (α := α → E) (β := α → E) (γ := α → F) (EventuallyEq l) (IsTheta l) (IsTheta l) := ⟨EventuallyEq.trans_isTheta⟩ lemma _root_.Filter.EventuallyEq.isTheta {f g : α → E} (h : f =ᶠ[l] g) : f =Θ[l] g := h.trans_isTheta isTheta_rfl @[simp] theorem isTheta_bot : f =Θ[⊥] g := by simp [IsTheta] @[simp] theorem isTheta_norm_left : (fun x ↦ ‖f' x‖) =Θ[l] g ↔ f' =Θ[l] g := by simp [IsTheta] @[simp] theorem isTheta_norm_right : (f =Θ[l] fun x ↦ ‖g' x‖) ↔ f =Θ[l] g' := by simp [IsTheta] alias ⟨IsTheta.of_norm_left, IsTheta.norm_left⟩ := isTheta_norm_left alias ⟨IsTheta.of_norm_right, IsTheta.norm_right⟩ := isTheta_norm_right theorem IsTheta.of_norm_eventuallyEq_norm (h : (fun x ↦ ‖f x‖) =ᶠ[l] fun x ↦ ‖g x‖) : f =Θ[l] g := ⟨.of_bound' h.le, .of_bound' h.symm.le⟩ @[deprecated (since := "2025-01-03")] alias isTheta_of_norm_eventuallyEq := IsTheta.of_norm_eventuallyEq_norm theorem IsTheta.of_norm_eventuallyEq {g : α → ℝ} (h : (fun x ↦ ‖f' x‖) =ᶠ[l] g) : f' =Θ[l] g := of_norm_eventuallyEq_norm <| h.mono fun x hx ↦ by simp only [← hx, norm_norm] @[deprecated (since := "2025-01-03")] alias isTheta_of_norm_eventuallyEq' := IsTheta.of_norm_eventuallyEq theorem IsTheta.isLittleO_congr_left (h : f' =Θ[l] g') : f' =o[l] k ↔ g' =o[l] k := ⟨h.symm.trans_isLittleO, h.trans_isLittleO⟩ theorem IsTheta.isLittleO_congr_right (h : g' =Θ[l] k') : f =o[l] g' ↔ f =o[l] k' := ⟨fun H ↦ H.trans_isTheta h, fun H ↦ H.trans_isTheta h.symm⟩ theorem IsTheta.isBigO_congr_left (h : f' =Θ[l] g') : f' =O[l] k ↔ g' =O[l] k := ⟨h.symm.trans_isBigO, h.trans_isBigO⟩ theorem IsTheta.isBigO_congr_right (h : g' =Θ[l] k') : f =O[l] g' ↔ f =O[l] k' := ⟨fun H ↦ H.trans_isTheta h, fun H ↦ H.trans_isTheta h.symm⟩ lemma IsTheta.isTheta_congr_left (h : f' =Θ[l] g') : f' =Θ[l] k ↔ g' =Θ[l] k := h.isBigO_congr_left.and h.isBigO_congr_right
lemma IsTheta.isTheta_congr_right (h : f' =Θ[l] g') : k =Θ[l] f' ↔ k =Θ[l] g' := h.isBigO_congr_right.and h.isBigO_congr_left
Mathlib/Analysis/Asymptotics/Theta.lean
166
168
/- Copyright (c) 2018 Violeta Hernández Palacios, Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Violeta Hernández Palacios, Mario Carneiro -/ import Mathlib.Logic.Small.List import Mathlib.SetTheory.Ordinal.Enum import Mathlib.SetTheory.Ordinal.Exponential /-! # Fixed points of normal functions We prove various statements about the fixed points of normal ordinal functions. We state them in three forms: as statements about type-indexed families of normal functions, as statements about ordinal-indexed families of normal functions, and as statements about a single normal function. For the most part, the first case encompasses the others. Moreover, we prove some lemmas about the fixed points of specific normal functions. ## Main definitions and results * `nfpFamily`, `nfp`: the next fixed point of a (family of) normal function(s). * `not_bddAbove_fp_family`, `not_bddAbove_fp`: the (common) fixed points of a (family of) normal function(s) are unbounded in the ordinals. * `deriv_add_eq_mul_omega0_add`: a characterization of the derivative of addition. * `deriv_mul_eq_opow_omega0_mul`: a characterization of the derivative of multiplication. -/ noncomputable section universe u v open Function Order namespace Ordinal /-! ### Fixed points of type-indexed families of ordinals -/ section variable {ι : Type*} {f : ι → Ordinal.{u} → Ordinal.{u}} /-- The next common fixed point, at least `a`, for a family of normal functions. This is defined for any family of functions, as the supremum of all values reachable by applying finitely many functions in the family to `a`. `Ordinal.nfpFamily_fp` shows this is a fixed point, `Ordinal.le_nfpFamily` shows it's at least `a`, and `Ordinal.nfpFamily_le_fp` shows this is the least ordinal with these properties. -/ def nfpFamily (f : ι → Ordinal.{u} → Ordinal.{u}) (a : Ordinal.{u}) : Ordinal := ⨆ i, List.foldr f a i theorem foldr_le_nfpFamily [Small.{u} ι] (f : ι → Ordinal.{u} → Ordinal.{u}) (a l) : List.foldr f a l ≤ nfpFamily f a := Ordinal.le_iSup _ _ theorem le_nfpFamily [Small.{u} ι] (f : ι → Ordinal.{u} → Ordinal.{u}) (a) : a ≤ nfpFamily f a := foldr_le_nfpFamily f a [] theorem lt_nfpFamily_iff [Small.{u} ι] {a b} : a < nfpFamily f b ↔ ∃ l, a < List.foldr f b l := Ordinal.lt_iSup_iff @[deprecated (since := "2025-02-16")] alias lt_nfpFamily := lt_nfpFamily_iff theorem nfpFamily_le_iff [Small.{u} ι] {a b} : nfpFamily f a ≤ b ↔ ∀ l, List.foldr f a l ≤ b := Ordinal.iSup_le_iff theorem nfpFamily_le {a b} : (∀ l, List.foldr f a l ≤ b) → nfpFamily f a ≤ b := Ordinal.iSup_le theorem nfpFamily_monotone [Small.{u} ι] (hf : ∀ i, Monotone (f i)) : Monotone (nfpFamily f) := fun _ _ h ↦ nfpFamily_le <| fun l ↦ (List.foldr_monotone hf l h).trans (foldr_le_nfpFamily _ _ l) theorem apply_lt_nfpFamily [Small.{u} ι] (H : ∀ i, IsNormal (f i)) {a b} (hb : b < nfpFamily f a) (i) : f i b < nfpFamily f a := let ⟨l, hl⟩ := lt_nfpFamily_iff.1 hb lt_nfpFamily_iff.2 ⟨i::l, (H i).strictMono hl⟩ theorem apply_lt_nfpFamily_iff [Nonempty ι] [Small.{u} ι] (H : ∀ i, IsNormal (f i)) {a b} : (∀ i, f i b < nfpFamily f a) ↔ b < nfpFamily f a := by refine ⟨fun h ↦ ?_, apply_lt_nfpFamily H⟩ let ⟨l, hl⟩ := lt_nfpFamily_iff.1 (h (Classical.arbitrary ι)) exact lt_nfpFamily_iff.2 <| ⟨l, (H _).le_apply.trans_lt hl⟩ theorem nfpFamily_le_apply [Nonempty ι] [Small.{u} ι] (H : ∀ i, IsNormal (f i)) {a b} : (∃ i, nfpFamily f a ≤ f i b) ↔ nfpFamily f a ≤ b := by rw [← not_iff_not] push_neg exact apply_lt_nfpFamily_iff H theorem nfpFamily_le_fp (H : ∀ i, Monotone (f i)) {a b} (ab : a ≤ b) (h : ∀ i, f i b ≤ b) : nfpFamily f a ≤ b := by apply Ordinal.iSup_le intro l induction' l with i l IH generalizing a · exact ab · exact (H i (IH ab)).trans (h i) theorem nfpFamily_fp [Small.{u} ι] {i} (H : IsNormal (f i)) (a) : f i (nfpFamily f a) = nfpFamily f a := by rw [nfpFamily, H.map_iSup] apply le_antisymm <;> refine Ordinal.iSup_le fun l => ?_ · exact Ordinal.le_iSup _ (i::l) · exact H.le_apply.trans (Ordinal.le_iSup _ _) theorem apply_le_nfpFamily [Small.{u} ι] [hι : Nonempty ι] (H : ∀ i, IsNormal (f i)) {a b} : (∀ i, f i b ≤ nfpFamily f a) ↔ b ≤ nfpFamily f a := by refine ⟨fun h => ?_, fun h i => ?_⟩ · obtain ⟨i⟩ := hι exact (H i).le_apply.trans (h i) · rw [← nfpFamily_fp (H i)] exact (H i).monotone h theorem nfpFamily_eq_self [Small.{u} ι] {a} (h : ∀ i, f i a = a) : nfpFamily f a = a := by apply (Ordinal.iSup_le ?_).antisymm (le_nfpFamily f a) intro l rw [List.foldr_fixed' h l] -- Todo: This is actually a special case of the fact the intersection of club sets is a club set. /-- A generalization of the fixed point lemma for normal functions: any family of normal functions has an unbounded set of common fixed points. -/ theorem not_bddAbove_fp_family [Small.{u} ι] (H : ∀ i, IsNormal (f i)) : ¬ BddAbove (⋂ i, Function.fixedPoints (f i)) := by rw [not_bddAbove_iff] refine fun a ↦ ⟨nfpFamily f (succ a), ?_, (lt_succ a).trans_le (le_nfpFamily f _)⟩ rintro _ ⟨i, rfl⟩ exact nfpFamily_fp (H i) _ /-- The derivative of a family of normal functions is the sequence of their common fixed points. This is defined for all functions such that `Ordinal.derivFamily_zero`, `Ordinal.derivFamily_succ`, and `Ordinal.derivFamily_limit` are satisfied. -/ def derivFamily (f : ι → Ordinal.{u} → Ordinal.{u}) (o : Ordinal.{u}) : Ordinal.{u} := limitRecOn o (nfpFamily f 0) (fun _ IH => nfpFamily f (succ IH)) fun a _ g => ⨆ b : Set.Iio a, g _ b.2 @[simp] theorem derivFamily_zero (f : ι → Ordinal → Ordinal) : derivFamily f 0 = nfpFamily f 0 := limitRecOn_zero .. @[simp] theorem derivFamily_succ (f : ι → Ordinal → Ordinal) (o) : derivFamily f (succ o) = nfpFamily f (succ (derivFamily f o)) := limitRecOn_succ .. theorem derivFamily_limit (f : ι → Ordinal → Ordinal) {o} : IsLimit o → derivFamily f o = ⨆ b : Set.Iio o, derivFamily f b := limitRecOn_limit _ _ _ _ theorem isNormal_derivFamily [Small.{u} ι] (f : ι → Ordinal.{u} → Ordinal.{u}) : IsNormal (derivFamily f) := by refine ⟨fun o ↦ ?_, fun o h a ↦ ?_⟩ · rw [derivFamily_succ, ← succ_le_iff] exact le_nfpFamily _ _ · simp_rw [derivFamily_limit _ h, Ordinal.iSup_le_iff, Subtype.forall, Set.mem_Iio] theorem derivFamily_strictMono [Small.{u} ι] (f : ι → Ordinal.{u} → Ordinal.{u}) : StrictMono (derivFamily f) := (isNormal_derivFamily f).strictMono theorem derivFamily_fp [Small.{u} ι] {i} (H : IsNormal (f i)) (o : Ordinal) : f i (derivFamily f o) = derivFamily f o := by induction' o using limitRecOn with o _ o l IH · rw [derivFamily_zero] exact nfpFamily_fp H 0 · rw [derivFamily_succ] exact nfpFamily_fp H _ · have : Nonempty (Set.Iio o) := ⟨0, l.pos⟩ rw [derivFamily_limit _ l, H.map_iSup] refine eq_of_forall_ge_iff fun c => ?_ rw [Ordinal.iSup_le_iff, Ordinal.iSup_le_iff] refine forall_congr' fun a ↦ ?_ rw [IH _ a.2] theorem le_iff_derivFamily [Small.{u} ι] (H : ∀ i, IsNormal (f i)) {a} : (∀ i, f i a ≤ a) ↔ ∃ o, derivFamily f o = a := ⟨fun ha => by suffices ∀ (o), a ≤ derivFamily f o → ∃ o, derivFamily f o = a from this a (isNormal_derivFamily _).le_apply intro o induction' o using limitRecOn with o IH o l IH · intro h₁ refine ⟨0, le_antisymm ?_ h₁⟩ rw [derivFamily_zero] exact nfpFamily_le_fp (fun i => (H i).monotone) (Ordinal.zero_le _) ha · intro h₁ rcases le_or_lt a (derivFamily f o) with h | h · exact IH h refine ⟨succ o, le_antisymm ?_ h₁⟩ rw [derivFamily_succ] exact nfpFamily_le_fp (fun i => (H i).monotone) (succ_le_of_lt h) ha · intro h₁ rcases eq_or_lt_of_le h₁ with h | h · exact ⟨_, h.symm⟩ rw [derivFamily_limit _ l, ← not_le, Ordinal.iSup_le_iff, not_forall] at h obtain ⟨o', h⟩ := h exact IH o' o'.2 (le_of_not_le h), fun ⟨_, e⟩ i => e ▸ (derivFamily_fp (H i) _).le⟩ theorem fp_iff_derivFamily [Small.{u} ι] (H : ∀ i, IsNormal (f i)) {a} : (∀ i, f i a = a) ↔ ∃ o, derivFamily f o = a := Iff.trans ⟨fun h i => le_of_eq (h i), fun h i => (H i).le_iff_eq.1 (h i)⟩ (le_iff_derivFamily H) /-- For a family of normal functions, `Ordinal.derivFamily` enumerates the common fixed points. -/ theorem derivFamily_eq_enumOrd [Small.{u} ι] (H : ∀ i, IsNormal (f i)) : derivFamily f = enumOrd (⋂ i, Function.fixedPoints (f i)) := by rw [eq_comm, eq_enumOrd _ (not_bddAbove_fp_family H)] use (isNormal_derivFamily f).strictMono rw [Set.range_eq_iff] refine ⟨?_, fun a ha => ?_⟩ · rintro a S ⟨i, hi⟩ rw [← hi] exact derivFamily_fp (H i) a rw [Set.mem_iInter] at ha rwa [← fp_iff_derivFamily H] end /-! ### Fixed points of a single function -/ section variable {f : Ordinal.{u} → Ordinal.{u}} /-- The next fixed point function, the least fixed point of the normal function `f`, at least `a`. This is defined as `nfpFamily` applied to a family consisting only of `f`. -/ def nfp (f : Ordinal → Ordinal) : Ordinal → Ordinal := nfpFamily fun _ : Unit => f theorem nfp_eq_nfpFamily (f : Ordinal → Ordinal) : nfp f = nfpFamily fun _ : Unit => f := rfl theorem iSup_iterate_eq_nfp (f : Ordinal.{u} → Ordinal.{u}) (a : Ordinal.{u}) : ⨆ n : ℕ, f^[n] a = nfp f a := by apply le_antisymm · rw [Ordinal.iSup_le_iff] intro n rw [← List.length_replicate (n := n) (a := Unit.unit), ← List.foldr_const f a] exact Ordinal.le_iSup _ _ · apply Ordinal.iSup_le intro l rw [List.foldr_const f a l] exact Ordinal.le_iSup _ _ theorem iterate_le_nfp (f a n) : f^[n] a ≤ nfp f a := by rw [← iSup_iterate_eq_nfp] exact Ordinal.le_iSup (fun n ↦ f^[n] a) n theorem le_nfp (f a) : a ≤ nfp f a := iterate_le_nfp f a 0 theorem lt_nfp_iff {a b} : a < nfp f b ↔ ∃ n, a < f^[n] b := by rw [← iSup_iterate_eq_nfp] exact Ordinal.lt_iSup_iff theorem nfp_le_iff {a b} : nfp f a ≤ b ↔ ∀ n, f^[n] a ≤ b := by rw [← iSup_iterate_eq_nfp] exact Ordinal.iSup_le_iff theorem nfp_le {a b} : (∀ n, f^[n] a ≤ b) → nfp f a ≤ b := nfp_le_iff.2 @[simp] theorem nfp_id : nfp id = id := by ext simp_rw [← iSup_iterate_eq_nfp, iterate_id] exact ciSup_const theorem nfp_monotone (hf : Monotone f) : Monotone (nfp f) := nfpFamily_monotone fun _ => hf theorem IsNormal.apply_lt_nfp (H : IsNormal f) {a b} : f b < nfp f a ↔ b < nfp f a := by unfold nfp rw [← @apply_lt_nfpFamily_iff Unit (fun _ => f) _ _ (fun _ => H) a b] exact ⟨fun h _ => h, fun h => h Unit.unit⟩ theorem IsNormal.nfp_le_apply (H : IsNormal f) {a b} : nfp f a ≤ f b ↔ nfp f a ≤ b := le_iff_le_iff_lt_iff_lt.2 H.apply_lt_nfp theorem nfp_le_fp (H : Monotone f) {a b} (ab : a ≤ b) (h : f b ≤ b) : nfp f a ≤ b := nfpFamily_le_fp (fun _ => H) ab fun _ => h theorem IsNormal.nfp_fp (H : IsNormal f) : ∀ a, f (nfp f a) = nfp f a := @nfpFamily_fp Unit (fun _ => f) _ () H theorem IsNormal.apply_le_nfp (H : IsNormal f) {a b} : f b ≤ nfp f a ↔ b ≤ nfp f a := ⟨H.le_apply.trans, fun h => by simpa only [H.nfp_fp] using H.le_iff.2 h⟩ theorem nfp_eq_self {a} (h : f a = a) : nfp f a = a := nfpFamily_eq_self fun _ => h /-- The fixed point lemma for normal functions: any normal function has an unbounded set of fixed points. -/ theorem not_bddAbove_fp (H : IsNormal f) : ¬ BddAbove (Function.fixedPoints f) := by convert not_bddAbove_fp_family fun _ : Unit => H exact (Set.iInter_const _).symm /-- The derivative of a normal function `f` is the sequence of fixed points of `f`. This is defined as `Ordinal.derivFamily` applied to a trivial family consisting only of `f`. -/ def deriv (f : Ordinal → Ordinal) : Ordinal → Ordinal := derivFamily fun _ : Unit => f theorem deriv_eq_derivFamily (f : Ordinal → Ordinal) : deriv f = derivFamily fun _ : Unit => f := rfl @[simp] theorem deriv_zero_right (f) : deriv f 0 = nfp f 0 := derivFamily_zero _ @[simp] theorem deriv_succ (f o) : deriv f (succ o) = nfp f (succ (deriv f o)) := derivFamily_succ _ _ theorem deriv_limit (f) {o} : IsLimit o → deriv f o = ⨆ a : {a // a < o}, deriv f a := derivFamily_limit _ theorem isNormal_deriv (f) : IsNormal (deriv f) := isNormal_derivFamily _ theorem deriv_strictMono (f) : StrictMono (deriv f) := derivFamily_strictMono _ theorem deriv_id_of_nfp_id (h : nfp f = id) : deriv f = id := ((isNormal_deriv _).eq_iff_zero_and_succ IsNormal.refl).2 (by simp [h]) theorem IsNormal.deriv_fp (H : IsNormal f) : ∀ o, f (deriv f o) = deriv f o := derivFamily_fp (i := ⟨⟩) H theorem IsNormal.le_iff_deriv (H : IsNormal f) {a} : f a ≤ a ↔ ∃ o, deriv f o = a := by unfold deriv rw [← le_iff_derivFamily fun _ : Unit => H] exact ⟨fun h _ => h, fun h => h Unit.unit⟩ theorem IsNormal.fp_iff_deriv (H : IsNormal f) {a} : f a = a ↔ ∃ o, deriv f o = a := by rw [← H.le_iff_eq, H.le_iff_deriv] /-- `Ordinal.deriv` enumerates the fixed points of a normal function. -/ theorem deriv_eq_enumOrd (H : IsNormal f) : deriv f = enumOrd (Function.fixedPoints f) := by convert derivFamily_eq_enumOrd fun _ : Unit => H exact (Set.iInter_const _).symm theorem deriv_eq_id_of_nfp_eq_id (h : nfp f = id) : deriv f = id := (IsNormal.eq_iff_zero_and_succ (isNormal_deriv _) IsNormal.refl).2 <| by simp [h] theorem nfp_zero_left (a) : nfp 0 a = a := by rw [← iSup_iterate_eq_nfp] apply (Ordinal.iSup_le ?_).antisymm (Ordinal.le_iSup _ 0) intro n cases n · rfl · rw [Function.iterate_succ'] simp @[simp] theorem nfp_zero : nfp 0 = id := by ext exact nfp_zero_left _ @[simp] theorem deriv_zero : deriv 0 = id := deriv_eq_id_of_nfp_eq_id nfp_zero theorem deriv_zero_left (a) : deriv 0 a = a := by rw [deriv_zero, id_eq] end /-! ### Fixed points of addition -/ @[simp] theorem nfp_add_zero (a) : nfp (a + ·) 0 = a * ω := by simp_rw [← iSup_iterate_eq_nfp, ← iSup_mul_nat] congr; funext n induction' n with n hn · rw [Nat.cast_zero, mul_zero, iterate_zero_apply] · rw [iterate_succ_apply', Nat.add_comm, Nat.cast_add, Nat.cast_one, mul_one_add, hn] theorem nfp_add_eq_mul_omega0 {a b} (hba : b ≤ a * ω) : nfp (a + ·) b = a * ω := by apply le_antisymm (nfp_le_fp (isNormal_add_right a).monotone hba _) · rw [← nfp_add_zero] exact nfp_monotone (isNormal_add_right a).monotone (Ordinal.zero_le b) · dsimp; rw [← mul_one_add, one_add_omega0] theorem add_eq_right_iff_mul_omega0_le {a b : Ordinal} : a + b = b ↔ a * ω ≤ b := by refine ⟨fun h => ?_, fun h => ?_⟩ · rw [← nfp_add_zero a, ← deriv_zero_right] obtain ⟨c, hc⟩ := (isNormal_add_right a).fp_iff_deriv.1 h rw [← hc] exact (isNormal_deriv _).monotone (Ordinal.zero_le _) · have := Ordinal.add_sub_cancel_of_le h nth_rw 1 [← this] rwa [← add_assoc, ← mul_one_add, one_add_omega0] theorem add_le_right_iff_mul_omega0_le {a b : Ordinal} : a + b ≤ b ↔ a * ω ≤ b := by rw [← add_eq_right_iff_mul_omega0_le] exact (isNormal_add_right a).le_iff_eq theorem deriv_add_eq_mul_omega0_add (a b : Ordinal.{u}) : deriv (a + ·) b = a * ω + b := by revert b rw [← funext_iff, IsNormal.eq_iff_zero_and_succ (isNormal_deriv _) (isNormal_add_right _)] refine ⟨?_, fun a h => ?_⟩ · rw [deriv_zero_right, add_zero] exact nfp_add_zero a · rw [deriv_succ, h, add_succ] exact nfp_eq_self (add_eq_right_iff_mul_omega0_le.2 ((le_add_right _ _).trans (le_succ _))) /-! ### Fixed points of multiplication -/ @[simp] theorem nfp_mul_one {a : Ordinal} (ha : 0 < a) : nfp (a * ·) 1 = a ^ ω := by rw [← iSup_iterate_eq_nfp, ← iSup_pow ha] congr funext n induction' n with n hn · rw [pow_zero, iterate_zero_apply] · rw [iterate_succ_apply', Nat.add_comm, pow_add, pow_one, hn] @[simp] theorem nfp_mul_zero (a : Ordinal) : nfp (a * ·) 0 = 0 := by rw [← Ordinal.le_zero, nfp_le_iff] intro n induction' n with n hn; · rfl dsimp only; rwa [iterate_succ_apply, mul_zero] theorem nfp_mul_eq_opow_omega0 {a b : Ordinal} (hb : 0 < b) (hba : b ≤ a ^ ω) : nfp (a * ·) b = a ^ ω := by rcases eq_zero_or_pos a with ha | ha · rw [ha, zero_opow omega0_ne_zero] at hba ⊢ simp_rw [Ordinal.le_zero.1 hba, zero_mul] exact nfp_zero_left 0 apply le_antisymm · apply nfp_le_fp (isNormal_mul_right ha).monotone hba rw [← opow_one_add, one_add_omega0] rw [← nfp_mul_one ha] exact nfp_monotone (isNormal_mul_right ha).monotone (one_le_iff_pos.2 hb) theorem eq_zero_or_opow_omega0_le_of_mul_eq_right {a b : Ordinal} (hab : a * b = b) : b = 0 ∨ a ^ ω ≤ b := by rcases eq_zero_or_pos a with ha | ha · rw [ha, zero_opow omega0_ne_zero] exact Or.inr (Ordinal.zero_le b) rw [or_iff_not_imp_left] intro hb rw [← nfp_mul_one ha] rw [← Ne, ← one_le_iff_ne_zero] at hb exact nfp_le_fp (isNormal_mul_right ha).monotone hb (le_of_eq hab) theorem mul_eq_right_iff_opow_omega0_dvd {a b : Ordinal} : a * b = b ↔ a ^ ω ∣ b := by rcases eq_zero_or_pos a with ha | ha · rw [ha, zero_mul, zero_opow omega0_ne_zero, zero_dvd_iff] exact eq_comm refine ⟨fun hab => ?_, fun h => ?_⟩ · rw [dvd_iff_mod_eq_zero] rw [← div_add_mod b (a ^ ω), mul_add, ← mul_assoc, ← opow_one_add, one_add_omega0, add_left_cancel_iff] at hab rcases eq_zero_or_opow_omega0_le_of_mul_eq_right hab with hab | hab · exact hab refine (not_lt_of_le hab (mod_lt b (opow_ne_zero ω ?_))).elim rwa [← Ordinal.pos_iff_ne_zero] obtain ⟨c, hc⟩ := h rw [hc, ← mul_assoc, ← opow_one_add, one_add_omega0] theorem mul_le_right_iff_opow_omega0_dvd {a b : Ordinal} (ha : 0 < a) : a * b ≤ b ↔ (a ^ ω) ∣ b := by rw [← mul_eq_right_iff_opow_omega0_dvd] exact (isNormal_mul_right ha).le_iff_eq theorem nfp_mul_opow_omega0_add {a c : Ordinal} (b) (ha : 0 < a) (hc : 0 < c) (hca : c ≤ a ^ ω) : nfp (a * ·) (a ^ ω * b + c) = a ^ ω * succ b := by apply le_antisymm · apply nfp_le_fp (isNormal_mul_right ha).monotone · rw [mul_succ] apply add_le_add_left hca · dsimp only; rw [← mul_assoc, ← opow_one_add, one_add_omega0] · obtain ⟨d, hd⟩ := mul_eq_right_iff_opow_omega0_dvd.1 ((isNormal_mul_right ha).nfp_fp ((a ^ ω) * b + c)) rw [hd] apply mul_le_mul_left' have := le_nfp (a * ·) (a ^ ω * b + c) rw [hd] at this have := (add_lt_add_left hc (a ^ ω * b)).trans_le this rw [add_zero, mul_lt_mul_iff_left (opow_pos ω ha)] at this rwa [succ_le_iff] theorem deriv_mul_eq_opow_omega0_mul {a : Ordinal.{u}} (ha : 0 < a) (b) : deriv (a * ·) b = a ^ ω * b := by revert b rw [← funext_iff, IsNormal.eq_iff_zero_and_succ (isNormal_deriv _) (isNormal_mul_right (opow_pos ω ha))] refine ⟨?_, fun c h => ?_⟩ · dsimp only; rw [deriv_zero_right, nfp_mul_zero, mul_zero] · rw [deriv_succ, h] exact nfp_mul_opow_omega0_add c ha zero_lt_one (one_le_iff_pos.2 (opow_pos _ ha)) end Ordinal
Mathlib/SetTheory/Ordinal/FixedPoint.lean
612
620
/- Copyright (c) 2018 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Mario Carneiro, Simon Hudon -/ import Mathlib.Data.PFunctor.Multivariate.Basic import Mathlib.Data.PFunctor.Univariate.M /-! # The M construction as a multivariate polynomial functor. M types are potentially infinite tree-like structures. They are defined as the greatest fixpoint of a polynomial functor. ## Main definitions * `M.mk` - constructor * `M.dest` - destructor * `M.corec` - corecursor: useful for formulating infinite, productive computations * `M.bisim` - bisimulation: proof technique to show the equality of infinite objects ## Implementation notes Dual view of M-types: * `mp`: polynomial functor * `M`: greatest fixed point of a polynomial functor Specifically, we define the polynomial functor `mp` as: * A := a possibly infinite tree-like structure without information in the nodes * B := given the tree-like structure `t`, `B t` is a valid path from the root of `t` to any given node. As a result `mp α` is made of a dataless tree and a function from its valid paths to values of `α` The difference with the polynomial functor of an initial algebra is that `A` is a possibly infinite tree. ## Reference * Jeremy Avigad, Mario M. Carneiro and Simon Hudon. [*Data Types as Quotients of Polynomial Functors*][avigad-carneiro-hudon2019] -/ universe u open MvFunctor namespace MvPFunctor open TypeVec variable {n : ℕ} (P : MvPFunctor.{u} (n + 1)) /-- A path from the root of a tree to one of its node -/ inductive M.Path : P.last.M → Fin2 n → Type u | root (x : P.last.M) (a : P.A) (f : P.last.B a → P.last.M) (h : PFunctor.M.dest x = ⟨a, f⟩) (i : Fin2 n) (c : P.drop.B a i) : M.Path x i | child (x : P.last.M) (a : P.A) (f : P.last.B a → P.last.M) (h : PFunctor.M.dest x = ⟨a, f⟩) (j : P.last.B a) (i : Fin2 n) (c : M.Path (f j) i) : M.Path x i instance M.Path.inhabited (x : P.last.M) {i} [Inhabited (P.drop.B x.head i)] : Inhabited (M.Path P x i) := let a := PFunctor.M.head x let f := PFunctor.M.children x ⟨M.Path.root _ a f (PFunctor.M.casesOn' x (r := fun _ => PFunctor.M.dest x = ⟨a, f⟩) <| by intros; simp [a, PFunctor.M.dest_mk, PFunctor.M.children_mk]; rfl) _ default⟩ /-- Polynomial functor of the M-type of `P`. `A` is a data-less possibly infinite tree whereas, for a given `a : A`, `B a` is a valid path in tree `a` so that `mp α` is made of a tree and a function from its valid paths to the values it contains -/ def mp : MvPFunctor n where A := P.last.M B := M.Path P /-- `n`-ary M-type for `P` -/ def M (α : TypeVec n) : Type _ := P.mp α instance mvfunctorM : MvFunctor P.M := by delta M; infer_instance instance inhabitedM {α : TypeVec _} [I : Inhabited P.A] [∀ i : Fin2 n, Inhabited (α i)] : Inhabited (P.M α) := @Obj.inhabited _ (mp P) _ (@PFunctor.M.inhabited P.last I) _ /-- construct through corecursion the shape of an M-type without its contents -/ def M.corecShape {β : Type u} (g₀ : β → P.A) (g₂ : ∀ b : β, P.last.B (g₀ b) → β) : β → P.last.M := PFunctor.M.corec fun b => ⟨g₀ b, g₂ b⟩ /-- Proof of type equality as an arrow -/ def castDropB {a a' : P.A} (h : a = a') : P.drop.B a ⟹ P.drop.B a' := fun _i b => Eq.recOn h b /-- Proof of type equality as a function -/ def castLastB {a a' : P.A} (h : a = a') : P.last.B a → P.last.B a' := fun b => Eq.recOn h b /-- Using corecursion, construct the contents of an M-type -/ def M.corecContents {α : TypeVec.{u} n} {β : Type u} (g₀ : β → P.A) (g₁ : ∀ b : β, P.drop.B (g₀ b) ⟹ α) (g₂ : ∀ b : β, P.last.B (g₀ b) → β) (x : _) (b : β) (h : x = M.corecShape P g₀ g₂ b) : M.Path P x ⟹ α | _, M.Path.root x a f h' i c => have : a = g₀ b := by rw [h, M.corecShape, PFunctor.M.dest_corec] at h' cases h' rfl g₁ b i (P.castDropB this i c) | _, M.Path.child x a f h' j i c => have h₀ : a = g₀ b := by rw [h, M.corecShape, PFunctor.M.dest_corec] at h' cases h' rfl have h₁ : f j = M.corecShape P g₀ g₂ (g₂ b (castLastB P h₀ j)) := by rw [h, M.corecShape, PFunctor.M.dest_corec] at h' cases h' rfl M.corecContents g₀ g₁ g₂ (f j) (g₂ b (P.castLastB h₀ j)) h₁ i c /-- Corecursor for M-type of `P` -/ def M.corec' {α : TypeVec n} {β : Type u} (g₀ : β → P.A) (g₁ : ∀ b : β, P.drop.B (g₀ b) ⟹ α) (g₂ : ∀ b : β, P.last.B (g₀ b) → β) : β → P.M α := fun b => ⟨M.corecShape P g₀ g₂ b, M.corecContents P g₀ g₁ g₂ _ _ rfl⟩ /-- Corecursor for M-type of `P` -/ def M.corec {α : TypeVec n} {β : Type u} (g : β → P (α.append1 β)) : β → P.M α := M.corec' P (fun b => (g b).fst) (fun b => dropFun (g b).snd) fun b => lastFun (g b).snd /-- Implementation of destructor for M-type of `P` -/ def M.pathDestLeft {α : TypeVec n} {x : P.last.M} {a : P.A} {f : P.last.B a → P.last.M} (h : PFunctor.M.dest x = ⟨a, f⟩) (f' : M.Path P x ⟹ α) : P.drop.B a ⟹ α := fun i c => f' i (M.Path.root x a f h i c) /-- Implementation of destructor for M-type of `P` -/ def M.pathDestRight {α : TypeVec n} {x : P.last.M} {a : P.A} {f : P.last.B a → P.last.M} (h : PFunctor.M.dest x = ⟨a, f⟩) (f' : M.Path P x ⟹ α) : ∀ j : P.last.B a, M.Path P (f j) ⟹ α := fun j i c => f' i (M.Path.child x a f h j i c) /-- Destructor for M-type of `P` -/ def M.dest' {α : TypeVec n} {x : P.last.M} {a : P.A} {f : P.last.B a → P.last.M} (h : PFunctor.M.dest x = ⟨a, f⟩) (f' : M.Path P x ⟹ α) : P (α.append1 (P.M α)) := ⟨a, splitFun (M.pathDestLeft P h f') fun x => ⟨f x, M.pathDestRight P h f' x⟩⟩ /-- Destructor for M-types -/ def M.dest {α : TypeVec n} (x : P.M α) : P (α ::: P.M α) := M.dest' P (Sigma.eta <| PFunctor.M.dest x.fst).symm x.snd /-- Constructor for M-types -/ def M.mk {α : TypeVec n} : P (α.append1 (P.M α)) → P.M α := M.corec _ fun i => appendFun id (M.dest P) <$$> i theorem M.dest'_eq_dest' {α : TypeVec n} {x : P.last.M} {a₁ : P.A} {f₁ : P.last.B a₁ → P.last.M} (h₁ : PFunctor.M.dest x = ⟨a₁, f₁⟩) {a₂ : P.A} {f₂ : P.last.B a₂ → P.last.M} (h₂ : PFunctor.M.dest x = ⟨a₂, f₂⟩) (f' : M.Path P x ⟹ α) : M.dest' P h₁ f' = M.dest' P h₂ f' := by cases h₁.symm.trans h₂; rfl theorem M.dest_eq_dest' {α : TypeVec n} {x : P.last.M} {a : P.A} {f : P.last.B a → P.last.M} (h : PFunctor.M.dest x = ⟨a, f⟩) (f' : M.Path P x ⟹ α) : M.dest P ⟨x, f'⟩ = M.dest' P h f' := M.dest'_eq_dest' _ _ _ _ theorem M.dest_corec' {α : TypeVec.{u} n} {β : Type u} (g₀ : β → P.A) (g₁ : ∀ b : β, P.drop.B (g₀ b) ⟹ α) (g₂ : ∀ b : β, P.last.B (g₀ b) → β) (x : β) : M.dest P (M.corec' P g₀ g₁ g₂ x) = ⟨g₀ x, splitFun (g₁ x) (M.corec' P g₀ g₁ g₂ ∘ g₂ x)⟩ := rfl theorem M.dest_corec {α : TypeVec n} {β : Type u} (g : β → P (α.append1 β)) (x : β) : M.dest P (M.corec P g x) = appendFun id (M.corec P g) <$$> g x := by trans · apply M.dest_corec' obtain ⟨a, f⟩ := g x; dsimp rw [MvPFunctor.map_eq]; congr conv_rhs => rw [← split_dropFun_lastFun f, appendFun_comp_splitFun] rfl theorem M.bisim_lemma {α : TypeVec n} {a₁ : (mp P).A} {f₁ : (mp P).B a₁ ⟹ α} {a' : P.A} {f' : (P.B a').drop ⟹ α} {f₁' : (P.B a').last → M P α} (e₁ : M.dest P ⟨a₁, f₁⟩ = ⟨a', splitFun f' f₁'⟩) : ∃ (g₁' : _)(e₁' : PFunctor.M.dest a₁ = ⟨a', g₁'⟩), f' = M.pathDestLeft P e₁' f₁ ∧ f₁' = fun x : (last P).B a' => ⟨g₁' x, M.pathDestRight P e₁' f₁ x⟩ := by generalize ef : @splitFun n _ (append1 α (M P α)) f' f₁' = ff at e₁ let he₁' := PFunctor.M.dest a₁ rcases e₁' : he₁' with ⟨a₁', g₁'⟩ rw [M.dest_eq_dest' _ e₁'] at e₁ cases e₁; exact ⟨_, e₁', splitFun_inj ef⟩ theorem M.bisim {α : TypeVec n} (R : P.M α → P.M α → Prop) (h : ∀ x y, R x y → ∃ a f f₁ f₂, M.dest P x = ⟨a, splitFun f f₁⟩ ∧ M.dest P y = ⟨a, splitFun f f₂⟩ ∧ ∀ i, R (f₁ i) (f₂ i)) (x y) (r : R x y) : x = y := by obtain ⟨a₁, f₁⟩ := x obtain ⟨a₂, f₂⟩ := y dsimp [mp] at * have : a₁ = a₂ := by
refine PFunctor.M.bisim (fun a₁ a₂ => ∃ x y, R x y ∧ x.1 = a₁ ∧ y.1 = a₂) ?_ _ _ ⟨⟨a₁, f₁⟩, ⟨a₂, f₂⟩, r, rfl, rfl⟩ rintro _ _ ⟨⟨a₁, f₁⟩, ⟨a₂, f₂⟩, r, rfl, rfl⟩ rcases h _ _ r with ⟨a', f', f₁', f₂', e₁, e₂, h'⟩ rcases M.bisim_lemma P e₁ with ⟨g₁', e₁', rfl, rfl⟩ rcases M.bisim_lemma P e₂ with ⟨g₂', e₂', _, rfl⟩ rw [e₁', e₂'] exact ⟨_, _, _, rfl, rfl, fun b => ⟨_, _, h' b, rfl, rfl⟩⟩ subst this congr with (i p)
Mathlib/Data/PFunctor/Multivariate/M.lean
223
233