blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
7
139
content_id
stringlengths
40
40
detected_licenses
listlengths
0
16
license_type
stringclasses
2 values
repo_name
stringlengths
7
55
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
6 values
visit_date
int64
1,471B
1,694B
revision_date
int64
1,378B
1,694B
committer_date
int64
1,378B
1,694B
github_id
float64
1.33M
604M
star_events_count
int64
0
43.5k
fork_events_count
int64
0
1.5k
gha_license_id
stringclasses
6 values
gha_event_created_at
int64
1,402B
1,695B
gha_created_at
int64
1,359B
1,637B
gha_language
stringclasses
19 values
src_encoding
stringclasses
2 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
1 class
length_bytes
int64
3
6.4M
extension
stringclasses
4 values
content
stringlengths
3
6.12M
fc193e249b1caa30e0f50179193ebbf5182c42d3
618003631150032a5676f229d13a079ac875ff77
/src/category_theory/limits/preserves.lean
e3a63a7016c4d59a56e1fff9ed632de6a24a9183
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
11,866
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Reid Barton, Bhavik Mehta -/ import category_theory.limits.limits /-! # Preservation and reflection of (co)limits. There are various distinct notions of "preserving limits". The one we aim to capture here is: A functor F : C → D "preserves limits" if it sends every limit cone in C to a limit cone in D. Informally, F preserves all the limits which exist in C. Note that: * Of course, we do not want to require F to *strictly* take chosen limit cones of C to chosen limit cones of D. Indeed, the above definition makes no reference to a choice of limit cones so it makes sense without any conditions on C or D. * Some diagrams in C may have no limit. In this case, there is no condition on the behavior of F on such diagrams. There are other notions (such as "flat functor") which impose conditions also on diagrams in C with no limits, but these are not considered here. In order to be able to express the property of preserving limits of a certain form, we say that a functor F preserves the limit of a diagram K if F sends every limit cone on K to a limit cone. This is vacuously satisfied when K does not admit a limit, which is consistent with the above definition of "preserves limits". -/ open category_theory namespace category_theory.limits universes v u₁ u₂ u₃ -- declare the `v`'s first; see `category_theory.category` for an explanation variables {C : Type u₁} [category.{v} C] variables {D : Type u₂} [category.{v} D] variables {J : Type v} [small_category J] {K : J ⥤ C} class preserves_limit (K : J ⥤ C) (F : C ⥤ D) : Type (max u₁ u₂ v) := (preserves : Π {c : cone K}, is_limit c → is_limit (F.map_cone c)) class preserves_colimit (K : J ⥤ C) (F : C ⥤ D) : Type (max u₁ u₂ v) := (preserves : Π {c : cocone K}, is_colimit c → is_colimit (F.map_cocone c)) /-- A functor which preserves limits preserves chosen limits up to isomorphism. -/ def preserves_limit_iso (K : J ⥤ C) [has_limit.{v} K] (F : C ⥤ D) [has_limit.{v} (K ⋙ F)] [preserves_limit K F] : F.obj (limit K) ≅ limit (K ⋙ F) := is_limit.cone_point_unique_up_to_iso (preserves_limit.preserves (limit.is_limit K)) (limit.is_limit (K ⋙ F)) /-- A functor which preserves colimits preserves chosen colimits up to isomorphism. -/ def preserves_colimit_iso (K : J ⥤ C) [has_colimit.{v} K] (F : C ⥤ D) [has_colimit.{v} (K ⋙ F)] [preserves_colimit K F] : F.obj (colimit K) ≅ colimit (K ⋙ F) := is_colimit.cocone_point_unique_up_to_iso (preserves_colimit.preserves (colimit.is_colimit K)) (colimit.is_colimit (K ⋙ F)) class preserves_limits_of_shape (J : Type v) [small_category J] (F : C ⥤ D) : Type (max u₁ u₂ v) := (preserves_limit : Π {K : J ⥤ C}, preserves_limit K F) class preserves_colimits_of_shape (J : Type v) [small_category J] (F : C ⥤ D) : Type (max u₁ u₂ v) := (preserves_colimit : Π {K : J ⥤ C}, preserves_colimit K F) class preserves_limits (F : C ⥤ D) : Type (max u₁ u₂ (v+1)) := (preserves_limits_of_shape : Π {J : Type v} [𝒥 : small_category J], by exactI preserves_limits_of_shape J F) class preserves_colimits (F : C ⥤ D) : Type (max u₁ u₂ (v+1)) := (preserves_colimits_of_shape : Π {J : Type v} [𝒥 : small_category J], by exactI preserves_colimits_of_shape J F) attribute [instance, priority 100] -- see Note [lower instance priority] preserves_limits_of_shape.preserves_limit preserves_limits.preserves_limits_of_shape preserves_colimits_of_shape.preserves_colimit preserves_colimits.preserves_colimits_of_shape instance preserves_limit_subsingleton (K : J ⥤ C) (F : C ⥤ D) : subsingleton (preserves_limit K F) := by split; rintros ⟨a⟩ ⟨b⟩; congr instance preserves_colimit_subsingleton (K : J ⥤ C) (F : C ⥤ D) : subsingleton (preserves_colimit K F) := by split; rintros ⟨a⟩ ⟨b⟩; congr instance preserves_limits_of_shape_subsingleton (J : Type v) [small_category J] (F : C ⥤ D) : subsingleton (preserves_limits_of_shape J F) := by { split, intros, cases a, cases b, congr } instance preserves_colimits_of_shape_subsingleton (J : Type v) [small_category J] (F : C ⥤ D) : subsingleton (preserves_colimits_of_shape J F) := by { split, intros, cases a, cases b, congr } instance preserves_limits_subsingleton (F : C ⥤ D) : subsingleton (preserves_limits F) := by { split, intros, cases a, cases b, cc } instance preserves_colimits_subsingleton (F : C ⥤ D) : subsingleton (preserves_colimits F) := by { split, intros, cases a, cases b, cc } instance id_preserves_limits : preserves_limits (𝟭 C) := { preserves_limits_of_shape := λ J 𝒥, { preserves_limit := λ K, by exactI ⟨λ c h, ⟨λ s, h.lift ⟨s.X, λ j, s.π.app j, λ j j' f, s.π.naturality f⟩, by cases K; rcases c with ⟨_, _, _⟩; intros s j; cases s; exact h.fac _ j, by cases K; rcases c with ⟨_, _, _⟩; intros s m w; rcases s with ⟨_, _, _⟩; exact h.uniq _ m w⟩⟩ } } instance id_preserves_colimits : preserves_colimits (𝟭 C) := { preserves_colimits_of_shape := λ J 𝒥, { preserves_colimit := λ K, by exactI ⟨λ c h, ⟨λ s, h.desc ⟨s.X, λ j, s.ι.app j, λ j j' f, s.ι.naturality f⟩, by cases K; rcases c with ⟨_, _, _⟩; intros s j; cases s; exact h.fac _ j, by cases K; rcases c with ⟨_, _, _⟩; intros s m w; rcases s with ⟨_, _, _⟩; exact h.uniq _ m w⟩⟩ } } section variables {E : Type u₃} [ℰ : category.{v} E] variables (F : C ⥤ D) (G : D ⥤ E) local attribute [elab_simple] preserves_limit.preserves preserves_colimit.preserves instance comp_preserves_limit [preserves_limit K F] [preserves_limit (K ⋙ F) G] : preserves_limit K (F ⋙ G) := ⟨λ c h, preserves_limit.preserves (preserves_limit.preserves h)⟩ instance comp_preserves_colimit [preserves_colimit K F] [preserves_colimit (K ⋙ F) G] : preserves_colimit K (F ⋙ G) := ⟨λ c h, preserves_colimit.preserves (preserves_colimit.preserves h)⟩ end /-- If F preserves one limit cone for the diagram K, then it preserves any limit cone for K. -/ def preserves_limit_of_preserves_limit_cone {F : C ⥤ D} {t : cone K} (h : is_limit t) (hF : is_limit (F.map_cone t)) : preserves_limit K F := ⟨λ t' h', is_limit.of_iso_limit hF (functor.map_iso _ (is_limit.unique_up_to_iso h h'))⟩ /-- Transfer preservation of limits along a natural isomorphism in the shape. -/ def preserves_limit_of_iso {K₁ K₂ : J ⥤ C} (F : C ⥤ D) (h : K₁ ≅ K₂) [preserves_limit K₁ F] : preserves_limit K₂ F := { preserves := λ c t, begin have t' := is_limit.of_cone_equiv (cones.postcompose_equivalence h) t, let hF := iso_whisker_right h F, have := is_limit.of_cone_equiv (cones.postcompose_equivalence hF).symm (preserves_limit.preserves t'), apply is_limit.of_iso_limit this, refine cones.ext (iso.refl _) (λ j, _), dsimp, rw [← F.map_comp], simp, end } /-- If F preserves one colimit cocone for the diagram K, then it preserves any colimit cocone for K. -/ def preserves_colimit_of_preserves_colimit_cocone {F : C ⥤ D} {t : cocone K} (h : is_colimit t) (hF : is_colimit (F.map_cocone t)) : preserves_colimit K F := ⟨λ t' h', is_colimit.of_iso_colimit hF (functor.map_iso _ (is_colimit.unique_up_to_iso h h'))⟩ /- A functor F : C → D reflects limits if whenever the image of a cone under F is a limit cone in D, the cone was already a limit cone in C. Note that again we do not assume a priori that D actually has any limits. -/ class reflects_limit (K : J ⥤ C) (F : C ⥤ D) : Type (max u₁ u₂ v) := (reflects : Π {c : cone K}, is_limit (F.map_cone c) → is_limit c) class reflects_colimit (K : J ⥤ C) (F : C ⥤ D) : Type (max u₁ u₂ v) := (reflects : Π {c : cocone K}, is_colimit (F.map_cocone c) → is_colimit c) class reflects_limits_of_shape (J : Type v) [small_category J] (F : C ⥤ D) : Type (max u₁ u₂ v) := (reflects_limit : Π {K : J ⥤ C}, reflects_limit K F) class reflects_colimits_of_shape (J : Type v) [small_category J] (F : C ⥤ D) : Type (max u₁ u₂ v) := (reflects_colimit : Π {K : J ⥤ C}, reflects_colimit K F) class reflects_limits (F : C ⥤ D) : Type (max u₁ u₂ (v+1)) := (reflects_limits_of_shape : Π {J : Type v} {𝒥 : small_category J}, by exactI reflects_limits_of_shape J F) class reflects_colimits (F : C ⥤ D) : Type (max u₁ u₂ (v+1)) := (reflects_colimits_of_shape : Π {J : Type v} {𝒥 : small_category J}, by exactI reflects_colimits_of_shape J F) instance reflects_limit_subsingleton (K : J ⥤ C) (F : C ⥤ D) : subsingleton (reflects_limit K F) := by split; rintros ⟨a⟩ ⟨b⟩; congr instance reflects_colimit_subsingleton (K : J ⥤ C) (F : C ⥤ D) : subsingleton (reflects_colimit K F) := by split; rintros ⟨a⟩ ⟨b⟩; congr instance reflects_limits_of_shape_subsingleton (J : Type v) [small_category J] (F : C ⥤ D) : subsingleton (reflects_limits_of_shape J F) := by { split, intros, cases a, cases b, congr } instance reflects_colimits_of_shape_subsingleton (J : Type v) [small_category J] (F : C ⥤ D) : subsingleton (reflects_colimits_of_shape J F) := by { split, intros, cases a, cases b, congr } instance reflects_limits_subsingleton (F : C ⥤ D) : subsingleton (reflects_limits F) := by { split, intros, cases a, cases b, cc } instance reflects_colimits_subsingleton (F : C ⥤ D) : subsingleton (reflects_colimits F) := by { split, intros, cases a, cases b, cc } @[priority 100] -- see Note [lower instance priority] instance reflects_limit_of_reflects_limits_of_shape (K : J ⥤ C) (F : C ⥤ D) [H : reflects_limits_of_shape J F] : reflects_limit K F := reflects_limits_of_shape.reflects_limit @[priority 100] -- see Note [lower instance priority] instance reflects_colimit_of_reflects_colimits_of_shape (K : J ⥤ C) (F : C ⥤ D) [H : reflects_colimits_of_shape J F] : reflects_colimit K F := reflects_colimits_of_shape.reflects_colimit @[priority 100] -- see Note [lower instance priority] instance reflects_limits_of_shape_of_reflects_limits (F : C ⥤ D) [H : reflects_limits F] : reflects_limits_of_shape J F := reflects_limits.reflects_limits_of_shape @[priority 100] -- see Note [lower instance priority] instance reflects_colimits_of_shape_of_reflects_colimits (F : C ⥤ D) [H : reflects_colimits F] : reflects_colimits_of_shape J F := reflects_colimits.reflects_colimits_of_shape instance id_reflects_limits : reflects_limits (𝟭 C) := { reflects_limits_of_shape := λ J 𝒥, { reflects_limit := λ K, by exactI ⟨λ c h, ⟨λ s, h.lift ⟨s.X, λ j, s.π.app j, λ j j' f, s.π.naturality f⟩, by cases K; rcases c with ⟨_, _, _⟩; intros s j; cases s; exact h.fac _ j, by cases K; rcases c with ⟨_, _, _⟩; intros s m w; rcases s with ⟨_, _, _⟩; exact h.uniq _ m w⟩⟩ } } instance id_reflects_colimits : reflects_colimits (𝟭 C) := { reflects_colimits_of_shape := λ J 𝒥, { reflects_colimit := λ K, by exactI ⟨λ c h, ⟨λ s, h.desc ⟨s.X, λ j, s.ι.app j, λ j j' f, s.ι.naturality f⟩, by cases K; rcases c with ⟨_, _, _⟩; intros s j; cases s; exact h.fac _ j, by cases K; rcases c with ⟨_, _, _⟩; intros s m w; rcases s with ⟨_, _, _⟩; exact h.uniq _ m w⟩⟩ } } section variables {E : Type u₃} [ℰ : category.{v} E] variables (F : C ⥤ D) (G : D ⥤ E) instance comp_reflects_limit [reflects_limit K F] [reflects_limit (K ⋙ F) G] : reflects_limit K (F ⋙ G) := ⟨λ c h, reflects_limit.reflects (reflects_limit.reflects h)⟩ instance comp_reflects_colimit [reflects_colimit K F] [reflects_colimit (K ⋙ F) G] : reflects_colimit K (F ⋙ G) := ⟨λ c h, reflects_colimit.reflects (reflects_colimit.reflects h)⟩ end end category_theory.limits
a216b691520c69bd535a845d1c5bb57986507836
46125763b4dbf50619e8846a1371029346f4c3db
/src/topology/metric_space/lipschitz.lean
1c5e5eb4613af3407adb94052cb06e2d43abf145
[ "Apache-2.0" ]
permissive
thjread/mathlib
a9d97612cedc2c3101060737233df15abcdb9eb1
7cffe2520a5518bba19227a107078d83fa725ddc
refs/heads/master
1,615,637,696,376
1,583,953,063,000
1,583,953,063,000
246,680,271
0
0
Apache-2.0
1,583,960,875,000
1,583,960,875,000
null
UTF-8
Lean
false
false
11,354
lean
/- Copyright (c) 2018 Rohan Mitta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rohan Mitta, Kevin Buzzard, Alistair Tucker, Johannes Hölzl, Yury Kudryashov -/ import topology.metric_space.basic import category_theory.endomorphism category_theory.types /-! # Lipschitz continuous functions A map `f : α → β` between two (extended) metric spaces is called *Lipschitz continuous* with constant `K ≥ 0` if for all `x, y` we have `edist (f x) (f y) ≤ K * edist x y`. For a metric space, the latter inequality is equivalent to `dist (f x) (f y) ≤ K * dist x y`. In this file we provide various ways to prove that various combinations of Lipschitz continuous functions are Lipschitz continuous. We also prove that Lipschitz continuous functions are uniformly continuous. ## Implementation notes The parameter `K` has type `nnreal`. This way we avoid conjuction in the definition and have coercions both to `ℝ` and `ennreal`. Constructors whose names end with `'` take `K : ℝ` as an argument, and return `lipschitz_with (nnreal.of_real K) f`. -/ universes u v w x open filter open_locale topological_space nnreal variables {α : Type u} {β : Type v} {γ : Type w} {ι : Type x} /-- A function `f` is Lipschitz continuous with constant `K ≥ 0` if for all `x, y` we have `dist (f x) (f y) ≤ K * dist x y` -/ def lipschitz_with [emetric_space α] [emetric_space β] (K : ℝ≥0) (f : α → β) := ∀x y, edist (f x) (f y) ≤ K * edist x y lemma lipschitz_with_iff_dist_le_mul [metric_space α] [metric_space β] {K : ℝ≥0} {f : α → β} : lipschitz_with K f ↔ ∀ x y, dist (f x) (f y) ≤ K * dist x y := by { simp only [lipschitz_with, edist_nndist, dist_nndist], norm_cast } alias lipschitz_with_iff_dist_le_mul ↔ lipschitz_with.dist_le_mul lipschitz_with.of_dist_le_mul namespace lipschitz_with section emetric variables [emetric_space α] [emetric_space β] [emetric_space γ] {K : ℝ≥0} {f : α → β} lemma edist_le_mul (h : lipschitz_with K f) (x y : α) : edist (f x) (f y) ≤ K * edist x y := h x y lemma mul_edist_le (h : lipschitz_with K f) (x y : α) : (K⁻¹ : ennreal) * edist (f x) (f y) ≤ edist x y := begin have := h x y, rw [mul_comm] at this, replace := ennreal.div_le_of_le_mul this, rwa [ennreal.div_def, mul_comm] at this end protected lemma of_edist_le (h : ∀ x y, edist (f x) (f y) ≤ edist x y) : lipschitz_with 1 f := λ x y, by simp only [ennreal.coe_one, one_mul, h] protected lemma weaken (hf : lipschitz_with K f) {K' : ℝ≥0} (h : K ≤ K') : lipschitz_with K' f := assume x y, le_trans (hf x y) $ ennreal.mul_right_mono (ennreal.coe_le_coe.2 h) lemma ediam_image_le (hf : lipschitz_with K f) (s : set α) : emetric.diam (f '' s) ≤ K * emetric.diam s := begin apply emetric.diam_le_of_forall_edist_le, rintros _ ⟨x, hx, rfl⟩ _ ⟨y, hy, rfl⟩, calc edist (f x) (f y) ≤ ↑K * edist x y : hf.edist_le_mul x y ... ≤ ↑K * emetric.diam s : ennreal.mul_left_mono (emetric.edist_le_diam_of_mem hx hy) end /-- A Lipschitz function is uniformly continuous -/ protected lemma uniform_continuous (hf : lipschitz_with K f) : uniform_continuous f := begin refine emetric.uniform_continuous_iff.2 (λε εpos, _), use [ε/K, canonically_ordered_semiring.mul_pos.2 ⟨εpos, ennreal.inv_pos.2 $ ennreal.coe_ne_top⟩], assume x y Dxy, apply lt_of_le_of_lt (hf.edist_le_mul x y), rw [mul_comm], exact ennreal.mul_lt_of_lt_div Dxy end /-- A Lipschitz function is continuous -/ protected lemma continuous (hf : lipschitz_with K f) : continuous f := hf.uniform_continuous.continuous protected lemma const (b : β) : lipschitz_with 0 (λa:α, b) := assume x y, by simp only [edist_self, zero_le] protected lemma id : lipschitz_with 1 (@id α) := lipschitz_with.of_edist_le $ assume x y, le_refl _ protected lemma subtype_val (s : set α) : lipschitz_with 1 (subtype.val : s → α) := lipschitz_with.of_edist_le $ assume x y, le_refl _ protected lemma subtype_coe (s : set α) : lipschitz_with 1 (coe : s → α) := lipschitz_with.subtype_val s protected lemma comp {Kf Kg : ℝ≥0} {f : β → γ} {g : α → β} (hf : lipschitz_with Kf f) (hg : lipschitz_with Kg g) : lipschitz_with (Kf * Kg) (f ∘ g) := assume x y, calc edist (f (g x)) (f (g y)) ≤ Kf * edist (g x) (g y) : hf _ _ ... ≤ Kf * (Kg * edist x y) : ennreal.mul_left_mono (hg _ _) ... = (Kf * Kg : ℝ≥0) * edist x y : by rw [← mul_assoc, ennreal.coe_mul] protected lemma prod_fst : lipschitz_with 1 (@prod.fst α β) := lipschitz_with.of_edist_le $ assume x y, le_max_left _ _ protected lemma prod_snd : lipschitz_with 1 (@prod.snd α β) := lipschitz_with.of_edist_le $ assume x y, le_max_right _ _ protected lemma prod {f : α → β} {Kf : ℝ≥0} (hf : lipschitz_with Kf f) {g : α → γ} {Kg : ℝ≥0} (hg : lipschitz_with Kg g) : lipschitz_with (max Kf Kg) (λ x, (f x, g x)) := begin assume x y, rw [ennreal.coe_mono.map_max, prod.edist_eq, ennreal.max_mul], exact max_le_max (hf x y) (hg x y) end protected lemma uncurry' {f : α → β → γ} {Kα Kβ : ℝ≥0} (hα : ∀ b, lipschitz_with Kα (λ a, f a b)) (hβ : ∀ a, lipschitz_with Kβ (f a)) : lipschitz_with (Kα + Kβ) (function.uncurry' f) := begin rintros ⟨a₁, b₁⟩ ⟨a₂, b₂⟩, simp only [function.uncurry', ennreal.coe_add, add_mul], apply le_trans (edist_triangle _ (f a₂ b₁) _), exact add_le_add' (le_trans (hα _ _ _) $ ennreal.mul_left_mono $ le_max_left _ _) (le_trans (hβ _ _ _) $ ennreal.mul_left_mono $ le_max_right _ _) end protected lemma uncurry {f : α → β → γ} {Kα Kβ : ℝ≥0} (hα : ∀ b, lipschitz_with Kα (λ a, f a b)) (hβ : ∀ a, lipschitz_with Kβ (f a)) : lipschitz_with (Kα + Kβ) (function.uncurry f) := by { rw function.uncurry_def, apply lipschitz_with.uncurry'; assumption } protected lemma iterate {f : α → α} (hf : lipschitz_with K f) : ∀n, lipschitz_with (K ^ n) (f^[n]) | 0 := lipschitz_with.id | (n + 1) := by rw [pow_succ']; exact (iterate n).comp hf lemma edist_iterate_succ_le_geometric {f : α → α} (hf : lipschitz_with K f) (x n) : edist (f^[n] x) (f^[n + 1] x) ≤ edist x (f x) * K ^ n := begin rw [nat.iterate_succ, mul_comm], simpa only [ennreal.coe_pow] using (hf.iterate n) x (f x) end open category_theory protected lemma mul {f g : End α} {Kf Kg} (hf : lipschitz_with Kf f) (hg : lipschitz_with Kg g) : lipschitz_with (Kf * Kg) (f * g : End α) := hf.comp hg /-- The product of a list of Lipschitz continuous endomorphisms is a Lipschitz continuous endomorphism. -/ protected lemma list_prod (f : ι → End α) (K : ι → ℝ≥0) (h : ∀ i, lipschitz_with (K i) (f i)) : ∀ l : list ι, lipschitz_with (l.map K).prod (l.map f).prod | [] := by simp [lipschitz_with.id] | (i :: l) := by { simp only [list.map_cons, list.prod_cons], exact (h i).mul (list_prod l) } protected lemma pow {f : End α} {K} (h : lipschitz_with K f) : ∀ n : ℕ, lipschitz_with (K^n) (f^n : End α) | 0 := lipschitz_with.id | (n + 1) := h.mul (pow n) end emetric section metric variables [metric_space α] [metric_space β] [metric_space γ] {K : ℝ≥0} protected lemma of_dist_le' {f : α → β} {K : ℝ} (h : ∀ x y, dist (f x) (f y) ≤ K * dist x y) : lipschitz_with (nnreal.of_real K) f := of_dist_le_mul $ λ x y, le_trans (h x y) $ mul_le_mul_of_nonneg_right (nnreal.le_coe_of_real K) dist_nonneg protected lemma mk_one {f : α → β} (h : ∀ x y, dist (f x) (f y) ≤ dist x y) : lipschitz_with 1 f := of_dist_le_mul $ by simpa only [nnreal.coe_one, one_mul] using h /-- For functions to `ℝ`, it suffices to prove `f x ≤ f y + K * dist x y`; this version doesn't assume `0≤K`. -/ protected lemma of_le_add_mul' {f : α → ℝ} (K : ℝ) (h : ∀x y, f x ≤ f y + K * dist x y) : lipschitz_with (nnreal.of_real K) f := have I : ∀ x y, f x - f y ≤ K * dist x y, from assume x y, sub_le_iff_le_add'.2 (h x y), lipschitz_with.of_dist_le' $ assume x y, abs_sub_le_iff.2 ⟨I x y, dist_comm y x ▸ I y x⟩ /-- For functions to `ℝ`, it suffices to prove `f x ≤ f y + K * dist x y`; this version assumes `0≤K`. -/ protected lemma of_le_add_mul {f : α → ℝ} (K : ℝ≥0) (h : ∀x y, f x ≤ f y + K * dist x y) : lipschitz_with K f := by simpa only [nnreal.of_real_coe] using lipschitz_with.of_le_add_mul' K h protected lemma of_le_add {f : α → ℝ} (h : ∀ x y, f x ≤ f y + dist x y) : lipschitz_with 1 f := lipschitz_with.of_le_add_mul 1 $ by simpa only [nnreal.coe_one, one_mul] protected lemma le_add_mul {f : α → ℝ} {K : ℝ≥0} (h : lipschitz_with K f) (x y) : f x ≤ f y + K * dist x y := sub_le_iff_le_add'.1 $ le_trans (le_abs_self _) $ h.dist_le_mul x y protected lemma iff_le_add_mul {f : α → ℝ} {K : ℝ≥0} : lipschitz_with K f ↔ ∀ x y, f x ≤ f y + K * dist x y := ⟨lipschitz_with.le_add_mul, lipschitz_with.of_le_add_mul K⟩ lemma nndist_le {f : α → β} (hf : lipschitz_with K f) (x y : α) : nndist (f x) (f y) ≤ K * nndist x y := hf.dist_le_mul x y lemma diam_image_le {f : α → β} (hf : lipschitz_with K f) (s : set α) (hs : metric.bounded s) : metric.diam (f '' s) ≤ K * metric.diam s := begin apply metric.diam_le_of_forall_dist_le (mul_nonneg K.coe_nonneg metric.diam_nonneg), rintros _ ⟨x, hx, rfl⟩ _ ⟨y, hy, rfl⟩, calc dist (f x) (f y) ≤ ↑K * dist x y : hf.dist_le_mul x y ... ≤ ↑K * metric.diam s : mul_le_mul_of_nonneg_left (metric.dist_le_diam_of_mem hs hx hy) K.2 end protected lemma dist_left (y : α) : lipschitz_with 1 (λ x, dist x y) := lipschitz_with.of_le_add $ assume x z, by { rw [add_comm], apply dist_triangle } protected lemma dist_right (x : α) : lipschitz_with 1 (dist x) := lipschitz_with.of_le_add $ assume y z, dist_triangle_right _ _ _ protected lemma dist : lipschitz_with 2 (function.uncurry' $ @dist α _) := lipschitz_with.uncurry' lipschitz_with.dist_left lipschitz_with.dist_right lemma dist_iterate_succ_le_geometric {f : α → α} (hf : lipschitz_with K f) (x n) : dist (f^[n] x) (f^[n + 1] x) ≤ dist x (f x) * K ^ n := begin rw [nat.iterate_succ, mul_comm], simpa only [nnreal.coe_pow] using (hf.iterate n).dist_le_mul x (f x) end end metric end lipschitz_with open metric /-- If a function is locally Lipschitz around a point, then it is continuous at this point. -/ lemma continuous_at_of_locally_lipschitz [metric_space α] [metric_space β] {f : α → β} {x : α} {r : ℝ} (hr : 0 < r) (K : ℝ) (h : ∀y, dist y x < r → dist (f y) (f x) ≤ K * dist y x) : continuous_at f x := begin refine (nhds_basis_ball.tendsto_iff nhds_basis_closed_ball).2 (λε εpos, ⟨min r (ε / max K 1), _, λ y hy, _⟩), { simp [hr, div_pos εpos, zero_lt_one] }, have A : max K 1 ≠ 0 := ne_of_gt (lt_max_iff.2 (or.inr zero_lt_one)), calc dist (f y) (f x) ≤ K * dist y x : h y (lt_of_lt_of_le hy (min_le_left _ _)) ... ≤ max K 1 * dist y x : mul_le_mul_of_nonneg_right (le_max_left K 1) dist_nonneg ... ≤ max K 1 * (ε / max K 1) : mul_le_mul_of_nonneg_left (le_of_lt (lt_of_lt_of_le hy (min_le_right _ _))) (le_trans zero_le_one (le_max_right K 1)) ... = ε : mul_div_cancel' _ A end
7e29c757effef862851d5dcc7ee2838a3370e17e
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/1797.lean
d2b6b269ab27ccfc39326dd59caecff640c74c72
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
142
lean
example (n : nat) : true := begin cases h : n with m, { guard_hyp h : n = nat.zero, admit }, { guard_hyp h : n = nat.succ m, admit} end
43f01030677252bd6f796930463b50e724dcf00a
95dcf8dea2baf2b4b0a60d438f27c35ae3dd3990
/src/analysis/normed_space/basic.lean
cbe2bfda3d4199c7e177cacdf19b8f5df653d312
[ "Apache-2.0" ]
permissive
uniformity1/mathlib
829341bad9dfa6d6be9adaacb8086a8a492e85a4
dd0e9bd8f2e5ec267f68e72336f6973311909105
refs/heads/master
1,588,592,015,670
1,554,219,842,000
1,554,219,842,000
179,110,702
0
0
Apache-2.0
1,554,220,076,000
1,554,220,076,000
null
UTF-8
Lean
false
false
21,058
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Normed spaces. Authors: Patrick Massot, Johannes Hölzl -/ import algebra.pi_instances import linear_algebra.basic import topology.instances.nnreal topology.instances.complex variables {α : Type*} {β : Type*} {γ : Type*} {ι : Type*} noncomputable theory open filter metric local notation f `→_{`:50 a `}`:0 b := tendsto f (nhds a) (nhds b) class has_norm (α : Type*) := (norm : α → ℝ) export has_norm (norm) notation `∥`:1024 e:1 `∥`:1 := norm e class normed_group (α : Type*) extends has_norm α, add_comm_group α, metric_space α := (dist_eq : ∀ x y, dist x y = norm (x - y)) /-- Construct a normed group from a translation invariant distance -/ def normed_group.of_add_dist [has_norm α] [add_comm_group α] [metric_space α] (H1 : ∀ x:α, ∥x∥ = dist x 0) (H2 : ∀ x y z : α, dist x y ≤ dist (x + z) (y + z)) : normed_group α := { dist_eq := λ x y, begin rw H1, apply le_antisymm, { rw [sub_eq_add_neg, ← add_right_neg y], apply H2 }, { have := H2 (x-y) 0 y, rwa [sub_add_cancel, zero_add] at this } end } /-- Construct a normed group from a translation invariant distance -/ def normed_group.of_add_dist' [has_norm α] [add_comm_group α] [metric_space α] (H1 : ∀ x:α, ∥x∥ = dist x 0) (H2 : ∀ x y z : α, dist (x + z) (y + z) ≤ dist x y) : normed_group α := { dist_eq := λ x y, begin rw H1, apply le_antisymm, { have := H2 (x-y) 0 y, rwa [sub_add_cancel, zero_add] at this }, { rw [sub_eq_add_neg, ← add_right_neg y], apply H2 } end } section normed_group variables [normed_group α] [normed_group β] lemma dist_eq_norm (g h : α) : dist g h = ∥g - h∥ := normed_group.dist_eq _ _ @[simp] lemma dist_zero_right (g : α) : dist g 0 = ∥g∥ := by { rw[dist_eq_norm], simp } lemma norm_triangle (g h : α) : ∥g + h∥ ≤ ∥g∥ + ∥h∥ := calc ∥g + h∥ = ∥g - (-h)∥ : by simp ... = dist g (-h) : by simp[dist_eq_norm] ... ≤ dist g 0 + dist 0 (-h) : by apply dist_triangle ... = ∥g∥ + ∥h∥ : by simp[dist_eq_norm] @[simp] lemma norm_nonneg (g : α) : 0 ≤ ∥g∥ := by { rw[←dist_zero_right], exact dist_nonneg } lemma norm_eq_zero (g : α) : ∥g∥ = 0 ↔ g = 0 := by { rw[←dist_zero_right], exact dist_eq_zero } @[simp] lemma norm_zero : ∥(0:α)∥ = 0 := (norm_eq_zero _).2 (by simp) lemma norm_triangle_sum {β} : ∀(s : finset β) (f : β → α), ∥s.sum f∥ ≤ s.sum (λa, ∥ f a ∥) := finset.le_sum_of_subadditive norm norm_zero norm_triangle lemma norm_pos_iff (g : α) : ∥ g ∥ > 0 ↔ g ≠ 0 := begin split ; intro h ; rw[←dist_zero_right] at *, { exact dist_pos.1 h }, { exact dist_pos.2 h } end lemma norm_le_zero_iff (g : α) : ∥g∥ ≤ 0 ↔ g = 0 := by { rw[←dist_zero_right], exact dist_le_zero } @[simp] lemma norm_neg (g : α) : ∥-g∥ = ∥g∥ := calc ∥-g∥ = ∥0 - g∥ : by simp ... = dist 0 g : (dist_eq_norm 0 g).symm ... = dist g 0 : dist_comm _ _ ... = ∥g - 0∥ : (dist_eq_norm g 0) ... = ∥g∥ : by simp lemma norm_triangle_sub {a b : α} : ∥a - b∥ ≤ ∥a∥ + ∥b∥ := by simpa only [sub_eq_add_neg, norm_neg] using norm_triangle a (-b) lemma abs_norm_sub_norm_le (g h : α) : abs(∥g∥ - ∥h∥) ≤ ∥g - h∥ := abs_le.2 $ and.intro (suffices -∥g - h∥ ≤ -(∥h∥ - ∥g∥), by simpa, neg_le_neg $ sub_right_le_of_le_add $ calc ∥h∥ = ∥h - g + g∥ : by simp ... ≤ ∥h - g∥ + ∥g∥ : norm_triangle _ _ ... = ∥-(g - h)∥ + ∥g∥ : by simp ... = ∥g - h∥ + ∥g∥ : by { rw [norm_neg (g-h)] }) (sub_right_le_of_le_add $ calc ∥g∥ = ∥g - h + h∥ : by simp ... ≤ ∥g-h∥ + ∥h∥ : norm_triangle _ _) lemma dist_norm_norm_le (g h : α) : dist ∥g∥ ∥h∥ ≤ ∥g - h∥ := abs_norm_sub_norm_le g h lemma norm_sub_rev (g h : α) : ∥g - h∥ = ∥h - g∥ := by rw ←norm_neg; simp lemma ball_0_eq (ε : ℝ) : ball (0:α) ε = {x | ∥x∥ < ε} := set.ext $ assume a, by simp theorem normed_space.tendsto_nhds_zero {f : γ → α} {l : filter γ} : tendsto f l (nhds 0) ↔ ∀ ε > 0, { x | ∥ f x ∥ < ε } ∈ l := begin rw [metric.tendsto_nhds], simp only [normed_group.dist_eq, sub_zero], split, { intros h ε εgt0, rcases h ε εgt0 with ⟨s, ssets, hs⟩, exact mem_sets_of_superset ssets hs }, intros h ε εgt0, exact ⟨_, h ε εgt0, set.subset.refl _⟩ end section nnnorm def nnnorm (a : α) : nnreal := ⟨norm a, norm_nonneg a⟩ @[simp] lemma coe_nnnorm (a : α) : (nnnorm a : ℝ) = norm a := rfl lemma nndist_eq_nnnorm (a b : α) : nndist a b = nnnorm (a - b) := nnreal.eq $ dist_eq_norm _ _ lemma nnnorm_eq_zero (a : α) : nnnorm a = 0 ↔ a = 0 := by simp only [nnreal.eq_iff.symm, nnreal.coe_zero, coe_nnnorm, norm_eq_zero] @[simp] lemma nnnorm_zero : nnnorm (0 : α) = 0 := nnreal.eq norm_zero lemma nnnorm_triangle (g h : α) : nnnorm (g + h) ≤ nnnorm g + nnnorm h := by simpa [nnreal.coe_le] using norm_triangle g h @[simp] lemma nnnorm_neg (g : α) : nnnorm (-g) = nnnorm g := nnreal.eq $ norm_neg g lemma nndist_nnnorm_nnnorm_le (g h : α) : nndist (nnnorm g) (nnnorm h) ≤ nnnorm (g - h) := nnreal.coe_le.2 $ dist_norm_norm_le g h end nnnorm instance prod.normed_group [normed_group β] : normed_group (α × β) := { norm := λx, max ∥x.1∥ ∥x.2∥, dist_eq := assume (x y : α × β), show max (dist x.1 y.1) (dist x.2 y.2) = (max ∥(x - y).1∥ ∥(x - y).2∥), by simp [dist_eq_norm] } lemma norm_fst_le (x : α × β) : ∥x.1∥ ≤ ∥x∥ := begin have : ∥x∥ = max (∥x.fst∥) (∥x.snd∥) := rfl, rw this, simp[le_max_left] end lemma norm_snd_le (x : α × β) : ∥x.2∥ ≤ ∥x∥ := begin have : ∥x∥ = max (∥x.fst∥) (∥x.snd∥) := rfl, rw this, simp[le_max_right] end instance fintype.normed_group {π : α → Type*} [fintype α] [∀i, normed_group (π i)] : normed_group (Πb, π b) := { norm := λf, ((finset.sup finset.univ (λ b, nnnorm (f b)) : nnreal) : ℝ), dist_eq := assume x y, congr_arg (coe : nnreal → ℝ) $ congr_arg (finset.sup finset.univ) $ funext $ assume a, show nndist (x a) (y a) = nnnorm (x a - y a), from nndist_eq_nnnorm _ _ } lemma tendsto_iff_norm_tendsto_zero {f : ι → β} {a : filter ι} {b : β} : tendsto f a (nhds b) ↔ tendsto (λ e, ∥ f e - b ∥) a (nhds 0) := by rw tendsto_iff_dist_tendsto_zero ; simp only [(dist_eq_norm _ _).symm] lemma tendsto_zero_iff_norm_tendsto_zero [normed_group α] [normed_group β] {f : γ → β} {a : filter γ} : tendsto f a (nhds 0) ↔ tendsto (λ e, ∥ f e ∥) a (nhds 0) := have tendsto f a (nhds 0) ↔ tendsto (λ e, ∥ f e - 0 ∥) a (nhds 0) := tendsto_iff_norm_tendsto_zero, by simpa lemma lim_norm (x : α) : (λg:α, ∥g - x∥) →_{x} 0 := tendsto_iff_norm_tendsto_zero.1 (continuous_iff_continuous_at.1 continuous_id x) lemma lim_norm_zero : (λg:α, ∥g∥) →_{0} 0 := by simpa using lim_norm (0:α) lemma continuous_norm : continuous (λg:α, ∥g∥) := begin rw continuous_iff_continuous_at, intro x, rw [continuous_at, tendsto_iff_dist_tendsto_zero], exact squeeze_zero (λ t, abs_nonneg _) (λ t, abs_norm_sub_norm_le _ _) (lim_norm x) end lemma continuous_nnnorm : continuous (nnnorm : α → nnreal) := continuous_subtype_mk _ continuous_norm instance normed_uniform_group : uniform_add_group α := begin refine ⟨metric.uniform_continuous_iff.2 $ assume ε hε, ⟨ε / 2, half_pos hε, assume a b h, _⟩⟩, rw [prod.dist_eq, max_lt_iff, dist_eq_norm, dist_eq_norm] at h, calc dist (a.1 - a.2) (b.1 - b.2) = ∥(a.1 - b.1) - (a.2 - b.2)∥ : by simp [dist_eq_norm] ... ≤ ∥a.1 - b.1∥ + ∥a.2 - b.2∥ : norm_triangle_sub ... < ε / 2 + ε / 2 : add_lt_add h.1 h.2 ... = ε : add_halves _ end instance normed_top_monoid : topological_add_monoid α := by apply_instance instance normed_top_group : topological_add_group α := by apply_instance end normed_group section normed_ring class normed_ring (α : Type*) extends has_norm α, ring α, metric_space α := (dist_eq : ∀ x y, dist x y = norm (x - y)) (norm_mul : ∀ a b, norm (a * b) ≤ norm a * norm b) instance normed_ring.to_normed_group [β : normed_ring α] : normed_group α := { ..β } lemma norm_mul_le {α : Type*} [normed_ring α] (a b : α) : (∥a*b∥) ≤ (∥a∥) * (∥b∥) := normed_ring.norm_mul _ _ lemma norm_pow_le {α : Type*} [normed_ring α] (a : α) : ∀ {n : ℕ}, n > 0 → ∥a^n∥ ≤ ∥a∥^n | 1 h := by simp | (n+2) h := le_trans (norm_mul_le a (a^(n+1))) (mul_le_mul (le_refl _) (norm_pow_le (nat.succ_pos _)) (norm_nonneg _) (norm_nonneg _)) instance prod.normed_ring [normed_ring α] [normed_ring β] : normed_ring (α × β) := { norm_mul := assume x y, calc ∥x * y∥ = ∥(x.1*y.1, x.2*y.2)∥ : rfl ... = (max ∥x.1*y.1∥ ∥x.2*y.2∥) : rfl ... ≤ (max (∥x.1∥*∥y.1∥) (∥x.2∥*∥y.2∥)) : max_le_max (norm_mul_le (x.1) (y.1)) (norm_mul_le (x.2) (y.2)) ... = (max (∥x.1∥*∥y.1∥) (∥y.2∥*∥x.2∥)) : by simp[mul_comm] ... ≤ (max (∥x.1∥) (∥x.2∥)) * (max (∥y.2∥) (∥y.1∥)) : by { apply max_mul_mul_le_max_mul_max; simp [norm_nonneg] } ... = (max (∥x.1∥) (∥x.2∥)) * (max (∥y.1∥) (∥y.2∥)) : by simp[max_comm] ... = (∥x∥*∥y∥) : rfl, ..prod.normed_group } end normed_ring instance normed_ring_top_monoid [normed_ring α] : topological_monoid α := ⟨ continuous_iff_continuous_at.2 $ λ x, tendsto_iff_norm_tendsto_zero.2 $ have ∀ e : α × α, e.fst * e.snd - x.fst * x.snd = e.fst * e.snd - e.fst * x.snd + (e.fst * x.snd - x.fst * x.snd), by intro; rw sub_add_sub_cancel, begin apply squeeze_zero, { intro, apply norm_nonneg }, { simp only [this], intro, apply norm_triangle }, { rw ←zero_add (0 : ℝ), apply tendsto_add, { apply squeeze_zero, { intro, apply norm_nonneg }, { intro t, show ∥t.fst * t.snd - t.fst * x.snd∥ ≤ ∥t.fst∥ * ∥t.snd - x.snd∥, rw ←mul_sub, apply norm_mul_le }, { rw ←mul_zero (∥x.fst∥), apply tendsto_mul, { apply continuous_iff_continuous_at.1, apply continuous.comp, { apply continuous_fst }, { apply continuous_norm }}, { apply tendsto_iff_norm_tendsto_zero.1, apply continuous_iff_continuous_at.1, apply continuous_snd }}}, { apply squeeze_zero, { intro, apply norm_nonneg }, { intro t, show ∥t.fst * x.snd - x.fst * x.snd∥ ≤ ∥t.fst - x.fst∥ * ∥x.snd∥, rw ←sub_mul, apply norm_mul_le }, { rw ←zero_mul (∥x.snd∥), apply tendsto_mul, { apply tendsto_iff_norm_tendsto_zero.1, apply continuous_iff_continuous_at.1, apply continuous_fst }, { apply tendsto_const_nhds }}}} end ⟩ instance normed_top_ring [normed_ring α] : topological_ring α := ⟨ continuous_iff_continuous_at.2 $ λ x, tendsto_iff_norm_tendsto_zero.2 $ have ∀ e : α, -e - -x = -(e - x), by intro; simp, by simp only [this, norm_neg]; apply lim_norm ⟩ section normed_field class normed_field (α : Type*) extends has_norm α, discrete_field α, metric_space α := (dist_eq : ∀ x y, dist x y = norm (x - y)) (norm_mul : ∀ a b, norm (a * b) = norm a * norm b) instance normed_field.to_normed_ring [i : normed_field α] : normed_ring α := { norm_mul := by finish [i.norm_mul], ..i } @[simp] lemma norm_one {α : Type*} [normed_field α] : ∥(1 : α)∥ = 1 := have ∥(1 : α)∥ * ∥(1 : α)∥ = ∥(1 : α)∥ * 1, by calc ∥(1 : α)∥ * ∥(1 : α)∥ = ∥(1 : α) * (1 : α)∥ : by rw normed_field.norm_mul ... = ∥(1 : α)∥ * 1 : by simp, eq_of_mul_eq_mul_left (ne_of_gt ((norm_pos_iff _).2 (by simp))) this @[simp] lemma norm_mul [normed_field α] (a b : α) : ∥a * b∥ = ∥a∥ * ∥b∥ := normed_field.norm_mul a b instance normed_field.is_monoid_hom_norm [normed_field α] : is_monoid_hom (norm : α → ℝ) := ⟨norm_one, norm_mul⟩ @[simp] lemma norm_pow [normed_field α] (a : α) : ∀ (n : ℕ), ∥a^n∥ = ∥a∥^n := is_monoid_hom.map_pow norm a @[simp] lemma norm_prod {β : Type*} [normed_field α] (s : finset β) (f : β → α) : ∥s.prod f∥ = s.prod (λb, ∥f b∥) := eq.symm (finset.prod_hom norm) @[simp] lemma norm_div {α : Type*} [normed_field α] (a b : α) : ∥a/b∥ = ∥a∥/∥b∥ := if hb : b = 0 then by simp [hb] else begin apply eq_div_of_mul_eq, { apply ne_of_gt, apply (norm_pos_iff _).mpr hb }, { rw [←normed_field.norm_mul, div_mul_cancel _ hb] } end @[simp] lemma norm_inv {α : Type*} [normed_field α] (a : α) : ∥a⁻¹∥ = ∥a∥⁻¹ := by simp only [inv_eq_one_div, norm_div, norm_one] instance : normed_field ℝ := { norm := λ x, abs x, dist_eq := assume x y, rfl, norm_mul := abs_mul } lemma real.norm_eq_abs (r : ℝ): norm r = abs r := rfl end normed_field @[simp] lemma norm_norm [normed_group α] (x : α) : ∥∥x∥∥ = ∥x∥ := by rw [real.norm_eq_abs, abs_of_nonneg (norm_nonneg _)] section normed_space class normed_space (α : Type*) (β : Type*) [normed_field α] extends normed_group β, vector_space α β := (norm_smul : ∀ (a:α) b, norm (a • b) = has_norm.norm a * norm b) variables [normed_field α] instance normed_field.to_normed_space : normed_space α α := { dist_eq := normed_field.dist_eq, norm_smul := normed_field.norm_mul } set_option class.instance_max_depth 43 lemma norm_smul [normed_space α β] (s : α) (x : β) : ∥s • x∥ = ∥s∥ * ∥x∥ := normed_space.norm_smul s x lemma nnnorm_smul [normed_space α β] (s : α) (x : β) : nnnorm (s • x) = nnnorm s * nnnorm x := nnreal.eq $ norm_smul s x variables {E : Type*} {F : Type*} [normed_space α E] [normed_space α F] lemma tendsto_smul {f : γ → α} { g : γ → F} {e : filter γ} {s : α} {b : F} : (tendsto f e (nhds s)) → (tendsto g e (nhds b)) → tendsto (λ x, (f x) • (g x)) e (nhds (s • b)) := begin intros limf limg, rw tendsto_iff_norm_tendsto_zero, have ineq := λ x : γ, calc ∥f x • g x - s • b∥ = ∥(f x • g x - s • g x) + (s • g x - s • b)∥ : by simp[add_assoc] ... ≤ ∥f x • g x - s • g x∥ + ∥s • g x - s • b∥ : norm_triangle (f x • g x - s • g x) (s • g x - s • b) ... ≤ ∥f x - s∥*∥g x∥ + ∥s∥*∥g x - b∥ : by { rw [←smul_sub, ←sub_smul, norm_smul, norm_smul] }, apply squeeze_zero, { intro t, exact norm_nonneg _ }, { exact ineq }, { clear ineq, have limf': tendsto (λ x, ∥f x - s∥) e (nhds 0) := tendsto_iff_norm_tendsto_zero.1 limf, have limg' : tendsto (λ x, ∥g x∥) e (nhds ∥b∥) := filter.tendsto.comp limg (continuous_iff_continuous_at.1 continuous_norm _), have lim1 := tendsto_mul limf' limg', simp only [zero_mul, sub_eq_add_neg] at lim1, have limg3 := tendsto_iff_norm_tendsto_zero.1 limg, have lim2 := tendsto_mul (tendsto_const_nhds : tendsto _ _ (nhds ∥ s ∥)) limg3, simp only [sub_eq_add_neg, mul_zero] at lim2, rw [show (0:ℝ) = 0 + 0, by simp], exact tendsto_add lim1 lim2 } end lemma tendsto_smul_const {g : γ → F} {e : filter γ} (s : α) {b : F} : (tendsto g e (nhds b)) → tendsto (λ x, s • (g x)) e (nhds (s • b)) := tendsto_smul tendsto_const_nhds lemma continuous_smul [topological_space γ] {f : γ → α} {g : γ → E} (hf : continuous f) (hg : continuous g) : continuous (λc, f c • g c) := continuous_iff_continuous_at.2 $ assume c, tendsto_smul (continuous_iff_continuous_at.1 hf _) (continuous_iff_continuous_at.1 hg _) instance : normed_space α (E × F) := { norm_smul := begin intros s x, cases x with x₁ x₂, change max (∥s • x₁∥) (∥s • x₂∥) = ∥s∥ * max (∥x₁∥) (∥x₂∥), rw [norm_smul, norm_smul, ← mul_max_of_nonneg _ _ (norm_nonneg _)] end, add_smul := λ r x y, prod.ext (add_smul _ _ _) (add_smul _ _ _), smul_add := λ r x y, prod.ext (smul_add _ _ _) (smul_add _ _ _), ..prod.normed_group, ..prod.vector_space } instance fintype.normed_space {ι : Type*} {E : ι → Type*} [fintype ι] [∀i, normed_space α (E i)] : normed_space α (Πi, E i) := { norm := λf, ((finset.univ.sup (λb, nnnorm (f b)) : nnreal) : ℝ), dist_eq := assume f g, congr_arg coe $ congr_arg (finset.sup finset.univ) $ by funext i; exact nndist_eq_nnnorm _ _, norm_smul := λ a f, show (↑(finset.sup finset.univ (λ (b : ι), nnnorm (a • f b))) : ℝ) = nnnorm a * ↑(finset.sup finset.univ (λ (b : ι), nnnorm (f b))), by simp only [(nnreal.coe_mul _ _).symm, nnreal.mul_finset_sup, nnnorm_smul], ..metric_space_pi, ..pi.vector_space α } /-- A normed space can be built from a norm that satisfies algebraic properties. This is formalised in this structure. -/ structure normed_space.core (α : Type*) (β : Type*) [normed_field α] [add_comm_group β] [has_scalar α β] [has_norm β] := (norm_eq_zero_iff : ∀ x : β, ∥x∥ = 0 ↔ x = 0) (norm_smul : ∀ c : α, ∀ x : β, ∥c • x∥ = ∥c∥ * ∥x∥) (triangle : ∀ x y : β, ∥x + y∥ ≤ ∥x∥ + ∥y∥) noncomputable def normed_space.of_core (α : Type*) (β : Type*) [normed_field α] [add_comm_group β] [vector_space α β] [has_norm β] (C : normed_space.core α β) : normed_space α β := { dist := λ x y, ∥x - y∥, dist_eq := assume x y, by refl, dist_self := assume x, (C.norm_eq_zero_iff (x - x)).mpr (show x - x = 0, by simp), eq_of_dist_eq_zero := assume x y h, show (x = y), from sub_eq_zero.mp $ (C.norm_eq_zero_iff (x - y)).mp h, dist_triangle := assume x y z, calc ∥x - z∥ = ∥x - y + (y - z)∥ : by simp ... ≤ ∥x - y∥ + ∥y - z∥ : C.triangle _ _, dist_comm := assume x y, calc ∥x - y∥ = ∥ -(1 : α) • (y - x)∥ : by simp ... = ∥y - x∥ : begin rw[C.norm_smul], simp end, norm_smul := C.norm_smul } end normed_space section has_sum local attribute [instance] classical.prop_decidable open finset filter variables [normed_group α] [complete_space α] lemma has_sum_iff_vanishing_norm {f : ι → α} : has_sum f ↔ ∀ε>0, (∃s:finset ι, ∀t, disjoint t s → ∥ t.sum f ∥ < ε) := begin simp only [has_sum_iff_vanishing, metric.mem_nhds_iff, exists_imp_distrib], split, { assume h ε hε, refine h {x | ∥x∥ < ε} ε hε _, rw [ball_0_eq ε] }, { assume h s ε hε hs, rcases h ε hε with ⟨t, ht⟩, refine ⟨t, assume u hu, hs _⟩, rw [ball_0_eq], exact ht u hu } end lemma has_sum_of_norm_bounded {f : ι → α} (g : ι → ℝ) (hf : has_sum g) (h : ∀i, ∥f i∥ ≤ g i) : has_sum f := has_sum_iff_vanishing_norm.2 $ assume ε hε, let ⟨s, hs⟩ := has_sum_iff_vanishing_norm.1 hf ε hε in ⟨s, assume t ht, have ∥t.sum g∥ < ε := hs t ht, have nn : 0 ≤ t.sum g := finset.zero_le_sum (assume a _, le_trans (norm_nonneg _) (h a)), lt_of_le_of_lt (norm_triangle_sum t f) $ lt_of_le_of_lt (finset.sum_le_sum $ assume i _, h i) $ by rwa [real.norm_eq_abs, abs_of_nonneg nn] at this⟩ lemma has_sum_of_has_sum_norm {f : ι → α} (hf : has_sum (λa, ∥f a∥)) : has_sum f := has_sum_of_norm_bounded _ hf (assume i, le_refl _) lemma norm_tsum_le_tsum_norm {f : ι → α} (hf : has_sum (λi, ∥f i∥)) : ∥(∑i, f i)∥ ≤ (∑ i, ∥f i∥) := have h₁ : tendsto (λs:finset ι, ∥s.sum f∥) at_top (nhds ∥(∑ i, f i)∥) := (is_sum_tsum $ has_sum_of_has_sum_norm hf).comp (continuous_norm.tendsto _), have h₂ : tendsto (λs:finset ι, s.sum (λi, ∥f i∥)) at_top (nhds (∑ i, ∥f i∥)) := is_sum_tsum hf, le_of_tendsto_of_tendsto at_top_ne_bot h₁ h₂ $ univ_mem_sets' $ assume s, norm_triangle_sum _ _ end has_sum namespace complex instance : normed_field ℂ := { norm := complex.abs, dist_eq := λ _ _, rfl, norm_mul := complex.abs_mul, .. complex.discrete_field } @[simp] lemma norm_real (r : ℝ) : ∥(r : ℂ)∥ = ∥r∥ := complex.abs_of_real _ @[simp] lemma norm_rat (r : ℚ) : ∥(r : ℂ)∥ = _root_.abs (r : ℝ) := suffices ∥((r : ℝ) : ℂ)∥ = _root_.abs r, by simpa, by rw [norm_real, real.norm_eq_abs] @[simp] lemma norm_nat (n : ℕ) : ∥(n : ℂ)∥ = n := complex.abs_of_nat _ @[simp] lemma norm_int {n : ℤ} : ∥(n : ℂ)∥ = _root_.abs n := suffices ∥((n : ℝ) : ℂ)∥ = _root_.abs n, by simpa, by rw [norm_real, real.norm_eq_abs] lemma norm_int_of_nonneg {n : ℤ} (hn : n ≥ 0) : ∥(n : ℂ)∥ = n := by rw [norm_int, _root_.abs_of_nonneg]; exact int.cast_nonneg.2 hn end complex
f1d1e2fbaa03d7abf2781a346dc44240097e6d53
38a6d5def645a1887e1306ceb4da06ff71452096
/_5_The_Physical_Layer/optical_fiber/entropy_of_channels.lean
dc11a2d265586dc18870d07309b73cc5eed4a6f3
[]
no_license
QTM3x/Quantum-Internet
bcc2d61e2ae7233bb2b369fedaed22a1feb6fba1
f90e09fb6c03d35043654d8b1bec1c63d6012268
refs/heads/master
1,609,224,401,937
1,599,911,583,000
1,599,911,583,000
238,495,221
45
33
null
1,603,625,079,000
1,580,919,815,000
Jupyter Notebook
UTF-8
Lean
false
false
12,108
lean
import data.real.basic import analysis.special_functions.exp_log import _5_The_Physical_Layer.optical_fiber.quantum_channel import _5_The_Physical_Layer.qubit_carriers.quantum_state import common.matrix_ops notation `|` x `|` := abs x ---- HOLEVO INFORMATION /- Definition (Holevo information of a quantum channel) "The Holevo information χ(𝒩) of a channel 𝒩 is a measure of the classical correlations that Alice can establish with Bob where the maximization is with respect to all input classical–quantum states." https://arxiv.org/pdf/1106.1445.pdf -/ def Holevo_info (𝒩 : quantum_channel) : ℝ := begin -- the set of all classical-quantum states let CQ_states := {ρ : density_operator | is_classical_quantum(ρ)}, -- the states after the channel acts on Bob's system let output_states := {I⊗𝒩 ρ | ρ ∈ CQ_states} -- the set of all values of mutual information for the output states let I_out := {I(X;B)_ρ | ρ ∈ CQ_states}, -- let maximum be a real number let maximum : ℝ := _, -- the maximum is in I_CQ let h := maximum ∈ I_out, -- the maximum is at least as big as any element in I_CQ let h' := ∀ x ∈ I_out, maximum ≥ x, -- Holevo info is the maximum exact maximum, end notation `χ(` 𝒩 `)` := Holevo_info 𝒩 /- Definition (regularized Holevo information of a quantum channel) -/ def reg_Holevo_info (𝒩 : quantum_channel) : ℝ := begin -- let lim be a real number let lim : ℝ := _, -- let the Holevo information of many uses of the channel -- tend to this limit lim. let h := ∀ ε > 0, ∃ N, ∀ n > N, |lim - χ(𝒩⊗..n..⊗𝒩)| ≤ ε, -- the regularized Holevo information is this limit exact lim, end notation `χ_reg(` ρ `)` := reg_Holevo_info 𝒩 /- Theorem (Holevo information of entanglement-breaking channels) -/ theorem Holevo_info_eq_reg_Holevo_info_of_entanglement_breaking {𝒩 : quantum_channel} : is_entanglement_breaking(𝒩) → χ(𝒩) = χ_reg(𝒩) := begin sorry end ---- SQUASHED ENTANGLEMENT /- Definition (squashed entanglement of a quantum channel) -/ def squashed_entanglement (𝒩 : quantum_channel) : ℝ := maximum_ρ squashed_entanglement(ρ) /- Theorem (upper bound on squashed entanglement of phase-insensisitve Gaussian quantum channels) https://arxiv.org/pdf/1511.08710.pdf -/ notation `ζ(` a `,` b `)` := a * b * real.log(a/b) theorem squashed_entanglement_phase_insensitive_channels_up_bound {𝒩 : phase_insensitive_channel} : squashed_entanglement(𝒩) ≤ (ζ(1 + 𝒩.noise + 3*𝒩.gain, 1 + 𝒩.noise - 𝒩.gain) - 𝒩.gain * ζ(𝒩.gain + 𝒩.noise + 3, 𝒩.gain + 𝒩.noise - 1)) / (2 * (1 + 𝒩.noise + 𝒩.gain) * (1 - 𝒩.gain^2)) := begin sorry end ---- MUTUAL INFORMATION /- Definition (mutual information of a quantum channel) "The mutual information of a quantum channel corresponds to an important operational task that is not particularly obvious from the above discussion. Suppose that Alice and Bob share unlimited bipartite entanglement in whatever form they wish, and suppose they have access to a large number of independent uses of the channel NA0→B. Then the mutual information of the channel corresponds to the maximal amount of classical information that they can transmit in such a setting." https://arxiv.org/pdf/1106.1445.pdf -/ def mut_info (𝒩 : quantum_channel) : ℝ := begin -- the set of all pure states let pure_states := {ρ : density_operator | is_pure(ρ)}, -- the states after the channel acts on Bob's system let output_states := {I⊗𝒩 ρ | ρ ∈ pure_states} -- the set of all values of mutual information let I_out := {I(A;B)_ρ | ρ ∈ pure_states}, -- let maximum be a real number let maximum : ℝ := _, -- the maximum is in I_CQ let h := maximum ∈ I_pure, -- the maximum is at least as big as any element in I_CQ let h' := ∀ x ∈ I_out, maximum ≥ x, -- Holevo info is the maximum exact maximum, end notation `I(` 𝒩 `)` := mut_info 𝒩 /- Definition (regularized mutual information) -/ def reg_mut_info (𝒩 : quantum_channel) : ℝ := begin -- let lim be a real number let lim : ℝ := _, -- let the mutual information of many uses of the channel -- tend to this limit lim. let h := ∀ ε > 0, ∃ N, ∀ n > N, |lim - I(𝒩⊗..n..⊗𝒩)| ≤ ε, -- the regularized private information is this limit exact lim, end notation `I_reg(` 𝒩 `)` := reg_mut_info 𝒩 /- Theorem (additivity) -/ @[simp] theorem mut_info_additive {𝒩 : quantum_channel} {ℳ : quantum_channel}: I(𝒩⊗ℳ) = I(𝒩) + I(ℳ) := begin sorry end /- Theorem (regularized mutual information = mutual information) -/ theorem reg_mut_info_eq_mut_info {𝒩 : quantum_channel} : I_reg(𝒩) = I(𝒩) := begin sorry end ---- COHERENT INFORMATION /- Definition (coherent information of a quantum channel) "The coherent information of a quantum channel corresponds to an important operational task (perhaps the most important for quantum information). It is a good lower bound on the capacity for Alice to transmit quantum information to Bob, but it is actually equal to such a quantum communication capacity of a quantum channel in some special cases." https://arxiv.org/pdf/1106.1445.pdf -/ def coherent_info (𝒩 : quantum_channel) : ℝ := begin -- the set of all pure states let pure_states := {ρ : density_operator | is_pure(ρ)}, -- the states after the channel acts on Bob's system let output_states := {I⊗𝒩 ρ | ρ ∈ pure_states} -- the set of all values of coherent information let I_out := {I(A⟩B)_ρ | ρ ∈ pure_states}, -- let maximum be a real number let maximum : ℝ := _, -- the maximum is in I_CQ let h := maximum ∈ I_pure, -- the maximum is at least as big as any element in I_CQ let h' := ∀ x ∈ I_out, maximum ≥ x, -- Holevo info is the maximum exact maximum, end notation `Q(` 𝒩 `)` := coherent_info 𝒩 /- Definition (regularized coherent information) -/ def reg_coherent_info (𝒩 : quantum_channel) : ℝ := begin -- let lim be a real number let lim : ℝ := _, -- let the coherent information of many uses of the channel -- tend to this limit lim. let h := ∀ ε > 0, ∃ N, ∀ n > N, |lim - Q(𝒩⊗..n..⊗𝒩)| ≤ ε, -- the regularized coherent information is this limit exact lim, end notation `Q_reg(` 𝒩 `)` := reg_coherent_info 𝒩 /- Theorem (non-negativity) -/ theorem coherent_info_nonneg {𝒩 : quantum_channel} : Q(𝒩) ≥ 0 := begin sorry end ---- REVERSE COHERENT INFORMATION /- Definition (reverse coherent information) -/ def reverse_coherent_info (𝒩 : quantum_channel) : ℝ := begin -- the set of all pure states let pure_states := {ρ : density_operator | is_pure(ρ)}, -- the states after the channel acts on Bob's system let output_states := {I⊗𝒩 ρ | ρ ∈ pure_states} -- the set of all values of coherent information let I_out := {I(B⟩A)_ρ | ρ ∈ pure_states}, -- let maximum be a real number let maximum : ℝ := _, -- the maximum is in I_CQ let h := maximum ∈ I_pure, -- the maximum is at least as big as any element in I_CQ let h' := ∀ x ∈ I_out, maximum ≥ x, -- Holevo info is the maximum exact maximum, end notation `Q_rev(` 𝒩 `)` := reverse_coherent_info 𝒩 ---- PRIVATE INFORMATION /- Definition (private information) "Alice would like to establish classical correlations with Bob, but does not want the environment of the channel to have access to these classical correlations." https://arxiv.org/pdf/1106.1445.pdf -/ def private_info (𝒩 : quantum_channel) : ℝ := begin -- the set of all classical-quantum states let CQ_states := {ρ : density_operator | is_classical_quantum(ρ)}, -- the states after the channel acts on Bob's system let output_states := {(isometric_extension 𝒩) ρ | ρ ∈ CQ_states} -- the set of all values of mutual information for the output states let I_out := {I(X;B)_ρ - I(X;E)_ρ | ρ ∈ CQ_states}, -- let maximum be a real number let maximum : ℝ := _, -- the maximum is in I_CQ let h := maximum ∈ I_out, -- the maximum is at least as big as any element in I_CQ let h' := ∀ x ∈ I_out, maximum ≥ x, -- Holevo info is the maximum exact maximum, end notation `P(` 𝒩 `)` := private_info 𝒩 /- Definition (regularized private information) -/ def reg_private_info {ε : ℝ} (𝒩 : quantum_channel) : ℝ := begin -- let lim be a real number let lim : ℝ := _, -- let the private information of many uses of the channel -- tend to this limit lim. let h := ∀ ε > 0, ∃ N, ∀ n > N, |lim - P(𝒩⊗..n..⊗𝒩)| ≤ ε, -- the regularized private information is this limit exact lim, end notation `P_reg(` 𝒩 `)` := reg_private_info 𝒩 /- Theorem (private info ≥ coherent info for any channel) -/ theorem private_info_geq_coherent_info : ∀ (𝒩 : quantum_channel), P(𝒩) ≥ Q(𝒩) := begin sorry end /- Theorem (private info is = coherent info for degradable channels) -/ theorem private_info_eq_coherent_info_of_degradable : ∀ (𝒩 : quantum_channel), is_degradable(𝒩) → P(𝒩) = Q(𝒩) := begin sorry end -- QUANTUM CAPACITY /- Definition (quantum communication code) -/ structure code : Type := (𝒩 : quantum_channel) -- the channel the code is designed for (n : ℕ) -- uses of the channel (ε : ℝ) -- allowed error (ℰ : quantum_channel) -- encoding channel (𝒟 : quantum_channel) -- decoding channel -- output state is within allowed error for all input states (hε : ∀ (ρ : density_operator), 1/2 * ∥ρ - 𝒟(tensor_pow_channel 𝒩 n (ℰ(ρ)))∥₁ ≤ ε) (rate_achieved : ℝ := 1/n * log ℰ.in_dim) -- the rate of the code /- Definition (achievable rate using a channel) -/ def is_achievable_rate (𝒩 : quantum_channel) (rate : ℝ) : Prop := ∀ (ε δ : ℝ) (hε : ε > 0 ∧ ε < 1) (hδ : δ > 0), ∃ (c : code), c.rate_achieved ≥ rate - δ ∧ c.ε ≤ ε /- Definition (quantum capacity of a quantum channel): supremum of all rates achievable using the channel. -/ def quantum_capacity (𝒩 : quantum_channel) : ℝ := begin let achievable_rates := {rate : ℝ | is_achievable_rate 𝒩 rate}, let bigger_rates := {rate : ℝ | ∀ ar ∈ achievable_rates, rate > ar}, let supremum_rate : ℝ := _, let h_supremum_rate : Prop := ∀ rate ∈ bigger_rates, supremum_rate ≤ rate, let h_supremum_rate' : Prop := ∀ rate ∈ achievable_rates, supremum_rate > rate, exact supremum_rate, end /- Theorem (quantum capacity equals regularized coherent information) https://arxiv.org/pdf/1106.1445.pdf -/ theorem quantum_capacity_eq_reg_coh_info {𝒩 : quantum_channel} : quantum_capacity(𝒩) = reg_coherent_info(𝒩) := begin sorry end /- Theorem (quantum capacity of amp damp channel) -/ theorem quantum_capacity_amp_damp {η : ℝ} (𝒩 := amp_damp_channel η) : quantum_capacity(𝒩) = min_p h₂((1-η)*p) - h₂(η*p) := begin sorry end ---- TWO-WAY QUANTUM CAPACITY -- can you represent the unlimited classical communication -- as a list of bits of arbitrary length that Alice and Bob can -- send to each other? -- can you think of the classical communication as transmission -- of qubits carrying only classical information through the -- identity channel? can you absorb the local gates in the -- LOCCs into the encoding channel? /- Defintion (two-way capacity): The quantum capacity of a channel if unlimited classical communication is allowed between the sender and the receiver. -/ def two_way_quantum_capacity (𝒩 : quantum_channel) : ℝ := sorry ---- /- Definition (σ-stretching): -/ def sigma_stretching (𝒩 : quantum_channel) := sorry /- Defintion (KL divergence): -/ def KL_divergence := sorry
54d9b6f741b5ea4059d74143e77f9400143ffa2e
ed27983dd289b3bcad416f0b1927105d6ef19db8
/src/inClassNotes/dependentTypes.lean
24224ccc215df8d9308da9a62dccf268f21ea405
[]
no_license
liuxin-James/complogic-s21
0d55b76dbe25024473d31d98b5b83655c365f811
13e03e0114626643b44015c654151fb651603486
refs/heads/master
1,681,109,264,463
1,618,848,261,000
1,618,848,261,000
337,599,491
0
0
null
1,613,141,619,000
1,612,925,555,000
null
UTF-8
Lean
false
false
6,787
lean
/- A FAMILY OF TYPES ("INDUCTIVE FAMILY") efine a family of types, *tuple n*, indexed by natural numbers. For any (n : nat), tuple n is the type of tuples (of natural numbers) of length n. -/ -- nat ⨯ nat -- ℕ ℕ ℕ -- (1,2,3) -- ℕ ⨯ (ℕ×ℕ) -- (1,(2,3)) -- (1, (2, (3, (4, 5)))) /- Build a function that takes a natural number, n, and returns a TYPE: the type of tuples of length n. #check tuple nat → (nat ⨯ (nat ⨯ nat)) tuple : Π (n : ℕ), _ -/ /- Reminder: prod is a type builder. Given types, α and β, prod α β (or α × β) is the the *type* of ordered α-β pairs. We can then use prod.mk to create values of such a type. The following function recursively applies × to nat, enabling us to build product types with any number of components, not just two (where, here, for simplicity, we support only products of the nat type). The base case for the recursion when n=0 is the unit type. -/ -- for each (n : nat), a type, (tuple n) def tuple : nat → Type | 0 := unit | (n' + 1) := nat × (tuple n') /- 0 tuple 0 = unit 1 tuple 1 = nat ⨯ unit 2 tuple 2 = nat ⨯ (nat ⨯ unit) 3 tuple 3 = nat ⨯ (nat ⨯ (nat ⨯ unit)) 4 tuple 4 = nat ⨯ (tuple 3) ... n tuple (n' + 1) = nat ⨯ (tuple n') -/ #check tuple 0 -- ℕ → Type (*important*) #check nat #check (prod nat nat) /- For values of n from 0 to 3, we get the following types by applying tuple to n. 0: unit 1: nat ⨯ unit 2: nat × (nat × unit) 3: nat × (nat × (nat × unit)) Values of these types include: 0 : (unit.star) 1: (1, unit.star) 2: (1, 2, unit.star) 3: (1, 2, 4, unit.star) -/ def t0 : tuple 0 := unit.star def t1' : tuple 1 := prod.mk 1 unit.star def t1 : tuple 1 := (1, unit.star) -- notation def t2 : tuple 2 := (1, 2, unit.star) def t3 : tuple 3 := (1, (2, (4, (unit.star)))) -- (1, 2, unit.star) -- (1, (2, (unit.star))) -- prod.mk 1 (prod.mk 2 unit.star) /- The length is typechecked! The error messages are cryptic, but, hey. -/ def t3' : tuple 4 := (1, 2, 3, 4, unit.star) -- no def t3'' : tuple 3 := (1, 2, 4, unit.star) -- no #check t3'' /- We could define a nicer concrete syntax that would let us avoid having to write the star at the end, but we'll skip that here to stay focused on the essentials. -/ /- Note that tuple is a *type builder*. It takes a natural number, n, and returns a *type*: in particular, one that depends on n. Tuple is defined by recursion on n. It iteratively computes the product type of nat and smaller product of nats until n=0, at which point it returns the product of all that with the unit type (base case). -/ /- More generally, given (α : Type) and (β : α → Type), we can view β as defining a *family of types over α*, with a different type, (β a), for such each value, (a : α). In our example above, α = nat and β = tuple. Tuple defines an inductive family of types "indexed by the natural numbers." To each natural number, n, tuple thus associates a corresponding type, tuple n,that depends on n. -/ def n0 : tuple 0 := () #reduce n0 def nil := tuple 0 def cons : Π {n : ℕ}, nat → tuple n → tuple (n + 1) | n a t := prod.mk a t -- {2} 7 (1, 2, star) -> (7, (1, 2, star)) --#reduce cons 7 ((1, (2, unit.star)) def head : Π {n : nat}, tuple n → option nat | 0 _ := none | (n' + 1) (prod.mk h t) := some h def tail {α : Type} : Π (n : nat), tuple n → option (tuple (n-1)) | 0 _ := none | (n' + 1) (prod.mk h t) := some t def append : Π {n m : ℕ}, (tuple n) → tuple m → tuple (m + n) | 0 m tn tm := tm | (n' + 1) m (prod.mk h tn') tm := prod.mk h (append tn' tm) -- infers n' m def t6 := append t3 t3 #reduce t6 #reduce tail 3 t3 -- Type check catches bounds errors def foo (t : tuple 3) : nat := 0 #check foo t3 -- No: type of t2 is tuple 2, not tuple 3 /- DEPENDENT FUNCTION TYPES -/ /- The importance of Pi types, Π x : α, β x, is that they generalize the notion of a function type, α → β, by allowing the type, β, to depend on (a : α). Here's a function that takes a value, n, of type nat, and that returns a value of type *(tuple n)*. Clearly the type of the return value depends on the value of the argument, n. It should now also be clear why Π binds a name to an argument: so that the value can be used in defining the rest of the *type* of a function. -/ def zerotuple : Π (n : nat), tuple n | 0 := () | (n' + 1) := (0, zerotuple n') -- Π (n : nat), tuple n #reduce zerotuple 4 #check zerotuple def nToNtuple (n : nat) : tuple n := zerotuple n #check nToNtuple def z0 := nToNtuple 0 def z1 := nToNtuple 1 def z2 := nToNtuple 2 def z3 := nToNtuple 3 def z4 := nToNtuple 4 #check z0 #check z1 #check z2 #check z3 #check z4 #reduce z0 #reduce z1 #reduce z2 #reduce z3 #reduce z4 -- General notation for dependently typed functions -- Π (a : A), B a -- Π (n : ℕ), tuple n -- Π (a : A), B -- special case where B doesn't depend on a -- A → B -- Ours is a dependently typed function #check nToNtuple /- SIGMA (DEPENDENT PRODUCT) TYPES -/ #print sigma /- structure sigma : Π {α : Type u}, (α → Type v) → Type (max u v) fields: sigma.fst : Π {α : Type u} {β : α → Type v}, sigma β → α sigma.snd : Π {α : Type u} {β : α → Type v} (c : sigma β), β c.fstLean -/ #check Σ (n : nat), tuple n -- dependent pair type, ⟨ n, tuple n ⟩ def s3 : Σ (n : nat), tuple n := sigma.mk 3 (1,2,3,unit.star) def s5 : Σ (n : nat), tuple n := ⟨ 5, (nToNtuple 5) ⟩ def sx : Σ (n : nat), tuple n := ⟨ 5, (nToNtuple 4) ⟩ -- Cannot form, snd has wrong type #print sigma #reduce sigma.fst s3 #reduce sigma.snd s3 #reduce s3.fst #reduce s3.snd #reduce s3.1 #reduce s3.2 -- Identical types, varying in notation #check Σ (n : nat), tuple n #check @sigma nat tuple #check sigma.mk 3 (nToNtuple 3) #check sigma.mk 4 (nToNtuple 4) #reduce sigma.mk 3 (nToNtuple 3) #reduce sigma.mk 4 (nToNtuple 4) def nToSigma (n : nat) : sigma tuple := ⟨ n, nToNtuple n⟩ def nToSigma' (n : nat): Σ (n : nat), tuple n := ⟨ n, nToNtuple n⟩ #reduce nToSigma 5 /- variable α : Type variable β : α → Type variable a : α variable b : β a #check sigma.mk a b -- Σ (a : α), β a #check (sigma.mk a b).1 -- α #check (sigma.mk a b).2 -- β (sigma.fst (sigma.mk a b)) #reduce (sigma.mk a b).1 -- a #reduce (sigma.mk a b).2 -- b-/ def evenNum : {n : nat // n%2 = 0} := ⟨ 2, rfl ⟩ #reduce evenNum def oops : {n : nat // n%2 = 0} := ⟨ 3, rfl ⟩ def evenId : {n : nat // n%2 = 0} → nat | ⟨ val, proof_about_val ⟩ := val #eval evenId ⟨ 0, rfl ⟩ #eval evenId ⟨ 1, rfl ⟩ #eval evenId ⟨ 2, rfl ⟩ #eval evenId ⟨ 3, rfl ⟩ #eval evenId ⟨ 4, rfl ⟩ #eval evenId ⟨ 5, rfl ⟩ #check evenId #print subtype
f93669940e492fdca9d37a3dd885b074ed0fa4f4
b3fced0f3ff82d577384fe81653e47df68bb2fa1
/src/algebra/ring.lean
5ab2e2cdfd4a4668c82ae81e5ca9826294e5fbaa
[ "Apache-2.0" ]
permissive
ratmice/mathlib
93b251ef5df08b6fd55074650ff47fdcc41a4c75
3a948a6a4cd5968d60e15ed914b1ad2f4423af8d
refs/heads/master
1,599,240,104,318
1,572,981,183,000
1,572,981,183,000
219,830,178
0
0
Apache-2.0
1,572,980,897,000
1,572,980,896,000
null
UTF-8
Lean
false
false
24,479
lean
/- 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, Floris van Doorn, Amelia Livingston -/ import algebra.group import tactic.norm_cast /-! # Properties and homomorphisms of semirings and rings This file proves simple properties of semirings, rings and domains and their unit groups. It also defines homomorphisms of semirings and rings, both unbundled (e.g. `is_semiring_hom f`) and bundled (e.g. `ring_hom a β`, a.k.a. `α →+* β`). The unbundled ones are deprecated and the plan is to slowly remove them from mathlib. ## Main definitions is_semiring_hom (deprecated), is_ring_hom (deprecated), ring_hom, nonzero_comm_semiring, nonzero_comm_ring, domain ## Notations →+* for bundled ring homs (also use for semiring homs) ## Implementation notes There's a coercion from bundled homs to fun, and the canonical notation is to use the bundled hom as a function via this coercion. There is no `semiring_hom` -- the idea is that `ring_hom` is used. The constructor for a `ring_hom` between semirings needs a proof of `map_zero`, `map_one` and `map_add` as well as `map_mul`; a separate constructor `ring_hom.mk'` will construct ring homs between rings from monoid homs given only a proof that addition is preserved. Throughout the section on `ring_hom` implicit `{}` brackets are often used instead of type class `[]` brackets. This is done when the instances can be inferred because they are implicit arguments to the type `ring_hom`. When they can be inferred from the type it is faster to use this method than to use type class inference. ## Tags is_ring_hom, is_semiring_hom, ring_hom, semiring_hom, semiring, comm_semiring, ring, comm_ring, domain, integral_domain, nonzero_comm_semiring, nonzero_comm_ring, units -/ universes u v w variable {α : Type u} section variable [semiring α] theorem mul_two (n : α) : n * 2 = n + n := (left_distrib n 1 1).trans (by simp) theorem bit0_eq_two_mul (n : α) : bit0 n = 2 * n := (two_mul _).symm @[simp] lemma mul_ite {α} [semiring α] (P : Prop) [decidable P] (a : α) : a * (if P then 1 else 0) = if P then a else 0 := by split_ifs; simp variable (α) /-- Either zero and one are nonequal in a semiring, or the semiring is the zero ring. -/ lemma zero_ne_one_or_forall_eq_0 : (0 : α) ≠ 1 ∨ (∀a:α, a = 0) := by haveI := classical.dec; refine not_or_of_imp (λ h a, _); simpa using congr_arg ((*) a) h.symm /-- If zero equals one in a semiring, the semiring is the zero ring. -/ lemma eq_zero_of_zero_eq_one (h : (0 : α) = 1) : (∀a:α, a = 0) := (zero_ne_one_or_forall_eq_0 α).neg_resolve_left h /-- If zero equals one in a semiring, all elements of that semiring are equal. -/ theorem subsingleton_of_zero_eq_one (h : (0 : α) = 1) : subsingleton α := ⟨λa b, by rw [eq_zero_of_zero_eq_one α h a, eq_zero_of_zero_eq_one α h b]⟩ end namespace units variables [ring α] {a b : α} /-- Each element of the group of units of a ring has an additive inverse. -/ instance : has_neg (units α) := ⟨λu, ⟨-↑u, -↑u⁻¹, by simp, by simp⟩ ⟩ /-- Representing an element of a ring's unit group as an element of the ring commutes with mapping this element to its additive inverse. -/ @[simp] protected theorem coe_neg (u : units α) : (↑-u : α) = -u := rfl /-- Mapping an element of a ring's unit group to its inverse commutes with mapping this element to its additive inverse. -/ @[simp] protected theorem neg_inv (u : units α) : (-u)⁻¹ = -u⁻¹ := rfl /-- An element of a ring's unit group equals the additive inverse of its additive inverse. -/ @[simp] protected theorem neg_neg (u : units α) : - -u = u := units.ext $ neg_neg _ /-- Multiplication of elements of a ring's unit group commutes with mapping the first argument to its additive inverse. -/ @[simp] protected theorem neg_mul (u₁ u₂ : units α) : -u₁ * u₂ = -(u₁ * u₂) := units.ext $ neg_mul_eq_neg_mul_symm _ _ /-- Multiplication of elements of a ring's unit group commutes with mapping the second argument to its additive inverse. -/ @[simp] protected theorem mul_neg (u₁ u₂ : units α) : u₁ * -u₂ = -(u₁ * u₂) := units.ext $ (neg_mul_eq_mul_neg _ _).symm /-- Multiplication of the additive inverses of two elements of a ring's unit group equals multiplication of the two original elements. -/ @[simp] protected theorem neg_mul_neg (u₁ u₂ : units α) : -u₁ * -u₂ = u₁ * u₂ := by simp /-- The additive inverse of an element of a ring's unit group equals the additive inverse of one times the original element. -/ protected theorem neg_eq_neg_one_mul (u : units α) : -u = -1 * u := by simp end units instance [semiring α] : semiring (with_zero α) := { left_distrib := λ a b c, begin cases a with a, {refl}, cases b with b; cases c with c; try {refl}, exact congr_arg some (left_distrib _ _ _) end, right_distrib := λ a b c, begin cases c with c, { change (a + b) * 0 = a * 0 + b * 0, simp }, cases a with a; cases b with b; try {refl}, exact congr_arg some (right_distrib _ _ _) end, ..with_zero.add_comm_monoid, ..with_zero.mul_zero_class, ..with_zero.monoid } attribute [refl] dvd_refl attribute [trans] dvd.trans /-- Predicate for semiring homomorphisms (deprecated -- use the bundled `ring_hom` version). -/ class is_semiring_hom {α : Type u} {β : Type v} [semiring α] [semiring β] (f : α → β) : Prop := (map_zero : f 0 = 0) (map_one : f 1 = 1) (map_add : ∀ {x y}, f (x + y) = f x + f y) (map_mul : ∀ {x y}, f (x * y) = f x * f y) namespace is_semiring_hom variables {β : Type v} [semiring α] [semiring β] variables (f : α → β) [is_semiring_hom f] {x y : α} /-- The identity map is a semiring homomorphism. -/ instance id : is_semiring_hom (@id α) := by refine {..}; intros; refl /-- The composition of two semiring homomorphisms is a semiring homomorphism. -/ instance comp {γ} [semiring γ] (g : β → γ) [is_semiring_hom g] : is_semiring_hom (g ∘ f) := { map_zero := by simp [map_zero f]; exact map_zero g, map_one := by simp [map_one f]; exact map_one g, map_add := λ x y, by simp [map_add f]; rw map_add g; refl, map_mul := λ x y, by simp [map_mul f]; rw map_mul g; refl } /-- A semiring homomorphism is an additive monoid homomorphism. -/ instance : is_add_monoid_hom f := { ..‹is_semiring_hom f› } /-- A semiring homomorphism is a monoid homomorphism. -/ instance : is_monoid_hom f := { ..‹is_semiring_hom f› } end is_semiring_hom section variables [ring α] (a b c d e : α) /-- An element of a ring multiplied by the additive inverse of one is the element's additive inverse. -/ lemma mul_neg_one (a : α) : a * -1 = -a := by simp /-- The additive inverse of one multiplied by an element of a ring is the element's additive inverse. -/ lemma neg_one_mul (a : α) : -1 * a = -a := by simp /-- An iff statement following from right distributivity in rings and the definition of subtraction. -/ theorem mul_add_eq_mul_add_iff_sub_mul_add_eq : a * e + c = b * e + d ↔ (a - b) * e + c = d := calc a * e + c = b * e + d ↔ a * e + c = d + b * e : by simp ... ↔ a * e + c - b * e = d : iff.intro (λ h, begin simp [h] end) (λ h, begin simp [h.symm] end) ... ↔ (a - b) * e + c = d : begin simp [@sub_eq_add_neg α, @right_distrib α] end /-- A simplification of one side of an equation exploiting right distributivity in rings and the definition of subtraction. -/ theorem sub_mul_add_eq_of_mul_add_eq_mul_add : a * e + c = b * e + d → (a - b) * e + c = d := assume h, calc (a - b) * e + c = (a * e + c) - b * e : begin simp [@sub_eq_add_neg α, @right_distrib α] end ... = d : begin rw h, simp [@add_sub_cancel α] end /-- If the product of two elements of a ring is nonzero, both elements are nonzero. -/ theorem ne_zero_and_ne_zero_of_mul_ne_zero {a b : α} (h : a * b ≠ 0) : a ≠ 0 ∧ b ≠ 0 := begin split, { intro ha, apply h, simp [ha] }, { intro hb, apply h, simp [hb] } end end /-- Given an element a of a commutative semiring, there exists another element whose product with zero equals a iff a equals zero. -/ @[simp] lemma zero_dvd_iff [comm_semiring α] {a : α} : 0 ∣ a ↔ a = 0 := ⟨eq_zero_of_zero_dvd, λ h, by rw h⟩ section comm_ring variable [comm_ring α] /-- Representation of a difference of two squares in a commutative ring as a product. -/ theorem mul_self_sub_mul_self (a b : α) : a * a - b * b = (a + b) * (a - b) := by rw [add_mul, mul_sub, mul_sub, mul_comm a b, sub_add_sub_cancel] /-- An element a of a commutative ring divides the additive inverse of an element b iff a divides b. -/ @[simp] lemma dvd_neg (a b : α) : (a ∣ -b) ↔ (a ∣ b) := ⟨dvd_of_dvd_neg, dvd_neg_of_dvd⟩ /-- The additive inverse of an element a of a commutative ring divides another element b iff a divides b. -/ @[simp] lemma neg_dvd (a b : α) : (-a ∣ b) ↔ (a ∣ b) := ⟨dvd_of_neg_dvd, neg_dvd_of_dvd⟩ /-- If an element a divides another element c in a commutative ring, a divides the sum of another element b with c iff a divides b. -/ theorem dvd_add_left {a b c : α} (h : a ∣ c) : a ∣ b + c ↔ a ∣ b := (dvd_add_iff_left h).symm /-- If an element a divides another element b in a commutative ring, a divides the sum of b and another element c iff a divides c. -/ theorem dvd_add_right {a b c : α} (h : a ∣ b) : a ∣ b + c ↔ a ∣ c := (dvd_add_iff_right h).symm /-- An element a divides the sum a + b if and only if a divides b.-/ @[simp] lemma dvd_add_self_left {a b : α} : a ∣ a + b ↔ a ∣ b := dvd_add_right (dvd_refl a) /-- An element a divides the sum b + a if and only if a divides b.-/ @[simp] lemma dvd_add_self_right {a b : α} : a ∣ b + a ↔ a ∣ b := dvd_add_left (dvd_refl a) /-- Vieta's formula for a quadratic equation, relating the coefficients of the polynomial with its roots. This particular version states that if we have a root `x` of a monic quadratic polynomial, then there is another root `y` such that `x + y` is negative the `a_1` coefficient and `x * y` is the `a_0` coefficient. -/ lemma Vieta_formula_quadratic {b c x : α} (h : x * x - b * x + c = 0) : ∃ y : α, y * y - b * y + c = 0 ∧ x + y = b ∧ x * y = c := begin have : c = b * x - x * x, { apply eq_of_sub_eq_zero, simpa using h }, use b - x, simp [left_distrib, mul_comm, this], end end comm_ring /-- Predicate for ring homomorphisms (deprecated -- use the bundled `ring_hom` version). -/ class is_ring_hom {α : Type u} {β : Type v} [ring α] [ring β] (f : α → β) : Prop := (map_one : f 1 = 1) (map_mul : ∀ {x y}, f (x * y) = f x * f y) (map_add : ∀ {x y}, f (x + y) = f x + f y) namespace is_ring_hom variables {β : Type v} [ring α] [ring β] /-- A map of rings that is a semiring homomorphism is also a ring homomorphism. -/ lemma of_semiring (f : α → β) [H : is_semiring_hom f] : is_ring_hom f := {..H} variables (f : α → β) [is_ring_hom f] {x y : α} /-- Ring homomorphisms map zero to zero. -/ lemma map_zero : f 0 = 0 := calc f 0 = f (0 + 0) - f 0 : by rw [map_add f]; simp ... = 0 : by simp /-- Ring homomorphisms preserve additive inverses. -/ lemma map_neg : f (-x) = -f x := calc f (-x) = f (-x + x) - f x : by rw [map_add f]; simp ... = -f x : by simp [map_zero f] /-- Ring homomorphisms preserve subtraction. -/ lemma map_sub : f (x - y) = f x - f y := by simp [map_add f, map_neg f] /-- The identity map is a ring homomorphism. -/ instance id : is_ring_hom (@id α) := by refine {..}; intros; refl /-- The composition of two ring homomorphisms is a ring homomorphism. -/ instance comp {γ} [ring γ] (g : β → γ) [is_ring_hom g] : is_ring_hom (g ∘ f) := { map_add := λ x y, by simp [map_add f]; rw map_add g; refl, map_mul := λ x y, by simp [map_mul f]; rw map_mul g; refl, map_one := by simp [map_one f]; exact map_one g } /-- A ring homomorphism is also a semiring homomorphism. -/ instance : is_semiring_hom f := { map_zero := map_zero f, ..‹is_ring_hom f› } instance : is_add_group_hom f := { } end is_ring_hom set_option old_structure_cmd true /-- Bundled semiring homomorphisms; use this for bundled ring homomorphisms too. -/ structure ring_hom (α : Type*) (β : Type*) [semiring α] [semiring β] extends monoid_hom α β, add_monoid_hom α β infixr ` →+* `:25 := ring_hom instance {α : Type*} {β : Type*} {rα : semiring α} {rβ : semiring β} : has_coe_to_fun (α →+* β) := ⟨_, ring_hom.to_fun⟩ instance {α : Type*} {β : Type*} {rα : semiring α} {rβ : semiring β} : has_coe (α →+* β) (α →* β) := ⟨ring_hom.to_monoid_hom⟩ instance {α : Type*} {β : Type*} {rα : semiring α} {rβ : semiring β} : has_coe (α →+* β) (α →+ β) := ⟨ring_hom.to_add_monoid_hom⟩ @[squash_cast] lemma coe_monoid_hom {α : Type*} {β : Type*} {rα : semiring α} {rβ : semiring β} (f : α →+* β) (a : α) : ((f : α →* β) : α → β) a = (f : α → β) a := rfl @[squash_cast] lemma coe_add_monoid_hom {α : Type*} {β : Type*} {rα : semiring α} {rβ : semiring β} (f : α →+* β) (a : α) : ((f : α →+ β) : α → β) a = (f : α → β) a := rfl namespace ring_hom variables {β : Type v} {γ : Type w} [rα : semiring α] [rβ : semiring β] include rα rβ /-- Interpret `f : α → β` with `is_semiring_hom f` as a ring homomorphism. -/ def of (f : α → β) [is_semiring_hom f] : α →+* β := { to_fun := f, .. monoid_hom.of f, .. add_monoid_hom.of f } @[simp] lemma coe_of (f : α → β) [is_semiring_hom f] : ⇑(of f) = f := rfl variables (f : α →+* β) {x y : α} {rα rβ} theorem coe_inj ⦃f g : α →+* β⦄ (h : (f : α → β) = g) : f = g := by cases f; cases g; cases h; refl @[extensionality] theorem ext ⦃f g : α →+* β⦄ (h : ∀ x, f x = g x) : f = g := coe_inj (funext h) theorem ext_iff {f g : α →+* β} : f = g ↔ ∀ x, f x = g x := ⟨λ h x, h ▸ rfl, λ h, ext h⟩ /-- Ring homomorphisms map zero to zero. -/ @[simp] lemma map_zero (f : α →+* β) : f 0 = 0 := f.map_zero' /-- Ring homomorphisms map one to one. -/ @[simp] lemma map_one (f : α →+* β) : f 1 = 1 := f.map_one' /-- Ring homomorphisms preserve addition. -/ @[simp] lemma map_add (f : α →+* β) (a b : α) : f (a + b) = f a + f b := f.map_add' a b /-- Ring homomorphisms preserve multiplication. -/ @[simp] lemma map_mul (f : α →+* β) (a b : α) : f (a * b) = f a * f b := f.map_mul' a b instance (f : α →+* β) : is_semiring_hom f := { map_zero := f.map_zero, map_one := f.map_one, map_add := f.map_add, map_mul := f.map_mul } omit rα rβ instance {α γ} [ring α] [ring γ] (g : α →+* γ) : is_ring_hom g := is_ring_hom.of_semiring g /-- The identity ring homomorphism from a semiring to itself. -/ def id (α : Type*) [semiring α] : α →+* α := by refine {to_fun := id, ..}; intros; refl include rα @[simp] lemma id_apply : ring_hom.id α x = x := rfl variable {rγ : semiring γ} include rβ rγ /-- Composition of ring homomorphisms is a ring homomorphism. -/ def comp (hnp : β →+* γ) (hmn : α →+* β) : α →+* γ := { to_fun := hnp ∘ hmn, map_zero' := by simp, map_one' := by simp, map_add' := λ x y, by simp, map_mul' := λ x y, by simp} @[simp] lemma coe_comp (hnp : β →+* γ) (hmn : α →+* β) : (hnp.comp hmn : α → γ) = hnp ∘ hmn := rfl @[simp] lemma comp_apply (hnp : β →+* γ) (hmn : α →+* β) (x : α) : (hnp.comp hmn : α → γ) x = (hnp (hmn x)) := rfl omit rα rβ rγ /-- Ring homomorphisms preserve additive inverse. -/ @[simp] theorem map_neg {α β} [ring α] [ring β] (f : α →+* β) (x : α) : f (-x) = -(f x) := eq_neg_of_add_eq_zero $ by rw [←f.map_add, neg_add_self, f.map_zero] /-- Ring homomorphisms preserve subtraction. -/ @[simp] theorem map_sub {α β} [ring α] [ring β] (f : α →+* β) (x y : α) : f (x - y) = (f x) - (f y) := by simp include rα /-- Makes a ring homomorphism from a monoid homomorphism of rings which preserves addition. -/ def mk' {γ} [ring γ] (f : α →* γ) (map_add : ∀ a b : α, f (a + b) = f a + f b) : α →+* γ := { to_fun := f, map_zero' := add_self_iff_eq_zero.1 $ by rw [←map_add, add_zero], map_one' := f.map_one, map_mul' := f.map_mul, map_add' := map_add } end ring_hom /-- Predicate for commutative semirings in which zero does not equal one. -/ class nonzero_comm_semiring (α : Type*) extends comm_semiring α, zero_ne_one_class α /-- Predicate for commutative rings in which zero does not equal one. -/ class nonzero_comm_ring (α : Type*) extends comm_ring α, zero_ne_one_class α /-- A nonzero commutative ring is a nonzero commutative semiring. -/ instance nonzero_comm_ring.to_nonzero_comm_semiring {α : Type*} [I : nonzero_comm_ring α] : nonzero_comm_semiring α := { zero_ne_one := by convert zero_ne_one, ..show comm_semiring α, by apply_instance } /-- An integral domain is a nonzero commutative ring. -/ instance integral_domain.to_nonzero_comm_ring (α : Type*) [id : integral_domain α] : nonzero_comm_ring α := { ..id } /-- An element of the unit group of a nonzero commutative semiring represented as an element of the semiring is nonzero. -/ lemma units.coe_ne_zero [nonzero_comm_semiring α] (u : units α) : (u : α) ≠ 0 := λ h : u.1 = 0, by simpa [h, zero_ne_one] using u.3 /-- Makes a nonzero commutative ring from a commutative ring containing at least two distinct elements. -/ def nonzero_comm_ring.of_ne [comm_ring α] {x y : α} (h : x ≠ y) : nonzero_comm_ring α := { one := 1, zero := 0, zero_ne_one := λ h01, h $ by rw [← one_mul x, ← one_mul y, ← h01, zero_mul, zero_mul], ..show comm_ring α, by apply_instance } /-- Makes a nonzero commutative semiring from a commutative semiring containing at least two distinct elements. -/ def nonzero_comm_semiring.of_ne [comm_semiring α] {x y : α} (h : x ≠ y) : nonzero_comm_semiring α := { one := 1, zero := 0, zero_ne_one := λ h01, h $ by rw [← one_mul x, ← one_mul y, ← h01, zero_mul, zero_mul], ..show comm_semiring α, by apply_instance } /-- this is needed for compatibility between Lean 3.4.2 and Lean 3.5.0c -/ def has_div_of_division_ring [division_ring α] : has_div α := division_ring_has_div /-- A domain is a ring with no zero divisors, i.e. satisfying the condition `a * b = 0 ↔ a = 0 ∨ b = 0`. Alternatively, a domain is an integral domain without assuming commutativity of multiplication. -/ class domain (α : Type u) extends ring α, no_zero_divisors α, zero_ne_one_class α section domain variable [domain α] /-- Simplification theorems for the definition of a domain. -/ @[simp] theorem mul_eq_zero {a b : α} : a * b = 0 ↔ a = 0 ∨ b = 0 := ⟨eq_zero_or_eq_zero_of_mul_eq_zero, λo, or.elim o (λh, by rw h; apply zero_mul) (λh, by rw h; apply mul_zero)⟩ @[simp] theorem zero_eq_mul {a b : α} : 0 = a * b ↔ a = 0 ∨ b = 0 := by rw [eq_comm, mul_eq_zero] lemma mul_self_eq_zero {α} [domain α] {x : α} : x * x = 0 ↔ x = 0 := by simp lemma zero_eq_mul_self {α} [domain α] {x : α} : 0 = x * x ↔ x = 0 := by simp /-- The product of two nonzero elements of a domain is nonzero. -/ theorem mul_ne_zero' {a b : α} (h₁ : a ≠ 0) (h₂ : b ≠ 0) : a * b ≠ 0 := λ h, or.elim (eq_zero_or_eq_zero_of_mul_eq_zero h) h₁ h₂ /-- Right multiplication by a nonzero element in a domain is injective. -/ theorem domain.mul_right_inj {a b c : α} (ha : a ≠ 0) : b * a = c * a ↔ b = c := by rw [← sub_eq_zero, ← mul_sub_right_distrib, mul_eq_zero]; simp [ha]; exact sub_eq_zero /-- Left multiplication by a nonzero element in a domain is injective. -/ theorem domain.mul_left_inj {a b c : α} (ha : a ≠ 0) : a * b = a * c ↔ b = c := by rw [← sub_eq_zero, ← mul_sub_left_distrib, mul_eq_zero]; simp [ha]; exact sub_eq_zero /-- An element of a domain fixed by right multiplication by an element other than one must be zero. -/ theorem eq_zero_of_mul_eq_self_right' {a b : α} (h₁ : b ≠ 1) (h₂ : a * b = a) : a = 0 := by apply (mul_eq_zero.1 _).resolve_right (sub_ne_zero.2 h₁); rw [mul_sub_left_distrib, mul_one, sub_eq_zero, h₂] /-- An element of a domain fixed by left multiplication by an element other than one must be zero. -/ theorem eq_zero_of_mul_eq_self_left' {a b : α} (h₁ : b ≠ 1) (h₂ : b * a = a) : a = 0 := by apply (mul_eq_zero.1 _).resolve_left (sub_ne_zero.2 h₁); rw [mul_sub_right_distrib, one_mul, sub_eq_zero, h₂] /-- For elements a, b of a domain, if a*b is nonzero, so is b*a. -/ theorem mul_ne_zero_comm' {a b : α} (h : a * b ≠ 0) : b * a ≠ 0 := mul_ne_zero' (ne_zero_of_mul_ne_zero_left h) (ne_zero_of_mul_ne_zero_right h) end domain /- integral domains -/ section variables [s : integral_domain α] (a b c d e : α) include s /-- An integral domain is a domain. -/ instance integral_domain.to_domain : domain α := {..s} /-- Right multiplcation by a nonzero element of an integral domain is injective. -/ theorem eq_of_mul_eq_mul_right_of_ne_zero {a b c : α} (ha : a ≠ 0) (h : b * a = c * a) : b = c := have b * a - c * a = 0, by simp [h], have (b - c) * a = 0, by rw [mul_sub_right_distrib, this], have b - c = 0, from (eq_zero_or_eq_zero_of_mul_eq_zero this).resolve_right ha, eq_of_sub_eq_zero this /-- Left multiplication by a nonzero element of an integral domain is injective. -/ theorem eq_of_mul_eq_mul_left_of_ne_zero {a b c : α} (ha : a ≠ 0) (h : a * b = a * c) : b = c := have a * b - a * c = 0, by simp [h], have a * (b - c) = 0, by rw [mul_sub_left_distrib, this], have b - c = 0, from (eq_zero_or_eq_zero_of_mul_eq_zero this).resolve_left ha, eq_of_sub_eq_zero this /-- Given two elements b, c of an integral domain and a nonzero element a, a*b divides a*c iff b divides c. -/ theorem mul_dvd_mul_iff_left {a b c : α} (ha : a ≠ 0) : a * b ∣ a * c ↔ b ∣ c := exists_congr $ λ d, by rw [mul_assoc, domain.mul_left_inj ha] /-- Given two elements a, b of an integral domain and a nonzero element c, a*c divides b*c iff a divides b. -/ theorem mul_dvd_mul_iff_right {a b c : α} (hc : c ≠ 0) : a * c ∣ b * c ↔ a ∣ b := exists_congr $ λ d, by rw [mul_right_comm, domain.mul_right_inj hc] /-- In the unit group of an integral domain, a unit is its own inverse iff the unit is one or one's additive inverse. -/ lemma units.inv_eq_self_iff (u : units α) : u⁻¹ = u ↔ u = 1 ∨ u = -1 := by conv {to_lhs, rw [inv_eq_iff_mul_eq_one, ← mul_one (1 : units α), units.ext_iff, units.coe_mul, units.coe_mul, mul_self_eq_mul_self_iff, ← units.ext_iff, ← units.coe_neg, ← units.ext_iff] } end /- units in various rings -/ namespace units section comm_semiring variables [comm_semiring α] (a b : α) (u : units α) /-- Elements of the unit group of a commutative semiring represented as elements of the semiring divide any element of the semiring. -/ @[simp] lemma coe_dvd : ↑u ∣ a := ⟨↑u⁻¹ * a, by simp⟩ /-- In a commutative semiring, an element a divides an element b iff a divides all associates of b. -/ @[simp] lemma dvd_coe_mul : a ∣ b * u ↔ a ∣ b := iff.intro (assume ⟨c, eq⟩, ⟨c * ↑u⁻¹, by rw [← mul_assoc, ← eq, units.mul_inv_cancel_right]⟩) (assume ⟨c, eq⟩, eq.symm ▸ dvd_mul_of_dvd_left (dvd_mul_right _ _) _) /-- An element of a commutative semiring divides a unit iff the element divides one. -/ @[simp] lemma dvd_coe : a ∣ ↑u ↔ a ∣ 1 := suffices a ∣ 1 * ↑u ↔ a ∣ 1, by simpa, dvd_coe_mul _ _ _ /-- In a commutative semiring, an element a divides an element b iff all associates of a divide b.-/ @[simp] lemma coe_mul_dvd : a * u ∣ b ↔ a ∣ b := iff.intro (assume ⟨c, eq⟩, ⟨c * ↑u, eq.symm ▸ by ac_refl⟩) (assume h, suffices a * ↑u ∣ b * 1, by simpa, mul_dvd_mul h (coe_dvd _ _)) end comm_semiring section domain variables [domain α] /-- Every unit in a domain is nonzero. -/ @[simp] theorem ne_zero : ∀(u : units α), (↑u : α) ≠ 0 | ⟨u, v, (huv : 0 * v = 1), hvu⟩ rfl := by simpa using huv end domain end units
d321c303c4f6efa05767fdb4a29e9160982825ab
63abd62053d479eae5abf4951554e1064a4c45b4
/src/topology/path_connected.lean
0b6c9e9a7d2f7d090fe490e845a6360b7adb363d
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
36,452
lean
/- Copyright (c) 2020 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot -/ import topology.instances.real /-! # Path connectedness ## Main definitions In the file the unit interval `[0, 1]` in `ℝ` is denoted by `I`, and `X` is a topological space. * `path (x y : X)` is the type of paths from `x` to `y`, i.e., continuous maps from `I` to `X` mapping `0` to `x` and `1` to `y`. * `path.map` is the image of a path under a continuous map. * `joined (x y : X)` means there is a path between `x` and `y`. * `joined.some_path (h : joined x y)` selects some path between two points `x` and `y`. * `path_component (x : X)` is the set of points joined to `x`. * `path_connected_space X` is a predicate class asserting that `X` is non-empty and every two points of `X` are joined. Then there are corresponding relative notions for `F : set X`. * `joined_in F (x y : X)` means there is a path `γ` joining `x` to `y` with values in `F`. * `joined_in.some_path (h : joined_in F x y)` selects a path from `x` to `y` inside `F`. * `path_component_in F (x : X)` is the set of points joined to `x` in `F`. * `is_path_connected F` asserts that `F` is non-empty and every two points of `F` are joined in `F`. * `loc_path_connected_space X` is a predicate class asserting that `X` is locally path-connected: each point has a basis of path-connected neighborhoods (we do *not* ask these to be open). ## Main theorems * `joined` and `joined_in F` are transitive relations. One can link the absolute and relative version in two directions, using `(univ : set X)` or the subtype `↥F`. * `path_connected_space_iff_univ : path_connected_space X ↔ is_path_connected (univ : set X)` * `is_path_connected_iff_path_connected_space : is_path_connected F ↔ path_connected_space ↥F` For locally path connected spaces, we have * `path_connected_space_iff_connected_space : path_connected_space X ↔ connected_space X` * `is_connected_iff_is_path_connected (U_op : is_open U) : is_path_connected U ↔ is_connected U` ## Implementation notes By default, all paths have `I` as their source and `X` as their target, but there is an operation `I_extend` that will extend any continuous map `γ : I → X` into a continuous map `I_extend γ : ℝ → X` that is constant before `0` and after `1`. This is used to define `path.extend` that turns `γ : path x y` into a continuous map `γ.extend : ℝ → X` whose restriction to `I` is the original `γ`, and is equal to `x` on `(-∞, 0]` and to `y` on `[1, +∞)`. -/ noncomputable theory open_locale classical topological_space filter open filter set function variables {X : Type*} [topological_space X] {x y z : X} {ι : Type*} /-! ### The unit interval -/ local notation `I` := Icc (0 : ℝ) 1 lemma Icc_zero_one_symm {t : ℝ} : t ∈ I ↔ 1 - t ∈ I := begin rw [mem_Icc, mem_Icc], split ; intro ; split ; linarith end instance I_has_zero : has_zero I := ⟨⟨0, by split ; norm_num⟩⟩ @[simp, norm_cast] lemma coe_I_zero : ((0 : I) : ℝ) = 0 := rfl instance I_has_one : has_one I := ⟨⟨1, by split ; norm_num⟩⟩ @[simp, norm_cast] lemma coe_I_one : ((1 : I) : ℝ) = 1 := rfl /-- Unit interval central symmetry. -/ def I_symm : I → I := λ t, ⟨1 - t.val, Icc_zero_one_symm.mp t.property⟩ local notation `σ` := I_symm @[simp] lemma I_symm_zero : σ 0 = 1 := subtype.ext $ by simp [I_symm] @[simp] lemma I_symm_one : σ 1 = 0 := subtype.ext $ by simp [I_symm] @[continuity] lemma continuous_I_symm : continuous σ := by continuity! /-- Projection of `ℝ` onto its unit interval. -/ def proj_I : ℝ → I := λ t, if h : t ≤ 0 then ⟨0, left_mem_Icc.mpr zero_le_one⟩ else if h' : t ≤ 1 then ⟨t, ⟨le_of_lt $ not_le.mp h, h'⟩⟩ else ⟨1, right_mem_Icc.mpr zero_le_one⟩ lemma proj_I_I {t : ℝ} (h : t ∈ I) : proj_I t = ⟨t, h⟩ := begin unfold proj_I, rw mem_Icc at h, split_ifs, { simp [show t = 0, by linarith] }, { refl }, { exfalso, linarith } end lemma proj_I_zero : proj_I 0 = 0 := proj_I_I (⟨le_refl 0, zero_le_one⟩) lemma proj_I_one : proj_I 1 = 1 := proj_I_I (⟨zero_le_one, le_refl 1⟩) lemma surjective_proj_I : surjective proj_I := λ ⟨t, t_in⟩, ⟨t, proj_I_I t_in⟩ lemma range_proj_I : range proj_I = univ := surjective_proj_I.range_eq @[continuity] lemma continuous_proj_I : continuous proj_I := begin refine continuous_induced_rng' (coe : I → ℝ) rfl _, have : continuous (λ t : ℝ, if t ≤ 0 then 0 else if t ≤ 1 then t else 1), { refine continuous_if _ continuous_const (continuous_if _ continuous_id continuous_const) ; simp [Iic_def, zero_le_one] }, convert this, ext, dsimp [proj_I], split_ifs ; refl end variables {β : Type*} /-- Extension of a function defined on the unit interval to `ℝ`, by precomposing with the projection. -/ def I_extend {β : Type*} (f : I → β) : ℝ → β := f ∘ proj_I @[continuity] lemma continuous.I_extend {f : I → X} (hf : continuous f) : continuous (I_extend f) := hf.comp continuous_proj_I lemma I_extend_extends (f : I → β) {t : ℝ} (ht : t ∈ I) : I_extend f t = f ⟨t, ht⟩ := by simp [I_extend, proj_I_I, ht] @[simp] lemma I_extend_zero (f : I → β) : I_extend f 0 = f 0 := I_extend_extends _ _ @[simp] lemma I_extend_one (f : I → β) : I_extend f 1 = f 1 := I_extend_extends _ _ @[simp] lemma I_extend_range (f : I → β) : range (I_extend f) = range f := surjective_proj_I.range_comp f instance : connected_space I := subtype.connected_space ⟨nonempty_Icc.mpr zero_le_one, is_preconnected_Icc⟩ instance : compact_space I := compact_iff_compact_space.1 compact_Icc /-! ### Paths -/ /-- Continuous path connecting two points `x` and `y` in a topological space -/ @[nolint has_inhabited_instance] structure path (x y : X) := (to_fun : I → X) (continuous' : continuous to_fun) (source' : to_fun 0 = x) (target' : to_fun 1 = y) instance : has_coe_to_fun (path x y) := ⟨_, path.to_fun⟩ @[ext] protected lemma path.ext {X : Type*} [topological_space X] {x y : X} : ∀ {γ₁ γ₂ : path x y}, (γ₁ : I → X) = γ₂ → γ₁ = γ₂ | ⟨x, h11, h12, h13⟩ ⟨.(x), h21, h22, h23⟩ rfl := rfl namespace path variable (γ : path x y) @[continuity] protected lemma continuous : continuous γ := γ.continuous' @[simp] protected lemma source : γ 0 = x := γ.source' @[simp] protected lemma target : γ 1 = y := γ.target' /-- Any function `φ : Π (a : α), path (x a) (y a)` can be seen as a function `α × I → X`. -/ instance has_uncurry_path {X α : Type*} [topological_space X] {x y : α → X} : has_uncurry (Π (a : α), path (x a) (y a)) (α × I) X := ⟨λ φ p, φ p.1 p.2⟩ /-- The constant path from a point to itself -/ @[refl] def refl (x : X) : path x x := { to_fun := λ t, x, continuous' := continuous_const, source' := rfl, target' := rfl } @[simp] lemma refl_range {X : Type*} [topological_space X] {a : X} : range (path.refl a) = {a} := by simp [path.refl, has_coe_to_fun.coe, coe_fn] /-- The reverse of a path from `x` to `y`, as a path from `y` to `x` -/ @[symm] def symm (γ : path x y) : path y x := { to_fun := γ ∘ σ, continuous' := by continuity, source' := by simpa [-path.target] using γ.target, target' := by simpa [-path.source] using γ.source } @[simp] lemma refl_symm {X : Type*} [topological_space X] {a : X} : (path.refl a).symm = path.refl a := by { ext, refl } @[simp] lemma symm_range {X : Type*} [topological_space X] {a b : X} (γ : path a b) : range γ.symm = range γ := begin ext x, simp only [ mem_range, path.symm, has_coe_to_fun.coe, coe_fn, I_symm, set_coe.exists, comp_app, subtype.coe_mk, subtype.val_eq_coe ], split; rintros ⟨y, hy, hxy⟩; refine ⟨1-y, Icc_zero_one_symm.mp hy, _⟩; convert hxy, exact sub_sub_cancel _ _ end /-- A continuous map extending a path to `ℝ`, constant before `0` and after `1`. -/ def extend : ℝ → X := I_extend γ lemma continuous_extend : continuous γ.extend := γ.continuous.I_extend @[simp] lemma extend_zero : γ.extend 0 = x := by simp [extend] @[simp] lemma extend_one : γ.extend 1 = y := by simp [extend] @[simp] lemma extend_extends {X : Type*} [topological_space X] {a b : X} (γ : path a b) {t : ℝ} (ht : t ∈ (Icc 0 1 : set ℝ)) : γ.extend t = γ ⟨t, ht⟩ := I_extend_extends γ.to_fun ht @[simp] lemma extend_extends' {X : Type*} [topological_space X] {a b : X} (γ : path a b) (t : (Icc 0 1 : set ℝ)) : γ.extend ↑t = γ t := by { convert γ.extend_extends t.2, rw subtype.ext_iff_val } @[simp] lemma extend_range {X : Type*} [topological_space X] {a b : X} (γ : path a b) : range γ.extend = range γ := I_extend_range γ.to_fun lemma extend_le_zero {X : Type*} [topological_space X] {a b : X} (γ : path a b) {t : ℝ} (ht : t ≤ 0) : γ.extend t = a := begin have := γ.source, simpa [path.extend, I_extend, proj_I, ht] end lemma extend_one_le {X : Type*} [topological_space X] {a b : X} (γ : path a b) {t : ℝ} (ht : 1 ≤ t) : γ.extend t = b := begin simp only [path.extend, I_extend, proj_I, comp_app], split_ifs, { exfalso, linarith }, { convert γ.target, linarith }, { exact γ.target } end @[simp] lemma refl_extend {X : Type*} [topological_space X] {a : X} : (path.refl a).extend = λ _, a := rfl /-- The path obtained from a map defined on `ℝ` by restriction to the unit interval. -/ def of_line {f : ℝ → X} (hf : continuous_on f I) (h₀ : f 0 = x) (h₁ : f 1 = y) : path x y := { to_fun := f ∘ coe, continuous' := hf.comp_continuous continuous_subtype_coe (by rw subtype.range_coe), source' := h₀, target' := h₁ } lemma of_line_mem {f : ℝ → X} (hf : continuous_on f I) (h₀ : f 0 = x) (h₁ : f 1 = y) : ∀ t, of_line hf h₀ h₁ t ∈ f '' I := λ ⟨t, t_in⟩, ⟨t, t_in, rfl⟩ local attribute [simp] Iic_def /-- Concatenation of two paths from `x` to `y` and from `y` to `z`, putting the first path on `[0, 1/2]` and the second one on `[1/2, 1]`. -/ @[trans] def trans (γ : path x y) (γ' : path y z) : path x z := { to_fun := (λ t : ℝ, if t ≤ 1/2 then γ.extend (2*t) else γ'.extend (2*t-1)) ∘ coe, continuous' := begin apply (continuous_if _ _ _).comp continuous_subtype_coe, { norm_num }, -- TODO: the following are provable by `continuity` but it is too slow { exact ((path.continuous γ).comp continuous_proj_I).comp (continuous_const.mul continuous_id')}, { exact ((path.continuous γ').comp continuous_proj_I).comp ((continuous_const.mul continuous_id').sub continuous_const) } end, source' := by norm_num, target' := by norm_num } @[simp] lemma refl_trans_refl {X : Type*} [topological_space X] {a : X} : (path.refl a).trans (path.refl a) = path.refl a := begin ext, simp only [path.trans, if_t_t, one_div, path.refl_extend], refl end lemma trans_range {X : Type*} [topological_space X] {a b c : X} (γ₁ : path a b) (γ₂ : path b c) : range (γ₁.trans γ₂) = range γ₁ ∪ range γ₂ := begin rw path.trans, apply eq_of_subset_of_subset, { rintros x ⟨⟨t, ht0, ht1⟩, hxt⟩, by_cases h : t ≤ 1/2, { left, use [2*t, ⟨by linarith, by linarith⟩], rw ← γ₁.extend_extends, unfold_coes at hxt, simp only [h, comp_app, if_true] at hxt, exact hxt }, { right, use [2*t-1, ⟨by linarith, by linarith⟩], rw ← γ₂.extend_extends, unfold_coes at hxt, simp only [h, comp_app, if_false] at hxt, exact hxt } }, { rintros x (⟨⟨t, ht0, ht1⟩, hxt⟩ | ⟨⟨t, ht0, ht1⟩, hxt⟩), { use ⟨t/2, ⟨by linarith, by linarith⟩⟩, unfold_coes, have : t/2 ≤ 1/2 := by linarith, simp only [this, comp_app, if_true], ring, rwa γ₁.extend_extends }, { by_cases h : t = 0, { use ⟨1/2, ⟨by linarith, by linarith⟩⟩, unfold_coes, simp only [h, comp_app, if_true, le_refl, mul_one_div_cancel (@two_ne_zero ℝ _ _)], rw γ₁.extend_one, rwa [← γ₂.extend_extends, h, γ₂.extend_zero] at hxt }, { use ⟨(t+1)/2, ⟨by linarith, by linarith⟩⟩, unfold_coes, change t ≠ 0 at h, have ht0 := lt_of_le_of_ne ht0 h.symm, have : ¬ (t+1)/2 ≤ 1/2 := by {rw not_le, linarith}, simp only [comp_app, if_false, this], ring, rwa γ₂.extend_extends } } } end /-- Image of a path from `x` to `y` by a continuous map -/ def map (γ : path x y) {Y : Type*} [topological_space Y] {f : X → Y} (h : continuous f) : path (f x) (f y) := { to_fun := f ∘ γ, continuous' := by continuity, source' := by simp, target' := by simp } @[simp] lemma map_coe (γ : path x y) {Y : Type*} [topological_space Y] {f : X → Y} (h : continuous f) : (γ.map h : I → Y) = f ∘ γ := by { ext t, refl } /-- Casting a path from `x` to `y` to a path from `x'` to `y'` when `x' = x` and `y' = y` -/ def cast (γ : path x y) {x' y'} (hx : x' = x) (hy : y' = y) : path x' y' := { to_fun := γ, continuous' := γ.continuous, source' := by simp [hx], target' := by simp [hy] } @[simp] lemma symm_cast {X : Type*} [topological_space X] {a₁ a₂ b₁ b₂ : X} (γ : path a₂ b₂) (ha : a₁ = a₂) (hb : b₁ = b₂) : (γ.cast ha hb).symm = (γ.symm).cast hb ha := rfl @[simp] lemma trans_cast {X : Type*} [topological_space X] {a₁ a₂ b₁ b₂ c₁ c₂ : X} (γ : path a₂ b₂) (γ' : path b₂ c₂) (ha : a₁ = a₂) (hb : b₁ = b₂) (hc : c₁ = c₂) : (γ.cast ha hb).trans (γ'.cast hb hc) = (γ.trans γ').cast ha hc := rfl @[simp] lemma cast_coe (γ : path x y) {x' y'} (hx : x' = x) (hy : y' = y) : (γ.cast hx hy : I → X) = γ := rfl lemma symm_continuous_family {X ι : Type*} [topological_space X] [topological_space ι] {a b : ι → X} (γ : Π (t : ι), path (a t) (b t)) (h : continuous ↿γ) : continuous ↿(λ t, (γ t).symm) := h.comp (continuous_id.prod_map continuous_I_symm) lemma continuous_uncurry_extend_of_continuous_family {X ι : Type*} [topological_space X] [topological_space ι] {a b : ι → X} (γ : Π (t : ι), path (a t) (b t)) (h : continuous ↿γ) : continuous ↿(λ t, (γ t).extend) := h.comp (continuous_id.prod_map continuous_proj_I) lemma trans_continuous_family {X ι : Type*} [topological_space X] [topological_space ι] {a b c : ι → X} (γ₁ : Π (t : ι), path (a t) (b t)) (h₁ : continuous ↿γ₁) (γ₂ : Π (t : ι), path (b t) (c t)) (h₂ : continuous ↿γ₂) : continuous ↿(λ t, (γ₁ t).trans (γ₂ t)) := begin have h₁' := path.continuous_uncurry_extend_of_continuous_family γ₁ h₁, have h₂' := path.continuous_uncurry_extend_of_continuous_family γ₂ h₂, simp [has_uncurry.uncurry, has_coe_to_fun.coe, coe_fn, path.trans], apply continuous_if _ _ _, { rintros st hst, have := frontier_le_subset_eq (continuous_subtype_coe.comp continuous_snd) continuous_const hst, simp only [mem_set_of_eq, comp_app] at this, simp [this, mul_inv_cancel (@two_ne_zero ℝ _ _)] }, { change continuous ((λ p : ι × ℝ, (γ₁ p.1).extend p.2) ∘ (prod.map id (λ x, 2*x : I → ℝ))), exact h₁'.comp (continuous_id.prod_map $ continuous_const.mul continuous_subtype_coe) }, { change continuous ((λ p : ι × ℝ, (γ₂ p.1).extend p.2) ∘ (prod.map id (λ x, 2*x - 1 : I → ℝ))), exact h₂'.comp (continuous_id.prod_map $ (continuous_const.mul continuous_subtype_coe).sub continuous_const) }, end /-! #### Truncating a path -/ /-- `γ.truncate t₀ t₁` is the path which follows the path `γ` on the time interval `[t₀, t₁]` and stays still otherwise. -/ def truncate {X : Type*} [topological_space X] {a b : X} (γ : path a b) (t₀ t₁ : ℝ) : path (γ.extend $ min t₀ t₁) (γ.extend t₁) := { to_fun := λ s, γ.extend (min (max s t₀) t₁), continuous' := γ.continuous_extend.comp ((continuous_subtype_coe.max continuous_const).min continuous_const), source' := begin unfold min max, norm_cast, split_ifs with h₁ h₂ h₃ h₄, { simp [γ.extend_le_zero h₁] }, { congr, linarith }, { have h₄ : t₁ ≤ 0 := le_of_lt (by simpa using h₂), simp [γ.extend_le_zero h₄, γ.extend_le_zero h₁] }, all_goals { refl } end, target' := begin unfold min max, norm_cast, split_ifs with h₁ h₂ h₃, { simp [γ.extend_one_le h₂] }, { refl }, { have h₄ : 1 ≤ t₀ := le_of_lt (by simpa using h₁), simp [γ.extend_one_le h₄, γ.extend_one_le (h₄.trans h₃)] }, { refl } end } /-- `γ.truncate_of_le t₀ t₁ h`, where `h : t₀ ≤ t₁` is `γ.truncate t₀ t₁` casted as a path from `γ.extend t₀` to `γ.extend t₁`. -/ def truncate_of_le {X : Type*} [topological_space X] {a b : X} (γ : path a b) {t₀ t₁ : ℝ} (h : t₀ ≤ t₁) : path (γ.extend t₀) (γ.extend t₁) := (γ.truncate t₀ t₁).cast (by rw min_eq_left h) rfl lemma truncate_range {X : Type*} [topological_space X] {a b : X} (γ : path a b) {t₀ t₁ : ℝ} : range (γ.truncate t₀ t₁) ⊆ range γ := begin rw ← γ.extend_range, simp only [range_subset_iff, set_coe.exists, set_coe.forall], intros x hx, simp only [has_coe_to_fun.coe, coe_fn, path.truncate, mem_range_self] end /-- For a path `γ`, `γ.truncate` gives a "continuous family of paths", by which we mean the uncurried function which maps `(t₀, t₁, s)` to `γ.truncate t₀ t₁ s` is continuous. -/ lemma truncate_continuous_family {X : Type*} [topological_space X] {a b : X} (γ : path a b) : continuous (λ x, γ.truncate x.1 x.2.1 x.2.2 : ℝ × ℝ × I → X) := (γ.continuous.comp continuous_proj_I).comp (((continuous_subtype_coe.comp (continuous_snd.comp continuous_snd)).max continuous_fst).min (continuous_fst.comp continuous_snd)) /- TODO : When `continuity` gets quicker, change the proof back to : `begin` `simp only [has_coe_to_fun.coe, coe_fn, path.truncate],` `continuity,` `exact continuous_subtype_coe` `end` -/ lemma truncate_const_continuous_family {X : Type*} [topological_space X] {a b : X} (γ : path a b) (t : ℝ) : continuous ↿(γ.truncate t) := have key : continuous (λ x, (t, x) : ℝ × I → ℝ × ℝ × I) := continuous_const.prod_mk continuous_id, by convert γ.truncate_continuous_family.comp key @[simp] lemma truncate_self {X : Type*} [topological_space X] {a b : X} (γ : path a b) (t : ℝ) : γ.truncate t t = (path.refl $ γ.extend t).cast (by rw min_self) rfl := begin ext x, rw cast_coe, simp only [truncate, has_coe_to_fun.coe, coe_fn, refl, min, max], split_ifs with h₁ h₂; congr, linarith end @[simp] lemma truncate_zero_zero {X : Type*} [topological_space X] {a b : X} (γ : path a b) : γ.truncate 0 0 = (path.refl a).cast (by rw [min_self, γ.extend_zero]) γ.extend_zero := by convert γ.truncate_self 0; exact γ.extend_zero.symm @[simp] lemma truncate_one_one {X : Type*} [topological_space X] {a b : X} (γ : path a b) : γ.truncate 1 1 = (path.refl b).cast (by rw [min_self, γ.extend_one]) γ.extend_one := by convert γ.truncate_self 1; exact γ.extend_one.symm @[simp] lemma truncate_zero_one {X : Type*} [topological_space X] {a b : X} (γ : path a b) : γ.truncate 0 1 = γ.cast (by simp [zero_le_one, extend_zero]) (by simp) := begin ext x, rw cast_coe, simp only [truncate, has_coe_to_fun.coe, coe_fn, refl, min, max, extend, I_extend, comp_app], congr, have : ↑x ∈ (Icc 0 1 : set ℝ) := x.2, simp [this.1, this.2, proj_I_I this] end end path /-! ### Being joined by a path -/ /-- The relation "being joined by a path". This is an equivalence relation. -/ def joined (x y : X) : Prop := nonempty (path x y) @[refl] lemma joined.refl (x : X) : joined x x := ⟨path.refl x⟩ /-- When two points are joined, choose some path from `x` to `y`. -/ def joined.some_path (h : joined x y) : path x y := nonempty.some h @[symm] lemma joined.symm {x y : X} (h : joined x y) : joined y x := ⟨h.some_path.symm⟩ @[trans] lemma joined.trans {x y z : X} (hxy : joined x y) (hyz : joined y z) : joined x z := ⟨hxy.some_path.trans hyz.some_path⟩ variables (X) /-- The setoid corresponding the equivalence relation of being joined by a continuous path. -/ def path_setoid : setoid X := { r := joined, iseqv := mk_equivalence _ joined.refl (λ x y, joined.symm) (λ x y z, joined.trans) } /-- The quotient type of points of a topological space modulo being joined by a continuous path. -/ def zeroth_homotopy := quotient (path_setoid X) instance : inhabited (zeroth_homotopy ℝ) := ⟨@quotient.mk ℝ (path_setoid ℝ) 0⟩ variables {X} /-! ### Being joined by a path inside a set -/ /-- The relation "being joined by a path in `F`". Not quite an equivalence relation since it's not reflexive for points that do not belong to `F`. -/ def joined_in (F : set X) (x y : X) : Prop := ∃ γ : path x y, ∀ t, γ t ∈ F variables {F : set X} lemma joined_in.mem (h : joined_in F x y) : x ∈ F ∧ y ∈ F := begin rcases h with ⟨γ, γ_in⟩, have : γ 0 ∈ F ∧ γ 1 ∈ F, by { split; apply γ_in }, simpa using this end lemma joined_in.source_mem (h : joined_in F x y) : x ∈ F := h.mem.1 lemma joined_in.target_mem (h : joined_in F x y) : y ∈ F := h.mem.2 /-- When `x` and `y` are joined in `F`, choose a path from `x` to `y` inside `F` -/ def joined_in.some_path (h : joined_in F x y) : path x y := classical.some h lemma joined_in.some_path_mem (h : joined_in F x y) (t : I) : h.some_path t ∈ F := classical.some_spec h t /-- If `x` and `y` are joined in the set `F`, then they are joined in the subtype `F`. -/ lemma joined_in.joined_subtype (h : joined_in F x y) : joined (⟨x, h.source_mem⟩ : F) (⟨y, h.target_mem⟩ : F) := ⟨{ to_fun := λ t, ⟨h.some_path t, h.some_path_mem t⟩, continuous' := by continuity, source' := by simp, target' := by simp }⟩ lemma joined_in.of_line {f : ℝ → X} (hf : continuous_on f I) (h₀ : f 0 = x) (h₁ : f 1 = y) (hF : f '' I ⊆ F) : joined_in F x y := ⟨path.of_line hf h₀ h₁, λ t, hF $ path.of_line_mem hf h₀ h₁ t⟩ lemma joined_in.joined (h : joined_in F x y) : joined x y := ⟨h.some_path⟩ lemma joined_in_iff_joined (x_in : x ∈ F) (y_in : y ∈ F) : joined_in F x y ↔ joined (⟨x, x_in⟩ : F) (⟨y, y_in⟩ : F) := ⟨λ h, h.joined_subtype, λ h, ⟨h.some_path.map continuous_subtype_coe, by simp⟩⟩ @[simp] lemma joined_in_univ : joined_in univ x y ↔ joined x y := by simp [joined_in, joined, exists_true_iff_nonempty] lemma joined_in.mono {U V : set X} (h : joined_in U x y) (hUV : U ⊆ V) : joined_in V x y := ⟨h.some_path, λ t, hUV (h.some_path_mem t)⟩ lemma joined_in.refl (h : x ∈ F) : joined_in F x x := ⟨path.refl x, λ t, h⟩ @[symm] lemma joined_in.symm (h : joined_in F x y) : joined_in F y x := begin cases h.mem with hx hy, simp [joined_in_iff_joined, *] at *, exact h.symm end lemma joined_in.trans (hxy : joined_in F x y) (hyz : joined_in F y z) : joined_in F x z := begin cases hxy.mem with hx hy, cases hyz.mem with hx hy, simp [joined_in_iff_joined, *] at *, exact hxy.trans hyz end /-! ### Path component -/ /-- The path component of `x` is the set of points that can be joined to `x`. -/ def path_component (x : X) := {y | joined x y} @[simp] lemma mem_path_component_self (x : X) : x ∈ path_component x := joined.refl x @[simp] lemma path_component.nonempty (x : X) : (path_component x).nonempty := ⟨x, mem_path_component_self x⟩ lemma mem_path_component_of_mem (h : x ∈ path_component y) : y ∈ path_component x := joined.symm h lemma path_component_symm : x ∈ path_component y ↔ y ∈ path_component x := ⟨λ h, mem_path_component_of_mem h, λ h, mem_path_component_of_mem h⟩ lemma path_component_congr (h : x ∈ path_component y) : path_component x = path_component y := begin ext z, split, { intro h', rw path_component_symm, exact (h.trans h').symm }, { intro h', rw path_component_symm at h' ⊢, exact h'.trans h }, end lemma path_component_subset_component (x : X) : path_component x ⊆ connected_component x := λ y h, subset_connected_component (is_connected_range h.some_path.continuous).2 ⟨0, by simp⟩ ⟨1, by simp⟩ /-- The path component of `x` in `F` is the set of points that can be joined to `x` in `F`. -/ def path_component_in (x : X) (F : set X) := {y | joined_in F x y} @[simp] lemma path_component_in_univ (x : X) : path_component_in x univ = path_component x := by simp [path_component_in, path_component, joined_in, joined, exists_true_iff_nonempty] lemma joined.mem_path_component (hyz : joined y z) (hxy : y ∈ path_component x) : z ∈ path_component x := hxy.trans hyz /-! ### Path connected sets -/ /-- A set `F` is path connected if it contains a point that can be joined to all other in `F`. -/ def is_path_connected (F : set X) : Prop := ∃ x ∈ F, ∀ {y}, y ∈ F → joined_in F x y lemma is_path_connected_iff_eq : is_path_connected F ↔ ∃ x ∈ F, path_component_in x F = F := begin split ; rintros ⟨x, x_in, h⟩ ; use [x, x_in], { ext y, exact ⟨λ hy, hy.mem.2, h⟩ }, { intros y y_in, rwa ← h at y_in }, end lemma is_path_connected.joined_in (h : is_path_connected F) : ∀ x y ∈ F, joined_in F x y := λ x y x_in y_in, let ⟨b, b_in, hb⟩ := h in (hb x_in).symm.trans (hb y_in) lemma is_path_connected_iff : is_path_connected F ↔ F.nonempty ∧ ∀ x y ∈ F, joined_in F x y := ⟨λ h, ⟨let ⟨b, b_in, hb⟩ := h in ⟨b, b_in⟩, h.joined_in⟩, λ ⟨⟨b, b_in⟩, h⟩, ⟨b, b_in, λ x x_in, h b x b_in x_in⟩⟩ lemma is_path_connected.image {Y : Type*} [topological_space Y] (hF : is_path_connected F) {f : X → Y} (hf : continuous f) : is_path_connected (f '' F) := begin rcases hF with ⟨x, x_in, hx⟩, use [f x, mem_image_of_mem f x_in], rintros _ ⟨y, y_in, rfl⟩, exact ⟨(hx y_in).some_path.map hf, λ t, ⟨_, (hx y_in).some_path_mem t, rfl⟩⟩, end lemma is_path_connected.mem_path_component (h : is_path_connected F) (x_in : x ∈ F) (y_in : y ∈ F) : y ∈ path_component x := (h.joined_in x y x_in y_in).joined lemma is_path_connected.subset_path_component (h : is_path_connected F) (x_in : x ∈ F) : F ⊆ path_component x := λ y y_in, h.mem_path_component x_in y_in lemma is_path_connected.union {U V : set X} (hU : is_path_connected U) (hV : is_path_connected V) (hUV : (U ∩ V).nonempty) : is_path_connected (U ∪ V) := begin rcases hUV with ⟨x, xU, xV⟩, use [x, or.inl xU], rintros y (yU | yV), { exact (hU.joined_in x y xU yU).mono (subset_union_left U V) }, { exact (hV.joined_in x y xV yV).mono (subset_union_right U V) }, end /-- If a set `W` is path-connected, then it is also path-connected when seen as a set in a smaller ambient type `U` (when `U` contains `W`). -/ lemma is_path_connected.preimage_coe {U W : set X} (hW : is_path_connected W) (hWU : W ⊆ U) : is_path_connected ((coe : U → X) ⁻¹' W) := begin rcases hW with ⟨x, x_in, hx⟩, use [⟨x, hWU x_in⟩, by simp [x_in]], rintros ⟨y, hyU⟩ hyW, exact ⟨(hx hyW).joined_subtype.some_path.map (continuous_inclusion hWU), by simp⟩ end lemma is_path_connected.exists_path_through_family {X : Type*} [topological_space X] {n : ℕ} {s : set X} (h : is_path_connected s) (p : fin (n+1) → X) (hp : ∀ i, p i ∈ s) : ∃ γ : path (p 0) (p n), (range γ ⊆ s) ∧ (∀ i, p i ∈ range γ) := begin let p' : ℕ → X := λ k, if h : k < n+1 then p ⟨k, h⟩ else p ⟨0, n.zero_lt_succ⟩, obtain ⟨γ, hγ⟩ : ∃ (γ : path (p' 0) (p' n)), (∀ i ≤ n, p' i ∈ range γ) ∧ range γ ⊆ s, { have hp' : ∀ i ≤ n, p' i ∈ s, { intros i hi, simp [p', nat.lt_succ_of_le hi, hp] }, clear_value p', clear hp p, induction n with n hn, { use (λ _, p' 0), { continuity }, { split, { rintros i hi, rw nat.le_zero_iff.mp hi, exact ⟨0, rfl⟩ }, { rw range_subset_iff, rintros x, exact hp' 0 (le_refl _) } } }, { rcases hn (λ i hi, hp' i $ nat.le_succ_of_le hi) with ⟨γ₀, hγ₀⟩, rcases h.joined_in (p' n) (p' $ n+1) (hp' n n.le_succ) (hp' (n+1) $ le_refl _) with ⟨γ₁, hγ₁⟩, let γ : path (p' 0) (p' $ n+1) := γ₀.trans γ₁, use γ, have range_eq : range γ = range γ₀ ∪ range γ₁ := γ₀.trans_range γ₁, split, { rintros i hi, by_cases hi' : i ≤ n, { rw range_eq, left, exact hγ₀.1 i hi' }, { rw [not_le, ← nat.succ_le_iff] at hi', have : i = n.succ := by linarith, rw this, use 1, exact γ.target } }, { rw range_eq, apply union_subset hγ₀.2, rw range_subset_iff, exact hγ₁ } } }, have hpp' : ∀ k < n+1, p k = p' k, { intros k hk, simp only [p', hk, dif_pos], congr, ext, rw fin.coe_coe_of_lt hk, norm_cast }, use γ.cast (hpp' 0 n.zero_lt_succ) (hpp' n n.lt_succ_self), simp only [γ.cast_coe], refine and.intro hγ.2 _, rintros ⟨i, hi⟩, convert hγ.1 i (nat.le_of_lt_succ hi), rw ← hpp' i hi, congr, ext, rw fin.coe_coe_of_lt hi, norm_cast end lemma is_path_connected.exists_path_through_family' {X : Type*} [topological_space X] {n : ℕ} {s : set X} (h : is_path_connected s) (p : fin (n+1) → X) (hp : ∀ i, p i ∈ s) : ∃ (γ : path (p 0) (p n)) (t : fin (n + 1) → I), (∀ t, γ t ∈ s) ∧ ∀ i, γ (t i) = p i := begin rcases h.exists_path_through_family p hp with ⟨γ, hγ⟩, rcases hγ with ⟨h₁, h₂⟩, simp only [range, mem_set_of_eq] at h₂, rw range_subset_iff at h₁, choose! t ht using h₂, exact ⟨γ, t, h₁, ht⟩ end /-! ### Path connected spaces -/ /-- A topological space is path-connected if it is non-empty and every two points can be joined by a continuous path. -/ class path_connected_space (X : Type*) [topological_space X] : Prop := (nonempty : nonempty X) (joined : ∀ x y : X, joined x y) attribute [instance, priority 50] path_connected_space.nonempty lemma path_connected_space_iff_zeroth_homotopy : path_connected_space X ↔ nonempty (zeroth_homotopy X) ∧ subsingleton (zeroth_homotopy X) := begin letI := path_setoid X, split, { introI h, refine ⟨(nonempty_quotient_iff _).mpr h.1, ⟨_⟩⟩, rintros ⟨x⟩ ⟨y⟩, exact quotient.sound (path_connected_space.joined x y) }, { unfold zeroth_homotopy, rintros ⟨h, h'⟩, resetI, exact ⟨(nonempty_quotient_iff _).mp h, λ x y, quotient.exact $ subsingleton.elim ⟦x⟧ ⟦y⟧⟩ }, end namespace path_connected_space variables [path_connected_space X] /-- Use path-connectedness to build a path between two points. -/ def some_path (x y : X) : path x y := nonempty.some (joined x y) end path_connected_space lemma is_path_connected_iff_path_connected_space : is_path_connected F ↔ path_connected_space F := begin rw is_path_connected_iff, split, { rintro ⟨⟨x, x_in⟩, h⟩, refine ⟨⟨⟨x, x_in⟩⟩, _⟩, rintros ⟨y, y_in⟩ ⟨z, z_in⟩, have H := h y z y_in z_in, rwa joined_in_iff_joined y_in z_in at H }, { rintros ⟨⟨x, x_in⟩, H⟩, refine ⟨⟨x, x_in⟩, λ y z y_in z_in, _⟩, rw joined_in_iff_joined y_in z_in, apply H } end lemma path_connected_space_iff_univ : path_connected_space X ↔ is_path_connected (univ : set X) := begin split, { introI h, inhabit X, refine ⟨default X, mem_univ _, _⟩, simpa using path_connected_space.joined (default X) }, { intro h, have h' := h.joined_in, cases h with x h, exact ⟨⟨x⟩, by simpa using h'⟩ }, end lemma path_connected_space_iff_eq : path_connected_space X ↔ ∃ x : X, path_component x = univ := by simp [path_connected_space_iff_univ, is_path_connected_iff_eq] @[priority 100] -- see Note [lower instance priority] instance path_connected_space.connected_space [path_connected_space X] : connected_space X := begin rw connected_space_iff_connected_component, rcases is_path_connected_iff_eq.mp (path_connected_space_iff_univ.mp ‹_›) with ⟨x, x_in, hx⟩, use x, rw ← univ_subset_iff, exact (by simpa using hx : path_component x = univ) ▸ path_component_subset_component x end namespace path_connected_space variables [path_connected_space X] lemma exists_path_through_family {n : ℕ} (p : fin (n+1) → X) : ∃ γ : path (p 0) (p n), (∀ i, p i ∈ range γ) := begin have : is_path_connected (univ : set X) := path_connected_space_iff_univ.mp (by apply_instance), rcases this.exists_path_through_family p (λ i, true.intro) with ⟨γ, -, h⟩, exact ⟨γ, h⟩ end lemma exists_path_through_family' {n : ℕ} (p : fin (n+1) → X) : ∃ (γ : path (p 0) (p n)) (t : fin (n + 1) → I), ∀ i, γ (t i) = p i := begin have : is_path_connected (univ : set X) := path_connected_space_iff_univ.mp (by apply_instance), rcases this.exists_path_through_family' p (λ i, true.intro) with ⟨γ, t, -, h⟩, exact ⟨γ, t, h⟩ end end path_connected_space /-! ### Locally path connected spaces -/ /-- A topological space is locally path connected, at every point, path connected neighborhoods form a neighborhood basis. -/ class loc_path_connected_space (X : Type*) [topological_space X] : Prop := (path_connected_basis : ∀ x : X, (𝓝 x).has_basis (λ s : set X, s ∈ 𝓝 x ∧ is_path_connected s) id) export loc_path_connected_space (path_connected_basis) lemma loc_path_connected_of_bases {p : ι → Prop} {s : X → ι → set X} (h : ∀ x, (𝓝 x).has_basis p (s x)) (h' : ∀ x i, p i → is_path_connected (s x i)) : loc_path_connected_space X := begin constructor, intro x, apply (h x).to_has_basis, { intros i pi, exact ⟨s x i, ⟨(h x).mem_of_mem pi, h' x i pi⟩, by refl⟩ }, { rintros U ⟨U_in, hU⟩, rcases (h x).mem_iff.mp U_in with ⟨i, pi, hi⟩, tauto } end lemma path_connected_space_iff_connected_space [loc_path_connected_space X] : path_connected_space X ↔ connected_space X := begin split, { introI h, apply_instance }, { introI hX, inhabit X, let x₀ := default X, rw path_connected_space_iff_eq, use x₀, refine eq_univ_of_nonempty_clopen (by simp) ⟨_, _⟩, { rw is_open_iff_mem_nhds, intros y y_in, rcases (path_connected_basis y).ex_mem with ⟨U, ⟨U_in, hU⟩⟩, apply mem_sets_of_superset U_in, rw ← path_component_congr y_in, exact hU.subset_path_component (mem_of_nhds U_in) }, { rw is_closed_iff_nhds, intros y H, rcases (path_connected_basis y).ex_mem with ⟨U, ⟨U_in, hU⟩⟩, rcases H U U_in with ⟨z, hz, hz'⟩, exact ((hU.joined_in z y hz $ mem_of_nhds U_in).joined.mem_path_component hz') } }, end lemma path_connected_subset_basis [loc_path_connected_space X] {U : set X} (h : is_open U) (hx : x ∈ U) : (𝓝 x).has_basis (λ s : set X, s ∈ 𝓝 x ∧ is_path_connected s ∧ s ⊆ U) id := (path_connected_basis x).has_basis_self_subset (mem_nhds_sets h hx) lemma loc_path_connected_of_is_open [loc_path_connected_space X] {U : set X} (h : is_open U) : loc_path_connected_space U := ⟨begin rintros ⟨x, x_in⟩, rw nhds_subtype_eq_comap, constructor, intros V, rw (has_basis.comap (coe : U → X) (path_connected_subset_basis h x_in)).mem_iff, split, { rintros ⟨W, ⟨W_in, hW, hWU⟩, hWV⟩, exact ⟨coe ⁻¹' W, ⟨⟨preimage_mem_comap W_in, hW.preimage_coe hWU⟩, hWV⟩⟩ }, { rintros ⟨W, ⟨W_in, hW⟩, hWV⟩, refine ⟨coe '' W, ⟨filter.image_coe_mem_sets (mem_nhds_sets h x_in) W_in, hW.image continuous_subtype_coe, subtype.coe_image_subset U W⟩, _⟩, rintros x ⟨y, ⟨y_in, hy⟩⟩, rw ← subtype.coe_injective hy, tauto }, end⟩ lemma is_open.is_connected_iff_is_path_connected [loc_path_connected_space X] {U : set X} (U_op : is_open U) : is_path_connected U ↔ is_connected U := begin rw [is_connected_iff_connected_space, is_path_connected_iff_path_connected_space], haveI := loc_path_connected_of_is_open U_op, exact path_connected_space_iff_connected_space end
f2991c6fc75678f60b2d4e42fd628a2cab46d101
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/stage0/src/Lean/Elab/Level.lean
50f64259a3e18dfcb5fbe0e78740cd1ef2739cc5
[ "Apache-2.0" ]
permissive
WojciechKarpiel/lean4
7f89706b8e3c1f942b83a2c91a3a00b05da0e65b
f6e1314fa08293dea66a329e05b6c196a0189163
refs/heads/master
1,686,633,402,214
1,625,821,189,000
1,625,821,258,000
384,640,886
0
0
Apache-2.0
1,625,903,617,000
1,625,903,026,000
null
UTF-8
Lean
false
false
3,294
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.LevelDefEq import Lean.Elab.Exception import Lean.Elab.Log import Lean.Elab.AutoBound namespace Lean.Elab.Level structure Context where options : Options ref : Syntax autoBoundImplicit : Bool structure State where ngen : NameGenerator mctx : MetavarContext levelNames : List Name abbrev LevelElabM := ReaderT Context (EStateM Exception State) instance : MonadOptions LevelElabM where getOptions := return (← read).options instance : MonadRef LevelElabM where getRef := return (← read).ref withRef ref x := withReader (fun ctx => { ctx with ref := ref }) x instance : AddMessageContext LevelElabM where addMessageContext msg := pure msg instance : MonadNameGenerator LevelElabM where getNGen := return (← get).ngen setNGen ngen := modify fun s => { s with ngen := ngen } def mkFreshLevelMVar : LevelElabM Level := do let mvarId ← mkFreshId modify fun s => { s with mctx := s.mctx.addLevelMVarDecl mvarId } return mkLevelMVar mvarId register_builtin_option maxUniverseOffset : Nat := { defValue := 32 descr := "maximum universe level offset" } private def checkUniverseOffset [Monad m] [MonadError m] [MonadOptions m] (n : Nat) : m Unit := do let max := maxUniverseOffset.get (← getOptions) unless n <= max do throwError "maximum universe level offset threshold ({max}) has been reached, you can increase the limit using option `set_option maxUniverseOffset <limit>`, but you are probably misusing universe levels since offsets are usually small natural numbers" partial def elabLevel (stx : Syntax) : LevelElabM Level := withRef stx do let kind := stx.getKind if kind == `Lean.Parser.Level.paren then elabLevel (stx.getArg 1) else if kind == `Lean.Parser.Level.max then let args := stx.getArg 1 |>.getArgs args[:args.size - 1].foldrM (init := ← elabLevel args.back) fun stx lvl => return mkLevelMax' (← elabLevel stx) lvl else if kind == `Lean.Parser.Level.imax then let args := stx.getArg 1 |>.getArgs args[:args.size - 1].foldrM (init := ← elabLevel args.back) fun stx lvl => return mkLevelIMax' (← elabLevel stx) lvl else if kind == `Lean.Parser.Level.hole then mkFreshLevelMVar else if kind == numLitKind then match stx.isNatLit? with | some val => checkUniverseOffset val; return Level.ofNat val | none => throwIllFormedSyntax else if kind == identKind then let paramName := stx.getId unless (← get).levelNames.contains paramName do if (← read).autoBoundImplicit && isValidAutoBoundLevelName paramName then modify fun s => { s with levelNames := paramName :: s.levelNames } else throwError "unknown universe level '{paramName}'" return mkLevelParam paramName else if kind == `Lean.Parser.Level.addLit then let lvl ← elabLevel (stx.getArg 0) match stx.getArg 2 |>.isNatLit? with | some val => checkUniverseOffset val; return lvl.addOffset val | none => throwIllFormedSyntax else throwError "unexpected universe level syntax kind" end Lean.Elab.Level
6ad2bce75dfe18c16aa350d90d1d4c8b728af937
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/1898.lean
c1c2cbc8b53727cab06a24899b37b2ffb28eaf2e
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
41
lean
def X (R : Type) [H : has_zero R] := H.0
74805de75448f83be71e1cd1361a21c4c5665358
e07b1aca72e83a272dd59d24c6e0fa246034d774
/src/tutorials/07_first_negations.lean
2ff7cf1f56689df77c631ead315d0aa0d0d3cd0a
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
pedrominicz/learn
637a343bd4f8669d76819ac660a2d2d3e0958710
b79b802a9846c86c21d4b6f3e17af36e7382f0ef
refs/heads/master
1,671,746,990,402
1,670,778,113,000
1,670,778,113,000
265,735,177
1
0
null
null
null
null
UTF-8
Lean
false
false
9,599
lean
import tuto_lib import data.int.parity /- Negations, proof by contradiction and contraposition. This file introduces the logical rules and tactics related to negation: exfalso, by_contradiction, contrapose, by_cases and push_neg. There is a special statement denoted by `false` which, by definition, has no proof. So `false` implies everything. Indeed `false → P` means any proof of `false` could be turned into a proof of P. This fact is known by its latin name "ex falso quod libet" (from false follows whatever you want). Hence Lean's tactic to invoke this is called `exfalso`. -/ example : false → 0 = 1 := begin intro h, exfalso, exact h, end /- The preceding example suggests that this definition of `false` isn't very useful. But actually it allows us to define the negation of a statement P as "P implies false" that we can read as "if P were true, we would get a contradiction". Lean denotes this by `¬ P`. One can prove that (¬ P) ↔ (P ↔ false). But in practice we directly use the definition of `¬ P`. -/ example {x : ℝ} : ¬ x < x := by { rw lt_iff_le_and_ne, cc } example {x : ℝ} : ¬ x < x := begin intro hyp, rw lt_iff_le_and_ne at hyp, cases hyp with hyp_inf hyp_non, clear hyp_inf, -- we won't use that one, so let's discard it change x = x → false at hyp_non, -- Lean doesn't need this psychological line apply hyp_non, refl, end open int -- 0045 example (n : ℤ) (h_pair : even n) (h_non_pair : ¬ even n) : 0 = 1 := by cc -- 0046 example (P Q : Prop) (h₁ : P ∨ Q) (h₂ : ¬ (P ∧ Q)) : ¬ P ↔ Q := begin split, { intro h₃, cases h₁ with p q, { exfalso, apply h₃, assumption }, { assumption } }, { intro h₃, cases h₁ with p q, { exfalso, apply h₂, split; assumption }, { intro q, apply h₂, split; assumption } } end /- The definition of negation easily implies that, for every statement P, P → ¬ ¬ P The excluded middle axiom, which asserts P ∨ ¬ P allows us to prove the converse implication. Together those two implications form the principle of double negation elimination. not_not {P : Prop} : (¬ ¬ P) ↔ P The implication `¬ ¬ P → P` is the basis for proofs by contradiction: in order to prove P, it suffices to prove ¬¬ P, ie `¬ P → false`. Of course there is no need to keep explaining all this. The tactic `by_contradiction Hyp` will transform any goal P into `false` and add Hyp : ¬ P to the local context. Let's return to a proof from the 5th file: uniqueness of limits for a sequence. This cannot be proved without using some version of the excluded middle axiom. We used it secretely in eq_of_abs_sub_le_all (x y : ℝ) : (∀ ε > 0, |x - y| ≤ ε) → x = y (we'll prove a variation on this lemma below). -/ example (u : ℕ → ℝ) (l l' : ℝ) : seq_limit u l → seq_limit u l' → l = l' := begin intros hl hl', by_contra h, change l ≠ l' at h, have h₁ : |l - l'| > 0, { apply abs_pos_of_ne_zero, apply sub_ne_zero_of_ne, assumption }, set ε := |l - l'| / 4 with hε, cases hl ε (by linarith) with N hN, cases hl' ε (by linarith) with N' hN', let N := max N N', specialize hN N le_sup_left, specialize hN' N le_sup_right, have h₂ : |l - l'| < |l - l'|, calc |l - l'| = |(l - u N) + (u N - l')| : by ring ... ≤ |l - u N| + |u N - l'| : by apply abs_add ... ≤ |u N - l| + |u N - l'| : by rw abs_sub ... < |l - l'| : by linarith, linarith end example (u : ℕ → ℝ) (l l' : ℝ) : seq_limit u l → seq_limit u l' → l = l' := begin intros hl hl', by_contradiction H, change l ≠ l' at H, -- Lean does not need this line have ineg : |l-l'| > 0, exact abs_pos_of_ne_zero (sub_ne_zero_of_ne H), cases hl ( |l-l'|/4 ) (by linarith) with N hN, cases hl' ( |l-l'|/4 ) (by linarith) with N' hN', let N₀ := max N N', -- this is a new tactic, whose effect should be clear specialize hN N₀ (le_max_left _ _), specialize hN' N₀ (le_max_right _ _), have clef : |l-l'| < |l-l'|, calc |l - l'| = |(l-u N₀) + (u N₀ -l')| : by ring ... ≤ |l - u N₀| + |u N₀ - l'| : by apply abs_add ... = |u N₀ - l| + |u N₀ - l'| : by rw abs_sub ... < |l-l'| : by linarith, linarith, -- linarith can also find simple numerical contradictions end /- Another incarnation of the excluded middle axiom is the principle of contraposition: in order to prove P ⇒ Q, it suffices to prove non Q ⇒ non P. -/ -- Using a proof by contradiction, let's prove the contraposition principle -- 0047 example (P Q : Prop) (h : ¬ Q → ¬ P) : P → Q := begin intro p, by_contra hq, apply h; assumption end /- Again Lean doesn't need to be explain this principle. We can use the `contrapose` tactic. -/ example (P Q : Prop) (h : ¬ Q → ¬ P) : P → Q := begin contrapose, exact h, end /- In the next exercise, we'll use odd n : ∃ k, n = 2*k + 1 not_even_iff_odd : ¬ even n ↔ odd n, -/ -- 0048 example (n : ℤ) : even (n^2) ↔ even n := begin rw pow_two, split, { contrapose, repeat { rw not_even_iff_odd }, rintros ⟨k, rfl⟩, set a := 2 * k with ha, use k * (a + 2), rw ha, ring }, { rintros ⟨k, rfl⟩, use 2 * k * k, ring } end /- As a last step on our law of the excluded middle tour, let's notice that, especially in pure logic exercises, it can sometimes be useful to use the excluded middle axiom in its original form: classical.em : ∀ P, P ∨ ¬ P Instead of applying this lemma and then using the `cases` tactic, we have the shortcut by_cases h : P, combining both steps to create two proof branches: one assuming h : P, and the other assuming h : ¬ P For instance, let's prove a reformulation of this implication relation, which is sometimes used as a definition in other logical foundations, especially those based on truth tables (hence very strongly using excluded middle from the very beginning). -/ variables (P Q : Prop) example : (P → Q) ↔ (¬ P ∨ Q) := begin split; intros h, { by_cases hq : Q, { right, assumption }, { left, exact λ p, hq (h p) } }, { intro p, cases h with hp q, { exfalso, apply hp, assumption }, { assumption } } end example : (P → Q) ↔ (¬ P ∨ Q) := begin split, { intro h, by_cases hP : P, { right, exact h hP }, { left, exact hP } }, { intros h hP, cases h with hnP hQ, { exfalso, exact hnP hP }, { exact hQ } }, end -- 0049 example : ¬ (P ∧ Q) ↔ ¬ P ∨ ¬ Q := begin split, { intro h, by_cases hp : P, { right, intro q, apply h, split; assumption }, { left; assumption } }, { rintros h ⟨p, q⟩, cases h; cc } end /- It is crucial to understand negation of quantifiers. Let's do it by hand for a little while. In the first exercise, only the definition of negation is needed. -/ -- 0050 example (n : ℤ) : ¬ (∃ k, n = 2*k) ↔ ∀ k, n ≠ 2*k := begin split; intro h, { intros k hk, exact h ⟨k, hk⟩ }, { rintro ⟨k, hk⟩, exact h k hk } end /- Contrary to negation of the existential quantifier, negation of the universal quantifier requires excluded middle for the first implication. In order to prove this, we can use either * a double proof by contradiction * a contraposition, not_not : (¬ ¬ P) ↔ P) and a proof by contradiction. -/ def even_fun (f : ℝ → ℝ) := ∀ x, f (-x) = f x -- 0051 example (f : ℝ → ℝ) : ¬ even_fun f ↔ ∃ x, f (-x) ≠ f x := begin split, { intro h₁, by_contra h₂, apply h₁, intro x, by_contra h₃, apply h₂, use x; assumption }, { rintros ⟨x, hx⟩ hf, apply hx, apply hf } end example (f : ℝ → ℝ) : ¬ even_fun f ↔ ∃ x, f (-x) ≠ f x := begin split, { contrapose, intro h, rw not_not, intro x, by_contra, apply h, use x; assumption }, { contrapose, rw not_not, intro h, -- It sucks that the anonymous contructor syntax isn't "builtin enough" in -- Lean, so I can't write `by_contra ⟨x, hx⟩`. by_contra this, cases this with x hx, apply hx, apply h } end /- Of course we can't keep repeating the above proofs, especially the second one. So we use the `push_neg` tactic. -/ example : ¬ even_fun (λ x, 2*x) := begin unfold even_fun, -- Here unfolding is important because push_neg won't do it. push_neg, use 42, linarith, end -- 0052 example (f : ℝ → ℝ) : ¬ even_fun f ↔ ∃ x, f (-x) ≠ f x := begin unfold even_fun, push_neg end def bounded_above (f : ℝ → ℝ) := ∃ M, ∀ x, f x ≤ M example : ¬ bounded_above (λ x, x) := begin unfold bounded_above, push_neg, intro M, use M + 1, linarith, end -- Let's contrapose -- 0053 example (x : ℝ) : (∀ ε > 0, x ≤ ε) → x ≤ 0 := begin contrapose, push_neg, intro h, use x/2, split; linarith end /- The "contrapose, push_neg" combo is so common that we can abreviate it to `contrapose!` Let's use this trick, together with: eq_or_lt_of_le : a ≤ b → a = b ∨ a < b -/ -- 0054 example (f : ℝ → ℝ) : (∀ x y, x < y → f x < f y) ↔ (∀ x y, (x ≤ y ↔ f x ≤ f y)) := begin split, { intros hf x y, split, { intro h, cases eq_or_lt_of_le h with h h, { rw h }, { linarith [hf x y h] } }, { contrapose!, apply hf } }, { intros hf x y, contrapose!, intro h, rwa hf } end
98d2f6879732c135cd06204c807abf6ea30148ea
82e44445c70db0f03e30d7be725775f122d72f3e
/src/analysis/calculus/fderiv.lean
d0411a26962e48172eaae1c68ed10e75411fa709
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
123,676
lean
/- 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 analysis.analytic.basic import analysis.asymptotics.asymptotic_equivalent import analysis.calculus.tangent_cone import analysis.normed_space.bounded_linear_maps import analysis.normed_space.units /-! # The Fréchet derivative Let `E` and `F` be normed spaces, `f : E → F`, and `f' : E →L[𝕜] F` a continuous 𝕜-linear map, where `𝕜` is a non-discrete normed field. Then `has_fderiv_within_at f f' s x` says that `f` has derivative `f'` at `x`, where the domain of interest is restricted to `s`. We also have `has_fderiv_at f f' x := has_fderiv_within_at f f' x univ` Finally, `has_strict_fderiv_at f f' x` means that `f : E → F` has derivative `f' : E →L[𝕜] F` in the sense of strict differentiability, i.e., `f y - f z - f'(y - z) = o(y - z)` as `y, z → x`. This notion is used in the inverse function theorem, and is defined here only to avoid proving theorems like `is_bounded_bilinear_map.has_fderiv_at` twice: first for `has_fderiv_at`, then for `has_strict_fderiv_at`. ## Main results In addition to the definition and basic properties of the derivative, this file contains the usual formulas (and existence assertions) for the derivative of * constants * the identity * bounded linear maps * bounded bilinear maps * sum of two functions * sum of finitely many functions * multiplication of a function by a scalar constant * negative of a function * subtraction of two functions * multiplication of a function by a scalar function * multiplication of two scalar functions * composition of functions (the chain rule) * inverse function (assuming that it exists; the inverse function theorem is in `inverse.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 `has_deriv_at`'s easier, and they more frequently lead to the desired result. One can also interpret the derivative of a function `f : 𝕜 → E` as an element of `E` (by identifying a linear function from `𝕜` to `E` with its value at `1`). Results on the Fréchet derivative are translated to this more elementary point of view on the derivative in the file `deriv.lean`. The derivative of polynomials is handled there, as it is naturally one-dimensional. The simplifier is set up to prove automatically that some functions are differentiable, or differentiable at a point (but not differentiable on a set or within a set at a point, as checking automatically that the good domains are mapped one to the other when using composition is not something the simplifier can easily do). This means that one can write `example (x : ℝ) : differentiable ℝ (λ x, sin (exp (3 + x^2)) - 5 * cos x) := by simp`. If there are divisions, one needs to supply to the simplifier proofs that the denominators do not vanish, as in ```lean example (x : ℝ) (h : 1 + sin x ≠ 0) : differentiable_at ℝ (λ x, exp x / (1 + sin x)) x := by simp [h] ``` Of course, these examples only work once `exp`, `cos` and `sin` have been shown to be differentiable, in `analysis.special_functions.trigonometric`. The simplifier is not set up to compute the Fréchet derivative of maps (as these are in general complicated multidimensional linear maps), but it will compute one-dimensional derivatives, see `deriv.lean`. ## Implementation details The derivative is defined in terms of the `is_o` relation, but also characterized in terms of the `tendsto` relation. We also introduce predicates `differentiable_within_at 𝕜 f s x` (where `𝕜` is the base field, `f` the function to be differentiated, `x` the point at which the derivative is asserted to exist, and `s` the set along which the derivative is defined), as well as `differentiable_at 𝕜 f x`, `differentiable_on 𝕜 f s` and `differentiable 𝕜 f` to express the existence of a derivative. To be able to compute with derivatives, we write `fderiv_within 𝕜 f s x` and `fderiv 𝕜 f x` for some choice of a derivative if it exists, and the zero function otherwise. This choice only behaves well along sets for which the derivative is unique, i.e., those for which the tangent directions span a dense subset of the whole space. The predicates `unique_diff_within_at s x` and `unique_diff_on s`, defined in `tangent_cone.lean` express this property. We prove that indeed they imply the uniqueness of the derivative. This is satisfied for open subsets, and in particular for `univ`. This uniqueness only holds when the field is non-discrete, which we request at the very beginning: otherwise, a derivative can be defined, but it has no interesting properties whatsoever. To make sure that the simplifier can prove automatically that functions are differentiable, we tag many lemmas with the `simp` attribute, for instance those saying that the sum of differentiable functions is differentiable, as well as their product, their cartesian product, and so on. A notable exception is the chain rule: we do not mark as a simp lemma the fact that, if `f` and `g` are differentiable, then their composition also is: `simp` would always be able to match this lemma, by taking `f` or `g` to be the identity. Instead, for every reasonable function (say, `exp`), we add a lemma that if `f` is differentiable then so is `(λ x, exp (f x))`. This means adding some boilerplate lemmas, but these can also be useful in their own right. Tests for this ability of the simplifier (with more examples) are provided in `tests/differentiable.lean`. ## Tags derivative, differentiable, Fréchet, calculus -/ open filter asymptotics continuous_linear_map set metric open_locale topological_space classical nnreal asymptotics filter ennreal noncomputable theory section variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] variables {E : Type*} [normed_group E] [normed_space 𝕜 E] variables {F : Type*} [normed_group F] [normed_space 𝕜 F] variables {G : Type*} [normed_group G] [normed_space 𝕜 G] variables {G' : Type*} [normed_group G'] [normed_space 𝕜 G'] /-- A function `f` has the continuous linear map `f'` as derivative along the filter `L` if `f x' = f x + f' (x' - x) + o (x' - x)` when `x'` converges along the filter `L`. This definition is designed to be specialized for `L = 𝓝 x` (in `has_fderiv_at`), giving rise to the usual notion of Fréchet derivative, and for `L = 𝓝[s] x` (in `has_fderiv_within_at`), giving rise to the notion of Fréchet derivative along the set `s`. -/ def has_fderiv_at_filter (f : E → F) (f' : E →L[𝕜] F) (x : E) (L : filter E) := is_o (λ x', f x' - f x - f' (x' - x)) (λ x', x' - x) L /-- A function `f` has the continuous linear map `f'` as derivative at `x` within a set `s` if `f x' = f x + f' (x' - x) + o (x' - x)` when `x'` tends to `x` inside `s`. -/ def has_fderiv_within_at (f : E → F) (f' : E →L[𝕜] F) (s : set E) (x : E) := has_fderiv_at_filter f f' x (𝓝[s] x) /-- A function `f` has the continuous linear map `f'` as derivative at `x` if `f x' = f x + f' (x' - x) + o (x' - x)` when `x'` tends to `x`. -/ def has_fderiv_at (f : E → F) (f' : E →L[𝕜] F) (x : E) := has_fderiv_at_filter f f' x (𝓝 x) /-- A function `f` has derivative `f'` at `a` in the sense of *strict differentiability* if `f x - f y - f' (x - y) = o(x - y)` as `x, y → a`. This form of differentiability is required, e.g., by the inverse function theorem. Any `C^1` function on a vector space over `ℝ` is strictly differentiable but this definition works, e.g., for vector spaces over `p`-adic numbers. -/ def has_strict_fderiv_at (f : E → F) (f' : E →L[𝕜] F) (x : E) := is_o (λ p : E × E, f p.1 - f p.2 - f' (p.1 - p.2)) (λ p : E × E, p.1 - p.2) (𝓝 (x, x)) variables (𝕜) /-- A function `f` is differentiable at a point `x` within a set `s` if it admits a derivative there (possibly non-unique). -/ def differentiable_within_at (f : E → F) (s : set E) (x : E) := ∃f' : E →L[𝕜] F, has_fderiv_within_at f f' s x /-- A function `f` is differentiable at a point `x` if it admits a derivative there (possibly non-unique). -/ def differentiable_at (f : E → F) (x : E) := ∃f' : E →L[𝕜] F, has_fderiv_at f f' x /-- If `f` has a derivative at `x` within `s`, then `fderiv_within 𝕜 f s x` is such a derivative. Otherwise, it is set to `0`. -/ def fderiv_within (f : E → F) (s : set E) (x : E) : E →L[𝕜] F := if h : ∃f', has_fderiv_within_at f f' s x then classical.some h else 0 /-- If `f` has a derivative at `x`, then `fderiv 𝕜 f x` is such a derivative. Otherwise, it is set to `0`. -/ def fderiv (f : E → F) (x : E) : E →L[𝕜] F := if h : ∃f', has_fderiv_at f f' x then classical.some h else 0 /-- `differentiable_on 𝕜 f s` means that `f` is differentiable within `s` at any point of `s`. -/ def differentiable_on (f : E → F) (s : set E) := ∀x ∈ s, differentiable_within_at 𝕜 f s x /-- `differentiable 𝕜 f` means that `f` is differentiable at any point. -/ def differentiable (f : E → F) := ∀x, differentiable_at 𝕜 f x variables {𝕜} variables {f f₀ f₁ g : E → F} variables {f' f₀' f₁' g' : E →L[𝕜] F} variables (e : E →L[𝕜] F) variables {x : E} variables {s t : set E} variables {L L₁ L₂ : filter E} lemma fderiv_within_zero_of_not_differentiable_within_at (h : ¬ differentiable_within_at 𝕜 f s x) : fderiv_within 𝕜 f s x = 0 := have ¬ ∃ f', has_fderiv_within_at f f' s x, from h, by simp [fderiv_within, this] lemma fderiv_zero_of_not_differentiable_at (h : ¬ differentiable_at 𝕜 f x) : fderiv 𝕜 f x = 0 := have ¬ ∃ f', has_fderiv_at f f' x, from h, by simp [fderiv, this] section derivative_uniqueness /- In this section, we discuss the uniqueness of the derivative. We prove that the definitions `unique_diff_within_at` and `unique_diff_on` indeed imply the uniqueness of the derivative. -/ /-- If a function f has a derivative f' at x, a rescaled version of f around x converges to f', i.e., `n (f (x + (1/n) v) - f x)` converges to `f' v`. More generally, if `c n` tends to infinity and `c n * d n` tends to `v`, then `c n * (f (x + d n) - f x)` tends to `f' v`. This lemma expresses this fact, for functions having a derivative within a set. Its specific formulation is useful for tangent cone related discussions. -/ theorem has_fderiv_within_at.lim (h : has_fderiv_within_at f f' s x) {α : Type*} (l : filter α) {c : α → 𝕜} {d : α → E} {v : E} (dtop : ∀ᶠ n in l, x + d n ∈ s) (clim : tendsto (λ n, ∥c n∥) l at_top) (cdlim : tendsto (λ n, c n • d n) l (𝓝 v)) : tendsto (λn, c n • (f (x + d n) - f x)) l (𝓝 (f' v)) := begin have tendsto_arg : tendsto (λ n, x + d n) l (𝓝[s] x), { conv in (𝓝[s] x) { rw ← add_zero x }, rw [nhds_within, tendsto_inf], split, { apply tendsto_const_nhds.add (tangent_cone_at.lim_zero l clim cdlim) }, { rwa tendsto_principal } }, have : is_o (λ y, f y - f x - f' (y - x)) (λ y, y - x) (𝓝[s] x) := h, have : is_o (λ n, f (x + d n) - f x - f' ((x + d n) - x)) (λ n, (x + d n) - x) l := this.comp_tendsto tendsto_arg, have : is_o (λ n, f (x + d n) - f x - f' (d n)) d l := by simpa only [add_sub_cancel'], have : is_o (λn, c n • (f (x + d n) - f x - f' (d n))) (λn, c n • d n) l := (is_O_refl c l).smul_is_o this, have : is_o (λn, c n • (f (x + d n) - f x - f' (d n))) (λn, (1:ℝ)) l := this.trans_is_O (is_O_one_of_tendsto ℝ cdlim), have L1 : tendsto (λn, c n • (f (x + d n) - f x - f' (d n))) l (𝓝 0) := (is_o_one_iff ℝ).1 this, have L2 : tendsto (λn, f' (c n • d n)) l (𝓝 (f' v)) := tendsto.comp f'.cont.continuous_at cdlim, have L3 : tendsto (λn, (c n • (f (x + d n) - f x - f' (d n)) + f' (c n • d n))) l (𝓝 (0 + f' v)) := L1.add L2, have : (λn, (c n • (f (x + d n) - f x - f' (d n)) + f' (c n • d n))) = (λn, c n • (f (x + d n) - f x)), by { ext n, simp [smul_add, smul_sub] }, rwa [this, zero_add] at L3 end /-- If `f'` and `f₁'` are two derivatives of `f` within `s` at `x`, then they are equal on the tangent cone to `s` at `x` -/ theorem has_fderiv_within_at.unique_on (hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at f f₁' s x) : eq_on f' f₁' (tangent_cone_at 𝕜 s x) := λ y ⟨c, d, dtop, clim, cdlim⟩, tendsto_nhds_unique (hf.lim at_top dtop clim cdlim) (hg.lim at_top dtop clim cdlim) /-- `unique_diff_within_at` achieves its goal: it implies the uniqueness of the derivative. -/ theorem unique_diff_within_at.eq (H : unique_diff_within_at 𝕜 s x) (hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at f f₁' s x) : f' = f₁' := continuous_linear_map.ext_on H.1 (hf.unique_on hg) theorem unique_diff_on.eq (H : unique_diff_on 𝕜 s) (hx : x ∈ s) (h : has_fderiv_within_at f f' s x) (h₁ : has_fderiv_within_at f f₁' s x) : f' = f₁' := (H x hx).eq h h₁ end derivative_uniqueness section fderiv_properties /-! ### Basic properties of the derivative -/ theorem has_fderiv_at_filter_iff_tendsto : has_fderiv_at_filter f f' x L ↔ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) L (𝓝 0) := have h : ∀ x', ∥x' - x∥ = 0 → ∥f x' - f x - f' (x' - x)∥ = 0, from λ x' hx', by { rw [sub_eq_zero.1 (norm_eq_zero.1 hx')], simp }, begin unfold has_fderiv_at_filter, rw [←is_o_norm_left, ←is_o_norm_right, is_o_iff_tendsto h], exact tendsto_congr (λ _, div_eq_inv_mul), end theorem has_fderiv_within_at_iff_tendsto : has_fderiv_within_at f f' s x ↔ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) (𝓝[s] x) (𝓝 0) := has_fderiv_at_filter_iff_tendsto theorem has_fderiv_at_iff_tendsto : has_fderiv_at f f' x ↔ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) (𝓝 x) (𝓝 0) := has_fderiv_at_filter_iff_tendsto theorem has_fderiv_at_iff_is_o_nhds_zero : has_fderiv_at f f' x ↔ is_o (λh, f (x + h) - f x - f' h) (λh, h) (𝓝 0) := begin rw [has_fderiv_at, has_fderiv_at_filter, ← map_add_left_nhds_zero x, is_o_map], simp [(∘)] end /-- Converse to the mean value inequality: if `f` is differentiable at `x₀` and `C`-lipschitz on a neighborhood of `x₀` then it its derivative at `x₀` has norm bounded by `C`. -/ lemma has_fderiv_at.le_of_lip {f : E → F} {f' : E →L[𝕜] F} {x₀ : E} (hf : has_fderiv_at f f' x₀) {s : set E} (hs : s ∈ 𝓝 x₀) {C : ℝ≥0} (hlip : lipschitz_on_with C f s) : ∥f'∥ ≤ C := begin refine le_of_forall_pos_le_add (λ ε ε0, op_norm_le_of_nhds_zero _ _), exact add_nonneg C.coe_nonneg ε0.le, have hs' := hs, rw [← map_add_left_nhds_zero x₀, mem_map] at hs', filter_upwards [is_o_iff.1 (has_fderiv_at_iff_is_o_nhds_zero.1 hf) ε0, hs'], intros y hy hys, have := hlip.norm_sub_le hys (mem_of_mem_nhds hs), rw add_sub_cancel' at this, calc ∥f' y∥ ≤ ∥f (x₀ + y) - f x₀∥ + ∥f (x₀ + y) - f x₀ - f' y∥ : norm_le_insert _ _ ... ≤ C * ∥y∥ + ε * ∥y∥ : add_le_add this hy ... = (C + ε) * ∥y∥ : (add_mul _ _ _).symm end theorem has_fderiv_at_filter.mono (h : has_fderiv_at_filter f f' x L₂) (hst : L₁ ≤ L₂) : has_fderiv_at_filter f f' x L₁ := h.mono hst theorem has_fderiv_within_at.mono (h : has_fderiv_within_at f f' t x) (hst : s ⊆ t) : has_fderiv_within_at f f' s x := h.mono (nhds_within_mono _ hst) theorem has_fderiv_at.has_fderiv_at_filter (h : has_fderiv_at f f' x) (hL : L ≤ 𝓝 x) : has_fderiv_at_filter f f' x L := h.mono hL theorem has_fderiv_at.has_fderiv_within_at (h : has_fderiv_at f f' x) : has_fderiv_within_at f f' s x := h.has_fderiv_at_filter inf_le_left lemma has_fderiv_within_at.differentiable_within_at (h : has_fderiv_within_at f f' s x) : differentiable_within_at 𝕜 f s x := ⟨f', h⟩ lemma has_fderiv_at.differentiable_at (h : has_fderiv_at f f' x) : differentiable_at 𝕜 f x := ⟨f', h⟩ @[simp] lemma has_fderiv_within_at_univ : has_fderiv_within_at f f' univ x ↔ has_fderiv_at f f' x := by { simp only [has_fderiv_within_at, nhds_within_univ], refl } lemma has_strict_fderiv_at.is_O_sub (hf : has_strict_fderiv_at f f' x) : is_O (λ p : E × E, f p.1 - f p.2) (λ p : E × E, p.1 - p.2) (𝓝 (x, x)) := hf.is_O.congr_of_sub.2 (f'.is_O_comp _ _) lemma has_fderiv_at_filter.is_O_sub (h : has_fderiv_at_filter f f' x L) : is_O (λ x', f x' - f x) (λ x', x' - x) L := h.is_O.congr_of_sub.2 (f'.is_O_sub _ _) protected lemma has_strict_fderiv_at.has_fderiv_at (hf : has_strict_fderiv_at f f' x) : has_fderiv_at f f' x := begin rw [has_fderiv_at, has_fderiv_at_filter, is_o_iff], exact (λ c hc, tendsto_id.prod_mk_nhds tendsto_const_nhds (is_o_iff.1 hf hc)) end protected lemma has_strict_fderiv_at.differentiable_at (hf : has_strict_fderiv_at f f' x) : differentiable_at 𝕜 f x := hf.has_fderiv_at.differentiable_at /-- If `f` is strictly differentiable at `x` with derivative `f'` and `K > ∥f'∥₊`, then `f` is `K`-Lipschitz in a neighborhood of `x`. -/ lemma has_strict_fderiv_at.exists_lipschitz_on_with_of_nnnorm_lt (hf : has_strict_fderiv_at f f' x) (K : ℝ≥0) (hK : ∥f'∥₊ < K) : ∃ s ∈ 𝓝 x, lipschitz_on_with K f s := begin have := hf.add_is_O_with (f'.is_O_with_comp _ _) hK, simp only [sub_add_cancel, is_O_with] at this, rcases exists_nhds_square this with ⟨U, Uo, xU, hU⟩, exact ⟨U, Uo.mem_nhds xU, lipschitz_on_with_iff_norm_sub_le.2 $ λ x hx y hy, hU (mk_mem_prod hx hy)⟩ end /-- If `f` is strictly differentiable at `x` with derivative `f'`, then `f` is Lipschitz in a neighborhood of `x`. See also `has_strict_fderiv_at.exists_lipschitz_on_with_of_nnnorm_lt` for a more precise statement. -/ lemma has_strict_fderiv_at.exists_lipschitz_on_with (hf : has_strict_fderiv_at f f' x) : ∃ K (s ∈ 𝓝 x), lipschitz_on_with K f s := (no_top _).imp hf.exists_lipschitz_on_with_of_nnnorm_lt /-- Directional derivative agrees with `has_fderiv`. -/ lemma has_fderiv_at.lim (hf : has_fderiv_at f f' x) (v : E) {α : Type*} {c : α → 𝕜} {l : filter α} (hc : tendsto (λ n, ∥c n∥) l at_top) : tendsto (λ n, (c n) • (f (x + (c n)⁻¹ • v) - f x)) l (𝓝 (f' v)) := begin refine (has_fderiv_within_at_univ.2 hf).lim _ (univ_mem_sets' (λ _, trivial)) hc _, assume U hU, refine (eventually_ne_of_tendsto_norm_at_top hc (0:𝕜)).mono (λ y hy, _), convert mem_of_mem_nhds hU, dsimp only, rw [← mul_smul, mul_inv_cancel hy, one_smul] end theorem has_fderiv_at.unique (h₀ : has_fderiv_at f f₀' x) (h₁ : has_fderiv_at f f₁' x) : f₀' = f₁' := begin rw ← has_fderiv_within_at_univ at h₀ h₁, exact unique_diff_within_at_univ.eq h₀ h₁ end lemma has_fderiv_within_at_inter' (h : t ∈ 𝓝[s] x) : has_fderiv_within_at f f' (s ∩ t) x ↔ has_fderiv_within_at f f' s x := by simp [has_fderiv_within_at, nhds_within_restrict'' s h] lemma has_fderiv_within_at_inter (h : t ∈ 𝓝 x) : has_fderiv_within_at f f' (s ∩ t) x ↔ has_fderiv_within_at f f' s x := by simp [has_fderiv_within_at, nhds_within_restrict' s h] lemma has_fderiv_within_at.union (hs : has_fderiv_within_at f f' s x) (ht : has_fderiv_within_at f f' t x) : has_fderiv_within_at f f' (s ∪ t) x := begin simp only [has_fderiv_within_at, nhds_within_union], exact hs.join ht, end lemma has_fderiv_within_at.nhds_within (h : has_fderiv_within_at f f' s x) (ht : s ∈ 𝓝[t] x) : has_fderiv_within_at f f' t x := (has_fderiv_within_at_inter' ht).1 (h.mono (inter_subset_right _ _)) lemma has_fderiv_within_at.has_fderiv_at (h : has_fderiv_within_at f f' s x) (hs : s ∈ 𝓝 x) : has_fderiv_at f f' x := by rwa [← univ_inter s, has_fderiv_within_at_inter hs, has_fderiv_within_at_univ] at h lemma differentiable_within_at.has_fderiv_within_at (h : differentiable_within_at 𝕜 f s x) : has_fderiv_within_at f (fderiv_within 𝕜 f s x) s x := begin dunfold fderiv_within, dunfold differentiable_within_at at h, rw dif_pos h, exact classical.some_spec h end lemma differentiable_at.has_fderiv_at (h : differentiable_at 𝕜 f x) : has_fderiv_at f (fderiv 𝕜 f x) x := begin dunfold fderiv, dunfold differentiable_at at h, rw dif_pos h, exact classical.some_spec h end lemma has_fderiv_at.fderiv (h : has_fderiv_at f f' x) : fderiv 𝕜 f x = f' := by { ext, rw h.unique h.differentiable_at.has_fderiv_at } /-- Converse to the mean value inequality: if `f` is differentiable at `x₀` and `C`-lipschitz on a neighborhood of `x₀` then it its derivative at `x₀` has norm bounded by `C`. Version using `fderiv`. -/ lemma fderiv_at.le_of_lip {f : E → F} {x₀ : E} (hf : differentiable_at 𝕜 f x₀) {s : set E} (hs : s ∈ 𝓝 x₀) {C : ℝ≥0} (hlip : lipschitz_on_with C f s) : ∥fderiv 𝕜 f x₀∥ ≤ C := hf.has_fderiv_at.le_of_lip hs hlip lemma has_fderiv_within_at.fderiv_within (h : has_fderiv_within_at f f' s x) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 f s x = f' := (hxs.eq h h.differentiable_within_at.has_fderiv_within_at).symm /-- If `x` is not in the closure of `s`, then `f` has any derivative at `x` within `s`, as this statement is empty. -/ lemma has_fderiv_within_at_of_not_mem_closure (h : x ∉ closure s) : has_fderiv_within_at f f' s x := begin simp only [mem_closure_iff_nhds_within_ne_bot, ne_bot_iff, ne.def, not_not] at h, simp [has_fderiv_within_at, has_fderiv_at_filter, h, is_o, is_O_with], end lemma differentiable_within_at.mono (h : differentiable_within_at 𝕜 f t x) (st : s ⊆ t) : differentiable_within_at 𝕜 f s x := begin rcases h with ⟨f', hf'⟩, exact ⟨f', hf'.mono st⟩ end lemma differentiable_within_at_univ : differentiable_within_at 𝕜 f univ x ↔ differentiable_at 𝕜 f x := by simp only [differentiable_within_at, has_fderiv_within_at_univ, differentiable_at] lemma differentiable_within_at_inter (ht : t ∈ 𝓝 x) : differentiable_within_at 𝕜 f (s ∩ t) x ↔ differentiable_within_at 𝕜 f s x := by simp only [differentiable_within_at, has_fderiv_within_at, has_fderiv_at_filter, nhds_within_restrict' s ht] lemma differentiable_within_at_inter' (ht : t ∈ 𝓝[s] x) : differentiable_within_at 𝕜 f (s ∩ t) x ↔ differentiable_within_at 𝕜 f s x := by simp only [differentiable_within_at, has_fderiv_within_at, has_fderiv_at_filter, nhds_within_restrict'' s ht] lemma differentiable_at.differentiable_within_at (h : differentiable_at 𝕜 f x) : differentiable_within_at 𝕜 f s x := (differentiable_within_at_univ.2 h).mono (subset_univ _) lemma differentiable.differentiable_at (h : differentiable 𝕜 f) : differentiable_at 𝕜 f x := h x lemma differentiable_within_at.differentiable_at (h : differentiable_within_at 𝕜 f s x) (hs : s ∈ 𝓝 x) : differentiable_at 𝕜 f x := h.imp (λ f' hf', hf'.has_fderiv_at hs) lemma differentiable_at.fderiv_within (h : differentiable_at 𝕜 f x) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 f s x = fderiv 𝕜 f x := begin apply has_fderiv_within_at.fderiv_within _ hxs, exact h.has_fderiv_at.has_fderiv_within_at end lemma differentiable_on.mono (h : differentiable_on 𝕜 f t) (st : s ⊆ t) : differentiable_on 𝕜 f s := λx hx, (h x (st hx)).mono st lemma differentiable_on_univ : differentiable_on 𝕜 f univ ↔ differentiable 𝕜 f := by { simp [differentiable_on, differentiable_within_at_univ], refl } lemma differentiable.differentiable_on (h : differentiable 𝕜 f) : differentiable_on 𝕜 f s := (differentiable_on_univ.2 h).mono (subset_univ _) lemma differentiable_on_of_locally_differentiable_on (h : ∀x∈s, ∃u, is_open u ∧ x ∈ u ∧ differentiable_on 𝕜 f (s ∩ u)) : differentiable_on 𝕜 f s := begin assume x xs, rcases h x xs with ⟨t, t_open, xt, ht⟩, exact (differentiable_within_at_inter (is_open.mem_nhds t_open xt)).1 (ht x ⟨xs, xt⟩) end lemma fderiv_within_subset (st : s ⊆ t) (ht : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f t x) : fderiv_within 𝕜 f s x = fderiv_within 𝕜 f t x := ((differentiable_within_at.has_fderiv_within_at h).mono st).fderiv_within ht @[simp] lemma fderiv_within_univ : fderiv_within 𝕜 f univ = fderiv 𝕜 f := begin ext x : 1, by_cases h : differentiable_at 𝕜 f x, { apply has_fderiv_within_at.fderiv_within _ unique_diff_within_at_univ, rw has_fderiv_within_at_univ, apply h.has_fderiv_at }, { have : ¬ differentiable_within_at 𝕜 f univ x, by contrapose! h; rwa ← differentiable_within_at_univ, rw [fderiv_zero_of_not_differentiable_at h, fderiv_within_zero_of_not_differentiable_within_at this] } end lemma fderiv_within_inter (ht : t ∈ 𝓝 x) (hs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 f (s ∩ t) x = fderiv_within 𝕜 f s x := begin by_cases h : differentiable_within_at 𝕜 f (s ∩ t) x, { apply fderiv_within_subset (inter_subset_left _ _) _ ((differentiable_within_at_inter ht).1 h), apply hs.inter ht }, { have : ¬ differentiable_within_at 𝕜 f s x, by contrapose! h; rw differentiable_within_at_inter; assumption, rw [fderiv_within_zero_of_not_differentiable_within_at h, fderiv_within_zero_of_not_differentiable_within_at this] } end lemma fderiv_within_of_mem_nhds (h : s ∈ 𝓝 x) : fderiv_within 𝕜 f s x = fderiv 𝕜 f x := begin have : s = univ ∩ s, by simp only [univ_inter], rw [this, ← fderiv_within_univ], exact fderiv_within_inter h (unique_diff_on_univ _ (mem_univ _)) end lemma fderiv_within_of_open (hs : is_open s) (hx : x ∈ s) : fderiv_within 𝕜 f s x = fderiv 𝕜 f x := fderiv_within_of_mem_nhds (is_open.mem_nhds hs hx) lemma fderiv_within_eq_fderiv (hs : unique_diff_within_at 𝕜 s x) (h : differentiable_at 𝕜 f x) : fderiv_within 𝕜 f s x = fderiv 𝕜 f x := begin rw ← fderiv_within_univ, exact fderiv_within_subset (subset_univ _) hs h.differentiable_within_at end lemma fderiv_mem_iff {f : E → F} {s : set (E →L[𝕜] F)} {x : E} : fderiv 𝕜 f x ∈ s ↔ (differentiable_at 𝕜 f x ∧ fderiv 𝕜 f x ∈ s) ∨ (0 : E →L[𝕜] F) ∈ s ∧ ¬differentiable_at 𝕜 f x := begin split, { intro hfx, by_cases hx : differentiable_at 𝕜 f x, { exact or.inl ⟨hx, hfx⟩ }, { rw [fderiv_zero_of_not_differentiable_at hx] at hfx, exact or.inr ⟨hfx, hx⟩ } }, { rintro (⟨hf, hf'⟩|⟨h₀, hx⟩), { exact hf' }, { rwa [fderiv_zero_of_not_differentiable_at hx] } } end end fderiv_properties section continuous /-! ### Deducing continuity from differentiability -/ theorem has_fderiv_at_filter.tendsto_nhds (hL : L ≤ 𝓝 x) (h : has_fderiv_at_filter f f' x L) : tendsto f L (𝓝 (f x)) := begin have : tendsto (λ x', f x' - f x) L (𝓝 0), { refine h.is_O_sub.trans_tendsto (tendsto.mono_left _ hL), rw ← sub_self x, exact tendsto_id.sub tendsto_const_nhds }, have := tendsto.add this tendsto_const_nhds, rw zero_add (f x) at this, exact this.congr (by simp) end theorem has_fderiv_within_at.continuous_within_at (h : has_fderiv_within_at f f' s x) : continuous_within_at f s x := has_fderiv_at_filter.tendsto_nhds inf_le_left h theorem has_fderiv_at.continuous_at (h : has_fderiv_at f f' x) : continuous_at f x := has_fderiv_at_filter.tendsto_nhds (le_refl _) h lemma differentiable_within_at.continuous_within_at (h : differentiable_within_at 𝕜 f s x) : continuous_within_at f s x := let ⟨f', hf'⟩ := h in hf'.continuous_within_at lemma differentiable_at.continuous_at (h : differentiable_at 𝕜 f x) : continuous_at f x := let ⟨f', hf'⟩ := h in hf'.continuous_at lemma differentiable_on.continuous_on (h : differentiable_on 𝕜 f s) : continuous_on f s := λx hx, (h x hx).continuous_within_at lemma differentiable.continuous (h : differentiable 𝕜 f) : continuous f := continuous_iff_continuous_at.2 $ λx, (h x).continuous_at protected lemma has_strict_fderiv_at.continuous_at (hf : has_strict_fderiv_at f f' x) : continuous_at f x := hf.has_fderiv_at.continuous_at lemma has_strict_fderiv_at.is_O_sub_rev {f' : E ≃L[𝕜] F} (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) x) : is_O (λ p : E × E, p.1 - p.2) (λ p : E × E, f p.1 - f p.2) (𝓝 (x, x)) := ((f'.is_O_comp_rev _ _).trans (hf.trans_is_O (f'.is_O_comp_rev _ _)).right_is_O_add).congr (λ _, rfl) (λ _, sub_add_cancel _ _) lemma has_fderiv_at_filter.is_O_sub_rev {f' : E ≃L[𝕜] F} (hf : has_fderiv_at_filter f (f' : E →L[𝕜] F) x L) : is_O (λ x', x' - x) (λ x', f x' - f x) L := ((f'.is_O_sub_rev _ _).trans (hf.trans_is_O (f'.is_O_sub_rev _ _)).right_is_O_add).congr (λ _, rfl) (λ _, sub_add_cancel _ _) end continuous section congr /-! ### congr properties of the derivative -/ theorem filter.eventually_eq.has_strict_fderiv_at_iff (h : f₀ =ᶠ[𝓝 x] f₁) (h' : ∀ y, f₀' y = f₁' y) : has_strict_fderiv_at f₀ f₀' x ↔ has_strict_fderiv_at f₁ f₁' x := begin refine is_o_congr ((h.prod_mk_nhds h).mono _) (eventually_of_forall $ λ _, rfl), rintros p ⟨hp₁, hp₂⟩, simp only [*] end theorem has_strict_fderiv_at.congr_of_eventually_eq (h : has_strict_fderiv_at f f' x) (h₁ : f =ᶠ[𝓝 x] f₁) : has_strict_fderiv_at f₁ f' x := (h₁.has_strict_fderiv_at_iff (λ _, rfl)).1 h theorem filter.eventually_eq.has_fderiv_at_filter_iff (h₀ : f₀ =ᶠ[L] f₁) (hx : f₀ x = f₁ x) (h₁ : ∀ x, f₀' x = f₁' x) : has_fderiv_at_filter f₀ f₀' x L ↔ has_fderiv_at_filter f₁ f₁' x L := is_o_congr (h₀.mono $ λ y hy, by simp only [hy, h₁, hx]) (eventually_of_forall $ λ _, rfl) lemma has_fderiv_at_filter.congr_of_eventually_eq (h : has_fderiv_at_filter f f' x L) (hL : f₁ =ᶠ[L] f) (hx : f₁ x = f x) : has_fderiv_at_filter f₁ f' x L := (hL.has_fderiv_at_filter_iff hx $ λ _, rfl).2 h lemma has_fderiv_within_at.congr_mono (h : has_fderiv_within_at f f' s x) (ht : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (h₁ : t ⊆ s) : has_fderiv_within_at f₁ f' t x := has_fderiv_at_filter.congr_of_eventually_eq (h.mono h₁) (filter.mem_inf_sets_of_right ht) hx lemma has_fderiv_within_at.congr (h : has_fderiv_within_at f f' s x) (hs : ∀x ∈ s, f₁ x = f x) (hx : f₁ x = f x) : has_fderiv_within_at f₁ f' s x := h.congr_mono hs hx (subset.refl _) lemma has_fderiv_within_at.congr' (h : has_fderiv_within_at f f' s x) (hs : ∀x ∈ s, f₁ x = f x) (hx : x ∈ s) : has_fderiv_within_at f₁ f' s x := h.congr hs (hs x hx) lemma has_fderiv_within_at.congr_of_eventually_eq (h : has_fderiv_within_at f f' s x) (h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : has_fderiv_within_at f₁ f' s x := has_fderiv_at_filter.congr_of_eventually_eq h h₁ hx lemma has_fderiv_at.congr_of_eventually_eq (h : has_fderiv_at f f' x) (h₁ : f₁ =ᶠ[𝓝 x] f) : has_fderiv_at f₁ f' x := has_fderiv_at_filter.congr_of_eventually_eq h h₁ (mem_of_mem_nhds h₁ : _) lemma differentiable_within_at.congr_mono (h : differentiable_within_at 𝕜 f s x) (ht : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (h₁ : t ⊆ s) : differentiable_within_at 𝕜 f₁ t x := (has_fderiv_within_at.congr_mono h.has_fderiv_within_at ht hx h₁).differentiable_within_at lemma differentiable_within_at.congr (h : differentiable_within_at 𝕜 f s x) (ht : ∀x ∈ s, f₁ x = f x) (hx : f₁ x = f x) : differentiable_within_at 𝕜 f₁ s x := differentiable_within_at.congr_mono h ht hx (subset.refl _) lemma differentiable_within_at.congr_of_eventually_eq (h : differentiable_within_at 𝕜 f s x) (h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : differentiable_within_at 𝕜 f₁ s x := (h.has_fderiv_within_at.congr_of_eventually_eq h₁ hx).differentiable_within_at lemma differentiable_on.congr_mono (h : differentiable_on 𝕜 f s) (h' : ∀x ∈ t, f₁ x = f x) (h₁ : t ⊆ s) : differentiable_on 𝕜 f₁ t := λ x hx, (h x (h₁ hx)).congr_mono h' (h' x hx) h₁ lemma differentiable_on.congr (h : differentiable_on 𝕜 f s) (h' : ∀x ∈ s, f₁ x = f x) : differentiable_on 𝕜 f₁ s := λ x hx, (h x hx).congr h' (h' x hx) lemma differentiable_on_congr (h' : ∀x ∈ s, f₁ x = f x) : differentiable_on 𝕜 f₁ s ↔ differentiable_on 𝕜 f s := ⟨λ h, differentiable_on.congr h (λy hy, (h' y hy).symm), λ h, differentiable_on.congr h h'⟩ lemma differentiable_at.congr_of_eventually_eq (h : differentiable_at 𝕜 f x) (hL : f₁ =ᶠ[𝓝 x] f) : differentiable_at 𝕜 f₁ x := has_fderiv_at.differentiable_at (has_fderiv_at_filter.congr_of_eventually_eq h.has_fderiv_at hL (mem_of_mem_nhds hL : _)) lemma differentiable_within_at.fderiv_within_congr_mono (h : differentiable_within_at 𝕜 f s x) (hs : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (hxt : unique_diff_within_at 𝕜 t x) (h₁ : t ⊆ s) : fderiv_within 𝕜 f₁ t x = fderiv_within 𝕜 f s x := (has_fderiv_within_at.congr_mono h.has_fderiv_within_at hs hx h₁).fderiv_within hxt lemma filter.eventually_eq.fderiv_within_eq (hs : unique_diff_within_at 𝕜 s x) (hL : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : fderiv_within 𝕜 f₁ s x = fderiv_within 𝕜 f s x := if h : differentiable_within_at 𝕜 f s x then has_fderiv_within_at.fderiv_within (h.has_fderiv_within_at.congr_of_eventually_eq hL hx) hs else have h' : ¬ differentiable_within_at 𝕜 f₁ s x, from mt (λ h, h.congr_of_eventually_eq (hL.mono $ λ x, eq.symm) hx.symm) h, by rw [fderiv_within_zero_of_not_differentiable_within_at h, fderiv_within_zero_of_not_differentiable_within_at h'] lemma fderiv_within_congr (hs : unique_diff_within_at 𝕜 s x) (hL : ∀y∈s, f₁ y = f y) (hx : f₁ x = f x) : fderiv_within 𝕜 f₁ s x = fderiv_within 𝕜 f s x := begin apply filter.eventually_eq.fderiv_within_eq hs _ hx, apply mem_sets_of_superset self_mem_nhds_within, exact hL end lemma filter.eventually_eq.fderiv_eq (hL : f₁ =ᶠ[𝓝 x] f) : fderiv 𝕜 f₁ x = fderiv 𝕜 f x := begin have A : f₁ x = f x := hL.eq_of_nhds, rw [← fderiv_within_univ, ← fderiv_within_univ], rw ← nhds_within_univ at hL, exact hL.fderiv_within_eq unique_diff_within_at_univ A end end congr section id /-! ### Derivative of the identity -/ theorem has_strict_fderiv_at_id (x : E) : has_strict_fderiv_at id (id 𝕜 E) x := (is_o_zero _ _).congr_left $ by simp theorem has_fderiv_at_filter_id (x : E) (L : filter E) : has_fderiv_at_filter id (id 𝕜 E) x L := (is_o_zero _ _).congr_left $ by simp theorem has_fderiv_within_at_id (x : E) (s : set E) : has_fderiv_within_at id (id 𝕜 E) s x := has_fderiv_at_filter_id _ _ theorem has_fderiv_at_id (x : E) : has_fderiv_at id (id 𝕜 E) x := has_fderiv_at_filter_id _ _ @[simp] lemma differentiable_at_id : differentiable_at 𝕜 id x := (has_fderiv_at_id x).differentiable_at @[simp] lemma differentiable_at_id' : differentiable_at 𝕜 (λ x, x) x := (has_fderiv_at_id x).differentiable_at lemma differentiable_within_at_id : differentiable_within_at 𝕜 id s x := differentiable_at_id.differentiable_within_at @[simp] lemma differentiable_id : differentiable 𝕜 (id : E → E) := λx, differentiable_at_id @[simp] lemma differentiable_id' : differentiable 𝕜 (λ (x : E), x) := λx, differentiable_at_id lemma differentiable_on_id : differentiable_on 𝕜 id s := differentiable_id.differentiable_on lemma fderiv_id : fderiv 𝕜 id x = id 𝕜 E := has_fderiv_at.fderiv (has_fderiv_at_id x) @[simp] lemma fderiv_id' : fderiv 𝕜 (λ (x : E), x) x = continuous_linear_map.id 𝕜 E := fderiv_id lemma fderiv_within_id (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 id s x = id 𝕜 E := begin rw differentiable_at.fderiv_within (differentiable_at_id) hxs, exact fderiv_id end lemma fderiv_within_id' (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λ (x : E), x) s x = continuous_linear_map.id 𝕜 E := fderiv_within_id hxs end id section const /-! ### derivative of a constant function -/ theorem has_strict_fderiv_at_const (c : F) (x : E) : has_strict_fderiv_at (λ _, c) (0 : E →L[𝕜] F) x := (is_o_zero _ _).congr_left $ λ _, by simp only [zero_apply, sub_self] theorem has_fderiv_at_filter_const (c : F) (x : E) (L : filter E) : has_fderiv_at_filter (λ x, c) (0 : E →L[𝕜] F) x L := (is_o_zero _ _).congr_left $ λ _, by simp only [zero_apply, sub_self] theorem has_fderiv_within_at_const (c : F) (x : E) (s : set E) : has_fderiv_within_at (λ x, c) (0 : E →L[𝕜] F) s x := has_fderiv_at_filter_const _ _ _ theorem has_fderiv_at_const (c : F) (x : E) : has_fderiv_at (λ x, c) (0 : E →L[𝕜] F) x := has_fderiv_at_filter_const _ _ _ @[simp] lemma differentiable_at_const (c : F) : differentiable_at 𝕜 (λx, c) x := ⟨0, has_fderiv_at_const c x⟩ lemma differentiable_within_at_const (c : F) : differentiable_within_at 𝕜 (λx, c) s x := differentiable_at.differentiable_within_at (differentiable_at_const _) lemma fderiv_const_apply (c : F) : fderiv 𝕜 (λy, c) x = 0 := has_fderiv_at.fderiv (has_fderiv_at_const c x) @[simp] lemma fderiv_const (c : F) : fderiv 𝕜 (λ (y : E), c) = 0 := by { ext m, rw fderiv_const_apply, refl } lemma fderiv_within_const_apply (c : F) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λy, c) s x = 0 := begin rw differentiable_at.fderiv_within (differentiable_at_const _) hxs, exact fderiv_const_apply _ end @[simp] lemma differentiable_const (c : F) : differentiable 𝕜 (λx : E, c) := λx, differentiable_at_const _ lemma differentiable_on_const (c : F) : differentiable_on 𝕜 (λx, c) s := (differentiable_const _).differentiable_on lemma has_fderiv_at_of_subsingleton {R X Y : Type*} [nondiscrete_normed_field R] [normed_group X] [normed_group Y] [normed_space R X] [normed_space R Y] [h : subsingleton X] (f : X → Y) (x : X) : has_fderiv_at f (0 : X →L[R] Y) x := begin rw subsingleton_iff at h, have key : function.const X (f 0) = f := by ext x'; rw h x' 0, exact key ▸ (has_fderiv_at_const (f 0) _), end end const section continuous_linear_map /-! ### Continuous linear maps There are currently two variants of these in mathlib, the bundled version (named `continuous_linear_map`, and denoted `E →L[𝕜] F`), and the unbundled version (with a predicate `is_bounded_linear_map`). We give statements for both versions. -/ protected theorem continuous_linear_map.has_strict_fderiv_at {x : E} : has_strict_fderiv_at e e x := (is_o_zero _ _).congr_left $ λ x, by simp only [e.map_sub, sub_self] protected lemma continuous_linear_map.has_fderiv_at_filter : has_fderiv_at_filter e e x L := (is_o_zero _ _).congr_left $ λ x, by simp only [e.map_sub, sub_self] protected lemma continuous_linear_map.has_fderiv_within_at : has_fderiv_within_at e e s x := e.has_fderiv_at_filter protected lemma continuous_linear_map.has_fderiv_at : has_fderiv_at e e x := e.has_fderiv_at_filter @[simp] protected lemma continuous_linear_map.differentiable_at : differentiable_at 𝕜 e x := e.has_fderiv_at.differentiable_at protected lemma continuous_linear_map.differentiable_within_at : differentiable_within_at 𝕜 e s x := e.differentiable_at.differentiable_within_at @[simp] protected lemma continuous_linear_map.fderiv : fderiv 𝕜 e x = e := e.has_fderiv_at.fderiv protected lemma continuous_linear_map.fderiv_within (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 e s x = e := begin rw differentiable_at.fderiv_within e.differentiable_at hxs, exact e.fderiv end @[simp] protected lemma continuous_linear_map.differentiable : differentiable 𝕜 e := λx, e.differentiable_at protected lemma continuous_linear_map.differentiable_on : differentiable_on 𝕜 e s := e.differentiable.differentiable_on lemma is_bounded_linear_map.has_fderiv_at_filter (h : is_bounded_linear_map 𝕜 f) : has_fderiv_at_filter f h.to_continuous_linear_map x L := h.to_continuous_linear_map.has_fderiv_at_filter lemma is_bounded_linear_map.has_fderiv_within_at (h : is_bounded_linear_map 𝕜 f) : has_fderiv_within_at f h.to_continuous_linear_map s x := h.has_fderiv_at_filter lemma is_bounded_linear_map.has_fderiv_at (h : is_bounded_linear_map 𝕜 f) : has_fderiv_at f h.to_continuous_linear_map x := h.has_fderiv_at_filter lemma is_bounded_linear_map.differentiable_at (h : is_bounded_linear_map 𝕜 f) : differentiable_at 𝕜 f x := h.has_fderiv_at.differentiable_at lemma is_bounded_linear_map.differentiable_within_at (h : is_bounded_linear_map 𝕜 f) : differentiable_within_at 𝕜 f s x := h.differentiable_at.differentiable_within_at lemma is_bounded_linear_map.fderiv (h : is_bounded_linear_map 𝕜 f) : fderiv 𝕜 f x = h.to_continuous_linear_map := has_fderiv_at.fderiv (h.has_fderiv_at) lemma is_bounded_linear_map.fderiv_within (h : is_bounded_linear_map 𝕜 f) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 f s x = h.to_continuous_linear_map := begin rw differentiable_at.fderiv_within h.differentiable_at hxs, exact h.fderiv end lemma is_bounded_linear_map.differentiable (h : is_bounded_linear_map 𝕜 f) : differentiable 𝕜 f := λx, h.differentiable_at lemma is_bounded_linear_map.differentiable_on (h : is_bounded_linear_map 𝕜 f) : differentiable_on 𝕜 f s := h.differentiable.differentiable_on end continuous_linear_map section analytic variables {p : formal_multilinear_series 𝕜 E F} {r : ℝ≥0∞} lemma has_fpower_series_at.has_strict_fderiv_at (h : has_fpower_series_at f p x) : has_strict_fderiv_at f (continuous_multilinear_curry_fin1 𝕜 E F (p 1)) x := begin refine h.is_O_image_sub_norm_mul_norm_sub.trans_is_o (is_o.of_norm_right _), refine is_o_iff_exists_eq_mul.2 ⟨λ y, ∥y - (x, x)∥, _, eventually_eq.rfl⟩, refine (continuous_id.sub continuous_const).norm.tendsto' _ _ _, rw [_root_.id, sub_self, norm_zero] end lemma has_fpower_series_at.has_fderiv_at (h : has_fpower_series_at f p x) : has_fderiv_at f (continuous_multilinear_curry_fin1 𝕜 E F (p 1)) x := h.has_strict_fderiv_at.has_fderiv_at lemma has_fpower_series_at.differentiable_at (h : has_fpower_series_at f p x) : differentiable_at 𝕜 f x := h.has_fderiv_at.differentiable_at lemma analytic_at.differentiable_at : analytic_at 𝕜 f x → differentiable_at 𝕜 f x | ⟨p, hp⟩ := hp.differentiable_at lemma analytic_at.differentiable_within_at (h : analytic_at 𝕜 f x) : differentiable_within_at 𝕜 f s x := h.differentiable_at.differentiable_within_at lemma has_fpower_series_at.fderiv (h : has_fpower_series_at f p x) : fderiv 𝕜 f x = continuous_multilinear_curry_fin1 𝕜 E F (p 1) := h.has_fderiv_at.fderiv lemma has_fpower_series_on_ball.differentiable_on [complete_space F] (h : has_fpower_series_on_ball f p x r) : differentiable_on 𝕜 f (emetric.ball x r) := λ y hy, (h.analytic_at_of_mem hy).differentiable_within_at end analytic section composition /-! ### Derivative of the composition of two functions For composition lemmas, we put x explicit to help the elaborator, as otherwise Lean tends to get confused since there are too many possibilities for composition -/ variable (x) theorem has_fderiv_at_filter.comp {g : F → G} {g' : F →L[𝕜] G} (hg : has_fderiv_at_filter g g' (f x) (L.map f)) (hf : has_fderiv_at_filter f f' x L) : has_fderiv_at_filter (g ∘ f) (g'.comp f') x L := let eq₁ := (g'.is_O_comp _ _).trans_is_o hf in let eq₂ := (hg.comp_tendsto tendsto_map).trans_is_O hf.is_O_sub in by { refine eq₂.triangle (eq₁.congr_left (λ x', _)), simp } /- A readable version of the previous theorem, a general form of the chain rule. -/ example {g : F → G} {g' : F →L[𝕜] G} (hg : has_fderiv_at_filter g g' (f x) (L.map f)) (hf : has_fderiv_at_filter f f' x L) : has_fderiv_at_filter (g ∘ f) (g'.comp f') x L := begin unfold has_fderiv_at_filter at hg, have : is_o (λ x', g (f x') - g (f x) - g' (f x' - f x)) (λ x', f x' - f x) L, from hg.comp_tendsto (le_refl _), have eq₁ : is_o (λ x', g (f x') - g (f x) - g' (f x' - f x)) (λ x', x' - x) L, from this.trans_is_O hf.is_O_sub, have eq₂ : is_o (λ x', f x' - f x - f' (x' - x)) (λ x', x' - x) L, from hf, have : is_O (λ x', g' (f x' - f x - f' (x' - x))) (λ x', f x' - f x - f' (x' - x)) L, from g'.is_O_comp _ _, have : is_o (λ x', g' (f x' - f x - f' (x' - x))) (λ x', x' - x) L, from this.trans_is_o eq₂, have eq₃ : is_o (λ x', g' (f x' - f x) - (g' (f' (x' - x)))) (λ x', x' - x) L, by { refine this.congr_left _, simp}, exact eq₁.triangle eq₃ end theorem has_fderiv_within_at.comp {g : F → G} {g' : F →L[𝕜] G} {t : set F} (hg : has_fderiv_within_at g g' t (f x)) (hf : has_fderiv_within_at f f' s x) (hst : s ⊆ f ⁻¹' t) : has_fderiv_within_at (g ∘ f) (g'.comp f') s x := begin apply has_fderiv_at_filter.comp _ (has_fderiv_at_filter.mono hg _) hf, calc map f (𝓝[s] x) ≤ 𝓝[f '' s] (f x) : hf.continuous_within_at.tendsto_nhds_within_image ... ≤ 𝓝[t] (f x) : nhds_within_mono _ (image_subset_iff.mpr hst) end /-- The chain rule. -/ theorem has_fderiv_at.comp {g : F → G} {g' : F →L[𝕜] G} (hg : has_fderiv_at g g' (f x)) (hf : has_fderiv_at f f' x) : has_fderiv_at (g ∘ f) (g'.comp f') x := (hg.mono hf.continuous_at).comp x hf theorem has_fderiv_at.comp_has_fderiv_within_at {g : F → G} {g' : F →L[𝕜] G} (hg : has_fderiv_at g g' (f x)) (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (g ∘ f) (g'.comp f') s x := begin rw ← has_fderiv_within_at_univ at hg, exact has_fderiv_within_at.comp x hg hf subset_preimage_univ end lemma differentiable_within_at.comp {g : F → G} {t : set F} (hg : differentiable_within_at 𝕜 g t (f x)) (hf : differentiable_within_at 𝕜 f s x) (h : s ⊆ f ⁻¹' t) : differentiable_within_at 𝕜 (g ∘ f) s x := begin rcases hf with ⟨f', hf'⟩, rcases hg with ⟨g', hg'⟩, exact ⟨continuous_linear_map.comp g' f', hg'.comp x hf' h⟩ end lemma differentiable_within_at.comp' {g : F → G} {t : set F} (hg : differentiable_within_at 𝕜 g t (f x)) (hf : differentiable_within_at 𝕜 f s x) : differentiable_within_at 𝕜 (g ∘ f) (s ∩ f⁻¹' t) x := hg.comp x (hf.mono (inter_subset_left _ _)) (inter_subset_right _ _) lemma differentiable_at.comp {g : F → G} (hg : differentiable_at 𝕜 g (f x)) (hf : differentiable_at 𝕜 f x) : differentiable_at 𝕜 (g ∘ f) x := (hg.has_fderiv_at.comp x hf.has_fderiv_at).differentiable_at lemma differentiable_at.comp_differentiable_within_at {g : F → G} (hg : differentiable_at 𝕜 g (f x)) (hf : differentiable_within_at 𝕜 f s x) : differentiable_within_at 𝕜 (g ∘ f) s x := (differentiable_within_at_univ.2 hg).comp x hf (by simp) lemma fderiv_within.comp {g : F → G} {t : set F} (hg : differentiable_within_at 𝕜 g t (f x)) (hf : differentiable_within_at 𝕜 f s x) (h : maps_to f s t) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (g ∘ f) s x = (fderiv_within 𝕜 g t (f x)).comp (fderiv_within 𝕜 f s x) := begin apply has_fderiv_within_at.fderiv_within _ hxs, exact has_fderiv_within_at.comp x (hg.has_fderiv_within_at) (hf.has_fderiv_within_at) h end lemma fderiv.comp {g : F → G} (hg : differentiable_at 𝕜 g (f x)) (hf : differentiable_at 𝕜 f x) : fderiv 𝕜 (g ∘ f) x = (fderiv 𝕜 g (f x)).comp (fderiv 𝕜 f x) := begin apply has_fderiv_at.fderiv, exact has_fderiv_at.comp x hg.has_fderiv_at hf.has_fderiv_at end lemma fderiv.comp_fderiv_within {g : F → G} (hg : differentiable_at 𝕜 g (f x)) (hf : differentiable_within_at 𝕜 f s x) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (g ∘ f) s x = (fderiv 𝕜 g (f x)).comp (fderiv_within 𝕜 f s x) := begin apply has_fderiv_within_at.fderiv_within _ hxs, exact has_fderiv_at.comp_has_fderiv_within_at x (hg.has_fderiv_at) (hf.has_fderiv_within_at) end lemma differentiable_on.comp {g : F → G} {t : set F} (hg : differentiable_on 𝕜 g t) (hf : differentiable_on 𝕜 f s) (st : s ⊆ f ⁻¹' t) : differentiable_on 𝕜 (g ∘ f) s := λx hx, differentiable_within_at.comp x (hg (f x) (st hx)) (hf x hx) st lemma differentiable.comp {g : F → G} (hg : differentiable 𝕜 g) (hf : differentiable 𝕜 f) : differentiable 𝕜 (g ∘ f) := λx, differentiable_at.comp x (hg (f x)) (hf x) lemma differentiable.comp_differentiable_on {g : F → G} (hg : differentiable 𝕜 g) (hf : differentiable_on 𝕜 f s) : differentiable_on 𝕜 (g ∘ f) s := (differentiable_on_univ.2 hg).comp hf (by simp) /-- The chain rule for derivatives in the sense of strict differentiability. -/ protected lemma has_strict_fderiv_at.comp {g : F → G} {g' : F →L[𝕜] G} (hg : has_strict_fderiv_at g g' (f x)) (hf : has_strict_fderiv_at f f' x) : has_strict_fderiv_at (λ x, g (f x)) (g'.comp f') x := ((hg.comp_tendsto (hf.continuous_at.prod_map' hf.continuous_at)).trans_is_O hf.is_O_sub).triangle $ by simpa only [g'.map_sub, f'.coe_comp'] using (g'.is_O_comp _ _).trans_is_o hf protected lemma differentiable.iterate {f : E → E} (hf : differentiable 𝕜 f) (n : ℕ) : differentiable 𝕜 (f^[n]) := nat.rec_on n differentiable_id (λ n ihn, ihn.comp hf) protected lemma differentiable_on.iterate {f : E → E} (hf : differentiable_on 𝕜 f s) (hs : maps_to f s s) (n : ℕ) : differentiable_on 𝕜 (f^[n]) s := nat.rec_on n differentiable_on_id (λ n ihn, ihn.comp hf hs) variable {x} protected lemma has_fderiv_at_filter.iterate {f : E → E} {f' : E →L[𝕜] E} (hf : has_fderiv_at_filter f f' x L) (hL : tendsto f L L) (hx : f x = x) (n : ℕ) : has_fderiv_at_filter (f^[n]) (f'^n) x L := begin induction n with n ihn, { exact has_fderiv_at_filter_id x L }, { change has_fderiv_at_filter (f^[n] ∘ f) (f'^(n+1)) x L, rw [pow_succ'], refine has_fderiv_at_filter.comp x _ hf, rw hx, exact ihn.mono hL } end protected lemma has_fderiv_at.iterate {f : E → E} {f' : E →L[𝕜] E} (hf : has_fderiv_at f f' x) (hx : f x = x) (n : ℕ) : has_fderiv_at (f^[n]) (f'^n) x := begin refine hf.iterate _ hx n, convert hf.continuous_at, exact hx.symm end protected lemma has_fderiv_within_at.iterate {f : E → E} {f' : E →L[𝕜] E} (hf : has_fderiv_within_at f f' s x) (hx : f x = x) (hs : maps_to f s s) (n : ℕ) : has_fderiv_within_at (f^[n]) (f'^n) s x := begin refine hf.iterate _ hx n, convert tendsto_inf.2 ⟨hf.continuous_within_at, _⟩, exacts [hx.symm, (tendsto_principal_principal.2 hs).mono_left inf_le_right] end protected lemma has_strict_fderiv_at.iterate {f : E → E} {f' : E →L[𝕜] E} (hf : has_strict_fderiv_at f f' x) (hx : f x = x) (n : ℕ) : has_strict_fderiv_at (f^[n]) (f'^n) x := begin induction n with n ihn, { exact has_strict_fderiv_at_id x }, { change has_strict_fderiv_at (f^[n] ∘ f) (f'^(n+1)) x, rw [pow_succ'], refine has_strict_fderiv_at.comp x _ hf, rwa hx } end protected lemma differentiable_at.iterate {f : E → E} (hf : differentiable_at 𝕜 f x) (hx : f x = x) (n : ℕ) : differentiable_at 𝕜 (f^[n]) x := exists.elim hf $ λ f' hf, (hf.iterate hx n).differentiable_at protected lemma differentiable_within_at.iterate {f : E → E} (hf : differentiable_within_at 𝕜 f s x) (hx : f x = x) (hs : maps_to f s s) (n : ℕ) : differentiable_within_at 𝕜 (f^[n]) s x := exists.elim hf $ λ f' hf, (hf.iterate hx hs n).differentiable_within_at end composition section cartesian_product /-! ### Derivative of the cartesian product of two functions -/ section prod variables {f₂ : E → G} {f₂' : E →L[𝕜] G} protected lemma has_strict_fderiv_at.prod (hf₁ : has_strict_fderiv_at f₁ f₁' x) (hf₂ : has_strict_fderiv_at f₂ f₂' x) : has_strict_fderiv_at (λx, (f₁ x, f₂ x)) (f₁'.prod f₂') x := hf₁.prod_left hf₂ lemma has_fderiv_at_filter.prod (hf₁ : has_fderiv_at_filter f₁ f₁' x L) (hf₂ : has_fderiv_at_filter f₂ f₂' x L) : has_fderiv_at_filter (λx, (f₁ x, f₂ x)) (f₁'.prod f₂') x L := hf₁.prod_left hf₂ lemma has_fderiv_within_at.prod (hf₁ : has_fderiv_within_at f₁ f₁' s x) (hf₂ : has_fderiv_within_at f₂ f₂' s x) : has_fderiv_within_at (λx, (f₁ x, f₂ x)) (f₁'.prod f₂') s x := hf₁.prod hf₂ lemma has_fderiv_at.prod (hf₁ : has_fderiv_at f₁ f₁' x) (hf₂ : has_fderiv_at f₂ f₂' x) : has_fderiv_at (λx, (f₁ x, f₂ x)) (continuous_linear_map.prod f₁' f₂') x := hf₁.prod hf₂ lemma differentiable_within_at.prod (hf₁ : differentiable_within_at 𝕜 f₁ s x) (hf₂ : differentiable_within_at 𝕜 f₂ s x) : differentiable_within_at 𝕜 (λx:E, (f₁ x, f₂ x)) s x := (hf₁.has_fderiv_within_at.prod hf₂.has_fderiv_within_at).differentiable_within_at @[simp] lemma differentiable_at.prod (hf₁ : differentiable_at 𝕜 f₁ x) (hf₂ : differentiable_at 𝕜 f₂ x) : differentiable_at 𝕜 (λx:E, (f₁ x, f₂ x)) x := (hf₁.has_fderiv_at.prod hf₂.has_fderiv_at).differentiable_at lemma differentiable_on.prod (hf₁ : differentiable_on 𝕜 f₁ s) (hf₂ : differentiable_on 𝕜 f₂ s) : differentiable_on 𝕜 (λx:E, (f₁ x, f₂ x)) s := λx hx, differentiable_within_at.prod (hf₁ x hx) (hf₂ x hx) @[simp] lemma differentiable.prod (hf₁ : differentiable 𝕜 f₁) (hf₂ : differentiable 𝕜 f₂) : differentiable 𝕜 (λx:E, (f₁ x, f₂ x)) := λ x, differentiable_at.prod (hf₁ x) (hf₂ x) lemma differentiable_at.fderiv_prod (hf₁ : differentiable_at 𝕜 f₁ x) (hf₂ : differentiable_at 𝕜 f₂ x) : fderiv 𝕜 (λx:E, (f₁ x, f₂ x)) x = (fderiv 𝕜 f₁ x).prod (fderiv 𝕜 f₂ x) := (hf₁.has_fderiv_at.prod hf₂.has_fderiv_at).fderiv lemma differentiable_at.fderiv_within_prod (hf₁ : differentiable_within_at 𝕜 f₁ s x) (hf₂ : differentiable_within_at 𝕜 f₂ s x) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λx:E, (f₁ x, f₂ x)) s x = (fderiv_within 𝕜 f₁ s x).prod (fderiv_within 𝕜 f₂ s x) := begin apply has_fderiv_within_at.fderiv_within _ hxs, exact has_fderiv_within_at.prod hf₁.has_fderiv_within_at hf₂.has_fderiv_within_at end end prod section fst variables {f₂ : E → F × G} {f₂' : E →L[𝕜] F × G} {p : E × F} lemma has_strict_fderiv_at_fst : has_strict_fderiv_at (fst 𝕜 E F) (fst 𝕜 E F) p := (fst 𝕜 E F).has_strict_fderiv_at protected lemma has_strict_fderiv_at.fst (h : has_strict_fderiv_at f₂ f₂' x) : has_strict_fderiv_at (λ x, (f₂ x).1) ((fst 𝕜 F G).comp f₂') x := has_strict_fderiv_at_fst.comp x h lemma has_fderiv_at_filter_fst {L : filter (E × F)} : has_fderiv_at_filter (fst 𝕜 E F) (fst 𝕜 E F) p L := (fst 𝕜 E F).has_fderiv_at_filter protected lemma has_fderiv_at_filter.fst (h : has_fderiv_at_filter f₂ f₂' x L) : has_fderiv_at_filter (λ x, (f₂ x).1) ((fst 𝕜 F G).comp f₂') x L := has_fderiv_at_filter_fst.comp x h lemma has_fderiv_at_fst : has_fderiv_at (fst 𝕜 E F) (fst 𝕜 E F) p := has_fderiv_at_filter_fst protected lemma has_fderiv_at.fst (h : has_fderiv_at f₂ f₂' x) : has_fderiv_at (λ x, (f₂ x).1) ((fst 𝕜 F G).comp f₂') x := h.fst lemma has_fderiv_within_at_fst {s : set (E × F)} : has_fderiv_within_at (fst 𝕜 E F) (fst 𝕜 E F) s p := has_fderiv_at_filter_fst protected lemma has_fderiv_within_at.fst (h : has_fderiv_within_at f₂ f₂' s x) : has_fderiv_within_at (λ x, (f₂ x).1) ((fst 𝕜 F G).comp f₂') s x := h.fst lemma differentiable_at_fst : differentiable_at 𝕜 prod.fst p := has_fderiv_at_fst.differentiable_at @[simp] protected lemma differentiable_at.fst (h : differentiable_at 𝕜 f₂ x) : differentiable_at 𝕜 (λ x, (f₂ x).1) x := differentiable_at_fst.comp x h lemma differentiable_fst : differentiable 𝕜 (prod.fst : E × F → E) := λ x, differentiable_at_fst @[simp] protected lemma differentiable.fst (h : differentiable 𝕜 f₂) : differentiable 𝕜 (λ x, (f₂ x).1) := differentiable_fst.comp h lemma differentiable_within_at_fst {s : set (E × F)} : differentiable_within_at 𝕜 prod.fst s p := differentiable_at_fst.differentiable_within_at protected lemma differentiable_within_at.fst (h : differentiable_within_at 𝕜 f₂ s x) : differentiable_within_at 𝕜 (λ x, (f₂ x).1) s x := differentiable_at_fst.comp_differentiable_within_at x h lemma differentiable_on_fst {s : set (E × F)} : differentiable_on 𝕜 prod.fst s := differentiable_fst.differentiable_on protected lemma differentiable_on.fst (h : differentiable_on 𝕜 f₂ s) : differentiable_on 𝕜 (λ x, (f₂ x).1) s := differentiable_fst.comp_differentiable_on h lemma fderiv_fst : fderiv 𝕜 prod.fst p = fst 𝕜 E F := has_fderiv_at_fst.fderiv lemma fderiv.fst (h : differentiable_at 𝕜 f₂ x) : fderiv 𝕜 (λ x, (f₂ x).1) x = (fst 𝕜 F G).comp (fderiv 𝕜 f₂ x) := h.has_fderiv_at.fst.fderiv lemma fderiv_within_fst {s : set (E × F)} (hs : unique_diff_within_at 𝕜 s p) : fderiv_within 𝕜 prod.fst s p = fst 𝕜 E F := has_fderiv_within_at_fst.fderiv_within hs lemma fderiv_within.fst (hs : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f₂ s x) : fderiv_within 𝕜 (λ x, (f₂ x).1) s x = (fst 𝕜 F G).comp (fderiv_within 𝕜 f₂ s x) := h.has_fderiv_within_at.fst.fderiv_within hs end fst section snd variables {f₂ : E → F × G} {f₂' : E →L[𝕜] F × G} {p : E × F} lemma has_strict_fderiv_at_snd : has_strict_fderiv_at (snd 𝕜 E F) (snd 𝕜 E F) p := (snd 𝕜 E F).has_strict_fderiv_at protected lemma has_strict_fderiv_at.snd (h : has_strict_fderiv_at f₂ f₂' x) : has_strict_fderiv_at (λ x, (f₂ x).2) ((snd 𝕜 F G).comp f₂') x := has_strict_fderiv_at_snd.comp x h lemma has_fderiv_at_filter_snd {L : filter (E × F)} : has_fderiv_at_filter (snd 𝕜 E F) (snd 𝕜 E F) p L := (snd 𝕜 E F).has_fderiv_at_filter protected lemma has_fderiv_at_filter.snd (h : has_fderiv_at_filter f₂ f₂' x L) : has_fderiv_at_filter (λ x, (f₂ x).2) ((snd 𝕜 F G).comp f₂') x L := has_fderiv_at_filter_snd.comp x h lemma has_fderiv_at_snd : has_fderiv_at (snd 𝕜 E F) (snd 𝕜 E F) p := has_fderiv_at_filter_snd protected lemma has_fderiv_at.snd (h : has_fderiv_at f₂ f₂' x) : has_fderiv_at (λ x, (f₂ x).2) ((snd 𝕜 F G).comp f₂') x := h.snd lemma has_fderiv_within_at_snd {s : set (E × F)} : has_fderiv_within_at (snd 𝕜 E F) (snd 𝕜 E F) s p := has_fderiv_at_filter_snd protected lemma has_fderiv_within_at.snd (h : has_fderiv_within_at f₂ f₂' s x) : has_fderiv_within_at (λ x, (f₂ x).2) ((snd 𝕜 F G).comp f₂') s x := h.snd lemma differentiable_at_snd : differentiable_at 𝕜 prod.snd p := has_fderiv_at_snd.differentiable_at @[simp] protected lemma differentiable_at.snd (h : differentiable_at 𝕜 f₂ x) : differentiable_at 𝕜 (λ x, (f₂ x).2) x := differentiable_at_snd.comp x h lemma differentiable_snd : differentiable 𝕜 (prod.snd : E × F → F) := λ x, differentiable_at_snd @[simp] protected lemma differentiable.snd (h : differentiable 𝕜 f₂) : differentiable 𝕜 (λ x, (f₂ x).2) := differentiable_snd.comp h lemma differentiable_within_at_snd {s : set (E × F)} : differentiable_within_at 𝕜 prod.snd s p := differentiable_at_snd.differentiable_within_at protected lemma differentiable_within_at.snd (h : differentiable_within_at 𝕜 f₂ s x) : differentiable_within_at 𝕜 (λ x, (f₂ x).2) s x := differentiable_at_snd.comp_differentiable_within_at x h lemma differentiable_on_snd {s : set (E × F)} : differentiable_on 𝕜 prod.snd s := differentiable_snd.differentiable_on protected lemma differentiable_on.snd (h : differentiable_on 𝕜 f₂ s) : differentiable_on 𝕜 (λ x, (f₂ x).2) s := differentiable_snd.comp_differentiable_on h lemma fderiv_snd : fderiv 𝕜 prod.snd p = snd 𝕜 E F := has_fderiv_at_snd.fderiv lemma fderiv.snd (h : differentiable_at 𝕜 f₂ x) : fderiv 𝕜 (λ x, (f₂ x).2) x = (snd 𝕜 F G).comp (fderiv 𝕜 f₂ x) := h.has_fderiv_at.snd.fderiv lemma fderiv_within_snd {s : set (E × F)} (hs : unique_diff_within_at 𝕜 s p) : fderiv_within 𝕜 prod.snd s p = snd 𝕜 E F := has_fderiv_within_at_snd.fderiv_within hs lemma fderiv_within.snd (hs : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f₂ s x) : fderiv_within 𝕜 (λ x, (f₂ x).2) s x = (snd 𝕜 F G).comp (fderiv_within 𝕜 f₂ s x) := h.has_fderiv_within_at.snd.fderiv_within hs end snd section prod_map variables {f₂ : G → G'} {f₂' : G →L[𝕜] G'} {y : G} (p : E × G) -- TODO (Lean 3.8): use `prod.map f f₂`` protected theorem has_strict_fderiv_at.prod_map (hf : has_strict_fderiv_at f f' p.1) (hf₂ : has_strict_fderiv_at f₂ f₂' p.2) : has_strict_fderiv_at (λ p : E × G, (f p.1, f₂ p.2)) (f'.prod_map f₂') p := (hf.comp p has_strict_fderiv_at_fst).prod (hf₂.comp p has_strict_fderiv_at_snd) protected theorem has_fderiv_at.prod_map (hf : has_fderiv_at f f' p.1) (hf₂ : has_fderiv_at f₂ f₂' p.2) : has_fderiv_at (λ p : E × G, (f p.1, f₂ p.2)) (f'.prod_map f₂') p := (hf.comp p has_fderiv_at_fst).prod (hf₂.comp p has_fderiv_at_snd) @[simp] protected theorem differentiable_at.prod_map (hf : differentiable_at 𝕜 f p.1) (hf₂ : differentiable_at 𝕜 f₂ p.2) : differentiable_at 𝕜 (λ p : E × G, (f p.1, f₂ p.2)) p := (hf.comp p differentiable_at_fst).prod (hf₂.comp p differentiable_at_snd) end prod_map end cartesian_product section const_smul /-! ### Derivative of a function multiplied by a constant -/ theorem has_strict_fderiv_at.const_smul (h : has_strict_fderiv_at f f' x) (c : 𝕜) : has_strict_fderiv_at (λ x, c • f x) (c • f') x := (c • (1 : F →L[𝕜] F)).has_strict_fderiv_at.comp x h theorem has_fderiv_at_filter.const_smul (h : has_fderiv_at_filter f f' x L) (c : 𝕜) : has_fderiv_at_filter (λ x, c • f x) (c • f') x L := (c • (1 : F →L[𝕜] F)).has_fderiv_at_filter.comp x h theorem has_fderiv_within_at.const_smul (h : has_fderiv_within_at f f' s x) (c : 𝕜) : has_fderiv_within_at (λ x, c • f x) (c • f') s x := h.const_smul c theorem has_fderiv_at.const_smul (h : has_fderiv_at f f' x) (c : 𝕜) : has_fderiv_at (λ x, c • f x) (c • f') x := h.const_smul c lemma differentiable_within_at.const_smul (h : differentiable_within_at 𝕜 f s x) (c : 𝕜) : differentiable_within_at 𝕜 (λy, c • f y) s x := (h.has_fderiv_within_at.const_smul c).differentiable_within_at lemma differentiable_at.const_smul (h : differentiable_at 𝕜 f x) (c : 𝕜) : differentiable_at 𝕜 (λy, c • f y) x := (h.has_fderiv_at.const_smul c).differentiable_at lemma differentiable_on.const_smul (h : differentiable_on 𝕜 f s) (c : 𝕜) : differentiable_on 𝕜 (λy, c • f y) s := λx hx, (h x hx).const_smul c lemma differentiable.const_smul (h : differentiable 𝕜 f) (c : 𝕜) : differentiable 𝕜 (λy, c • f y) := λx, (h x).const_smul c lemma fderiv_within_const_smul (hxs : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f s x) (c : 𝕜) : fderiv_within 𝕜 (λy, c • f y) s x = c • fderiv_within 𝕜 f s x := (h.has_fderiv_within_at.const_smul c).fderiv_within hxs lemma fderiv_const_smul (h : differentiable_at 𝕜 f x) (c : 𝕜) : fderiv 𝕜 (λy, c • f y) x = c • fderiv 𝕜 f x := (h.has_fderiv_at.const_smul c).fderiv end const_smul section add /-! ### Derivative of the sum of two functions -/ theorem has_strict_fderiv_at.add (hf : has_strict_fderiv_at f f' x) (hg : has_strict_fderiv_at g g' x) : has_strict_fderiv_at (λ y, f y + g y) (f' + g') x := (hf.add hg).congr_left $ λ y, by simp; abel theorem has_fderiv_at_filter.add (hf : has_fderiv_at_filter f f' x L) (hg : has_fderiv_at_filter g g' x L) : has_fderiv_at_filter (λ y, f y + g y) (f' + g') x L := (hf.add hg).congr_left $ λ _, by simp; abel theorem has_fderiv_within_at.add (hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at g g' s x) : has_fderiv_within_at (λ y, f y + g y) (f' + g') s x := hf.add hg theorem has_fderiv_at.add (hf : has_fderiv_at f f' x) (hg : has_fderiv_at g g' x) : has_fderiv_at (λ x, f x + g x) (f' + g') x := hf.add hg lemma differentiable_within_at.add (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : differentiable_within_at 𝕜 (λ y, f y + g y) s x := (hf.has_fderiv_within_at.add hg.has_fderiv_within_at).differentiable_within_at @[simp] lemma differentiable_at.add (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : differentiable_at 𝕜 (λ y, f y + g y) x := (hf.has_fderiv_at.add hg.has_fderiv_at).differentiable_at lemma differentiable_on.add (hf : differentiable_on 𝕜 f s) (hg : differentiable_on 𝕜 g s) : differentiable_on 𝕜 (λy, f y + g y) s := λx hx, (hf x hx).add (hg x hx) @[simp] lemma differentiable.add (hf : differentiable 𝕜 f) (hg : differentiable 𝕜 g) : differentiable 𝕜 (λy, f y + g y) := λx, (hf x).add (hg x) lemma fderiv_within_add (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : fderiv_within 𝕜 (λy, f y + g y) s x = fderiv_within 𝕜 f s x + fderiv_within 𝕜 g s x := (hf.has_fderiv_within_at.add hg.has_fderiv_within_at).fderiv_within hxs lemma fderiv_add (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : fderiv 𝕜 (λy, f y + g y) x = fderiv 𝕜 f x + fderiv 𝕜 g x := (hf.has_fderiv_at.add hg.has_fderiv_at).fderiv theorem has_strict_fderiv_at.add_const (hf : has_strict_fderiv_at f f' x) (c : F) : has_strict_fderiv_at (λ y, f y + c) f' x := add_zero f' ▸ hf.add (has_strict_fderiv_at_const _ _) theorem has_fderiv_at_filter.add_const (hf : has_fderiv_at_filter f f' x L) (c : F) : has_fderiv_at_filter (λ y, f y + c) f' x L := add_zero f' ▸ hf.add (has_fderiv_at_filter_const _ _ _) theorem has_fderiv_within_at.add_const (hf : has_fderiv_within_at f f' s x) (c : F) : has_fderiv_within_at (λ y, f y + c) f' s x := hf.add_const c theorem has_fderiv_at.add_const (hf : has_fderiv_at f f' x) (c : F): has_fderiv_at (λ x, f x + c) f' x := hf.add_const c lemma differentiable_within_at.add_const (hf : differentiable_within_at 𝕜 f s x) (c : F) : differentiable_within_at 𝕜 (λ y, f y + c) s x := (hf.has_fderiv_within_at.add_const c).differentiable_within_at @[simp] lemma differentiable_within_at_add_const_iff (c : F) : differentiable_within_at 𝕜 (λ y, f y + c) s x ↔ differentiable_within_at 𝕜 f s x := ⟨λ h, by simpa using h.add_const (-c), λ h, h.add_const c⟩ lemma differentiable_at.add_const (hf : differentiable_at 𝕜 f x) (c : F) : differentiable_at 𝕜 (λ y, f y + c) x := (hf.has_fderiv_at.add_const c).differentiable_at @[simp] lemma differentiable_at_add_const_iff (c : F) : differentiable_at 𝕜 (λ y, f y + c) x ↔ differentiable_at 𝕜 f x := ⟨λ h, by simpa using h.add_const (-c), λ h, h.add_const c⟩ lemma differentiable_on.add_const (hf : differentiable_on 𝕜 f s) (c : F) : differentiable_on 𝕜 (λy, f y + c) s := λx hx, (hf x hx).add_const c @[simp] lemma differentiable_on_add_const_iff (c : F) : differentiable_on 𝕜 (λ y, f y + c) s ↔ differentiable_on 𝕜 f s := ⟨λ h, by simpa using h.add_const (-c), λ h, h.add_const c⟩ lemma differentiable.add_const (hf : differentiable 𝕜 f) (c : F) : differentiable 𝕜 (λy, f y + c) := λx, (hf x).add_const c @[simp] lemma differentiable_add_const_iff (c : F) : differentiable 𝕜 (λ y, f y + c) ↔ differentiable 𝕜 f := ⟨λ h, by simpa using h.add_const (-c), λ h, h.add_const c⟩ lemma fderiv_within_add_const (hxs : unique_diff_within_at 𝕜 s x) (c : F) : fderiv_within 𝕜 (λy, f y + c) s x = fderiv_within 𝕜 f s x := if hf : differentiable_within_at 𝕜 f s x then (hf.has_fderiv_within_at.add_const c).fderiv_within hxs else by { rw [fderiv_within_zero_of_not_differentiable_within_at hf, fderiv_within_zero_of_not_differentiable_within_at], simpa } lemma fderiv_add_const (c : F) : fderiv 𝕜 (λy, f y + c) x = fderiv 𝕜 f x := by simp only [← fderiv_within_univ, fderiv_within_add_const unique_diff_within_at_univ] theorem has_strict_fderiv_at.const_add (hf : has_strict_fderiv_at f f' x) (c : F) : has_strict_fderiv_at (λ y, c + f y) f' x := zero_add f' ▸ (has_strict_fderiv_at_const _ _).add hf theorem has_fderiv_at_filter.const_add (hf : has_fderiv_at_filter f f' x L) (c : F) : has_fderiv_at_filter (λ y, c + f y) f' x L := zero_add f' ▸ (has_fderiv_at_filter_const _ _ _).add hf theorem has_fderiv_within_at.const_add (hf : has_fderiv_within_at f f' s x) (c : F) : has_fderiv_within_at (λ y, c + f y) f' s x := hf.const_add c theorem has_fderiv_at.const_add (hf : has_fderiv_at f f' x) (c : F): has_fderiv_at (λ x, c + f x) f' x := hf.const_add c lemma differentiable_within_at.const_add (hf : differentiable_within_at 𝕜 f s x) (c : F) : differentiable_within_at 𝕜 (λ y, c + f y) s x := (hf.has_fderiv_within_at.const_add c).differentiable_within_at @[simp] lemma differentiable_within_at_const_add_iff (c : F) : differentiable_within_at 𝕜 (λ y, c + f y) s x ↔ differentiable_within_at 𝕜 f s x := ⟨λ h, by simpa using h.const_add (-c), λ h, h.const_add c⟩ lemma differentiable_at.const_add (hf : differentiable_at 𝕜 f x) (c : F) : differentiable_at 𝕜 (λ y, c + f y) x := (hf.has_fderiv_at.const_add c).differentiable_at @[simp] lemma differentiable_at_const_add_iff (c : F) : differentiable_at 𝕜 (λ y, c + f y) x ↔ differentiable_at 𝕜 f x := ⟨λ h, by simpa using h.const_add (-c), λ h, h.const_add c⟩ lemma differentiable_on.const_add (hf : differentiable_on 𝕜 f s) (c : F) : differentiable_on 𝕜 (λy, c + f y) s := λx hx, (hf x hx).const_add c @[simp] lemma differentiable_on_const_add_iff (c : F) : differentiable_on 𝕜 (λ y, c + f y) s ↔ differentiable_on 𝕜 f s := ⟨λ h, by simpa using h.const_add (-c), λ h, h.const_add c⟩ lemma differentiable.const_add (hf : differentiable 𝕜 f) (c : F) : differentiable 𝕜 (λy, c + f y) := λx, (hf x).const_add c @[simp] lemma differentiable_const_add_iff (c : F) : differentiable 𝕜 (λ y, c + f y) ↔ differentiable 𝕜 f := ⟨λ h, by simpa using h.const_add (-c), λ h, h.const_add c⟩ lemma fderiv_within_const_add (hxs : unique_diff_within_at 𝕜 s x) (c : F) : fderiv_within 𝕜 (λy, c + f y) s x = fderiv_within 𝕜 f s x := by simpa only [add_comm] using fderiv_within_add_const hxs c lemma fderiv_const_add (c : F) : fderiv 𝕜 (λy, c + f y) x = fderiv 𝕜 f x := by simp only [add_comm c, fderiv_add_const] end add section sum /-! ### Derivative of a finite sum of functions -/ open_locale big_operators variables {ι : Type*} {u : finset ι} {A : ι → (E → F)} {A' : ι → (E →L[𝕜] F)} theorem has_strict_fderiv_at.sum (h : ∀ i ∈ u, has_strict_fderiv_at (A i) (A' i) x) : has_strict_fderiv_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x := begin dsimp [has_strict_fderiv_at] at *, convert is_o.sum h, simp [finset.sum_sub_distrib, continuous_linear_map.sum_apply] end theorem has_fderiv_at_filter.sum (h : ∀ i ∈ u, has_fderiv_at_filter (A i) (A' i) x L) : has_fderiv_at_filter (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x L := begin dsimp [has_fderiv_at_filter] at *, convert is_o.sum h, simp [continuous_linear_map.sum_apply] end theorem has_fderiv_within_at.sum (h : ∀ i ∈ u, has_fderiv_within_at (A i) (A' i) s x) : has_fderiv_within_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) s x := has_fderiv_at_filter.sum h theorem has_fderiv_at.sum (h : ∀ i ∈ u, has_fderiv_at (A i) (A' i) x) : has_fderiv_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x := has_fderiv_at_filter.sum h theorem differentiable_within_at.sum (h : ∀ i ∈ u, differentiable_within_at 𝕜 (A i) s x) : differentiable_within_at 𝕜 (λ y, ∑ i in u, A i y) s x := has_fderiv_within_at.differentiable_within_at $ has_fderiv_within_at.sum $ λ i hi, (h i hi).has_fderiv_within_at @[simp] theorem differentiable_at.sum (h : ∀ i ∈ u, differentiable_at 𝕜 (A i) x) : differentiable_at 𝕜 (λ y, ∑ i in u, A i y) x := has_fderiv_at.differentiable_at $ has_fderiv_at.sum $ λ i hi, (h i hi).has_fderiv_at theorem differentiable_on.sum (h : ∀ i ∈ u, differentiable_on 𝕜 (A i) s) : differentiable_on 𝕜 (λ y, ∑ i in u, A i y) s := λ x hx, differentiable_within_at.sum $ λ i hi, h i hi x hx @[simp] theorem differentiable.sum (h : ∀ i ∈ u, differentiable 𝕜 (A i)) : differentiable 𝕜 (λ y, ∑ i in u, A i y) := λ x, differentiable_at.sum $ λ i hi, h i hi x theorem fderiv_within_sum (hxs : unique_diff_within_at 𝕜 s x) (h : ∀ i ∈ u, differentiable_within_at 𝕜 (A i) s x) : fderiv_within 𝕜 (λ y, ∑ i in u, A i y) s x = (∑ i in u, fderiv_within 𝕜 (A i) s x) := (has_fderiv_within_at.sum (λ i hi, (h i hi).has_fderiv_within_at)).fderiv_within hxs theorem fderiv_sum (h : ∀ i ∈ u, differentiable_at 𝕜 (A i) x) : fderiv 𝕜 (λ y, ∑ i in u, A i y) x = (∑ i in u, fderiv 𝕜 (A i) x) := (has_fderiv_at.sum (λ i hi, (h i hi).has_fderiv_at)).fderiv end sum section pi /-! ### Derivatives of functions `f : E → Π i, F' i` In this section we formulate `has_*fderiv*_pi` theorems as `iff`s, and provide two versions of each theorem: * the version without `'` deals with `φ : Π i, E → F' i` and `φ' : Π i, E →L[𝕜] F' i` and is designed to deduce differentiability of `λ x i, φ i x` from differentiability of each `φ i`; * the version with `'` deals with `Φ : E → Π i, F' i` and `Φ' : E →L[𝕜] Π i, F' i` and is designed to deduce differentiability of the components `λ x, Φ x i` from differentiability of `Φ`. -/ variables {ι : Type*} [fintype ι] {F' : ι → Type*} [Π i, normed_group (F' i)] [Π i, normed_space 𝕜 (F' i)] {φ : Π i, E → F' i} {φ' : Π i, E →L[𝕜] F' i} {Φ : E → Π i, F' i} {Φ' : E →L[𝕜] Π i, F' i} @[simp] lemma has_strict_fderiv_at_pi' : has_strict_fderiv_at Φ Φ' x ↔ ∀ i, has_strict_fderiv_at (λ x, Φ x i) ((proj i).comp Φ') x := begin simp only [has_strict_fderiv_at, continuous_linear_map.coe_pi], exact is_o_pi end @[simp] lemma has_strict_fderiv_at_pi : has_strict_fderiv_at (λ x i, φ i x) (continuous_linear_map.pi φ') x ↔ ∀ i, has_strict_fderiv_at (φ i) (φ' i) x := has_strict_fderiv_at_pi' @[simp] lemma has_fderiv_at_filter_pi' : has_fderiv_at_filter Φ Φ' x L ↔ ∀ i, has_fderiv_at_filter (λ x, Φ x i) ((proj i).comp Φ') x L := begin simp only [has_fderiv_at_filter, continuous_linear_map.coe_pi], exact is_o_pi end lemma has_fderiv_at_filter_pi : has_fderiv_at_filter (λ x i, φ i x) (continuous_linear_map.pi φ') x L ↔ ∀ i, has_fderiv_at_filter (φ i) (φ' i) x L := has_fderiv_at_filter_pi' @[simp] lemma has_fderiv_at_pi' : has_fderiv_at Φ Φ' x ↔ ∀ i, has_fderiv_at (λ x, Φ x i) ((proj i).comp Φ') x := has_fderiv_at_filter_pi' lemma has_fderiv_at_pi : has_fderiv_at (λ x i, φ i x) (continuous_linear_map.pi φ') x ↔ ∀ i, has_fderiv_at (φ i) (φ' i) x := has_fderiv_at_filter_pi @[simp] lemma has_fderiv_within_at_pi' : has_fderiv_within_at Φ Φ' s x ↔ ∀ i, has_fderiv_within_at (λ x, Φ x i) ((proj i).comp Φ') s x := has_fderiv_at_filter_pi' lemma has_fderiv_within_at_pi : has_fderiv_within_at (λ x i, φ i x) (continuous_linear_map.pi φ') s x ↔ ∀ i, has_fderiv_within_at (φ i) (φ' i) s x := has_fderiv_at_filter_pi @[simp] lemma differentiable_within_at_pi : differentiable_within_at 𝕜 Φ s x ↔ ∀ i, differentiable_within_at 𝕜 (λ x, Φ x i) s x := ⟨λ h i, (has_fderiv_within_at_pi'.1 h.has_fderiv_within_at i).differentiable_within_at, λ h, (has_fderiv_within_at_pi.2 (λ i, (h i).has_fderiv_within_at)).differentiable_within_at⟩ @[simp] lemma differentiable_at_pi : differentiable_at 𝕜 Φ x ↔ ∀ i, differentiable_at 𝕜 (λ x, Φ x i) x := ⟨λ h i, (has_fderiv_at_pi'.1 h.has_fderiv_at i).differentiable_at, λ h, (has_fderiv_at_pi.2 (λ i, (h i).has_fderiv_at)).differentiable_at⟩ lemma differentiable_on_pi : differentiable_on 𝕜 Φ s ↔ ∀ i, differentiable_on 𝕜 (λ x, Φ x i) s := ⟨λ h i x hx, differentiable_within_at_pi.1 (h x hx) i, λ h x hx, differentiable_within_at_pi.2 (λ i, h i x hx)⟩ lemma differentiable_pi : differentiable 𝕜 Φ ↔ ∀ i, differentiable 𝕜 (λ x, Φ x i) := ⟨λ h i x, differentiable_at_pi.1 (h x) i, λ h x, differentiable_at_pi.2 (λ i, h i x)⟩ -- TODO: find out which version (`φ` or `Φ`) works better with `rw`/`simp` lemma fderiv_within_pi (h : ∀ i, differentiable_within_at 𝕜 (φ i) s x) (hs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λ x i, φ i x) s x = pi (λ i, fderiv_within 𝕜 (φ i) s x) := (has_fderiv_within_at_pi.2 (λ i, (h i).has_fderiv_within_at)).fderiv_within hs lemma fderiv_pi (h : ∀ i, differentiable_at 𝕜 (φ i) x) : fderiv 𝕜 (λ x i, φ i x) x = pi (λ i, fderiv 𝕜 (φ i) x) := (has_fderiv_at_pi.2 (λ i, (h i).has_fderiv_at)).fderiv end pi section neg /-! ### Derivative of the negative of a function -/ theorem has_strict_fderiv_at.neg (h : has_strict_fderiv_at f f' x) : has_strict_fderiv_at (λ x, -f x) (-f') x := (-1 : F →L[𝕜] F).has_strict_fderiv_at.comp x h theorem has_fderiv_at_filter.neg (h : has_fderiv_at_filter f f' x L) : has_fderiv_at_filter (λ x, -f x) (-f') x L := (-1 : F →L[𝕜] F).has_fderiv_at_filter.comp x h theorem has_fderiv_within_at.neg (h : has_fderiv_within_at f f' s x) : has_fderiv_within_at (λ x, -f x) (-f') s x := h.neg theorem has_fderiv_at.neg (h : has_fderiv_at f f' x) : has_fderiv_at (λ x, -f x) (-f') x := h.neg lemma differentiable_within_at.neg (h : differentiable_within_at 𝕜 f s x) : differentiable_within_at 𝕜 (λy, -f y) s x := h.has_fderiv_within_at.neg.differentiable_within_at @[simp] lemma differentiable_within_at_neg_iff : differentiable_within_at 𝕜 (λy, -f y) s x ↔ differentiable_within_at 𝕜 f s x := ⟨λ h, by simpa only [neg_neg] using h.neg, λ h, h.neg⟩ lemma differentiable_at.neg (h : differentiable_at 𝕜 f x) : differentiable_at 𝕜 (λy, -f y) x := h.has_fderiv_at.neg.differentiable_at @[simp] lemma differentiable_at_neg_iff : differentiable_at 𝕜 (λy, -f y) x ↔ differentiable_at 𝕜 f x := ⟨λ h, by simpa only [neg_neg] using h.neg, λ h, h.neg⟩ lemma differentiable_on.neg (h : differentiable_on 𝕜 f s) : differentiable_on 𝕜 (λy, -f y) s := λx hx, (h x hx).neg @[simp] lemma differentiable_on_neg_iff : differentiable_on 𝕜 (λy, -f y) s ↔ differentiable_on 𝕜 f s := ⟨λ h, by simpa only [neg_neg] using h.neg, λ h, h.neg⟩ lemma differentiable.neg (h : differentiable 𝕜 f) : differentiable 𝕜 (λy, -f y) := λx, (h x).neg @[simp] lemma differentiable_neg_iff : differentiable 𝕜 (λy, -f y) ↔ differentiable 𝕜 f := ⟨λ h, by simpa only [neg_neg] using h.neg, λ h, h.neg⟩ lemma fderiv_within_neg (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λy, -f y) s x = - fderiv_within 𝕜 f s x := if h : differentiable_within_at 𝕜 f s x then h.has_fderiv_within_at.neg.fderiv_within hxs else by { rw [fderiv_within_zero_of_not_differentiable_within_at h, fderiv_within_zero_of_not_differentiable_within_at, neg_zero], simpa } @[simp] lemma fderiv_neg : fderiv 𝕜 (λy, -f y) x = - fderiv 𝕜 f x := by simp only [← fderiv_within_univ, fderiv_within_neg unique_diff_within_at_univ] end neg section sub /-! ### Derivative of the difference of two functions -/ theorem has_strict_fderiv_at.sub (hf : has_strict_fderiv_at f f' x) (hg : has_strict_fderiv_at g g' x) : has_strict_fderiv_at (λ x, f x - g x) (f' - g') x := by simpa only [sub_eq_add_neg] using hf.add hg.neg theorem has_fderiv_at_filter.sub (hf : has_fderiv_at_filter f f' x L) (hg : has_fderiv_at_filter g g' x L) : has_fderiv_at_filter (λ x, f x - g x) (f' - g') x L := by simpa only [sub_eq_add_neg] using hf.add hg.neg theorem has_fderiv_within_at.sub (hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at g g' s x) : has_fderiv_within_at (λ x, f x - g x) (f' - g') s x := hf.sub hg theorem has_fderiv_at.sub (hf : has_fderiv_at f f' x) (hg : has_fderiv_at g g' x) : has_fderiv_at (λ x, f x - g x) (f' - g') x := hf.sub hg lemma differentiable_within_at.sub (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : differentiable_within_at 𝕜 (λ y, f y - g y) s x := (hf.has_fderiv_within_at.sub hg.has_fderiv_within_at).differentiable_within_at @[simp] lemma differentiable_at.sub (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : differentiable_at 𝕜 (λ y, f y - g y) x := (hf.has_fderiv_at.sub hg.has_fderiv_at).differentiable_at lemma differentiable_on.sub (hf : differentiable_on 𝕜 f s) (hg : differentiable_on 𝕜 g s) : differentiable_on 𝕜 (λy, f y - g y) s := λx hx, (hf x hx).sub (hg x hx) @[simp] lemma differentiable.sub (hf : differentiable 𝕜 f) (hg : differentiable 𝕜 g) : differentiable 𝕜 (λy, f y - g y) := λx, (hf x).sub (hg x) lemma fderiv_within_sub (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : fderiv_within 𝕜 (λy, f y - g y) s x = fderiv_within 𝕜 f s x - fderiv_within 𝕜 g s x := (hf.has_fderiv_within_at.sub hg.has_fderiv_within_at).fderiv_within hxs lemma fderiv_sub (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : fderiv 𝕜 (λy, f y - g y) x = fderiv 𝕜 f x - fderiv 𝕜 g x := (hf.has_fderiv_at.sub hg.has_fderiv_at).fderiv theorem has_strict_fderiv_at.sub_const (hf : has_strict_fderiv_at f f' x) (c : F) : has_strict_fderiv_at (λ x, f x - c) f' x := by simpa only [sub_eq_add_neg] using hf.add_const (-c) theorem has_fderiv_at_filter.sub_const (hf : has_fderiv_at_filter f f' x L) (c : F) : has_fderiv_at_filter (λ x, f x - c) f' x L := by simpa only [sub_eq_add_neg] using hf.add_const (-c) theorem has_fderiv_within_at.sub_const (hf : has_fderiv_within_at f f' s x) (c : F) : has_fderiv_within_at (λ x, f x - c) f' s x := hf.sub_const c theorem has_fderiv_at.sub_const (hf : has_fderiv_at f f' x) (c : F) : has_fderiv_at (λ x, f x - c) f' x := hf.sub_const c lemma differentiable_within_at.sub_const (hf : differentiable_within_at 𝕜 f s x) (c : F) : differentiable_within_at 𝕜 (λ y, f y - c) s x := (hf.has_fderiv_within_at.sub_const c).differentiable_within_at @[simp] lemma differentiable_within_at_sub_const_iff (c : F) : differentiable_within_at 𝕜 (λ y, f y - c) s x ↔ differentiable_within_at 𝕜 f s x := by simp only [sub_eq_add_neg, differentiable_within_at_add_const_iff] lemma differentiable_at.sub_const (hf : differentiable_at 𝕜 f x) (c : F) : differentiable_at 𝕜 (λ y, f y - c) x := (hf.has_fderiv_at.sub_const c).differentiable_at @[simp] lemma differentiable_at_sub_const_iff (c : F) : differentiable_at 𝕜 (λ y, f y - c) x ↔ differentiable_at 𝕜 f x := by simp only [sub_eq_add_neg, differentiable_at_add_const_iff] lemma differentiable_on.sub_const (hf : differentiable_on 𝕜 f s) (c : F) : differentiable_on 𝕜 (λy, f y - c) s := λx hx, (hf x hx).sub_const c @[simp] lemma differentiable_on_sub_const_iff (c : F) : differentiable_on 𝕜 (λ y, f y - c) s ↔ differentiable_on 𝕜 f s := by simp only [sub_eq_add_neg, differentiable_on_add_const_iff] lemma differentiable.sub_const (hf : differentiable 𝕜 f) (c : F) : differentiable 𝕜 (λy, f y - c) := λx, (hf x).sub_const c @[simp] lemma differentiable_sub_const_iff (c : F) : differentiable 𝕜 (λ y, f y - c) ↔ differentiable 𝕜 f := by simp only [sub_eq_add_neg, differentiable_add_const_iff] lemma fderiv_within_sub_const (hxs : unique_diff_within_at 𝕜 s x) (c : F) : fderiv_within 𝕜 (λy, f y - c) s x = fderiv_within 𝕜 f s x := by simp only [sub_eq_add_neg, fderiv_within_add_const hxs] lemma fderiv_sub_const (c : F) : fderiv 𝕜 (λy, f y - c) x = fderiv 𝕜 f x := by simp only [sub_eq_add_neg, fderiv_add_const] theorem has_strict_fderiv_at.const_sub (hf : has_strict_fderiv_at f f' x) (c : F) : has_strict_fderiv_at (λ x, c - f x) (-f') x := by simpa only [sub_eq_add_neg] using hf.neg.const_add c theorem has_fderiv_at_filter.const_sub (hf : has_fderiv_at_filter f f' x L) (c : F) : has_fderiv_at_filter (λ x, c - f x) (-f') x L := by simpa only [sub_eq_add_neg] using hf.neg.const_add c theorem has_fderiv_within_at.const_sub (hf : has_fderiv_within_at f f' s x) (c : F) : has_fderiv_within_at (λ x, c - f x) (-f') s x := hf.const_sub c theorem has_fderiv_at.const_sub (hf : has_fderiv_at f f' x) (c : F) : has_fderiv_at (λ x, c - f x) (-f') x := hf.const_sub c lemma differentiable_within_at.const_sub (hf : differentiable_within_at 𝕜 f s x) (c : F) : differentiable_within_at 𝕜 (λ y, c - f y) s x := (hf.has_fderiv_within_at.const_sub c).differentiable_within_at @[simp] lemma differentiable_within_at_const_sub_iff (c : F) : differentiable_within_at 𝕜 (λ y, c - f y) s x ↔ differentiable_within_at 𝕜 f s x := by simp [sub_eq_add_neg] lemma differentiable_at.const_sub (hf : differentiable_at 𝕜 f x) (c : F) : differentiable_at 𝕜 (λ y, c - f y) x := (hf.has_fderiv_at.const_sub c).differentiable_at @[simp] lemma differentiable_at_const_sub_iff (c : F) : differentiable_at 𝕜 (λ y, c - f y) x ↔ differentiable_at 𝕜 f x := by simp [sub_eq_add_neg] lemma differentiable_on.const_sub (hf : differentiable_on 𝕜 f s) (c : F) : differentiable_on 𝕜 (λy, c - f y) s := λx hx, (hf x hx).const_sub c @[simp] lemma differentiable_on_const_sub_iff (c : F) : differentiable_on 𝕜 (λ y, c - f y) s ↔ differentiable_on 𝕜 f s := by simp [sub_eq_add_neg] lemma differentiable.const_sub (hf : differentiable 𝕜 f) (c : F) : differentiable 𝕜 (λy, c - f y) := λx, (hf x).const_sub c @[simp] lemma differentiable_const_sub_iff (c : F) : differentiable 𝕜 (λ y, c - f y) ↔ differentiable 𝕜 f := by simp [sub_eq_add_neg] lemma fderiv_within_const_sub (hxs : unique_diff_within_at 𝕜 s x) (c : F) : fderiv_within 𝕜 (λy, c - f y) s x = -fderiv_within 𝕜 f s x := by simp only [sub_eq_add_neg, fderiv_within_const_add, fderiv_within_neg, hxs] lemma fderiv_const_sub (c : F) : fderiv 𝕜 (λy, c - f y) x = -fderiv 𝕜 f x := by simp only [← fderiv_within_univ, fderiv_within_const_sub unique_diff_within_at_univ] end sub section bilinear_map /-! ### Derivative of a bounded bilinear map -/ variables {b : E × F → G} {u : set (E × F) } open normed_field lemma is_bounded_bilinear_map.has_strict_fderiv_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : has_strict_fderiv_at b (h.deriv p) p := begin rw has_strict_fderiv_at, set T := (E × F) × (E × F), have : is_o (λ q : T, b (q.1 - q.2)) (λ q : T, ∥q.1 - q.2∥ * 1) (𝓝 (p, p)), { refine (h.is_O'.comp_tendsto le_top).trans_is_o _, simp only [(∘)], refine (is_O_refl (λ q : T, ∥q.1 - q.2∥) _).mul_is_o (is_o.norm_left $ (is_o_one_iff _).2 _), rw [← sub_self p], exact continuous_at_fst.sub continuous_at_snd }, simp only [mul_one, is_o_norm_right] at this, refine (is_o.congr_of_sub _).1 this, clear this, convert_to is_o (λ q : T, h.deriv (p - q.2) (q.1 - q.2)) (λ q : T, q.1 - q.2) (𝓝 (p, p)), { ext ⟨⟨x₁, y₁⟩, ⟨x₂, y₂⟩⟩, rcases p with ⟨x, y⟩, simp only [is_bounded_bilinear_map_deriv_coe, prod.mk_sub_mk, h.map_sub_left, h.map_sub_right], abel }, have : is_o (λ q : T, p - q.2) (λ q, (1:ℝ)) (𝓝 (p, p)), from (is_o_one_iff _).2 (sub_self p ▸ tendsto_const_nhds.sub continuous_at_snd), apply is_bounded_bilinear_map_apply.is_O_comp.trans_is_o, refine is_o.trans_is_O _ (is_O_const_mul_self 1 _ _).of_norm_right, refine is_o.mul_is_O _ (is_O_refl _ _), exact (((h.is_bounded_linear_map_deriv.is_O_id ⊤).comp_tendsto le_top : _).trans_is_o this).norm_left end lemma is_bounded_bilinear_map.has_fderiv_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : has_fderiv_at b (h.deriv p) p := (h.has_strict_fderiv_at p).has_fderiv_at lemma is_bounded_bilinear_map.has_fderiv_within_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : has_fderiv_within_at b (h.deriv p) u p := (h.has_fderiv_at p).has_fderiv_within_at lemma is_bounded_bilinear_map.differentiable_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : differentiable_at 𝕜 b p := (h.has_fderiv_at p).differentiable_at lemma is_bounded_bilinear_map.differentiable_within_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : differentiable_within_at 𝕜 b u p := (h.differentiable_at p).differentiable_within_at lemma is_bounded_bilinear_map.fderiv (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : fderiv 𝕜 b p = h.deriv p := has_fderiv_at.fderiv (h.has_fderiv_at p) lemma is_bounded_bilinear_map.fderiv_within (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) (hxs : unique_diff_within_at 𝕜 u p) : fderiv_within 𝕜 b u p = h.deriv p := begin rw differentiable_at.fderiv_within (h.differentiable_at p) hxs, exact h.fderiv p end lemma is_bounded_bilinear_map.differentiable (h : is_bounded_bilinear_map 𝕜 b) : differentiable 𝕜 b := λx, h.differentiable_at x lemma is_bounded_bilinear_map.differentiable_on (h : is_bounded_bilinear_map 𝕜 b) : differentiable_on 𝕜 b u := h.differentiable.differentiable_on lemma is_bounded_bilinear_map.continuous (h : is_bounded_bilinear_map 𝕜 b) : continuous b := h.differentiable.continuous lemma is_bounded_bilinear_map.continuous_left (h : is_bounded_bilinear_map 𝕜 b) {f : F} : continuous (λe, b (e, f)) := h.continuous.comp (continuous_id.prod_mk continuous_const) lemma is_bounded_bilinear_map.continuous_right (h : is_bounded_bilinear_map 𝕜 b) {e : E} : continuous (λf, b (e, f)) := h.continuous.comp (continuous_const.prod_mk continuous_id) end bilinear_map namespace continuous_linear_equiv /-! ### The set of continuous linear equivalences between two Banach spaces is open In this section we establish that the set of continuous linear equivalences between two Banach spaces is an open subset of the space of linear maps between them. These facts are placed here because the proof uses `is_bounded_bilinear_map.continuous_left`, proved just above as a consequence of its differentiability. -/ protected lemma is_open [complete_space E] : is_open (range (coe : (E ≃L[𝕜] F) → (E →L[𝕜] F))) := begin nontriviality E, rw [is_open_iff_mem_nhds, forall_range_iff], refine λ e, is_open.mem_nhds _ (mem_range_self _), let O : (E →L[𝕜] F) → (E →L[𝕜] E) := λ f, (e.symm : F →L[𝕜] E).comp f, have h_O : continuous O := is_bounded_bilinear_map_comp.continuous_left, convert units.is_open.preimage h_O using 1, ext f', split, { rintros ⟨e', rfl⟩, exact ⟨(e'.trans e.symm).to_unit, rfl⟩ }, { rintros ⟨w, hw⟩, use (units_equiv 𝕜 E w).trans e, ext x, simp [hw] } end protected lemma nhds [complete_space E] (e : E ≃L[𝕜] F) : (range (coe : (E ≃L[𝕜] F) → (E →L[𝕜] F))) ∈ 𝓝 (e : E →L[𝕜] F) := is_open.mem_nhds continuous_linear_equiv.is_open (by simp) end continuous_linear_equiv section smul /-! ### Derivative of the product of a scalar-valued function and a vector-valued function If `c` is a differentiable scalar-valued function and `f` is a differentiable vector-valued function, then `λ x, c x • f x` is differentiable as well. Lemmas in this section works for function `c` taking values in the base field, as well as in a normed algebra over the base field: e.g., they work for `c : E → ℂ` and `f : E → F` provided that `F` is a complex normed vector space. -/ variables {𝕜' : Type*} [nondiscrete_normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] [normed_space 𝕜' F] [is_scalar_tower 𝕜 𝕜' F] variables {c : E → 𝕜'} {c' : E →L[𝕜] 𝕜'} theorem has_strict_fderiv_at.smul (hc : has_strict_fderiv_at c c' x) (hf : has_strict_fderiv_at f f' x) : has_strict_fderiv_at (λ y, c y • f y) (c x • f' + c'.smul_right (f x)) x := (is_bounded_bilinear_map_smul.has_strict_fderiv_at (c x, f x)).comp x $ hc.prod hf theorem has_fderiv_within_at.smul (hc : has_fderiv_within_at c c' s x) (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (λ y, c y • f y) (c x • f' + c'.smul_right (f x)) s x := (is_bounded_bilinear_map_smul.has_fderiv_at (c x, f x)).comp_has_fderiv_within_at x $ hc.prod hf theorem has_fderiv_at.smul (hc : has_fderiv_at c c' x) (hf : has_fderiv_at f f' x) : has_fderiv_at (λ y, c y • f y) (c x • f' + c'.smul_right (f x)) x := (is_bounded_bilinear_map_smul.has_fderiv_at (c x, f x)).comp x $ hc.prod hf lemma differentiable_within_at.smul (hc : differentiable_within_at 𝕜 c s x) (hf : differentiable_within_at 𝕜 f s x) : differentiable_within_at 𝕜 (λ y, c y • f y) s x := (hc.has_fderiv_within_at.smul hf.has_fderiv_within_at).differentiable_within_at @[simp] lemma differentiable_at.smul (hc : differentiable_at 𝕜 c x) (hf : differentiable_at 𝕜 f x) : differentiable_at 𝕜 (λ y, c y • f y) x := (hc.has_fderiv_at.smul hf.has_fderiv_at).differentiable_at lemma differentiable_on.smul (hc : differentiable_on 𝕜 c s) (hf : differentiable_on 𝕜 f s) : differentiable_on 𝕜 (λ y, c y • f y) s := λx hx, (hc x hx).smul (hf x hx) @[simp] lemma differentiable.smul (hc : differentiable 𝕜 c) (hf : differentiable 𝕜 f) : differentiable 𝕜 (λ y, c y • f y) := λx, (hc x).smul (hf x) lemma fderiv_within_smul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (hf : differentiable_within_at 𝕜 f s x) : fderiv_within 𝕜 (λ y, c y • f y) s x = c x • fderiv_within 𝕜 f s x + (fderiv_within 𝕜 c s x).smul_right (f x) := (hc.has_fderiv_within_at.smul hf.has_fderiv_within_at).fderiv_within hxs lemma fderiv_smul (hc : differentiable_at 𝕜 c x) (hf : differentiable_at 𝕜 f x) : fderiv 𝕜 (λ y, c y • f y) x = c x • fderiv 𝕜 f x + (fderiv 𝕜 c x).smul_right (f x) := (hc.has_fderiv_at.smul hf.has_fderiv_at).fderiv theorem has_strict_fderiv_at.smul_const (hc : has_strict_fderiv_at c c' x) (f : F) : has_strict_fderiv_at (λ y, c y • f) (c'.smul_right f) x := by simpa only [smul_zero, zero_add] using hc.smul (has_strict_fderiv_at_const f x) theorem has_fderiv_within_at.smul_const (hc : has_fderiv_within_at c c' s x) (f : F) : has_fderiv_within_at (λ y, c y • f) (c'.smul_right f) s x := by simpa only [smul_zero, zero_add] using hc.smul (has_fderiv_within_at_const f x s) theorem has_fderiv_at.smul_const (hc : has_fderiv_at c c' x) (f : F) : has_fderiv_at (λ y, c y • f) (c'.smul_right f) x := by simpa only [smul_zero, zero_add] using hc.smul (has_fderiv_at_const f x) lemma differentiable_within_at.smul_const (hc : differentiable_within_at 𝕜 c s x) (f : F) : differentiable_within_at 𝕜 (λ y, c y • f) s x := (hc.has_fderiv_within_at.smul_const f).differentiable_within_at lemma differentiable_at.smul_const (hc : differentiable_at 𝕜 c x) (f : F) : differentiable_at 𝕜 (λ y, c y • f) x := (hc.has_fderiv_at.smul_const f).differentiable_at lemma differentiable_on.smul_const (hc : differentiable_on 𝕜 c s) (f : F) : differentiable_on 𝕜 (λ y, c y • f) s := λx hx, (hc x hx).smul_const f lemma differentiable.smul_const (hc : differentiable 𝕜 c) (f : F) : differentiable 𝕜 (λ y, c y • f) := λx, (hc x).smul_const f lemma fderiv_within_smul_const (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (f : F) : fderiv_within 𝕜 (λ y, c y • f) s x = (fderiv_within 𝕜 c s x).smul_right f := (hc.has_fderiv_within_at.smul_const f).fderiv_within hxs lemma fderiv_smul_const (hc : differentiable_at 𝕜 c x) (f : F) : fderiv 𝕜 (λ y, c y • f) x = (fderiv 𝕜 c x).smul_right f := (hc.has_fderiv_at.smul_const f).fderiv end smul section mul /-! ### Derivative of the product of two scalar-valued functions -/ variables {c d : E → 𝕜} {c' d' : E →L[𝕜] 𝕜} theorem has_strict_fderiv_at.mul (hc : has_strict_fderiv_at c c' x) (hd : has_strict_fderiv_at d d' x) : has_strict_fderiv_at (λ y, c y * d y) (c x • d' + d x • c') x := by { convert hc.smul hd, ext z, apply mul_comm } theorem has_fderiv_within_at.mul (hc : has_fderiv_within_at c c' s x) (hd : has_fderiv_within_at d d' s x) : has_fderiv_within_at (λ y, c y * d y) (c x • d' + d x • c') s x := by { convert hc.smul hd, ext z, apply mul_comm } theorem has_fderiv_at.mul (hc : has_fderiv_at c c' x) (hd : has_fderiv_at d d' x) : has_fderiv_at (λ y, c y * d y) (c x • d' + d x • c') x := by { convert hc.smul hd, ext z, apply mul_comm } lemma differentiable_within_at.mul (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) : differentiable_within_at 𝕜 (λ y, c y * d y) s x := (hc.has_fderiv_within_at.mul hd.has_fderiv_within_at).differentiable_within_at @[simp] lemma differentiable_at.mul (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) : differentiable_at 𝕜 (λ y, c y * d y) x := (hc.has_fderiv_at.mul hd.has_fderiv_at).differentiable_at lemma differentiable_on.mul (hc : differentiable_on 𝕜 c s) (hd : differentiable_on 𝕜 d s) : differentiable_on 𝕜 (λ y, c y * d y) s := λx hx, (hc x hx).mul (hd x hx) @[simp] lemma differentiable.mul (hc : differentiable 𝕜 c) (hd : differentiable 𝕜 d) : differentiable 𝕜 (λ y, c y * d y) := λx, (hc x).mul (hd x) lemma fderiv_within_mul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) : fderiv_within 𝕜 (λ y, c y * d y) s x = c x • fderiv_within 𝕜 d s x + d x • fderiv_within 𝕜 c s x := (hc.has_fderiv_within_at.mul hd.has_fderiv_within_at).fderiv_within hxs lemma fderiv_mul (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) : fderiv 𝕜 (λ y, c y * d y) x = c x • fderiv 𝕜 d x + d x • fderiv 𝕜 c x := (hc.has_fderiv_at.mul hd.has_fderiv_at).fderiv theorem has_strict_fderiv_at.mul_const (hc : has_strict_fderiv_at c c' x) (d : 𝕜) : has_strict_fderiv_at (λ y, c y * d) (d • c') x := by simpa only [smul_zero, zero_add] using hc.mul (has_strict_fderiv_at_const d x) theorem has_fderiv_within_at.mul_const (hc : has_fderiv_within_at c c' s x) (d : 𝕜) : has_fderiv_within_at (λ y, c y * d) (d • c') s x := by simpa only [smul_zero, zero_add] using hc.mul (has_fderiv_within_at_const d x s) theorem has_fderiv_at.mul_const (hc : has_fderiv_at c c' x) (d : 𝕜) : has_fderiv_at (λ y, c y * d) (d • c') x := begin rw [← has_fderiv_within_at_univ] at *, exact hc.mul_const d end lemma differentiable_within_at.mul_const (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) : differentiable_within_at 𝕜 (λ y, c y * d) s x := (hc.has_fderiv_within_at.mul_const d).differentiable_within_at lemma differentiable_at.mul_const (hc : differentiable_at 𝕜 c x) (d : 𝕜) : differentiable_at 𝕜 (λ y, c y * d) x := (hc.has_fderiv_at.mul_const d).differentiable_at lemma differentiable_on.mul_const (hc : differentiable_on 𝕜 c s) (d : 𝕜) : differentiable_on 𝕜 (λ y, c y * d) s := λx hx, (hc x hx).mul_const d lemma differentiable.mul_const (hc : differentiable 𝕜 c) (d : 𝕜) : differentiable 𝕜 (λ y, c y * d) := λx, (hc x).mul_const d lemma fderiv_within_mul_const (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) : fderiv_within 𝕜 (λ y, c y * d) s x = d • fderiv_within 𝕜 c s x := (hc.has_fderiv_within_at.mul_const d).fderiv_within hxs lemma fderiv_mul_const (hc : differentiable_at 𝕜 c x) (d : 𝕜) : fderiv 𝕜 (λ y, c y * d) x = d • fderiv 𝕜 c x := (hc.has_fderiv_at.mul_const d).fderiv theorem has_strict_fderiv_at.const_mul (hc : has_strict_fderiv_at c c' x) (d : 𝕜) : has_strict_fderiv_at (λ y, d * c y) (d • c') x := begin simp only [mul_comm d], exact hc.mul_const d, end theorem has_fderiv_within_at.const_mul (hc : has_fderiv_within_at c c' s x) (d : 𝕜) : has_fderiv_within_at (λ y, d * c y) (d • c') s x := begin simp only [mul_comm d], exact hc.mul_const d, end theorem has_fderiv_at.const_mul (hc : has_fderiv_at c c' x) (d : 𝕜) : has_fderiv_at (λ y, d * c y) (d • c') x := begin simp only [mul_comm d], exact hc.mul_const d, end lemma differentiable_within_at.const_mul (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) : differentiable_within_at 𝕜 (λ y, d * c y) s x := (hc.has_fderiv_within_at.const_mul d).differentiable_within_at lemma differentiable_at.const_mul (hc : differentiable_at 𝕜 c x) (d : 𝕜) : differentiable_at 𝕜 (λ y, d * c y) x := (hc.has_fderiv_at.const_mul d).differentiable_at lemma differentiable_on.const_mul (hc : differentiable_on 𝕜 c s) (d : 𝕜) : differentiable_on 𝕜 (λ y, d * c y) s := λx hx, (hc x hx).const_mul d lemma differentiable.const_mul (hc : differentiable 𝕜 c) (d : 𝕜) : differentiable 𝕜 (λ y, d * c y) := λx, (hc x).const_mul d lemma fderiv_within_const_mul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) : fderiv_within 𝕜 (λ y, d * c y) s x = d • fderiv_within 𝕜 c s x := (hc.has_fderiv_within_at.const_mul d).fderiv_within hxs lemma fderiv_const_mul (hc : differentiable_at 𝕜 c x) (d : 𝕜) : fderiv 𝕜 (λ y, d * c y) x = d • fderiv 𝕜 c x := (hc.has_fderiv_at.const_mul d).fderiv end mul section algebra_inverse variables {R : Type*} [normed_ring R] [normed_algebra 𝕜 R] [complete_space R] open normed_ring continuous_linear_map ring /-- At an invertible element `x` of a normed algebra `R`, the Fréchet derivative of the inversion operation is the linear map `λ t, - x⁻¹ * t * x⁻¹`. -/ lemma has_fderiv_at_ring_inverse (x : units R) : has_fderiv_at ring.inverse (-lmul_left_right 𝕜 R ↑x⁻¹ ↑x⁻¹) x := begin have h_is_o : is_o (λ (t : R), inverse (↑x + t) - ↑x⁻¹ + ↑x⁻¹ * t * ↑x⁻¹) (λ (t : R), t) (𝓝 0), { refine (inverse_add_norm_diff_second_order x).trans_is_o ((is_o_norm_norm).mp _), simp only [normed_field.norm_pow, norm_norm], have h12 : 1 < 2 := by norm_num, convert (asymptotics.is_o_pow_pow h12).comp_tendsto tendsto_norm_zero, ext, simp }, have h_lim : tendsto (λ (y:R), y - x) (𝓝 x) (𝓝 0), { refine tendsto_zero_iff_norm_tendsto_zero.mpr _, exact tendsto_iff_norm_tendsto_zero.mp tendsto_id }, simp only [has_fderiv_at, has_fderiv_at_filter], convert h_is_o.comp_tendsto h_lim, ext y, simp only [coe_comp', function.comp_app, lmul_left_right_apply, neg_apply, inverse_unit x, units.inv_mul, add_sub_cancel'_right, mul_sub, sub_mul, one_mul, sub_neg_eq_add] end lemma differentiable_at_inverse (x : units R) : differentiable_at 𝕜 (@ring.inverse R _) x := (has_fderiv_at_ring_inverse x).differentiable_at lemma fderiv_inverse (x : units R) : fderiv 𝕜 (@ring.inverse R _) x = - lmul_left_right 𝕜 R ↑x⁻¹ ↑x⁻¹ := (has_fderiv_at_ring_inverse x).fderiv end algebra_inverse namespace continuous_linear_equiv /-! ### Differentiability of linear equivs, and invariance of differentiability -/ variable (iso : E ≃L[𝕜] F) protected lemma has_strict_fderiv_at : has_strict_fderiv_at iso (iso : E →L[𝕜] F) x := iso.to_continuous_linear_map.has_strict_fderiv_at protected lemma has_fderiv_within_at : has_fderiv_within_at iso (iso : E →L[𝕜] F) s x := iso.to_continuous_linear_map.has_fderiv_within_at protected lemma has_fderiv_at : has_fderiv_at iso (iso : E →L[𝕜] F) x := iso.to_continuous_linear_map.has_fderiv_at_filter protected lemma differentiable_at : differentiable_at 𝕜 iso x := iso.has_fderiv_at.differentiable_at protected lemma differentiable_within_at : differentiable_within_at 𝕜 iso s x := iso.differentiable_at.differentiable_within_at protected lemma fderiv : fderiv 𝕜 iso x = iso := iso.has_fderiv_at.fderiv protected lemma fderiv_within (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 iso s x = iso := iso.to_continuous_linear_map.fderiv_within hxs protected lemma differentiable : differentiable 𝕜 iso := λx, iso.differentiable_at protected lemma differentiable_on : differentiable_on 𝕜 iso s := iso.differentiable.differentiable_on lemma comp_differentiable_within_at_iff {f : G → E} {s : set G} {x : G} : differentiable_within_at 𝕜 (iso ∘ f) s x ↔ differentiable_within_at 𝕜 f s x := begin refine ⟨λ H, _, λ H, iso.differentiable.differentiable_at.comp_differentiable_within_at x H⟩, have : differentiable_within_at 𝕜 (iso.symm ∘ (iso ∘ f)) s x := iso.symm.differentiable.differentiable_at.comp_differentiable_within_at x H, rwa [← function.comp.assoc iso.symm iso f, iso.symm_comp_self] at this, end lemma comp_differentiable_at_iff {f : G → E} {x : G} : differentiable_at 𝕜 (iso ∘ f) x ↔ differentiable_at 𝕜 f x := by rw [← differentiable_within_at_univ, ← differentiable_within_at_univ, iso.comp_differentiable_within_at_iff] lemma comp_differentiable_on_iff {f : G → E} {s : set G} : differentiable_on 𝕜 (iso ∘ f) s ↔ differentiable_on 𝕜 f s := begin rw [differentiable_on, differentiable_on], simp only [iso.comp_differentiable_within_at_iff], end lemma comp_differentiable_iff {f : G → E} : differentiable 𝕜 (iso ∘ f) ↔ differentiable 𝕜 f := begin rw [← differentiable_on_univ, ← differentiable_on_univ], exact iso.comp_differentiable_on_iff end lemma comp_has_fderiv_within_at_iff {f : G → E} {s : set G} {x : G} {f' : G →L[𝕜] E} : has_fderiv_within_at (iso ∘ f) ((iso : E →L[𝕜] F).comp f') s x ↔ has_fderiv_within_at f f' s x := begin refine ⟨λ H, _, λ H, iso.has_fderiv_at.comp_has_fderiv_within_at x H⟩, have A : f = iso.symm ∘ (iso ∘ f), by { rw [← function.comp.assoc, iso.symm_comp_self], refl }, have B : f' = (iso.symm : F →L[𝕜] E).comp ((iso : E →L[𝕜] F).comp f'), by rw [← continuous_linear_map.comp_assoc, iso.coe_symm_comp_coe, continuous_linear_map.id_comp], rw [A, B], exact iso.symm.has_fderiv_at.comp_has_fderiv_within_at x H end lemma comp_has_strict_fderiv_at_iff {f : G → E} {x : G} {f' : G →L[𝕜] E} : has_strict_fderiv_at (iso ∘ f) ((iso : E →L[𝕜] F).comp f') x ↔ has_strict_fderiv_at f f' x := begin refine ⟨λ H, _, λ H, iso.has_strict_fderiv_at.comp x H⟩, convert iso.symm.has_strict_fderiv_at.comp x H; ext z; apply (iso.symm_apply_apply _).symm end lemma comp_has_fderiv_at_iff {f : G → E} {x : G} {f' : G →L[𝕜] E} : has_fderiv_at (iso ∘ f) ((iso : E →L[𝕜] F).comp f') x ↔ has_fderiv_at f f' x := by rw [← has_fderiv_within_at_univ, ← has_fderiv_within_at_univ, iso.comp_has_fderiv_within_at_iff] lemma comp_has_fderiv_within_at_iff' {f : G → E} {s : set G} {x : G} {f' : G →L[𝕜] F} : has_fderiv_within_at (iso ∘ f) f' s x ↔ has_fderiv_within_at f ((iso.symm : F →L[𝕜] E).comp f') s x := by rw [← iso.comp_has_fderiv_within_at_iff, ← continuous_linear_map.comp_assoc, iso.coe_comp_coe_symm, continuous_linear_map.id_comp] lemma comp_has_fderiv_at_iff' {f : G → E} {x : G} {f' : G →L[𝕜] F} : has_fderiv_at (iso ∘ f) f' x ↔ has_fderiv_at f ((iso.symm : F →L[𝕜] E).comp f') x := by rw [← has_fderiv_within_at_univ, ← has_fderiv_within_at_univ, iso.comp_has_fderiv_within_at_iff'] lemma comp_fderiv_within {f : G → E} {s : set G} {x : G} (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (iso ∘ f) s x = (iso : E →L[𝕜] F).comp (fderiv_within 𝕜 f s x) := begin by_cases h : differentiable_within_at 𝕜 f s x, { rw [fderiv.comp_fderiv_within x iso.differentiable_at h hxs, iso.fderiv] }, { have : ¬differentiable_within_at 𝕜 (iso ∘ f) s x, from mt iso.comp_differentiable_within_at_iff.1 h, rw [fderiv_within_zero_of_not_differentiable_within_at h, fderiv_within_zero_of_not_differentiable_within_at this, continuous_linear_map.comp_zero] } end lemma comp_fderiv {f : G → E} {x : G} : fderiv 𝕜 (iso ∘ f) x = (iso : E →L[𝕜] F).comp (fderiv 𝕜 f x) := begin rw [← fderiv_within_univ, ← fderiv_within_univ], exact iso.comp_fderiv_within unique_diff_within_at_univ, end end continuous_linear_equiv namespace linear_isometry_equiv /-! ### Differentiability of linear isometry equivs, and invariance of differentiability -/ variable (iso : E ≃ₗᵢ[𝕜] F) protected lemma has_strict_fderiv_at : has_strict_fderiv_at iso (iso : E →L[𝕜] F) x := (iso : E ≃L[𝕜] F).has_strict_fderiv_at protected lemma has_fderiv_within_at : has_fderiv_within_at iso (iso : E →L[𝕜] F) s x := (iso : E ≃L[𝕜] F).has_fderiv_within_at protected lemma has_fderiv_at : has_fderiv_at iso (iso : E →L[𝕜] F) x := (iso : E ≃L[𝕜] F).has_fderiv_at protected lemma differentiable_at : differentiable_at 𝕜 iso x := iso.has_fderiv_at.differentiable_at protected lemma differentiable_within_at : differentiable_within_at 𝕜 iso s x := iso.differentiable_at.differentiable_within_at protected lemma fderiv : fderiv 𝕜 iso x = iso := iso.has_fderiv_at.fderiv protected lemma fderiv_within (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 iso s x = iso := (iso : E ≃L[𝕜] F).fderiv_within hxs protected lemma differentiable : differentiable 𝕜 iso := λx, iso.differentiable_at protected lemma differentiable_on : differentiable_on 𝕜 iso s := iso.differentiable.differentiable_on lemma comp_differentiable_within_at_iff {f : G → E} {s : set G} {x : G} : differentiable_within_at 𝕜 (iso ∘ f) s x ↔ differentiable_within_at 𝕜 f s x := (iso : E ≃L[𝕜] F).comp_differentiable_within_at_iff lemma comp_differentiable_at_iff {f : G → E} {x : G} : differentiable_at 𝕜 (iso ∘ f) x ↔ differentiable_at 𝕜 f x := (iso : E ≃L[𝕜] F).comp_differentiable_at_iff lemma comp_differentiable_on_iff {f : G → E} {s : set G} : differentiable_on 𝕜 (iso ∘ f) s ↔ differentiable_on 𝕜 f s := (iso : E ≃L[𝕜] F).comp_differentiable_on_iff lemma comp_differentiable_iff {f : G → E} : differentiable 𝕜 (iso ∘ f) ↔ differentiable 𝕜 f := (iso : E ≃L[𝕜] F).comp_differentiable_iff lemma comp_has_fderiv_within_at_iff {f : G → E} {s : set G} {x : G} {f' : G →L[𝕜] E} : has_fderiv_within_at (iso ∘ f) ((iso : E →L[𝕜] F).comp f') s x ↔ has_fderiv_within_at f f' s x := (iso : E ≃L[𝕜] F).comp_has_fderiv_within_at_iff lemma comp_has_strict_fderiv_at_iff {f : G → E} {x : G} {f' : G →L[𝕜] E} : has_strict_fderiv_at (iso ∘ f) ((iso : E →L[𝕜] F).comp f') x ↔ has_strict_fderiv_at f f' x := (iso : E ≃L[𝕜] F).comp_has_strict_fderiv_at_iff lemma comp_has_fderiv_at_iff {f : G → E} {x : G} {f' : G →L[𝕜] E} : has_fderiv_at (iso ∘ f) ((iso : E →L[𝕜] F).comp f') x ↔ has_fderiv_at f f' x := (iso : E ≃L[𝕜] F).comp_has_fderiv_at_iff lemma comp_has_fderiv_within_at_iff' {f : G → E} {s : set G} {x : G} {f' : G →L[𝕜] F} : has_fderiv_within_at (iso ∘ f) f' s x ↔ has_fderiv_within_at f ((iso.symm : F →L[𝕜] E).comp f') s x := (iso : E ≃L[𝕜] F).comp_has_fderiv_within_at_iff' lemma comp_has_fderiv_at_iff' {f : G → E} {x : G} {f' : G →L[𝕜] F} : has_fderiv_at (iso ∘ f) f' x ↔ has_fderiv_at f ((iso.symm : F →L[𝕜] E).comp f') x := (iso : E ≃L[𝕜] F).comp_has_fderiv_at_iff' lemma comp_fderiv_within {f : G → E} {s : set G} {x : G} (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (iso ∘ f) s x = (iso : E →L[𝕜] F).comp (fderiv_within 𝕜 f s x) := (iso : E ≃L[𝕜] F).comp_fderiv_within hxs lemma comp_fderiv {f : G → E} {x : G} : fderiv 𝕜 (iso ∘ f) x = (iso : E →L[𝕜] F).comp (fderiv 𝕜 f x) := (iso : E ≃L[𝕜] F).comp_fderiv end linear_isometry_equiv /-- If `f (g y) = y` for `y` in some neighborhood of `a`, `g` is continuous at `a`, and `f` has an invertible derivative `f'` at `g a` in the strict sense, then `g` has the derivative `f'⁻¹` at `a` in the strict sense. This is one of the easy parts of the inverse function theorem: it assumes that we already have an inverse function. -/ theorem has_strict_fderiv_at.of_local_left_inverse {f : E → F} {f' : E ≃L[𝕜] F} {g : F → E} {a : F} (hg : continuous_at g a) (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) (g a)) (hfg : ∀ᶠ y in 𝓝 a, f (g y) = y) : has_strict_fderiv_at g (f'.symm : F →L[𝕜] E) a := begin replace hg := hg.prod_map' hg, replace hfg := hfg.prod_mk_nhds hfg, have : is_O (λ p : F × F, g p.1 - g p.2 - f'.symm (p.1 - p.2)) (λ p : F × F, f' (g p.1 - g p.2) - (p.1 - p.2)) (𝓝 (a, a)), { refine ((f'.symm : F →L[𝕜] E).is_O_comp _ _).congr (λ x, _) (λ _, rfl), simp }, refine this.trans_is_o _, clear this, refine ((hf.comp_tendsto hg).symm.congr' (hfg.mono _) (eventually_of_forall $ λ _, rfl)).trans_is_O _, { rintros p ⟨hp1, hp2⟩, simp [hp1, hp2] }, { refine (hf.is_O_sub_rev.comp_tendsto hg).congr' (eventually_of_forall $ λ _, rfl) (hfg.mono _), rintros p ⟨hp1, hp2⟩, simp only [(∘), hp1, hp2] } end /-- If `f (g y) = y` for `y` in some neighborhood of `a`, `g` is continuous at `a`, and `f` has an invertible derivative `f'` at `g a`, then `g` has the derivative `f'⁻¹` at `a`. This is one of the easy parts of the inverse function theorem: it assumes that we already have an inverse function. -/ theorem has_fderiv_at.of_local_left_inverse {f : E → F} {f' : E ≃L[𝕜] F} {g : F → E} {a : F} (hg : continuous_at g a) (hf : has_fderiv_at f (f' : E →L[𝕜] F) (g a)) (hfg : ∀ᶠ y in 𝓝 a, f (g y) = y) : has_fderiv_at g (f'.symm : F →L[𝕜] E) a := begin have : is_O (λ x : F, g x - g a - f'.symm (x - a)) (λ x : F, f' (g x - g a) - (x - a)) (𝓝 a), { refine ((f'.symm : F →L[𝕜] E).is_O_comp _ _).congr (λ x, _) (λ _, rfl), simp }, refine this.trans_is_o _, clear this, refine ((hf.comp_tendsto hg).symm.congr' (hfg.mono _) (eventually_of_forall $ λ _, rfl)).trans_is_O _, { rintros p hp, simp [hp, hfg.self_of_nhds] }, { refine (hf.is_O_sub_rev.comp_tendsto hg).congr' (eventually_of_forall $ λ _, rfl) (hfg.mono _), rintros p hp, simp only [(∘), hp, hfg.self_of_nhds] } end /-- If `f` is a local homeomorphism defined on a neighbourhood of `f.symm a`, and `f` has an invertible derivative `f'` in the sense of strict differentiability at `f.symm a`, then `f.symm` has the derivative `f'⁻¹` at `a`. This is one of the easy parts of the inverse function theorem: it assumes that we already have an inverse function. -/ lemma local_homeomorph.has_strict_fderiv_at_symm (f : local_homeomorph E F) {f' : E ≃L[𝕜] F} {a : F} (ha : a ∈ f.target) (htff' : has_strict_fderiv_at f (f' : E →L[𝕜] F) (f.symm a)) : has_strict_fderiv_at f.symm (f'.symm : F →L[𝕜] E) a := htff'.of_local_left_inverse (f.symm.continuous_at ha) (f.eventually_right_inverse ha) /-- If `f` is a local homeomorphism defined on a neighbourhood of `f.symm a`, and `f` has an invertible derivative `f'` at `f.symm a`, then `f.symm` has the derivative `f'⁻¹` at `a`. This is one of the easy parts of the inverse function theorem: it assumes that we already have an inverse function. -/ lemma local_homeomorph.has_fderiv_at_symm (f : local_homeomorph E F) {f' : E ≃L[𝕜] F} {a : F} (ha : a ∈ f.target) (htff' : has_fderiv_at f (f' : E →L[𝕜] F) (f.symm a)) : has_fderiv_at f.symm (f'.symm : F →L[𝕜] E) a := htff'.of_local_left_inverse (f.symm.continuous_at ha) (f.eventually_right_inverse ha) lemma has_fderiv_within_at.eventually_ne (h : has_fderiv_within_at f f' s x) (hf' : ∃ C, ∀ z, ∥z∥ ≤ C * ∥f' z∥) : ∀ᶠ z in 𝓝[s \ {x}] x, f z ≠ f x := begin rw [nhds_within, diff_eq, ← inf_principal, ← inf_assoc, eventually_inf_principal], have A : is_O (λ z, z - x) (λ z, f' (z - x)) (𝓝[s] x) := (is_O_iff.2 $ hf'.imp $ λ C hC, eventually_of_forall $ λ z, hC _), have : (λ z, f z - f x) ~[𝓝[s] x] (λ z, f' (z - x)) := h.trans_is_O A, simpa [not_imp_not, sub_eq_zero] using (A.trans this.is_O_symm).eq_zero_imp end lemma has_fderiv_at.eventually_ne (h : has_fderiv_at f f' x) (hf' : ∃ C, ∀ z, ∥z∥ ≤ C * ∥f' z∥) : ∀ᶠ z in 𝓝[{x}ᶜ] x, f z ≠ f x := by simpa only [compl_eq_univ_diff] using (has_fderiv_within_at_univ.2 h).eventually_ne hf' end section /- In the special case of a normed space over the reals, we can use scalar multiplication in the `tendsto` characterization of the Fréchet derivative. -/ variables {E : Type*} [normed_group E] [normed_space ℝ E] variables {F : Type*} [normed_group F] [normed_space ℝ F] variables {f : E → F} {f' : E →L[ℝ] F} {x : E} theorem has_fderiv_at_filter_real_equiv {L : filter E} : tendsto (λ x' : E, ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) L (𝓝 0) ↔ tendsto (λ x' : E, ∥x' - x∥⁻¹ • (f x' - f x - f' (x' - x))) L (𝓝 0) := begin symmetry, rw [tendsto_iff_norm_tendsto_zero], refine tendsto_congr (λ x', _), have : ∥x' - x∥⁻¹ ≥ 0, from inv_nonneg.mpr (norm_nonneg _), simp [norm_smul, real.norm_eq_abs, abs_of_nonneg this] end lemma has_fderiv_at.lim_real (hf : has_fderiv_at f f' x) (v : E) : tendsto (λ (c:ℝ), c • (f (x + c⁻¹ • v) - f x)) at_top (𝓝 (f' v)) := begin apply hf.lim v, rw tendsto_at_top_at_top, exact λ b, ⟨b, λ a ha, le_trans ha (le_abs_self _)⟩ end end section tangent_cone variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {F : Type*} [normed_group F] [normed_space 𝕜 F] {f : E → F} {s : set E} {f' : E →L[𝕜] F} /-- The image of a tangent cone under the differential of a map is included in the tangent cone to the image. -/ lemma has_fderiv_within_at.maps_to_tangent_cone {x : E} (h : has_fderiv_within_at f f' s x) : maps_to f' (tangent_cone_at 𝕜 s x) (tangent_cone_at 𝕜 (f '' s) (f x)) := begin rintros v ⟨c, d, dtop, clim, cdlim⟩, refine ⟨c, (λn, f (x + d n) - f x), mem_sets_of_superset dtop _, clim, h.lim at_top dtop clim cdlim⟩, simp [-mem_image, mem_image_of_mem] {contextual := tt} end /-- If a set has the unique differentiability property at a point x, then the image of this set under a map with onto derivative has also the unique differentiability property at the image point. -/ lemma has_fderiv_within_at.unique_diff_within_at {x : E} (h : has_fderiv_within_at f f' s x) (hs : unique_diff_within_at 𝕜 s x) (h' : dense_range f') : unique_diff_within_at 𝕜 (f '' s) (f x) := begin refine ⟨h'.dense_of_maps_to f'.continuous hs.1 _, h.continuous_within_at.mem_closure_image hs.2⟩, show submodule.span 𝕜 (tangent_cone_at 𝕜 s x) ≤ (submodule.span 𝕜 (tangent_cone_at 𝕜 (f '' s) (f x))).comap f', rw [submodule.span_le], exact h.maps_to_tangent_cone.mono (subset.refl _) submodule.subset_span end lemma unique_diff_on.image {f' : E → E →L[𝕜] F} (hs : unique_diff_on 𝕜 s) (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (hd : ∀ x ∈ s, dense_range (f' x)) : unique_diff_on 𝕜 (f '' s) := ball_image_iff.2 $ λ x hx, (hf' x hx).unique_diff_within_at (hs x hx) (hd x hx) lemma has_fderiv_within_at.unique_diff_within_at_of_continuous_linear_equiv {x : E} (e' : E ≃L[𝕜] F) (h : has_fderiv_within_at f (e' : E →L[𝕜] F) s x) (hs : unique_diff_within_at 𝕜 s x) : unique_diff_within_at 𝕜 (f '' s) (f x) := h.unique_diff_within_at hs e'.surjective.dense_range lemma continuous_linear_equiv.unique_diff_on_image (e : E ≃L[𝕜] F) (h : unique_diff_on 𝕜 s) : unique_diff_on 𝕜 (e '' s) := h.image (λ x _, e.has_fderiv_within_at) (λ x hx, e.surjective.dense_range) @[simp] lemma continuous_linear_equiv.unique_diff_on_image_iff (e : E ≃L[𝕜] F) : unique_diff_on 𝕜 (e '' s) ↔ unique_diff_on 𝕜 s := ⟨λ h, e.symm_image_image s ▸ e.symm.unique_diff_on_image h, e.unique_diff_on_image⟩ @[simp] lemma continuous_linear_equiv.unique_diff_on_preimage_iff (e : F ≃L[𝕜] E) : unique_diff_on 𝕜 (e ⁻¹' s) ↔ unique_diff_on 𝕜 s := by rw [← e.image_symm_eq_preimage, e.symm.unique_diff_on_image_iff] end tangent_cone section restrict_scalars /-! ### Restricting from `ℂ` to `ℝ`, or generally from `𝕜'` to `𝕜` If a function is differentiable over `ℂ`, then it is differentiable over `ℝ`. In this paragraph, we give variants of this statement, in the general situation where `ℂ` and `ℝ` are replaced respectively by `𝕜'` and `𝕜` where `𝕜'` is a normed algebra over `𝕜`. -/ variables (𝕜 : Type*) [nondiscrete_normed_field 𝕜] variables {𝕜' : Type*} [nondiscrete_normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] variables {E : Type*} [normed_group E] [normed_space 𝕜 E] [normed_space 𝕜' E] variables [is_scalar_tower 𝕜 𝕜' E] variables {F : Type*} [normed_group F] [normed_space 𝕜 F] [normed_space 𝕜' F] variables [is_scalar_tower 𝕜 𝕜' F] variables {f : E → F} {f' : E →L[𝕜'] F} {s : set E} {x : E} lemma has_strict_fderiv_at.restrict_scalars (h : has_strict_fderiv_at f f' x) : has_strict_fderiv_at f (f'.restrict_scalars 𝕜) x := h lemma has_fderiv_at.restrict_scalars (h : has_fderiv_at f f' x) : has_fderiv_at f (f'.restrict_scalars 𝕜) x := h lemma has_fderiv_within_at.restrict_scalars (h : has_fderiv_within_at f f' s x) : has_fderiv_within_at f (f'.restrict_scalars 𝕜) s x := h lemma differentiable_at.restrict_scalars (h : differentiable_at 𝕜' f x) : differentiable_at 𝕜 f x := (h.has_fderiv_at.restrict_scalars 𝕜).differentiable_at lemma differentiable_within_at.restrict_scalars (h : differentiable_within_at 𝕜' f s x) : differentiable_within_at 𝕜 f s x := (h.has_fderiv_within_at.restrict_scalars 𝕜).differentiable_within_at lemma differentiable_on.restrict_scalars (h : differentiable_on 𝕜' f s) : differentiable_on 𝕜 f s := λx hx, (h x hx).restrict_scalars 𝕜 lemma differentiable.restrict_scalars (h : differentiable 𝕜' f) : differentiable 𝕜 f := λx, (h x).restrict_scalars 𝕜 end restrict_scalars
0bd2e677432abba7855995121bb84cce28d66a03
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/data/dfinsupp.lean
0ece9aa7e7a8d009ad09963fe02685b3db48ae0f
[ "Apache-2.0" ]
permissive
vaibhavkarve/mathlib
a574aaf68c0a431a47fa82ce0637f0f769826bfe
17f8340912468f49bdc30acdb9a9fa02eeb0473a
refs/heads/master
1,621,263,802,637
1,585,399,588,000
1,585,399,588,000
250,833,447
0
0
Apache-2.0
1,585,410,341,000
1,585,410,341,000
null
UTF-8
Lean
false
false
32,036
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Kenny Lau Dependent functions with finite support (see `data/finsupp.lean`). -/ import data.finset data.set.finite algebra.big_operators algebra.module algebra.pi_instances universes u u₁ u₂ v v₁ v₂ v₃ w x y l variables (ι : Type u) (β : ι → Type v) def decidable_zero_symm {γ : Type w} [has_zero γ] [decidable_pred (eq (0 : γ))] : decidable_pred (λ x, x = (0:γ)) := λ x, decidable_of_iff (0 = x) eq_comm local attribute [instance] decidable_zero_symm namespace dfinsupp variable [Π i, has_zero (β i)] structure pre : Type (max u v) := (to_fun : Π i, β i) (pre_support : multiset ι) (zero : ∀ i, i ∈ pre_support ∨ to_fun i = 0) instance : setoid (pre ι β) := { r := λ x y, ∀ i, x.to_fun i = y.to_fun i, iseqv := ⟨λ f i, rfl, λ f g H i, (H i).symm, λ f g h H1 H2 i, (H1 i).trans (H2 i)⟩ } end dfinsupp variable {ι} @[reducible] def dfinsupp [Π i, has_zero (β i)] : Type* := quotient (dfinsupp.setoid ι β) variable {β} notation `Π₀` binders `, ` r:(scoped f, dfinsupp f) := r infix ` →ₚ `:25 := dfinsupp namespace dfinsupp section basic variables [Π i, has_zero (β i)] variables {β₁ : ι → Type v₁} {β₂ : ι → Type v₂} variables [Π i, has_zero (β₁ i)] [Π i, has_zero (β₂ i)] instance : has_coe_to_fun (Π₀ i, β i) := ⟨λ _, Π i, β i, λ f, quotient.lift_on f pre.to_fun $ λ _ _, funext⟩ instance : has_zero (Π₀ i, β i) := ⟨⟦⟨λ i, 0, ∅, λ i, or.inr rfl⟩⟧⟩ instance : inhabited (Π₀ i, β i) := ⟨0⟩ @[simp] lemma zero_apply {i : ι} : (0 : Π₀ i, β i) i = 0 := rfl @[ext] lemma ext {f g : Π₀ i, β i} (H : ∀ i, f i = g i) : f = g := quotient.induction_on₂ f g (λ _ _ H, quotient.sound H) H /-- The composition of `f : β₁ → β₂` and `g : Π₀ i, β₁ i` is `map_range f hf g : Π₀ i, β₂ i`, well defined when `f 0 = 0`. -/ def map_range (f : Π i, β₁ i → β₂ i) (hf : ∀ i, f i 0 = 0) (g : Π₀ i, β₁ i) : Π₀ i, β₂ i := quotient.lift_on g (λ x, ⟦(⟨λ i, f i (x.1 i), x.2, λ i, or.cases_on (x.3 i) or.inl $ λ H, or.inr $ by rw [H, hf]⟩ : pre ι β₂)⟧) $ λ x y H, quotient.sound $ λ i, by simp only [H i] @[simp] lemma map_range_apply {f : Π i, β₁ i → β₂ i} {hf : ∀ i, f i 0 = 0} {g : Π₀ i, β₁ i} {i : ι} : map_range f hf g i = f i (g i) := quotient.induction_on g $ λ x, rfl def zip_with (f : Π i, β₁ i → β₂ i → β i) (hf : ∀ i, f i 0 0 = 0) (g₁ : Π₀ i, β₁ i) (g₂ : Π₀ i, β₂ i) : (Π₀ i, β i) := begin refine quotient.lift_on₂ g₁ g₂ (λ x y, ⟦(⟨λ i, f i (x.1 i) (y.1 i), x.2 + y.2, λ i, _⟩ : pre ι β)⟧) _, { cases x.3 i with h1 h1, { left, rw multiset.mem_add, left, exact h1 }, cases y.3 i with h2 h2, { left, rw multiset.mem_add, right, exact h2 }, right, rw [h1, h2, hf] }, exact λ x₁ x₂ y₁ y₂ H1 H2, quotient.sound $ λ i, by simp only [H1 i, H2 i] end @[simp] lemma zip_with_apply {f : Π i, β₁ i → β₂ i → β i} {hf : ∀ i, f i 0 0 = 0} {g₁ : Π₀ i, β₁ i} {g₂ : Π₀ i, β₂ i} {i : ι} : zip_with f hf g₁ g₂ i = f i (g₁ i) (g₂ i) := quotient.induction_on₂ g₁ g₂ $ λ _ _, rfl end basic section algebra instance [Π i, add_monoid (β i)] : has_add (Π₀ i, β i) := ⟨zip_with (λ _, (+)) (λ _, add_zero 0)⟩ @[simp] lemma add_apply [Π i, add_monoid (β i)] {g₁ g₂ : Π₀ i, β i} {i : ι} : (g₁ + g₂) i = g₁ i + g₂ i := zip_with_apply instance [Π i, add_monoid (β i)] : add_monoid (Π₀ i, β i) := { add_monoid . zero := 0, add := (+), add_assoc := λ f g h, ext $ λ i, by simp only [add_apply, add_assoc], zero_add := λ f, ext $ λ i, by simp only [add_apply, zero_apply, zero_add], add_zero := λ f, ext $ λ i, by simp only [add_apply, zero_apply, add_zero] } instance [Π i, add_monoid (β i)] {i : ι} : is_add_monoid_hom (λ g : Π₀ i : ι, β i, g i) := { map_add := λ _ _, add_apply, map_zero := zero_apply } instance [Π i, add_group (β i)] : has_neg (Π₀ i, β i) := ⟨λ f, f.map_range (λ _, has_neg.neg) (λ _, neg_zero)⟩ instance [Π i, add_comm_monoid (β i)] : add_comm_monoid (Π₀ i, β i) := { add_comm := λ f g, ext $ λ i, by simp only [add_apply, add_comm], .. dfinsupp.add_monoid } @[simp] lemma neg_apply [Π i, add_group (β i)] {g : Π₀ i, β i} {i : ι} : (- g) i = - g i := map_range_apply instance [Π i, add_group (β i)] : add_group (Π₀ i, β i) := { add_left_neg := λ f, ext $ λ i, by simp only [add_apply, neg_apply, zero_apply, add_left_neg], .. dfinsupp.add_monoid, .. (infer_instance : has_neg (Π₀ i, β i)) } @[simp] lemma sub_apply [Π i, add_group (β i)] {g₁ g₂ : Π₀ i, β i} {i : ι} : (g₁ - g₂) i = g₁ i - g₂ i := by rw [sub_eq_add_neg]; simp [sub_eq_add_neg] instance [Π i, add_comm_group (β i)] : add_comm_group (Π₀ i, β i) := { add_comm := λ f g, ext $ λ i, by simp only [add_apply, add_comm], ..dfinsupp.add_group } def to_has_scalar {γ : Type w} [ring γ] [Π i, add_comm_group (β i)] [Π i, module γ (β i)] : has_scalar γ (Π₀ i, β i) := ⟨λc v, v.map_range (λ _, (•) c) (λ _, smul_zero _)⟩ local attribute [instance] to_has_scalar @[simp] lemma smul_apply {γ : Type w} [ring γ] [Π i, add_comm_group (β i)] [Π i, module γ (β i)] {i : ι} {b : γ} {v : Π₀ i, β i} : (b • v) i = b • (v i) := map_range_apply def to_module {γ : Type w} [ring γ] [Π i, add_comm_group (β i)] [Π i, module γ (β i)] : module γ (Π₀ i, β i) := module.of_core { smul_add := λ c x y, ext $ λ i, by simp only [add_apply, smul_apply, smul_add], add_smul := λ c x y, ext $ λ i, by simp only [add_apply, smul_apply, add_smul], one_smul := λ x, ext $ λ i, by simp only [smul_apply, one_smul], mul_smul := λ r s x, ext $ λ i, by simp only [smul_apply, smul_smul], .. (infer_instance : has_scalar γ (Π₀ i, β i)) } end algebra section filter_and_subtype_domain /-- `filter p f` is the function which is `f i` if `p i` is true and 0 otherwise. -/ def filter [Π i, has_zero (β i)] (p : ι → Prop) [decidable_pred p] (f : Π₀ i, β i) : Π₀ i, β i := quotient.lift_on f (λ x, ⟦(⟨λ i, if p i then x.1 i else 0, x.2, λ i, or.cases_on (x.3 i) or.inl $ λ H, or.inr $ by rw [H, if_t_t]⟩ : pre ι β)⟧) $ λ x y H, quotient.sound $ λ i, by simp only [H i] @[simp] lemma filter_apply [Π i, has_zero (β i)] {p : ι → Prop} [decidable_pred p] {i : ι} {f : Π₀ i, β i} : f.filter p i = if p i then f i else 0 := quotient.induction_on f $ λ x, rfl lemma filter_apply_pos [Π i, has_zero (β i)] {p : ι → Prop} [decidable_pred p] {f : Π₀ i, β i} {i : ι} (h : p i) : f.filter p i = f i := by simp only [filter_apply, if_pos h] lemma filter_apply_neg [Π i, has_zero (β i)] {p : ι → Prop} [decidable_pred p] {f : Π₀ i, β i} {i : ι} (h : ¬ p i) : f.filter p i = 0 := by simp only [filter_apply, if_neg h] lemma filter_pos_add_filter_neg [Π i, add_monoid (β i)] {f : Π₀ i, β i} {p : ι → Prop} [decidable_pred p] : f.filter p + f.filter (λi, ¬ p i) = f := ext $ λ i, by simp only [add_apply, filter_apply]; split_ifs; simp only [add_zero, zero_add] /-- `subtype_domain p f` is the restriction of the finitely supported function `f` to the subtype `p`. -/ def subtype_domain [Π i, has_zero (β i)] (p : ι → Prop) [decidable_pred p] (f : Π₀ i, β i) : Π₀ i : subtype p, β i.1 := begin fapply quotient.lift_on f, { intro x, refine ⟦⟨λ i, x.1 i.1, (x.2.filter p).attach.map $ λ j, ⟨j.1, (multiset.mem_filter.1 j.2).2⟩, _⟩⟧, refine λ i, or.cases_on (x.3 i.1) (λ H, _) or.inr, left, rw multiset.mem_map, refine ⟨⟨i.1, multiset.mem_filter.2 ⟨H, i.2⟩⟩, _, subtype.eta _ _⟩, apply multiset.mem_attach }, intros x y H, exact quotient.sound (λ i, H i.1) end @[simp] lemma subtype_domain_zero [Π i, has_zero (β i)] {p : ι → Prop} [decidable_pred p] : subtype_domain p (0 : Π₀ i, β i) = 0 := rfl @[simp] lemma subtype_domain_apply [Π i, has_zero (β i)] {p : ι → Prop} [decidable_pred p] {i : subtype p} {v : Π₀ i, β i} : (subtype_domain p v) i = v (i.val) := quotient.induction_on v $ λ x, rfl @[simp] lemma subtype_domain_add [Π i, add_monoid (β i)] {p : ι → Prop} [decidable_pred p] {v v' : Π₀ i, β i} : (v + v').subtype_domain p = v.subtype_domain p + v'.subtype_domain p := ext $ λ i, by simp only [add_apply, subtype_domain_apply] instance subtype_domain.is_add_monoid_hom [Π i, add_monoid (β i)] {p : ι → Prop} [decidable_pred p] : is_add_monoid_hom (subtype_domain p : (Π₀ i : ι, β i) → Π₀ i : subtype p, β i) := { map_add := λ _ _, subtype_domain_add, map_zero := subtype_domain_zero } @[simp] lemma subtype_domain_neg [Π i, add_group (β i)] {p : ι → Prop} [decidable_pred p] {v : Π₀ i, β i} : (- v).subtype_domain p = - v.subtype_domain p := ext $ λ i, by simp only [neg_apply, subtype_domain_apply] @[simp] lemma subtype_domain_sub [Π i, add_group (β i)] {p : ι → Prop} [decidable_pred p] {v v' : Π₀ i, β i} : (v - v').subtype_domain p = v.subtype_domain p - v'.subtype_domain p := ext $ λ i, by simp only [sub_apply, subtype_domain_apply] end filter_and_subtype_domain variable [decidable_eq ι] section basic variable [Π i, has_zero (β i)] lemma finite_supp (f : Π₀ i, β i) : set.finite {i | f i ≠ 0} := quotient.induction_on f $ λ x, set.finite_subset (finset.finite_to_set x.2.to_finset) $ λ i H, multiset.mem_to_finset.2 $ (x.3 i).resolve_right H def mk (s : finset ι) (x : Π i : (↑s : set ι), β i.1) : Π₀ i, β i := ⟦⟨λ i, if H : i ∈ s then x ⟨i, H⟩ else 0, s.1, λ i, if H : i ∈ s then or.inl H else or.inr $ dif_neg H⟩⟧ @[simp] lemma mk_apply {s : finset ι} {x : Π i : (↑s : set ι), β i.1} {i : ι} : (mk s x : Π i, β i) i = if H : i ∈ s then x ⟨i, H⟩ else 0 := rfl theorem mk_inj (s : finset ι) : function.injective (@mk ι β _ _ s) := begin intros x y H, ext i, have h1 : (mk s x : Π i, β i) i = (mk s y : Π i, β i) i, {rw H}, cases i with i hi, change i ∈ s at hi, dsimp only [mk_apply, subtype.coe_mk] at h1, simpa only [dif_pos hi] using h1 end def single (i : ι) (b : β i) : Π₀ i, β i := mk (finset.singleton i) $ λ j, eq.rec_on (finset.mem_singleton.1 j.2).symm b @[simp] lemma single_apply {i i' b} : (single i b : Π₀ i, β i) i' = (if h : i = i' then eq.rec_on h b else 0) := begin dsimp only [single], by_cases h : i = i', { have h1 : i' ∈ finset.singleton i, { simp only [h, finset.mem_singleton] }, simp only [mk_apply, dif_pos h, dif_pos h1] }, { have h1 : i' ∉ finset.singleton i, { simp only [ne.symm h, finset.mem_singleton, not_false_iff] }, simp only [mk_apply, dif_neg h, dif_neg h1] } end @[simp] lemma single_zero {i} : (single i 0 : Π₀ i, β i) = 0 := quotient.sound $ λ j, if H : j ∈ finset.singleton i then by dsimp only; rw [dif_pos H]; cases finset.mem_singleton.1 H; refl else dif_neg H @[simp] lemma single_eq_same {i b} : (single i b : Π₀ i, β i) i = b := by simp only [single_apply, dif_pos rfl] lemma single_eq_of_ne {i i' b} (h : i ≠ i') : (single i b : Π₀ i, β i) i' = 0 := by simp only [single_apply, dif_neg h] def erase (i : ι) (f : Π₀ i, β i) : Π₀ i, β i := quotient.lift_on f (λ x, ⟦(⟨λ j, if j = i then 0 else x.1 j, x.2, λ j, or.cases_on (x.3 j) or.inl $ λ H, or.inr $ by simp only [H, if_t_t]⟩ : pre ι β)⟧) $ λ x y H, quotient.sound $ λ j, if h : j = i then by simp only [if_pos h] else by simp only [if_neg h, H j] @[simp] lemma erase_apply {i j : ι} {f : Π₀ i, β i} : (f.erase i) j = if j = i then 0 else f j := quotient.induction_on f $ λ x, rfl @[simp] lemma erase_same {i : ι} {f : Π₀ i, β i} : (f.erase i) i = 0 := by simp lemma erase_ne {i i' : ι} {f : Π₀ i, β i} (h : i' ≠ i) : (f.erase i) i' = f i' := by simp [h] end basic section add_monoid variable [Π i, add_monoid (β i)] @[simp] lemma single_add {i : ι} {b₁ b₂ : β i} : single i (b₁ + b₂) = single i b₁ + single i b₂ := ext $ assume i', begin by_cases h : i = i', { subst h, simp only [add_apply, single_eq_same] }, { simp only [add_apply, single_eq_of_ne h, zero_add] } end lemma single_add_erase {i : ι} {f : Π₀ i, β i} : single i (f i) + f.erase i = f := ext $ λ i', if h : i = i' then by subst h; simp only [add_apply, single_apply, erase_apply, dif_pos rfl, if_pos, add_zero] else by simp only [add_apply, single_apply, erase_apply, dif_neg h, if_neg (ne.symm h), zero_add] lemma erase_add_single {i : ι} {f : Π₀ i, β i} : f.erase i + single i (f i) = f := ext $ λ i', if h : i = i' then by subst h; simp only [add_apply, single_apply, erase_apply, dif_pos rfl, if_pos, zero_add] else by simp only [add_apply, single_apply, erase_apply, dif_neg h, if_neg (ne.symm h), add_zero] protected theorem induction {p : (Π₀ i, β i) → Prop} (f : Π₀ i, β i) (h0 : p 0) (ha : ∀i b (f : Π₀ i, β i), f i = 0 → b ≠ 0 → p f → p (single i b + f)) : p f := begin refine quotient.induction_on f (λ x, _), cases x with f s H, revert f H, apply multiset.induction_on s, { intros f H, convert h0, ext i, exact (H i).resolve_left id }, intros i s ih f H, by_cases H1 : i ∈ s, { have H2 : ∀ j, j ∈ s ∨ f j = 0, { intro j, cases H j with H2 H2, { cases multiset.mem_cons.1 H2 with H3 H3, { left, rw H3, exact H1 }, { left, exact H3 } }, right, exact H2 }, have H3 : (⟦{to_fun := f, pre_support := i :: s, zero := H}⟧ : Π₀ i, β i) = ⟦{to_fun := f, pre_support := s, zero := H2}⟧, { exact quotient.sound (λ i, rfl) }, rw H3, apply ih }, have H2 : p (erase i ⟦{to_fun := f, pre_support := i :: s, zero := H}⟧), { dsimp only [erase, quotient.lift_on_beta], have H2 : ∀ j, j ∈ s ∨ ite (j = i) 0 (f j) = 0, { intro j, cases H j with H2 H2, { cases multiset.mem_cons.1 H2 with H3 H3, { right, exact if_pos H3 }, { left, exact H3 } }, right, split_ifs; [refl, exact H2] }, have H3 : (⟦{to_fun := λ (j : ι), ite (j = i) 0 (f j), pre_support := i :: s, zero := _}⟧ : Π₀ i, β i) = ⟦{to_fun := λ (j : ι), ite (j = i) 0 (f j), pre_support := s, zero := H2}⟧ := quotient.sound (λ i, rfl), rw H3, apply ih }, have H3 : single i _ + _ = (⟦{to_fun := f, pre_support := i :: s, zero := H}⟧ : Π₀ i, β i) := single_add_erase, rw ← H3, change p (single i (f i) + _), cases classical.em (f i = 0) with h h, { rw [h, single_zero, zero_add], exact H2 }, refine ha _ _ _ _ h H2, rw erase_same end lemma induction₂ {p : (Π₀ i, β i) → Prop} (f : Π₀ i, β i) (h0 : p 0) (ha : ∀i b (f : Π₀ i, β i), f i = 0 → b ≠ 0 → p f → p (f + single i b)) : p f := dfinsupp.induction f h0 $ λ i b f h1 h2 h3, have h4 : f + single i b = single i b + f, { ext j, by_cases H : i = j, { subst H, simp [h1] }, { simp [H] } }, eq.rec_on h4 $ ha i b f h1 h2 h3 end add_monoid @[simp] lemma mk_add [Π i, add_monoid (β i)] {s : finset ι} {x y : Π i : (↑s : set ι), β i.1} : mk s (x + y) = mk s x + mk s y := ext $ λ i, by simp only [add_apply, mk_apply]; split_ifs; [refl, rw zero_add] @[simp] lemma mk_zero [Π i, has_zero (β i)] {s : finset ι} : mk s (0 : Π i : (↑s : set ι), β i.1) = 0 := ext $ λ i, by simp only [mk_apply]; split_ifs; refl @[simp] lemma mk_neg [Π i, add_group (β i)] {s : finset ι} {x : Π i : (↑s : set ι), β i.1} : mk s (-x) = -mk s x := ext $ λ i, by simp only [neg_apply, mk_apply]; split_ifs; [refl, rw neg_zero] @[simp] lemma mk_sub [Π i, add_group (β i)] {s : finset ι} {x y : Π i : (↑s : set ι), β i.1} : mk s (x - y) = mk s x - mk s y := ext $ λ i, by simp only [sub_apply, mk_apply]; split_ifs; [refl, rw sub_zero] instance [Π i, add_group (β i)] {s : finset ι} : is_add_group_hom (@mk ι β _ _ s) := { map_add := λ _ _, mk_add } section local attribute [instance] to_module variables (γ : Type w) [ring γ] [Π i, add_comm_group (β i)] [Π i, module γ (β i)] include γ @[simp] lemma mk_smul {s : finset ι} {c : γ} (x : Π i : (↑s : set ι), β i.1) : mk s (c • x) = c • mk s x := ext $ λ i, by simp only [smul_apply, mk_apply]; split_ifs; [refl, rw smul_zero] @[simp] lemma single_smul {i : ι} {c : γ} {x : β i} : single i (c • x) = c • single i x := ext $ λ i, by simp only [smul_apply, single_apply]; split_ifs; [cases h, rw smul_zero]; refl variable β def lmk (s : finset ι) : (Π i : (↑s : set ι), β i.1) →ₗ[γ] Π₀ i, β i := ⟨mk s, λ _ _, mk_add, λ c x, by rw [mk_smul γ x]⟩ def lsingle (i) : β i →ₗ[γ] Π₀ i, β i := ⟨single i, λ _ _, single_add, λ _ _, single_smul _⟩ variable {β} @[simp] lemma lmk_apply {s : finset ι} {x} : lmk β γ s x = mk s x := rfl @[simp] lemma lsingle_apply {i : ι} {x : β i} : lsingle β γ i x = single i x := rfl end section support_basic variables [Π i, has_zero (β i)] [Π i, decidable_pred (eq (0 : β i))] def support (f : Π₀ i, β i) : finset ι := quotient.lift_on f (λ x, x.2.to_finset.filter $ λ i, x.1 i ≠ 0) $ begin intros x y Hxy, ext i, split, { intro H, rcases finset.mem_filter.1 H with ⟨h1, h2⟩, rw Hxy i at h2, exact finset.mem_filter.2 ⟨multiset.mem_to_finset.2 $ (y.3 i).resolve_right h2, h2⟩ }, { intro H, rcases finset.mem_filter.1 H with ⟨h1, h2⟩, rw ← Hxy i at h2, exact finset.mem_filter.2 ⟨multiset.mem_to_finset.2 $ (x.3 i).resolve_right h2, h2⟩ }, end @[simp] theorem support_mk_subset {s : finset ι} {x : Π i : (↑s : set ι), β i.1} : (mk s x).support ⊆ s := λ i H, multiset.mem_to_finset.1 (finset.mem_filter.1 H).1 @[simp] theorem mem_support_to_fun (f : Π₀ i, β i) (i) : i ∈ f.support ↔ f i ≠ 0 := begin refine quotient.induction_on f (λ x, _), dsimp only [support, quotient.lift_on_beta], rw [finset.mem_filter, multiset.mem_to_finset], exact and_iff_right_of_imp (x.3 i).resolve_right end theorem eq_mk_support (f : Π₀ i, β i) : f = mk f.support (λ i, f i.1) := by ext i; by_cases h : f i = 0; try {simp at h}; simp [h] @[simp] lemma support_zero : (0 : Π₀ i, β i).support = ∅ := rfl lemma mem_support_iff (f : Π₀ i, β i) : ∀i:ι, i ∈ f.support ↔ f i ≠ 0 := f.mem_support_to_fun @[simp] lemma support_eq_empty {f : Π₀ i, β i} : f.support = ∅ ↔ f = 0 := ⟨λ H, ext $ by simpa [finset.ext] using H, by simp {contextual:=tt}⟩ instance decidable_zero : decidable_pred (eq (0 : Π₀ i, β i)) := λ f, decidable_of_iff _ $ support_eq_empty.trans eq_comm lemma support_subset_iff {s : set ι} {f : Π₀ i, β i} : ↑f.support ⊆ s ↔ (∀i∉s, f i = 0) := by simp [set.subset_def]; exact forall_congr (assume i, @not_imp_comm _ _ (classical.dec _) (classical.dec _)) lemma support_single_ne_zero {i : ι} {b : β i} (hb : b ≠ 0) : (single i b).support = {i} := begin ext j, by_cases h : i = j, { subst h, simp [hb] }, simp [ne.symm h, h] end lemma support_single_subset {i : ι} {b : β i} : (single i b).support ⊆ {i} := support_mk_subset section map_range_and_zip_with variables {β₁ : ι → Type v₁} {β₂ : ι → Type v₂} variables [Π i, has_zero (β₁ i)] [Π i, has_zero (β₂ i)] variables [Π i, decidable_pred (eq (0 : β₁ i))] [Π i, decidable_pred (eq (0 : β₂ i))] lemma map_range_def {f : Π i, β₁ i → β₂ i} {hf : ∀ i, f i 0 = 0} {g : Π₀ i, β₁ i} : map_range f hf g = mk g.support (λ i, f i.1 (g i.1)) := begin ext i, by_cases h : g i = 0, { simp [h, hf] }, { simp at h, simp [h, hf] } end lemma support_map_range {f : Π i, β₁ i → β₂ i} {hf : ∀ i, f i 0 = 0} {g : Π₀ i, β₁ i} : (map_range f hf g).support ⊆ g.support := by simp [map_range_def] @[simp] lemma map_range_single {f : Π i, β₁ i → β₂ i} {hf : ∀ i, f i 0 = 0} {i : ι} {b : β₁ i} : map_range f hf (single i b) = single i (f i b) := dfinsupp.ext $ λ i', by by_cases i = i'; [{subst i', simp}, simp [h, hf]] lemma zip_with_def {f : Π i, β₁ i → β₂ i → β i} {hf : ∀ i, f i 0 0 = 0} {g₁ : Π₀ i, β₁ i} {g₂ : Π₀ i, β₂ i} : zip_with f hf g₁ g₂ = mk (g₁.support ∪ g₂.support) (λ i, f i.1 (g₁ i.1) (g₂ i.1)) := begin ext i, by_cases h1 : g₁ i = 0; by_cases h2 : g₂ i = 0; try {simp at h1 h2}; simp [h1, h2, hf] end lemma support_zip_with {f : Π i, β₁ i → β₂ i → β i} {hf : ∀ i, f i 0 0 = 0} {g₁ : Π₀ i, β₁ i} {g₂ : Π₀ i, β₂ i} : (zip_with f hf g₁ g₂).support ⊆ g₁.support ∪ g₂.support := by simp [zip_with_def] end map_range_and_zip_with lemma erase_def (i : ι) (f : Π₀ i, β i) : f.erase i = mk (f.support.erase i) (λ j, f j.1) := begin ext j, by_cases h1 : j = i; by_cases h2 : f j = 0; try {simp at h2}; simp [h1, h2] end @[simp] lemma support_erase (i : ι) (f : Π₀ i, β i) : (f.erase i).support = f.support.erase i := begin ext j, by_cases h1 : j = i; by_cases h2 : f j = 0; try {simp at h2}; simp [h1, h2] end section filter_and_subtype_domain variables {p : ι → Prop} [decidable_pred p] lemma filter_def (f : Π₀ i, β i) : f.filter p = mk (f.support.filter p) (λ i, f i.1) := by ext i; by_cases h1 : p i; by_cases h2 : f i = 0; try {simp at h2}; simp [h1, h2] @[simp] lemma support_filter (f : Π₀ i, β i) : (f.filter p).support = f.support.filter p := by ext i; by_cases h : p i; simp [h] lemma subtype_domain_def (f : Π₀ i, β i) : f.subtype_domain p = mk (f.support.subtype p) (λ i, f i.1) := by ext i; cases i with i hi; by_cases h1 : p i; by_cases h2 : f i = 0; try {simp at h2}; dsimp; simp [h1, h2] @[simp] lemma support_subtype_domain {f : Π₀ i, β i} : (subtype_domain p f).support = f.support.subtype p := by ext i; cases i with i hi; by_cases h1 : p i; by_cases h2 : f i = 0; try {simp at h2}; dsimp; simp [h1, h2] end filter_and_subtype_domain end support_basic lemma support_add [Π i, add_monoid (β i)] [Π i, decidable_pred (eq (0 : β i))] {g₁ g₂ : Π₀ i, β i} : (g₁ + g₂).support ⊆ g₁.support ∪ g₂.support := support_zip_with @[simp] lemma support_neg [Π i, add_group (β i)] [Π i, decidable_pred (eq (0 : β i))] {f : Π₀ i, β i} : support (-f) = support f := by ext i; simp local attribute [instance] dfinsupp.to_module lemma support_smul {γ : Type w} [ring γ] [Π i, add_comm_group (β i)] [Π i, module γ (β i)] [Π (i : ι), decidable_pred (eq (0 : β i))] {b : γ} {v : Π₀ i, β i} : (b • v).support ⊆ v.support := support_map_range instance [decidable_eq ι] [Π i, has_zero (β i)] [Π i, decidable_eq (β i)] : decidable_eq (Π₀ i, β i) := assume f g, decidable_of_iff (f.support = g.support ∧ (∀i∈f.support, f i = g i)) ⟨assume ⟨h₁, h₂⟩, ext $ assume i, if h : i ∈ f.support then h₂ i h else have hf : f i = 0, by rwa [f.mem_support_iff, not_not] at h, have hg : g i = 0, by rwa [h₁, g.mem_support_iff, not_not] at h, by rw [hf, hg], by intro h; subst h; simp⟩ section prod_and_sum variables {γ : Type w} -- [to_additive sum] for dfinsupp.prod doesn't work, the equation lemmas are not generated /-- `sum f g` is the sum of `g i (f i)` over the support of `f`. -/ def sum [Π i, has_zero (β i)] [Π i, decidable_pred (eq (0 : β i))] [add_comm_monoid γ] (f : Π₀ i, β i) (g : Π i, β i → γ) : γ := f.support.sum (λi, g i (f i)) /-- `prod f g` is the product of `g i (f i)` over the support of `f`. -/ @[to_additive] def prod [Π i, has_zero (β i)] [Π i, decidable_pred (eq (0 : β i))] [comm_monoid γ] (f : Π₀ i, β i) (g : Π i, β i → γ) : γ := f.support.prod (λi, g i (f i)) @[to_additive] lemma prod_map_range_index {β₁ : ι → Type v₁} {β₂ : ι → Type v₂} [Π i, has_zero (β₁ i)] [Π i, has_zero (β₂ i)] [Π i, decidable_pred (eq (0 : β₁ i))] [Π i, decidable_pred (eq (0 : β₂ i))] [comm_monoid γ] {f : Π i, β₁ i → β₂ i} {hf : ∀ i, f i 0 = 0} {g : Π₀ i, β₁ i} {h : Π i, β₂ i → γ} (h0 : ∀i, h i 0 = 1) : (map_range f hf g).prod h = g.prod (λi b, h i (f i b)) := begin rw [map_range_def], refine (finset.prod_subset support_mk_subset _).trans _, { intros i h1 h2, dsimp, simp [h1] at h2, dsimp at h2, simp [h1, h2, h0] }, { refine finset.prod_congr rfl _, intros i h1, simp [h1] } end @[to_additive] lemma prod_zero_index [Π i, add_comm_monoid (β i)] [Π i, decidable_pred (eq (0 : β i))] [comm_monoid γ] {h : Π i, β i → γ} : (0 : Π₀ i, β i).prod h = 1 := rfl @[to_additive] lemma prod_single_index [Π i, has_zero (β i)] [Π i, decidable_pred (eq (0 : β i))] [comm_monoid γ] {i : ι} {b : β i} {h : Π i, β i → γ} (h_zero : h i 0 = 1) : (single i b).prod h = h i b := begin by_cases h : b = 0, { simp [h, prod_zero_index, h_zero], refl }, { simp [dfinsupp.prod, support_single_ne_zero h] } end @[to_additive] lemma prod_neg_index [Π i, add_group (β i)] [Π i, decidable_pred (eq (0 : β i))] [comm_monoid γ] {g : Π₀ i, β i} {h : Π i, β i → γ} (h0 : ∀i, h i 0 = 1) : (-g).prod h = g.prod (λi b, h i (- b)) := prod_map_range_index h0 @[simp] lemma sum_apply {ι₁ : Type u₁} [decidable_eq ι₁] {β₁ : ι₁ → Type v₁} [Π i₁, has_zero (β₁ i₁)] [Π i, decidable_pred (eq (0 : β₁ i))] [Π i, add_comm_monoid (β i)] {f : Π₀ i₁, β₁ i₁} {g : Π i₁, β₁ i₁ → Π₀ i, β i} {i₂ : ι} : (f.sum g) i₂ = f.sum (λi₁ b, g i₁ b i₂) := (f.support.sum_hom (λf : Π₀ i, β i, f i₂)).symm lemma support_sum {ι₁ : Type u₁} [decidable_eq ι₁] {β₁ : ι₁ → Type v₁} [Π i₁, has_zero (β₁ i₁)] [Π i, decidable_pred (eq (0 : β₁ i))] [Π i, add_comm_monoid (β i)] [Π i, decidable_pred (eq (0 : β i))] {f : Π₀ i₁, β₁ i₁} {g : Π i₁, β₁ i₁ → Π₀ i, β i} : (f.sum g).support ⊆ f.support.bind (λi, (g i (f i)).support) := have ∀i₁ : ι, f.sum (λ (i : ι₁) (b : β₁ i), (g i b) i₁) ≠ 0 → (∃ (i : ι₁), f i ≠ 0 ∧ ¬ (g i (f i)) i₁ = 0), from assume i₁ h, let ⟨i, hi, ne⟩ := finset.exists_ne_zero_of_sum_ne_zero h in ⟨i, (f.mem_support_iff i).mp hi, ne⟩, by simpa [finset.subset_iff, mem_support_iff, finset.mem_bind, sum_apply] using this @[simp] lemma sum_zero [Π i, add_comm_monoid (β i)] [Π i, decidable_pred (eq (0 : β i))] [add_comm_monoid γ] {f : Π₀ i, β i} : f.sum (λi b, (0 : γ)) = 0 := finset.sum_const_zero @[simp] lemma sum_add [Π i, add_comm_monoid (β i)] [Π i, decidable_pred (eq (0 : β i))] [add_comm_monoid γ] {f : Π₀ i, β i} {h₁ h₂ : Π i, β i → γ} : f.sum (λi b, h₁ i b + h₂ i b) = f.sum h₁ + f.sum h₂ := finset.sum_add_distrib @[simp] lemma sum_neg [Π i, add_comm_monoid (β i)] [Π i, decidable_pred (eq (0 : β i))] [add_comm_group γ] {f : Π₀ i, β i} {h : Π i, β i → γ} : f.sum (λi b, - h i b) = - f.sum h := f.support.sum_hom (@has_neg.neg γ _) @[to_additive] lemma prod_add_index [Π i, add_comm_monoid (β i)] [Π i, decidable_pred (eq (0 : β i))] [comm_monoid γ] {f g : Π₀ i, β i} {h : Π i, β i → γ} (h_zero : ∀i, h i 0 = 1) (h_add : ∀i b₁ b₂, h i (b₁ + b₂) = h i b₁ * h i b₂) : (f + g).prod h = f.prod h * g.prod h := have f_eq : (f.support ∪ g.support).prod (λi, h i (f i)) = f.prod h, from (finset.prod_subset (finset.subset_union_left _ _) $ by simp [mem_support_iff, h_zero] {contextual := tt}).symm, have g_eq : (f.support ∪ g.support).prod (λi, h i (g i)) = g.prod h, from (finset.prod_subset (finset.subset_union_right _ _) $ by simp [mem_support_iff, h_zero] {contextual := tt}).symm, calc (f + g).support.prod (λi, h i ((f + g) i)) = (f.support ∪ g.support).prod (λi, h i ((f + g) i)) : finset.prod_subset support_add $ by simp [mem_support_iff, h_zero] {contextual := tt} ... = (f.support ∪ g.support).prod (λi, h i (f i)) * (f.support ∪ g.support).prod (λi, h i (g i)) : by simp [h_add, finset.prod_mul_distrib] ... = _ : by rw [f_eq, g_eq] lemma sum_sub_index [Π i, add_comm_group (β i)] [Π i, decidable_pred (eq (0 : β i))] [add_comm_group γ] {f g : Π₀ i, β i} {h : Π i, β i → γ} (h_sub : ∀i b₁ b₂, h i (b₁ - b₂) = h i b₁ - h i b₂) : (f - g).sum h = f.sum h - g.sum h := have h_zero : ∀i, h i 0 = 0, from assume i, have h i (0 - 0) = h i 0 - h i 0, from h_sub i 0 0, by simpa using this, have h_neg : ∀i b, h i (- b) = - h i b, from assume i b, have h i (0 - b) = h i 0 - h i b, from h_sub i 0 b, by simpa [h_zero] using this, have h_add : ∀i b₁ b₂, h i (b₁ + b₂) = h i b₁ + h i b₂, from assume i b₁ b₂, have h i (b₁ - (- b₂)) = h i b₁ - h i (- b₂), from h_sub i b₁ (-b₂), by simpa [h_neg, sub_eq_add_neg] using this, by simp [sub_eq_add_neg]; simp [@sum_add_index ι β _ γ _ _ _ f (-g) h h_zero h_add]; simp [@sum_neg_index ι β _ γ _ _ _ g h h_zero, h_neg]; simp [@sum_neg ι β _ γ _ _ _ g h] @[to_additive] lemma prod_finset_sum_index {γ : Type w} {α : Type x} [Π i, add_comm_monoid (β i)] [Π i, decidable_pred (eq (0 : β i))] [comm_monoid γ] [decidable_eq α] {s : finset α} {g : α → Π₀ i, β i} {h : Π i, β i → γ} (h_zero : ∀i, h i 0 = 1) (h_add : ∀i b₁ b₂, h i (b₁ + b₂) = h i b₁ * h i b₂) : s.prod (λi, (g i).prod h) = (s.sum g).prod h := finset.induction_on s (by simp [prod_zero_index]) (by simp [prod_add_index, h_zero, h_add] {contextual := tt}) @[to_additive] lemma prod_sum_index {ι₁ : Type u₁} [decidable_eq ι₁] {β₁ : ι₁ → Type v₁} [Π i₁, has_zero (β₁ i₁)] [Π i, decidable_pred (eq (0 : β₁ i))] [Π i, add_comm_monoid (β i)] [Π i, decidable_pred (eq (0 : β i))] [comm_monoid γ] {f : Π₀ i₁, β₁ i₁} {g : Π i₁, β₁ i₁ → Π₀ i, β i} {h : Π i, β i → γ} (h_zero : ∀i, h i 0 = 1) (h_add : ∀i b₁ b₂, h i (b₁ + b₂) = h i b₁ * h i b₂) : (f.sum g).prod h = f.prod (λi b, (g i b).prod h) := (prod_finset_sum_index h_zero h_add).symm @[simp] lemma sum_single [Π i, add_comm_monoid (β i)] [Π i, decidable_pred (eq (0 : β i))] {f : Π₀ i, β i} : f.sum single = f := begin apply dfinsupp.induction f, {rw [sum_zero_index]}, intros i b f H hb ih, rw [sum_add_index, ih, sum_single_index], all_goals { intros, simp } end @[to_additive] lemma prod_subtype_domain_index [Π i, has_zero (β i)] [Π i, decidable_pred (eq (0 : β i))] [comm_monoid γ] {v : Π₀ i, β i} {p : ι → Prop} [decidable_pred p] {h : Π i, β i → γ} (hp : ∀x∈v.support, p x) : (v.subtype_domain p).prod (λi b, h i.1 b) = v.prod h := finset.prod_bij (λp _, p.val) (by simp) (by simp) (assume ⟨a₀, ha₀⟩ ⟨a₁, ha₁⟩, by simp) (λ i hi, ⟨⟨i, hp i hi⟩, by simpa using hi, rfl⟩) lemma subtype_domain_sum [Π i, add_comm_monoid (β i)] [Π i, decidable_pred (eq (0 : β i))] {s : finset γ} {h : γ → Π₀ i, β i} {p : ι → Prop} [decidable_pred p] : (s.sum h).subtype_domain p = s.sum (λc, (h c).subtype_domain p) := eq.symm (s.sum_hom _) lemma subtype_domain_finsupp_sum {δ : γ → Type x} [decidable_eq γ] [Π c, has_zero (δ c)] [Π c, decidable_pred (eq (0 : δ c))] [Π i, add_comm_monoid (β i)] [Π i, decidable_pred (eq (0 : β i))] {p : ι → Prop} [decidable_pred p] {s : Π₀ c, δ c} {h : Π c, δ c → Π₀ i, β i} : (s.sum h).subtype_domain p = s.sum (λc d, (h c d).subtype_domain p) := subtype_domain_sum end prod_and_sum end dfinsupp
12aa775bfc09f6c856dc59bc8f674dde139fcab9
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/logic/small.lean
6c31694f07a169a203822359932e4c05d35ef650
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,026
lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import data.equiv.set /-! # Small types A type is `w`-small if there exists an equivalence to some `S : Type w`. We provide a noncomputable model `shrink α : Type w`, and `equiv_shrink α : α ≃ shrink α`. A subsingleton type is `w`-small for any `w`. If `α ≃ β`, then `small.{w} α ↔ small.{w} β`. -/ universes u w v /-- A type is `small.{w}` if there exists an equivalence to some `S : Type w`. -/ class small (α : Type v) : Prop := (equiv_small : ∃ (S : Type w), nonempty (α ≃ S)) /-- Constructor for `small α` from an explicit witness type and equivalence. -/ lemma small.mk' {α : Type v} {S : Type w} (e : α ≃ S) : small.{w} α := ⟨⟨S, ⟨e⟩⟩⟩ /-- An arbitrarily chosen model in `Type w` for a `w`-small type. -/ @[nolint has_inhabited_instance] def shrink (α : Type v) [small.{w} α] : Type w := classical.some (@small.equiv_small α _) /-- The noncomputable equivalence between a `w`-small type and a model. -/ noncomputable def equiv_shrink (α : Type v) [small.{w} α] : α ≃ shrink α := nonempty.some (classical.some_spec (@small.equiv_small α _)) @[priority 100] instance small_self (α : Type v) : small.{v} α := small.mk' (equiv.refl _) @[priority 100] instance small_max (α : Type v) : small.{max w v} α := small.mk' equiv.ulift.{w}.symm instance small_ulift (α : Type v) : small.{v} (ulift.{w} α) := small.mk' equiv.ulift theorem small_type : small.{max (u+1) v} (Type u) := small_max.{max (u+1) v} _ section open_locale classical theorem small_congr {α : Type*} {β : Type*} (e : α ≃ β) : small.{w} α ↔ small.{w} β := begin fsplit, { rintro ⟨S, ⟨f⟩⟩, exact small.mk' (e.symm.trans f), }, { rintro ⟨S, ⟨f⟩⟩, exact small.mk' (e.trans f), }, end instance small_subtype (α : Type v) [small.{w} α] (P : α → Prop) : small.{w} { x // P x } := begin rw small_congr (equiv_shrink α).subtype_equiv_of_subtype', apply_instance, end theorem small_of_injective {α : Type*} {β : Type*} [small.{w} β] (f : α → β) (hf : function.injective f) : small.{w} α := begin rw small_congr (equiv.of_injective f hf), apply_instance, end @[priority 100] instance small_subsingleton (α : Type v) [subsingleton α] : small.{w} α := begin rcases is_empty_or_nonempty α; resetI, { rw small_congr (equiv.equiv_pempty α), apply small_self, }, { rw small_congr equiv.punit_of_nonempty_of_subsingleton, apply small_self, assumption, assumption, }, end /-! We don't define `small_of_fintype` or `small_of_encodable` in this file, to keep imports to `logic` to a minimum. -/ instance small_Pi {α} (β : α → Type*) [small.{w} α] [∀ a, small.{w} (β a)] : small.{w} (Π a, β a) := ⟨⟨Π a' : shrink α, shrink (β ((equiv_shrink α).symm a')), ⟨equiv.Pi_congr (equiv_shrink α) (λ a, by simpa using equiv_shrink (β a))⟩⟩⟩ instance small_sigma {α} (β : α → Type*) [small.{w} α] [∀ a, small.{w} (β a)] : small.{w} (Σ a, β a) := ⟨⟨Σ a' : shrink α, shrink (β ((equiv_shrink α).symm a')), ⟨equiv.sigma_congr (equiv_shrink α) (λ a, by simpa using equiv_shrink (β a))⟩⟩⟩ instance small_prod {α β} [small.{w} α] [small.{w} β] : small.{w} (α × β) := ⟨⟨shrink α × shrink β, ⟨equiv.prod_congr (equiv_shrink α) (equiv_shrink β)⟩⟩⟩ instance small_sum {α β} [small.{w} α] [small.{w} β] : small.{w} (α ⊕ β) := ⟨⟨shrink α ⊕ shrink β, ⟨equiv.sum_congr (equiv_shrink α) (equiv_shrink β)⟩⟩⟩ instance small_set {α} [small.{w} α] : small.{w} (set α) := ⟨⟨set (shrink α), ⟨equiv.set.congr (equiv_shrink α)⟩⟩⟩ theorem not_small_type : ¬ small.{u} (Type (max u v)) | ⟨⟨S, ⟨e⟩⟩⟩ := @function.cantor_injective (Σ α, e.symm α) (λ a, ⟨_, cast (e.3 _).symm a⟩) (λ a b e, (cast_inj _).1 $ eq_of_heq (sigma.mk.inj e).2) end
133ca770238b900e7fd88200825934c9bbd8667b
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/library/init/meta/level.lean
f0459135dc611e7b2010e26c3bbe1a59848555fc
[ "Apache-2.0" ]
permissive
soonhokong/lean-osx
4a954262c780e404c1369d6c06516161d07fcb40
3670278342d2f4faa49d95b46d86642d7875b47c
refs/heads/master
1,611,410,334,552
1,474,425,686,000
1,474,425,686,000
12,043,103
5
1
null
null
null
null
UTF-8
Lean
false
false
2,563
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.meta.name init.meta.format /- Reflect a C++ level object. The VM replaces it with the C++ implementation. -/ inductive level | zero : level | succ : level → level | max : level → level → level | imax : level → level → level | param : name → level | global : name → level | meta : name → level attribute [instance] definition level.is_inhabited : inhabited level := inhabited.mk level.zero /- TODO(Leo): provide a definition in Lean. -/ meta_constant level.has_decidable_eq : decidable_eq level attribute [instance] level.has_decidable_eq meta_constant level.lt : level → level → bool meta_constant level.lex_lt : level → level → bool meta_constant level.fold {A :Type} : level → A → (level → A → A) → A /- Return the given level expression normal form -/ meta_constant level.normalize : level → level /- Return tt iff lhs and rhs denote the same level. The check is done by normalization. -/ meta_constant level.eqv : level → level → bool /- Return tt iff the first level occurs in the second -/ meta_constant level.occurs : level → level → bool /- Replace a parameter named n with l in the first level if the list contains the pair (n, l) -/ meta_constant level.instantiate : level → list (name × level) → list level meta_constant level.to_format : level → options → format meta_constant level.to_string : level → string meta_definition level.cmp (a b : level) : ordering := if level.lt a b = bool.tt then ordering.lt else if a = b then ordering.eq else ordering.gt attribute [instance] meta_definition level.has_to_string : has_to_string level := has_to_string.mk level.to_string attribute [instance] meta_definition level.has_to_format : has_to_format level := has_to_format.mk (λ l, level.to_format l options.mk) attribute [instance] meta_definition level.has_to_cmp : has_ordering level := has_ordering.mk level.cmp meta_definition level.of_nat : nat → level | 0 := level.zero | (nat.succ n) := level.succ (level.of_nat n) open decidable meta_definition level.has_param : level → name → bool | (level.succ l) n := level.has_param l n | (level.max l₁ l₂) n := level.has_param l₁ n || level.has_param l₂ n | (level.imax l₁ l₂) n := level.has_param l₁ n || level.has_param l₂ n | (level.param n₁) n := to_bool (n₁ = n) | l n := ff
a5fe75a57b07ec1ae950bba36f5f0990a7076663
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/clear_auto.lean
5d51ae409a3bf3a8c6bc9d64c0a78dc98aba28ab
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
2,457
lean
/- Copyright (c) 2020 Jannis Limperg. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jannis Limperg -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.tactic.core import Mathlib.PostPort namespace Mathlib /-! # Better `clear` tactics We define two variants of the standard `clear` tactic: * `clear'` works like `clear` but the hypotheses that should be cleared can be given in any order. In contrast, `clear` can fail if hypotheses that depend on each other are given in the wrong order, even if all of them could be cleared. * `clear_dependent` works like `clear'` but also clears any hypotheses that depend on the given hypotheses. ## Implementation notes The implementation (ab)uses the native `revert_lst`, which can figure out dependencies between hypotheses. This implementation strategy was suggested by Simon Hudon. -/ /-- Clears all the hypotheses in `hyps`. The tactic fails if any of the `hyps` is not a local or if the target depends on any of the `hyps`. It also fails if `hyps` contains duplicates. If there are local hypotheses or definitions, say `H`, which are not in `hyps` but depend on one of the `hyps`, what we do depends on `clear_dependent`. If it is true, `H` is implicitly also cleared. If it is false, `clear'` fails. -/ -- Check if the target depends on any of the hyps. Doing this (instead of -- letting one of the later tactics fail) lets us give a much more informative -- error message. -- If revert_lst reverted more hypotheses than we wanted to clear, there must -- have been other hypotheses dependent on some of the hyps. namespace tactic.interactive /-- An improved version of the standard `clear` tactic. `clear` is sensitive to the order of its arguments: `clear x y` may fail even though both `x` and `y` could be cleared (if the type of `y` depends on `x`). `clear'` lifts this limitation. ```lean example {α} {β : α → Type} (a : α) (b : β a) : unit := begin try { clear a b }, -- fails since `b` depends on `a` clear' a b, -- succeeds exact () end ``` -/ /-- A variant of `clear'` which clears not only the given hypotheses, but also any other hypotheses depending on them. ```lean example {α} {β : α → Type} (a : α) (b : β a) : unit := begin try { clear' a }, -- fails since `b` depends on `a` clear_dependent a, -- succeeds, clearing `a` and `b` exact () end ``` -/ end Mathlib
ce3714c8fd601b1f271acf806890e10dd72db2b3
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/geometry/euclidean/circumcenter.lean
a56354f92eb914dfaef14d0fca1a5239ca9fc2b5
[ "Apache-2.0" ]
permissive
lacker/mathlib
f2439c743c4f8eb413ec589430c82d0f73b2d539
ddf7563ac69d42cfa4a1bfe41db1fed521bd795f
refs/heads/master
1,671,948,326,773
1,601,479,268,000
1,601,479,268,000
298,686,743
0
0
Apache-2.0
1,601,070,794,000
1,601,070,794,000
null
UTF-8
Lean
false
false
38,134
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Joseph Myers. -/ import geometry.euclidean.basic import linear_algebra.affine_space.finite_dimensional import tactic.derive_fintype noncomputable theory open_locale big_operators open_locale classical open_locale real /-! # Circumcenter and circumradius This file proves some lemmas on points equidistant from a set of points, and defines the circumradius and circumcenter of a simplex. There are also some definitions for use in calculations where it is convenient to work with affine combinations of vertices together with the circumcenter. ## Main definitions * `circumcenter` and `circumradius` are the circumcenter and circumradius of a simplex. ## References * https://en.wikipedia.org/wiki/Circumscribed_circle -/ namespace euclidean_geometry open inner_product_geometry variables {V : Type*} {P : Type*} [inner_product_space V] [metric_space P] [normed_add_torsor V P] include V open affine_subspace /-- `p` is equidistant from two points in `s` if and only if its `orthogonal_projection` is. -/ lemma dist_eq_iff_dist_orthogonal_projection_eq {s : affine_subspace ℝ P} {p1 p2 : P} (p3 : P) (hp1 : p1 ∈ s) (hp2 : p2 ∈ s) : dist p1 p3 = dist p2 p3 ↔ dist p1 (orthogonal_projection s p3) = dist p2 (orthogonal_projection s p3) := begin rw [←mul_self_inj_of_nonneg dist_nonneg dist_nonneg, ←mul_self_inj_of_nonneg dist_nonneg dist_nonneg, dist_square_eq_dist_orthogonal_projection_square_add_dist_orthogonal_projection_square p3 hp1, dist_square_eq_dist_orthogonal_projection_square_add_dist_orthogonal_projection_square p3 hp2], simp end /-- `p` is equidistant from a set of points in `s` if and only if its `orthogonal_projection` is. -/ lemma dist_set_eq_iff_dist_orthogonal_projection_eq {s : affine_subspace ℝ P} {ps : set P} (hps : ps ⊆ s) (p : P) : (set.pairwise_on ps (λ p1 p2, dist p1 p = dist p2 p) ↔ (set.pairwise_on ps (λ p1 p2, dist p1 (orthogonal_projection s p) = dist p2 (orthogonal_projection s p)))) := ⟨λ h p1 hp1 p2 hp2 hne, (dist_eq_iff_dist_orthogonal_projection_eq p (hps hp1) (hps hp2)).1 (h p1 hp1 p2 hp2 hne), λ h p1 hp1 p2 hp2 hne, (dist_eq_iff_dist_orthogonal_projection_eq p (hps hp1) (hps hp2)).2 (h p1 hp1 p2 hp2 hne)⟩ /-- There exists `r` such that `p` has distance `r` from all the points of a set of points in `s` if and only if there exists (possibly different) `r` such that its `orthogonal_projection` has that distance from all the points in that set. -/ lemma exists_dist_eq_iff_exists_dist_orthogonal_projection_eq {s : affine_subspace ℝ P} {ps : set P} (hps : ps ⊆ s) (p : P) : (∃ r, ∀ p1 ∈ ps, dist p1 p = r) ↔ ∃ r, ∀ p1 ∈ ps, dist p1 (orthogonal_projection s p) = r := begin have h := dist_set_eq_iff_dist_orthogonal_projection_eq hps p, simp_rw set.pairwise_on_eq_iff_exists_eq at h, exact h end /-- The induction step for the existence and uniqueness of the circumcenter. Given a nonempty set of points in a nonempty affine subspace whose direction is complete, such that there is a unique (circumcenter, circumradius) pair for those points in that subspace, and a point `p` not in that subspace, there is a unique (circumcenter, circumradius) pair for the set with `p` added, in the span of the subspace with `p` added. -/ lemma exists_unique_dist_eq_of_insert {s : affine_subspace ℝ P} (hc : is_complete (s.direction : set V)) {ps : set P} (hnps : ps.nonempty) {p : P} (hps : ps ⊆ s) (hp : p ∉ s) (hu : ∃! cccr : (P × ℝ), cccr.fst ∈ s ∧ ∀ p1 ∈ ps, dist p1 cccr.fst = cccr.snd) : ∃! cccr₂ : (P × ℝ), cccr₂.fst ∈ affine_span ℝ (insert p (s : set P)) ∧ ∀ p1 ∈ insert p ps, dist p1 cccr₂.fst = cccr₂.snd := begin have hn : (s : set P).nonempty := hnps.mono hps, rcases hu with ⟨⟨cc, cr⟩, ⟨hcc, hcr⟩, hcccru⟩, simp only [prod.fst, prod.snd] at hcc hcr hcccru, let x := dist cc (orthogonal_projection s p), let y := dist p (orthogonal_projection s p), have hy0 : y ≠ 0 := dist_orthogonal_projection_ne_zero_of_not_mem hn hc hp, let ycc₂ := (x * x + y * y - cr * cr) / (2 * y), let cc₂ := (ycc₂ / y) • (p -ᵥ orthogonal_projection s p : V) +ᵥ cc, let cr₂ := real.sqrt (cr * cr + ycc₂ * ycc₂), use (cc₂, cr₂), simp only [prod.fst, prod.snd], have hpo : p = (1 : ℝ) • (p -ᵥ orthogonal_projection s p : V) +ᵥ orthogonal_projection s p, { simp }, split, { split, { refine vadd_mem_of_mem_direction _ (mem_affine_span ℝ (set.mem_insert_of_mem _ hcc)), rw direction_affine_span, exact submodule.smul_mem _ _ (vsub_mem_vector_span ℝ (set.mem_insert _ _) (set.mem_insert_of_mem _ (orthogonal_projection_mem hn hc _))) }, { intros p1 hp1, rw [←mul_self_inj_of_nonneg dist_nonneg (real.sqrt_nonneg _), real.mul_self_sqrt (add_nonneg (mul_self_nonneg _) (mul_self_nonneg _))], cases hp1, { rw hp1, rw [hpo, dist_square_smul_orthogonal_vadd_smul_orthogonal_vadd (orthogonal_projection_mem hn hc p) hcc _ _ (vsub_orthogonal_projection_mem_direction_orthogonal s p), ←dist_eq_norm_vsub V p, dist_comm _ cc], field_simp [hy0], ring }, { rw [dist_square_eq_dist_orthogonal_projection_square_add_dist_orthogonal_projection_square _ (hps hp1), orthogonal_projection_vadd_smul_vsub_orthogonal_projection hc _ _ hcc, hcr p1 hp1, dist_eq_norm_vsub V cc₂ cc, vadd_vsub, norm_smul, ←dist_eq_norm_vsub V, real.norm_eq_abs, abs_div, abs_of_nonneg dist_nonneg, div_mul_cancel _ hy0, abs_mul_abs_self] } } }, { rintros ⟨cc₃, cr₃⟩ ⟨hcc₃, hcr₃⟩, simp only [prod.fst, prod.snd] at hcc₃ hcr₃, rw mem_affine_span_insert_iff (orthogonal_projection_mem hn hc p) at hcc₃, rcases hcc₃ with ⟨t₃, cc₃', hcc₃', hcc₃⟩, have hcr₃' : ∃ r, ∀ p1 ∈ ps, dist p1 cc₃ = r := ⟨cr₃, λ p1 hp1, hcr₃ p1 (set.mem_insert_of_mem _ hp1)⟩, rw [exists_dist_eq_iff_exists_dist_orthogonal_projection_eq hps cc₃, hcc₃, orthogonal_projection_vadd_smul_vsub_orthogonal_projection hc _ _ hcc₃'] at hcr₃', cases hcr₃' with cr₃' hcr₃', have hu := hcccru (cc₃', cr₃'), simp only [prod.fst, prod.snd] at hu, replace hu := hu ⟨hcc₃', hcr₃'⟩, rw prod.ext_iff at hu, simp only [prod.fst, prod.snd] at hu, cases hu with hucc hucr, substs hucc hucr, have hcr₃val : cr₃ = real.sqrt (cr₃' * cr₃' + (t₃ * y) * (t₃ * y)), { cases hnps with p0 hp0, rw [←hcr₃ p0 (set.mem_insert_of_mem _ hp0), hcc₃, ←mul_self_inj_of_nonneg dist_nonneg (real.sqrt_nonneg _), real.mul_self_sqrt (add_nonneg (mul_self_nonneg _) (mul_self_nonneg _)), dist_square_eq_dist_orthogonal_projection_square_add_dist_orthogonal_projection_square _ (hps hp0), orthogonal_projection_vadd_smul_vsub_orthogonal_projection hc _ _ hcc₃', hcr p0 hp0, dist_eq_norm_vsub V _ cc₃', vadd_vsub, norm_smul, ←dist_eq_norm_vsub V p, real.norm_eq_abs, ←mul_assoc, mul_comm _ (abs t₃), ←mul_assoc, abs_mul_abs_self], ring }, replace hcr₃ := hcr₃ p (set.mem_insert _ _), rw [hpo, hcc₃, hcr₃val, ←mul_self_inj_of_nonneg dist_nonneg (real.sqrt_nonneg _), dist_square_smul_orthogonal_vadd_smul_orthogonal_vadd (orthogonal_projection_mem hn hc p) hcc₃' _ _ (vsub_orthogonal_projection_mem_direction_orthogonal s p), dist_comm, ←dist_eq_norm_vsub V p, real.mul_self_sqrt (add_nonneg (mul_self_nonneg _) (mul_self_nonneg _))] at hcr₃, change x * x + _ * (y * y) = _ at hcr₃, rw [(show x * x + (1 - t₃) * (1 - t₃) * (y * y) = x * x + y * y - 2 * y * (t₃ * y) + t₃ * y * (t₃ * y), by ring), add_left_inj] at hcr₃, have ht₃ : t₃ = ycc₂ / y, { field_simp [←hcr₃, hy0], ring }, subst ht₃, change cc₃ = cc₂ at hcc₃, congr', rw hcr₃val, congr' 2, field_simp [hy0], ring } end /-- Given a finite nonempty affinely independent family of points, there is a unique (circumcenter, circumradius) pair for those points in the affine subspace they span. -/ lemma exists_unique_dist_eq_of_affine_independent {ι : Type*} [hne : nonempty ι] [fintype ι] {p : ι → P} (ha : affine_independent ℝ p) : ∃! cccr : (P × ℝ), cccr.fst ∈ affine_span ℝ (set.range p) ∧ ∀ i, dist (p i) cccr.fst = cccr.snd := begin generalize' hn : fintype.card ι = n, unfreezingI { induction n with m hm generalizing ι }, { exfalso, have h := fintype.card_pos_iff.2 hne, rw hn at h, exact lt_irrefl 0 h }, { cases m, { rw fintype.card_eq_one_iff at hn, cases hn with i hi, haveI : unique ι := ⟨⟨i⟩, hi⟩, use (p i, 0), simp only [prod.fst, prod.snd, set.range_unique, affine_subspace.mem_affine_span_singleton], split, { simp_rw [hi (default ι)], use rfl, intro i1, rw hi i1, exact dist_self _ }, { rintros ⟨cc, cr⟩, simp only [prod.fst, prod.snd], rintros ⟨rfl, hdist⟩, rw hi (default ι), congr', rw ←hdist (default ι), exact dist_self _ } }, { have i := hne.some, let ι2 := {x // x ≠ i}, have hc : fintype.card ι2 = m + 1, { rw fintype.card_of_subtype (finset.univ.filter (λ x, x ≠ i)), { rw finset.filter_not, simp_rw eq_comm, rw [finset.filter_eq, if_pos (finset.mem_univ _), finset.card_sdiff (finset.subset_univ _), finset.card_singleton, finset.card_univ, hn], simp }, { simp } }, haveI : nonempty ι2 := fintype.card_pos_iff.1 (hc.symm ▸ nat.zero_lt_succ _), have ha2 : affine_independent ℝ (λ i2 : ι2, p i2) := affine_independent_subtype_of_affine_independent ha _, replace hm := hm ha2 hc, have hr : set.range p = insert (p i) (set.range (λ i2 : ι2, p i2)), { change _ = insert _ (set.range (λ i2 : {x | x ≠ i}, p i2)), rw [←set.image_eq_range, ←set.image_univ, ←set.image_insert_eq], congr' with j, simp [classical.em] }, change ∃! (cccr : P × ℝ), (_ ∧ ∀ i2, (λ q, dist q cccr.fst = cccr.snd) (p i2)), conv { congr, funext, conv { congr, skip, rw ←set.forall_range_iff } }, dsimp only, rw hr, change ∃! (cccr : P × ℝ), (_ ∧ ∀ (i2 : ι2), (λ q, dist q cccr.fst = cccr.snd) (p i2)) at hm, conv at hm { congr, funext, conv { congr, skip, rw ←set.forall_range_iff } }, rw ←affine_span_insert_affine_span, refine exists_unique_dist_eq_of_insert (submodule.complete_of_finite_dimensional _) (set.range_nonempty _) (subset_span_points ℝ _) _ hm, convert not_mem_affine_span_diff_of_affine_independent ha i set.univ, change set.range (λ i2 : {x | x ≠ i}, p i2) = _, rw ←set.image_eq_range, congr' with j, simp, refl } } end end euclidean_geometry namespace affine namespace simplex open finset affine_subspace euclidean_geometry variables {V : Type*} {P : Type*} [inner_product_space V] [metric_space P] [normed_add_torsor V P] include V /-- The pair (circumcenter, circumradius) of a simplex. -/ def circumcenter_circumradius {n : ℕ} (s : simplex ℝ P n) : (P × ℝ) := (exists_unique_dist_eq_of_affine_independent s.independent).some /-- The property satisfied by the (circumcenter, circumradius) pair. -/ lemma circumcenter_circumradius_unique_dist_eq {n : ℕ} (s : simplex ℝ P n) : (s.circumcenter_circumradius.fst ∈ affine_span ℝ (set.range s.points) ∧ ∀ i, dist (s.points i) s.circumcenter_circumradius.fst = s.circumcenter_circumradius.snd) ∧ (∀ cccr : (P × ℝ), (cccr.fst ∈ affine_span ℝ (set.range s.points) ∧ ∀ i, dist (s.points i) cccr.fst = cccr.snd) → cccr = s.circumcenter_circumradius) := (exists_unique_dist_eq_of_affine_independent s.independent).some_spec /-- The circumcenter of a simplex. -/ def circumcenter {n : ℕ} (s : simplex ℝ P n) : P := s.circumcenter_circumradius.fst /-- The circumradius of a simplex. -/ def circumradius {n : ℕ} (s : simplex ℝ P n) : ℝ := s.circumcenter_circumradius.snd /-- The circumcenter lies in the affine span. -/ lemma circumcenter_mem_affine_span {n : ℕ} (s : simplex ℝ P n) : s.circumcenter ∈ affine_span ℝ (set.range s.points) := s.circumcenter_circumradius_unique_dist_eq.1.1 /-- All points have distance from the circumcenter equal to the circumradius. -/ @[simp] lemma dist_circumcenter_eq_circumradius {n : ℕ} (s : simplex ℝ P n) : ∀ i, dist (s.points i) s.circumcenter = s.circumradius := s.circumcenter_circumradius_unique_dist_eq.1.2 /-- All points have distance to the circumcenter equal to the circumradius. -/ @[simp] lemma dist_circumcenter_eq_circumradius' {n : ℕ} (s : simplex ℝ P n) : ∀ i, dist s.circumcenter (s.points i) = s.circumradius := begin intro i, rw dist_comm, exact dist_circumcenter_eq_circumradius _ _ end /-- Given a point in the affine span from which all the points are equidistant, that point is the circumcenter. -/ lemma eq_circumcenter_of_dist_eq {n : ℕ} (s : simplex ℝ P n) {p : P} (hp : p ∈ affine_span ℝ (set.range s.points)) {r : ℝ} (hr : ∀ i, dist (s.points i) p = r) : p = s.circumcenter := begin have h := s.circumcenter_circumradius_unique_dist_eq.2 (p, r), simp only [hp, hr, forall_const, eq_self_iff_true, and_self, prod.ext_iff] at h, exact h.1 end /-- Given a point in the affine span from which all the points are equidistant, that distance is the circumradius. -/ lemma eq_circumradius_of_dist_eq {n : ℕ} (s : simplex ℝ P n) {p : P} (hp : p ∈ affine_span ℝ (set.range s.points)) {r : ℝ} (hr : ∀ i, dist (s.points i) p = r) : r = s.circumradius := begin have h := s.circumcenter_circumradius_unique_dist_eq.2 (p, r), simp only [hp, hr, forall_const, eq_self_iff_true, and_self, prod.ext_iff] at h, exact h.2 end /-- The circumradius is non-negative. -/ lemma circumradius_nonneg {n : ℕ} (s : simplex ℝ P n) : 0 ≤ s.circumradius := s.dist_circumcenter_eq_circumradius 0 ▸ dist_nonneg /-- The circumradius of a simplex with at least two points is positive. -/ lemma circumradius_pos {n : ℕ} (s : simplex ℝ P (n + 1)) : 0 < s.circumradius := begin refine lt_of_le_of_ne s.circumradius_nonneg _, intro h, have hr := s.dist_circumcenter_eq_circumradius, simp_rw [←h, dist_eq_zero] at hr, have h01 := (injective_of_affine_independent s.independent).ne (dec_trivial : (0 : fin (n + 2)) ≠ 1), simpa [hr] using h01 end /-- The circumcenter of a 0-simplex equals its unique point. -/ lemma circumcenter_eq_point (s : simplex ℝ P 0) (i : fin 1) : s.circumcenter = s.points i := begin have h := s.circumcenter_mem_affine_span, rw [set.range_unique, mem_affine_span_singleton] at h, rw h, congr end /-- The circumcenter of a 1-simplex equals its centroid. -/ lemma circumcenter_eq_centroid (s : simplex ℝ P 1) : s.circumcenter = finset.univ.centroid ℝ s.points := begin have hr : set.pairwise_on set.univ (λ i j : fin 2, dist (s.points i) (finset.univ.centroid ℝ s.points) = dist (s.points j) (finset.univ.centroid ℝ s.points)), { intros i hi j hj hij, rw [finset.centroid_insert_singleton_fin, dist_eq_norm_vsub V (s.points i), dist_eq_norm_vsub V (s.points j), vsub_vadd_eq_vsub_sub, vsub_vadd_eq_vsub_sub, ←one_smul ℝ (s.points i -ᵥ s.points 0), ←one_smul ℝ (s.points j -ᵥ s.points 0)], fin_cases i; fin_cases j; simp [-one_smul, ←sub_smul]; norm_num }, rw set.pairwise_on_eq_iff_exists_eq at hr, cases hr with r hr, exact (s.eq_circumcenter_of_dist_eq (centroid_mem_affine_span_of_card_eq_add_one ℝ _ (finset.card_fin 2)) (λ i, hr i (set.mem_univ _))).symm end /-- If there exists a distance that a point has from all vertices of a simplex, the orthogonal projection of that point onto the subspace spanned by that simplex is its circumcenter. -/ lemma orthogonal_projection_eq_circumcenter_of_exists_dist_eq {n : ℕ} (s : simplex ℝ P n) {p : P} (hr : ∃ r, ∀ i, dist (s.points i) p = r) : orthogonal_projection (affine_span ℝ (set.range s.points)) p = s.circumcenter := begin change ∃ r : ℝ, ∀ i, (λ x, dist x p = r) (s.points i) at hr, conv at hr { congr, funext, rw ←set.forall_range_iff }, rw exists_dist_eq_iff_exists_dist_orthogonal_projection_eq (subset_affine_span ℝ _) p at hr, cases hr with r hr, rw set.forall_range_iff at hr, exact s.eq_circumcenter_of_dist_eq (orthogonal_projection_mem ((affine_span_nonempty ℝ _).2 (set.range_nonempty _)) (submodule.complete_of_finite_dimensional _) p) hr end /-- If a point has the same distance from all vertices of a simplex, the orthogonal projection of that point onto the subspace spanned by that simplex is its circumcenter. -/ lemma orthogonal_projection_eq_circumcenter_of_dist_eq {n : ℕ} (s : simplex ℝ P n) {p : P} {r : ℝ} (hr : ∀ i, dist (s.points i) p = r) : orthogonal_projection (affine_span ℝ (set.range s.points)) p = s.circumcenter := s.orthogonal_projection_eq_circumcenter_of_exists_dist_eq ⟨r, hr⟩ /-- The orthogonal projection of the circumcenter onto a face is the circumcenter of that face. -/ lemma orthogonal_projection_circumcenter {n : ℕ} (s : simplex ℝ P n) {fs : finset (fin (n + 1))} {m : ℕ} (h : fs.card = m + 1) : orthogonal_projection (affine_span ℝ (s.points '' ↑fs)) s.circumcenter = (s.face h).circumcenter := begin have hr : ∃ r, ∀ i, dist ((s.face h).points i) s.circumcenter = r, { use s.circumradius, simp [face_points] }, rw [←range_face_points, orthogonal_projection_eq_circumcenter_of_exists_dist_eq _ hr] end /-- Two simplices with the same points have the same circumcenter. -/ lemma circumcenter_eq_of_range_eq {n : ℕ} {s₁ s₂ : simplex ℝ P n} (h : set.range s₁.points = set.range s₂.points) : s₁.circumcenter = s₂.circumcenter := begin have hs : s₁.circumcenter ∈ affine_span ℝ (set.range s₂.points) := h ▸ s₁.circumcenter_mem_affine_span, have hr : ∀ i, dist (s₂.points i) s₁.circumcenter = s₁.circumradius, { intro i, have hi : s₂.points i ∈ set.range s₂.points := set.mem_range_self _, rw [←h, set.mem_range] at hi, rcases hi with ⟨j, hj⟩, rw [←hj, s₁.dist_circumcenter_eq_circumradius j] }, exact s₂.eq_circumcenter_of_dist_eq hs hr end omit V /-- An index type for the vertices of a simplex plus its circumcenter. This is for use in calculations where it is convenient to work with affine combinations of vertices together with the circumcenter. (An equivalent form sometimes used in the literature is placing the circumcenter at the origin and working with vectors for the vertices.) -/ @[derive fintype] inductive points_with_circumcenter_index (n : ℕ) | point_index : fin (n + 1) → points_with_circumcenter_index | circumcenter_index : points_with_circumcenter_index open points_with_circumcenter_index instance points_with_circumcenter_index_inhabited (n : ℕ) : inhabited (points_with_circumcenter_index n) := ⟨circumcenter_index⟩ /-- `point_index` as an embedding. -/ def point_index_embedding (n : ℕ) : fin (n + 1) ↪ points_with_circumcenter_index n := ⟨λ i, point_index i, λ _ _ h, by injection h⟩ /-- The sum of a function over `points_with_circumcenter_index`. -/ lemma sum_points_with_circumcenter {α : Type*} [add_comm_monoid α] {n : ℕ} (f : points_with_circumcenter_index n → α) : ∑ i, f i = (∑ (i : fin (n + 1)), f (point_index i)) + f circumcenter_index := begin have h : univ = insert circumcenter_index (univ.map (point_index_embedding n)), { ext x, refine ⟨λ h, _, λ _, mem_univ _⟩, cases x with i, { exact mem_insert_of_mem (mem_map_of_mem _ (mem_univ i)) }, { exact mem_insert_self _ _ } }, change _ = ∑ i, f (point_index_embedding n i) + _, rw [add_comm, h, ←sum_map, sum_insert], simp_rw [mem_map, not_exists], intros x hx h, injection h end include V /-- The vertices of a simplex plus its circumcenter. -/ def points_with_circumcenter {n : ℕ} (s : simplex ℝ P n) : points_with_circumcenter_index n → P | (point_index i) := s.points i | circumcenter_index := s.circumcenter /-- `points_with_circumcenter`, applied to a `point_index` value, equals `points` applied to that value. -/ @[simp] lemma points_with_circumcenter_point {n : ℕ} (s : simplex ℝ P n) (i : fin (n + 1)) : s.points_with_circumcenter (point_index i) = s.points i := rfl /-- `points_with_circumcenter`, applied to `circumcenter_index`, equals the circumcenter. -/ @[simp] lemma points_with_circumcenter_eq_circumcenter {n : ℕ} (s : simplex ℝ P n) : s.points_with_circumcenter circumcenter_index = s.circumcenter := rfl omit V /-- The weights for a single vertex of a simplex, in terms of `points_with_circumcenter`. -/ def point_weights_with_circumcenter {n : ℕ} (i : fin (n + 1)) : points_with_circumcenter_index n → ℝ | (point_index j) := if j = i then 1 else 0 | circumcenter_index := 0 /-- `point_weights_with_circumcenter` sums to 1. -/ @[simp] lemma sum_point_weights_with_circumcenter {n : ℕ} (i : fin (n + 1)) : ∑ j, point_weights_with_circumcenter i j = 1 := begin convert sum_ite_eq' univ (point_index i) (function.const _ (1 : ℝ)), { ext j, cases j ; simp [point_weights_with_circumcenter] }, { simp } end include V /-- A single vertex, in terms of `points_with_circumcenter`. -/ lemma point_eq_affine_combination_of_points_with_circumcenter {n : ℕ} (s : simplex ℝ P n) (i : fin (n + 1)) : s.points i = (univ : finset (points_with_circumcenter_index n)).affine_combination s.points_with_circumcenter (point_weights_with_circumcenter i) := begin rw ←points_with_circumcenter_point, symmetry, refine affine_combination_of_eq_one_of_eq_zero _ _ _ (mem_univ _) (by simp [point_weights_with_circumcenter]) _, intros i hi hn, cases i, { have h : i_1 ≠ i := λ h, hn (h ▸ rfl), simp [point_weights_with_circumcenter, h] }, { refl } end omit V /-- The weights for the centroid of some vertices of a simplex, in terms of `points_with_circumcenter`. -/ def centroid_weights_with_circumcenter {n : ℕ} (fs : finset (fin (n + 1))) : points_with_circumcenter_index n → ℝ | (point_index i) := if i ∈ fs then ((card fs : ℝ) ⁻¹) else 0 | circumcenter_index := 0 /-- `centroid_weights_with_circumcenter` sums to 1, if the `finset` is nonempty. -/ @[simp] lemma sum_centroid_weights_with_circumcenter {n : ℕ} {fs : finset (fin (n + 1))} (h : fs.nonempty) : ∑ i, centroid_weights_with_circumcenter fs i = 1 := begin simp_rw [sum_points_with_circumcenter, centroid_weights_with_circumcenter, add_zero, ←fs.sum_centroid_weights_eq_one_of_nonempty ℝ h, set.sum_indicator_subset _ fs.subset_univ], rcongr end include V /-- The centroid of some vertices of a simplex, in terms of `points_with_circumcenter`. -/ lemma centroid_eq_affine_combination_of_points_with_circumcenter {n : ℕ} (s : simplex ℝ P n) (fs : finset (fin (n + 1))) : fs.centroid ℝ s.points = (univ : finset (points_with_circumcenter_index n)).affine_combination s.points_with_circumcenter (centroid_weights_with_circumcenter fs) := begin simp_rw [centroid_def, affine_combination_apply, weighted_vsub_of_point_apply, sum_points_with_circumcenter, centroid_weights_with_circumcenter, points_with_circumcenter_point, zero_smul, add_zero, centroid_weights, set.sum_indicator_subset_of_eq_zero (function.const (fin (n + 1)) ((card fs : ℝ)⁻¹)) (λ i wi, wi • (s.points i -ᵥ classical.choice add_torsor.nonempty)) fs.subset_univ (λ i, zero_smul ℝ _), set.indicator_apply], rcongr end omit V /-- The weights for the circumcenter of a simplex, in terms of `points_with_circumcenter`. -/ def circumcenter_weights_with_circumcenter (n : ℕ) : points_with_circumcenter_index n → ℝ | (point_index i) := 0 | circumcenter_index := 1 /-- `circumcenter_weights_with_circumcenter` sums to 1. -/ @[simp] lemma sum_circumcenter_weights_with_circumcenter (n : ℕ) : ∑ i, circumcenter_weights_with_circumcenter n i = 1 := begin convert sum_ite_eq' univ circumcenter_index (function.const _ (1 : ℝ)), { ext ⟨j⟩ ; simp [circumcenter_weights_with_circumcenter] }, { simp }, { exact classical.dec_eq _ } end include V /-- The circumcenter of a simplex, in terms of `points_with_circumcenter`. -/ lemma circumcenter_eq_affine_combination_of_points_with_circumcenter {n : ℕ} (s : simplex ℝ P n) : s.circumcenter = (univ : finset (points_with_circumcenter_index n)).affine_combination s.points_with_circumcenter (circumcenter_weights_with_circumcenter n) := begin rw ←points_with_circumcenter_eq_circumcenter, symmetry, refine affine_combination_of_eq_one_of_eq_zero _ _ _ (mem_univ _) rfl _, rintros ⟨i⟩ hi hn ; tauto end omit V /-- The weights for the reflection of the circumcenter in an edge of a simplex. This definition is only valid with `i₁ ≠ i₂`. -/ def reflection_circumcenter_weights_with_circumcenter {n : ℕ} (i₁ i₂ : fin (n + 1)) : points_with_circumcenter_index n → ℝ | (point_index i) := if i = i₁ ∨ i = i₂ then 1 else 0 | circumcenter_index := -1 /-- `reflection_circumcenter_weights_with_circumcenter` sums to 1. -/ @[simp] lemma sum_reflection_circumcenter_weights_with_circumcenter {n : ℕ} {i₁ i₂ : fin (n + 1)} (h : i₁ ≠ i₂) : ∑ i, reflection_circumcenter_weights_with_circumcenter i₁ i₂ i = 1 := begin simp_rw [sum_points_with_circumcenter, reflection_circumcenter_weights_with_circumcenter, sum_ite, sum_const, filter_or, filter_eq'], rw card_union_eq, { simp }, { simp [h.symm] } end include V /-- The reflection of the circumcenter of a simplex in an edge, in terms of `points_with_circumcenter`. -/ lemma reflection_circumcenter_eq_affine_combination_of_points_with_circumcenter {n : ℕ} (s : simplex ℝ P n) {i₁ i₂ : fin (n + 1)} (h : i₁ ≠ i₂) : reflection (affine_span ℝ (s.points '' {i₁, i₂})) s.circumcenter = (univ : finset (points_with_circumcenter_index n)).affine_combination s.points_with_circumcenter (reflection_circumcenter_weights_with_circumcenter i₁ i₂) := begin have hc : card ({i₁, i₂} : finset (fin (n + 1))) = 2, { simp [h] }, rw [reflection_apply, ←coe_singleton, ←coe_insert, s.orthogonal_projection_circumcenter hc, circumcenter_eq_centroid, s.face_centroid_eq_centroid hc, centroid_eq_affine_combination_of_points_with_circumcenter, circumcenter_eq_affine_combination_of_points_with_circumcenter, ←@vsub_eq_zero_iff_eq V, affine_combination_vsub, weighted_vsub_vadd_affine_combination, affine_combination_vsub, weighted_vsub_apply, sum_points_with_circumcenter], simp_rw [pi.sub_apply, pi.add_apply, pi.sub_apply, sub_smul, add_smul, sub_smul, centroid_weights_with_circumcenter, circumcenter_weights_with_circumcenter, reflection_circumcenter_weights_with_circumcenter, ite_smul, zero_smul, sub_zero, apply_ite2 (+), add_zero, ←add_smul, hc, zero_sub, neg_smul, sub_self, add_zero], convert sum_const_zero, norm_num end end simplex end affine namespace euclidean_geometry open affine affine_subspace finite_dimensional variables {V : Type*} {P : Type*} [inner_product_space V] [metric_space P] [normed_add_torsor V P] include V /-- Given a nonempty affine subspace, whose direction is complete, that contains a set of points, those points are cospherical if and only if they are equidistant from some point in that subspace. -/ lemma cospherical_iff_exists_mem_of_complete {s : affine_subspace ℝ P} {ps : set P} (h : ps ⊆ s) (hn : (s : set P).nonempty) (hc : is_complete (s.direction : set V)) : cospherical ps ↔ ∃ (center ∈ s) (radius : ℝ), ∀ p ∈ ps, dist p center = radius := begin split, { rintro ⟨c, hcr⟩, rw exists_dist_eq_iff_exists_dist_orthogonal_projection_eq h c at hcr, exact ⟨orthogonal_projection s c, orthogonal_projection_mem hn hc _, hcr⟩ }, { exact λ ⟨c, hc, hd⟩, ⟨c, hd⟩ } end /-- Given a nonempty affine subspace, whose direction is finite-dimensional, that contains a set of points, those points are cospherical if and only if they are equidistant from some point in that subspace. -/ lemma cospherical_iff_exists_mem_of_finite_dimensional {s : affine_subspace ℝ P} {ps : set P} (h : ps ⊆ s) (hn : (s : set P).nonempty) [finite_dimensional ℝ s.direction] : cospherical ps ↔ ∃ (center ∈ s) (radius : ℝ), ∀ p ∈ ps, dist p center = radius := cospherical_iff_exists_mem_of_complete h hn (submodule.complete_of_finite_dimensional _) /-- All n-simplices among cospherical points in an n-dimensional subspace have the same circumradius. -/ lemma exists_circumradius_eq_of_cospherical_subset {s : affine_subspace ℝ P} {ps : set P} (h : ps ⊆ s) (hn : (s : set P).nonempty) {n : ℕ} [finite_dimensional ℝ s.direction] (hd : findim ℝ s.direction = n) (hc : cospherical ps) : ∃ r : ℝ, ∀ sx : simplex ℝ P n, set.range sx.points ⊆ ps → sx.circumradius = r := begin rw cospherical_iff_exists_mem_of_finite_dimensional h hn at hc, rcases hc with ⟨c, hc, r, hcr⟩, use r, intros sx hsxps, have hsx : affine_span ℝ (set.range sx.points) = s, { refine affine_span_eq_of_le_of_affine_independent_of_card_eq_findim_add_one sx.independent (span_points_subset_coe_of_subset_coe (set.subset.trans hsxps h)) _, simp [hd] }, have hc : c ∈ affine_span ℝ (set.range sx.points) := hsx.symm ▸ hc, exact (sx.eq_circumradius_of_dist_eq hc (λ i, hcr (sx.points i) (hsxps (set.mem_range_self i)))).symm end /-- Two n-simplices among cospherical points in an n-dimensional subspace have the same circumradius. -/ lemma circumradius_eq_of_cospherical_subset {s : affine_subspace ℝ P} {ps : set P} (h : ps ⊆ s) (hn : (s : set P).nonempty) {n : ℕ} [finite_dimensional ℝ s.direction] (hd : findim ℝ s.direction = n) (hc : cospherical ps) {sx₁ sx₂ : simplex ℝ P n} (hsx₁ : set.range sx₁.points ⊆ ps) (hsx₂ : set.range sx₂.points ⊆ ps) : sx₁.circumradius = sx₂.circumradius := begin rcases exists_circumradius_eq_of_cospherical_subset h hn hd hc with ⟨r, hr⟩, rw [hr sx₁ hsx₁, hr sx₂ hsx₂] end /-- All n-simplices among cospherical points in n-space have the same circumradius. -/ lemma exists_circumradius_eq_of_cospherical {ps : set P} {n : ℕ} [finite_dimensional ℝ V] (hd : findim ℝ V = n) (hc : cospherical ps) : ∃ r : ℝ, ∀ sx : simplex ℝ P n, set.range sx.points ⊆ ps → sx.circumradius = r := begin rw [←findim_top, ←direction_top ℝ V P] at hd, refine exists_circumradius_eq_of_cospherical_subset _ ⟨add_torsor.nonempty.some, mem_top _ _ _⟩ hd hc, exact set.subset_univ _ end /-- Two n-simplices among cospherical points in n-space have the same circumradius. -/ lemma circumradius_eq_of_cospherical {ps : set P} {n : ℕ} [finite_dimensional ℝ V] (hd : findim ℝ V = n) (hc : cospherical ps) {sx₁ sx₂ : simplex ℝ P n} (hsx₁ : set.range sx₁.points ⊆ ps) (hsx₂ : set.range sx₂.points ⊆ ps) : sx₁.circumradius = sx₂.circumradius := begin rcases exists_circumradius_eq_of_cospherical hd hc with ⟨r, hr⟩, rw [hr sx₁ hsx₁, hr sx₂ hsx₂] end /-- All n-simplices among cospherical points in an n-dimensional subspace have the same circumcenter. -/ lemma exists_circumcenter_eq_of_cospherical_subset {s : affine_subspace ℝ P} {ps : set P} (h : ps ⊆ s) (hn : (s : set P).nonempty) {n : ℕ} [finite_dimensional ℝ s.direction] (hd : findim ℝ s.direction = n) (hc : cospherical ps) : ∃ c : P, ∀ sx : simplex ℝ P n, set.range sx.points ⊆ ps → sx.circumcenter = c := begin rw cospherical_iff_exists_mem_of_finite_dimensional h hn at hc, rcases hc with ⟨c, hc, r, hcr⟩, use c, intros sx hsxps, have hsx : affine_span ℝ (set.range sx.points) = s, { refine affine_span_eq_of_le_of_affine_independent_of_card_eq_findim_add_one sx.independent (span_points_subset_coe_of_subset_coe (set.subset.trans hsxps h)) _, simp [hd] }, have hc : c ∈ affine_span ℝ (set.range sx.points) := hsx.symm ▸ hc, exact (sx.eq_circumcenter_of_dist_eq hc (λ i, hcr (sx.points i) (hsxps (set.mem_range_self i)))).symm end /-- Two n-simplices among cospherical points in an n-dimensional subspace have the same circumcenter. -/ lemma circumcenter_eq_of_cospherical_subset {s : affine_subspace ℝ P} {ps : set P} (h : ps ⊆ s) (hn : (s : set P).nonempty) {n : ℕ} [finite_dimensional ℝ s.direction] (hd : findim ℝ s.direction = n) (hc : cospherical ps) {sx₁ sx₂ : simplex ℝ P n} (hsx₁ : set.range sx₁.points ⊆ ps) (hsx₂ : set.range sx₂.points ⊆ ps) : sx₁.circumcenter = sx₂.circumcenter := begin rcases exists_circumcenter_eq_of_cospherical_subset h hn hd hc with ⟨r, hr⟩, rw [hr sx₁ hsx₁, hr sx₂ hsx₂] end /-- All n-simplices among cospherical points in n-space have the same circumcenter. -/ lemma exists_circumcenter_eq_of_cospherical {ps : set P} {n : ℕ} [finite_dimensional ℝ V] (hd : findim ℝ V = n) (hc : cospherical ps) : ∃ c : P, ∀ sx : simplex ℝ P n, set.range sx.points ⊆ ps → sx.circumcenter = c := begin rw [←findim_top, ←direction_top ℝ V P] at hd, refine exists_circumcenter_eq_of_cospherical_subset _ ⟨add_torsor.nonempty.some, mem_top _ _ _⟩ hd hc, exact set.subset_univ _ end /-- Two n-simplices among cospherical points in n-space have the same circumcenter. -/ lemma circumcenter_eq_of_cospherical {ps : set P} {n : ℕ} [finite_dimensional ℝ V] (hd : findim ℝ V = n) (hc : cospherical ps) {sx₁ sx₂ : simplex ℝ P n} (hsx₁ : set.range sx₁.points ⊆ ps) (hsx₂ : set.range sx₂.points ⊆ ps) : sx₁.circumcenter = sx₂.circumcenter := begin rcases exists_circumcenter_eq_of_cospherical hd hc with ⟨r, hr⟩, rw [hr sx₁ hsx₁, hr sx₂ hsx₂] end /-- Suppose all distances from `p₁` and `p₂` to the points of a simplex are equal, and that `p₁` and `p₂` lie in the affine span of `p` with the vertices of that simplex. Then `p₁` and `p₂` are equal or reflections of each other in the affine span of the vertices of the simplex. -/ lemma eq_or_eq_reflection_of_dist_eq {n : ℕ} {s : simplex ℝ P n} {p p₁ p₂ : P} {r : ℝ} (hp₁ : p₁ ∈ affine_span ℝ (insert p (set.range s.points))) (hp₂ : p₂ ∈ affine_span ℝ (insert p (set.range s.points))) (h₁ : ∀ i, dist (s.points i) p₁ = r) (h₂ : ∀ i, dist (s.points i) p₂ = r) : p₁ = p₂ ∨ p₁ = reflection (affine_span ℝ (set.range s.points)) p₂ := begin let span_s := affine_span ℝ (set.range s.points), have h₁' := s.orthogonal_projection_eq_circumcenter_of_dist_eq h₁, have h₂' := s.orthogonal_projection_eq_circumcenter_of_dist_eq h₂, have hn : (span_s : set P).nonempty := (affine_span_nonempty ℝ _).2 (set.range_nonempty _), have hc : is_complete (span_s.direction : set V) := submodule.complete_of_finite_dimensional _, rw [←affine_span_insert_affine_span, mem_affine_span_insert_iff (orthogonal_projection_mem hn hc p)] at hp₁ hp₂, obtain ⟨r₁, p₁o, hp₁o, hp₁⟩ := hp₁, obtain ⟨r₂, p₂o, hp₂o, hp₂⟩ := hp₂, obtain rfl : orthogonal_projection span_s p₁ = p₁o, { rw hp₁, exact orthogonal_projection_vadd_smul_vsub_orthogonal_projection hc _ _ hp₁o }, rw h₁' at hp₁, obtain rfl : orthogonal_projection span_s p₂ = p₂o, { rw hp₂, exact orthogonal_projection_vadd_smul_vsub_orthogonal_projection hc _ _ hp₂o }, rw h₂' at hp₂, have h : s.points 0 ∈ span_s := mem_affine_span ℝ (set.mem_range_self _), have hd₁ : dist p₁ s.circumcenter * dist p₁ s.circumcenter = r * r - s.circumradius * s.circumradius, { rw [dist_comm, ←h₁ 0, dist_square_eq_dist_orthogonal_projection_square_add_dist_orthogonal_projection_square p₁ h], simp [h₁', dist_comm p₁] }, have hd₂ : dist p₂ s.circumcenter * dist p₂ s.circumcenter = r * r - s.circumradius * s.circumradius, { rw [dist_comm, ←h₂ 0, dist_square_eq_dist_orthogonal_projection_square_add_dist_orthogonal_projection_square p₂ h], simp [h₂', dist_comm p₂] }, rw [←hd₂, hp₁, hp₂, dist_eq_norm_vsub V _ s.circumcenter, dist_eq_norm_vsub V _ s.circumcenter, vadd_vsub, vadd_vsub, ←inner_self_eq_norm_square, ←inner_self_eq_norm_square, inner_smul_left, inner_smul_left, inner_smul_right, inner_smul_right, ←mul_assoc, ←mul_assoc] at hd₁, by_cases hp : p = orthogonal_projection span_s p, { rw [hp₁, hp₂, ←hp], simp }, { have hz : inner (p -ᵥ orthogonal_projection span_s p) (p -ᵥ orthogonal_projection span_s p) ≠ 0, { simpa using hp }, rw [mul_left_inj' hz, mul_self_eq_mul_self_iff] at hd₁, rw [hp₁, hp₂], cases hd₁, { left, rw hd₁ }, { right, rw [hd₁, reflection_vadd_smul_vsub_orthogonal_projection hc p r₂ s.circumcenter_mem_affine_span, neg_smul] } } end end euclidean_geometry
d824fdef81d0b854c913201701ed7d16baf3110f
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/blast_ematch6.lean
d9bddeaee976125c89f6bf1ca208473e406c0481
[ "Apache-2.0" ]
permissive
soonhokong/lean
cb8aa01055ffe2af0fb99a16b4cda8463b882cd1
38607e3eb57f57f77c0ac114ad169e9e4262e24f
refs/heads/master
1,611,187,284,081
1,450,766,737,000
1,476,122,547,000
11,513,992
2
0
null
1,401,763,102,000
1,374,182,235,000
C++
UTF-8
Lean
false
false
861
lean
import algebra.ring data.nat open algebra variables {A : Type} section variable [s : group A] include s set_option blast.strategy "ematch" attribute mul_one [forward] attribute mul.assoc [forward] attribute mul.left_inv [forward] attribute one_mul [forward] theorem inv_eq_of_mul_eq_one₁ {a b : A} (H : a * b = 1) : a⁻¹ = b := -- This is the kind of theorem that can be easily proved using superposition, -- but cannot to be proved using E-matching. -- To prove it using E-matching, we must provide the following auxiliary assertion. -- E-matching can prove it automatically, and then it is trivial to prove the conclusion -- using it. -- Remark: this theorem can also be proved using model-based quantifier instantiation (MBQI) available in Z3. -- So, we may be able to prove it using qcf. assert a⁻¹ * 1 = b, by blast, by blast end
89d9fe6bdafd75f59dc45d7bbf1f6f1cecd288c2
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/ring_theory/valuation/basic.lean
69a1209df46a9f266d6f190e206649252978a32b
[ "Apache-2.0" ]
permissive
hikari0108/mathlib
b7ea2b7350497ab1a0b87a09d093ecc025a50dfa
a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901
refs/heads/master
1,690,483,608,260
1,631,541,580,000
1,631,541,580,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
24,540
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard, Johan Commelin, Patrick Massot -/ import algebra.linear_ordered_comm_group_with_zero import algebra.group_power import ring_theory.ideal.operations import algebra.punit_instances /-! # The basics of valuation theory. The basic theory of valuations (non-archimedean norms) on a commutative ring, following T. Wedhorn's unpublished notes “Adic Spaces” ([wedhorn_adic]). The definition of a valuation we use here is Definition 1.22 of [wedhorn_adic]. A valuation on a ring `R` is a monoid homomorphism `v` to a linearly ordered commutative monoid with zero, that in addition satisfies the following two axioms: * `v 0 = 0` * `∀ x y, v (x + y) ≤ max (v x) (v y)` `valuation R Γ₀`is the type of valuations `R → Γ₀`, with a coercion to the underlying function. If `v` is a valuation from `R` to `Γ₀` then the induced group homomorphism `units(R) → Γ₀` is called `unit_map v`. The equivalence "relation" `is_equiv v₁ v₂ : Prop` defined in 1.27 of [wedhorn_adic] is not strictly speaking a relation, because `v₁ : valuation R Γ₁` and `v₂ : valuation R Γ₂` might not have the same type. This corresponds in ZFC to the set-theoretic difficulty that the class of all valuations (as `Γ₀` varies) on a ring `R` is not a set. The "relation" is however reflexive, symmetric and transitive in the obvious sense. Note that we use 1.27(iii) of [wedhorn_adic] as the definition of equivalence. The support of a valuation `v : valuation R Γ₀` is `supp v`. If `J` is an ideal of `R` with `h : J ⊆ supp v` then the induced valuation on R / J = `ideal.quotient J` is `on_quot v h`. ## Main definitions * `valuation R Γ₀`, the type of valuations on `R` with values in `Γ₀` * `valuation.is_equiv`, the heterogeneous equivalence relation on valuations * `valuation.supp`, the support of a valuation * `add_valuation R Γ₀`, the type of additive valuations on `R` with values in a linearly ordered additive commutative group with a top element, `Γ₀`. ## Implementation Details `add_valuation R Γ₀` is implemented as `valuation R (multiplicative (order_dual Γ₀))`. -/ open_locale classical big_operators noncomputable theory open function ideal variables {R : Type*} -- This will be a ring, assumed commutative in some sections set_option old_structure_cmd true section variables (R) (Γ₀ : Type*) [linear_ordered_comm_monoid_with_zero Γ₀] [ring R] /-- The type of `Γ₀`-valued valuations on `R`. -/ @[nolint has_inhabited_instance] structure valuation extends monoid_with_zero_hom R Γ₀ := (map_add' : ∀ x y, to_fun (x + y) ≤ max (to_fun x) (to_fun y)) /-- The `monoid_with_zero_hom` underlying a valuation. -/ add_decl_doc valuation.to_monoid_with_zero_hom end namespace valuation variables {Γ₀ : Type*} variables {Γ'₀ : Type*} variables {Γ''₀ : Type*} [linear_ordered_comm_monoid_with_zero Γ''₀] section basic variables (R) (Γ₀) [ring R] section monoid variables [linear_ordered_comm_monoid_with_zero Γ₀] [linear_ordered_comm_monoid_with_zero Γ'₀] /-- A valuation is coerced to the underlying function `R → Γ₀`. -/ instance : has_coe_to_fun (valuation R Γ₀) := { F := λ _, R → Γ₀, coe := valuation.to_fun } /-- A valuation is coerced to a monoid morphism R → Γ₀. -/ instance : has_coe (valuation R Γ₀) (monoid_with_zero_hom R Γ₀) := ⟨valuation.to_monoid_with_zero_hom⟩ variables {R} {Γ₀} (v : valuation R Γ₀) {x y z : R} @[simp, norm_cast] lemma coe_coe : ((v : monoid_with_zero_hom R Γ₀) : R → Γ₀) = v := rfl @[simp] lemma map_zero : v 0 = 0 := v.map_zero' @[simp] lemma map_one : v 1 = 1 := v.map_one' @[simp] lemma map_mul : ∀ x y, v (x * y) = v x * v y := v.map_mul' @[simp] lemma map_add : ∀ x y, v (x + y) ≤ max (v x) (v y) := v.map_add' lemma map_add_le {x y g} (hx : v x ≤ g) (hy : v y ≤ g) : v (x + y) ≤ g := le_trans (v.map_add x y) $ max_le hx hy lemma map_add_lt {x y g} (hx : v x < g) (hy : v y < g) : v (x + y) < g := lt_of_le_of_lt (v.map_add x y) $ max_lt hx hy lemma map_sum_le {ι : Type*} {s : finset ι} {f : ι → R} {g : Γ₀} (hf : ∀ i ∈ s, v (f i) ≤ g) : v (∑ i in s, f i) ≤ g := begin refine finset.induction_on s (λ _, trans_rel_right (≤) v.map_zero zero_le') (λ a s has ih hf, _) hf, rw finset.forall_mem_insert at hf, rw finset.sum_insert has, exact v.map_add_le hf.1 (ih hf.2) end lemma map_sum_lt {ι : Type*} {s : finset ι} {f : ι → R} {g : Γ₀} (hg : g ≠ 0) (hf : ∀ i ∈ s, v (f i) < g) : v (∑ i in s, f i) < g := begin refine finset.induction_on s (λ _, trans_rel_right (<) v.map_zero (zero_lt_iff.2 hg)) (λ a s has ih hf, _) hf, rw finset.forall_mem_insert at hf, rw finset.sum_insert has, exact v.map_add_lt hf.1 (ih hf.2) end lemma map_sum_lt' {ι : Type*} {s : finset ι} {f : ι → R} {g : Γ₀} (hg : 0 < g) (hf : ∀ i ∈ s, v (f i) < g) : v (∑ i in s, f i) < g := v.map_sum_lt (ne_of_gt hg) hf @[simp] lemma map_pow : ∀ x (n:ℕ), v (x^n) = (v x)^n := v.to_monoid_with_zero_hom.to_monoid_hom.map_pow @[ext] lemma ext {v₁ v₂ : valuation R Γ₀} (h : ∀ r, v₁ r = v₂ r) : v₁ = v₂ := by { cases v₁, cases v₂, congr, funext r, exact h r } lemma ext_iff {v₁ v₂ : valuation R Γ₀} : v₁ = v₂ ↔ ∀ r, v₁ r = v₂ r := ⟨λ h r, congr_arg _ h, ext⟩ -- The following definition is not an instance, because we have more than one `v` on a given `R`. -- In addition, type class inference would not be able to infer `v`. /-- A valuation gives a preorder on the underlying ring. -/ def to_preorder : preorder R := preorder.lift v /-- If `v` is a valuation on a division ring then `v(x) = 0` iff `x = 0`. -/ @[simp] lemma zero_iff [nontrivial Γ₀] {K : Type*} [division_ring K] (v : valuation K Γ₀) {x : K} : v x = 0 ↔ x = 0 := v.to_monoid_with_zero_hom.map_eq_zero lemma ne_zero_iff [nontrivial Γ₀] {K : Type*} [division_ring K] (v : valuation K Γ₀) {x : K} : v x ≠ 0 ↔ x ≠ 0 := v.to_monoid_with_zero_hom.map_ne_zero theorem unit_map_eq (u : units R) : (units.map (v : R →* Γ₀) u : Γ₀) = v u := rfl /-- A ring homomorphism `S → R` induces a map `valuation R Γ₀ → valuation S Γ₀`. -/ def comap {S : Type*} [ring S] (f : S →+* R) (v : valuation R Γ₀) : valuation S Γ₀ := { to_fun := v ∘ f, map_add' := λ x y, by simp only [comp_app, map_add, f.map_add], .. v.to_monoid_with_zero_hom.comp f.to_monoid_with_zero_hom, } @[simp] lemma comap_id : v.comap (ring_hom.id R) = v := ext $ λ r, rfl lemma comap_comp {S₁ : Type*} {S₂ : Type*} [ring S₁] [ring S₂] (f : S₁ →+* S₂) (g : S₂ →+* R) : v.comap (g.comp f) = (v.comap g).comap f := ext $ λ r, rfl /-- A `≤`-preserving group homomorphism `Γ₀ → Γ'₀` induces a map `valuation R Γ₀ → valuation R Γ'₀`. -/ def map (f : monoid_with_zero_hom Γ₀ Γ'₀) (hf : monotone f) (v : valuation R Γ₀) : valuation R Γ'₀ := { to_fun := f ∘ v, map_add' := λ r s, calc f (v (r + s)) ≤ f (max (v r) (v s)) : hf (v.map_add r s) ... = max (f (v r)) (f (v s)) : hf.map_max, .. monoid_with_zero_hom.comp f v.to_monoid_with_zero_hom } /-- Two valuations on `R` are defined to be equivalent if they induce the same preorder on `R`. -/ def is_equiv (v₁ : valuation R Γ₀) (v₂ : valuation R Γ'₀) : Prop := ∀ r s, v₁ r ≤ v₁ s ↔ v₂ r ≤ v₂ s end monoid section group variables [linear_ordered_comm_group_with_zero Γ₀] {R} {Γ₀} (v : valuation R Γ₀) {x y z : R} @[simp] lemma map_inv {K : Type*} [division_ring K] (v : valuation K Γ₀) {x : K} : v x⁻¹ = (v x)⁻¹ := v.to_monoid_with_zero_hom.map_inv' x lemma map_units_inv (x : units R) : v (x⁻¹ : units R) = (v x)⁻¹ := v.to_monoid_with_zero_hom.to_monoid_hom.map_units_inv x @[simp] lemma map_neg (x : R) : v (-x) = v x := v.to_monoid_with_zero_hom.to_monoid_hom.map_neg x lemma map_sub_swap (x y : R) : v (x - y) = v (y - x) := v.to_monoid_with_zero_hom.to_monoid_hom.map_sub_swap x y lemma map_sub (x y : R) : v (x - y) ≤ max (v x) (v y) := calc v (x - y) = v (x + -y) : by rw [sub_eq_add_neg] ... ≤ max (v x) (v $ -y) : v.map_add _ _ ... = max (v x) (v y) : by rw map_neg lemma map_sub_le {x y g} (hx : v x ≤ g) (hy : v y ≤ g) : v (x - y) ≤ g := begin rw sub_eq_add_neg, exact v.map_add_le hx (le_trans (le_of_eq (v.map_neg y)) hy) end lemma map_add_of_distinct_val (h : v x ≠ v y) : v (x + y) = max (v x) (v y) := begin suffices : ¬v (x + y) < max (v x) (v y), from or_iff_not_imp_right.1 (le_iff_eq_or_lt.1 (v.map_add x y)) this, intro h', wlog vyx : v y < v x using x y, { apply lt_or_gt_of_ne h.symm }, { rw max_eq_left_of_lt vyx at h', apply lt_irrefl (v x), calc v x = v ((x+y) - y) : by simp ... ≤ max (v $ x + y) (v y) : map_sub _ _ _ ... < v x : max_lt h' vyx }, { apply this h.symm, rwa [add_comm, max_comm] at h' } end lemma map_eq_of_sub_lt (h : v (y - x) < v x) : v y = v x := begin have := valuation.map_add_of_distinct_val v (ne_of_gt h).symm, rw max_eq_right (le_of_lt h) at this, simpa using this end end group end basic -- end of section namespace is_equiv variables [ring R] variables [linear_ordered_comm_monoid_with_zero Γ₀] [linear_ordered_comm_monoid_with_zero Γ'₀] variables {v : valuation R Γ₀} variables {v₁ : valuation R Γ₀} {v₂ : valuation R Γ'₀} {v₃ : valuation R Γ''₀} @[refl] lemma refl : v.is_equiv v := λ _ _, iff.refl _ @[symm] lemma symm (h : v₁.is_equiv v₂) : v₂.is_equiv v₁ := λ _ _, iff.symm (h _ _) @[trans] lemma trans (h₁₂ : v₁.is_equiv v₂) (h₂₃ : v₂.is_equiv v₃) : v₁.is_equiv v₃ := λ _ _, iff.trans (h₁₂ _ _) (h₂₃ _ _) lemma of_eq {v' : valuation R Γ₀} (h : v = v') : v.is_equiv v' := by { subst h } lemma map {v' : valuation R Γ₀} (f : monoid_with_zero_hom Γ₀ Γ'₀) (hf : monotone f) (inf : injective f) (h : v.is_equiv v') : (v.map f hf).is_equiv (v'.map f hf) := let H : strict_mono f := strict_mono_of_monotone_of_injective hf inf in λ r s, calc f (v r) ≤ f (v s) ↔ v r ≤ v s : by rw H.le_iff_le ... ↔ v' r ≤ v' s : h r s ... ↔ f (v' r) ≤ f (v' s) : by rw H.le_iff_le /-- `comap` preserves equivalence. -/ lemma comap {S : Type*} [ring S] (f : S →+* R) (h : v₁.is_equiv v₂) : (v₁.comap f).is_equiv (v₂.comap f) := λ r s, h (f r) (f s) lemma val_eq (h : v₁.is_equiv v₂) {r s : R} : v₁ r = v₁ s ↔ v₂ r = v₂ s := by simpa only [le_antisymm_iff] using and_congr (h r s) (h s r) lemma ne_zero (h : v₁.is_equiv v₂) {r : R} : v₁ r ≠ 0 ↔ v₂ r ≠ 0 := begin have : v₁ r ≠ v₁ 0 ↔ v₂ r ≠ v₂ 0 := not_iff_not_of_iff h.val_eq, rwa [v₁.map_zero, v₂.map_zero] at this, end end is_equiv -- end of namespace section lemma is_equiv_of_map_strict_mono [linear_ordered_comm_monoid_with_zero Γ₀] [linear_ordered_comm_monoid_with_zero Γ'₀] [ring R] {v : valuation R Γ₀} (f : monoid_with_zero_hom Γ₀ Γ'₀) (H : strict_mono f) : is_equiv (v.map f (H.monotone)) v := λ x y, ⟨H.le_iff_le.mp, λ h, H.monotone h⟩ lemma is_equiv_of_val_le_one [linear_ordered_comm_group_with_zero Γ₀] [linear_ordered_comm_group_with_zero Γ'₀] {K : Type*} [division_ring K] (v : valuation K Γ₀) (v' : valuation K Γ'₀) (h : ∀ {x:K}, v x ≤ 1 ↔ v' x ≤ 1) : v.is_equiv v' := begin intros x y, by_cases hy : y = 0, { simp [hy, zero_iff], }, rw show y = 1 * y, by rw one_mul, rw [← (inv_mul_cancel_right' hy x)], iterate 2 {rw [v.map_mul _ y, v'.map_mul _ y]}, rw [v.map_one, v'.map_one], split; intro H, { apply mul_le_mul_right', replace hy := v.ne_zero_iff.mpr hy, replace H := le_of_le_mul_right hy H, rwa h at H, }, { apply mul_le_mul_right', replace hy := v'.ne_zero_iff.mpr hy, replace H := le_of_le_mul_right hy H, rwa h, }, end end section supp variables [comm_ring R] variables [linear_ordered_comm_monoid_with_zero Γ₀] [linear_ordered_comm_monoid_with_zero Γ'₀] variables (v : valuation R Γ₀) /-- The support of a valuation `v : R → Γ₀` is the ideal of `R` where `v` vanishes. -/ def supp : ideal R := { carrier := {x | v x = 0}, zero_mem' := map_zero v, add_mem' := λ x y hx hy, le_zero_iff.mp $ calc v (x + y) ≤ max (v x) (v y) : v.map_add x y ... ≤ 0 : max_le (le_zero_iff.mpr hx) (le_zero_iff.mpr hy), smul_mem' := λ c x hx, calc v (c * x) = v c * v x : map_mul v c x ... = v c * 0 : congr_arg _ hx ... = 0 : mul_zero _ } @[simp] lemma mem_supp_iff (x : R) : x ∈ supp v ↔ v x = 0 := iff.rfl -- @[simp] lemma mem_supp_iff' (x : R) : x ∈ (supp v : set R) ↔ v x = 0 := iff.rfl /-- The support of a valuation is a prime ideal. -/ instance [nontrivial Γ₀] [no_zero_divisors Γ₀] : ideal.is_prime (supp v) := ⟨λ (h : v.supp = ⊤), one_ne_zero $ show (1 : Γ₀) = 0, from calc 1 = v 1 : v.map_one.symm ... = 0 : show (1:R) ∈ supp v, by { rw h, trivial }, λ x y hxy, begin show v x = 0 ∨ v y = 0, change v (x * y) = 0 at hxy, rw [v.map_mul x y] at hxy, exact eq_zero_or_eq_zero_of_mul_eq_zero hxy end⟩ lemma map_add_supp (a : R) {s : R} (h : s ∈ supp v) : v (a + s) = v a := begin have aux : ∀ a s, v s = 0 → v (a + s) ≤ v a, { intros a' s' h', refine le_trans (v.map_add a' s') (max_le (le_refl _) _), simp [h'], }, apply le_antisymm (aux a s h), calc v a = v (a + s + -s) : by simp ... ≤ v (a + s) : aux (a + s) (-s) (by rwa ←ideal.neg_mem_iff at h) end /-- If `hJ : J ⊆ supp v` then `on_quot_val hJ` is the induced function on R/J as a function. Note: it's just the function; the valuation is `on_quot hJ`. -/ def on_quot_val {J : ideal R} (hJ : J ≤ supp v) : J.quotient → Γ₀ := λ q, quotient.lift_on' q v $ λ a b h, calc v a = v (b + (a - b)) : by simp ... = v b : v.map_add_supp b (hJ h) /-- The extension of valuation v on R to valuation on R/J if J ⊆ supp v -/ def on_quot {J : ideal R} (hJ : J ≤ supp v) : valuation J.quotient Γ₀ := { to_fun := v.on_quot_val hJ, map_zero' := v.map_zero, map_one' := v.map_one, map_mul' := λ xbar ybar, quotient.ind₂' v.map_mul xbar ybar, map_add' := λ xbar ybar, quotient.ind₂' v.map_add xbar ybar } @[simp] lemma on_quot_comap_eq {J : ideal R} (hJ : J ≤ supp v) : (v.on_quot hJ).comap (ideal.quotient.mk J) = v := ext $ λ r, begin refine @quotient.lift_on_mk _ _ (J.quotient_rel) v (λ a b h, _) _, calc v a = v (b + (a - b)) : by simp ... = v b : v.map_add_supp b (hJ h) end lemma comap_supp {S : Type*} [comm_ring S] (f : S →+* R) : supp (v.comap f) = ideal.comap f v.supp := ideal.ext $ λ x, begin rw [mem_supp_iff, ideal.mem_comap, mem_supp_iff], refl, end lemma self_le_supp_comap (J : ideal R) (v : valuation (quotient J) Γ₀) : J ≤ (v.comap (ideal.quotient.mk J)).supp := by { rw [comap_supp, ← ideal.map_le_iff_le_comap], simp } @[simp] lemma comap_on_quot_eq (J : ideal R) (v : valuation J.quotient Γ₀) : (v.comap (ideal.quotient.mk J)).on_quot (v.self_le_supp_comap J) = v := ext $ by { rintro ⟨x⟩, refl } /-- The quotient valuation on R/J has support supp(v)/J if J ⊆ supp v. -/ lemma supp_quot {J : ideal R} (hJ : J ≤ supp v) : supp (v.on_quot hJ) = (supp v).map (ideal.quotient.mk J) := begin apply le_antisymm, { rintro ⟨x⟩ hx, apply ideal.subset_span, exact ⟨x, hx, rfl⟩ }, { rw ideal.map_le_iff_le_comap, intros x hx, exact hx } end lemma supp_quot_supp : supp (v.on_quot (le_refl _)) = 0 := by { rw supp_quot, exact ideal.map_quotient_self _ } end supp -- end of section end valuation section add_monoid variables (R) [ring R] (Γ₀ : Type*) [linear_ordered_add_comm_monoid_with_top Γ₀] /-- The type of `Γ₀`-valued additive valuations on `R`. -/ @[nolint has_inhabited_instance] def add_valuation := valuation R (multiplicative (order_dual Γ₀)) end add_monoid namespace add_valuation variables {Γ₀ : Type*} {Γ'₀ : Type*} section basic section monoid variables [linear_ordered_add_comm_monoid_with_top Γ₀] [linear_ordered_add_comm_monoid_with_top Γ'₀] variables (R) (Γ₀) [ring R] /-- A valuation is coerced to the underlying function `R → Γ₀`. -/ instance : has_coe_to_fun (add_valuation R Γ₀) := { F := λ _, R → Γ₀, coe := valuation.to_fun } variables {R} {Γ₀} (v : add_valuation R Γ₀) {x y z : R} section variables (f : R → Γ₀) (h0 : f 0 = ⊤) (h1 : f 1 = 0) variables (hadd : ∀ x y, min (f x) (f y) ≤ f (x + y)) (hmul : ∀ x y, f (x * y) = f x + f y) /-- An alternate constructor of `add_valuation`, that doesn't reference `multiplicative (order_dual Γ₀)` -/ def of : add_valuation R Γ₀ := { to_fun := f, map_one' := h1, map_zero' := h0, map_add' := hadd, map_mul' := hmul } variables {h0} {h1} {hadd} {hmul} {r : R} @[simp] theorem of_apply : (of f h0 h1 hadd hmul) r = f r := rfl end @[simp] lemma map_zero : v 0 = ⊤ := v.map_zero @[simp] lemma map_one : v 1 = 0 := v.map_one @[simp] lemma map_mul : ∀ x y, v (x * y) = v x + v y := v.map_mul @[simp] lemma map_add : ∀ x y, min (v x) (v y) ≤ v (x + y) := v.map_add lemma map_le_add {x y g} (hx : g ≤ v x) (hy : g ≤ v y) : g ≤ v (x + y) := v.map_add_le hx hy lemma map_lt_add {x y g} (hx : g < v x) (hy : g < v y) : g < v (x + y) := v.map_add_lt hx hy lemma map_le_sum {ι : Type*} {s : finset ι} {f : ι → R} {g : Γ₀} (hf : ∀ i ∈ s, g ≤ v (f i)) : g ≤ v (∑ i in s, f i) := v.map_sum_le hf lemma map_lt_sum {ι : Type*} {s : finset ι} {f : ι → R} {g : Γ₀} (hg : g ≠ ⊤) (hf : ∀ i ∈ s, g < v (f i)) : g < v (∑ i in s, f i) := v.map_sum_lt hg hf lemma map_lt_sum' {ι : Type*} {s : finset ι} {f : ι → R} {g : Γ₀} (hg : g < ⊤) (hf : ∀ i ∈ s, g < v (f i)) : g < v (∑ i in s, f i) := v.map_sum_lt' hg hf @[simp] lemma map_pow : ∀ x (n:ℕ), v (x^n) = n • (v x) := v.map_pow @[ext] lemma ext {v₁ v₂ : add_valuation R Γ₀} (h : ∀ r, v₁ r = v₂ r) : v₁ = v₂ := valuation.ext h lemma ext_iff {v₁ v₂ : add_valuation R Γ₀} : v₁ = v₂ ↔ ∀ r, v₁ r = v₂ r := valuation.ext_iff -- The following definition is not an instance, because we have more than one `v` on a given `R`. -- In addition, type class inference would not be able to infer `v`. /-- A valuation gives a preorder on the underlying ring. -/ def to_preorder : preorder R := preorder.lift v /-- If `v` is an additive valuation on a division ring then `v(x) = ⊤` iff `x = 0`. -/ @[simp] lemma top_iff [nontrivial Γ₀] {K : Type*} [division_ring K] (v : add_valuation K Γ₀) {x : K} : v x = ⊤ ↔ x = 0 := v.zero_iff lemma ne_top_iff [nontrivial Γ₀] {K : Type*} [division_ring K] (v : add_valuation K Γ₀) {x : K} : v x ≠ ⊤ ↔ x ≠ 0 := v.ne_zero_iff /-- A ring homomorphism `S → R` induces a map `add_valuation R Γ₀ → add_valuation S Γ₀`. -/ def comap {S : Type*} [ring S] (f : S →+* R) (v : add_valuation R Γ₀) : add_valuation S Γ₀ := v.comap f @[simp] lemma comap_id : v.comap (ring_hom.id R) = v := v.comap_id lemma comap_comp {S₁ : Type*} {S₂ : Type*} [ring S₁] [ring S₂] (f : S₁ →+* S₂) (g : S₂ →+* R) : v.comap (g.comp f) = (v.comap g).comap f := v.comap_comp f g /-- A `≤`-preserving, `⊤`-preserving group homomorphism `Γ₀ → Γ'₀` induces a map `add_valuation R Γ₀ → add_valuation R Γ'₀`. -/ def map (f : Γ₀ →+ Γ'₀) (ht : f ⊤ = ⊤) (hf : monotone f) (v : add_valuation R Γ₀) : add_valuation R Γ'₀ := v.map { to_fun := f, map_mul' := f.map_add, map_one' := f.map_zero, map_zero' := ht } (λ x y h, hf h) /-- Two additive valuations on `R` are defined to be equivalent if they induce the same preorder on `R`. -/ def is_equiv (v₁ : add_valuation R Γ₀) (v₂ : add_valuation R Γ'₀) : Prop := v₁.is_equiv v₂ end monoid section group variables [linear_ordered_add_comm_group_with_top Γ₀] [ring R] (v : add_valuation R Γ₀) {x y z : R} @[simp] lemma map_inv {K : Type*} [division_ring K] (v : add_valuation K Γ₀) {x : K} : v x⁻¹ = - (v x) := v.map_inv lemma map_units_inv (x : units R) : v (x⁻¹ : units R) = - (v x) := v.map_units_inv x @[simp] lemma map_neg (x : R) : v (-x) = v x := v.map_neg x lemma map_sub_swap (x y : R) : v (x - y) = v (y - x) := v.map_sub_swap x y lemma map_sub (x y : R) : min (v x) (v y) ≤ v (x - y) := v.map_sub x y lemma map_le_sub {x y g} (hx : g ≤ v x) (hy : g ≤ v y) : g ≤ v (x - y) := v.map_sub_le hx hy lemma map_add_of_distinct_val (h : v x ≠ v y) : v (x + y) = min (v x) (v y) := v.map_add_of_distinct_val h lemma map_eq_of_lt_sub (h : v x < v (y - x)) : v y = v x := v.map_eq_of_sub_lt h end group end basic namespace is_equiv variables [linear_ordered_add_comm_monoid_with_top Γ₀] [linear_ordered_add_comm_monoid_with_top Γ'₀] variables [ring R] variables {Γ''₀ : Type*} [linear_ordered_add_comm_monoid_with_top Γ''₀] variables {v : add_valuation R Γ₀} variables {v₁ : add_valuation R Γ₀} {v₂ : add_valuation R Γ'₀} {v₃ : add_valuation R Γ''₀} @[refl] lemma refl : v.is_equiv v := valuation.is_equiv.refl @[symm] lemma symm (h : v₁.is_equiv v₂) : v₂.is_equiv v₁ := h.symm @[trans] lemma trans (h₁₂ : v₁.is_equiv v₂) (h₂₃ : v₂.is_equiv v₃) : v₁.is_equiv v₃ := h₁₂.trans h₂₃ lemma of_eq {v' : add_valuation R Γ₀} (h : v = v') : v.is_equiv v' := valuation.is_equiv.of_eq h lemma map {v' : add_valuation R Γ₀} (f : Γ₀ →+ Γ'₀) (ht : f ⊤ = ⊤) (hf : monotone f) (inf : injective f) (h : v.is_equiv v') : (v.map f ht hf).is_equiv (v'.map f ht hf) := h.map { to_fun := f, map_mul' := f.map_add, map_one' := f.map_zero, map_zero' := ht } (λ x y h, hf h) inf /-- `comap` preserves equivalence. -/ lemma comap {S : Type*} [ring S] (f : S →+* R) (h : v₁.is_equiv v₂) : (v₁.comap f).is_equiv (v₂.comap f) := h.comap f lemma val_eq (h : v₁.is_equiv v₂) {r s : R} : v₁ r = v₁ s ↔ v₂ r = v₂ s := h.val_eq lemma ne_top (h : v₁.is_equiv v₂) {r : R} : v₁ r ≠ ⊤ ↔ v₂ r ≠ ⊤ := h.ne_zero end is_equiv section supp variables [linear_ordered_add_comm_monoid_with_top Γ₀] [linear_ordered_add_comm_monoid_with_top Γ'₀] variables [comm_ring R] variables (v : add_valuation R Γ₀) /-- The support of an additive valuation `v : R → Γ₀` is the ideal of `R` where `v x = ⊤` -/ def supp : ideal R := v.supp @[simp] lemma mem_supp_iff (x : R) : x ∈ supp v ↔ v x = ⊤ := v.mem_supp_iff x lemma map_add_supp (a : R) {s : R} (h : s ∈ supp v) : v (a + s) = v a := v.map_add_supp a h /-- If `hJ : J ⊆ supp v` then `on_quot_val hJ` is the induced function on R/J as a function. Note: it's just the function; the valuation is `on_quot hJ`. -/ def on_quot_val {J : ideal R} (hJ : J ≤ supp v) : J.quotient → Γ₀ := v.on_quot_val hJ /-- The extension of valuation v on R to valuation on R/J if J ⊆ supp v -/ def on_quot {J : ideal R} (hJ : J ≤ supp v) : add_valuation J.quotient Γ₀ := v.on_quot hJ @[simp] lemma on_quot_comap_eq {J : ideal R} (hJ : J ≤ supp v) : (v.on_quot hJ).comap (ideal.quotient.mk J) = v := v.on_quot_comap_eq hJ lemma comap_supp {S : Type*} [comm_ring S] (f : S →+* R) : supp (v.comap f) = ideal.comap f v.supp := v.comap_supp f lemma self_le_supp_comap (J : ideal R) (v : add_valuation (quotient J) Γ₀) : J ≤ (v.comap (ideal.quotient.mk J)).supp := v.self_le_supp_comap J @[simp] lemma comap_on_quot_eq (J : ideal R) (v : add_valuation J.quotient Γ₀) : (v.comap (ideal.quotient.mk J)).on_quot (v.self_le_supp_comap J) = v := v.comap_on_quot_eq J /-- The quotient valuation on R/J has support supp(v)/J if J ⊆ supp v. -/ lemma supp_quot {J : ideal R} (hJ : J ≤ supp v) : supp (v.on_quot hJ) = (supp v).map (ideal.quotient.mk J) := v.supp_quot hJ lemma supp_quot_supp : supp (v.on_quot (le_refl _)) = 0 := v.supp_quot_supp end supp -- end of section attribute [irreducible] add_valuation end add_valuation
4bc5eaae6ffb24d0d7333c321b11a2a7f47a682b
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Meta/IndPredBelow.lean
3145f29d311c8189c77ad1e47bcae566fb86d2c0
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
25,628
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Dany Fabian -/ import Lean.Meta.Constructions import Lean.Meta.Match.Match namespace Lean.Meta.IndPredBelow open Match register_builtin_option maxBackwardChainingDepth : Nat := { defValue := 10 descr := "The maximum search depth used in the backwards chaining part of the proof of `brecOn` for inductive predicates." } /-- The context used in the creation of the `below` scheme for inductive predicates. -/ structure Context where motives : Array (Name × Expr) typeInfos : Array InductiveVal belowNames : Array Name headers : Array Expr numParams : Nat /-- Collection of variables used to keep track of the positions of binders in the construction of `below` motives and constructors. -/ structure Variables where target : Array Expr indVal : Array Expr params : Array Expr args : Array Expr motives : Array Expr innerType : Expr deriving Inhabited /-- Collection of variables used to keep track of the local context used in the `brecOn` proof. -/ structure BrecOnVariables where params : Array FVarId motives : Array FVarId indices : Array FVarId witness : FVarId indHyps : Array FVarId def mkContext (declName : Name) : MetaM Context := do let indVal ← getConstInfoInduct declName let typeInfos ← indVal.all.toArray.mapM getConstInfoInduct let motiveTypes ← typeInfos.mapM motiveType let motives ← motiveTypes.mapIdxM fun j motive => return (← motiveName motiveTypes j.val, motive) let headers ← typeInfos.mapM $ mkHeader motives indVal.numParams return { motives := motives typeInfos := typeInfos numParams := indVal.numParams headers := headers belowNames := indVal.all.toArray.map (· ++ `below) } where motiveName (motiveTypes : Array Expr) (i : Nat) : MetaM Name := if motiveTypes.size > 1 then mkFreshUserName s!"motive_{i.succ}" else mkFreshUserName "motive" mkHeader (motives : Array (Name × Expr)) (numParams : Nat) (indVal : InductiveVal) : MetaM Expr := do let header ← forallTelescopeReducing indVal.type fun xs t => do withNewBinderInfos (xs.map fun x => (x.fvarId!, BinderInfo.implicit)) $ mkForallFVars xs (← mkArrow (mkAppN (mkIndValConst indVal) xs) t) addMotives motives numParams header addMotives (motives : Array (Name × Expr)) (numParams : Nat) : Expr → MetaM Expr := motives.foldrM (fun (motiveName, motive) t => forallTelescopeReducing t fun xs s => do let motiveType ← instantiateForall motive xs[:numParams] withLocalDecl motiveName BinderInfo.implicit motiveType fun motive => do mkForallFVars (xs.insertAt! numParams motive) s) motiveType (indVal : InductiveVal) : MetaM Expr := forallTelescopeReducing indVal.type fun xs _ => do mkForallFVars xs (← mkArrow (mkAppN (mkIndValConst indVal) xs) (mkSort levelZero)) mkIndValConst (indVal : InductiveVal) : Expr := mkConst indVal.name $ indVal.levelParams.map mkLevelParam partial def mkCtorType (ctx : Context) (belowIdx : Nat) (originalCtor : ConstructorVal) : MetaM Expr := forallTelescopeReducing originalCtor.type fun xs t => addHeaderVars { innerType := t indVal := #[] motives := #[] params := xs[:ctx.numParams] args := xs[ctx.numParams:] target := xs[:ctx.numParams] } where addHeaderVars (vars : Variables) := do let headersWithNames ← ctx.headers.mapIdxM fun idx header => return (ctx.belowNames[idx]!, fun _ : Array Expr => pure header) withLocalDeclsD headersWithNames fun xs => addMotives { vars with indVal := xs } addMotives (vars : Variables) := do let motiveBuilders ← ctx.motives.mapM fun (motiveName, motiveType) => return (motiveName, BinderInfo.implicit, fun _ : Array Expr => instantiateForall motiveType vars.params) withLocalDecls motiveBuilders fun xs => modifyBinders { vars with target := vars.target ++ xs, motives := xs } 0 modifyBinders (vars : Variables) (i : Nat) := do if i < vars.args.size then let binder := vars.args[i]! let binderType ← inferType binder if (← checkCount binderType) then mkBelowBinder vars binder binderType fun indValIdx x => mkMotiveBinder vars indValIdx binder binderType fun y => withNewBinderInfos #[(binder.fvarId!, BinderInfo.implicit)] do modifyBinders { vars with target := vars.target ++ #[binder, x, y]} i.succ else modifyBinders { vars with target := vars.target.push binder } i.succ else rebuild vars rebuild (vars : Variables) := vars.innerType.withApp fun _ args => do let hApp := mkAppN (mkConst originalCtor.name $ ctx.typeInfos[0]!.levelParams.map mkLevelParam) (vars.params ++ vars.args) let innerType := mkAppN vars.indVal[belowIdx]! $ vars.params ++ vars.motives ++ args[ctx.numParams:] ++ #[hApp] let x ← mkForallFVars vars.target innerType return replaceTempVars vars x replaceTempVars (vars : Variables) (ctor : Expr) := let levelParams := ctx.typeInfos[0]!.levelParams.map mkLevelParam ctor.replaceFVars vars.indVal $ ctx.belowNames.map fun indVal => mkConst indVal levelParams checkCount (domain : Expr) : MetaM Bool := do let run (x : StateRefT Nat MetaM Expr) : MetaM (Expr × Nat) := StateRefT'.run x 0 let (_, cnt) ← run <| transform domain fun e => do if let some name := e.constName? then if let some _ := ctx.typeInfos.findIdx? fun indVal => indVal.name == name then modify (· + 1) return .continue if cnt > 1 then throwError "only arrows are allowed as premises. Multiple recursive occurrences detected:{indentExpr domain}" return cnt == 1 mkBelowBinder (vars : Variables) (binder : Expr) (domain : Expr) {α : Type} (k : Nat → Expr → MetaM α) : MetaM α := do forallTelescopeReducing domain fun xs t => do let fail _ := do throwError "only trivial inductive applications supported in premises:{indentExpr t}" t.withApp fun f args => do if let some name := f.constName? then if let some idx := ctx.typeInfos.findIdx? fun indVal => indVal.name == name then let hApp := mkAppN binder xs let t := mkAppN vars.indVal[idx]! $ vars.params ++ vars.motives ++ args[ctx.numParams:] ++ #[hApp] let newDomain ← mkForallFVars xs t withLocalDecl (←copyVarName binder.fvarId!) binder.binderInfo newDomain (k idx) else fail () else fail () mkMotiveBinder (vars : Variables) (indValIdx : Nat) (binder : Expr) (domain : Expr) {α : Type} (k : Expr → MetaM α) : MetaM α := do forallTelescopeReducing domain fun xs t => do t.withApp fun _ args => do let hApp := mkAppN binder xs let t := mkAppN vars.motives[indValIdx]! $ args[ctx.numParams:] ++ #[hApp] let newDomain ← mkForallFVars xs t withLocalDecl (←copyVarName binder.fvarId!) binder.binderInfo newDomain k copyVarName (oldName : FVarId) : MetaM Name := do let binderDecl ← oldName.getDecl mkFreshUserName binderDecl.userName def mkConstructor (ctx : Context) (i : Nat) (ctor : Name) : MetaM Constructor := do let ctorInfo ← getConstInfoCtor ctor let name := ctor.updatePrefix ctx.belowNames[i]! let type ← mkCtorType ctx i ctorInfo return { name := name type := type } def mkInductiveType (ctx : Context) (i : Fin ctx.typeInfos.size) (indVal : InductiveVal) : MetaM InductiveType := do return { name := ctx.belowNames[i]! type := ctx.headers[i]! ctors := (← indVal.ctors.mapM (mkConstructor ctx i)) } def mkBelowDecl (ctx : Context) : MetaM Declaration := do let lparams := ctx.typeInfos[0]!.levelParams return Declaration.inductDecl lparams (ctx.numParams + ctx.motives.size) (←ctx.typeInfos.mapIdxM $ mkInductiveType ctx).toList ctx.typeInfos[0]!.isUnsafe partial def backwardsChaining (m : MVarId) (depth : Nat) : MetaM Bool := do if depth = 0 then return false else m.withContext do let lctx ← getLCtx let mTy ← m.getType lctx.anyM fun localDecl => if localDecl.isAuxDecl then return false else commitWhen do let (mvars, _, t) ← forallMetaTelescope localDecl.type if ←isDefEq mTy t then m.assign (mkAppN localDecl.toExpr mvars) mvars.allM fun v => v.mvarId!.isAssigned <||> backwardsChaining v.mvarId! (depth - 1) else return false partial def proveBrecOn (ctx : Context) (indVal : InductiveVal) (type : Expr) : MetaM Expr := do let main ← mkFreshExprSyntheticOpaqueMVar type let (m, vars) ← intros main.mvarId! let [m] ← applyIH m vars | throwError "applying the induction hypothesis should only return one goal" let ms ← induction m vars let ms ← applyCtors ms let maxDepth := maxBackwardChainingDepth.get $ ←getOptions ms.forM (closeGoal maxDepth) instantiateMVars main where intros (m : MVarId) : MetaM (MVarId × BrecOnVariables) := do let (params, m) ← m.introNP indVal.numParams let (motives, m) ← m.introNP ctx.motives.size let (indices, m) ← m.introNP indVal.numIndices let (witness, m) ← m.intro1P let (indHyps, m) ← m.introNP ctx.motives.size return (m, ⟨params, motives, indices, witness, indHyps⟩) applyIH (m : MVarId) (vars : BrecOnVariables) : MetaM (List MVarId) := do match (← vars.indHyps.findSomeM? fun ih => do try pure <| some <| (← m.apply <| mkFVar ih) catch _ => pure none) with | some goals => pure goals | none => throwError "cannot apply induction hypothesis: {MessageData.ofGoal m}" induction (m : MVarId) (vars : BrecOnVariables) : MetaM (List MVarId) := do let params := vars.params.map mkFVar let motives := vars.motives.map mkFVar let levelParams := indVal.levelParams.map mkLevelParam let motives ← ctx.motives.mapIdxM fun idx (_, motive) => do let motive ← instantiateForall motive params forallTelescopeReducing motive fun xs _ => do mkLambdaFVars xs <| mkAppN (mkConst ctx.belowNames[idx]! levelParams) $ (params ++ motives ++ xs) let recursorInfo ← getConstInfo $ mkRecName indVal.name let recLevels := if recursorInfo.numLevelParams > levelParams.length then levelZero::levelParams else levelParams let recursor := mkAppN (mkConst recursorInfo.name $ recLevels) $ params ++ motives m.apply recursor applyCtors (ms : List MVarId) : MetaM $ List MVarId := do let mss ← ms.toArray.mapIdxM fun _ m => do let m ← introNPRec m (← m.getType).withApp fun below args => m.withContext do args.back.withApp fun ctor _ => do let ctorName := ctor.constName!.updatePrefix below.constName! let ctor := mkConst ctorName below.constLevels! let ctorInfo ← getConstInfoCtor ctorName let (mvars, _, _) ← forallMetaTelescope ctorInfo.type let ctor := mkAppN ctor mvars m.apply ctor return mss.foldr List.append [] introNPRec (m : MVarId) : MetaM MVarId := do if (← m.getType).isForall then introNPRec (← m.intro1P).2 else return m closeGoal (maxDepth : Nat) (m : MVarId) : MetaM Unit := do unless (← m.isAssigned) do let m ← introNPRec m unless (← backwardsChaining m maxDepth) do m.withContext do throwError "couldn't solve by backwards chaining ({``maxBackwardChainingDepth} = {maxDepth}): {MessageData.ofGoal m}" def mkBrecOnDecl (ctx : Context) (idx : Nat) : MetaM Declaration := do let type ← mkType let indVal := ctx.typeInfos[idx]! let name := indVal.name ++ brecOnSuffix return Declaration.thmDecl { name := name levelParams := indVal.levelParams type := type value := ←proveBrecOn ctx indVal type } where mkType : MetaM Expr := forallTelescopeReducing ctx.headers[idx]! fun xs _ => do let params := xs[:ctx.numParams] let motives := xs[ctx.numParams:ctx.numParams + ctx.motives.size].toArray let indices := xs[ctx.numParams + ctx.motives.size:] let motiveBinders ← ctx.motives.mapIdxM $ mkIH params motives withLocalDeclsD motiveBinders fun ys => do mkForallFVars (xs ++ ys) (mkAppN motives[idx]! indices) mkIH (params : Array Expr) (motives : Array Expr) (idx : Fin ctx.motives.size) (motive : Name × Expr) : MetaM $ Name × (Array Expr → MetaM Expr) := do let name := if ctx.motives.size > 1 then mkFreshUserName s!"ih_{idx.val.succ}" else mkFreshUserName "ih" let ih ← instantiateForall motive.2 params let mkDomain (_ : Array Expr) : MetaM Expr := forallTelescopeReducing ih fun ys _ => do let levels := ctx.typeInfos[idx]!.levelParams.map mkLevelParam let args := params ++ motives ++ ys let premise := mkAppN (mkConst ctx.belowNames[idx.val]! levels) args let conclusion := mkAppN motives[idx]! ys mkForallFVars ys (←mkArrow premise conclusion) return (←name, mkDomain) /-- Given a constructor name, find the indices of the corresponding `below` version thereof. -/ partial def getBelowIndices (ctorName : Name) : MetaM $ Array Nat := do let ctorInfo ← getConstInfoCtor ctorName let belowCtorInfo ← getConstInfoCtor (ctorName.updatePrefix $ ctorInfo.induct ++ `below) forallTelescopeReducing ctorInfo.type fun xs _ => do loop xs belowCtorInfo.type #[] 0 0 where loop (xs : Array Expr) (rest : Expr) (belowIndices : Array Nat) (xIdx yIdx : Nat) : MetaM $ Array Nat := do if xIdx ≥ xs.size then return belowIndices else let x := xs[xIdx]! let xTy ← inferType x let yTy := rest.bindingDomain! if (← isDefEq xTy yTy) then let rest ← instantiateForall rest #[x] loop xs rest (belowIndices.push yIdx) (xIdx + 1) (yIdx + 1) else forallBoundedTelescope rest (some 1) fun _ rest => loop xs rest belowIndices xIdx (yIdx + 1) private def belowType (motive : Expr) (xs : Array Expr) (idx : Nat) : MetaM $ Name × Expr := do (← inferType xs[idx]!).withApp fun type args => do let indName := type.constName! let indInfo ← getConstInfoInduct indName let belowArgs := args[:indInfo.numParams] ++ #[motive] ++ args[indInfo.numParams:] ++ #[xs[idx]!] let belowType := mkAppN (mkConst (indName ++ `below) type.constLevels!) belowArgs return (indName, belowType) /-- This function adds an additional `below` discriminant to a matcher application. It is used for modifying the patterns, such that the structural recursion can use the new `below` predicate instead of the original one and thus be used prove structural recursion. It takes as parameters: - matcherApp: a matcher application - belowMotive: the motive, that the `below` type should carry - below: an expression from the local context that is the `below` version of a predicate and can be used for structural recursion - idx: the index of the original predicate discriminant. It returns: - A matcher application as an expression - A side-effect for adding the matcher to the environment -/ partial def mkBelowMatcher (matcherApp : MatcherApp) (belowMotive : Expr) (below : Expr) (idx : Nat) : MetaM $ Expr × MetaM Unit := do let mkMatcherInput ← getMkMatcherInputInContext matcherApp let (indName, _, motive, matchType) ← forallBoundedTelescope mkMatcherInput.matchType mkMatcherInput.numDiscrs fun xs t => do let (indName, belowType) ← belowType belowMotive xs idx let matchType ← withLocalDeclD (←mkFreshUserName `h_below) belowType fun h_below => do mkForallFVars (xs.push h_below) t let motive ← newMotive belowType xs pure (indName, belowType.replaceFVars xs matcherApp.discrs, motive, matchType) let lhss ← mkMatcherInput.lhss.mapM <| addBelowPattern indName let alts ← mkMatcherInput.lhss.zip lhss |>.toArray.zip matcherApp.alts |>.mapIdxM fun idx ((oldLhs, lhs), alt) => do withExistingLocalDecls (oldLhs.fvarDecls ++ lhs.fvarDecls) do lambdaTelescope alt fun xs t => do let oldFVars := oldLhs.fvarDecls.toArray let fvars := lhs.fvarDecls.toArray.map (·.toExpr) let xs := -- special case: if we had no free vars, i.e. there was a unit added and no we do have free vars, we get rid of the unit. match oldFVars.size, fvars.size with | 0, _+1 => xs[1:] | _, _ => xs let t := t.replaceFVars xs[:oldFVars.size] fvars[:oldFVars.size] trace[Meta.IndPredBelow.match] "xs = {xs}; oldFVars = {oldFVars.map (·.toExpr)}; fvars = {fvars}; new = {fvars[:oldFVars.size] ++ xs[oldFVars.size:] ++ fvars[oldFVars.size:]}" let newAlt ← mkLambdaFVars (fvars[:oldFVars.size] ++ xs[oldFVars.size:] ++ fvars[oldFVars.size:]) t trace[Meta.IndPredBelow.match] "alt {idx}:\n{alt} ↦ {newAlt}" pure newAlt let matcherName ← mkFreshUserName mkMatcherInput.matcherName withExistingLocalDecls (lhss.foldl (init := []) fun s v => s ++ v.fvarDecls) do for lhs in lhss do trace[Meta.IndPredBelow.match] "{lhs.patterns.map (·.toMessageData)}" let res ← Match.mkMatcher { matcherName, matchType, discrInfos := mkArray (mkMatcherInput.numDiscrs + 1) {}, lhss } res.addMatcher -- if a wrong index is picked, the resulting matcher can be type-incorrect. -- we check here, so that errors can propagate higher up the call stack. check res.matcher let newApp := mkApp res.matcher motive let newApp := mkAppN newApp <| matcherApp.discrs.push below let newApp := mkAppN newApp alts return (newApp, res.addMatcher) where addBelowPattern (indName : Name) (lhs : AltLHS) : MetaM AltLHS := do withExistingLocalDecls lhs.fvarDecls do let patterns := lhs.patterns.toArray let originalPattern := patterns[idx]! let (fVars, belowPattern) ← convertToBelow indName patterns[idx]! withExistingLocalDecls fVars.toList do let patterns := patterns.push belowPattern let patterns := patterns.set! idx (←toInaccessible originalPattern) return { lhs with patterns := patterns.toList, fvarDecls := lhs.fvarDecls ++ fVars.toList } /-- this function changes the type of the pattern from the original type to the `below` version thereof. Most of the cases don't apply. In order to change the type and the pattern to be type correct, we don't simply recursively change all occurrences, but rather, we recursively change occurences of the constructor. As such there are only a few cases: - the pattern is a constructor from the original type. Here we need to: - replace the constructor - copy original recursive patterns and convert them to below and reintroduce them in the correct position - turn original recursive patterns inaccessible - introduce free variables as needed. - it is an `as` pattern. Here the contstructor could be hidden inside of it. - it is a variable. Here you we need to introduce a fresh variable of a different type. -/ convertToBelow (indName : Name) (originalPattern : Pattern) : MetaM $ Array LocalDecl × Pattern := do match originalPattern with | Pattern.ctor ctorName us params fields => let ctorInfo ← getConstInfoCtor ctorName let belowCtor ← getConstInfoCtor $ ctorName.updatePrefix $ ctorInfo.induct ++ `below let belowIndices ← IndPredBelow.getBelowIndices ctorName let belowIndices := belowIndices[ctorInfo.numParams:].toArray.map (· - belowCtor.numParams) -- belowFieldOpts starts off with an array of empty fields. -- We then go over pattern's fields and set the appropriate fields to values. -- In general, there are fewer `fields` than `belowFieldOpts`, because the -- `belowCtor` carries a `below`, a non-`below` and a `motive` version of each -- field that occurs in a recursive application of the inductive predicate. -- `belowIndices` is a mapping from non-`below` to the `below` version of each field. let mut belowFieldOpts := mkArray belowCtor.numFields none let fields := fields.toArray for fieldIdx in [:fields.size] do belowFieldOpts := belowFieldOpts.set! belowIndices[fieldIdx]! (some fields[fieldIdx]!) let belowParams := params.toArray.push belowMotive let belowCtorExpr := mkAppN (mkConst belowCtor.name us) belowParams let (additionalFVars, belowFields) ← transformFields belowCtorExpr indName belowFieldOpts withExistingLocalDecls additionalFVars.toList do let ctor := Pattern.ctor belowCtor.name us belowParams.toList belowFields.toList trace[Meta.IndPredBelow.match] "{originalPattern.toMessageData} ↦ {ctor.toMessageData}" return (additionalFVars, ctor) | Pattern.as varId p hId => let (additionalFVars, p) ← convertToBelow indName p return (additionalFVars, Pattern.as varId p hId) | Pattern.var varId => let var := mkFVar varId let (_, tgtType) ← belowType belowMotive #[var] 0 withLocalDeclD (←mkFreshUserName `h) tgtType fun h => do let localDecl ← getFVarLocalDecl h return (#[localDecl], Pattern.var h.fvarId!) | p => return (#[], p) transformFields belowCtor indName belowFieldOpts := let rec loop (belowCtor : Expr) (belowFieldOpts : Array $ Option Pattern) (belowFields : Array Pattern) (additionalFVars : Array LocalDecl) : MetaM (Array LocalDecl × Array Pattern) := do if belowFields.size ≥ belowFieldOpts.size then pure (additionalFVars, belowFields) else if let some belowField := belowFieldOpts[belowFields.size]! then let belowFieldExpr ← belowField.toExpr let belowCtor := mkApp belowCtor belowFieldExpr let patTy ← inferType belowFieldExpr patTy.withApp fun f _ => do let constName := f.constName? if constName == indName then let (fvars, transformedField) ← convertToBelow indName belowField withExistingLocalDecls fvars.toList do let belowFieldOpts := belowFieldOpts.set! (belowFields.size + 1) transformedField let belowField := match belowField with | Pattern.ctor .. => Pattern.inaccessible belowFieldExpr | _ => belowField loop belowCtor belowFieldOpts (belowFields.push belowField) (additionalFVars ++ fvars) else loop belowCtor belowFieldOpts (belowFields.push belowField) additionalFVars else let ctorType ← inferType belowCtor withLocalDeclD (←mkFreshUserName `a) ctorType.bindingDomain! fun a => do let localDecl ← getFVarLocalDecl a loop (mkApp belowCtor a) belowFieldOpts (belowFields.push $ Pattern.var a.fvarId!) (additionalFVars.push localDecl) loop belowCtor belowFieldOpts #[] #[] toInaccessible : Pattern → MetaM Pattern | Pattern.inaccessible p => return Pattern.inaccessible p | Pattern.var v => return Pattern.var v | p => return Pattern.inaccessible $ ←p.toExpr newMotive (belowType : Expr) (ys : Array Expr) : MetaM Expr := lambdaTelescope matcherApp.motive fun xs t => do let numDiscrs := matcherApp.discrs.size withLocalDeclD (←mkFreshUserName `h_below) (belowType.replaceFVars ys xs) fun h_below => do let motive ← mkLambdaFVars (xs[:numDiscrs] ++ #[h_below] ++ xs[numDiscrs:]) t trace[Meta.IndPredBelow.match] "motive := {motive}" return motive def findBelowIdx (xs : Array Expr) (motive : Expr) : MetaM $ Option (Expr × Nat) := do xs.findSomeM? fun x => do let xTy ← inferType x xTy.withApp fun f _ => match f.constName?, xs.indexOf? x with | some name, some idx => do if (← isInductivePredicate name) then let (_, belowTy) ← belowType motive xs idx let below ← mkFreshExprSyntheticOpaqueMVar belowTy try trace[Meta.IndPredBelow.match] "{←Meta.ppGoal below.mvarId!}" if (← backwardsChaining below.mvarId! 10) then trace[Meta.IndPredBelow.match] "Found below term in the local context: {below}" if (← xs.anyM (isDefEq below)) then pure none else pure (below, idx.val) else trace[Meta.IndPredBelow.match] "could not find below term in the local context" pure none catch _ => pure none else pure none | _, _ => pure none def mkBelow (declName : Name) : MetaM Unit := do if (← isInductivePredicate declName) then let x ← getConstInfoInduct declName if x.isRec then let ctx ← IndPredBelow.mkContext declName let decl ← IndPredBelow.mkBelowDecl ctx addDecl decl trace[Meta.IndPredBelow] "added {ctx.belowNames}" ctx.belowNames.forM Lean.mkCasesOn for i in [:ctx.typeInfos.size] do try let decl ← IndPredBelow.mkBrecOnDecl ctx i addDecl decl catch e => trace[Meta.IndPredBelow] "failed to prove brecOn for {ctx.belowNames[i]!}\n{e.toMessageData}" else trace[Meta.IndPredBelow] "Not recursive" else trace[Meta.IndPredBelow] "Not inductive predicate" builtin_initialize registerTraceClass `Meta.IndPredBelow registerTraceClass `Meta.IndPredBelow.match end Lean.Meta.IndPredBelow
a3ab2510970bb6a5d5fe1bfa923d5cf5a07c320c
ce89339993655da64b6ccb555c837ce6c10f9ef4
/ukikagi/top35.lean
75a1fa12525bebe8d123ad3896f1c50a712a29f0
[]
no_license
zeptometer/LearnLean
ef32dc36a22119f18d843f548d0bb42f907bff5d
bb84d5dbe521127ba134d4dbf9559b294a80b9f7
refs/heads/master
1,625,710,824,322
1,601,382,570,000
1,601,382,570,000
195,228,870
2
0
null
null
null
null
UTF-8
Lean
false
false
397
lean
definition NtoB := nat -> bool. definition NtoB_eqv (g h : NtoB) : Prop := ∀ i, g i = h i. constant f: nat -> NtoB axiom f_surjective: ∀ g : NtoB, ∃ n, NtoB_eqv (f n) g example: false := begin let g := λ n: nat, bnot (f n n), cases f_surjective (λ n: nat, bnot (f n n)) with n, have hn: f n n = g n, from h n, simp [g] at hn, cases f n n with b; contradiction, end
5ffb30897b7160a7ae26bc8a78cd701b718b58ac
63abd62053d479eae5abf4951554e1064a4c45b4
/src/data/padics/ring_homs.lean
80f7f23389977ed99175e37ac25c7c3073e420bf
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
24,698
lean
/- Copyright (c) 2020 Johan Commelin and Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin and Robert Y. Lewis -/ import data.padics.padic_integers /-! # Relating `ℤ_[p]` to `zmod (p ^ n)` In this file we establish connections between the `p`-adic integers $\mathbb{Z}_p$ and the integers modulo powers of `p`, $\mathbb{Z}/p^n\mathbb{Z}$. ## Main declarations We show that $\mathbb{Z}_p$ has a ring hom to $\mathbb{Z}/p^n\mathbb{Z}$ for each `n`. The case for `n = 1` is handled separately, since it is used in the general construction and we may want to use it without the `^1` getting in the way. * `padic_int.to_zmod`: ring hom to `zmod p` * `padic_int.to_zmod_pow`: ring hom to `zmod (p^n)` * `padic_int.ker_to_zmod` / `padic_int.ker_to_zmod_pow`: the kernels of these maps are the ideals generated by `p^n` We also establish the universal property of $\mathbb{Z}_p$ as a projective limit. Given a family of compatible ring homs $f_k : R \to \mathbb{Z}/p^n\mathbb{Z}$, there is a unique limit $R \to \mathbb{Z}_p$. * `padic_int.lift`: the limit function * `padic_int.lift_spec` / `padic_int.lift_unique`: the universal property ## Implementation notes The ring hom constructions go through an auxiliary constructor `padic_int.to_zmod_hom`, which removes some boilerplate code. -/ noncomputable theory open_locale classical namespace padic_int open nat local_ring padic variables {p : ℕ} [hp_prime : fact (p.prime)] include hp_prime section ring_homs /-! ### Ring homomorphisms to `zmod p` and `zmod (p ^ n)` -/ variables (p) (r : ℚ) omit hp_prime /-- `mod_part p r` is an integer that satisfies `∥(r - mod_part p r : ℚ_[p])∥ < 1` when `∥(r : ℚ_[p])∥ ≤ 1`, see `padic_int.norm_sub_mod_part`. It is the unique non-negative integer that is `< p` with this property. (Note that this definition assumes `r : ℚ`. See `padic_int.zmod_repr` for a version that takes values in `ℕ` and works for arbitrary `x : ℤ_[p]`.) -/ def mod_part : ℤ := (r.num * gcd_a r.denom p) % p include hp_prime variable {p} lemma mod_part_lt_p : mod_part p r < p := begin convert int.mod_lt _ _, { simp }, { exact_mod_cast hp_prime.ne_zero } end lemma mod_part_nonneg : 0 ≤ mod_part p r := int.mod_nonneg _ $ by exact_mod_cast hp_prime.ne_zero lemma is_unit_denom (r : ℚ) (h : ∥(r : ℚ_[p])∥ ≤ 1) : is_unit (r.denom : ℤ_[p]) := begin rw is_unit_iff, apply le_antisymm (r.denom : ℤ_[p]).2, rw [← not_lt, val_eq_coe, coe_coe], intro norm_denom_lt, have hr : ∥(r * r.denom : ℚ_[p])∥ = ∥(r.num : ℚ_[p])∥, { rw_mod_cast @rat.mul_denom_eq_num r, refl, }, rw padic_norm_e.mul at hr, have key : ∥(r.num : ℚ_[p])∥ < 1, { calc _ = _ : hr.symm ... < 1 * 1 : mul_lt_mul' h norm_denom_lt (norm_nonneg _) zero_lt_one ... = 1 : mul_one 1 }, have : ↑p ∣ r.num ∧ (p : ℤ) ∣ r.denom, { simp only [← norm_int_lt_one_iff_dvd, ← padic_norm_e_of_padic_int], norm_cast, exact ⟨key, norm_denom_lt⟩ }, apply hp_prime.not_dvd_one, rwa [← r.cop.gcd_eq_one, nat.dvd_gcd_iff, ← int.coe_nat_dvd_left, ← int.coe_nat_dvd], end lemma norm_sub_mod_part_aux (r : ℚ) (h : ∥(r : ℚ_[p])∥ ≤ 1) : ↑p ∣ r.num - r.num * r.denom.gcd_a p % p * ↑(r.denom) := begin rw ← zmod.int_coe_zmod_eq_zero_iff_dvd, simp only [int.cast_coe_nat, zmod.cast_mod_nat p, int.cast_mul, int.cast_sub], have := congr_arg (coe : ℤ → zmod p) (gcd_eq_gcd_ab r.denom p), simp only [int.cast_coe_nat, add_zero, int.cast_add, zmod.cast_self, int.cast_mul, zero_mul] at this, push_cast, rw [mul_right_comm, mul_assoc, ←this], suffices rdcp : r.denom.coprime p, { rw rdcp.gcd_eq_one, simp only [mul_one, cast_one, sub_self], }, apply coprime.symm, apply (coprime_or_dvd_of_prime ‹_› _).resolve_right, rw [← int.coe_nat_dvd, ← norm_int_lt_one_iff_dvd, not_lt], apply ge_of_eq, rw ← is_unit_iff, exact is_unit_denom r h, end lemma norm_sub_mod_part (h : ∥(r : ℚ_[p])∥ ≤ 1) : ∥(⟨r,h⟩ - mod_part p r : ℤ_[p])∥ < 1 := begin let n := mod_part p r, by_cases aux : (⟨r,h⟩ - n : ℤ_[p]) = 0, { rw [aux, norm_zero], exact zero_lt_one, }, rw [norm_lt_one_iff_dvd, ← (is_unit_denom r h).dvd_mul_right], suffices : ↑p ∣ r.num - n * r.denom, { convert (int.cast_ring_hom ℤ_[p]).map_dvd this, simp only [sub_mul, int.cast_coe_nat, ring_hom.eq_int_cast, int.cast_mul, sub_left_inj, int.cast_sub], apply subtype.coe_injective, simp only [coe_mul, subtype.coe_mk, coe_coe], rw_mod_cast @rat.mul_denom_eq_num r, refl }, exact norm_sub_mod_part_aux r h end lemma exists_mem_range_of_norm_rat_le_one (h : ∥(r : ℚ_[p])∥ ≤ 1) : ∃ n : ℤ, 0 ≤ n ∧ n < p ∧ ∥(⟨r,h⟩ - n : ℤ_[p])∥ < 1 := ⟨mod_part p r, mod_part_nonneg _, mod_part_lt_p _, norm_sub_mod_part _ h⟩ lemma zmod_congr_of_sub_mem_span_aux (n : ℕ) (x : ℤ_[p]) (a b : ℤ) (ha : x - a ∈ (ideal.span {p ^ n} : ideal ℤ_[p])) (hb : x - b ∈ (ideal.span {p ^ n} : ideal ℤ_[p])) : (a : zmod (p ^ n)) = b := begin rw [ideal.mem_span_singleton] at ha hb, rw [← sub_eq_zero, ← int.cast_sub, zmod.int_coe_zmod_eq_zero_iff_dvd, int.coe_nat_pow], rw [← dvd_neg, neg_sub] at ha, have := dvd_add ha hb, rwa [sub_eq_add_neg, sub_eq_add_neg, add_assoc, neg_add_cancel_left, ← sub_eq_add_neg, ← int.cast_sub, pow_p_dvd_int_iff] at this, end lemma zmod_congr_of_sub_mem_span (n : ℕ) (x : ℤ_[p]) (a b : ℕ) (ha : x - a ∈ (ideal.span {p ^ n} : ideal ℤ_[p])) (hb : x - b ∈ (ideal.span {p ^ n} : ideal ℤ_[p])) : (a : zmod (p ^ n)) = b := zmod_congr_of_sub_mem_span_aux n x a b ha hb lemma zmod_congr_of_sub_mem_max_ideal (x : ℤ_[p]) (m n : ℕ) (hm : x - m ∈ maximal_ideal ℤ_[p]) (hn : x - n ∈ maximal_ideal ℤ_[p]) : (m : zmod p) = n := begin rw maximal_ideal_eq_span_p at hm hn, have := zmod_congr_of_sub_mem_span_aux 1 x m n, simp only [pow_one] at this, specialize this hm hn, apply_fun zmod.cast_hom (show p ∣ p ^ 1, by rw pow_one) (zmod p) at this, simpa only [ring_hom.map_int_cast], end variable (x : ℤ_[p]) lemma exists_mem_range : ∃ n : ℕ, n < p ∧ (x - n ∈ maximal_ideal ℤ_[p]) := begin simp only [maximal_ideal_eq_span_p, ideal.mem_span_singleton, ← norm_lt_one_iff_dvd], obtain ⟨r, hr⟩ := rat_dense (x : ℚ_[p]) zero_lt_one, have H : ∥(r : ℚ_[p])∥ ≤ 1, { rw norm_sub_rev at hr, calc _ = ∥(r : ℚ_[p]) - x + x∥ : by ring ... ≤ _ : padic_norm_e.nonarchimedean _ _ ... ≤ _ : max_le (le_of_lt hr) x.2 }, obtain ⟨n, hzn, hnp, hn⟩ := exists_mem_range_of_norm_rat_le_one r H, lift n to ℕ using hzn, use n, split, {exact_mod_cast hnp}, simp only [norm_def, coe_sub, subtype.coe_mk, coe_coe] at hn ⊢, rw show (x - n : ℚ_[p]) = (x - r) + (r - n), by ring, apply lt_of_le_of_lt (padic_norm_e.nonarchimedean _ _), apply max_lt hr, simpa using hn end /-- `zmod_repr x` is the unique natural number smaller than `p` satisfying `∥(x - zmod_repr x : ℤ_[p])∥ < 1`. -/ def zmod_repr : ℕ := classical.some (exists_mem_range x) lemma zmod_repr_spec : zmod_repr x < p ∧ (x - zmod_repr x ∈ maximal_ideal ℤ_[p]) := classical.some_spec (exists_mem_range x) lemma zmod_repr_lt_p : zmod_repr x < p := (zmod_repr_spec _).1 lemma sub_zmod_repr_mem : (x - zmod_repr x ∈ maximal_ideal ℤ_[p]) := (zmod_repr_spec _).2 /-- `to_zmod_hom` is an auxiliary constructor for creating ring homs from `ℤ_[p]` to `zmod v`. -/ def to_zmod_hom (v : ℕ) (f : ℤ_[p] → ℕ) (f_spec : ∀ x, x - f x ∈ (ideal.span {v} : ideal ℤ_[p])) (f_congr : ∀ (x : ℤ_[p]) (a b : ℕ), x - a ∈ (ideal.span {v} : ideal ℤ_[p]) → x - b ∈ (ideal.span {v} : ideal ℤ_[p]) → (a : zmod v) = b) : ℤ_[p] →+* zmod v := { to_fun := λ x, f x, map_zero' := begin rw [f_congr (0 : ℤ_[p]) _ 0, cast_zero], { exact f_spec _ }, { simp only [sub_zero, cast_zero, submodule.zero_mem], } end, map_one' := begin rw [f_congr (1 : ℤ_[p]) _ 1, cast_one], { exact f_spec _ }, { simp only [sub_self, cast_one, submodule.zero_mem], } end, map_add' := begin intros x y, rw [f_congr (x + y) _ (f x + f y), cast_add], { exact f_spec _ }, { convert ideal.add_mem _ (f_spec x) (f_spec y), rw cast_add, ring, } end, map_mul' := begin intros x y, rw [f_congr (x * y) _ (f x * f y), cast_mul], { exact f_spec _ }, { let I : ideal ℤ_[p] := ideal.span {v}, have A : x * (y - f y) ∈ I := I.mul_mem_left (f_spec _), have B : (x - f x) * (f y) ∈ I := I.mul_mem_right (f_spec _), convert I.add_mem A B, rw cast_mul, ring, } end, } /-- `to_zmod` is a ring hom from `ℤ_[p]` to `zmod p`, with the equality `to_zmod x = (zmod_repr x : zmod p)`. -/ def to_zmod : ℤ_[p] →+* zmod p := to_zmod_hom p zmod_repr (by { rw ←maximal_ideal_eq_span_p, exact sub_zmod_repr_mem }) (by { rw ←maximal_ideal_eq_span_p, exact zmod_congr_of_sub_mem_max_ideal } ) /-- `z - (to_zmod z : ℤ_[p])` is contained in the maximal ideal of `ℤ_[p]`, for every `z : ℤ_[p]`. The coercion from `zmod p` to `ℤ_[p]` is `zmod.has_coe_t`, which coerces `zmod p` into artibrary rings. This is unfortunate, but a consequence of the fact that we allow `zmod p` to coerce to rings of arbitrary characteristic, instead of only rings of characteristic `p`. This coercion is only a ring homomorphism if it coerces into a ring whose characteristic divides `p`. While this is not the case here we can still make use of the coercion. -/ lemma to_zmod_spec (z : ℤ_[p]) : z - (to_zmod z : ℤ_[p]) ∈ maximal_ideal ℤ_[p] := begin convert sub_zmod_repr_mem z using 2, dsimp [to_zmod, to_zmod_hom], unfreezingI { rcases (exists_eq_add_of_lt (hp_prime.pos)) with ⟨p', rfl⟩ }, change ↑(zmod.val _) = _, simp only [zmod.val_cast_nat, add_zero, add_def, cast_inj, zero_add], apply mod_eq_of_lt, simpa only [zero_add] using zmod_repr_lt_p z, end lemma ker_to_zmod : (to_zmod : ℤ_[p] →+* zmod p).ker = maximal_ideal ℤ_[p] := begin ext x, rw ring_hom.mem_ker, split, { intro h, simpa only [h, zmod.cast_zero, sub_zero] using to_zmod_spec x, }, { intro h, rw ← sub_zero x at h, dsimp [to_zmod, to_zmod_hom], convert zmod_congr_of_sub_mem_max_ideal x _ 0 _ h, apply sub_zmod_repr_mem, } end /-- `appr n x` gives a value `v : ℕ` such that `x` and `↑v : ℤ_p` are congruent mod `p^n`. See `appr_spec`. -/ noncomputable def appr : ℤ_[p] → ℕ → ℕ | x 0 := 0 | x (n+1) := let y := x - appr x n in if hy : y = 0 then appr x n else let u := unit_coeff hy in appr x n + p ^ n * (to_zmod ((u : ℤ_[p]) * (p ^ (y.valuation - n).nat_abs))).val lemma appr_lt (x : ℤ_[p]) (n : ℕ) : x.appr n < p ^ n := begin induction n with n ih generalizing x, { simp only [appr, succ_pos', pow_zero], }, simp only [appr, ring_hom.map_nat_cast, zmod.cast_self, ring_hom.map_pow, int.nat_abs, ring_hom.map_mul], have hp : p ^ n < p ^ (n + 1), { apply pow_lt_pow hp_prime.one_lt (lt_add_one n) }, split_ifs with h, { apply lt_trans (ih _) hp, }, { calc _ < p ^ n + p ^ n * (p - 1) : _ ... = p ^ (n + 1) : _, { apply add_lt_add_of_lt_of_le (ih _), apply nat.mul_le_mul_left, apply le_pred_of_lt, apply zmod.val_lt }, { rw [nat.mul_sub_left_distrib, mul_one, ← pow_succ'], apply nat.add_sub_cancel' (le_of_lt hp) } } end lemma appr_mono (x : ℤ_[p]) : monotone x.appr := begin apply monotone_of_monotone_nat, intro n, dsimp [appr], split_ifs, { refl, }, apply nat.le_add_right, end lemma dvd_appr_sub_appr (x : ℤ_[p]) (m n : ℕ) (h : m ≤ n) : p ^ m ∣ x.appr n - x.appr m := begin obtain ⟨k, rfl⟩ := nat.exists_eq_add_of_le h, clear h, induction k with k ih, { simp only [add_zero, nat.sub_self, dvd_zero], }, rw [nat.succ_eq_add_one, ← add_assoc], dsimp [appr], split_ifs with h, { exact ih }, rw [add_comm, nat.add_sub_assoc (appr_mono _ (nat.le_add_right m k))], apply dvd_add _ ih, apply dvd_mul_of_dvd_left, apply pow_dvd_pow _ (nat.le_add_right m k), end lemma appr_spec (n : ℕ) : ∀ (x : ℤ_[p]), x - appr x n ∈ (ideal.span {p^n} : ideal ℤ_[p]) := begin simp only [ideal.mem_span_singleton], induction n with n ih, { simp only [is_unit_one, is_unit.dvd, pow_zero, forall_true_iff], }, { intro x, dsimp only [appr], split_ifs with h, { rw h, apply dvd_zero }, { push_cast, rw sub_add_eq_sub_sub, obtain ⟨c, hc⟩ := ih x, simp only [ring_hom.map_nat_cast, zmod.cast_self, ring_hom.map_pow, ring_hom.map_mul, zmod.nat_cast_val], have hc' : c ≠ 0, { rintro rfl, simp only [mul_zero] at hc, contradiction }, conv_rhs { congr, simp only [hc], }, rw show (x - ↑(appr x n)).valuation = (↑p ^ n * c).valuation, { rw hc }, rw [valuation_p_pow_mul _ _ hc', add_sub_cancel', pow_succ', ← mul_sub], apply mul_dvd_mul_left, by_cases hc0 : c.valuation.nat_abs = 0, { simp only [hc0, mul_one, pow_zero], rw [mul_comm, unit_coeff_spec h] at hc, suffices : c = unit_coeff h, { rw [← this, ← ideal.mem_span_singleton, ← maximal_ideal_eq_span_p], apply to_zmod_spec }, obtain ⟨c, rfl⟩ : is_unit c, -- TODO: write a can_lift instance for units { rw int.nat_abs_eq_zero at hc0, rw [is_unit_iff, norm_eq_pow_val hc', hc0, neg_zero, fpow_zero], }, rw discrete_valuation_ring.unit_mul_pow_congr_unit _ _ _ _ _ hc, exact irreducible_p }, { rw [zero_pow (nat.pos_of_ne_zero hc0)], simp only [sub_zero, zmod.cast_zero, mul_zero], rw unit_coeff_spec hc', apply dvd_mul_of_dvd_right, apply dvd_pow (dvd_refl _), exact hc0 } } } end attribute [irreducible] appr /-- A ring hom from `ℤ_[p]` to `zmod (p^n)`, with underlying function `padic_int.appr n`. -/ def to_zmod_pow (n : ℕ) : ℤ_[p] →+* zmod (p ^ n) := to_zmod_hom (p^n) (λ x, appr x n) (by { intros, convert appr_spec n _ using 1, simp }) (by { intros x a b ha hb, apply zmod_congr_of_sub_mem_span n x a b, { simpa using ha }, { simpa using hb } }) lemma ker_to_zmod_pow (n : ℕ) : (to_zmod_pow n : ℤ_[p] →+* zmod (p ^ n)).ker = ideal.span {p ^ n} := begin ext x, rw ring_hom.mem_ker, split, { intro h, suffices : x.appr n = 0, { convert appr_spec n x, simp only [this, sub_zero, cast_zero], }, dsimp [to_zmod_pow, to_zmod_hom] at h, rw zmod.nat_coe_zmod_eq_zero_iff_dvd at h, apply eq_zero_of_dvd_of_lt h (appr_lt _ _), }, { intro h, rw ← sub_zero x at h, dsimp [to_zmod_pow, to_zmod_hom], rw [zmod_congr_of_sub_mem_span n x _ 0 _ h, cast_zero], apply appr_spec, } end @[simp] lemma zmod_cast_comp_to_zmod_pow (m n : ℕ) (h : m ≤ n) : (zmod.cast_hom (pow_dvd_pow p h) (zmod (p ^ m))).comp (to_zmod_pow n) = to_zmod_pow m := begin apply zmod.ring_hom_eq_of_ker_eq, ext x, rw [ring_hom.mem_ker, ring_hom.mem_ker], simp only [function.comp_app, zmod.cast_hom_apply, ring_hom.coe_comp], simp only [to_zmod_pow, to_zmod_hom, ring_hom.coe_mk], rw [zmod.cast_nat_cast (pow_dvd_pow p h), zmod_congr_of_sub_mem_span m (x.appr n) (x.appr n) (x.appr m)], { rw [sub_self], apply ideal.zero_mem _, }, { rw ideal.mem_span_singleton, rcases dvd_appr_sub_appr x m n h with ⟨c, hc⟩, use c, rw [← nat.cast_sub (appr_mono _ h), hc, nat.cast_mul, nat.cast_pow], }, { apply_instance } end @[simp] lemma cast_to_zmod_pow (m n : ℕ) (h : m ≤ n) (x : ℤ_[p]) : ↑(to_zmod_pow n x) = to_zmod_pow m x := by { rw ← zmod_cast_comp_to_zmod_pow _ _ h, refl } lemma dense_range_nat_cast : dense_range (nat.cast : ℕ → ℤ_[p]) := begin intro x, rw metric.mem_closure_range_iff, intros ε hε, obtain ⟨n, hn⟩ := exists_pow_neg_lt p hε, use (x.appr n), rw dist_eq_norm, apply lt_of_le_of_lt _ hn, rw norm_le_pow_iff_mem_span_pow, apply appr_spec, end lemma dense_range_int_cast : dense_range (int.cast : ℤ → ℤ_[p]) := begin intro x, apply dense_range_nat_cast.induction_on x, { exact is_closed_closure, }, { intro a, change (a.cast : ℤ_[p]) with (a : ℤ).cast, apply subset_closure, exact set.mem_range_self _ } end end ring_homs section lift /-! ### Universal property as projective limit -/ open cau_seq padic_seq variables {R : Type*} [comm_ring R] (f : Π k : ℕ, R →+* zmod (p^k)) (f_compat : ∀ k1 k2 (hk : k1 ≤ k2), (zmod.cast_hom (pow_dvd_pow p hk) _).comp (f k2) = f k1) omit hp_prime /-- Given a family of ring homs `f : Π n : ℕ, R →+* zmod (p ^ n)`, `nth_hom f r` is an integer-valued sequence whose `n`th value is the unique integer `k` such that `0 ≤ k < p ^ n` and `f n r = (k : zmod (p ^ n))`. -/ def nth_hom (r : R) : ℕ → ℤ := λ n, (f n r : zmod (p^n)).val @[simp] lemma nth_hom_zero : nth_hom f 0 = 0 := by simp [nth_hom]; refl variable {f} include hp_prime include f_compat lemma pow_dvd_nth_hom_sub (r : R) (i j : ℕ) (h : i ≤ j) : ↑p ^ i ∣ nth_hom f r j - nth_hom f r i := begin specialize f_compat (i) (j) h, rw [← int.coe_nat_pow, ← zmod.int_coe_zmod_eq_zero_iff_dvd, int.cast_sub], dsimp [nth_hom], rw [← f_compat, ring_hom.comp_apply], have : fact (p ^ (i) > 0) := pow_pos (nat.prime.pos ‹_›) _, have : fact (p ^ (j) > 0) := pow_pos (nat.prime.pos ‹_›) _, unfreezingI { simp only [zmod.cast_id, zmod.cast_hom_apply, sub_self, zmod.nat_cast_val], }, end lemma is_cau_seq_nth_hom (r : R): is_cau_seq (padic_norm p) (λ n, nth_hom f r n) := begin intros ε hε, obtain ⟨k, hk⟩ : ∃ k : ℕ, (p ^ - (↑(k : ℕ) : ℤ) : ℚ) < ε := exists_pow_neg_lt_rat p hε, use k, intros j hj, refine lt_of_le_of_lt _ hk, norm_cast, rw ← padic_norm.dvd_iff_norm_le, exact_mod_cast pow_dvd_nth_hom_sub f_compat r k j hj end /-- `nth_hom_seq f_compat r` bundles `padic_int.nth_hom f r` as a Cauchy sequence of rationals with respect to the `p`-adic norm. The `n`th value of the sequence is `((f n r).val : ℚ)`. -/ def nth_hom_seq (r : R) : padic_seq p := ⟨λ n, nth_hom f r n, is_cau_seq_nth_hom f_compat r⟩ lemma nth_hom_seq_one : nth_hom_seq f_compat 1 ≈ 1 := begin intros ε hε, change _ < _ at hε, use 1, intros j hj, haveI : fact (1 < p^j) := nat.one_lt_pow _ _ (by linarith) (nat.prime.one_lt ‹_›), simp [nth_hom_seq, nth_hom, zmod.val_one, hε], end lemma nth_hom_seq_add (r s : R) : nth_hom_seq f_compat (r + s) ≈ nth_hom_seq f_compat r + nth_hom_seq f_compat s := begin intros ε hε, obtain ⟨n, hn⟩ := exists_pow_neg_lt_rat p hε, use n, intros j hj, dsimp [nth_hom_seq], apply lt_of_le_of_lt _ hn, rw [← int.cast_add, ← int.cast_sub, ← padic_norm.dvd_iff_norm_le, ← zmod.int_coe_zmod_eq_zero_iff_dvd], dsimp [nth_hom], have : fact (p ^ n > 0) := pow_pos (nat.prime.pos ‹_›) _, have : fact (p ^ j > 0) := pow_pos (nat.prime.pos ‹_›) _, unfreezingI { simp only [int.cast_coe_nat, int.cast_add, ring_hom.map_add, int.cast_sub, zmod.nat_cast_val] }, rw [zmod.cast_add (show p ^ n ∣ p ^ j, from _), sub_self], { apply_instance }, { apply pow_dvd_pow, linarith only [hj] }, end lemma nth_hom_seq_mul (r s : R) : nth_hom_seq f_compat (r * s) ≈ nth_hom_seq f_compat r * nth_hom_seq f_compat s := begin intros ε hε, obtain ⟨n, hn⟩ := exists_pow_neg_lt_rat p hε, use n, intros j hj, dsimp [nth_hom_seq], apply lt_of_le_of_lt _ hn, rw [← int.cast_mul, ← int.cast_sub, ← padic_norm.dvd_iff_norm_le, ← zmod.int_coe_zmod_eq_zero_iff_dvd], dsimp [nth_hom], have : fact (p ^ n > 0) := pow_pos (nat.prime.pos ‹_›) _, have : fact (p ^ j > 0) := pow_pos (nat.prime.pos ‹_›) _, unfreezingI { simp only [int.cast_coe_nat, int.cast_mul, int.cast_sub, ring_hom.map_mul, zmod.nat_cast_val] }, rw [zmod.cast_mul (show p ^ n ∣ p ^ j, from _), sub_self], { apply_instance }, { apply pow_dvd_pow, linarith only [hj] }, end /-- `lim_nth_hom f_compat r` is the limit of a sequence `f` of compatible ring homs `R →+* zmod (p^k)`. This is itself a ring hom: see `padic_int.lift`. -/ def lim_nth_hom (r : R) : ℤ_[p] := of_int_seq (nth_hom f r) (is_cau_seq_nth_hom f_compat r) lemma lim_nth_hom_spec (r : R) : ∀ ε : ℝ, 0 < ε → ∃ N : ℕ, ∀ n ≥ N, ∥lim_nth_hom f_compat r - nth_hom f r n∥ < ε := begin intros ε hε, obtain ⟨ε', hε'0, hε'⟩ : ∃ v : ℚ, (0 : ℝ) < v ∧ ↑v < ε := exists_rat_btwn hε, norm_cast at hε'0, obtain ⟨N, hN⟩ := padic_norm_e.defn (nth_hom_seq f_compat r) hε'0, use N, intros n hn, apply lt_trans _ hε', change ↑(padic_norm_e _) < _, norm_cast, convert hN _ hn, simp [nth_hom, lim_nth_hom, nth_hom_seq, of_int_seq], end lemma lim_nth_hom_zero : lim_nth_hom f_compat 0 = 0 := by simp [lim_nth_hom]; refl lemma lim_nth_hom_one : lim_nth_hom f_compat 1 = 1 := subtype.ext $ quot.sound $ nth_hom_seq_one _ lemma lim_nth_hom_add (r s : R) : lim_nth_hom f_compat (r + s) = lim_nth_hom f_compat r + lim_nth_hom f_compat s := subtype.ext $ quot.sound $ nth_hom_seq_add _ _ _ lemma lim_nth_hom_mul (r s : R) : lim_nth_hom f_compat (r * s) = lim_nth_hom f_compat r * lim_nth_hom f_compat s := subtype.ext $ quot.sound $ nth_hom_seq_mul _ _ _ -- TODO: generalize this to arbitrary complete discrete valuation rings /-- `lift f_compat` is the limit of a sequence `f` of compatible ring homs `R →+* zmod (p^k)`, with the equality `lift f_compat r = padic_int.lim_nth_hom f_compat r`. -/ def lift : R →+* ℤ_[p] := { to_fun := lim_nth_hom f_compat, map_one' := lim_nth_hom_one f_compat, map_mul' := lim_nth_hom_mul f_compat, map_zero' := lim_nth_hom_zero f_compat, map_add' := lim_nth_hom_add f_compat } omit f_compat lemma lift_sub_val_mem_span (r : R) (n : ℕ) : (lift f_compat r - (f n r).val) ∈ (ideal.span {↑p ^ n} : ideal ℤ_[p]) := begin obtain ⟨k, hk⟩ := lim_nth_hom_spec f_compat r _ (show (0 : ℝ) < p ^ (-n : ℤ), from nat.fpow_pos_of_pos hp_prime.pos _), have := le_of_lt (hk (max n k) (le_max_right _ _)), rw norm_le_pow_iff_mem_span_pow at this, dsimp [lift], rw sub_eq_sub_add_sub (lim_nth_hom f_compat r) _ ↑(nth_hom f r (max n k)), apply ideal.add_mem _ _ this, rw [ideal.mem_span_singleton], simpa only [ring_hom.eq_int_cast, ring_hom.map_pow, int.cast_sub] using (int.cast_ring_hom ℤ_[p]).map_dvd (pow_dvd_nth_hom_sub f_compat r n (max n k) (le_max_left _ _)), end /-- One part of the universal property of `ℤ_[p]` as a projective limit. See also `padic_int.lift_unique`. -/ lemma lift_spec (n : ℕ) : (to_zmod_pow n).comp (lift f_compat) = f n := begin ext r, haveI : fact (0 < p ^ n) := pow_pos (nat.prime.pos ‹_›) n, rw [ring_hom.comp_apply, ← zmod.cast_val (f n r), ← (to_zmod_pow n).map_nat_cast, ← sub_eq_zero, ← ring_hom.map_sub, ← ring_hom.mem_ker, ker_to_zmod_pow], apply lift_sub_val_mem_span, end /-- One part of the universal property of `ℤ_[p]` as a projective limit. See also `padic_int.lift_spec`. -/ lemma lift_unique (g : R →+* ℤ_[p]) (hg : ∀ n, (to_zmod_pow n).comp g = f n) : lift f_compat = g := begin ext1 r, apply eq_of_forall_dist_le, intros ε hε, obtain ⟨n, hn⟩ := exists_pow_neg_lt p hε, apply le_trans _ (le_of_lt hn), rw [dist_eq_norm, norm_le_pow_iff_mem_span_pow, ← ker_to_zmod_pow, ring_hom.mem_ker, ring_hom.map_sub, ← ring_hom.comp_apply, ← ring_hom.comp_apply, lift_spec, hg, sub_self], end @[simp] lemma lift_self (z : ℤ_[p]) : @lift p _ ℤ_[p] _ to_zmod_pow zmod_cast_comp_to_zmod_pow z = z := begin show _ = ring_hom.id _ z, rw @lift_unique p _ ℤ_[p] _ _ zmod_cast_comp_to_zmod_pow (ring_hom.id ℤ_[p]), intro, rw ring_hom.comp_id, end end lift lemma ext_of_to_zmod_pow {x y : ℤ_[p]} : (∀ n, to_zmod_pow n x = to_zmod_pow n y) ↔ x = y := begin split, { intro h, rw [← lift_self x, ← lift_self y], simp [lift, lim_nth_hom, nth_hom, h] }, { rintro rfl _, refl } end lemma to_zmod_pow_eq_iff_ext {R : Type*} [comm_ring R] {g g' : R →+* ℤ_[p]} : (∀ n, (to_zmod_pow n).comp g = (to_zmod_pow n).comp g') ↔ g = g' := begin split, { intro hg, ext x : 1, apply ext_of_to_zmod_pow.mp, intro n, show (to_zmod_pow n).comp g x = (to_zmod_pow n).comp g' x, rw hg n }, { rintro rfl _, refl } end end padic_int
51e7efa98a4a1ac386084b56b51299cd34a52aca
367134ba5a65885e863bdc4507601606690974c1
/src/algebra/associated.lean
61da2f393e4a587d8591bd81ecc9c82f31a8e059
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
28,686
lean
/- 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, Jens Wagemaker -/ import data.multiset.basic import algebra.divisibility /-! # Associated, prime, and irreducible elements. -/ variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} lemma is_unit.pow [monoid α] {a : α} (n : ℕ) : is_unit a → is_unit (a ^ n) := λ ⟨u, hu⟩, ⟨u ^ n, by simp *⟩ theorem is_unit_iff_dvd_one [comm_monoid α] {x : α} : is_unit x ↔ x ∣ 1 := ⟨by rintro ⟨u, rfl⟩; exact ⟨_, u.mul_inv.symm⟩, λ ⟨y, h⟩, ⟨⟨x, y, h.symm, by rw [h, mul_comm]⟩, rfl⟩⟩ theorem is_unit_iff_forall_dvd [comm_monoid α] {x : α} : is_unit x ↔ ∀ y, x ∣ y := is_unit_iff_dvd_one.trans ⟨λ h y, dvd.trans h (one_dvd _), λ h, h _⟩ theorem is_unit_of_dvd_unit {α} [comm_monoid α] {x y : α} (xy : x ∣ y) (hu : is_unit y) : is_unit x := is_unit_iff_dvd_one.2 $ dvd_trans xy $ is_unit_iff_dvd_one.1 hu theorem is_unit_int {n : ℤ} : is_unit n ↔ n.nat_abs = 1 := ⟨begin rintro ⟨u, rfl⟩, exact (int.units_eq_one_or u).elim (by simp) (by simp) end, λ h, is_unit_iff_dvd_one.2 ⟨n, by rw [← int.nat_abs_mul_self, h]; refl⟩⟩ lemma is_unit_of_dvd_one [comm_monoid α] : ∀a ∣ 1, is_unit (a:α) | a ⟨b, eq⟩ := ⟨units.mk_of_mul_eq_one a b eq.symm, rfl⟩ lemma dvd_and_not_dvd_iff [comm_cancel_monoid_with_zero α] {x y : α} : x ∣ y ∧ ¬y ∣ x ↔ dvd_not_unit x y := ⟨λ ⟨⟨d, hd⟩, hyx⟩, ⟨λ hx0, by simpa [hx0] using hyx, ⟨d, mt is_unit_iff_dvd_one.1 (λ ⟨e, he⟩, hyx ⟨e, by rw [hd, mul_assoc, ← he, mul_one]⟩), hd⟩⟩, λ ⟨hx0, d, hdu, hdx⟩, ⟨⟨d, hdx⟩, λ ⟨e, he⟩, hdu (is_unit_of_dvd_one _ ⟨e, mul_left_cancel' hx0 $ by conv {to_lhs, rw [he, hdx]};simp [mul_assoc]⟩)⟩⟩ lemma pow_dvd_pow_iff [comm_cancel_monoid_with_zero α] {x : α} {n m : ℕ} (h0 : x ≠ 0) (h1 : ¬ is_unit x) : x ^ n ∣ x ^ m ↔ n ≤ m := begin split, { intro h, rw [← not_lt], intro hmn, apply h1, have : x ^ m * x ∣ x ^ m * 1, { rw [← pow_succ', mul_one], exact dvd_trans (pow_dvd_pow _ (nat.succ_le_of_lt hmn)) h }, rwa [mul_dvd_mul_iff_left, ← is_unit_iff_dvd_one] at this, apply pow_ne_zero m h0 }, { apply pow_dvd_pow } end section prime variables [comm_monoid_with_zero α] /-- prime element of a `comm_monoid_with_zero` -/ def prime (p : α) : Prop := p ≠ 0 ∧ ¬ is_unit p ∧ (∀a b, p ∣ a * b → p ∣ a ∨ p ∣ b) namespace prime variables {p : α} (hp : prime p) lemma ne_zero (hp : prime p) : p ≠ 0 := hp.1 lemma not_unit (hp : prime p) : ¬ is_unit p := hp.2.1 lemma ne_one (hp : prime p) : p ≠ 1 := λ h, hp.2.1 (h.symm ▸ is_unit_one) lemma div_or_div (hp : prime p) {a b : α} (h : p ∣ a * b) : p ∣ a ∨ p ∣ b := hp.2.2 a b h lemma dvd_of_dvd_pow (hp : prime p) {a : α} {n : ℕ} (h : p ∣ a^n) : p ∣ a := begin induction n with n ih, { rw pow_zero at h, have := is_unit_of_dvd_one _ h, have := not_unit hp, contradiction }, rw pow_succ at h, cases div_or_div hp h with dvd_a dvd_pow, { assumption }, exact ih dvd_pow end end prime @[simp] lemma not_prime_zero : ¬ prime (0 : α) := λ h, h.ne_zero rfl @[simp] lemma not_prime_one : ¬ prime (1 : α) := λ h, h.not_unit is_unit_one lemma exists_mem_multiset_dvd_of_prime {s : multiset α} {p : α} (hp : prime p) : p ∣ s.prod → ∃a∈s, p ∣ a := multiset.induction_on s (assume h, (hp.not_unit $ is_unit_of_dvd_one _ h).elim) $ assume a s ih h, have p ∣ a * s.prod, by simpa using h, match hp.div_or_div this with | or.inl h := ⟨a, multiset.mem_cons_self a s, h⟩ | or.inr h := let ⟨a, has, h⟩ := ih h in ⟨a, multiset.mem_cons_of_mem has, h⟩ end end prime lemma left_dvd_or_dvd_right_of_dvd_prime_mul [comm_cancel_monoid_with_zero α] {a : α} : ∀ {b p : α}, prime p → a ∣ p * b → p ∣ a ∨ a ∣ b := begin rintros b p hp ⟨c, hc⟩, rcases hp.2.2 a c (hc ▸ dvd_mul_right _ _) with h | ⟨x, rfl⟩, { exact or.inl h }, { rw [mul_left_comm, mul_right_inj' hp.ne_zero] at hc, exact or.inr (hc.symm ▸ dvd_mul_right _ _) } end /-- `irreducible p` states that `p` is non-unit and only factors into units. We explicitly avoid stating that `p` is non-zero, this would require a semiring. Assuming only a monoid allows us to reuse irreducible for associated elements. -/ class irreducible [monoid α] (p : α) : Prop := (not_unit' : ¬ is_unit p) (is_unit_or_is_unit' : ∀a b, p = a * b → is_unit a ∨ is_unit b) namespace irreducible lemma not_unit [monoid α] {p : α} (hp : irreducible p) : ¬ is_unit p := hp.1 lemma is_unit_or_is_unit [monoid α] {p : α} (hp : irreducible p) {a b : α} (h : p = a * b) : is_unit a ∨ is_unit b := irreducible.is_unit_or_is_unit' a b h end irreducible lemma irreducible_iff [monoid α] {p : α} : irreducible p ↔ ¬ is_unit p ∧ ∀a b, p = a * b → is_unit a ∨ is_unit b := ⟨λ h, ⟨h.1, h.2⟩, λ h, ⟨h.1, h.2⟩⟩ @[simp] theorem not_irreducible_one [monoid α] : ¬ irreducible (1 : α) := by simp [irreducible_iff] @[simp] theorem not_irreducible_zero [monoid_with_zero α] : ¬ irreducible (0 : α) | ⟨hn0, h⟩ := have is_unit (0:α) ∨ is_unit (0:α), from h 0 0 ((mul_zero 0).symm), this.elim hn0 hn0 theorem irreducible.ne_zero [monoid_with_zero α] : ∀ {p:α}, irreducible p → p ≠ 0 | _ hp rfl := not_irreducible_zero hp theorem of_irreducible_mul {α} [monoid α] {x y : α} : irreducible (x * y) → is_unit x ∨ is_unit y | ⟨_, h⟩ := h _ _ rfl theorem irreducible_or_factor {α} [monoid α] (x : α) (h : ¬ is_unit x) : irreducible x ∨ ∃ a b, ¬ is_unit a ∧ ¬ is_unit b ∧ a * b = x := begin haveI := classical.dec, refine or_iff_not_imp_right.2 (λ H, _), simp [h, irreducible_iff] at H ⊢, refine λ a b h, classical.by_contradiction $ λ o, _, simp [not_or_distrib] at o, exact H _ o.1 _ o.2 h.symm end lemma irreducible_of_prime [comm_cancel_monoid_with_zero α] {p : α} (hp : prime p) : irreducible p := ⟨hp.not_unit, λ a b hab, (show a * b ∣ a ∨ a * b ∣ b, from hab ▸ hp.div_or_div (hab ▸ (dvd_refl _))).elim (λ ⟨x, hx⟩, or.inr (is_unit_iff_dvd_one.2 ⟨x, mul_right_cancel' (show a ≠ 0, from λ h, by simp [*, prime] at *) $ by conv {to_lhs, rw hx}; simp [mul_comm, mul_assoc, mul_left_comm]⟩)) (λ ⟨x, hx⟩, or.inl (is_unit_iff_dvd_one.2 ⟨x, mul_right_cancel' (show b ≠ 0, from λ h, by simp [*, prime] at *) $ by conv {to_lhs, rw hx}; simp [mul_comm, mul_assoc, mul_left_comm]⟩))⟩ lemma succ_dvd_or_succ_dvd_of_succ_sum_dvd_mul [comm_cancel_monoid_with_zero α] {p : α} (hp : prime p) {a b : α} {k l : ℕ} : p ^ k ∣ a → p ^ l ∣ b → p ^ ((k + l) + 1) ∣ a * b → p ^ (k + 1) ∣ a ∨ p ^ (l + 1) ∣ b := λ ⟨x, hx⟩ ⟨y, hy⟩ ⟨z, hz⟩, have h : p ^ (k + l) * (x * y) = p ^ (k + l) * (p * z), by simpa [mul_comm, pow_add, hx, hy, mul_assoc, mul_left_comm] using hz, have hp0: p ^ (k + l) ≠ 0, from pow_ne_zero _ hp.ne_zero, have hpd : p ∣ x * y, from ⟨z, by rwa [mul_right_inj' hp0] at h⟩, (hp.div_or_div hpd).elim (λ ⟨d, hd⟩, or.inl ⟨d, by simp [*, pow_succ, mul_comm, mul_left_comm, mul_assoc]⟩) (λ ⟨d, hd⟩, or.inr ⟨d, by simp [*, pow_succ, mul_comm, mul_left_comm, mul_assoc]⟩) /-- If `p` and `q` are irreducible, then `p ∣ q` implies `q ∣ p`. -/ lemma dvd_symm_of_irreducible [monoid α] {p q : α} (hp : irreducible p) (hq : irreducible q) : p ∣ q → q ∣ p := begin tactic.unfreeze_local_instances, rintros ⟨q', rfl⟩, rw is_unit.mul_right_dvd (or.resolve_left (of_irreducible_mul hq) hp.not_unit), end lemma dvd_symm_iff_of_irreducible [monoid α] {p q : α} (hp : irreducible p) (hq : irreducible q) : p ∣ q ↔ q ∣ p := ⟨dvd_symm_of_irreducible hp hq, dvd_symm_of_irreducible hq hp⟩ /-- Two elements of a `monoid` are `associated` if one of them is another one multiplied by a unit on the right. -/ def associated [monoid α] (x y : α) : Prop := ∃u:units α, x * u = y local infix ` ~ᵤ ` : 50 := associated namespace associated @[refl] protected theorem refl [monoid α] (x : α) : x ~ᵤ x := ⟨1, by simp⟩ @[symm] protected theorem symm [monoid α] : ∀{x y : α}, x ~ᵤ y → y ~ᵤ x | x _ ⟨u, rfl⟩ := ⟨u⁻¹, by rw [mul_assoc, units.mul_inv, mul_one]⟩ @[trans] protected theorem trans [monoid α] : ∀{x y z : α}, x ~ᵤ y → y ~ᵤ z → x ~ᵤ z | x _ _ ⟨u, rfl⟩ ⟨v, rfl⟩ := ⟨u * v, by rw [units.coe_mul, mul_assoc]⟩ /-- The setoid of the relation `x ~ᵤ y` iff there is a unit `u` such that `x * u = y` -/ protected def setoid (α : Type*) [monoid α] : setoid α := { r := associated, iseqv := ⟨associated.refl, λa b, associated.symm, λa b c, associated.trans⟩ } end associated local attribute [instance] associated.setoid theorem unit_associated_one [monoid α] {u : units α} : (u : α) ~ᵤ 1 := ⟨u⁻¹, units.mul_inv u⟩ theorem associated_one_iff_is_unit [monoid α] {a : α} : (a : α) ~ᵤ 1 ↔ is_unit a := iff.intro (assume h, let ⟨c, h⟩ := h.symm in h ▸ ⟨c, (one_mul _).symm⟩) (assume ⟨c, h⟩, associated.symm ⟨c, by simp [h]⟩) theorem associated_zero_iff_eq_zero [monoid_with_zero α] (a : α) : a ~ᵤ 0 ↔ a = 0 := iff.intro (assume h, let ⟨u, h⟩ := h.symm in by simpa using h.symm) (assume h, h ▸ associated.refl a) theorem associated_one_of_mul_eq_one [comm_monoid α] {a : α} (b : α) (hab : a * b = 1) : a ~ᵤ 1 := show (units.mk_of_mul_eq_one a b hab : α) ~ᵤ 1, from unit_associated_one theorem associated_one_of_associated_mul_one [comm_monoid α] {a b : α} : a * b ~ᵤ 1 → a ~ᵤ 1 | ⟨u, h⟩ := associated_one_of_mul_eq_one (b * u) $ by simpa [mul_assoc] using h lemma associated_mul_mul [comm_monoid α] {a₁ a₂ b₁ b₂ : α} : a₁ ~ᵤ b₁ → a₂ ~ᵤ b₂ → (a₁ * a₂) ~ᵤ (b₁ * b₂) | ⟨c₁, h₁⟩ ⟨c₂, h₂⟩ := ⟨c₁ * c₂, by simp [h₁.symm, h₂.symm, mul_assoc, mul_comm, mul_left_comm]⟩ lemma associated_pow_pow [comm_monoid α] {a b : α} {n : ℕ} (h : a ~ᵤ b) : a ^ n ~ᵤ b ^ n := begin induction n with n ih, { simp [h] }, convert associated_mul_mul h ih, end lemma dvd_of_associated [monoid α] {a b : α} : a ~ᵤ b → a ∣ b := λ ⟨u, hu⟩, ⟨u, hu.symm⟩ lemma dvd_dvd_of_associated [monoid α] {a b : α} (h : a ~ᵤ b) : a ∣ b ∧ b ∣ a := ⟨dvd_of_associated h, dvd_of_associated h.symm⟩ theorem associated_of_dvd_dvd [cancel_monoid_with_zero α] {a b : α} (hab : a ∣ b) (hba : b ∣ a) : a ~ᵤ b := begin rcases hab with ⟨c, rfl⟩, rcases hba with ⟨d, a_eq⟩, by_cases ha0 : a = 0, { simp [*] at * }, have hac0 : a * c ≠ 0, { intro con, rw [con, zero_mul] at a_eq, apply ha0 a_eq, }, have : a * (c * d) = a * 1 := by rw [← mul_assoc, ← a_eq, mul_one], have hcd : (c * d) = 1, from mul_left_cancel' ha0 this, have : a * c * (d * c) = a * c * 1 := by rw [← mul_assoc, ← a_eq, mul_one], have hdc : d * c = 1, from mul_left_cancel' hac0 this, exact ⟨⟨c, d, hcd, hdc⟩, rfl⟩ end theorem dvd_dvd_iff_associated [cancel_monoid_with_zero α] {a b : α} : a ∣ b ∧ b ∣ a ↔ a ~ᵤ b := ⟨λ ⟨h1, h2⟩, associated_of_dvd_dvd h1 h2, dvd_dvd_of_associated⟩ lemma exists_associated_mem_of_dvd_prod [comm_cancel_monoid_with_zero α] {p : α} (hp : prime p) {s : multiset α} : (∀ r ∈ s, prime r) → p ∣ s.prod → ∃ q ∈ s, p ~ᵤ q := multiset.induction_on s (by simp [mt is_unit_iff_dvd_one.2 hp.not_unit]) (λ a s ih hs hps, begin rw [multiset.prod_cons] at hps, cases hp.div_or_div hps with h h, { use [a, by simp], cases h with u hu, cases ((irreducible_of_prime (hs a (multiset.mem_cons.2 (or.inl rfl)))).is_unit_or_is_unit hu).resolve_left hp.not_unit with v hv, exact ⟨v, by simp [hu, hv]⟩ }, { rcases ih (λ r hr, hs _ (multiset.mem_cons.2 (or.inr hr))) h with ⟨q, hq₁, hq₂⟩, exact ⟨q, multiset.mem_cons.2 (or.inr hq₁), hq₂⟩ } end) lemma dvd_iff_dvd_of_rel_left [comm_monoid_with_zero α] {a b c : α} (h : a ~ᵤ b) : a ∣ c ↔ b ∣ c := let ⟨u, hu⟩ := h in hu ▸ units.mul_right_dvd.symm lemma dvd_iff_dvd_of_rel_right [comm_monoid_with_zero α] {a b c : α} (h : b ~ᵤ c) : a ∣ b ↔ a ∣ c := let ⟨u, hu⟩ := h in hu ▸ units.dvd_mul_right.symm lemma eq_zero_iff_of_associated [comm_monoid_with_zero α] {a b : α} (h : a ~ᵤ b) : a = 0 ↔ b = 0 := ⟨λ ha, let ⟨u, hu⟩ := h in by simp [hu.symm, ha], λ hb, let ⟨u, hu⟩ := h.symm in by simp [hu.symm, hb]⟩ lemma ne_zero_iff_of_associated [comm_monoid_with_zero α] {a b : α} (h : a ~ᵤ b) : a ≠ 0 ↔ b ≠ 0 := by haveI := classical.dec; exact not_iff_not.2 (eq_zero_iff_of_associated h) lemma prime_of_associated [comm_monoid_with_zero α] {p q : α} (h : p ~ᵤ q) (hp : prime p) : prime q := ⟨(ne_zero_iff_of_associated h).1 hp.ne_zero, let ⟨u, hu⟩ := h in ⟨λ ⟨v, hv⟩, hp.not_unit ⟨v * u⁻¹, by simp [hv, hu.symm]⟩, hu ▸ by { simp [units.mul_right_dvd], intros a b, exact hp.div_or_div }⟩⟩ lemma prime_iff_of_associated [comm_monoid_with_zero α] {p q : α} (h : p ~ᵤ q) : prime p ↔ prime q := ⟨prime_of_associated h, prime_of_associated h.symm⟩ lemma is_unit_iff_of_associated [monoid α] {a b : α} (h : a ~ᵤ b) : is_unit a ↔ is_unit b := ⟨let ⟨u, hu⟩ := h in λ ⟨v, hv⟩, ⟨v * u, by simp [hv, hu.symm]⟩, let ⟨u, hu⟩ := h.symm in λ ⟨v, hv⟩, ⟨v * u, by simp [hv, hu.symm]⟩⟩ lemma irreducible_of_associated [comm_monoid_with_zero α] {p q : α} (h : p ~ᵤ q) (hp : irreducible p) : irreducible q := ⟨mt (is_unit_iff_of_associated h).2 hp.1, let ⟨u, hu⟩ := h in λ a b hab, have hpab : p = a * (b * (u⁻¹ : units α)), from calc p = (p * u) * (u ⁻¹ : units α) : by simp ... = _ : by rw hu; simp [hab, mul_assoc], (hp.is_unit_or_is_unit hpab).elim or.inl (λ ⟨v, hv⟩, or.inr ⟨v * u, by simp [hv]⟩)⟩ lemma irreducible_iff_of_associated [comm_monoid_with_zero α] {p q : α} (h : p ~ᵤ q) : irreducible p ↔ irreducible q := ⟨irreducible_of_associated h, irreducible_of_associated h.symm⟩ lemma associated_mul_left_cancel [comm_cancel_monoid_with_zero α] {a b c d : α} (h : a * b ~ᵤ c * d) (h₁ : a ~ᵤ c) (ha : a ≠ 0) : b ~ᵤ d := let ⟨u, hu⟩ := h in let ⟨v, hv⟩ := associated.symm h₁ in ⟨u * (v : units α), mul_left_cancel' ha begin rw [← hv, mul_assoc c (v : α) d, mul_left_comm c, ← hu], simp [hv.symm, mul_assoc, mul_comm, mul_left_comm] end⟩ lemma associated_mul_right_cancel [comm_cancel_monoid_with_zero α] {a b c d : α} : a * b ~ᵤ c * d → b ~ᵤ d → b ≠ 0 → a ~ᵤ c := by rw [mul_comm a, mul_comm c]; exact associated_mul_left_cancel section unique_units variables [monoid α] [unique (units α)] theorem associated_iff_eq {x y : α} : x ~ᵤ y ↔ x = y := begin split, { rintro ⟨c, rfl⟩, simp [subsingleton.elim c 1] }, { rintro rfl, refl }, end theorem associated_eq_eq : (associated : α → α → Prop) = eq := by { ext, rw associated_iff_eq } end unique_units /-- The quotient of a monoid by the `associated` relation. Two elements `x` and `y` are associated iff there is a unit `u` such that `x * u = y`. There is a natural monoid structure on `associates α`. -/ def associates (α : Type*) [monoid α] : Type* := quotient (associated.setoid α) namespace associates open associated /-- The canonical quotient map from a monoid `α` into the `associates` of `α` -/ protected def mk {α : Type*} [monoid α] (a : α) : associates α := ⟦ a ⟧ instance [monoid α] : inhabited (associates α) := ⟨⟦1⟧⟩ theorem mk_eq_mk_iff_associated [monoid α] {a b : α} : associates.mk a = associates.mk b ↔ a ~ᵤ b := iff.intro quotient.exact quot.sound theorem quotient_mk_eq_mk [monoid α] (a : α) : ⟦ a ⟧ = associates.mk a := rfl theorem quot_mk_eq_mk [monoid α] (a : α) : quot.mk setoid.r a = associates.mk a := rfl theorem forall_associated [monoid α] {p : associates α → Prop} : (∀a, p a) ↔ (∀a, p (associates.mk a)) := iff.intro (assume h a, h _) (assume h a, quotient.induction_on a h) theorem mk_surjective [monoid α] : function.surjective (@associates.mk α _) := forall_associated.2 (λ a, ⟨a, rfl⟩) instance [monoid α] : has_one (associates α) := ⟨⟦ 1 ⟧⟩ theorem one_eq_mk_one [monoid α] : (1 : associates α) = associates.mk 1 := rfl instance [monoid α] : has_bot (associates α) := ⟨1⟩ lemma exists_rep [monoid α] (a : associates α) : ∃ a0 : α, associates.mk a0 = a := quot.exists_rep a section comm_monoid variable [comm_monoid α] instance : has_mul (associates α) := ⟨λa' b', quotient.lift_on₂ a' b' (λa b, ⟦ a * b ⟧) $ assume a₁ a₂ b₁ b₂ ⟨c₁, h₁⟩ ⟨c₂, h₂⟩, quotient.sound $ ⟨c₁ * c₂, by simp [h₁.symm, h₂.symm, mul_assoc, mul_comm, mul_left_comm]⟩⟩ theorem mk_mul_mk {x y : α} : associates.mk x * associates.mk y = associates.mk (x * y) := rfl instance : comm_monoid (associates α) := { one := 1, mul := (*), mul_one := assume a', quotient.induction_on a' $ assume a, show ⟦a * 1⟧ = ⟦ a ⟧, by simp, one_mul := assume a', quotient.induction_on a' $ assume a, show ⟦1 * a⟧ = ⟦ a ⟧, by simp, mul_assoc := assume a' b' c', quotient.induction_on₃ a' b' c' $ assume a b c, show ⟦a * b * c⟧ = ⟦a * (b * c)⟧, by rw [mul_assoc], mul_comm := assume a' b', quotient.induction_on₂ a' b' $ assume a b, show ⟦a * b⟧ = ⟦b * a⟧, by rw [mul_comm] } instance : preorder (associates α) := { le := has_dvd.dvd, le_refl := dvd_refl, le_trans := λ a b c, dvd_trans} @[simp] lemma mk_one : associates.mk (1 : α) = 1 := rfl /-- `associates.mk` as a `monoid_hom`. -/ protected def mk_monoid_hom : α →* (associates α) := ⟨associates.mk, mk_one, λ x y, mk_mul_mk⟩ @[simp] lemma mk_monoid_hom_apply (a : α) : associates.mk_monoid_hom a = associates.mk a := rfl lemma associated_map_mk {f : associates α →* α} (hinv : function.right_inverse f associates.mk) (a : α) : a ~ᵤ f (associates.mk a) := associates.mk_eq_mk_iff_associated.1 (hinv (associates.mk a)).symm lemma mk_pow (a : α) (n : ℕ) : associates.mk (a ^ n) = (associates.mk a) ^ n := by induction n; simp [*, pow_succ, associates.mk_mul_mk.symm] lemma dvd_eq_le : ((∣) : associates α → associates α → Prop) = (≤) := rfl theorem prod_mk {p : multiset α} : (p.map associates.mk).prod = associates.mk p.prod := multiset.induction_on p (by simp; refl) $ assume a s ih, by simp [ih]; refl theorem rel_associated_iff_map_eq_map {p q : multiset α} : multiset.rel associated p q ↔ p.map associates.mk = q.map associates.mk := by rw [← multiset.rel_eq]; simp [multiset.rel_map_left, multiset.rel_map_right, mk_eq_mk_iff_associated] theorem mul_eq_one_iff {x y : associates α} : x * y = 1 ↔ (x = 1 ∧ y = 1) := iff.intro (quotient.induction_on₂ x y $ assume a b h, have a * b ~ᵤ 1, from quotient.exact h, ⟨quotient.sound $ associated_one_of_associated_mul_one this, quotient.sound $ associated_one_of_associated_mul_one $ by rwa [mul_comm] at this⟩) (by simp {contextual := tt}) theorem prod_eq_one_iff {p : multiset (associates α)} : p.prod = 1 ↔ (∀a ∈ p, (a:associates α) = 1) := multiset.induction_on p (by simp) (by simp [mul_eq_one_iff, or_imp_distrib, forall_and_distrib] {contextual := tt}) theorem units_eq_one (u : units (associates α)) : u = 1 := units.ext (mul_eq_one_iff.1 u.val_inv).1 instance unique_units : unique (units (associates α)) := { default := 1, uniq := associates.units_eq_one } theorem coe_unit_eq_one (u : units (associates α)): (u : associates α) = 1 := by simp theorem is_unit_iff_eq_one (a : associates α) : is_unit a ↔ a = 1 := iff.intro (assume ⟨u, h⟩, h ▸ coe_unit_eq_one _) (assume h, h.symm ▸ is_unit_one) theorem is_unit_mk {a : α} : is_unit (associates.mk a) ↔ is_unit a := calc is_unit (associates.mk a) ↔ a ~ᵤ 1 : by rw [is_unit_iff_eq_one, one_eq_mk_one, mk_eq_mk_iff_associated] ... ↔ is_unit a : associated_one_iff_is_unit section order theorem mul_mono {a b c d : associates α} (h₁ : a ≤ b) (h₂ : c ≤ d) : a * c ≤ b * d := let ⟨x, hx⟩ := h₁, ⟨y, hy⟩ := h₂ in ⟨x * y, by simp [hx, hy, mul_comm, mul_assoc, mul_left_comm]⟩ theorem one_le {a : associates α} : 1 ≤ a := dvd.intro _ (one_mul a) theorem prod_le_prod {p q : multiset (associates α)} (h : p ≤ q) : p.prod ≤ q.prod := begin haveI := classical.dec_eq (associates α), haveI := classical.dec_eq α, suffices : p.prod ≤ (p + (q - p)).prod, { rwa [multiset.add_sub_of_le h] at this }, suffices : p.prod * 1 ≤ p.prod * (q - p).prod, { simpa }, exact mul_mono (le_refl p.prod) one_le end theorem le_mul_right {a b : associates α} : a ≤ a * b := ⟨b, rfl⟩ theorem le_mul_left {a b : associates α} : a ≤ b * a := by rw [mul_comm]; exact le_mul_right end order end comm_monoid instance [has_zero α] [monoid α] : has_zero (associates α) := ⟨⟦ 0 ⟧⟩ instance [has_zero α] [monoid α] : has_top (associates α) := ⟨0⟩ section comm_monoid_with_zero variables [comm_monoid_with_zero α] @[simp] theorem mk_eq_zero {a : α} : associates.mk a = 0 ↔ a = 0 := ⟨assume h, (associated_zero_iff_eq_zero a).1 $ quotient.exact h, assume h, h.symm ▸ rfl⟩ instance : comm_monoid_with_zero (associates α) := { zero_mul := by { rintro ⟨a⟩, show associates.mk (0 * a) = associates.mk 0, rw [zero_mul] }, mul_zero := by { rintro ⟨a⟩, show associates.mk (a * 0) = associates.mk 0, rw [mul_zero] }, .. associates.comm_monoid, .. associates.has_zero } instance [nontrivial α] : nontrivial (associates α) := ⟨⟨0, 1, assume h, have (0 : α) ~ᵤ 1, from quotient.exact h, have (0 : α) = 1, from ((associated_zero_iff_eq_zero 1).1 this.symm).symm, zero_ne_one this⟩⟩ lemma exists_non_zero_rep {a : associates α} : a ≠ 0 → ∃ a0 : α, a0 ≠ 0 ∧ associates.mk a0 = a := quotient.induction_on a (λ b nz, ⟨b, mt (congr_arg quotient.mk) nz, rfl⟩) theorem dvd_of_mk_le_mk {a b : α} : associates.mk a ≤ associates.mk b → a ∣ b | ⟨c', hc'⟩ := (quotient.induction_on c' $ assume c hc, let ⟨d, hd⟩ := (quotient.exact hc).symm in ⟨(↑d) * c, calc b = (a * c) * ↑d : hd.symm ... = a * (↑d * c) : by ac_refl⟩) hc' theorem mk_le_mk_of_dvd {a b : α} : a ∣ b → associates.mk a ≤ associates.mk b := assume ⟨c, hc⟩, ⟨associates.mk c, by simp [hc]; refl⟩ theorem mk_le_mk_iff_dvd_iff {a b : α} : associates.mk a ≤ associates.mk b ↔ a ∣ b := iff.intro dvd_of_mk_le_mk mk_le_mk_of_dvd theorem mk_dvd_mk {a b : α} : associates.mk a ∣ associates.mk b ↔ a ∣ b := iff.intro dvd_of_mk_le_mk mk_le_mk_of_dvd lemma prime.le_or_le {p : associates α} (hp : prime p) {a b : associates α} (h : p ≤ a * b) : p ≤ a ∨ p ≤ b := hp.2.2 a b h lemma exists_mem_multiset_le_of_prime {s : multiset (associates α)} {p : associates α} (hp : prime p) : p ≤ s.prod → ∃a∈s, p ≤ a := multiset.induction_on s (assume ⟨d, eq⟩, (hp.ne_one (mul_eq_one_iff.1 eq.symm).1).elim) $ assume a s ih h, have p ≤ a * s.prod, by simpa using h, match prime.le_or_le hp this with | or.inl h := ⟨a, multiset.mem_cons_self a s, h⟩ | or.inr h := let ⟨a, has, h⟩ := ih h in ⟨a, multiset.mem_cons_of_mem has, h⟩ end lemma prime_mk (p : α) : prime (associates.mk p) ↔ _root_.prime p := begin rw [prime, _root_.prime, forall_associated], transitivity, { apply and_congr, refl, apply and_congr, refl, apply forall_congr, assume a, exact forall_associated }, apply and_congr, { rw [(≠), mk_eq_zero] }, apply and_congr, { rw [is_unit_mk], }, apply forall_congr, assume a, apply forall_congr, assume b, rw [mk_mul_mk, mk_dvd_mk, mk_dvd_mk, mk_dvd_mk], end theorem irreducible_mk (a : α) : irreducible (associates.mk a) ↔ irreducible a := begin simp only [irreducible_iff, is_unit_mk], apply and_congr iff.rfl, split, { rintro h x y rfl, simpa [is_unit_mk] using h (associates.mk x) (associates.mk y) rfl }, { intros h x y, refine quotient.induction_on₂ x y (assume x y a_eq, _), rcases quotient.exact a_eq.symm with ⟨u, a_eq⟩, rw mul_assoc at a_eq, show is_unit (associates.mk x) ∨ is_unit (associates.mk y), simpa [is_unit_mk] using h _ _ a_eq.symm } end theorem mk_dvd_not_unit_mk_iff {a b : α} : dvd_not_unit (associates.mk a) (associates.mk b) ↔ dvd_not_unit a b := begin rw [dvd_not_unit, dvd_not_unit, ne, ne, mk_eq_zero], apply and_congr_right, intro ane0, split, { contrapose!, rw forall_associated, intros h x hx hbax, rw [mk_mul_mk, mk_eq_mk_iff_associated] at hbax, cases hbax with u hu, apply h (x * ↑u⁻¹), { rw is_unit_mk at hx, rw is_unit_iff_of_associated, apply hx, use u, simp, }, simp [← mul_assoc, ← hu] }, { rintro ⟨x, ⟨hx, rfl⟩⟩, use associates.mk x, simp [is_unit_mk, mk_mul_mk, hx], } end theorem dvd_not_unit_of_lt {a b : associates α} (hlt : a < b) : dvd_not_unit a b := begin split, { rintro rfl, apply not_lt_of_le _ hlt, apply dvd_zero }, rcases hlt with ⟨⟨x, rfl⟩, ndvd⟩, refine ⟨x, _, rfl⟩, contrapose! ndvd, rcases ndvd with ⟨u, rfl⟩, simp, end end comm_monoid_with_zero section comm_cancel_monoid_with_zero variable [comm_cancel_monoid_with_zero α] instance : partial_order (associates α) := { le_antisymm := λ a' b', quotient.induction_on₂ a' b' (λ a b hab hba, quot.sound $ associated_of_dvd_dvd (dvd_of_mk_le_mk hab) (dvd_of_mk_le_mk hba)) .. associates.preorder } instance : order_bot (associates α) := { bot := 1, bot_le := assume a, one_le, .. associates.partial_order } instance : order_top (associates α) := { top := 0, le_top := assume a, ⟨0, (mul_zero a).symm⟩, .. associates.partial_order } instance : no_zero_divisors (associates α) := ⟨λ x y, (quotient.induction_on₂ x y $ assume a b h, have a * b = 0, from (associated_zero_iff_eq_zero _).1 (quotient.exact h), have a = 0 ∨ b = 0, from mul_eq_zero.1 this, this.imp (assume h, h.symm ▸ rfl) (assume h, h.symm ▸ rfl))⟩ theorem irreducible_iff_prime_iff : (∀ a : α, irreducible a ↔ prime a) ↔ (∀ a : (associates α), irreducible a ↔ prime a) := begin rw forall_associated, split; intros h a; have ha := h a; rw irreducible_mk at *; rw prime_mk at *; exact ha, end lemma eq_of_mul_eq_mul_left : ∀(a b c : associates α), a ≠ 0 → a * b = a * c → b = c := begin rintros ⟨a⟩ ⟨b⟩ ⟨c⟩ ha h, rcases quotient.exact' h with ⟨u, hu⟩, have hu : a * (b * ↑u) = a * c, { rwa [← mul_assoc] }, exact quotient.sound' ⟨u, mul_left_cancel' (mt mk_eq_zero.2 ha) hu⟩ end lemma eq_of_mul_eq_mul_right : ∀(a b c : associates α), b ≠ 0 → a * b = c * b → a = c := λ a b c bne0, (mul_comm b a) ▸ (mul_comm b c) ▸ (eq_of_mul_eq_mul_left b a c bne0) lemma le_of_mul_le_mul_left (a b c : associates α) (ha : a ≠ 0) : a * b ≤ a * c → b ≤ c | ⟨d, hd⟩ := ⟨d, eq_of_mul_eq_mul_left a _ _ ha $ by rwa ← mul_assoc⟩ lemma one_or_eq_of_le_of_prime : ∀(p m : associates α), prime p → m ≤ p → (m = 1 ∨ m = p) | _ m ⟨hp0, hp1, h⟩ ⟨d, rfl⟩ := match h m d (dvd_refl _) with | or.inl h := classical.by_cases (assume : m = 0, by simp [this]) $ assume : m ≠ 0, have m * d ≤ m * 1, by simpa using h, have d ≤ 1, from associates.le_of_mul_le_mul_left m d 1 ‹m ≠ 0› this, have d = 1, from bot_unique this, by simp [this] | or.inr h := classical.by_cases (assume : d = 0, by simp [this] at hp0; contradiction) $ assume : d ≠ 0, have d * m ≤ d * 1, by simpa [mul_comm] using h, or.inl $ bot_unique $ associates.le_of_mul_le_mul_left d m 1 ‹d ≠ 0› this end instance : comm_cancel_monoid_with_zero (associates α) := { mul_left_cancel_of_ne_zero := eq_of_mul_eq_mul_left, mul_right_cancel_of_ne_zero := eq_of_mul_eq_mul_right, .. (infer_instance : comm_monoid_with_zero (associates α)) } theorem dvd_not_unit_iff_lt {a b : associates α} : dvd_not_unit a b ↔ a < b := dvd_and_not_dvd_iff.symm end comm_cancel_monoid_with_zero end associates
0c45b68fd879069c688fe89e7f3cb57610c29018
9dc8cecdf3c4634764a18254e94d43da07142918
/src/linear_algebra/free_module/finite/rank.lean
40638dfa67547cc67757f4d9d3b4d59c076257b0
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
4,974
lean
/- Copyright (c) 2021 Riccardo Brasca. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Riccardo Brasca -/ import linear_algebra.free_module.rank import linear_algebra.free_module.finite.basic /-! # Rank of finite free modules This is a basic API for the rank of finite free modules. -/ --TODO: `linear_algebra/finite_dimensional` should import this file, and a lot of results should --be moved here. universes u v w variables (R : Type u) (M : Type v) (N : Type w) open_locale tensor_product direct_sum big_operators cardinal open cardinal finite_dimensional fintype namespace module.free section ring variables [ring R] [strong_rank_condition R] variables [add_comm_group M] [module R M] [module.free R M] [module.finite R M] variables [add_comm_group N] [module R N] [module.free R N] [module.finite R N] /-- The rank of a finite and free module is finite. -/ lemma rank_lt_aleph_0 : module.rank R M < ℵ₀ := begin letI := nontrivial_of_invariant_basis_number R, rw [← (choose_basis R M).mk_eq_dim'', lt_aleph_0_iff_fintype], exact nonempty.intro infer_instance end /-- If `M` is finite and free, `finrank M = rank M`. -/ @[simp] lemma finrank_eq_rank : ↑(finrank R M) = module.rank R M := by { rw [finrank, cast_to_nat_of_lt_aleph_0 (rank_lt_aleph_0 R M)] } /-- The finrank of a free module `M` over `R` is the cardinality of `choose_basis_index R M`. -/ lemma finrank_eq_card_choose_basis_index : finrank R M = @card (choose_basis_index R M) (@choose_basis_index.fintype R M _ _ _ _ (nontrivial_of_invariant_basis_number R) _) := begin letI := nontrivial_of_invariant_basis_number R, simp [finrank, rank_eq_card_choose_basis_index] end /-- The finrank of `(ι →₀ R)` is `fintype.card ι`. -/ @[simp] lemma finrank_finsupp {ι : Type v} [fintype ι] : finrank R (ι →₀ R) = card ι := by { rw [finrank, rank_finsupp, ← mk_to_nat_eq_card, to_nat_lift] } /-- The finrank of `(ι → R)` is `fintype.card ι`. -/ lemma finrank_pi {ι : Type v} [fintype ι] : finrank R (ι → R) = card ι := by simp [finrank] /-- The finrank of the direct sum is the sum of the finranks. -/ @[simp] lemma finrank_direct_sum {ι : Type v} [fintype ι] (M : ι → Type w) [Π (i : ι), add_comm_group (M i)] [Π (i : ι), module R (M i)] [Π (i : ι), module.free R (M i)] [Π (i : ι), module.finite R (M i)] : finrank R (⨁ i, M i) = ∑ i, finrank R (M i) := begin letI := nontrivial_of_invariant_basis_number R, simp only [finrank, λ i, rank_eq_card_choose_basis_index R (M i), rank_direct_sum, ← mk_sigma, mk_to_nat_eq_card, card_sigma], end /-- The finrank of `M × N` is `(finrank R M) + (finrank R N)`. -/ @[simp] lemma finrank_prod : finrank R (M × N) = (finrank R M) + (finrank R N) := by { simp [finrank, rank_lt_aleph_0 R M, rank_lt_aleph_0 R N] } /-- The finrank of a finite product is the sum of the finranks. -/ --TODO: this should follow from `linear_equiv.finrank_eq`, that is over a field. lemma finrank_pi_fintype {ι : Type v} [fintype ι] {M : ι → Type w} [Π (i : ι), add_comm_group (M i)] [Π (i : ι), module R (M i)] [Π (i : ι), module.free R (M i)] [Π (i : ι), module.finite R (M i)] : finrank R (Π i, M i) = ∑ i, finrank R (M i) := begin letI := nontrivial_of_invariant_basis_number R, simp only [finrank, λ i, rank_eq_card_choose_basis_index R (M i), rank_pi_finite, ← mk_sigma, mk_to_nat_eq_card, card_sigma], end /-- If `m` and `n` are `fintype`, the finrank of `m × n` matrices is `(fintype.card m) * (fintype.card n)`. -/ lemma finrank_matrix (m n : Type v) [fintype m] [fintype n] : finrank R (matrix m n R) = (card m) * (card n) := by { simp [finrank] } end ring section comm_ring variables [comm_ring R] [strong_rank_condition R] variables [add_comm_group M] [module R M] [module.free R M] [module.finite R M] variables [add_comm_group N] [module R N] [module.free R N] [module.finite R N] /-- The finrank of `M →ₗ[R] N` is `(finrank R M) * (finrank R N)`. -/ --TODO: this should follow from `linear_equiv.finrank_eq`, that is over a field. lemma finrank_linear_hom : finrank R (M →ₗ[R] N) = (finrank R M) * (finrank R N) := begin classical, letI := nontrivial_of_invariant_basis_number R, have h := (linear_map.to_matrix (choose_basis R M) (choose_basis R N)), let b := (matrix.std_basis _ _ _).map h.symm, rw [finrank, dim_eq_card_basis b, ← mk_fintype, mk_to_nat_eq_card, finrank, finrank, rank_eq_card_choose_basis_index, rank_eq_card_choose_basis_index, mk_to_nat_eq_card, mk_to_nat_eq_card, card_prod, mul_comm] end /-- The finrank of `M ⊗[R] N` is `(finrank R M) * (finrank R N)`. -/ @[simp] lemma finrank_tensor_product (M : Type v) (N : Type w) [add_comm_group M] [module R M] [module.free R M] [add_comm_group N] [module R N] [module.free R N] : finrank R (M ⊗[R] N) = (finrank R M) * (finrank R N) := by { simp [finrank] } end comm_ring end module.free
e8efb828ec23dee3193ffb7ae6faa9e2fef74f9f
1e3a43e8ba59c6fe1c66775b6e833e721eaf1675
/src/data/padics/padic_numbers.lean
3b1222f0292a7367aa552dc02cbb1d243dd43ef9
[ "Apache-2.0" ]
permissive
Sterrs/mathlib
ea6910847b8dfd18500486de9ab0ee35704a3f52
d9327e433804004aa1dc65091bbe0de1e5a08c5e
refs/heads/master
1,650,769,884,257
1,587,808,694,000
1,587,808,694,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
32,489
lean
/- 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 data.padics.padic_norm import analysis.normed_space.basic /-! # p-adic numbers This file defines the p-adic numbers (rationals) ℚ_p as the completion of ℚ with respect to the p-adic norm. We show that the p-adic norm on ℚ extends to ℚ_p, that ℚ is embedded in ℚ_p, and that ℚ_p is Cauchy complete. ## Important definitions * `padic` : the type of p-adic numbers * `padic_norm_e` : the rational valued p-adic norm on ℚ_p ## Notation We introduce the notation ℚ_[p] for the p-adic numbers. ## Implementation notes Much, but not all, of this file assumes that `p` is prime. This assumption is inferred automatically by taking (prime p) as a type class argument. We use the same concrete Cauchy sequence construction that is used to construct ℝ. ℚ_p inherits a field structure from this construction. The extension of the norm on ℚ to ℚ_p is *not* analogous to extending the absolute value to ℝ, and hence the proof that ℚ_p is complete is different from the proof that ℝ is complete. A small special-purpose simplification tactic, `padic_index_simp`, is used to manipulate sequence indices in the proof that the norm extends. `padic_norm_e` is the rational-valued p-adic norm on ℚ_p. To instantiate ℚ_p as a normed field, we must cast this into a ℝ-valued norm. The ℝ-valued norm, using notation ∥ ∥ from normed spaces, is the canonical representation of this norm. Coercions from ℚ to ℚ_p are set up to work with the `norm_cast` tactic. ## References * [F. Q. Gouêva, *p-adic numbers*][gouvea1997] * [R. Y. Lewis, *A formal proof of Hensel's lemma over the p-adic integers*][lewis2019] * <https://en.wikipedia.org/wiki/P-adic_number> ## Tags p-adic, p adic, padic, norm, valuation, cauchy, completion, p-adic completion -/ noncomputable theory open_locale classical open nat multiplicity padic_norm cau_seq cau_seq.completion metric /-- The type of Cauchy sequences of rationals with respect to the p-adic norm. -/ @[reducible] def padic_seq (p : ℕ) [p.prime] := cau_seq _ (padic_norm p) namespace padic_seq section variables {p : ℕ} [nat.prime p] /-- The p-adic norm of the entries of a nonzero Cauchy sequence of rationals is eventually constant. -/ lemma stationary {f : cau_seq ℚ (padic_norm p)} (hf : ¬ f ≈ 0) : ∃ N, ∀ m n, N ≤ m → N ≤ n → padic_norm p (f n) = padic_norm p (f m) := have ∃ ε > 0, ∃ N1, ∀ j ≥ N1, ε ≤ padic_norm p (f j), from cau_seq.abv_pos_of_not_lim_zero $ not_lim_zero_of_not_congr_zero hf, let ⟨ε, hε, N1, hN1⟩ := this, ⟨N2, hN2⟩ := cau_seq.cauchy₂ f hε in ⟨ max N1 N2, λ n m hn hm, have padic_norm p (f n - f m) < ε, from hN2 _ _ (max_le_iff.1 hn).2 (max_le_iff.1 hm).2, have padic_norm p (f n - f m) < padic_norm p (f n), from lt_of_lt_of_le this $ hN1 _ (max_le_iff.1 hn).1, have padic_norm p (f n - f m) < max (padic_norm p (f n)) (padic_norm p (f m)), from lt_max_iff.2 (or.inl this), begin by_contradiction hne, rw ←padic_norm.neg p (f m) at hne, have hnam := add_eq_max_of_ne p hne, rw [padic_norm.neg, max_comm] at hnam, rw [←hnam, sub_eq_add_neg, add_comm] at this, apply _root_.lt_irrefl _ this end ⟩ /-- For all n ≥ stationary_point f hf, the p-adic norm of f n is the same. -/ def stationary_point {f : padic_seq p} (hf : ¬ f ≈ 0) : ℕ := classical.some $ stationary hf lemma stationary_point_spec {f : padic_seq p} (hf : ¬ f ≈ 0) : ∀ {m n}, m ≥ stationary_point hf → n ≥ stationary_point hf → padic_norm p (f n) = padic_norm p (f m) := classical.some_spec $ stationary hf /-- Since the norm of the entries of a Cauchy sequence is eventually stationary, we can lift the norm to sequences. -/ def norm (f : padic_seq p) : ℚ := if hf : f ≈ 0 then 0 else padic_norm p (f (stationary_point hf)) lemma norm_zero_iff (f : padic_seq p) : f.norm = 0 ↔ f ≈ 0 := begin constructor, { intro h, by_contradiction hf, unfold norm at h, split_ifs at h, apply hf, intros ε hε, existsi stationary_point hf, intros j hj, have heq := stationary_point_spec hf (le_refl _) hj, simpa [h, heq] }, { intro h, simp [norm, h] } end end section embedding open cau_seq variables {p : ℕ} [nat.prime p] lemma equiv_zero_of_val_eq_of_equiv_zero {f g : padic_seq p} (h : ∀ k, padic_norm p (f k) = padic_norm p (g k)) (hf : f ≈ 0) : g ≈ 0 := λ ε hε, let ⟨i, hi⟩ := hf _ hε in ⟨i, λ j hj, by simpa [h] using hi _ hj⟩ lemma norm_nonzero_of_not_equiv_zero {f : padic_seq p} (hf : ¬ f ≈ 0) : f.norm ≠ 0 := hf ∘ f.norm_zero_iff.1 lemma norm_eq_norm_app_of_nonzero {f : padic_seq p} (hf : ¬ f ≈ 0) : ∃ k, f.norm = padic_norm p k ∧ k ≠ 0 := have heq : f.norm = padic_norm p (f $ stationary_point hf), by simp [norm, hf], ⟨f $ stationary_point hf, heq, λ h, norm_nonzero_of_not_equiv_zero hf (by simpa [h] using heq)⟩ lemma not_lim_zero_const_of_nonzero {q : ℚ} (hq : q ≠ 0) : ¬ lim_zero (const (padic_norm p) q) := λ h', hq $ const_lim_zero.1 h' lemma not_equiv_zero_const_of_nonzero {q : ℚ} (hq : q ≠ 0) : ¬ (const (padic_norm p) q) ≈ 0 := λ h : lim_zero (const (padic_norm p) q - 0), not_lim_zero_const_of_nonzero hq $ by simpa using h lemma norm_nonneg (f : padic_seq p) : f.norm ≥ 0 := if hf : f ≈ 0 then by simp [hf, norm] else by simp [norm, hf, padic_norm.nonneg] /-- An auxiliary lemma for manipulating sequence indices. -/ lemma lift_index_left_left {f : padic_seq p} (hf : ¬ f ≈ 0) (v2 v3 : ℕ) : padic_norm p (f (stationary_point hf)) = padic_norm p (f (max (stationary_point hf) (max v2 v3))) := let i := max (stationary_point hf) (max v2 v3) in begin apply stationary_point_spec hf, { apply le_max_left }, { apply le_refl } end /-- An auxiliary lemma for manipulating sequence indices. -/ lemma lift_index_left {f : padic_seq p} (hf : ¬ f ≈ 0) (v1 v3 : ℕ) : padic_norm p (f (stationary_point hf)) = padic_norm p (f (max v1 (max (stationary_point hf) v3))) := let i := max v1 (max (stationary_point hf) v3) in begin apply stationary_point_spec hf, { apply le_trans, { apply le_max_left _ v3 }, { apply le_max_right } }, { apply le_refl } end /-- An auxiliary lemma for manipulating sequence indices. -/ lemma lift_index_right {f : padic_seq p} (hf : ¬ f ≈ 0) (v1 v2 : ℕ) : padic_norm p (f (stationary_point hf)) = padic_norm p (f (max v1 (max v2 (stationary_point hf)))) := let i := max v1 (max v2 (stationary_point hf)) in begin apply stationary_point_spec hf, { apply le_trans, { apply le_max_right v2 }, { apply le_max_right } }, { apply le_refl } end end embedding end padic_seq section open padic_seq private meta def index_simp_core (hh hf hg : expr) (at_ : interactive.loc := interactive.loc.ns [none]) : tactic unit := do [v1, v2, v3] ← [hh, hf, hg].mmap (λ n, tactic.mk_app ``stationary_point [n] <|> return n), e1 ← tactic.mk_app ``lift_index_left_left [hh, v2, v3] <|> return `(true), e2 ← tactic.mk_app ``lift_index_left [hf, v1, v3] <|> return `(true), e3 ← tactic.mk_app ``lift_index_right [hg, v1, v2] <|> return `(true), sl ← [e1, e2, e3].mfoldl (λ s e, simp_lemmas.add s e) simp_lemmas.mk, when at_.include_goal (tactic.simp_target sl), hs ← at_.get_locals, hs.mmap' (tactic.simp_hyp sl []) /-- This is a special-purpose tactic that lifts padic_norm (f (stationary_point f)) to padic_norm (f (max _ _ _)). -/ meta def tactic.interactive.padic_index_simp (l : interactive.parse interactive.types.pexpr_list) (at_ : interactive.parse interactive.types.location) : tactic unit := do [h, f, g] ← l.mmap tactic.i_to_expr, index_simp_core h f g at_ end namespace padic_seq section embedding open cau_seq variables {p : ℕ} [hp : nat.prime p] include hp lemma norm_mul (f g : padic_seq p) : (f * g).norm = f.norm * g.norm := if hf : f ≈ 0 then have hg : f * g ≈ 0, from mul_equiv_zero' _ hf, by simp [hf, hg, norm] else if hg : g ≈ 0 then have hf : f * g ≈ 0, from mul_equiv_zero _ hg, by simp [hf, hg, norm] else have hfg : ¬ f * g ≈ 0, by apply mul_not_equiv_zero; assumption, begin unfold norm, split_ifs, padic_index_simp [hfg, hf, hg], apply padic_norm.mul end lemma eq_zero_iff_equiv_zero (f : padic_seq p) : mk f = 0 ↔ f ≈ 0 := mk_eq lemma ne_zero_iff_nequiv_zero (f : padic_seq p) : mk f ≠ 0 ↔ ¬ f ≈ 0 := not_iff_not.2 (eq_zero_iff_equiv_zero _) lemma norm_const (q : ℚ) : norm (const (padic_norm p) q) = padic_norm p q := if hq : q = 0 then have (const (padic_norm p) q) ≈ 0, by simp [hq]; apply setoid.refl (const (padic_norm p) 0), by subst hq; simp [norm, this] else have ¬ (const (padic_norm p) q) ≈ 0, from not_equiv_zero_const_of_nonzero hq, by simp [norm, this] lemma norm_image (a : padic_seq p) (ha : ¬ a ≈ 0) : (∃ (n : ℤ), a.norm = ↑p ^ (-n)) := let ⟨k, hk, hk'⟩ := norm_eq_norm_app_of_nonzero ha in by simpa [hk] using padic_norm.image p hk' lemma norm_one : norm (1 : padic_seq p) = 1 := have h1 : ¬ (1 : padic_seq p) ≈ 0, from one_not_equiv_zero _, by simp [h1, norm, hp.one_lt] private lemma norm_eq_of_equiv_aux {f g : padic_seq p} (hf : ¬ f ≈ 0) (hg : ¬ g ≈ 0) (hfg : f ≈ g) (h : padic_norm p (f (stationary_point hf)) ≠ padic_norm p (g (stationary_point hg))) (hgt : padic_norm p (f (stationary_point hf)) > padic_norm p (g (stationary_point hg))) : false := begin have hpn : padic_norm p (f (stationary_point hf)) - padic_norm p (g (stationary_point hg)) > 0, from sub_pos_of_lt hgt, cases hfg _ hpn with N hN, let i := max N (max (stationary_point hf) (stationary_point hg)), have hi : i ≥ N, from le_max_left _ _, have hN' := hN _ hi, padic_index_simp [N, hf, hg] at hN' h hgt, have hpne : padic_norm p (f i) ≠ padic_norm p (-(g i)), by rwa [ ←padic_norm.neg p (g i)] at h, let hpnem := add_eq_max_of_ne p hpne, have hpeq : padic_norm p ((f - g) i) = max (padic_norm p (f i)) (padic_norm p (g i)), { rwa padic_norm.neg at hpnem }, rw [hpeq, max_eq_left_of_lt hgt] at hN', have : padic_norm p (f i) < padic_norm p (f i), { apply lt_of_lt_of_le hN', apply sub_le_self, apply padic_norm.nonneg }, exact lt_irrefl _ this end private lemma norm_eq_of_equiv {f g : padic_seq p} (hf : ¬ f ≈ 0) (hg : ¬ g ≈ 0) (hfg : f ≈ g) : padic_norm p (f (stationary_point hf)) = padic_norm p (g (stationary_point hg)) := begin by_contradiction h, cases (decidable.em (padic_norm p (f (stationary_point hf)) > padic_norm p (g (stationary_point hg)))) with hgt hngt, { exact norm_eq_of_equiv_aux hf hg hfg h hgt }, { apply norm_eq_of_equiv_aux hg hf (setoid.symm hfg) (ne.symm h), apply lt_of_le_of_ne, apply le_of_not_gt hngt, apply h } end theorem norm_equiv {f g : padic_seq p} (hfg : f ≈ g) : f.norm = g.norm := if hf : f ≈ 0 then have hg : g ≈ 0, from setoid.trans (setoid.symm hfg) hf, by simp [norm, hf, hg] else have hg : ¬ g ≈ 0, from hf ∘ setoid.trans hfg, by unfold norm; split_ifs; exact norm_eq_of_equiv hf hg hfg private lemma norm_nonarchimedean_aux {f g : padic_seq p} (hfg : ¬ f + g ≈ 0) (hf : ¬ f ≈ 0) (hg : ¬ g ≈ 0) : (f + g).norm ≤ max (f.norm) (g.norm) := begin unfold norm, split_ifs, padic_index_simp [hfg, hf, hg], apply padic_norm.nonarchimedean end theorem norm_nonarchimedean (f g : padic_seq p) : (f + g).norm ≤ max (f.norm) (g.norm) := if hfg : f + g ≈ 0 then have 0 ≤ max (f.norm) (g.norm), from le_max_left_of_le (norm_nonneg _), by simpa [hfg, norm] else if hf : f ≈ 0 then have hfg' : f + g ≈ g, { change lim_zero (f - 0) at hf, show lim_zero (f + g - g), by simpa using hf }, have hcfg : (f + g).norm = g.norm, from norm_equiv hfg', have hcl : f.norm = 0, from (norm_zero_iff f).2 hf, have max (f.norm) (g.norm) = g.norm, by rw hcl; exact max_eq_right (norm_nonneg _), by rw [this, hcfg] else if hg : g ≈ 0 then have hfg' : f + g ≈ f, { change lim_zero (g - 0) at hg, show lim_zero (f + g - f), by simpa [add_sub_cancel'] using hg }, have hcfg : (f + g).norm = f.norm, from norm_equiv hfg', have hcl : g.norm = 0, from (norm_zero_iff g).2 hg, have max (f.norm) (g.norm) = f.norm, by rw hcl; exact max_eq_left (norm_nonneg _), by rw [this, hcfg] else norm_nonarchimedean_aux hfg hf hg lemma norm_eq {f g : padic_seq p} (h : ∀ k, padic_norm p (f k) = padic_norm p (g k)) : f.norm = g.norm := if hf : f ≈ 0 then have hg : g ≈ 0, from equiv_zero_of_val_eq_of_equiv_zero h hf, by simp [hf, hg, norm] else have hg : ¬ g ≈ 0, from λ hg, hf $ equiv_zero_of_val_eq_of_equiv_zero (by simp [h]) hg, begin simp [hg, hf, norm], let i := max (stationary_point hf) (stationary_point hg), have hpf : padic_norm p (f (stationary_point hf)) = padic_norm p (f i), { apply stationary_point_spec, apply le_max_left, apply le_refl }, have hpg : padic_norm p (g (stationary_point hg)) = padic_norm p (g i), { apply stationary_point_spec, apply le_max_right, apply le_refl }, rw [hpf, hpg, h] end lemma norm_neg (a : padic_seq p) : (-a).norm = a.norm := norm_eq $ by simp lemma norm_eq_of_add_equiv_zero {f g : padic_seq p} (h : f + g ≈ 0) : f.norm = g.norm := have lim_zero (f + g - 0), from h, have f ≈ -g, from show lim_zero (f - (-g)), by simpa, have f.norm = (-g).norm, from norm_equiv this, by simpa [norm_neg] using this lemma add_eq_max_of_ne {f g : padic_seq p} (hfgne : f.norm ≠ g.norm) : (f + g).norm = max f.norm g.norm := have hfg : ¬f + g ≈ 0, from mt norm_eq_of_add_equiv_zero hfgne, if hf : f ≈ 0 then have lim_zero (f - 0), from hf, have f + g ≈ g, from show lim_zero ((f + g) - g), by simpa, have h1 : (f+g).norm = g.norm, from norm_equiv this, have h2 : f.norm = 0, from (norm_zero_iff _).2 hf, by rw [h1, h2]; rw max_eq_right (norm_nonneg _) else if hg : g ≈ 0 then have lim_zero (g - 0), from hg, have f + g ≈ f, from show lim_zero ((f + g) - f), by rw [add_sub_cancel']; simpa, have h1 : (f+g).norm = f.norm, from norm_equiv this, have h2 : g.norm = 0, from (norm_zero_iff _).2 hg, by rw [h1, h2]; rw max_eq_left (norm_nonneg _) else begin unfold norm at ⊢ hfgne, split_ifs at ⊢ hfgne, padic_index_simp [hfg, hf, hg] at ⊢ hfgne, apply padic_norm.add_eq_max_of_ne, simpa [hf, hg, norm] using hfgne end end embedding end padic_seq /-- The p-adic numbers `Q_[p]` are the Cauchy completion of `ℚ` with respect to the p-adic norm. -/ def padic (p : ℕ) [nat.prime p] := @cau_seq.completion.Cauchy _ _ _ _ (padic_norm p) _ notation `ℚ_[` p `]` := padic p namespace padic section completion variables {p : ℕ} [nat.prime p] /-- The discrete field structure on ℚ_p is inherited from the Cauchy completion construction. -/ instance field : field (ℚ_[p]) := cau_seq.completion.field instance : inhabited ℚ_[p] := ⟨0⟩ -- short circuits instance : has_zero ℚ_[p] := by apply_instance instance : has_one ℚ_[p] := by apply_instance instance : has_add ℚ_[p] := by apply_instance instance : has_mul ℚ_[p] := by apply_instance instance : has_sub ℚ_[p] := by apply_instance instance : has_neg ℚ_[p] := by apply_instance instance : has_div ℚ_[p] := by apply_instance instance : add_comm_group ℚ_[p] := by apply_instance instance : comm_ring ℚ_[p] := by apply_instance /-- Builds the equivalence class of a Cauchy sequence of rationals. -/ def mk : padic_seq p → ℚ_[p] := quotient.mk end completion section completion variables (p : ℕ) [nat.prime p] lemma mk_eq {f g : padic_seq p} : mk f = mk g ↔ f ≈ g := quotient.eq /-- Embeds the rational numbers in the p-adic numbers. -/ def of_rat : ℚ → ℚ_[p] := cau_seq.completion.of_rat @[simp] lemma of_rat_add : ∀ (x y : ℚ), of_rat p (x + y) = of_rat p x + of_rat p y := cau_seq.completion.of_rat_add @[simp] lemma of_rat_neg : ∀ (x : ℚ), of_rat p (-x) = -of_rat p x := cau_seq.completion.of_rat_neg @[simp] lemma of_rat_mul : ∀ (x y : ℚ), of_rat p (x * y) = of_rat p x * of_rat p y := cau_seq.completion.of_rat_mul @[simp] lemma of_rat_sub : ∀ (x y : ℚ), of_rat p (x - y) = of_rat p x - of_rat p y := cau_seq.completion.of_rat_sub @[simp] lemma of_rat_div : ∀ (x y : ℚ), of_rat p (x / y) = of_rat p x / of_rat p y := cau_seq.completion.of_rat_div @[simp] lemma of_rat_one : of_rat p 1 = 1 := rfl @[simp] lemma of_rat_zero : of_rat p 0 = 0 := rfl @[simp] lemma cast_eq_of_rat_of_nat (n : ℕ) : (↑n : ℚ_[p]) = of_rat p n := begin induction n with n ih, { refl }, { simpa using ih } end -- without short circuits, this needs an increase of class.instance_max_depth @[simp] lemma cast_eq_of_rat_of_int (n : ℤ) : ↑n = of_rat p n := by induction n; simp lemma cast_eq_of_rat : ∀ (q : ℚ), (↑q : ℚ_[p]) = of_rat p q | ⟨n, d, h1, h2⟩ := show ↑n / ↑d = _, from have (⟨n, d, h1, h2⟩ : ℚ) = rat.mk n d, from rat.num_denom', by simp [this, rat.mk_eq_div, of_rat_div] @[norm_cast] lemma coe_add : ∀ {x y : ℚ}, (↑(x + y) : ℚ_[p]) = ↑x + ↑y := by simp [cast_eq_of_rat] @[norm_cast] lemma coe_neg : ∀ {x : ℚ}, (↑(-x) : ℚ_[p]) = -↑x := by simp [cast_eq_of_rat] @[norm_cast] lemma coe_mul : ∀ {x y : ℚ}, (↑(x * y) : ℚ_[p]) = ↑x * ↑y := by simp [cast_eq_of_rat] @[norm_cast] lemma coe_sub : ∀ {x y : ℚ}, (↑(x - y) : ℚ_[p]) = ↑x - ↑y := by simp [cast_eq_of_rat] @[norm_cast] lemma coe_div : ∀ {x y : ℚ}, (↑(x / y) : ℚ_[p]) = ↑x / ↑y := by simp [cast_eq_of_rat] @[norm_cast] lemma coe_one : (↑1 : ℚ_[p]) = 1 := rfl @[norm_cast] lemma coe_zero : (↑0 : ℚ_[p]) = 0 := rfl lemma const_equiv {q r : ℚ} : const (padic_norm p) q ≈ const (padic_norm p) r ↔ q = r := ⟨ λ heq : lim_zero (const (padic_norm p) (q - r)), eq_of_sub_eq_zero $ const_lim_zero.1 heq, λ heq, by rw heq; apply setoid.refl _ ⟩ lemma of_rat_eq {q r : ℚ} : of_rat p q = of_rat p r ↔ q = r := ⟨(const_equiv p).1 ∘ quotient.eq.1, λ h, by rw h⟩ @[norm_cast] lemma coe_inj {q r : ℚ} : (↑q : ℚ_[p]) = ↑r ↔ q = r := by simp [cast_eq_of_rat, of_rat_eq] instance : char_zero ℚ_[p] := ⟨λ m n, by { rw ← rat.cast_coe_nat, norm_cast, exact id }⟩ end completion end padic /-- The rational-valued p-adic norm on ℚ_p is lifted from the norm on Cauchy sequences. The canonical form of this function is the normed space instance, with notation `∥ ∥`. -/ def padic_norm_e {p : ℕ} [hp : nat.prime p] : ℚ_[p] → ℚ := quotient.lift padic_seq.norm $ @padic_seq.norm_equiv _ _ namespace padic_norm_e section embedding open padic_seq variables {p : ℕ} [nat.prime p] lemma defn (f : padic_seq p) {ε : ℚ} (hε : ε > 0) : ∃ N, ∀ i ≥ N, padic_norm_e (⟦f⟧ - f i) < ε := begin simp only [padic.cast_eq_of_rat], change ∃ N, ∀ i ≥ N, (f - const _ (f i)).norm < ε, by_contradiction h, cases cauchy₂ f hε with N hN, have : ∀ N, ∃ i ≥ N, (f - const _ (f i)).norm ≥ ε, by simpa [not_forall] using h, rcases this N with ⟨i, hi, hge⟩, have hne : ¬ (f - const (padic_norm p) (f i)) ≈ 0, { intro h, unfold padic_seq.norm at hge; split_ifs at hge, exact not_lt_of_ge hge hε }, unfold padic_seq.norm at hge; split_ifs at hge, apply not_le_of_gt _ hge, cases decidable.em ((stationary_point hne) ≥ N) with hgen hngen, { apply hN; assumption }, { have := stationary_point_spec hne (le_refl _) (le_of_not_le hngen), rw ←this, apply hN, apply le_refl, assumption } end protected lemma nonneg (q : ℚ_[p]) : padic_norm_e q ≥ 0 := quotient.induction_on q $ norm_nonneg lemma zero_def : (0 : ℚ_[p]) = ⟦0⟧ := rfl lemma zero_iff (q : ℚ_[p]) : padic_norm_e q = 0 ↔ q = 0 := quotient.induction_on q $ by simpa only [zero_def, quotient.eq] using norm_zero_iff @[simp] protected lemma zero : padic_norm_e (0 : ℚ_[p]) = 0 := (zero_iff _).2 rfl /-- Theorems about `padic_norm_e` are named with a `'` so the names do not conflict with the equivalent theorems about `norm` (`∥ ∥`). -/ @[simp] protected lemma one' : padic_norm_e (1 : ℚ_[p]) = 1 := norm_one @[simp] protected lemma neg (q : ℚ_[p]) : padic_norm_e (-q) = padic_norm_e q := quotient.induction_on q $ norm_neg /-- Theorems about `padic_norm_e` are named with a `'` so the names do not conflict with the equivalent theorems about `norm` (`∥ ∥`). -/ theorem nonarchimedean' (q r : ℚ_[p]) : padic_norm_e (q + r) ≤ max (padic_norm_e q) (padic_norm_e r) := quotient.induction_on₂ q r $ norm_nonarchimedean /-- Theorems about `padic_norm_e` are named with a `'` so the names do not conflict with the equivalent theorems about `norm` (`∥ ∥`). -/ theorem add_eq_max_of_ne' {q r : ℚ_[p]} : padic_norm_e q ≠ padic_norm_e r → padic_norm_e (q + r) = max (padic_norm_e q) (padic_norm_e r) := quotient.induction_on₂ q r $ λ _ _, padic_seq.add_eq_max_of_ne lemma triangle_ineq (x y z : ℚ_[p]) : padic_norm_e (x - z) ≤ padic_norm_e (x - y) + padic_norm_e (y - z) := calc padic_norm_e (x - z) = padic_norm_e ((x - y) + (y - z)) : by rw sub_add_sub_cancel ... ≤ max (padic_norm_e (x - y)) (padic_norm_e (y - z)) : padic_norm_e.nonarchimedean' _ _ ... ≤ padic_norm_e (x - y) + padic_norm_e (y - z) : max_le_add_of_nonneg (padic_norm_e.nonneg _) (padic_norm_e.nonneg _) protected lemma add (q r : ℚ_[p]) : padic_norm_e (q + r) ≤ (padic_norm_e q) + (padic_norm_e r) := calc padic_norm_e (q + r) ≤ max (padic_norm_e q) (padic_norm_e r) : nonarchimedean' _ _ ... ≤ (padic_norm_e q) + (padic_norm_e r) : max_le_add_of_nonneg (padic_norm_e.nonneg _) (padic_norm_e.nonneg _) protected lemma mul' (q r : ℚ_[p]) : padic_norm_e (q * r) = (padic_norm_e q) * (padic_norm_e r) := quotient.induction_on₂ q r $ norm_mul instance : is_absolute_value (@padic_norm_e p _) := { abv_nonneg := padic_norm_e.nonneg, abv_eq_zero := zero_iff, abv_add := padic_norm_e.add, abv_mul := padic_norm_e.mul' } @[simp] lemma eq_padic_norm' (q : ℚ) : padic_norm_e (padic.of_rat p q) = padic_norm p q := norm_const _ protected theorem image' {q : ℚ_[p]} : q ≠ 0 → ∃ n : ℤ, padic_norm_e q = p ^ (-n) := quotient.induction_on q $ λ f hf, have ¬ f ≈ 0, from (ne_zero_iff_nequiv_zero f).1 hf, norm_image f this lemma sub_rev (q r : ℚ_[p]) : padic_norm_e (q - r) = padic_norm_e (r - q) := by rw ←(padic_norm_e.neg); simp end embedding end padic_norm_e namespace padic section complete open padic_seq padic theorem rat_dense' {p : ℕ} [nat.prime p] (q : ℚ_[p]) {ε : ℚ} (hε : ε > 0) : ∃ r : ℚ, padic_norm_e (q - r) < ε := quotient.induction_on q $ λ q', have ∃ N, ∀ m n ≥ N, padic_norm p (q' m - q' n) < ε, from cauchy₂ _ hε, let ⟨N, hN⟩ := this in ⟨q' N, begin simp only [padic.cast_eq_of_rat], change padic_seq.norm (q' - const _ (q' N)) < ε, cases decidable.em ((q' - const (padic_norm p) (q' N)) ≈ 0) with heq hne', { simpa only [heq, padic_seq.norm, dif_pos] }, { simp only [padic_seq.norm, dif_neg hne'], change padic_norm p (q' _ - q' _) < ε, have := stationary_point_spec hne', cases decidable.em (N ≥ stationary_point hne') with hle hle, { have := eq.symm (this (le_refl _) hle), simp at this, simpa [this] }, { apply hN, apply le_of_lt, apply lt_of_not_ge, apply hle, apply le_refl }} end⟩ variables {p : ℕ} [nat.prime p] (f : cau_seq _ (@padic_norm_e p _)) open classical private lemma div_nat_pos (n : ℕ) : (1 / ((n + 1): ℚ)) > 0 := div_pos zero_lt_one (by exact_mod_cast succ_pos _) def lim_seq : ℕ → ℚ := λ n, classical.some (rat_dense' (f n) (div_nat_pos n)) lemma exi_rat_seq_conv {ε : ℚ} (hε : 0 < ε) : ∃ N, ∀ i ≥ N, padic_norm_e (f i - ((lim_seq f) i : ℚ_[p])) < ε := begin refine (exists_nat_gt (1/ε)).imp (λ N hN i hi, _), have h := classical.some_spec (rat_dense' (f i) (div_nat_pos i)), refine lt_of_lt_of_le h (div_le_of_le_mul (by exact_mod_cast succ_pos _) _), rw right_distrib, apply le_add_of_le_of_nonneg, { exact le_mul_of_div_le hε (le_trans (le_of_lt hN) (by exact_mod_cast hi)) }, { apply le_of_lt, simpa } end lemma exi_rat_seq_conv_cauchy : is_cau_seq (padic_norm p) (lim_seq f) := assume ε hε, have hε3 : ε / 3 > 0, from div_pos hε (by norm_num), let ⟨N, hN⟩ := exi_rat_seq_conv f hε3, ⟨N2, hN2⟩ := f.cauchy₂ hε3 in begin existsi max N N2, intros j hj, suffices : padic_norm_e ((↑(lim_seq f j) - f (max N N2)) + (f (max N N2) - lim_seq f (max N N2))) < ε, { ring at this ⊢, rw [← padic_norm_e.eq_padic_norm', ← padic.cast_eq_of_rat], exact_mod_cast this }, { apply lt_of_le_of_lt, { apply padic_norm_e.add }, { have : (3 : ℚ) ≠ 0, by norm_num, have : ε = ε / 3 + ε / 3 + ε / 3, { apply eq_of_mul_eq_mul_left this, simp [left_distrib, mul_div_cancel' _ this ], ring }, rw this, apply add_lt_add, { suffices : padic_norm_e ((↑(lim_seq f j) - f j) + (f j - f (max N N2))) < ε / 3 + ε / 3, by simpa [sub_eq_add_neg], apply lt_of_le_of_lt, { apply padic_norm_e.add }, { apply add_lt_add, { rw [padic_norm_e.sub_rev], apply_mod_cast hN, exact le_of_max_le_left hj }, { apply hN2, exact le_of_max_le_right hj, apply le_max_right }}}, { apply_mod_cast hN, apply le_max_left }}} end private def lim' : padic_seq p := ⟨_, exi_rat_seq_conv_cauchy f⟩ private def lim : ℚ_[p] := ⟦lim' f⟧ theorem complete' : ∃ q : ℚ_[p], ∀ ε > 0, ∃ N, ∀ i ≥ N, padic_norm_e (q - f i) < ε := ⟨ lim f, λ ε hε, let ⟨N, hN⟩ := exi_rat_seq_conv f (show ε / 2 > 0, from div_pos hε (by norm_num)), ⟨N2, hN2⟩ := padic_norm_e.defn (lim' f) (show ε / 2 > 0, from div_pos hε (by norm_num)) in begin existsi max N N2, intros i hi, suffices : padic_norm_e ((lim f - lim' f i) + (lim' f i - f i)) < ε, { ring at this; exact this }, { apply lt_of_le_of_lt, { apply padic_norm_e.add }, { have : ε = ε / 2 + ε / 2, by rw ←(add_self_div_two ε); simp, rw this, apply add_lt_add, { apply hN2, exact le_of_max_le_right hi }, { rw_mod_cast [padic_norm_e.sub_rev], apply hN, exact le_of_max_le_left hi }}} end ⟩ end complete section normed_space variables (p : ℕ) [nat.prime p] instance : has_dist ℚ_[p] := ⟨λ x y, padic_norm_e (x - y)⟩ instance : metric_space ℚ_[p] := { dist_self := by simp [dist], dist_comm := λ x y, by unfold dist; rw ←padic_norm_e.neg (x - y); simp, dist_triangle := begin intros, unfold dist, exact_mod_cast padic_norm_e.triangle_ineq _ _ _, end, eq_of_dist_eq_zero := begin unfold dist, intros _ _ h, apply eq_of_sub_eq_zero, apply (padic_norm_e.zero_iff _).1, exact_mod_cast h end } instance : has_norm ℚ_[p] := ⟨λ x, padic_norm_e x⟩ instance : normed_field ℚ_[p] := { dist_eq := λ _ _, rfl, norm_mul' := by simp [has_norm.norm, padic_norm_e.mul'] } instance : is_absolute_value (λ a : ℚ_[p], ∥a∥) := { abv_nonneg := norm_nonneg, abv_eq_zero := λ _, norm_eq_zero, abv_add := norm_add_le, abv_mul := by simp [has_norm.norm, padic_norm_e.mul'] } theorem rat_dense {p : ℕ} {hp : p.prime} (q : ℚ_[p]) {ε : ℝ} (hε : ε > 0) : ∃ r : ℚ, ∥q - r∥ < ε := let ⟨ε', hε'l, hε'r⟩ := exists_rat_btwn hε, ⟨r, hr⟩ := rat_dense' q (by simpa using hε'l) in ⟨r, lt.trans (by simpa [has_norm.norm] using hr) hε'r⟩ end normed_space end padic namespace padic_norm_e section normed_space variables {p : ℕ} [hp : p.prime] include hp @[simp] protected lemma mul (q r : ℚ_[p]) : ∥q * r∥ = ∥q∥ * ∥r∥ := by simp [has_norm.norm, padic_norm_e.mul'] protected lemma is_norm (q : ℚ_[p]) : ↑(padic_norm_e q) = ∥q∥ := rfl theorem nonarchimedean (q r : ℚ_[p]) : ∥q + r∥ ≤ max (∥q∥) (∥r∥) := begin unfold has_norm.norm, exact_mod_cast nonarchimedean' _ _ end theorem add_eq_max_of_ne {q r : ℚ_[p]} (h : ∥q∥ ≠ ∥r∥) : ∥q+r∥ = max (∥q∥) (∥r∥) := begin unfold has_norm.norm, apply_mod_cast add_eq_max_of_ne', intro h', apply h, unfold has_norm.norm, exact_mod_cast h' end @[simp] lemma eq_padic_norm (q : ℚ) : ∥(↑q : ℚ_[p])∥ = padic_norm p q := begin unfold has_norm.norm, rw [← padic_norm_e.eq_padic_norm', ← padic.cast_eq_of_rat] end instance : nondiscrete_normed_field ℚ_[p] := { non_trivial := ⟨padic.of_rat p (p⁻¹), begin have h0 : p ≠ 0 := ne_of_gt (hp.pos), have h1 : 1 < p := hp.one_lt, rw [← padic.cast_eq_of_rat, eq_padic_norm], simp only [padic_norm, inv_eq_zero], simp only [if_neg] {discharger := `[exact_mod_cast h0]}, norm_cast, simp only [padic_val_rat.inv] {discharger := `[exact_mod_cast h0]}, rw [neg_neg, padic_val_rat.padic_val_rat_self h1], erw _root_.pow_one, exact_mod_cast h1, end⟩ } protected theorem image {q : ℚ_[p]} : q ≠ 0 → ∃ n : ℤ, ∥q∥ = ↑((↑p : ℚ) ^ (-n)) := quotient.induction_on q $ λ f hf, have ¬ f ≈ 0, from (padic_seq.ne_zero_iff_nequiv_zero f).1 hf, let ⟨n, hn⟩ := padic_seq.norm_image f this in ⟨n, congr_arg coe hn⟩ protected lemma is_rat (q : ℚ_[p]) : ∃ q' : ℚ, ∥q∥ = ↑q' := if h : q = 0 then ⟨0, by simp [h]⟩ else let ⟨n, hn⟩ := padic_norm_e.image h in ⟨_, hn⟩ def rat_norm (q : ℚ_[p]) : ℚ := classical.some (padic_norm_e.is_rat q) lemma eq_rat_norm (q : ℚ_[p]) : ∥q∥ = rat_norm q := classical.some_spec (padic_norm_e.is_rat q) theorem norm_rat_le_one : ∀ {q : ℚ} (hq : ¬ p ∣ q.denom), ∥(q : ℚ_[p])∥ ≤ 1 | ⟨n, d, hn, hd⟩ := λ hq : ¬ p ∣ d, if hnz : n = 0 then have (⟨n, d, hn, hd⟩ : ℚ) = 0, from rat.zero_iff_num_zero.mpr hnz, by norm_num [this] else begin have hnz' : {rat . num := n, denom := d, pos := hn, cop := hd} ≠ 0, from mt rat.zero_iff_num_zero.1 hnz, rw [padic_norm_e.eq_padic_norm], norm_cast, rw [padic_norm.eq_fpow_of_nonzero p hnz', padic_val_rat_def p hnz'], have h : (multiplicity p d).get _ = 0, by simp [multiplicity_eq_zero_of_not_dvd, hq], simp only [], norm_cast, rw_mod_cast [h, sub_zero], apply fpow_le_one_of_nonpos, { exact_mod_cast le_of_lt hp.one_lt, }, { apply neg_nonpos_of_nonneg, norm_cast, simp, } end lemma eq_of_norm_add_lt_right {p : ℕ} {hp : p.prime} {z1 z2 : ℚ_[p]} (h : ∥z1 + z2∥ < ∥z2∥) : ∥z1∥ = ∥z2∥ := by_contradiction $ λ hne, not_lt_of_ge (by rw padic_norm_e.add_eq_max_of_ne hne; apply le_max_right) h lemma eq_of_norm_add_lt_left {p : ℕ} {hp : p.prime} {z1 z2 : ℚ_[p]} (h : ∥z1 + z2∥ < ∥z1∥) : ∥z1∥ = ∥z2∥ := by_contradiction $ λ hne, not_lt_of_ge (by rw padic_norm_e.add_eq_max_of_ne hne; apply le_max_left) h end normed_space end padic_norm_e namespace padic variables {p : ℕ} [nat.prime p] set_option eqn_compiler.zeta true instance complete : cau_seq.is_complete ℚ_[p] norm := begin split, intro f, have cau_seq_norm_e : is_cau_seq padic_norm_e f, { intros ε hε, let h := is_cau f ε (by exact_mod_cast hε), unfold norm at h, apply_mod_cast h }, cases padic.complete' ⟨f, cau_seq_norm_e⟩ with q hq, existsi q, intros ε hε, cases exists_rat_btwn hε with ε' hε', norm_cast at hε', cases hq ε' hε'.1 with N hN, existsi N, intros i hi, let h := hN i hi, unfold norm, rw_mod_cast [cau_seq.sub_apply, padic_norm_e.sub_rev], refine lt.trans _ hε'.2, exact_mod_cast hN i hi end lemma padic_norm_e_lim_le {f : cau_seq ℚ_[p] norm} {a : ℝ} (ha : a > 0) (hf : ∀ i, ∥f i∥ ≤ a) : ∥f.lim∥ ≤ a := let ⟨N, hN⟩ := setoid.symm (cau_seq.equiv_lim f) _ ha in calc ∥f.lim∥ = ∥f.lim - f N + f N∥ : by simp ... ≤ max (∥f.lim - f N∥) (∥f N∥) : padic_norm_e.nonarchimedean _ _ ... ≤ a : max_le (le_of_lt (hN _ (le_refl _))) (hf _) end padic
998b3fc2441678c192109a1ec4ecb5320252115c
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/stage0/src/Lean/Meta/Match/CaseArraySizes.lean
370e6a51d7e1de590992068735fe432020371eb0
[ "Apache-2.0" ]
permissive
williamdemeo/lean4
72161c58fe65c3ad955d6a3050bb7d37c04c0d54
6d00fcf1d6d873e195f9220c668ef9c58e9c4a35
refs/heads/master
1,678,305,356,877
1,614,708,995,000
1,614,708,995,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,826
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Tactic.Assert import Lean.Meta.Match.CaseValues namespace Lean.Meta structure CaseArraySizesSubgoal where mvarId : MVarId elems : Array FVarId := #[] diseqs : Array FVarId := #[] subst : FVarSubst := {} instance : Inhabited CaseArraySizesSubgoal := ⟨{ mvarId := arbitrary }⟩ def getArrayArgType (a : Expr) : MetaM Expr := do let aType ← inferType a let aType ← whnfD aType unless aType.isAppOfArity `Array 1 do throwError! "array expected{indentExpr a}" pure aType.appArg! private def mkArrayGetLit (a : Expr) (i : Nat) (n : Nat) (h : Expr) : MetaM Expr := do let lt ← mkLt (mkNatLit i) (mkNatLit n) let ltPrf ← mkDecideProof lt mkAppM `Array.getLit #[a, mkNatLit i, h, ltPrf] private partial def introArrayLit (mvarId : MVarId) (a : Expr) (n : Nat) (xNamePrefix : Name) (aSizeEqN : Expr) : MetaM MVarId := do let α ← getArrayArgType a let rec loop (i : Nat) (xs : Array Expr) (args : Array Expr) := do if i < n then withLocalDeclD (xNamePrefix.appendIndexAfter (i+1)) α fun xi => do let xs := xs.push xi let ai ← mkArrayGetLit a i n aSizeEqN let args := args.push ai loop (i+1) xs args else let xsLit ← mkArrayLit α xs.toList let aEqXsLit ← mkEq a xsLit let aEqLitPrf ← mkAppM `Array.toArrayLitEq #[a, mkNatLit n, aSizeEqN] withLocalDeclD `hEqALit aEqXsLit fun heq => do let target ← getMVarType mvarId let newTarget ← mkForallFVars (xs.push heq) target pure (newTarget, args.push aEqLitPrf) let (newTarget, args) ← loop 0 #[] #[] let tag ← getMVarTag mvarId let newMVar ← mkFreshExprSyntheticOpaqueMVar newTarget tag assignExprMVar mvarId (mkAppN newMVar args) pure newMVar.mvarId! /-- Split goal `... |- C a` into sizes.size + 1 subgoals 1) `..., x_1 ... x_{sizes[0]} |- C #[x_1, ... x_{sizes[0]}]` ... n) `..., x_1 ... x_{sizes[n-1]} |- C #[x_1, ..., x_{sizes[n-1]}]` n+1) `..., (h_1 : a.size != sizes[0]), ..., (h_n : a.size != sizes[n-1]) |- C a` where `n = sizes.size` -/ def caseArraySizes (mvarId : MVarId) (fvarId : FVarId) (sizes : Array Nat) (xNamePrefix := `x) (hNamePrefix := `h) : MetaM (Array CaseArraySizesSubgoal) := withMVarContext mvarId do let a := mkFVar fvarId let α ← getArrayArgType a let aSize ← mkAppM `Array.size #[a] let mvarId ← assertExt mvarId `aSize (mkConst `Nat) aSize let (aSizeFVarId, mvarId) ← intro1 mvarId let (hEq, mvarId) ← intro1 mvarId let subgoals ← caseValues mvarId aSizeFVarId (sizes.map mkNatLit) hNamePrefix subgoals.mapIdxM fun i subgoal => do let subst := subgoal.subst let mvarId := subgoal.mvarId let hEqSz := (subst.get hEq).fvarId! if h : i.val < sizes.size then let n := sizes.get ⟨i, h⟩ let mvarId ← clear mvarId subgoal.newHs[0] let mvarId ← clear mvarId (subst.get aSizeFVarId).fvarId! withMVarContext mvarId do let hEqSzSymm ← mkEqSymm (mkFVar hEqSz) let mvarId ← introArrayLit mvarId a n xNamePrefix hEqSzSymm let (xs, mvarId) ← introN mvarId n let (hEqLit, mvarId) ← intro1 mvarId let mvarId ← clear mvarId hEqSz let (subst, mvarId) ← substCore mvarId hEqLit false subst pure { mvarId := mvarId, elems := xs, subst := subst } else let (subst, mvarId) ← substCore mvarId hEq false subst let diseqs := subgoal.newHs.map fun fvarId => (subst.get fvarId).fvarId! pure { mvarId := mvarId, diseqs := diseqs, subst := subst } end Lean.Meta
385f049d619a6979a6d60b83f868ac483725e979
4e0d7c3132ce31edc5829849735dd25db406b144
/lean/love07_metaprogramming_demo.lean
36542ba8e6f88423d5daf3576339114548ac70d1
[]
no_license
gonzalgu/logical_verification_2020
a0013a6c22ea254e9f4d245f2948f0f4d44df4bb
724d0457dff2c3ff10f9ab2170388f4c5e958b75
refs/heads/master
1,660,886,374,533
1,589,859,641,000
1,589,859,641,000
256,069,971
0
0
null
1,586,997,430,000
1,586,997,429,000
null
UTF-8
Lean
false
false
14,243
lean
import .love05_inductive_predicates_demo /-! # LoVe Demo 7: Metaprogramming Users can extend Lean with custom monadic tactics and tools. This kind of programming—programming the prover—is called metaprogramming. Lean's metaprogramming framework uses mostly the same notions and syntax as Lean's input language itself. Abstract syntax trees __reflect__ internal data structures, e.g., for expressions (terms). The prover's C++ internals are exposed through Lean interfaces, which we can use for accessing the current context and goal, unifying expressions, querying and modifying the environment, and setting attributes (e.g., `@[simp]`). Most of Lean's predefined tactics are implemented in Lean (and not in C++). Example applications: * proof goal transformations; * heuristic proof search; * decision procedures; * definition generators; * advisor tools; * exporters; * ad hoc automation. Advantages of Lean's metaprogramming framework: * Users do not need to learn another programming language to write metaprograms; they can work with the same constructs and notation used to define ordinary objects in the prover's library. * Everything in that library is available for metaprogramming purposes. * Metaprograms can be written and debugged in the same interactive environment, encouraging a style where formal libraries and supporting automation are developed at the same time. -/ set_option pp.beta true namespace LoVe /-! ## Tactics and Tactic Combinators When programming our own tactics, we often need to repeat some actions on several goals, or to recover if a tactic fails. Tactic combinators help in such case. `repeat` applies its argument repeatedly on all (sub…sub)goals until it cannot be applied any further. -/ lemma repeat_example : even 4 ∧ even 7 ∧ even 3 ∧ even 0 := begin repeat { apply and.intro }, repeat { apply even.add_two }, repeat { sorry } end /-! The "orelse" combinator `<|>` tries its first argument and applies its second argument in case of failure. -/ lemma repeat_orelse_example : even 4 ∧ even 7 ∧ even 3 ∧ even 0 := begin repeat { apply and.intro }, repeat { apply even.add_two <|> apply even.zero }, repeat { sorry } end /-! `iterate` works repeatedly on the first goal until it fails; then it stops. -/ lemma iterate_orelse_example : even 4 ∧ even 7 ∧ even 3 ∧ even 0 := begin repeat { apply and.intro }, iterate { apply even.add_two <|> apply even.zero }, repeat { sorry } end /-! `all_goals` applies its argument exactly once to each goal. It succeeds only if the argument succeeds on **all** goals. -/ lemma all_goals_example : even 4 ∧ even 7 ∧ even 3 ∧ even 0 := begin repeat { apply and.intro }, all_goals { apply even.add_two }, -- fails repeat { sorry } end /-! `try` transforms its argument into a tactic that never fails. -/ lemma all_goals_try_example : even 4 ∧ even 7 ∧ even 3 ∧ even 0 := begin repeat { apply and.intro }, all_goals { try { apply even.add_two } }, repeat { sorry } end /-! `any_goals` applies its argument exactly once to each goal. It succeeds if the argument succeeds on **any** goal. -/ lemma any_goals_example : even 4 ∧ even 7 ∧ even 3 ∧ even 0 := begin repeat { apply and.intro }, any_goals { apply even.add_two }, repeat { sorry } end /-! `solve1` transforms its argument into an all-or-nothing tactic. If the argument does not prove the goal, `solve1` fails. -/ lemma any_goals_solve1_repeat_orelse_example : even 4 ∧ even 7 ∧ even 3 ∧ even 0 := begin repeat { apply and.intro }, any_goals { solve1 { repeat { apply even.add_two <|> apply even.zero } } }, repeat { sorry } end /-! The combinators `repeat`, `iterate`, `all_goals`, and `any_goals` can easily lead to infinite looping: -/ /-! lemma repeat_not_example : ¬ even 1 := begin repeat { apply not.intro }, sorry end -/ /-! Let us start with the actual metaprogramming, by coding a custom tactic. The tactic embodies the behavior we hardcoded in the `solve1` example above: -/ meta def intro_and_even : tactic unit := do tactic.repeat (tactic.applyc ``and.intro), tactic.any_goals (tactic.solve1 (tactic.repeat (tactic.applyc ``even.add_two <|> tactic.applyc ``even.zero))) /-! The `meta` keyword makes it possible for the function to call other metafunctions. The `do` keyword enters a monad, and the `<|>` operator is the "orelse" operator of alternative monads. Any executable Lean definition can be used as a metaprogram. In addition, we can put `meta` in front of a definition to indicate that is a metadefinition. Such definitions need not terminate but cannot be used in non-`meta` contexts. Let us apply our custom tactic: -/ lemma any_goals_solve1_repeat_orelse_example₂ : even 4 ∧ even 7 ∧ even 3 ∧ even 0 := begin intro_and_even, repeat { sorry } end /-! ## The Metaprogramming Monad Tactics have access to * the list of **goals** as metavariables (each metavariables has a type and a local context (hypothesis); they can optionally be instantiated); * the **elaborator** (to elaborate expressions and compute their type); * the **environment**, containing all declarations and inductive types; * the **attributes** (e.g., the list of `@[simp]` rules). The tactic monad is an alternative monad, with `fail` and `<|>`. Tactics can also produce trace messages. -/ lemma even_14 : even 14 := by do tactic.trace "Proving evenness …", intro_and_even meta def hello_then_intro_and_even : tactic unit := do tactic.trace "Proving evenness …", intro_and_even lemma even_16 : even 16 := by hello_then_intro_and_even run_cmd tactic.trace "Hello, Metaworld!" meta def trace_goals : tactic unit := do tactic.trace "local context:", ctx ← tactic.local_context, tactic.trace ctx, tactic.trace "target:", P ← tactic.target, tactic.trace P, tactic.trace "all missing proofs:", Hs ← tactic.get_goals, tactic.trace Hs, τs ← list.mmap tactic.infer_type Hs, tactic.trace τs lemma even_18_and_even_20 (α : Type) (a : α) : even 18 ∧ even 20 := by do tactic.applyc ``and.intro, trace_goals, intro_and_even lemma triv_imp (a : Prop) (h : a) : a := by do h ← tactic.get_local `h, tactic.trace "h:", tactic.trace h, tactic.trace "raw h:", tactic.trace (expr.to_raw_fmt h), tactic.trace "type of h:", τ ← tactic.infer_type h, tactic.trace τ, tactic.trace "type of type of h:", υ ← tactic.infer_type τ, tactic.trace υ, tactic.apply h meta def exact_list : list expr → tactic unit | [] := tactic.fail "no matching expression found" | (h :: hs) := do { tactic.trace "trying", tactic.trace h, tactic.exact h } <|> exact_list hs meta def hypothesis : tactic unit := do hs ← tactic.local_context, exact_list hs lemma p_a_of_p_a {α : Type} {p : α → Prop} {a : α} (h : p a) : p a := by hypothesis /-! ## Names, Expressions, Declarations, and Environments The metaprogramming framework is articulated around five main types: * `tactic` manages the proof state, the global context, and more; * `name` represents a structured name (e.g., `x`, `even.add_two`); * `expr` represents an expression (a term) as an abstract syntax tree; * `declaration` represents a constant declaration, a definition, an axiom, or a lemma; * `environment` stores all the declarations and notations that make up the global context. -/ #print expr #check expr tt -- elaborated expressions #check expr ff -- unelaborated expressions (pre-expressions) #print name #check (expr.const `ℕ [] : expr) #check expr.sort level.zero -- Sort 0, i.e., Prop #check expr.sort (level.succ level.zero) -- Sort 1, i.e., Type #check expr.var 0 -- bound variable with De Bruijn index 0 #check (expr.local_const `uniq_name `pp_name binder_info.default `(ℕ) : expr) #check (expr.mvar `uniq_name `pp_name `(ℕ) : expr) #check (expr.pi `pp_name binder_info.default `(ℕ) (expr.sort level.zero) : expr) #check (expr.lam `pp_name binder_info.default `(ℕ) (expr.var 0) : expr) #check expr.elet #check expr.macro /-! We can create literal expressions conveniently using backticks and parentheses: * Expressions with a single backtick must be fully elaborated. * Expressions with two backticks are __pre-expressions__: They may contain some holes to be filled in later, based on some context. * Expressions with three backticks are pre-expressions without name checking. -/ run_cmd do let e : expr := `(list.map (λn : ℕ, n + 1) [1, 2, 3]), tactic.trace e run_cmd do let e : expr := `(list.map _ [1, 2, 3]), -- fails tactic.trace e run_cmd do let e₁ : pexpr := ``(list.map (λn, n + 1) [1, 2, 3]), let e₂ : pexpr := ``(list.map _ [1, 2, 3]), tactic.trace e₁, tactic.trace e₂ run_cmd do let e : pexpr := ```(seattle.washington), tactic.trace e /-! We can also create literal names with backticks: * Names with a single backtick, `n, are not checked for existence. * Names with two backticks, ``n, are resolved and checked. -/ run_cmd tactic.trace `and.intro run_cmd tactic.trace `intro_and_even run_cmd tactic.trace `seattle.washington run_cmd tactic.trace ``and.intro run_cmd tactic.trace ``intro_and_even run_cmd tactic.trace ``seattle.washington -- fails /-! __Antiquotations__ embed an existing expression in a larger expression. They are announced by the prefix `%%` followed by a name from the current context. Antiquotations are available with one, two, and three backticks: -/ run_cmd do let x : expr := `(2 : ℕ), let e : expr := `(%%x + 1), tactic.trace e run_cmd do let x : expr := `(@id ℕ), let e : pexpr := ``(list.map %%x), tactic.trace e run_cmd do let x : expr := `(@id ℕ), let e : pexpr := ```(a _ %%x), tactic.trace e lemma one_add_two_eq_three : 1 + 2 = 3 := by do `(%%a + %%b = %%c) ← tactic.target, tactic.trace a, tactic.trace b, tactic.trace c, `(@eq %%α %%l %%r) ← tactic.target, tactic.trace α, tactic.trace l, tactic.trace r, tactic.exact `(refl _ : 3 = 3) #print declaration /-! The `environment` type is presented as an abstract type, equipped with some operations to query and modify it. The `environment.fold` metafunction iterates over all declarations making up the environment. -/ run_cmd do env ← tactic.get_env, tactic.trace (environment.fold env 0 (λdecl n, n + 1)) /-! ## First Example: A Conjuction-Destructing Tactic We define a `destruct_and` tactic that automates the elimination of `∧` in premises, automating proofs such as these: -/ lemma abcd_a (a b c d : Prop) (h : a ∧ (b ∧ c) ∧ d) : a := and.elim_left h lemma abcd_b (a b c d : Prop) (h : a ∧ (b ∧ c) ∧ d) : b := and.elim_left (and.elim_left (and.elim_right h)) lemma abcd_bc (a b c d : Prop) (h : a ∧ (b ∧ c) ∧ d) : b ∧ c := and.elim_left (and.elim_right h) /-! Our tactic relies on a helper metafunction, which takes as argument the hypothesis `h` to use as an expression rather than as a name: -/ meta def destruct_and_helper : expr → tactic unit | h := do t ← tactic.infer_type h, match t with | `(%%a ∧ %%b) := tactic.exact h <|> do { ha ← tactic.to_expr ``(and.elim_left %%h), destruct_and_helper ha } <|> do { hb ← tactic.to_expr ``(and.elim_right %%h), destruct_and_helper hb } | _ := tactic.exact h end meta def destruct_and (nam : name) : tactic unit := do h ← tactic.get_local nam, destruct_and_helper h /-! Let us check that our tactic works: -/ lemma abc_a (a b c : Prop) (h : a ∧ b ∧ c) : a := by destruct_and `h lemma abc_b (a b c : Prop) (h : a ∧ b ∧ c) : b := by destruct_and `h lemma abc_bc (a b c : Prop) (h : a ∧ b ∧ c) : b ∧ c := by destruct_and `h lemma abc_ac (a b c : Prop) (h : a ∧ b ∧ c) : a ∧ c := by destruct_and `h -- fails /-! ## Second Example: A Provability Advisor Next, we implement a `prove_direct` tool that traverses all lemmas in the database and checks whether one of them can be used to prove the current goal. A similar tactic is available in `mathlib` under the name `library_search`. -/ meta def is_theorem : declaration → bool | (declaration.defn _ _ _ _ _ _) := ff | (declaration.thm _ _ _ _) := tt | (declaration.cnst _ _ _ _) := ff | (declaration.ax _ _ _) := tt meta def get_all_theorems : tactic (list name) := do env ← tactic.get_env, pure (environment.fold env [] (λdecl nams, if is_theorem decl then declaration.to_name decl :: nams else nams)) meta def prove_with_name (nam : name) : tactic unit := do tactic.applyc nam ({ md := tactic.transparency.reducible, unify := ff } : tactic.apply_cfg), tactic.all_goals tactic.assumption meta def prove_direct : tactic unit := do nams ← get_all_theorems, list.mfirst (λnam, do prove_with_name nam, tactic.trace ("directly proved by " ++ to_string nam)) nams lemma nat.eq_symm (x y : ℕ) (h : x = y) : y = x := by prove_direct lemma nat.eq_symm₂ (x y : ℕ) (h : x = y) : y = x := by library_search lemma list.reverse_twice (xs : list ℕ) : list.reverse (list.reverse xs) = xs := by prove_direct lemma list.reverse_twice_symm (xs : list ℕ) : xs = list.reverse (list.reverse xs) := by prove_direct -- fails /-! As a small refinement, we propose a version of `prove_direct` that also looks for equalities stated in symmetric form. -/ meta def prove_direct_symm : tactic unit := prove_direct <|> do { tactic.applyc `eq.symm, prove_direct } lemma list.reverse_twice₂ (xs : list ℕ) : list.reverse (list.reverse xs) = xs := by prove_direct_symm lemma list.reverse_twice_symm₂ (xs : list ℕ) : xs = list.reverse (list.reverse xs) := by prove_direct_symm /-! ## A Look at Two Predefined Tactics Quite a few of Lean's predefined tactics are implemented as metaprograms and not in C++. We can find these definitions by clicking the name of a construct in Visual Studio Code while holding the control or command key. -/ #check tactic.intro #check tactic.assumption end LoVe
e8e7d416ed147091082a2fc1d7360f02faeb652e
94e33a31faa76775069b071adea97e86e218a8ee
/src/analysis/inner_product_space/pi_L2.lean
13bab813b7523af6f4e60fab6fcc75df4ba87732
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
22,783
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Myers, Sébastien Gouëzel, Heather Macbeth -/ import analysis.inner_product_space.projection import analysis.normed_space.pi_Lp /-! # `L²` inner product space structure on finite products of inner product spaces The `L²` norm on a finite product of inner product spaces is compatible with an inner product $$ \langle x, y\rangle = \sum \langle x_i, y_i \rangle. $$ This is recorded in this file as an inner product space instance on `pi_Lp 2`. ## Main definitions - `euclidean_space 𝕜 n`: defined to be `pi_Lp 2 (n → 𝕜)` for any `fintype n`, i.e., the space from functions to `n` to `𝕜` with the `L²` norm. We register several instances on it (notably that it is a finite-dimensional inner product space). - `orthonormal_basis 𝕜 ι`: defined to be an isometry to Euclidean space from a given finite-dimensional innner product space, `E ≃ₗᵢ[𝕜] euclidean_space 𝕜 ι`. - `basis.to_orthonormal_basis`: constructs an `orthonormal_basis` for a finite-dimensional Euclidean space from a `basis` which is `orthonormal`. - `linear_isometry_equiv.of_inner_product_space`: provides an arbitrary isometry to Euclidean space from a given finite-dimensional inner product space, induced by choosing an arbitrary basis. - `complex.isometry_euclidean`: standard isometry from `ℂ` to `euclidean_space ℝ (fin 2)` -/ open real set filter is_R_or_C open_locale big_operators uniformity topological_space nnreal ennreal complex_conjugate direct_sum noncomputable theory variables {ι : Type*} {ι' : Type*} variables {𝕜 : Type*} [is_R_or_C 𝕜] {E : Type*} [inner_product_space 𝕜 E] variables {E' : Type*} [inner_product_space 𝕜 E'] variables {F : Type*} [inner_product_space ℝ F] variables {F' : Type*} [inner_product_space ℝ F'] local notation `⟪`x`, `y`⟫` := @inner 𝕜 _ _ x y /- If `ι` is a finite type and each space `f i`, `i : ι`, is an inner product space, then `Π i, f i` is an inner product space as well. Since `Π i, f i` is endowed with the sup norm, we use instead `pi_Lp 2 f` for the product space, which is endowed with the `L^2` norm. -/ instance pi_Lp.inner_product_space {ι : Type*} [fintype ι] (f : ι → Type*) [Π i, inner_product_space 𝕜 (f i)] : inner_product_space 𝕜 (pi_Lp 2 f) := { inner := λ x y, ∑ i, inner (x i) (y i), norm_sq_eq_inner := begin intro x, have h₂ : 0 ≤ ∑ (i : ι), ∥x i∥ ^ (2 : ℝ) := finset.sum_nonneg (λ j hj, rpow_nonneg_of_nonneg (norm_nonneg (x j)) 2), simp only [norm, add_monoid_hom.map_sum, ← norm_sq_eq_inner, one_div], rw [← rpow_nat_cast ((∑ (i : ι), ∥x i∥ ^ (2 : ℝ)) ^ (2 : ℝ)⁻¹) 2, ← rpow_mul h₂], norm_num, end, conj_sym := begin intros x y, unfold inner, rw ring_hom.map_sum, apply finset.sum_congr rfl, rintros z -, apply inner_conj_sym, end, add_left := λ x y z, show ∑ i, inner (x i + y i) (z i) = ∑ i, inner (x i) (z i) + ∑ i, inner (y i) (z i), by simp only [inner_add_left, finset.sum_add_distrib], smul_left := λ x y r, show ∑ (i : ι), inner (r • x i) (y i) = (conj r) * ∑ i, inner (x i) (y i), by simp only [finset.mul_sum, inner_smul_left] } @[simp] lemma pi_Lp.inner_apply {ι : Type*} [fintype ι] {f : ι → Type*} [Π i, inner_product_space 𝕜 (f i)] (x y : pi_Lp 2 f) : ⟪x, y⟫ = ∑ i, ⟪x i, y i⟫ := rfl /-- The standard real/complex Euclidean space, functions on a finite type. For an `n`-dimensional space use `euclidean_space 𝕜 (fin n)`. -/ @[reducible, nolint unused_arguments] def euclidean_space (𝕜 : Type*) [is_R_or_C 𝕜] (n : Type*) [fintype n] : Type* := pi_Lp 2 (λ (i : n), 𝕜) lemma euclidean_space.norm_eq {𝕜 : Type*} [is_R_or_C 𝕜] {n : Type*} [fintype n] (x : euclidean_space 𝕜 n) : ∥x∥ = real.sqrt (∑ i, ∥x i∥ ^ 2) := pi_Lp.norm_eq_of_L2 x lemma euclidean_space.nnnorm_eq {𝕜 : Type*} [is_R_or_C 𝕜] {n : Type*} [fintype n] (x : euclidean_space 𝕜 n) : ∥x∥₊ = nnreal.sqrt (∑ i, ∥x i∥₊ ^ 2) := pi_Lp.nnnorm_eq_of_L2 x lemma euclidean_space.dist_eq {𝕜 : Type*} [is_R_or_C 𝕜] {n : Type*} [fintype n] (x y : euclidean_space 𝕜 n) : dist x y = (∑ i, dist (x i) (y i) ^ 2).sqrt := (pi_Lp.dist_eq_of_L2 x y : _) lemma euclidean_space.nndist_eq {𝕜 : Type*} [is_R_or_C 𝕜] {n : Type*} [fintype n] (x y : euclidean_space 𝕜 n) : nndist x y = (∑ i, nndist (x i) (y i) ^ 2).sqrt := (pi_Lp.nndist_eq_of_L2 x y : _) lemma euclidean_space.edist_eq {𝕜 : Type*} [is_R_or_C 𝕜] {n : Type*} [fintype n] (x y : euclidean_space 𝕜 n) : edist x y = (∑ i, edist (x i) (y i) ^ 2) ^ (1 / 2 : ℝ) := (pi_Lp.edist_eq_of_L2 x y : _) variables [fintype ι] section local attribute [reducible] pi_Lp instance : finite_dimensional 𝕜 (euclidean_space 𝕜 ι) := by apply_instance instance : inner_product_space 𝕜 (euclidean_space 𝕜 ι) := by apply_instance @[simp] lemma finrank_euclidean_space : finite_dimensional.finrank 𝕜 (euclidean_space 𝕜 ι) = fintype.card ι := by simp lemma finrank_euclidean_space_fin {n : ℕ} : finite_dimensional.finrank 𝕜 (euclidean_space 𝕜 (fin n)) = n := by simp lemma euclidean_space.inner_eq_star_dot_product (x y : euclidean_space 𝕜 ι) : ⟪x, y⟫ = matrix.dot_product (star $ pi_Lp.equiv _ _ x) (pi_Lp.equiv _ _ y) := rfl /-- A finite, mutually orthogonal family of subspaces of `E`, which span `E`, induce an isometry from `E` to `pi_Lp 2` of the subspaces equipped with the `L2` inner product. -/ def direct_sum.is_internal.isometry_L2_of_orthogonal_family [decidable_eq ι] {V : ι → submodule 𝕜 E} (hV : direct_sum.is_internal V) (hV' : @orthogonal_family 𝕜 _ _ _ _ (λ i, V i) _ (λ i, (V i).subtypeₗᵢ)) : E ≃ₗᵢ[𝕜] pi_Lp 2 (λ i, V i) := begin let e₁ := direct_sum.linear_equiv_fun_on_fintype 𝕜 ι (λ i, V i), let e₂ := linear_equiv.of_bijective (direct_sum.coe_linear_map V) hV.injective hV.surjective, refine (e₂.symm.trans e₁).isometry_of_inner _, suffices : ∀ v w, ⟪v, w⟫ = ⟪e₂ (e₁.symm v), e₂ (e₁.symm w)⟫, { intros v₀ w₀, convert this (e₁ (e₂.symm v₀)) (e₁ (e₂.symm w₀)); simp only [linear_equiv.symm_apply_apply, linear_equiv.apply_symm_apply] }, intros v w, transitivity ⟪(∑ i, (V i).subtypeₗᵢ (v i)), ∑ i, (V i).subtypeₗᵢ (w i)⟫, { simp only [sum_inner, hV'.inner_right_fintype, pi_Lp.inner_apply] }, { congr; simp } end @[simp] lemma direct_sum.is_internal.isometry_L2_of_orthogonal_family_symm_apply [decidable_eq ι] {V : ι → submodule 𝕜 E} (hV : direct_sum.is_internal V) (hV' : @orthogonal_family 𝕜 _ _ _ _ (λ i, V i) _ (λ i, (V i).subtypeₗᵢ)) (w : pi_Lp 2 (λ i, V i)) : (hV.isometry_L2_of_orthogonal_family hV').symm w = ∑ i, (w i : E) := begin classical, let e₁ := direct_sum.linear_equiv_fun_on_fintype 𝕜 ι (λ i, V i), let e₂ := linear_equiv.of_bijective (direct_sum.coe_linear_map V) hV.injective hV.surjective, suffices : ∀ v : ⨁ i, V i, e₂ v = ∑ i, e₁ v i, { exact this (e₁.symm w) }, intros v, simp [e₂, direct_sum.coe_linear_map, direct_sum.to_module, dfinsupp.sum_add_hom_apply] end end /-- The vector given in euclidean space by being `1 : 𝕜` at coordinate `i : ι` and `0 : 𝕜` at all other coordinates. -/ def euclidean_space.single [decidable_eq ι] (i : ι) (a : 𝕜) : euclidean_space 𝕜 ι := (pi_Lp.equiv _ _).symm (pi.single i a) @[simp] lemma pi_Lp.equiv_single [decidable_eq ι] (i : ι) (a : 𝕜) : pi_Lp.equiv _ _ (euclidean_space.single i a) = pi.single i a := rfl @[simp] lemma pi_Lp.equiv_symm_single [decidable_eq ι] (i : ι) (a : 𝕜) : (pi_Lp.equiv _ _).symm (pi.single i a) = euclidean_space.single i a := rfl @[simp] theorem euclidean_space.single_apply [decidable_eq ι] (i : ι) (a : 𝕜) (j : ι) : (euclidean_space.single i a) j = ite (j = i) a 0 := by { rw [euclidean_space.single, pi_Lp.equiv_symm_apply, ← pi.single_apply i a j] } lemma euclidean_space.inner_single_left [decidable_eq ι] (i : ι) (a : 𝕜) (v : euclidean_space 𝕜 ι) : ⟪euclidean_space.single i (a : 𝕜), v⟫ = conj a * (v i) := by simp [apply_ite conj] lemma euclidean_space.inner_single_right [decidable_eq ι] (i : ι) (a : 𝕜) (v : euclidean_space 𝕜 ι) : ⟪v, euclidean_space.single i (a : 𝕜)⟫ = a * conj (v i) := by simp [apply_ite conj, mul_comm] variables (ι 𝕜 E) /-- An orthonormal basis on E is an identification of `E` with its dimensional-matching `euclidean_space 𝕜 ι`. -/ structure orthonormal_basis := of_repr :: (repr : E ≃ₗᵢ[𝕜] euclidean_space 𝕜 ι) variables {ι 𝕜 E} namespace orthonormal_basis instance : inhabited (orthonormal_basis ι 𝕜 (euclidean_space 𝕜 ι)) := ⟨of_repr (linear_isometry_equiv.refl 𝕜 (euclidean_space 𝕜 ι))⟩ /-- `b i` is the `i`th basis vector. -/ instance : has_coe_to_fun (orthonormal_basis ι 𝕜 E) (λ _, ι → E) := { coe := λ b i, by classical; exact b.repr.symm (euclidean_space.single i (1 : 𝕜)) } @[simp] protected lemma repr_symm_single [decidable_eq ι] (b : orthonormal_basis ι 𝕜 E) (i : ι) : b.repr.symm (euclidean_space.single i (1:𝕜)) = b i := by { classical, congr, simp, } @[simp] protected lemma repr_self [decidable_eq ι] (b : orthonormal_basis ι 𝕜 E) (i : ι) : b.repr (b i) = euclidean_space.single i (1:𝕜) := by rw [← b.repr_symm_single i, linear_isometry_equiv.apply_symm_apply] protected lemma repr_apply_apply (b : orthonormal_basis ι 𝕜 E) (v : E) (i : ι) : b.repr v i = ⟪b i, v⟫ := begin classical, rw [← b.repr.inner_map_map (b i) v, b.repr_self i, euclidean_space.inner_single_left], simp only [one_mul, eq_self_iff_true, map_one], end @[simp] protected lemma orthonormal (b : orthonormal_basis ι 𝕜 E) : orthonormal 𝕜 b := begin classical, rw orthonormal_iff_ite, intros i j, rw [← b.repr.inner_map_map (b i) (b j), b.repr_self i, b.repr_self j], rw euclidean_space.inner_single_left, rw euclidean_space.single_apply, simp only [mul_boole, map_one], end /-- The `basis ι 𝕜 E` underlying the `orthonormal_basis` --/ protected def to_basis (b : orthonormal_basis ι 𝕜 E) : basis ι 𝕜 E := basis.of_equiv_fun b.repr.to_linear_equiv @[simp] protected lemma coe_to_basis (b : orthonormal_basis ι 𝕜 E) : (⇑b.to_basis : ι → E) = ⇑b := begin change ⇑(basis.of_equiv_fun b.repr.to_linear_equiv) = b, ext j, rw basis.coe_of_equiv_fun, simp only [orthonormal_basis.repr_symm_single], congr, end @[simp] protected lemma coe_to_basis_repr (b : orthonormal_basis ι 𝕜 E) : b.to_basis.equiv_fun = b.repr.to_linear_equiv := begin change (basis.of_equiv_fun b.repr.to_linear_equiv).equiv_fun = b.repr.to_linear_equiv, ext x j, simp only [basis.of_equiv_fun_repr_apply, eq_self_iff_true, linear_isometry_equiv.coe_to_linear_equiv, basis.equiv_fun_apply], end protected lemma sum_repr_symm (b : orthonormal_basis ι 𝕜 E) (v : euclidean_space 𝕜 ι) : ∑ i , v i • b i = (b.repr.symm v) := by { classical, simpa using (b.to_basis.equiv_fun_symm_apply v).symm } variable {v : ι → E} /-- A basis that is orthonormal is an orthonormal basis. -/ def _root_.basis.to_orthonormal_basis (v : basis ι 𝕜 E) (hv : orthonormal 𝕜 v) : orthonormal_basis ι 𝕜 E := orthonormal_basis.of_repr $ linear_equiv.isometry_of_inner v.equiv_fun begin intros x y, let p : euclidean_space 𝕜 ι := v.equiv_fun x, let q : euclidean_space 𝕜 ι := v.equiv_fun y, have key : ⟪p, q⟫ = ⟪∑ i, p i • v i, ∑ i, q i • v i⟫, { simp [sum_inner, inner_smul_left, hv.inner_right_fintype] }, convert key, { rw [← v.equiv_fun.symm_apply_apply x, v.equiv_fun_symm_apply] }, { rw [← v.equiv_fun.symm_apply_apply y, v.equiv_fun_symm_apply] } end @[simp] lemma _root_.basis.coe_to_orthonormal_basis_repr (v : basis ι 𝕜 E) (hv : orthonormal 𝕜 v) : ((v.to_orthonormal_basis hv).repr : E → euclidean_space 𝕜 ι) = v.equiv_fun := rfl @[simp] lemma _root_.basis.coe_to_orthonormal_basis_repr_symm (v : basis ι 𝕜 E) (hv : orthonormal 𝕜 v) : ((v.to_orthonormal_basis hv).repr.symm : euclidean_space 𝕜 ι → E) = v.equiv_fun.symm := rfl @[simp] lemma _root_.basis.to_basis_to_orthonormal_basis (v : basis ι 𝕜 E) (hv : orthonormal 𝕜 v) : (v.to_orthonormal_basis hv).to_basis = v := by simp [basis.to_orthonormal_basis, orthonormal_basis.to_basis] @[simp] lemma _root_.basis.coe_to_orthonormal_basis (v : basis ι 𝕜 E) (hv : orthonormal 𝕜 v) : (v.to_orthonormal_basis hv : ι → E) = (v : ι → E) := calc (v.to_orthonormal_basis hv : ι → E) = ((v.to_orthonormal_basis hv).to_basis : ι → E) : by { classical, rw orthonormal_basis.coe_to_basis } ... = (v : ι → E) : by simp /-- An orthonormal set that spans is an orthonormal basis -/ protected def mk (hon : orthonormal 𝕜 v) (hsp: submodule.span 𝕜 (set.range v) = ⊤): orthonormal_basis ι 𝕜 E := (basis.mk (orthonormal.linear_independent hon) hsp).to_orthonormal_basis (by rwa basis.coe_mk) @[simp] protected lemma coe_mk (hon : orthonormal 𝕜 v) (hsp: submodule.span 𝕜 (set.range v) = ⊤) : ⇑(orthonormal_basis.mk hon hsp) = v := by classical; rw [orthonormal_basis.mk, _root_.basis.coe_to_orthonormal_basis, basis.coe_mk] end orthonormal_basis /-- If `f : E ≃ₗᵢ[𝕜] E'` is a linear isometry of inner product spaces then an orthonormal basis `v` of `E` determines a linear isometry `e : E' ≃ₗᵢ[𝕜] euclidean_space 𝕜 ι`. This result states that `e` may be obtained either by transporting `v` to `E'` or by composing with the linear isometry `E ≃ₗᵢ[𝕜] euclidean_space 𝕜 ι` provided by `v`. -/ @[simp] lemma basis.map_isometry_euclidean_of_orthonormal (v : basis ι 𝕜 E) (hv : orthonormal 𝕜 v) (f : E ≃ₗᵢ[𝕜] E') : ((v.map f.to_linear_equiv).to_orthonormal_basis (hv.map_linear_isometry_equiv f)).repr = f.symm.trans (v.to_orthonormal_basis hv).repr := linear_isometry_equiv.to_linear_equiv_injective $ v.map_equiv_fun _ /-- `ℂ` is isometric to `ℝ²` with the Euclidean inner product. -/ def complex.isometry_euclidean : ℂ ≃ₗᵢ[ℝ] (euclidean_space ℝ (fin 2)) := (complex.basis_one_I.to_orthonormal_basis begin rw orthonormal_iff_ite, intros i, fin_cases i; intros j; fin_cases j; simp [real_inner_eq_re_inner] end).repr @[simp] lemma complex.isometry_euclidean_symm_apply (x : euclidean_space ℝ (fin 2)) : complex.isometry_euclidean.symm x = (x 0) + (x 1) * I := begin convert complex.basis_one_I.equiv_fun_symm_apply x, { simpa }, { simp }, end lemma complex.isometry_euclidean_proj_eq_self (z : ℂ) : ↑(complex.isometry_euclidean z 0) + ↑(complex.isometry_euclidean z 1) * (I : ℂ) = z := by rw [← complex.isometry_euclidean_symm_apply (complex.isometry_euclidean z), complex.isometry_euclidean.symm_apply_apply z] @[simp] lemma complex.isometry_euclidean_apply_zero (z : ℂ) : complex.isometry_euclidean z 0 = z.re := by { conv_rhs { rw ← complex.isometry_euclidean_proj_eq_self z }, simp } @[simp] lemma complex.isometry_euclidean_apply_one (z : ℂ) : complex.isometry_euclidean z 1 = z.im := by { conv_rhs { rw ← complex.isometry_euclidean_proj_eq_self z }, simp } /-- The isometry between `ℂ` and a two-dimensional real inner product space given by a basis. -/ def complex.isometry_of_orthonormal {v : basis (fin 2) ℝ F} (hv : orthonormal ℝ v) : ℂ ≃ₗᵢ[ℝ] F := complex.isometry_euclidean.trans (v.to_orthonormal_basis hv).repr.symm @[simp] lemma complex.map_isometry_of_orthonormal {v : basis (fin 2) ℝ F} (hv : orthonormal ℝ v) (f : F ≃ₗᵢ[ℝ] F') : complex.isometry_of_orthonormal (hv.map_linear_isometry_equiv f) = (complex.isometry_of_orthonormal hv).trans f := by simp [complex.isometry_of_orthonormal, linear_isometry_equiv.trans_assoc] lemma complex.isometry_of_orthonormal_symm_apply {v : basis (fin 2) ℝ F} (hv : orthonormal ℝ v) (f : F) : (complex.isometry_of_orthonormal hv).symm f = (v.coord 0 f : ℂ) + (v.coord 1 f : ℂ) * I := by simp [complex.isometry_of_orthonormal] lemma complex.isometry_of_orthonormal_apply {v : basis (fin 2) ℝ F} (hv : orthonormal ℝ v) (z : ℂ) : complex.isometry_of_orthonormal hv z = z.re • v 0 + z.im • v 1 := by simp [complex.isometry_of_orthonormal, (dec_trivial : (finset.univ : finset (fin 2)) = {0, 1})] open finite_dimensional /-- Given a natural number `n` equal to the `finrank` of a finite-dimensional inner product space, there exists an isometry from the space to `euclidean_space 𝕜 (fin n)`. -/ def linear_isometry_equiv.of_inner_product_space [finite_dimensional 𝕜 E] {n : ℕ} (hn : finrank 𝕜 E = n) : E ≃ₗᵢ[𝕜] (euclidean_space 𝕜 (fin n)) := ((fin_std_orthonormal_basis hn).to_orthonormal_basis (fin_std_orthonormal_basis_orthonormal hn)).repr local attribute [instance] fact_finite_dimensional_of_finrank_eq_succ /-- Given a natural number `n` one less than the `finrank` of a finite-dimensional inner product space, there exists an isometry from the orthogonal complement of a nonzero singleton to `euclidean_space 𝕜 (fin n)`. -/ def linear_isometry_equiv.from_orthogonal_span_singleton (n : ℕ) [fact (finrank 𝕜 E = n + 1)] {v : E} (hv : v ≠ 0) : (𝕜 ∙ v)ᗮ ≃ₗᵢ[𝕜] (euclidean_space 𝕜 (fin n)) := linear_isometry_equiv.of_inner_product_space (finrank_orthogonal_span_singleton hv) section linear_isometry variables {V : Type*} [inner_product_space 𝕜 V] [finite_dimensional 𝕜 V] variables {S : submodule 𝕜 V} {L : S →ₗᵢ[𝕜] V} open finite_dimensional /-- Let `S` be a subspace of a finite-dimensional complex inner product space `V`. A linear isometry mapping `S` into `V` can be extended to a full isometry of `V`. TODO: The case when `S` is a finite-dimensional subspace of an infinite-dimensional `V`.-/ noncomputable def linear_isometry.extend (L : S →ₗᵢ[𝕜] V): V →ₗᵢ[𝕜] V := begin -- Build an isometry from Sᗮ to L(S)ᗮ through euclidean_space let d := finrank 𝕜 Sᗮ, have dim_S_perp : finrank 𝕜 Sᗮ = d := rfl, let LS := L.to_linear_map.range, have E : Sᗮ ≃ₗᵢ[𝕜] LSᗮ, { have dim_LS_perp : finrank 𝕜 LSᗮ = d, calc finrank 𝕜 LSᗮ = finrank 𝕜 V - finrank 𝕜 LS : by simp only [← LS.finrank_add_finrank_orthogonal, add_tsub_cancel_left] ... = finrank 𝕜 V - finrank 𝕜 S : by simp only [linear_map.finrank_range_of_inj L.injective] ... = finrank 𝕜 Sᗮ : by simp only [← S.finrank_add_finrank_orthogonal, add_tsub_cancel_left] ... = d : dim_S_perp, let BS := ((fin_std_orthonormal_basis dim_S_perp).to_orthonormal_basis (fin_std_orthonormal_basis_orthonormal dim_S_perp)), let BLS := ((fin_std_orthonormal_basis dim_LS_perp).to_orthonormal_basis (fin_std_orthonormal_basis_orthonormal dim_LS_perp)), exact BS.repr.trans BLS.repr.symm }, let L3 := (LS)ᗮ.subtypeₗᵢ.comp E.to_linear_isometry, -- Project onto S and Sᗮ haveI : complete_space S := finite_dimensional.complete 𝕜 S, haveI : complete_space V := finite_dimensional.complete 𝕜 V, let p1 := (orthogonal_projection S).to_linear_map, let p2 := (orthogonal_projection Sᗮ).to_linear_map, -- Build a linear map from the isometries on S and Sᗮ let M := L.to_linear_map.comp p1 + L3.to_linear_map.comp p2, -- Prove that M is an isometry have M_norm_map : ∀ (x : V), ∥M x∥ = ∥x∥, { intro x, -- Apply M to the orthogonal decomposition of x have Mx_decomp : M x = L (p1 x) + L3 (p2 x), { simp only [linear_map.add_apply, linear_map.comp_apply, linear_map.comp_apply, linear_isometry.coe_to_linear_map]}, -- Mx_decomp is the orthogonal decomposition of M x have Mx_orth : ⟪ L (p1 x), L3 (p2 x) ⟫ = 0, { have Lp1x : L (p1 x) ∈ L.to_linear_map.range := L.to_linear_map.mem_range_self (p1 x), have Lp2x : L3 (p2 x) ∈ (L.to_linear_map.range)ᗮ, { simp only [L3, linear_isometry.coe_comp, function.comp_app, submodule.coe_subtypeₗᵢ, ← submodule.range_subtype (LSᗮ)], apply linear_map.mem_range_self}, apply submodule.inner_right_of_mem_orthogonal Lp1x Lp2x}, -- Apply the Pythagorean theorem and simplify rw [← sq_eq_sq (norm_nonneg _) (norm_nonneg _), norm_sq_eq_add_norm_sq_projection x S], simp only [sq, Mx_decomp], rw norm_add_sq_eq_norm_sq_add_norm_sq_of_inner_eq_zero (L (p1 x)) (L3 (p2 x)) Mx_orth, simp only [linear_isometry.norm_map, p1, p2, continuous_linear_map.to_linear_map_eq_coe, add_left_inj, mul_eq_mul_left_iff, norm_eq_zero, true_or, eq_self_iff_true, continuous_linear_map.coe_coe, submodule.coe_norm, submodule.coe_eq_zero] }, exact { to_linear_map := M, norm_map' := M_norm_map }, end lemma linear_isometry.extend_apply (L : S →ₗᵢ[𝕜] V) (s : S): L.extend s = L s := begin haveI : complete_space S := finite_dimensional.complete 𝕜 S, simp only [linear_isometry.extend, continuous_linear_map.to_linear_map_eq_coe, ←linear_isometry.coe_to_linear_map], simp only [add_right_eq_self, linear_isometry.coe_to_linear_map, linear_isometry_equiv.coe_to_linear_isometry, linear_isometry.coe_comp, function.comp_app, orthogonal_projection_mem_subspace_eq_self, linear_map.coe_comp, continuous_linear_map.coe_coe, submodule.coe_subtype, linear_map.add_apply, submodule.coe_eq_zero, linear_isometry_equiv.map_eq_zero_iff, submodule.coe_subtypeₗᵢ, orthogonal_projection_mem_subspace_orthogonal_complement_eq_zero, submodule.orthogonal_orthogonal, submodule.coe_mem], end end linear_isometry section matrix open_locale matrix variables {n m : ℕ} local notation `⟪`x`, `y`⟫ₘ` := @inner 𝕜 (euclidean_space 𝕜 (fin m)) _ x y local notation `⟪`x`, `y`⟫ₙ` := @inner 𝕜 (euclidean_space 𝕜 (fin n)) _ x y /-- The inner product of a row of A and a row of B is an entry of B ⬝ Aᴴ. -/ lemma inner_matrix_row_row (A B : matrix (fin n) (fin m) 𝕜) (i j : (fin n)) : ⟪A i, B j⟫ₘ = (B ⬝ Aᴴ) j i := by {simp only [inner, matrix.mul_apply, star_ring_end_apply, matrix.conj_transpose_apply,mul_comm]} /-- The inner product of a column of A and a column of B is an entry of Aᴴ ⬝ B -/ lemma inner_matrix_col_col (A B : matrix (fin n) (fin m) 𝕜) (i j : (fin m)) : ⟪Aᵀ i, Bᵀ j⟫ₙ = (Aᴴ ⬝ B) i j := rfl end matrix
b8e87f98d897cdbb468791f823e80224b2f82c08
5749d8999a76f3a8fddceca1f6941981e33aaa96
/src/order/filter/bases.lean
884fc6d8a4b507da509aff50d74d5d7554386698
[ "Apache-2.0" ]
permissive
jdsalchow/mathlib
13ab43ef0d0515a17e550b16d09bd14b76125276
497e692b946d93906900bb33a51fd243e7649406
refs/heads/master
1,585,819,143,348
1,580,072,892,000
1,580,072,892,000
154,287,128
0
0
Apache-2.0
1,540,281,610,000
1,540,281,609,000
null
UTF-8
Lean
false
false
8,660
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Yury Kudryashov -/ import order.filter.basic /-! # Filter bases In this file we define `filter.has_basis l p s`, where `l` is a filter on `α`, `p` is a predicate on some index set `ι`, and `s : ι → set α`. ## Main statements * `has_basis.mem_iff`, `has_basis.mem_of_superset`, `has_basis.mem_of_mem` : restate `t ∈ f` in terms of a basis; * `basis_sets` : all sets of a filter form a basis; * `has_basis.inf`, `has_basis.inf_principal`, `has_basis.prod`, `has_basis.prod_self`, `has_basis.map`, `has_basis.comap` : combinators to construct filters of `l ⊓ l'`, `l ⊓ principal t`, `l.prod l'`, `l.prod l`, `l.map f`, `l.comap f` respectively; * `has_basis.le_iff`, `has_basis.ge_iff`, has_basis.le_basis_iff` : restate `l ≤ l'` in terms of bases. * `has_basis.tendsto_right_iff`, `has_basis.tendsto_left_iff`, `has_basis.tendsto_iff` : restate `tendsto f l l'` in terms of bases. ## Implementation notes As with `Union`/`bUnion`/`sUnion`, there are three different approaches to filter bases: * `has_basis l s`, `s : set (set α)`; * `has_basis l s`, `s : ι → set α`; * `has_basis l p s`, `p : ι → Prop`, `s : ι → set α`. We use the latter one because, e.g., `𝓝 x` in an `emetric_space` or in a `metric_space` has a basis of this form. The other two can be emulated using `s = id` or `p = λ _, true`. With this approach sometimes one needs to `simp` the statement provided by the `has_basis` machinery, e.g., `simp only [exists_prop, true_and]` or `simp only [forall_const]` can help with the case `p = λ _, true`. -/ namespace filter variables {α : Type*} {β : Type*} {γ : Type*} {ι : Type*} {ι' : Type*} open set lattice /-- We say that a filter `l` has a basis `s : ι → set α` bounded by `p : ι → Prop`, if `t ∈ l` if and only if `t` includes `s i` for some `i` such that `p i`. -/ protected def has_basis (l : filter α) (p : ι → Prop) (s : ι → set α) : Prop := ∀ t : set α, t ∈ l ↔ ∃ i (hi : p i), s i ⊆ t section same_type variables {l l' : filter α} {p : ι → Prop} {s : ι → set α} {t : set α} {i : ι} {p' : ι' → Prop} {s' : ι' → set α} {i' : ι'} /-- Definition of `has_basis` unfolded to make it useful for `rw` and `simp`. -/ lemma has_basis.mem_iff (hl : l.has_basis p s) : t ∈ l ↔ ∃ i (hi : p i), s i ⊆ t := hl t lemma has_basis.mem_of_superset (hl : l.has_basis p s) (hi : p i) (ht : s i ⊆ t) : t ∈ l := (hl t).2 ⟨i, hi, ht⟩ lemma has_basis.mem_of_mem (hl : l.has_basis p s) (hi : p i) : s i ∈ l := hl.mem_of_superset hi $ subset.refl _ lemma has_basis.forall_nonempty_iff_ne_bot (hl : l.has_basis p s) : (∀ {i}, p i → (s i).nonempty) ↔ l ≠ ⊥ := ⟨λ H, forall_sets_nonempty_iff_ne_bot.1 $ λ s hs, let ⟨i, hi, his⟩ := (hl s).1 hs in (H hi).of_subset his, λ H i hi, inhabited_of_mem_sets H (hl.mem_of_mem hi)⟩ lemma basis_sets (l : filter α) : l.has_basis (λ s : set α, s ∈ l) id := λ t, exists_sets_subset_iff.symm lemma at_top_basis [nonempty α] [semilattice_sup α] : (@at_top α _).has_basis (λ _, true) Ici := λ t, by simpa only [exists_prop, true_and] using @mem_at_top_sets α _ _ t lemma at_top_basis' [semilattice_sup α] (a : α) : (@at_top α _).has_basis (λ x, a ≤ x) Ici := λ t, (@at_top_basis α ⟨a⟩ _ t).trans ⟨λ ⟨x, _, hx⟩, ⟨x ⊔ a, le_sup_right, λ y hy, hx (le_trans le_sup_left hy)⟩, λ ⟨x, _, hx⟩, ⟨x, trivial, hx⟩⟩ theorem has_basis.ge_iff (hl' : l'.has_basis p' s') : l ≤ l' ↔ ∀ i', p' i' → s' i' ∈ l := ⟨λ h i' hi', h $ hl'.mem_of_mem hi', λ h s hs, let ⟨i', hi', hs⟩ := (hl' s).1 hs in mem_sets_of_superset (h _ hi') hs⟩ theorem has_basis.le_iff (hl : l.has_basis p s) : l ≤ l' ↔ ∀ t ∈ l', ∃ i (hi : p i), s i ⊆ t := by simp only [le_def, hl.mem_iff] theorem has_basis.le_basis_iff (hl : l.has_basis p s) (hl' : l'.has_basis p' s') : l ≤ l' ↔ ∀ i', p' i' → ∃ i (hi : p i), s i ⊆ s' i' := by simp only [hl'.ge_iff, hl.mem_iff] lemma has_basis.inf (hl : l.has_basis p s) (hl' : l'.has_basis p' s') : (l ⊓ l').has_basis (λ i : ι × ι', p i.1 ∧ p' i.2) (λ i, s i.1 ∩ s' i.2) := begin intro t, simp only [mem_inf_sets, exists_prop, hl.mem_iff, hl'.mem_iff], split, { rintros ⟨t, ⟨i, hi, ht⟩, t', ⟨i', hi', ht'⟩, H⟩, use [(i, i'), ⟨hi, hi'⟩, subset.trans (inter_subset_inter ht ht') H] }, { rintros ⟨⟨i, i'⟩, ⟨hi, hi'⟩, H⟩, use [s i, i, hi, subset.refl _, s' i', i', hi', subset.refl _, H] } end lemma has_basis.inf_principal (hl : l.has_basis p s) (s' : set α) : (l ⊓ principal s').has_basis p (λ i, s i ∩ s') := λ t, by simp only [mem_inf_principal, hl.mem_iff, subset_def, mem_set_of_eq, mem_inter_iff, and_imp] lemma has_basis.eq_binfi (h : l.has_basis p s) : l = ⨅ i (_ : p i), principal (s i) := eq_binfi_of_mem_sets_iff_exists_mem $ λ t, by simp only [h.mem_iff, mem_principal_sets] lemma has_basis.eq_infi (h : l.has_basis (λ _, true) s) : l = ⨅ i, principal (s i) := by simpa only [infi_true] using h.eq_binfi @[nolint] -- see Note [nolint_ge] lemma has_basis_infi_principal {s : ι → set α} (h : directed (≥) s) (ne : nonempty ι) : (⨅ i, principal (s i)).has_basis (λ _, true) s := begin refine λ t, (mem_infi (h.mono_comp _ _) ne t).trans $ by simp only [exists_prop, true_and, mem_principal_sets], exact λ _ _, principal_mono.2 end @[nolint] -- see Note [nolint_ge] lemma has_basis_binfi_principal {s : β → set α} {S : set β} (h : directed_on (s ⁻¹'o (≥)) S) (ne : S.nonempty) : (⨅ i ∈ S, principal (s i)).has_basis (λ i, i ∈ S) s := begin refine λ t, (mem_binfi _ ne).trans $ by simp only [mem_principal_sets], rw [directed_on_iff_directed, ← directed_comp, (∘)] at h ⊢, apply h.mono_comp _ _, exact λ _ _, principal_mono.2 end lemma has_basis.map (f : α → β) (hl : l.has_basis p s) : (l.map f).has_basis p (λ i, f '' (s i)) := λ t, by simp only [mem_map, image_subset_iff, hl.mem_iff, preimage] lemma has_basis.comap (f : β → α) (hl : l.has_basis p s) : (l.comap f).has_basis p (λ i, f ⁻¹' (s i)) := begin intro t, simp only [mem_comap_sets, exists_prop, hl.mem_iff], split, { rintros ⟨t', ⟨i, hi, ht'⟩, H⟩, exact ⟨i, hi, subset.trans (preimage_mono ht') H⟩ }, { rintros ⟨i, hi, H⟩, exact ⟨s i, ⟨i, hi, subset.refl _⟩, H⟩ } end lemma has_basis.prod_self (hl : l.has_basis p s) : (l.prod l).has_basis p (λ i, (s i).prod (s i)) := begin intro t, apply mem_prod_iff.trans, split, { rintros ⟨t₁, ht₁, t₂, ht₂, H⟩, rcases hl.mem_iff.1 (inter_mem_sets ht₁ ht₂) with ⟨i, hi, ht⟩, exact ⟨i, hi, λ p ⟨hp₁, hp₂⟩, H ⟨(ht hp₁).1, (ht hp₂).2⟩⟩ }, { rintros ⟨i, hi, H⟩, exact ⟨s i, hl.mem_of_mem hi, s i, hl.mem_of_mem hi, H⟩ } end end same_type section two_types variables {la : filter α} {pa : ι → Prop} {sa : ι → set α} {lb : filter β} {pb : ι' → Prop} {sb : ι' → set β} {f : α → β} lemma has_basis.tendsto_left_iff (hla : la.has_basis pa sa) : tendsto f la lb ↔ ∀ t ∈ lb, ∃ i (hi : pa i), ∀ x ∈ sa i, f x ∈ t := by { simp only [tendsto, (hla.map f).le_iff, image_subset_iff], refl } lemma has_basis.tendsto_right_iff (hlb : lb.has_basis pb sb) : tendsto f la lb ↔ ∀ i (hi : pb i), {x | f x ∈ sb i} ∈ la := by simp only [tendsto, hlb.ge_iff, mem_map, preimage] lemma has_basis.tendsto_iff (hla : la.has_basis pa sa) (hlb : lb.has_basis pb sb) : tendsto f la lb ↔ ∀ ib (hib : pb ib), ∃ ia (hia : pa ia), ∀ x ∈ sa ia, f x ∈ sb ib := by simp only [hlb.tendsto_right_iff, hla.mem_iff, subset_def, mem_set_of_eq] lemma tendsto.basis_left (H : tendsto f la lb) (hla : la.has_basis pa sa) : ∀ t ∈ lb, ∃ i (hi : pa i), ∀ x ∈ sa i, f x ∈ t := hla.tendsto_left_iff.1 H lemma tendsto.basis_right (H : tendsto f la lb) (hlb : lb.has_basis pb sb) : ∀ i (hi : pb i), {x | f x ∈ sb i} ∈ la := hlb.tendsto_right_iff.1 H lemma tendsto.basis_both (H : tendsto f la lb) (hla : la.has_basis pa sa) (hlb : lb.has_basis pb sb) : ∀ ib (hib : pb ib), ∃ ia (hia : pa ia), ∀ x ∈ sa ia, f x ∈ sb ib := (hla.tendsto_iff hlb).1 H lemma has_basis.prod (hla : la.has_basis pa sa) (hlb : lb.has_basis pb sb) : (la.prod lb).has_basis (λ i : ι × ι', pa i.1 ∧ pb i.2) (λ i, (sa i.1).prod (sb i.2)) := (hla.comap prod.fst).inf (hlb.comap prod.snd) end two_types end filter
1281276a01915b60027b5e17938d7f2b31076004
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/data/multiset/basic.lean
aa0e5ab1edeb95e5253f7b7db585670e8dc2d14b
[ "Apache-2.0" ]
permissive
abentkamp/mathlib
d9a75d291ec09f4637b0f30cc3880ffb07549ee5
5360e476391508e092b5a1e5210bd0ed22dc0755
refs/heads/master
1,682,382,954,948
1,622,106,077,000
1,622,106,077,000
149,285,665
0
0
null
null
null
null
UTF-8
Lean
false
false
98,219
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.list.perm import algebra.group_power /-! # Multisets These are implemented as the quotient of a list by permutations. ## Notation We define the global infix notation `::ₘ` for `multiset.cons`. -/ open list subtype nat variables {α : Type*} {β : Type*} {γ : Type*} /-- `multiset α` is the quotient of `list α` by list permutation. The result is a type of finite sets with duplicates allowed. -/ def {u} multiset (α : Type u) : Type u := quotient (list.is_setoid α) namespace multiset instance : has_coe (list α) (multiset α) := ⟨quot.mk _⟩ @[simp] theorem quot_mk_to_coe (l : list α) : @eq (multiset α) ⟦l⟧ l := rfl @[simp] theorem quot_mk_to_coe' (l : list α) : @eq (multiset α) (quot.mk (≈) l) l := rfl @[simp] theorem quot_mk_to_coe'' (l : list α) : @eq (multiset α) (quot.mk setoid.r l) l := rfl @[simp] theorem coe_eq_coe {l₁ l₂ : list α} : (l₁ : multiset α) = l₂ ↔ l₁ ~ l₂ := quotient.eq instance has_decidable_eq [decidable_eq α] : decidable_eq (multiset α) | s₁ s₂ := quotient.rec_on_subsingleton₂ s₁ s₂ $ λ l₁ l₂, decidable_of_iff' _ quotient.eq /-- defines a size for a multiset by referring to the size of the underlying list -/ protected def sizeof [has_sizeof α] (s : multiset α) : ℕ := quot.lift_on s sizeof $ λ l₁ l₂, perm.sizeof_eq_sizeof instance has_sizeof [has_sizeof α] : has_sizeof (multiset α) := ⟨multiset.sizeof⟩ /-! ### Empty multiset -/ /-- `0 : multiset α` is the empty set -/ protected def zero : multiset α := @nil α instance : has_zero (multiset α) := ⟨multiset.zero⟩ instance : has_emptyc (multiset α) := ⟨0⟩ instance inhabited_multiset : inhabited (multiset α) := ⟨0⟩ @[simp] theorem coe_nil_eq_zero : (@nil α : multiset α) = 0 := rfl @[simp] theorem empty_eq_zero : (∅ : multiset α) = 0 := rfl theorem coe_eq_zero (l : list α) : (l : multiset α) = 0 ↔ l = [] := iff.trans coe_eq_coe perm_nil /-! ### `multiset.cons` -/ /-- `cons a s` is the multiset which contains `s` plus one more instance of `a`. -/ def cons (a : α) (s : multiset α) : multiset α := quot.lift_on s (λ l, (a :: l : multiset α)) (λ l₁ l₂ p, quot.sound (p.cons a)) infixr ` ::ₘ `:67 := multiset.cons instance : has_insert α (multiset α) := ⟨cons⟩ @[simp] theorem insert_eq_cons (a : α) (s : multiset α) : insert a s = a ::ₘ s := rfl @[simp] theorem cons_coe (a : α) (l : list α) : (a ::ₘ l : multiset α) = (a::l : list α) := rfl theorem singleton_coe (a : α) : (a ::ₘ 0 : multiset α) = ([a] : list α) := rfl @[simp] theorem cons_inj_left {a b : α} (s : multiset α) : a ::ₘ s = b ::ₘ s ↔ a = b := ⟨quot.induction_on s $ λ l e, have [a] ++ l ~ [b] ++ l, from quotient.exact e, singleton_perm_singleton.1 $ (perm_append_right_iff _).1 this, congr_arg _⟩ @[simp] theorem cons_inj_right (a : α) : ∀{s t : multiset α}, a ::ₘ s = a ::ₘ t ↔ s = t := by rintros ⟨l₁⟩ ⟨l₂⟩; simp @[recursor 5] protected theorem induction {p : multiset α → Prop} (h₁ : p 0) (h₂ : ∀ ⦃a : α⦄ {s : multiset α}, p s → p (a ::ₘ s)) : ∀s, p s := by rintros ⟨l⟩; induction l with _ _ ih; [exact h₁, exact h₂ ih] @[elab_as_eliminator] protected theorem induction_on {p : multiset α → Prop} (s : multiset α) (h₁ : p 0) (h₂ : ∀ ⦃a : α⦄ {s : multiset α}, p s → p (a ::ₘ s)) : p s := multiset.induction h₁ h₂ s theorem cons_swap (a b : α) (s : multiset α) : a ::ₘ b ::ₘ s = b ::ₘ a ::ₘ s := quot.induction_on s $ λ l, quotient.sound $ perm.swap _ _ _ section rec variables {C : multiset α → Sort*} /-- Dependent recursor on multisets. TODO: should be @[recursor 6], but then the definition of `multiset.pi` fails with a stack overflow in `whnf`. -/ protected def rec (C_0 : C 0) (C_cons : Πa m, C m → C (a ::ₘ m)) (C_cons_heq : ∀ a a' m b, C_cons a (a' ::ₘ m) (C_cons a' m b) == C_cons a' (a ::ₘ m) (C_cons a m b)) (m : multiset α) : C m := quotient.hrec_on m (@list.rec α (λl, C ⟦l⟧) C_0 (λa l b, C_cons a ⟦l⟧ b)) $ assume l l' h, h.rec_heq (assume a l l' b b' hl, have ⟦l⟧ = ⟦l'⟧, from quot.sound hl, by cc) (assume a a' l, C_cons_heq a a' ⟦l⟧) @[elab_as_eliminator] protected def rec_on (m : multiset α) (C_0 : C 0) (C_cons : Πa m, C m → C (a ::ₘ m)) (C_cons_heq : ∀a a' m b, C_cons a (a' ::ₘ m) (C_cons a' m b) == C_cons a' (a ::ₘ m) (C_cons a m b)) : C m := multiset.rec C_0 C_cons C_cons_heq m variables {C_0 : C 0} {C_cons : Πa m, C m → C (a ::ₘ m)} {C_cons_heq : ∀a a' m b, C_cons a (a' ::ₘ m) (C_cons a' m b) == C_cons a' (a ::ₘ m) (C_cons a m b)} @[simp] lemma rec_on_0 : @multiset.rec_on α C (0:multiset α) C_0 C_cons C_cons_heq = C_0 := rfl @[simp] lemma rec_on_cons (a : α) (m : multiset α) : (a ::ₘ m).rec_on C_0 C_cons C_cons_heq = C_cons a m (m.rec_on C_0 C_cons C_cons_heq) := quotient.induction_on m $ assume l, rfl end rec section mem /-- `a ∈ s` means that `a` has nonzero multiplicity in `s`. -/ def mem (a : α) (s : multiset α) : Prop := quot.lift_on s (λ l, a ∈ l) (λ l₁ l₂ (e : l₁ ~ l₂), propext $ e.mem_iff) instance : has_mem α (multiset α) := ⟨mem⟩ @[simp] lemma mem_coe {a : α} {l : list α} : a ∈ (l : multiset α) ↔ a ∈ l := iff.rfl instance decidable_mem [decidable_eq α] (a : α) (s : multiset α) : decidable (a ∈ s) := quot.rec_on_subsingleton s $ list.decidable_mem a @[simp] theorem mem_cons {a b : α} {s : multiset α} : a ∈ b ::ₘ s ↔ a = b ∨ a ∈ s := quot.induction_on s $ λ l, iff.rfl lemma mem_cons_of_mem {a b : α} {s : multiset α} (h : a ∈ s) : a ∈ b ::ₘ s := mem_cons.2 $ or.inr h @[simp] theorem mem_cons_self (a : α) (s : multiset α) : a ∈ a ::ₘ s := mem_cons.2 (or.inl rfl) theorem forall_mem_cons {p : α → Prop} {a : α} {s : multiset α} : (∀ x ∈ (a ::ₘ s), p x) ↔ p a ∧ ∀ x ∈ s, p x := quotient.induction_on' s $ λ L, list.forall_mem_cons theorem exists_cons_of_mem {s : multiset α} {a : α} : a ∈ s → ∃ t, s = a ::ₘ t := quot.induction_on s $ λ l (h : a ∈ l), let ⟨l₁, l₂, e⟩ := mem_split h in e.symm ▸ ⟨(l₁++l₂ : list α), quot.sound perm_middle⟩ @[simp] theorem not_mem_zero (a : α) : a ∉ (0 : multiset α) := id theorem eq_zero_of_forall_not_mem {s : multiset α} : (∀x, x ∉ s) → s = 0 := quot.induction_on s $ λ l H, by rw eq_nil_iff_forall_not_mem.mpr H; refl theorem eq_zero_iff_forall_not_mem {s : multiset α} : s = 0 ↔ ∀ a, a ∉ s := ⟨λ h, h.symm ▸ λ _, not_false, eq_zero_of_forall_not_mem⟩ theorem exists_mem_of_ne_zero {s : multiset α} : s ≠ 0 → ∃ a : α, a ∈ s := quot.induction_on s $ assume l hl, match l, hl with | [] := assume h, false.elim $ h rfl | (a :: l) := assume _, ⟨a, by simp⟩ end @[simp] lemma zero_ne_cons {a : α} {m : multiset α} : 0 ≠ a ::ₘ m := assume h, have a ∈ (0:multiset α), from h.symm ▸ mem_cons_self _ _, not_mem_zero _ this @[simp] lemma cons_ne_zero {a : α} {m : multiset α} : a ::ₘ m ≠ 0 := zero_ne_cons.symm lemma cons_eq_cons {a b : α} {as bs : multiset α} : a ::ₘ as = b ::ₘ bs ↔ ((a = b ∧ as = bs) ∨ (a ≠ b ∧ ∃cs, as = b ::ₘ cs ∧ bs = a ::ₘ cs)) := begin haveI : decidable_eq α := classical.dec_eq α, split, { assume eq, by_cases a = b, { subst h, simp * at * }, { have : a ∈ b ::ₘ bs, from eq ▸ mem_cons_self _ _, have : a ∈ bs, by simpa [h], rcases exists_cons_of_mem this with ⟨cs, hcs⟩, simp [h, hcs], have : a ::ₘ as = b ::ₘ a ::ₘ cs, by simp [eq, hcs], have : a ::ₘ as = a ::ₘ b ::ₘ cs, by rwa [cons_swap], simpa using this } }, { assume h, rcases h with ⟨eq₁, eq₂⟩ | ⟨h, cs, eq₁, eq₂⟩, { simp * }, { simp [*, cons_swap a b] } } end end mem /-! ### `multiset.subset` -/ section subset /-- `s ⊆ t` is the lift of the list subset relation. It means that any element with nonzero multiplicity in `s` has nonzero multiplicity in `t`, but it does not imply that the multiplicity of `a` in `s` is less or equal than in `t`; see `s ≤ t` for this relation. -/ protected def subset (s t : multiset α) : Prop := ∀ ⦃a : α⦄, a ∈ s → a ∈ t instance : has_subset (multiset α) := ⟨multiset.subset⟩ @[simp] theorem coe_subset {l₁ l₂ : list α} : (l₁ : multiset α) ⊆ l₂ ↔ l₁ ⊆ l₂ := iff.rfl @[simp] theorem subset.refl (s : multiset α) : s ⊆ s := λ a h, h theorem subset.trans {s t u : multiset α} : s ⊆ t → t ⊆ u → s ⊆ u := λ h₁ h₂ a m, h₂ (h₁ m) theorem subset_iff {s t : multiset α} : s ⊆ t ↔ (∀⦃x⦄, x ∈ s → x ∈ t) := iff.rfl theorem mem_of_subset {s t : multiset α} {a : α} (h : s ⊆ t) : a ∈ s → a ∈ t := @h _ @[simp] theorem zero_subset (s : multiset α) : 0 ⊆ s := λ a, (not_mem_nil a).elim @[simp] theorem cons_subset {a : α} {s t : multiset α} : (a ::ₘ s) ⊆ t ↔ a ∈ t ∧ s ⊆ t := by simp [subset_iff, or_imp_distrib, forall_and_distrib] theorem eq_zero_of_subset_zero {s : multiset α} (h : s ⊆ 0) : s = 0 := eq_zero_of_forall_not_mem h theorem subset_zero {s : multiset α} : s ⊆ 0 ↔ s = 0 := ⟨eq_zero_of_subset_zero, λ xeq, xeq.symm ▸ subset.refl 0⟩ lemma induction_on' {p : multiset α → Prop} (S : multiset α) (h₁ : p ∅) (h₂ : ∀ {a s}, a ∈ S → s ⊆ S → p s → p (insert a s)) : p S := @multiset.induction_on α (λ T, T ⊆ S → p T) S (λ _, h₁) (λ a s hps hs, let ⟨hS, sS⟩ := cons_subset.1 hs in h₂ hS sS (hps sS)) (subset.refl S) end subset section to_list /-- Produces a list of the elements in the multiset using choice. -/ @[reducible] noncomputable def to_list {α : Type*} (s : multiset α) := classical.some (quotient.exists_rep s) @[simp] lemma to_list_zero {α : Type*} : (multiset.to_list 0 : list α) = [] := (multiset.coe_eq_zero _).1 (classical.some_spec (quotient.exists_rep multiset.zero)) @[simp, norm_cast] lemma coe_to_list {α : Type*} (s : multiset α) : (s.to_list : multiset α) = s := classical.some_spec (quotient.exists_rep _) @[simp] lemma mem_to_list {α : Type*} (a : α) (s : multiset α) : a ∈ s.to_list ↔ a ∈ s := by rw [←multiset.mem_coe, multiset.coe_to_list] end to_list /-! ### Partial order on `multiset`s -/ /-- `s ≤ t` means that `s` is a sublist of `t` (up to permutation). Equivalently, `s ≤ t` means that `count a s ≤ count a t` for all `a`. -/ protected def le (s t : multiset α) : Prop := quotient.lift_on₂ s t (<+~) $ λ v₁ v₂ w₁ w₂ p₁ p₂, propext (p₂.subperm_left.trans p₁.subperm_right) instance : partial_order (multiset α) := { le := multiset.le, le_refl := by rintros ⟨l⟩; exact subperm.refl _, le_trans := by rintros ⟨l₁⟩ ⟨l₂⟩ ⟨l₃⟩; exact @subperm.trans _ _ _ _, le_antisymm := by rintros ⟨l₁⟩ ⟨l₂⟩ h₁ h₂; exact quot.sound (subperm.antisymm h₁ h₂) } theorem subset_of_le {s t : multiset α} : s ≤ t → s ⊆ t := quotient.induction_on₂ s t $ λ l₁ l₂, subperm.subset theorem mem_of_le {s t : multiset α} {a : α} (h : s ≤ t) : a ∈ s → a ∈ t := mem_of_subset (subset_of_le h) @[simp] theorem coe_le {l₁ l₂ : list α} : (l₁ : multiset α) ≤ l₂ ↔ l₁ <+~ l₂ := iff.rfl @[elab_as_eliminator] theorem le_induction_on {C : multiset α → multiset α → Prop} {s t : multiset α} (h : s ≤ t) (H : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → C l₁ l₂) : C s t := quotient.induction_on₂ s t (λ l₁ l₂ ⟨l, p, s⟩, (show ⟦l⟧ = ⟦l₁⟧, from quot.sound p) ▸ H s) h theorem zero_le (s : multiset α) : 0 ≤ s := quot.induction_on s $ λ l, (nil_sublist l).subperm theorem le_zero {s : multiset α} : s ≤ 0 ↔ s = 0 := ⟨λ h, le_antisymm h (zero_le _), le_of_eq⟩ theorem lt_cons_self (s : multiset α) (a : α) : s < a ::ₘ s := quot.induction_on s $ λ l, suffices l <+~ a :: l ∧ (¬l ~ a :: l), by simpa [lt_iff_le_and_ne], ⟨(sublist_cons _ _).subperm, λ p, ne_of_lt (lt_succ_self (length l)) p.length_eq⟩ theorem le_cons_self (s : multiset α) (a : α) : s ≤ a ::ₘ s := le_of_lt $ lt_cons_self _ _ theorem cons_le_cons_iff (a : α) {s t : multiset α} : a ::ₘ s ≤ a ::ₘ t ↔ s ≤ t := quotient.induction_on₂ s t $ λ l₁ l₂, subperm_cons a theorem cons_le_cons (a : α) {s t : multiset α} : s ≤ t → a ::ₘ s ≤ a ::ₘ t := (cons_le_cons_iff a).2 theorem le_cons_of_not_mem {a : α} {s t : multiset α} (m : a ∉ s) : s ≤ a ::ₘ t ↔ s ≤ t := begin refine ⟨_, λ h, le_trans h $ le_cons_self _ _⟩, suffices : ∀ {t'} (_ : s ≤ t') (_ : a ∈ t'), a ::ₘ s ≤ t', { exact λ h, (cons_le_cons_iff a).1 (this h (mem_cons_self _ _)) }, introv h, revert m, refine le_induction_on h _, introv s m₁ m₂, rcases mem_split m₂ with ⟨r₁, r₂, rfl⟩, exact perm_middle.subperm_left.2 ((subperm_cons _).2 $ ((sublist_or_mem_of_sublist s).resolve_right m₁).subperm) end /-! ### Additive monoid -/ /-- The sum of two multisets is the lift of the list append operation. This adds the multiplicities of each element, i.e. `count a (s + t) = count a s + count a t`. -/ protected def add (s₁ s₂ : multiset α) : multiset α := quotient.lift_on₂ s₁ s₂ (λ l₁ l₂, ((l₁ ++ l₂ : list α) : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ p₁.append p₂ instance : has_add (multiset α) := ⟨multiset.add⟩ @[simp] theorem coe_add (s t : list α) : (s + t : multiset α) = (s ++ t : list α) := rfl protected theorem add_comm (s t : multiset α) : s + t = t + s := quotient.induction_on₂ s t $ λ l₁ l₂, quot.sound perm_append_comm protected theorem zero_add (s : multiset α) : 0 + s = s := quot.induction_on s $ λ l, rfl theorem singleton_add (a : α) (s : multiset α) : ↑[a] + s = a ::ₘ s := rfl protected theorem add_le_add_left (s) {t u : multiset α} : s + t ≤ s + u ↔ t ≤ u := quotient.induction_on₃ s t u $ λ l₁ l₂ l₃, subperm_append_left _ protected theorem add_left_cancel (s) {t u : multiset α} (h : s + t = s + u) : t = u := le_antisymm ((multiset.add_le_add_left _).1 (le_of_eq h)) ((multiset.add_le_add_left _).1 (le_of_eq h.symm)) instance : ordered_cancel_add_comm_monoid (multiset α) := { zero := 0, add := (+), add_comm := multiset.add_comm, add_assoc := λ s₁ s₂ s₃, quotient.induction_on₃ s₁ s₂ s₃ $ λ l₁ l₂ l₃, congr_arg coe $ append_assoc l₁ l₂ l₃, zero_add := multiset.zero_add, add_zero := λ s, by rw [multiset.add_comm, multiset.zero_add], add_left_cancel := multiset.add_left_cancel, add_le_add_left := λ s₁ s₂ h s₃, (multiset.add_le_add_left _).2 h, le_of_add_le_add_left := λ s₁ s₂ s₃, (multiset.add_le_add_left _).1, ..@multiset.partial_order α } theorem le_add_right (s t : multiset α) : s ≤ s + t := by simpa using add_le_add_left (zero_le t) s theorem le_add_left (s t : multiset α) : s ≤ t + s := by simpa using add_le_add_right (zero_le t) s theorem le_iff_exists_add {s t : multiset α} : s ≤ t ↔ ∃ u, t = s + u := ⟨λ h, le_induction_on h $ λ l₁ l₂ s, let ⟨l, p⟩ := s.exists_perm_append in ⟨l, quot.sound p⟩, λ ⟨u, e⟩, e.symm ▸ le_add_right _ _⟩ instance : canonically_ordered_add_monoid (multiset α) := { lt_of_add_lt_add_left := λ a b c, (add_lt_add_iff_left a).mp, le_iff_exists_add := @le_iff_exists_add _, bot := 0, bot_le := multiset.zero_le, ..multiset.ordered_cancel_add_comm_monoid } @[simp] theorem cons_add (a : α) (s t : multiset α) : a ::ₘ s + t = a ::ₘ (s + t) := by rw [← singleton_add, ← singleton_add, add_assoc] @[simp] theorem add_cons (a : α) (s t : multiset α) : s + a ::ₘ t = a ::ₘ (s + t) := by rw [add_comm, cons_add, add_comm] @[simp] theorem mem_add {a : α} {s t : multiset α} : a ∈ s + t ↔ a ∈ s ∨ a ∈ t := quotient.induction_on₂ s t $ λ l₁ l₂, mem_append /-! ### Cardinality -/ /-- The cardinality of a multiset is the sum of the multiplicities of all its elements, or simply the length of the underlying list. -/ def card : multiset α →+ ℕ := { to_fun := λ s, quot.lift_on s length $ λ l₁ l₂, perm.length_eq, map_zero' := rfl, map_add' := λ s t, quotient.induction_on₂ s t length_append } @[simp] theorem coe_card (l : list α) : card (l : multiset α) = length l := rfl @[simp] theorem card_zero : @card α 0 = 0 := rfl theorem card_add (s t : multiset α) : card (s + t) = card s + card t := card.map_add s t lemma card_nsmul (s : multiset α) (n : ℕ) : (n • s).card = n * s.card := by rw [card.map_nsmul s n, nat.nsmul_eq_mul] @[simp] theorem card_cons (a : α) (s : multiset α) : card (a ::ₘ s) = card s + 1 := quot.induction_on s $ λ l, rfl @[simp] theorem card_singleton (a : α) : card (a ::ₘ 0) = 1 := by simp theorem card_le_of_le {s t : multiset α} (h : s ≤ t) : card s ≤ card t := le_induction_on h $ λ l₁ l₂, length_le_of_sublist theorem eq_of_le_of_card_le {s t : multiset α} (h : s ≤ t) : card t ≤ card s → s = t := le_induction_on h $ λ l₁ l₂ s h₂, congr_arg coe $ eq_of_sublist_of_length_le s h₂ theorem card_lt_of_lt {s t : multiset α} (h : s < t) : card s < card t := lt_of_not_ge $ λ h₂, ne_of_lt h $ eq_of_le_of_card_le (le_of_lt h) h₂ theorem lt_iff_cons_le {s t : multiset α} : s < t ↔ ∃ a, a ::ₘ s ≤ t := ⟨quotient.induction_on₂ s t $ λ l₁ l₂ h, subperm.exists_of_length_lt (le_of_lt h) (card_lt_of_lt h), λ ⟨a, h⟩, lt_of_lt_of_le (lt_cons_self _ _) h⟩ @[simp] theorem card_eq_zero {s : multiset α} : card s = 0 ↔ s = 0 := ⟨λ h, (eq_of_le_of_card_le (zero_le _) (le_of_eq h)).symm, λ e, by simp [e]⟩ theorem card_pos {s : multiset α} : 0 < card s ↔ s ≠ 0 := pos_iff_ne_zero.trans $ not_congr card_eq_zero theorem card_pos_iff_exists_mem {s : multiset α} : 0 < card s ↔ ∃ a, a ∈ s := quot.induction_on s $ λ l, length_pos_iff_exists_mem @[elab_as_eliminator] def strong_induction_on {p : multiset α → Sort*} : ∀ (s : multiset α), (∀ s, (∀t < s, p t) → p s) → p s | s := λ ih, ih s $ λ t h, have card t < card s, from card_lt_of_lt h, strong_induction_on t ih using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf card⟩]} theorem strong_induction_eq {p : multiset α → Sort*} (s : multiset α) (H) : @strong_induction_on _ p s H = H s (λ t h, @strong_induction_on _ p t H) := by rw [strong_induction_on] @[elab_as_eliminator] lemma case_strong_induction_on {p : multiset α → Prop} (s : multiset α) (h₀ : p 0) (h₁ : ∀ a s, (∀t ≤ s, p t) → p (a ::ₘ s)) : p s := multiset.strong_induction_on s $ assume s, multiset.induction_on s (λ _, h₀) $ λ a s _ ih, h₁ _ _ $ λ t h, ih _ $ lt_of_le_of_lt h $ lt_cons_self _ _ /-- Suppose that, given that `p t` can be defined on all supersets of `s` of cardinality less than `n`, one knows how to define `p s`. Then one can inductively define `p s` for all multisets `s` of cardinality less than `n`, starting from multisets of card `n` and iterating. This can be used either to define data, or to prove properties. -/ def strong_downward_induction {p : multiset α → Sort*} {n : ℕ} (H : ∀ t₁, (∀ {t₂ : multiset α}, t₂.card ≤ n → t₁ < t₂ → p t₂) → t₁.card ≤ n → p t₁) : ∀ (s : multiset α), s.card ≤ n → p s | s := H s (λ t ht h, have n - card t < n - card s, from (nat.sub_lt_sub_left_iff ht).2 (card_lt_of_lt h), strong_downward_induction t ht) using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ (t : multiset α), n - t.card)⟩]} lemma strong_downward_induction_eq {p : multiset α → Sort*} {n : ℕ} (H : ∀ t₁, (∀ {t₂ : multiset α}, t₂.card ≤ n → t₁ < t₂ → p t₂) → t₁.card ≤ n → p t₁) (s : multiset α) : strong_downward_induction H s = H s (λ t ht hst, strong_downward_induction H t ht) := by rw strong_downward_induction /-- Analogue of `strong_downward_induction` with order of arguments swapped. -/ @[elab_as_eliminator] def strong_downward_induction_on {p : multiset α → Sort*} {n : ℕ} : ∀ (s : multiset α), (∀ t₁, (∀ {t₂ : multiset α}, t₂.card ≤ n → t₁ < t₂ → p t₂) → t₁.card ≤ n → p t₁) → s.card ≤ n → p s := λ s H, strong_downward_induction H s lemma strong_downward_induction_on_eq {p : multiset α → Sort*} (s : multiset α) {n : ℕ} (H : ∀ t₁, (∀ {t₂ : multiset α}, t₂.card ≤ n → t₁ < t₂ → p t₂) → t₁.card ≤ n → p t₁) : s.strong_downward_induction_on H = H s (λ t ht h, t.strong_downward_induction_on H ht) := by { dunfold strong_downward_induction_on, rw strong_downward_induction } /-! ### Singleton -/ instance : has_singleton α (multiset α) := ⟨λ a, a ::ₘ 0⟩ instance : is_lawful_singleton α (multiset α) := ⟨λ a, rfl⟩ @[simp] theorem singleton_eq_singleton (a : α) : singleton a = a ::ₘ 0 := rfl @[simp] theorem mem_singleton {a b : α} : b ∈ a ::ₘ 0 ↔ b = a := by simp theorem mem_singleton_self (a : α) : a ∈ (a ::ₘ 0 : multiset α) := mem_cons_self _ _ theorem singleton_inj {a b : α} : a ::ₘ 0 = b ::ₘ 0 ↔ a = b := cons_inj_left _ @[simp] theorem singleton_ne_zero (a : α) : a ::ₘ 0 ≠ 0 := ne_of_gt (lt_cons_self _ _) @[simp] theorem singleton_le {a : α} {s : multiset α} : a ::ₘ 0 ≤ s ↔ a ∈ s := ⟨λ h, mem_of_le h (mem_singleton_self _), λ h, let ⟨t, e⟩ := exists_cons_of_mem h in e.symm ▸ cons_le_cons _ (zero_le _)⟩ theorem card_eq_one {s : multiset α} : card s = 1 ↔ ∃ a, s = a ::ₘ 0 := ⟨quot.induction_on s $ λ l h, (list.length_eq_one.1 h).imp $ λ a, congr_arg coe, λ ⟨a, e⟩, e.symm ▸ rfl⟩ /-! ### `multiset.repeat` -/ /-- `repeat a n` is the multiset containing only `a` with multiplicity `n`. -/ def repeat (a : α) (n : ℕ) : multiset α := repeat a n @[simp] lemma repeat_zero (a : α) : repeat a 0 = 0 := rfl @[simp] lemma repeat_succ (a : α) (n) : repeat a (n+1) = a ::ₘ repeat a n := by simp [repeat] @[simp] lemma repeat_one (a : α) : repeat a 1 = a ::ₘ 0 := by simp @[simp] lemma card_repeat : ∀ (a : α) n, card (repeat a n) = n := length_repeat theorem eq_of_mem_repeat {a b : α} {n} : b ∈ repeat a n → b = a := eq_of_mem_repeat theorem eq_repeat' {a : α} {s : multiset α} : s = repeat a s.card ↔ ∀ b ∈ s, b = a := quot.induction_on s $ λ l, iff.trans ⟨λ h, (perm_repeat.1 $ (quotient.exact h)), congr_arg coe⟩ eq_repeat' theorem eq_repeat_of_mem {a : α} {s : multiset α} : (∀ b ∈ s, b = a) → s = repeat a s.card := eq_repeat'.2 theorem eq_repeat {a : α} {n} {s : multiset α} : s = repeat a n ↔ card s = n ∧ ∀ b ∈ s, b = a := ⟨λ h, h.symm ▸ ⟨card_repeat _ _, λ b, eq_of_mem_repeat⟩, λ ⟨e, al⟩, e ▸ eq_repeat_of_mem al⟩ theorem repeat_subset_singleton : ∀ (a : α) n, repeat a n ⊆ a ::ₘ 0 := repeat_subset_singleton theorem repeat_le_coe {a : α} {n} {l : list α} : repeat a n ≤ l ↔ list.repeat a n <+ l := ⟨λ ⟨l', p, s⟩, (perm_repeat.1 p) ▸ s, sublist.subperm⟩ /-! ### Erasing one copy of an element -/ section erase variables [decidable_eq α] {s t : multiset α} {a b : α} /-- `erase s a` is the multiset that subtracts 1 from the multiplicity of `a`. -/ def erase (s : multiset α) (a : α) : multiset α := quot.lift_on s (λ l, (l.erase a : multiset α)) (λ l₁ l₂ p, quot.sound (p.erase a)) @[simp] theorem coe_erase (l : list α) (a : α) : erase (l : multiset α) a = l.erase a := rfl @[simp] theorem erase_zero (a : α) : (0 : multiset α).erase a = 0 := rfl @[simp] theorem erase_cons_head (a : α) (s : multiset α) : (a ::ₘ s).erase a = s := quot.induction_on s $ λ l, congr_arg coe $ erase_cons_head a l @[simp, priority 990] theorem erase_cons_tail {a b : α} (s : multiset α) (h : b ≠ a) : (b ::ₘ s).erase a = b ::ₘ s.erase a := quot.induction_on s $ λ l, congr_arg coe $ erase_cons_tail l h @[simp, priority 980] theorem erase_of_not_mem {a : α} {s : multiset α} : a ∉ s → s.erase a = s := quot.induction_on s $ λ l h, congr_arg coe $ erase_of_not_mem h @[simp, priority 980] theorem cons_erase {s : multiset α} {a : α} : a ∈ s → a ::ₘ s.erase a = s := quot.induction_on s $ λ l h, quot.sound (perm_cons_erase h).symm theorem le_cons_erase (s : multiset α) (a : α) : s ≤ a ::ₘ s.erase a := if h : a ∈ s then le_of_eq (cons_erase h).symm else by rw erase_of_not_mem h; apply le_cons_self theorem erase_add_left_pos {a : α} {s : multiset α} (t) : a ∈ s → (s + t).erase a = s.erase a + t := quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ erase_append_left l₂ h theorem erase_add_right_pos {a : α} (s) {t : multiset α} (h : a ∈ t) : (s + t).erase a = s + t.erase a := by rw [add_comm, erase_add_left_pos s h, add_comm] theorem erase_add_right_neg {a : α} {s : multiset α} (t) : a ∉ s → (s + t).erase a = s + t.erase a := quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ erase_append_right l₂ h theorem erase_add_left_neg {a : α} (s) {t : multiset α} (h : a ∉ t) : (s + t).erase a = s.erase a + t := by rw [add_comm, erase_add_right_neg s h, add_comm] theorem erase_le (a : α) (s : multiset α) : s.erase a ≤ s := quot.induction_on s $ λ l, (erase_sublist a l).subperm @[simp] theorem erase_lt {a : α} {s : multiset α} : s.erase a < s ↔ a ∈ s := ⟨λ h, not_imp_comm.1 erase_of_not_mem (ne_of_lt h), λ h, by simpa [h] using lt_cons_self (s.erase a) a⟩ theorem erase_subset (a : α) (s : multiset α) : s.erase a ⊆ s := subset_of_le (erase_le a s) theorem mem_erase_of_ne {a b : α} {s : multiset α} (ab : a ≠ b) : a ∈ s.erase b ↔ a ∈ s := quot.induction_on s $ λ l, list.mem_erase_of_ne ab theorem mem_of_mem_erase {a b : α} {s : multiset α} : a ∈ s.erase b → a ∈ s := mem_of_subset (erase_subset _ _) theorem erase_comm (s : multiset α) (a b : α) : (s.erase a).erase b = (s.erase b).erase a := quot.induction_on s $ λ l, congr_arg coe $ l.erase_comm a b theorem erase_le_erase {s t : multiset α} (a : α) (h : s ≤ t) : s.erase a ≤ t.erase a := le_induction_on h $ λ l₁ l₂ h, (h.erase _).subperm theorem erase_le_iff_le_cons {s t : multiset α} {a : α} : s.erase a ≤ t ↔ s ≤ a ::ₘ t := ⟨λ h, le_trans (le_cons_erase _ _) (cons_le_cons _ h), λ h, if m : a ∈ s then by rw ← cons_erase m at h; exact (cons_le_cons_iff _).1 h else le_trans (erase_le _ _) ((le_cons_of_not_mem m).1 h)⟩ @[simp] theorem card_erase_of_mem {a : α} {s : multiset α} : a ∈ s → card (s.erase a) = pred (card s) := quot.induction_on s $ λ l, length_erase_of_mem theorem card_erase_lt_of_mem {a : α} {s : multiset α} : a ∈ s → card (s.erase a) < card s := λ h, card_lt_of_lt (erase_lt.mpr h) theorem card_erase_le {a : α} {s : multiset α} : card (s.erase a) ≤ card s := card_le_of_le (erase_le a s) end erase @[simp] theorem coe_reverse (l : list α) : (reverse l : multiset α) = l := quot.sound $ reverse_perm _ /-! ### `multiset.map` -/ /-- `map f s` is the lift of the list `map` operation. The multiplicity of `b` in `map f s` is the number of `a ∈ s` (counting multiplicity) such that `f a = b`. -/ def map (f : α → β) (s : multiset α) : multiset β := quot.lift_on s (λ l : list α, (l.map f : multiset β)) (λ l₁ l₂ p, quot.sound (p.map f)) theorem forall_mem_map_iff {f : α → β} {p : β → Prop} {s : multiset α} : (∀ y ∈ s.map f, p y) ↔ (∀ x ∈ s, p (f x)) := quotient.induction_on' s $ λ L, list.forall_mem_map_iff @[simp] theorem coe_map (f : α → β) (l : list α) : map f ↑l = l.map f := rfl @[simp] theorem map_zero (f : α → β) : map f 0 = 0 := rfl @[simp] theorem map_cons (f : α → β) (a s) : map f (a ::ₘ s) = f a ::ₘ map f s := quot.induction_on s $ λ l, rfl lemma map_singleton (f : α → β) (a : α) : ({a} : multiset α).map f = {f a} := rfl theorem map_repeat (f : α → β) (a : α) (k : ℕ) : (repeat a k).map f = repeat (f a) k := by { induction k, simp, simpa } @[simp] theorem map_add (f : α → β) (s t) : map f (s + t) = map f s + map f t := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ map_append _ _ _ instance (f : α → β) : is_add_monoid_hom (map f) := { map_add := map_add _, map_zero := map_zero _ } theorem map_nsmul (f : α → β) (n : ℕ) (s) : map f (n • s) = n • (map f s) := (add_monoid_hom.of (map f)).map_nsmul _ _ @[simp] theorem mem_map {f : α → β} {b : β} {s : multiset α} : b ∈ map f s ↔ ∃ a, a ∈ s ∧ f a = b := quot.induction_on s $ λ l, mem_map @[simp] theorem card_map (f : α → β) (s) : card (map f s) = card s := quot.induction_on s $ λ l, length_map _ _ @[simp] theorem map_eq_zero {s : multiset α} {f : α → β} : s.map f = 0 ↔ s = 0 := by rw [← multiset.card_eq_zero, multiset.card_map, multiset.card_eq_zero] theorem mem_map_of_mem (f : α → β) {a : α} {s : multiset α} (h : a ∈ s) : f a ∈ map f s := mem_map.2 ⟨_, h, rfl⟩ theorem mem_map_of_injective {f : α → β} (H : function.injective f) {a : α} {s : multiset α} : f a ∈ map f s ↔ a ∈ s := quot.induction_on s $ λ l, mem_map_of_injective H @[simp] theorem map_map (g : β → γ) (f : α → β) (s : multiset α) : map g (map f s) = map (g ∘ f) s := quot.induction_on s $ λ l, congr_arg coe $ list.map_map _ _ _ theorem map_id (s : multiset α) : map id s = s := quot.induction_on s $ λ l, congr_arg coe $ map_id _ @[simp] lemma map_id' (s : multiset α) : map (λx, x) s = s := map_id s @[simp] theorem map_const (s : multiset α) (b : β) : map (function.const α b) s = repeat b s.card := quot.induction_on s $ λ l, congr_arg coe $ map_const _ _ @[congr] theorem map_congr {f g : α → β} {s : multiset α} : (∀ x ∈ s, f x = g x) → map f s = map g s := quot.induction_on s $ λ l H, congr_arg coe $ map_congr H lemma map_hcongr {β' : Type*} {m : multiset α} {f : α → β} {f' : α → β'} (h : β = β') (hf : ∀a∈m, f a == f' a) : map f m == map f' m := begin subst h, simp at hf, simp [map_congr hf] end theorem eq_of_mem_map_const {b₁ b₂ : β} {l : list α} (h : b₁ ∈ map (function.const α b₂) l) : b₁ = b₂ := eq_of_mem_repeat $ by rwa map_const at h @[simp] theorem map_le_map {f : α → β} {s t : multiset α} (h : s ≤ t) : map f s ≤ map f t := le_induction_on h $ λ l₁ l₂ h, (h.map f).subperm @[simp] theorem map_subset_map {f : α → β} {s t : multiset α} (H : s ⊆ t) : map f s ⊆ map f t := λ b m, let ⟨a, h, e⟩ := mem_map.1 m in mem_map.2 ⟨a, H h, e⟩ /-! ### `multiset.fold` -/ /-- `foldl f H b s` is the lift of the list operation `foldl f b l`, which folds `f` over the multiset. It is well defined when `f` is right-commutative, that is, `f (f b a₁) a₂ = f (f b a₂) a₁`. -/ def foldl (f : β → α → β) (H : right_commutative f) (b : β) (s : multiset α) : β := quot.lift_on s (λ l, foldl f b l) (λ l₁ l₂ p, p.foldl_eq H b) @[simp] theorem foldl_zero (f : β → α → β) (H b) : foldl f H b 0 = b := rfl @[simp] theorem foldl_cons (f : β → α → β) (H b a s) : foldl f H b (a ::ₘ s) = foldl f H (f b a) s := quot.induction_on s $ λ l, rfl @[simp] theorem foldl_add (f : β → α → β) (H b s t) : foldl f H b (s + t) = foldl f H (foldl f H b s) t := quotient.induction_on₂ s t $ λ l₁ l₂, foldl_append _ _ _ _ /-- `foldr f H b s` is the lift of the list operation `foldr f b l`, which folds `f` over the multiset. It is well defined when `f` is left-commutative, that is, `f a₁ (f a₂ b) = f a₂ (f a₁ b)`. -/ def foldr (f : α → β → β) (H : left_commutative f) (b : β) (s : multiset α) : β := quot.lift_on s (λ l, foldr f b l) (λ l₁ l₂ p, p.foldr_eq H b) @[simp] theorem foldr_zero (f : α → β → β) (H b) : foldr f H b 0 = b := rfl @[simp] theorem foldr_cons (f : α → β → β) (H b a s) : foldr f H b (a ::ₘ s) = f a (foldr f H b s) := quot.induction_on s $ λ l, rfl @[simp] theorem foldr_add (f : α → β → β) (H b s t) : foldr f H b (s + t) = foldr f H (foldr f H b t) s := quotient.induction_on₂ s t $ λ l₁ l₂, foldr_append _ _ _ _ @[simp] theorem coe_foldr (f : α → β → β) (H : left_commutative f) (b : β) (l : list α) : foldr f H b l = l.foldr f b := rfl @[simp] theorem coe_foldl (f : β → α → β) (H : right_commutative f) (b : β) (l : list α) : foldl f H b l = l.foldl f b := rfl theorem coe_foldr_swap (f : α → β → β) (H : left_commutative f) (b : β) (l : list α) : foldr f H b l = l.foldl (λ x y, f y x) b := (congr_arg (foldr f H b) (coe_reverse l)).symm.trans $ foldr_reverse _ _ _ theorem foldr_swap (f : α → β → β) (H : left_commutative f) (b : β) (s : multiset α) : foldr f H b s = foldl (λ x y, f y x) (λ x y z, (H _ _ _).symm) b s := quot.induction_on s $ λ l, coe_foldr_swap _ _ _ _ theorem foldl_swap (f : β → α → β) (H : right_commutative f) (b : β) (s : multiset α) : foldl f H b s = foldr (λ x y, f y x) (λ x y z, (H _ _ _).symm) b s := (foldr_swap _ _ _ _).symm lemma foldr_induction' (f : α → β → β) (H : left_commutative f) (x : β) (q : α → Prop) (p : β → Prop) (s : multiset α) (hpqf : ∀ a b, q a → p b → p (f a b)) (px : p x) (q_s : ∀ a ∈ s, q a) : p (foldr f H x s) := begin revert s, refine multiset.induction (by simp [px]) _, intros a s hs hsa, rw foldr_cons, have hps : ∀ (x : α), x ∈ s → q x, from λ x hxs, hsa x (mem_cons_of_mem hxs), exact hpqf a (foldr f H x s) (hsa a (mem_cons_self a s)) (hs hps), end lemma foldr_induction (f : α → α → α) (H : left_commutative f) (x : α) (p : α → Prop) (s : multiset α) (p_f : ∀ a b, p a → p b → p (f a b)) (px : p x) (p_s : ∀ a ∈ s, p a) : p (foldr f H x s) := foldr_induction' f H x p p s p_f px p_s lemma foldl_induction' (f : β → α → β) (H : right_commutative f) (x : β) (q : α → Prop) (p : β → Prop) (s : multiset α) (hpqf : ∀ a b, q a → p b → p (f b a)) (px : p x) (q_s : ∀ a ∈ s, q a) : p (foldl f H x s) := begin rw foldl_swap, exact foldr_induction' (λ x y, f y x) (λ x y z, (H _ _ _).symm) x q p s hpqf px q_s, end lemma foldl_induction (f : α → α → α) (H : right_commutative f) (x : α) (p : α → Prop) (s : multiset α) (p_f : ∀ a b, p a → p b → p (f b a)) (px : p x) (p_s : ∀ a ∈ s, p a) : p (foldl f H x s) := foldl_induction' f H x p p s p_f px p_s /-- Product of a multiset given a commutative monoid structure on `α`. `prod {a, b, c} = a * b * c` -/ @[to_additive] def prod [comm_monoid α] : multiset α → α := foldr (*) (λ x y z, by simp [mul_left_comm]) 1 @[to_additive] theorem prod_eq_foldr [comm_monoid α] (s : multiset α) : prod s = foldr (*) (λ x y z, by simp [mul_left_comm]) 1 s := rfl @[to_additive] theorem prod_eq_foldl [comm_monoid α] (s : multiset α) : prod s = foldl (*) (λ x y z, by simp [mul_right_comm]) 1 s := (foldr_swap _ _ _ _).trans (by simp [mul_comm]) @[simp, to_additive] theorem coe_prod [comm_monoid α] (l : list α) : prod ↑l = l.prod := prod_eq_foldl _ attribute [norm_cast] coe_prod coe_sum @[simp, to_additive] theorem prod_zero [comm_monoid α] : @prod α _ 0 = 1 := rfl @[simp, to_additive] theorem prod_cons [comm_monoid α] (a : α) (s) : prod (a ::ₘ s) = a * prod s := foldr_cons _ _ _ _ _ @[to_additive] theorem prod_singleton [comm_monoid α] (a : α) : prod (a ::ₘ 0) = a := by simp @[simp, to_additive] theorem prod_add [comm_monoid α] (s t : multiset α) : prod (s + t) = prod s * prod t := quotient.induction_on₂ s t $ λ l₁ l₂, by simp instance sum.is_add_monoid_hom [add_comm_monoid α] : is_add_monoid_hom (sum : multiset α → α) := { map_add := sum_add, map_zero := sum_zero } lemma prod_nsmul {α : Type*} [comm_monoid α] (m : multiset α) : ∀ (n : ℕ), (n • m).prod = m.prod ^ n | 0 := by { rw [zero_nsmul, pow_zero], refl } | (n + 1) := by rw [add_nsmul, one_nsmul, pow_add, pow_one, prod_add, prod_nsmul n] @[simp] theorem prod_repeat [comm_monoid α] (a : α) (n : ℕ) : prod (multiset.repeat a n) = a ^ n := by simp [repeat, list.prod_repeat] @[simp] theorem sum_repeat [add_comm_monoid α] : ∀ (a : α) (n : ℕ), sum (multiset.repeat a n) = n • a := @prod_repeat (multiplicative α) _ attribute [to_additive] prod_repeat lemma prod_map_one [comm_monoid γ] {m : multiset α} : prod (m.map (λa, (1 : γ))) = (1 : γ) := by simp lemma sum_map_zero [add_comm_monoid γ] {m : multiset α} : sum (m.map (λa, (0 : γ))) = (0 : γ) := by simp [nsmul_zero] attribute [to_additive] prod_map_one @[simp, to_additive] lemma prod_map_mul [comm_monoid γ] {m : multiset α} {f g : α → γ} : prod (m.map $ λa, f a * g a) = prod (m.map f) * prod (m.map g) := multiset.induction_on m (by simp) (assume a m ih, by simp [ih]; cc) lemma prod_map_prod_map [comm_monoid γ] (m : multiset α) (n : multiset β) {f : α → β → γ} : prod (m.map $ λa, prod $ n.map $ λb, f a b) = prod (n.map $ λb, prod $ m.map $ λa, f a b) := multiset.induction_on m (by simp) (assume a m ih, by simp [ih]) lemma sum_map_sum_map [add_comm_monoid γ] : ∀ (m : multiset α) (n : multiset β) {f : α → β → γ}, sum (m.map $ λa, sum $ n.map $ λb, f a b) = sum (n.map $ λb, sum $ m.map $ λa, f a b) := @prod_map_prod_map _ _ (multiplicative γ) _ attribute [to_additive] prod_map_prod_map lemma sum_map_mul_left [semiring β] {b : β} {s : multiset α} {f : α → β} : sum (s.map (λa, b * f a)) = b * sum (s.map f) := multiset.induction_on s (by simp) (assume a s ih, by simp [ih, mul_add]) lemma sum_map_mul_right [semiring β] {b : β} {s : multiset α} {f : α → β} : sum (s.map (λa, f a * b)) = sum (s.map f) * b := multiset.induction_on s (by simp) (assume a s ih, by simp [ih, add_mul]) lemma prod_eq_zero {M₀ : Type*} [comm_monoid_with_zero M₀] {s : multiset M₀} (h : (0 : M₀) ∈ s) : multiset.prod s = 0 := begin rcases multiset.exists_cons_of_mem h with ⟨s', hs'⟩, simp [hs', multiset.prod_cons] end lemma prod_eq_zero_iff {M₀ : Type*} [comm_monoid_with_zero M₀] [no_zero_divisors M₀] [nontrivial M₀] {s : multiset M₀} : multiset.prod s = 0 ↔ (0 : M₀) ∈ s := by { rcases s with ⟨l⟩, simp } theorem prod_ne_zero {M₀ : Type*} [comm_monoid_with_zero M₀] [no_zero_divisors M₀] [nontrivial M₀] {m : multiset M₀} (h : (0 : M₀) ∉ m) : m.prod ≠ 0 := mt prod_eq_zero_iff.1 h @[to_additive] lemma prod_hom [comm_monoid α] [comm_monoid β] (s : multiset α) (f : α →* β) : (s.map f).prod = f s.prod := quotient.induction_on s $ λ l, by simp only [l.prod_hom f, quot_mk_to_coe, coe_map, coe_prod] @[to_additive] theorem prod_hom_rel [comm_monoid β] [comm_monoid γ] (s : multiset α) {r : β → γ → Prop} {f : α → β} {g : α → γ} (h₁ : r 1 1) (h₂ : ∀⦃a b c⦄, r b c → r (f a * b) (g a * c)) : r (s.map f).prod (s.map g).prod := quotient.induction_on s $ λ l, by simp only [l.prod_hom_rel h₁ h₂, quot_mk_to_coe, coe_map, coe_prod] @[simp, to_additive] lemma prod_map_inv {G : Type*} [comm_group G] (m : multiset G) : (m.map has_inv.inv).prod = m.prod⁻¹ := m.prod_hom (monoid_hom.of has_inv.inv) lemma dvd_prod [comm_monoid α] {a : α} {s : multiset α} : a ∈ s → a ∣ s.prod := quotient.induction_on s (λ l a h, by simpa using list.dvd_prod h) a lemma prod_dvd_prod [comm_monoid α] {s t : multiset α} (h : s ≤ t) : s.prod ∣ t.prod := begin rcases multiset.le_iff_exists_add.1 h with ⟨z, rfl⟩, simp, end @[to_additive sum_nonneg] lemma one_le_prod_of_one_le [ordered_comm_monoid α] {m : multiset α} : (∀ x ∈ m, (1 : α) ≤ x) → 1 ≤ m.prod := quotient.induction_on m $ λ l hl, by simpa using list.one_le_prod_of_one_le hl @[to_additive] lemma single_le_prod [ordered_comm_monoid α] {m : multiset α} : (∀ x ∈ m, (1 : α) ≤ x) → ∀ x ∈ m, x ≤ m.prod := quotient.induction_on m $ λ l hl x hx, by simpa using list.single_le_prod hl x hx @[to_additive all_zero_of_le_zero_le_of_sum_eq_zero] lemma all_one_of_le_one_le_of_prod_eq_one [ordered_comm_monoid α] {m : multiset α} : (∀ x ∈ m, (1 : α) ≤ x) → m.prod = 1 → (∀ x ∈ m, x = (1 : α)) := begin apply quotient.induction_on m, simp only [quot_mk_to_coe, coe_prod, mem_coe], intros l hl₁ hl₂ x hx, apply all_one_of_le_one_le_of_prod_eq_one hl₁ hl₂ _ hx, end lemma sum_eq_zero_iff [canonically_ordered_add_monoid α] {m : multiset α} : m.sum = 0 ↔ ∀ x ∈ m, x = (0 : α) := quotient.induction_on m $ λ l, by simpa using list.sum_eq_zero_iff l @[to_additive] lemma prod_induction {M : Type*} [comm_monoid M] (p : M → Prop) (s : multiset M) (p_mul : ∀ a b, p a → p b → p (a * b)) (p_one : p 1) (p_s : ∀ a ∈ s, p a) : p s.prod := begin rw prod_eq_foldr, exact foldr_induction (*) (λ x y z, by simp [mul_left_comm]) 1 p s p_mul p_one p_s, end @[to_additive le_sum_of_subadditive_on_pred] lemma le_prod_of_submultiplicative_on_pred [comm_monoid α] [ordered_comm_monoid β] (f : α → β) (p : α → Prop) (h_one : f 1 = 1) (hp_one : p 1) (h_mul : ∀ a b, p a → p b → f (a * b) ≤ f a * f b) (hp_mul : ∀ a b, p a → p b → p (a * b)) (s : multiset α) (hps : ∀ a, a ∈ s → p a) : f s.prod ≤ (s.map f).prod := begin revert s, refine multiset.induction _ _, { simp [le_of_eq h_one], }, intros a s hs hpsa, have hps : ∀ x, x ∈ s → p x, from λ x hx, hpsa x (mem_cons_of_mem hx), have hp_prod : p s.prod, from prod_induction p s hp_mul hp_one hps, rw [prod_cons, map_cons, prod_cons], exact (h_mul a s.prod (hpsa a (mem_cons_self a s)) hp_prod).trans (mul_le_mul_left' (hs hps) _), end @[to_additive le_sum_of_subadditive] lemma le_prod_of_submultiplicative [comm_monoid α] [ordered_comm_monoid β] (f : α → β) (h_one : f 1 = 1) (h_mul : ∀ a b, f (a * b) ≤ f a * f b) (s : multiset α) : f s.prod ≤ (s.map f).prod := le_prod_of_submultiplicative_on_pred f (λ i, true) h_one trivial (λ x y _ _ , h_mul x y) (by simp) s (by simp) @[to_additive] lemma prod_induction_nonempty {M : Type*} [comm_monoid M] (p : M → Prop) (p_mul : ∀ a b, p a → p b → p (a * b)) {s : multiset M} (hs_nonempty : s ≠ ∅) (p_s : ∀ a ∈ s, p a) : p s.prod := begin revert s, refine multiset.induction _ _, { intro h, exfalso, simpa using h, }, intros a s hs hsa hpsa, rw prod_cons, by_cases hs_empty : s = ∅, { simp [hs_empty, hpsa a], }, have hps : ∀ (x : M), x ∈ s → p x, from λ x hxs, hpsa x (mem_cons_of_mem hxs), exact p_mul a s.prod (hpsa a (mem_cons_self a s)) (hs hs_empty hps), end @[to_additive le_sum_nonempty_of_subadditive_on_pred] lemma le_prod_nonempty_of_submultiplicative_on_pred [comm_monoid α] [ordered_comm_monoid β] (f : α → β) (p : α → Prop) (h_mul : ∀ a b, p a → p b → f (a * b) ≤ f a * f b) (hp_mul : ∀ a b, p a → p b → p (a * b)) (s : multiset α) (hs_nonempty : s ≠ ∅) (hs : ∀ a, a ∈ s → p a) : f s.prod ≤ (s.map f).prod := begin revert s, refine multiset.induction _ _, { intro h, exfalso, exact h rfl, }, rintros a s hs hsa_nonempty hsa_prop, rw [prod_cons, map_cons, prod_cons], by_cases hs_empty : s = ∅, { simp [hs_empty], }, have hsa_restrict : (∀ x, x ∈ s → p x), from λ x hx, hsa_prop x (mem_cons_of_mem hx), have hp_sup : p s.prod, from prod_induction_nonempty p hp_mul hs_empty hsa_restrict, have hp_a : p a, from hsa_prop a (mem_cons_self a s), exact (h_mul a _ hp_a hp_sup).trans (mul_le_mul_left' (hs hs_empty hsa_restrict) _), end @[to_additive le_sum_nonempty_of_subadditive] lemma le_prod_nonempty_of_submultiplicative [comm_monoid α] [ordered_comm_monoid β] (f : α → β) (h_mul : ∀ a b, f (a * b) ≤ f a * f b) (s : multiset α) (hs_nonempty : s ≠ ∅) : f s.prod ≤ (s.map f).prod := le_prod_nonempty_of_submultiplicative_on_pred f (λ i, true) (by simp [h_mul]) (by simp) s hs_nonempty (by simp) lemma abs_sum_le_sum_abs [linear_ordered_field α] {s : multiset α} : abs s.sum ≤ (s.map abs).sum := le_sum_of_subadditive _ abs_zero abs_add s theorem dvd_sum [comm_semiring α] {a : α} {s : multiset α} : (∀ x ∈ s, a ∣ x) → a ∣ s.sum := multiset.induction_on s (λ _, dvd_zero _) (λ x s ih h, by rw sum_cons; exact dvd_add (h _ (mem_cons_self _ _)) (ih (λ y hy, h _ (mem_cons.2 (or.inr hy))))) @[simp] theorem sum_map_singleton (s : multiset α) : (s.map (λ a, a ::ₘ 0)).sum = s := multiset.induction_on s (by simp) (by simp) @[simp, to_additive] theorem prod_to_list [comm_monoid α] (s : multiset α) : s.to_list.prod = s.prod := begin conv_rhs { rw ←coe_to_list s, }, rw coe_prod, end /-! ### Join -/ /-- `join S`, where `S` is a multiset of multisets, is the lift of the list join operation, that is, the union of all the sets. join {{1, 2}, {1, 2}, {0, 1}} = {0, 1, 1, 1, 2, 2} -/ def join : multiset (multiset α) → multiset α := sum theorem coe_join : ∀ L : list (list α), join (L.map (@coe _ (multiset α) _) : multiset (multiset α)) = L.join | [] := rfl | (l :: L) := congr_arg (λ s : multiset α, ↑l + s) (coe_join L) @[simp] theorem join_zero : @join α 0 = 0 := rfl @[simp] theorem join_cons (s S) : @join α (s ::ₘ S) = s + join S := sum_cons _ _ @[simp] theorem join_add (S T) : @join α (S + T) = join S + join T := sum_add _ _ @[simp] theorem mem_join {a S} : a ∈ @join α S ↔ ∃ s ∈ S, a ∈ s := multiset.induction_on S (by simp) $ by simp [or_and_distrib_right, exists_or_distrib] {contextual := tt} @[simp] theorem card_join (S) : card (@join α S) = sum (map card S) := multiset.induction_on S (by simp) (by simp) /-! ### `multiset.bind` -/ /-- `bind s f` is the monad bind operation, defined as `join (map f s)`. It is the union of `f a` as `a` ranges over `s`. -/ def bind (s : multiset α) (f : α → multiset β) : multiset β := join (map f s) @[simp] theorem coe_bind (l : list α) (f : α → list β) : @bind α β l (λ a, f a) = l.bind f := by rw [list.bind, ← coe_join, list.map_map]; refl @[simp] theorem zero_bind (f : α → multiset β) : bind 0 f = 0 := rfl @[simp] theorem cons_bind (a s) (f : α → multiset β) : bind (a ::ₘ s) f = f a + bind s f := by simp [bind] @[simp] theorem add_bind (s t) (f : α → multiset β) : bind (s + t) f = bind s f + bind t f := by simp [bind] @[simp] theorem bind_zero (s : multiset α) : bind s (λa, 0 : α → multiset β) = 0 := by simp [bind, join, nsmul_zero] @[simp] theorem bind_add (s : multiset α) (f g : α → multiset β) : bind s (λa, f a + g a) = bind s f + bind s g := by simp [bind, join] @[simp] theorem bind_cons (s : multiset α) (f : α → β) (g : α → multiset β) : bind s (λa, f a ::ₘ g a) = map f s + bind s g := multiset.induction_on s (by simp) (by simp [add_comm, add_left_comm] {contextual := tt}) @[simp] theorem mem_bind {b s} {f : α → multiset β} : b ∈ bind s f ↔ ∃ a ∈ s, b ∈ f a := by simp [bind]; simp [-exists_and_distrib_right, exists_and_distrib_right.symm]; rw exists_swap; simp [and_assoc] @[simp] theorem card_bind (s) (f : α → multiset β) : card (bind s f) = sum (map (card ∘ f) s) := by simp [bind] lemma bind_congr {f g : α → multiset β} {m : multiset α} : (∀a∈m, f a = g a) → bind m f = bind m g := by simp [bind] {contextual := tt} lemma bind_hcongr {β' : Type*} {m : multiset α} {f : α → multiset β} {f' : α → multiset β'} (h : β = β') (hf : ∀a∈m, f a == f' a) : bind m f == bind m f' := begin subst h, simp at hf, simp [bind_congr hf] end lemma map_bind (m : multiset α) (n : α → multiset β) (f : β → γ) : map f (bind m n) = bind m (λa, map f (n a)) := multiset.induction_on m (by simp) (by simp {contextual := tt}) lemma bind_map (m : multiset α) (n : β → multiset γ) (f : α → β) : bind (map f m) n = bind m (λa, n (f a)) := multiset.induction_on m (by simp) (by simp {contextual := tt}) lemma bind_assoc {s : multiset α} {f : α → multiset β} {g : β → multiset γ} : (s.bind f).bind g = s.bind (λa, (f a).bind g) := multiset.induction_on s (by simp) (by simp {contextual := tt}) lemma bind_bind (m : multiset α) (n : multiset β) {f : α → β → multiset γ} : (bind m $ λa, bind n $ λb, f a b) = (bind n $ λb, bind m $ λa, f a b) := multiset.induction_on m (by simp) (by simp {contextual := tt}) lemma bind_map_comm (m : multiset α) (n : multiset β) {f : α → β → γ} : (bind m $ λa, n.map $ λb, f a b) = (bind n $ λb, m.map $ λa, f a b) := multiset.induction_on m (by simp) (by simp {contextual := tt}) @[simp, to_additive] lemma prod_bind [comm_monoid β] (s : multiset α) (t : α → multiset β) : prod (bind s t) = prod (s.map $ λa, prod (t a)) := multiset.induction_on s (by simp) (assume a s ih, by simp [ih, cons_bind]) /-! ### Product of two `multiset`s -/ /-- The multiplicity of `(a, b)` in `product s t` is the product of the multiplicity of `a` in `s` and `b` in `t`. -/ def product (s : multiset α) (t : multiset β) : multiset (α × β) := s.bind $ λ a, t.map $ prod.mk a @[simp] theorem coe_product (l₁ : list α) (l₂ : list β) : @product α β l₁ l₂ = l₁.product l₂ := by rw [product, list.product, ← coe_bind]; simp @[simp] theorem zero_product (t) : @product α β 0 t = 0 := rfl @[simp] theorem cons_product (a : α) (s : multiset α) (t : multiset β) : product (a ::ₘ s) t = map (prod.mk a) t + product s t := by simp [product] @[simp] theorem product_singleton (a : α) (b : β) : product (a ::ₘ 0) (b ::ₘ 0) = (a,b) ::ₘ 0 := rfl @[simp] theorem add_product (s t : multiset α) (u : multiset β) : product (s + t) u = product s u + product t u := by simp [product] @[simp] theorem product_add (s : multiset α) : ∀ t u : multiset β, product s (t + u) = product s t + product s u := multiset.induction_on s (λ t u, rfl) $ λ a s IH t u, by rw [cons_product, IH]; simp; cc @[simp] theorem mem_product {s t} : ∀ {p : α × β}, p ∈ @product α β s t ↔ p.1 ∈ s ∧ p.2 ∈ t | (a, b) := by simp [product, and.left_comm] @[simp] theorem card_product (s : multiset α) (t : multiset β) : card (product s t) = card s * card t := by simp [product, repeat, (∘), mul_comm] /-! ### Sigma multiset -/ section variable {σ : α → Type*} /-- `sigma s t` is the dependent version of `product`. It is the sum of `(a, b)` as `a` ranges over `s` and `b` ranges over `t a`. -/ protected def sigma (s : multiset α) (t : Π a, multiset (σ a)) : multiset (Σ a, σ a) := s.bind $ λ a, (t a).map $ sigma.mk a @[simp] theorem coe_sigma (l₁ : list α) (l₂ : Π a, list (σ a)) : @multiset.sigma α σ l₁ (λ a, l₂ a) = l₁.sigma l₂ := by rw [multiset.sigma, list.sigma, ← coe_bind]; simp @[simp] theorem zero_sigma (t) : @multiset.sigma α σ 0 t = 0 := rfl @[simp] theorem cons_sigma (a : α) (s : multiset α) (t : Π a, multiset (σ a)) : (a ::ₘ s).sigma t = map (sigma.mk a) (t a) + s.sigma t := by simp [multiset.sigma] @[simp] theorem sigma_singleton (a : α) (b : α → β) : (a ::ₘ 0).sigma (λ a, b a ::ₘ 0) = ⟨a, b a⟩ ::ₘ 0 := rfl @[simp] theorem add_sigma (s t : multiset α) (u : Π a, multiset (σ a)) : (s + t).sigma u = s.sigma u + t.sigma u := by simp [multiset.sigma] @[simp] theorem sigma_add (s : multiset α) : ∀ t u : Π a, multiset (σ a), s.sigma (λ a, t a + u a) = s.sigma t + s.sigma u := multiset.induction_on s (λ t u, rfl) $ λ a s IH t u, by rw [cons_sigma, IH]; simp; cc @[simp] theorem mem_sigma {s t} : ∀ {p : Σ a, σ a}, p ∈ @multiset.sigma α σ s t ↔ p.1 ∈ s ∧ p.2 ∈ t p.1 | ⟨a, b⟩ := by simp [multiset.sigma, and_assoc, and.left_comm] @[simp] theorem card_sigma (s : multiset α) (t : Π a, multiset (σ a)) : card (s.sigma t) = sum (map (λ a, card (t a)) s) := by simp [multiset.sigma, (∘)] end /-! ### Map for partial functions -/ /-- Lift of the list `pmap` operation. Map a partial function `f` over a multiset `s` whose elements are all in the domain of `f`. -/ def pmap {p : α → Prop} (f : Π a, p a → β) (s : multiset α) : (∀ a ∈ s, p a) → multiset β := quot.rec_on s (λ l H, ↑(pmap f l H)) $ λ l₁ l₂ (pp : l₁ ~ l₂), funext $ λ (H₂ : ∀ a ∈ l₂, p a), have H₁ : ∀ a ∈ l₁, p a, from λ a h, H₂ a (pp.subset h), have ∀ {s₂ e H}, @eq.rec (multiset α) l₁ (λ s, (∀ a ∈ s, p a) → multiset β) (λ _, ↑(pmap f l₁ H₁)) s₂ e H = ↑(pmap f l₁ H₁), by intros s₂ e _; subst e, this.trans $ quot.sound $ pp.pmap f @[simp] theorem coe_pmap {p : α → Prop} (f : Π a, p a → β) (l : list α) (H : ∀ a ∈ l, p a) : pmap f l H = l.pmap f H := rfl @[simp] lemma pmap_zero {p : α → Prop} (f : Π a, p a → β) (h : ∀a∈(0:multiset α), p a) : pmap f 0 h = 0 := rfl @[simp] lemma pmap_cons {p : α → Prop} (f : Π a, p a → β) (a : α) (m : multiset α) : ∀(h : ∀b∈a ::ₘ m, p b), pmap f (a ::ₘ m) h = f a (h a (mem_cons_self a m)) ::ₘ pmap f m (λa ha, h a $ mem_cons_of_mem ha) := quotient.induction_on m $ assume l h, rfl /-- "Attach" a proof that `a ∈ s` to each element `a` in `s` to produce a multiset on `{x // x ∈ s}`. -/ def attach (s : multiset α) : multiset {x // x ∈ s} := pmap subtype.mk s (λ a, id) @[simp] theorem coe_attach (l : list α) : @eq (multiset {x // x ∈ l}) (@attach α l) l.attach := rfl theorem sizeof_lt_sizeof_of_mem [has_sizeof α] {x : α} {s : multiset α} (hx : x ∈ s) : sizeof x < sizeof s := by { induction s with l a b, exact list.sizeof_lt_sizeof_of_mem hx, refl } theorem pmap_eq_map (p : α → Prop) (f : α → β) (s : multiset α) : ∀ H, @pmap _ _ p (λ a _, f a) s H = map f s := quot.induction_on s $ λ l H, congr_arg coe $ pmap_eq_map p f l H theorem pmap_congr {p q : α → Prop} {f : Π a, p a → β} {g : Π a, q a → β} (s : multiset α) {H₁ H₂} (h : ∀ a h₁ h₂, f a h₁ = g a h₂) : pmap f s H₁ = pmap g s H₂ := quot.induction_on s (λ l H₁ H₂, congr_arg coe $ pmap_congr l h) H₁ H₂ theorem map_pmap {p : α → Prop} (g : β → γ) (f : Π a, p a → β) (s) : ∀ H, map g (pmap f s H) = pmap (λ a h, g (f a h)) s H := quot.induction_on s $ λ l H, congr_arg coe $ map_pmap g f l H theorem pmap_eq_map_attach {p : α → Prop} (f : Π a, p a → β) (s) : ∀ H, pmap f s H = s.attach.map (λ x, f x.1 (H _ x.2)) := quot.induction_on s $ λ l H, congr_arg coe $ pmap_eq_map_attach f l H theorem attach_map_val (s : multiset α) : s.attach.map subtype.val = s := quot.induction_on s $ λ l, congr_arg coe $ attach_map_val l @[simp] theorem mem_attach (s : multiset α) : ∀ x, x ∈ s.attach := quot.induction_on s $ λ l, mem_attach _ @[simp] theorem mem_pmap {p : α → Prop} {f : Π a, p a → β} {s H b} : b ∈ pmap f s H ↔ ∃ a (h : a ∈ s), f a (H a h) = b := quot.induction_on s (λ l H, mem_pmap) H @[simp] theorem card_pmap {p : α → Prop} (f : Π a, p a → β) (s H) : card (pmap f s H) = card s := quot.induction_on s (λ l H, length_pmap) H @[simp] theorem card_attach {m : multiset α} : card (attach m) = card m := card_pmap _ _ _ @[simp] lemma attach_zero : (0 : multiset α).attach = 0 := rfl lemma attach_cons (a : α) (m : multiset α) : (a ::ₘ m).attach = ⟨a, mem_cons_self a m⟩ ::ₘ (m.attach.map $ λp, ⟨p.1, mem_cons_of_mem p.2⟩) := quotient.induction_on m $ assume l, congr_arg coe $ congr_arg (list.cons _) $ by rw [list.map_pmap]; exact list.pmap_congr _ (assume a' h₁ h₂, subtype.eq rfl) section decidable_pi_exists variables {m : multiset α} protected def decidable_forall_multiset {p : α → Prop} [hp : ∀a, decidable (p a)] : decidable (∀a∈m, p a) := quotient.rec_on_subsingleton m (λl, decidable_of_iff (∀a∈l, p a) $ by simp) instance decidable_dforall_multiset {p : Πa∈m, Prop} [hp : ∀a (h : a ∈ m), decidable (p a h)] : decidable (∀a (h : a ∈ m), p a h) := decidable_of_decidable_of_iff (@multiset.decidable_forall_multiset {a // a ∈ m} m.attach (λa, p a.1 a.2) _) (iff.intro (assume h a ha, h ⟨a, ha⟩ (mem_attach _ _)) (assume h ⟨a, ha⟩ _, h _ _)) /-- decidable equality for functions whose domain is bounded by multisets -/ instance decidable_eq_pi_multiset {β : α → Type*} [h : ∀a, decidable_eq (β a)] : decidable_eq (Πa∈m, β a) := assume f g, decidable_of_iff (∀a (h : a ∈ m), f a h = g a h) (by simp [function.funext_iff]) def decidable_exists_multiset {p : α → Prop} [decidable_pred p] : decidable (∃ x ∈ m, p x) := quotient.rec_on_subsingleton m list.decidable_exists_mem instance decidable_dexists_multiset {p : Πa∈m, Prop} [hp : ∀a (h : a ∈ m), decidable (p a h)] : decidable (∃a (h : a ∈ m), p a h) := decidable_of_decidable_of_iff (@multiset.decidable_exists_multiset {a // a ∈ m} m.attach (λa, p a.1 a.2) _) (iff.intro (λ ⟨⟨a, ha₁⟩, _, ha₂⟩, ⟨a, ha₁, ha₂⟩) (λ ⟨a, ha₁, ha₂⟩, ⟨⟨a, ha₁⟩, mem_attach _ _, ha₂⟩)) end decidable_pi_exists /-! ### Subtraction -/ section variables [decidable_eq α] {s t u : multiset α} {a b : α} /-- `s - t` is the multiset such that `count a (s - t) = count a s - count a t` for all `a`. -/ protected def sub (s t : multiset α) : multiset α := quotient.lift_on₂ s t (λ l₁ l₂, (l₁.diff l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ p₁.diff p₂ instance : has_sub (multiset α) := ⟨multiset.sub⟩ @[simp] theorem coe_sub (s t : list α) : (s - t : multiset α) = (s.diff t : list α) := rfl theorem sub_eq_fold_erase (s t : multiset α) : s - t = foldl erase erase_comm s t := quotient.induction_on₂ s t $ λ l₁ l₂, show ↑(l₁.diff l₂) = foldl erase erase_comm ↑l₁ ↑l₂, by { rw diff_eq_foldl l₁ l₂, symmetry, exact foldl_hom _ _ _ _ _ (λ x y, rfl) } @[simp] theorem sub_zero (s : multiset α) : s - 0 = s := quot.induction_on s $ λ l, rfl @[simp] theorem sub_cons (a : α) (s t : multiset α) : s - a ::ₘ t = s.erase a - t := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ diff_cons _ _ _ theorem add_sub_of_le (h : s ≤ t) : s + (t - s) = t := begin revert t, refine multiset.induction_on s (by simp) (λ a s IH t h, _), have := cons_erase (mem_of_le h (mem_cons_self _ _)), rw [cons_add, sub_cons, IH, this], exact (cons_le_cons_iff a).1 (this.symm ▸ h) end theorem sub_add' : s - (t + u) = s - t - u := quotient.induction_on₃ s t u $ λ l₁ l₂ l₃, congr_arg coe $ diff_append _ _ _ theorem sub_add_cancel (h : t ≤ s) : s - t + t = s := by rw [add_comm, add_sub_of_le h] @[simp] theorem add_sub_cancel_left (s : multiset α) : ∀ t, s + t - s = t := multiset.induction_on s (by simp) (λ a s IH t, by rw [cons_add, sub_cons, erase_cons_head, IH]) @[simp] theorem add_sub_cancel (s t : multiset α) : s + t - t = s := by rw [add_comm, add_sub_cancel_left] theorem sub_le_sub_right (h : s ≤ t) (u) : s - u ≤ t - u := by revert s t h; exact multiset.induction_on u (by simp {contextual := tt}) (λ a u IH s t h, by simp [IH, erase_le_erase a h]) theorem sub_le_sub_left (h : s ≤ t) : ∀ u, u - t ≤ u - s := le_induction_on h $ λ l₁ l₂ h, begin induction h with l₁ l₂ a s IH l₁ l₂ a s IH; intro u, { refl }, { rw [← cons_coe, sub_cons], exact le_trans (sub_le_sub_right (erase_le _ _) _) (IH u) }, { rw [← cons_coe, sub_cons, ← cons_coe, sub_cons], exact IH _ } end theorem sub_le_iff_le_add : s - t ≤ u ↔ s ≤ u + t := by revert s; exact multiset.induction_on t (by simp) (λ a t IH s, by simp [IH, erase_le_iff_le_cons]) theorem le_sub_add (s t : multiset α) : s ≤ s - t + t := sub_le_iff_le_add.1 (le_refl _) theorem sub_le_self (s t : multiset α) : s - t ≤ s := sub_le_iff_le_add.2 (le_add_right _ _) @[simp] theorem card_sub {s t : multiset α} (h : t ≤ s) : card (s - t) = card s - card t := (nat.sub_eq_of_eq_add $ by rw [add_comm, ← card_add, sub_add_cancel h]).symm /-! ### Union -/ /-- `s ∪ t` is the lattice join operation with respect to the multiset `≤`. The multiplicity of `a` in `s ∪ t` is the maximum of the multiplicities in `s` and `t`. -/ def union (s t : multiset α) : multiset α := s - t + t instance : has_union (multiset α) := ⟨union⟩ theorem union_def (s t : multiset α) : s ∪ t = s - t + t := rfl theorem le_union_left (s t : multiset α) : s ≤ s ∪ t := le_sub_add _ _ theorem le_union_right (s t : multiset α) : t ≤ s ∪ t := le_add_left _ _ theorem eq_union_left : t ≤ s → s ∪ t = s := sub_add_cancel theorem union_le_union_right (h : s ≤ t) (u) : s ∪ u ≤ t ∪ u := add_le_add_right (sub_le_sub_right h _) u theorem union_le (h₁ : s ≤ u) (h₂ : t ≤ u) : s ∪ t ≤ u := by rw ← eq_union_left h₂; exact union_le_union_right h₁ t @[simp] theorem mem_union : a ∈ s ∪ t ↔ a ∈ s ∨ a ∈ t := ⟨λ h, (mem_add.1 h).imp_left (mem_of_le $ sub_le_self _ _), or.rec (mem_of_le $ le_union_left _ _) (mem_of_le $ le_union_right _ _)⟩ @[simp] theorem map_union [decidable_eq β] {f : α → β} (finj : function.injective f) {s t : multiset α} : map f (s ∪ t) = map f s ∪ map f t := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe (by rw [list.map_append f, list.map_diff finj]) /-! ### Intersection -/ /-- `s ∩ t` is the lattice meet operation with respect to the multiset `≤`. The multiplicity of `a` in `s ∩ t` is the minimum of the multiplicities in `s` and `t`. -/ def inter (s t : multiset α) : multiset α := quotient.lift_on₂ s t (λ l₁ l₂, (l₁.bag_inter l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ p₁.bag_inter p₂ instance : has_inter (multiset α) := ⟨inter⟩ @[simp] theorem inter_zero (s : multiset α) : s ∩ 0 = 0 := quot.induction_on s $ λ l, congr_arg coe l.bag_inter_nil @[simp] theorem zero_inter (s : multiset α) : 0 ∩ s = 0 := quot.induction_on s $ λ l, congr_arg coe l.nil_bag_inter @[simp] theorem cons_inter_of_pos {a} (s : multiset α) {t} : a ∈ t → (a ::ₘ s) ∩ t = a ::ₘ s ∩ t.erase a := quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ cons_bag_inter_of_pos _ h @[simp] theorem cons_inter_of_neg {a} (s : multiset α) {t} : a ∉ t → (a ::ₘ s) ∩ t = s ∩ t := quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ cons_bag_inter_of_neg _ h theorem inter_le_left (s t : multiset α) : s ∩ t ≤ s := quotient.induction_on₂ s t $ λ l₁ l₂, (bag_inter_sublist_left _ _).subperm theorem inter_le_right (s : multiset α) : ∀ t, s ∩ t ≤ t := multiset.induction_on s (λ t, (zero_inter t).symm ▸ zero_le _) $ λ a s IH t, if h : a ∈ t then by simpa [h] using cons_le_cons a (IH (t.erase a)) else by simp [h, IH] theorem le_inter (h₁ : s ≤ t) (h₂ : s ≤ u) : s ≤ t ∩ u := begin revert s u, refine multiset.induction_on t _ (λ a t IH, _); intros, { simp [h₁] }, by_cases a ∈ u, { rw [cons_inter_of_pos _ h, ← erase_le_iff_le_cons], exact IH (erase_le_iff_le_cons.2 h₁) (erase_le_erase _ h₂) }, { rw cons_inter_of_neg _ h, exact IH ((le_cons_of_not_mem $ mt (mem_of_le h₂) h).1 h₁) h₂ } end @[simp] theorem mem_inter : a ∈ s ∩ t ↔ a ∈ s ∧ a ∈ t := ⟨λ h, ⟨mem_of_le (inter_le_left _ _) h, mem_of_le (inter_le_right _ _) h⟩, λ ⟨h₁, h₂⟩, by rw [← cons_erase h₁, cons_inter_of_pos _ h₂]; apply mem_cons_self⟩ instance : lattice (multiset α) := { sup := (∪), sup_le := @union_le _ _, le_sup_left := le_union_left, le_sup_right := le_union_right, inf := (∩), le_inf := @le_inter _ _, inf_le_left := inter_le_left, inf_le_right := inter_le_right, ..@multiset.partial_order α } @[simp] theorem sup_eq_union (s t : multiset α) : s ⊔ t = s ∪ t := rfl @[simp] theorem inf_eq_inter (s t : multiset α) : s ⊓ t = s ∩ t := rfl @[simp] theorem le_inter_iff : s ≤ t ∩ u ↔ s ≤ t ∧ s ≤ u := le_inf_iff @[simp] theorem union_le_iff : s ∪ t ≤ u ↔ s ≤ u ∧ t ≤ u := sup_le_iff instance : semilattice_inf_bot (multiset α) := { bot := 0, bot_le := zero_le, ..multiset.lattice } theorem union_comm (s t : multiset α) : s ∪ t = t ∪ s := sup_comm theorem inter_comm (s t : multiset α) : s ∩ t = t ∩ s := inf_comm theorem eq_union_right (h : s ≤ t) : s ∪ t = t := by rw [union_comm, eq_union_left h] theorem union_le_union_left (h : s ≤ t) (u) : u ∪ s ≤ u ∪ t := sup_le_sup_left h _ theorem union_le_add (s t : multiset α) : s ∪ t ≤ s + t := union_le (le_add_right _ _) (le_add_left _ _) theorem union_add_distrib (s t u : multiset α) : (s ∪ t) + u = (s + u) ∪ (t + u) := by simpa [(∪), union, eq_comm, add_assoc] using show s + u - (t + u) = s - t, by rw [add_comm t, sub_add', add_sub_cancel] theorem add_union_distrib (s t u : multiset α) : s + (t ∪ u) = (s + t) ∪ (s + u) := by rw [add_comm, union_add_distrib, add_comm s, add_comm s] theorem cons_union_distrib (a : α) (s t : multiset α) : a ::ₘ (s ∪ t) = (a ::ₘ s) ∪ (a ::ₘ t) := by simpa using add_union_distrib (a ::ₘ 0) s t theorem inter_add_distrib (s t u : multiset α) : (s ∩ t) + u = (s + u) ∩ (t + u) := begin by_contra h, cases lt_iff_cons_le.1 (lt_of_le_of_ne (le_inter (add_le_add_right (inter_le_left s t) u) (add_le_add_right (inter_le_right s t) u)) h) with a hl, rw ← cons_add at hl, exact not_le_of_lt (lt_cons_self (s ∩ t) a) (le_inter (le_of_add_le_add_right (le_trans hl (inter_le_left _ _))) (le_of_add_le_add_right (le_trans hl (inter_le_right _ _)))) end theorem add_inter_distrib (s t u : multiset α) : s + (t ∩ u) = (s + t) ∩ (s + u) := by rw [add_comm, inter_add_distrib, add_comm s, add_comm s] theorem cons_inter_distrib (a : α) (s t : multiset α) : a ::ₘ (s ∩ t) = (a ::ₘ s) ∩ (a ::ₘ t) := by simp theorem union_add_inter (s t : multiset α) : s ∪ t + s ∩ t = s + t := begin apply le_antisymm, { rw union_add_distrib, refine union_le (add_le_add_left (inter_le_right _ _) _) _, rw add_comm, exact add_le_add_right (inter_le_left _ _) _ }, { rw [add_comm, add_inter_distrib], refine le_inter (add_le_add_right (le_union_right _ _) _) _, rw add_comm, exact add_le_add_right (le_union_left _ _) _ } end theorem sub_add_inter (s t : multiset α) : s - t + s ∩ t = s := begin rw [inter_comm], revert s, refine multiset.induction_on t (by simp) (λ a t IH s, _), by_cases a ∈ s, { rw [cons_inter_of_pos _ h, sub_cons, add_cons, IH, cons_erase h] }, { rw [cons_inter_of_neg _ h, sub_cons, erase_of_not_mem h, IH] } end theorem sub_inter (s t : multiset α) : s - (s ∩ t) = s - t := add_right_cancel $ by rw [sub_add_inter s t, sub_add_cancel (inter_le_left _ _)] end /-! ### `multiset.filter` -/ section variables (p : α → Prop) [decidable_pred p] /-- `filter p s` returns the elements in `s` (with the same multiplicities) which satisfy `p`, and removes the rest. -/ def filter (s : multiset α) : multiset α := quot.lift_on s (λ l, (filter p l : multiset α)) (λ l₁ l₂ h, quot.sound $ h.filter p) @[simp] theorem coe_filter (l : list α) : filter p (↑l) = l.filter p := rfl @[simp] theorem filter_zero : filter p 0 = 0 := rfl lemma filter_congr {p q : α → Prop} [decidable_pred p] [decidable_pred q] {s : multiset α} : (∀ x ∈ s, p x ↔ q x) → filter p s = filter q s := quot.induction_on s $ λ l h, congr_arg coe $ filter_congr h @[simp] theorem filter_add (s t : multiset α) : filter p (s + t) = filter p s + filter p t := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ filter_append _ _ @[simp] theorem filter_le (s : multiset α) : filter p s ≤ s := quot.induction_on s $ λ l, (filter_sublist _).subperm @[simp] theorem filter_subset (s : multiset α) : filter p s ⊆ s := subset_of_le $ filter_le _ _ theorem filter_le_filter {s t} (h : s ≤ t) : filter p s ≤ filter p t := le_induction_on h $ λ l₁ l₂ h, (filter_sublist_filter p h).subperm variable {p} @[simp] theorem filter_cons_of_pos {a : α} (s) : p a → filter p (a ::ₘ s) = a ::ₘ filter p s := quot.induction_on s $ λ l h, congr_arg coe $ filter_cons_of_pos l h @[simp] theorem filter_cons_of_neg {a : α} (s) : ¬ p a → filter p (a ::ₘ s) = filter p s := quot.induction_on s $ λ l h, @congr_arg _ _ _ _ coe $ filter_cons_of_neg l h @[simp] theorem mem_filter {a : α} {s} : a ∈ filter p s ↔ a ∈ s ∧ p a := quot.induction_on s $ λ l, mem_filter theorem of_mem_filter {a : α} {s} (h : a ∈ filter p s) : p a := (mem_filter.1 h).2 theorem mem_of_mem_filter {a : α} {s} (h : a ∈ filter p s) : a ∈ s := (mem_filter.1 h).1 theorem mem_filter_of_mem {a : α} {l} (m : a ∈ l) (h : p a) : a ∈ filter p l := mem_filter.2 ⟨m, h⟩ theorem filter_eq_self {s} : filter p s = s ↔ ∀ a ∈ s, p a := quot.induction_on s $ λ l, iff.trans ⟨λ h, eq_of_sublist_of_length_eq (filter_sublist _) (@congr_arg _ _ _ _ card h), congr_arg coe⟩ filter_eq_self theorem filter_eq_nil {s} : filter p s = 0 ↔ ∀ a ∈ s, ¬p a := quot.induction_on s $ λ l, iff.trans ⟨λ h, eq_nil_of_length_eq_zero (@congr_arg _ _ _ _ card h), congr_arg coe⟩ filter_eq_nil theorem le_filter {s t} : s ≤ filter p t ↔ s ≤ t ∧ ∀ a ∈ s, p a := ⟨λ h, ⟨le_trans h (filter_le _ _), λ a m, of_mem_filter (mem_of_le h m)⟩, λ ⟨h, al⟩, filter_eq_self.2 al ▸ filter_le_filter p h⟩ variable (p) @[simp] theorem filter_sub [decidable_eq α] (s t : multiset α) : filter p (s - t) = filter p s - filter p t := begin revert s, refine multiset.induction_on t (by simp) (λ a t IH s, _), rw [sub_cons, IH], by_cases p a, { rw [filter_cons_of_pos _ h, sub_cons], congr, by_cases m : a ∈ s, { rw [← cons_inj_right a, ← filter_cons_of_pos _ h, cons_erase (mem_filter_of_mem m h), cons_erase m] }, { rw [erase_of_not_mem m, erase_of_not_mem (mt mem_of_mem_filter m)] } }, { rw [filter_cons_of_neg _ h], by_cases m : a ∈ s, { rw [(by rw filter_cons_of_neg _ h : filter p (erase s a) = filter p (a ::ₘ erase s a)), cons_erase m] }, { rw [erase_of_not_mem m] } } end @[simp] theorem filter_union [decidable_eq α] (s t : multiset α) : filter p (s ∪ t) = filter p s ∪ filter p t := by simp [(∪), union] @[simp] theorem filter_inter [decidable_eq α] (s t : multiset α) : filter p (s ∩ t) = filter p s ∩ filter p t := le_antisymm (le_inter (filter_le_filter _ $ inter_le_left _ _) (filter_le_filter _ $ inter_le_right _ _)) $ le_filter.2 ⟨inf_le_inf (filter_le _ _) (filter_le _ _), λ a h, of_mem_filter (mem_of_le (inter_le_left _ _) h)⟩ @[simp] theorem filter_filter (q) [decidable_pred q] (s : multiset α) : filter p (filter q s) = filter (λ a, p a ∧ q a) s := quot.induction_on s $ λ l, congr_arg coe $ filter_filter p q l theorem filter_add_filter (q) [decidable_pred q] (s : multiset α) : filter p s + filter q s = filter (λ a, p a ∨ q a) s + filter (λ a, p a ∧ q a) s := multiset.induction_on s rfl $ λ a s IH, by by_cases p a; by_cases q a; simp * theorem filter_add_not (s : multiset α) : filter p s + filter (λ a, ¬ p a) s = s := by rw [filter_add_filter, filter_eq_self.2, filter_eq_nil.2]; simp [decidable.em] theorem map_filter (f : β → α) (s : multiset β) : filter p (map f s) = map f (filter (p ∘ f) s) := quot.induction_on s (λ l, by simp [map_filter]) /-! ### Simultaneously filter and map elements of a multiset -/ /-- `filter_map f s` is a combination filter/map operation on `s`. The function `f : α → option β` is applied to each element of `s`; if `f a` is `some b` then `b` is added to the result, otherwise `a` is removed from the resulting multiset. -/ def filter_map (f : α → option β) (s : multiset α) : multiset β := quot.lift_on s (λ l, (filter_map f l : multiset β)) (λ l₁ l₂ h, quot.sound $ h.filter_map f) @[simp] theorem coe_filter_map (f : α → option β) (l : list α) : filter_map f l = l.filter_map f := rfl @[simp] theorem filter_map_zero (f : α → option β) : filter_map f 0 = 0 := rfl @[simp] theorem filter_map_cons_none {f : α → option β} (a : α) (s : multiset α) (h : f a = none) : filter_map f (a ::ₘ s) = filter_map f s := quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ filter_map_cons_none a l h @[simp] theorem filter_map_cons_some (f : α → option β) (a : α) (s : multiset α) {b : β} (h : f a = some b) : filter_map f (a ::ₘ s) = b ::ₘ filter_map f s := quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ filter_map_cons_some f a l h theorem filter_map_eq_map (f : α → β) : filter_map (some ∘ f) = map f := funext $ λ s, quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ congr_fun (filter_map_eq_map f) l theorem filter_map_eq_filter : filter_map (option.guard p) = filter p := funext $ λ s, quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ congr_fun (filter_map_eq_filter p) l theorem filter_map_filter_map (f : α → option β) (g : β → option γ) (s : multiset α) : filter_map g (filter_map f s) = filter_map (λ x, (f x).bind g) s := quot.induction_on s $ λ l, congr_arg coe $ filter_map_filter_map f g l theorem map_filter_map (f : α → option β) (g : β → γ) (s : multiset α) : map g (filter_map f s) = filter_map (λ x, (f x).map g) s := quot.induction_on s $ λ l, congr_arg coe $ map_filter_map f g l theorem filter_map_map (f : α → β) (g : β → option γ) (s : multiset α) : filter_map g (map f s) = filter_map (g ∘ f) s := quot.induction_on s $ λ l, congr_arg coe $ filter_map_map f g l theorem filter_filter_map (f : α → option β) (p : β → Prop) [decidable_pred p] (s : multiset α) : filter p (filter_map f s) = filter_map (λ x, (f x).filter p) s := quot.induction_on s $ λ l, congr_arg coe $ filter_filter_map f p l theorem filter_map_filter (f : α → option β) (s : multiset α) : filter_map f (filter p s) = filter_map (λ x, if p x then f x else none) s := quot.induction_on s $ λ l, congr_arg coe $ filter_map_filter p f l @[simp] theorem filter_map_some (s : multiset α) : filter_map some s = s := quot.induction_on s $ λ l, congr_arg coe $ filter_map_some l @[simp] theorem mem_filter_map (f : α → option β) (s : multiset α) {b : β} : b ∈ filter_map f s ↔ ∃ a, a ∈ s ∧ f a = some b := quot.induction_on s $ λ l, mem_filter_map f l theorem map_filter_map_of_inv (f : α → option β) (g : β → α) (H : ∀ x : α, (f x).map g = some x) (s : multiset α) : map g (filter_map f s) = s := quot.induction_on s $ λ l, congr_arg coe $ map_filter_map_of_inv f g H l theorem filter_map_le_filter_map (f : α → option β) {s t : multiset α} (h : s ≤ t) : filter_map f s ≤ filter_map f t := le_induction_on h $ λ l₁ l₂ h, (h.filter_map _).subperm /-! ### countp -/ /-- `countp p s` counts the number of elements of `s` (with multiplicity) that satisfy `p`. -/ def countp (s : multiset α) : ℕ := quot.lift_on s (countp p) (λ l₁ l₂, perm.countp_eq p) @[simp] theorem coe_countp (l : list α) : countp p l = l.countp p := rfl @[simp] theorem countp_zero : countp p 0 = 0 := rfl variable {p} @[simp] theorem countp_cons_of_pos {a : α} (s) : p a → countp p (a ::ₘ s) = countp p s + 1 := quot.induction_on s $ countp_cons_of_pos p @[simp] theorem countp_cons_of_neg {a : α} (s) : ¬ p a → countp p (a ::ₘ s) = countp p s := quot.induction_on s $ countp_cons_of_neg p variable (p) theorem countp_eq_card_filter (s) : countp p s = card (filter p s) := quot.induction_on s $ λ l, countp_eq_length_filter _ _ @[simp] theorem countp_add (s t) : countp p (s + t) = countp p s + countp p t := by simp [countp_eq_card_filter] instance countp.is_add_monoid_hom : is_add_monoid_hom (countp p : multiset α → ℕ) := { map_add := countp_add _, map_zero := countp_zero _ } @[simp] theorem countp_sub [decidable_eq α] {s t : multiset α} (h : t ≤ s) : countp p (s - t) = countp p s - countp p t := by simp [countp_eq_card_filter, h, filter_le_filter] theorem countp_le_of_le {s t} (h : s ≤ t) : countp p s ≤ countp p t := by simpa [countp_eq_card_filter] using card_le_of_le (filter_le_filter p h) @[simp] theorem countp_filter (q) [decidable_pred q] (s : multiset α) : countp p (filter q s) = countp (λ a, p a ∧ q a) s := by simp [countp_eq_card_filter] variable {p} theorem countp_pos {s} : 0 < countp p s ↔ ∃ a ∈ s, p a := by simp [countp_eq_card_filter, card_pos_iff_exists_mem] theorem countp_pos_of_mem {s a} (h : a ∈ s) (pa : p a) : 0 < countp p s := countp_pos.2 ⟨_, h, pa⟩ end /-! ### Multiplicity of an element -/ section variable [decidable_eq α] /-- `count a s` is the multiplicity of `a` in `s`. -/ def count (a : α) : multiset α → ℕ := countp (eq a) @[simp] theorem coe_count (a : α) (l : list α) : count a (↑l) = l.count a := coe_countp _ _ @[simp] theorem count_zero (a : α) : count a 0 = 0 := rfl @[simp] theorem count_cons_self (a : α) (s : multiset α) : count a (a ::ₘ s) = succ (count a s) := countp_cons_of_pos _ rfl @[simp, priority 990] theorem count_cons_of_ne {a b : α} (h : a ≠ b) (s : multiset α) : count a (b ::ₘ s) = count a s := countp_cons_of_neg _ h theorem count_le_of_le (a : α) {s t} : s ≤ t → count a s ≤ count a t := countp_le_of_le _ theorem count_le_count_cons (a b : α) (s : multiset α) : count a s ≤ count a (b ::ₘ s) := count_le_of_le _ (le_cons_self _ _) theorem count_cons (a b : α) (s : multiset α) : count a (b ::ₘ s) = count a s + (if a = b then 1 else 0) := by by_cases h : a = b; simp [h] theorem count_singleton (a : α) : count a (a ::ₘ 0) = 1 := by simp @[simp] theorem count_add (a : α) : ∀ s t, count a (s + t) = count a s + count a t := countp_add _ instance count.is_add_monoid_hom (a : α) : is_add_monoid_hom (count a : multiset α → ℕ) := countp.is_add_monoid_hom _ @[simp] theorem count_nsmul (a : α) (n s) : count a (n • s) = n * count a s := by induction n; simp [*, succ_nsmul', succ_mul, zero_nsmul] theorem count_pos {a : α} {s : multiset α} : 0 < count a s ↔ a ∈ s := by simp [count, countp_pos] @[simp, priority 980] theorem count_eq_zero_of_not_mem {a : α} {s : multiset α} (h : a ∉ s) : count a s = 0 := by_contradiction $ λ h', h $ count_pos.1 (nat.pos_of_ne_zero h') @[simp] theorem count_eq_zero {a : α} {s : multiset α} : count a s = 0 ↔ a ∉ s := iff_not_comm.1 $ count_pos.symm.trans pos_iff_ne_zero theorem count_ne_zero {a : α} {s : multiset α} : count a s ≠ 0 ↔ a ∈ s := by simp [ne.def, count_eq_zero] @[simp] theorem count_repeat_self (a : α) (n : ℕ) : count a (repeat a n) = n := by simp [repeat] theorem count_repeat (a b : α) (n : ℕ) : count a (repeat b n) = if (a = b) then n else 0 := begin split_ifs with h₁, { rw [h₁, count_repeat_self] }, { rw [count_eq_zero], apply mt eq_of_mem_repeat h₁ }, end @[simp] theorem count_erase_self (a : α) (s : multiset α) : count a (erase s a) = pred (count a s) := begin by_cases a ∈ s, { rw [(by rw cons_erase h : count a s = count a (a ::ₘ erase s a)), count_cons_self]; refl }, { rw [erase_of_not_mem h, count_eq_zero.2 h]; refl } end @[simp, priority 980] theorem count_erase_of_ne {a b : α} (ab : a ≠ b) (s : multiset α) : count a (erase s b) = count a s := begin by_cases b ∈ s, { rw [← count_cons_of_ne ab, cons_erase h] }, { rw [erase_of_not_mem h] } end @[simp] theorem count_sub (a : α) (s t : multiset α) : count a (s - t) = count a s - count a t := begin revert s, refine multiset.induction_on t (by simp) (λ b t IH s, _), rw [sub_cons, IH], by_cases ab : a = b, { subst b, rw [count_erase_self, count_cons_self, sub_succ, pred_sub] }, { rw [count_erase_of_ne ab, count_cons_of_ne ab] } end @[simp] theorem count_union (a : α) (s t : multiset α) : count a (s ∪ t) = max (count a s) (count a t) := by simp [(∪), union, sub_add_eq_max, -add_comm] @[simp] theorem count_inter (a : α) (s t : multiset α) : count a (s ∩ t) = min (count a s) (count a t) := begin apply @nat.add_left_cancel (count a (s - t)), rw [← count_add, sub_add_inter, count_sub, sub_add_min], end lemma count_sum {m : multiset β} {f : β → multiset α} {a : α} : count a (map f m).sum = sum (m.map $ λb, count a $ f b) := multiset.induction_on m (by simp) ( by simp) lemma count_bind {m : multiset β} {f : β → multiset α} {a : α} : count a (bind m f) = sum (m.map $ λb, count a $ f b) := count_sum theorem le_count_iff_repeat_le {a : α} {s : multiset α} {n : ℕ} : n ≤ count a s ↔ repeat a n ≤ s := quot.induction_on s $ λ l, le_count_iff_repeat_sublist.trans repeat_le_coe.symm @[simp] theorem count_filter_of_pos {p} [decidable_pred p] {a} {s : multiset α} (h : p a) : count a (filter p s) = count a s := quot.induction_on s $ λ l, count_filter h @[simp] theorem count_filter_of_neg {p} [decidable_pred p] {a} {s : multiset α} (h : ¬ p a) : count a (filter p s) = 0 := multiset.count_eq_zero_of_not_mem (λ t, h (of_mem_filter t)) theorem ext {s t : multiset α} : s = t ↔ ∀ a, count a s = count a t := quotient.induction_on₂ s t $ λ l₁ l₂, quotient.eq.trans perm_iff_count @[ext] theorem ext' {s t : multiset α} : (∀ a, count a s = count a t) → s = t := ext.2 @[simp] theorem coe_inter (s t : list α) : (s ∩ t : multiset α) = (s.bag_inter t : list α) := by ext; simp theorem le_iff_count {s t : multiset α} : s ≤ t ↔ ∀ a, count a s ≤ count a t := ⟨λ h a, count_le_of_le a h, λ al, by rw ← (ext.2 (λ a, by simp [max_eq_right (al a)]) : s ∪ t = t); apply le_union_left⟩ instance : distrib_lattice (multiset α) := { le_sup_inf := λ s t u, le_of_eq $ eq.symm $ ext.2 $ λ a, by simp only [max_min_distrib_left, multiset.count_inter, multiset.sup_eq_union, multiset.count_union, multiset.inf_eq_inter], ..multiset.lattice } instance : semilattice_sup_bot (multiset α) := { bot := 0, bot_le := zero_le, ..multiset.lattice } end @[simp] lemma mem_nsmul {a : α} {s : multiset α} {n : ℕ} (h0 : n ≠ 0) : a ∈ n • s ↔ a ∈ s := begin classical, cases n, { exfalso, apply h0 rfl }, rw [← not_iff_not, ← count_eq_zero, ← count_eq_zero], simp [h0], end /-! ### Lift a relation to `multiset`s -/ section rel /-- `rel r s t` -- lift the relation `r` between two elements to a relation between `s` and `t`, s.t. there is a one-to-one mapping betweem elements in `s` and `t` following `r`. -/ @[mk_iff] inductive rel (r : α → β → Prop) : multiset α → multiset β → Prop | zero : rel 0 0 | cons {a b as bs} : r a b → rel as bs → rel (a ::ₘ as) (b ::ₘ bs) variables {δ : Type*} {r : α → β → Prop} {p : γ → δ → Prop} private lemma rel_flip_aux {s t} (h : rel r s t) : rel (flip r) t s := rel.rec_on h rel.zero (assume _ _ _ _ h₀ h₁ ih, rel.cons h₀ ih) lemma rel_flip {s t} : rel (flip r) s t ↔ rel r t s := ⟨rel_flip_aux, rel_flip_aux⟩ lemma rel_refl_of_refl_on {m : multiset α} {r : α → α → Prop} : (∀ x ∈ m, r x x) → rel r m m := begin apply m.induction_on, { intros, apply rel.zero }, { intros a m ih h, exact rel.cons (h _ (mem_cons_self _ _)) (ih (λ _ ha, h _ (mem_cons_of_mem ha))) } end lemma rel_eq_refl {s : multiset α} : rel (=) s s := rel_refl_of_refl_on (λ x hx, rfl) lemma rel_eq {s t : multiset α} : rel (=) s t ↔ s = t := begin split, { assume h, induction h; simp * }, { assume h, subst h, exact rel_eq_refl } end lemma rel.mono {r p : α → β → Prop} {s t} (hst : rel r s t) (h : ∀(a ∈ s) (b ∈ t), r a b → p a b) : rel p s t := begin induction hst, case rel.zero { exact rel.zero }, case rel.cons : a b s t hab hst ih { apply rel.cons (h a (mem_cons_self _ _) b (mem_cons_self _ _) hab), exact ih (λ a' ha' b' hb' h', h a' (mem_cons_of_mem ha') b' (mem_cons_of_mem hb') h') } end lemma rel.add {s t u v} (hst : rel r s t) (huv : rel r u v) : rel r (s + u) (t + v) := begin induction hst, case rel.zero { simpa using huv }, case rel.cons : a b s t hab hst ih { simpa using ih.cons hab } end lemma rel_flip_eq {s t : multiset α} : rel (λa b, b = a) s t ↔ s = t := show rel (flip (=)) s t ↔ s = t, by rw [rel_flip, rel_eq, eq_comm] @[simp] lemma rel_zero_left {b : multiset β} : rel r 0 b ↔ b = 0 := by rw [rel_iff]; simp @[simp] lemma rel_zero_right {a : multiset α} : rel r a 0 ↔ a = 0 := by rw [rel_iff]; simp lemma rel_cons_left {a as bs} : rel r (a ::ₘ as) bs ↔ (∃b bs', r a b ∧ rel r as bs' ∧ bs = b ::ₘ bs') := begin split, { generalize hm : a ::ₘ as = m, assume h, induction h generalizing as, case rel.zero { simp at hm, contradiction }, case rel.cons : a' b as' bs ha'b h ih { rcases cons_eq_cons.1 hm with ⟨eq₁, eq₂⟩ | ⟨h, cs, eq₁, eq₂⟩, { subst eq₁, subst eq₂, exact ⟨b, bs, ha'b, h, rfl⟩ }, { rcases ih eq₂.symm with ⟨b', bs', h₁, h₂, eq⟩, exact ⟨b', b ::ₘ bs', h₁, eq₁.symm ▸ rel.cons ha'b h₂, eq.symm ▸ cons_swap _ _ _⟩ } } }, { exact assume ⟨b, bs', hab, h, eq⟩, eq.symm ▸ rel.cons hab h } end lemma rel_cons_right {as b bs} : rel r as (b ::ₘ bs) ↔ (∃a as', r a b ∧ rel r as' bs ∧ as = a ::ₘ as') := begin rw [← rel_flip, rel_cons_left], apply exists_congr, assume a, apply exists_congr, assume as', rw [rel_flip, flip] end lemma rel_add_left {as₀ as₁} : ∀{bs}, rel r (as₀ + as₁) bs ↔ (∃bs₀ bs₁, rel r as₀ bs₀ ∧ rel r as₁ bs₁ ∧ bs = bs₀ + bs₁) := multiset.induction_on as₀ (by simp) begin assume a s ih bs, simp only [ih, cons_add, rel_cons_left], split, { assume h, rcases h with ⟨b, bs', hab, h, rfl⟩, rcases h with ⟨bs₀, bs₁, h₀, h₁, rfl⟩, exact ⟨b ::ₘ bs₀, bs₁, ⟨b, bs₀, hab, h₀, rfl⟩, h₁, by simp⟩ }, { assume h, rcases h with ⟨bs₀, bs₁, h, h₁, rfl⟩, rcases h with ⟨b, bs, hab, h₀, rfl⟩, exact ⟨b, bs + bs₁, hab, ⟨bs, bs₁, h₀, h₁, rfl⟩, by simp⟩ } end lemma rel_add_right {as bs₀ bs₁} : rel r as (bs₀ + bs₁) ↔ (∃as₀ as₁, rel r as₀ bs₀ ∧ rel r as₁ bs₁ ∧ as = as₀ + as₁) := by rw [← rel_flip, rel_add_left]; simp [rel_flip] lemma rel_map_left {s : multiset γ} {f : γ → α} : ∀{t}, rel r (s.map f) t ↔ rel (λa b, r (f a) b) s t := multiset.induction_on s (by simp) (by simp [rel_cons_left] {contextual := tt}) lemma rel_map_right {s : multiset α} {t : multiset γ} {f : γ → β} : rel r s (t.map f) ↔ rel (λa b, r a (f b)) s t := by rw [← rel_flip, rel_map_left, ← rel_flip]; refl lemma rel_join {s t} (h : rel (rel r) s t) : rel r s.join t.join := begin induction h, case rel.zero { simp }, case rel.cons : a b s t hab hst ih { simpa using hab.add ih } end lemma rel_map {s : multiset α} {t : multiset β} {f : α → γ} {g : β → δ} : rel p (s.map f) (t.map g) ↔ rel (λa b, p (f a) (g b)) s t := rel_map_left.trans rel_map_right lemma rel_bind {p : γ → δ → Prop} {s t} {f : α → multiset γ} {g : β → multiset δ} (h : (r ⇒ rel p) f g) (hst : rel r s t) : rel p (s.bind f) (t.bind g) := by { apply rel_join, rw rel_map, exact hst.mono (λ a ha b hb hr, h hr) } lemma card_eq_card_of_rel {r : α → β → Prop} {s : multiset α} {t : multiset β} (h : rel r s t) : card s = card t := by induction h; simp [*] lemma exists_mem_of_rel_of_mem {r : α → β → Prop} {s : multiset α} {t : multiset β} (h : rel r s t) : ∀ {a : α} (ha : a ∈ s), ∃ b ∈ t, r a b := begin induction h with x y s t hxy hst ih, { simp }, { assume a ha, cases mem_cons.1 ha with ha ha, { exact ⟨y, mem_cons_self _ _, ha.symm ▸ hxy⟩ }, { rcases ih ha with ⟨b, hbt, hab⟩, exact ⟨b, mem_cons.2 (or.inr hbt), hab⟩ } } end lemma rel_of_forall {m1 m2 : multiset α} {r : α → α → Prop} (h : ∀ a b, a ∈ m1 → b ∈ m2 → r a b) (hc : card m1 = card m2) : m1.rel r m2 := begin revert m1, apply m2.induction_on, { intros m h hc, rw [rel_zero_right, ← card_eq_zero, hc, card_zero] }, { intros a t ih m h hc, rw card_cons at hc, obtain ⟨b, hb⟩ := card_pos_iff_exists_mem.1 (show 0 < card m, from hc.symm ▸ (nat.succ_pos _)), obtain ⟨m', rfl⟩ := exists_cons_of_mem hb, refine rel_cons_right.mpr ⟨b, m', h _ _ hb (mem_cons_self _ _), ih _ _, rfl⟩, { exact λ _ _ ha hb, h _ _ (mem_cons_of_mem ha) (mem_cons_of_mem hb) }, { simpa using hc } } end lemma rel_repeat_left {m : multiset α} {a : α} {r : α → α → Prop} {n : ℕ} : (repeat a n).rel r m ↔ m.card = n ∧ ∀ x, x ∈ m → r a x := ⟨λ h, ⟨(card_eq_card_of_rel h).symm.trans (card_repeat _ _), λ x hx, begin obtain ⟨b, hb1, hb2⟩ := exists_mem_of_rel_of_mem (rel_flip.2 h) hx, rwa eq_of_mem_repeat hb1 at hb2, end⟩, λ h, rel_of_forall (λ x y hx hy, (eq_of_mem_repeat hx).symm ▸ (h.2 _ hy)) (eq.trans (card_repeat _ _) h.1.symm)⟩ lemma rel_repeat_right {m : multiset α} {a : α} {r : α → α → Prop} {n : ℕ} : m.rel r (repeat a n) ↔ m.card = n ∧ ∀ x, x ∈ m → r x a := by { rw [← rel_flip], exact rel_repeat_left } lemma sum_le_sum_of_rel_le [ordered_add_comm_monoid α] {m1 m2 : multiset α} (h : m1.rel (≤) m2) : m1.sum ≤ m2.sum := begin induction h with _ _ _ _ rh _ rt, { refl }, { rw [sum_cons, sum_cons], exact add_le_add rh rt } end end rel section sum_inequalities variables [ordered_add_comm_monoid α] lemma sum_map_le_sum {m : multiset α} (f : α → α) (h : ∀ x, x ∈ m → f x ≤ x) : (m.map f).sum ≤ m.sum := sum_le_sum_of_rel_le (rel_map_left.2 (rel_refl_of_refl_on h)) lemma sum_le_sum_map {m : multiset α} (f : α → α) (h : ∀ x, x ∈ m → x ≤ f x) : m.sum ≤ (m.map f).sum := @sum_map_le_sum (order_dual α) _ _ f h lemma card_nsmul_le_sum {b : α} {m : multiset α} (h : ∀ x, x ∈ m → b ≤ x) : (card m) • b ≤ m.sum := begin rw [←multiset.sum_repeat, ←multiset.map_const], exact sum_map_le_sum _ h, end lemma sum_le_card_nsmul {b : α} {m : multiset α} (h : ∀ x, x ∈ m → x ≤ b) : m.sum ≤ (card m) • b := begin rw [←multiset.sum_repeat, ←multiset.map_const], exact sum_le_sum_map _ h, end end sum_inequalities section map theorem map_eq_map {f : α → β} (hf : function.injective f) {s t : multiset α} : s.map f = t.map f ↔ s = t := by { rw [← rel_eq, ← rel_eq, rel_map], simp only [hf.eq_iff] } theorem map_injective {f : α → β} (hf : function.injective f) : function.injective (multiset.map f) := assume x y, (map_eq_map hf).1 end map section quot theorem map_mk_eq_map_mk_of_rel {r : α → α → Prop} {s t : multiset α} (hst : s.rel r t) : s.map (quot.mk r) = t.map (quot.mk r) := rel.rec_on hst rfl $ assume a b s t hab hst ih, by simp [ih, quot.sound hab] theorem exists_multiset_eq_map_quot_mk {r : α → α → Prop} (s : multiset (quot r)) : ∃t:multiset α, s = t.map (quot.mk r) := multiset.induction_on s ⟨0, rfl⟩ $ assume a s ⟨t, ht⟩, quot.induction_on a $ assume a, ht.symm ▸ ⟨a ::ₘ t, (map_cons _ _ _).symm⟩ theorem induction_on_multiset_quot {r : α → α → Prop} {p : multiset (quot r) → Prop} (s : multiset (quot r)) : (∀s:multiset α, p (s.map (quot.mk r))) → p s := match s, exists_multiset_eq_map_quot_mk s with _, ⟨t, rfl⟩ := assume h, h _ end end quot /-! ### Disjoint multisets -/ /-- `disjoint s t` means that `s` and `t` have no elements in common. -/ def disjoint (s t : multiset α) : Prop := ∀ ⦃a⦄, a ∈ s → a ∈ t → false @[simp] theorem coe_disjoint (l₁ l₂ : list α) : @disjoint α l₁ l₂ ↔ l₁.disjoint l₂ := iff.rfl theorem disjoint.symm {s t : multiset α} (d : disjoint s t) : disjoint t s | a i₂ i₁ := d i₁ i₂ theorem disjoint_comm {s t : multiset α} : disjoint s t ↔ disjoint t s := ⟨disjoint.symm, disjoint.symm⟩ theorem disjoint_left {s t : multiset α} : disjoint s t ↔ ∀ {a}, a ∈ s → a ∉ t := iff.rfl theorem disjoint_right {s t : multiset α} : disjoint s t ↔ ∀ {a}, a ∈ t → a ∉ s := disjoint_comm theorem disjoint_iff_ne {s t : multiset α} : disjoint s t ↔ ∀ a ∈ s, ∀ b ∈ t, a ≠ b := by simp [disjoint_left, imp_not_comm] theorem disjoint_of_subset_left {s t u : multiset α} (h : s ⊆ u) (d : disjoint u t) : disjoint s t | x m₁ := d (h m₁) theorem disjoint_of_subset_right {s t u : multiset α} (h : t ⊆ u) (d : disjoint s u) : disjoint s t | x m m₁ := d m (h m₁) theorem disjoint_of_le_left {s t u : multiset α} (h : s ≤ u) : disjoint u t → disjoint s t := disjoint_of_subset_left (subset_of_le h) theorem disjoint_of_le_right {s t u : multiset α} (h : t ≤ u) : disjoint s u → disjoint s t := disjoint_of_subset_right (subset_of_le h) @[simp] theorem zero_disjoint (l : multiset α) : disjoint 0 l | a := (not_mem_nil a).elim @[simp, priority 1100] theorem singleton_disjoint {l : multiset α} {a : α} : disjoint (a ::ₘ 0) l ↔ a ∉ l := by simp [disjoint]; refl @[simp, priority 1100] theorem disjoint_singleton {l : multiset α} {a : α} : disjoint l (a ::ₘ 0) ↔ a ∉ l := by rw disjoint_comm; simp @[simp] theorem disjoint_add_left {s t u : multiset α} : disjoint (s + t) u ↔ disjoint s u ∧ disjoint t u := by simp [disjoint, or_imp_distrib, forall_and_distrib] @[simp] theorem disjoint_add_right {s t u : multiset α} : disjoint s (t + u) ↔ disjoint s t ∧ disjoint s u := by rw [disjoint_comm, disjoint_add_left]; tauto @[simp] theorem disjoint_cons_left {a : α} {s t : multiset α} : disjoint (a ::ₘ s) t ↔ a ∉ t ∧ disjoint s t := (@disjoint_add_left _ (a ::ₘ 0) s t).trans $ by simp @[simp] theorem disjoint_cons_right {a : α} {s t : multiset α} : disjoint s (a ::ₘ t) ↔ a ∉ s ∧ disjoint s t := by rw [disjoint_comm, disjoint_cons_left]; tauto theorem inter_eq_zero_iff_disjoint [decidable_eq α] {s t : multiset α} : s ∩ t = 0 ↔ disjoint s t := by rw ← subset_zero; simp [subset_iff, disjoint] @[simp] theorem disjoint_union_left [decidable_eq α] {s t u : multiset α} : disjoint (s ∪ t) u ↔ disjoint s u ∧ disjoint t u := by simp [disjoint, or_imp_distrib, forall_and_distrib] @[simp] theorem disjoint_union_right [decidable_eq α] {s t u : multiset α} : disjoint s (t ∪ u) ↔ disjoint s t ∧ disjoint s u := by simp [disjoint, or_imp_distrib, forall_and_distrib] lemma disjoint_map_map {f : α → γ} {g : β → γ} {s : multiset α} {t : multiset β} : disjoint (s.map f) (t.map g) ↔ (∀a∈s, ∀b∈t, f a ≠ g b) := by { simp [disjoint, @eq_comm _ (f _) (g _)], refl } /-- `pairwise r m` states that there exists a list of the elements s.t. `r` holds pairwise on this list. -/ def pairwise (r : α → α → Prop) (m : multiset α) : Prop := ∃l:list α, m = l ∧ l.pairwise r lemma pairwise_coe_iff_pairwise {r : α → α → Prop} (hr : symmetric r) {l : list α} : multiset.pairwise r l ↔ l.pairwise r := iff.intro (assume ⟨l', eq, h⟩, ((quotient.exact eq).pairwise_iff hr).2 h) (assume h, ⟨l, rfl, h⟩) end multiset namespace multiset section choose variables (p : α → Prop) [decidable_pred p] (l : multiset α) /-- Given a proof `hp` that there exists a unique `a ∈ l` such that `p a`, `choose_x p l hp` returns that `a` together with proofs of `a ∈ l` and `p a`. -/ def choose_x : Π hp : (∃! a, a ∈ l ∧ p a), { a // a ∈ l ∧ p a } := quotient.rec_on l (λ l' ex_unique, list.choose_x p l' (exists_of_exists_unique ex_unique)) begin intros, funext hp, suffices all_equal : ∀ x y : { t // t ∈ b ∧ p t }, x = y, { apply all_equal }, { rintros ⟨x, px⟩ ⟨y, py⟩, rcases hp with ⟨z, ⟨z_mem_l, pz⟩, z_unique⟩, congr, calc x = z : z_unique x px ... = y : (z_unique y py).symm } end /-- Given a proof `hp` that there exists a unique `a ∈ l` such that `p a`, `choose p l hp` returns that `a`. -/ def choose (hp : ∃! a, a ∈ l ∧ p a) : α := choose_x p l hp lemma choose_spec (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l ∧ p (choose p l hp) := (choose_x p l hp).property lemma choose_mem (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l := (choose_spec _ _ _).1 lemma choose_property (hp : ∃! a, a ∈ l ∧ p a) : p (choose p l hp) := (choose_spec _ _ _).2 end choose variable (α) /-- The equivalence between lists and multisets of a subsingleton type. -/ def subsingleton_equiv [subsingleton α] : list α ≃ multiset α := { to_fun := coe, inv_fun := quot.lift id $ λ (a b : list α) (h : a ~ b), list.ext_le h.length_eq $ λ n h₁ h₂, subsingleton.elim _ _, left_inv := λ l, rfl, right_inv := λ m, quot.induction_on m $ λ l, rfl } variable {α} @[simp] lemma coe_subsingleton_equiv [subsingleton α] : (subsingleton_equiv α : list α → multiset α) = coe := rfl end multiset @[to_additive] theorem monoid_hom.map_multiset_prod [comm_monoid α] [comm_monoid β] (f : α →* β) (s : multiset α) : f s.prod = (s.map f).prod := (s.prod_hom f).symm
059f844ef9e16a0cbf4c6087f30bd65c0e8088ca
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/ring_theory/algebra_operations.lean
da20984a3eda8a7f88ff9999721251035ff2eb04
[ "Apache-2.0" ]
permissive
vaibhavkarve/mathlib
a574aaf68c0a431a47fa82ce0637f0f769826bfe
17f8340912468f49bdc30acdb9a9fa02eeb0473a
refs/heads/master
1,621,263,802,637
1,585,399,588,000
1,585,399,588,000
250,833,447
0
0
Apache-2.0
1,585,410,341,000
1,585,410,341,000
null
UTF-8
Lean
false
false
9,134
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau Multiplication and division of submodules of an algebra. -/ import ring_theory.algebra algebra.pointwise import tactic.chain import tactic.monotonicity.basic universes u v open algebra local attribute [instance] set.pointwise_mul_semiring namespace submodule variables {R : Type u} [comm_ring R] section ring variables {A : Type v} [ring A] [algebra R A] variables (S T : set A) {M N P Q : submodule R A} {m n : A} instance : has_one (submodule R A) := ⟨submodule.map (of_id R A).to_linear_map (⊤ : ideal R)⟩ theorem one_eq_map_top : (1 : submodule R A) = submodule.map (of_id R A).to_linear_map (⊤ : ideal R) := rfl theorem one_eq_span : (1 : submodule R A) = span R {1} := begin apply submodule.ext, intro a, erw [mem_map, mem_span_singleton], apply exists_congr, intro r, simpa [smul_def], end theorem one_le : (1 : submodule R A) ≤ P ↔ (1 : A) ∈ P := by simpa only [one_eq_span, span_le, set.singleton_subset_iff] set_option class.instance_max_depth 50 instance : has_mul (submodule R A) := ⟨λ M N, ⨆ s : M, N.map $ algebra.lmul R A s.1⟩ set_option class.instance_max_depth 32 theorem mul_mem_mul (hm : m ∈ M) (hn : n ∈ N) : m * n ∈ M * N := (le_supr _ ⟨m, hm⟩ : _ ≤ M * N) ⟨n, hn, rfl⟩ theorem mul_le : M * N ≤ P ↔ ∀ (m ∈ M) (n ∈ N), m * n ∈ P := ⟨λ H m hm n hn, H $ mul_mem_mul hm hn, λ H, supr_le $ λ ⟨m, hm⟩, map_le_iff_le_comap.2 $ λ n hn, H m hm n hn⟩ @[elab_as_eliminator] protected theorem mul_induction_on {C : A → Prop} {r : A} (hr : r ∈ M * N) (hm : ∀ (m ∈ M) (n ∈ N), C (m * n)) (h0 : C 0) (ha : ∀ x y, C x → C y → C (x + y)) (hs : ∀ (r : R) x, C x → C (r • x)) : C r := (@mul_le _ _ _ _ _ _ _ ⟨C, h0, ha, hs⟩).2 hm hr variables R theorem span_mul_span : span R S * span R T = span R (S * T) := begin apply le_antisymm, { rw mul_le, intros a ha b hb, apply span_induction ha, work_on_goal 0 { intros, apply span_induction hb, work_on_goal 0 { intros, exact subset_span ⟨_, ‹_›, _, ‹_›, rfl⟩ } }, all_goals { intros, simp only [mul_zero, zero_mul, zero_mem, left_distrib, right_distrib, mul_smul_comm, smul_mul_assoc], try {apply add_mem _ _ _}, try {apply smul_mem _ _ _} }, assumption' }, { rw span_le, rintros _ ⟨a, ha, b, hb, rfl⟩, exact mul_mem_mul (subset_span ha) (subset_span hb) } end variables {R} variables (M N P Q) set_option class.instance_max_depth 50 protected theorem mul_assoc : (M * N) * P = M * (N * P) := le_antisymm (mul_le.2 $ λ mn hmn p hp, suffices M * N ≤ (M * (N * P)).comap ((algebra.lmul R A).flip p), from this hmn, mul_le.2 $ λ m hm n hn, show m * n * p ∈ M * (N * P), from (mul_assoc m n p).symm ▸ mul_mem_mul hm (mul_mem_mul hn hp)) (mul_le.2 $ λ m hm np hnp, suffices N * P ≤ (M * N * P).comap (algebra.lmul R A m), from this hnp, mul_le.2 $ λ n hn p hp, show m * (n * p) ∈ M * N * P, from mul_assoc m n p ▸ mul_mem_mul (mul_mem_mul hm hn) hp) set_option class.instance_max_depth 32 @[simp] theorem mul_bot : M * ⊥ = ⊥ := eq_bot_iff.2 $ mul_le.2 $ λ m hm n hn, by rw [submodule.mem_bot] at hn ⊢; rw [hn, mul_zero] @[simp] theorem bot_mul : ⊥ * M = ⊥ := eq_bot_iff.2 $ mul_le.2 $ λ m hm n hn, by rw [submodule.mem_bot] at hm ⊢; rw [hm, zero_mul] @[simp] protected theorem one_mul : (1 : submodule R A) * M = M := by { conv_lhs { rw [one_eq_span, ← span_eq M] }, erw [span_mul_span, one_mul, span_eq] } @[simp] protected theorem mul_one : M * 1 = M := by { conv_lhs { rw [one_eq_span, ← span_eq M] }, erw [span_mul_span, mul_one, span_eq] } variables {M N P Q} @[mono] theorem mul_le_mul (hmp : M ≤ P) (hnq : N ≤ Q) : M * N ≤ P * Q := mul_le.2 $ λ m hm n hn, mul_mem_mul (hmp hm) (hnq hn) theorem mul_le_mul_left (h : M ≤ N) : M * P ≤ N * P := mul_le_mul h (le_refl P) theorem mul_le_mul_right (h : N ≤ P) : M * N ≤ M * P := mul_le_mul (le_refl M) h variables (M N P) theorem mul_sup : M * (N ⊔ P) = M * N ⊔ M * P := le_antisymm (mul_le.2 $ λ m hm np hnp, let ⟨n, hn, p, hp, hnp⟩ := mem_sup.1 hnp in mem_sup.2 ⟨_, mul_mem_mul hm hn, _, mul_mem_mul hm hp, hnp ▸ (mul_add m n p).symm⟩) (sup_le (mul_le_mul_right le_sup_left) (mul_le_mul_right le_sup_right)) theorem sup_mul : (M ⊔ N) * P = M * P ⊔ N * P := le_antisymm (mul_le.2 $ λ mn hmn p hp, let ⟨m, hm, n, hn, hmn⟩ := mem_sup.1 hmn in mem_sup.2 ⟨_, mul_mem_mul hm hp, _, mul_mem_mul hn hp, hmn ▸ (add_mul m n p).symm⟩) (sup_le (mul_le_mul_left le_sup_left) (mul_le_mul_left le_sup_right)) lemma mul_subset_mul : (↑M : set A) * (↑N : set A) ⊆ (↑(M * N) : set A) := begin rintros _ ⟨i, hi, j, hj, rfl⟩, exact mul_mem_mul hi hj end variables {M N P} instance : semiring (submodule R A) := { one_mul := submodule.one_mul, mul_one := submodule.mul_one, mul_assoc := submodule.mul_assoc, zero_mul := bot_mul, mul_zero := mul_bot, left_distrib := mul_sup, right_distrib := sup_mul, ..submodule.add_comm_monoid, ..submodule.has_one, ..submodule.has_mul } variables (M) lemma pow_subset_pow {n : ℕ} : (↑M : set A)^n ⊆ ↑(M^n : submodule R A) := begin induction n with n ih, { erw [pow_zero, pow_zero, set.singleton_subset_iff], rw [mem_coe, ← one_le], exact le_refl _ }, { rw [pow_succ, pow_succ], refine set.subset.trans (set.pointwise_mul_subset_mul (set.subset.refl _) ih) _, apply mul_subset_mul } end instance span.is_semiring_hom : is_semiring_hom (submodule.span R : set A → submodule R A) := { map_zero := span_empty, map_one := show _ = map _ ⊤, by erw [← ideal.span_singleton_one, ← span_image, set.image_singleton, alg_hom.map_one]; refl, map_add := span_union, map_mul := λ s t, by erw [span_mul_span, set.pointwise_mul_eq_image] } end ring section comm_ring variables {A : Type v} [comm_ring A] [algebra R A] variables {M N : submodule R A} {m n : A} theorem mul_mem_mul_rev (hm : m ∈ M) (hn : n ∈ N) : n * m ∈ M * N := mul_comm m n ▸ mul_mem_mul hm hn variables (M N) protected theorem mul_comm : M * N = N * M := le_antisymm (mul_le.2 $ λ r hrm s hsn, mul_mem_mul_rev hsn hrm) (mul_le.2 $ λ r hrn s hsm, mul_mem_mul_rev hsm hrn) instance : comm_semiring (submodule R A) := { mul_comm := submodule.mul_comm, .. submodule.semiring } variables (R A) instance semimodule_set : semimodule (set A) (submodule R A) := { smul := λ s P, span R s * P, smul_add := λ _ _ _, mul_add _ _ _, add_smul := λ s t P, show span R (s ⊔ t) * P = _, by { erw [span_union, right_distrib] }, mul_smul := λ s t P, show _ = _ * (_ * _), by { rw [← mul_assoc, span_mul_span, set.pointwise_mul_eq_image] }, one_smul := λ P, show span R {(1 : A)} * P = _, by { conv_lhs {erw ← span_eq P}, erw [span_mul_span, one_mul, span_eq] }, zero_smul := λ P, show span R ∅ * P = ⊥, by erw [span_empty, bot_mul], smul_zero := λ _, mul_bot _ } set_option class.instance_max_depth 45 variables {R A} lemma smul_def {s : set A} {P : submodule R A} : s • P = span R s * P := rfl lemma smul_le_smul {s t : set A} {M N : submodule R A} (h₁ : s ≤ t) (h₂ : M ≤ N) : s • M ≤ t • N := mul_le_mul (span_mono h₁) h₂ lemma smul_singleton (a : A) (M : submodule R A) : ({a} : set A) • M = M.map (lmul_left _ _ a) := begin conv_lhs {rw ← span_eq M}, change span _ _ * span _ _ = _, rw [span_mul_span], apply le_antisymm, { rw span_le, rintros _ ⟨b, hb, m, hm, rfl⟩, erw [mem_map, set.mem_singleton_iff.mp hb], exact ⟨m, hm, rfl⟩ }, { rintros _ ⟨m, hm, rfl⟩, exact subset_span ⟨a, set.mem_singleton a, m, hm, rfl⟩ } end section quotient local attribute [instance] set.smul_set_action /-- The elements of `I / J` are the `x` such that `x • J ⊆ I`. In fact, we define `x ∈ I / J` to be `∀ y ∈ J, x * y ∈ I` (see `mem_div_iff_forall_mul_mem`), which is equivalent to `x • J ⊆ I` (see `mem_div_iff_smul_subset`), but nicer to use in proofs. This is the general form of the ideal quotient, traditionally written $I : J$. -/ instance : has_div (submodule R A) := ⟨ λ I J, { carrier := { x | ∀ y ∈ J, x * y ∈ I }, zero := λ y hy, by { rw zero_mul, apply submodule.zero }, add := λ a b ha hb y hy, by { rw add_mul, exact submodule.add _ (ha _ hy) (hb _ hy) }, smul := λ r x hx y hy, by { rw algebra.smul_mul_assoc, exact submodule.smul _ _ (hx _ hy) } } ⟩ lemma mem_div_iff_forall_mul_mem {x : A} {I J : submodule R A} : x ∈ I / J ↔ ∀ y ∈ J, x * y ∈ I := iff.refl _ lemma mem_div_iff_smul_subset {x : A} {I J : submodule R A} : x ∈ I / J ↔ x • (J : set A) ⊆ I := ⟨ λ h y ⟨y', hy', y_eq_xy'⟩, by { rw y_eq_xy', apply h, assumption }, λ h y hy, h (set.smul_mem_smul_set _ hy)⟩ lemma le_div_iff {I J K : submodule R A} : I ≤ J / K ↔ ∀ (x ∈ I) (z ∈ K), x * z ∈ J := iff.refl _ end quotient end comm_ring end submodule
fc320dac76ec7af9044f0e6b0acbbf63b38b4cec
b66669ef1ec06ddbd9526fe3afe0a68566dfbad3
/src/grid.lean
ed1a50785afcbd375afaf9762bb1700328c1dc6b
[ "MIT" ]
permissive
FerdoSil/LatticesAndCellularAutomata
40185a9099bb3cf1371c85f1ca33a17c2e26fecb
2a69d2e74a231addf0e446dca86ef90d50d60218
refs/heads/master
1,587,683,992,072
1,586,018,471,000
1,586,018,471,000
171,533,028
0
0
null
null
null
null
UTF-8
Lean
false
false
58,713
lean
-- A formalization of two-dimensional orthogonal geometric lattices, simply called 'grid's. -- The class 'relative_grid' is an abstract interpretation thereof with relative (0, 0)-based indexing. -- The class 'grid' is a generalization of 'relative_grid' to arbitrary (x, y)-relative grids. -- Three concrete instances are available. -- 'vec_grid' and its absolutely-indexed counterpart 'vec_grid₀' represent -- a homogeneous vector-based implementation. -- 'dep_vec_grid' is identical to 'vec_grid' but uses dependent indices -- for its rows and columns -- absolutely-indexed 'fgrid₀' represents -- a function-based implementation. -- The function 'gip_g' enumerates coordinates of a grid. -- The function 'generate' turns a grid into a sequence of elements. -- The function 'abs_data g ⟨x, y⟩' yields the element of g at ⟨x, y⟩. -- The functions 'row' 'col' 'top' 'bot' 'left' 'right' return the respective slices of a grid. -- The function 'subgrid' returns a subgrid of a grid. -- Most theorems present are properties related to this functionality. import utils import data.vector data.list data.int.basic tactic.omega data.fin tactic.linarith tactic.sanity_check open utils section grids class relative_grid (α : Type*) := (carrier : Type) (rows : α → ℕ) (cols : α → ℕ) (nonempty : Πg, rows g * cols g > 0) (contents : Πg, fin (rows g) → fin (cols g) → carrier) class grid (α : Type*) extends relative_grid α := (bl : α → point) section grid_defs variables {α : Type*} [grid α] (g : α) open grid relative_grid notation `|`:max x `|`:0 := int.nat_abs x def size := rows g * cols g attribute [simp] lemma size_eq_rows_mul_cols : size g = rows g * cols g := rfl def tr (bl : point) (r c : ℕ) : point := ⟨bl.x + c, bl.y + r⟩ attribute [simp] def grid_rows := rows g attribute [simp] def grid_cols := cols g attribute [simp] def gbl := bl g def gtr := tr (bl g) (rows g) (cols g) def tl : point := ⟨(bl g).x, (bl g).y + rows g⟩ def br : point := ⟨(bl g).x + cols g, (bl g).y⟩ lemma expand_gbl : gbl g = bl g := by simp lemma expand_gtr : gtr g = ⟨(bl g).x + cols g, (bl g).y + rows g⟩ := by simp [gtr, tr] lemma blx_eq_tlx {g : α} : (bl g).x = (tl g).x := by simp [bl, tl] lemma brx_eq_trx {g : α} : (br g).x = (gtr g).x := by simp [br, expand_gtr] lemma bly_eq_bry {g : α} : (bl g).y = (br g).y := by simp [br] lemma tly_eq_try {g : α} : (tl g).y = (gtr g).y := by simp [expand_gtr, tl] private lemma linear_bounds {l r : ℤ} {c : ℕ} (h₁ : l < r) (h₂ : r - ↑c ≤ l) : |l + ↑c - r| < c := begin rw [← int.coe_nat_lt, @int.nat_abs_of_nonneg (l + ↑c - r) (by linarith)], linarith end structure bounding_box := (p₁ : point) (p₂ : point) (h : p₁ ↗ p₂) def bbox_str : bounding_box → string | ⟨p₁, p₂, _⟩ := "<(" ++ to_string p₁ ++ ", " ++ to_string p₂ ++ ")>" instance : has_to_string bounding_box := ⟨bbox_str⟩ instance : has_repr bounding_box := ⟨bbox_str⟩ def points_of_box (bb : bounding_box) : point × point := ⟨bb.p₁, bb.p₂⟩ def rows_of_box (bb : bounding_box) : ℕ := |bb.p₂.y - bb.p₁.y| def cols_of_box (bb : bounding_box) : ℕ := |bb.p₂.x - bb.p₁.x| private def data_option (g : α) (x y : ℕ) := if h : y < cols g then if h₁ : x < rows g then some $ contents g ⟨x, h₁⟩ ⟨y, h⟩ else none else none end grid_defs section grid_lemmas open grid relative_grid function variables {α : Type*} [grid α] {g : α} private theorem data_data_option {x y : ℕ} (h₁ : y < rows g) (h₂ : x < cols g) : some (contents g ⟨y, h₁⟩ ⟨x, h₂⟩) = data_option g y x := by unfold data_option; repeat { rw dif_pos; try { simp [is_bounded, h.2] } }; simpa lemma rows_of_box_pos {bb : bounding_box} : rows_of_box bb > 0 := let ⟨⟨_, y₁⟩, ⟨_, y₂⟩, h⟩ := bb in begin simp only [rows_of_box, gt_from_lt], simp [grid_bounded_iff] at h, rw [← int.coe_nat_lt_coe_nat_iff, int.nat_abs_of_nonneg]; omega end lemma cols_of_box_pos {bb : bounding_box} : cols_of_box bb > 0 := let ⟨⟨x₁, _⟩, ⟨x₂, _⟩, h⟩ := bb in begin simp only [cols_of_box, gt_from_lt], simp [grid_bounded_iff] at h, rw [← int.coe_nat_lt_coe_nat_iff, int.nat_abs_of_nonneg]; omega end lemma rows_pos : 0 < rows g := (gt_and_gt_of_mul_gt (nonempty g)).1 lemma cols_pos : 0 < cols g := (gt_and_gt_of_mul_gt (nonempty g)).2 lemma abs_rows_pos : 0 < |rows g| := rows_pos lemma abs_cols_pos : 0 < |cols g| := cols_pos lemma coe_rows_pos : (0 : ℤ) < ↑(rows g) := by simp [rows_pos] lemma coe_cols_pos {g : α} : (0 : ℤ) < ↑(cols g) := by simp [cols_pos] lemma idx_div_cols_bounded {n} (h : n < size g) : (bl g).y + ↑n / ↑(cols g) < (gtr g).y := begin simp [expand_gtr, gt_from_lt] at *, norm_cast, rw mul_comm at h, replace h := nat.div_lt_of_lt_mul h, linarith end lemma idx_mod_cols_bounded {n : ℕ} : (bl g).x + ↑n % ↑(cols g) < (gtr g).x := by simp [expand_gtr]; exact int.mod_lt_of_pos _ coe_cols_pos lemma grid_is_bounding_box : bl g ↗ gtr g := let ⟨h₁, h₂⟩ := gt_and_gt_of_mul_gt (nonempty g) in grid_bounded_iff.2 ⟨ by simpa [expand_gtr], by simpa [expand_gtr] ⟩ def bbox_of_grid (g : α) : bounding_box := ⟨bl g, gtr g, grid_is_bounding_box⟩ theorem bbox_of_grid_p₁ : (bbox_of_grid g).p₁ = (gbl g) := rfl theorem bbox_of_grid_p₂ : (bbox_of_grid g).p₂ = (gtr g) := rfl structure relative_point (g : α) := (x : fin (rows g)) (y : fin (cols g)) def relative_point_str (g : α) : relative_point g → string | ⟨x, y⟩ := "[" ++ to_string x ++ ", " ++ to_string y ++ "]" instance : has_to_string (relative_point g) := ⟨relative_point_str g⟩ instance : has_repr (relative_point g) := ⟨relative_point_str g⟩ structure grid_point (g : α) := (y : bounded (bl g).y (gtr g).y) (x : bounded (bl g).x (gtr g).x) def grid_point_str (g : α) : grid_point g → string | ⟨x, y⟩ := "[" ++ to_string x ++ ", " ++ to_string y ++ "] - " ++ to_string (bl g) instance : has_to_string (grid_point g) := ⟨grid_point_str g⟩ instance : has_repr (grid_point g) := ⟨grid_point_str g⟩ lemma gtry_lt_bly : (bl g).y < (gtr g).y := by simp [expand_gtr, rows_pos] lemma gblx_lt_gtrx : (gbl g).x < (gtr g).x := expand_gtr g ▸ expand_gbl g ▸ lt_add_of_pos_right _ coe_cols_pos private lemma grid_rows_eq_try_sub_bly : grid_rows g = |(gtr g).y - (bl g).y| := by simp [expand_gtr] lemma rows_eq_try_sub_bly : rows g = |(gtr g).y - (bl g).y| := grid_rows_eq_try_sub_bly lemma rows_eq_try_sub_bly' : ↑(rows g) = (gtr g).y - (bl g).y := by simp [gtr, tr] private lemma grid_cols_eq_trx_sub_blx : grid_cols g = |((gtr g).x - (bl g).x)| := by simp [expand_gtr] lemma cols_eq_trx_sub_blx : cols g = |((gtr g).x - (bl g).x)| := grid_cols_eq_trx_sub_blx def relpoint_of_gpoint {g : α} (p : grid_point g) : relative_point g := ⟨ ⟨|p.y.1 - (bl g).y|, begin rcases p with ⟨⟨x, ⟨xl, xu⟩⟩, ⟨y, ⟨yl, yu⟩⟩⟩, simp, have eq₁ : x + -(bl g).y ≥ 0, by linarith, have eq₂ : (gtr g).y - (bl g).y ≥ 0, by simp [expand_gtr]; linarith, rw [ ← int.coe_nat_lt_coe_nat_iff, rows_eq_try_sub_bly, int.nat_abs_of_nonneg eq₁, int.nat_abs_of_nonneg eq₂ ], linarith end ⟩, ⟨|p.x.1 - (bl g).x|, have h : p.x.1 - (tl g).x ≥ 0, from le_sub_iff_add_le.2 (by simp [tl, p.x.2.1]), ((int.coe_nat_lt_coe_nat_iff _ _).1 $ (int.nat_abs_of_nonneg h).symm ▸ begin let uby := p.x.2.2, simp only [expand_gtr] at uby, simp only [tl], linarith end) ⟩ ⟩ def gpoint_of_relpoint {g : α} (p : relative_point g) : grid_point g := ⟨ ⟨(bl g).y + p.x.1, ⟨ by simp [tl, expand_gtr], by rcases p with ⟨⟨_, h⟩, _⟩; simp only [tl, expand_gtr, h]; linarith ⟩ ⟩, ⟨(bl g).x + p.y.1, ⟨ by simp [tl], by rcases p with ⟨⟨_, _⟩, ⟨_, h⟩⟩; simp only [tl, expand_gtr, h]; linarith ⟩ ⟩ ⟩ lemma relpoint_gpoint_id {g : α} {p : grid_point g} : gpoint_of_relpoint (relpoint_of_gpoint p) = p := begin rcases p with ⟨⟨x, ⟨hx₁, _⟩⟩, ⟨y, ⟨hy₁, _⟩⟩⟩, simp [relpoint_of_gpoint, gpoint_of_relpoint, -sub_eq_add_neg], have : x - (bl g).y ≥ 0, by linarith, have : y - (bl g).x ≥ 0, by linarith, split; rw int.nat_abs_of_nonneg; try { simp }; assumption end lemma gpoint_relpoint_id {g : α} {p : relative_point g} : relpoint_of_gpoint (gpoint_of_relpoint p) = p := by cases p with x y; simp [gpoint_of_relpoint, relpoint_of_gpoint] def prod_of_rel_point {g : α} (rp : relative_point g) := (rp.x, rp.y) def prod_of_grid_point {g : α} (ap : grid_point g) := (ap.x, ap.y) def grid_point_of_prod {g : α} (p : bounded (bl g).x (gtr g).x × bounded (bl g).y (gtr g).y) : grid_point g := ⟨p.snd, p.fst⟩ def grid_point_of_prod' {g : α} (p : bounded (bl g).y (gtr g).y × bounded (bl g).x (gtr g).x) : grid_point g := ⟨p.fst, p.snd⟩ -- Cell of 'g' at ⟨x, y⟩ relative to origin. def abs_data (g : α) (gp : grid_point g) := let rp := relpoint_of_gpoint gp in (contents g) rp.x rp.y lemma try_lt_bly : (gbl g).y < (gtr g).y := (grid_bounded_iff.1 grid_is_bounding_box).2 private lemma bounded_establishes_bounds {a b : ℤ} (h : a < b) (x : bounded 0 ( |b - a| )) : a ≤ a + ↑x ∧ a + ↑x < b := have xpos : ↑x ≥ 0, from positive_bounded _, have xmax : ↑x < |b - a|, from bounded_lt _, ⟨ by apply le_add_of_nonneg_right; unfold coe, begin unfold_coes at *, rw add_comm, rw [← int.coe_nat_lt, int.nat_abs_of_nonneg, lt_sub_iff_add_lt] at xmax, exact xmax, { simp [ge_from_le], rw [ ← sub_eq_add_neg, ← add_le_add_iff_right a, zero_add, sub_add_cancel ], exact int.le_of_lt h, } end ⟩ end grid_lemmas end grids section grid_impls -- Vector-based grid concrete instance. structure vec_grid (α : Type) := (r : ℕ) (c : ℕ) (h : r * c > 0) (contents : vector α (r * c)) -- Absolute vector-based grid concrete instance. structure vec_grid₀ (α : Type) extends vec_grid α := (o : point) -- Absolute function-based grid concrete instance. structure fgrid₀ (α : Type) := (r : ℕ) (c : ℕ) (h : r * c > 0) (o : point) (contents : bounded o.y (o.y + r) → bounded o.x (o.x + c) → α) -- Absolute vector-based grid concrete instance with dependent size. structure dep_vec_grid (α : Type) (r : ℕ) (c : ℕ) := (h : r * c > 0) (contents : vector α (r * c)) end grid_impls section grid_instances open relative_grid grid lemma data_not_empty {α : Type} {g : vec_grid₀ α} : ¬empty_list g.contents.to_list := assume contra, begin simp [empty_list] at contra, have contra₁ := contra.symm, rw [list_empty_iff_len, vector.to_list_length] at contra₁, rcases g with ⟨⟨_, _, h,_⟩, _⟩, linarith end lemma linearize_array {x y r c : ℕ} (xb : x < c) (yb : y < r) : y * c + x < r * c := have h₁ : y * c < r * c, by apply mul_lt_mul yb; omega, have h₂ : ∃n, nat.succ y + n = r, from nat_le_dest yb, let ⟨n, h₂⟩ := h₂ in by rw [← h₂, right_distrib, nat.succ_mul, add_assoc]; linarith def rel_point_to_fin {α : Type} [grid α] {g : α} (p : relative_point g) : fin (size g) := ⟨p.x * cols g + p.y, linearize_array p.y.2 p.x.2⟩ def grid_point_to_fin {α : Type} [grid α] {g : α} (p : grid_point g) : fin (size g) := rel_point_to_fin (relpoint_of_gpoint p) lemma expand_grid_point_to_fin {α : Type} [grid α] {g : α} (p : grid_point g) : grid_point_to_fin p = ⟨|p.y.1 - (bl g).y| * cols g + |p.x.1 - (bl g).x|, linearize_array begin rcases p with ⟨_, ⟨y, ⟨_, yu⟩⟩⟩, simp only [tl], rw ← int.coe_nat_lt_coe_nat_iff, have : y - (grid.bl g).x ≥ 0, by rw [ge_from_le]; linarith, rw int.nat_abs_of_nonneg this, simp [expand_gtr] at yu, linarith end begin rcases p with ⟨⟨x, ⟨xl, xu⟩⟩, _⟩, simp only [tl], rw ← int.coe_nat_lt_coe_nat_iff, have : x - (bl g).y ≥ 0, by linarith, rw [int.nat_abs_of_nonneg this, rows_eq_try_sub_bly'], linarith end⟩ := by simp [grid_point_to_fin, relpoint_of_gpoint, rel_point_to_fin]; unfold_coes instance rg_vec_grid {α : Type} : relative_grid (vec_grid α) := { carrier := α, rows := λg, g.r, cols := λg, g.c, nonempty := λg, g.h, contents := λg y x, g.contents.nth ⟨ y.1 * g.c + x.1, linearize_array x.2 y.2 ⟩ } instance rg_vec_grid₀ {α : Type} : relative_grid (vec_grid₀ α) := { carrier := α, rows := λg, g.r, cols := λg, g.c, nonempty := λg, g.h, contents := λg y x, g.contents.nth ⟨ y.1 * g.c + x.1, linearize_array x.2 y.2 ⟩ } private lemma absolute_bounds {o : ℤ} {r : ℕ} (x : fin r) : o + ↑x < o + ↑r := by simp; cases x; unfold_coes; simpa instance rg_fgrid₀ {α : Type} : relative_grid (fgrid₀ α) := { carrier := α, rows := λg, g.r, cols := λg, g.c, nonempty := λg, g.h, contents := λg y x, g.contents ⟨g.o.y + y, ⟨by simp, absolute_bounds _⟩⟩ ⟨g.o.x + x, ⟨by simp, absolute_bounds _⟩⟩ } instance ag_vec_agrid₀ {α : Type} : grid (vec_grid₀ α) := { bl := λg, g.o } instance ag_fgrid₀ {α : Type} : grid (fgrid₀ α) := { bl := λg, g.o } instance rg_dep_fgrid₀ {α : Type} {r c : ℕ} : relative_grid (dep_vec_grid α r c) := { carrier := α, rows := λ_, r, cols := λ_, c, nonempty := λg, g.h, contents := λg y x, g.contents.nth ⟨ y.1 * c + x.1, linearize_array x.2 y.2 ⟩ } -- instance ag_dep_vec_grid₀ {α : Type} {r c : ℕ} : -- grid (dep_vec_grid₀ α r c) := { -- bl := λg, g.o -- } def point_of_grid_point {α : Type*} [grid α] {g : α} : grid_point g → point | ⟨b₁, b₂⟩ := ⟨b₂, b₁⟩ instance point_grid_point_coe {α : Type*} [grid α] (g : α) : has_coe (grid_point g) point := ⟨point_of_grid_point⟩ end grid_instances section finite_grid open list int function section spec open grid relative_grid variables {α : Type} {ag : vec_grid₀ α} {fg : fgrid₀ α} lemma coe_rows_pos_a : ↑ag.r > (0 : ℤ) := by change ag.r with (rows ag); simp [gt_from_lt, rows_pos] lemma coe_rows_pos_f : ↑fg.r > (0 : ℤ) := by change fg.r with (rows fg); simp [gt_from_lt, rows_pos] lemma coe_cols_pos_a : ↑ag.c > (0 : ℤ) := by change ag.c with (cols ag); simp [gt_from_lt, cols_pos] lemma coe_cols_pos_f : ↑fg.c > (0 : ℤ) := by change fg.c with (cols fg); simp [gt_from_lt, cols_pos] end spec variables {α : Type*} [grid α] (g : α) def grp (a b row : ℤ) : list point := map (uncurry point.mk) $ zip (range_pure a b) (repeat row ( |b - a| )) private lemma expand_grp {a b r} (h : a < b) : grp a b r = ⟨a, r⟩ :: grp (a + 1) b r := begin conv_lhs { simp only [grp] }, rw range_pure_next h, have : |b - a| ≥ 1, from nat_abs_ge_one_of_lt h, rw repeat_more this, simp [-sub_eq_add_neg], exact ⟨ by simp [uncurry], by simp [grp, -sub_eq_add_neg, abs_minus_plus h] ⟩ end private lemma expand_grp_g {g : α} : grp (gbl g).x (gtr g).x (gtr g).y = ⟨(gbl g).x, (gtr g).y⟩ :: grp ((gbl g).x + 1) (gtr g).x (gtr g).y := begin simp only [grp], have h : range_pure ((gbl g).x) ((gtr g).x) = (gbl g).x :: range_pure (((gbl g).x) + 1) ((gtr g).x), from range_pure_next (grid_bounded_iff.1 grid_is_bounding_box).1, rw h, have h₁ : repeat ((gtr g).y) ( |(gtr g).x - (gbl g).x| ) = (gtr g).y :: repeat (gtr g).y ( |(gtr g).x - (gbl g).x| - 1), { simp only [expand_gbl], apply repeat_more, rw ← cols_eq_trx_sub_blx, exact abs_cols_pos }, simp only [map, h₁, zip_cons_cons], exact ⟨ by simp [uncurry], by rw abs_minus_plus; exact (grid_bounded_iff.1 grid_is_bounding_box).1 ⟩ end private lemma grp_empty_iff {a b r} : empty_list (grp a b r) ↔ b ≤ a := ⟨ assume h, begin by_cases contra : a < b, {rw expand_grp at h, cases h, exact contra}, {exact le_of_not_lt contra} end, assume h, begin unfold grp, have : range_pure a b = [], by unfold1 range_pure; exact if_neg (not_lt_of_le h), simp [zip_nil_left, empty_list, this] end ⟩ open function private lemma grp_bounds {a b row : ℤ} : ∀{c : point}, c ∈ grp a b row → is_bounded a b c.x ∧ is_bounded row (row + 1) c.y := assume c h, begin simp [grp] at h, rcases h with ⟨a₁, ⟨b₁, ⟨h₂, h₃⟩⟩⟩, have h₄ : a₁ ∈ range_pure a b, from pair_in_zip_l h₂, have h₅ : b₁ ∈ repeat row ( |b + -a| ), from pair_in_zip_r h₂, rw ← h₃, split; split, {exact (range_pure_bounded h₄).1}, {exact (range_pure_bounded h₄).2}, {simp [repeat_bounded h₅, uncurry]}, {rw (repeat_bounded h₅), exact lt_add_succ _ _} end lemma length_grp {a b : ℤ} (h : a < b) {x : ℤ} : length (grp a b x) = |b - a| := have h₁ : length (range_pure a b) = |b - a|, from range_length_pure (int.le_of_lt h), by simp [grp, length_map, length_zip_left, length_repeat, h₁] def gip (p₁ p₂ : point) : list point := join (map (grp p₁.x p₂.x) (range_pure p₁.y p₂.y)) open relative_grid grid def gip_g {α : Type*} [grid α] (g : α) := gip (bl g) (gtr g) private lemma expand_gip {p₁ p₂} (h : p₁ ↗ p₂) : gip p₁ p₂ = ⟨p₁.x, p₁.y⟩ :: grp (p₁.x + 1) p₂.x p₁.y ++ gip ⟨p₁.x, p₁.y + 1⟩ p₂ := by simp [ gip, expand_grp (grid_bounded_iff.1 h).1, range_pure_next (grid_bounded_iff.1 h).2 ] private lemma expand_row_gip {p₁ p₂} (h : p₁ ↗ p₂) : gip p₁ p₂ = grp p₁.x p₂.x p₁.y ++ gip ⟨p₁.x, p₁.y + 1⟩ p₂ := by simp [gip, range_pure_next (grid_bounded_iff.1 h).2] private lemma expand_gip_g : (gip_g g) = grp (gbl g).x (gtr g).x (gbl g).y ++ gip ⟨(gbl g).x, (gbl g).y + 1⟩ ⟨(gtr g).x, ((gtr g).y)⟩ := begin generalize h : gip ⟨(gbl g).x, (gbl g).y⟩ ⟨(gtr g).x, ((gtr g).y + 1)⟩ = t, simp only [gip_g, gip], rw range_pure_next, dsimp, {apply congr_arg, simp [h.symm, gip]}, {exact try_lt_bly} end def is_in_grid' (xy : point) := is_bounded (gbl g).y (gtr g).y xy.y ∧ is_bounded (gbl g).x (gtr g).x xy.x def is_in_grid (bb : bounding_box) (xy : point) := is_bounded bb.p₁.y bb.p₂.y xy.y ∧ is_bounded bb.p₁.x bb.p₂.x xy.x attribute [reducible] instance has_mem_grid : has_mem point α := ⟨flip is_in_grid'⟩ attribute [reducible] instance has_mem_bb : has_mem point bounding_box := ⟨flip is_in_grid⟩ lemma gip_in_grid {p₁ p₂ : point} {h : p₁ ↗ p₂} : ∀{a}, a ∈ gip p₁ p₂ → a ∈ (⟨p₁, p₂, h⟩ : bounding_box) := assume a h, begin simp [gip] at h, cases a with al ar, rcases h with ⟨l, ⟨⟨a₁, ⟨h₂, h₃⟩⟩, h₁⟩⟩, have h₄ := range_pure_bounded h₂, rw ← h₃ at h₁, have h₅ := grp_bounds h₁, split; split, { simp [bounding_box.p₁], rcases h₅ with ⟨⟨h₅l₁, h₅l₂⟩, ⟨h₅r₁, h₅r₂⟩⟩, cases h₄, transitivity a₁; assumption }, {exact lt_of_le_of_lt (le_of_lt_add_one h₅.2.2) h₄.2}, {exact h₅.1.1}, {exact h₅.1.2} end lemma gip_g_in_grid {g : α} : ∀{a}, a ∈ gip_g g → a ∈ (bbox_of_grid g) := assume a h, gip_in_grid h private def make_bounded_idx {g : α} {p : point} (h : p ∈ (bbox_of_grid g)) : bounded (bl g).x (gtr g).x × bounded (gbl g).y (gtr g).y := (make_bounded h.2, make_bounded h.1) private def make_bounded_indices (is : list point) (h : ∀p, p ∈ is → p ∈ (bbox_of_grid g)) : list ( bounded (bl g).x (gtr g).x × bounded (gbl g).y (gtr g).y ) := map (λp : {x // x ∈ is}, (⟨p.1.1, (h p.1 p.2).2⟩, ⟨p.1.2, (h p.1 p.2).1⟩)) (attach is) instance decidable_is_in_grid' {xy : point} : decidable (is_in_grid' g xy) := by simp [is_in_grid']; apply_instance instance decidable_is_in_grid (bb : bounding_box) {xy : point} : decidable (is_in_grid bb xy) := by simp [is_in_grid]; apply_instance instance decidable_is_in_grid'_op {xy : point} : decidable (xy ∈ g) := by simp [(∈), is_in_grid', flip]; apply_instance instance decidable_is_in_grid_op (bb : bounding_box) {xy : point} : decidable (xy ∈ bb) := by simp [is_in_grid, (∈), flip]; apply_instance private def inject_into_bounded (p : {x // x ∈ gip_g g}) : bounded (bl g).x (gtr g).x × bounded (gbl g).y (gtr g).y := make_bounded_idx (gip_g_in_grid p.2) private def inject_row_into_bounded {a b r} (p : {x // x ∈ grp a b r}) : bounded a b × bounded r (r + 1) := ⟨⟨p.1.1, (grp_bounds p.2).1⟩, ⟨p.1.2, (grp_bounds p.2).2⟩⟩ private lemma blgx_trgx_of_mem {g : α} {x} {y} (h : point.mk x y ∈ g) : (bl g).x < (gtr g).x := by simp only [(∈), flip, is_in_grid'] at h; exact lt_of_le_of_lt h.2.1 h.2.2 theorem in_gip_g_of_in_g {α : Type*} [grid α] {g : α} {p} (h : p ∈ g) : p ∈ gip_g g := begin cases p with x y, simp [-gtr, gip_g, gip], have h₂ : y ∈ range_pure (gbl g).y (gtr g).y, by simp [(∈), flip, is_in_grid'] at h; exact in_range_iff.2 h.1, split, { split, {use y, exact ⟨h₂, by simp [grp]⟩}, { generalize h₂ : range_pure ((bl g).x) ((gtr g).x) = l₁, generalize h₃ : repeat y ( |(gtr g).x - (bl g).x| ) = l₂, rw point_in_zip_prod_iff, apply point_in_zip_repeat_right _ h₃ _, { simp [ h₂.symm, h₃.symm, range_length_pure, length_repeat, int.le_of_lt (blgx_trgx_of_mem h) ] }, { rw [← h₂, in_range_iff], simp only [(∈), flip, is_in_grid'] at h, exact h.2 } } } end theorem in_grid_iff_in_gip_g {p} {g : α} : p ∈ g ↔ p ∈ gip_g g := ⟨ in_gip_g_of_in_g, λh, by apply gip_in_grid h; exact grid_is_bounding_box ⟩ private def grid_point_of_mem {p} (h : p ∈ g) : grid_point g := ⟨make_bounded h.1, make_bounded h.2⟩ def generate := map (abs_data g ∘ grid_point_of_prod ∘ inject_into_bounded g) (attach $ gip_g g) notation `℘` g:max := generate g section grid_instances instance vec_grid_functor : functor vec_grid := { map := λα β f g, {g with contents := vector.map f g.contents} } instance vec_grid_functor_law : is_lawful_functor vec_grid := { id_map := λα ⟨r, c, h, d⟩, by simp [(<$>)], comp_map := λα β γ f h ⟨r, c, h, d⟩, by simp [(<$>)] } instance vec_grid₀_functor : functor vec_grid₀ := { map := λα β f g, {g with contents := vector.map f g.contents} } instance vec_grid₀_functor_law : is_lawful_functor vec_grid₀ := { id_map := λα ⟨⟨r, c, h, d⟩, o⟩, by simp [(<$>)], comp_map := λα β γ f h ⟨⟨r, c, h, d⟩, o⟩, by simp [(<$>)] } instance fgrid₀_functor : functor fgrid₀ := { map := λα β f g, {g with contents := λx y, f (g.contents x y)} } instance fgrid₀_functor_law : is_lawful_functor fgrid₀ := { id_map := λα ⟨r, c, h, d, o⟩, by simp [(<$>)], comp_map := λα β γ f h ⟨r, c, h, d, o⟩, by simp [(<$>)] } instance dep_vec_grid₀_functor {m n} : functor (λt, dep_vec_grid t m n) := { map := λα β f g, {g with contents := vector.map f g.contents} } instance dep_vec_grid₀_functor_law {m n} : is_lawful_functor (λt, dep_vec_grid t m n) := { id_map := λα ⟨r, c, h⟩, by simp [(<$>)], comp_map := λα β γ f h ⟨r, c, h⟩, by simp [(<$>)] } end grid_instances attribute [simp] lemma vec_grid_fmap_r {α β : Type} {g : vec_grid α} {f : α → β} : (f <$> g).r = g.r := by simp [(<$>)] attribute [simp] lemma vec_grid_fmap_c {α β : Type} {g : vec_grid α} {f : α → β} : (f <$> g).c = g.c := by simp [(<$>)] attribute [simp] lemma vec_grid₀_fmap_r {α β : Type} {g : vec_grid₀ α} {f : α → β} : (f <$> g).r = g.r := by simp [(<$>)] attribute [simp] lemma vec_grid₀_fmap_c {α β : Type} {g : vec_grid₀ α} {f : α → β} : (f <$> g).c = g.c := by simp [(<$>)] attribute [simp] lemma fgrid₀_fmap_r {α β : Type} {g : fgrid₀ α} {f : α → β} : (f <$> g).r = g.r := by simp [(<$>)] attribute [simp] lemma fgrid₀_fmap_c {α β : Type} {g : fgrid₀ α} {f : α → β} : (f <$> g).c = g.c := by simp [(<$>)] def point_of_bounded_prod {a b c d : ℤ} : bounded a b × bounded c d → point | ⟨⟨a, _⟩, ⟨c, _⟩⟩ := ⟨a, c⟩ lemma gip_g_nonempty : ¬empty_list (gip_g g) := assume contra, begin simp [gip_g, gip] at contra, have c₁ : ¬empty_list ( range_pure (bl g).y (gtr g).y ), { simp only [empty_list], intros c₂, symmetry' at c₂, rw range_pure_empty_iff at c₂, have c₃ := @grid_is_bounding_box _ _ g, rw grid_bounded_iff at c₃, exact absurd (lt_of_le_of_lt c₂ c₃.2) (lt_irrefl _) }, have c₂ := @not_map_empty_of_not_empty _ _ _ (grp (bl g).x (tr (bl g) (rows g) (cols g)).x) c₁, have c₃ := not_join_empty_of_not_empty contra, cases c₃, {contradiction}, { revert c₃ contra c₂ c₁, generalize c₆ : bl g = bl, generalize c₅ : tr bl (rows g) (cols g) = tr', generalize c₄ : map (grp bl.x tr'.x) (range_pure bl.y (gtr g).y) = l, let h₃ := @grid_is_bounding_box _ _ g, rw grid_bounded_iff at h₃, simp [gtr, c₆, c₅] at h₃, intros, have c₅ : ∃z ∈ l, ¬empty_list z, { let h := grp bl.x tr'.x bl.y, have h₁ : h = grp bl.x tr'.x bl.y, by cc, use h, split, { rw h₁, revert c₄, generalize h₂ : range_pure bl.y tr'.y = l₁, intros, cases l₁ with w ws, { rw range_pure_empty_iff at h₂, exact absurd (lt_of_le_of_lt h₂ h₃.2) (lt_irrefl _) }, { have h₄ : w = bl.y, by unfold1 range_pure at h₂; rw if_pos h₃.2 at h₂; injection h₂ with h₃ _; rw h₃, have : bl.y < (gtr g).y, by subst c₅; simp [gtr, c₆]; exact h₃.2, simp [c₄.symm, range_pure_next this] }, }, { unfold1 grp at h₁, have h₂ : tr'.x > bl.x, from h₃.1, have h₄ : range_pure (bl.x) (tr'.x) = bl.x :: range_pure (bl.x + 1) (tr'.x), from range_pure_next h₂, rw h₄ at h₁, have : |tr'.x - bl.x| ≥ 1, begin apply nat.succ_le_of_lt (lt_of_coe_nat_lt_coe_nat _), rw [nat_abs_of_nonneg, lt_sub], simpa, linarith end, have h₅ : repeat bl.y ( |tr'.x - bl.x| ) = bl.y :: repeat bl.y (( |tr'.x - bl.x| ) - 1), from repeat_more this, rw [h₅, zip_cons_cons, map_cons] at h₁, rw h₁, apply not_empty_cons } }, rcases c₅ with ⟨c₅l, ⟨c₅₁, c₅₂⟩⟩, rw [← c₄, ← c₅] at c₅₁, simp only [gtr] at c₃, subst c₆, exact absurd (c₃ c₅l c₅₁) c₅₂ } end lemma length_gip {p₁ p₂ : point} (h : p₁ ↗ p₂) : length (gip p₁ p₂) = |p₂.y - p₁.y| * |p₂.x - p₁.x| := begin rw [← int.coe_nat_eq_coe_nat_iff, ← nat_abs_mul], rw grid_bounded_iff at h, have h₁ : (p₂.y - p₁.y) * (p₂.x - p₁.x) > 0, {cases p₁, cases p₂, apply mul_pos; omega}, simp [ -sub_eq_add_neg, gip, length_join, (∘), length_grp h.1, range_length_pure (int.le_of_lt h.2), nat_abs_of_nonneg (int.le_of_lt h₁) ], repeat {rw nat_abs_of_nonneg}; simp [-sub_eq_add_neg, ge_from_le]; apply int.le_of_lt; simp [h.1, h.2] end theorem length_gip_g : length (gip_g g) = rows g * cols g := by simp [ gip_g, length_gip, rows_eq_try_sub_bly, cols_eq_trx_sub_blx, grid_is_bounding_box ] private theorem length_generate {α : Type*} [grid α] (g : α) : length (℘ g) = grid_rows g * grid_cols g := by unfold generate gip_g; rw [ length_map, grid_rows_eq_try_sub_bly, grid_cols_eq_trx_sub_blx, length_attach, length_gip_g, rows_eq_try_sub_bly, cols_eq_trx_sub_blx ] lemma length_generate_eq_size : length (℘ g) = size g := by simp [size, length_generate] lemma map_generate_map_v₀ {α β : Type} {g : vec_grid₀ α} {f : α → β} : f <$> (℘ g) = ℘ (f <$> g) := by simpa [(<$>), generate, abs_data, contents, vector.nth_map, (∘)] lemma map_generate_map_f₀ {α β : Type} (g : fgrid₀ α) {f : α → β} : f <$> (℘ g) = ℘ (f <$> g) := by simpa [(<$>), generate, abs_data, contents] lemma dec_grid_len_eq_indices_len : length (℘ g) = length (gip_g g) := by simp [length_generate, length_gip_g] def vec_grid₀_of_fgrid₀ {α : Type} (g : fgrid₀ α) : vec_grid₀ α := {g with contents := ⟨℘ g, length_generate_eq_size _⟩} def fgrid₀_of_vec_grid₀ {α : Type} (g : vec_grid₀ α) : fgrid₀ α := {g with contents := λx y, abs_data g ⟨x, y⟩} def dep_vec_grid₀_of_fgrid₀ {α : Type} (g : fgrid₀ α) : dep_vec_grid α g.r g.c := {g with contents := ⟨℘ g, length_generate_eq_size _⟩} def vec_grid_of_dep_vec_grid {m n} {α : Type} (g : dep_vec_grid α m n) : vec_grid₀ α := ⟨⟨m, n, g.1, g.2⟩, ⟨0, 0⟩⟩ instance f₀_v₀_coe {α : Type} : has_coe (fgrid₀ α) (vec_grid₀ α) := ⟨vec_grid₀_of_fgrid₀⟩ instance v₀_f₀_coe {α : Type} : has_coe (vec_grid₀ α) (fgrid₀ α) := ⟨fgrid₀_of_vec_grid₀⟩ attribute [simp] lemma vec_grid₀_of_fgrid₀_r {α : Type} {g : fgrid₀ α} : (vec_grid₀_of_fgrid₀ g).r = g.r := by simp [vec_grid₀_of_fgrid₀] attribute [simp] lemma vec_grid₀_of_fgrid₀_c {α : Type} {g : fgrid₀ α} : (vec_grid₀_of_fgrid₀ g).c = g.c := by simp [vec_grid₀_of_fgrid₀] attribute [simp] lemma vec_grid₀_of_fgrid₀_o {α : Type} {g : fgrid₀ α} : (vec_grid₀_of_fgrid₀ g).o = g.o := by simp [vec_grid₀_of_fgrid₀] attribute [simp] lemma fgrid₀_of_vec_grid₀_r {α : Type} {g : vec_grid₀ α} : (fgrid₀_of_vec_grid₀ g).r = g.r := by simp [fgrid₀_of_vec_grid₀] attribute [simp] lemma fgrid₀_of_vec_grid₀_c {α : Type} {g : vec_grid₀ α} : (fgrid₀_of_vec_grid₀ g).c = g.c := by simp [fgrid₀_of_vec_grid₀] attribute [simp] lemma fgrid₀_of_vec_grid₀_o {α : Type} {g : vec_grid₀ α} : (fgrid₀_of_vec_grid₀ g).o = g.o := by simp [fgrid₀_of_vec_grid₀] attribute [simp] lemma vec_grid₀_of_fgrid₀_gtr {α : Type} {g : fgrid₀ α} : gtr (vec_grid₀_of_fgrid₀ g) = gtr g := by simp [expand_gtr, bl, cols, rows, vec_grid₀_of_fgrid₀] attribute [simp] lemma fgrid₀_of_vec_grid₀_gtr {α : Type} {g : vec_grid₀ α} : gtr (fgrid₀_of_vec_grid₀ g) = gtr g := by simp [expand_gtr, bl, cols, rows, fgrid₀_of_vec_grid₀] private theorem nth_le_grp {n} {a b r : ℤ} (h : a < b) (H) : nth_le (grp a b r) n H = ⟨a + n, r⟩ := begin rw ← option.some_inj, rw ← nth_le_nth H, induction n with n ih generalizing a b, {simp [expand_grp h]}, { simp [expand_grp h], have : a + 1 < b, begin have : a + 1 ≠ b, assume contra, by simp [contra.symm, @length_grp a (a + 1) (by cc)] at H; clear contra h ih; omega, by_contradiction h₁, replace h₁ := le_of_not_lt h₁, rw le_iff_eq_or_lt at h₁, cases h₁; try { cc }, have : a = b, by linarith, rw [this, length_grp] at H, simp at H, cases H, linarith end, have lenok : n < length (grp (a + 1) b r), begin rw length_grp this, rw length_grp h at H, have eq₁ : b - (a + 1) ≥ 0, by linarith, have eq₂ : b - a ≥ 0, by linarith, rw [← int.coe_nat_lt_coe_nat_iff, int.nat_abs_of_nonneg eq₁], rw [← int.coe_nat_lt_coe_nat_iff, int.nat_abs_of_nonneg eq₂] at H, simp, simp at H, linarith end, specialize @ih (a + 1) b this lenok, simp [ih] } end theorem nth_grp {n} {a b r : ℤ} (h : a < b) (H : n < length (grp a b r)) : nth (grp a b r) n = some ⟨a + n, r⟩ := by rw nth_le_nth H; exact congr_arg _ (nth_le_grp h _) theorem nth_le_gip {n} {p₁ p₂ : point} (h : p₁ ↗ p₂) (H) : nth_le (gip p₁ p₂) n H = ⟨p₁.x + n % |p₂.x - p₁.x|, p₁.y + n / |p₂.x - p₁.x|⟩ := begin cases p₁ with x₁ y₁, cases p₂ with x₂ y₂, have x₁x₂ : x₁ < x₂, from (grid_bounded_iff.1 h).1, have y₁y₂ : y₁ < y₂, from (grid_bounded_iff.1 h).2, rw [← option.some_inj, ← nth_le_nth H], rw length_gip h at H, repeat { rw nat_abs_of_nonneg (nonneg_of_lt x₁x₂) }, simp [-sub_eq_add_neg] at *, have : y₂ = y₁ + (y₂ - y₁), by linarith, rw this, clear this, have : y₂ - y₁ = ↑|y₂ - y₁|, by rw nat_abs_of_nonneg; exact nonneg_of_lt y₁y₂, rw this, clear this, generalize hrows : |y₂ - y₁| = rows, rw hrows at H, induction rows with rows ih generalizing y₁ y₂ n, {exfalso, simp at H, cases H}, { rw expand_row_gip _, { by_cases h₁ : n < |x₂ - x₁|, { simp [-sub_eq_add_neg], rw [nth_split, nth_grp]; try {simpa [length_grp x₁x₂]}, congr' 2; rw [ ← int.coe_nat_lt_coe_nat_iff, nat_abs_of_nonneg (nonneg_of_lt x₁x₂) ] at h₁, rw mod_eq_of_lt (coe_zero_le _) h₁, rw div_eq_zero_of_lt (coe_zero_le _) h₁, simp }, { generalize hcols : x₂ - x₁ = cols, have rowsnezero : rows ≠ 0, assume contra, by simp [contra, -sub_eq_add_neg] at H; contradiction, have colsnezero : cols ≠ 0, by linarith, have x₂x₁n : |x₂ - x₁| ≤ n, from not_lt.1 h₁, have lenok : ¬n < length (grp x₁ x₂ y₁), by simpa [length_grp x₁x₂, -sub_eq_add_neg], simp [-sub_eq_add_neg], rw nth_split_second lenok, by_cases h₂ : y₁ + 1 < y₂, { have h₃ : {x := x₁, y := y₁ + 1}↗{x := x₂, y := y₂}, from ⟨x₁x₂, h₂⟩, have lenok : n - length (grp x₁ x₂ y₁) < rows * |x₂ - x₁|, { rw nat.succ_mul at H, rw [ length_grp x₁x₂, ← int.coe_nat_lt_coe_nat_iff, int.coe_nat_sub x₂x₁n, int.coe_nat_mul, sub_lt_iff_lt_add, ← int.coe_nat_mul, ← int.coe_nat_add ], rwa int.coe_nat_lt_coe_nat_iff }, have rowsok : |y₂ - (y₁ + 1)| = rows, by rw [← abs_minus_plus y₁y₂, hrows, nat.succ_sub_one], rw [ ← add_assoc, @ih (y₁ + 1) y₂ (n - length (grp x₁ x₂ y₁)) h₃ h₂ rowsok lenok, length_grp x₁x₂ ], simp [-sub_eq_add_neg], exact ⟨ begin rw [ int.coe_nat_sub x₂x₁n, nat_abs_of_nonneg, ← hcols, mod_eq_mod_iff_mod_sub_eq_zero, mod_eq_zero_of_dvd ], simp, rw ← dvd_neg, simp, exact nonneg_of_lt x₁x₂ end, begin rw [ int.coe_nat_sub x₂x₁n, nat_abs_of_nonneg (nonneg_of_lt x₁x₂), hcols ], simp, have : -cols = cols * (-1 : ℤ), by simp, rw this, rw int.add_mul_div_left _ _ colsnezero, simp end ⟩ }, { have h₃ : y₁ + 1 = y₂, by linarith, have h₄ : |y₂ - y₁| = 1, by simp [h₃.symm, add_sub_cancel'], rw h₄ at hrows, injection hrows with contra, cc } } }, { exact ⟨ (grid_bounded_iff.1 h).1, begin simp [ sub_lt_iff_lt_add, lt_add_iff_pos_right, -sub_eq_add_neg ], exact nat.cases_on rows zero_lt_one (λ_, lt_trans zero_lt_one (lt_add_succ _ _)), end ⟩ } } end theorem nth_le_gip_g {n} (H) : nth_le (gip_g g) n H = ⟨(bl g).x + n % cols g, (bl g).y + n / cols g⟩ := begin rw cols_eq_trx_sub_blx, exact @nth_le_gip n (gbl g) (gtr g) grid_is_bounding_box H end theorem nth_generate {n} (H) : nth_le (℘ g) n H = abs_data g ⟨ ⟨(bl g).y + n / cols g, ⟨ by simp, idx_div_cols_bounded (by rwa length_generate_eq_size at H) ⟩⟩, ⟨(bl g).x + n % cols g, ⟨ by simp, idx_mod_cols_bounded⟩ ⟩⟩ := begin rw length_generate at H, rw [← option.some_inj, ← nth_le_nth], simp only [ abs_data, (∘), relpoint_of_gpoint, prod_of_rel_point, expand_gtr, generate, nth_map ], have : n < length (attach (gip_g g)), by simpa [length_attach, length_gip_g], simp [ nth_le_nth this, inject_into_bounded, make_bounded_idx, make_bounded, nth_le_gip_g, grid_point_of_prod, data_option ] end theorem nth_generate' {n} (h : n < length ℘ g) : nth (℘ g) n = some (abs_data g ⟨ ⟨(bl g).y + n / cols g, ⟨ by simp, idx_div_cols_bounded (by rwa length_generate_eq_size at h) ⟩⟩, ⟨(bl g).x + n % cols g, ⟨ by simp, idx_mod_cols_bounded⟩ ⟩⟩) := by simp [nth_le_nth h, congr_arg, nth_generate] lemma abs_data_eq_nth_v₀ {α : Type} {g : vec_grid₀ α} {p} : abs_data g p = vector.nth g.contents (grid_point_to_fin p) := by simpa [ abs_data, (∘), relpoint_of_gpoint, prod_of_rel_point, contents, grid_point_to_fin, rel_point_to_fin ] lemma abs_data_eq_nth_v₀' {α : Type} {g : vec_grid₀ α} {p} : abs_data g p = vector.nth g.contents ⟨|p.y.1 - g.o.y| * g.c + |p.x.1 - g.o.x|, begin rcases p with ⟨⟨x, ⟨xl, xu⟩⟩, ⟨y, ⟨yl, yu⟩⟩⟩, simp [-sub_eq_add_neg], simp [-sub_eq_add_neg, expand_gtr, bl, rows, cols] at *, rw add_comm, have eq₁ : |y - g.o.x| < g.c, { have : y - (g.o).x ≥ 0, by linarith, rw [← int.coe_nat_lt_coe_nat_iff, int.nat_abs_of_nonneg this], linarith }, have eq₂ : |x - g.o.y| < g.r, { have : x - g.o.y ≥ 0, by linarith, rw [← int.coe_nat_lt_coe_nat_iff, int.nat_abs_of_nonneg this], linarith }, exact linearize_array eq₁ eq₂ end⟩ := by simp [ abs_data, (∘), relpoint_of_gpoint, prod_of_rel_point, contents, grid_point_to_fin, rel_point_to_fin, bl, rows, cols ] lemma abs_data_eq_nth_f₀ {α : Type} {g : fgrid₀ α} {p} : abs_data g p = g.contents p.y p.x := begin rcases p with ⟨⟨x, ⟨xl, xu⟩⟩, ⟨y, ⟨yl, yu⟩⟩⟩, simp only [ abs_data, (∘), relpoint_of_gpoint, prod_of_rel_point, contents ], unfold_coes, simp only [fin.val, of_nat_eq_coe], have h₁ : x - (bl g).y ≥ 0, by linarith, have h₂ : y - (bl g).x ≥ 0, by linarith, congr; rw int.nat_abs_of_nonneg; try { assumption }; simp only [bl]; linarith end lemma some_nth_le_generate_v₀ {α : Type} {g : vec_grid₀ α} {n} (H) : some (nth_le (℘ g) n H) = nth g.contents.to_list ( |↑n % ↑g.c| + |↑n / ↑g.c| * g.c ) := begin rcases g with ⟨⟨r, c, h, ⟨d, hd⟩⟩, o⟩, rw [nth_le_nth, nth_generate], simp [abs_data_eq_nth_v₀', expand_gtr, bl, rows, cols, vector.nth, hd], rw mod_add_div_coe, simp [length_generate, rows, cols] at H, simp [H], simpa [hd] end lemma nth_generate_v₀ {α : Type} {g : vec_grid₀ α} {n} (H : n < length ℘ g): nth (℘ g) n = nth g.contents.to_list ( |↑n % ↑g.c| + |↑n / ↑g.c| * g.c) := by simp [nth_le_nth, some_nth_le_generate_v₀, H] private lemma goy_add_n_div_c_lt_goy_add_r {α : Type} {g : fgrid₀ α} {n : ℕ} (h : n < length ℘ g) : g.o.y + ↑n / ↑g.c < g.o.y + ↑g.r := begin simp [-sub_eq_add_neg], norm_cast, rw [length_generate, nat.mul_comm] at h, exact nat.div_lt_of_lt_mul h end lemma some_nth_le_generate_f₀ {α : Type} {g : fgrid₀ α} {n} (H) : some (nth_le (℘ g) n H) = g.contents ⟨g.o.y + ↑n / ↑g.c, ⟨by simp, goy_add_n_div_c_lt_goy_add_r H⟩⟩ ⟨g.o.x + ↑n % ↑g.c, ⟨by simp, by simp; exact mod_lt_of_pos _ coe_cols_pos_f⟩⟩ := by simpa [nth_generate, abs_data_eq_nth_f₀, expand_gtr] lemma nth_generate_f₀ {α : Type} {g : fgrid₀ α} {n} (H : n < length ℘ g) : nth (℘ g) n = g.contents ⟨g.o.y + ↑n / ↑g.c, ⟨by simp, goy_add_n_div_c_lt_goy_add_r H⟩⟩ ⟨g.o.x + ↑n % ↑g.c, ⟨by simp, by simp; exact mod_lt_of_pos _ coe_cols_pos_f⟩⟩ := by simp [nth_le_nth H, some_nth_le_generate_f₀] lemma nth_le_generate_f₀ {α : Type} {g : fgrid₀ α} {n} (H) : nth_le (℘ g) n H = g.contents ⟨g.o.y + ↑n / ↑g.c, ⟨by simp, goy_add_n_div_c_lt_goy_add_r H⟩⟩ ⟨g.o.x + ↑n % ↑g.c, ⟨by simp, by simp; exact mod_lt_of_pos _ coe_cols_pos_f⟩⟩ := by simpa [nth_generate, abs_data_eq_nth_f₀, expand_gtr] lemma generate_eq_data {α : Type} (g : vec_grid₀ α) : ℘ g = g.contents.to_list := begin have h₁ : length (℘ g) = rows g * cols g, from length_generate _, have h₂ : length (g.contents.to_list) = rows g * cols g, by simp [rows, cols], apply ext_le (eq.trans h₁ h₂.symm) (λi hi₁ hi₂, _), rw h₁ at hi₁, rw h₂ at hi₂, have : hi₁ = hi₂, from rfl, subst this, dedup, rw ← option.some_inj, repeat { rw ← nth_le_nth }, rename hi₁_1 hi, rcases g with ⟨⟨r, c, h, ⟨contents, hd⟩⟩, o⟩, simp [-sub_eq_add_neg, rows, cols] at *, rw [nth_le_nth (by simpa [length_generate_eq_sizes]), some_nth_le_generate_v₀], rw nth_le_nth hi₂, simp, have : |↑i % ↑c| + |↑i / ↑c| * c = i, from mod_add_div_coe, repeat { rw ← nth_le_nth }, simp [this] end private theorem generate_inj_v₀_v₀ {α : Type} {g₁ g₂ : vec_grid₀ α} (hrows : g₁.r = g₂.r) (hcols : g₁.c = g₂.c) (horig : g₁.o = g₂.o) (h : ℘ g₁ = ℘ g₂) : g₁ = g₂ := begin repeat { rw generate_eq_data at h }, rcases g₁ with ⟨⟨g₁r, g₁c, g₁h, g₁d⟩, g₁o⟩, rcases g₂ with ⟨⟨g₂r, g₂c, g₂h, g₂d⟩, g₂o⟩, dsimp at hrows hcols horig h, substs hrows hcols horig, congr, exact vector.to_list_inj h end theorem grid_eq_iff_v₀_v₀ {α : Type} {g₁ g₂ : vec_grid₀ α} (hrows : g₁.r = g₂.r) (hcols : g₁.c = g₂.c) (horig : g₁.o = g₂.o) : g₁ = g₂ ↔ ℘ g₁ = ℘ g₂ := ⟨λh, h ▸ rfl, generate_inj_v₀_v₀ hrows hcols horig⟩ private theorem generate_inj_f₀_f₀ {α : Type} {g₁ g₂ : fgrid₀ α} (hrows : g₁.r = g₂.r) (hcols : g₁.c = g₂.c) (horig : g₁.o = g₂.o) (h : ℘ g₁ = ℘ g₂) : g₁ = g₂ := begin have hl₁ : length (℘ g₁) = g₁.r * g₁.c, from length_generate _, have hl₂ : length (℘ g₂) = g₂.r * g₂.c, from length_generate _, cases g₁ with g₁r g₁c g₁h g₁o g₁d, cases g₂ with g₂r g₂c g₂h g₂o g₂d, dsimp at hrows hcols horig hl₁ hl₂, subst hrows, subst hcols, subst horig, congr, ext x y, rcases x with ⟨x, ⟨xl, xu⟩⟩, rcases y with ⟨y, ⟨yl, yu⟩⟩, have rowsnezero : g₁r ≠ 0, assume contra, by simp [contra] at g₁h; exact absurd g₁h (lt_irrefl _), have colsnezero : g₁c ≠ 0, assume contra, by simp [contra] at g₂h; exact absurd g₂h (lt_irrefl _), let i := |x - g₁o.y| * g₁c + |y - g₁o.x|, have hi : i = |x - g₁o.y| * g₁c + |y - g₁o.x|, refl, have r_nonneg : x - g₁o.y ≥ 0, by simp only [ge_from_le, le_sub_iff_add_le, zero_add]; exact xl, have c_nonneg : y - g₁o.x ≥ 0, by simp only [ge_from_le, le_sub_iff_add_le, zero_add]; exact yl, have i_nonneg : 0 ≤ i, by linarith, have i_bounded : i < g₁r * g₁c, { have yb : y - g₁o.x < ↑g₁c, from sub_lt_iff_lt_add'.2 yu, have xb : x - g₁o.y < ↑g₁r, from sub_lt_iff_lt_add'.2 xu, rw hi, apply linearize_array; try { rw ← int.coe_nat_lt_coe_nat_iff }; rw nat_abs_of_nonneg; try { assumption } }, have h₁ : ∀hh, list.nth_le (℘ ( {r := g₁r, c := g₁c, h := g₁h, o := g₁o, contents := g₁d} : fgrid₀ α )) i hh = list.nth_le (℘ ( {r := g₁r, c := g₁c, h := g₂h, o := g₁o, contents := g₂d} : fgrid₀ α )) i (hl₂.symm ▸ i_bounded), { rw h, intro, refl }, specialize h₁ (hl₁.symm ▸ i_bounded), simp [-sub_eq_add_neg, nth_le_generate_f₀] at h₁, have : g₁o.y + (↑|y - g₁o.x| + ↑|x - g₁o.y| * ↑g₁c) / ↑g₁c = x, { repeat { rw nat_abs_of_nonneg; try { assumption } }, rw @int.add_mul_div_right _ _ ↑g₁c (by simp [colsnezero]), rw div_eq_zero_of_lt c_nonneg (sub_lt_iff_lt_add'.2 yu), simp }, simp only [this] at h₁, have : g₁o.x + ↑|y - g₁o.x| % ↑g₁c = y, { repeat { rw nat_abs_of_nonneg; try { assumption } }, rw mod_eq_of_lt c_nonneg (sub_lt_iff_lt_add'.2 yu), simp }, simp only [this] at h₁, exact h₁ end theorem grid_eq_iff_f₀_f₀ {α : Type} {g₁ g₂ : fgrid₀ α} (hrows : g₁.r = g₂.r) (hcols : g₁.c = g₂.c) (horig : g₁.o = g₂.o) : g₁ = g₂ ↔ ℘ g₁ = ℘ g₂ := ⟨λh, h ▸ rfl, generate_inj_f₀_f₀ hrows hcols horig⟩ def row (n : fin (rows g)) : (fin (cols g)) → carrier α := contents g n def col (n : fin (cols g)) : (fin (rows g)) → carrier α := flip (contents g) n def top := row g ⟨ 0, and.elim_left (gt_and_gt_of_mul_gt (nonempty g)) ⟩ def bot := row g ⟨nat.pred (rows g), nat.pred_lt (ne_of_gt (gt_and_gt_of_mul_gt (nonempty g)).1) ⟩ def left := have h : cols g > 0, from (gt_and_gt_of_mul_gt (nonempty g)).2, col g ⟨0, h⟩ def right := have h : cols g > 0, from (gt_and_gt_of_mul_gt (nonempty g)).2, col g ⟨nat.pred (cols g), nat.pred_lt (ne_of_gt h)⟩ def grid_bounds : bounding_box := ⟨gbl g, gtr g, grid_is_bounding_box⟩ def overlaid_by (bb₁ bb₂ : bounding_box) := (bb₂.p₁.x ≤ bb₁.p₁.x ∧ bb₁.p₂.x ≤ bb₂.p₂.x) ∧ (bb₁.p₂.y ≤ bb₂.p₂.y ∧ bb₂.p₁.y ≤ bb₁.p₁.y) def in_grid_bounded (p : point) (h : is_in_grid' g p) := let ⟨left, right⟩ := h in (make_bounded left, make_bounded right) instance overlaid_decidable (p₁ p₂ : bounding_box) : decidable (overlaid_by p₁ p₂) := by simp [overlaid_by]; apply_instance lemma overlaid_by_refl (bb : bounding_box) : overlaid_by bb bb := by simp [overlaid_by]; repeat {split}; refl lemma overlaid_by_trans {bb₁ bb₂ bb₃ : bounding_box} (h : overlaid_by bb₁ bb₂) (h₁ : overlaid_by bb₂ bb₃) : overlaid_by bb₁ bb₃ := by simp [overlaid_by] at *; repeat {split}; transitivity; finish lemma overlaid_by_antisymm {bb₁ bb₂ : bounding_box} (h : overlaid_by bb₁ bb₂) (h₁ : overlaid_by bb₂ bb₁) : bb₁ = bb₂ := begin simp [overlaid_by] at *, rcases bb₁ with ⟨⟨_, _⟩, ⟨_, _⟩⟩, rcases bb₂ with ⟨⟨_, _⟩, ⟨_, _⟩⟩, safe end lemma is_in_larger {bb₁ bb₂ : bounding_box} {xy : point} (h : xy ∈ bb₁) (h₁ : overlaid_by bb₁ bb₂) : xy ∈ bb₂ := ⟨⟨le_trans h₁.2.2 h.1.1, lt_of_lt_of_le h.1.2 h₁.2.1⟩, ⟨le_trans h₁.1.1 h.2.1, lt_of_lt_of_le h.2.2 h₁.1.2⟩⟩ private def bounded_prod_of_point {p : point} {g : α} (h : p ∈ g) : bounded (bl g).x (gtr g).x × bounded (bl g).y (gtr g).y := ⟨make_bounded h.2, make_bounded h.1⟩ open bounding_box def subgrid {α : Type*} [grid α] (g : α) (bb : bounding_box) (h : overlaid_by bb (bbox_of_grid g)) : fgrid₀ (carrier α) := ⟨rows_of_box bb, cols_of_box bb, mul_pos rows_of_box_pos cols_of_box_pos, bb.p₁, λx y, abs_data g ⟨⟨x.1, begin unfold overlaid_by at h, cases x with x hx, simp, rw bbox_of_grid_p₁ at h, rw bbox_of_grid_p₂ at h, exact ⟨ le_trans h.2.2 hx.1, begin have : bb.p₁.y + ↑(rows_of_box bb) = bb.p₂.y, begin have : (bb.p₂).y - (bb.p₁).y ≥ 0, by simp [-sub_eq_add_neg, ge_from_le]; apply int.le_of_lt (grid_bounded_iff.1 bb.3).2, simp [-sub_eq_add_neg, rows_of_box], rw nat_abs_of_nonneg this, simp end, rw this at hx, exact lt_of_lt_of_le hx.2 h.2.1 end ⟩ end⟩, ⟨y.1, begin unfold overlaid_by at h, cases y with y hy, simp, rw bbox_of_grid_p₁ at h, rw bbox_of_grid_p₂ at h, have : (bb.p₁).x + ↑(cols_of_box bb) = bb.p₂.x, by simp [ -sub_eq_add_neg, bounding_box.p₁, bounding_box.p₂, cols_of_box, nat_abs_of_nonneg (nonneg_of_lt (grid_bounded_iff.1 bb.3).1), add_sub_cancel'_right ], rw this at hy, exact ⟨le_trans h.1.1 hy.1, lt_of_lt_of_le hy.2 h.1.2⟩ end⟩⟩⟩ private def modify_vec {α : Type} {m} (v : vector α m) (n : ℕ) (x : α) : vector α m := ⟨update_nth v.to_list n x, by simp [update_nth_pres_len, *]⟩ def modify_at {α : Type} (p : point) (x : α) (g : vec_grid₀ α) : vec_grid₀ α := if h : p ∈ g then let ⟨r, c⟩ := relpoint_of_gpoint $ @grid_point.mk _ _ g ⟨p.y, by simp only [(∈)] at h; exact h.left⟩ ⟨p.x, by simp only [(∈)] at h; exact h.right⟩ in ⟨⟨g.r, g.c, g.h, modify_vec g.contents (r * g.c + c) x⟩, g.o⟩ else g def modify_many {α : Type} (l : list (point × α)) (g : vec_grid₀ α) : vec_grid₀ α := foldr (uncurry modify_at) g l def count_grid {α : Type} [grid α] [decidable_eq (carrier α)] (g : α) (x : carrier α) := list.count x (℘ g) lemma gen_aof_eq_gen {α : Type} {g : fgrid₀ α} : ℘ (vec_grid₀_of_fgrid₀ g) = @generate _ ag_fgrid₀ g := by simp [vec_grid₀_of_fgrid₀, generate_eq_data] private theorem generate_inj_a_f {α : Type} {g₁ : vec_grid₀ α} {g₂ : fgrid₀ α} (hrows : g₁.r = g₂.r) (hcols : g₁.c = g₂.c) (horig : g₁.o = g₂.o) (h : ℘ g₁ = @generate (fgrid₀ α) _ g₂) : g₁ = g₂ := begin have hl₁ : length (℘ g₁) = g₁.r * g₁.c, from length_generate _, have hl₂ : length (℘ g₂) = g₂.r * g₂.c, from length_generate _, rcases g₁ with ⟨⟨g₁r, g₁c, g₁h, ⟨g₁dv, g₁dh⟩⟩, g₁o⟩, cases g₂ with g₂r g₂c g₂h g₂o g₂d, dsimp at hrows hcols horig hl₁ hl₂, subst hrows, subst hcols, subst horig, unfold_coes, simp [vec_grid₀_of_fgrid₀, h.symm, generate_eq_data] end lemma gen_foa_eq_gen {α : Type} {g : vec_grid₀ α} : ℘ (fgrid₀_of_vec_grid₀ g) = @generate (vec_grid₀ α) _ g := begin have hl₁ : length (℘ g) = rows g * cols g, from length_generate _, have hl₂ : length (℘ (fgrid₀_of_vec_grid₀ g)) = rows g * cols g, from length_generate _, simp [fgrid₀_of_vec_grid₀] at *, apply list.ext_le (hl₂.trans hl₁.symm) (λi hi₁ hi₂, _), simp [ nth_le_generate_f₀, nth_generate, abs_data_eq_nth_v₀', abs_data_eq_nth_f₀, tl, bl, rows, cols, expand_gtr ] end private theorem generate_inj_f₀_v₀ {α : Type} {g₁ : fgrid₀ α} {g₂ : vec_grid₀ α} (hrows : g₁.r = g₂.r) (hcols : g₁.c = g₂.c) (horig : g₁.o = g₂.o) (h : ℘ g₁ = @generate (fgrid₀ α) _ g₂) : g₁ = g₂ := generate_inj_f₀_f₀ hrows hcols horig h theorem grid_eq_iff_v₀_f₀ {α : Type} {g₁ : vec_grid₀ α} {g₂ : fgrid₀ α} (h₁ : g₁.r = g₂.r) (h₂ : g₁.c = g₂.c) (h₃ : g₁.o = g₂.o) : g₁ = g₂ ↔ ℘ g₁ = ℘ g₂ := ⟨λh, h ▸ rfl, λh, generate_inj_a_f h₁ h₂ h₃ $ by rwa gen_aof_eq_gen.symm⟩ theorem grid_eq_iff_f₀_v₀ {α : Type} {g₁ : fgrid₀ α} {g₂ : vec_grid₀ α} (h₁ : g₁.r = g₂.r) (h₂ : g₁.c = g₂.c) (h₃ : g₁.o = g₂.o) : g₁ = g₂ ↔ ℘ g₁ = ℘ g₂ := ⟨λh, h ▸ rfl, λh, generate_inj_f₀_v₀ h₁ h₂ h₃ h⟩ attribute [extensionality] theorem grid_eq_ext_v₀_v₀ {α : Type} {g₁ g₂ : vec_grid₀ α} (hrows : g₁.r = g₂.r) (hcols : g₁.c = g₂.c) (horig : g₁.o = g₂.o) : ℘ g₁ = ℘ g₂ → g₁ = g₂ := (grid_eq_iff_v₀_v₀ hrows hcols horig).2 attribute [extensionality] theorem grid_eq_ext_f₀_f₀ {α : Type} {g₁ g₂ : fgrid₀ α} (hrows : g₁.r = g₂.r) (hcols : g₁.c = g₂.c) (horig : g₁.o = g₂.o) : ℘ g₁ = ℘ g₂ → g₁ = g₂ := (grid_eq_iff_f₀_f₀ hrows hcols horig).2 attribute [extensionality] theorem grid_eq_ext_v₀_f₀ {α : Type} {g₁ : vec_grid₀ α} {g₂ : fgrid₀ α} (hrows : g₁.r = g₂.r) (hcols : g₁.c = g₂.c) (horig : g₁.o = g₂.o) : ℘ g₁ = ℘ g₂ → g₁ = g₂ := (grid_eq_iff_v₀_f₀ hrows hcols horig).2 attribute [extensionality] theorem grid_eq_ext_f₀_v₀ {α : Type} {g₁ : fgrid₀ α} {g₂ : vec_grid₀ α} (hrows : g₁.r = g₂.r) (hcols : g₁.c = g₂.c) (horig : g₁.o = g₂.o) : ℘ g₁ = ℘ g₂ → g₁ = g₂ := (grid_eq_iff_f₀_v₀ hrows hcols horig).2 lemma nth_vecgrid_of_fgrid {α : Type} {g : fgrid₀ α} {n} : list.nth (vec_grid₀_of_fgrid₀ g).contents.val n = list.nth (℘ g) n := by delta vec_grid₀_of_fgrid₀; simp instance decidable_eq_v₀_v₀ {α : Type} [decidable_eq α] : decidable_eq (vec_grid₀ α) := λg₁ g₂, if h : g₁.r = g₂.r ∧ g₁.c = g₂.c ∧ g₁.o = g₂.o then by simp [grid_eq_iff_v₀_v₀, *]; apply_instance else is_false $ by finish instance decidable_eq_f₀_f₀ {α : Type} [decidable_eq α] : decidable_eq (fgrid₀ α) := λg₁ g₂, if h : g₁.r = g₂.r ∧ g₁.c = g₂.c ∧ g₁.o = g₂.o then by simp [grid_eq_iff_f₀_f₀, *]; apply_instance else is_false $ by finish instance decidable_eq_v₀_f₀ {α : Type} [decidable_eq α] {g₁ : vec_grid₀ α} {g₂ : fgrid₀ α} : decidable (g₁ = g₂) := if h : g₁.r = g₂.r ∧ g₁.c = g₂.c ∧ g₁.o = g₂.o then by simp [grid_eq_iff_v₀_f₀, *]; apply_instance else is_false $ by finish instance decidable_eq_f₀_v₀ {α : Type} [decidable_eq α] {g₁ : fgrid₀ α} {g₂ : vec_grid₀ α} : decidable (g₁ = g₂) := if h : g₁.r = g₂.r ∧ g₁.c = g₂.c ∧ g₁.o = g₂.o then by simp [grid_eq_iff_f₀_v₀, *]; apply_instance else is_false $ by finish lemma subgrid_self {α : Type} {g : vec_grid₀ α} {bb : bounding_box} (h : bb = {bounding_box. p₁ := bl g, p₂ := gtr g, h := grid_is_bounding_box }) : subgrid g bb begin unfold bbox_of_grid, rw h, exact overlaid_by_refl _ end = g := begin rcases g with ⟨⟨r, c, h, ⟨d, hd⟩⟩, o⟩, simp [h, subgrid], unfold_coes, rw grid_eq_iff_f₀_f₀; try { simp [cols_of_box, bl, expand_gtr, cols] }; try { simp }; try { simp [rows_of_box, bl, expand_gtr, rows] }, rw gen_foa_eq_gen, apply ext_le, { simp [ length_generate_eq_size, size, rows, cols, rows_of_box, cols_of_box, bl, expand_gtr ] }, { intros, rw nth_le_generate_f₀, simp only [ nth_generate, abs_data, contents, expand_gtr, bl, (∘), relpoint_of_gpoint, prod_of_rel_point, rows, cols, tl, rows_of_box, cols_of_box ], simp } end lemma p_in_g_iff_v₀_f₀ {α : Type} {g₁ : vec_grid₀ α} {g₂ : fgrid₀ α} {p} (h₁ : g₁.r = g₂.r) (h₂ : g₁.c = g₂.c) (h₃ : g₁.o = g₂.o) : p ∈ g₁ ↔ p ∈ g₂ := begin rcases g₁ with ⟨⟨r₁, c₁, gh₁, d₁⟩, o₁⟩, rcases g₂ with ⟨r₂, c₂, gh₂, o₂, d₂⟩, simp [flip, is_in_grid'] at *, split; intros; unfold_projs at *; subst h₁; subst h₂; subst h₃; finish end end finite_grid section grid_instances open relative_grid def split_rows_cols : ℕ → ℕ → list string → list string | cols 0 ls := [""] | cols (k + 1) ls := list.take cols ls ++ ["\n"] ++ split_rows_cols cols k (list.drop cols ls) def grid_str {α : Type*} [grid α] [has_to_string (carrier α)] (g : α) : string := let points := list.map to_string $ ℘ g in " " ++ (list.foldr append "" $ list.intersperse " " $ split_rows_cols (cols g) (rows g) points) instance grid_repr {α : Type*} [grid α] [has_to_string (carrier α)] : has_repr α := ⟨grid_str⟩ instance grid_to_string {α : Type*} [grid α] [has_to_string (carrier α)] : has_to_string α := ⟨grid_str⟩ end grid_instances
1415e8c904794bb0a17db4f9bdfc6f9878fa6f6b
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/algebra/continued_fractions/computation/terminates_iff_rat.lean
7f9548334e889f74e4f3bd334faae3c6183be151
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
8,135
lean
/- Copyright (c) 2020 Kevin Kappelmann. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Kappelmann -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.continued_fractions.computation.approximations import Mathlib.algebra.continued_fractions.computation.correctness_terminating import Mathlib.data.rat.default import Mathlib.PostPort universes u_1 namespace Mathlib /-! # Termination of Continued Fraction Computations (`gcf.of`) ## Summary We show that the continued fraction for a value `v`, as defined in `algebra.continued_fractions.computation.basic`, terminates if and only if `v` corresponds to a rational number, that is `↑v = q` for some `q : ℚ`. ## Main Theorems - `gcf.coe_of_rat` shows that `gcf.of v = gcf.of q` for `v : α` given that `↑v = q` and `q : ℚ`. - `gcf.terminates_iff_rat` shows that `gcf.of v` terminates if and only if `↑v = q` for some `q : ℚ`. ## Tags rational, continued fraction, termination -/ namespace generalized_continued_fraction /- We will have to constantly coerce along our structures in the following proofs using their provided map functions. -/ /-! We want to show that the computation of a continued fraction `gcf.of v` terminates if and only if `v ∈ ℚ`. In the next section, we show the implication from left to right. We first show that every finite convergent corresponds to a rational number `q` and then use the finite correctness proof (`of_correctness_of_terminates`) of `gcf.of` to show that `v = ↑q`. -/ theorem exists_gcf_pair_rat_eq_of_nth_conts_aux {K : Type u_1} [linear_ordered_field K] [floor_ring K] (v : K) (n : ℕ) : ∃ (conts : pair ℚ), continuants_aux (generalized_continued_fraction.of v) n = pair.map coe conts := sorry theorem exists_gcf_pair_rat_eq_nth_conts {K : Type u_1} [linear_ordered_field K] [floor_ring K] (v : K) (n : ℕ) : ∃ (conts : pair ℚ), continuants (generalized_continued_fraction.of v) n = pair.map coe conts := sorry theorem exists_rat_eq_nth_numerator {K : Type u_1} [linear_ordered_field K] [floor_ring K] (v : K) (n : ℕ) : ∃ (q : ℚ), numerators (generalized_continued_fraction.of v) n = ↑q := sorry theorem exists_rat_eq_nth_denominator {K : Type u_1} [linear_ordered_field K] [floor_ring K] (v : K) (n : ℕ) : ∃ (q : ℚ), denominators (generalized_continued_fraction.of v) n = ↑q := sorry /-- Every finite convergent corresponds to a rational number. -/ theorem exists_rat_eq_nth_convergent {K : Type u_1} [linear_ordered_field K] [floor_ring K] (v : K) (n : ℕ) : ∃ (q : ℚ), convergents (generalized_continued_fraction.of v) n = ↑q := sorry /-- Every terminating continued fraction corresponds to a rational number. -/ theorem exists_rat_eq_of_terminates {K : Type u_1} [linear_ordered_field K] [floor_ring K] {v : K} (terminates : terminates (generalized_continued_fraction.of v)) : ∃ (q : ℚ), v = ↑q := sorry /-! Before we can show that the continued fraction of a rational number terminates, we have to prove some technical translation lemmas. More precisely, in this section, we show that, given a rational number `q : ℚ` and value `v : K` with `v = ↑q`, the continued fraction of `q` and `v` coincide. In particular, we show that `(↑(gcf.of q : gcf ℚ) : gcf K) = gcf.of v` in `gcf.coe_of_rat`. To do this, we proceed bottom-up, showing the correspondence between the basic functions involved in the computation first and then lift the results step-by-step. -/ /- The lifting works for arbitrary linear ordered, archimedean fields with a floor function. -/ /-! First, we show the correspondence for the very basic functions in `gcf.int_fract_pair`. -/ namespace int_fract_pair theorem coe_of_rat_eq {K : Type u_1} [linear_ordered_field K] [floor_ring K] [archimedean K] {v : K} {q : ℚ} (v_eq_q : v = ↑q) : mapFr coe (int_fract_pair.of q) = int_fract_pair.of v := sorry theorem coe_stream_nth_rat_eq {K : Type u_1} [linear_ordered_field K] [floor_ring K] [archimedean K] {v : K} {q : ℚ} (v_eq_q : v = ↑q) (n : ℕ) : option.map (mapFr coe) (int_fract_pair.stream q n) = int_fract_pair.stream v n := sorry theorem coe_stream_rat_eq {K : Type u_1} [linear_ordered_field K] [floor_ring K] [archimedean K] {v : K} {q : ℚ} (v_eq_q : v = ↑q) : stream.map (option.map (mapFr coe)) (int_fract_pair.stream q) = int_fract_pair.stream v := funext fun (n : ℕ) => coe_stream_nth_rat_eq v_eq_q n end int_fract_pair /-! Now we lift the coercion results to the continued fraction computation. -/ theorem coe_of_h_rat_eq {K : Type u_1} [linear_ordered_field K] [floor_ring K] [archimedean K] {v : K} {q : ℚ} (v_eq_q : v = ↑q) : ↑(h (generalized_continued_fraction.of q)) = h (generalized_continued_fraction.of v) := sorry theorem coe_of_s_nth_rat_eq {K : Type u_1} [linear_ordered_field K] [floor_ring K] [archimedean K] {v : K} {q : ℚ} (v_eq_q : v = ↑q) (n : ℕ) : option.map (pair.map coe) (seq.nth (s (generalized_continued_fraction.of q)) n) = seq.nth (s (generalized_continued_fraction.of v)) n := sorry theorem coe_of_s_rat_eq {K : Type u_1} [linear_ordered_field K] [floor_ring K] [archimedean K] {v : K} {q : ℚ} (v_eq_q : v = ↑q) : seq.map (pair.map coe) (s (generalized_continued_fraction.of q)) = s (generalized_continued_fraction.of v) := sorry /-- Given `(v : K), (q : ℚ), and v = q`, we have that `gcf.of q = gcf.of v` -/ theorem coe_of_rat_eq {K : Type u_1} [linear_ordered_field K] [floor_ring K] [archimedean K] {v : K} {q : ℚ} (v_eq_q : v = ↑q) : mk (↑(h (generalized_continued_fraction.of q))) (seq.map (pair.map coe) (s (generalized_continued_fraction.of q))) = generalized_continued_fraction.of v := sorry theorem of_terminates_iff_of_rat_terminates {K : Type u_1} [linear_ordered_field K] [floor_ring K] [archimedean K] {v : K} {q : ℚ} (v_eq_q : v = ↑q) : terminates (generalized_continued_fraction.of v) ↔ terminates (generalized_continued_fraction.of q) := sorry /-! Finally, we show that the continued fraction of a rational number terminates. The crucial insight is that, given any `q : ℚ` with `0 < q < 1`, the numerator of `fract q` is smaller than the numerator of `q`. As the continued fraction computation recursively operates on the fractional part of a value `v` and `0 ≤ fract v < 1`, we infer that the numerator of the fractional part in the computation decreases by at least one in each step. As `0 ≤ fract v`, this process must stop after finite number of steps, and the computation hence terminates. -/ namespace int_fract_pair /-- Shows that for any `q : ℚ` with `0 < q < 1`, the numerator of the fractional part of `int_fract_pair.of q⁻¹` is smaller than the numerator of `q`. -/ theorem of_inv_fr_num_lt_num_of_pos {q : ℚ} (q_pos : 0 < q) : rat.num (fr (int_fract_pair.of (q⁻¹))) < rat.num q := rat.fract_inv_num_lt_num_of_pos q_pos /-- Shows that the sequence of numerators of the fractional parts of the stream is strictly monotonically decreasing. -/ theorem stream_succ_nth_fr_num_lt_nth_fr_num_rat {q : ℚ} {n : ℕ} {ifp_n : int_fract_pair ℚ} {ifp_succ_n : int_fract_pair ℚ} (stream_nth_eq : int_fract_pair.stream q n = some ifp_n) (stream_succ_nth_eq : int_fract_pair.stream q (n + 1) = some ifp_succ_n) : rat.num (fr ifp_succ_n) < rat.num (fr ifp_n) := sorry theorem stream_nth_fr_num_le_fr_num_sub_n_rat {q : ℚ} {n : ℕ} {ifp_n : int_fract_pair ℚ} : int_fract_pair.stream q n = some ifp_n → rat.num (fr ifp_n) ≤ rat.num (fr (int_fract_pair.of q)) - ↑n := sorry theorem exists_nth_stream_eq_none_of_rat (q : ℚ) : ∃ (n : ℕ), int_fract_pair.stream q n = none := sorry end int_fract_pair /-- The continued fraction of a rational number terminates. -/ theorem terminates_of_rat (q : ℚ) : terminates (generalized_continued_fraction.of q) := sorry /-- The continued fraction `gcf.of v` terminates if and only if `v ∈ ℚ`. -/ theorem terminates_iff_rat {K : Type u_1} [linear_ordered_field K] [floor_ring K] [archimedean K] (v : K) : terminates (generalized_continued_fraction.of v) ↔ ∃ (q : ℚ), v = ↑q := sorry
1033ed37728306b94824e70295c4ef053a77cb9a
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/data/set/basic.lean
d53a33ccba7abd1e5412cae259970b48206d7b8e
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
108,825
lean
/- 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 -/ import logic.unique import order.boolean_algebra /-! # Basic properties of sets Sets in Lean are homogeneous; all their elements have the same type. Sets whose elements have type `X` are thus defined as `set X := X → Prop`. Note that this function need not be decidable. The definition is in the core library. This file provides some basic definitions related to sets and functions not present in the core library, as well as extra lemmas for functions in the core library (empty set, univ, union, intersection, insert, singleton, set-theoretic difference, complement, and powerset). Note that a set is a term, not a type. There is a coercion from `set α` to `Type*` sending `s` to the corresponding subtype `↥s`. See also the file `set_theory/zfc.lean`, which contains an encoding of ZFC set theory in Lean. ## Main definitions Notation used here: - `f : α → β` is a function, - `s : set α` and `s₁ s₂ : set α` are subsets of `α` - `t : set β` is a subset of `β`. Definitions in the file: * `strict_subset s₁ s₂ : Prop` : the predicate `s₁ ⊆ s₂` but `s₁ ≠ s₂`. * `nonempty s : Prop` : the predicate `s ≠ ∅`. Note that this is the preferred way to express the fact that `s` has an element (see the Implementation Notes). * `preimage f t : set α` : the preimage f⁻¹(t) (written `f ⁻¹' t` in Lean) of a subset of β. * `subsingleton s : Prop` : the predicate saying that `s` has at most one element. * `range f : set β` : the image of `univ` under `f`. Also works for `{p : Prop} (f : p → α)` (unlike `image`) * `s.prod t : set (α × β)` : the subset `s × t`. * `inclusion s₁ s₂ : ↥s₁ → ↥s₂` : the map `↥s₁ → ↥s₂` induced by an inclusion `s₁ ⊆ s₂`. ## Notation * `f ⁻¹' t` for `preimage f t` * `f '' s` for `image f s` * `sᶜ` for the complement of `s` ## Implementation notes * `s.nonempty` is to be preferred to `s ≠ ∅` or `∃ x, x ∈ s`. It has the advantage that the `s.nonempty` dot notation can be used. * For `s : set α`, do not use `subtype s`. Instead use `↥s` or `(s : Type*)` or `s`. ## Tags set, sets, subset, subsets, image, preimage, pre-image, range, union, intersection, insert, singleton, complement, powerset -/ /-! ### Set coercion to a type -/ open function universe variables u v w x run_cmd do e ← tactic.get_env, tactic.set_env $ e.mk_protected `set.compl lemma has_subset.subset.trans {α : Type*} [has_subset α] [is_trans α (⊆)] {a b c : α} (h : a ⊆ b) (h' : b ⊆ c) : a ⊆ c := trans h h' lemma has_subset.subset.antisymm {α : Type*} [has_subset α] [is_antisymm α (⊆)] {a b : α} (h : a ⊆ b) (h' : b ⊆ a) : a = b := antisymm h h' lemma has_ssubset.ssubset.trans {α : Type*} [has_ssubset α] [is_trans α (⊂)] {a b c : α} (h : a ⊂ b) (h' : b ⊂ c) : a ⊂ c := trans h h' lemma has_ssubset.ssubset.asymm {α : Type*} [has_ssubset α] [is_asymm α (⊂)] {a b : α} (h : a ⊂ b) : ¬(b ⊂ a) := asymm h namespace set variable {α : Type*} instance : has_le (set α) := ⟨(⊆)⟩ instance : has_lt (set α) := ⟨λ s t, s ≤ t ∧ ¬t ≤ s⟩ -- `⊂` is not defined until further down instance {α : Type*} : boolean_algebra (set α) := { sup := (∪), le := (≤), lt := (<), inf := (∩), bot := ∅, compl := set.compl, top := univ, sdiff := (\), .. (infer_instance : boolean_algebra (α → Prop)) } @[simp] lemma top_eq_univ : (⊤ : set α) = univ := rfl @[simp] lemma bot_eq_empty : (⊥ : set α) = ∅ := rfl @[simp] lemma sup_eq_union : ((⊔) : set α → set α → set α) = (∪) := rfl @[simp] lemma inf_eq_inter : ((⊓) : set α → set α → set α) = (∩) := rfl @[simp] lemma le_eq_subset : ((≤) : set α → set α → Prop) = (⊆) := rfl /-! `set.lt_eq_ssubset` is defined further down -/ @[simp] lemma compl_eq_compl : set.compl = (has_compl.compl : set α → set α) := rfl /-- Coercion from a set to the corresponding subtype. -/ instance {α : Type*} : has_coe_to_sort (set α) := ⟨_, λ s, {x // x ∈ s}⟩ instance pi_set_coe.can_lift (ι : Type u) (α : Π i : ι, Type v) [ne : Π i, nonempty (α i)] (s : set ι) : can_lift (Π i : s, α i) (Π i, α i) := { coe := λ f i, f i, .. pi_subtype.can_lift ι α s } instance pi_set_coe.can_lift' (ι : Type u) (α : Type v) [ne : nonempty α] (s : set ι) : can_lift (s → α) (ι → α) := pi_set_coe.can_lift ι (λ _, α) s instance set_coe.can_lift (s : set α) : can_lift α s := { coe := coe, cond := λ a, a ∈ s, prf := λ a ha, ⟨⟨a, ha⟩, rfl⟩ } end set section set_coe variables {α : Type u} theorem set.set_coe_eq_subtype (s : set α) : coe_sort.{(u+1) (u+2)} s = {x // x ∈ s} := rfl @[simp] theorem set_coe.forall {s : set α} {p : s → Prop} : (∀ x : s, p x) ↔ (∀ x (h : x ∈ s), p ⟨x, h⟩) := subtype.forall @[simp] theorem set_coe.exists {s : set α} {p : s → Prop} : (∃ x : s, p x) ↔ (∃ x (h : x ∈ s), p ⟨x, h⟩) := subtype.exists theorem set_coe.exists' {s : set α} {p : Π x, x ∈ s → Prop} : (∃ x (h : x ∈ s), p x h) ↔ (∃ x : s, p x x.2) := (@set_coe.exists _ _ $ λ x, p x.1 x.2).symm theorem set_coe.forall' {s : set α} {p : Π x, x ∈ s → Prop} : (∀ x (h : x ∈ s), p x h) ↔ (∀ x : s, p x x.2) := (@set_coe.forall _ _ $ λ x, p x.1 x.2).symm @[simp] theorem set_coe_cast : ∀ {s t : set α} (H' : s = t) (H : @eq (Type u) s t) (x : s), cast H x = ⟨x.1, H' ▸ x.2⟩ | s _ rfl _ ⟨x, h⟩ := rfl theorem set_coe.ext {s : set α} {a b : s} : (↑a : α) = ↑b → a = b := subtype.eq theorem set_coe.ext_iff {s : set α} {a b : s} : (↑a : α) = ↑b ↔ a = b := iff.intro set_coe.ext (assume h, h ▸ rfl) end set_coe /-- See also `subtype.prop` -/ lemma subtype.mem {α : Type*} {s : set α} (p : s) : (p : α) ∈ s := p.prop lemma eq.subset {α} {s t : set α} : s = t → s ⊆ t := by { rintro rfl x hx, exact hx } namespace set variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} {a : α} {s t : set α} instance : inhabited (set α) := ⟨∅⟩ @[ext] theorem ext {a b : set α} (h : ∀ x, x ∈ a ↔ x ∈ b) : a = b := funext (assume x, propext (h x)) theorem ext_iff {s t : set α} : s = t ↔ ∀ x, x ∈ s ↔ x ∈ t := ⟨λ h x, by rw h, ext⟩ @[trans] theorem mem_of_mem_of_subset {x : α} {s t : set α} (hx : x ∈ s) (h : s ⊆ t) : x ∈ t := h hx /-! ### Lemmas about `mem` and `set_of` -/ @[simp] theorem mem_set_of_eq {a : α} {p : α → Prop} : a ∈ {a | p a} = p a := rfl theorem nmem_set_of_eq {a : α} {P : α → Prop} : a ∉ {a : α | P a} = ¬ P a := rfl @[simp] theorem set_of_mem_eq {s : set α} : {x | x ∈ s} = s := rfl theorem set_of_set {s : set α} : set_of s = s := rfl lemma set_of_app_iff {p : α → Prop} {x : α} : { x | p x } x ↔ p x := iff.rfl theorem mem_def {a : α} {s : set α} : a ∈ s ↔ s a := iff.rfl instance decidable_mem (s : set α) [H : decidable_pred s] : ∀ a, decidable (a ∈ s) := H instance decidable_set_of (p : α → Prop) [H : decidable_pred p] : decidable_pred {a | p a} := H @[simp] theorem set_of_subset_set_of {p q : α → Prop} : {a | p a} ⊆ {a | q a} ↔ (∀a, p a → q a) := iff.rfl @[simp] lemma sep_set_of {p q : α → Prop} : {a ∈ {a | p a } | q a} = {a | p a ∧ q a} := rfl lemma set_of_and {p q : α → Prop} : {a | p a ∧ q a} = {a | p a} ∩ {a | q a} := rfl lemma set_of_or {p q : α → Prop} : {a | p a ∨ q a} = {a | p a} ∪ {a | q a} := rfl /-! ### Lemmas about subsets -/ -- TODO(Jeremy): write a tactic to unfold specific instances of generic notation? theorem subset_def {s t : set α} : (s ⊆ t) = ∀ x, x ∈ s → x ∈ t := rfl @[refl] theorem subset.refl (a : set α) : a ⊆ a := assume x, id theorem subset.rfl {s : set α} : s ⊆ s := subset.refl s @[trans] theorem subset.trans {a b c : set α} (ab : a ⊆ b) (bc : b ⊆ c) : a ⊆ c := assume x h, bc (ab h) @[trans] theorem mem_of_eq_of_mem {x y : α} {s : set α} (hx : x = y) (h : y ∈ s) : x ∈ s := hx.symm ▸ h theorem subset.antisymm {a b : set α} (h₁ : a ⊆ b) (h₂ : b ⊆ a) : a = b := set.ext $ λ x, ⟨@h₁ _, @h₂ _⟩ theorem subset.antisymm_iff {a b : set α} : a = b ↔ a ⊆ b ∧ b ⊆ a := ⟨λ e, ⟨e.subset, e.symm.subset⟩, λ ⟨h₁, h₂⟩, subset.antisymm h₁ h₂⟩ -- an alternative name theorem eq_of_subset_of_subset {a b : set α} : a ⊆ b → b ⊆ a → a = b := subset.antisymm theorem mem_of_subset_of_mem {s₁ s₂ : set α} {a : α} (h : s₁ ⊆ s₂) : a ∈ s₁ → a ∈ s₂ := @h _ theorem not_mem_subset (h : s ⊆ t) : a ∉ t → a ∉ s := mt $ mem_of_subset_of_mem h theorem not_subset : (¬ s ⊆ t) ↔ ∃a ∈ s, a ∉ t := by simp only [subset_def, not_forall] /-! ### Definition of strict subsets `s ⊂ t` and basic properties. -/ instance : has_ssubset (set α) := ⟨(<)⟩ @[simp] lemma lt_eq_ssubset : ((<) : set α → set α → Prop) = (⊂) := rfl theorem ssubset_def : (s ⊂ t) = (s ⊆ t ∧ ¬ (t ⊆ s)) := rfl theorem eq_or_ssubset_of_subset (h : s ⊆ t) : s = t ∨ s ⊂ t := eq_or_lt_of_le h lemma exists_of_ssubset {s t : set α} (h : s ⊂ t) : (∃x∈t, x ∉ s) := not_subset.1 h.2 lemma ssubset_iff_subset_ne {s t : set α} : s ⊂ t ↔ s ⊆ t ∧ s ≠ t := @lt_iff_le_and_ne (set α) _ s t lemma ssubset_iff_of_subset {s t : set α} (h : s ⊆ t) : s ⊂ t ↔ ∃ x ∈ t, x ∉ s := ⟨exists_of_ssubset, λ ⟨x, hxt, hxs⟩, ⟨h, λ h, hxs $ h hxt⟩⟩ lemma ssubset_of_ssubset_of_subset {s₁ s₂ s₃ : set α} (hs₁s₂ : s₁ ⊂ s₂) (hs₂s₃ : s₂ ⊆ s₃) : s₁ ⊂ s₃ := ⟨subset.trans hs₁s₂.1 hs₂s₃, λ hs₃s₁, hs₁s₂.2 (subset.trans hs₂s₃ hs₃s₁)⟩ lemma ssubset_of_subset_of_ssubset {s₁ s₂ s₃ : set α} (hs₁s₂ : s₁ ⊆ s₂) (hs₂s₃ : s₂ ⊂ s₃) : s₁ ⊂ s₃ := ⟨subset.trans hs₁s₂ hs₂s₃.1, λ hs₃s₁, hs₂s₃.2 (subset.trans hs₃s₁ hs₁s₂)⟩ theorem not_mem_empty (x : α) : ¬ (x ∈ (∅ : set α)) := id @[simp] theorem not_not_mem : ¬ (a ∉ s) ↔ a ∈ s := not_not /-! ### Non-empty sets -/ /-- The property `s.nonempty` expresses the fact that the set `s` is not empty. It should be used in theorem assumptions instead of `∃ x, x ∈ s` or `s ≠ ∅` as it gives access to a nice API thanks to the dot notation. -/ protected def nonempty (s : set α) : Prop := ∃ x, x ∈ s lemma nonempty_def : s.nonempty ↔ ∃ x, x ∈ s := iff.rfl lemma nonempty_of_mem {x} (h : x ∈ s) : s.nonempty := ⟨x, h⟩ theorem nonempty.not_subset_empty : s.nonempty → ¬(s ⊆ ∅) | ⟨x, hx⟩ hs := hs hx theorem nonempty.ne_empty : ∀ {s : set α}, s.nonempty → s ≠ ∅ | _ ⟨x, hx⟩ rfl := hx @[simp] theorem not_nonempty_empty : ¬(∅ : set α).nonempty := λ h, h.ne_empty rfl /-- Extract a witness from `s.nonempty`. This function might be used instead of case analysis on the argument. Note that it makes a proof depend on the `classical.choice` axiom. -/ protected noncomputable def nonempty.some (h : s.nonempty) : α := classical.some h protected lemma nonempty.some_mem (h : s.nonempty) : h.some ∈ s := classical.some_spec h lemma nonempty.mono (ht : s ⊆ t) (hs : s.nonempty) : t.nonempty := hs.imp ht lemma nonempty_of_not_subset (h : ¬s ⊆ t) : (s \ t).nonempty := let ⟨x, xs, xt⟩ := not_subset.1 h in ⟨x, xs, xt⟩ lemma nonempty_of_ssubset (ht : s ⊂ t) : (t \ s).nonempty := nonempty_of_not_subset ht.2 lemma nonempty.of_diff (h : (s \ t).nonempty) : s.nonempty := h.imp $ λ _, and.left lemma nonempty_of_ssubset' (ht : s ⊂ t) : t.nonempty := (nonempty_of_ssubset ht).of_diff lemma nonempty.inl (hs : s.nonempty) : (s ∪ t).nonempty := hs.imp $ λ _, or.inl lemma nonempty.inr (ht : t.nonempty) : (s ∪ t).nonempty := ht.imp $ λ _, or.inr @[simp] lemma union_nonempty : (s ∪ t).nonempty ↔ s.nonempty ∨ t.nonempty := exists_or_distrib lemma nonempty.left (h : (s ∩ t).nonempty) : s.nonempty := h.imp $ λ _, and.left lemma nonempty.right (h : (s ∩ t).nonempty) : t.nonempty := h.imp $ λ _, and.right lemma nonempty_inter_iff_exists_right : (s ∩ t).nonempty ↔ ∃ x : t, ↑x ∈ s := ⟨λ ⟨x, xs, xt⟩, ⟨⟨x, xt⟩, xs⟩, λ ⟨⟨x, xt⟩, xs⟩, ⟨x, xs, xt⟩⟩ lemma nonempty_inter_iff_exists_left : (s ∩ t).nonempty ↔ ∃ x : s, ↑x ∈ t := ⟨λ ⟨x, xs, xt⟩, ⟨⟨x, xs⟩, xt⟩, λ ⟨⟨x, xt⟩, xs⟩, ⟨x, xt, xs⟩⟩ lemma nonempty_iff_univ_nonempty : nonempty α ↔ (univ : set α).nonempty := ⟨λ ⟨x⟩, ⟨x, trivial⟩, λ ⟨x, _⟩, ⟨x⟩⟩ @[simp] lemma univ_nonempty : ∀ [h : nonempty α], (univ : set α).nonempty | ⟨x⟩ := ⟨x, trivial⟩ lemma nonempty.to_subtype (h : s.nonempty) : nonempty s := nonempty_subtype.2 h instance [nonempty α] : nonempty (set.univ : set α) := set.univ_nonempty.to_subtype @[simp] lemma nonempty_insert (a : α) (s : set α) : (insert a s).nonempty := ⟨a, or.inl rfl⟩ lemma nonempty_of_nonempty_subtype [nonempty s] : s.nonempty := nonempty_subtype.mp ‹_› /-! ### Lemmas about the empty set -/ theorem empty_def : (∅ : set α) = {x | false} := rfl @[simp] theorem mem_empty_eq (x : α) : x ∈ (∅ : set α) = false := rfl @[simp] theorem set_of_false : {a : α | false} = ∅ := rfl @[simp] theorem empty_subset (s : set α) : ∅ ⊆ s. theorem subset_empty_iff {s : set α} : s ⊆ ∅ ↔ s = ∅ := (subset.antisymm_iff.trans $ and_iff_left (empty_subset _)).symm theorem eq_empty_iff_forall_not_mem {s : set α} : s = ∅ ↔ ∀ x, x ∉ s := subset_empty_iff.symm theorem eq_empty_of_subset_empty {s : set α} : s ⊆ ∅ → s = ∅ := subset_empty_iff.1 theorem eq_empty_of_not_nonempty (h : ¬nonempty α) (s : set α) : s = ∅ := eq_empty_of_subset_empty $ λ x hx, h ⟨x⟩ theorem eq_empty_of_is_empty [is_empty α] (s : set α) : s = ∅ := eq_empty_of_subset_empty $ λ x hx, is_empty_elim x /-- There is exactly one set of a type that is empty. -/ -- TODO[gh-6025]: make this an instance once safe to do so def unique_empty [is_empty α] : unique (set α) := { default := ∅, uniq := eq_empty_of_is_empty } lemma not_nonempty_iff_eq_empty {s : set α} : ¬s.nonempty ↔ s = ∅ := by simp only [set.nonempty, eq_empty_iff_forall_not_mem, not_exists] lemma empty_not_nonempty : ¬(∅ : set α).nonempty := λ h, h.ne_empty rfl theorem ne_empty_iff_nonempty : s ≠ ∅ ↔ s.nonempty := not_iff_comm.1 not_nonempty_iff_eq_empty lemma eq_empty_or_nonempty (s : set α) : s = ∅ ∨ s.nonempty := or_iff_not_imp_left.2 ne_empty_iff_nonempty.1 theorem subset_eq_empty {s t : set α} (h : t ⊆ s) (e : s = ∅) : t = ∅ := subset_empty_iff.1 $ e ▸ h theorem ball_empty_iff {p : α → Prop} : (∀ x ∈ (∅ : set α), p x) ↔ true := iff_true_intro $ λ x, false.elim instance (α : Type u) : is_empty.{u+1} (∅ : set α) := ⟨λ x, x.2⟩ /-! ### Universal set. In Lean `@univ α` (or `univ : set α`) is the set that contains all elements of type `α`. Mathematically it is the same as `α` but it has a different type. -/ @[simp] theorem set_of_true : {x : α | true} = univ := rfl @[simp] theorem mem_univ (x : α) : x ∈ @univ α := trivial @[simp] lemma univ_eq_empty_iff : (univ : set α) = ∅ ↔ ¬ nonempty α := eq_empty_iff_forall_not_mem.trans ⟨λ H ⟨x⟩, H x trivial, λ H x _, H ⟨x⟩⟩ theorem empty_ne_univ [h : nonempty α] : (∅ : set α) ≠ univ := λ e, univ_eq_empty_iff.1 e.symm h @[simp] theorem subset_univ (s : set α) : s ⊆ univ := λ x H, trivial theorem univ_subset_iff {s : set α} : univ ⊆ s ↔ s = univ := (subset.antisymm_iff.trans $ and_iff_right (subset_univ _)).symm theorem eq_univ_of_univ_subset {s : set α} : univ ⊆ s → s = univ := univ_subset_iff.1 theorem eq_univ_iff_forall {s : set α} : s = univ ↔ ∀ x, x ∈ s := univ_subset_iff.symm.trans $ forall_congr $ λ x, imp_iff_right ⟨⟩ theorem eq_univ_of_forall {s : set α} : (∀ x, x ∈ s) → s = univ := eq_univ_iff_forall.2 lemma eq_univ_of_subset {s t : set α} (h : s ⊆ t) (hs : s = univ) : t = univ := eq_univ_of_univ_subset $ hs ▸ h lemma exists_mem_of_nonempty (α) : ∀ [nonempty α], ∃x:α, x ∈ (univ : set α) | ⟨x⟩ := ⟨x, trivial⟩ instance univ_decidable : decidable_pred (@set.univ α) := λ x, is_true trivial /-- `diagonal α` is the subset of `α × α` consisting of all pairs of the form `(a, a)`. -/ def diagonal (α : Type*) : set (α × α) := {p | p.1 = p.2} @[simp] lemma mem_diagonal {α : Type*} (x : α) : (x, x) ∈ diagonal α := by simp [diagonal] /-! ### Lemmas about union -/ theorem union_def {s₁ s₂ : set α} : s₁ ∪ s₂ = {a | a ∈ s₁ ∨ a ∈ s₂} := rfl theorem mem_union_left {x : α} {a : set α} (b : set α) : x ∈ a → x ∈ a ∪ b := or.inl theorem mem_union_right {x : α} {b : set α} (a : set α) : x ∈ b → x ∈ a ∪ b := or.inr theorem mem_or_mem_of_mem_union {x : α} {a b : set α} (H : x ∈ a ∪ b) : x ∈ a ∨ x ∈ b := H theorem mem_union.elim {x : α} {a b : set α} {P : Prop} (H₁ : x ∈ a ∪ b) (H₂ : x ∈ a → P) (H₃ : x ∈ b → P) : P := or.elim H₁ H₂ H₃ theorem mem_union (x : α) (a b : set α) : x ∈ a ∪ b ↔ x ∈ a ∨ x ∈ b := iff.rfl @[simp] theorem mem_union_eq (x : α) (a b : set α) : x ∈ a ∪ b = (x ∈ a ∨ x ∈ b) := rfl @[simp] theorem union_self (a : set α) : a ∪ a = a := ext $ λ x, or_self _ @[simp] theorem union_empty (a : set α) : a ∪ ∅ = a := ext $ λ x, or_false _ @[simp] theorem empty_union (a : set α) : ∅ ∪ a = a := ext $ λ x, false_or _ theorem union_comm (a b : set α) : a ∪ b = b ∪ a := ext $ λ x, or.comm theorem union_assoc (a b c : set α) : (a ∪ b) ∪ c = a ∪ (b ∪ c) := ext $ λ x, or.assoc instance union_is_assoc : is_associative (set α) (∪) := ⟨union_assoc⟩ instance union_is_comm : is_commutative (set α) (∪) := ⟨union_comm⟩ theorem union_left_comm (s₁ s₂ s₃ : set α) : s₁ ∪ (s₂ ∪ s₃) = s₂ ∪ (s₁ ∪ s₃) := ext $ λ x, or.left_comm theorem union_right_comm (s₁ s₂ s₃ : set α) : (s₁ ∪ s₂) ∪ s₃ = (s₁ ∪ s₃) ∪ s₂ := ext $ λ x, or.right_comm theorem union_eq_self_of_subset_left {s t : set α} (h : s ⊆ t) : s ∪ t = t := ext $ λ x, or_iff_right_of_imp $ @h _ theorem union_eq_self_of_subset_right {s t : set α} (h : t ⊆ s) : s ∪ t = s := ext $ λ x, or_iff_left_of_imp $ @h _ @[simp] theorem subset_union_left (s t : set α) : s ⊆ s ∪ t := λ x, or.inl @[simp] theorem subset_union_right (s t : set α) : t ⊆ s ∪ t := λ x, or.inr theorem union_subset {s t r : set α} (sr : s ⊆ r) (tr : t ⊆ r) : s ∪ t ⊆ r := λ x, or.rec (@sr _) (@tr _) @[simp] theorem union_subset_iff {s t u : set α} : s ∪ t ⊆ u ↔ s ⊆ u ∧ t ⊆ u := (forall_congr (by exact λ x, or_imp_distrib)).trans forall_and_distrib theorem union_subset_union {s₁ s₂ t₁ t₂ : set α} (h₁ : s₁ ⊆ s₂) (h₂ : t₁ ⊆ t₂) : s₁ ∪ t₁ ⊆ s₂ ∪ t₂ := λ x, or.imp (@h₁ _) (@h₂ _) theorem union_subset_union_left {s₁ s₂ : set α} (t) (h : s₁ ⊆ s₂) : s₁ ∪ t ⊆ s₂ ∪ t := union_subset_union h subset.rfl theorem union_subset_union_right (s) {t₁ t₂ : set α} (h : t₁ ⊆ t₂) : s ∪ t₁ ⊆ s ∪ t₂ := union_subset_union subset.rfl h lemma subset_union_of_subset_left {s t : set α} (h : s ⊆ t) (u : set α) : s ⊆ t ∪ u := subset.trans h (subset_union_left t u) lemma subset_union_of_subset_right {s u : set α} (h : s ⊆ u) (t : set α) : s ⊆ t ∪ u := subset.trans h (subset_union_right t u) @[simp] theorem union_empty_iff {s t : set α} : s ∪ t = ∅ ↔ s = ∅ ∧ t = ∅ := by simp only [← subset_empty_iff]; exact union_subset_iff @[simp] lemma union_univ {s : set α} : s ∪ univ = univ := sup_top_eq @[simp] lemma univ_union {s : set α} : univ ∪ s = univ := top_sup_eq /-! ### Lemmas about intersection -/ theorem inter_def {s₁ s₂ : set α} : s₁ ∩ s₂ = {a | a ∈ s₁ ∧ a ∈ s₂} := rfl theorem mem_inter_iff (x : α) (a b : set α) : x ∈ a ∩ b ↔ x ∈ a ∧ x ∈ b := iff.rfl @[simp] theorem mem_inter_eq (x : α) (a b : set α) : x ∈ a ∩ b = (x ∈ a ∧ x ∈ b) := rfl theorem mem_inter {x : α} {a b : set α} (ha : x ∈ a) (hb : x ∈ b) : x ∈ a ∩ b := ⟨ha, hb⟩ theorem mem_of_mem_inter_left {x : α} {a b : set α} (h : x ∈ a ∩ b) : x ∈ a := h.left theorem mem_of_mem_inter_right {x : α} {a b : set α} (h : x ∈ a ∩ b) : x ∈ b := h.right @[simp] theorem inter_self (a : set α) : a ∩ a = a := ext $ λ x, and_self _ @[simp] theorem inter_empty (a : set α) : a ∩ ∅ = ∅ := ext $ λ x, and_false _ @[simp] theorem empty_inter (a : set α) : ∅ ∩ a = ∅ := ext $ λ x, false_and _ theorem inter_comm (a b : set α) : a ∩ b = b ∩ a := ext $ λ x, and.comm theorem inter_assoc (a b c : set α) : (a ∩ b) ∩ c = a ∩ (b ∩ c) := ext $ λ x, and.assoc instance inter_is_assoc : is_associative (set α) (∩) := ⟨inter_assoc⟩ instance inter_is_comm : is_commutative (set α) (∩) := ⟨inter_comm⟩ theorem inter_left_comm (s₁ s₂ s₃ : set α) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) := ext $ λ x, and.left_comm theorem inter_right_comm (s₁ s₂ s₃ : set α) : (s₁ ∩ s₂) ∩ s₃ = (s₁ ∩ s₃) ∩ s₂ := ext $ λ x, and.right_comm @[simp] theorem inter_subset_left (s t : set α) : s ∩ t ⊆ s := λ x, and.left @[simp] theorem inter_subset_right (s t : set α) : s ∩ t ⊆ t := λ x, and.right theorem subset_inter {s t r : set α} (rs : r ⊆ s) (rt : r ⊆ t) : r ⊆ s ∩ t := λ x h, ⟨rs h, rt h⟩ @[simp] theorem subset_inter_iff {s t r : set α} : r ⊆ s ∩ t ↔ r ⊆ s ∧ r ⊆ t := (forall_congr (by exact λ x, imp_and_distrib)).trans forall_and_distrib theorem inter_eq_left_iff_subset {s t : set α} : s ∩ t = s ↔ s ⊆ t := ext_iff.trans $ forall_congr $ λ x, and_iff_left_iff_imp theorem inter_eq_right_iff_subset {s t : set α} : s ∩ t = t ↔ t ⊆ s := ext_iff.trans $ forall_congr $ λ x, and_iff_right_iff_imp theorem inter_eq_self_of_subset_left {s t : set α} : s ⊆ t → s ∩ t = s := inter_eq_left_iff_subset.mpr theorem inter_eq_self_of_subset_right {s t : set α} : t ⊆ s → s ∩ t = t := inter_eq_right_iff_subset.mpr @[simp] theorem inter_univ (a : set α) : a ∩ univ = a := inter_eq_self_of_subset_left $ subset_univ _ @[simp] theorem univ_inter (a : set α) : univ ∩ a = a := inter_eq_self_of_subset_right $ subset_univ _ theorem inter_subset_inter {s₁ s₂ t₁ t₂ : set α} (h₁ : s₁ ⊆ t₁) (h₂ : s₂ ⊆ t₂) : s₁ ∩ s₂ ⊆ t₁ ∩ t₂ := λ x, and.imp (@h₁ _) (@h₂ _) theorem inter_subset_inter_left {s t : set α} (u : set α) (H : s ⊆ t) : s ∩ u ⊆ t ∩ u := inter_subset_inter H subset.rfl theorem inter_subset_inter_right {s t : set α} (u : set α) (H : s ⊆ t) : u ∩ s ⊆ u ∩ t := inter_subset_inter subset.rfl H theorem union_inter_cancel_left {s t : set α} : (s ∪ t) ∩ s = s := inter_eq_self_of_subset_right $ subset_union_left _ _ theorem union_inter_cancel_right {s t : set α} : (s ∪ t) ∩ t = t := inter_eq_self_of_subset_right $ subset_union_right _ _ /-! ### Distributivity laws -/ theorem inter_distrib_left (s t u : set α) : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) := inf_sup_left theorem inter_union_distrib_left {s t u : set α} : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) := inf_sup_left theorem inter_distrib_right (s t u : set α) : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) := inf_sup_right theorem union_inter_distrib_right {s t u : set α} : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) := inf_sup_right theorem union_distrib_left (s t u : set α) : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) := sup_inf_left theorem union_inter_distrib_left {s t u : set α} : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) := sup_inf_left theorem union_distrib_right (s t u : set α) : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) := sup_inf_right theorem inter_union_distrib_right {s t u : set α} : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) := sup_inf_right /-! ### Lemmas about `insert` `insert α s` is the set `{α} ∪ s`. -/ theorem insert_def (x : α) (s : set α) : insert x s = { y | y = x ∨ y ∈ s } := rfl @[simp] theorem subset_insert (x : α) (s : set α) : s ⊆ insert x s := λ y, or.inr theorem mem_insert (x : α) (s : set α) : x ∈ insert x s := or.inl rfl theorem mem_insert_of_mem {x : α} {s : set α} (y : α) : x ∈ s → x ∈ insert y s := or.inr theorem eq_or_mem_of_mem_insert {x a : α} {s : set α} : x ∈ insert a s → x = a ∨ x ∈ s := id theorem mem_of_mem_insert_of_ne {x a : α} {s : set α} : x ∈ insert a s → x ≠ a → x ∈ s := or.resolve_left @[simp] theorem mem_insert_iff {x a : α} {s : set α} : x ∈ insert a s ↔ x = a ∨ x ∈ s := iff.rfl @[simp] theorem insert_eq_of_mem {a : α} {s : set α} (h : a ∈ s) : insert a s = s := ext $ λ x, or_iff_right_of_imp $ λ e, e.symm ▸ h lemma ne_insert_of_not_mem {s : set α} (t : set α) {a : α} : a ∉ s → s ≠ insert a t := mt $ λ e, e.symm ▸ mem_insert _ _ theorem insert_subset : insert a s ⊆ t ↔ (a ∈ t ∧ s ⊆ t) := by simp only [subset_def, or_imp_distrib, forall_and_distrib, forall_eq, mem_insert_iff] theorem insert_subset_insert (h : s ⊆ t) : insert a s ⊆ insert a t := λ x, or.imp_right (@h _) theorem ssubset_iff_insert {s t : set α} : s ⊂ t ↔ ∃ a ∉ s, insert a s ⊆ t := begin simp only [insert_subset, exists_and_distrib_right, ssubset_def, not_subset], simp only [exists_prop, and_comm] end theorem ssubset_insert {s : set α} {a : α} (h : a ∉ s) : s ⊂ insert a s := ssubset_iff_insert.2 ⟨a, h, subset.refl _⟩ theorem insert_comm (a b : α) (s : set α) : insert a (insert b s) = insert b (insert a s) := ext $ λ x, or.left_comm theorem insert_union : insert a s ∪ t = insert a (s ∪ t) := ext $ λ x, or.assoc @[simp] theorem union_insert : s ∪ insert a t = insert a (s ∪ t) := ext $ λ x, or.left_comm theorem insert_nonempty (a : α) (s : set α) : (insert a s).nonempty := ⟨a, mem_insert a s⟩ instance (a : α) (s : set α) : nonempty (insert a s : set α) := (insert_nonempty a s).to_subtype lemma insert_inter (x : α) (s t : set α) : insert x (s ∩ t) = insert x s ∩ insert x t := ext $ λ y, or_and_distrib_left -- useful in proofs by induction theorem forall_of_forall_insert {P : α → Prop} {a : α} {s : set α} (H : ∀ x, x ∈ insert a s → P x) (x) (h : x ∈ s) : P x := H _ (or.inr h) theorem forall_insert_of_forall {P : α → Prop} {a : α} {s : set α} (H : ∀ x, x ∈ s → P x) (ha : P a) (x) (h : x ∈ insert a s) : P x := h.elim (λ e, e.symm ▸ ha) (H _) theorem bex_insert_iff {P : α → Prop} {a : α} {s : set α} : (∃ x ∈ insert a s, P x) ↔ P a ∨ (∃ x ∈ s, P x) := bex_or_left_distrib.trans $ or_congr_left bex_eq_left theorem ball_insert_iff {P : α → Prop} {a : α} {s : set α} : (∀ x ∈ insert a s, P x) ↔ P a ∧ (∀x ∈ s, P x) := ball_or_left_distrib.trans $ and_congr_left' forall_eq /-! ### Lemmas about singletons -/ theorem singleton_def (a : α) : ({a} : set α) = insert a ∅ := (insert_emptyc_eq _).symm @[simp] theorem mem_singleton_iff {a b : α} : a ∈ ({b} : set α) ↔ a = b := iff.rfl @[simp] lemma set_of_eq_eq_singleton {a : α} : {n | n = a} = {a} := ext $ λ n, (set.mem_singleton_iff).symm -- TODO: again, annotation needed @[simp] theorem mem_singleton (a : α) : a ∈ ({a} : set α) := @rfl _ _ theorem eq_of_mem_singleton {x y : α} (h : x ∈ ({y} : set α)) : x = y := h @[simp] theorem singleton_eq_singleton_iff {x y : α} : {x} = ({y} : set α) ↔ x = y := ext_iff.trans eq_iff_eq_cancel_left theorem mem_singleton_of_eq {x y : α} (H : x = y) : x ∈ ({y} : set α) := H theorem insert_eq (x : α) (s : set α) : insert x s = ({x} : set α) ∪ s := rfl @[simp] theorem pair_eq_singleton (a : α) : ({a, a} : set α) = {a} := union_self _ theorem pair_comm (a b : α) : ({a, b} : set α) = {b, a} := union_comm _ _ @[simp] theorem singleton_nonempty (a : α) : ({a} : set α).nonempty := ⟨a, rfl⟩ @[simp] theorem singleton_subset_iff {a : α} {s : set α} : {a} ⊆ s ↔ a ∈ s := forall_eq theorem set_compr_eq_eq_singleton {a : α} : {b | b = a} = {a} := rfl @[simp] theorem singleton_union : {a} ∪ s = insert a s := rfl @[simp] theorem union_singleton : s ∪ {a} = insert a s := union_comm _ _ @[simp] theorem singleton_inter_nonempty : ({a} ∩ s).nonempty ↔ a ∈ s := by simp only [set.nonempty, mem_inter_eq, mem_singleton_iff, exists_eq_left] @[simp] theorem inter_singleton_nonempty : (s ∩ {a}).nonempty ↔ a ∈ s := by rw [inter_comm, singleton_inter_nonempty] @[simp] theorem singleton_inter_eq_empty : {a} ∩ s = ∅ ↔ a ∉ s := not_nonempty_iff_eq_empty.symm.trans $ not_congr singleton_inter_nonempty @[simp] theorem inter_singleton_eq_empty : s ∩ {a} = ∅ ↔ a ∉ s := by rw [inter_comm, singleton_inter_eq_empty] lemma nmem_singleton_empty {s : set α} : s ∉ ({∅} : set (set α)) ↔ s.nonempty := ne_empty_iff_nonempty instance unique_singleton (a : α) : unique ↥({a} : set α) := ⟨⟨⟨a, mem_singleton a⟩⟩, λ ⟨x, h⟩, subtype.eq h⟩ lemma eq_singleton_iff_unique_mem {s : set α} {a : α} : s = {a} ↔ a ∈ s ∧ ∀ x ∈ s, x = a := subset.antisymm_iff.trans $ and.comm.trans $ and_congr_left' singleton_subset_iff lemma eq_singleton_iff_nonempty_unique_mem {s : set α} {a : α} : s = {a} ↔ s.nonempty ∧ ∀ x ∈ s, x = a := eq_singleton_iff_unique_mem.trans $ and_congr_left $ λ H, ⟨λ h', ⟨_, h'⟩, λ ⟨x, h⟩, H x h ▸ h⟩ -- while `simp` is capable of proving this, it is not capable of turning the LHS into the RHS. @[simp] lemma default_coe_singleton (x : α) : default ({x} : set α) = ⟨x, rfl⟩ := rfl /-! ### Lemmas about sets defined as `{x ∈ s | p x}`. -/ theorem mem_sep {s : set α} {p : α → Prop} {x : α} (xs : x ∈ s) (px : p x) : x ∈ {x ∈ s | p x} := ⟨xs, px⟩ @[simp] theorem sep_mem_eq {s t : set α} : {x ∈ s | x ∈ t} = s ∩ t := rfl @[simp] theorem mem_sep_eq {s : set α} {p : α → Prop} {x : α} : x ∈ {x ∈ s | p x} = (x ∈ s ∧ p x) := rfl theorem mem_sep_iff {s : set α} {p : α → Prop} {x : α} : x ∈ {x ∈ s | p x} ↔ x ∈ s ∧ p x := iff.rfl theorem eq_sep_of_subset {s t : set α} (h : s ⊆ t) : s = {x ∈ t | x ∈ s} := (inter_eq_self_of_subset_right h).symm theorem sep_subset (s : set α) (p : α → Prop) : {x ∈ s | p x} ⊆ s := λ x, and.left theorem forall_not_of_sep_empty {s : set α} {p : α → Prop} (H : {x ∈ s | p x} = ∅) (x) : x ∈ s → ¬ p x := not_and.1 (eq_empty_iff_forall_not_mem.1 H x : _) @[simp] lemma sep_univ {α} {p : α → Prop} : {a ∈ (univ : set α) | p a} = {a | p a} := univ_inter _ @[simp] lemma sep_true : {a ∈ s | true} = s := by { ext, simp } @[simp] lemma sep_false : {a ∈ s | false} = ∅ := by { ext, simp } @[simp] lemma subset_singleton_iff {α : Type*} {s : set α} {x : α} : s ⊆ {x} ↔ ∀ y ∈ s, y = x := iff.rfl lemma subset_singleton_iff_eq {s : set α} {x : α} : s ⊆ {x} ↔ s = ∅ ∨ s = {x} := begin obtain (rfl | hs) := s.eq_empty_or_nonempty, use ⟨λ _, or.inl rfl, λ _, empty_subset _⟩, simp [eq_singleton_iff_nonempty_unique_mem, hs, ne_empty_iff_nonempty.2 hs], end lemma ssubset_singleton_iff {s : set α} {x : α} : s ⊂ {x} ↔ s = ∅ := begin rw [ssubset_iff_subset_ne, subset_singleton_iff_eq, or_and_distrib_right, and_not_self, or_false, and_iff_left_iff_imp], rintro rfl, refine ne_comm.1 (ne_empty_iff_nonempty.2 (singleton_nonempty _)), end lemma eq_empty_of_ssubset_singleton {s : set α} {x : α} (hs : s ⊂ {x}) : s = ∅ := ssubset_singleton_iff.1 hs /-! ### Lemmas about complement -/ theorem mem_compl {s : set α} {x : α} (h : x ∉ s) : x ∈ sᶜ := h lemma compl_set_of {α} (p : α → Prop) : {a | p a}ᶜ = { a | ¬ p a } := rfl theorem not_mem_of_mem_compl {s : set α} {x : α} (h : x ∈ sᶜ) : x ∉ s := h @[simp] theorem mem_compl_eq (s : set α) (x : α) : x ∈ sᶜ = (x ∉ s) := rfl theorem mem_compl_iff (s : set α) (x : α) : x ∈ sᶜ ↔ x ∉ s := iff.rfl @[simp] theorem inter_compl_self (s : set α) : s ∩ sᶜ = ∅ := inf_compl_eq_bot @[simp] theorem compl_inter_self (s : set α) : sᶜ ∩ s = ∅ := compl_inf_eq_bot @[simp] theorem compl_empty : (∅ : set α)ᶜ = univ := compl_bot @[simp] theorem compl_union (s t : set α) : (s ∪ t)ᶜ = sᶜ ∩ tᶜ := compl_sup theorem compl_inter (s t : set α) : (s ∩ t)ᶜ = sᶜ ∪ tᶜ := compl_inf @[simp] theorem compl_univ : (univ : set α)ᶜ = ∅ := compl_top @[simp] lemma compl_empty_iff {s : set α} : sᶜ = ∅ ↔ s = univ := compl_eq_bot @[simp] lemma compl_univ_iff {s : set α} : sᶜ = univ ↔ s = ∅ := compl_eq_top lemma nonempty_compl {s : set α} : sᶜ.nonempty ↔ s ≠ univ := ne_empty_iff_nonempty.symm.trans $ not_congr $ compl_empty_iff lemma mem_compl_singleton_iff {a x : α} : x ∈ ({a} : set α)ᶜ ↔ x ≠ a := not_congr mem_singleton_iff lemma compl_singleton_eq (a : α) : ({a} : set α)ᶜ = {x | x ≠ a} := ext $ λ x, mem_compl_singleton_iff @[simp] lemma compl_ne_eq_singleton (a : α) : ({x | x ≠ a} : set α)ᶜ = {a} := by { ext, simp, } theorem union_eq_compl_compl_inter_compl (s t : set α) : s ∪ t = (sᶜ ∩ tᶜ)ᶜ := ext $ λ x, or_iff_not_and_not theorem inter_eq_compl_compl_union_compl (s t : set α) : s ∩ t = (sᶜ ∪ tᶜ)ᶜ := ext $ λ x, and_iff_not_or_not @[simp] theorem union_compl_self (s : set α) : s ∪ sᶜ = univ := eq_univ_iff_forall.2 $ λ x, em _ @[simp] theorem compl_union_self (s : set α) : sᶜ ∪ s = univ := by rw [union_comm, union_compl_self] theorem compl_comp_compl : compl ∘ compl = @id (set α) := funext compl_compl theorem compl_subset_comm {s t : set α} : sᶜ ⊆ t ↔ tᶜ ⊆ s := @compl_le_iff_compl_le _ s t _ @[simp] lemma compl_subset_compl {s t : set α} : sᶜ ⊆ tᶜ ↔ t ⊆ s := @compl_le_compl_iff_le _ t s _ theorem compl_subset_iff_union {s t : set α} : sᶜ ⊆ t ↔ s ∪ t = univ := iff.symm $ eq_univ_iff_forall.trans $ forall_congr $ λ a, or_iff_not_imp_left theorem subset_compl_comm {s t : set α} : s ⊆ tᶜ ↔ t ⊆ sᶜ := forall_congr $ λ a, imp_not_comm theorem subset_compl_iff_disjoint {s t : set α} : s ⊆ tᶜ ↔ s ∩ t = ∅ := iff.trans (forall_congr $ λ a, and_imp.symm) subset_empty_iff lemma subset_compl_singleton_iff {a : α} {s : set α} : s ⊆ {a}ᶜ ↔ a ∉ s := subset_compl_comm.trans singleton_subset_iff theorem inter_subset (a b c : set α) : a ∩ b ⊆ c ↔ a ⊆ bᶜ ∪ c := forall_congr $ λ x, and_imp.trans $ imp_congr_right $ λ _, imp_iff_not_or lemma inter_compl_nonempty_iff {s t : set α} : (s ∩ tᶜ).nonempty ↔ ¬ s ⊆ t := (not_subset.trans $ exists_congr $ by exact λ x, by simp [mem_compl]).symm /-! ### Lemmas about set difference -/ theorem diff_eq (s t : set α) : s \ t = s ∩ tᶜ := rfl @[simp] theorem mem_diff {s t : set α} (x : α) : x ∈ s \ t ↔ x ∈ s ∧ x ∉ t := iff.rfl theorem mem_diff_of_mem {s t : set α} {x : α} (h1 : x ∈ s) (h2 : x ∉ t) : x ∈ s \ t := ⟨h1, h2⟩ theorem mem_of_mem_diff {s t : set α} {x : α} (h : x ∈ s \ t) : x ∈ s := h.left theorem not_mem_of_mem_diff {s t : set α} {x : α} (h : x ∈ s \ t) : x ∉ t := h.right theorem diff_eq_compl_inter {s t : set α} : s \ t = tᶜ ∩ s := by rw [diff_eq, inter_comm] theorem nonempty_diff {s t : set α} : (s \ t).nonempty ↔ ¬ (s ⊆ t) := inter_compl_nonempty_iff theorem diff_subset (s t : set α) : s \ t ⊆ s := show s \ t ≤ s, from sdiff_le theorem union_diff_cancel' {s t u : set α} (h₁ : s ⊆ t) (h₂ : t ⊆ u) : t ∪ (u \ s) = u := sup_sdiff_cancel' h₁ h₂ theorem union_diff_cancel {s t : set α} (h : s ⊆ t) : s ∪ (t \ s) = t := sup_sdiff_of_le h theorem union_diff_cancel_left {s t : set α} (h : s ∩ t ⊆ ∅) : (s ∪ t) \ s = t := disjoint.sup_sdiff_cancel_left h theorem union_diff_cancel_right {s t : set α} (h : s ∩ t ⊆ ∅) : (s ∪ t) \ t = s := disjoint.sup_sdiff_cancel_right h @[simp] theorem union_diff_left {s t : set α} : (s ∪ t) \ s = t \ s := sup_sdiff_left_self @[simp] theorem union_diff_right {s t : set α} : (s ∪ t) \ t = s \ t := sup_sdiff_right_self theorem union_diff_distrib {s t u : set α} : (s ∪ t) \ u = s \ u ∪ t \ u := sup_sdiff theorem inter_diff_assoc (a b c : set α) : (a ∩ b) \ c = a ∩ (b \ c) := inf_sdiff_assoc @[simp] theorem inter_diff_self (a b : set α) : a ∩ (b \ a) = ∅ := inf_sdiff_self_right @[simp] theorem inter_union_diff (s t : set α) : (s ∩ t) ∪ (s \ t) = s := sup_inf_sdiff s t @[simp] lemma diff_union_inter (s t : set α) : (s \ t) ∪ (s ∩ t) = s := by { rw union_comm, exact sup_inf_sdiff _ _ } @[simp] theorem inter_union_compl (s t : set α) : (s ∩ t) ∪ (s ∩ tᶜ) = s := inter_union_diff _ _ theorem diff_subset_diff {s₁ s₂ t₁ t₂ : set α} : s₁ ⊆ s₂ → t₂ ⊆ t₁ → s₁ \ t₁ ⊆ s₂ \ t₂ := show s₁ ≤ s₂ → t₂ ≤ t₁ → s₁ \ t₁ ≤ s₂ \ t₂, from sdiff_le_sdiff theorem diff_subset_diff_left {s₁ s₂ t : set α} (h : s₁ ⊆ s₂) : s₁ \ t ⊆ s₂ \ t := sdiff_le_self_sdiff ‹s₁ ≤ s₂› theorem diff_subset_diff_right {s t u : set α} (h : t ⊆ u) : s \ u ⊆ s \ t := sdiff_le_sdiff_self ‹t ≤ u› theorem compl_eq_univ_diff (s : set α) : sᶜ = univ \ s := top_sdiff.symm @[simp] lemma empty_diff (s : set α) : (∅ \ s : set α) = ∅ := bot_sdiff theorem diff_eq_empty {s t : set α} : s \ t = ∅ ↔ s ⊆ t := sdiff_eq_bot_iff @[simp] theorem diff_empty {s : set α} : s \ ∅ = s := sdiff_bot @[simp] lemma diff_univ (s : set α) : s \ univ = ∅ := diff_eq_empty.2 (subset_univ s) theorem diff_diff {u : set α} : s \ t \ u = s \ (t ∪ u) := sdiff_sdiff_left -- the following statement contains parentheses to help the reader lemma diff_diff_comm {s t u : set α} : (s \ t) \ u = (s \ u) \ t := sdiff_sdiff_comm lemma diff_subset_iff {s t u : set α} : s \ t ⊆ u ↔ s ⊆ t ∪ u := show s \ t ≤ u ↔ s ≤ t ∪ u, from sdiff_le_iff lemma subset_diff_union (s t : set α) : s ⊆ (s \ t) ∪ t := show s ≤ (s \ t) ∪ t, from le_sdiff_sup lemma diff_union_of_subset {s t : set α} (h : t ⊆ s) : (s \ t) ∪ t = s := subset.antisymm (union_subset (diff_subset _ _) h) (subset_diff_union _ _) @[simp] lemma diff_singleton_subset_iff {x : α} {s t : set α} : s \ {x} ⊆ t ↔ s ⊆ insert x t := by { rw [←union_singleton, union_comm], apply diff_subset_iff } lemma subset_diff_singleton {x : α} {s t : set α} (h : s ⊆ t) (hx : x ∉ s) : s ⊆ t \ {x} := subset_inter h $ subset_compl_comm.1 $ singleton_subset_iff.2 hx lemma subset_insert_diff_singleton (x : α) (s : set α) : s ⊆ insert x (s \ {x}) := by rw [←diff_singleton_subset_iff] lemma diff_subset_comm {s t u : set α} : s \ t ⊆ u ↔ s \ u ⊆ t := show s \ t ≤ u ↔ s \ u ≤ t, from sdiff_le_comm lemma diff_inter {s t u : set α} : s \ (t ∩ u) = (s \ t) ∪ (s \ u) := sdiff_inf lemma diff_inter_diff {s t u : set α} : s \ t ∩ (s \ u) = s \ (t ∪ u) := sdiff_sup.symm lemma diff_compl : s \ tᶜ = s ∩ t := sdiff_compl lemma diff_diff_right {s t u : set α} : s \ (t \ u) = (s \ t) ∪ (s ∩ u) := sdiff_sdiff_right' @[simp] theorem insert_diff_of_mem (s) (h : a ∈ t) : insert a s \ t = s \ t := by { ext, split; simp [or_imp_distrib, h] {contextual := tt} } theorem insert_diff_of_not_mem (s) (h : a ∉ t) : insert a s \ t = insert a (s \ t) := begin classical, ext x, by_cases h' : x ∈ t, { have : x ≠ a, { assume H, rw H at h', exact h h' }, simp [h, h', this] }, { simp [h, h'] } end lemma insert_diff_self_of_not_mem {a : α} {s : set α} (h : a ∉ s) : insert a s \ {a} = s := by { ext, simp [and_iff_left_of_imp (λ hx : x ∈ s, show x ≠ a, from λ hxa, h $ hxa ▸ hx)] } lemma insert_inter_of_mem {s₁ s₂ : set α} {a : α} (h : a ∈ s₂) : insert a s₁ ∩ s₂ = insert a (s₁ ∩ s₂) := by simp [set.insert_inter, h] lemma insert_inter_of_not_mem {s₁ s₂ : set α} {a : α} (h : a ∉ s₂) : insert a s₁ ∩ s₂ = s₁ ∩ s₂ := begin ext x, simp only [mem_inter_iff, mem_insert_iff, mem_inter_eq, and.congr_left_iff, or_iff_right_iff_imp], cc, end @[simp] theorem union_diff_self {s t : set α} : s ∪ (t \ s) = s ∪ t := sup_sdiff_self_right @[simp] theorem diff_union_self {s t : set α} : (s \ t) ∪ t = s ∪ t := sup_sdiff_self_left theorem diff_inter_self {a b : set α} : (b \ a) ∩ a = ∅ := inf_sdiff_self_left theorem diff_inter_self_eq_diff {s t : set α} : s \ (t ∩ s) = s \ t := sdiff_inf_self_right theorem diff_self_inter {s t : set α} : s \ (s ∩ t) = s \ t := sdiff_inf_self_left theorem diff_eq_self {s t : set α} : s \ t = s ↔ t ∩ s ⊆ ∅ := show s \ t = s ↔ t ⊓ s ≤ ⊥, from sdiff_eq_self_iff_disjoint @[simp] theorem diff_singleton_eq_self {a : α} {s : set α} (h : a ∉ s) : s \ {a} = s := diff_eq_self.2 $ by simp [singleton_inter_eq_empty.2 h] @[simp] theorem insert_diff_singleton {a : α} {s : set α} : insert a (s \ {a}) = insert a s := by simp [insert_eq, union_diff_self, -union_singleton, -singleton_union] @[simp] lemma diff_self {s : set α} : s \ s = ∅ := sdiff_self lemma diff_diff_cancel_left {s t : set α} (h : s ⊆ t) : t \ (t \ s) = s := sdiff_sdiff_eq_self h lemma mem_diff_singleton {x y : α} {s : set α} : x ∈ s \ {y} ↔ (x ∈ s ∧ x ≠ y) := iff.rfl lemma mem_diff_singleton_empty {s : set α} {t : set (set α)} : s ∈ t \ {∅} ↔ (s ∈ t ∧ s.nonempty) := mem_diff_singleton.trans $ and_congr iff.rfl ne_empty_iff_nonempty lemma union_eq_diff_union_diff_union_inter (s t : set α) : s ∪ t = (s \ t) ∪ (t \ s) ∪ (s ∩ t) := sup_eq_sdiff_sup_sdiff_sup_inf /-! ### Powerset -/ theorem mem_powerset {x s : set α} (h : x ⊆ s) : x ∈ powerset s := h theorem subset_of_mem_powerset {x s : set α} (h : x ∈ powerset s) : x ⊆ s := h @[simp] theorem mem_powerset_iff (x s : set α) : x ∈ powerset s ↔ x ⊆ s := iff.rfl theorem powerset_inter (s t : set α) : 𝒫 (s ∩ t) = 𝒫 s ∩ 𝒫 t := ext $ λ u, subset_inter_iff @[simp] theorem powerset_mono : 𝒫 s ⊆ 𝒫 t ↔ s ⊆ t := ⟨λ h, h (subset.refl s), λ h u hu, subset.trans hu h⟩ theorem monotone_powerset : monotone (powerset : set α → set (set α)) := λ s t, powerset_mono.2 @[simp] theorem powerset_nonempty : (𝒫 s).nonempty := ⟨∅, empty_subset s⟩ @[simp] theorem powerset_empty : 𝒫 (∅ : set α) = {∅} := ext $ λ s, subset_empty_iff @[simp] theorem powerset_univ : 𝒫 (univ : set α) = univ := eq_univ_of_forall subset_univ /-! ### If-then-else for sets -/ /-- `ite` for sets: `set.ite t s s' ∩ t = s ∩ t`, `set.ite t s s' ∩ tᶜ = s' ∩ tᶜ`. Defined as `s ∩ t ∪ s' \ t`. -/ protected def ite (t s s' : set α) : set α := s ∩ t ∪ s' \ t @[simp] lemma ite_inter_self (t s s' : set α) : t.ite s s' ∩ t = s ∩ t := by rw [set.ite, union_inter_distrib_right, diff_inter_self, inter_assoc, inter_self, union_empty] @[simp] lemma ite_compl (t s s' : set α) : tᶜ.ite s s' = t.ite s' s := by rw [set.ite, set.ite, diff_compl, union_comm, diff_eq] @[simp] lemma ite_inter_compl_self (t s s' : set α) : t.ite s s' ∩ tᶜ = s' ∩ tᶜ := by rw [← ite_compl, ite_inter_self] @[simp] lemma ite_diff_self (t s s' : set α) : t.ite s s' \ t = s' \ t := ite_inter_compl_self t s s' @[simp] lemma ite_same (t s : set α) : t.ite s s = s := inter_union_diff _ _ @[simp] lemma ite_left (s t : set α) : s.ite s t = s ∪ t := by simp [set.ite] @[simp] lemma ite_right (s t : set α) : s.ite t s = t ∩ s := by simp [set.ite] @[simp] lemma ite_empty (s s' : set α) : set.ite ∅ s s' = s' := by simp [set.ite] @[simp] lemma ite_univ (s s' : set α) : set.ite univ s s' = s := by simp [set.ite] @[simp] lemma ite_empty_left (t s : set α) : t.ite ∅ s = s \ t := by simp [set.ite] @[simp] lemma ite_empty_right (t s : set α) : t.ite s ∅ = s ∩ t := by simp [set.ite] lemma ite_mono (t : set α) {s₁ s₁' s₂ s₂' : set α} (h : s₁ ⊆ s₂) (h' : s₁' ⊆ s₂') : t.ite s₁ s₁' ⊆ t.ite s₂ s₂' := union_subset_union (inter_subset_inter_left _ h) (inter_subset_inter_left _ h') lemma ite_subset_union (t s s' : set α) : t.ite s s' ⊆ s ∪ s' := union_subset_union (inter_subset_left _ _) (diff_subset _ _) lemma inter_subset_ite (t s s' : set α) : s ∩ s' ⊆ t.ite s s' := ite_same t (s ∩ s') ▸ ite_mono _ (inter_subset_left _ _) (inter_subset_right _ _) lemma ite_inter_inter (t s₁ s₂ s₁' s₂' : set α) : t.ite (s₁ ∩ s₂) (s₁' ∩ s₂') = t.ite s₁ s₁' ∩ t.ite s₂ s₂' := by { ext x, finish [set.ite, iff_def] } lemma ite_inter (t s₁ s₂ s : set α) : t.ite (s₁ ∩ s) (s₂ ∩ s) = t.ite s₁ s₂ ∩ s := by rw [ite_inter_inter, ite_same] lemma ite_inter_of_inter_eq (t : set α) {s₁ s₂ s : set α} (h : s₁ ∩ s = s₂ ∩ s) : t.ite s₁ s₂ ∩ s = s₁ ∩ s := by rw [← ite_inter, ← h, ite_same] lemma subset_ite {t s s' u : set α} : u ⊆ t.ite s s' ↔ u ∩ t ⊆ s ∧ u \ t ⊆ s' := begin simp only [subset_def, ← forall_and_distrib], refine forall_congr (λ x, _), by_cases hx : x ∈ t; simp [*, set.ite] end /-! ### Inverse image -/ /-- The preimage of `s : set β` by `f : α → β`, written `f ⁻¹' s`, is the set of `x : α` such that `f x ∈ s`. -/ def preimage {α : Type u} {β : Type v} (f : α → β) (s : set β) : set α := {x | f x ∈ s} infix ` ⁻¹' `:80 := preimage section preimage variables {f : α → β} {g : β → γ} @[simp] theorem preimage_empty : f ⁻¹' ∅ = ∅ := rfl @[simp] theorem mem_preimage {s : set β} {a : α} : (a ∈ f ⁻¹' s) ↔ (f a ∈ s) := iff.rfl lemma preimage_congr {f g : α → β} {s : set β} (h : ∀ (x : α), f x = g x) : f ⁻¹' s = g ⁻¹' s := by { congr' with x, apply_assumption } theorem preimage_mono {s t : set β} (h : s ⊆ t) : f ⁻¹' s ⊆ f ⁻¹' t := assume x hx, h hx @[simp] theorem preimage_univ : f ⁻¹' univ = univ := rfl theorem subset_preimage_univ {s : set α} : s ⊆ f ⁻¹' univ := subset_univ _ @[simp] theorem preimage_inter {s t : set β} : f ⁻¹' (s ∩ t) = f ⁻¹' s ∩ f ⁻¹' t := rfl @[simp] theorem preimage_union {s t : set β} : f ⁻¹' (s ∪ t) = f ⁻¹' s ∪ f ⁻¹' t := rfl @[simp] theorem preimage_compl {s : set β} : f ⁻¹' sᶜ = (f ⁻¹' s)ᶜ := rfl @[simp] theorem preimage_diff (f : α → β) (s t : set β) : f ⁻¹' (s \ t) = f ⁻¹' s \ f ⁻¹' t := rfl @[simp] theorem preimage_ite (f : α → β) (s t₁ t₂ : set β) : f ⁻¹' (s.ite t₁ t₂) = (f ⁻¹' s).ite (f ⁻¹' t₁) (f ⁻¹' t₂) := rfl @[simp] theorem preimage_set_of_eq {p : α → Prop} {f : β → α} : f ⁻¹' {a | p a} = {a | p (f a)} := rfl @[simp] theorem preimage_id {s : set α} : id ⁻¹' s = s := rfl @[simp] theorem preimage_id' {s : set α} : (λ x, x) ⁻¹' s = s := rfl @[simp] theorem preimage_const_of_mem {b : β} {s : set β} (h : b ∈ s) : (λ (x : α), b) ⁻¹' s = univ := eq_univ_of_forall $ λ x, h @[simp] theorem preimage_const_of_not_mem {b : β} {s : set β} (h : b ∉ s) : (λ (x : α), b) ⁻¹' s = ∅ := eq_empty_of_subset_empty $ λ x hx, h hx theorem preimage_const (b : β) (s : set β) [decidable (b ∈ s)] : (λ (x : α), b) ⁻¹' s = if b ∈ s then univ else ∅ := by { split_ifs with hb hb, exacts [preimage_const_of_mem hb, preimage_const_of_not_mem hb] } theorem preimage_comp {s : set γ} : (g ∘ f) ⁻¹' s = f ⁻¹' (g ⁻¹' s) := rfl lemma preimage_preimage {g : β → γ} {f : α → β} {s : set γ} : f ⁻¹' (g ⁻¹' s) = (λ x, g (f x)) ⁻¹' s := preimage_comp.symm theorem eq_preimage_subtype_val_iff {p : α → Prop} {s : set (subtype p)} {t : set α} : s = subtype.val ⁻¹' t ↔ (∀x (h : p x), (⟨x, h⟩ : subtype p) ∈ s ↔ x ∈ t) := ⟨assume s_eq x h, by { rw [s_eq], simp }, assume h, ext $ λ ⟨x, hx⟩, by simp [h]⟩ lemma preimage_coe_coe_diagonal {α : Type*} (s : set α) : (prod.map coe coe) ⁻¹' (diagonal α) = diagonal s := begin ext ⟨⟨x, x_in⟩, ⟨y, y_in⟩⟩, simp [set.diagonal], end end preimage /-! ### Image of a set under a function -/ section image infix ` '' `:80 := image theorem mem_image_iff_bex {f : α → β} {s : set α} {y : β} : y ∈ f '' s ↔ ∃ x (_ : x ∈ s), f x = y := bex_def.symm theorem mem_image_eq (f : α → β) (s : set α) (y: β) : y ∈ f '' s = ∃ x, x ∈ s ∧ f x = y := rfl @[simp] theorem mem_image (f : α → β) (s : set α) (y : β) : y ∈ f '' s ↔ ∃ x, x ∈ s ∧ f x = y := iff.rfl lemma image_eta (f : α → β) : f '' s = (λ x, f x) '' s := rfl theorem mem_image_of_mem (f : α → β) {x : α} {a : set α} (h : x ∈ a) : f x ∈ f '' a := ⟨_, h, rfl⟩ theorem mem_image_of_injective {f : α → β} {a : α} {s : set α} (hf : injective f) : f a ∈ f '' s ↔ a ∈ s := iff.intro (assume ⟨b, hb, eq⟩, (hf eq) ▸ hb) (assume h, mem_image_of_mem _ h) theorem ball_image_iff {f : α → β} {s : set α} {p : β → Prop} : (∀ y ∈ f '' s, p y) ↔ (∀ x ∈ s, p (f x)) := by simp theorem ball_image_of_ball {f : α → β} {s : set α} {p : β → Prop} (h : ∀ x ∈ s, p (f x)) : ∀ y ∈ f '' s, p y := ball_image_iff.2 h theorem bex_image_iff {f : α → β} {s : set α} {p : β → Prop} : (∃ y ∈ f '' s, p y) ↔ (∃ x ∈ s, p (f x)) := by simp theorem mem_image_elim {f : α → β} {s : set α} {C : β → Prop} (h : ∀ (x : α), x ∈ s → C (f x)) : ∀{y : β}, y ∈ f '' s → C y | ._ ⟨a, a_in, rfl⟩ := h a a_in theorem mem_image_elim_on {f : α → β} {s : set α} {C : β → Prop} {y : β} (h_y : y ∈ f '' s) (h : ∀ (x : α), x ∈ s → C (f x)) : C y := mem_image_elim h h_y @[congr] lemma image_congr {f g : α → β} {s : set α} (h : ∀a∈s, f a = g a) : f '' s = g '' s := by safe [ext_iff, iff_def] /-- A common special case of `image_congr` -/ lemma image_congr' {f g : α → β} {s : set α} (h : ∀ (x : α), f x = g x) : f '' s = g '' s := image_congr (λx _, h x) theorem image_comp (f : β → γ) (g : α → β) (a : set α) : (f ∘ g) '' a = f '' (g '' a) := subset.antisymm (ball_image_of_ball $ assume a ha, mem_image_of_mem _ $ mem_image_of_mem _ ha) (ball_image_of_ball $ ball_image_of_ball $ assume a ha, mem_image_of_mem _ ha) /-- A variant of `image_comp`, useful for rewriting -/ lemma image_image (g : β → γ) (f : α → β) (s : set α) : g '' (f '' s) = (λ x, g (f x)) '' s := (image_comp g f s).symm /-- Image is monotone with respect to `⊆`. See `set.monotone_image` for the statement in terms of `≤`. -/ theorem image_subset {a b : set α} (f : α → β) (h : a ⊆ b) : f '' a ⊆ f '' b := by finish [subset_def, mem_image_eq] theorem image_union (f : α → β) (s t : set α) : f '' (s ∪ t) = f '' s ∪ f '' t := ext $ λ x, ⟨by rintro ⟨a, h|h, rfl⟩; [left, right]; exact ⟨_, h, rfl⟩, by rintro (⟨a, h, rfl⟩ | ⟨a, h, rfl⟩); refine ⟨_, _, rfl⟩; [left, right]; exact h⟩ @[simp] theorem image_empty (f : α → β) : f '' ∅ = ∅ := by { ext, simp } lemma image_inter_subset (f : α → β) (s t : set α) : f '' (s ∩ t) ⊆ f '' s ∩ f '' t := subset_inter (image_subset _ $ inter_subset_left _ _) (image_subset _ $ inter_subset_right _ _) theorem image_inter_on {f : α → β} {s t : set α} (h : ∀x∈t, ∀y∈s, f x = f y → x = y) : f '' s ∩ f '' t = f '' (s ∩ t) := subset.antisymm (assume b ⟨⟨a₁, ha₁, h₁⟩, ⟨a₂, ha₂, h₂⟩⟩, have a₂ = a₁, from h _ ha₂ _ ha₁ (by simp *), ⟨a₁, ⟨ha₁, this ▸ ha₂⟩, h₁⟩) (image_inter_subset _ _ _) theorem image_inter {f : α → β} {s t : set α} (H : injective f) : f '' s ∩ f '' t = f '' (s ∩ t) := image_inter_on (assume x _ y _ h, H h) theorem image_univ_of_surjective {ι : Type*} {f : ι → β} (H : surjective f) : f '' univ = univ := eq_univ_of_forall $ by { simpa [image] } @[simp] theorem image_singleton {f : α → β} {a : α} : f '' {a} = {f a} := by { ext, simp [image, eq_comm] } @[simp] theorem nonempty.image_const {s : set α} (hs : s.nonempty) (a : β) : (λ _, a) '' s = {a} := ext $ λ x, ⟨λ ⟨y, _, h⟩, h ▸ mem_singleton _, λ h, (eq_of_mem_singleton h).symm ▸ hs.imp (λ y hy, ⟨hy, rfl⟩)⟩ @[simp] lemma image_eq_empty {α β} {f : α → β} {s : set α} : f '' s = ∅ ↔ s = ∅ := by { simp only [eq_empty_iff_forall_not_mem], exact ⟨λ H a ha, H _ ⟨_, ha, rfl⟩, λ H b ⟨_, ha, _⟩, H _ ha⟩ } -- TODO(Jeremy): there is an issue with - t unfolding to compl t theorem mem_compl_image (t : set α) (S : set (set α)) : t ∈ compl '' S ↔ tᶜ ∈ S := begin suffices : ∀ x, xᶜ = t ↔ tᶜ = x, { simp [this] }, intro x, split; { intro e, subst e, simp } end /-- A variant of `image_id` -/ @[simp] lemma image_id' (s : set α) : (λx, x) '' s = s := by { ext, simp } theorem image_id (s : set α) : id '' s = s := by simp theorem compl_compl_image (S : set (set α)) : compl '' (compl '' S) = S := by rw [← image_comp, compl_comp_compl, image_id] theorem image_insert_eq {f : α → β} {a : α} {s : set α} : f '' (insert a s) = insert (f a) (f '' s) := by { ext, simp [and_or_distrib_left, exists_or_distrib, eq_comm, or_comm, and_comm] } theorem image_pair (f : α → β) (a b : α) : f '' {a, b} = {f a, f b} := by simp only [image_insert_eq, image_singleton] theorem image_subset_preimage_of_inverse {f : α → β} {g : β → α} (I : left_inverse g f) (s : set α) : f '' s ⊆ g ⁻¹' s := λ b ⟨a, h, e⟩, e ▸ ((I a).symm ▸ h : g (f a) ∈ s) theorem preimage_subset_image_of_inverse {f : α → β} {g : β → α} (I : left_inverse g f) (s : set β) : f ⁻¹' s ⊆ g '' s := λ b h, ⟨f b, h, I b⟩ theorem image_eq_preimage_of_inverse {f : α → β} {g : β → α} (h₁ : left_inverse g f) (h₂ : right_inverse g f) : image f = preimage g := funext $ λ s, subset.antisymm (image_subset_preimage_of_inverse h₁ s) (preimage_subset_image_of_inverse h₂ s) theorem mem_image_iff_of_inverse {f : α → β} {g : β → α} {b : β} {s : set α} (h₁ : left_inverse g f) (h₂ : right_inverse g f) : b ∈ f '' s ↔ g b ∈ s := by rw image_eq_preimage_of_inverse h₁ h₂; refl theorem image_compl_subset {f : α → β} {s : set α} (H : injective f) : f '' sᶜ ⊆ (f '' s)ᶜ := subset_compl_iff_disjoint.2 $ by simp [image_inter H] theorem subset_image_compl {f : α → β} {s : set α} (H : surjective f) : (f '' s)ᶜ ⊆ f '' sᶜ := compl_subset_iff_union.2 $ by { rw ← image_union, simp [image_univ_of_surjective H] } theorem image_compl_eq {f : α → β} {s : set α} (H : bijective f) : f '' sᶜ = (f '' s)ᶜ := subset.antisymm (image_compl_subset H.1) (subset_image_compl H.2) theorem subset_image_diff (f : α → β) (s t : set α) : f '' s \ f '' t ⊆ f '' (s \ t) := begin rw [diff_subset_iff, ← image_union, union_diff_self], exact image_subset f (subset_union_right t s) end theorem image_diff {f : α → β} (hf : injective f) (s t : set α) : f '' (s \ t) = f '' s \ f '' t := subset.antisymm (subset.trans (image_inter_subset _ _ _) $ inter_subset_inter_right _ $ image_compl_subset hf) (subset_image_diff f s t) lemma nonempty.image (f : α → β) {s : set α} : s.nonempty → (f '' s).nonempty | ⟨x, hx⟩ := ⟨f x, mem_image_of_mem f hx⟩ lemma nonempty.of_image {f : α → β} {s : set α} : (f '' s).nonempty → s.nonempty | ⟨y, x, hx, _⟩ := ⟨x, hx⟩ @[simp] lemma nonempty_image_iff {f : α → β} {s : set α} : (f '' s).nonempty ↔ s.nonempty := ⟨nonempty.of_image, λ h, h.image f⟩ lemma nonempty.preimage {s : set β} (hs : s.nonempty) {f : α → β} (hf : surjective f) : (f ⁻¹' s).nonempty := let ⟨y, hy⟩ := hs, ⟨x, hx⟩ := hf y in ⟨x, mem_preimage.2 $ hx.symm ▸ hy⟩ instance (f : α → β) (s : set α) [nonempty s] : nonempty (f '' s) := (set.nonempty.image f nonempty_of_nonempty_subtype).to_subtype /-- image and preimage are a Galois connection -/ @[simp] theorem image_subset_iff {s : set α} {t : set β} {f : α → β} : f '' s ⊆ t ↔ s ⊆ f ⁻¹' t := ball_image_iff theorem image_preimage_subset (f : α → β) (s : set β) : f '' (f ⁻¹' s) ⊆ s := image_subset_iff.2 (subset.refl _) theorem subset_preimage_image (f : α → β) (s : set α) : s ⊆ f ⁻¹' (f '' s) := λ x, mem_image_of_mem f theorem preimage_image_eq {f : α → β} (s : set α) (h : injective f) : f ⁻¹' (f '' s) = s := subset.antisymm (λ x ⟨y, hy, e⟩, h e ▸ hy) (subset_preimage_image f s) theorem image_preimage_eq {f : α → β} (s : set β) (h : surjective f) : f '' (f ⁻¹' s) = s := subset.antisymm (image_preimage_subset f s) (λ x hx, let ⟨y, e⟩ := h x in ⟨y, (e.symm ▸ hx : f y ∈ s), e⟩) lemma preimage_eq_preimage {f : β → α} (hf : surjective f) : f ⁻¹' s = f ⁻¹' t ↔ s = t := iff.intro (assume eq, by rw [← image_preimage_eq s hf, ← image_preimage_eq t hf, eq]) (assume eq, eq ▸ rfl) lemma image_inter_preimage (f : α → β) (s : set α) (t : set β) : f '' (s ∩ f ⁻¹' t) = f '' s ∩ t := begin apply subset.antisymm, { calc f '' (s ∩ f ⁻¹' t) ⊆ f '' s ∩ (f '' (f⁻¹' t)) : image_inter_subset _ _ _ ... ⊆ f '' s ∩ t : inter_subset_inter_right _ (image_preimage_subset f t) }, { rintros _ ⟨⟨x, h', rfl⟩, h⟩, exact ⟨x, ⟨h', h⟩, rfl⟩ } end lemma image_preimage_inter (f : α → β) (s : set α) (t : set β) : f '' (f ⁻¹' t ∩ s) = t ∩ f '' s := by simp only [inter_comm, image_inter_preimage] @[simp] lemma image_inter_nonempty_iff {f : α → β} {s : set α} {t : set β} : (f '' s ∩ t).nonempty ↔ (s ∩ f ⁻¹' t).nonempty := by rw [←image_inter_preimage, nonempty_image_iff] lemma image_diff_preimage {f : α → β} {s : set α} {t : set β} : f '' (s \ f ⁻¹' t) = f '' s \ t := by simp_rw [diff_eq, ← preimage_compl, image_inter_preimage] theorem compl_image : image (compl : set α → set α) = preimage compl := image_eq_preimage_of_inverse compl_compl compl_compl theorem compl_image_set_of {p : set α → Prop} : compl '' {s | p s} = {s | p sᶜ} := congr_fun compl_image p theorem inter_preimage_subset (s : set α) (t : set β) (f : α → β) : s ∩ f ⁻¹' t ⊆ f ⁻¹' (f '' s ∩ t) := λ x h, ⟨mem_image_of_mem _ h.left, h.right⟩ theorem union_preimage_subset (s : set α) (t : set β) (f : α → β) : s ∪ f ⁻¹' t ⊆ f ⁻¹' (f '' s ∪ t) := λ x h, or.elim h (λ l, or.inl $ mem_image_of_mem _ l) (λ r, or.inr r) theorem subset_image_union (f : α → β) (s : set α) (t : set β) : f '' (s ∪ f ⁻¹' t) ⊆ f '' s ∪ t := image_subset_iff.2 (union_preimage_subset _ _ _) lemma preimage_subset_iff {A : set α} {B : set β} {f : α → β} : f⁻¹' B ⊆ A ↔ (∀ a : α, f a ∈ B → a ∈ A) := iff.rfl lemma image_eq_image {f : α → β} (hf : injective f) : f '' s = f '' t ↔ s = t := iff.symm $ iff.intro (assume eq, eq ▸ rfl) $ assume eq, by rw [← preimage_image_eq s hf, ← preimage_image_eq t hf, eq] lemma image_subset_image_iff {f : α → β} (hf : injective f) : f '' s ⊆ f '' t ↔ s ⊆ t := begin refine (iff.symm $ iff.intro (image_subset f) $ assume h, _), rw [← preimage_image_eq s hf, ← preimage_image_eq t hf], exact preimage_mono h end lemma prod_quotient_preimage_eq_image [s : setoid α] (g : quotient s → β) {h : α → β} (Hh : h = g ∘ quotient.mk) (r : set (β × β)) : {x : quotient s × quotient s | (g x.1, g x.2) ∈ r} = (λ a : α × α, (⟦a.1⟧, ⟦a.2⟧)) '' ((λ a : α × α, (h a.1, h a.2)) ⁻¹' r) := Hh.symm ▸ set.ext (λ ⟨a₁, a₂⟩, ⟨quotient.induction_on₂ a₁ a₂ (λ a₁ a₂ h, ⟨(a₁, a₂), h, rfl⟩), λ ⟨⟨b₁, b₂⟩, h₁, h₂⟩, show (g a₁, g a₂) ∈ r, from have h₃ : ⟦b₁⟧ = a₁ ∧ ⟦b₂⟧ = a₂ := prod.ext_iff.1 h₂, h₃.1 ▸ h₃.2 ▸ h₁⟩) /-- Restriction of `f` to `s` factors through `s.image_factorization f : s → f '' s`. -/ def image_factorization (f : α → β) (s : set α) : s → f '' s := λ p, ⟨f p.1, mem_image_of_mem f p.2⟩ lemma image_factorization_eq {f : α → β} {s : set α} : subtype.val ∘ image_factorization f s = f ∘ subtype.val := funext $ λ p, rfl lemma surjective_onto_image {f : α → β} {s : set α} : surjective (image_factorization f s) := λ ⟨_, ⟨a, ha, rfl⟩⟩, ⟨⟨a, ha⟩, rfl⟩ end image /-! ### Subsingleton -/ /-- A set `s` is a `subsingleton`, if it has at most one element. -/ protected def subsingleton (s : set α) : Prop := ∀ ⦃x⦄ (hx : x ∈ s) ⦃y⦄ (hy : y ∈ s), x = y lemma subsingleton.mono (ht : t.subsingleton) (hst : s ⊆ t) : s.subsingleton := λ x hx y hy, ht (hst hx) (hst hy) lemma subsingleton.image (hs : s.subsingleton) (f : α → β) : (f '' s).subsingleton := λ _ ⟨x, hx, Hx⟩ _ ⟨y, hy, Hy⟩, Hx ▸ Hy ▸ congr_arg f (hs hx hy) lemma subsingleton.eq_singleton_of_mem (hs : s.subsingleton) {x:α} (hx : x ∈ s) : s = {x} := ext $ λ y, ⟨λ hy, (hs hx hy) ▸ mem_singleton _, λ hy, (eq_of_mem_singleton hy).symm ▸ hx⟩ @[simp] lemma subsingleton_empty : (∅ : set α).subsingleton := λ x, false.elim @[simp] lemma subsingleton_singleton {a} : ({a} : set α).subsingleton := λ x hx y hy, (eq_of_mem_singleton hx).symm ▸ (eq_of_mem_singleton hy).symm ▸ rfl lemma subsingleton_iff_singleton {x} (hx : x ∈ s) : s.subsingleton ↔ s = {x} := ⟨λ h, h.eq_singleton_of_mem hx, λ h,h.symm ▸ subsingleton_singleton⟩ lemma subsingleton.eq_empty_or_singleton (hs : s.subsingleton) : s = ∅ ∨ ∃ x, s = {x} := s.eq_empty_or_nonempty.elim or.inl (λ ⟨x, hx⟩, or.inr ⟨x, hs.eq_singleton_of_mem hx⟩) lemma subsingleton.induction_on {p : set α → Prop} (hs : s.subsingleton) (he : p ∅) (h₁ : ∀ x, p {x}) : p s := by { rcases hs.eq_empty_or_singleton with rfl|⟨x, rfl⟩, exacts [he, h₁ _] } lemma subsingleton_univ [subsingleton α] : (univ : set α).subsingleton := λ x hx y hy, subsingleton.elim x y /-- `s`, coerced to a type, is a subsingleton type if and only if `s` is a subsingleton set. -/ @[simp, norm_cast] lemma subsingleton_coe (s : set α) : subsingleton s ↔ s.subsingleton := begin split, { refine λ h, (λ a ha b hb, _), exact set_coe.ext_iff.2 (@subsingleton.elim s h ⟨a, ha⟩ ⟨b, hb⟩) }, { exact λ h, subsingleton.intro (λ a b, set_coe.ext (h a.property b.property)) } end /-- `s` is a subsingleton, if its image of an injective function is. -/ theorem subsingleton_of_image {α β : Type*} {f : α → β} (hf : function.injective f) (s : set α) (hs : (f '' s).subsingleton) : s.subsingleton := λ a ha b hb, hf $ hs (mem_image_of_mem _ ha) (mem_image_of_mem _ hb) theorem univ_eq_true_false : univ = ({true, false} : set Prop) := eq.symm $ eq_univ_of_forall $ classical.cases (by simp) (by simp) /-! ### Lemmas about range of a function. -/ section range variables {f : ι → α} open function /-- Range of a function. This function is more flexible than `f '' univ`, as the image requires that the domain is in Type and not an arbitrary Sort. -/ def range (f : ι → α) : set α := {x | ∃y, f y = x} @[simp] theorem mem_range {x : α} : x ∈ range f ↔ ∃ y, f y = x := iff.rfl @[simp] theorem mem_range_self (i : ι) : f i ∈ range f := ⟨i, rfl⟩ theorem forall_range_iff {p : α → Prop} : (∀ a ∈ range f, p a) ↔ (∀ i, p (f i)) := by simp theorem exists_range_iff {p : α → Prop} : (∃ a ∈ range f, p a) ↔ (∃ i, p (f i)) := by simp lemma exists_range_iff' {p : α → Prop} : (∃ a, a ∈ range f ∧ p a) ↔ ∃ i, p (f i) := by simpa only [exists_prop] using exists_range_iff theorem range_iff_surjective : range f = univ ↔ surjective f := eq_univ_iff_forall alias range_iff_surjective ↔ _ function.surjective.range_eq @[simp] theorem range_id : range (@id α) = univ := range_iff_surjective.2 surjective_id theorem is_compl_range_inl_range_inr : is_compl (range $ @sum.inl α β) (range sum.inr) := ⟨by { rintro y ⟨⟨x₁, rfl⟩, ⟨x₂, _⟩⟩, cc }, by { rintro (x|y) -; [left, right]; exact mem_range_self _ }⟩ @[simp] theorem range_inl_union_range_inr : range (sum.inl : α → α ⊕ β) ∪ range sum.inr = univ := is_compl_range_inl_range_inr.sup_eq_top @[simp] theorem range_inl_inter_range_inr : range (sum.inl : α → α ⊕ β) ∩ range sum.inr = ∅ := is_compl_range_inl_range_inr.inf_eq_bot @[simp] theorem range_inr_union_range_inl : range (sum.inr : β → α ⊕ β) ∪ range sum.inl = univ := is_compl_range_inl_range_inr.symm.sup_eq_top @[simp] theorem range_inr_inter_range_inl : range (sum.inr : β → α ⊕ β) ∩ range sum.inl = ∅ := is_compl_range_inl_range_inr.symm.inf_eq_bot @[simp] theorem preimage_inl_range_inr : sum.inl ⁻¹' range (sum.inr : β → α ⊕ β) = ∅ := by { ext, simp } @[simp] theorem preimage_inr_range_inl : sum.inr ⁻¹' range (sum.inl : α → α ⊕ β) = ∅ := by { ext, simp } @[simp] theorem range_quot_mk (r : α → α → Prop) : range (quot.mk r) = univ := (surjective_quot_mk r).range_eq @[simp] theorem image_univ {f : α → β} : f '' univ = range f := by { ext, simp [image, range] } theorem image_subset_range (f : α → β) (s) : f '' s ⊆ range f := by rw ← image_univ; exact image_subset _ (subset_univ _) theorem mem_range_of_mem_image (f : α → β) (s) {x : β} (h : x ∈ f '' s) : x ∈ range f := mem_of_mem_of_subset h $ image_subset_range f s theorem range_comp (g : α → β) (f : ι → α) : range (g ∘ f) = g '' range f := subset.antisymm (forall_range_iff.mpr $ assume i, mem_image_of_mem g (mem_range_self _)) (ball_image_iff.mpr $ forall_range_iff.mpr mem_range_self) theorem range_subset_iff : range f ⊆ s ↔ ∀ y, f y ∈ s := forall_range_iff lemma range_comp_subset_range (f : α → β) (g : β → γ) : range (g ∘ f) ⊆ range g := by rw range_comp; apply image_subset_range lemma range_nonempty_iff_nonempty : (range f).nonempty ↔ nonempty ι := ⟨λ ⟨y, x, hxy⟩, ⟨x⟩, λ ⟨x⟩, ⟨f x, mem_range_self x⟩⟩ lemma range_nonempty [h : nonempty ι] (f : ι → α) : (range f).nonempty := range_nonempty_iff_nonempty.2 h @[simp] lemma range_eq_empty {f : ι → α} : range f = ∅ ↔ ¬ nonempty ι := not_nonempty_iff_eq_empty.symm.trans $ not_congr range_nonempty_iff_nonempty instance [nonempty ι] (f : ι → α) : nonempty (range f) := (range_nonempty f).to_subtype @[simp] lemma image_union_image_compl_eq_range (f : α → β) : (f '' s) ∪ (f '' sᶜ) = range f := by rw [← image_union, ← image_univ, ← union_compl_self] theorem image_preimage_eq_inter_range {f : α → β} {t : set β} : f '' (f ⁻¹' t) = t ∩ range f := ext $ assume x, ⟨assume ⟨x, hx, heq⟩, heq ▸ ⟨hx, mem_range_self _⟩, assume ⟨hx, ⟨y, h_eq⟩⟩, h_eq ▸ mem_image_of_mem f $ show y ∈ f ⁻¹' t, by simp [preimage, h_eq, hx]⟩ lemma image_preimage_eq_of_subset {f : α → β} {s : set β} (hs : s ⊆ range f) : f '' (f ⁻¹' s) = s := by rw [image_preimage_eq_inter_range, inter_eq_self_of_subset_left hs] lemma image_preimage_eq_iff {f : α → β} {s : set β} : f '' (f ⁻¹' s) = s ↔ s ⊆ range f := ⟨by { intro h, rw [← h], apply image_subset_range }, image_preimage_eq_of_subset⟩ lemma preimage_subset_preimage_iff {s t : set α} {f : β → α} (hs : s ⊆ range f) : f ⁻¹' s ⊆ f ⁻¹' t ↔ s ⊆ t := begin split, { intros h x hx, rcases hs hx with ⟨y, rfl⟩, exact h hx }, intros h x, apply h end lemma preimage_eq_preimage' {s t : set α} {f : β → α} (hs : s ⊆ range f) (ht : t ⊆ range f) : f ⁻¹' s = f ⁻¹' t ↔ s = t := begin split, { intro h, apply subset.antisymm, rw [←preimage_subset_preimage_iff hs, h], rw [←preimage_subset_preimage_iff ht, h] }, rintro rfl, refl end @[simp] theorem preimage_inter_range {f : α → β} {s : set β} : f ⁻¹' (s ∩ range f) = f ⁻¹' s := set.ext $ λ x, and_iff_left ⟨x, rfl⟩ @[simp] theorem preimage_range_inter {f : α → β} {s : set β} : f ⁻¹' (range f ∩ s) = f ⁻¹' s := by rw [inter_comm, preimage_inter_range] theorem preimage_image_preimage {f : α → β} {s : set β} : f ⁻¹' (f '' (f ⁻¹' s)) = f ⁻¹' s := by rw [image_preimage_eq_inter_range, preimage_inter_range] @[simp] theorem quot_mk_range_eq [setoid α] : range (λx : α, ⟦x⟧) = univ := range_iff_surjective.2 quot.exists_rep lemma range_const_subset {c : α} : range (λx:ι, c) ⊆ {c} := range_subset_iff.2 $ λ x, rfl @[simp] lemma range_const : ∀ [nonempty ι] {c : α}, range (λx:ι, c) = {c} | ⟨x⟩ c := subset.antisymm range_const_subset $ assume y hy, (mem_singleton_iff.1 hy).symm ▸ mem_range_self x lemma diagonal_eq_range {α : Type*} : diagonal α = range (λ x, (x, x)) := by { ext ⟨x, y⟩, simp [diagonal, eq_comm] } theorem preimage_singleton_nonempty {f : α → β} {y : β} : (f ⁻¹' {y}).nonempty ↔ y ∈ range f := iff.rfl theorem preimage_singleton_eq_empty {f : α → β} {y : β} : f ⁻¹' {y} = ∅ ↔ y ∉ range f := not_nonempty_iff_eq_empty.symm.trans $ not_congr preimage_singleton_nonempty lemma range_subset_singleton {f : ι → α} {x : α} : range f ⊆ {x} ↔ f = const ι x := by simp [range_subset_iff, funext_iff, mem_singleton] lemma image_compl_preimage {f : α → β} {s : set β} : f '' ((f ⁻¹' s)ᶜ) = range f \ s := by rw [compl_eq_univ_diff, image_diff_preimage, image_univ] @[simp] theorem range_sigma_mk {β : α → Type*} (a : α) : range (sigma.mk a : β a → Σ a, β a) = sigma.fst ⁻¹' {a} := begin apply subset.antisymm, { rintros _ ⟨b, rfl⟩, simp }, { rintros ⟨x, y⟩ (rfl|_), exact mem_range_self y } end /-- Any map `f : ι → β` factors through a map `range_factorization f : ι → range f`. -/ def range_factorization (f : ι → β) : ι → range f := λ i, ⟨f i, mem_range_self i⟩ lemma range_factorization_eq {f : ι → β} : subtype.val ∘ range_factorization f = f := funext $ λ i, rfl lemma surjective_onto_range : surjective (range_factorization f) := λ ⟨_, ⟨i, rfl⟩⟩, ⟨i, rfl⟩ lemma image_eq_range (f : α → β) (s : set α) : f '' s = range (λ(x : s), f x) := by { ext, split, rintro ⟨x, h1, h2⟩, exact ⟨⟨x, h1⟩, h2⟩, rintro ⟨⟨x, h1⟩, h2⟩, exact ⟨x, h1, h2⟩ } @[simp] lemma sum.elim_range {α β γ : Type*} (f : α → γ) (g : β → γ) : range (sum.elim f g) = range f ∪ range g := by simp [set.ext_iff, mem_range] lemma range_ite_subset' {p : Prop} [decidable p] {f g : α → β} : range (if p then f else g) ⊆ range f ∪ range g := begin by_cases h : p, {rw if_pos h, exact subset_union_left _ _}, {rw if_neg h, exact subset_union_right _ _} end lemma range_ite_subset {p : α → Prop} [decidable_pred p] {f g : α → β} : range (λ x, if p x then f x else g x) ⊆ range f ∪ range g := begin rw range_subset_iff, intro x, by_cases h : p x, simp [if_pos h, mem_union, mem_range_self], simp [if_neg h, mem_union, mem_range_self] end @[simp] lemma preimage_range (f : α → β) : f ⁻¹' (range f) = univ := eq_univ_of_forall mem_range_self /-- The range of a function from a `unique` type contains just the function applied to its single value. -/ lemma range_unique [h : unique ι] : range f = {f $ default ι} := begin ext x, rw mem_range, split, { rintros ⟨i, hi⟩, rw h.uniq i at hi, exact hi ▸ mem_singleton _ }, { exact λ h, ⟨default ι, h.symm⟩ } end lemma range_diff_image_subset (f : α → β) (s : set α) : range f \ f '' s ⊆ f '' sᶜ := λ y ⟨⟨x, h₁⟩, h₂⟩, ⟨x, λ h, h₂ ⟨x, h, h₁⟩, h₁⟩ lemma range_diff_image {f : α → β} (H : injective f) (s : set α) : range f \ f '' s = f '' sᶜ := subset.antisymm (range_diff_image_subset f s) $ λ y ⟨x, hx, hy⟩, hy ▸ ⟨mem_range_self _, λ ⟨x', hx', eq⟩, hx $ H eq ▸ hx'⟩ end range /-- The set `s` is pairwise `r` if `r x y` for all *distinct* `x y ∈ s`. -/ def pairwise_on (s : set α) (r : α → α → Prop) := ∀ x ∈ s, ∀ y ∈ s, x ≠ y → r x y lemma pairwise_on_of_forall (s : set α) (p : α → α → Prop) (h : ∀ (a b : α), p a b) : pairwise_on s p := λ a _ b _ _, h a b lemma pairwise_on.imp_on {s : set α} {p q : α → α → Prop} (h : pairwise_on s p) (hpq : pairwise_on s (λ ⦃a b : α⦄, p a b → q a b)) : pairwise_on s q := λ a ha b hb hab, hpq a ha b hb hab (h a ha b hb hab) lemma pairwise_on.imp {s : set α} {p q : α → α → Prop} (h : pairwise_on s p) (hpq : ∀ ⦃a b : α⦄, p a b → q a b) : pairwise_on s q := h.imp_on (pairwise_on_of_forall s _ hpq) theorem pairwise_on.mono {s t : set α} {r} (h : t ⊆ s) (hp : pairwise_on s r) : pairwise_on t r := λ x xt y yt, hp x (h xt) y (h yt) theorem pairwise_on.mono' {s : set α} {r r' : α → α → Prop} (H : r ≤ r') (hp : pairwise_on s r) : pairwise_on s r' := hp.imp H theorem pairwise_on_top (s : set α) : pairwise_on s ⊤ := pairwise_on_of_forall s _ (λ a b, trivial) /-- If and only if `f` takes pairwise equal values on `s`, there is some value it takes everywhere on `s`. -/ lemma pairwise_on_eq_iff_exists_eq [nonempty β] (s : set α) (f : α → β) : (pairwise_on s (λ x y, f x = f y)) ↔ ∃ z, ∀ x ∈ s, f x = z := begin split, { intro h, rcases eq_empty_or_nonempty s with rfl | ⟨x, hx⟩, { exact ⟨classical.arbitrary β, λ x hx, false.elim hx⟩ }, { use f x, intros y hy, by_cases hyx : y = x, { rw hyx }, { exact h y hy x hx hyx } } }, { rintros ⟨z, hz⟩ x hx y hy hne, rw [hz x hx, hz y hy] } end protected lemma subsingleton.pairwise_on (h : s.subsingleton) (r : α → α → Prop) : pairwise_on s r := λ x hx y hy hne, (hne (h hx hy)).elim @[simp] lemma pairwise_on_empty (r : α → α → Prop) : (∅ : set α).pairwise_on r := subsingleton_empty.pairwise_on r @[simp] lemma pairwise_on_singleton (a : α) (r : α → α → Prop) : pairwise_on {a} r := subsingleton_singleton.pairwise_on r lemma pairwise_on_insert_of_symmetric {α} {s : set α} {a : α} {r : α → α → Prop} (hr : symmetric r) : (insert a s).pairwise_on r ↔ s.pairwise_on r ∧ ∀ b ∈ s, a ≠ b → r a b := begin refine ⟨λ h, ⟨_, _⟩, λ h, _⟩, { exact h.mono (s.subset_insert a) }, { intros b hb hn, exact h a (s.mem_insert _) b (set.mem_insert_of_mem _ hb) hn }, { intros b hb c hc hn, rw [mem_insert_iff] at hb hc, rcases hb with (rfl | hb); rcases hc with (rfl | hc), { exact absurd rfl hn }, { exact h.right _ hc hn }, { exact hr (h.right _ hb hn.symm) }, { exact h.left _ hb _ hc hn } } end end set open set namespace function variables {ι : Sort*} {α : Type*} {β : Type*} {f : α → β} lemma surjective.preimage_injective (hf : surjective f) : injective (preimage f) := assume s t, (preimage_eq_preimage hf).1 lemma injective.preimage_image (hf : injective f) (s : set α) : f ⁻¹' (f '' s) = s := preimage_image_eq s hf lemma injective.preimage_surjective (hf : injective f) : surjective (preimage f) := by { intro s, use f '' s, rw hf.preimage_image } lemma injective.subsingleton_image_iff (hf : injective f) {s : set α} : (f '' s).subsingleton ↔ s.subsingleton := ⟨subsingleton_of_image hf s, λ h, h.image f⟩ lemma surjective.image_preimage (hf : surjective f) (s : set β) : f '' (f ⁻¹' s) = s := image_preimage_eq s hf lemma surjective.image_surjective (hf : surjective f) : surjective (image f) := by { intro s, use f ⁻¹' s, rw hf.image_preimage } lemma injective.image_injective (hf : injective f) : injective (image f) := by { intros s t h, rw [←preimage_image_eq s hf, ←preimage_image_eq t hf, h] } lemma surjective.preimage_subset_preimage_iff {s t : set β} (hf : surjective f) : f ⁻¹' s ⊆ f ⁻¹' t ↔ s ⊆ t := by { apply preimage_subset_preimage_iff, rw [hf.range_eq], apply subset_univ } lemma surjective.range_comp {ι' : Sort*} {f : ι → ι'} (hf : surjective f) (g : ι' → α) : range (g ∘ f) = range g := ext $ λ y, (@surjective.exists _ _ _ hf (λ x, g x = y)).symm lemma injective.nonempty_apply_iff {f : set α → set β} (hf : injective f) (h2 : f ∅ = ∅) {s : set α} : (f s).nonempty ↔ s.nonempty := by rw [← ne_empty_iff_nonempty, ← h2, ← ne_empty_iff_nonempty, hf.ne_iff] lemma injective.mem_range_iff_exists_unique (hf : injective f) {b : β} : b ∈ range f ↔ ∃! a, f a = b := ⟨λ ⟨a, h⟩, ⟨a, h, λ a' ha, hf (ha.trans h.symm)⟩, exists_unique.exists⟩ lemma injective.exists_unique_of_mem_range (hf : injective f) {b : β} (hb : b ∈ range f) : ∃! a, f a = b := hf.mem_range_iff_exists_unique.mp hb end function open function /-! ### Image and preimage on subtypes -/ namespace subtype variable {α : Type*} lemma coe_image {p : α → Prop} {s : set (subtype p)} : coe '' s = {x | ∃h : p x, (⟨x, h⟩ : subtype p) ∈ s} := set.ext $ assume a, ⟨assume ⟨⟨a', ha'⟩, in_s, h_eq⟩, h_eq ▸ ⟨ha', in_s⟩, assume ⟨ha, in_s⟩, ⟨⟨a, ha⟩, in_s, rfl⟩⟩ lemma range_coe {s : set α} : range (coe : s → α) = s := by { rw ← set.image_univ, simp [-set.image_univ, coe_image] } /-- A variant of `range_coe`. Try to use `range_coe` if possible. This version is useful when defining a new type that is defined as the subtype of something. In that case, the coercion doesn't fire anymore. -/ lemma range_val {s : set α} : range (subtype.val : s → α) = s := range_coe /-- We make this the simp lemma instead of `range_coe`. The reason is that if we write for `s : set α` the function `coe : s → α`, then the inferred implicit arguments of `coe` are `coe α (λ x, x ∈ s)`. -/ @[simp] lemma range_coe_subtype {p : α → Prop} : range (coe : subtype p → α) = {x | p x} := range_coe @[simp] lemma coe_preimage_self (s : set α) : (coe : s → α) ⁻¹' s = univ := by rw [← preimage_range (coe : s → α), range_coe] lemma range_val_subtype {p : α → Prop} : range (subtype.val : subtype p → α) = {x | p x} := range_coe theorem coe_image_subset (s : set α) (t : set s) : coe '' t ⊆ s := λ x ⟨y, yt, yvaleq⟩, by rw ←yvaleq; exact y.property theorem coe_image_univ (s : set α) : (coe : s → α) '' set.univ = s := image_univ.trans range_coe @[simp] theorem image_preimage_coe (s t : set α) : (coe : s → α) '' (coe ⁻¹' t) = t ∩ s := image_preimage_eq_inter_range.trans $ congr_arg _ range_coe theorem image_preimage_val (s t : set α) : (subtype.val : s → α) '' (subtype.val ⁻¹' t) = t ∩ s := image_preimage_coe s t theorem preimage_coe_eq_preimage_coe_iff {s t u : set α} : ((coe : s → α) ⁻¹' t = coe ⁻¹' u) ↔ t ∩ s = u ∩ s := begin rw [←image_preimage_coe, ←image_preimage_coe], split, { intro h, rw h }, intro h, exact coe_injective.image_injective h end theorem preimage_val_eq_preimage_val_iff (s t u : set α) : ((subtype.val : s → α) ⁻¹' t = subtype.val ⁻¹' u) ↔ (t ∩ s = u ∩ s) := preimage_coe_eq_preimage_coe_iff lemma exists_set_subtype {t : set α} (p : set α → Prop) : (∃(s : set t), p (coe '' s)) ↔ ∃(s : set α), s ⊆ t ∧ p s := begin split, { rintro ⟨s, hs⟩, refine ⟨coe '' s, _, hs⟩, convert image_subset_range _ _, rw [range_coe] }, rintro ⟨s, hs₁, hs₂⟩, refine ⟨coe ⁻¹' s, _⟩, rw [image_preimage_eq_of_subset], exact hs₂, rw [range_coe], exact hs₁ end lemma preimage_coe_nonempty {s t : set α} : ((coe : s → α) ⁻¹' t).nonempty ↔ (s ∩ t).nonempty := by rw [inter_comm, ← image_preimage_coe, nonempty_image_iff] lemma preimage_coe_eq_empty {s t : set α} : (coe : s → α) ⁻¹' t = ∅ ↔ s ∩ t = ∅ := by simp only [← not_nonempty_iff_eq_empty, preimage_coe_nonempty] @[simp] lemma preimage_coe_compl (s : set α) : (coe : s → α) ⁻¹' sᶜ = ∅ := preimage_coe_eq_empty.2 (inter_compl_self s) @[simp] lemma preimage_coe_compl' (s : set α) : (coe : sᶜ → α) ⁻¹' s = ∅ := preimage_coe_eq_empty.2 (compl_inter_self s) end subtype namespace set /-! ### Lemmas about cartesian product of sets -/ section prod variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} variables {s s₁ s₂ : set α} {t t₁ t₂ : set β} /-- The cartesian product `prod s t` is the set of `(a, b)` such that `a ∈ s` and `b ∈ t`. -/ protected def prod (s : set α) (t : set β) : set (α × β) := {p | p.1 ∈ s ∧ p.2 ∈ t} lemma prod_eq (s : set α) (t : set β) : s.prod t = prod.fst ⁻¹' s ∩ prod.snd ⁻¹' t := rfl theorem mem_prod_eq {p : α × β} : p ∈ s.prod t = (p.1 ∈ s ∧ p.2 ∈ t) := rfl @[simp] theorem mem_prod {p : α × β} : p ∈ s.prod t ↔ p.1 ∈ s ∧ p.2 ∈ t := iff.rfl @[simp] theorem prod_mk_mem_set_prod_eq {a : α} {b : β} : (a, b) ∈ s.prod t = (a ∈ s ∧ b ∈ t) := rfl lemma mk_mem_prod {a : α} {b : β} (a_in : a ∈ s) (b_in : b ∈ t) : (a, b) ∈ s.prod t := ⟨a_in, b_in⟩ theorem prod_mono {s₁ s₂ : set α} {t₁ t₂ : set β} (hs : s₁ ⊆ s₂) (ht : t₁ ⊆ t₂) : s₁.prod t₁ ⊆ s₂.prod t₂ := assume x ⟨h₁, h₂⟩, ⟨hs h₁, ht h₂⟩ lemma prod_subset_iff {P : set (α × β)} : (s.prod t ⊆ P) ↔ ∀ (x ∈ s) (y ∈ t), (x, y) ∈ P := ⟨λ h _ xin _ yin, h (mk_mem_prod xin yin), λ h ⟨_, _⟩ pin, h _ pin.1 _ pin.2⟩ lemma forall_prod_set {p : α × β → Prop} : (∀ x ∈ s.prod t, p x) ↔ ∀ (x ∈ s) (y ∈ t), p (x, y) := prod_subset_iff lemma exists_prod_set {p : α × β → Prop} : (∃ x ∈ s.prod t, p x) ↔ ∃ (x ∈ s) (y ∈ t), p (x, y) := by simp [and_assoc] @[simp] theorem prod_empty : s.prod ∅ = (∅ : set (α × β)) := by { ext, simp } @[simp] theorem empty_prod : set.prod ∅ t = (∅ : set (α × β)) := by { ext, simp } @[simp] theorem univ_prod_univ : (@univ α).prod (@univ β) = univ := by { ext ⟨x, y⟩, simp } lemma univ_prod {t : set β} : set.prod (univ : set α) t = prod.snd ⁻¹' t := by simp [prod_eq] lemma prod_univ {s : set α} : set.prod s (univ : set β) = prod.fst ⁻¹' s := by simp [prod_eq] @[simp] theorem singleton_prod {a : α} : set.prod {a} t = prod.mk a '' t := by { ext ⟨x, y⟩, simp [and.left_comm, eq_comm] } @[simp] theorem prod_singleton {b : β} : s.prod {b} = (λ a, (a, b)) '' s := by { ext ⟨x, y⟩, simp [and.left_comm, eq_comm] } theorem singleton_prod_singleton {a : α} {b : β} : set.prod {a} {b} = ({(a, b)} : set (α × β)) := by simp @[simp] theorem union_prod : (s₁ ∪ s₂).prod t = s₁.prod t ∪ s₂.prod t := by { ext ⟨x, y⟩, simp [or_and_distrib_right] } @[simp] theorem prod_union : s.prod (t₁ ∪ t₂) = s.prod t₁ ∪ s.prod t₂ := by { ext ⟨x, y⟩, simp [and_or_distrib_left] } theorem prod_inter_prod : s₁.prod t₁ ∩ s₂.prod t₂ = (s₁ ∩ s₂).prod (t₁ ∩ t₂) := by { ext ⟨x, y⟩, simp [and_assoc, and.left_comm] } theorem insert_prod {a : α} : (insert a s).prod t = (prod.mk a '' t) ∪ s.prod t := by { ext ⟨x, y⟩, simp [image, iff_def, or_imp_distrib, imp.swap] {contextual := tt} } theorem prod_insert {b : β} : s.prod (insert b t) = ((λa, (a, b)) '' s) ∪ s.prod t := by { ext ⟨x, y⟩, simp [image, iff_def, or_imp_distrib, imp.swap] {contextual := tt} } theorem prod_preimage_eq {f : γ → α} {g : δ → β} : (f ⁻¹' s).prod (g ⁻¹' t) = (λ p, (f p.1, g p.2)) ⁻¹' s.prod t := rfl lemma prod_preimage_left {f : γ → α} : (f ⁻¹' s).prod t = (λp, (f p.1, p.2)) ⁻¹' (s.prod t) := rfl lemma prod_preimage_right {g : δ → β} : s.prod (g ⁻¹' t) = (λp, (p.1, g p.2)) ⁻¹' (s.prod t) := rfl lemma preimage_prod_map_prod (f : α → β) (g : γ → δ) (s : set β) (t : set δ) : prod.map f g ⁻¹' (s.prod t) = (f ⁻¹' s).prod (g ⁻¹' t) := rfl lemma mk_preimage_prod (f : γ → α) (g : γ → β) : (λ x, (f x, g x)) ⁻¹' s.prod t = f ⁻¹' s ∩ g ⁻¹' t := rfl @[simp] lemma mk_preimage_prod_left {y : β} (h : y ∈ t) : (λ x, (x, y)) ⁻¹' s.prod t = s := by { ext x, simp [h] } @[simp] lemma mk_preimage_prod_right {x : α} (h : x ∈ s) : prod.mk x ⁻¹' s.prod t = t := by { ext y, simp [h] } @[simp] lemma mk_preimage_prod_left_eq_empty {y : β} (hy : y ∉ t) : (λ x, (x, y)) ⁻¹' s.prod t = ∅ := by { ext z, simp [hy] } @[simp] lemma mk_preimage_prod_right_eq_empty {x : α} (hx : x ∉ s) : prod.mk x ⁻¹' s.prod t = ∅ := by { ext z, simp [hx] } lemma mk_preimage_prod_left_eq_if {y : β} [decidable_pred (∈ t)] : (λ x, (x, y)) ⁻¹' s.prod t = if y ∈ t then s else ∅ := by { split_ifs; simp [h] } lemma mk_preimage_prod_right_eq_if {x : α} [decidable_pred (∈ s)] : prod.mk x ⁻¹' s.prod t = if x ∈ s then t else ∅ := by { split_ifs; simp [h] } lemma mk_preimage_prod_left_fn_eq_if {y : β} [decidable_pred (∈ t)] (f : γ → α) : (λ x, (f x, y)) ⁻¹' s.prod t = if y ∈ t then f ⁻¹' s else ∅ := by rw [← mk_preimage_prod_left_eq_if, prod_preimage_left, preimage_preimage] lemma mk_preimage_prod_right_fn_eq_if {x : α} [decidable_pred (∈ s)] (g : δ → β) : (λ y, (x, g y)) ⁻¹' s.prod t = if x ∈ s then g ⁻¹' t else ∅ := by rw [← mk_preimage_prod_right_eq_if, prod_preimage_right, preimage_preimage] theorem image_swap_eq_preimage_swap : image (@prod.swap α β) = preimage prod.swap := image_eq_preimage_of_inverse prod.swap_left_inverse prod.swap_right_inverse theorem preimage_swap_prod {s : set α} {t : set β} : prod.swap ⁻¹' t.prod s = s.prod t := by { ext ⟨x, y⟩, simp [and_comm] } theorem image_swap_prod : prod.swap '' t.prod s = s.prod t := by rw [image_swap_eq_preimage_swap, preimage_swap_prod] theorem prod_image_image_eq {m₁ : α → γ} {m₂ : β → δ} : (m₁ '' s).prod (m₂ '' t) = image (λp:α×β, (m₁ p.1, m₂ p.2)) (s.prod t) := ext $ by simp [-exists_and_distrib_right, exists_and_distrib_right.symm, and.left_comm, and.assoc, and.comm] theorem prod_range_range_eq {α β γ δ} {m₁ : α → γ} {m₂ : β → δ} : (range m₁).prod (range m₂) = range (λp:α×β, (m₁ p.1, m₂ p.2)) := ext $ by simp [range] @[simp] theorem range_prod_map {α β γ δ} {m₁ : α → γ} {m₂ : β → δ} : range (prod.map m₁ m₂) = (range m₁).prod (range m₂) := prod_range_range_eq.symm theorem prod_range_univ_eq {α β γ} {m₁ : α → γ} : (range m₁).prod (univ : set β) = range (λp:α×β, (m₁ p.1, p.2)) := ext $ by simp [range] theorem prod_univ_range_eq {α β δ} {m₂ : β → δ} : (univ : set α).prod (range m₂) = range (λp:α×β, (p.1, m₂ p.2)) := ext $ by simp [range] lemma range_pair_subset {α β γ : Type*} (f : α → β) (g : α → γ) : range (λ x, (f x, g x)) ⊆ (range f).prod (range g) := have (λ x, (f x, g x)) = prod.map f g ∘ (λ x, (x, x)), from funext (λ x, rfl), by { rw [this, ← range_prod_map], apply range_comp_subset_range } theorem nonempty.prod : s.nonempty → t.nonempty → (s.prod t).nonempty | ⟨x, hx⟩ ⟨y, hy⟩ := ⟨(x, y), ⟨hx, hy⟩⟩ theorem nonempty.fst : (s.prod t).nonempty → s.nonempty | ⟨p, hp⟩ := ⟨p.1, hp.1⟩ theorem nonempty.snd : (s.prod t).nonempty → t.nonempty | ⟨p, hp⟩ := ⟨p.2, hp.2⟩ theorem prod_nonempty_iff : (s.prod t).nonempty ↔ s.nonempty ∧ t.nonempty := ⟨λ h, ⟨h.fst, h.snd⟩, λ h, nonempty.prod h.1 h.2⟩ theorem prod_eq_empty_iff : s.prod t = ∅ ↔ (s = ∅ ∨ t = ∅) := by simp only [not_nonempty_iff_eq_empty.symm, prod_nonempty_iff, not_and_distrib] lemma prod_sub_preimage_iff {W : set γ} {f : α × β → γ} : s.prod t ⊆ f ⁻¹' W ↔ ∀ a b, a ∈ s → b ∈ t → f (a, b) ∈ W := by simp [subset_def] lemma fst_image_prod_subset (s : set α) (t : set β) : prod.fst '' (s.prod t) ⊆ s := λ _ h, let ⟨_, ⟨h₂, _⟩, h₁⟩ := (set.mem_image _ _ _).1 h in h₁ ▸ h₂ lemma prod_subset_preimage_fst (s : set α) (t : set β) : s.prod t ⊆ prod.fst ⁻¹' s := image_subset_iff.1 (fst_image_prod_subset s t) lemma fst_image_prod (s : set β) {t : set α} (ht : t.nonempty) : prod.fst '' (s.prod t) = s := set.subset.antisymm (fst_image_prod_subset _ _) $ λ y y_in, let ⟨x, x_in⟩ := ht in ⟨(y, x), ⟨y_in, x_in⟩, rfl⟩ lemma snd_image_prod_subset (s : set α) (t : set β) : prod.snd '' (s.prod t) ⊆ t := λ _ h, let ⟨_, ⟨_, h₂⟩, h₁⟩ := (set.mem_image _ _ _).1 h in h₁ ▸ h₂ lemma prod_subset_preimage_snd (s : set α) (t : set β) : s.prod t ⊆ prod.snd ⁻¹' t := image_subset_iff.1 (snd_image_prod_subset s t) lemma snd_image_prod {s : set α} (hs : s.nonempty) (t : set β) : prod.snd '' (s.prod t) = t := set.subset.antisymm (snd_image_prod_subset _ _) $ λ y y_in, let ⟨x, x_in⟩ := hs in ⟨(x, y), ⟨x_in, y_in⟩, rfl⟩ lemma prod_diff_prod : s.prod t \ s₁.prod t₁ = s.prod (t \ t₁) ∪ (s \ s₁).prod t := by { ext x, by_cases h₁ : x.1 ∈ s₁; by_cases h₂ : x.2 ∈ t₁; simp * } /-- A product set is included in a product set if and only factors are included, or a factor of the first set is empty. -/ lemma prod_subset_prod_iff : (s.prod t ⊆ s₁.prod t₁) ↔ (s ⊆ s₁ ∧ t ⊆ t₁) ∨ (s = ∅) ∨ (t = ∅) := begin classical, cases (s.prod t).eq_empty_or_nonempty with h h, { simp [h, prod_eq_empty_iff.1 h] }, { have st : s.nonempty ∧ t.nonempty, by rwa [prod_nonempty_iff] at h, split, { assume H : s.prod t ⊆ s₁.prod t₁, have h' : s₁.nonempty ∧ t₁.nonempty := prod_nonempty_iff.1 (h.mono H), refine or.inl ⟨_, _⟩, show s ⊆ s₁, { have := image_subset (prod.fst : α × β → α) H, rwa [fst_image_prod _ st.2, fst_image_prod _ h'.2] at this }, show t ⊆ t₁, { have := image_subset (prod.snd : α × β → β) H, rwa [snd_image_prod st.1, snd_image_prod h'.1] at this } }, { assume H, simp only [st.1.ne_empty, st.2.ne_empty, or_false] at H, exact prod_mono H.1 H.2 } } end end prod /-! ### Lemmas about set-indexed products of sets -/ section pi variables {ι : Type*} {α : ι → Type*} {s s₁ : set ι} {t t₁ t₂ : Π i, set (α i)} /-- Given an index set `ι` and a family of sets `t : Π i, set (α i)`, `pi s t` is the set of dependent functions `f : Πa, π a` such that `f a` belongs to `t a` whenever `a ∈ s`. -/ def pi (s : set ι) (t : Π i, set (α i)) : set (Π i, α i) := { f | ∀i ∈ s, f i ∈ t i } @[simp] lemma mem_pi {f : Π i, α i} : f ∈ s.pi t ↔ ∀ i ∈ s, f i ∈ t i := by refl @[simp] lemma mem_univ_pi {f : Π i, α i} : f ∈ pi univ t ↔ ∀ i, f i ∈ t i := by simp @[simp] lemma empty_pi (s : Π i, set (α i)) : pi ∅ s = univ := by { ext, simp [pi] } @[simp] lemma pi_univ (s : set ι) : pi s (λ i, (univ : set (α i))) = univ := eq_univ_of_forall $ λ f i hi, mem_univ _ lemma pi_mono (h : ∀ i ∈ s, t₁ i ⊆ t₂ i) : pi s t₁ ⊆ pi s t₂ := λ x hx i hi, (h i hi $ hx i hi) lemma pi_inter_distrib : s.pi (λ i, t i ∩ t₁ i) = s.pi t ∩ s.pi t₁ := ext $ λ x, by simp only [forall_and_distrib, mem_pi, mem_inter_eq] lemma pi_congr (h : s = s₁) (h' : ∀ i ∈ s, t i = t₁ i) : pi s t = pi s₁ t₁ := h ▸ (ext $ λ x, forall_congr $ λ i, forall_congr $ λ hi, h' i hi ▸ iff.rfl) lemma pi_eq_empty {i : ι} (hs : i ∈ s) (ht : t i = ∅) : s.pi t = ∅ := by { ext f, simp only [mem_empty_eq, not_forall, iff_false, mem_pi, not_imp], exact ⟨i, hs, by simp [ht]⟩ } lemma univ_pi_eq_empty {i : ι} (ht : t i = ∅) : pi univ t = ∅ := pi_eq_empty (mem_univ i) ht lemma pi_nonempty_iff : (s.pi t).nonempty ↔ ∀ i, ∃ x, i ∈ s → x ∈ t i := by simp [classical.skolem, set.nonempty] lemma univ_pi_nonempty_iff : (pi univ t).nonempty ↔ ∀ i, (t i).nonempty := by simp [classical.skolem, set.nonempty] lemma pi_eq_empty_iff : s.pi t = ∅ ↔ ∃ i, (α i → false) ∨ (i ∈ s ∧ t i = ∅) := begin rw [← not_nonempty_iff_eq_empty, pi_nonempty_iff], push_neg, apply exists_congr, intro i, split, { intro h, by_cases hα : nonempty (α i), { cases hα with x, refine or.inr ⟨(h x).1, by simp [eq_empty_iff_forall_not_mem, h]⟩ }, { exact or.inl (λ x, hα ⟨x⟩) }}, { rintro (h|h) x, exfalso, exact h x, simp [h] } end lemma univ_pi_eq_empty_iff : pi univ t = ∅ ↔ ∃ i, t i = ∅ := by simp [← not_nonempty_iff_eq_empty, univ_pi_nonempty_iff] @[simp] lemma range_dcomp {β : ι → Type*} (f : Π i, α i → β i) : range (λ (g : Π i, α i), (λ i, f i (g i))) = pi univ (λ i, range (f i)) := begin apply subset.antisymm, { rintro _ ⟨x, rfl⟩ i -, exact ⟨x i, rfl⟩ }, { intros x hx, choose y hy using hx, exact ⟨λ i, y i trivial, funext $ λ i, hy i trivial⟩ } end @[simp] lemma insert_pi (i : ι) (s : set ι) (t : Π i, set (α i)) : pi (insert i s) t = (eval i ⁻¹' t i) ∩ pi s t := by { ext, simp [pi, or_imp_distrib, forall_and_distrib] } @[simp] lemma singleton_pi (i : ι) (t : Π i, set (α i)) : pi {i} t = (eval i ⁻¹' t i) := by { ext, simp [pi] } lemma singleton_pi' (i : ι) (t : Π i, set (α i)) : pi {i} t = {x | x i ∈ t i} := singleton_pi i t lemma pi_if {p : ι → Prop} [h : decidable_pred p] (s : set ι) (t₁ t₂ : Π i, set (α i)) : pi s (λ i, if p i then t₁ i else t₂ i) = pi {i ∈ s | p i} t₁ ∩ pi {i ∈ s | ¬ p i} t₂ := begin ext f, split, { assume h, split; { rintros i ⟨his, hpi⟩, simpa [*] using h i } }, { rintros ⟨ht₁, ht₂⟩ i his, by_cases p i; simp * at * } end lemma union_pi : (s ∪ s₁).pi t = s.pi t ∩ s₁.pi t := by simp [pi, or_imp_distrib, forall_and_distrib, set_of_and] @[simp] lemma pi_inter_compl (s : set ι) : pi s t ∩ pi sᶜ t = pi univ t := by rw [← union_pi, union_compl_self] lemma pi_update_of_not_mem [decidable_eq ι] {β : Π i, Type*} {i : ι} (hi : i ∉ s) (f : Π j, α j) (a : α i) (t : Π j, α j → set (β j)) : s.pi (λ j, t j (update f i a j)) = s.pi (λ j, t j (f j)) := pi_congr rfl $ λ j hj, by { rw update_noteq, exact λ h, hi (h ▸ hj) } lemma pi_update_of_mem [decidable_eq ι] {β : Π i, Type*} {i : ι} (hi : i ∈ s) (f : Π j, α j) (a : α i) (t : Π j, α j → set (β j)) : s.pi (λ j, t j (update f i a j)) = {x | x i ∈ t i a} ∩ (s \ {i}).pi (λ j, t j (f j)) := calc s.pi (λ j, t j (update f i a j)) = ({i} ∪ s \ {i}).pi (λ j, t j (update f i a j)) : by rw [union_diff_self, union_eq_self_of_subset_left (singleton_subset_iff.2 hi)] ... = {x | x i ∈ t i a} ∩ (s \ {i}).pi (λ j, t j (f j)) : by { rw [union_pi, singleton_pi', update_same, pi_update_of_not_mem], simp } lemma univ_pi_update [decidable_eq ι] {β : Π i, Type*} (i : ι) (f : Π j, α j) (a : α i) (t : Π j, α j → set (β j)) : pi univ (λ j, t j (update f i a j)) = {x | x i ∈ t i a} ∩ pi {i}ᶜ (λ j, t j (f j)) := by rw [compl_eq_univ_diff, ← pi_update_of_mem (mem_univ _)] lemma univ_pi_update_univ [decidable_eq ι] (i : ι) (s : set (α i)) : pi univ (update (λ j : ι, (univ : set (α j))) i s) = eval i ⁻¹' s := by rw [univ_pi_update i (λ j, (univ : set (α j))) s (λ j t, t), pi_univ, inter_univ, preimage] open_locale classical lemma eval_image_pi {i : ι} (hs : i ∈ s) (ht : (s.pi t).nonempty) : eval i '' s.pi t = t i := begin ext x, rcases ht with ⟨f, hf⟩, split, { rintro ⟨g, hg, rfl⟩, exact hg i hs }, { intro hg, refine ⟨update f i x, _, by simp⟩, intros j hj, by_cases hji : j = i, { subst hji, simp [hg] }, { rw [mem_pi] at hf, simp [hji, hf, hj] }}, end @[simp] lemma eval_image_univ_pi {i : ι} (ht : (pi univ t).nonempty) : (λ f : Π i, α i, f i) '' pi univ t = t i := eval_image_pi (mem_univ i) ht lemma eval_preimage {ι} {α : ι → Type*} {i : ι} {s : set (α i)} : eval i ⁻¹' s = pi univ (update (λ i, univ) i s) := by { ext x, simp [@forall_update_iff _ (λ i, set (α i)) _ _ _ _ (λ i' y, x i' ∈ y)] } lemma eval_preimage' {ι} {α : ι → Type*} {i : ι} {s : set (α i)} : eval i ⁻¹' s = pi {i} (update (λ i, univ) i s) := by { ext, simp } lemma update_preimage_pi {i : ι} {f : Π i, α i} (hi : i ∈ s) (hf : ∀ j ∈ s, j ≠ i → f j ∈ t j) : (update f i) ⁻¹' s.pi t = t i := begin ext x, split, { intro h, convert h i hi, simp }, { intros hx j hj, by_cases h : j = i, { cases h, simpa }, { rw [update_noteq h], exact hf j hj h }} end lemma update_preimage_univ_pi {i : ι} {f : Π i, α i} (hf : ∀ j ≠ i, f j ∈ t j) : (update f i) ⁻¹' pi univ t = t i := update_preimage_pi (mem_univ i) (λ j _, hf j) lemma subset_pi_eval_image (s : set ι) (u : set (Π i, α i)) : u ⊆ pi s (λ i, eval i '' u) := λ f hf i hi, ⟨f, hf, rfl⟩ lemma univ_pi_ite (s : set ι) (t : Π i, set (α i)) : pi univ (λ i, if i ∈ s then t i else univ) = s.pi t := by { ext, simp_rw [mem_univ_pi], apply forall_congr, intro i, split_ifs; simp [h] } end pi /-! ### Lemmas about `inclusion`, the injection of subtypes induced by `⊆` -/ section inclusion variable {α : Type*} /-- `inclusion` is the "identity" function between two subsets `s` and `t`, where `s ⊆ t` -/ def inclusion {s t : set α} (h : s ⊆ t) : s → t := λ x : s, (⟨x, h x.2⟩ : t) @[simp] lemma inclusion_self {s : set α} (x : s) : inclusion (set.subset.refl _) x = x := by { cases x, refl } @[simp] lemma inclusion_right {s t : set α} (h : s ⊆ t) (x : t) (m : (x : α) ∈ s) : inclusion h ⟨x, m⟩ = x := by { cases x, refl } @[simp] lemma inclusion_inclusion {s t u : set α} (hst : s ⊆ t) (htu : t ⊆ u) (x : s) : inclusion htu (inclusion hst x) = inclusion (set.subset.trans hst htu) x := by { cases x, refl } @[simp] lemma coe_inclusion {s t : set α} (h : s ⊆ t) (x : s) : (inclusion h x : α) = (x : α) := rfl lemma inclusion_injective {s t : set α} (h : s ⊆ t) : function.injective (inclusion h) | ⟨_, _⟩ ⟨_, _⟩ := subtype.ext_iff_val.2 ∘ subtype.ext_iff_val.1 @[simp] lemma range_inclusion {s t : set α} (h : s ⊆ t) : range (inclusion h) = {x : t | (x:α) ∈ s} := by { ext ⟨x, hx⟩, simp [inclusion] } lemma eq_of_inclusion_surjective {s t : set α} {h : s ⊆ t} (h_surj : function.surjective (inclusion h)) : s = t := begin rw [← range_iff_surjective, range_inclusion, eq_univ_iff_forall] at h_surj, exact set.subset.antisymm h (λ x hx, h_surj ⟨x, hx⟩) end end inclusion /-! ### Injectivity and surjectivity lemmas for image and preimage -/ section image_preimage variables {α : Type u} {β : Type v} {f : α → β} @[simp] lemma preimage_injective : injective (preimage f) ↔ surjective f := begin refine ⟨λ h y, _, surjective.preimage_injective⟩, obtain ⟨x, hx⟩ : (f ⁻¹' {y}).nonempty, { rw [h.nonempty_apply_iff preimage_empty], apply singleton_nonempty }, exact ⟨x, hx⟩ end @[simp] lemma preimage_surjective : surjective (preimage f) ↔ injective f := begin refine ⟨λ h x x' hx, _, injective.preimage_surjective⟩, cases h {x} with s hs, have := mem_singleton x, rwa [← hs, mem_preimage, hx, ← mem_preimage, hs, mem_singleton_iff, eq_comm] at this end @[simp] lemma image_surjective : surjective (image f) ↔ surjective f := begin refine ⟨λ h y, _, surjective.image_surjective⟩, cases h {y} with s hs, have := mem_singleton y, rw [← hs] at this, rcases this with ⟨x, h1x, h2x⟩, exact ⟨x, h2x⟩ end @[simp] lemma image_injective : injective (image f) ↔ injective f := begin refine ⟨λ h x x' hx, _, injective.image_injective⟩, rw [← singleton_eq_singleton_iff], apply h, rw [image_singleton, image_singleton, hx] end lemma preimage_eq_iff_eq_image {f : α → β} (hf : bijective f) {s t} : f ⁻¹' s = t ↔ s = f '' t := by rw [← image_eq_image hf.1, hf.2.image_preimage] lemma eq_preimage_iff_image_eq {f : α → β} (hf : bijective f) {s t} : s = f ⁻¹' t ↔ f '' s = t := by rw [← image_eq_image hf.1, hf.2.image_preimage] end image_preimage /-! ### Lemmas about images of binary and ternary functions -/ section n_ary_image variables {α β γ δ ε : Type*} {f f' : α → β → γ} {g g' : α → β → γ → δ} variables {s s' : set α} {t t' : set β} {u u' : set γ} {a a' : α} {b b' : β} {c c' : γ} {d d' : δ} /-- The image of a binary function `f : α → β → γ` as a function `set α → set β → set γ`. Mathematically this should be thought of as the image of the corresponding function `α × β → γ`. -/ def image2 (f : α → β → γ) (s : set α) (t : set β) : set γ := {c | ∃ a b, a ∈ s ∧ b ∈ t ∧ f a b = c } lemma mem_image2_eq : c ∈ image2 f s t = ∃ a b, a ∈ s ∧ b ∈ t ∧ f a b = c := rfl @[simp] lemma mem_image2 : c ∈ image2 f s t ↔ ∃ a b, a ∈ s ∧ b ∈ t ∧ f a b = c := iff.rfl lemma mem_image2_of_mem (h1 : a ∈ s) (h2 : b ∈ t) : f a b ∈ image2 f s t := ⟨a, b, h1, h2, rfl⟩ lemma mem_image2_iff (hf : injective2 f) : f a b ∈ image2 f s t ↔ a ∈ s ∧ b ∈ t := ⟨ by { rintro ⟨a', b', ha', hb', h⟩, rcases hf h with ⟨rfl, rfl⟩, exact ⟨ha', hb'⟩ }, λ ⟨ha, hb⟩, mem_image2_of_mem ha hb⟩ /-- image2 is monotone with respect to `⊆`. -/ lemma image2_subset (hs : s ⊆ s') (ht : t ⊆ t') : image2 f s t ⊆ image2 f s' t' := by { rintro _ ⟨a, b, ha, hb, rfl⟩, exact mem_image2_of_mem (hs ha) (ht hb) } lemma forall_image2_iff {p : γ → Prop} : (∀ z ∈ image2 f s t, p z) ↔ ∀ (x ∈ s) (y ∈ t), p (f x y) := ⟨λ h x hx y hy, h _ ⟨x, y, hx, hy, rfl⟩, λ h z ⟨x, y, hx, hy, hz⟩, hz ▸ h x hx y hy⟩ @[simp] lemma image2_subset_iff {u : set γ} : image2 f s t ⊆ u ↔ ∀ (x ∈ s) (y ∈ t), f x y ∈ u := forall_image2_iff lemma image2_union_left : image2 f (s ∪ s') t = image2 f s t ∪ image2 f s' t := begin ext c, split, { rintros ⟨a, b, h1a|h2a, hb, rfl⟩;[left, right]; exact ⟨_, _, ‹_›, ‹_›, rfl⟩ }, { rintro (⟨_, _, _, _, rfl⟩|⟨_, _, _, _, rfl⟩); refine ⟨_, _, _, ‹_›, rfl⟩; simp [mem_union, *] } end lemma image2_union_right : image2 f s (t ∪ t') = image2 f s t ∪ image2 f s t' := begin ext c, split, { rintros ⟨a, b, ha, h1b|h2b, rfl⟩;[left, right]; exact ⟨_, _, ‹_›, ‹_›, rfl⟩ }, { rintro (⟨_, _, _, _, rfl⟩|⟨_, _, _, _, rfl⟩); refine ⟨_, _, ‹_›, _, rfl⟩; simp [mem_union, *] } end @[simp] lemma image2_empty_left : image2 f ∅ t = ∅ := ext $ by simp @[simp] lemma image2_empty_right : image2 f s ∅ = ∅ := ext $ by simp lemma image2_inter_subset_left : image2 f (s ∩ s') t ⊆ image2 f s t ∩ image2 f s' t := by { rintro _ ⟨a, b, ⟨h1a, h2a⟩, hb, rfl⟩, split; exact ⟨_, _, ‹_›, ‹_›, rfl⟩ } lemma image2_inter_subset_right : image2 f s (t ∩ t') ⊆ image2 f s t ∩ image2 f s t' := by { rintro _ ⟨a, b, ha, ⟨h1b, h2b⟩, rfl⟩, split; exact ⟨_, _, ‹_›, ‹_›, rfl⟩ } @[simp] lemma image2_singleton_left : image2 f {a} t = f a '' t := ext $ λ x, by simp @[simp] lemma image2_singleton_right : image2 f s {b} = (λ a, f a b) '' s := ext $ λ x, by simp lemma image2_singleton : image2 f {a} {b} = {f a b} := by simp @[congr] lemma image2_congr (h : ∀ (a ∈ s) (b ∈ t), f a b = f' a b) : image2 f s t = image2 f' s t := by { ext, split; rintro ⟨a, b, ha, hb, rfl⟩; refine ⟨a, b, ha, hb, by rw h a ha b hb⟩ } /-- A common special case of `image2_congr` -/ lemma image2_congr' (h : ∀ a b, f a b = f' a b) : image2 f s t = image2 f' s t := image2_congr (λ a _ b _, h a b) /-- The image of a ternary function `f : α → β → γ → δ` as a function `set α → set β → set γ → set δ`. Mathematically this should be thought of as the image of the corresponding function `α × β × γ → δ`. -/ def image3 (g : α → β → γ → δ) (s : set α) (t : set β) (u : set γ) : set δ := {d | ∃ a b c, a ∈ s ∧ b ∈ t ∧ c ∈ u ∧ g a b c = d } @[simp] lemma mem_image3 : d ∈ image3 g s t u ↔ ∃ a b c, a ∈ s ∧ b ∈ t ∧ c ∈ u ∧ g a b c = d := iff.rfl @[congr] lemma image3_congr (h : ∀ (a ∈ s) (b ∈ t) (c ∈ u), g a b c = g' a b c) : image3 g s t u = image3 g' s t u := by { ext x, split; rintro ⟨a, b, c, ha, hb, hc, rfl⟩; exact ⟨a, b, c, ha, hb, hc, by rw h a ha b hb c hc⟩ } /-- A common special case of `image3_congr` -/ lemma image3_congr' (h : ∀ a b c, g a b c = g' a b c) : image3 g s t u = image3 g' s t u := image3_congr (λ a _ b _ c _, h a b c) lemma image2_image2_left (f : δ → γ → ε) (g : α → β → δ) : image2 f (image2 g s t) u = image3 (λ a b c, f (g a b) c) s t u := begin ext, split, { rintro ⟨_, c, ⟨a, b, ha, hb, rfl⟩, hc, rfl⟩, refine ⟨a, b, c, ha, hb, hc, rfl⟩ }, { rintro ⟨a, b, c, ha, hb, hc, rfl⟩, refine ⟨_, c, ⟨a, b, ha, hb, rfl⟩, hc, rfl⟩ } end lemma image2_image2_right (f : α → δ → ε) (g : β → γ → δ) : image2 f s (image2 g t u) = image3 (λ a b c, f a (g b c)) s t u := begin ext, split, { rintro ⟨a, _, ha, ⟨b, c, hb, hc, rfl⟩, rfl⟩, refine ⟨a, b, c, ha, hb, hc, rfl⟩ }, { rintro ⟨a, b, c, ha, hb, hc, rfl⟩, refine ⟨a, _, ha, ⟨b, c, hb, hc, rfl⟩, rfl⟩ } end lemma image2_assoc {ε'} {f : δ → γ → ε} {g : α → β → δ} {f' : α → ε' → ε} {g' : β → γ → ε'} (h_assoc : ∀ a b c, f (g a b) c = f' a (g' b c)) : image2 f (image2 g s t) u = image2 f' s (image2 g' t u) := by simp only [image2_image2_left, image2_image2_right, h_assoc] lemma image_image2 (f : α → β → γ) (g : γ → δ) : g '' image2 f s t = image2 (λ a b, g (f a b)) s t := begin ext, split, { rintro ⟨_, ⟨a, b, ha, hb, rfl⟩, rfl⟩, refine ⟨a, b, ha, hb, rfl⟩ }, { rintro ⟨a, b, ha, hb, rfl⟩, refine ⟨_, ⟨a, b, ha, hb, rfl⟩, rfl⟩ } end lemma image2_image_left (f : γ → β → δ) (g : α → γ) : image2 f (g '' s) t = image2 (λ a b, f (g a) b) s t := begin ext, split, { rintro ⟨_, b, ⟨a, ha, rfl⟩, hb, rfl⟩, refine ⟨a, b, ha, hb, rfl⟩ }, { rintro ⟨a, b, ha, hb, rfl⟩, refine ⟨_, b, ⟨a, ha, rfl⟩, hb, rfl⟩ } end lemma image2_image_right (f : α → γ → δ) (g : β → γ) : image2 f s (g '' t) = image2 (λ a b, f a (g b)) s t := begin ext, split, { rintro ⟨a, _, ha, ⟨b, hb, rfl⟩, rfl⟩, refine ⟨a, b, ha, hb, rfl⟩ }, { rintro ⟨a, b, ha, hb, rfl⟩, refine ⟨a, _, ha, ⟨b, hb, rfl⟩, rfl⟩ } end lemma image2_swap (f : α → β → γ) (s : set α) (t : set β) : image2 f s t = image2 (λ a b, f b a) t s := by { ext, split; rintro ⟨a, b, ha, hb, rfl⟩; refine ⟨b, a, hb, ha, rfl⟩ } @[simp] lemma image2_left (h : t.nonempty) : image2 (λ x y, x) s t = s := by simp [nonempty_def.mp h, ext_iff] @[simp] lemma image2_right (h : s.nonempty) : image2 (λ x y, y) s t = t := by simp [nonempty_def.mp h, ext_iff] @[simp] lemma image_prod (f : α → β → γ) : (λ x : α × β, f x.1 x.2) '' s.prod t = image2 f s t := set.ext $ λ a, ⟨ by { rintros ⟨_, _, rfl⟩, exact ⟨_, _, (mem_prod.mp ‹_›).1, (mem_prod.mp ‹_›).2, rfl⟩ }, by { rintros ⟨_, _, _, _, rfl⟩, exact ⟨(_, _), mem_prod.mpr ⟨‹_›, ‹_›⟩, rfl⟩ }⟩ lemma nonempty.image2 (hs : s.nonempty) (ht : t.nonempty) : (image2 f s t).nonempty := by { cases hs with a ha, cases ht with b hb, exact ⟨f a b, ⟨a, b, ha, hb, rfl⟩⟩ } end n_ary_image end set namespace subsingleton variables {α : Type*} [subsingleton α] lemma eq_univ_of_nonempty {s : set α} : s.nonempty → s = univ := λ ⟨x, hx⟩, eq_univ_of_forall $ λ y, subsingleton.elim x y ▸ hx @[elab_as_eliminator] lemma set_cases {p : set α → Prop} (h0 : p ∅) (h1 : p univ) (s) : p s := s.eq_empty_or_nonempty.elim (λ h, h.symm ▸ h0) $ λ h, (eq_univ_of_nonempty h).symm ▸ h1 end subsingleton
8b8258f796e5fd5a22b7005fe8780dfffc301b85
41ebf3cb010344adfa84907b3304db00e02db0a6
/uexp/src/uexp/rules/transitiveInferenceJoin3way.lean
a9deb0445c96c1381824d5784430d7640478c51c
[ "BSD-2-Clause" ]
permissive
ReinierKoops/Cosette
e061b2ba58b26f4eddf4cd052dcf7abd16dfe8fb
eb8dadd06ee05fe7b6b99de431dd7c4faef5cb29
refs/heads/master
1,686,483,953,198
1,624,293,498,000
1,624,293,498,000
378,997,885
0
0
BSD-2-Clause
1,624,293,485,000
1,624,293,484,000
null
UTF-8
Lean
false
false
2,660
lean
import ..sql import ..tactics import ..u_semiring import ..extra_constants import ..meta.ucongr import ..meta.TDP open Expr open Proj open Pred open SQL open tree set_option profiler true notation `int` := datatypes.int variable integer_1: const datatypes.int variable integer_7: const datatypes.int theorem rule: forall ( Γ scm_t scm_account scm_bonus scm_dept scm_emp: Schema) (rel_t: relation scm_t) (rel_account: relation scm_account) (rel_bonus: relation scm_bonus) (rel_dept: relation scm_dept) (rel_emp: relation scm_emp) (t_k0 : Column int scm_t) (t_c1 : Column int scm_t) (t_f1_a0 : Column int scm_t) (t_f2_a0 : Column int scm_t) (t_f0_c0 : Column int scm_t) (t_f1_c0 : Column int scm_t) (t_f0_c1 : Column int scm_t) (t_f1_c2 : Column int scm_t) (t_f2_c3 : Column int scm_t) (account_acctno : Column int scm_account) (account_type : Column int scm_account) (account_balance : Column int scm_account) (bonus_ename : Column int scm_bonus) (bonus_job : Column int scm_bonus) (bonus_sal : Column int scm_bonus) (bonus_comm : Column int scm_bonus) (dept_deptno : Column int scm_dept) (dept_name : Column int scm_dept) (emp_empno : Column int scm_emp) (emp_ename : Column int scm_emp) (emp_job : Column int scm_emp) (emp_mgr : Column int scm_emp) (emp_hiredate : Column int scm_emp) (emp_comm : Column int scm_emp) (emp_sal : Column int scm_emp) (emp_deptno : Column int scm_emp) (emp_slacker : Column int scm_emp), denoteSQL ((SELECT1 (e2p (constantExpr integer_1)) FROM1 (product ((SELECT * FROM1 (table rel_emp) WHERE (castPred (combine (right⋅emp_deptno) (e2p (constantExpr integer_7)) ) predicates.gt))) (product (table rel_emp) (table rel_emp))) WHERE (and (equal (uvariable (right⋅left⋅emp_deptno)) (uvariable (right⋅right⋅left⋅emp_deptno))) (equal (uvariable (right⋅right⋅left⋅emp_deptno)) (uvariable (right⋅right⋅right⋅emp_deptno))))) :SQL Γ _) = denoteSQL ((SELECT1 (e2p (constantExpr integer_1)) FROM1 (product ((SELECT * FROM1 (table rel_emp) WHERE (castPred (combine (right⋅emp_deptno) (e2p (constantExpr integer_7)) ) predicates.gt))) (product ((SELECT * FROM1 (table rel_emp) WHERE (castPred (combine (right⋅emp_deptno) (e2p (constantExpr integer_7)) ) predicates.gt))) ((SELECT * FROM1 (table rel_emp) WHERE (castPred (combine (right⋅emp_deptno) (e2p (constantExpr integer_7)) ) predicates.gt))))) WHERE (and (equal (uvariable (right⋅left⋅emp_deptno)) (uvariable (right⋅right⋅left⋅emp_deptno))) (equal (uvariable (right⋅right⋅left⋅emp_deptno)) (uvariable (right⋅right⋅right⋅emp_deptno))))) :SQL Γ _) := begin intros, unfold_all_denotations, funext, try {simp}, TDP, end
d122640071e584aed9174a470bc48870fc66e056
9ee042bf34eebe0464f0f80c0db14ceb048dab10
/stage0/src/Lean/Parser/Command.lean
c756db4624c7c5b9901897975423fda1a7846f50
[ "Apache-2.0" ]
permissive
dexmagic/lean4
7507e7b07dc9f49db45df5ebd011886367dc2a6c
48764b60d5bac337eaff4bf8a3d63a216e1d9e03
refs/heads/master
1,692,156,265,016
1,633,276,980,000
1,633,339,480,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
11,111
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ import Lean.Parser.Term import Lean.Parser.Do namespace Lean namespace Parser /-- Syntax quotation for terms and (lists of) commands. We prefer terms, so ambiguous quotations like `` `($x $y) `` will be parsed as an application, not two commands. Use `` `($x:command $y:command) `` instead. Multiple command will be put in a `` `null `` node, but a single command will not (so that you can directly match against a quotation in a command kind's elaborator). -/ -- TODO: use two separate quotation parsers with parser priorities instead @[builtinTermParser] def Term.quot := leading_parser "`(" >> incQuotDepth (termParser <|> many1Unbox commandParser) >> ")" @[builtinTermParser] def Term.precheckedQuot := leading_parser "`" >> Term.quot namespace Command -- A mutual block may be broken in different cliques, we identify them using an `ident` (an element of the clique) def terminationByMany := leading_parser atomic (lookahead (ident >> " => ")) >> many1Indent (group (ppLine >> ident >> " => " >> termParser >> optional ";")) -- Simpler syntax for mutual blocks containing single clique that requires well-founded recursion. def terminationBy1 := leading_parser termParser def terminationBy := leading_parser "termination_by " >> (terminationByMany <|> terminationBy1) def decreasingTactic := leading_parser "decreasing_tactic " >> Tactic.tacticSeq def terminationSuffix := optional terminationBy >> optional decreasingTactic @[builtinCommandParser] def moduleDoc := leading_parser ppDedent $ "/-!" >> commentBody >> ppLine def namedPrio := leading_parser (atomic ("(" >> nonReservedSymbol "priority") >> " := " >> priorityParser >> ")") def optNamedPrio := optional namedPrio def «private» := leading_parser "private " def «protected» := leading_parser "protected " def visibility := «private» <|> «protected» def «noncomputable» := leading_parser "noncomputable " def «unsafe» := leading_parser "unsafe " def «partial» := leading_parser "partial " def «nonrec» := leading_parser "nonrec " def declModifiers (inline : Bool) := leading_parser optional docComment >> optional (Term.«attributes» >> if inline then skip else ppDedent ppLine) >> optional visibility >> optional «noncomputable» >> optional «unsafe» >> optional («partial» <|> «nonrec») def declId := leading_parser ident >> optional (".{" >> sepBy1 ident ", " >> "}") def declSig := leading_parser many (ppSpace >> (Term.simpleBinderWithoutType <|> Term.bracketedBinder)) >> Term.typeSpec def optDeclSig := leading_parser many (ppSpace >> (Term.simpleBinderWithoutType <|> Term.bracketedBinder)) >> Term.optType def declValSimple := leading_parser " :=\n" >> termParser >> optional Term.whereDecls def declValEqns := leading_parser Term.matchAltsWhereDecls def declVal := declValSimple <|> declValEqns <|> Term.whereDecls def «abbrev» := leading_parser "abbrev " >> declId >> optDeclSig >> declVal def optDefDeriving := optional (atomic ("deriving " >> notSymbol "instance") >> sepBy1 ident ", ") def «def» := leading_parser "def " >> declId >> optDeclSig >> declVal >> optDefDeriving >> terminationSuffix def «theorem» := leading_parser "theorem " >> declId >> declSig >> declVal >> terminationSuffix def «constant» := leading_parser "constant " >> declId >> declSig >> optional declValSimple def «instance» := leading_parser Term.attrKind >> "instance " >> optNamedPrio >> optional declId >> declSig >> declVal >> terminationSuffix def «axiom» := leading_parser "axiom " >> declId >> declSig def «example» := leading_parser "example " >> declSig >> declVal def inferMod := leading_parser atomic (symbol "{" >> "}") def ctor := leading_parser "\n| " >> declModifiers true >> ident >> optional inferMod >> optDeclSig def derivingClasses := sepBy1 (group (ident >> optional (" with " >> Term.structInst))) ", " def optDeriving := leading_parser optional (atomic ("deriving " >> notSymbol "instance") >> derivingClasses) def «inductive» := leading_parser "inductive " >> declId >> optDeclSig >> optional (symbol ":=" <|> "where") >> many ctor >> optDeriving def classInductive := leading_parser atomic (group (symbol "class " >> "inductive ")) >> declId >> optDeclSig >> optional (symbol ":=" <|> "where") >> many ctor >> optDeriving def structExplicitBinder := leading_parser atomic (declModifiers true >> "(") >> many1 ident >> optional inferMod >> optDeclSig >> optional (Term.binderTactic <|> Term.binderDefault) >> ")" def structImplicitBinder := leading_parser atomic (declModifiers true >> "{") >> many1 ident >> optional inferMod >> declSig >> "}" def structInstBinder := leading_parser atomic (declModifiers true >> "[") >> many1 ident >> optional inferMod >> declSig >> "]" def structSimpleBinder := leading_parser atomic (declModifiers true >> ident) >> optional inferMod >> optDeclSig >> optional (Term.binderTactic <|> Term.binderDefault) def structFields := leading_parser manyIndent (ppLine >> checkColGe >>(structExplicitBinder <|> structImplicitBinder <|> structInstBinder <|> structSimpleBinder)) def structCtor := leading_parser atomic (declModifiers true >> ident >> optional inferMod >> " :: ") def structureTk := leading_parser "structure " def classTk := leading_parser "class " def «extends» := leading_parser " extends " >> sepBy1 termParser ", " def «structure» := leading_parser (structureTk <|> classTk) >> declId >> many Term.bracketedBinder >> optional «extends» >> Term.optType >> optional ((symbol " := " <|> " where ") >> optional structCtor >> structFields) >> optDeriving @[builtinCommandParser] def declaration := leading_parser declModifiers false >> («abbrev» <|> «def» <|> «theorem» <|> «constant» <|> «instance» <|> «axiom» <|> «example» <|> «inductive» <|> classInductive <|> «structure») @[builtinCommandParser] def «deriving» := leading_parser "deriving " >> "instance " >> derivingClasses >> " for " >> sepBy1 ident ", " @[builtinCommandParser] def «section» := leading_parser "section " >> optional ident @[builtinCommandParser] def «namespace» := leading_parser "namespace " >> ident @[builtinCommandParser] def «end» := leading_parser "end " >> optional ident @[builtinCommandParser] def «variable» := leading_parser "variable" >> many1 Term.bracketedBinder @[builtinCommandParser] def «universe» := leading_parser "universe " >> many1 ident @[builtinCommandParser] def check := leading_parser "#check " >> termParser @[builtinCommandParser] def check_failure := leading_parser "#check_failure " >> termParser -- Like `#check`, but succeeds only if term does not type check @[builtinCommandParser] def reduce := leading_parser "#reduce " >> termParser @[builtinCommandParser] def eval := leading_parser "#eval " >> termParser @[builtinCommandParser] def synth := leading_parser "#synth " >> termParser @[builtinCommandParser] def exit := leading_parser "#exit" @[builtinCommandParser] def print := leading_parser "#print " >> (ident <|> strLit) @[builtinCommandParser] def printAxioms := leading_parser "#print " >> nonReservedSymbol "axioms " >> ident @[builtinCommandParser] def «resolve_name» := leading_parser "#resolve_name " >> ident @[builtinCommandParser] def «init_quot» := leading_parser "init_quot" def optionValue := nonReservedSymbol "true" <|> nonReservedSymbol "false" <|> strLit <|> numLit @[builtinCommandParser] def «set_option» := leading_parser "set_option " >> ident >> ppSpace >> optionValue def eraseAttr := leading_parser "-" >> rawIdent @[builtinCommandParser] def «attribute» := leading_parser "attribute " >> "[" >> sepBy1 (eraseAttr <|> Term.attrInstance) ", " >> "] " >> many1 ident @[builtinCommandParser] def «export» := leading_parser "export " >> ident >> "(" >> many1 ident >> ")" def openHiding := leading_parser atomic (ident >> "hiding") >> many1 (checkColGt >> ident) def openRenamingItem := leading_parser ident >> unicodeSymbol "→" "->" >> checkColGt >> ident def openRenaming := leading_parser atomic (ident >> "renaming") >> sepBy1 openRenamingItem ", " def openOnly := leading_parser atomic (ident >> "(") >> many1 ident >> ")" def openSimple := leading_parser many1 (checkColGt >> ident) def openScoped := leading_parser "scoped " >> many1 (checkColGt >> ident) def openDecl := openHiding <|> openRenaming <|> openOnly <|> openSimple <|> openScoped @[builtinCommandParser] def «open» := leading_parser withPosition ("open " >> openDecl) @[builtinCommandParser] def «mutual» := leading_parser "mutual " >> many1 (ppLine >> notSymbol "end" >> commandParser) >> ppDedent (ppLine >> "end") >> terminationSuffix @[builtinCommandParser] def «initialize» := leading_parser optional visibility >> "initialize " >> optional (atomic (ident >> Term.typeSpec >> Term.leftArrow)) >> Term.doSeq @[builtinCommandParser] def «builtin_initialize» := leading_parser optional visibility >> "builtin_initialize " >> optional (atomic (ident >> Term.typeSpec >> Term.leftArrow)) >> Term.doSeq @[builtinCommandParser] def «in» := trailing_parser withOpen (" in " >> commandParser) /- This is an auxiliary command for generation constructor injectivity theorems for inductive types defined at `Prelude.lean`. It is meant for bootstrapping purposes only. -/ @[builtinCommandParser] def genInjectiveTheorems := leading_parser "gen_injective_theorems% " >> ident @[runBuiltinParserAttributeHooks] abbrev declModifiersF := declModifiers false @[runBuiltinParserAttributeHooks] abbrev declModifiersT := declModifiers true builtin_initialize register_parser_alias "declModifiers" declModifiersF register_parser_alias "nestedDeclModifiers" declModifiersT register_parser_alias declId register_parser_alias declSig register_parser_alias declVal register_parser_alias optDeclSig register_parser_alias openDecl end Command namespace Term @[builtinTermParser] def «open» := leading_parser:leadPrec "open " >> Command.openDecl >> withOpenDecl (" in " >> termParser) @[builtinTermParser] def «set_option» := leading_parser:leadPrec "set_option " >> ident >> ppSpace >> Command.optionValue >> " in " >> termParser end Term namespace Tactic @[builtinTacticParser] def «open» := leading_parser:leadPrec "open " >> Command.openDecl >> withOpenDecl (" in " >> tacticSeq) @[builtinTacticParser] def «set_option» := leading_parser:leadPrec "set_option " >> ident >> ppSpace >> Command.optionValue >> " in " >> tacticSeq end Tactic end Parser end Lean
8ab8eb6ad287c869300b87d134d1a607ad0d1ae6
ed9ca7f44f366ca3a04272f939b2275961f36c59
/src/for_mathlib/open_subgroup.lean
148fbf87a689bdfff99c24808c08f63c2b377d71
[ "Apache-2.0" ]
permissive
wh941231/lean-perfectoid-spaces
e88fb5d76746009242349f276cd0920285d8beb9
43954f64ce4afdf4fa39e2aeef8ec43826b24f2a
refs/heads/master
1,653,641,928,775
1,588,499,720,000
1,588,499,720,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
701
lean
import topology.algebra.open_subgroup open topological_space variables (G : Type*) [group G] [topological_space G] [topological_group G] namespace open_subgroup def of_mem_nhds {s : set G} [is_subgroup s] (h : s ∈ nhds (1 : G)) : open_subgroup G := ⟨s, is_open_of_nonempty_open_subset (by { rcases mem_nhds_sets_iff.mp h with ⟨U, UG, U_op, one_U⟩, exact ⟨⟨U, U_op⟩, ⟨⟨(1 : G), one_U⟩⟩, UG⟩ }), by apply_instance⟩ attribute [to_additive open_add_subgroup.of_mem_nhds._proof_1] of_mem_nhds._proof_1 attribute [to_additive open_add_subgroup.of_mem_nhds] of_mem_nhds end open_subgroup attribute [to_additive open_add_subgroup.mem_nhds_zero] open_subgroup.mem_nhds_one
bc086d72f3239d6ed08d515c75c3f26daf0f6c03
2bafba05c98c1107866b39609d15e849a4ca2bb8
/src/week_5/solutions/Part_A_filters.lean
e4a3f3cec9bb7ecd4d11bd0c009069690b14a74d
[ "Apache-2.0" ]
permissive
ImperialCollegeLondon/formalising-mathematics
b54c83c94b5c315024ff09997fcd6b303892a749
7cf1d51c27e2038d2804561d63c74711924044a1
refs/heads/master
1,651,267,046,302
1,638,888,459,000
1,638,888,459,000
331,592,375
284
24
Apache-2.0
1,669,593,705,000
1,611,224,849,000
Lean
UTF-8
Lean
false
false
15,152
lean
import order.filter.basic -- the basics /- # Filters ## Introduction A topological space structure on a type `α` is a collection of subsets of `α` (the open sets) satisfying some axioms. A filter is a similar kind of thing -- it's a collection of subsets of `α` satisfying some different axioms. Before we go into the formal definition, let us start with the picture. A filter on `α` is an extremely powerful generalisation of the concept of a subset of `α`. If `S : set α` is a subset, then there is a principal filter `𝓟 S` corresponding to `S` -- it is just the collection of all subsets of `α` which contain `S`. However there may be other filters on `α` corresponding to things which are a bit more general than subsets. For example if `α` is a topological space and `x : α` then there is a filter `𝓝 x` corresponding to "an infinitesimal neighbourhood of `x`" even if there is no smallest open set containing `x`. As another example, if `α` has an ordering then there is a filter of "neighbourhoods of infinity" on `α` even though there might be no `∞` in `α`. If `F` is a filter, then you can think of `F` as a generalised kind of subset `F` of `α`, and you should think of `S ∈ F` as meaning `F ⊆ S`. Keeping this in mind will help to motivate the axioms below. ## Definition Here's the formal definition. A filter on `α` is a collection `F` of subsets of `α` satisfying the following three axioms: 1) `α ∈ F` (in Lean this is written `univ ∈ F` because a distinction is made between the type `α` and the term `univ : set α` corresponding to `α`) 2) If `S ∈ F` and `S ⊆ T` then `T ∈ F` -- i.e. `F` is "upwards-closed", 3) If `A ∈ F` and `B ∈ F` then `A ∩ B ∈ F` -- i.e. `F` is closed under binary intersections. Note that (1) and (3) together imply (and are indeed equivalent to) the statement that `F` is closed under all finite intersections, i.e. the intersection of finitely many elements of `F` is in `F`. Here's the Lean definition: ``` structure filter (α : Type*) := (sets : set (set α)) (univ_sets : set.univ ∈ sets) (sets_of_superset {x y} : x ∈ sets → x ⊆ y → y ∈ sets) (inter_sets {x y} : x ∈ sets → y ∈ sets → x ∩ y ∈ sets) ``` In words, `filter α` is the type of filters on `α`, so to give a filter on `α` is to give a term `F : filter α` of type `filter α`. To make a term of type `filter α` you need to give a collection `sets` of subsets of `α` and then three proofs of the three axioms. A rather simple example of a filter is the filter of *all* subsets of `α`. Those of you who have seen definitions of filters in other places (for example in Bourbaki) might have seen an extra axiom in the definition of a filter, saying that a filter is not allowed to be the collection of all subsets of `α`. This turns out to be rather an unnatural axiom, it is like demanding in ideal theory that if `R` is a ring then `R` is not allowed to be an ideal of `R`. An advantage of such a definition of an ideal would be that a maximal ideal of `R` would literally be a maximal element of the ideals of `R`, but this advantage is outweighed by the disadvantage that the definition then becomes much less functorial -- e.g. the image of an ideal along a ring homomorphism might not be an ideal, you cannot in general add two ideals etc). To preserve the functoriality of filters, mathlib does not have this Bourbaki axiom as an axiom for filters. As a result there are two "extreme" filters on `α`, namely the one which only contains `univ` (note that this is forced by `univ_sets`), and then the one we mentioned above, which contains all subsets of `α`. These two filters are called `⊥` and `⊤`, although you might be surprised to find out which one is which! The filter consisting of all subsets of `α` is the one corresponding to the empty set, so it is `⊥`, and the one consisting of just `univ` is the one corresponding to the whole of `α` so it is `⊤`. ## Notation, helpful tactics and helpful theorems We are not going to build filters from first principles, we will be using Lean's API for filters. Say `α : Type` and `F : filter α` and `S : set α`. The notation `S ∈ F` is defined to mean `S ∈ F.sets`. The `ext` tactic can be used to reduce a goal `F = G` to a goal of the form `∀ S, S ∈ F ↔ S ∈ G`. The fields of the structure mention things like `S ∈ F.sets`, so the axioms are restated with different names, but using the `S ∈ F` notation. The lemmas corresponding to the definitions are: `univ_mem_sets : univ ∈ F` `mem_sets_of_superset : S ∈ F → S ⊆ T → T ∈ F` `inter_mem_sets : S ∈ F → T ∈ F → S ∩ T ∈ F` These lemmas in the `filter` namespace, i.e. their full names are `filter.univ_mem_sets` etc. But we are about to say `open filter` which means that you don't have to type this `filter.` thing in front of every lemma you need about filters. In fact we'll also be using a bunch of stuff about sets, like `set.inter_subset_left`, so why don't we `open set` as well. -/ open filter set -- Variables! -- let `α` be a type, let `F` be a filter on `α`, and let `S` and `T` -- denote subsets of `α`. variables (α : Type) (F : filter α) (S T : set α) /- Here's a lemma about filters: Two sets `S` and `T` are both in a filter `F` iff their intersection is. See if you can deduce it from the axioms of a filter. For this one it's useful to know the following results (from the set namespace) `inter_subset_left S T : S ∩ T ⊆ S` and `inter_subset_right S T : S ∩ T ⊆ S` -/ example : S ∩ T ∈ F ↔ S ∈ F ∧ T ∈ F := begin split, { intro hST, split, { apply mem_sets_of_superset hST, exact inter_subset_left S T }, { apply mem_sets_of_superset hST, exact inter_subset_right S T } }, { rintros ⟨hS, hT⟩, exact inter_mem_sets hS hT } end /- The principal filter `𝓟 X` generated by `X : set α` is the subsets of `α` which contain `X`. Prove that it's a filter. Helpful for this exercise: `mem_univ s : s ∈ univ` `subset.trans : A ⊆ B → B ⊆ C → A ⊆ C` `subset_inter : X ⊆ S → X ⊆ T → X ⊆ S ∩ T` (note that you could probably prove those last two things directly yourself, but we may as well use the interface for sets given that it's there) `mem_set_of_eq : x ∈ {a : α | p a} = p x` (this one is definitional, so you could use `change` instead, or just not rewrite it at all) -/ -- this is called `𝓟 X` in mathlib but let's just make it ourselves. example (X : set α) : filter α := { sets := {S : set α | X ⊆ S}, univ_sets := begin intros a ha, exact mem_univ _, end, sets_of_superset := begin intros S T hS hT, -- change X ⊆ T, -- change X ⊆ S at hS, exact subset.trans hS hT, end, inter_sets := begin intros S T hS hT, -- rw mem_set_of_eq at ⊢ hS hT, exact subset_inter hS hT, end } -- The notation for the principal filter generated by `X : set α` is `𝓟 X`. -- This notation is in the "filter locale", which is just a posh way -- of saying that you have to type open_locale filter -- in order to get the notation. /- ## The order (≤) on filters The following is unsurprising: the collection of all filters on `α` is partially ordered. Perhaps more surprising: the order is the other way around to what you think it should be! If `F` and `G` are filters on `α`, then `F ≤ G` is defined to mean that `G.sets ⊆ F.sets`, i.e. every set in the `G`-filter is also in the `F`-filter. Why is this? Well, think about principal filters. If `S ⊆ T` are two subsets, then `X ∈ 𝓟 T` implies `T ⊆ X`, so `S ⊆ X`, so `X ∈ 𝓟 S`. The smaller the set, the bigger the collection of sets in the filter. Let's formalise this. Show that 𝓟 S ≤ 𝓟 T ↔ S ⊆ T. Note that this is called `principal_mono` in mathlib but there's no harm in proving it yourself. Some helpful lemmas: `mem_principal_sets : T ∈ 𝓟 S ↔ S ⊆ T` `mem_principal_self S : S ∈ 𝓟 S` `le_def : F ≤ G ↔ ∀ (S : set α), S ∈ G → S ∈ F` -/ example (S T : set α) : 𝓟 S ≤ 𝓟 T ↔ S ⊆ T := begin split, { intro h, rw le_def at h, have hT : T ∈ 𝓟 T := mem_principal_self T, specialize h T hT, rwa mem_principal_sets at h }, { intro hST, rw le_def, intros X hX, rw mem_principal_sets at hX ⊢, exact subset.trans hST hX } end -- Here's another useful lemma about principal filters. -- It's called `le_principal_iff` in mathlib but why -- not try proving it yourself? example : F ≤ 𝓟 S ↔ S ∈ F := begin rw le_def, split, { intro h, apply h, exact mem_principal_self S }, { intros hSF X hX, rw mem_principal_sets at hX, exact mem_sets_of_superset hSF hX }, end /- ## Filters are a complete lattice Just like it's possible to talk about the topological space generated by a collection of subsets of `α` -- this is the smallest topology for which the given subsets are all open -- it's also possible to talk about the filter generated by a collection of subsets of `α`. One can define it as the intersection of all the filters that contain your given collection of subsets. In order theory, given a partial order (like the partial order on filters) you can start asking whether infs and sups exist. Filters are an example where all these things exist (finite and infinite infs and sups) and they satisfy a natural collection of axioms, making them into what is called a *complete lattice*. One can prove this by showing that "filter generated by these sets" and "underlying sets of a filter" are adjoint functors and then using the theory of Galois insertions. I talked about this a bit when doing subgroups, and won't talk about it again. -/ /- ## Other examples of filters. ### `at_top` filter on a totally ordered set Let `L` be a non-empty totally ordered set. Let's say that a subset `X` of `L` is "big" if there exists `x : L` such for all `y ≥ x`, `y ∈ X`. I claim that the big subsets are a filter. Check this. The mathematical idea is that the "big subsets" are the neighbourhoods of `∞`, so the corresponding filter is some representation of an infinitesimal neighbourhood of `∞`. Implementation notes: `linear_order L` is the type of linear orders on `L`. `e : L` is just an easy way of saying that `L` is nonempty. Recall that `max x y` is the max of x and y in a `linear_order`, and `le_max_left a b : a ≤ max a b` and similarly `le_max_right`. -/ def at_top (L : Type) [linear_order L] (e : L) : filter L := { sets := {X : set L | ∃ x : L, ∀ y, x ≤ y → y ∈ X}, univ_sets := begin use e, intros y hy, exact mem_univ y, end, sets_of_superset := begin rintros X Y ⟨x, hX⟩ hXY, --rw mem_set_of_eq, use x, intros y hxy, --rw subset_def at hXY, apply hXY, exact hX _ hxy, end, inter_sets := begin rintros X Y ⟨x, hX⟩ ⟨y, hY⟩, use max x y, intros z hz, split, { apply hX, apply le_trans _ hz, exact le_max_left x y }, { exact hY _ (le_trans (le_max_right _ _) hz) } end } /- ### the cofinite filter The _cofinite filter_ on a type `α` has as its sets the subsets `S : set α` with the property that `Sᶜ`, the complement of `S`, is finite. Let's show that these are a filter. Things you might find helpful: `compl_univ : univᶜ = ∅` `finite_empty : finite ∅` `compl_subset_compl : Xᶜ ⊆ Yᶜ ↔ Y ⊆ X` `finite.subset : S.finite → ∀ {T : set α}, T ⊆ S → T.finite` `compl_inter S T : (S ∩ T)ᶜ = Sᶜ ∪ Tᶜ` `finite.union : S.finite → T.finite → (S ∪ T).finite` NB if you are thinking "I could never use Lean by myself, I don't know the names of all the lemmas so I have to rely on Kevin telling them all to me" then what you don't realise is that I myself don't know the names of all the lemmas either -- I am literally just guessing them and pressing ctrl-space to check. Look at the names of the lemmas and begin to understand that you can probably guess them yourself. -/ def cofinite (α : Type) : filter α := { sets := { S : set α | (Sᶜ).finite }, univ_sets := begin rw mem_set_of_eq, rw compl_univ, exact finite_empty, end, sets_of_superset := begin intros S T hS hST, rw mem_set_of_eq at hS ⊢, rw ← compl_subset_compl at hST, exact finite.subset hS hST, end, inter_sets := begin intros S T hS hT, rw mem_set_of_eq at *, rw compl_inter, exact finite.union hS hT, end } /- ### Exercises (to do on paper): You don't need to be able to do these in order to move onto the topology part of this workshop. (1) prove that the cofinite filter on a finite type is the entire power set filter. (2) prove that the cofinite filter on `ℕ` is equal to the `at_top` filter. (3) Prove that the cofinite filter on `ℤ` is not equal to the `at_top` filter. (4) Prove that the cofinite filter on `ℕ` is not principal. You can try them in Lean but you will have to be a master of finiteness. Here, for example, are some of the ideas you'll need to do (4) in Lean. The proof uses a bunch of lemmas from the set API. Here are some of the things I used: `filter.ext_iff : F = G ↔ ∀ (S : set α), s ∈ F ↔ s ∈ G` Facts about `S \ {a}` and other sets: `diff_eq_compl_inter`, `compl_inter`, `compl_compl`, `finite_singleton`, `mem_diff_singleton`. I also needed the following two lemmas, which weren't in mathlib so I had to prove them myself (my proof of the first one was longer; thanks to Yakov Pechersky on Zulip for coming up with the one-linear) -/ lemma infinite_of_finite_compl {α : Type} [infinite α] {s : set α} (hs : sᶜ.finite) : s.infinite := λ h, set.infinite_univ (by simpa using hs.union h) lemma set.infinite.nonempty {α} {s : set α} (h : s.infinite) : ∃ a : α, a ∈ s := let a := set.infinite.nat_embedding s h 37 in ⟨a.1, a.2⟩ -- This is also convenient for rewriting purposes: lemma mem_cofinite {S : set ℕ} : S ∈ cofinite ℕ ↔ Sᶜ.finite := begin -- true by definition refl end -- Here's a proof which I formalised: if natural_cofinite = 𝓟 S then S must -- be cofinite and hence infinite and hence non-empty, but then if a ∈ S -- then S \ {a} causes us problems as it's cofinite but doesn't contain `S`. theorem cofinite_not_principal : ∀ S : set ℕ, cofinite ℕ ≠ 𝓟 S := begin intros S h, rw filter.ext_iff at h, have hS := h S, rw mem_cofinite at hS, have hS2 : Sᶜ.finite, { rw hS, apply mem_principal_self }, clear hS, have hS3 := infinite_of_finite_compl hS2, have hS4 : ∃ s : ℕ, s ∈ S := set.infinite.nonempty hS3, cases hS4 with a ha, set T := S \ {a} with hTdef, specialize h T, have hT : T ∈ cofinite ℕ, { rw [mem_cofinite, hTdef, diff_eq_compl_inter, compl_inter, compl_compl], apply finite.union _ hS2, apply finite_singleton }, rw h at hT, rw mem_principal_sets at hT, specialize hT ha, rw [hTdef, mem_diff_singleton] at hT, cases hT with _ hcontra, apply hcontra, refl, end
b035465ca59f2f0034ddd881d7bb65d573022852
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/data/int/range.lean
2f9f48ee2b88cd9972e760f53723c7f671d47521
[ "Apache-2.0" ]
permissive
abentkamp/mathlib
d9a75d291ec09f4637b0f30cc3880ffb07549ee5
5360e476391508e092b5a1e5210bd0ed22dc0755
refs/heads/master
1,682,382,954,948
1,622,106,077,000
1,622,106,077,000
149,285,665
0
0
null
null
null
null
UTF-8
Lean
false
false
1,794
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Kenny Lau -/ import data.int.basic import data.list.range namespace int local attribute [semireducible] int.nonneg /-- List enumerating `[m, n)`. -/ def range (m n : ℤ) : list ℤ := (list.range (to_nat (n-m))).map $ λ r, m+r theorem mem_range_iff {m n r : ℤ} : r ∈ range m n ↔ m ≤ r ∧ r < n := ⟨λ H, let ⟨s, h1, h2⟩ := list.mem_map.1 H in h2 ▸ ⟨le_add_of_nonneg_right trivial, add_lt_of_lt_sub_left $ match n-m, h1 with | (k:ℕ), h1 := by rwa [list.mem_range, to_nat_coe_nat, ← coe_nat_lt] at h1 end⟩, λ ⟨h1, h2⟩, list.mem_map.2 ⟨to_nat (r-m), list.mem_range.2 $ by rw [← coe_nat_lt, to_nat_of_nonneg (sub_nonneg_of_le h1), to_nat_of_nonneg (sub_nonneg_of_le (le_of_lt (lt_of_le_of_lt h1 h2)))]; exact sub_lt_sub_right h2 _, show m + _ = _, by rw [to_nat_of_nonneg (sub_nonneg_of_le h1), add_sub_cancel'_right]⟩⟩ instance decidable_le_lt (P : int → Prop) [decidable_pred P] (m n : ℤ) : decidable (∀ r, m ≤ r → r < n → P r) := decidable_of_iff (∀ r ∈ range m n, P r) $ by simp only [mem_range_iff, and_imp] instance decidable_le_le (P : int → Prop) [decidable_pred P] (m n : ℤ) : decidable (∀ r, m ≤ r → r ≤ n → P r) := decidable_of_iff (∀ r ∈ range m (n+1), P r) $ by simp only [mem_range_iff, and_imp, lt_add_one_iff] instance decidable_lt_lt (P : int → Prop) [decidable_pred P] (m n : ℤ) : decidable (∀ r, m < r → r < n → P r) := int.decidable_le_lt P _ _ instance decidable_lt_le (P : int → Prop) [decidable_pred P] (m n : ℤ) : decidable (∀ r, m < r → r ≤ n → P r) := int.decidable_le_le P _ _ end int
7426c91a1b84d956b290fd9d6600595b777b039b
bb31430994044506fa42fd667e2d556327e18dfe
/src/measure_theory/constructions/prod.lean
2f7ef21f9d5b7e5cc98abfd9957702c042e0b599
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
55,726
lean
/- 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 measure_theory.measure.giry_monad import dynamics.ergodic.measure_preserving import measure_theory.integral.set_integral import measure_theory.measure.open_pos /-! # The product measure In this file we define and prove properties about the binary product measure. If `α` and `β` have σ-finite measures `μ` resp. `ν` then `α × β` can be equipped with a σ-finite measure `μ.prod ν` that satisfies `(μ.prod ν) s = ∫⁻ x, ν {y | (x, y) ∈ s} ∂μ`. We also have `(μ.prod ν) (s ×ˢ t) = μ s * ν t`, i.e. the measure of a rectangle is the product of the measures of the sides. We also prove Tonelli's theorem and Fubini's theorem. ## Main definition * `measure_theory.measure.prod`: The product of two measures. ## Main results * `measure_theory.measure.prod_apply` states `μ.prod ν s = ∫⁻ x, ν {y | (x, y) ∈ s} ∂μ` for measurable `s`. `measure_theory.measure.prod_apply_symm` is the reversed version. * `measure_theory.measure.prod_prod` states `μ.prod ν (s ×ˢ t) = μ s * ν t` for measurable sets `s` and `t`. * `measure_theory.lintegral_prod`: Tonelli's theorem. It states that for a measurable function `α × β → ℝ≥0∞` we have `∫⁻ z, f z ∂(μ.prod ν) = ∫⁻ x, ∫⁻ y, f (x, y) ∂ν ∂μ`. The version for functions `α → β → ℝ≥0∞` is reversed, and called `lintegral_lintegral`. Both versions have a variant with `_symm` appended, where the order of integration is reversed. The lemma `measurable.lintegral_prod_right'` states that the inner integral of the right-hand side is measurable. * `measure_theory.integrable_prod_iff` states that a binary function is integrable iff both * `y ↦ f (x, y)` is integrable for almost every `x`, and * the function `x ↦ ∫ ‖f (x, y)‖ dy` is integrable. * `measure_theory.integral_prod`: Fubini's theorem. It states that for a integrable function `α × β → E` (where `E` is a second countable Banach space) we have `∫ z, f z ∂(μ.prod ν) = ∫ x, ∫ y, f (x, y) ∂ν ∂μ`. This theorem has the same variants as Tonelli's theorem. The lemma `measure_theory.integrable.integral_prod_right` states that the inner integral of the right-hand side is integrable. ## Implementation Notes Many results are proven twice, once for functions in curried form (`α → β → γ`) and one for functions in uncurried form (`α × β → γ`). The former often has an assumption `measurable (uncurry f)`, which could be inconvenient to discharge, but for the latter it is more common that the function has to be given explicitly, since Lean cannot synthesize the function by itself. We name the lemmas about the uncurried form with a prime. Tonelli's theorem and Fubini's theorem have a different naming scheme, since the version for the uncurried version is reversed. ## Tags product measure, Fubini's theorem, Tonelli's theorem, Fubini-Tonelli theorem -/ noncomputable theory open_locale classical topological_space ennreal measure_theory open set function real ennreal open measure_theory measurable_space measure_theory.measure open topological_space (hiding generate_from) open filter (hiding prod_eq map) variables {α α' β β' γ E : Type*} /-- Rectangles formed by π-systems form a π-system. -/ lemma is_pi_system.prod {C : set (set α)} {D : set (set β)} (hC : is_pi_system C) (hD : is_pi_system D) : is_pi_system (image2 (×ˢ) C D) := begin rintro _ ⟨s₁, t₁, hs₁, ht₁, rfl⟩ _ ⟨s₂, t₂, hs₂, ht₂, rfl⟩ hst, rw [prod_inter_prod] at hst ⊢, rw [prod_nonempty_iff] at hst, exact mem_image2_of_mem (hC _ hs₁ _ hs₂ hst.1) (hD _ ht₁ _ ht₂ hst.2) end /-- Rectangles of countably spanning sets are countably spanning. -/ lemma is_countably_spanning.prod {C : set (set α)} {D : set (set β)} (hC : is_countably_spanning C) (hD : is_countably_spanning D) : is_countably_spanning (image2 (×ˢ) C D) := begin rcases ⟨hC, hD⟩ with ⟨⟨s, h1s, h2s⟩, t, h1t, h2t⟩, refine ⟨λ n, (s n.unpair.1) ×ˢ (t n.unpair.2), λ n, mem_image2_of_mem (h1s _) (h1t _), _⟩, rw [Union_unpair_prod, h2s, h2t, univ_prod_univ] end variables [measurable_space α] [measurable_space α'] [measurable_space β] [measurable_space β'] variables [measurable_space γ] variables {μ μ' : measure α} {ν ν' : measure β} {τ : measure γ} variables [normed_add_comm_group E] /-! ### Measurability Before we define the product measure, we can talk about the measurability of operations on binary functions. We show that if `f` is a binary measurable function, then the function that integrates along one of the variables (using either the Lebesgue or Bochner integral) is measurable. -/ /-- The product of generated σ-algebras is the one generated by rectangles, if both generating sets are countably spanning. -/ lemma generate_from_prod_eq {α β} {C : set (set α)} {D : set (set β)} (hC : is_countably_spanning C) (hD : is_countably_spanning D) : @prod.measurable_space _ _ (generate_from C) (generate_from D) = generate_from (image2 (×ˢ) C D) := begin apply le_antisymm, { refine sup_le _ _; rw [comap_generate_from]; apply generate_from_le; rintro _ ⟨s, hs, rfl⟩, { rcases hD with ⟨t, h1t, h2t⟩, rw [← prod_univ, ← h2t, prod_Union], apply measurable_set.Union, intro n, apply measurable_set_generate_from, exact ⟨s, t n, hs, h1t n, rfl⟩ }, { rcases hC with ⟨t, h1t, h2t⟩, rw [← univ_prod, ← h2t, Union_prod_const], apply measurable_set.Union, rintro n, apply measurable_set_generate_from, exact mem_image2_of_mem (h1t n) hs } }, { apply generate_from_le, rintro _ ⟨s, t, hs, ht, rfl⟩, rw [prod_eq], apply (measurable_fst _).inter (measurable_snd _), { exact measurable_set_generate_from hs }, { exact measurable_set_generate_from ht } } end /-- If `C` and `D` generate the σ-algebras on `α` resp. `β`, then rectangles formed by `C` and `D` generate the σ-algebra on `α × β`. -/ lemma generate_from_eq_prod {C : set (set α)} {D : set (set β)} (hC : generate_from C = ‹_›) (hD : generate_from D = ‹_›) (h2C : is_countably_spanning C) (h2D : is_countably_spanning D) : generate_from (image2 (×ˢ) C D) = prod.measurable_space := by rw [← hC, ← hD, generate_from_prod_eq h2C h2D] /-- The product σ-algebra is generated from boxes, i.e. `s ×ˢ t` for sets `s : set α` and `t : set β`. -/ lemma generate_from_prod : generate_from (image2 (×ˢ) {s : set α | measurable_set s} {t : set β | measurable_set t}) = prod.measurable_space := generate_from_eq_prod generate_from_measurable_set generate_from_measurable_set is_countably_spanning_measurable_set is_countably_spanning_measurable_set /-- Rectangles form a π-system. -/ lemma is_pi_system_prod : is_pi_system (image2 (×ˢ) {s : set α | measurable_set s} {t : set β | measurable_set t}) := is_pi_system_measurable_set.prod is_pi_system_measurable_set /-- If `ν` is a finite measure, and `s ⊆ α × β` is measurable, then `x ↦ ν { y | (x, y) ∈ s }` is a measurable function. `measurable_measure_prod_mk_left` is strictly more general. -/ lemma measurable_measure_prod_mk_left_finite [is_finite_measure ν] {s : set (α × β)} (hs : measurable_set s) : measurable (λ x, ν (prod.mk x ⁻¹' s)) := begin refine induction_on_inter generate_from_prod.symm is_pi_system_prod _ _ _ _ hs, { simp [measurable_zero, const_def] }, { rintro _ ⟨s, t, hs, ht, rfl⟩, simp only [mk_preimage_prod_right_eq_if, measure_if], exact measurable_const.indicator hs }, { intros t ht h2t, simp_rw [preimage_compl, measure_compl (measurable_prod_mk_left ht) (measure_ne_top ν _)], exact h2t.const_sub _ }, { intros f h1f h2f h3f, simp_rw [preimage_Union], have : ∀ b, ν (⋃ i, prod.mk b ⁻¹' f i) = ∑' i, ν (prod.mk b ⁻¹' f i) := λ b, measure_Union (λ i j hij, disjoint.preimage _ (h1f hij)) (λ i, measurable_prod_mk_left (h2f i)), simp_rw [this], apply measurable.ennreal_tsum h3f }, end /-- If `ν` is a σ-finite measure, and `s ⊆ α × β` is measurable, then `x ↦ ν { y | (x, y) ∈ s }` is a measurable function. -/ lemma measurable_measure_prod_mk_left [sigma_finite ν] {s : set (α × β)} (hs : measurable_set s) : measurable (λ x, ν (prod.mk x ⁻¹' s)) := begin have : ∀ x, measurable_set (prod.mk x ⁻¹' s) := λ x, measurable_prod_mk_left hs, simp only [← @supr_restrict_spanning_sets _ _ ν, this], apply measurable_supr, intro i, haveI := fact.mk (measure_spanning_sets_lt_top ν i), exact measurable_measure_prod_mk_left_finite hs end /-- If `μ` is a σ-finite measure, and `s ⊆ α × β` is measurable, then `y ↦ μ { x | (x, y) ∈ s }` is a measurable function. -/ lemma measurable_measure_prod_mk_right {μ : measure α} [sigma_finite μ] {s : set (α × β)} (hs : measurable_set s) : measurable (λ y, μ ((λ x, (x, y)) ⁻¹' s)) := measurable_measure_prod_mk_left (measurable_set_swap_iff.mpr hs) lemma measurable.map_prod_mk_left [sigma_finite ν] : measurable (λ x : α, map (prod.mk x) ν) := begin apply measurable_of_measurable_coe, intros s hs, simp_rw [map_apply measurable_prod_mk_left hs], exact measurable_measure_prod_mk_left hs end lemma measurable.map_prod_mk_right {μ : measure α} [sigma_finite μ] : measurable (λ y : β, map (λ x : α, (x, y)) μ) := begin apply measurable_of_measurable_coe, intros s hs, simp_rw [map_apply measurable_prod_mk_right hs], exact measurable_measure_prod_mk_right hs end /-- The Lebesgue integral is measurable. This shows that the integrand of (the right-hand-side of) Tonelli's theorem is measurable. -/ lemma measurable.lintegral_prod_right' [sigma_finite ν] : ∀ {f : α × β → ℝ≥0∞} (hf : measurable f), measurable (λ x, ∫⁻ y, f (x, y) ∂ν) := begin have m := @measurable_prod_mk_left, refine measurable.ennreal_induction _ _ _, { intros c s hs, simp only [← indicator_comp_right], suffices : measurable (λ x, c * ν (prod.mk x ⁻¹' s)), { simpa [lintegral_indicator _ (m hs)] }, exact (measurable_measure_prod_mk_left hs).const_mul _ }, { rintro f g - hf hg h2f h2g, simp_rw [pi.add_apply, lintegral_add_left (hf.comp m)], exact h2f.add h2g }, { intros f hf h2f h3f, have := measurable_supr h3f, have : ∀ x, monotone (λ n y, f n (x, y)) := λ x i j hij y, h2f hij (x, y), simpa [lintegral_supr (λ n, (hf n).comp m), this] } end /-- The Lebesgue integral is measurable. This shows that the integrand of (the right-hand-side of) Tonelli's theorem is measurable. This version has the argument `f` in curried form. -/ lemma measurable.lintegral_prod_right [sigma_finite ν] {f : α → β → ℝ≥0∞} (hf : measurable (uncurry f)) : measurable (λ x, ∫⁻ y, f x y ∂ν) := hf.lintegral_prod_right' /-- The Lebesgue integral is measurable. This shows that the integrand of (the right-hand-side of) the symmetric version of Tonelli's theorem is measurable. -/ lemma measurable.lintegral_prod_left' [sigma_finite μ] {f : α × β → ℝ≥0∞} (hf : measurable f) : measurable (λ y, ∫⁻ x, f (x, y) ∂μ) := (measurable_swap_iff.mpr hf).lintegral_prod_right' /-- The Lebesgue integral is measurable. This shows that the integrand of (the right-hand-side of) the symmetric version of Tonelli's theorem is measurable. This version has the argument `f` in curried form. -/ lemma measurable.lintegral_prod_left [sigma_finite μ] {f : α → β → ℝ≥0∞} (hf : measurable (uncurry f)) : measurable (λ y, ∫⁻ x, f x y ∂μ) := hf.lintegral_prod_left' lemma measurable_set_integrable [sigma_finite ν] ⦃f : α → β → E⦄ (hf : strongly_measurable (uncurry f)) : measurable_set {x | integrable (f x) ν} := begin simp_rw [integrable, hf.of_uncurry_left.ae_strongly_measurable, true_and], exact measurable_set_lt (measurable.lintegral_prod_right hf.ennnorm) measurable_const end section variables [normed_space ℝ E] [complete_space E] /-- The Bochner integral is measurable. This shows that the integrand of (the right-hand-side of) Fubini's theorem is measurable. This version has `f` in curried form. -/ lemma measure_theory.strongly_measurable.integral_prod_right [sigma_finite ν] ⦃f : α → β → E⦄ (hf : strongly_measurable (uncurry f)) : strongly_measurable (λ x, ∫ y, f x y ∂ν) := begin borelize E, haveI : separable_space (range (uncurry f) ∪ {0} : set E) := hf.separable_space_range_union_singleton, let s : ℕ → simple_func (α × β) E := simple_func.approx_on _ hf.measurable (range (uncurry f) ∪ {0}) 0 (by simp), let s' : ℕ → α → simple_func β E := λ n x, (s n).comp (prod.mk x) measurable_prod_mk_left, let f' : ℕ → α → E := λ n, {x | integrable (f x) ν}.indicator (λ x, (s' n x).integral ν), have hf' : ∀ n, strongly_measurable (f' n), { intro n, refine strongly_measurable.indicator _ (measurable_set_integrable hf), have : ∀ x, (s' n x).range.filter (λ x, x ≠ 0) ⊆ (s n).range, { intros x, refine finset.subset.trans (finset.filter_subset _ _) _, intro y, simp_rw [simple_func.mem_range], rintro ⟨z, rfl⟩, exact ⟨(x, z), rfl⟩ }, simp only [simple_func.integral_eq_sum_of_subset (this _)], refine finset.strongly_measurable_sum _ (λ x _, _), refine (measurable.ennreal_to_real _).strongly_measurable.smul_const _, simp only [simple_func.coe_comp, preimage_comp] {single_pass := tt}, apply measurable_measure_prod_mk_left, exact (s n).measurable_set_fiber x }, have h2f' : tendsto f' at_top (𝓝 (λ (x : α), ∫ (y : β), f x y ∂ν)), { rw [tendsto_pi_nhds], intro x, by_cases hfx : integrable (f x) ν, { have : ∀ n, integrable (s' n x) ν, { intro n, apply (hfx.norm.add hfx.norm).mono' (s' n x).ae_strongly_measurable, apply eventually_of_forall, intro y, simp_rw [s', simple_func.coe_comp], exact simple_func.norm_approx_on_zero_le _ _ (x, y) n }, simp only [f', hfx, simple_func.integral_eq_integral _ (this _), indicator_of_mem, mem_set_of_eq], refine tendsto_integral_of_dominated_convergence (λ y, ‖f x y‖ + ‖f x y‖) (λ n, (s' n x).ae_strongly_measurable) (hfx.norm.add hfx.norm) _ _, { exact λ n, eventually_of_forall (λ y, simple_func.norm_approx_on_zero_le _ _ (x, y) n) }, { refine eventually_of_forall (λ y, simple_func.tendsto_approx_on _ _ _), apply subset_closure, simp [-uncurry_apply_pair], } }, { simp [f', hfx, integral_undef], } }, exact strongly_measurable_of_tendsto _ hf' h2f' end /-- The Bochner integral is measurable. This shows that the integrand of (the right-hand-side of) Fubini's theorem is measurable. -/ lemma measure_theory.strongly_measurable.integral_prod_right' [sigma_finite ν] ⦃f : α × β → E⦄ (hf : strongly_measurable f) : strongly_measurable (λ x, ∫ y, f (x, y) ∂ν) := by { rw [← uncurry_curry f] at hf, exact hf.integral_prod_right } /-- The Bochner integral is measurable. This shows that the integrand of (the right-hand-side of) the symmetric version of Fubini's theorem is measurable. This version has `f` in curried form. -/ lemma measure_theory.strongly_measurable.integral_prod_left [sigma_finite μ] ⦃f : α → β → E⦄ (hf : strongly_measurable (uncurry f)) : strongly_measurable (λ y, ∫ x, f x y ∂μ) := (hf.comp_measurable measurable_swap).integral_prod_right' /-- The Bochner integral is measurable. This shows that the integrand of (the right-hand-side of) the symmetric version of Fubini's theorem is measurable. -/ lemma measure_theory.strongly_measurable.integral_prod_left' [sigma_finite μ] ⦃f : α × β → E⦄ (hf : strongly_measurable f) : strongly_measurable (λ y, ∫ x, f (x, y) ∂μ) := (hf.comp_measurable measurable_swap).integral_prod_right' end /-! ### The product measure -/ namespace measure_theory namespace measure /-- The binary product of measures. They are defined for arbitrary measures, but we basically prove all properties under the assumption that at least one of them is σ-finite. -/ @[irreducible] protected def prod (μ : measure α) (ν : measure β) : measure (α × β) := bind μ $ λ x : α, map (prod.mk x) ν instance prod.measure_space {α β} [measure_space α] [measure_space β] : measure_space (α × β) := { volume := volume.prod volume } variables [sigma_finite ν] lemma volume_eq_prod (α β) [measure_space α] [measure_space β] : (volume : measure (α × β)) = (volume : measure α).prod (volume : measure β) := rfl lemma prod_apply {s : set (α × β)} (hs : measurable_set s) : μ.prod ν s = ∫⁻ x, ν (prod.mk x ⁻¹' s) ∂μ := by simp_rw [measure.prod, bind_apply hs measurable.map_prod_mk_left, map_apply measurable_prod_mk_left hs] /-- The product measure of the product of two sets is the product of their measures. Note that we do not need the sets to be measurable. -/ @[simp] lemma prod_prod (s : set α) (t : set β) : μ.prod ν (s ×ˢ t) = μ s * ν t := begin apply le_antisymm, { set ST := (to_measurable μ s) ×ˢ (to_measurable ν t), have hSTm : measurable_set ST := (measurable_set_to_measurable _ _).prod (measurable_set_to_measurable _ _), calc μ.prod ν (s ×ˢ t) ≤ μ.prod ν ST : measure_mono $ set.prod_mono (subset_to_measurable _ _) (subset_to_measurable _ _) ... = μ (to_measurable μ s) * ν (to_measurable ν t) : by simp_rw [prod_apply hSTm, mk_preimage_prod_right_eq_if, measure_if, lintegral_indicator _ (measurable_set_to_measurable _ _), lintegral_const, restrict_apply_univ, mul_comm] ... = μ s * ν t : by rw [measure_to_measurable, measure_to_measurable] }, { /- Formalization is based on https://mathoverflow.net/a/254134/136589 -/ set ST := to_measurable (μ.prod ν) (s ×ˢ t), have hSTm : measurable_set ST := measurable_set_to_measurable _ _, have hST : s ×ˢ t ⊆ ST := subset_to_measurable _ _, set f : α → ℝ≥0∞ := λ x, ν (prod.mk x ⁻¹' ST), have hfm : measurable f := measurable_measure_prod_mk_left hSTm, set s' : set α := {x | ν t ≤ f x}, have hss' : s ⊆ s' := λ x hx, measure_mono (λ y hy, hST $ mk_mem_prod hx hy), calc μ s * ν t ≤ μ s' * ν t : mul_le_mul_right' (measure_mono hss') _ ... = ∫⁻ x in s', ν t ∂μ : by rw [set_lintegral_const, mul_comm] ... ≤ ∫⁻ x in s', f x ∂μ : set_lintegral_mono measurable_const hfm (λ x, id) ... ≤ ∫⁻ x, f x ∂μ : lintegral_mono' restrict_le_self le_rfl ... = μ.prod ν ST : (prod_apply hSTm).symm ... = μ.prod ν (s ×ˢ t) : measure_to_measurable _ } end instance {X Y : Type*} [topological_space X] [topological_space Y] {m : measurable_space X} {μ : measure X} [is_open_pos_measure μ] {m' : measurable_space Y} {ν : measure Y} [is_open_pos_measure ν] [sigma_finite ν] : is_open_pos_measure (μ.prod ν) := begin constructor, rintros U U_open ⟨⟨x, y⟩, hxy⟩, rcases is_open_prod_iff.1 U_open x y hxy with ⟨u, v, u_open, v_open, xu, yv, huv⟩, refine ne_of_gt (lt_of_lt_of_le _ (measure_mono huv)), simp only [prod_prod, canonically_ordered_comm_semiring.mul_pos], split, { exact u_open.measure_pos μ ⟨x, xu⟩ }, { exact v_open.measure_pos ν ⟨y, yv⟩ } end instance {α β : Type*} {mα : measurable_space α} {mβ : measurable_space β} (μ : measure α) (ν : measure β) [is_finite_measure μ] [is_finite_measure ν] : is_finite_measure (μ.prod ν) := begin constructor, rw [← univ_prod_univ, prod_prod], exact mul_lt_top (measure_lt_top _ _).ne (measure_lt_top _ _).ne, end instance {α β : Type*} {mα : measurable_space α} {mβ : measurable_space β} (μ : measure α) (ν : measure β) [is_probability_measure μ] [is_probability_measure ν] : is_probability_measure (μ.prod ν) := ⟨by rw [← univ_prod_univ, prod_prod, measure_univ, measure_univ, mul_one]⟩ instance {α β : Type*} [topological_space α] [topological_space β] {mα : measurable_space α} {mβ : measurable_space β} (μ : measure α) (ν : measure β) [is_finite_measure_on_compacts μ] [is_finite_measure_on_compacts ν] [sigma_finite ν] : is_finite_measure_on_compacts (μ.prod ν) := begin refine ⟨λ K hK, _⟩, set L := (prod.fst '' K) ×ˢ (prod.snd '' K) with hL, have : K ⊆ L, { rintros ⟨x, y⟩ hxy, simp only [prod_mk_mem_set_prod_eq, mem_image, prod.exists, exists_and_distrib_right, exists_eq_right], exact ⟨⟨y, hxy⟩, ⟨x, hxy⟩⟩ }, apply lt_of_le_of_lt (measure_mono this), rw [hL, prod_prod], exact mul_lt_top ((is_compact.measure_lt_top ((hK.image continuous_fst))).ne) ((is_compact.measure_lt_top ((hK.image continuous_snd))).ne) end lemma ae_measure_lt_top {s : set (α × β)} (hs : measurable_set s) (h2s : (μ.prod ν) s ≠ ∞) : ∀ᵐ x ∂μ, ν (prod.mk x ⁻¹' s) < ∞ := by { simp_rw [prod_apply hs] at h2s, refine ae_lt_top (measurable_measure_prod_mk_left hs) h2s } lemma integrable_measure_prod_mk_left {s : set (α × β)} (hs : measurable_set s) (h2s : (μ.prod ν) s ≠ ∞) : integrable (λ x, (ν (prod.mk x ⁻¹' s)).to_real) μ := begin refine ⟨(measurable_measure_prod_mk_left hs).ennreal_to_real.ae_measurable.ae_strongly_measurable, _⟩, simp_rw [has_finite_integral, ennnorm_eq_of_real to_real_nonneg], convert h2s.lt_top using 1, simp_rw [prod_apply hs], apply lintegral_congr_ae, refine (ae_measure_lt_top hs h2s).mp _, apply eventually_of_forall, intros x hx, rw [lt_top_iff_ne_top] at hx, simp [of_real_to_real, hx], end /-- Note: the assumption `hs` cannot be dropped. For a counterexample, see Walter Rudin *Real and Complex Analysis*, example (c) in section 8.9. -/ lemma measure_prod_null {s : set (α × β)} (hs : measurable_set s) : μ.prod ν s = 0 ↔ (λ x, ν (prod.mk x ⁻¹' s)) =ᵐ[μ] 0 := by simp_rw [prod_apply hs, lintegral_eq_zero_iff (measurable_measure_prod_mk_left hs)] /-- Note: the converse is not true without assuming that `s` is measurable. For a counterexample, see Walter Rudin *Real and Complex Analysis*, example (c) in section 8.9. -/ lemma measure_ae_null_of_prod_null {s : set (α × β)} (h : μ.prod ν s = 0) : (λ x, ν (prod.mk x ⁻¹' s)) =ᵐ[μ] 0 := begin obtain ⟨t, hst, mt, ht⟩ := exists_measurable_superset_of_null h, simp_rw [measure_prod_null mt] at ht, rw [eventually_le_antisymm_iff], exact ⟨eventually_le.trans_eq (eventually_of_forall $ λ x, (measure_mono (preimage_mono hst) : _)) ht, eventually_of_forall $ λ x, zero_le _⟩ end lemma absolutely_continuous.prod [sigma_finite ν'] (h1 : μ ≪ μ') (h2 : ν ≪ ν') : μ.prod ν ≪ μ'.prod ν' := begin refine absolutely_continuous.mk (λ s hs h2s, _), simp_rw [measure_prod_null hs] at h2s ⊢, exact (h2s.filter_mono h1.ae_le).mono (λ _ h, h2 h) end /-- Note: the converse is not true. For a counterexample, see Walter Rudin *Real and Complex Analysis*, example (c) in section 8.9. -/ lemma ae_ae_of_ae_prod {p : α × β → Prop} (h : ∀ᵐ z ∂μ.prod ν, p z) : ∀ᵐ x ∂ μ, ∀ᵐ y ∂ ν, p (x, y) := measure_ae_null_of_prod_null h /-- `μ.prod ν` has finite spanning sets in rectangles of finite spanning sets. -/ noncomputable! def finite_spanning_sets_in.prod {ν : measure β} {C : set (set α)} {D : set (set β)} (hμ : μ.finite_spanning_sets_in C) (hν : ν.finite_spanning_sets_in D) : (μ.prod ν).finite_spanning_sets_in (image2 (×ˢ) C D) := begin haveI := hν.sigma_finite, refine ⟨λ n, hμ.set n.unpair.1 ×ˢ hν.set n.unpair.2, λ n, mem_image2_of_mem (hμ.set_mem _) (hν.set_mem _), λ n, _, _⟩, { rw [prod_prod], exact mul_lt_top (hμ.finite _).ne (hν.finite _).ne }, { simp_rw [Union_unpair_prod, hμ.spanning, hν.spanning, univ_prod_univ] } end lemma quasi_measure_preserving_fst : quasi_measure_preserving prod.fst (μ.prod ν) μ := begin refine ⟨measurable_fst, absolutely_continuous.mk (λ s hs h2s, _)⟩, rw [map_apply measurable_fst hs, ← prod_univ, prod_prod, h2s, zero_mul], end lemma quasi_measure_preserving_snd : quasi_measure_preserving prod.snd (μ.prod ν) ν := begin refine ⟨measurable_snd, absolutely_continuous.mk (λ s hs h2s, _)⟩, rw [map_apply measurable_snd hs, ← univ_prod, prod_prod, h2s, mul_zero] end variables [sigma_finite μ] instance prod.sigma_finite : sigma_finite (μ.prod ν) := (μ.to_finite_spanning_sets_in.prod ν.to_finite_spanning_sets_in).sigma_finite /-- A measure on a product space equals the product measure if they are equal on rectangles with as sides sets that generate the corresponding σ-algebras. -/ lemma prod_eq_generate_from {μ : measure α} {ν : measure β} {C : set (set α)} {D : set (set β)} (hC : generate_from C = ‹_›) (hD : generate_from D = ‹_›) (h2C : is_pi_system C) (h2D : is_pi_system D) (h3C : μ.finite_spanning_sets_in C) (h3D : ν.finite_spanning_sets_in D) {μν : measure (α × β)} (h₁ : ∀ (s ∈ C) (t ∈ D), μν (s ×ˢ t) = μ s * ν t) : μ.prod ν = μν := begin refine (h3C.prod h3D).ext (generate_from_eq_prod hC hD h3C.is_countably_spanning h3D.is_countably_spanning).symm (h2C.prod h2D) _, { rintro _ ⟨s, t, hs, ht, rfl⟩, haveI := h3D.sigma_finite, rw [h₁ s hs t ht, prod_prod] } end /-- A measure on a product space equals the product measure if they are equal on rectangles. -/ lemma prod_eq {μν : measure (α × β)} (h : ∀ s t, measurable_set s → measurable_set t → μν (s ×ˢ t) = μ s * ν t) : μ.prod ν = μν := prod_eq_generate_from generate_from_measurable_set generate_from_measurable_set is_pi_system_measurable_set is_pi_system_measurable_set μ.to_finite_spanning_sets_in ν.to_finite_spanning_sets_in (λ s hs t ht, h s t hs ht) lemma prod_swap : map prod.swap (μ.prod ν) = ν.prod μ := begin refine (prod_eq _).symm, intros s t hs ht, simp_rw [map_apply measurable_swap (hs.prod ht), preimage_swap_prod, prod_prod, mul_comm] end lemma measure_preserving_swap : measure_preserving prod.swap (μ.prod ν) (ν.prod μ) := ⟨measurable_swap, prod_swap⟩ lemma prod_apply_symm {s : set (α × β)} (hs : measurable_set s) : μ.prod ν s = ∫⁻ y, μ ((λ x, (x, y)) ⁻¹' s) ∂ν := by { rw [← prod_swap, map_apply measurable_swap hs], simp only [prod_apply (measurable_swap hs)], refl } lemma prod_assoc_prod [sigma_finite τ] : map measurable_equiv.prod_assoc ((μ.prod ν).prod τ) = μ.prod (ν.prod τ) := begin refine (prod_eq_generate_from generate_from_measurable_set generate_from_prod is_pi_system_measurable_set is_pi_system_prod μ.to_finite_spanning_sets_in (ν.to_finite_spanning_sets_in.prod τ.to_finite_spanning_sets_in) _).symm, rintro s hs _ ⟨t, u, ht, hu, rfl⟩, rw [mem_set_of_eq] at hs ht hu, simp_rw [map_apply (measurable_equiv.measurable _) (hs.prod (ht.prod hu)), measurable_equiv.prod_assoc, measurable_equiv.coe_mk, equiv.prod_assoc_preimage, prod_prod, mul_assoc] end /-! ### The product of specific measures -/ lemma prod_restrict (s : set α) (t : set β) : (μ.restrict s).prod (ν.restrict t) = (μ.prod ν).restrict (s ×ˢ t) := begin refine prod_eq (λ s' t' hs' ht', _), rw [restrict_apply (hs'.prod ht'), prod_inter_prod, prod_prod, restrict_apply hs', restrict_apply ht'] end lemma restrict_prod_eq_prod_univ (s : set α) : (μ.restrict s).prod ν = (μ.prod ν).restrict (s ×ˢ (univ : set β)) := begin have : ν = ν.restrict set.univ := measure.restrict_univ.symm, rwa [this, measure.prod_restrict, ← this], end lemma prod_dirac (y : β) : μ.prod (dirac y) = map (λ x, (x, y)) μ := begin refine prod_eq (λ s t hs ht, _), simp_rw [map_apply measurable_prod_mk_right (hs.prod ht), mk_preimage_prod_left_eq_if, measure_if, dirac_apply' _ ht, ← indicator_mul_right _ (λ x, μ s), pi.one_apply, mul_one] end lemma dirac_prod (x : α) : (dirac x).prod ν = map (prod.mk x) ν := begin refine prod_eq (λ s t hs ht, _), simp_rw [map_apply measurable_prod_mk_left (hs.prod ht), mk_preimage_prod_right_eq_if, measure_if, dirac_apply' _ hs, ← indicator_mul_left _ _ (λ x, ν t), pi.one_apply, one_mul] end lemma dirac_prod_dirac {x : α} {y : β} : (dirac x).prod (dirac y) = dirac (x, y) := by rw [prod_dirac, map_dirac measurable_prod_mk_right] lemma prod_sum {ι : Type*} [finite ι] (ν : ι → measure β) [∀ i, sigma_finite (ν i)] : μ.prod (sum ν) = sum (λ i, μ.prod (ν i)) := begin refine prod_eq (λ s t hs ht, _), simp_rw [sum_apply _ (hs.prod ht), sum_apply _ ht, prod_prod, ennreal.tsum_mul_left] end lemma sum_prod {ι : Type*} [finite ι] (μ : ι → measure α) [∀ i, sigma_finite (μ i)] : (sum μ).prod ν = sum (λ i, (μ i).prod ν) := begin refine prod_eq (λ s t hs ht, _), simp_rw [sum_apply _ (hs.prod ht), sum_apply _ hs, prod_prod, ennreal.tsum_mul_right] end lemma prod_add (ν' : measure β) [sigma_finite ν'] : μ.prod (ν + ν') = μ.prod ν + μ.prod ν' := by { refine prod_eq (λ s t hs ht, _), simp_rw [add_apply, prod_prod, left_distrib] } lemma add_prod (μ' : measure α) [sigma_finite μ'] : (μ + μ').prod ν = μ.prod ν + μ'.prod ν := by { refine prod_eq (λ s t hs ht, _), simp_rw [add_apply, prod_prod, right_distrib] } @[simp] lemma zero_prod (ν : measure β) : (0 : measure α).prod ν = 0 := by { rw measure.prod, exact bind_zero_left _ } @[simp] lemma prod_zero (μ : measure α) : μ.prod (0 : measure β) = 0 := by simp [measure.prod] lemma map_prod_map {δ} [measurable_space δ] {f : α → β} {g : γ → δ} {μa : measure α} {μc : measure γ} (hfa : sigma_finite (map f μa)) (hgc : sigma_finite (map g μc)) (hf : measurable f) (hg : measurable g) : (map f μa).prod (map g μc) = map (prod.map f g) (μa.prod μc) := begin haveI := hgc.of_map μc hg.ae_measurable, refine prod_eq (λ s t hs ht, _), rw [map_apply (hf.prod_map hg) (hs.prod ht), map_apply hf hs, map_apply hg ht], exact prod_prod (f ⁻¹' s) (g ⁻¹' t) end end measure open measure namespace measure_preserving variables {δ : Type*} [measurable_space δ] {μa : measure α} {μb : measure β} {μc : measure γ} {μd : measure δ} lemma skew_product [sigma_finite μb] [sigma_finite μd] {f : α → β} (hf : measure_preserving f μa μb) {g : α → γ → δ} (hgm : measurable (uncurry g)) (hg : ∀ᵐ x ∂μa, map (g x) μc = μd) : measure_preserving (λ p : α × γ, (f p.1, g p.1 p.2)) (μa.prod μc) (μb.prod μd) := begin classical, have : measurable (λ p : α × γ, (f p.1, g p.1 p.2)) := (hf.1.comp measurable_fst).prod_mk hgm, /- if `μa = 0`, then the lemma is trivial, otherwise we can use `hg` to deduce `sigma_finite μc`. -/ rcases eq_or_ne μa 0 with (rfl|ha), { rw [← hf.map_eq, zero_prod, measure.map_zero, zero_prod], exact ⟨this, by simp only [measure.map_zero]⟩ }, haveI : sigma_finite μc, { rcases (ae_ne_bot.2 ha).nonempty_of_mem hg with ⟨x, hx : map (g x) μc = μd⟩, exact sigma_finite.of_map _ hgm.of_uncurry_left.ae_measurable (by rwa hx) }, -- Thus we can apply `measure.prod_eq` to prove equality of measures. refine ⟨this, (prod_eq $ λ s t hs ht, _).symm⟩, rw [map_apply this (hs.prod ht)], refine (prod_apply (this $ hs.prod ht)).trans _, have : ∀ᵐ x ∂μa, μc ((λ y, (f x, g x y)) ⁻¹' s ×ˢ t) = indicator (f ⁻¹' s) (λ y, μd t) x, { refine hg.mono (λ x hx, _), unfreezingI { subst hx }, simp only [mk_preimage_prod_right_fn_eq_if, indicator_apply, mem_preimage], split_ifs, exacts [(map_apply hgm.of_uncurry_left ht).symm, measure_empty] }, simp only [preimage_preimage], rw [lintegral_congr_ae this, lintegral_indicator _ (hf.1 hs), set_lintegral_const, hf.measure_preimage hs, mul_comm] end /-- If `f : α → β` sends the measure `μa` to `μb` and `g : γ → δ` sends the measure `μc` to `μd`, then `prod.map f g` sends `μa.prod μc` to `μb.prod μd`. -/ protected lemma prod [sigma_finite μb] [sigma_finite μd] {f : α → β} {g : γ → δ} (hf : measure_preserving f μa μb) (hg : measure_preserving g μc μd) : measure_preserving (prod.map f g) (μa.prod μc) (μb.prod μd) := have measurable (uncurry $ λ _ : α, g), from (hg.1.comp measurable_snd), hf.skew_product this $ filter.eventually_of_forall $ λ _, hg.map_eq end measure_preserving namespace quasi_measure_preserving lemma prod_of_right {f : α × β → γ} {μ : measure α} {ν : measure β} {τ : measure γ} (hf : measurable f) [sigma_finite ν] (h2f : ∀ᵐ x ∂μ, quasi_measure_preserving (λ y, f (x, y)) ν τ) : quasi_measure_preserving f (μ.prod ν) τ := begin refine ⟨hf, _⟩, refine absolutely_continuous.mk (λ s hs h2s, _), simp_rw [map_apply hf hs, prod_apply (hf hs), preimage_preimage, lintegral_congr_ae (h2f.mono (λ x hx, hx.preimage_null h2s)), lintegral_zero], end lemma prod_of_left {α β γ} [measurable_space α] [measurable_space β] [measurable_space γ] {f : α × β → γ} {μ : measure α} {ν : measure β} {τ : measure γ} (hf : measurable f) [sigma_finite μ] [sigma_finite ν] (h2f : ∀ᵐ y ∂ν, quasi_measure_preserving (λ x, f (x, y)) μ τ) : quasi_measure_preserving f (μ.prod ν) τ := begin rw [← prod_swap], convert (quasi_measure_preserving.prod_of_right (hf.comp measurable_swap) h2f).comp ((measurable_swap.measure_preserving (ν.prod μ)).symm measurable_equiv.prod_comm) .quasi_measure_preserving, ext ⟨x, y⟩, refl, end end quasi_measure_preserving end measure_theory open measure_theory.measure section lemma ae_measurable.prod_swap [sigma_finite μ] [sigma_finite ν] {f : β × α → γ} (hf : ae_measurable f (ν.prod μ)) : ae_measurable (λ (z : α × β), f z.swap) (μ.prod ν) := by { rw ← prod_swap at hf, exact hf.comp_measurable measurable_swap } lemma measure_theory.ae_strongly_measurable.prod_swap {γ : Type*} [topological_space γ] [sigma_finite μ] [sigma_finite ν] {f : β × α → γ} (hf : ae_strongly_measurable f (ν.prod μ)) : ae_strongly_measurable (λ (z : α × β), f z.swap) (μ.prod ν) := by { rw ← prod_swap at hf, exact hf.comp_measurable measurable_swap } lemma ae_measurable.fst [sigma_finite ν] {f : α → γ} (hf : ae_measurable f μ) : ae_measurable (λ (z : α × β), f z.1) (μ.prod ν) := hf.comp_quasi_measure_preserving quasi_measure_preserving_fst lemma ae_measurable.snd [sigma_finite ν] {f : β → γ} (hf : ae_measurable f ν) : ae_measurable (λ (z : α × β), f z.2) (μ.prod ν) := hf.comp_quasi_measure_preserving quasi_measure_preserving_snd lemma measure_theory.ae_strongly_measurable.fst {γ} [topological_space γ] [sigma_finite ν] {f : α → γ} (hf : ae_strongly_measurable f μ) : ae_strongly_measurable (λ (z : α × β), f z.1) (μ.prod ν) := hf.comp_quasi_measure_preserving quasi_measure_preserving_fst lemma measure_theory.ae_strongly_measurable.snd {γ} [topological_space γ] [sigma_finite ν] {f : β → γ} (hf : ae_strongly_measurable f ν) : ae_strongly_measurable (λ (z : α × β), f z.2) (μ.prod ν) := hf.comp_quasi_measure_preserving quasi_measure_preserving_snd /-- The Bochner integral is a.e.-measurable. This shows that the integrand of (the right-hand-side of) Fubini's theorem is a.e.-measurable. -/ lemma measure_theory.ae_strongly_measurable.integral_prod_right' [sigma_finite ν] [normed_space ℝ E] [complete_space E] ⦃f : α × β → E⦄ (hf : ae_strongly_measurable f (μ.prod ν)) : ae_strongly_measurable (λ x, ∫ y, f (x, y) ∂ν) μ := ⟨λ x, ∫ y, hf.mk f (x, y) ∂ν, hf.strongly_measurable_mk.integral_prod_right', by { filter_upwards [ae_ae_of_ae_prod hf.ae_eq_mk] with _ hx using integral_congr_ae hx }⟩ lemma measure_theory.ae_strongly_measurable.prod_mk_left {γ : Type*} [sigma_finite ν] [topological_space γ] {f : α × β → γ} (hf : ae_strongly_measurable f (μ.prod ν)) : ∀ᵐ x ∂μ, ae_strongly_measurable (λ y, f (x, y)) ν := begin filter_upwards [ae_ae_of_ae_prod hf.ae_eq_mk] with x hx, exact ⟨λ y, hf.mk f (x, y), hf.strongly_measurable_mk.comp_measurable measurable_prod_mk_left, hx⟩ end end namespace measure_theory /-! ### The Lebesgue integral on a product -/ variables [sigma_finite ν] lemma lintegral_prod_swap [sigma_finite μ] (f : α × β → ℝ≥0∞) (hf : ae_measurable f (μ.prod ν)) : ∫⁻ z, f z.swap ∂(ν.prod μ) = ∫⁻ z, f z ∂(μ.prod ν) := by { rw ← prod_swap at hf, rw [← lintegral_map' hf measurable_swap.ae_measurable, prod_swap] } /-- **Tonelli's Theorem**: For `ℝ≥0∞`-valued measurable functions on `α × β`, the integral of `f` is equal to the iterated integral. -/ lemma lintegral_prod_of_measurable : ∀ (f : α × β → ℝ≥0∞) (hf : measurable f), ∫⁻ z, f z ∂(μ.prod ν) = ∫⁻ x, ∫⁻ y, f (x, y) ∂ν ∂μ := begin have m := @measurable_prod_mk_left, refine measurable.ennreal_induction _ _ _, { intros c s hs, simp only [← indicator_comp_right], simp [lintegral_indicator, m hs, hs, lintegral_const_mul, measurable_measure_prod_mk_left hs, prod_apply] }, { rintro f g - hf hg h2f h2g, simp [lintegral_add_left, measurable.lintegral_prod_right', hf.comp m, hf, h2f, h2g] }, { intros f hf h2f h3f, have kf : ∀ x n, measurable (λ y, f n (x, y)) := λ x n, (hf n).comp m, have k2f : ∀ x, monotone (λ n y, f n (x, y)) := λ x i j hij y, h2f hij (x, y), have lf : ∀ n, measurable (λ x, ∫⁻ y, f n (x, y) ∂ν) := λ n, (hf n).lintegral_prod_right', have l2f : monotone (λ n x, ∫⁻ y, f n (x, y) ∂ν) := λ i j hij x, lintegral_mono (k2f x hij), simp only [lintegral_supr hf h2f, lintegral_supr (kf _), k2f, lintegral_supr lf l2f, h3f] }, end /-- **Tonelli's Theorem**: For `ℝ≥0∞`-valued almost everywhere measurable functions on `α × β`, the integral of `f` is equal to the iterated integral. -/ lemma lintegral_prod (f : α × β → ℝ≥0∞) (hf : ae_measurable f (μ.prod ν)) : ∫⁻ z, f z ∂(μ.prod ν) = ∫⁻ x, ∫⁻ y, f (x, y) ∂ν ∂μ := begin have A : ∫⁻ z, f z ∂(μ.prod ν) = ∫⁻ z, hf.mk f z ∂(μ.prod ν) := lintegral_congr_ae hf.ae_eq_mk, have B : ∫⁻ x, ∫⁻ y, f (x, y) ∂ν ∂μ = ∫⁻ x, ∫⁻ y, hf.mk f (x, y) ∂ν ∂μ, { apply lintegral_congr_ae, filter_upwards [ae_ae_of_ae_prod hf.ae_eq_mk] with _ ha using lintegral_congr_ae ha, }, rw [A, B, lintegral_prod_of_measurable _ hf.measurable_mk], apply_instance end /-- The symmetric verion of Tonelli's Theorem: For `ℝ≥0∞`-valued almost everywhere measurable functions on `α × β`, the integral of `f` is equal to the iterated integral, in reverse order. -/ lemma lintegral_prod_symm [sigma_finite μ] (f : α × β → ℝ≥0∞) (hf : ae_measurable f (μ.prod ν)) : ∫⁻ z, f z ∂(μ.prod ν) = ∫⁻ y, ∫⁻ x, f (x, y) ∂μ ∂ν := by { simp_rw [← lintegral_prod_swap f hf], exact lintegral_prod _ hf.prod_swap } /-- The symmetric verion of Tonelli's Theorem: For `ℝ≥0∞`-valued measurable functions on `α × β`, the integral of `f` is equal to the iterated integral, in reverse order. -/ lemma lintegral_prod_symm' [sigma_finite μ] (f : α × β → ℝ≥0∞) (hf : measurable f) : ∫⁻ z, f z ∂(μ.prod ν) = ∫⁻ y, ∫⁻ x, f (x, y) ∂μ ∂ν := lintegral_prod_symm f hf.ae_measurable /-- The reversed version of **Tonelli's Theorem**. In this version `f` is in curried form, which makes it easier for the elaborator to figure out `f` automatically. -/ lemma lintegral_lintegral ⦃f : α → β → ℝ≥0∞⦄ (hf : ae_measurable (uncurry f) (μ.prod ν)) : ∫⁻ x, ∫⁻ y, f x y ∂ν ∂μ = ∫⁻ z, f z.1 z.2 ∂(μ.prod ν) := (lintegral_prod _ hf).symm /-- The reversed version of **Tonelli's Theorem** (symmetric version). In this version `f` is in curried form, which makes it easier for the elaborator to figure out `f` automatically. -/ lemma lintegral_lintegral_symm [sigma_finite μ] ⦃f : α → β → ℝ≥0∞⦄ (hf : ae_measurable (uncurry f) (μ.prod ν)) : ∫⁻ x, ∫⁻ y, f x y ∂ν ∂μ = ∫⁻ z, f z.2 z.1 ∂(ν.prod μ) := (lintegral_prod_symm _ hf.prod_swap).symm /-- Change the order of Lebesgue integration. -/ lemma lintegral_lintegral_swap [sigma_finite μ] ⦃f : α → β → ℝ≥0∞⦄ (hf : ae_measurable (uncurry f) (μ.prod ν)) : ∫⁻ x, ∫⁻ y, f x y ∂ν ∂μ = ∫⁻ y, ∫⁻ x, f x y ∂μ ∂ν := (lintegral_lintegral hf).trans (lintegral_prod_symm _ hf) lemma lintegral_prod_mul {f : α → ℝ≥0∞} {g : β → ℝ≥0∞} (hf : ae_measurable f μ) (hg : ae_measurable g ν) : ∫⁻ z, f z.1 * g z.2 ∂(μ.prod ν) = ∫⁻ x, f x ∂μ * ∫⁻ y, g y ∂ν := by simp [lintegral_prod _ (hf.fst.mul hg.snd), lintegral_lintegral_mul hf hg] /-! ### Integrability on a product -/ section lemma integrable.swap [sigma_finite μ] ⦃f : α × β → E⦄ (hf : integrable f (μ.prod ν)) : integrable (f ∘ prod.swap) (ν.prod μ) := ⟨hf.ae_strongly_measurable.prod_swap, (lintegral_prod_swap _ hf.ae_strongly_measurable.ennnorm : _).le.trans_lt hf.has_finite_integral⟩ lemma integrable_swap_iff [sigma_finite μ] ⦃f : α × β → E⦄ : integrable (f ∘ prod.swap) (ν.prod μ) ↔ integrable f (μ.prod ν) := ⟨λ hf, by { convert hf.swap, ext ⟨x, y⟩, refl }, λ hf, hf.swap⟩ lemma has_finite_integral_prod_iff ⦃f : α × β → E⦄ (h1f : strongly_measurable f) : has_finite_integral f (μ.prod ν) ↔ (∀ᵐ x ∂ μ, has_finite_integral (λ y, f (x, y)) ν) ∧ has_finite_integral (λ x, ∫ y, ‖f (x, y)‖ ∂ν) μ := begin simp only [has_finite_integral, lintegral_prod_of_measurable _ h1f.ennnorm], have : ∀ x, ∀ᵐ y ∂ν, 0 ≤ ‖f (x, y)‖ := λ x, eventually_of_forall (λ y, norm_nonneg _), simp_rw [integral_eq_lintegral_of_nonneg_ae (this _) (h1f.norm.comp_measurable measurable_prod_mk_left).ae_strongly_measurable, ennnorm_eq_of_real to_real_nonneg, of_real_norm_eq_coe_nnnorm], -- this fact is probably too specialized to be its own lemma have : ∀ {p q r : Prop} (h1 : r → p), (r ↔ p ∧ q) ↔ (p → (r ↔ q)) := λ p q r h1, by rw [← and.congr_right_iff, and_iff_right_of_imp h1], rw [this], { intro h2f, rw lintegral_congr_ae, refine h2f.mp _, apply eventually_of_forall, intros x hx, dsimp only, rw [of_real_to_real], rw [← lt_top_iff_ne_top], exact hx }, { intro h2f, refine ae_lt_top _ h2f.ne, exact h1f.ennnorm.lintegral_prod_right' }, end lemma has_finite_integral_prod_iff' ⦃f : α × β → E⦄ (h1f : ae_strongly_measurable f (μ.prod ν)) : has_finite_integral f (μ.prod ν) ↔ (∀ᵐ x ∂ μ, has_finite_integral (λ y, f (x, y)) ν) ∧ has_finite_integral (λ x, ∫ y, ‖f (x, y)‖ ∂ν) μ := begin rw [has_finite_integral_congr h1f.ae_eq_mk, has_finite_integral_prod_iff h1f.strongly_measurable_mk], apply and_congr, { apply eventually_congr, filter_upwards [ae_ae_of_ae_prod h1f.ae_eq_mk.symm], assume x hx, exact has_finite_integral_congr hx }, { apply has_finite_integral_congr, filter_upwards [ae_ae_of_ae_prod h1f.ae_eq_mk.symm] with _ hx using integral_congr_ae (eventually_eq.fun_comp hx _), }, { apply_instance, }, end /-- A binary function is integrable if the function `y ↦ f (x, y)` is integrable for almost every `x` and the function `x ↦ ∫ ‖f (x, y)‖ dy` is integrable. -/ lemma integrable_prod_iff ⦃f : α × β → E⦄ (h1f : ae_strongly_measurable f (μ.prod ν)) : integrable f (μ.prod ν) ↔ (∀ᵐ x ∂ μ, integrable (λ y, f (x, y)) ν) ∧ integrable (λ x, ∫ y, ‖f (x, y)‖ ∂ν) μ := by simp [integrable, h1f, has_finite_integral_prod_iff', h1f.norm.integral_prod_right', h1f.prod_mk_left] /-- A binary function is integrable if the function `x ↦ f (x, y)` is integrable for almost every `y` and the function `y ↦ ∫ ‖f (x, y)‖ dx` is integrable. -/ lemma integrable_prod_iff' [sigma_finite μ] ⦃f : α × β → E⦄ (h1f : ae_strongly_measurable f (μ.prod ν)) : integrable f (μ.prod ν) ↔ (∀ᵐ y ∂ ν, integrable (λ x, f (x, y)) μ) ∧ integrable (λ y, ∫ x, ‖f (x, y)‖ ∂μ) ν := by { convert integrable_prod_iff (h1f.prod_swap) using 1, rw [integrable_swap_iff] } lemma integrable.prod_left_ae [sigma_finite μ] ⦃f : α × β → E⦄ (hf : integrable f (μ.prod ν)) : ∀ᵐ y ∂ ν, integrable (λ x, f (x, y)) μ := ((integrable_prod_iff' hf.ae_strongly_measurable).mp hf).1 lemma integrable.prod_right_ae [sigma_finite μ] ⦃f : α × β → E⦄ (hf : integrable f (μ.prod ν)) : ∀ᵐ x ∂ μ, integrable (λ y, f (x, y)) ν := hf.swap.prod_left_ae lemma integrable.integral_norm_prod_left ⦃f : α × β → E⦄ (hf : integrable f (μ.prod ν)) : integrable (λ x, ∫ y, ‖f (x, y)‖ ∂ν) μ := ((integrable_prod_iff hf.ae_strongly_measurable).mp hf).2 lemma integrable.integral_norm_prod_right [sigma_finite μ] ⦃f : α × β → E⦄ (hf : integrable f (μ.prod ν)) : integrable (λ y, ∫ x, ‖f (x, y)‖ ∂μ) ν := hf.swap.integral_norm_prod_left lemma integrable_prod_mul {L : Type*} [is_R_or_C L] {f : α → L} {g : β → L} (hf : integrable f μ) (hg : integrable g ν) : integrable (λ (z : α × β), f z.1 * g z.2) (μ.prod ν) := begin refine (integrable_prod_iff _).2 ⟨_, _⟩, { exact hf.1.fst.mul hg.1.snd }, { exact eventually_of_forall (λ x, hg.const_mul (f x)) }, { simpa only [norm_mul, integral_mul_left] using hf.norm.mul_const _ } end end variables [normed_space ℝ E] [complete_space E] lemma integrable.integral_prod_left ⦃f : α × β → E⦄ (hf : integrable f (μ.prod ν)) : integrable (λ x, ∫ y, f (x, y) ∂ν) μ := integrable.mono hf.integral_norm_prod_left hf.ae_strongly_measurable.integral_prod_right' $ eventually_of_forall $ λ x, (norm_integral_le_integral_norm _).trans_eq $ (norm_of_nonneg $ integral_nonneg_of_ae $ eventually_of_forall $ λ y, (norm_nonneg (f (x, y)) : _)).symm lemma integrable.integral_prod_right [sigma_finite μ] ⦃f : α × β → E⦄ (hf : integrable f (μ.prod ν)) : integrable (λ y, ∫ x, f (x, y) ∂μ) ν := hf.swap.integral_prod_left /-! ### The Bochner integral on a product -/ variables [sigma_finite μ] lemma integral_prod_swap (f : α × β → E) (hf : ae_strongly_measurable f (μ.prod ν)) : ∫ z, f z.swap ∂(ν.prod μ) = ∫ z, f z ∂(μ.prod ν) := begin rw ← prod_swap at hf, rw [← integral_map measurable_swap.ae_measurable hf, prod_swap] end variables {E' : Type*} [normed_add_comm_group E'] [complete_space E'] [normed_space ℝ E'] /-! Some rules about the sum/difference of double integrals. They follow from `integral_add`, but we separate them out as separate lemmas, because they involve quite some steps. -/ /-- Integrals commute with addition inside another integral. `F` can be any function. -/ lemma integral_fn_integral_add ⦃f g : α × β → E⦄ (F : E → E') (hf : integrable f (μ.prod ν)) (hg : integrable g (μ.prod ν)) : ∫ x, F (∫ y, f (x, y) + g (x, y) ∂ν) ∂μ = ∫ x, F (∫ y, f (x, y) ∂ν + ∫ y, g (x, y) ∂ν) ∂μ := begin refine integral_congr_ae _, filter_upwards [hf.prod_right_ae, hg.prod_right_ae] with _ h2f h2g, simp [integral_add h2f h2g], end /-- Integrals commute with subtraction inside another integral. `F` can be any measurable function. -/ lemma integral_fn_integral_sub ⦃f g : α × β → E⦄ (F : E → E') (hf : integrable f (μ.prod ν)) (hg : integrable g (μ.prod ν)) : ∫ x, F (∫ y, f (x, y) - g (x, y) ∂ν) ∂μ = ∫ x, F (∫ y, f (x, y) ∂ν - ∫ y, g (x, y) ∂ν) ∂μ := begin refine integral_congr_ae _, filter_upwards [hf.prod_right_ae, hg.prod_right_ae] with _ h2f h2g, simp [integral_sub h2f h2g], end /-- Integrals commute with subtraction inside a lower Lebesgue integral. `F` can be any function. -/ lemma lintegral_fn_integral_sub ⦃f g : α × β → E⦄ (F : E → ℝ≥0∞) (hf : integrable f (μ.prod ν)) (hg : integrable g (μ.prod ν)) : ∫⁻ x, F (∫ y, f (x, y) - g (x, y) ∂ν) ∂μ = ∫⁻ x, F (∫ y, f (x, y) ∂ν - ∫ y, g (x, y) ∂ν) ∂μ := begin refine lintegral_congr_ae _, filter_upwards [hf.prod_right_ae, hg.prod_right_ae] with _ h2f h2g, simp [integral_sub h2f h2g], end /-- Double integrals commute with addition. -/ lemma integral_integral_add ⦃f g : α × β → E⦄ (hf : integrable f (μ.prod ν)) (hg : integrable g (μ.prod ν)) : ∫ x, ∫ y, f (x, y) + g (x, y) ∂ν ∂μ = ∫ x, ∫ y, f (x, y) ∂ν ∂μ + ∫ x, ∫ y, g (x, y) ∂ν ∂μ := (integral_fn_integral_add id hf hg).trans $ integral_add hf.integral_prod_left hg.integral_prod_left /-- Double integrals commute with addition. This is the version with `(f + g) (x, y)` (instead of `f (x, y) + g (x, y)`) in the LHS. -/ lemma integral_integral_add' ⦃f g : α × β → E⦄ (hf : integrable f (μ.prod ν)) (hg : integrable g (μ.prod ν)) : ∫ x, ∫ y, (f + g) (x, y) ∂ν ∂μ = ∫ x, ∫ y, f (x, y) ∂ν ∂μ + ∫ x, ∫ y, g (x, y) ∂ν ∂μ := integral_integral_add hf hg /-- Double integrals commute with subtraction. -/ lemma integral_integral_sub ⦃f g : α × β → E⦄ (hf : integrable f (μ.prod ν)) (hg : integrable g (μ.prod ν)) : ∫ x, ∫ y, f (x, y) - g (x, y) ∂ν ∂μ = ∫ x, ∫ y, f (x, y) ∂ν ∂μ - ∫ x, ∫ y, g (x, y) ∂ν ∂μ := (integral_fn_integral_sub id hf hg).trans $ integral_sub hf.integral_prod_left hg.integral_prod_left /-- Double integrals commute with subtraction. This is the version with `(f - g) (x, y)` (instead of `f (x, y) - g (x, y)`) in the LHS. -/ lemma integral_integral_sub' ⦃f g : α × β → E⦄ (hf : integrable f (μ.prod ν)) (hg : integrable g (μ.prod ν)) : ∫ x, ∫ y, (f - g) (x, y) ∂ν ∂μ = ∫ x, ∫ y, f (x, y) ∂ν ∂μ - ∫ x, ∫ y, g (x, y) ∂ν ∂μ := integral_integral_sub hf hg /-- The map that sends an L¹-function `f : α × β → E` to `∫∫f` is continuous. -/ lemma continuous_integral_integral : continuous (λ (f : α × β →₁[μ.prod ν] E), ∫ x, ∫ y, f (x, y) ∂ν ∂μ) := begin rw [continuous_iff_continuous_at], intro g, refine tendsto_integral_of_L1 _ (L1.integrable_coe_fn g).integral_prod_left (eventually_of_forall $ λ h, (L1.integrable_coe_fn h).integral_prod_left) _, simp_rw [← lintegral_fn_integral_sub (λ x, (‖x‖₊ : ℝ≥0∞)) (L1.integrable_coe_fn _) (L1.integrable_coe_fn g)], refine tendsto_of_tendsto_of_tendsto_of_le_of_le tendsto_const_nhds _ (λ i, zero_le _) _, { exact λ i, ∫⁻ x, ∫⁻ y, ‖i (x, y) - g (x, y)‖₊ ∂ν ∂μ }, swap, { exact λ i, lintegral_mono (λ x, ennnorm_integral_le_lintegral_ennnorm _) }, show tendsto (λ (i : α × β →₁[μ.prod ν] E), ∫⁻ x, ∫⁻ (y : β), ‖i (x, y) - g (x, y)‖₊ ∂ν ∂μ) (𝓝 g) (𝓝 0), have : ∀ (i : α × β →₁[μ.prod ν] E), measurable (λ z, (‖i z - g z‖₊ : ℝ≥0∞)) := λ i, ((Lp.strongly_measurable i).sub (Lp.strongly_measurable g)).ennnorm, simp_rw [← lintegral_prod_of_measurable _ (this _), ← L1.of_real_norm_sub_eq_lintegral, ← of_real_zero], refine (continuous_of_real.tendsto 0).comp _, rw [← tendsto_iff_norm_tendsto_zero], exact tendsto_id end /-- **Fubini's Theorem**: For integrable functions on `α × β`, the Bochner integral of `f` is equal to the iterated Bochner integral. `integrable_prod_iff` can be useful to show that the function in question in integrable. `measure_theory.integrable.integral_prod_right` is useful to show that the inner integral of the right-hand side is integrable. -/ lemma integral_prod : ∀ (f : α × β → E) (hf : integrable f (μ.prod ν)), ∫ z, f z ∂(μ.prod ν) = ∫ x, ∫ y, f (x, y) ∂ν ∂μ := begin apply integrable.induction, { intros c s hs h2s, simp_rw [integral_indicator hs, ← indicator_comp_right, function.comp, integral_indicator (measurable_prod_mk_left hs), set_integral_const, integral_smul_const, integral_to_real (measurable_measure_prod_mk_left hs).ae_measurable (ae_measure_lt_top hs h2s.ne), prod_apply hs] }, { intros f g hfg i_f i_g hf hg, simp_rw [integral_add' i_f i_g, integral_integral_add' i_f i_g, hf, hg] }, { exact is_closed_eq continuous_integral continuous_integral_integral }, { intros f g hfg i_f hf, convert hf using 1, { exact integral_congr_ae hfg.symm }, { refine integral_congr_ae _, refine (ae_ae_of_ae_prod hfg).mp _, apply eventually_of_forall, intros x hfgx, exact integral_congr_ae (ae_eq_symm hfgx) } } end /-- Symmetric version of **Fubini's Theorem**: For integrable functions on `α × β`, the Bochner integral of `f` is equal to the iterated Bochner integral. This version has the integrals on the right-hand side in the other order. -/ lemma integral_prod_symm (f : α × β → E) (hf : integrable f (μ.prod ν)) : ∫ z, f z ∂(μ.prod ν) = ∫ y, ∫ x, f (x, y) ∂μ ∂ν := by { simp_rw [← integral_prod_swap f hf.ae_strongly_measurable], exact integral_prod _ hf.swap } /-- Reversed version of **Fubini's Theorem**. -/ lemma integral_integral {f : α → β → E} (hf : integrable (uncurry f) (μ.prod ν)) : ∫ x, ∫ y, f x y ∂ν ∂μ = ∫ z, f z.1 z.2 ∂(μ.prod ν) := (integral_prod _ hf).symm /-- Reversed version of **Fubini's Theorem** (symmetric version). -/ lemma integral_integral_symm {f : α → β → E} (hf : integrable (uncurry f) (μ.prod ν)) : ∫ x, ∫ y, f x y ∂ν ∂μ = ∫ z, f z.2 z.1 ∂(ν.prod μ) := (integral_prod_symm _ hf.swap).symm /-- Change the order of Bochner integration. -/ lemma integral_integral_swap ⦃f : α → β → E⦄ (hf : integrable (uncurry f) (μ.prod ν)) : ∫ x, ∫ y, f x y ∂ν ∂μ = ∫ y, ∫ x, f x y ∂μ ∂ν := (integral_integral hf).trans (integral_prod_symm _ hf) /-- **Fubini's Theorem** for set integrals. -/ lemma set_integral_prod (f : α × β → E) {s : set α} {t : set β} (hf : integrable_on f (s ×ˢ t) (μ.prod ν)) : ∫ z in s ×ˢ t, f z ∂(μ.prod ν) = ∫ x in s, ∫ y in t, f (x, y) ∂ν ∂μ := begin simp only [← measure.prod_restrict s t, integrable_on] at hf ⊢, exact integral_prod f hf end lemma integral_prod_mul {L : Type*} [is_R_or_C L] (f : α → L) (g : β → L) : ∫ z, f z.1 * g z.2 ∂(μ.prod ν) = (∫ x, f x ∂μ) * (∫ y, g y ∂ν) := begin by_cases h : integrable (λ (z : α × β), f z.1 * g z.2) (μ.prod ν), { rw integral_prod _ h, simp_rw [integral_mul_left, integral_mul_right] }, have H : ¬(integrable f μ) ∨ ¬(integrable g ν), { contrapose! h, exact integrable_prod_mul h.1 h.2 }, cases H; simp [integral_undef h, integral_undef H], end lemma set_integral_prod_mul {L : Type*} [is_R_or_C L] (f : α → L) (g : β → L) (s : set α) (t : set β) : ∫ z in s ×ˢ t, f z.1 * g z.2 ∂(μ.prod ν) = (∫ x in s, f x ∂μ) * (∫ y in t, g y ∂ν) := by simp only [← measure.prod_restrict s t, integrable_on, integral_prod_mul] end measure_theory
81df0cea19f53719391309ba77214a8cc09d329e
491068d2ad28831e7dade8d6dff871c3e49d9431
/tests/lean/run/constr_tac.lean
6d5b4b298269e688189a04766e016ca0e298b4d3
[ "Apache-2.0" ]
permissive
davidmueller13/lean
65a3ed141b4088cd0a268e4de80eb6778b21a0e9
c626e2e3c6f3771e07c32e82ee5b9e030de5b050
refs/heads/master
1,611,278,313,401
1,444,021,177,000
1,444,021,177,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
848
lean
import data.list example (a b c : Prop) : a → b → c → a ∧ b ∧ c := begin intro Ha Hb Hc, split, assumption, split, repeat assumption end example (a b c : Type) : a → b → c → a × b × c := begin intro Ha Hb Hc, repeat (split | assumption) end example (a b : Type) : a → sum a b := begin intro Ha, left, assumption end example (a b : Type) : b → sum a b := begin intro Ha, right, assumption end example (a b : Prop) : a → a ∨ b := begin intro Ha, left, assumption end example (a b : Prop) : b → a ∨ b := begin intro Ha, right, assumption end open nat example (a : nat) : a > 0 → ∃ x, x > 0 := begin intro Ha, existsi a, apply Ha end example : list nat := begin constructor 1 end example : list nat := begin constructor 2, constructor 1, constructor 1 end
50960bf708f421ce492a6cb88e1021c8642674c4
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/library/init/meta/mk_dec_eq_instance.lean
572e6e50858fe6ce2b29306fd06c81b3e440cae2
[ "Apache-2.0" ]
permissive
soonhokong/lean-osx
4a954262c780e404c1369d6c06516161d07fcb40
3670278342d2f4faa49d95b46d86642d7875b47c
refs/heads/master
1,611,410,334,552
1,474,425,686,000
1,474,425,686,000
12,043,103
5
1
null
null
null
null
UTF-8
Lean
false
false
4,552
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura Helper tactic for showing that a type has decidable equality. -/ prelude import init.meta.contradiction_tactic init.meta.constructor_tactic import init.meta.injection_tactic init.meta.relation_tactics import init.meta.rec_util namespace tactic open expr environment list /- Retrieve the name of the type we are building a decidable equality proof for. -/ private meta_definition get_dec_eq_type_name : tactic name := do { (pi x1 i1 d1 (pi x2 i2 d2 b)) ← target >>= whnf | failed, (const n ls) ← return (get_app_fn b) | failed, when (n ≠ `decidable) failed, (const I ls) ← return (get_app_fn d1) | failed, return I } <|> fail "mk_dec_eq_instance tactic failed, target type is expected to be of the form (decidable_eq ...)" /- Extract (lhs, rhs) from a goal (decidable (lhs = rhs)) -/ private meta_definition get_lhs_rhs : tactic (expr × expr) := do (app dec lhs_eq_rhs) ← target | fail "mk_dec_eq_instance failed, unexpected case", match_eq lhs_eq_rhs private meta_definition find_next_target : list expr → list expr → tactic (expr × expr) | (t::ts) (r::rs) := if t = r then find_next_target ts rs else return (t, r) | l1 l2 := failed /- Create an inhabitant of (decidable (lhs = rhs)) -/ private meta_definition mk_dec_eq_for (lhs : expr) (rhs : expr) : tactic expr := do lhs_type ← infer_type lhs, dec_type ← mk_app `decidable_eq [lhs_type] >>= whnf, do { inst : expr ← mk_instance dec_type, return $ app_of_list inst [lhs, rhs] } <|> do { f ← pp dec_type, fail $ to_fmt "mk_dec_eq_instance failed, failed to generate instance for" ++ format.nest 2 (format.line ++ f) } /- Target is of the form (decidable (C ... = C ...)) where C is a constructor -/ private meta_definition dec_eq_same_constructor : name → name → nat → tactic unit | I_name F_name num_rec := do (lhs, rhs) ← get_lhs_rhs, -- Try easy case first, where the proof is just reflexivity (unify lhs rhs >> right >> reflexivity) <|> do { lhs_list : list expr ← return $ get_app_args lhs, rhs_list : list expr ← return $ get_app_args rhs, when (length lhs_list ≠ length rhs_list) (fail "mk_dec_eq_instance failed, constructor applications have different number of arguments"), (lhs_arg, rhs_arg) ← find_next_target lhs_list rhs_list, rec ← is_type_app_of lhs_arg I_name, inst ← if rec = tt then do { inst_fn : expr ← mk_brec_on_rec_value F_name num_rec, return $ app inst_fn rhs_arg } else do { mk_dec_eq_for lhs_arg rhs_arg }, tgt ← target, by_cases ← mk_mapp_core transparency.all `decidable.by_cases [none, some tgt, some inst], apply by_cases, -- discharge first (positive) case by recursion intro1 >>= subst >> dec_eq_same_constructor I_name F_name (if rec = tt then num_rec + 1 else num_rec), -- discharge second (negative) case by contradiction intro1, left, -- decidable.is_false intro1 >>= injection, intros, contradiction, return () } /- Easy case: target is of the form (decidable (C_1 ... = C_2 ...)) where C_1 and C_2 are distinct constructors -/ private meta_definition dec_eq_diff_constructor : tactic unit := left >> intron 1 >> contradiction /- This tactic is invoked for each case of decidable_eq. There n^2 cases, where n is the number of constructors. -/ private meta_definition dec_eq_case_2 (I_name : name) (F_name : name) : tactic unit := do (lhs, rhs) ← get_lhs_rhs, lhs_fn : expr ← return $ get_app_fn lhs, rhs_fn : expr ← return $ get_app_fn rhs, if lhs_fn = rhs_fn then dec_eq_same_constructor I_name F_name 0 else dec_eq_diff_constructor private meta_definition dec_eq_case_1 (I_name : name) (F_name : name) : tactic unit := intro `w >>= cases >> all_goals (dec_eq_case_2 I_name F_name) meta_definition mk_dec_eq_instance : tactic unit := do I_name ← get_dec_eq_type_name, env ← get_env, v_name ← return `_v, F_name ← return `_F, -- Use brec_on if type is recursive. -- We store the functional in the variable F. if (is_recursive env I_name = tt) then intro1 >>= (λ x, induction_core semireducible x (I_name <.> "brec_on") [v_name, F_name]) else intro v_name >> return (), -- Apply cases to first element of type (I ...) get_local v_name >>= cases, all_goals (dec_eq_case_1 I_name F_name) end tactic
9190dda45b25c973c2d23b474de683dfa2413bca
38bf3fd2bb651ab70511408fcf70e2029e2ba310
/src/topology/algebra/infinite_sum.lean
0d03b0c91963f81b10bdf4050406ddbea08c6927
[ "Apache-2.0" ]
permissive
JaredCorduan/mathlib
130392594844f15dad65a9308c242551bae6cd2e
d5de80376088954d592a59326c14404f538050a1
refs/heads/master
1,595,862,206,333
1,570,816,457,000
1,570,816,457,000
209,134,499
0
0
Apache-2.0
1,568,746,811,000
1,568,746,811,000
null
UTF-8
Lean
false
false
25,726
lean
/- 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 Infinite sum over a topological monoid This sum is known as unconditionally convergent, as it sums to the same value under all possible permutations. For Euclidean spaces (finite dimensional Banach spaces) this is equivalent to absolute convergence. Note: There are summable sequences which are not unconditionally convergent! The other way holds generally, see `tendsto_sum_nat_of_has_sum`. Reference: * Bourbaki: General Topology (1995), Chapter 3 §5 (Infinite sums in commutative groups) -/ import logic.function algebra.big_operators data.set.lattice data.finset topology.metric_space.basic topology.algebra.uniform_group topology.algebra.ring topology.algebra.ordered topology.instances.real noncomputable theory open lattice finset filter function classical local attribute [instance] classical.prop_decidable -- TODO: use "open_locale classical" def option.cases_on' {α β} : option α → β → (α → β) → β | none n s := n | (some a) n s := s a variables {α : Type*} {β : Type*} {γ : Type*} section has_sum variables [add_comm_monoid α] [topological_space α] /-- Infinite sum on a topological monoid The `at_top` filter on `finset α` is the limit of all finite sets towards the entire type. So we sum up bigger and bigger sets. This sum operation is still invariant under reordering, and a absolute sum operator. This is based on Mario Carneiro's infinite sum in Metamath. For the definition or many statements, α does not need to be a topological monoid. We only add this assumption later, for the lemmas where it is relevant. -/ def has_sum (f : β → α) (a : α) : Prop := tendsto (λs:finset β, s.sum f) at_top (nhds a) /-- `summable f` means that `f` has some (infinite) sum. Use `tsum` to get the value. -/ def summable (f : β → α) : Prop := ∃a, has_sum f a /-- `tsum f` is the sum of `f` it exists, or 0 otherwise -/ def tsum (f : β → α) := if h : summable f then classical.some h else 0 notation `∑` binders `, ` r:(scoped f, tsum f) := r variables {f g : β → α} {a b : α} {s : finset β} lemma has_sum_tsum (ha : summable f) : has_sum f (∑b, f b) := by simp [ha, tsum]; exact some_spec ha lemma summable_spec (ha : has_sum f a) : summable f := ⟨a, ha⟩ lemma has_sum_zero : has_sum (λb, 0 : β → α) 0 := by simp [has_sum, tendsto_const_nhds] lemma summable_zero : summable (λb, 0 : β → α) := summable_spec has_sum_zero lemma has_sum_sum_of_ne_finset_zero (hf : ∀b∉s, f b = 0) : has_sum f (s.sum f) := tendsto_infi' s $ tendsto.congr' (assume t (ht : s ⊆ t), show s.sum f = t.sum f, from sum_subset ht $ assume x _, hf _) tendsto_const_nhds lemma summable_sum_of_ne_finset_zero (hf : ∀b∉s, f b = 0) : summable f := summable_spec $ has_sum_sum_of_ne_finset_zero hf lemma has_sum_ite_eq (b : β) (a : α) : has_sum (λb', if b' = b then a else 0) a := suffices has_sum (λb', if b' = b then a else 0) (({b} : finset β).sum (λb', if b' = b then a else 0)), from by simpa, has_sum_sum_of_ne_finset_zero $ assume b' hb, have b' ≠ b, by simpa using hb, by rw [if_neg this] lemma has_sum_of_iso {j : γ → β} {i : β → γ} (hf : has_sum f a) (h₁ : ∀x, i (j x) = x) (h₂ : ∀x, j (i x) = x) : has_sum (f ∘ j) a := have ∀x y, j x = j y → x = y, from assume x y h, have i (j x) = i (j y), by rw [h], by rwa [h₁, h₁] at this, have (λs:finset γ, s.sum (f ∘ j)) = (λs:finset β, s.sum f) ∘ (λs:finset γ, s.image j), from funext $ assume s, (sum_image $ assume x _ y _, this x y).symm, show tendsto (λs:finset γ, s.sum (f ∘ j)) at_top (nhds a), by rw [this]; apply hf.comp (tendsto_finset_image_at_top_at_top h₂) lemma has_sum_iff_has_sum_of_iso {j : γ → β} (i : β → γ) (h₁ : ∀x, i (j x) = x) (h₂ : ∀x, j (i x) = x) : has_sum (f ∘ j) a ↔ has_sum f a := iff.intro (assume hfj, have has_sum ((f ∘ j) ∘ i) a, from has_sum_of_iso hfj h₂ h₁, by simp [(∘), h₂] at this; assumption) (assume hf, has_sum_of_iso hf h₁ h₂) lemma has_sum_hom (g : α → γ) [add_comm_monoid γ] [topological_space γ] [is_add_monoid_hom g] (h₃ : continuous g) (hf : has_sum f a) : has_sum (g ∘ f) (g a) := have (λs:finset β, s.sum (g ∘ f)) = g ∘ (λs:finset β, s.sum f), from funext $ assume s, sum_hom g, show tendsto (λs:finset β, s.sum (g ∘ f)) at_top (nhds (g a)), by rw [this]; exact tendsto.comp (continuous_iff_continuous_at.mp h₃ a) hf lemma tendsto_sum_nat_of_has_sum {f : ℕ → α} (h : has_sum f a) : tendsto (λn:ℕ, (range n).sum f) at_top (nhds a) := suffices map (λ (n : ℕ), sum (range n) f) at_top ≤ map (λ (s : finset ℕ), sum s f) at_top, from le_trans this h, assume s (hs : {t : finset ℕ | t.sum f ∈ s} ∈ at_top), let ⟨t, ht⟩ := mem_at_top_sets.mp hs, ⟨n, hn⟩ := @exists_nat_subset_range t in mem_at_top_sets.mpr ⟨n, assume n' hn', ht _ $ finset.subset.trans hn $ range_subset.mpr hn'⟩ variable [topological_add_monoid α] lemma has_sum_add (hf : has_sum f a) (hg : has_sum g b) : has_sum (λb, f b + g b) (a + b) := by simp [has_sum, sum_add_distrib]; exact tendsto_add hf hg lemma summable_add (hf : summable f) (hg : summable g) : summable (λb, f b + g b) := summable_spec $ has_sum_add (has_sum_tsum hf)(has_sum_tsum hg) lemma has_sum_sum {f : γ → β → α} {a : γ → α} {s : finset γ} : (∀i∈s, has_sum (f i) (a i)) → has_sum (λb, s.sum $ λi, f i b) (s.sum a) := finset.induction_on s (by simp [has_sum_zero]) (by simp [has_sum_add] {contextual := tt}) lemma summable_sum {f : γ → β → α} {s : finset γ} (hf : ∀i∈s, summable (f i)) : summable (λb, s.sum $ λi, f i b) := summable_spec $ has_sum_sum $ assume i hi, has_sum_tsum $ hf i hi lemma has_sum_sigma [regular_space α] {γ : β → Type*} {f : (Σ b:β, γ b) → α} {g : β → α} {a : α} (hf : ∀b, has_sum (λc, f ⟨b, c⟩) (g b)) (ha : has_sum f a) : has_sum g a := assume s' hs', let ⟨s, hs, hss', hsc⟩ := nhds_is_closed hs', ⟨u, hu⟩ := mem_at_top_sets.mp $ ha $ hs, fsts := u.image sigma.fst, snds := λb, u.bind (λp, (if h : p.1 = b then {cast (congr_arg γ h) p.2} else ∅ : finset (γ b))) in have u_subset : u ⊆ fsts.sigma snds, from subset_iff.mpr $ assume ⟨b, c⟩ hu, have hb : b ∈ fsts, from finset.mem_image.mpr ⟨_, hu, rfl⟩, have hc : c ∈ snds b, from mem_bind.mpr ⟨_, hu, by simp; refl⟩, by simp [mem_sigma, hb, hc] , mem_at_top_sets.mpr $ exists.intro fsts $ assume bs (hbs : fsts ⊆ bs), have h : ∀cs : Π b ∈ bs, finset (γ b), (⋂b (hb : b ∈ bs), (λp:Πb, finset (γ b), p b) ⁻¹' {cs' | cs b hb ⊆ cs' }) ∩ (λp, bs.sum (λb, (p b).sum (λc, f ⟨b, c⟩))) ⁻¹' s ≠ ∅, from assume cs, let cs' := λb, (if h : b ∈ bs then cs b h else ∅) ∪ snds b in have sum_eq : bs.sum (λb, (cs' b).sum (λc, f ⟨b, c⟩)) = (bs.sigma cs').sum f, from sum_sigma.symm, have (bs.sigma cs').sum f ∈ s, from hu _ $ finset.subset.trans u_subset $ sigma_mono hbs $ assume b, @finset.subset_union_right (γ b) _ _ _, set.ne_empty_iff_exists_mem.mpr $ exists.intro cs' $ by simp [sum_eq, this]; { intros b hb, simp [cs', hb, finset.subset_union_right] }, have tendsto (λp:(Πb:β, finset (γ b)), bs.sum (λb, (p b).sum (λc, f ⟨b, c⟩))) (⨅b (h : b ∈ bs), at_top.comap (λp, p b)) (nhds (bs.sum g)), from tendsto_finset_sum bs $ assume c hc, tendsto_infi' c $ tendsto_infi' hc $ by apply tendsto.comp (hf c) tendsto_comap, have bs.sum g ∈ s, from mem_of_closed_of_tendsto' this hsc $ forall_sets_neq_empty_iff_neq_bot.mp $ by simp [mem_inf_sets, exists_imp_distrib, and_imp, forall_and_distrib, filter.mem_infi_sets_finset, mem_comap_sets, skolem, mem_at_top_sets, and_comm]; from assume s₁ s₂ s₃ hs₁ hs₃ p hs₂ p' hp cs hp', have (⋂b (h : b ∈ bs), (λp:(Πb, finset (γ b)), p b) ⁻¹' {cs' | cs b h ⊆ cs' }) ≤ (⨅b∈bs, p b), from infi_le_infi $ assume b, infi_le_infi $ assume hb, le_trans (set.preimage_mono $ hp' b hb) (hp b hb), neq_bot_of_le_neq_bot (h _) (le_trans (set.inter_subset_inter (le_trans this hs₂) hs₃) hs₁), hss' this lemma summable_sigma [regular_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α} (hf : ∀b, summable (λc, f ⟨b, c⟩)) (ha : summable f) : summable (λb, ∑c, f ⟨b, c⟩) := summable_spec $ has_sum_sigma (assume b, has_sum_tsum $ hf b) (has_sum_tsum ha) end has_sum section has_sum_iff_has_sum_of_iso_ne_zero variables [add_comm_monoid α] [topological_space α] variables {f : β → α} {g : γ → α} {a : α} lemma has_sum_of_has_sum (h_eq : ∀u:finset γ, ∃v:finset β, ∀v', v ⊆ v' → ∃u', u ⊆ u' ∧ u'.sum g = v'.sum f) (hf : has_sum g a) : has_sum f a := suffices at_top.map (λs:finset β, s.sum f) ≤ at_top.map (λs:finset γ, s.sum g), from le_trans this hf, by rw [map_at_top_eq, map_at_top_eq]; from (le_infi $ assume b, let ⟨v, hv⟩ := h_eq b in infi_le_of_le v $ by simp [set.image_subset_iff]; exact hv) lemma has_sum_iff_has_sum (h₁ : ∀u:finset γ, ∃v:finset β, ∀v', v ⊆ v' → ∃u', u ⊆ u' ∧ u'.sum g = v'.sum f) (h₂ : ∀v:finset β, ∃u:finset γ, ∀u', u ⊆ u' → ∃v', v ⊆ v' ∧ v'.sum f = u'.sum g) : has_sum f a ↔ has_sum g a := ⟨has_sum_of_has_sum h₂, has_sum_of_has_sum h₁⟩ variables (i : Π⦃c⦄, g c ≠ 0 → β) (hi : ∀⦃c⦄ (h : g c ≠ 0), f (i h) ≠ 0) (j : Π⦃b⦄, f b ≠ 0 → γ) (hj : ∀⦃b⦄ (h : f b ≠ 0), g (j h) ≠ 0) (hji : ∀⦃c⦄ (h : g c ≠ 0), j (hi h) = c) (hij : ∀⦃b⦄ (h : f b ≠ 0), i (hj h) = b) (hgj : ∀⦃b⦄ (h : f b ≠ 0), g (j h) = f b) include hi hj hji hij hgj lemma has_sum_of_has_sum_ne_zero : has_sum g a → has_sum f a := have j_inj : ∀x y (hx : f x ≠ 0) (hy : f y ≠ 0), (j hx = j hy ↔ x = y), from assume x y hx hy, ⟨assume h, have i (hj hx) = i (hj hy), by simp [h], by rwa [hij, hij] at this; assumption, by simp {contextual := tt}⟩, let ii : finset γ → finset β := λu, u.bind $ λc, if h : g c = 0 then ∅ else {i h} in let jj : finset β → finset γ := λv, v.bind $ λb, if h : f b = 0 then ∅ else {j h} in has_sum_of_has_sum $ assume u, exists.intro (ii u) $ assume v hv, exists.intro (u ∪ jj v) $ and.intro (subset_union_left _ _) $ have ∀c:γ, c ∈ u ∪ jj v → c ∉ jj v → g c = 0, from assume c hc hnc, classical.by_contradiction $ assume h : g c ≠ 0, have c ∈ u, from (finset.mem_union.1 hc).resolve_right hnc, have i h ∈ v, from hv $ by simp [mem_bind]; existsi c; simp [h, this], have j (hi h) ∈ jj v, by simp [mem_bind]; existsi i h; simp [h, hi, this], by rw [hji h] at this; exact hnc this, calc (u ∪ jj v).sum g = (jj v).sum g : (sum_subset (subset_union_right _ _) this).symm ... = v.sum _ : sum_bind $ by intros x _ y _ _; by_cases f x = 0; by_cases f y = 0; simp [*]; cc ... = v.sum f : sum_congr rfl $ by intros x hx; by_cases f x = 0; simp [*] lemma has_sum_iff_has_sum_of_ne_zero : has_sum f a ↔ has_sum g a := iff.intro (has_sum_of_has_sum_ne_zero j hj i hi hij hji $ assume b hb, by rw [←hgj (hi _), hji]) (has_sum_of_has_sum_ne_zero i hi j hj hji hij hgj) lemma summable_iff_summable_ne_zero : summable g ↔ summable f := exists_congr $ assume a, has_sum_iff_has_sum_of_ne_zero j hj i hi hij hji $ assume b hb, by rw [←hgj (hi _), hji] end has_sum_iff_has_sum_of_iso_ne_zero section has_sum_iff_has_sum_of_bij_ne_zero variables [add_comm_monoid α] [topological_space α] variables {f : β → α} {g : γ → α} {a : α} (i : Π⦃c⦄, g c ≠ 0 → β) (h₁ : ∀⦃c₁ c₂⦄ (h₁ : g c₁ ≠ 0) (h₂ : g c₂ ≠ 0), i h₁ = i h₂ → c₁ = c₂) (h₂ : ∀⦃b⦄, f b ≠ 0 → ∃c (h : g c ≠ 0), i h = b) (h₃ : ∀⦃c⦄ (h : g c ≠ 0), f (i h) = g c) include i h₁ h₂ h₃ lemma has_sum_iff_has_sum_of_ne_zero_bij : has_sum f a ↔ has_sum g a := have hi : ∀⦃c⦄ (h : g c ≠ 0), f (i h) ≠ 0, from assume c h, by simp [h₃, h], let j : Π⦃b⦄, f b ≠ 0 → γ := λb h, some $ h₂ h in have hj : ∀⦃b⦄ (h : f b ≠ 0), ∃(h : g (j h) ≠ 0), i h = b, from assume b h, some_spec $ h₂ h, have hj₁ : ∀⦃b⦄ (h : f b ≠ 0), g (j h) ≠ 0, from assume b h, let ⟨h₁, _⟩ := hj h in h₁, have hj₂ : ∀⦃b⦄ (h : f b ≠ 0), i (hj₁ h) = b, from assume b h, let ⟨h₁, h₂⟩ := hj h in h₂, has_sum_iff_has_sum_of_ne_zero i hi j hj₁ (assume c h, h₁ (hj₁ _) h $ hj₂ _) hj₂ (assume b h, by rw [←h₃ (hj₁ _), hj₂]) lemma summable_iff_summable_ne_zero_bij : summable f ↔ summable g := exists_congr $ assume a, has_sum_iff_has_sum_of_ne_zero_bij @i h₁ h₂ h₃ end has_sum_iff_has_sum_of_bij_ne_zero section tsum variables [add_comm_monoid α] [topological_space α] [t2_space α] variables {f g : β → α} {a a₁ a₂ : α} lemma has_sum_unique : has_sum f a₁ → has_sum f a₂ → a₁ = a₂ := tendsto_nhds_unique at_top_ne_bot lemma tsum_eq_has_sum (ha : has_sum f a) : (∑b, f b) = a := has_sum_unique (has_sum_tsum ⟨a, ha⟩) ha lemma has_sum_iff_of_summable (h : summable f) : has_sum f a ↔ (∑b, f b) = a := iff.intro tsum_eq_has_sum (assume eq, eq ▸ has_sum_tsum h) @[simp] lemma tsum_zero : (∑b:β, 0:α) = 0 := tsum_eq_has_sum has_sum_zero lemma tsum_eq_sum {f : β → α} {s : finset β} (hf : ∀b∉s, f b = 0) : (∑b, f b) = s.sum f := tsum_eq_has_sum $ has_sum_sum_of_ne_finset_zero hf lemma tsum_fintype [fintype β] (f : β → α) : (∑b, f b) = finset.univ.sum f := tsum_eq_sum $ λ a h, h.elim (mem_univ _) lemma tsum_eq_single {f : β → α} (b : β) (hf : ∀b' ≠ b, f b' = 0) : (∑b, f b) = f b := calc (∑b, f b) = (finset.singleton b).sum f : tsum_eq_sum $ by simp [hf] {contextual := tt} ... = f b : by simp @[simp] lemma tsum_ite_eq (b : β) (a : α) : (∑b', if b' = b then a else 0) = a := tsum_eq_has_sum (has_sum_ite_eq b a) lemma tsum_eq_tsum_of_has_sum_iff_has_sum {f : β → α} {g : γ → α} (h : ∀{a}, has_sum f a ↔ has_sum g a) : (∑b, f b) = (∑c, g c) := by_cases (assume : ∃a, has_sum f a, let ⟨a, hfa⟩ := this in have hga : has_sum g a, from h.mp hfa, by rw [tsum_eq_has_sum hfa, tsum_eq_has_sum hga]) (assume hf : ¬ summable f, have hg : ¬ summable g, from assume ⟨a, hga⟩, hf ⟨a, h.mpr hga⟩, by simp [tsum, hf, hg]) lemma tsum_eq_tsum_of_ne_zero {f : β → α} {g : γ → α} (i : Π⦃c⦄, g c ≠ 0 → β) (hi : ∀⦃c⦄ (h : g c ≠ 0), f (i h) ≠ 0) (j : Π⦃b⦄, f b ≠ 0 → γ) (hj : ∀⦃b⦄ (h : f b ≠ 0), g (j h) ≠ 0) (hji : ∀⦃c⦄ (h : g c ≠ 0), j (hi h) = c) (hij : ∀⦃b⦄ (h : f b ≠ 0), i (hj h) = b) (hgj : ∀⦃b⦄ (h : f b ≠ 0), g (j h) = f b) : (∑i, f i) = (∑j, g j) := tsum_eq_tsum_of_has_sum_iff_has_sum $ assume a, has_sum_iff_has_sum_of_ne_zero i hi j hj hji hij hgj lemma tsum_eq_tsum_of_ne_zero_bij {f : β → α} {g : γ → α} (i : Π⦃c⦄, g c ≠ 0 → β) (h₁ : ∀⦃c₁ c₂⦄ (h₁ : g c₁ ≠ 0) (h₂ : g c₂ ≠ 0), i h₁ = i h₂ → c₁ = c₂) (h₂ : ∀⦃b⦄, f b ≠ 0 → ∃c (h : g c ≠ 0), i h = b) (h₃ : ∀⦃c⦄ (h : g c ≠ 0), f (i h) = g c) : (∑i, f i) = (∑j, g j) := tsum_eq_tsum_of_has_sum_iff_has_sum $ assume a, has_sum_iff_has_sum_of_ne_zero_bij i h₁ h₂ h₃ lemma tsum_eq_tsum_of_iso (j : γ → β) (i : β → γ) (h₁ : ∀x, i (j x) = x) (h₂ : ∀x, j (i x) = x) : (∑c, f (j c)) = (∑b, f b) := tsum_eq_tsum_of_has_sum_iff_has_sum $ assume a, has_sum_iff_has_sum_of_iso i h₁ h₂ lemma tsum_equiv (j : γ ≃ β) : (∑c, f (j c)) = (∑b, f b) := tsum_eq_tsum_of_iso j j.symm (by simp) (by simp) variable [topological_add_monoid α] lemma tsum_add (hf : summable f) (hg : summable g) : (∑b, f b + g b) = (∑b, f b) + (∑b, g b) := tsum_eq_has_sum $ has_sum_add (has_sum_tsum hf) (has_sum_tsum hg) lemma tsum_sum {f : γ → β → α} {s : finset γ} (hf : ∀i∈s, summable (f i)) : (∑b, s.sum (λi, f i b)) = s.sum (λi, ∑b, f i b) := tsum_eq_has_sum $ has_sum_sum $ assume i hi, has_sum_tsum $ hf i hi lemma tsum_sigma [regular_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α} (h₁ : ∀b, summable (λc, f ⟨b, c⟩)) (h₂ : summable f) : (∑p, f p) = (∑b c, f ⟨b, c⟩) := (tsum_eq_has_sum $ has_sum_sigma (assume b, has_sum_tsum $ h₁ b) $ has_sum_tsum h₂).symm end tsum section topological_group variables [add_comm_group α] [topological_space α] [topological_add_group α] variables {f g : β → α} {a a₁ a₂ : α} lemma has_sum_neg : has_sum f a → has_sum (λb, - f b) (- a) := has_sum_hom has_neg.neg continuous_neg' lemma summable_neg (hf : summable f) : summable (λb, - f b) := summable_spec $ has_sum_neg $ has_sum_tsum $ hf lemma has_sum_sub (hf : has_sum f a₁) (hg : has_sum g a₂) : has_sum (λb, f b - g b) (a₁ - a₂) := by simp; exact has_sum_add hf (has_sum_neg hg) lemma summable_sub (hf : summable f) (hg : summable g) : summable (λb, f b - g b) := summable_spec $ has_sum_sub (has_sum_tsum hf) (has_sum_tsum hg) section tsum variables [t2_space α] lemma tsum_neg (hf : summable f) : (∑b, - f b) = - (∑b, f b) := tsum_eq_has_sum $ has_sum_neg $ has_sum_tsum $ hf lemma tsum_sub (hf : summable f) (hg : summable g) : (∑b, f b - g b) = (∑b, f b) - (∑b, g b) := tsum_eq_has_sum $ has_sum_sub (has_sum_tsum hf) (has_sum_tsum hg) lemma tsum_eq_zero_add {f : ℕ → α} (hf : summable f) : (∑b, f b) = f 0 + (∑b, f (b + 1)) := begin let f₁ : ℕ → α := λ n, nat.rec (f 0) (λ _ _, 0) n, let f₂ : ℕ → α := λ n, nat.rec 0 (λ k _, f (k+1)) n, have : f = λ n, f₁ n + f₂ n, { ext n, symmetry, cases n, apply add_zero, apply zero_add }, have hf₁ : summable f₁, { fapply summable_sum_of_ne_finset_zero, { exact finset.singleton 0 }, { rintros (_ | n) hn, { exfalso, apply hn, apply finset.mem_singleton_self }, { refl } } }, have hf₂ : summable f₂, { have : f₂ = λ n, f n - f₁ n, ext, rw [eq_sub_iff_add_eq', this], rw [this], apply summable_sub hf hf₁ }, conv_lhs { rw [this] }, rw [tsum_add hf₁ hf₂, tsum_eq_single 0], { congr' 1, fapply tsum_eq_tsum_of_ne_zero_bij (λ n _, n + 1), { intros _ _ _ _, exact nat.succ_inj }, { rintros (_ | n) h, { contradiction }, { exact ⟨n, h, rfl⟩ } }, { intros, refl }, { apply_instance } }, { rintros (_ | n) hn, { contradiction }, { refl } }, { apply_instance } end end tsum end topological_group section topological_semiring variables [semiring α] [topological_space α] [topological_semiring α] variables {f g : β → α} {a a₁ a₂ : α} lemma has_sum_mul_left (a₂) : has_sum f a₁ → has_sum (λb, a₂ * f b) (a₂ * a₁) := has_sum_hom _ (continuous_mul continuous_const continuous_id) lemma has_sum_mul_right (a₂) (hf : has_sum f a₁) : has_sum (λb, f b * a₂) (a₁ * a₂) := @has_sum_hom _ _ _ _ _ f a₁ (λa, a * a₂) _ _ _ (continuous_mul continuous_id continuous_const) hf lemma summable_mul_left (a) (hf : summable f) : summable (λb, a * f b) := summable_spec $ has_sum_mul_left _ $ has_sum_tsum hf lemma summable_mul_right (a) (hf : summable f) : summable (λb, f b * a) := summable_spec $ has_sum_mul_right _ $ has_sum_tsum hf section tsum variables [t2_space α] lemma tsum_mul_left (a) (hf : summable f) : (∑b, a * f b) = a * (∑b, f b) := tsum_eq_has_sum $ has_sum_mul_left _ $ has_sum_tsum hf lemma tsum_mul_right (a) (hf : summable f) : (∑b, f b * a) = (∑b, f b) * a := tsum_eq_has_sum $ has_sum_mul_right _ $ has_sum_tsum hf end tsum end topological_semiring section order_topology variables [ordered_comm_monoid α] [topological_space α] [ordered_topology α] variables {f g : β → α} {a a₁ a₂ : α} lemma has_sum_le (h : ∀b, f b ≤ g b) (hf : has_sum f a₁) (hg : has_sum g a₂) : a₁ ≤ a₂ := le_of_tendsto_of_tendsto at_top_ne_bot hf hg $ univ_mem_sets' $ assume s, sum_le_sum $ assume b _, h b lemma has_sum_le_inj {g : γ → α} (i : β → γ) (hi : injective i) (hs : ∀c∉set.range i, 0 ≤ g c) (h : ∀b, f b ≤ g (i b)) (hf : has_sum f a₁) (hg : has_sum g a₂) : a₁ ≤ a₂ := have has_sum (λc, (partial_inv i c).cases_on' 0 f) a₁, begin refine (has_sum_iff_has_sum_of_ne_zero_bij (λb _, i b) _ _ _).2 hf, { assume c₁ c₂ h₁ h₂ eq, exact hi eq }, { assume c hc, cases eq : partial_inv i c with b; rw eq at hc, { contradiction }, { rw [partial_inv_of_injective hi] at eq, exact ⟨b, hc, eq⟩ } }, { assume c hc, rw [partial_inv_left hi, option.cases_on'] } end, begin refine has_sum_le (assume c, _) this hg, by_cases c ∈ set.range i, { rcases h with ⟨b, rfl⟩, rw [partial_inv_left hi, option.cases_on'], exact h _ }, { have : partial_inv i c = none := dif_neg h, rw [this, option.cases_on'], exact hs _ h } end lemma tsum_le_tsum (h : ∀b, f b ≤ g b) (hf : summable f) (hg : summable g) : (∑b, f b) ≤ (∑b, g b) := has_sum_le h (has_sum_tsum hf) (has_sum_tsum hg) end order_topology section uniform_group variables [add_comm_group α] [uniform_space α] [complete_space α] variables (f g : β → α) {a a₁ a₂ : α} lemma summable_iff_cauchy : summable f ↔ cauchy (map (λ (s : finset β), sum s f) at_top) := (cauchy_map_iff_exists_tendsto at_top_ne_bot).symm variable [uniform_add_group α] lemma summable_iff_vanishing : summable f ↔ ∀ e ∈ nhds (0:α), (∃s:finset β, ∀t, disjoint t s → t.sum f ∈ e) := begin simp only [summable_iff_cauchy, cauchy_map_iff, and_iff_right at_top_ne_bot, prod_at_top_at_top_eq, uniformity_eq_comap_nhds_zero α, tendsto_comap_iff, (∘)], rw [tendsto_at_top' (_ : finset β × finset β → α)], split, { assume h e he, rcases h e he with ⟨⟨s₁, s₂⟩, h⟩, use [s₁ ∪ s₂], assume t ht, specialize h (s₁ ∪ s₂, (s₁ ∪ s₂) ∪ t) ⟨le_sup_left, le_sup_left_of_le le_sup_right⟩, simpa only [finset.sum_union ht.symm, add_sub_cancel'] using h }, { assume h e he, rcases exists_nhds_half_neg he with ⟨d, hd, hde⟩, rcases h d hd with ⟨s, h⟩, use [(s, s)], rintros ⟨t₁, t₂⟩ ⟨ht₁, ht₂⟩, have : t₂.sum f - t₁.sum f = (t₂ \ s).sum f - (t₁ \ s).sum f, { simp only [(finset.sum_sdiff ht₁).symm, (finset.sum_sdiff ht₂).symm, add_sub_add_right_eq_sub] }, simp only [this], exact hde _ _ (h _ finset.sdiff_disjoint) (h _ finset.sdiff_disjoint) } end /- TODO: generalize to monoid with a uniform continuous subtraction operator: `(a + b) - b = a` -/ lemma summable_of_summable_of_sub (hf : summable f) (h : ∀b, g b = 0 ∨ g b = f b) : summable g := (summable_iff_vanishing g).2 $ assume e he, let ⟨s, hs⟩ := (summable_iff_vanishing f).1 hf e he in ⟨s, assume t ht, have eq : (t.filter (λb, g b = f b)).sum f = t.sum g := calc (t.filter (λb, g b = f b)).sum f = (t.filter (λb, g b = f b)).sum g : finset.sum_congr rfl (assume b hb, (finset.mem_filter.1 hb).2.symm) ... = t.sum g : begin refine finset.sum_subset (finset.filter_subset _) _, assume b hbt hb, simp only [(∉), finset.mem_filter, and_iff_right hbt] at hb, exact (h b).resolve_right hb end, eq ▸ hs _ $ finset.disjoint_of_subset_left (finset.filter_subset _) ht⟩ lemma summable_comp_of_summable_of_injective {i : γ → β} (hf : summable f) (hi : injective i) : summable (f ∘ i) := suffices summable (λb, if b ∈ set.range i then f b else 0), begin refine (summable_iff_summable_ne_zero_bij (λc _, i c) _ _ _).1 this, { assume c₁ c₂ hc₁ hc₂ eq, exact hi eq }, { assume b hb, split_ifs at hb, { rcases h with ⟨c, rfl⟩, exact ⟨c, hb, rfl⟩ }, { contradiction } }, { assume c hc, exact if_pos (set.mem_range_self _) } end, summable_of_summable_of_sub _ _ hf $ assume b, by by_cases b ∈ set.range i; simp [h] end uniform_group section cauchy_seq open finset.Ico filter lemma cauchy_seq_of_summable_dist [metric_space α] {f : ℕ → α} (h : summable (λn, dist (f n) (f n.succ))) : cauchy_seq f := begin let d := λn, dist (f n) (f (n+1)), refine metric.cauchy_seq_iff'.2 (λε εpos, _), rcases (summable_iff_vanishing _).1 h {x : ℝ | x < ε} (gt_mem_nhds εpos) with ⟨s, hs⟩, have : ∃N:ℕ, ∀x ∈ s, x < N, { by_cases h : s = ∅, { use 0, simp [h]}, { use s.max' h + 1, exact λx hx, lt_of_le_of_lt (s.le_max' h x hx) (nat.lt_succ_self _) }}, rcases this with ⟨N, hN⟩, refine ⟨N, λn hn, _⟩, have : ∀n, n ≥ N → dist (f N) (f n) ≤ (Ico N n).sum d, { apply nat.le_induction, { simp }, { assume n hn hrec, calc dist (f N) (f (n+1)) ≤ dist (f N) (f n) + d n : dist_triangle _ _ _ ... ≤ (Ico N n).sum d + d n : add_le_add hrec (le_refl _) ... = (Ico N (n+1)).sum d : by rw [succ_top hn, sum_insert, add_comm]; simp }}, calc dist (f n) (f N) ≤ (Ico N n).sum d : by rw dist_comm; apply this n hn ... < ε : hs _ (finset.disjoint_iff_ne.2 (λa ha b hb, ne_of_gt (lt_of_lt_of_le (hN _ hb) (mem.1 ha).1))) end end cauchy_seq
a8597d771fcbee6cac943fc89915d562b7a0f1b5
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/logic/embedding.lean
79b063ca89d64bdaa6bb52e567a49538941d4e31
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
10,474
lean
/- 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.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.equiv.basic import Mathlib.data.sigma.basic import Mathlib.algebra.group.defs import Mathlib.PostPort universes u_1 u_2 l u v u_3 w x u_4 namespace Mathlib /-! # Injective functions -/ namespace function /-- `α ↪ β` is a bundled injective function. -/ structure embedding (α : Sort u_1) (β : Sort u_2) where to_fun : α → β inj' : injective to_fun infixr:25 " ↪ " => Mathlib.function.embedding protected instance embedding.has_coe_to_fun {α : Sort u} {β : Sort v} : has_coe_to_fun (α ↪ β) := has_coe_to_fun.mk (fun (x : α ↪ β) => α → β) embedding.to_fun end function /-- Convert an `α ≃ β` to `α ↪ β`. -/ @[simp] theorem equiv.to_embedding_apply {α : Sort u} {β : Sort v} (f : α ≃ β) : ∀ (ᾰ : α), coe_fn (equiv.to_embedding f) ᾰ = coe_fn f ᾰ := fun (ᾰ : α) => Eq.refl (coe_fn (equiv.to_embedding f) ᾰ) namespace function namespace embedding theorem ext {α : Sort u_1} {β : Sort u_2} {f : α ↪ β} {g : α ↪ β} (h : ∀ (x : α), coe_fn f x = coe_fn g x) : f = g := sorry theorem ext_iff {α : Sort u_1} {β : Sort u_2} {f : α ↪ β} {g : α ↪ β} : (∀ (x : α), coe_fn f x = coe_fn g x) ↔ f = g := sorry @[simp] theorem to_fun_eq_coe {α : Sort u_1} {β : Sort u_2} (f : α ↪ β) : to_fun f = ⇑f := rfl @[simp] theorem coe_fn_mk {α : Sort u_1} {β : Sort u_2} (f : α → β) (i : injective f) : ⇑(mk f i) = f := rfl theorem injective {α : Sort u_1} {β : Sort u_2} (f : α ↪ β) : injective ⇑f := inj' f @[simp] theorem refl_apply (α : Sort u_1) (a : α) : coe_fn (embedding.refl α) a = a := Eq.refl a @[simp] theorem trans_apply {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} (f : α ↪ β) (g : β ↪ γ) : ∀ (ᾰ : α), coe_fn (embedding.trans f g) ᾰ = coe_fn g (coe_fn f ᾰ) := fun (ᾰ : α) => Eq.refl (coe_fn g (coe_fn f ᾰ)) @[simp] theorem equiv_to_embedding_trans_symm_to_embedding {α : Sort u_1} {β : Sort u_2} (e : α ≃ β) : embedding.trans (equiv.to_embedding e) (equiv.to_embedding (equiv.symm e)) = embedding.refl α := sorry @[simp] theorem equiv_symm_to_embedding_trans_to_embedding {α : Sort u_1} {β : Sort u_2} (e : α ≃ β) : embedding.trans (equiv.to_embedding (equiv.symm e)) (equiv.to_embedding e) = embedding.refl β := sorry protected def congr {α : Sort u} {β : Sort v} {γ : Sort w} {δ : Sort x} (e₁ : α ≃ β) (e₂ : γ ≃ δ) (f : α ↪ γ) : β ↪ δ := embedding.trans (equiv.to_embedding (equiv.symm e₁)) (embedding.trans f (equiv.to_embedding e₂)) /-- A right inverse `surj_inv` of a surjective function as an `embedding`. -/ protected def of_surjective {α : Sort u_1} {β : Sort u_2} (f : β → α) (hf : surjective f) : α ↪ β := mk (surj_inv hf) (injective_surj_inv hf) /-- Convert a surjective `embedding` to an `equiv` -/ protected def equiv_of_surjective {α : Sort u_1} {β : Type u_2} (f : α ↪ β) (hf : surjective ⇑f) : α ≃ β := equiv.of_bijective ⇑f sorry protected def of_not_nonempty {α : Sort u_1} {β : Sort u_2} (hα : ¬Nonempty α) : α ↪ β := mk (fun (a : α) => false.elim sorry) sorry /-- Change the value of an embedding `f` at one point. If the prescribed image is already occupied by some `f a'`, then swap the values at these two points. -/ def set_value {α : Sort u_1} {β : Sort u_2} (f : α ↪ β) (a : α) (b : β) [(a' : α) → Decidable (a' = a)] [(a' : α) → Decidable (coe_fn f a' = b)] : α ↪ β := mk (fun (a' : α) => ite (a' = a) b (ite (coe_fn f a' = b) (coe_fn f a) (coe_fn f a'))) sorry theorem set_value_eq {α : Sort u_1} {β : Sort u_2} (f : α ↪ β) (a : α) (b : β) [(a' : α) → Decidable (a' = a)] [(a' : α) → Decidable (coe_fn f a' = b)] : coe_fn (set_value f a b) a = b := sorry /-- Embedding into `option` -/ protected def some {α : Type u_1} : α ↪ Option α := mk some (option.some_injective α) /-- Embedding of a `subtype`. -/ def subtype {α : Sort u_1} (p : α → Prop) : Subtype p ↪ α := mk coe sorry @[simp] theorem coe_subtype {α : Sort u_1} (p : α → Prop) : ⇑(subtype p) = coe := rfl /-- Choosing an element `b : β` gives an embedding of `punit` into `β`. -/ def punit {β : Sort u_1} (b : β) : PUnit ↪ β := mk (fun (_x : PUnit) => b) sorry /-- Fixing an element `b : β` gives an embedding `α ↪ α × β`. -/ def sectl (α : Type u_1) {β : Type u_2} (b : β) : α ↪ α × β := mk (fun (a : α) => (a, b)) sorry /-- Fixing an element `a : α` gives an embedding `β ↪ α × β`. -/ def sectr {α : Type u_1} (a : α) (β : Type u_2) : β ↪ α × β := mk (fun (b : β) => (a, b)) sorry /-- Restrict the codomain of an embedding. -/ def cod_restrict {α : Sort u_1} {β : Type u_2} (p : set β) (f : α ↪ β) (H : ∀ (a : α), coe_fn f a ∈ p) : α ↪ ↥p := mk (fun (a : α) => { val := coe_fn f a, property := H a }) sorry @[simp] theorem cod_restrict_apply {α : Sort u_1} {β : Type u_2} (p : set β) (f : α ↪ β) (H : ∀ (a : α), coe_fn f a ∈ p) (a : α) : coe_fn (cod_restrict p f H) a = { val := coe_fn f a, property := H a } := rfl /-- If `e₁` and `e₂` are embeddings, then so is `prod.map e₁ e₂ : (a, b) ↦ (e₁ a, e₂ b)`. -/ def prod_map {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} (e₁ : α ↪ β) (e₂ : γ ↪ δ) : α × γ ↪ β × δ := mk (prod.map ⇑e₁ ⇑e₂) sorry @[simp] theorem coe_prod_map {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} (e₁ : α ↪ β) (e₂ : γ ↪ δ) : ⇑(prod_map e₁ e₂) = prod.map ⇑e₁ ⇑e₂ := rfl /-- If `e₁` and `e₂` are embeddings, then so is `sum.map e₁ e₂`. -/ def sum_map {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} (e₁ : α ↪ β) (e₂ : γ ↪ δ) : α ⊕ γ ↪ β ⊕ δ := mk (sum.map ⇑e₁ ⇑e₂) sorry @[simp] theorem coe_sum_map {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} (e₁ : α ↪ β) (e₂ : γ ↪ δ) : ⇑(sum_map e₁ e₂) = sum.map ⇑e₁ ⇑e₂ := rfl /-- The embedding of `α` into the sum `α ⊕ β`. -/ @[simp] theorem inl_apply {α : Type u_1} {β : Type u_2} (val : α) : coe_fn inl val = sum.inl val := Eq.refl (coe_fn inl val) /-- The embedding of `β` into the sum `α ⊕ β`. -/ @[simp] theorem inr_apply {α : Type u_1} {β : Type u_2} (val : β) : coe_fn inr val = sum.inr val := Eq.refl (coe_fn inr val) /-- `sigma.mk` as an `function.embedding`. -/ @[simp] theorem sigma_mk_apply {α : Type u_1} {β : α → Type u_3} (a : α) (snd : β a) : coe_fn (sigma_mk a) snd = sigma.mk a snd := Eq.refl (coe_fn (sigma_mk a) snd) /-- If `f : α ↪ α'` is an embedding and `g : Π a, β α ↪ β' (f α)` is a family of embeddings, then `sigma.map f g` is an embedding. -/ @[simp] theorem sigma_map_apply {α : Type u_1} {α' : Type u_2} {β : α → Type u_3} {β' : α' → Type u_4} (f : α ↪ α') (g : (a : α) → β a ↪ β' (coe_fn f a)) (x : sigma fun (a : α) => β a) : coe_fn (sigma_map f g) x = sigma.map (⇑f) (fun (a : α) => ⇑(g a)) x := Eq.refl (coe_fn (sigma_map f g) x) def Pi_congr_right {α : Sort u_1} {β : α → Sort u_2} {γ : α → Sort u_3} (e : (a : α) → β a ↪ γ a) : ((a : α) → β a) ↪ (a : α) → γ a := mk (fun (f : (a : α) → β a) (a : α) => coe_fn (e a) (f a)) sorry def arrow_congr_left {α : Sort u} {β : Sort v} {γ : Sort w} (e : α ↪ β) : (γ → α) ↪ γ → β := Pi_congr_right fun (_x : γ) => e def arrow_congr_right {α : Sort u} {β : Sort v} {γ : Sort w} [Inhabited γ] (e : α ↪ β) : (α → γ) ↪ β → γ := let f' : (α → γ) → β → γ := fun (f : α → γ) (b : β) => dite (∃ (c : α), coe_fn e c = b) (fun (h : ∃ (c : α), coe_fn e c = b) => f (classical.some h)) fun (h : ¬∃ (c : α), coe_fn e c = b) => Inhabited.default; mk f' sorry protected def subtype_map {α : Sort u_1} {β : Sort u_2} {p : α → Prop} {q : β → Prop} (f : α ↪ β) (h : ∀ {x : α}, p x → q (coe_fn f x)) : (Subtype fun (x : α) => p x) ↪ Subtype fun (y : β) => q y := mk (subtype.map (⇑f) h) sorry /-- `set.image` as an embedding `set α ↪ set β`. -/ protected def image {α : Type u_1} {β : Type u_2} (f : α ↪ β) : set α ↪ set β := mk (set.image ⇑f) sorry theorem swap_apply {α : Type u_1} {β : Type u_2} [DecidableEq α] [DecidableEq β] (f : α ↪ β) (x : α) (y : α) (z : α) : coe_fn (equiv.swap (coe_fn f x) (coe_fn f y)) (coe_fn f z) = coe_fn f (coe_fn (equiv.swap x y) z) := injective.swap_apply (injective f) x y z theorem swap_comp {α : Type u_1} {β : Type u_2} [DecidableEq α] [DecidableEq β] (f : α ↪ β) (x : α) (y : α) : ⇑(equiv.swap (coe_fn f x) (coe_fn f y)) ∘ ⇑f = ⇑f ∘ ⇑(equiv.swap x y) := injective.swap_comp (injective f) x y end embedding end function namespace equiv @[simp] theorem refl_to_embedding {α : Type u_1} : equiv.to_embedding (equiv.refl α) = function.embedding.refl α := rfl @[simp] theorem trans_to_embedding {α : Type u_1} {β : Type u_2} {γ : Type u_3} (e : α ≃ β) (f : β ≃ γ) : equiv.to_embedding (equiv.trans e f) = function.embedding.trans (equiv.to_embedding e) (equiv.to_embedding f) := rfl end equiv namespace set /-- The injection map is an embedding between subsets. -/ def embedding_of_subset {α : Type u_1} (s : set α) (t : set α) (h : s ⊆ t) : ↥s ↪ ↥t := function.embedding.mk (fun (x : ↥s) => { val := subtype.val x, property := sorry }) sorry end set -- TODO: these two definitions probably belong somewhere else, so that we can remove the -- `algebra.group.defs` import. /-- The embedding of a left cancellative semigroup into itself by left multiplication by a fixed element. -/ @[simp] theorem add_left_embedding_apply {G : Type u} [add_left_cancel_semigroup G] (g : G) (h : G) : coe_fn (add_left_embedding g) h = g + h := Eq.refl (coe_fn (add_left_embedding g) h) /-- The embedding of a right cancellative semigroup into itself by right multiplication by a fixed element. -/ def mul_right_embedding {G : Type u} [right_cancel_semigroup G] (g : G) : G ↪ G := function.embedding.mk (fun (h : G) => h * g) (mul_left_injective g)
0e422b18d59e6718eef77499659036f5851344f2
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/meta/hole_command.lean
5759a33937ca1cfef65788182aa88a6c6a1f83f1
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
940
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.meta.tactic namespace Mathlib /-- The front-end (e.g., Emacs, VS Code) can invoke commands for holes `{! ... !}` in a declaration. A command is a tactic that takes zero or more pre-terms in the hole, and returns a list of pair (s, descr) where 's' is a substitution and 'descr' is a short explanation for the substitution. Each string 's' represents a different way to fill the hole. The front-end is responsible for replacing the hole with the string/alternative selected by the user. This infra-structure can be use to implement auto-fill and/or refine commands. An action may return an empty list. This is useful for actions that just return information such as: the type of an expression, its normal form, etc. -/
54e9cc8b8d55cd9bb694a32d5bc2516474a1d00c
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/library/init/category/applicative.lean
4bf778dd529be796e50732c1314454b37c2b0845
[ "Apache-2.0" ]
permissive
bre7k30/lean
de893411bcfa7b3c5572e61b9e1c52951b310aa4
5a924699d076dab1bd5af23a8f910b433e598d7a
refs/heads/master
1,610,900,145,817
1,488,006,845,000
1,488,006,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
967
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import init.category.functor import init.function open function universes u v class applicative (f : Type u → Type v) extends functor f : Type (max u+1 v):= (pure : Π {a : Type u}, a → f a) (seq : Π {a b : Type u}, f (a → b) → f a → f b) section variables {a b : Type u} {f : Type u → Type v} [applicative f] @[inline] def pure : a → f a := applicative.pure f @[inline] def seq_app : f (a → b) → f a → f b := applicative.seq infixl ` <*> `:2 := seq_app /-- Sequence actions, discarding the first value. -/ def seq_left (x : f a) (y : f b) : f a := pure (λ x y, x) <*> x <*> y /-- Sequence actions, discarding the second value. -/ def seq_right (x : f a) (y : f b) : f b := pure (λ x y, y) <*> x <*> y infixl ` <* `:2 := seq_left infixl ` *> `:2 := seq_right end
c0fc507276b6ebf5472828c1ecf1310f39fdf709
d0f9af2b0ace5ce352570d61b09019c8ef4a3b96
/hw8/lecture notes/propositional_logic_syntax_and_semantics.lean
809a36a793fb0db83276c169cf887a946f7d907b
[]
no_license
jngo13/Discrete-Mathematics
8671540ef2da7c75915d32332dd20c02f001474e
bf674a866e61f60e6e6d128df85fa73819091787
refs/heads/master
1,675,615,657,924
1,609,142,011,000
1,609,142,011,000
267,190,341
0
0
null
null
null
null
UTF-8
Lean
false
false
1,108
lean
-- justin inductive var : Type | mk : ℕ → var -- SYNTAX inductive pExp : Type | pTrue : pExp | pFalse : pExp | pVar : var → pExp | pNot : pExp → pExp | pAnd : pExp → pExp → pExp | pOr : pExp → pExp → pExp | pImp : pExp → pExp → pExp | pIff : pExp → pExp → pExp | pXor : pExp → pExp → pExp -- Utility function def bimp : bool → bool → bool | tt tt := tt | tt ff := ff | ff tt := tt | ff ff := tt open pExp -- ABSTRACT SEMANTICS def pEval : pExp → (var → bool) → bool | pTrue _ := tt | pFalse _ := ff | (pVar v) i := i v | (pNot e) i := bnot (pEval e i) | (pAnd e1 e2) i := band (pEval e1 i) (pEval e2 i) | (pOr e1 e2) i := bor (pEval e1 i) (pEval e2 i) | (pImp e1 e2) i := bimp (pEval e1 i) (pEval e2 i) | (pIff e1 e2) i := tt -- HOMEWORK | (pXor e1 e2) i := xor (pEval e1 i) (pEval e2 i) -- CONCRETE SYNTAX ("syntactic sugar") notation e1 ∧ e2 := pAnd e1 e2 --desugaring notation e1 ∨ e2 := pOr e1 e2 notation ¬ e := pNot e notation e1 > e2 := pImp e1 e2 -- infixr ` >> ` : 30 := pImp notation e1 ↔ e2 := pIff e1 e2 notation e1 ⊕ e2 := pXor e1 e2
81e733b0dc86669a3a9895535e65c58bc99b7fad
8e2026ac8a0660b5a490dfb895599fb445bb77a0
/library/init/meta/format.lean
9b302ea30c16a6a54c8ffaf5bc43a9d78d8034eb
[ "Apache-2.0" ]
permissive
pcmoritz/lean
6a8575115a724af933678d829b4f791a0cb55beb
35eba0107e4cc8a52778259bb5392300267bfc29
refs/heads/master
1,607,896,326,092
1,490,752,175,000
1,490,752,175,000
86,612,290
0
0
null
1,490,809,641,000
1,490,809,641,000
null
UTF-8
Lean
false
false
4,590
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.meta.options init.function universes u v inductive format.color | red | green | orange | blue | pink | cyan | grey meta constant format : Type meta constant format.line : format meta constant format.space : format meta constant format.nil : format meta constant format.compose : format → format → format meta constant format.nest : nat → format → format meta constant format.highlight : format → color → format meta constant format.group : format → format meta constant format.of_string : string → format meta constant format.of_nat : nat → format meta constant format.flatten : format → format meta constant format.to_string : format → options → string meta constant format.of_options : options → format meta constant format.is_nil : format → bool meta constant trace_fmt {α : Type u} : format → (unit → α) → α meta instance : inhabited format := ⟨format.space⟩ meta instance : has_append format := ⟨format.compose⟩ meta instance : has_to_string format := ⟨λ f, format.to_string f options.mk⟩ meta class has_to_format (α : Type u) := (to_format : α → format) meta instance : has_to_format format := ⟨id⟩ meta def to_fmt {α : Type u} [has_to_format α] : α → format := has_to_format.to_format meta instance nat_to_format : has_coe nat format := ⟨format.of_nat⟩ meta instance string_to_format : has_coe string format := ⟨format.of_string⟩ open format list meta def format.indent (f : format) (n : nat) : format := nest n (line ++ f) meta def format.when {α : Type u} [has_to_format α] : bool → α → format | tt a := to_fmt a | ff a := nil meta def format.join (xs : list format) : format := foldl compose (of_string "") xs meta instance : has_to_format options := ⟨λ o, format.of_options o⟩ meta instance : has_to_format bool := ⟨λ b, if b then of_string "tt" else of_string "ff"⟩ meta instance {p : Prop} : has_to_format (decidable p) := ⟨λ b : decidable p, @ite p b _ (of_string "tt") (of_string "ff")⟩ meta instance : has_to_format string := ⟨λ s, format.of_string s⟩ meta instance : has_to_format nat := ⟨λ n, format.of_nat n⟩ meta instance : has_to_format char := ⟨λ c : char, format.of_string [c]⟩ meta def list.to_format {α : Type u} [has_to_format α] : list α → format | [] := to_fmt "[]" | xs := to_fmt "[" ++ group (nest 1 $ format.join $ list.intersperse ("," ++ line) $ xs.map to_fmt) ++ to_fmt "]" meta instance {α : Type u} [has_to_format α] : has_to_format (list α) := ⟨list.to_format⟩ attribute [instance] string.has_to_format meta instance : has_to_format name := ⟨λ n, to_fmt (to_string n)⟩ meta instance : has_to_format unit := ⟨λ u, to_fmt "()"⟩ meta instance {α : Type u} [has_to_format α] : has_to_format (option α) := ⟨λ o, option.cases_on o (to_fmt "none") (λ a, to_fmt "(some " ++ nest 6 (to_fmt a) ++ to_fmt ")")⟩ meta instance sum_has_to_format {α : Type u} {β : Type v} [has_to_format α] [has_to_format β] : has_to_format (sum α β) := ⟨λ s, sum.cases_on s (λ a, to_fmt "(inl " ++ nest 5 (to_fmt a) ++ to_fmt ")") (λ b, to_fmt "(inr " ++ nest 5 (to_fmt b) ++ to_fmt ")")⟩ open prod meta instance {α : Type u} {β : Type v} [has_to_format α] [has_to_format β] : has_to_format (prod α β) := ⟨λ ⟨a, b⟩, group (nest 1 (to_fmt "(" ++ to_fmt a ++ to_fmt "," ++ line ++ to_fmt b ++ to_fmt ")"))⟩ open sigma meta instance {α : Type u} {β : α → Type v} [has_to_format α] [s : ∀ x, has_to_format (β x)] : has_to_format (sigma β) := ⟨λ ⟨a, b⟩, group (nest 1 (to_fmt "⟨" ++ to_fmt a ++ to_fmt "," ++ line ++ to_fmt b ++ to_fmt "⟩"))⟩ open subtype meta instance {α : Type u} {p : α → Prop} [has_to_format α] : has_to_format (subtype p) := ⟨λ s, to_fmt (val s)⟩ meta def format.bracket : string → string → format → format | o c f := to_fmt o ++ nest (utf8_length o) f ++ to_fmt c meta def format.paren (f : format) : format := format.bracket "(" ")" f meta def format.cbrace (f : format) : format := format.bracket "{" "}" f meta def format.sbracket (f : format) : format := format.bracket "[" "]" f meta def format.dcbrace (f : format) : format := to_fmt "⦃" ++ nest 1 f ++ to_fmt "⦄"
d4cf44cf0c7a731a5c884e0f15386d0f0580a79e
5412d79aa1dc0b521605c38bef9f0d4557b5a29d
/src/Lean/Elab/DeclModifiers.lean
c4cd1761c35914681c0dcba1fde1b6f2003a0532
[ "Apache-2.0" ]
permissive
smunix/lean4
a450ec0927dc1c74816a1bf2818bf8600c9fc9bf
3407202436c141e3243eafbecb4b8720599b970a
refs/heads/master
1,676,334,875,188
1,610,128,510,000
1,610,128,521,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,571
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ import Lean.Modifiers import Lean.Elab.Attributes import Lean.Elab.Exception import Lean.Elab.DeclUtil namespace Lean.Elab def checkNotAlreadyDeclared {m} [Monad m] [MonadEnv m] [MonadError m] (declName : Name) : m Unit := do let env ← getEnv if env.contains declName then match privateToUserName? declName with | none => throwError! "'{declName}' has already been declared" | some declName => throwError! "private declaration '{declName}' has already been declared" if env.contains (mkPrivateName env declName) then throwError! "a private declaration '{declName}' has already been declared" match privateToUserName? declName with | none => pure () | some declName => if env.contains declName then throwError! "a non-private declaration '{declName}' has already been declared" inductive Visibility where | regular | «protected» | «private» deriving Inhabited instance : ToString Visibility := ⟨fun | Visibility.regular => "regular" | Visibility.«private» => "private" | Visibility.«protected» => "protected"⟩ structure Modifiers where docString : Option String := none visibility : Visibility := Visibility.regular isNoncomputable : Bool := false isPartial : Bool := false isUnsafe : Bool := false attrs : Array Attribute := #[] deriving Inhabited def Modifiers.isPrivate : Modifiers → Bool | { visibility := Visibility.private, .. } => true | _ => false def Modifiers.isProtected : Modifiers → Bool | { visibility := Visibility.protected, .. } => true | _ => false def Modifiers.addAttribute (modifiers : Modifiers) (attr : Attribute) : Modifiers := { modifiers with attrs := modifiers.attrs.push attr } instance : ToFormat Modifiers := ⟨fun m => let components : List Format := (match m.docString with | some str => [f!"/--{str}-/"] | none => []) ++ (match m.visibility with | Visibility.regular => [] | Visibility.protected => [f!"protected"] | Visibility.private => [f!"private"]) ++ (if m.isNoncomputable then [f!"noncomputable"] else []) ++ (if m.isPartial then [f!"partial"] else []) ++ (if m.isUnsafe then [f!"unsafe"] else []) ++ m.attrs.toList.map (fun attr => fmt attr) Format.bracket "{" (Format.joinSep components ("," ++ Format.line)) "}"⟩ instance : ToString Modifiers := ⟨toString ∘ format⟩ section Methods variables [Monad m] [MonadEnv m] [MonadResolveName m] [MonadError m] [MonadMacroAdapter m] [MonadRecDepth m] def elabModifiers (stx : Syntax) : m Modifiers := do let docCommentStx := stx[0] let attrsStx := stx[1] let visibilityStx := stx[2] let noncompStx := stx[3] let unsafeStx := stx[4] let partialStx := stx[5] let docString ← match docCommentStx.getOptional? with | none => pure none | some s => match s[1] with | Syntax.atom _ val => pure (some (val.extract 0 (val.bsize - 2))) | _ => throwErrorAt! s "unexpected doc string {s[1]}" let visibility ← match visibilityStx.getOptional? with | none => pure Visibility.regular | some v => let kind := v.getKind if kind == `Lean.Parser.Command.private then pure Visibility.private else if kind == `Lean.Parser.Command.protected then pure Visibility.protected else throwErrorAt v "unexpected visibility modifier" let attrs ← match attrsStx.getOptional? with | none => pure #[] | some attrs => elabDeclAttrs attrs pure { docString := docString, visibility := visibility, isPartial := !partialStx.isNone, isUnsafe := !unsafeStx.isNone, isNoncomputable := !noncompStx.isNone, attrs := attrs } def applyVisibility (visibility : Visibility) (declName : Name) : m Name := do match visibility with | Visibility.private => let env ← getEnv let declName := mkPrivateName env declName checkNotAlreadyDeclared declName pure declName | Visibility.protected => checkNotAlreadyDeclared declName let env ← getEnv let env := addProtected env declName setEnv env pure declName | _ => checkNotAlreadyDeclared declName pure declName def mkDeclName (currNamespace : Name) (modifiers : Modifiers) (shortName : Name) : m (Name × Name) := do let name := (extractMacroScopes shortName).name unless name.isAtomic || isFreshInstanceName name do throwError! "atomic identifier expected '{shortName}'" let declName := currNamespace ++ shortName let declName ← applyVisibility modifiers.visibility declName match modifiers.visibility with | Visibility.protected => match currNamespace with | Name.str _ s _ => pure (declName, Name.mkSimple s ++ shortName) | _ => throwError "protected declarations must be in a namespace" | _ => pure (declName, shortName) /- `declId` is of the form ``` parser! ident >> optional (".{" >> sepBy1 ident ", " >> "}") ``` but we also accept a single identifier to users to make macro writing more convenient . -/ def expandDeclIdCore (declId : Syntax) : Name × Syntax := if declId.isIdent then (declId.getId, mkNullNode) else let id := declId[0].getId let optUnivDeclStx := declId[1] (id, optUnivDeclStx) structure ExpandDeclIdResult where shortName : Name declName : Name levelNames : List Name def expandDeclId (currNamespace : Name) (currLevelNames : List Name) (declId : Syntax) (modifiers : Modifiers) : m ExpandDeclIdResult := do -- ident >> optional (".{" >> sepBy1 ident ", " >> "}") let (shortName, optUnivDeclStx) := expandDeclIdCore declId let levelNames ← if optUnivDeclStx.isNone then pure currLevelNames else let extraLevels := optUnivDeclStx[1].getArgs.getEvenElems extraLevels.foldlM (fun levelNames idStx => let id := idStx.getId if levelNames.elem id then withRef idStx $ throwAlreadyDeclaredUniverseLevel id else pure (id :: levelNames)) currLevelNames let (declName, shortName) ← withRef declId $ mkDeclName currNamespace modifiers shortName pure { shortName := shortName, declName := declName, levelNames := levelNames } end Methods end Lean.Elab
3efded7041e00fd48124f97e5d72b162cd37ad7c
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/set_theory/surreal.lean
03ec0b90641e9351010b8a6b066d225e54939a3b
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
12,920
lean
/- Copyright (c) 2019 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Scott Morrison -/ import set_theory.game /-! # Surreal numbers The basic theory of surreal numbers, built on top of the theory of combinatorial (pre-)games. A pregame is `numeric` if all the Left options are strictly smaller than all the Right options, and all those options are themselves numeric. In terms of combinatorial games, the numeric games have "frozen"; you can only make your position worse by playing, and Left is some definite "number" of moves ahead (or behind) Right. A surreal number is an equivalence class of numeric pregames. In fact, the surreals form a complete ordered field, containing a copy of the reals (and much else besides!) but we do not yet have a complete development. ## Order properties Surreal numbers inherit the relations `≤` and `<` from games, and these relations satisfy the axioms of a partial order (recall that `x < y ↔ x ≤ y ∧ ¬ y ≤ x` did not hold for games). ## Algebraic operations At this point, we have defined addition and negation (from pregames), and shown that surreals form an additive semigroup. It would be very little work to finish showing that the surreals form an ordered commutative group. ## Embeddings It would be nice projects to define the group homomorphism `surreal → game`, and also `ℤ → surreal`, and then the homomorphic inclusion of the dyadic rationals into surreals, and finally via dyadic Dedekind cuts the homomorphic inclusion of the reals into the surreals. One can also map all the ordinals into the surreals! ## References * [Conway, *On numbers and games*][conway2001] -/ universes u local infix ` ≈ ` := pgame.equiv namespace pgame /-- A pre-game is numeric if everything in the L set is less than everything in the R set, and all the elements of L and R are also numeric. -/ def numeric : pgame → Prop | ⟨l, r, L, R⟩ := (∀ i j, L i < R j) ∧ (∀ i, numeric (L i)) ∧ (∀ i, numeric (R i)) lemma numeric.move_left {x : pgame} (o : numeric x) (i : x.left_moves) : numeric (x.move_left i) := begin cases x with xl xr xL xR, exact o.2.1 i, end lemma numeric.move_right {x : pgame} (o : numeric x) (j : x.right_moves) : numeric (x.move_right j) := begin cases x with xl xr xL xR, exact o.2.2 j, end @[elab_as_eliminator] theorem numeric_rec {C : pgame → Prop} (H : ∀ l r (L : l → pgame) (R : r → pgame), (∀ i j, L i < R j) → (∀ i, numeric (L i)) → (∀ i, numeric (R i)) → (∀ i, C (L i)) → (∀ i, C (R i)) → C ⟨l, r, L, R⟩) : ∀ x, numeric x → C x | ⟨l, r, L, R⟩ ⟨h, hl, hr⟩ := H _ _ _ _ h hl hr (λ i, numeric_rec _ (hl i)) (λ i, numeric_rec _ (hr i)) theorem lt_asymm {x y : pgame} (ox : numeric x) (oy : numeric y) : x < y → ¬ y < x := begin refine numeric_rec (λ xl xr xL xR hx oxl oxr IHxl IHxr, _) x ox y oy, refine numeric_rec (λ yl yr yL yR hy oyl oyr IHyl IHyr, _), rw [mk_lt_mk, mk_lt_mk], rintro (⟨i, h₁⟩ | ⟨j, h₁⟩) (⟨i, h₂⟩ | ⟨j, h₂⟩), { exact IHxl _ _ (oyl _) (lt_of_le_mk h₁) (lt_of_le_mk h₂) }, { exact not_lt.2 (le_trans h₂ h₁) (hy _ _) }, { exact not_lt.2 (le_trans h₁ h₂) (hx _ _) }, { exact IHxr _ _ (oyr _) (lt_of_mk_le h₁) (lt_of_mk_le h₂) }, end theorem le_of_lt {x y : pgame} (ox : numeric x) (oy : numeric y) (h : x < y) : x ≤ y := not_lt.1 (lt_asymm ox oy h) /-- On numeric pre-games, `<` and `≤` satisfy the axioms of a partial order (even though they don't on all pre-games). -/ theorem lt_iff_le_not_le {x y : pgame} (ox : numeric x) (oy : numeric y) : x < y ↔ x ≤ y ∧ ¬ y ≤ x := ⟨λ h, ⟨le_of_lt ox oy h, not_le.2 h⟩, λ h, not_le.1 h.2⟩ theorem numeric_zero : numeric 0 := ⟨by rintros ⟨⟩ ⟨⟩, ⟨by rintros ⟨⟩, by rintros ⟨⟩⟩⟩ theorem numeric_one : numeric 1 := ⟨by rintros ⟨⟩ ⟨⟩, ⟨λ x, numeric_zero, by rintros ⟨⟩⟩⟩ theorem numeric_neg : Π {x : pgame} (o : numeric x), numeric (-x) | ⟨l, r, L, R⟩ o := ⟨λ j i, lt_iff_neg_gt.1 (o.1 i j), ⟨λ j, numeric_neg (o.2.2 j), λ i, numeric_neg (o.2.1 i)⟩⟩ theorem numeric.move_left_lt {x : pgame.{u}} (o : numeric x) (i : x.left_moves) : x.move_left i < x := begin rw lt_def_le, left, use i, end theorem numeric.move_left_le {x : pgame} (o : numeric x) (i : x.left_moves) : x.move_left i ≤ x := le_of_lt (o.move_left i) o (o.move_left_lt i) theorem numeric.lt_move_right {x : pgame} (o : numeric x) (j : x.right_moves) : x < x.move_right j := begin rw lt_def_le, right, use j, end theorem numeric.le_move_right {x : pgame} (o : numeric x) (j : x.right_moves) : x ≤ x.move_right j := le_of_lt o (o.move_right j) (o.lt_move_right j) theorem add_lt_add {w x y z : pgame.{u}} (ow : numeric w) (ox : numeric x) (oy : numeric y) (oz : numeric z) (hwx : w < x) (hyz : y < z) : w + y < x + z := begin rw lt_def_le at *, rcases hwx with ⟨ix, hix⟩|⟨jw, hjw⟩; rcases hyz with ⟨iz, hiz⟩|⟨jy, hjy⟩, { left, use (left_moves_add x z).symm (sum.inl ix), simp only [add_move_left_inl], calc w + y ≤ move_left x ix + y : add_le_add_right hix ... ≤ move_left x ix + move_left z iz : add_le_add_left hiz ... ≤ move_left x ix + z : add_le_add_left (oz.move_left_le iz) }, { left, use (left_moves_add x z).symm (sum.inl ix), simp only [add_move_left_inl], calc w + y ≤ move_left x ix + y : add_le_add_right hix ... ≤ move_left x ix + move_right y jy : add_le_add_left (oy.le_move_right jy) ... ≤ move_left x ix + z : add_le_add_left hjy }, { right, use (right_moves_add w y).symm (sum.inl jw), simp only [add_move_right_inl], calc move_right w jw + y ≤ x + y : add_le_add_right hjw ... ≤ x + move_left z iz : add_le_add_left hiz ... ≤ x + z : add_le_add_left (oz.move_left_le iz), }, { right, use (right_moves_add w y).symm (sum.inl jw), simp only [add_move_right_inl], calc move_right w jw + y ≤ x + y : add_le_add_right hjw ... ≤ x + move_right y jy : add_le_add_left (oy.le_move_right jy) ... ≤ x + z : add_le_add_left hjy, }, end theorem numeric_add : Π {x y : pgame} (ox : numeric x) (oy : numeric y), numeric (x + y) | ⟨xl, xr, xL, xR⟩ ⟨yl, yr, yL, yR⟩ ox oy := ⟨begin rintros (ix|iy) (jx|jy), { show xL ix + ⟨yl, yr, yL, yR⟩ < xR jx + ⟨yl, yr, yL, yR⟩, exact add_lt_add_right (ox.1 ix jx), }, { show xL ix + ⟨yl, yr, yL, yR⟩ < ⟨xl, xr, xL, xR⟩ + yR jy, apply add_lt_add (ox.move_left ix) ox oy (oy.move_right jy), apply ox.move_left_lt, apply oy.lt_move_right }, { -- show ⟨xl, xr, xL, xR⟩ + yL iy < xR jx + ⟨yl, yr, yL, yR⟩, -- fails? apply add_lt_add ox (ox.move_right jx) (oy.move_left iy) oy, apply ox.lt_move_right, apply oy.move_left_lt, }, { -- show ⟨xl, xr, xL, xR⟩ + yL iy < ⟨xl, xr, xL, xR⟩ + yR jy, -- fails? exact @add_lt_add_left ⟨xl, xr, xL, xR⟩ _ _ (oy.1 iy jy), } end, begin split, { rintros (ix|iy), { apply numeric_add (ox.move_left ix) oy, }, { apply numeric_add ox (oy.move_left iy), }, }, { rintros (jx|jy), { apply numeric_add (ox.move_right jx) oy, }, { apply numeric_add ox (oy.move_right jy), }, }, end⟩ using_well_founded { dec_tac := pgame_wf_tac } /-- Pre-games defined by natural numbers are numeric. -/ theorem numeric_nat : Π (n : ℕ), numeric n | 0 := numeric_zero | (n + 1) := numeric_add (numeric_nat n) numeric_one /-- The pre-game omega is numeric. -/ theorem numeric_omega : numeric omega := ⟨by rintros ⟨⟩ ⟨⟩, λ i, numeric_nat i.down, by rintros ⟨⟩⟩ end pgame /-- The equivalence on numeric pre-games. -/ def surreal.equiv (x y : {x // pgame.numeric x}) : Prop := x.1.equiv y.1 instance surreal.setoid : setoid {x // pgame.numeric x} := ⟨λ x y, x.1.equiv y.1, λ x, pgame.equiv_refl _, λ x y, pgame.equiv_symm, λ x y z, pgame.equiv_trans⟩ /-- The type of surreal numbers. These are the numeric pre-games quotiented by the equivalence relation `x ≈ y ↔ x ≤ y ∧ y ≤ x`. In the quotient, the order becomes a total order. -/ def surreal := quotient surreal.setoid namespace surreal open pgame /-- Construct a surreal number from a numeric pre-game. -/ def mk (x : pgame) (h : x.numeric) : surreal := quotient.mk ⟨x, h⟩ instance : has_zero surreal := { zero := ⟦⟨0, numeric_zero⟩⟧ } instance : has_one surreal := { one := ⟦⟨1, numeric_one⟩⟧ } instance : inhabited surreal := ⟨0⟩ /-- Lift an equivalence-respecting function on pre-games to surreals. -/ def lift {α} (f : ∀ x, numeric x → α) (H : ∀ {x y} (hx : numeric x) (hy : numeric y), x.equiv y → f x hx = f y hy) : surreal → α := quotient.lift (λ x : {x // numeric x}, f x.1 x.2) (λ x y, H x.2 y.2) /-- Lift a binary equivalence-respecting function on pre-games to surreals. -/ def lift₂ {α} (f : ∀ x y, numeric x → numeric y → α) (H : ∀ {x₁ y₁ x₂ y₂} (ox₁ : numeric x₁) (oy₁ : numeric y₁) (ox₂ : numeric x₂) (oy₂ : numeric y₂), x₁.equiv x₂ → y₁.equiv y₂ → f x₁ y₁ ox₁ oy₁ = f x₂ y₂ ox₂ oy₂) : surreal → surreal → α := lift (λ x ox, lift (λ y oy, f x y ox oy) (λ y₁ y₂ oy₁ oy₂ h, H _ _ _ _ (equiv_refl _) h)) (λ x₁ x₂ ox₁ ox₂ h, funext $ quotient.ind $ by exact λ ⟨y, oy⟩, H _ _ _ _ h (equiv_refl _)) /-- The relation `x ≤ y` on surreals. -/ def le : surreal → surreal → Prop := lift₂ (λ x y _ _, x ≤ y) (λ x₁ y₁ x₂ y₂ _ _ _ _ hx hy, propext (le_congr hx hy)) /-- The relation `x < y` on surreals. -/ def lt : surreal → surreal → Prop := lift₂ (λ x y _ _, x < y) (λ x₁ y₁ x₂ y₂ _ _ _ _ hx hy, propext (lt_congr hx hy)) theorem not_le : ∀ {x y : surreal}, ¬ le x y ↔ lt y x := by rintro ⟨⟨x, ox⟩⟩ ⟨⟨y, oy⟩⟩; exact not_le /-- Addition on surreals is inherited from pre-game addition: the sum of `x = {xL | xR}` and `y = {yL | yR}` is `{xL + y, x + yL | xR + y, x + yR}`. -/ def add : surreal → surreal → surreal := surreal.lift₂ (λ (x y : pgame) (ox) (oy), ⟦⟨x + y, numeric_add ox oy⟩⟧) (λ x₁ y₁ x₂ y₂ _ _ _ _ hx hy, quotient.sound (pgame.add_congr hx hy)) /-- Negation for surreal numbers is inherited from pre-game negation: the negation of `{L | R}` is `{-R | -L}`. -/ def neg : surreal → surreal := surreal.lift (λ x ox, ⟦⟨-x, pgame.numeric_neg ox⟩⟧) (λ _ _ _ _ a, quotient.sound (pgame.neg_congr a)) instance : has_le surreal := ⟨le⟩ instance : has_lt surreal := ⟨lt⟩ instance : has_add surreal := ⟨add⟩ instance : has_neg surreal := ⟨neg⟩ instance : ordered_add_comm_group surreal := { add := (+), add_assoc := by { rintros ⟨_⟩ ⟨_⟩ ⟨_⟩, exact quotient.sound add_assoc_equiv }, zero := 0, zero_add := by { rintros ⟨_⟩, exact quotient.sound (pgame.zero_add_equiv _) }, add_zero := by { rintros ⟨_⟩, exact quotient.sound (pgame.add_zero_equiv _) }, neg := has_neg.neg, add_left_neg := by { rintros ⟨_⟩, exact quotient.sound pgame.add_left_neg_equiv }, add_comm := by { rintros ⟨_⟩ ⟨_⟩, exact quotient.sound pgame.add_comm_equiv }, le := (≤), lt := (<), le_refl := by { rintros ⟨_⟩, refl }, le_trans := by { rintros ⟨_⟩ ⟨_⟩ ⟨_⟩, exact pgame.le_trans }, lt_iff_le_not_le := by { rintros ⟨_, ox⟩ ⟨_, oy⟩, exact pgame.lt_iff_le_not_le ox oy }, le_antisymm := by { rintros ⟨_⟩ ⟨_⟩ h₁ h₂, exact quotient.sound ⟨h₁, h₂⟩ }, add_le_add_left := by { rintros ⟨_⟩ ⟨_⟩ hx ⟨_⟩, exact pgame.add_le_add_left hx } } noncomputable instance : linear_ordered_add_comm_group surreal := { le_total := by rintro ⟨⟨x, ox⟩⟩ ⟨⟨y, oy⟩⟩; classical; exact or_iff_not_imp_left.2 (λ h, le_of_lt oy ox (pgame.not_le.1 h)), decidable_le := classical.dec_rel _, ..surreal.ordered_add_comm_group } -- We conclude with some ideas for further work on surreals; these would make fun projects. -- TODO define the inclusion of groups `surreal → game` -- TODO define the dyadic rationals, and show they map into the surreals via the formula -- m / 2^n ↦ { (m-1) / 2^n | (m+1) / 2^n } -- TODO show this is a group homomorphism, and injective -- TODO map the reals into the surreals, using dyadic Dedekind cuts -- TODO show this is a group homomorphism, and injective -- TODO define the field structure on the surreals -- TODO show the maps from the dyadic rationals and from the reals -- into the surreals are multiplicative end surreal
96c575b27283e1678cbb757c1ab3f8f7fb2e4cbc
ebf7140a9ea507409ff4c994124fa36e79b4ae35
/src/exercises_sources/thursday/order.lean
f7c61aa6ad90b22bcdc8f27b3eef1a890e2454c0
[]
no_license
fundou/lftcm2020
3e88d58a92755ea5dd49f19c36239c35286ecf5e
99d11bf3bcd71ffeaef0250caa08ecc46e69b55b
refs/heads/master
1,685,610,799,304
1,624,070,416,000
1,624,070,416,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
17,312
lean
/- # Orders Groups, rings, fields, modules etc are in the "algebra hierarchy". Metric and topological spaces are in the "topology hierarchy". The other important hierarchy is the "order hierarchy". It starts with partially ordered sets, and then goes on to lattices. Because I like algebra, let's demonstrate the order hierarchy by making an algebraic type, namely the type of subgroups of a group G, and then working up the order hierarchy with it. Subgroups of a group are ordered by inclusion, and this is where we shall start. We will then define infs and sups, and bot and top, and go on from there. -/ import tactic -- We will be using all of the theory of subsets of a type -- without further comment (e.g. `inter_subset_left A B : A ∩ B ⊆ A`) -- so let's open the `set` namespace. open set -- The type of subgroups of a group G is called `subgroup G` in Lean. -- It already has a lattice structure in Lean. -- So let's just redo the entire theory and call it `subgp G`. /-- The type of subgroups of a group `G`. -/ structure subgp (G : Type) [group G] := -- A subgroup of G is a sub*set* of G, called `carrier` (carrier : set G) -- and then axioms saying it's closed under the group structure (i.e. *, 1, ⁻¹) (mul_mem {a b : G} : a ∈ carrier → b ∈ carrier → a * b ∈ carrier) (one_mem : (1 : G) ∈ carrier) (inv_mem {a : G} : a ∈ carrier → a⁻¹ ∈ carrier) namespace subgp /- Note in particular that we have a function `subgp.carrier : subgp G → set G`, sending a subgroup of `G` to the underlying subset (`set G` is the type of subsets of G). -/ -- Let G be a group, let H,J,K be subgroups of G, and let a,b,c be elements of G. variables {G : Type} [group G] (H J K : subgp G) (a b c : G) /- # Extensionality One of the first things you should consider proving about a newly-defined type is an extensionality lemma: a sensible criterion to check that two terms are equal. When are two subgroups of `G` equal? A subgroup is defined by four things: a subset, and three proofs. But two proofs of a proposition `P` are equal by definition in Lean, so two subgroups of `G` are equal iff their underlying subsets are equal, which is true iff their underlying subsets have the same elements. Let's give names to these basic results because they'll show up everywhere. Let's start by showing that two subgroups are equal if their underlying subsets are equal. This is precisely the statement that `∀ H J : subgp G, H.carrier = J.carrier → H = J`, and a good name for this would be `carrier_injective`. We adopt the Lean tradition of putting as many things to the left of the `:` as we can; it doesn't change the statement of the theorem. -/ lemma carrier_injective (H J : subgp G) (h : H.carrier = J.carrier) : H = J := begin -- take H and J apart cases H, cases J, -- and note that they are the same set, and then a bunch of proofs -- which are equal by definition, so it's obvious simp * at *, end -- Now let's prove that two subgroups are equal iff they have the same elements. -- This is the most useful "extensionality lemma" so we tag it `@[ext]`. @[ext] theorem ext {H J : subgp G} (h : ∀ (x : G), x ∈ H.carrier ↔ x ∈ J.carrier) : H = J := begin -- it suffices to prove the subsets are equal apply carrier_injective, -- Now let's use extensionality for subsets ext x, exact h x, end -- We also want the `iff` version of this. theorem ext_iff {H J : subgp G} : H = J ↔ ∀ (x : G), x ∈ H.carrier ↔ x ∈ J.carrier := begin sorry end /- ## Partial orders -/ -- These are familiar to most mathematicians. We will put a partial order -- structure on `subgp G`. In other words, we will create a term of -- type `partial_order (subgp G)`. -- Let's define `H ≤ J` to mean `H.carrier ⊆ J.carrier`, using the `has_le` notation typeclass instance : has_le (subgp G) := ⟨λ H J, H.carrier ⊆ J.carrier⟩ -- "tidy" is a one-size-fits-all tactic which solves certain kinds of "follow your nose" goals. instance : partial_order (subgp G) := { le := (≤), le_refl := by tidy, le_trans := by tidy, le_antisymm := by tidy } /- Here is a second proof. If X → Y is injective, and Y is partially ordered, then X inherits a partial order. This construction (it's not a theorem, because it involves data) is called `partial_order.lift`. Applying it to the injection `subgp.carrier` and the fact that Lean already knows that `set G` is partially ordered, turns into this second construction, (which I won't call an `instance` because if I did then I would have committed the sin of making two terms of type `partial_order (subgp G)`, and `partial_order (subgp G)` is a class so should have at most one instance): -/ -- partial_order.lift is the function which pulls a partial order back along an injection. example : partial_order (subgp G) := partial_order.lift subgp.carrier carrier_injective /- Note that we magically just inherited `<` notatation, because `#check partial_order` tells you that `partial_order` extends `preorder`, which extends `has_lt`, which is a notation typeclass. In other words, `#check (H < J)` makes sense, and is a `Prop`. In fact `H < J` is defined to mean `H ≤ J ∧ ¬ (J ≤ H)`. # From partial orders to lattices. Let's now prove that `subgp G` is a `semilattice_inf_top`. This is a class which extends `partial_order` -- it is a partial order equipped with a top element, and a function `inf : subgp G → subgp G → subgp G` (called "inf" or "meet" or "greatest lower bound", satisfying some axioms. In our case, `top` will be the subgroup `G` of `G` (or more precisely `univ`), and `inf` will just be intersection. The work we need to do is to check that these are subgroups, and to prove the axioms for a `semilattice_inf_top`, which we'll come to later. First let's define `top` -- the biggest subgroup. The underlying carrier is `univ : set G`, i.e. the subset `G` of `G`. I'll leave it to you to prove that the subgroup axioms hold! The useful piece of interface for `univ` you'll need is `mem_univ g : g ∈ univ`. -/ def top : subgp G := { carrier := set.univ, mul_mem := begin sorry end, one_mem := begin sorry end, inv_mem := begin sorry end } -- Add the `⊤` notation (typed with `\top`) for this subgroup: instance : has_top (subgp G) := ⟨top⟩ -- Now `#check (⊤ : subgp G)` works /- We'll now prove the theorem that the intersection of two subgroups is a subgroup. This is a *definition* in Lean, indeed it is a construction which given two subgroups `H` and `K` of `G` produces a third subgroup `H ⊓ K` (Lean's notation for `inf H K`). The part of the interface for `∩` you'll need is that `a ∈ B ∩ C` is definitionally equal to `a ∈ B ∧ a ∈ C`, so you can use `split` if you have a goal `⊢ a ∈ B ∩ C`, and you can use `cases h` if you have a hypothesis `h : a ∈ B ∩ C`. Don't forget `mul_mem H`, `one_mem H` and `inv_mem H`, the axioms for `H` if `H : subgp G`. -/ /-- "Theorem" : intersection of two subgps is a subgp -/ definition inf (H K : subgp G) : subgp G := { carrier := H.carrier ∩ K.carrier, mul_mem := begin sorry end, one_mem := begin sorry end, inv_mem := begin sorry end } -- Add the `⊓` notation (type with `\inf`) for the intersection (inf) of two subgroups: instance : has_inf (subgp G) := ⟨inf⟩ -- We now check the four axioms for a semilattice_inf_top. -- They are called `le_top`, `inf_le_left`, `inf_le_right` and `le_inf`. -- You might be able to guess the statementss of the axioms -- from their names. lemma le_top (H : subgp G) : H ≤ ⊤ := begin sorry end lemma inf_le_left (H K : subgp G) : H ⊓ K ≤ H := begin -- by definition this says `H.carrier ∩ K.carrier ⊆ H.carrier` change H.carrier ∩ K.carrier ⊆ H.carrier, -- now try `library_search`, to find that this is called `inter_subset_left apply inter_subset_left, end lemma inf_le_right (H K : subgp G) : H ⊓ K ≤ K := sorry -- Can you use `library_search`, or other methods, to find the name of the -- statement that if `A B C : set G` then `A ⊆ B → A ⊆ C → A ⊆ (B ∩ C)`? lemma le_inf (H J K : subgp G) (h1 : H ≤ J) (h2 : H ≤ K) : H ≤ J ⊓ K := sorry -- Now we're ready to make the instance. instance : semilattice_inf_top (subgp G) := { top := top, le_top := le_top, inf := inf, inf_le_left := inf_le_left, inf_le_right := inf_le_right, le_inf := le_inf, .. subgp.partial_order } -- don't forget to inlude the partial order /- The logic behind `semilattice_inf_top` is that it is the simplest class which is closed under all finite "meet"s. The meet of 0 subgroups is `top`, the meet of one subgroup is the subgroup, the meet of two subgroups is their inf, and for three or more you proceed by induction. We could now go on to make a `semilattice_sup_bot` structure, and then a lattice structure. But let's jump straight to the strongest type in the order hierarchy -- a `complete_lattice`. This has arbitrary `Inf` and `Sup`s. So let's first note that we can do better than finite intersections -- we can take arbitrary intersections! Let's now define the `Inf` of an arbitrary set of subgroups of `G`. The part of the interface for sets you'll need to know here is that if `S` is a set of subsets of `G`, then `⋂₀ S` is notation for their intersection, and to work with it you'll need to know `set.mem_sInter : g ∈ ⋂₀ S ↔ ∀ (U : set G), U ∈ S → g ∈ U`. -/ def Inf (S : set (subgp G)) : subgp G := { carrier := Inf (subgp.carrier '' S), mul_mem := begin sorry end, one_mem := begin sorry end, inv_mem := begin sorry end } -- We now equip `subgp G` with an Inf. I think the notation is `⨅`, or `\Inf`, -- but I find it hard to use, and `#print notation ⨅` returns garbage. instance : has_Inf (subgp G) := ⟨Inf⟩ /- # Complete lattices Let's jump straight from `semilattice_inf_bot` to `complete_lattice`. A complete lattice has arbitrary Infs and arbitrary Sups, and satisfies some other axioms which you can probably imagine. Our next goal is to make `subgp G` into a complete lattice. We will do it in two ways. The first way is to show that if our `Inf` satisfies `(∀ (S : set (subgp G)), is_glb S (Inf S))` then we can build a complete lattice from this, using `complete_lattice_of_Inf`. -/ instance : complete_lattice (subgp G) := complete_lattice_of_Inf _ begin -- ⊢ ∀ (s : set (subgp G)), is_glb s (has_Inf.Inf s) -- See if you can figure out what this says, and how to prove it. -- You might find the function `is_glb.of_image` useful. sorry end /- Now let me show you another way to do this. # Galois connections A Galois conection is a pair of adjoint functors between two partially ordered sets, considered as categories whose hom sets Hom(H,J) have size 1 if H ≤ J and size 0 otherwise. In other words, a Galois connection between two partial orders α and β is a pair of monotone functions `l : α → β` and `u : β → α` such that `∀ (a : α) (b : β), l a ≤ b ↔ a ≤ u b`. There is an example coming from Galois theory (between subfields and subgroups), and an example coming from classical algebraic geometry (between affine varieties and ideals); note that in both cases you have to use the opposite partial order on one side to make everything covariant. The examples we want to keep in mind here are: 1) α = subsets of G, β = subgroups of G, l = "subgroup generated by", u = `carrier` 2) X : Type, α := set (set X), β := topologies on X, l = topology generated by a collection of open sets, u = the open sets regarded as subsets. As you can imagine, there are a bunch of abstract theorems with simple proofs proved for Galois connections. You can see them by `#check galois_connection`, jumping to the definition, and reading the next 150 lines of the mathlib file after the definition. Examples of theorems you might recognise from contexts where you have seen this before: lemma le_u_l (a : α) : a ≤ u (l a) := ... lemma l_u_le (b : β) : l (u b) ≤ b := ... lemma u_l_u_eq_u : u ∘ l ∘ u = u := ... lemma l_u_l_eq_l : l ∘ u ∘ l = l := ... # Galois insertions A particularly cool kind of Galois connection is a Galois insertion, which is a Galois connection such that `l ∘ u = id`. This is true for both the examples we're keeping in mind (the subgroup of `G` generated by a subgroup is the same subgroup; the topology on `X` generated by a topology is the same topology). Our new goal: let's make subgroups of a group into a complete lattice, using the fact that `carrier` is part of a Galois insertion. -/ -- The adjoint functor to the `carrier` functor is the `span` functor -- from subsets to subgps. Here we will CHEAT by using `Inf` to -- define `span`. We could have built `span` directly with -- an inductive definition. def span (S : set G) : subgp G := Inf {H : subgp G | S ⊆ H.carrier} -- Here are some theorems about it. lemma monotone_carrier : monotone (subgp.carrier : subgp G → set G) := sorry lemma monotone_span : monotone (span : set G → subgp G) := sorry lemma subset_span (S : set G) : S ≤ (span S).carrier := begin sorry end lemma span_subgp (H : subgp G) : span H.carrier = H := begin sorry end -- We have proved all the things we need to show that `span` and `carrier` -- form a Galois insertion, using `galois_insertion.monotone_intro`. def gi_subgp : galois_insertion (span : set G → subgp G) (subgp.carrier : subgp G → set G) := galois_insertion.monotone_intro monotone_carrier monotone_span subset_span span_subgp -- Note that `set G` is already a complete lattice: example : complete_lattice (set G) := by apply_instance -- and now `subgp G` can also be made into a complete lattice, by -- a theorem about Galois insertions. Again, I don't use `instance` -- because we already made the instance above. example : complete_lattice (subgp G) := galois_insertion.lift_complete_lattice gi_subgp end subgp -- Because Alex defined the topology generated by a collection of subsets -- yesterday, I'll show you how you can use Galois insertions to prove -- that if `X : Type` then the type of topological space structures on `X` -- is a complete lattice. We use the topology generated by a collection -- of subsets, which is a functor adjoint to the forgetful functor. -- We start by literally copying some stuff from Alex' talk. open set @[ext] class topological_space (X : Type) := (is_open : set X → Prop) -- why set X → Prop not set (set X)? former plays -- nicer with typeclasses later (univ_mem : is_open univ) (union : ∀ (B : set (set X)) (h : ∀ b ∈ B, is_open b), is_open (⋃₀ B)) (inter : ∀ (A B : set X) (hA : is_open A) (hB : is_open B), is_open (A ∩ B)) namespace topological_space def forget {X : Type} : topological_space X → set (set X) := @is_open X /-- The open sets of the least topology containing a collection of basic sets. -/ inductive generated_open (X : Type) (g : set (set X)) : set X → Prop | basic : ∀ s ∈ g, generated_open s | univ : generated_open univ | inter : ∀s t, generated_open s → generated_open t → generated_open (s ∩ t) | sUnion : ∀k, (∀ s ∈ k, generated_open s) → generated_open (⋃₀ k) /-- The smallest topological space containing the collection `g` of basic sets -/ def generate_from {X : Type} (g : set (set X)) : topological_space X := { is_open := generated_open X g, univ_mem := sorry, inter := sorry, union := sorry } -- Recall that `topological_space X` is the type of topological space structures -- on `X`. Our Galois insertion will use the adjoint functors -- `generate_from` and `is_open`. -- We'd better start by giving the collection of topological space structures on X -- a partial order: instance (X : Type) : partial_order (topological_space X) := partial_order.lift (forget) begin -- need to show that a top space is determined by its open sets intros τ₁ τ₂ h, cases τ₁, cases τ₂, simp [forget, *] at *, end -- Exercise (LONG): First, show that we have a Galois insertion. lemma monotone_is_open {X : Type} : monotone (forget : topological_space X → set (set X)) := begin sorry end lemma monotone_span {X : Type} : monotone (generate_from : set (set X) → topological_space X) := begin sorry end lemma subset_forget {X : Type} (Us : set (set X)) : Us ≤ forget (generate_from Us) := begin sorry end lemma generate_forget {X : Type} (τ : topological_space X) : generate_from (forget τ) = τ := begin sorry end def gi_top (X : Type) : galois_insertion (generate_from : set (set X) → topological_space X) (forget : topological_space X → set (set X)) := galois_insertion.monotone_intro monotone_is_open monotone_span subset_forget generate_forget /- Then deduce that the type of topological space structures on X is a complete lattice, i.e. that there is a good definition of arbitrary Infs and Sups of topological space structures on a type, and they satisfy all the correct properties of Infs and Sups. In other words, -/ example (X : Type) : complete_lattice (topological_space X) := galois_insertion.lift_complete_lattice (gi_top X) end topological_space
d90696ee8e7a5249cb7c63fed466c5422df18e00
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/data/nat/choose/sum.lean
3192a4d80a438483a8d5603ceaf39d6937dac397
[ "Apache-2.0" ]
permissive
ilitzroth/mathlib
ea647e67f1fdfd19a0f7bdc5504e8acec6180011
5254ef14e3465f6504306132fe3ba9cec9ffff16
refs/heads/master
1,680,086,661,182
1,617,715,647,000
1,617,715,647,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,980
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Patrick Stevens -/ import data.nat.choose.basic import tactic.linarith import algebra.big_operators.ring import algebra.big_operators.intervals import algebra.big_operators.order /-! # Sums of binomial coefficients This file includes variants of the binomial theorem and other results on sums of binomial coefficients. Theorems whose proofs depend on such sums may also go in this file for import reasons. -/ open nat open finset open_locale big_operators variables {R : Type*} /-- A version of the binomial theorem for noncommutative semirings. -/ theorem commute.add_pow [semiring R] {x y : R} (h : commute x y) (n : ℕ) : (x + y) ^ n = ∑ m in range (n + 1), x ^ m * y ^ (n - m) * choose n m := begin let t : ℕ → ℕ → R := λ n m, x ^ m * (y ^ (n - m)) * (choose n m), change (x + y) ^ n = ∑ m in range (n + 1), t n m, have h_first : ∀ n, t n 0 = y ^ n := λ n, by { dsimp [t], rw[choose_zero_right, nat.cast_one, mul_one, one_mul] }, have h_last : ∀ n, t n n.succ = 0 := λ n, by { dsimp [t], rw [choose_succ_self, nat.cast_zero, mul_zero] }, have h_middle : ∀ (n i : ℕ), (i ∈ finset.range n.succ) → ((t n.succ) ∘ nat.succ) i = x * (t n i) + y * (t n i.succ) := begin intros n i h_mem, have h_le : i ≤ n := nat.le_of_lt_succ (finset.mem_range.mp h_mem), dsimp [t], rw [choose_succ_succ, nat.cast_add, mul_add], congr' 1, { rw[pow_succ x, succ_sub_succ, mul_assoc, mul_assoc, mul_assoc] }, { rw[← mul_assoc y, ← mul_assoc y, (h.symm.pow_right i.succ).eq], by_cases h_eq : i = n, { rw [h_eq, choose_succ_self, nat.cast_zero, mul_zero, mul_zero] }, { rw[succ_sub (lt_of_le_of_ne h_le h_eq)], rw[pow_succ y, mul_assoc, mul_assoc, mul_assoc, mul_assoc] } } end, induction n with n ih, { rw [pow_zero, sum_range_succ, range_zero, sum_empty, add_zero], dsimp [t], rw [choose_self, nat.cast_one, mul_one, mul_one] }, { rw[sum_range_succ', h_first], rw[finset.sum_congr rfl (h_middle n), finset.sum_add_distrib, add_assoc], rw[pow_succ (x + y), ih, add_mul, finset.mul_sum, finset.mul_sum], congr' 1, rw[finset.sum_range_succ', finset.sum_range_succ, h_first, h_last, mul_zero, zero_add, pow_succ] } end /-- The binomial theorem -/ theorem add_pow [comm_semiring R] (x y : R) (n : ℕ) : (x + y) ^ n = ∑ m in range (n + 1), x ^ m * y ^ (n - m) * choose n m := (commute.all x y).add_pow n namespace nat /-- The sum of entries in a row of Pascal's triangle -/ theorem sum_range_choose (n : ℕ) : ∑ m in range (n + 1), choose n m = 2 ^ n := by simpa using (add_pow 1 1 n).symm lemma sum_range_choose_halfway (m : nat) : ∑ i in range (m + 1), choose (2 * m + 1) i = 4 ^ m := have ∑ i in range (m + 1), choose (2 * m + 1) (2 * m + 1 - i) = ∑ i in range (m + 1), choose (2 * m + 1) i, from sum_congr rfl $ λ i hi, choose_symm $ by linarith [mem_range.1 hi], (nat.mul_right_inj zero_lt_two).1 $ calc 2 * (∑ i in range (m + 1), choose (2 * m + 1) i) = (∑ i in range (m + 1), choose (2 * m + 1) i) + ∑ i in range (m + 1), choose (2 * m + 1) (2 * m + 1 - i) : by rw [two_mul, this] ... = (∑ i in range (m + 1), choose (2 * m + 1) i) + ∑ i in Ico (m + 1) (2 * m + 2), choose (2 * m + 1) i : begin rw [range_eq_Ico, sum_Ico_reflect], { congr, have A : m + 1 ≤ 2 * m + 1, by linarith, rw [add_comm, nat.add_sub_assoc A, ← add_comm], congr, rw nat.sub_eq_iff_eq_add A, ring, }, { linarith } end ... = ∑ i in range (2 * m + 2), choose (2 * m + 1) i : sum_range_add_sum_Ico _ (by linarith) ... = 2^(2 * m + 1) : sum_range_choose (2 * m + 1) ... = 2 * 4^m : by { rw [pow_succ, pow_mul], refl } lemma choose_middle_le_pow (n : ℕ) : choose (2 * n + 1) n ≤ 4 ^ n := begin have t : choose (2 * n + 1) n ≤ ∑ i in range (n + 1), choose (2 * n + 1) i := single_le_sum (λ x _, by linarith) (self_mem_range_succ n), simpa [sum_range_choose_halfway n] using t end end nat theorem int.alternating_sum_range_choose {n : ℕ} : ∑ m in range (n + 1), ((-1) ^ m * ↑(choose n m) : ℤ) = if n = 0 then 1 else 0 := begin cases n, { simp }, have h := add_pow (-1 : ℤ) 1 n.succ, simp only [one_pow, mul_one, add_left_neg, int.nat_cast_eq_coe_nat] at h, rw [← h, zero_pow (nat.succ_pos n), if_neg (nat.succ_ne_zero n)], end theorem int.alternating_sum_range_choose_of_ne {n : ℕ} (h0 : n ≠ 0) : ∑ m in range (n + 1), ((-1) ^ m * ↑(choose n m) : ℤ) = 0 := by rw [int.alternating_sum_range_choose, if_neg h0] namespace finset theorem sum_powerset_apply_card {α β : Type*} [add_comm_monoid α] (f : ℕ → α) {x : finset β} : ∑ m in x.powerset, f m.card = ∑ m in range (x.card + 1), (x.card.choose m) •ℕ f m := begin transitivity ∑ m in range (x.card + 1), ∑ j in x.powerset.filter (λ z, z.card = m), f j.card, { refine (sum_fiberwise_of_maps_to _ _).symm, intros y hy, rw [mem_range, nat.lt_succ_iff], rw mem_powerset at hy, exact card_le_of_subset hy }, { refine sum_congr rfl (λ y hy, _), rw [← card_powerset_len, ← sum_const], refine sum_congr powerset_len_eq_filter.symm (λ z hz, _), rw (mem_powerset_len.1 hz).2 } end theorem sum_powerset_neg_one_pow_card {α : Type*} [decidable_eq α] {x : finset α} : ∑ m in x.powerset, (-1 : ℤ) ^ m.card = if x = ∅ then 1 else 0 := begin rw sum_powerset_apply_card, simp only [nsmul_eq_mul', ← card_eq_zero], convert int.alternating_sum_range_choose, ext, simp, end theorem sum_powerset_neg_one_pow_card_of_nonempty {α : Type*} {x : finset α} (h0 : x.nonempty) : ∑ m in x.powerset, (-1 : ℤ) ^ m.card = 0 := begin classical, rw [sum_powerset_neg_one_pow_card, if_neg], rw [← ne.def, ← nonempty_iff_ne_empty], apply h0, end end finset
ad75c1277a6f788621e31d88124cbc66a3fc7719
e030b0259b777fedcdf73dd966f3f1556d392178
/tests/lean/run/cases_tac1.lean
e0d4835335c362a7ea2db1735c50aa4cd190537b
[ "Apache-2.0" ]
permissive
fgdorais/lean
17b46a095b70b21fa0790ce74876658dc5faca06
c3b7c54d7cca7aaa25328f0a5660b6b75fe26055
refs/heads/master
1,611,523,590,686
1,484,412,902,000
1,484,412,902,000
38,489,734
0
0
null
1,435,923,380,000
1,435,923,379,000
null
UTF-8
Lean
false
false
1,057
lean
inductive vec (A : Type*) : nat → Type* | nil : vec 0 | cons : ∀ {n}, A → vec n → vec (n+1) open tactic nat vec definition head {A : Type*} : ∀ {n : nat}, vec A (n+1) → A | n (cons h t) := h definition tail {A : Type*} : ∀ {n : nat}, vec A (n+1) → vec A n | n (cons h t) := t @[simp] definition head_cons {A : Type*} {n : nat} (a : A) (v : vec A n) : head (cons a v) = a := rfl @[simp] definition tail_cons {A : Type*} {n : nat} (a : A) (v : vec A n) : tail (cons a v) = v := rfl example {A : Type*} {n : nat} (v w : vec A (n+1)) : head v = head w → tail v = tail w → v = w := by do v ← get_local `v, cases_using v [`n', `hv, `tv], trace_state, w ← get_local `w, cases_using w [`n', `hw, `tw], trace_state, dsimp, trace_state, Heq1 ← intro1, Heq2 ← intro1, subst Heq1, subst Heq2, reflexivity print "-------" example (n : nat) : n ≠ 0 → succ (pred n) = n := by do H ← intro `H, n ← get_local `n, cases_using n [`n'], trace_state, contradiction, reflexivity print "---------"
1dbc25fa119b376daf4062e28fde45ccdf4c6b36
130c49f47783503e462c16b2eff31933442be6ff
/stage0/src/Lean/Server/Utils.lean
afc2036b845598150e5642bf44b1a0bba5b72c2e
[ "Apache-2.0" ]
permissive
Hazel-Brown/lean4
8aa5860e282435ffc30dcdfccd34006c59d1d39c
79e6732fc6bbf5af831b76f310f9c488d44e7a16
refs/heads/master
1,689,218,208,951
1,629,736,869,000
1,629,736,896,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,527
lean
/- Copyright (c) 2020 Wojciech Nawrocki. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Wojciech Nawrocki, Marc Huisinga -/ import Lean.Data.Position import Lean.Data.Lsp import Lean.Server.InfoUtils import Init.System.FilePath namespace IO def throwServerError (err : String) : IO α := throw (userError err) namespace FS.Stream /-- Chains two streams by creating a new stream s.t. writing to it just writes to `a` but reading from it also duplicates the read output into `b`, c.f. `a | tee b` on Unix. NB: if `a` is written to but this stream is never read from, the output will *not* be duplicated. Use this if you only care about the data that was actually read. -/ def chainRight (a : Stream) (b : Stream) (flushEagerly : Bool := false) : Stream := { a with flush := a.flush *> b.flush read := fun sz => do let bs ← a.read sz b.write bs if flushEagerly then b.flush pure bs getLine := do let ln ← a.getLine b.putStr ln if flushEagerly then b.flush pure ln } /-- Like `tee a | b` on Unix. See `chainOut`. -/ def chainLeft (a : Stream) (b : Stream) (flushEagerly : Bool := false) : Stream := { b with flush := a.flush *> b.flush write := fun bs => do a.write bs if flushEagerly then a.flush b.write bs putStr := fun s => do a.putStr s if flushEagerly then a.flush b.putStr s } /-- Prefixes all written outputs with `pre`. -/ def withPrefix (a : Stream) (pre : String) : Stream := { a with write := fun bs => do a.putStr pre a.write bs putStr := fun s => a.putStr (pre ++ s) } end FS.Stream end IO namespace Lean.Server structure DocumentMeta where uri : Lsp.DocumentUri version : Nat text : FileMap deriving Inhabited def replaceLspRange (text : FileMap) (r : Lsp.Range) (newText : String) : FileMap := let start := text.lspPosToUtf8Pos r.start let «end» := text.lspPosToUtf8Pos r.«end» let pre := text.source.extract 0 start let post := text.source.extract «end» text.source.bsize (pre ++ newText ++ post).toFileMap open IO /-- Duplicates an I/O stream to a log file `fName` in LEAN_SERVER_LOG_DIR if that envvar is set. -/ def maybeTee (fName : String) (isOut : Bool) (h : FS.Stream) : IO FS.Stream := do match (← IO.getEnv "LEAN_SERVER_LOG_DIR") with | none => pure h | some logDir => let hTee ← FS.Handle.mk (System.mkFilePath [logDir, fName]) FS.Mode.write true let hTee := FS.Stream.ofHandle hTee pure $ if isOut then hTee.chainLeft h true else h.chainRight hTee true /-- Transform the given path to a file:// URI. -/ def toFileUri (fname : System.FilePath) : Lsp.DocumentUri := let fname := fname.normalize.toString let fname := if System.Platform.isWindows then fname.map fun c => if c == '\\' then '/' else c else fname -- TODO(WN): URL-encode special characters -- Three slashes denote localhost. "file:///" ++ fname.dropWhile (· == '/') open Lsp /-- Returns the document contents with all changes applied, together with the position of the change which lands earliest in the file. Panics if there are no changes. -/ def foldDocumentChanges (changes : @& Array Lsp.TextDocumentContentChangeEvent) (oldText : FileMap) : FileMap × String.Pos := if changes.isEmpty then panic! "Lean.Server.foldDocumentChanges: empty change array" else let accumulateChanges : FileMap × String.Pos → TextDocumentContentChangeEvent → FileMap × String.Pos := fun ⟨newDocText, minStartOff⟩ change => match change with | TextDocumentContentChangeEvent.rangeChange (range : Range) (newText : String) => let startOff := oldText.lspPosToUtf8Pos range.start let newDocText := replaceLspRange newDocText range newText let minStartOff := minStartOff.min startOff ⟨newDocText, minStartOff⟩ | TextDocumentContentChangeEvent.fullChange (newText : String) => ⟨newText.toFileMap, 0⟩ -- NOTE: We assume Lean files are below 16 EiB. changes.foldl accumulateChanges (oldText, 0xffffffff) def publishDiagnostics (m : DocumentMeta) (diagnostics : Array Lsp.Diagnostic) (hOut : FS.Stream) : IO Unit := hOut.writeLspNotification { method := "textDocument/publishDiagnostics" param := { uri := m.uri version? := m.version diagnostics := diagnostics : PublishDiagnosticsParams } } def publishMessages (m : DocumentMeta) (msgLog : MessageLog) (hOut : FS.Stream) : IO Unit := do let diagnostics ← msgLog.msgs.mapM (msgToDiagnostic m.text) publishDiagnostics m diagnostics.toArray hOut def publishProgress (m : DocumentMeta) (processing : Array LeanFileProgressProcessingInfo) (hOut : FS.Stream) : IO Unit := hOut.writeLspNotification { method := "$/lean/fileProgress" param := { textDocument := { uri := m.uri, version? := m.version } processing : LeanFileProgressParams } } def publishProgressAtPos (m : DocumentMeta) (pos : String.Pos) (hOut : FS.Stream) : IO Unit := publishProgress m #[{ range := ⟨m.text.utf8PosToLspPos pos, m.text.utf8PosToLspPos m.text.source.bsize⟩ }] hOut def publishProgressDone (m : DocumentMeta) (hOut : FS.Stream) : IO Unit := publishProgress m #[] hOut end Lean.Server def String.Range.toLspRange (text : Lean.FileMap) (r : String.Range) : Lean.Lsp.Range := ⟨text.utf8PosToLspPos r.start, text.utf8PosToLspPos r.stop⟩
bb6f57fd284efc6f81063788e79f1fcf99d36f55
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/order/well_founded.lean
4ee42fa17d93440e380a9acbc434b29d52cb8e5c
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
10,598
lean
/- Copyright (c) 2020 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Mario Carneiro -/ import tactic.by_contra import data.set.basic /-! # Well-founded relations A relation is well-founded if it can be used for induction: for each `x`, `(∀ y, r y x → P y) → P x` implies `P x`. Well-founded relations can be used for induction and recursion, including construction of fixed points in the space of dependent functions `Π x : α , β x`. The predicate `well_founded` is defined in the core library. In this file we prove some extra lemmas and provide a few new definitions: `well_founded.min`, `well_founded.sup`, and `well_founded.succ`, and an induction principle `well_founded.induction_bot`. -/ variables {α : Type*} namespace well_founded protected theorem is_asymm {α : Sort*} {r : α → α → Prop} (h : well_founded r) : is_asymm α r := ⟨h.asymmetric⟩ instance {α : Sort*} [has_well_founded α] : is_asymm α has_well_founded.r := has_well_founded.wf.is_asymm protected theorem is_irrefl {α : Sort*} {r : α → α → Prop} (h : well_founded r) : is_irrefl α r := (@is_asymm.is_irrefl α r h.is_asymm) instance {α : Sort*} [has_well_founded α] : is_irrefl α has_well_founded.r := is_asymm.is_irrefl /-- If `r` is a well-founded relation, then any nonempty set has a minimal element with respect to `r`. -/ theorem has_min {α} {r : α → α → Prop} (H : well_founded r) (s : set α) : s.nonempty → ∃ a ∈ s, ∀ x ∈ s, ¬ r x a | ⟨a, ha⟩ := (acc.rec_on (H.apply a) $ λ x _ IH, not_imp_not.1 $ λ hne hx, hne $ ⟨x, hx, λ y hy hyx, hne $ IH y hyx hy⟩) ha /-- A minimal element of a nonempty set in a well-founded order. If you're working with a nonempty linear order, consider defining a `conditionally_complete_linear_order_bot` instance via `well_founded.conditionally_complete_linear_order_with_bot` and using `Inf` instead. -/ noncomputable def min {r : α → α → Prop} (H : well_founded r) (s : set α) (h : s.nonempty) : α := classical.some (H.has_min s h) theorem min_mem {r : α → α → Prop} (H : well_founded r) (s : set α) (h : s.nonempty) : H.min s h ∈ s := let ⟨h, _⟩ := classical.some_spec (H.has_min s h) in h theorem not_lt_min {r : α → α → Prop} (H : well_founded r) (s : set α) (h : s.nonempty) {x} (hx : x ∈ s) : ¬ r x (H.min s h) := let ⟨_, h'⟩ := classical.some_spec (H.has_min s h) in h' _ hx theorem well_founded_iff_has_min {r : α → α → Prop} : (well_founded r) ↔ ∀ (s : set α), s.nonempty → ∃ m ∈ s, ∀ x ∈ s, ¬ r x m := begin refine ⟨λ h, h.has_min, λ h, ⟨λ x, _⟩⟩, by_contra hx, obtain ⟨m, hm, hm'⟩ := h _ ⟨x, hx⟩, refine hm ⟨_, λ y hy, _⟩, by_contra hy', exact hm' y hy' hy end lemma eq_iff_not_lt_of_le {α} [partial_order α] {x y : α} : x ≤ y → y = x ↔ ¬ x < y := begin split, { intros xle nge, cases le_not_le_of_lt nge, rw xle left at nge, exact lt_irrefl x nge }, { intros ngt xle, contrapose! ngt, exact lt_of_le_of_ne xle (ne.symm ngt) } end theorem well_founded_iff_has_max' [partial_order α] : (well_founded ((>) : α → α → Prop) ↔ ∀ (p : set α), p.nonempty → ∃ m ∈ p, ∀ x ∈ p, m ≤ x → x = m) := by simp only [eq_iff_not_lt_of_le, well_founded_iff_has_min] theorem well_founded_iff_has_min' [partial_order α] : (well_founded (has_lt.lt : α → α → Prop)) ↔ ∀ (p : set α), p.nonempty → ∃ m ∈ p, ∀ x ∈ p, x ≤ m → x = m := @well_founded_iff_has_max' αᵒᵈ _ open set /-- The supremum of a bounded, well-founded order -/ protected noncomputable def sup {r : α → α → Prop} (wf : well_founded r) (s : set α) (h : bounded r s) : α := wf.min { x | ∀a ∈ s, r a x } h protected lemma lt_sup {r : α → α → Prop} (wf : well_founded r) {s : set α} (h : bounded r s) {x} (hx : x ∈ s) : r x (wf.sup s h) := min_mem wf { x | ∀a ∈ s, r a x } h x hx section open_locale classical /-- A successor of an element `x` in a well-founded order is a minimal element `y` such that `x < y` if one exists. Otherwise it is `x` itself. -/ protected noncomputable def succ {r : α → α → Prop} (wf : well_founded r) (x : α) : α := if h : ∃y, r x y then wf.min { y | r x y } h else x protected lemma lt_succ {r : α → α → Prop} (wf : well_founded r) {x : α} (h : ∃y, r x y) : r x (wf.succ x) := by { rw [well_founded.succ, dif_pos h], apply min_mem } end protected lemma lt_succ_iff {r : α → α → Prop} [wo : is_well_order α r] {x : α} (h : ∃y, r x y) (y : α) : r y (wo.wf.succ x) ↔ r y x ∨ y = x := begin split, { intro h', have : ¬r x y, { intro hy, rw [well_founded.succ, dif_pos] at h', exact wo.wf.not_lt_min _ h hy h' }, rcases trichotomous_of r x y with hy | hy | hy, exfalso, exact this hy, right, exact hy.symm, left, exact hy }, rintro (hy | rfl), exact trans hy (wo.wf.lt_succ h), exact wo.wf.lt_succ h end section linear_order variables {β : Type*} [linear_order β] (h : well_founded ((<) : β → β → Prop)) {γ : Type*} [partial_order γ] theorem min_le {x : β} {s : set β} (hx : x ∈ s) (hne : s.nonempty := ⟨x, hx⟩) : h.min s hne ≤ x := not_lt.1 $ h.not_lt_min _ _ hx private theorem eq_strict_mono_iff_eq_range_aux {f g : β → γ} (hf : strict_mono f) (hg : strict_mono g) (hfg : set.range f = set.range g) {b : β} (H : ∀ a < b, f a = g a) : f b ≤ g b := begin obtain ⟨c, hc⟩ : g b ∈ set.range f := by { rw hfg, exact set.mem_range_self b }, cases lt_or_le c b with hcb hbc, { rw [H c hcb] at hc, rw hg.injective hc at hcb, exact hcb.false.elim }, { rw ←hc, exact hf.monotone hbc } end include h theorem eq_strict_mono_iff_eq_range {f g : β → γ} (hf : strict_mono f) (hg : strict_mono g) : set.range f = set.range g ↔ f = g := ⟨λ hfg, begin funext a, apply h.induction a, exact λ b H, le_antisymm (eq_strict_mono_iff_eq_range_aux hf hg hfg H) (eq_strict_mono_iff_eq_range_aux hg hf hfg.symm (λ a hab, (H a hab).symm)) end, congr_arg _⟩ theorem self_le_of_strict_mono {f : β → β} (hf : strict_mono f) : ∀ n, n ≤ f n := by { by_contra' h₁, have h₂ := h.min_mem _ h₁, exact h.not_lt_min _ h₁ (hf h₂) h₂ } end linear_order end well_founded namespace function variables {β : Type*} (f : α → β) section has_lt variables [has_lt β] (h : well_founded ((<) : β → β → Prop)) /-- Given a function `f : α → β` where `β` carries a well-founded `<`, this is an element of `α` whose image under `f` is minimal in the sense of `function.not_lt_argmin`. -/ noncomputable def argmin [nonempty α] : α := well_founded.min (inv_image.wf f h) set.univ set.univ_nonempty lemma not_lt_argmin [nonempty α] (a : α) : ¬ f a < f (argmin f h) := well_founded.not_lt_min (inv_image.wf f h) _ _ (set.mem_univ a) /-- Given a function `f : α → β` where `β` carries a well-founded `<`, and a non-empty subset `s` of `α`, this is an element of `s` whose image under `f` is minimal in the sense of `function.not_lt_argmin_on`. -/ noncomputable def argmin_on (s : set α) (hs : s.nonempty) : α := well_founded.min (inv_image.wf f h) s hs @[simp] lemma argmin_on_mem (s : set α) (hs : s.nonempty) : argmin_on f h s hs ∈ s := well_founded.min_mem _ _ _ @[simp] lemma not_lt_argmin_on (s : set α) {a : α} (ha : a ∈ s) (hs : s.nonempty := set.nonempty_of_mem ha) : ¬ f a < f (argmin_on f h s hs) := well_founded.not_lt_min (inv_image.wf f h) s hs ha end has_lt section linear_order variables [linear_order β] (h : well_founded ((<) : β → β → Prop)) @[simp] lemma argmin_le (a : α) [nonempty α] : f (argmin f h) ≤ f a := not_lt.mp $ not_lt_argmin f h a @[simp] lemma argmin_on_le (s : set α) {a : α} (ha : a ∈ s) (hs : s.nonempty := set.nonempty_of_mem ha) : f (argmin_on f h s hs) ≤ f a := not_lt.mp $ not_lt_argmin_on f h s ha hs end linear_order end function section induction /-- Let `r` be a relation on `α`, let `f : α → β` be a function, let `C : β → Prop`, and let `bot : α`. This induction principle shows that `C (f bot)` holds, given that * some `a` that is accessible by `r` satisfies `C (f a)`, and * for each `b` such that `f b ≠ f bot` and `C (f b)` holds, there is `c` satisfying `r c b` and `C (f c)`. -/ lemma acc.induction_bot' {α β} {r : α → α → Prop} {a bot : α} (ha : acc r a) {C : β → Prop} {f : α → β} (ih : ∀ b, f b ≠ f bot → C (f b) → ∃ c, r c b ∧ C (f c)) : C (f a) → C (f bot) := @acc.rec_on _ _ (λ x, C (f x) → C (f bot)) _ ha $ λ x ac ih' hC, (eq_or_ne (f x) (f bot)).elim (λ h, h ▸ hC) (λ h, let ⟨y, hy₁, hy₂⟩ := ih x h hC in ih' y hy₁ hy₂) /-- Let `r` be a relation on `α`, let `C : α → Prop` and let `bot : α`. This induction principle shows that `C bot` holds, given that * some `a` that is accessible by `r` satisfies `C a`, and * for each `b ≠ bot` such that `C b` holds, there is `c` satisfying `r c b` and `C c`. -/ lemma acc.induction_bot {α} {r : α → α → Prop} {a bot : α} (ha : acc r a) {C : α → Prop} (ih : ∀ b, b ≠ bot → C b → ∃ c, r c b ∧ C c) : C a → C bot := ha.induction_bot' ih /-- Let `r` be a well-founded relation on `α`, let `f : α → β` be a function, let `C : β → Prop`, and let `bot : α`. This induction principle shows that `C (f bot)` holds, given that * some `a` satisfies `C (f a)`, and * for each `b` such that `f b ≠ f bot` and `C (f b)` holds, there is `c` satisfying `r c b` and `C (f c)`. -/ lemma well_founded.induction_bot' {α β} {r : α → α → Prop} (hwf : well_founded r) {a bot : α} {C : β → Prop} {f : α → β} (ih : ∀ b, f b ≠ f bot → C (f b) → ∃ c, r c b ∧ C (f c)) : C (f a) → C (f bot) := (hwf.apply a).induction_bot' ih /-- Let `r` be a well-founded relation on `α`, let `C : α → Prop`, and let `bot : α`. This induction principle shows that `C bot` holds, given that * some `a` satisfies `C a`, and * for each `b` that satisfies `C b`, there is `c` satisfying `r c b` and `C c`. The naming is inspired by the fact that when `r` is transitive, it follows that `bot` is the smallest element w.r.t. `r` that satisfies `C`. -/ lemma well_founded.induction_bot {α} {r : α → α → Prop} (hwf : well_founded r) {a bot : α} {C : α → Prop} (ih : ∀ b, b ≠ bot → C b → ∃ c, r c b ∧ C c) : C a → C bot := hwf.induction_bot' ih end induction
73e0d81891e2e2ee87ed566bdee7760f2fcfd056
206422fb9edabf63def0ed2aa3f489150fb09ccb
/src/algebra/euclidean_domain.lean
8ae195e400830d95aacb7d7638143dc2735ec4a3
[ "Apache-2.0" ]
permissive
hamdysalah1/mathlib
b915f86b2503feeae268de369f1b16932321f097
95454452f6b3569bf967d35aab8d852b1ddf8017
refs/heads/master
1,677,154,116,545
1,611,797,994,000
1,611,797,994,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
15,018
lean
/- Copyright (c) 2018 Louis Carlin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Louis Carlin, Mario Carneiro Euclidean domains and Euclidean algorithm (extended to come) A lot is based on pre-existing code in mathlib for natural number gcds -/ import data.int.basic import algebra.field universe u section old_structure_cmd set_option old_structure_cmd true /-- A `euclidean_domain` is an `integral_domain` with a division and a remainder, satisfying `b * (a / b) + a % b = a`. The definition of a euclidean domain usually includes a valuation function `R → ℕ`. This definition is slightly generalised to include a well founded relation `r` with the property that `r (a % b) b`, instead of a valuation. -/ @[protect_proj without mul_left_not_lt r_well_founded] class euclidean_domain (R : Type u) extends comm_ring R, nontrivial R := (quotient : R → R → R) (quotient_zero : ∀ a, quotient a 0 = 0) (remainder : R → R → R) -- This could be changed to the same order as int.mod_add_div. -- We normally write `qb+r` rather than `r + qb` though. (quotient_mul_add_remainder_eq : ∀ a b, b * quotient a b + remainder a b = a) (r : R → R → Prop) (r_well_founded : well_founded r) (remainder_lt : ∀ a {b}, b ≠ 0 → r (remainder a b) b) (mul_left_not_lt : ∀ a {b}, b ≠ 0 → ¬r (a * b) a) end old_structure_cmd namespace euclidean_domain variable {R : Type u} variables [euclidean_domain R] local infix ` ≺ `:50 := euclidean_domain.r @[priority 70] -- see Note [lower instance priority] instance : has_div R := ⟨euclidean_domain.quotient⟩ @[priority 70] -- see Note [lower instance priority] instance : has_mod R := ⟨euclidean_domain.remainder⟩ theorem div_add_mod (a b : R) : b * (a / b) + a % b = a := euclidean_domain.quotient_mul_add_remainder_eq _ _ lemma mod_add_div (a b : R) : a % b + b * (a / b) = a := (add_comm _ _).trans (div_add_mod _ _) lemma mod_eq_sub_mul_div {R : Type*} [euclidean_domain R] (a b : R) : a % b = a - b * (a / b) := calc a % b = b * (a / b) + a % b - b * (a / b) : (add_sub_cancel' _ _).symm ... = a - b * (a / b) : by rw div_add_mod theorem mod_lt : ∀ a {b : R}, b ≠ 0 → (a % b) ≺ b := euclidean_domain.remainder_lt theorem mul_right_not_lt {a : R} (b) (h : a ≠ 0) : ¬(a * b) ≺ b := by rw mul_comm; exact mul_left_not_lt b h lemma mul_div_cancel_left {a : R} (b) (a0 : a ≠ 0) : a * b / a = b := eq.symm $ eq_of_sub_eq_zero $ classical.by_contradiction $ λ h, begin have := mul_left_not_lt a h, rw [mul_sub, sub_eq_iff_eq_add'.2 (div_add_mod (a*b) a).symm] at this, exact this (mod_lt _ a0) end lemma mul_div_cancel (a) {b : R} (b0 : b ≠ 0) : a * b / b = a := by rw mul_comm; exact mul_div_cancel_left a b0 @[simp] lemma mod_zero (a : R) : a % 0 = a := by simpa only [zero_mul, zero_add] using div_add_mod a 0 @[simp] lemma mod_eq_zero {a b : R} : a % b = 0 ↔ b ∣ a := ⟨λ h, by rw [← div_add_mod a b, h, add_zero]; exact dvd_mul_right _ _, λ ⟨c, e⟩, begin rw [e, ← add_left_cancel_iff, div_add_mod, add_zero], haveI := classical.dec, by_cases b0 : b = 0, { simp only [b0, zero_mul] }, { rw [mul_div_cancel_left _ b0] } end⟩ @[simp] lemma mod_self (a : R) : a % a = 0 := mod_eq_zero.2 (dvd_refl _) lemma dvd_mod_iff {a b c : R} (h : c ∣ b) : c ∣ a % b ↔ c ∣ a := by rw [dvd_add_iff_right (dvd_mul_of_dvd_left h _), div_add_mod] lemma lt_one (a : R) : a ≺ (1:R) → a = 0 := by haveI := classical.dec; exact not_imp_not.1 (λ h, by simpa only [one_mul] using mul_left_not_lt 1 h) lemma val_dvd_le : ∀ a b : R, b ∣ a → a ≠ 0 → ¬a ≺ b | _ b ⟨d, rfl⟩ ha := mul_left_not_lt b (mt (by rintro rfl; exact mul_zero _) ha) @[simp] lemma mod_one (a : R) : a % 1 = 0 := mod_eq_zero.2 (one_dvd _) @[simp] lemma zero_mod (b : R) : 0 % b = 0 := mod_eq_zero.2 (dvd_zero _) @[simp, priority 900] lemma div_zero (a : R) : a / 0 = 0 := euclidean_domain.quotient_zero a @[simp, priority 900] lemma zero_div {a : R} : 0 / a = 0 := classical.by_cases (λ a0 : a = 0, a0.symm ▸ div_zero 0) (λ a0, by simpa only [zero_mul] using mul_div_cancel 0 a0) @[simp, priority 900] lemma div_self {a : R} (a0 : a ≠ 0) : a / a = 1 := by simpa only [one_mul] using mul_div_cancel 1 a0 lemma eq_div_of_mul_eq_left {a b c : R} (hb : b ≠ 0) (h : a * b = c) : a = c / b := by rw [← h, mul_div_cancel _ hb] lemma eq_div_of_mul_eq_right {a b c : R} (ha : a ≠ 0) (h : a * b = c) : b = c / a := by rw [← h, mul_div_cancel_left _ ha] theorem mul_div_assoc (x : R) {y z : R} (h : z ∣ y) : x * y / z = x * (y / z) := begin classical, by_cases hz : z = 0, { subst hz, rw [div_zero, div_zero, mul_zero] }, rcases h with ⟨p, rfl⟩, rw [mul_div_cancel_left _ hz, mul_left_comm, mul_div_cancel_left _ hz] end section open_locale classical @[elab_as_eliminator] theorem gcd.induction {P : R → R → Prop} : ∀ a b : R, (∀ x, P 0 x) → (∀ a b, a ≠ 0 → P (b % a) a → P a b) → P a b | a := λ b H0 H1, if a0 : a = 0 then by rw [a0]; apply H0 else have h:_ := mod_lt b a0, H1 _ _ a0 (gcd.induction (b%a) a H0 H1) using_well_founded {dec_tac := tactic.assumption, rel_tac := λ _ _, `[exact ⟨_, r_well_founded⟩]} end section gcd variable [decidable_eq R] /-- `gcd a b` is a (non-unique) element such that `gcd a b ∣ a` `gcd a b ∣ b`, and for any element `c` such that `c ∣ a` and `c ∣ b`, then `c ∣ gcd a b` -/ def gcd : R → R → R | a := λ b, if a0 : a = 0 then b else have h:_ := mod_lt b a0, gcd (b%a) a using_well_founded {dec_tac := tactic.assumption, rel_tac := λ _ _, `[exact ⟨_, r_well_founded⟩]} @[simp] theorem gcd_zero_left (a : R) : gcd 0 a = a := by rw gcd; exact if_pos rfl @[simp] theorem gcd_zero_right (a : R) : gcd a 0 = a := by rw gcd; split_ifs; simp only [h, zero_mod, gcd_zero_left] theorem gcd_val (a b : R) : gcd a b = gcd (b % a) a := by rw gcd; split_ifs; [simp only [h, mod_zero, gcd_zero_right], refl] theorem gcd_dvd (a b : R) : gcd a b ∣ a ∧ gcd a b ∣ b := gcd.induction a b (λ b, by rw [gcd_zero_left]; exact ⟨dvd_zero _, dvd_refl _⟩) (λ a b aneq ⟨IH₁, IH₂⟩, by rw gcd_val; exact ⟨IH₂, (dvd_mod_iff IH₂).1 IH₁⟩) theorem gcd_dvd_left (a b : R) : gcd a b ∣ a := (gcd_dvd a b).left theorem gcd_dvd_right (a b : R) : gcd a b ∣ b := (gcd_dvd a b).right protected theorem gcd_eq_zero_iff {a b : R} : gcd a b = 0 ↔ a = 0 ∧ b = 0 := ⟨λ h, by simpa [h] using gcd_dvd a b, by rintro ⟨rfl, rfl⟩; simp⟩ theorem dvd_gcd {a b c : R} : c ∣ a → c ∣ b → c ∣ gcd a b := gcd.induction a b (λ _ _ H, by simpa only [gcd_zero_left] using H) (λ a b a0 IH ca cb, by rw gcd_val; exact IH ((dvd_mod_iff ca).2 cb) ca) theorem gcd_eq_left {a b : R} : gcd a b = a ↔ a ∣ b := ⟨λ h, by rw ← h; apply gcd_dvd_right, λ h, by rw [gcd_val, mod_eq_zero.2 h, gcd_zero_left]⟩ @[simp] theorem gcd_one_left (a : R) : gcd 1 a = 1 := gcd_eq_left.2 (one_dvd _) @[simp] theorem gcd_self (a : R) : gcd a a = a := gcd_eq_left.2 (dvd_refl _) /-- An implementation of the extended GCD algorithm. At each step we are computing a triple `(r, s, t)`, where `r` is the next value of the GCD algorithm, to compute the greatest common divisor of the input (say `x` and `y`), and `s` and `t` are the coefficients in front of `x` and `y` to obtain `r` (i.e. `r = s * x + t * y`). The function `xgcd_aux` takes in two triples, and from these recursively computes the next triple: ``` xgcd_aux (r, s, t) (r', s', t') = xgcd_aux (r' % r, s' - (r' / r) * s, t' - (r' / r) * t) (r, s, t) ``` -/ def xgcd_aux : R → R → R → R → R → R → R × R × R | r := λ s t r' s' t', if hr : r = 0 then (r', s', t') else have r' % r ≺ r, from mod_lt _ hr, let q := r' / r in xgcd_aux (r' % r) (s' - q * s) (t' - q * t) r s t using_well_founded {dec_tac := tactic.assumption, rel_tac := λ _ _, `[exact ⟨_, r_well_founded⟩]} @[simp] theorem xgcd_zero_left {s t r' s' t' : R} : xgcd_aux 0 s t r' s' t' = (r', s', t') := by unfold xgcd_aux; exact if_pos rfl theorem xgcd_aux_rec {r s t r' s' t' : R} (h : r ≠ 0) : xgcd_aux r s t r' s' t' = xgcd_aux (r' % r) (s' - (r' / r) * s) (t' - (r' / r) * t) r s t := by conv {to_lhs, rw [xgcd_aux]}; exact if_neg h /-- Use the extended GCD algorithm to generate the `a` and `b` values satisfying `gcd x y = x * a + y * b`. -/ def xgcd (x y : R) : R × R := (xgcd_aux x 1 0 y 0 1).2 /-- The extended GCD `a` value in the equation `gcd x y = x * a + y * b`. -/ def gcd_a (x y : R) : R := (xgcd x y).1 /-- The extended GCD `b` value in the equation `gcd x y = x * a + y * b`. -/ def gcd_b (x y : R) : R := (xgcd x y).2 @[simp] theorem gcd_a_zero_left {s : R} : gcd_a 0 s = 0 := by { unfold gcd_a, rw [xgcd, xgcd_zero_left] } @[simp] theorem gcd_b_zero_left {s : R} : gcd_b 0 s = 1 := by { unfold gcd_b, rw [xgcd, xgcd_zero_left] } @[simp] theorem xgcd_aux_fst (x y : R) : ∀ s t s' t', (xgcd_aux x s t y s' t').1 = gcd x y := gcd.induction x y (by intros; rw [xgcd_zero_left, gcd_zero_left]) (λ x y h IH s t s' t', by simp only [xgcd_aux_rec h, if_neg h, IH]; rw ← gcd_val) theorem xgcd_aux_val (x y : R) : xgcd_aux x 1 0 y 0 1 = (gcd x y, xgcd x y) := by rw [xgcd, ← xgcd_aux_fst x y 1 0 0 1, prod.mk.eta] theorem xgcd_val (x y : R) : xgcd x y = (gcd_a x y, gcd_b x y) := prod.mk.eta.symm private def P (a b : R) : R × R × R → Prop | (r, s, t) := (r : R) = a * s + b * t theorem xgcd_aux_P (a b : R) {r r' : R} : ∀ {s t s' t'}, P a b (r, s, t) → P a b (r', s', t') → P a b (xgcd_aux r s t r' s' t') := gcd.induction r r' (by intros; simpa only [xgcd_zero_left]) $ λ x y h IH s t s' t' p p', begin rw [xgcd_aux_rec h], refine IH _ p, unfold P at p p' ⊢, rw [mul_sub, mul_sub, add_sub, sub_add_eq_add_sub, ← p', sub_sub, mul_comm _ s, ← mul_assoc, mul_comm _ t, ← mul_assoc, ← add_mul, ← p, mod_eq_sub_mul_div] end theorem gcd_eq_gcd_ab (a b : R) : (gcd a b : R) = a * gcd_a a b + b * gcd_b a b := by have := @xgcd_aux_P _ _ _ a b a b 1 0 0 1 (by rw [P, mul_one, mul_zero, add_zero]) (by rw [P, mul_one, mul_zero, zero_add]); rwa [xgcd_aux_val, xgcd_val] at this @[priority 70] -- see Note [lower instance priority] instance (R : Type*) [e : euclidean_domain R] : integral_domain R := by haveI := classical.dec_eq R; exact { eq_zero_or_eq_zero_of_mul_eq_zero := λ a b h, (or_iff_not_and_not.2 $ λ h0, h0.1 $ by rw [← mul_div_cancel a h0.2, h, zero_div]), zero := 0, add := (+), mul := (*), ..e } end gcd section lcm variables [decidable_eq R] /-- `lcm a b` is a (non-unique) element such that `a ∣ lcm a b` `b ∣ lcm a b`, and for any element `c` such that `a ∣ c` and `b ∣ c`, then `lcm a b ∣ c` -/ def lcm (x y : R) : R := x * y / gcd x y theorem dvd_lcm_left (x y : R) : x ∣ lcm x y := classical.by_cases (assume hxy : gcd x y = 0, by rw [lcm, hxy, div_zero]; exact dvd_zero _) (λ hxy, let ⟨z, hz⟩ := (gcd_dvd x y).2 in ⟨z, eq.symm $ eq_div_of_mul_eq_left hxy $ by rw [mul_right_comm, mul_assoc, ← hz]⟩) theorem dvd_lcm_right (x y : R) : y ∣ lcm x y := classical.by_cases (assume hxy : gcd x y = 0, by rw [lcm, hxy, div_zero]; exact dvd_zero _) (λ hxy, let ⟨z, hz⟩ := (gcd_dvd x y).1 in ⟨z, eq.symm $ eq_div_of_mul_eq_right hxy $ by rw [← mul_assoc, mul_right_comm, ← hz]⟩) theorem lcm_dvd {x y z : R} (hxz : x ∣ z) (hyz : y ∣ z) : lcm x y ∣ z := begin rw lcm, by_cases hxy : gcd x y = 0, { rw [hxy, div_zero], rw euclidean_domain.gcd_eq_zero_iff at hxy, rwa hxy.1 at hxz }, rcases gcd_dvd x y with ⟨⟨r, hr⟩, ⟨s, hs⟩⟩, suffices : x * y ∣ z * gcd x y, { cases this with p hp, use p, generalize_hyp : gcd x y = g at hxy hs hp ⊢, subst hs, rw [mul_left_comm, mul_div_cancel_left _ hxy, ← mul_left_inj' hxy, hp], rw [← mul_assoc], simp only [mul_right_comm] }, rw [gcd_eq_gcd_ab, mul_add], apply dvd_add, { rw mul_left_comm, exact mul_dvd_mul_left _ (dvd_mul_of_dvd_left hyz _) }, { rw [mul_left_comm, mul_comm], exact mul_dvd_mul_left _ (dvd_mul_of_dvd_left hxz _) } end @[simp] lemma lcm_dvd_iff {x y z : R} : lcm x y ∣ z ↔ x ∣ z ∧ y ∣ z := ⟨λ hz, ⟨dvd_trans (dvd_lcm_left _ _) hz, dvd_trans (dvd_lcm_right _ _) hz⟩, λ ⟨hxz, hyz⟩, lcm_dvd hxz hyz⟩ @[simp] lemma lcm_zero_left (x : R) : lcm 0 x = 0 := by rw [lcm, zero_mul, zero_div] @[simp] lemma lcm_zero_right (x : R) : lcm x 0 = 0 := by rw [lcm, mul_zero, zero_div] @[simp] lemma lcm_eq_zero_iff {x y : R} : lcm x y = 0 ↔ x = 0 ∨ y = 0 := begin split, { intro hxy, rw [lcm, mul_div_assoc _ (gcd_dvd_right _ _), mul_eq_zero] at hxy, apply or_of_or_of_imp_right hxy, intro hy, by_cases hgxy : gcd x y = 0, { rw euclidean_domain.gcd_eq_zero_iff at hgxy, exact hgxy.2 }, { rcases gcd_dvd x y with ⟨⟨r, hr⟩, ⟨s, hs⟩⟩, generalize_hyp : gcd x y = g at hr hs hy hgxy ⊢, subst hs, rw [mul_div_cancel_left _ hgxy] at hy, rw [hy, mul_zero] } }, rintro (hx | hy), { rw [hx, lcm_zero_left] }, { rw [hy, lcm_zero_right] } end @[simp] lemma gcd_mul_lcm (x y : R) : gcd x y * lcm x y = x * y := begin rw lcm, by_cases h : gcd x y = 0, { rw [h, zero_mul], rw euclidean_domain.gcd_eq_zero_iff at h, rw [h.1, zero_mul] }, rcases gcd_dvd x y with ⟨⟨r, hr⟩, ⟨s, hs⟩⟩, generalize_hyp : gcd x y = g at h hr ⊢, subst hr, rw [mul_assoc, mul_div_cancel_left _ h] end end lcm end euclidean_domain instance int.euclidean_domain : euclidean_domain ℤ := { add := (+), mul := (*), one := 1, zero := 0, neg := has_neg.neg, quotient := (/), quotient_zero := int.div_zero, remainder := (%), quotient_mul_add_remainder_eq := λ a b, by rw add_comm; exact int.mod_add_div _ _, r := λ a b, a.nat_abs < b.nat_abs, r_well_founded := measure_wf (λ a, int.nat_abs a), remainder_lt := λ a b b0, int.coe_nat_lt.1 $ by rw [int.nat_abs_of_nonneg (int.mod_nonneg _ b0), ← int.abs_eq_nat_abs]; exact int.mod_lt _ b0, mul_left_not_lt := λ a b b0, not_lt_of_ge $ by rw [← mul_one a.nat_abs, int.nat_abs_mul]; exact mul_le_mul_of_nonneg_left (int.nat_abs_pos_of_ne_zero b0) (nat.zero_le _), .. int.comm_ring, .. int.nontrivial } @[priority 100] -- see Note [lower instance priority] instance field.to_euclidean_domain {K : Type u} [field K] : euclidean_domain K := { add := (+), mul := (*), one := 1, zero := 0, neg := has_neg.neg, quotient := (/), remainder := λ a b, a - a * b / b, quotient_zero := div_zero, quotient_mul_add_remainder_eq := λ a b, by classical; by_cases b = 0; simp [h, mul_div_cancel'], r := λ a b, a = 0 ∧ b ≠ 0, r_well_founded := well_founded.intro $ λ a, acc.intro _ $ λ b ⟨hb, hna⟩, acc.intro _ $ λ c ⟨hc, hnb⟩, false.elim $ hnb hb, remainder_lt := λ a b hnb, by simp [hnb], mul_left_not_lt := λ a b hnb ⟨hab, hna⟩, or.cases_on (mul_eq_zero.1 hab) hna hnb, .. ‹field K› }
d4690951baa9929ea580055f22e178d808a61ce1
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/tactic/norm_cast.lean
af9709c58d3f5e5d37941d51c359c1b111efdcbc
[ "Apache-2.0" ]
permissive
hikari0108/mathlib
b7ea2b7350497ab1a0b87a09d093ecc025a50dfa
a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901
refs/heads/master
1,690,483,608,260
1,631,541,580,000
1,631,541,580,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
26,430
lean
/- Copyright (c) 2019 Paul-Nicolas Madelaine. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Paul-Nicolas Madelaine, Robert Y. Lewis Normalizing casts inside expressions. -/ import tactic.converter.interactive import tactic.hint /-! # A tactic for normalizing casts inside expressions This tactic normalizes casts inside expressions. It can be thought of as a call to the simplifier with a specific set of lemmas to move casts upwards in the expression. It has special handling of numerals and a simple heuristic to help moving casts "past" binary operators. Contrary to simp, it should be safe to use as a non-terminating tactic. The algorithm implemented here is described in the paper <https://lean-forward.github.io/norm_cast/norm_cast.pdf>. ## Important definitions * `tactic.interactive.norm_cast` * `tactic.interactive.push_cast` * `tactic.interactive.exact_mod_cast` * `tactic.interactive.apply_mod_cast` * `tactic.interactive.rw_mod_cast` * `tactic.interactive.assumption_mod_cast` -/ setup_tactic_parser namespace tactic /-- Runs `mk_instance` with a time limit. This is a work around to the fact that in some cases mk_instance times out instead of failing, for example: `has_lift_t ℤ ℕ` `mk_instance_fast` is used when we assume the type class search should end instantly. -/ meta def mk_instance_fast (e : expr) (timeout := 1000) : tactic expr := try_for timeout (mk_instance e) end tactic namespace norm_cast open tactic expr declare_trace norm_cast /-- Output a trace message if `trace.norm_cast` is enabled. -/ meta def trace_norm_cast {α} [has_to_tactic_format α] (msg : string) (a : α) : tactic unit := when_tracing `norm_cast $ do a ← pp a, trace ("[norm_cast] " ++ msg ++ a : format) mk_simp_attribute push_cast "The `push_cast` simp attribute uses `norm_cast` lemmas to move casts toward the leaf nodes of the expression." /-- `label` is a type used to classify `norm_cast` lemmas. * elim lemma: LHS has 0 head coes and ≥ 1 internal coe * move lemma: LHS has 1 head coe and 0 internal coes, RHS has 0 head coes and ≥ 1 internal coes * squash lemma: LHS has ≥ 1 head coes and 0 internal coes, RHS has fewer head coes -/ @[derive [decidable_eq, has_reflect, inhabited]] inductive label | elim : label | move : label | squash : label namespace label /-- Convert `label` into `string`. -/ protected def to_string : label → string | elim := "elim" | move := "move" | squash := "squash" instance : has_to_string label := ⟨label.to_string⟩ instance : has_repr label := ⟨label.to_string⟩ meta instance : has_to_format label := ⟨λ l, l.to_string⟩ /-- Convert `string` into `label`. -/ def of_string : string -> option label | "elim" := some elim | "move" := some move | "squash" := some squash | _ := none end label open label /-- Count how many coercions are at the top of the expression. -/ meta def count_head_coes : expr → ℕ | `(coe %%e) := count_head_coes e + 1 | `(coe_sort %%e) := count_head_coes e + 1 | `(coe_fn %%e) := count_head_coes e + 1 | _ := 0 /-- Count how many coercions are inside the expression, including the top ones. -/ meta def count_coes : expr → tactic ℕ | `(coe %%e) := (+1) <$> count_coes e | `(coe_sort %%e) := (+1) <$> count_coes e | `(coe_fn %%e) := (+1) <$> count_coes e | (app `(coe_fn %%e) x) := (+) <$> count_coes x <*> (+1) <$> count_coes e | (expr.lam n bi t e) := do l ← mk_local' n bi t, count_coes $ e.instantiate_var l | e := do as ← e.get_simp_args, list.sum <$> as.mmap count_coes /-- Count how many coercions are inside the expression, excluding the top ones. -/ private meta def count_internal_coes (e : expr) : tactic ℕ := do ncoes ← count_coes e, pure $ ncoes - count_head_coes e /-- Classifies a declaration of type `ty` as a `norm_cast` rule. -/ meta def classify_type (ty : expr) : tactic label := do (_, ty) ← open_pis ty, (lhs, rhs) ← match ty with | `(%%lhs = %%rhs) := pure (lhs, rhs) | `(%%lhs ↔ %%rhs) := pure (lhs, rhs) | _ := fail "norm_cast: lemma must be = or ↔" end, lhs_coes ← count_coes lhs, when (lhs_coes = 0) $ fail "norm_cast: badly shaped lemma, lhs must contain at least one coe", let lhs_head_coes := count_head_coes lhs, lhs_internal_coes ← count_internal_coes lhs, let rhs_head_coes := count_head_coes rhs, rhs_internal_coes ← count_internal_coes rhs, if lhs_head_coes = 0 then return elim else if lhs_head_coes = 1 then do when (rhs_head_coes ≠ 0) $ fail "norm_cast: badly shaped lemma, rhs can't start with coe", if rhs_internal_coes = 0 then return squash else return move else if rhs_head_coes < lhs_head_coes then do return squash else do fail "norm_cast: badly shaped shaped squash lemma, rhs must have fewer head coes than lhs" /-- The cache for `norm_cast` attribute stores three `simp_lemma` objects. -/ meta structure norm_cast_cache := (up : simp_lemmas) (down : simp_lemmas) (squash : simp_lemmas) /-- Empty `norm_cast_cache`. -/ meta def empty_cache : norm_cast_cache := { up := simp_lemmas.mk, down := simp_lemmas.mk, squash := simp_lemmas.mk, } meta instance : inhabited norm_cast_cache := ⟨empty_cache⟩ /-- `add_elim cache e` adds `e` as an `elim` lemma to `cache`. -/ meta def add_elim (cache : norm_cast_cache) (e : expr) : tactic norm_cast_cache := do new_up ← simp_lemmas.add cache.up e, return { up := new_up, down := cache.down, squash := cache.squash, } /-- `add_move cache e` adds `e` as a `move` lemma to `cache`. -/ meta def add_move (cache : norm_cast_cache) (e : expr) : tactic norm_cast_cache := do ty ← infer_type e, new_up ← cache.up.add e tt, new_down ← simp_lemmas.add cache.down e, return { up := new_up, down := new_down, squash := cache.squash, } /-- `add_squash cache e` adds `e` as an `squash` lemma to `cache`. -/ meta def add_squash (cache : norm_cast_cache) (e : expr) : tactic norm_cast_cache := do new_squash ← simp_lemmas.add cache.squash e, new_down ← simp_lemmas.add cache.down e, return { up := cache.up, down := new_down, squash := new_squash, } /-- The type of the `norm_cast` attribute. The optional label is used to overwrite the classifier. -/ meta def norm_cast_attr_ty : Type := user_attribute norm_cast_cache (option label) /-- Efficient getter for the `@[norm_cast]` attribute parameter that does not call `eval_expr`. See Note [user attribute parameters]. -/ meta def get_label_param (attr : norm_cast_attr_ty) (decl : name) : tactic (option label) := do p ← attr.get_param_untyped decl, match p with | `(none) := pure none | `(some label.elim) := pure label.elim | `(some label.move) := pure label.move | `(some label.squash) := pure label.squash | _ := fail p end /-- `add_lemma cache decl` infers the proper `norm_cast` attribute for `decl` and adds it to `cache`. -/ meta def add_lemma (attr : norm_cast_attr_ty) (cache : norm_cast_cache) (decl : name) : tactic norm_cast_cache := do e ← mk_const decl, param ← get_label_param attr decl, l ← param <|> (infer_type e >>= classify_type), match l with | elim := add_elim cache e | move := add_move cache e | squash := add_squash cache e end -- special lemmas to handle the ≥, > and ≠ operators private lemma ge_from_le {α} [has_le α] : ∀ (x y : α), x ≥ y ↔ y ≤ x := λ _ _, iff.rfl private lemma gt_from_lt {α} [has_lt α] : ∀ (x y : α), x > y ↔ y < x := λ _ _, iff.rfl private lemma ne_from_not_eq {α} : ∀ (x y : α), x ≠ y ↔ ¬(x = y) := λ _ _, iff.rfl /-- `mk_cache names` creates a `norm_cast_cache`. It infers the proper `norm_cast` attributes for names in `names`, and collects the lemmas attributed with specific `norm_cast` attributes. -/ meta def mk_cache (attr : thunk norm_cast_attr_ty) (names : list name) : tactic norm_cast_cache := do -- names has the declarations in reverse order cache ← names.mfoldr (λ name cache, add_lemma (attr ()) cache name) empty_cache, --some special lemmas to handle binary relations let up := cache.up, up ← up.add_simp ``ge_from_le, up ← up.add_simp ``gt_from_lt, up ← up.add_simp ``ne_from_not_eq, let down := cache.down, down ← down.add_simp ``coe_coe, pure { up := up, down := down, squash := cache.squash } /-- The `norm_cast` attribute. -/ @[user_attribute] meta def norm_cast_attr : user_attribute norm_cast_cache (option label) := { name := `norm_cast, descr := "attribute for norm_cast", parser := (do some l ← (label.of_string ∘ to_string) <$> ident, return l) <|> return none, after_set := some (λ decl prio persistent, do param ← get_label_param norm_cast_attr decl, match param with | some l := when (l ≠ elim) $ simp_attr.push_cast.set decl () tt | none := do e ← mk_const decl, ty ← infer_type e, l ← classify_type ty, norm_cast_attr.set decl l persistent prio end), before_unset := some $ λ _ _, tactic.skip, cache_cfg := { mk_cache := mk_cache norm_cast_attr, dependencies := [] } } /-- Classify a declaration as a `norm_cast` rule. -/ meta def make_guess (decl : name) : tactic label := do e ← mk_const decl, ty ← infer_type e, classify_type ty /-- Gets the `norm_cast` classification label for a declaration. Applies the override specified on the attribute, if necessary. -/ meta def get_label (decl : name) : tactic label := do param ← get_label_param norm_cast_attr decl, param <|> make_guess decl end norm_cast namespace tactic.interactive open norm_cast /-- `push_cast` rewrites the expression to move casts toward the leaf nodes. For example, `↑(a + b)` will be written to `↑a + ↑b`. Equivalent to `simp only with push_cast`. Can also be used at hypotheses. `push_cast` can also be used at hypotheses and with extra simp rules. ```lean example (a b : ℕ) (h1 : ((a + b : ℕ) : ℤ) = 10) (h2 : ((a + b + 0 : ℕ) : ℤ) = 10) : ((a + b : ℕ) : ℤ) = 10 := begin push_cast, push_cast at h1, push_cast [int.add_zero] at h2, end ``` -/ meta def push_cast (hs : parse tactic.simp_arg_list) (l : parse location) : tactic unit := tactic.interactive.simp none none tt hs [`push_cast] l end tactic.interactive namespace norm_cast open tactic expr /-- Prove `a = b` using the given simp set. -/ meta def prove_eq_using (s : simp_lemmas) (a b : expr) : tactic expr := do (a', a_a', _) ← simplify s [] a {fail_if_unchanged := ff}, (b', b_b', _) ← simplify s [] b {fail_if_unchanged := ff}, on_exception (trace_norm_cast "failed: " (to_expr ``(%%a' = %%b') >>= pp)) $ is_def_eq a' b' reducible, b'_b ← mk_eq_symm b_b', mk_eq_trans a_a' b'_b /-- Prove `a = b` by simplifying using move and squash lemmas. -/ meta def prove_eq_using_down (a b : expr) : tactic expr := do cache ← norm_cast_attr.get_cache, trace_norm_cast "proving: " (to_expr ``(%%a = %%b) >>= pp), prove_eq_using cache.down a b /-- This is the main heuristic used alongside the elim and move lemmas. The goal is to help casts move past operators by adding intermediate casts. An expression of the shape: op (↑(x : α) : γ) (↑(y : β) : γ) is rewritten to: op (↑(↑(x : α) : β) : γ) (↑(y : β) : γ) when (↑(↑(x : α) : β) : γ) = (↑(x : α) : γ) can be proven with a squash lemma -/ meta def splitting_procedure : expr → tactic (expr × expr) | (app (app op x) y) := (do `(@coe %%α %%δ %%coe1 %%xx) ← return x, `(@coe %%β %%γ %%coe2 %%yy) ← return y, success_if_fail $ is_def_eq α β, is_def_eq δ γ, (do coe3 ← mk_app `has_lift_t [α, β] >>= mk_instance_fast, new_x ← to_expr ``(@coe %%β %%δ %%coe2 (@coe %%α %%β %%coe3 %%xx)), let new_e := app (app op new_x) y, eq_x ← prove_eq_using_down x new_x, pr ← mk_congr_arg op eq_x, pr ← mk_congr_fun pr y, return (new_e, pr) ) <|> (do coe3 ← mk_app `has_lift_t [β, α] >>= mk_instance_fast, new_y ← to_expr ``(@coe %%α %%δ %%coe1 (@coe %%β %%α %%coe3 %%yy)), let new_e := app (app op x) new_y, eq_y ← prove_eq_using_down y new_y, pr ← mk_congr_arg (app op x) eq_y, return (new_e, pr) ) ) <|> (do `(@coe %%α %%β %%coe1 %%xx) ← return x, `(@has_one.one %%β %%h1) ← return y, h2 ← to_expr ``(has_one %%α) >>= mk_instance_fast, new_y ← to_expr ``(@coe %%α %%β %%coe1 (@has_one.one %%α %%h2)), eq_y ← prove_eq_using_down y new_y, let new_e := app (app op x) new_y, pr ← mk_congr_arg (app op x) eq_y, return (new_e, pr) ) <|> (do `(@coe %%α %%β %%coe1 %%xx) ← return x, `(@has_zero.zero %%β %%h1) ← return y, h2 ← to_expr ``(has_zero %%α) >>= mk_instance_fast, new_y ← to_expr ``(@coe %%α %%β %%coe1 (@has_zero.zero %%α %%h2)), eq_y ← prove_eq_using_down y new_y, let new_e := app (app op x) new_y, pr ← mk_congr_arg (app op x) eq_y, return (new_e, pr) ) <|> (do `(@has_one.one %%β %%h1) ← return x, `(@coe %%α %%β %%coe1 %%xx) ← return y, h1 ← to_expr ``(has_one %%α) >>= mk_instance_fast, new_x ← to_expr ``(@coe %%α %%β %%coe1 (@has_one.one %%α %%h1)), eq_x ← prove_eq_using_down x new_x, let new_e := app (app op new_x) y, pr ← mk_congr_arg (lam `x binder_info.default β (app (app op (var 0)) y)) eq_x, return (new_e, pr) ) <|> (do `(@has_zero.zero %%β %%h1) ← return x, `(@coe %%α %%β %%coe1 %%xx) ← return y, h1 ← to_expr ``(has_zero %%α) >>= mk_instance_fast, new_x ← to_expr ``(@coe %%α %%β %%coe1 (@has_zero.zero %%α %%h1)), eq_x ← prove_eq_using_down x new_x, let new_e := app (app op new_x) y, pr ← mk_congr_arg (lam `x binder_info.default β (app (app op (var 0)) y)) eq_x, return (new_e, pr) ) | _ := failed /-- Discharging function used during simplification in the "squash" step. TODO: norm_cast takes a list of expressions to use as lemmas for the discharger TODO: a tactic to print the results the discharger fails to proove -/ private meta def prove : tactic unit := assumption /-- Core rewriting function used in the "squash" step, which moves casts upwards and eliminates them. It tries to rewrite an expression using the elim and move lemmas. On failure, it calls the splitting procedure heuristic. -/ meta def upward_and_elim (s : simp_lemmas) (e : expr) : tactic (expr × expr) := (do r ← mcond (is_prop e) (return `iff) (return `eq), (new_e, pr) ← s.rewrite e prove r, pr ← match r with | `iff := mk_app `propext [pr] | _ := return pr end, return (new_e, pr) ) <|> splitting_procedure e /-! The following auxiliary functions are used to handle numerals. -/ /-- If possible, rewrite `(n : α)` to `((n : ℕ) : α)` where `n` is a numeral and `α ≠ ℕ`. Returns a pair of the new expression and proof that they are equal. -/ meta def numeral_to_coe (e : expr) : tactic (expr × expr) := do α ← infer_type e, success_if_fail $ is_def_eq α `(ℕ), n ← e.to_nat, h1 ← mk_app `has_lift_t [`(ℕ), α] >>= mk_instance_fast, let new_e : expr := reflect n, new_e ← to_expr ``(@coe ℕ %%α %%h1 %%new_e), pr ← prove_eq_using_down e new_e, return (new_e, pr) /-- If possible, rewrite `((n : ℕ) : α)` to `(n : α)` where `n` is a numeral. Returns a pair of the new expression and proof that they are equal. -/ meta def coe_to_numeral (e : expr) : tactic (expr × expr) := do `(@coe ℕ %%α %%h1 %%e') ← return e, n ← e'.to_nat, -- replace e' by normalized numeral is_def_eq (reflect n) e' reducible, let e := e.app_fn (reflect n), new_e ← expr.of_nat α n, pr ← prove_eq_using_down e new_e, return (new_e, pr) /-- A local variant on `simplify_top_down`. -/ private meta def simplify_top_down' {α} (a : α) (pre : α → expr → tactic (α × expr × expr)) (e : expr) (cfg : simp_config := {}) : tactic (α × expr × expr) := ext_simplify_core a cfg simp_lemmas.mk (λ _, failed) (λ a _ _ _ e, do (new_a, new_e, pr) ← pre a e, guard (¬ new_e =ₐ e), return (new_a, new_e, some pr, ff)) (λ _ _ _ _ _, failed) `eq e /-- The core simplification routine of `norm_cast`. -/ meta def derive (e : expr) : tactic (expr × expr) := do cache ← norm_cast_attr.get_cache, e ← instantiate_mvars e, let cfg : simp_config := { zeta := ff, beta := ff, eta := ff, proj := ff, iota := ff, iota_eqn := ff, fail_if_unchanged := ff }, let e0 := e, -- step 1: pre-processing of numerals ((), e1, pr1) ← simplify_top_down' () (λ _ e, prod.mk () <$> numeral_to_coe e) e0 cfg, trace_norm_cast "after numeral_to_coe: " e1, -- step 2: casts are moved upwards and eliminated ((), e2, pr2) ← simplify_bottom_up () (λ _ e, prod.mk () <$> upward_and_elim cache.up e) e1 cfg, trace_norm_cast "after upward_and_elim: " e2, -- step 3: casts are squashed (e3, pr3, _) ← simplify cache.squash [] e2 cfg, trace_norm_cast "after squashing: " e3, -- step 4: post-processing of numerals ((), e4, pr4) ← simplify_top_down' () (λ _ e, prod.mk () <$> coe_to_numeral e) e3 cfg, trace_norm_cast "after coe_to_numeral: " e4, let new_e := e4, guard (¬ new_e =ₐ e), pr ← mk_eq_trans pr1 pr2, pr ← mk_eq_trans pr pr3, pr ← mk_eq_trans pr pr4, return (new_e, pr) /-- A small variant of `push_cast` suited for non-interactive use. `derive_push_cast extra_lems e` returns an expression `e'` and a proof that `e = e'`. -/ meta def derive_push_cast (extra_lems : list simp_arg_type) (e : expr) : tactic (expr × expr) := do (s, _) ← mk_simp_set tt [`push_cast] extra_lems, (e, prf, _) ← simplify (s.erase [`int.coe_nat_succ]) [] e {fail_if_unchanged := ff}, return (e, prf) end norm_cast namespace tactic open expr norm_cast /-- `aux_mod_cast e` runs `norm_cast` on `e` and returns the result. If `include_goal` is true, it also normalizes the goal. -/ meta def aux_mod_cast (e : expr) (include_goal : bool := tt) : tactic expr := match e with | local_const _ lc _ _ := do e ← get_local lc, replace_at derive [e] include_goal, get_local lc | e := do t ← infer_type e, e ← assertv `this t e, replace_at derive [e] include_goal, get_local `this end /-- `exact_mod_cast e` runs `norm_cast` on the goal and `e`, and tries to use `e` to close the goal. -/ meta def exact_mod_cast (e : expr) : tactic unit := decorate_error "exact_mod_cast failed:" $ do new_e ← aux_mod_cast e, exact new_e /-- `apply_mod_cast e` runs `norm_cast` on the goal and `e`, and tries to apply `e`. -/ meta def apply_mod_cast (e : expr) : tactic (list (name × expr)) := decorate_error "apply_mod_cast failed:" $ do new_e ← aux_mod_cast e, apply new_e /-- `assumption_mod_cast` runs `norm_cast` on the goal. For each local hypothesis `h`, it also normalizes `h` and tries to use that to close the goal. -/ meta def assumption_mod_cast : tactic unit := decorate_error "assumption_mod_cast failed:" $ do let cfg : simp_config := { fail_if_unchanged := ff, canonize_instances := ff, canonize_proofs := ff, proj := ff }, replace_at derive [] tt, ctx ← local_context, ctx.mfirst (λ h, aux_mod_cast h ff >>= tactic.exact) end tactic namespace tactic.interactive open tactic norm_cast /-- Normalize casts at the given locations by moving them "upwards". As opposed to simp, norm_cast can be used without necessarily closing the goal. -/ meta def norm_cast (loc : parse location) : tactic unit := do ns ← loc.get_locals, tt ← replace_at derive ns loc.include_goal | fail "norm_cast failed to simplify", when loc.include_goal $ try tactic.reflexivity, when loc.include_goal $ try tactic.triv, when (¬ ns.empty) $ try tactic.contradiction /-- Rewrite with the given rules and normalize casts between steps. -/ meta def rw_mod_cast (rs : parse rw_rules) (loc : parse location) : tactic unit := decorate_error "rw_mod_cast failed:" $ do let cfg_norm : simp_config := {}, let cfg_rw : rewrite_cfg := {}, ns ← loc.get_locals, monad.mapm' (λ r : rw_rule, do save_info r.pos, replace_at derive ns loc.include_goal, rw ⟨[r], none⟩ loc {} ) rs.rules, replace_at derive ns loc.include_goal, skip /-- Normalize the goal and the given expression, then close the goal with exact. -/ meta def exact_mod_cast (e : parse texpr) : tactic unit := do e ← i_to_expr e <|> do { ty ← target, e ← i_to_expr_strict ``(%%e : %%ty), pty ← pp ty, ptgt ← pp e, fail ("exact_mod_cast failed, expression type not directly " ++ "inferrable. Try:\n\nexact_mod_cast ...\nshow " ++ to_fmt pty ++ ",\nfrom " ++ ptgt : format) }, tactic.exact_mod_cast e /-- Normalize the goal and the given expression, then apply the expression to the goal. -/ meta def apply_mod_cast (e : parse texpr) : tactic unit := do e ← i_to_expr_for_apply e, concat_tags $ tactic.apply_mod_cast e /-- Normalize the goal and every expression in the local context, then close the goal with assumption. -/ meta def assumption_mod_cast : tactic unit := tactic.assumption_mod_cast end tactic.interactive namespace conv.interactive open conv open norm_cast (derive) /-- the converter version of `norm_cast' -/ meta def norm_cast : conv unit := replace_lhs derive end conv.interactive -- TODO: move this elsewhere? @[norm_cast] lemma ite_cast {α β} [has_lift_t α β] {c : Prop} [decidable c] {a b : α} : ↑(ite c a b) = ite c (↑a : β) (↑b : β) := by by_cases h : c; simp [h] @[norm_cast] lemma dite_cast {α β} [has_lift_t α β] {c : Prop} [decidable c] {a : c → α} {b : ¬ c → α} : ↑(dite c a b) = dite c (λ h, (↑(a h) : β)) (λ h, (↑(b h) : β)) := by by_cases h : c; simp [h] add_hint_tactic "norm_cast at *" /-- The `norm_cast` family of tactics is used to normalize casts inside expressions. It is basically a simp tactic with a specific set of lemmas to move casts upwards in the expression. Therefore it can be used more safely as a non-terminating tactic. It also has special handling of numerals. For instance, given an assumption ```lean a b : ℤ h : ↑a + ↑b < (10 : ℚ) ``` writing `norm_cast at h` will turn `h` into ```lean h : a + b < 10 ``` You can also use `exact_mod_cast`, `apply_mod_cast`, `rw_mod_cast` or `assumption_mod_cast`. Writing `exact_mod_cast h` and `apply_mod_cast h` will normalize the goal and `h` before using `exact h` or `apply h`. Writing `assumption_mod_cast` will normalize the goal and for every expression `h` in the context it will try to normalize `h` and use `exact h`. `rw_mod_cast` acts like the `rw` tactic but it applies `norm_cast` between steps. `push_cast` rewrites the expression to move casts toward the leaf nodes. This uses `norm_cast` lemmas in the forward direction. For example, `↑(a + b)` will be written to `↑a + ↑b`. It is equivalent to `simp only with push_cast`. It can also be used at hypotheses with `push_cast at h` and with extra simp lemmas with `push_cast [int.add_zero]`. ```lean example (a b : ℕ) (h1 : ((a + b : ℕ) : ℤ) = 10) (h2 : ((a + b + 0 : ℕ) : ℤ) = 10) : ((a + b : ℕ) : ℤ) = 10 := begin push_cast, push_cast at h1, push_cast [int.add_zero] at h2, end ``` The implementation and behavior of the `norm_cast` family is described in detail at <https://lean-forward.github.io/norm_cast/norm_cast.pdf>. -/ add_tactic_doc { name := "norm_cast", category := doc_category.tactic, decl_names := [``tactic.interactive.norm_cast, ``tactic.interactive.rw_mod_cast, ``tactic.interactive.apply_mod_cast, ``tactic.interactive.assumption_mod_cast, ``tactic.interactive.exact_mod_cast, ``tactic.interactive.push_cast], tags := ["coercions", "simplification"] } /-- The `norm_cast` attribute should be given to lemmas that describe the behaviour of a coercion in regard to an operator, a relation, or a particular function. It only concerns equality or iff lemmas involving `↑`, `⇑` and `↥`, describing the behavior of the coercion functions. It does not apply to the explicit functions that define the coercions. Examples: ```lean @[norm_cast] theorem coe_nat_inj' {m n : ℕ} : (↑m : ℤ) = ↑n ↔ m = n @[norm_cast] theorem coe_int_denom (n : ℤ) : (n : ℚ).denom = 1 @[norm_cast] theorem cast_id : ∀ n : ℚ, ↑n = n @[norm_cast] theorem coe_nat_add (m n : ℕ) : (↑(m + n) : ℤ) = ↑m + ↑n @[norm_cast] theorem cast_sub [add_group α] [has_one α] {m n} (h : m ≤ n) : ((n - m : ℕ) : α) = n - m @[norm_cast] theorem coe_nat_bit0 (n : ℕ) : (↑(bit0 n) : ℤ) = bit0 ↑n @[norm_cast] theorem cast_coe_nat (n : ℕ) : ((n : ℤ) : α) = n @[norm_cast] theorem cast_one : ((1 : ℚ) : α) = 1 ``` Lemmas tagged with `@[norm_cast]` are classified into three categories: `move`, `elim`, and `squash`. They are classified roughly as follows: * elim lemma: LHS has 0 head coes and ≥ 1 internal coe * move lemma: LHS has 1 head coe and 0 internal coes, RHS has 0 head coes and ≥ 1 internal coes * squash lemma: LHS has ≥ 1 head coes and 0 internal coes, RHS has fewer head coes `norm_cast` uses `move` and `elim` lemmas to factor coercions toward the root of an expression and to cancel them from both sides of an equation or relation. It uses `squash` lemmas to clean up the result. Occasionally you may want to override the automatic classification. You can do this by giving an optional `elim`, `move`, or `squash` parameter to the attribute. ```lean @[simp, norm_cast elim] lemma nat_cast_re (n : ℕ) : (n : ℂ).re = n := by rw [← of_real_nat_cast, of_real_re] ``` Don't do this unless you understand what you are doing. A full description of the tactic, and the use of each lemma category, can be found at <https://lean-forward.github.io/norm_cast/norm_cast.pdf>. -/ add_tactic_doc { name := "norm_cast attributes", category := doc_category.attr, decl_names := [``norm_cast.norm_cast_attr], tags := ["coercions", "simplification"] } -- Lemmas defined in core. attribute [norm_cast] int.nat_abs_of_nat int.coe_nat_sub int.coe_nat_mul int.coe_nat_zero int.coe_nat_one int.coe_nat_add -- Lemmas about nat.succ need to get a low priority, so that they are tried last. -- This is because `nat.succ _` matches `1`, `3`, `x+1`, etc. -- Rewriting would then produce really wrong terms. attribute [norm_cast, priority 500] int.coe_nat_succ
bbeaca58d0f1570d116595752a4e3708986564e3
2a70b774d16dbdf5a533432ee0ebab6838df0948
/_target/deps/mathlib/src/data/polynomial/degree/definitions.lean
e90f102c640a2b0bbd1ca84a99c2b75545b06113
[ "Apache-2.0" ]
permissive
hjvromen/lewis
40b035973df7c77ebf927afab7878c76d05ff758
105b675f73630f028ad5d890897a51b3c1146fb0
refs/heads/master
1,677,944,636,343
1,676,555,301,000
1,676,555,301,000
327,553,599
0
0
null
null
null
null
UTF-8
Lean
false
false
36,585
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker -/ import data.polynomial.coeff import data.nat.with_bot /-! # Theory of univariate polynomials The definitions include `degree`, `monic`, `leading_coeff` Results include - `degree_mul` : The degree of the product is the sum of degrees - `leading_coeff_add_of_degree_eq` and `leading_coeff_add_of_degree_lt` : The leading_coefficient of a sum is determined by the leading coefficients and degrees -/ noncomputable theory local attribute [instance, priority 100] classical.prop_decidable open finsupp finset open_locale big_operators namespace polynomial universes u v variables {R : Type u} {S : Type v} {a b : R} {n m : ℕ} section semiring variables [semiring R] {p q r : polynomial R} /-- `degree p` is the degree of the polynomial `p`, i.e. the largest `X`-exponent in `p`. `degree p = some n` when `p ≠ 0` and `n` is the highest power of `X` that appears in `p`, otherwise `degree 0 = ⊥`. -/ def degree (p : polynomial R) : with_bot ℕ := p.support.sup some lemma degree_lt_wf : well_founded (λp q : polynomial R, degree p < degree q) := inv_image.wf degree (with_bot.well_founded_lt nat.lt_wf) instance : has_well_founded (polynomial R) := ⟨_, degree_lt_wf⟩ /-- `nat_degree p` forces `degree p` to ℕ, by defining nat_degree 0 = 0. -/ def nat_degree (p : polynomial R) : ℕ := (degree p).get_or_else 0 /-- `leading_coeff p` gives the coefficient of the highest power of `X` in `p`-/ def leading_coeff (p : polynomial R) : R := coeff p (nat_degree p) /-- a polynomial is `monic` if its leading coefficient is 1 -/ def monic (p : polynomial R) := leading_coeff p = (1 : R) @[nontriviality] lemma monic_of_subsingleton [subsingleton R] (p : polynomial R) : monic p := subsingleton.elim _ _ lemma monic.def : monic p ↔ leading_coeff p = 1 := iff.rfl instance monic.decidable [decidable_eq R] : decidable (monic p) := by unfold monic; apply_instance @[simp] lemma monic.leading_coeff {p : polynomial R} (hp : p.monic) : leading_coeff p = 1 := hp lemma monic.coeff_nat_degree {p : polynomial R} (hp : p.monic) : p.coeff p.nat_degree = 1 := hp @[simp] lemma degree_zero : degree (0 : polynomial R) = ⊥ := rfl @[simp] lemma nat_degree_zero : nat_degree (0 : polynomial R) = 0 := rfl @[simp] lemma coeff_nat_degree : coeff p (nat_degree p) = leading_coeff p := rfl lemma degree_eq_bot : degree p = ⊥ ↔ p = 0 := ⟨λ h, by rw [degree, ← max_eq_sup_with_bot] at h; exact support_eq_empty.1 (max_eq_none.1 h), λ h, h.symm ▸ rfl⟩ @[nontriviality] lemma degree_of_subsingleton [subsingleton R] : degree p = ⊥ := by rw [subsingleton.elim p 0, degree_zero] @[nontriviality] lemma nat_degree_of_subsingleton [subsingleton R] : nat_degree p = 0 := by rw [subsingleton.elim p 0, nat_degree_zero] lemma degree_eq_nat_degree (hp : p ≠ 0) : degree p = (nat_degree p : with_bot ℕ) := let ⟨n, hn⟩ := not_forall.1 (mt option.eq_none_iff_forall_not_mem.2 (mt degree_eq_bot.1 hp)) in have hn : degree p = some n := not_not.1 hn, by rw [nat_degree, hn]; refl lemma degree_eq_iff_nat_degree_eq {p : polynomial R} {n : ℕ} (hp : p ≠ 0) : p.degree = n ↔ p.nat_degree = n := by rw [degree_eq_nat_degree hp, with_bot.coe_eq_coe] lemma degree_eq_iff_nat_degree_eq_of_pos {p : polynomial R} {n : ℕ} (hn : 0 < n) : p.degree = n ↔ p.nat_degree = n := begin split, { intro H, rwa ← degree_eq_iff_nat_degree_eq, rintro rfl, rw degree_zero at H, exact option.no_confusion H }, { intro H, rwa degree_eq_iff_nat_degree_eq, rintro rfl, rw nat_degree_zero at H, rw H at hn, exact lt_irrefl _ hn } end lemma nat_degree_eq_of_degree_eq_some {p : polynomial R} {n : ℕ} (h : degree p = n) : nat_degree p = n := have hp0 : p ≠ 0, from λ hp0, by rw hp0 at h; exact option.no_confusion h, option.some_inj.1 $ show (nat_degree p : with_bot ℕ) = n, by rwa [← degree_eq_nat_degree hp0] @[simp] lemma degree_le_nat_degree : degree p ≤ nat_degree p := with_bot.gi_get_or_else_bot.gc.le_u_l _ lemma nat_degree_eq_of_degree_eq [semiring S] {q : polynomial S} (h : degree p = degree q) : nat_degree p = nat_degree q := by unfold nat_degree; rw h lemma le_degree_of_ne_zero (h : coeff p n ≠ 0) : (n : with_bot ℕ) ≤ degree p := show @has_le.le (with_bot ℕ) _ (some n : with_bot ℕ) (p.support.sup some : with_bot ℕ), from finset.le_sup (finsupp.mem_support_iff.2 h) lemma le_nat_degree_of_ne_zero (h : coeff p n ≠ 0) : n ≤ nat_degree p := begin rw [← with_bot.coe_le_coe, ← degree_eq_nat_degree], exact le_degree_of_ne_zero h, { assume h, subst h, exact h rfl } end lemma le_nat_degree_of_mem_supp (a : ℕ) : a ∈ p.support → a ≤ nat_degree p:= le_nat_degree_of_ne_zero ∘ mem_support_iff_coeff_ne_zero.mp lemma supp_subset_range (h : nat_degree p < m) : p.support ⊆ finset.range m := λ n hn, mem_range.2 $ (le_nat_degree_of_mem_supp _ hn).trans_lt h lemma supp_subset_range_nat_degree_succ : p.support ⊆ finset.range (nat_degree p + 1) := supp_subset_range (nat.lt_succ_self _) lemma degree_le_degree (h : coeff q (nat_degree p) ≠ 0) : degree p ≤ degree q := begin by_cases hp : p = 0, { rw hp, exact bot_le }, { rw degree_eq_nat_degree hp, exact le_degree_of_ne_zero h } end lemma degree_ne_of_nat_degree_ne {n : ℕ} : p.nat_degree ≠ n → degree p ≠ n := mt $ λ h, by rw [nat_degree, h, option.get_or_else_coe] theorem nat_degree_le_iff_degree_le {n : ℕ} : nat_degree p ≤ n ↔ degree p ≤ n := with_bot.get_or_else_bot_le_iff alias polynomial.nat_degree_le_iff_degree_le ↔ . . lemma nat_degree_le_nat_degree (hpq : p.degree ≤ q.degree) : p.nat_degree ≤ q.nat_degree := with_bot.gi_get_or_else_bot.gc.monotone_l hpq @[simp] lemma degree_C (ha : a ≠ 0) : degree (C a) = (0 : with_bot ℕ) := show sup (ite (a = 0) ∅ {0}) some = 0, by rw if_neg ha; refl lemma degree_C_le : degree (C a) ≤ (0 : with_bot ℕ) := by by_cases h : a = 0; [rw [h, C_0], rw [degree_C h]]; [exact bot_le, exact le_refl _] lemma degree_one_le : degree (1 : polynomial R) ≤ (0 : with_bot ℕ) := by rw [← C_1]; exact degree_C_le @[simp] lemma nat_degree_C (a : R) : nat_degree (C a) = 0 := begin by_cases ha : a = 0, { have : C a = 0, { rw [ha, C_0] }, rw [nat_degree, degree_eq_bot.2 this], refl }, { rw [nat_degree, degree_C ha], refl } end @[simp] lemma nat_degree_one : nat_degree (1 : polynomial R) = 0 := nat_degree_C 1 @[simp] lemma nat_degree_nat_cast (n : ℕ) : nat_degree (n : polynomial R) = 0 := by simp only [←C_eq_nat_cast, nat_degree_C] @[simp] lemma degree_monomial (n : ℕ) (ha : a ≠ 0) : degree (monomial n a) = n := by rw [degree, support_monomial _ _ ha]; refl @[simp] lemma degree_C_mul_X_pow (n : ℕ) (ha : a ≠ 0) : degree (C a * X ^ n) = n := by rw [← single_eq_C_mul_X, degree_monomial n ha] lemma degree_monomial_le (n : ℕ) (a : R) : degree (monomial n a) ≤ n := if h : a = 0 then by rw [h, (monomial n).map_zero]; exact bot_le else le_of_eq (degree_monomial n h) lemma degree_C_mul_X_pow_le (n : ℕ) (a : R) : degree (C a * X ^ n) ≤ n := by { rw C_mul_X_pow_eq_monomial, apply degree_monomial_le } @[simp] lemma nat_degree_C_mul_X_pow (n : ℕ) (a : R) (ha : a ≠ 0) : nat_degree (C a * X ^ n) = n := nat_degree_eq_of_degree_eq_some (degree_C_mul_X_pow n ha) @[simp] lemma nat_degree_C_mul_X (a : R) (ha : a ≠ 0) : nat_degree (C a * X) = 1 := by simpa only [pow_one] using nat_degree_C_mul_X_pow 1 a ha @[simp] lemma nat_degree_monomial (i : ℕ) (r : R) (hr : r ≠ 0) : nat_degree (monomial i r) = i := by rw [← C_mul_X_pow_eq_monomial, nat_degree_C_mul_X_pow i r hr] lemma coeff_eq_zero_of_degree_lt (h : degree p < n) : coeff p n = 0 := not_not.1 (mt le_degree_of_ne_zero (not_le_of_gt h)) lemma coeff_eq_zero_of_nat_degree_lt {p : polynomial R} {n : ℕ} (h : p.nat_degree < n) : p.coeff n = 0 := begin apply coeff_eq_zero_of_degree_lt, by_cases hp : p = 0, { subst hp, exact with_bot.bot_lt_coe n }, { rwa [degree_eq_nat_degree hp, with_bot.coe_lt_coe] } end @[simp] lemma coeff_nat_degree_succ_eq_zero {p : polynomial R} : p.coeff (p.nat_degree + 1) = 0 := coeff_eq_zero_of_nat_degree_lt (lt_add_one _) -- We need the explicit `decidable` argument here because an exotic one shows up in a moment! lemma ite_le_nat_degree_coeff (p : polynomial R) (n : ℕ) (I : decidable (n < 1 + nat_degree p)) : @ite (n < 1 + nat_degree p) I _ (coeff p n) 0 = coeff p n := begin split_ifs, { refl }, { exact (coeff_eq_zero_of_nat_degree_lt (not_le.1 (λ w, h (nat.lt_one_add_iff.2 w)))).symm, } end lemma as_sum_support (p : polynomial R) : p = ∑ i in p.support, monomial i (p.coeff i) := p.sum_single.symm lemma as_sum_support_C_mul_X_pow (p : polynomial R) : p = ∑ i in p.support, C (p.coeff i) * X^i := trans p.as_sum_support $ by simp only [C_mul_X_pow_eq_monomial] /-- We can reexpress a sum over `p.support` as a sum over `range n`, for any `n` satisfying `p.nat_degree < n`. -/ lemma sum_over_range' [add_comm_monoid S] (p : polynomial R) {f : ℕ → R → S} (h : ∀ n, f n 0 = 0) (n : ℕ) (w : p.nat_degree < n) : p.sum f = ∑ (a : ℕ) in range n, f a (coeff p a) := finsupp.sum_of_support_subset _ (supp_subset_range w) _ $ λ n hn, h n /-- We can reexpress a sum over `p.support` as a sum over `range (p.nat_degree + 1)`. -/ lemma sum_over_range [add_comm_monoid S] (p : polynomial R) {f : ℕ → R → S} (h : ∀ n, f n 0 = 0) : p.sum f = ∑ (a : ℕ) in range (p.nat_degree + 1), f a (coeff p a) := sum_over_range' p h (p.nat_degree + 1) (lt_add_one _) lemma as_sum_range' (p : polynomial R) (n : ℕ) (w : p.nat_degree < n) : p = ∑ i in range n, monomial i (coeff p i) := p.sum_single.symm.trans $ p.sum_over_range' (λ n, single_zero) _ w lemma as_sum_range (p : polynomial R) : p = ∑ i in range (p.nat_degree + 1), monomial i (coeff p i) := p.sum_single.symm.trans $ p.sum_over_range $ λ n, single_zero lemma as_sum_range_C_mul_X_pow (p : polynomial R) : p = ∑ i in range (p.nat_degree + 1), C (coeff p i) * X ^ i := p.as_sum_range.trans $ by simp only [C_mul_X_pow_eq_monomial] lemma coeff_ne_zero_of_eq_degree (hn : degree p = n) : coeff p n ≠ 0 := λ h, mem_support_iff.mp (mem_of_max hn) h lemma eq_X_add_C_of_degree_le_one (h : degree p ≤ 1) : p = C (p.coeff 1) * X + C (p.coeff 0) := ext (λ n, nat.cases_on n (by simp) (λ n, nat.cases_on n (by simp [coeff_C]) (λ m, have degree p < m.succ.succ, from lt_of_le_of_lt h dec_trivial, by simp [coeff_eq_zero_of_degree_lt this, coeff_C, nat.succ_ne_zero, coeff_X, nat.succ_inj', @eq_comm ℕ 0]))) lemma eq_X_add_C_of_degree_eq_one (h : degree p = 1) : p = C (p.leading_coeff) * X + C (p.coeff 0) := (eq_X_add_C_of_degree_le_one (show degree p ≤ 1, from h ▸ le_refl _)).trans (by simp [leading_coeff, nat_degree_eq_of_degree_eq_some h]) lemma eq_X_add_C_of_nat_degree_le_one (h : nat_degree p ≤ 1) : p = C (p.coeff 1) * X + C (p.coeff 0) := eq_X_add_C_of_degree_le_one $ degree_le_of_nat_degree_le h lemma exists_eq_X_add_C_of_nat_degree_le_one (h : nat_degree p ≤ 1) : ∃ a b, p = C a * X + C b := ⟨p.coeff 1, p.coeff 0, eq_X_add_C_of_nat_degree_le_one h⟩ theorem degree_X_pow_le (n : ℕ) : degree (X^n : polynomial R) ≤ n := by simpa only [C_1, one_mul] using degree_C_mul_X_pow_le n (1:R) theorem degree_X_le : degree (X : polynomial R) ≤ 1 := degree_monomial_le _ _ lemma nat_degree_X_le : (X : polynomial R).nat_degree ≤ 1 := nat_degree_le_of_degree_le degree_X_le lemma support_C_mul_X_pow (c : R) (n : ℕ) : (C c * X ^ n).support ⊆ singleton n := begin rw [C_mul_X_pow_eq_monomial], exact support_single_subset end lemma mem_support_C_mul_X_pow {n a : ℕ} {c : R} (h : a ∈ (C c * X ^ n).support) : a = n := mem_singleton.1 $ support_C_mul_X_pow _ _ h lemma card_support_C_mul_X_pow_le_one {c : R} {n : ℕ} : (C c * X ^ n).support.card ≤ 1 := begin rw ← card_singleton n, apply card_le_of_subset (support_C_mul_X_pow c n), end lemma card_supp_le_succ_nat_degree (p : polynomial R) : p.support.card ≤ p.nat_degree + 1 := begin rw ← finset.card_range (p.nat_degree + 1), exact finset.card_le_of_subset supp_subset_range_nat_degree_succ, end lemma le_degree_of_mem_supp (a : ℕ) : a ∈ p.support → ↑a ≤ degree p := le_degree_of_ne_zero ∘ mem_support_iff_coeff_ne_zero.mp lemma nonempty_support_iff : p.support.nonempty ↔ p ≠ 0 := by rw [ne.def, nonempty_iff_ne_empty, ne.def, ← support_eq_empty] lemma support_C_mul_X_pow_nonzero {c : R} {n : ℕ} (h : c ≠ 0) : (C c * X ^ n).support = singleton n := begin rw [C_mul_X_pow_eq_monomial], exact support_single_ne_zero h end end semiring section nonzero_semiring variables [semiring R] [nontrivial R] {p q : polynomial R} @[simp] lemma degree_one : degree (1 : polynomial R) = (0 : with_bot ℕ) := degree_C (show (1 : R) ≠ 0, from zero_ne_one.symm) @[simp] lemma degree_X : degree (X : polynomial R) = 1 := degree_monomial _ one_ne_zero @[simp] lemma nat_degree_X : (X : polynomial R).nat_degree = 1 := nat_degree_eq_of_degree_eq_some degree_X end nonzero_semiring section ring variables [ring R] lemma coeff_mul_X_sub_C {p : polynomial R} {r : R} {a : ℕ} : coeff (p * (X - C r)) (a + 1) = coeff p a - coeff p (a + 1) * r := by simp [mul_sub] lemma C_eq_int_cast (n : ℤ) : C (n : R) = n := (C : R →+* _).map_int_cast n @[simp] lemma degree_neg (p : polynomial R) : degree (-p) = degree p := by unfold degree; rw support_neg @[simp] lemma nat_degree_neg (p : polynomial R) : nat_degree (-p) = nat_degree p := by simp [nat_degree] @[simp] lemma nat_degree_int_cast (n : ℤ) : nat_degree (n : polynomial R) = 0 := by simp only [←C_eq_int_cast, nat_degree_C] end ring section semiring variables [semiring R] /-- The second-highest coefficient, or 0 for constants -/ def next_coeff (p : polynomial R) : R := if p.nat_degree = 0 then 0 else p.coeff (p.nat_degree - 1) @[simp] lemma next_coeff_C_eq_zero (c : R) : next_coeff (C c) = 0 := by { rw next_coeff, simp } lemma next_coeff_of_pos_nat_degree (p : polynomial R) (hp : 0 < p.nat_degree) : next_coeff p = p.coeff (p.nat_degree - 1) := by { rw [next_coeff, if_neg], contrapose! hp, simpa } end semiring section semiring variables [semiring R] {p q : polynomial R} {ι : Type*} lemma coeff_nat_degree_eq_zero_of_degree_lt (h : degree p < degree q) : coeff p (nat_degree q) = 0 := coeff_eq_zero_of_degree_lt (lt_of_lt_of_le h degree_le_nat_degree) lemma ne_zero_of_degree_gt {n : with_bot ℕ} (h : n < degree p) : p ≠ 0 := mt degree_eq_bot.2 (ne.symm (ne_of_lt (lt_of_le_of_lt bot_le h))) lemma eq_C_of_degree_le_zero (h : degree p ≤ 0) : p = C (coeff p 0) := begin ext (_|n), { simp }, rw [coeff_C, if_neg (nat.succ_ne_zero _), coeff_eq_zero_of_degree_lt], exact h.trans_lt (with_bot.some_lt_some.2 n.succ_pos), end lemma eq_C_of_degree_eq_zero (h : degree p = 0) : p = C (coeff p 0) := eq_C_of_degree_le_zero (h ▸ le_refl _) lemma degree_le_zero_iff : degree p ≤ 0 ↔ p = C (coeff p 0) := ⟨eq_C_of_degree_le_zero, λ h, h.symm ▸ degree_C_le⟩ lemma degree_add_le (p q : polynomial R) : degree (p + q) ≤ max (degree p) (degree q) := calc degree (p + q) = ((p + q).support).sup some : rfl ... ≤ (p.support ∪ q.support).sup some : by convert sup_mono support_add ... = p.support.sup some ⊔ q.support.sup some : by convert sup_union ... = _ : with_bot.sup_eq_max _ _ @[simp] lemma leading_coeff_zero : leading_coeff (0 : polynomial R) = 0 := rfl @[simp] lemma leading_coeff_eq_zero : leading_coeff p = 0 ↔ p = 0 := ⟨λ h, by_contradiction $ λ hp, mt mem_support_iff.1 (not_not.2 h) (mem_of_max (degree_eq_nat_degree hp)), λ h, h.symm ▸ leading_coeff_zero⟩ lemma leading_coeff_eq_zero_iff_deg_eq_bot : leading_coeff p = 0 ↔ degree p = ⊥ := by rw [leading_coeff_eq_zero, degree_eq_bot] lemma nat_degree_mem_support_of_nonzero (H : p ≠ 0) : p.nat_degree ∈ p.support := (p.mem_support_to_fun p.nat_degree).mpr ((not_congr leading_coeff_eq_zero).mpr H) lemma nat_degree_eq_support_max' (h : p ≠ 0) : p.nat_degree = p.support.max' (nonempty_support_iff.mpr h) := begin apply le_antisymm, { apply finset.le_max', rw mem_support_iff_coeff_ne_zero, exact (not_congr leading_coeff_eq_zero).mpr h, }, { apply max'_le, refine le_nat_degree_of_mem_supp, }, end lemma nat_degree_C_mul_X_pow_le (a : R) (n : ℕ) : nat_degree (C a * X ^ n) ≤ n := nat_degree_le_iff_degree_le.2 $ degree_C_mul_X_pow_le _ _ lemma degree_add_eq_left_of_degree_lt (h : degree q < degree p) : degree (p + q) = degree p := le_antisymm (max_eq_left_of_lt h ▸ degree_add_le _ _) $ degree_le_degree $ begin rw [coeff_add, coeff_nat_degree_eq_zero_of_degree_lt h, add_zero], exact mt leading_coeff_eq_zero.1 (ne_zero_of_degree_gt h) end lemma degree_add_eq_right_of_degree_lt (h : degree p < degree q) : degree (p + q) = degree q := by rw [add_comm, degree_add_eq_left_of_degree_lt h] lemma degree_add_C (hp : 0 < degree p) : degree (p + C a) = degree p := add_comm (C a) p ▸ degree_add_eq_right_of_degree_lt $ lt_of_le_of_lt degree_C_le hp lemma degree_add_eq_of_leading_coeff_add_ne_zero (h : leading_coeff p + leading_coeff q ≠ 0) : degree (p + q) = max p.degree q.degree := le_antisymm (degree_add_le _ _) $ match lt_trichotomy (degree p) (degree q) with | or.inl hlt := by rw [degree_add_eq_right_of_degree_lt hlt, max_eq_right_of_lt hlt]; exact le_refl _ | or.inr (or.inl heq) := le_of_not_gt $ assume hlt : max (degree p) (degree q) > degree (p + q), h $ show leading_coeff p + leading_coeff q = 0, begin rw [heq, max_self] at hlt, rw [leading_coeff, leading_coeff, nat_degree_eq_of_degree_eq heq, ← coeff_add], exact coeff_nat_degree_eq_zero_of_degree_lt hlt end | or.inr (or.inr hlt) := by rw [degree_add_eq_left_of_degree_lt hlt, max_eq_left_of_lt hlt]; exact le_refl _ end lemma degree_erase_le (p : polynomial R) (n : ℕ) : degree (p.erase n) ≤ degree p := by convert sup_mono (erase_subset _ _) lemma degree_erase_lt (hp : p ≠ 0) : degree (p.erase (nat_degree p)) < degree p := lt_of_le_of_ne (degree_erase_le _ _) $ (degree_eq_nat_degree hp).symm ▸ (by convert λ h, not_mem_erase _ _ (mem_of_max h)) lemma degree_sum_le (s : finset ι) (f : ι → polynomial R) : degree (∑ i in s, f i) ≤ s.sup (λ b, degree (f b)) := finset.induction_on s (by simp only [sum_empty, sup_empty, degree_zero, le_refl]) $ assume a s has ih, calc degree (∑ i in insert a s, f i) ≤ max (degree (f a)) (degree (∑ i in s, f i)) : by rw sum_insert has; exact degree_add_le _ _ ... ≤ _ : by rw [sup_insert, with_bot.sup_eq_max]; exact max_le_max (le_refl _) ih lemma degree_mul_le (p q : polynomial R) : degree (p * q) ≤ degree p + degree q := calc degree (p * q) ≤ (p.support).sup (λi, degree (sum q (λj a, C (coeff p i * a) * X ^ (i + j)))) : by simp only [single_eq_C_mul_X.symm]; exact degree_sum_le _ _ ... ≤ p.support.sup (λi, q.support.sup (λj, degree (C (coeff p i * coeff q j) * X ^ (i + j)))) : finset.sup_mono_fun (assume i hi, degree_sum_le _ _) ... ≤ degree p + degree q : begin refine finset.sup_le (λ a ha, finset.sup_le (λ b hb, le_trans (degree_C_mul_X_pow_le _ _) _)), rw [with_bot.coe_add], rw mem_support_iff at ha hb, exact add_le_add (le_degree_of_ne_zero ha) (le_degree_of_ne_zero hb) end lemma degree_pow_le (p : polynomial R) : ∀ n, degree (p ^ n) ≤ n •ℕ (degree p) | 0 := by rw [pow_zero, zero_nsmul]; exact degree_one_le | (n+1) := calc degree (p ^ (n + 1)) ≤ degree p + degree (p ^ n) : by rw pow_succ; exact degree_mul_le _ _ ... ≤ _ : by rw succ_nsmul; exact add_le_add (le_refl _) (degree_pow_le _) @[simp] lemma leading_coeff_monomial (a : R) (n : ℕ) : leading_coeff (monomial n a) = a := begin by_cases ha : a = 0, { simp only [ha, (monomial n).map_zero, leading_coeff_zero] }, { rw [leading_coeff, nat_degree_monomial _ _ ha], exact @finsupp.single_eq_same _ _ _ n a } end lemma leading_coeff_C_mul_X_pow (a : R) (n : ℕ) : leading_coeff (C a * X ^ n) = a := by rw [C_mul_X_pow_eq_monomial, leading_coeff_monomial] @[simp] lemma leading_coeff_C (a : R) : leading_coeff (C a) = a := leading_coeff_monomial a 0 @[simp] lemma leading_coeff_X_pow (n : ℕ) : leading_coeff ((X : polynomial R) ^ n) = 1 := by simpa only [C_1, one_mul] using leading_coeff_C_mul_X_pow (1 : R) n @[simp] lemma leading_coeff_X : leading_coeff (X : polynomial R) = 1 := by simpa only [pow_one] using @leading_coeff_X_pow R _ 1 @[simp] lemma monic_X_pow (n : ℕ) : monic (X ^ n : polynomial R) := leading_coeff_X_pow n @[simp] lemma monic_X : monic (X : polynomial R) := leading_coeff_X @[simp] lemma leading_coeff_one : leading_coeff (1 : polynomial R) = 1 := leading_coeff_C 1 @[simp] lemma monic_one : monic (1 : polynomial R) := leading_coeff_C _ lemma monic.ne_zero {R : Type*} [semiring R] [nontrivial R] {p : polynomial R} (hp : p.monic) : p ≠ 0 := by { rintro rfl, simpa [monic] using hp } lemma monic.ne_zero_of_ne (h : (0:R) ≠ 1) {p : polynomial R} (hp : p.monic) : p ≠ 0 := by { nontriviality R, exact hp.ne_zero } lemma monic.ne_zero_of_polynomial_ne {r} (hp : monic p) (hne : q ≠ r) : p ≠ 0 := by { haveI := nontrivial.of_polynomial_ne hne, exact hp.ne_zero } lemma leading_coeff_add_of_degree_lt (h : degree p < degree q) : leading_coeff (p + q) = leading_coeff q := have coeff p (nat_degree q) = 0, from coeff_nat_degree_eq_zero_of_degree_lt h, by simp only [leading_coeff, nat_degree_eq_of_degree_eq (degree_add_eq_right_of_degree_lt h), this, coeff_add, zero_add] lemma leading_coeff_add_of_degree_eq (h : degree p = degree q) (hlc : leading_coeff p + leading_coeff q ≠ 0) : leading_coeff (p + q) = leading_coeff p + leading_coeff q := have nat_degree (p + q) = nat_degree p, by apply nat_degree_eq_of_degree_eq; rw [degree_add_eq_of_leading_coeff_add_ne_zero hlc, h, max_self], by simp only [leading_coeff, this, nat_degree_eq_of_degree_eq h, coeff_add] @[simp] lemma coeff_mul_degree_add_degree (p q : polynomial R) : coeff (p * q) (nat_degree p + nat_degree q) = leading_coeff p * leading_coeff q := calc coeff (p * q) (nat_degree p + nat_degree q) = ∑ x in nat.antidiagonal (nat_degree p + nat_degree q), coeff p x.1 * coeff q x.2 : coeff_mul _ _ _ ... = coeff p (nat_degree p) * coeff q (nat_degree q) : begin refine finset.sum_eq_single (nat_degree p, nat_degree q) _ _, { rintro ⟨i,j⟩ h₁ h₂, rw nat.mem_antidiagonal at h₁, by_cases H : nat_degree p < i, { rw [coeff_eq_zero_of_degree_lt (lt_of_le_of_lt degree_le_nat_degree (with_bot.coe_lt_coe.2 H)), zero_mul] }, { rw not_lt_iff_eq_or_lt at H, cases H, { subst H, rw add_left_cancel_iff at h₁, dsimp at h₁, subst h₁, exfalso, exact h₂ rfl }, { suffices : nat_degree q < j, { rw [coeff_eq_zero_of_degree_lt (lt_of_le_of_lt degree_le_nat_degree (with_bot.coe_lt_coe.2 this)), mul_zero] }, { by_contra H', rw not_lt at H', exact ne_of_lt (nat.lt_of_lt_of_le (nat.add_lt_add_right H j) (nat.add_le_add_left H' _)) h₁ } } } }, { intro H, exfalso, apply H, rw nat.mem_antidiagonal } end lemma degree_mul' (h : leading_coeff p * leading_coeff q ≠ 0) : degree (p * q) = degree p + degree q := have hp : p ≠ 0 := by refine mt _ h; exact λ hp, by rw [hp, leading_coeff_zero, zero_mul], have hq : q ≠ 0 := by refine mt _ h; exact λ hq, by rw [hq, leading_coeff_zero, mul_zero], le_antisymm (degree_mul_le _ _) begin rw [degree_eq_nat_degree hp, degree_eq_nat_degree hq], refine le_degree_of_ne_zero _, rwa coeff_mul_degree_add_degree end lemma degree_mul_monic (hq : monic q) : degree (p * q) = degree p + degree q := if hp : p = 0 then by simp [hp] else degree_mul' $ by rwa [hq.leading_coeff, mul_one, ne.def, leading_coeff_eq_zero] lemma nat_degree_mul' (h : leading_coeff p * leading_coeff q ≠ 0) : nat_degree (p * q) = nat_degree p + nat_degree q := have hp : p ≠ 0 := mt leading_coeff_eq_zero.2 (λ h₁, h $ by rw [h₁, zero_mul]), have hq : q ≠ 0 := mt leading_coeff_eq_zero.2 (λ h₁, h $ by rw [h₁, mul_zero]), nat_degree_eq_of_degree_eq_some $ by rw [degree_mul' h, with_bot.coe_add, degree_eq_nat_degree hp, degree_eq_nat_degree hq] lemma leading_coeff_mul' (h : leading_coeff p * leading_coeff q ≠ 0) : leading_coeff (p * q) = leading_coeff p * leading_coeff q := begin unfold leading_coeff, rw [nat_degree_mul' h, coeff_mul_degree_add_degree], refl end lemma leading_coeff_pow' : leading_coeff p ^ n ≠ 0 → leading_coeff (p ^ n) = leading_coeff p ^ n := nat.rec_on n (by simp) $ λ n ih h, have h₁ : leading_coeff p ^ n ≠ 0 := λ h₁, h $ by rw [pow_succ, h₁, mul_zero], have h₂ : leading_coeff p * leading_coeff (p ^ n) ≠ 0 := by rwa [pow_succ, ← ih h₁] at h, by rw [pow_succ, pow_succ, leading_coeff_mul' h₂, ih h₁] lemma degree_pow' : ∀ {n}, leading_coeff p ^ n ≠ 0 → degree (p ^ n) = n •ℕ (degree p) | 0 := λ h, by rw [pow_zero, ← C_1] at *; rw [degree_C h, zero_nsmul] | (n+1) := λ h, have h₁ : leading_coeff p ^ n ≠ 0 := λ h₁, h $ by rw [pow_succ, h₁, mul_zero], have h₂ : leading_coeff p * leading_coeff (p ^ n) ≠ 0 := by rwa [pow_succ, ← leading_coeff_pow' h₁] at h, by rw [pow_succ, degree_mul' h₂, succ_nsmul, degree_pow' h₁] lemma nat_degree_pow' {n : ℕ} (h : leading_coeff p ^ n ≠ 0) : nat_degree (p ^ n) = n * nat_degree p := if hp0 : p = 0 then if hn0 : n = 0 then by simp * else by rw [hp0, zero_pow (nat.pos_of_ne_zero hn0)]; simp else have hpn : p ^ n ≠ 0, from λ hpn0, have h1 : _ := h, by rw [← leading_coeff_pow' h1, hpn0, leading_coeff_zero] at h; exact h rfl, option.some_inj.1 $ show (nat_degree (p ^ n) : with_bot ℕ) = (n * nat_degree p : ℕ), by rw [← degree_eq_nat_degree hpn, degree_pow' h, degree_eq_nat_degree hp0, ← with_bot.coe_nsmul]; simp theorem leading_coeff_mul_monic {p q : polynomial R} (hq : monic q) : leading_coeff (p * q) = leading_coeff p := decidable.by_cases (λ H : leading_coeff p = 0, by rw [H, leading_coeff_eq_zero.1 H, zero_mul, leading_coeff_zero]) (λ H : leading_coeff p ≠ 0, by rw [leading_coeff_mul', hq.leading_coeff, mul_one]; rwa [hq.leading_coeff, mul_one]) @[simp] theorem leading_coeff_mul_X_pow {p : polynomial R} {n : ℕ} : leading_coeff (p * X ^ n) = leading_coeff p := leading_coeff_mul_monic (monic_X_pow n) @[simp] theorem leading_coeff_mul_X {p : polynomial R} : leading_coeff (p * X) = leading_coeff p := leading_coeff_mul_monic monic_X lemma nat_degree_mul_le {p q : polynomial R} : nat_degree (p * q) ≤ nat_degree p + nat_degree q := begin apply nat_degree_le_of_degree_le, apply le_trans (degree_mul_le p q), rw with_bot.coe_add, refine add_le_add _ _; apply degree_le_nat_degree, end lemma subsingleton_of_monic_zero (h : monic (0 : polynomial R)) : (∀ p q : polynomial R, p = q) ∧ (∀ a b : R, a = b) := by rw [monic.def, leading_coeff_zero] at h; exact ⟨λ p q, by rw [← mul_one p, ← mul_one q, ← C_1, ← h, C_0, mul_zero, mul_zero], λ a b, by rw [← mul_one a, ← mul_one b, ← h, mul_zero, mul_zero]⟩ lemma zero_le_degree_iff {p : polynomial R} : 0 ≤ degree p ↔ p ≠ 0 := by rw [ne.def, ← degree_eq_bot]; cases degree p; exact dec_trivial lemma degree_nonneg_iff_ne_zero : 0 ≤ degree p ↔ p ≠ 0 := ⟨λ h0p hp0, absurd h0p (by rw [hp0, degree_zero]; exact dec_trivial), λ hp0, le_of_not_gt (λ h, by simp [gt, degree_eq_bot, *] at *)⟩ lemma nat_degree_eq_zero_iff_degree_le_zero : p.nat_degree = 0 ↔ p.degree ≤ 0 := by rw [← nonpos_iff_eq_zero, nat_degree_le_iff_degree_le, with_bot.coe_zero] theorem degree_le_iff_coeff_zero (f : polynomial R) (n : with_bot ℕ) : degree f ≤ n ↔ ∀ m : ℕ, n < m → coeff f m = 0 := ⟨λ (H : finset.sup (f.support) some ≤ n) m (Hm : n < (m : with_bot ℕ)), decidable.of_not_not $ λ H4, have H1 : m ∉ f.support, from λ H2, not_lt_of_ge ((finset.sup_le_iff.1 H) m H2 : ((m : with_bot ℕ) ≤ n)) Hm, H1 $ (finsupp.mem_support_to_fun f m).2 H4, λ H, finset.sup_le $ λ b Hb, decidable.of_not_not $ λ Hn, (finsupp.mem_support_to_fun f b).1 Hb $ H b $ lt_of_not_ge Hn⟩ theorem degree_lt_iff_coeff_zero (f : polynomial R) (n : ℕ) : degree f < n ↔ ∀ m : ℕ, n ≤ m → coeff f m = 0 := begin refine ⟨λ hf m hm, coeff_eq_zero_of_degree_lt (lt_of_lt_of_le hf (with_bot.coe_le_coe.2 hm)), _⟩, simp only [degree, finset.sup_lt_iff (with_bot.bot_lt_coe n), mem_support_iff, with_bot.some_eq_coe, with_bot.coe_lt_coe, ← @not_le ℕ], exact λ h m, mt (h m), end lemma degree_lt_degree_mul_X (hp : p ≠ 0) : p.degree < (p * X).degree := by haveI := nontrivial.of_polynomial_ne hp; exact have leading_coeff p * leading_coeff X ≠ 0, by simpa, by erw [degree_mul' this, degree_eq_nat_degree hp, degree_X, ← with_bot.coe_one, ← with_bot.coe_add, with_bot.coe_lt_coe]; exact nat.lt_succ_self _ lemma nat_degree_pos_iff_degree_pos {p : polynomial R} : 0 < nat_degree p ↔ 0 < degree p := lt_iff_lt_of_le_iff_le nat_degree_le_iff_degree_le lemma eq_C_of_nat_degree_le_zero {p : polynomial R} (h : nat_degree p ≤ 0) : p = C (coeff p 0) := eq_C_of_degree_le_zero $ degree_le_of_nat_degree_le h lemma eq_C_of_nat_degree_eq_zero {p : polynomial R} (h : nat_degree p = 0) : p = C (coeff p 0) := eq_C_of_nat_degree_le_zero h.le end semiring section nonzero_semiring variables [semiring R] [nontrivial R] {p q : polynomial R} @[simp] lemma degree_X_pow (n : ℕ) : degree ((X : polynomial R) ^ n) = n := by rw [X_pow_eq_monomial, degree_monomial _ (@one_ne_zero R _ _)] @[simp] lemma nat_degree_X_pow (n : ℕ) : nat_degree ((X : polynomial R) ^ n) = n := nat_degree_eq_of_degree_eq_some (degree_X_pow n) theorem not_is_unit_X : ¬ is_unit (X : polynomial R) := λ ⟨⟨_, g, hfg, hgf⟩, rfl⟩, @zero_ne_one R _ _ $ by { rw [← coeff_one_zero, ← hgf], simp } @[simp] lemma degree_mul_X : degree (p * X) = degree p + 1 := by simp [degree_mul_monic monic_X] @[simp] lemma degree_mul_X_pow : degree (p * X ^ n) = degree p + n := by simp [degree_mul_monic (monic_X_pow n)] end nonzero_semiring section ring variables [ring R] {p q : polynomial R} lemma degree_sub_le (p q : polynomial R) : degree (p - q) ≤ max (degree p) (degree q) := by simpa only [sub_eq_add_neg, degree_neg q] using degree_add_le p (-q) lemma degree_sub_lt (hd : degree p = degree q) (hp0 : p ≠ 0) (hlc : leading_coeff p = leading_coeff q) : degree (p - q) < degree p := have hp : single (nat_degree p) (leading_coeff p) + p.erase (nat_degree p) = p := finsupp.single_add_erase _ _, have hq : single (nat_degree q) (leading_coeff q) + q.erase (nat_degree q) = q := finsupp.single_add_erase _ _, have hd' : nat_degree p = nat_degree q := by unfold nat_degree; rw hd, have hq0 : q ≠ 0 := mt degree_eq_bot.2 (hd ▸ mt degree_eq_bot.1 hp0), calc degree (p - q) = degree (erase (nat_degree q) p + -erase (nat_degree q) q) : by conv {to_lhs, rw [← hp, ← hq, hlc, hd', add_sub_add_left_eq_sub, sub_eq_add_neg]} ... ≤ max (degree (erase (nat_degree q) p)) (degree (erase (nat_degree q) q)) : degree_neg (erase (nat_degree q) q) ▸ degree_add_le _ _ ... < degree p : max_lt_iff.2 ⟨hd' ▸ degree_erase_lt hp0, hd.symm ▸ degree_erase_lt hq0⟩ lemma nat_degree_X_sub_C_le {r : R} : (X - C r).nat_degree ≤ 1 := nat_degree_le_iff_degree_le.2 $ le_trans (degree_sub_le _ _) $ max_le degree_X_le $ le_trans degree_C_le $ with_bot.coe_le_coe.2 zero_le_one lemma degree_sum_fin_lt {n : ℕ} (f : fin n → R) : degree (∑ i : fin n, C (f i) * X ^ (i : ℕ)) < n := begin haveI : is_commutative (with_bot ℕ) max := ⟨max_comm⟩, haveI : is_associative (with_bot ℕ) max := ⟨max_assoc⟩, calc (∑ i, C (f i) * X ^ (i : ℕ)).degree ≤ finset.univ.fold (⊔) ⊥ (λ i, (C (f i) * X ^ (i : ℕ)).degree) : degree_sum_le _ _ ... = finset.univ.fold max ⊥ (λ i, (C (f i) * X ^ (i : ℕ)).degree) : (@finset.fold_hom _ _ _ (⊔) _ _ _ ⊥ finset.univ _ _ _ id (with_bot.sup_eq_max)).symm ... < n : (finset.fold_max_lt (n : with_bot ℕ)).mpr ⟨with_bot.bot_lt_some _, _⟩, rintros ⟨i, hi⟩ -, calc (C (f ⟨i, hi⟩) * X ^ i).degree ≤ (C _).degree + (X ^ i).degree : degree_mul_le _ _ ... ≤ 0 + i : add_le_add degree_C_le (degree_X_pow_le i) ... = i : zero_add _ ... < n : with_bot.some_lt_some.mpr hi, end lemma degree_sub_eq_left_of_degree_lt (h : degree q < degree p) : degree (p - q) = degree p := by { rw ← degree_neg q at h, rw [sub_eq_add_neg, degree_add_eq_left_of_degree_lt h] } lemma degree_sub_eq_right_of_degree_lt (h : degree p < degree q) : degree (p - q) = degree q := by { rw ← degree_neg q at h, rw [sub_eq_add_neg, degree_add_eq_right_of_degree_lt h, degree_neg] } end ring section nonzero_ring variables [nontrivial R] [ring R] @[simp] lemma degree_X_sub_C (a : R) : degree (X - C a) = 1 := have degree (C a) < degree (X : polynomial R), from calc degree (C a) ≤ 0 : degree_C_le ... < 1 : with_bot.some_lt_some.mpr zero_lt_one ... = degree X : degree_X.symm, by rw [degree_sub_eq_left_of_degree_lt this, degree_X] @[simp] lemma nat_degree_X_sub_C (x : R) : (X - C x).nat_degree = 1 := nat_degree_eq_of_degree_eq_some $ degree_X_sub_C x @[simp] lemma next_coeff_X_sub_C (c : R) : next_coeff (X - C c) = - c := by simp [next_coeff_of_pos_nat_degree] lemma degree_X_pow_sub_C {n : ℕ} (hn : 0 < n) (a : R) : degree ((X : polynomial R) ^ n - C a) = n := have degree (C a) < degree ((X : polynomial R) ^ n), from calc degree (C a) ≤ 0 : degree_C_le ... < degree ((X : polynomial R) ^ n) : by rwa [degree_X_pow]; exact with_bot.coe_lt_coe.2 hn, by rw [degree_sub_eq_left_of_degree_lt this, degree_X_pow] lemma X_pow_sub_C_ne_zero {n : ℕ} (hn : 0 < n) (a : R) : (X : polynomial R) ^ n - C a ≠ 0 := mt degree_eq_bot.2 (show degree ((X : polynomial R) ^ n - C a) ≠ ⊥, by rw degree_X_pow_sub_C hn a; exact dec_trivial) theorem X_sub_C_ne_zero (r : R) : X - C r ≠ 0 := pow_one (X : polynomial R) ▸ X_pow_sub_C_ne_zero zero_lt_one r lemma nat_degree_X_pow_sub_C {n : ℕ} (hn : 0 < n) {r : R} : (X ^ n - C r).nat_degree = n := by { apply nat_degree_eq_of_degree_eq_some, simp [degree_X_pow_sub_C hn], } end nonzero_ring section integral_domain variables [integral_domain R] {p q : polynomial R} @[simp] lemma degree_mul : degree (p * q) = degree p + degree q := if hp0 : p = 0 then by simp only [hp0, degree_zero, zero_mul, with_bot.bot_add] else if hq0 : q = 0 then by simp only [hq0, degree_zero, mul_zero, with_bot.add_bot] else degree_mul' $ mul_ne_zero (mt leading_coeff_eq_zero.1 hp0) (mt leading_coeff_eq_zero.1 hq0) @[simp] lemma degree_pow (p : polynomial R) (n : ℕ) : degree (p ^ n) = n •ℕ (degree p) := by induction n; [simp only [pow_zero, degree_one, zero_nsmul], simp only [*, pow_succ, succ_nsmul, degree_mul]] @[simp] lemma leading_coeff_mul (p q : polynomial R) : leading_coeff (p * q) = leading_coeff p * leading_coeff q := begin by_cases hp : p = 0, { simp only [hp, zero_mul, leading_coeff_zero] }, { by_cases hq : q = 0, { simp only [hq, mul_zero, leading_coeff_zero] }, { rw [leading_coeff_mul'], exact mul_ne_zero (mt leading_coeff_eq_zero.1 hp) (mt leading_coeff_eq_zero.1 hq) } } end @[simp] lemma leading_coeff_X_add_C (a b : R) (ha : a ≠ 0): leading_coeff (C a * X + C b) = a := begin rw [add_comm, leading_coeff_add_of_degree_lt], { simp }, { simpa [degree_C ha] using lt_of_le_of_lt degree_C_le (with_bot.coe_lt_coe.2 zero_lt_one)} end /-- `polynomial.leading_coeff` bundled as a `monoid_hom` when `R` is an `integral_domain`, and thus `leading_coeff` is multiplicative -/ def leading_coeff_hom : polynomial R →* R := { to_fun := leading_coeff, map_one' := by simp, map_mul' := leading_coeff_mul } @[simp] lemma leading_coeff_hom_apply (p : polynomial R) : leading_coeff_hom p = leading_coeff p := rfl @[simp] lemma leading_coeff_pow (p : polynomial R) (n : ℕ) : leading_coeff (p ^ n) = leading_coeff p ^ n := leading_coeff_hom.map_pow p n end integral_domain end polynomial
a7d950b3428d42827efaeb5e7638691256a78e33
d1a52c3f208fa42c41df8278c3d280f075eb020c
/stage0/src/Lean/Compiler/IR/ExpandResetReuse.lean
14ded60811ed49caa3da1e9dc43b8d037e822052
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
10,026
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Compiler.IR.CompilerM import Lean.Compiler.IR.NormIds import Lean.Compiler.IR.FreeVars namespace Lean.IR.ExpandResetReuse /- Mapping from variable to projections -/ abbrev ProjMap := Std.HashMap VarId Expr namespace CollectProjMap abbrev Collector := ProjMap → ProjMap @[inline] def collectVDecl (x : VarId) (v : Expr) : Collector := fun m => match v with | Expr.proj .. => m.insert x v | Expr.sproj .. => m.insert x v | Expr.uproj .. => m.insert x v | _ => m partial def collectFnBody : FnBody → Collector | FnBody.vdecl x _ v b => collectVDecl x v ∘ collectFnBody b | FnBody.jdecl _ _ v b => collectFnBody v ∘ collectFnBody b | FnBody.case _ _ _ alts => fun s => alts.foldl (fun s alt => collectFnBody alt.body s) s | e => if e.isTerminal then id else collectFnBody e.body end CollectProjMap /- Create a mapping from variables to projections. This function assumes variable ids have been normalized -/ def mkProjMap (d : Decl) : ProjMap := match d with | Decl.fdecl (body := b) .. => CollectProjMap.collectFnBody b {} | _ => {} structure Context where projMap : ProjMap /- Return true iff `x` is consumed in all branches of the current block. Here consumption means the block contains a `dec x` or `reuse x ...`. -/ partial def consumed (x : VarId) : FnBody → Bool | FnBody.vdecl _ _ v b => match v with | Expr.reuse y _ _ _ => x == y || consumed x b | _ => consumed x b | FnBody.dec y _ _ _ b => x == y || consumed x b | FnBody.case _ _ _ alts => alts.all fun alt => consumed x alt.body | e => !e.isTerminal && consumed x e.body abbrev Mask := Array (Option VarId) /- Auxiliary function for eraseProjIncFor -/ partial def eraseProjIncForAux (y : VarId) (bs : Array FnBody) (mask : Mask) (keep : Array FnBody) : Array FnBody × Mask := let done (_ : Unit) := (bs ++ keep.reverse, mask) let keepInstr (b : FnBody) := eraseProjIncForAux y bs.pop mask (keep.push b) if bs.size < 2 then done () else let b := bs.back match b with | (FnBody.vdecl _ _ (Expr.sproj _ _ _) _) => keepInstr b | (FnBody.vdecl _ _ (Expr.uproj _ _) _) => keepInstr b | (FnBody.inc z n c p _) => if n == 0 then done () else let b' := bs[bs.size - 2] match b' with | (FnBody.vdecl w _ (Expr.proj i x) _) => if w == z && y == x then /- Found ``` let z := proj[i] y inc z n c ``` We keep `proj`, and `inc` when `n > 1` -/ let bs := bs.pop.pop let mask := mask.set! i (some z) let keep := keep.push b' let keep := if n == 1 then keep else keep.push (FnBody.inc z (n-1) c p FnBody.nil) eraseProjIncForAux y bs mask keep else done () | other => done () | other => done () /- Try to erase `inc` instructions on projections of `y` occurring in the tail of `bs`. Return the updated `bs` and a bit mask specifying which `inc`s have been removed. -/ def eraseProjIncFor (n : Nat) (y : VarId) (bs : Array FnBody) : Array FnBody × Mask := eraseProjIncForAux y bs (mkArray n none) #[] /- Replace `reuse x ctor ...` with `ctor ...`, and remoce `dec x` -/ partial def reuseToCtor (x : VarId) : FnBody → FnBody | FnBody.dec y n c p b => if x == y then b -- n must be 1 since `x := reset ...` else FnBody.dec y n c p (reuseToCtor x b) | FnBody.vdecl z t v b => match v with | Expr.reuse y c u xs => if x == y then FnBody.vdecl z t (Expr.ctor c xs) b else FnBody.vdecl z t v (reuseToCtor x b) | _ => FnBody.vdecl z t v (reuseToCtor x b) | FnBody.case tid y yType alts => let alts := alts.map fun alt => alt.modifyBody (reuseToCtor x) FnBody.case tid y yType alts | e => if e.isTerminal then e else let (instr, b) := e.split let b := reuseToCtor x b instr.setBody b /- replace ``` x := reset y; b ``` with ``` inc z_1; ...; inc z_i; dec y; b' ``` where `z_i`'s are the variables in `mask`, and `b'` is `b` where we removed `dec x` and replaced `reuse x ctor_i ...` with `ctor_i ...`. -/ def mkSlowPath (x y : VarId) (mask : Mask) (b : FnBody) : FnBody := let b := reuseToCtor x b let b := FnBody.dec y 1 true false b mask.foldl (init := b) fun b m => match m with | some z => FnBody.inc z 1 true false b | none => b abbrev M := ReaderT Context (StateM Nat) def mkFresh : M VarId := modifyGet $ fun n => ({ idx := n }, n + 1) def releaseUnreadFields (y : VarId) (mask : Mask) (b : FnBody) : M FnBody := mask.size.foldM (init := b) fun i b => match mask.get! i with | some _ => pure b -- code took ownership of this field | none => do let fld ← mkFresh pure (FnBody.vdecl fld IRType.object (Expr.proj i y) (FnBody.dec fld 1 true false b)) def setFields (y : VarId) (zs : Array Arg) (b : FnBody) : FnBody := zs.size.fold (init := b) fun i b => FnBody.set y i (zs.get! i) b /- Given `set x[i] := y`, return true iff `y := proj[i] x` -/ def isSelfSet (ctx : Context) (x : VarId) (i : Nat) (y : Arg) : Bool := match y with | Arg.var y => match ctx.projMap.find? y with | some (Expr.proj j w) => j == i && w == x | _ => false | _ => false /- Given `uset x[i] := y`, return true iff `y := uproj[i] x` -/ def isSelfUSet (ctx : Context) (x : VarId) (i : Nat) (y : VarId) : Bool := match ctx.projMap.find? y with | some (Expr.uproj j w) => j == i && w == x | _ => false /- Given `sset x[n, i] := y`, return true iff `y := sproj[n, i] x` -/ def isSelfSSet (ctx : Context) (x : VarId) (n : Nat) (i : Nat) (y : VarId) : Bool := match ctx.projMap.find? y with | some (Expr.sproj m j w) => n == m && j == i && w == x | _ => false /- Remove unnecessary `set/uset/sset` operations -/ partial def removeSelfSet (ctx : Context) : FnBody → FnBody | FnBody.set x i y b => if isSelfSet ctx x i y then removeSelfSet ctx b else FnBody.set x i y (removeSelfSet ctx b) | FnBody.uset x i y b => if isSelfUSet ctx x i y then removeSelfSet ctx b else FnBody.uset x i y (removeSelfSet ctx b) | FnBody.sset x n i y t b => if isSelfSSet ctx x n i y then removeSelfSet ctx b else FnBody.sset x n i y t (removeSelfSet ctx b) | FnBody.case tid y yType alts => let alts := alts.map fun alt => alt.modifyBody (removeSelfSet ctx) FnBody.case tid y yType alts | e => if e.isTerminal then e else let (instr, b) := e.split let b := removeSelfSet ctx b instr.setBody b partial def reuseToSet (ctx : Context) (x y : VarId) : FnBody → FnBody | FnBody.dec z n c p b => if x == z then FnBody.del y b else FnBody.dec z n c p (reuseToSet ctx x y b) | FnBody.vdecl z t v b => match v with | Expr.reuse w c u zs => if x == w then let b := setFields y zs (b.replaceVar z y) let b := if u then FnBody.setTag y c.cidx b else b removeSelfSet ctx b else FnBody.vdecl z t v (reuseToSet ctx x y b) | _ => FnBody.vdecl z t v (reuseToSet ctx x y b) | FnBody.case tid z zType alts => let alts := alts.map fun alt => alt.modifyBody (reuseToSet ctx x y) FnBody.case tid z zType alts | e => if e.isTerminal then e else let (instr, b) := e.split let b := reuseToSet ctx x y b instr.setBody b /- replace ``` x := reset y; b ``` with ``` let f_i_1 := proj[i_1] y; ... let f_i_k := proj[i_k] y; b' ``` where `i_j`s are the field indexes that the code did not touch immediately before the reset. That is `mask[j] == none`. `b'` is `b` where `y` `dec x` is replaced with `del y`, and `z := reuse x ctor_i ws; F` is replaced with `set x i ws[i]` operations, and we replace `z` with `x` in `F` -/ def mkFastPath (x y : VarId) (mask : Mask) (b : FnBody) : M FnBody := do let ctx ← read let b := reuseToSet ctx x y b releaseUnreadFields y mask b -- Expand `bs; x := reset[n] y; b` partial def expand (mainFn : FnBody → Array FnBody → M FnBody) (bs : Array FnBody) (x : VarId) (n : Nat) (y : VarId) (b : FnBody) : M FnBody := do let bOld := FnBody.vdecl x IRType.object (Expr.reset n y) b let (bs, mask) := eraseProjIncFor n y bs /- Remark: we may be duplicting variable/JP indices. That is, `bSlow` and `bFast` may have duplicate indices. We run `normalizeIds` to fix the ids after we have expand them. -/ let bSlow := mkSlowPath x y mask b let bFast ← mkFastPath x y mask b /- We only optimize recursively the fast. -/ let bFast ← mainFn bFast #[] let c ← mkFresh let b := FnBody.vdecl c IRType.uint8 (Expr.isShared y) (mkIf c bSlow bFast) pure $ reshape bs b partial def searchAndExpand : FnBody → Array FnBody → M FnBody | d@(FnBody.vdecl x t (Expr.reset n y) b), bs => if consumed x b then do expand searchAndExpand bs x n y b else searchAndExpand b (push bs d) | FnBody.jdecl j xs v b, bs => do let v ← searchAndExpand v #[] searchAndExpand b (push bs (FnBody.jdecl j xs v FnBody.nil)) | FnBody.case tid x xType alts, bs => do let alts ← alts.mapM $ fun alt => alt.mmodifyBody fun b => searchAndExpand b #[] pure $ reshape bs (FnBody.case tid x xType alts) | b, bs => if b.isTerminal then pure $ reshape bs b else searchAndExpand b.body (push bs b) def main (d : Decl) : Decl := match d with | Decl.fdecl (body := b) .. => let m := mkProjMap d let nextIdx := d.maxIndex + 1 let bNew := (searchAndExpand b #[] { projMap := m }).run' nextIdx d.updateBody! bNew | d => d end ExpandResetReuse /-- (Try to) expand `reset` and `reuse` instructions. -/ def Decl.expandResetReuse (d : Decl) : Decl := (ExpandResetReuse.main d).normalizeIds end Lean.IR
0237a4c0c68a3dad95fa90dc83df7f2ce2189ec0
a45212b1526d532e6e83c44ddca6a05795113ddc
/test/push_neg.lean
10cea2b4e58dba73fd6f723aa6140f99db29ec3e
[ "Apache-2.0" ]
permissive
fpvandoorn/mathlib
b21ab4068db079cbb8590b58fda9cc4bc1f35df4
b3433a51ea8bc07c4159c1073838fc0ee9b8f227
refs/heads/master
1,624,791,089,608
1,556,715,231,000
1,556,715,231,000
165,722,980
5
0
Apache-2.0
1,552,657,455,000
1,547,494,646,000
Lean
UTF-8
Lean
false
false
1,026
lean
import tactic.push_neg example (h : ∃ p: ℕ, ¬ ∀ n : ℕ, n > p) (h' : ∃ p: ℕ, ¬ ∃ n : ℕ, n < p) : ¬ ∀ n : ℕ, n = 0 := begin push_neg at *, guard_target_strict ∃ (n : ℕ), n ≠ 0, guard_hyp_strict h := ∃ (p n : ℕ), n ≤ p, guard_hyp_strict h' := ∃ (p : ℕ), ∀ (n : ℕ), p ≤ n, use 1, end -- In the next example, ℤ should be ℝ in maths, but I don't want to import real numbers -- for testing only local notation `|` x `|` := abs x example (a : ℕ → ℤ) (l : ℤ) (h : ¬ ∀ ε > 0, ∃ N, ∀ n ≥ N, | a n - l | < ε) : true := begin push_neg at h, guard_hyp_strict h := ∃ (ε : ℤ), ε > 0 ∧ ∀ (N : ℕ), ∃ (n : ℕ), n ≥ N ∧ ε ≤ |a n - l|, trivial end example (f : ℤ → ℤ) (x₀ y₀) (h : ¬ ∀ ε > 0, ∃ δ > 0, ∀ x, |x - x₀| ≤ δ → |f x - y₀| ≤ ε) : true := begin push_neg at h, guard_hyp_strict h := ∃ (ε : ℤ), ε > 0 ∧ ∀ δ > 0, (∃ (x : ℤ), |x - x₀| ≤ δ ∧ ε < |f x - y₀| ), trivial end
17573500268da0c563a6bbe6fb7c60fc0d30db1d
0c1546a496eccfb56620165cad015f88d56190c5
/tests/lean/run/smt_ematch2.lean
a0585d92b454945b7ea26a8ddc397a297a2da5d4
[ "Apache-2.0" ]
permissive
Solertis/lean
491e0939957486f664498fbfb02546e042699958
84188c5aa1673fdf37a082b2de8562dddf53df3f
refs/heads/master
1,610,174,257,606
1,486,263,620,000
1,486,263,620,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,728
lean
universe variables u namespace foo variables {α : Type u} open smt_tactic meta def no_ac : smt_config := { cc_cfg := { ac := ff }} meta def blast : tactic unit := using_smt_core no_ac $ intros >> repeat (ematch >> try close) section add_comm_monoid variables [add_comm_monoid α] attribute [ematch] add_comm add_assoc theorem add_comm_three (a b c : α) : a + b + c = c + b + a := by blast theorem add.comm4 : ∀ (n m k l : α), n + m + (k + l) = n + k + (m + l) := by blast end add_comm_monoid section group variable [group α] attribute [ematch] mul_assoc mul_left_inv one_mul theorem inv_mul_cancel_left (a b : α) : a⁻¹ * (a * b) = b := by blast end group namespace subt constant subt : nat → nat → Prop axiom subt_trans {a b c : nat} : subt a b → subt b c → subt a c attribute [ematch] subt_trans lemma ex (a b c d : nat) : subt a b → subt b c → subt c d → subt a d := by blast end subt section ring variables [ring α] (a b : α) attribute [ematch] zero_mul lemma ex2 : a = 0 → a * b = 0 := by blast definition ex1 (a b : int) : a = 0 → a * b = 0 := by blast end ring namespace cast1 constant C : nat → Type constant f : ∀ n, C n → C n axiom fax (n : nat) (a : C (2*n)) : (: f (2*n) a :) = a attribute [ematch] fax lemma ex3 (n m : nat) (a : C n) : n = 2*m → f n a = a := by blast end cast1 namespace cast2 constant C : nat → Type constant f : ∀ n, C n → C n constant g : ∀ n, C n → C n → C n axiom gffax (n : nat) (a b : C n) : (: g n (f n a) (f n b) :) = a attribute [ematch] gffax lemma ex4 (n m : nat) (a c : C n) (b : C m) : n = m → a == f m b → g n a (f n c) == b := by blast end cast2 namespace cast3 constant C : nat → Type constant f : ∀ n, C n → C n constant g : ∀ n, C n → C n → C n axiom gffax (n : nat) (a b : C n) : (: g n a b :) = a attribute [ematch] gffax lemma ex5 (n m : nat) (a c : C n) (b : C m) (e : m = n) : a == b → g n a a == b := by blast end cast3 namespace tuple constant {α} tuple: Type α → nat → Type α constant nil {α : Type u} : tuple α 0 constant append {α : Type u} {n m : nat} : tuple α n → tuple α m → tuple α (n + m) infix ` ++ ` := append axiom append_assoc {α : Type u} {n₁ n₂ n₃ : nat} (v₁ : tuple α n₁) (v₂ : tuple α n₂) (v₃ : tuple α n₃) : (v₁ ++ v₂) ++ v₃ == v₁ ++ (v₂ ++ v₃) attribute [ematch] append_assoc variables {p m n q : nat} variables {xs : tuple α m} variables {ys : tuple α n} variables {zs : tuple α p} variables {ws : tuple α q} lemma ex6 : p = m + n → zs == xs ++ ys → zs ++ ws == xs ++ (ys ++ ws) := by blast def ex : p = n + m → zs == xs ++ ys → zs ++ ws == xs ++ (ys ++ ws) := by blast end tuple end foo
bff7f1d1a0a7a2605ce1f1de206058d19471de96
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/deprecated/subgroup_auto.lean
148611d14b95a59c1e61b201a9da1326e20381a9
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
25,200
lean
/- 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, Mitchell Rowett, Scott Morrison, Johan Commelin, Mario Carneiro, Michael Howes -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.group_theory.subgroup import Mathlib.deprecated.submonoid import Mathlib.PostPort universes u_3 l u_1 u_2 u_4 namespace Mathlib /-- `s` is an additive subgroup: a set containing 0 and closed under addition and negation. -/ class is_add_subgroup {A : Type u_3} [add_group A] (s : set A) extends is_add_submonoid s where neg_mem : ∀ {a : A}, a ∈ s → -a ∈ s /-- `s` is a subgroup: a set containing 1 and closed under multiplication and inverse. -/ class is_subgroup {G : Type u_1} [group G] (s : set G) extends is_submonoid s where inv_mem : ∀ {a : G}, a ∈ s → a⁻¹ ∈ s theorem is_subgroup.div_mem {G : Type u_1} [group G] {s : set G} [is_subgroup s] {x : G} {y : G} (hx : x ∈ s) (hy : y ∈ s) : x / y ∈ s := sorry theorem additive.is_add_subgroup {G : Type u_1} [group G] (s : set G) [is_subgroup s] : is_add_subgroup s := is_add_subgroup.mk is_subgroup.inv_mem theorem additive.is_add_subgroup_iff {G : Type u_1} [group G] {s : set G} : is_add_subgroup s ↔ is_subgroup s := sorry theorem multiplicative.is_subgroup {A : Type u_3} [add_group A] (s : set A) [is_add_subgroup s] : is_subgroup s := is_subgroup.mk is_add_subgroup.neg_mem theorem multiplicative.is_subgroup_iff {A : Type u_3} [add_group A] {s : set A} : is_subgroup s ↔ is_add_subgroup s := sorry /-- The group structure on a subgroup coerced to a type. -/ def subtype.group {G : Type u_1} [group G] {s : set G} [is_subgroup s] : group ↥s := group.mk monoid.mul sorry monoid.one sorry sorry (fun (x : ↥s) => { val := ↑x⁻¹, property := sorry }) (fun (x y : ↥s) => { val := ↑x / ↑y, property := sorry }) sorry /-- The commutative group structure on a commutative subgroup coerced to a type. -/ def subtype.comm_group {G : Type u_1} [comm_group G] {s : set G} [is_subgroup s] : comm_group ↥s := comm_group.mk group.mul sorry group.one sorry sorry group.inv group.div sorry sorry @[simp] theorem is_subgroup.coe_inv {G : Type u_1} [group G] {s : set G} [is_subgroup s] (a : ↥s) : ↑(a⁻¹) = (↑a⁻¹) := rfl @[simp] theorem is_subgroup.coe_gpow {G : Type u_1} [group G] {s : set G} [is_subgroup s] (a : ↥s) (n : ℤ) : ↑(a ^ n) = ↑a ^ n := sorry @[simp] theorem is_add_subgroup.gsmul_coe {A : Type u_3} [add_group A] {s : set A} [is_add_subgroup s] (a : ↥s) (n : ℤ) : ↑(n •ℤ a) = n •ℤ ↑a := sorry theorem is_add_subgroup.of_add_neg {G : Type u_1} [add_group G] (s : set G) (one_mem : 0 ∈ s) (div_mem : ∀ {a b : G}, a ∈ s → b ∈ s → a + -b ∈ s) : is_add_subgroup s := sorry theorem is_add_subgroup.of_sub {A : Type u_3} [add_group A] (s : set A) (zero_mem : 0 ∈ s) (sub_mem : ∀ {a b : A}, a ∈ s → b ∈ s → a - b ∈ s) : is_add_subgroup s := sorry protected instance is_add_subgroup.inter {G : Type u_1} [add_group G] (s₁ : set G) (s₂ : set G) [is_add_subgroup s₁] [is_add_subgroup s₂] : is_add_subgroup (s₁ ∩ s₂) := is_add_subgroup.mk fun (x : G) (hx : x ∈ s₁ ∩ s₂) => { left := is_add_subgroup.neg_mem (and.left hx), right := is_add_subgroup.neg_mem (and.right hx) } protected instance is_add_subgroup.Inter {G : Type u_1} [add_group G] {ι : Sort u_2} (s : ι → set G) [h : ∀ (y : ι), is_add_subgroup (s y)] : is_add_subgroup (set.Inter s) := is_add_subgroup.mk fun (x : G) (h_1 : x ∈ set.Inter s) => iff.mpr set.mem_Inter fun (y : ι) => is_add_subgroup.neg_mem (iff.mp set.mem_Inter h_1 y) theorem is_add_subgroup_Union_of_directed {G : Type u_1} [add_group G] {ι : Type u_2} [hι : Nonempty ι] (s : ι → set G) [∀ (i : ι), is_add_subgroup (s i)] (directed : ∀ (i j : ι), ∃ (k : ι), s i ⊆ s k ∧ s j ⊆ s k) : is_add_subgroup (set.Union fun (i : ι) => s i) := sorry def gpowers {G : Type u_1} [group G] (x : G) : set G := set.range (pow x) def gmultiples {A : Type u_3} [add_group A] (x : A) : set A := set.range fun (i : ℤ) => i •ℤ x protected instance gpowers.is_subgroup {G : Type u_1} [group G] (x : G) : is_subgroup (gpowers x) := is_subgroup.mk fun (x₀ : G) (_x : x₀ ∈ gpowers x) => sorry protected instance gmultiples.is_add_subgroup {A : Type u_3} [add_group A] (x : A) : is_add_subgroup (gmultiples x) := iff.mp multiplicative.is_subgroup_iff (gpowers.is_subgroup x) theorem is_subgroup.gpow_mem {G : Type u_1} [group G] {a : G} {s : set G} [is_subgroup s] (h : a ∈ s) {i : ℤ} : a ^ i ∈ s := int.cases_on i (fun (i : ℕ) => idRhs (a ^ i ∈ s) (is_submonoid.pow_mem h)) fun (i : ℕ) => idRhs (a ^ Nat.succ i⁻¹ ∈ s) (is_subgroup.inv_mem (is_submonoid.pow_mem h)) theorem is_add_subgroup.gsmul_mem {A : Type u_3} [add_group A] {a : A} {s : set A} [is_add_subgroup s] : a ∈ s → ∀ {i : ℤ}, i •ℤ a ∈ s := is_subgroup.gpow_mem theorem gpowers_subset {G : Type u_1} [group G] {a : G} {s : set G} [is_subgroup s] (h : a ∈ s) : gpowers a ⊆ s := sorry theorem gmultiples_subset {A : Type u_3} [add_group A] {a : A} {s : set A} [is_add_subgroup s] (h : a ∈ s) : gmultiples a ⊆ s := gpowers_subset h theorem mem_gpowers {G : Type u_1} [group G] {a : G} : a ∈ gpowers a := sorry theorem mem_gmultiples {A : Type u_3} [add_group A] {a : A} : a ∈ gmultiples a := sorry namespace is_subgroup theorem inv_mem_iff {G : Type u_1} {a : G} [group G] (s : set G) [is_subgroup s] : a⁻¹ ∈ s ↔ a ∈ s := sorry theorem Mathlib.is_add_subgroup.add_mem_cancel_right {G : Type u_1} {a : G} {b : G} [add_group G] (s : set G) [is_add_subgroup s] (h : a ∈ s) : b + a ∈ s ↔ b ∈ s := sorry theorem Mathlib.is_add_subgroup.add_mem_cancel_left {G : Type u_1} {a : G} {b : G} [add_group G] (s : set G) [is_add_subgroup s] (h : a ∈ s) : a + b ∈ s ↔ b ∈ s := sorry end is_subgroup class normal_add_subgroup {A : Type u_3} [add_group A] (s : set A) extends is_add_subgroup s where normal : ∀ (n : A), n ∈ s → ∀ (g : A), g + n + -g ∈ s class normal_subgroup {G : Type u_1} [group G] (s : set G) extends is_subgroup s where normal : ∀ (n : G), n ∈ s → ∀ (g : G), g * n * (g⁻¹) ∈ s theorem normal_add_subgroup_of_add_comm_group {G : Type u_1} [add_comm_group G] (s : set G) [hs : is_add_subgroup s] : normal_add_subgroup s := sorry theorem additive.normal_add_subgroup {G : Type u_1} [group G] (s : set G) [normal_subgroup s] : normal_add_subgroup s := normal_add_subgroup.mk normal_subgroup.normal theorem additive.normal_add_subgroup_iff {G : Type u_1} [group G] {s : set G} : normal_add_subgroup s ↔ normal_subgroup s := sorry theorem multiplicative.normal_subgroup {A : Type u_3} [add_group A] (s : set A) [normal_add_subgroup s] : normal_subgroup s := normal_subgroup.mk normal_add_subgroup.normal theorem multiplicative.normal_subgroup_iff {A : Type u_3} [add_group A] {s : set A} : normal_subgroup s ↔ normal_add_subgroup s := sorry namespace is_subgroup -- Normal subgroup properties theorem mem_norm_comm {G : Type u_1} [group G] {s : set G} [normal_subgroup s] {a : G} {b : G} (hab : a * b ∈ s) : b * a ∈ s := sorry theorem Mathlib.is_add_subgroup.mem_norm_comm_iff {G : Type u_1} [add_group G] {s : set G} [normal_add_subgroup s] {a : G} {b : G} : a + b ∈ s ↔ b + a ∈ s := { mp := is_add_subgroup.mem_norm_comm, mpr := is_add_subgroup.mem_norm_comm } /-- The trivial subgroup -/ def trivial (G : Type u_1) [group G] : set G := singleton 1 @[simp] theorem Mathlib.is_add_subgroup.mem_trivial {G : Type u_1} [add_group G] {g : G} : g ∈ is_add_subgroup.trivial G ↔ g = 0 := set.mem_singleton_iff protected instance Mathlib.is_add_subgroup.trivial_normal {G : Type u_1} [add_group G] : normal_add_subgroup (is_add_subgroup.trivial G) := sorry theorem Mathlib.is_add_subgroup.eq_trivial_iff {G : Type u_1} [add_group G] {s : set G} [is_add_subgroup s] : s = is_add_subgroup.trivial G ↔ ∀ (x : G), x ∈ s → x = 0 := sorry protected instance univ_subgroup {G : Type u_1} [group G] : normal_subgroup set.univ := normal_subgroup.mk (eq.mpr (id (Eq.trans (forall_congr_eq fun (n : G) => Eq.trans (imp_congr_eq (propext ((fun {α : Type u_1} (x : α) => iff_true_intro (set.mem_univ x)) n)) (Eq.trans (forall_congr_eq fun (g : G) => propext ((fun {α : Type u_1} (x : α) => iff_true_intro (set.mem_univ x)) (g * n * (g⁻¹)))) (propext (forall_const G)))) (propext (forall_prop_of_true True.intro))) (propext (forall_const G)))) trivial) def Mathlib.is_add_subgroup.add_center (G : Type u_1) [add_group G] : set G := set_of fun (z : G) => ∀ (g : G), g + z = z + g theorem mem_center {G : Type u_1} [group G] {a : G} : a ∈ center G ↔ ∀ (g : G), g * a = a * g := iff.rfl protected instance center_normal {G : Type u_1} [group G] : normal_subgroup (center G) := sorry def Mathlib.is_add_subgroup.add_normalizer {G : Type u_1} [add_group G] (s : set G) : set G := set_of fun (g : G) => ∀ (n : G), n ∈ s ↔ g + n + -g ∈ s protected instance Mathlib.is_add_subgroup.normalizer_is_add_subgroup {G : Type u_1} [add_group G] (s : set G) : is_add_subgroup (is_add_subgroup.add_normalizer s) := sorry theorem Mathlib.is_add_subgroup.subset_add_normalizer {G : Type u_1} [add_group G] (s : set G) [is_add_subgroup s] : s ⊆ is_add_subgroup.add_normalizer s := sorry /-- Every subgroup is a normal subgroup of its normalizer -/ protected instance Mathlib.is_add_subgroup.add_normal_in_add_normalizer {G : Type u_1} [add_group G] (s : set G) [is_add_subgroup s] : normal_add_subgroup (subtype.val ⁻¹' s) := normal_add_subgroup.mk fun (a : ↥(is_add_subgroup.add_normalizer s)) (ha : a ∈ subtype.val ⁻¹' s) (_x : ↥(is_add_subgroup.add_normalizer s)) => sorry end is_subgroup -- Homomorphism subgroups namespace is_group_hom def ker {G : Type u_1} {H : Type u_2} [group H] (f : G → H) : set G := f ⁻¹' is_subgroup.trivial H theorem Mathlib.is_add_group_hom.mem_ker {G : Type u_1} {H : Type u_2} [add_group H] (f : G → H) {x : G} : x ∈ is_add_group_hom.ker f ↔ f x = 0 := is_add_subgroup.mem_trivial theorem Mathlib.is_add_group_hom.zero_ker_neg {G : Type u_1} {H : Type u_2} [add_group G] [add_group H] (f : G → H) [is_add_group_hom f] {a : G} {b : G} (h : f (a + -b) = 0) : f a = f b := sorry theorem one_ker_inv' {G : Type u_1} {H : Type u_2} [group G] [group H] (f : G → H) [is_group_hom f] {a : G} {b : G} (h : f (a⁻¹ * b) = 1) : f a = f b := sorry theorem Mathlib.is_add_group_hom.neg_ker_zero {G : Type u_1} {H : Type u_2} [add_group G] [add_group H] (f : G → H) [is_add_group_hom f] {a : G} {b : G} (h : f a = f b) : f (a + -b) = 0 := sorry theorem inv_ker_one' {G : Type u_1} {H : Type u_2} [group G] [group H] (f : G → H) [is_group_hom f] {a : G} {b : G} (h : f a = f b) : f (a⁻¹ * b) = 1 := sorry theorem Mathlib.is_add_group_hom.zero_iff_ker_neg {G : Type u_1} {H : Type u_2} [add_group G] [add_group H] (f : G → H) [is_add_group_hom f] (a : G) (b : G) : f a = f b ↔ f (a + -b) = 0 := { mp := is_add_group_hom.neg_ker_zero f, mpr := is_add_group_hom.zero_ker_neg f } theorem one_iff_ker_inv' {G : Type u_1} {H : Type u_2} [group G] [group H] (f : G → H) [is_group_hom f] (a : G) (b : G) : f a = f b ↔ f (a⁻¹ * b) = 1 := { mp := inv_ker_one' f, mpr := one_ker_inv' f } theorem inv_iff_ker {G : Type u_1} {H : Type u_2} [group G] [group H] (f : G → H) [w : is_group_hom f] (a : G) (b : G) : f a = f b ↔ a * (b⁻¹) ∈ ker f := eq.mpr (id (Eq._oldrec (Eq.refl (f a = f b ↔ a * (b⁻¹) ∈ ker f)) (propext (mem_ker f)))) (one_iff_ker_inv f a b) theorem inv_iff_ker' {G : Type u_1} {H : Type u_2} [group G] [group H] (f : G → H) [w : is_group_hom f] (a : G) (b : G) : f a = f b ↔ a⁻¹ * b ∈ ker f := eq.mpr (id (Eq._oldrec (Eq.refl (f a = f b ↔ a⁻¹ * b ∈ ker f)) (propext (mem_ker f)))) (one_iff_ker_inv' f a b) protected instance Mathlib.is_add_group_hom.image_add_subgroup {G : Type u_1} {H : Type u_2} [add_group G] [add_group H] (f : G → H) [is_add_group_hom f] (s : set G) [is_add_subgroup s] : is_add_subgroup (f '' s) := is_add_subgroup.mk fun (a : H) (_x : a ∈ f '' s) => sorry protected instance range_subgroup {G : Type u_1} {H : Type u_2} [group G] [group H] (f : G → H) [is_group_hom f] : is_subgroup (set.range f) := set.image_univ ▸ is_group_hom.image_subgroup f set.univ protected instance preimage {G : Type u_1} {H : Type u_2} [group G] [group H] (f : G → H) [is_group_hom f] (s : set H) [is_subgroup s] : is_subgroup (f ⁻¹' s) := is_subgroup.mk (eq.mpr (id (Eq.trans (forall_congr_eq fun (a : G) => Eq.trans (imp_congr_ctx_eq (propext set.mem_preimage) fun (_h : f a ∈ s) => Eq.trans (Eq.trans (propext set.mem_preimage) ((fun (ᾰ ᾰ_1 : H) (e_2 : ᾰ = ᾰ_1) (ᾰ_2 ᾰ_3 : set H) (e_3 : ᾰ_2 = ᾰ_3) => congr (congr_arg has_mem.mem e_2) e_3) (f (a⁻¹)) (f a⁻¹) (map_inv f a) s s (Eq.refl s))) (propext ((fun [c : is_subgroup s] {a : H} (ᾰ : a ∈ s) => iff_true_intro (is_subgroup.inv_mem ᾰ)) (iff.mpr (iff_true_intro _h) True.intro)))) (propext forall_true_iff)) (propext (forall_const G)))) trivial) protected instance preimage_normal {G : Type u_1} {H : Type u_2} [group G] [group H] (f : G → H) [is_group_hom f] (s : set H) [normal_subgroup s] : normal_subgroup (f ⁻¹' s) := sorry protected instance normal_subgroup_ker {G : Type u_1} {H : Type u_2} [group G] [group H] (f : G → H) [is_group_hom f] : normal_subgroup (ker f) := is_group_hom.preimage_normal f (is_subgroup.trivial H) theorem Mathlib.is_add_group_hom.injective_of_trivial_ker {G : Type u_1} {H : Type u_2} [add_group G] [add_group H] (f : G → H) [is_add_group_hom f] (h : is_add_group_hom.ker f = is_add_subgroup.trivial G) : function.injective f := sorry theorem trivial_ker_of_injective {G : Type u_1} {H : Type u_2} [group G] [group H] (f : G → H) [is_group_hom f] (h : function.injective f) : ker f = is_subgroup.trivial G := sorry theorem Mathlib.is_add_group_hom.injective_iff_trivial_ker {G : Type u_1} {H : Type u_2} [add_group G] [add_group H] (f : G → H) [is_add_group_hom f] : function.injective f ↔ is_add_group_hom.ker f = is_add_subgroup.trivial G := { mp := is_add_group_hom.trivial_ker_of_injective f, mpr := is_add_group_hom.injective_of_trivial_ker f } theorem Mathlib.is_add_group_hom.trivial_ker_iff_eq_zero {G : Type u_1} {H : Type u_2} [add_group G] [add_group H] (f : G → H) [is_add_group_hom f] : is_add_group_hom.ker f = is_add_subgroup.trivial G ↔ ∀ (x : G), f x = 0 → x = 0 := sorry end is_group_hom protected instance subtype_val.is_add_group_hom {G : Type u_1} [add_group G] {s : set G} [is_add_subgroup s] : is_add_group_hom subtype.val := is_add_group_hom.mk protected instance coe.is_add_group_hom {G : Type u_1} [add_group G] {s : set G} [is_add_subgroup s] : is_add_group_hom coe := is_add_group_hom.mk protected instance subtype_mk.is_group_hom {G : Type u_1} {H : Type u_2} [group G] [group H] {s : set G} [is_subgroup s] (f : H → G) [is_group_hom f] (h : ∀ (x : H), f x ∈ s) : is_group_hom fun (x : H) => { val := f x, property := h x } := is_group_hom.mk protected instance set_inclusion.is_group_hom {G : Type u_1} [group G] {s : set G} {t : set G} [is_subgroup s] [is_subgroup t] (h : s ⊆ t) : is_group_hom (set.inclusion h) := subtype_mk.is_group_hom (fun (x : ↥s) => ↑x) fun (x : ↥s) => set.inclusion._proof_1 h x /-- `subtype.val : set.range f → H` as a monoid homomorphism, when `f` is a monoid homomorphism. -/ def monoid_hom.range_subtype_val {G : Type u_1} {H : Type u_2} [monoid G] [monoid H] (f : G →* H) : ↥(set.range ⇑f) →* H := monoid_hom.of subtype.val /-- `set.range_factorization f : G → set.range f` as a monoid homomorphism, when `f` is a monoid homomorphism. -/ def add_monoid_hom.range_factorization {G : Type u_1} {H : Type u_2} [add_monoid G] [add_monoid H] (f : G →+ H) : G →+ ↥(set.range ⇑f) := add_monoid_hom.mk (set.range_factorization ⇑f) sorry sorry namespace add_group inductive in_closure {A : Type u_3} [add_group A] (s : set A) : A → Prop where | basic : ∀ {a : A}, a ∈ s → in_closure s a | zero : in_closure s 0 | neg : ∀ {a : A}, in_closure s a → in_closure s (-a) | add : ∀ {a b : A}, in_closure s a → in_closure s b → in_closure s (a + b) end add_group namespace group inductive in_closure {G : Type u_1} [group G] (s : set G) : G → Prop where | basic : ∀ {a : G}, a ∈ s → in_closure s a | one : in_closure s 1 | inv : ∀ {a : G}, in_closure s a → in_closure s (a⁻¹) | mul : ∀ {a b : G}, in_closure s a → in_closure s b → in_closure s (a * b) /-- `group.closure s` is the subgroup closed over `s`, i.e. the smallest subgroup containg s. -/ def Mathlib.add_group.closure {G : Type u_1} [add_group G] (s : set G) : set G := set_of fun (a : G) => add_group.in_closure s a theorem Mathlib.add_group.mem_closure {G : Type u_1} [add_group G] {s : set G} {a : G} : a ∈ s → a ∈ add_group.closure s := add_group.in_closure.basic protected instance closure.is_subgroup {G : Type u_1} [group G] (s : set G) : is_subgroup (closure s) := is_subgroup.mk fun (a : G) => in_closure.inv theorem Mathlib.add_group.subset_closure {G : Type u_1} [add_group G] {s : set G} : s ⊆ add_group.closure s := fun (a : G) => add_group.mem_closure theorem Mathlib.add_group.closure_subset {G : Type u_1} [add_group G] {s : set G} {t : set G} [is_add_subgroup t] (h : s ⊆ t) : add_group.closure s ⊆ t := sorry theorem Mathlib.add_group.closure_subset_iff {G : Type u_1} [add_group G] (s : set G) (t : set G) [is_add_subgroup t] : add_group.closure s ⊆ t ↔ s ⊆ t := { mp := fun (h : add_group.closure s ⊆ t) (b : G) (ha : b ∈ s) => h (add_group.mem_closure ha), mpr := fun (h : s ⊆ t) (b : G) (ha : b ∈ add_group.closure s) => add_group.closure_subset h ha } theorem Mathlib.add_group.closure_mono {G : Type u_1} [add_group G] {s : set G} {t : set G} (h : s ⊆ t) : add_group.closure s ⊆ add_group.closure t := add_group.closure_subset (set.subset.trans h add_group.subset_closure) @[simp] theorem closure_subgroup {G : Type u_1} [group G] (s : set G) [is_subgroup s] : closure s = s := set.subset.antisymm (closure_subset (set.subset.refl s)) subset_closure theorem Mathlib.add_group.exists_list_of_mem_closure {G : Type u_1} [add_group G] {s : set G} {a : G} (h : a ∈ add_group.closure s) : ∃ (l : List G), (∀ (x : G), x ∈ l → x ∈ s ∨ -x ∈ s) ∧ list.sum l = a := sorry theorem Mathlib.add_group.image_closure {G : Type u_1} {H : Type u_2} [add_group G] [add_group H] (f : G → H) [is_add_group_hom f] (s : set G) : f '' add_group.closure s = add_group.closure (f '' s) := sorry theorem Mathlib.add_group.mclosure_subset {G : Type u_1} [add_group G] {s : set G} : add_monoid.closure s ⊆ add_group.closure s := add_monoid.closure_subset add_group.subset_closure theorem Mathlib.add_group.mclosure_neg_subset {G : Type u_1} [add_group G] {s : set G} : add_monoid.closure (Neg.neg ⁻¹' s) ⊆ add_group.closure s := add_monoid.closure_subset fun (x : G) (hx : x ∈ Neg.neg ⁻¹' s) => neg_neg x ▸ is_add_subgroup.neg_mem (add_group.subset_closure hx) theorem Mathlib.add_group.closure_eq_mclosure {G : Type u_1} [add_group G] {s : set G} : add_group.closure s = add_monoid.closure (s ∪ Neg.neg ⁻¹' s) := sorry theorem Mathlib.add_group.mem_closure_union_iff {G : Type u_1} [add_comm_group G] {s : set G} {t : set G} {x : G} : x ∈ add_group.closure (s ∪ t) ↔ ∃ (y : G), ∃ (H : y ∈ add_group.closure s), ∃ (z : G), ∃ (H : z ∈ add_group.closure t), y + z = x := sorry theorem gpowers_eq_closure {G : Type u_1} [group G] {a : G} : gpowers a = closure (singleton a) := sorry end group namespace is_subgroup theorem Mathlib.is_add_subgroup.trivial_eq_closure {G : Type u_1} [add_group G] : is_add_subgroup.trivial G = add_group.closure ∅ := sorry end is_subgroup /-The normal closure of a set s is the subgroup closure of all the conjugates of elements of s. It is the smallest normal subgroup containing s. -/ namespace group theorem conjugates_subset {G : Type u_1} [group G] {t : set G} [normal_subgroup t] {a : G} (h : a ∈ t) : conjugates a ⊆ t := sorry theorem conjugates_of_set_subset' {G : Type u_1} [group G] {s : set G} {t : set G} [normal_subgroup t] (h : s ⊆ t) : conjugates_of_set s ⊆ t := set.bUnion_subset fun (x : G) (H : x ∈ s) => conjugates_subset (h H) /-- The normal closure of a set s is the subgroup closure of all the conjugates of elements of s. It is the smallest normal subgroup containing s. -/ def normal_closure {G : Type u_1} [group G] (s : set G) : set G := closure (conjugates_of_set s) theorem conjugates_of_set_subset_normal_closure {G : Type u_1} {s : set G} [group G] : conjugates_of_set s ⊆ normal_closure s := subset_closure theorem subset_normal_closure {G : Type u_1} {s : set G} [group G] : s ⊆ normal_closure s := set.subset.trans subset_conjugates_of_set conjugates_of_set_subset_normal_closure /-- The normal closure of a set is a subgroup. -/ protected instance normal_closure.is_subgroup {G : Type u_1} [group G] (s : set G) : is_subgroup (normal_closure s) := closure.is_subgroup (conjugates_of_set s) /-- The normal closure of s is a normal subgroup. -/ protected instance normal_closure.is_normal {G : Type u_1} {s : set G} [group G] : normal_subgroup (normal_closure s) := sorry /-- The normal closure of s is the smallest normal subgroup containing s. -/ theorem normal_closure_subset {G : Type u_1} [group G] {s : set G} {t : set G} [normal_subgroup t] (h : s ⊆ t) : normal_closure s ⊆ t := sorry theorem normal_closure_subset_iff {G : Type u_1} [group G] {s : set G} {t : set G} [normal_subgroup t] : s ⊆ t ↔ normal_closure s ⊆ t := { mp := normal_closure_subset, mpr := set.subset.trans subset_normal_closure } theorem normal_closure_mono {G : Type u_1} [group G] {s : set G} {t : set G} : s ⊆ t → normal_closure s ⊆ normal_closure t := fun (h : s ⊆ t) => normal_closure_subset (set.subset.trans h subset_normal_closure) end group class simple_group (G : Type u_4) [group G] where simple : ∀ (N : set G) [_inst_1_1 : normal_subgroup N], N = is_subgroup.trivial G ∨ N = set.univ class simple_add_group (A : Type u_4) [add_group A] where simple : ∀ (N : set A) [_inst_1_1 : normal_add_subgroup N], N = is_add_subgroup.trivial A ∨ N = set.univ theorem additive.simple_add_group_iff {G : Type u_1} [group G] : simple_add_group (additive G) ↔ simple_group G := sorry protected instance additive.simple_add_group {G : Type u_1} [group G] [simple_group G] : simple_add_group (additive G) := iff.mpr additive.simple_add_group_iff _inst_2 theorem multiplicative.simple_group_iff {A : Type u_3} [add_group A] : simple_group (multiplicative A) ↔ simple_add_group A := sorry protected instance multiplicative.simple_group {A : Type u_3} [add_group A] [simple_add_group A] : simple_group (multiplicative A) := iff.mpr multiplicative.simple_group_iff _inst_2 theorem simple_add_group_of_surjective {G : Type u_1} {H : Type u_2} [add_group G] [add_group H] [simple_add_group G] (f : G → H) [is_add_group_hom f] (hf : function.surjective f) : simple_add_group H := sorry /-- Create a bundled subgroup from a set `s` and `[is_subroup s]`. -/ def subgroup.of {G : Type u_1} [group G] (s : set G) [h : is_subgroup s] : subgroup G := subgroup.mk s sorry sorry is_subgroup.inv_mem protected instance subgroup.is_subgroup {G : Type u_1} [group G] (K : subgroup G) : is_subgroup ↑K := is_subgroup.mk (subgroup.inv_mem' K) protected instance subgroup.of_normal {G : Type u_1} [group G] (s : set G) [h : is_subgroup s] [n : normal_subgroup s] : subgroup.normal (subgroup.of s) := subgroup.normal.mk normal_subgroup.normal end Mathlib
91dfc645e15d792033da0b4fad9551da7b4b3ddf
2fb7334a212c3858db44039b5fa6cd57fd5d1443
/src/extremally_disconnected.lean
05890c2168d8d86c1e0d71ed6acaa81aaadb11b4
[]
no_license
ImperialCollegeLondon/condensed-sets
24514be041533b07fd62d337b1d6a5ce2b09c78c
e308291646396003dbed3896e5fbb40cb57c7050
refs/heads/master
1,628,397,992,041
1,601,549,576,000
1,601,549,576,000
224,198,323
3
1
null
1,601,549,578,000
1,574,774,780,000
Lean
UTF-8
Lean
false
false
4,985
lean
import topology.compact_open import topology.stone_cech /-! # Extremally disconnected spaces An extremally disconnected topological space is a space in which the closure of every open set is open. Such spaces are also called Stonean spaces. The are the projective objects in the category of compact Hausdorff spaces; a fact is proven in `TODO`. ## References Gleason, Andrew M. (1958), "Projective topological spaces", Illinois Journal of Mathematics, 2 (4A): 482–489, doi:10.1215/ijm/1255454110, MR 0121775 -/ universe variables u v w noncomputable theory open_locale classical section variables {X : Type u} {Y : Type v} {Z : Type w} variables [topological_space Y] [topological_space Z] [t2_space Z] variables {f : X → Y} lemma dense_range.equalizer (hfd : dense_range f) {g h : Y → Z} (hg : continuous g) (hh : continuous h) (H : g ∘ f = h ∘ f) : g = h := funext $ λ y, hfd.induction_on y (is_closed_eq hg hh) $ congr_fun H end variables (X : Type u) [topological_space X] open function /-- An extremally disconnected topological space is a space in which the closure of every open set is open. Such spaces are also called Stonean spaces. The are the projective objects in the category of compact Hausdorff spaces; a fact is proven in `TODO`. -/ class extremally_disconnected : Prop := (open_closure : ∀ U : set X, is_open U → is_open (closure U)) section include X def compact_t2.projective : Prop := Π {Y Z : Type u} [topological_space Y] [topological_space Z], by exactI Π [compact_space Y] [t2_space Y] [compact_space Z] [t2_space Z], by exactI Π {f : X → Z} {g : Y → Z} (hf : continuous f) (hg : continuous g) (g_sur : surjective g), ∃ h : X → Y, continuous h ∧ g ∘ h = f end variable {X} lemma stone_cech.projective [discrete_topology X] : compact_t2.projective (stone_cech X) := begin introsI Y Z _tsY _tsZ _csY _t2Y _csZ _csZ f g hf hg g_sur, let s : Z → Y := λ z, classical.some $ g_sur z, have hs : g ∘ s = id := funext (λ z, classical.some_spec (g_sur z)), let t := s ∘ f ∘ stone_cech_unit, have ht : continuous t := continuous_of_discrete_topology, let h : stone_cech X → Y := stone_cech_extend ht, have hh : continuous h := continuous_stone_cech_extend ht, use [h, hh], have H : dense_range (stone_cech_unit : X → stone_cech X), { rw dense_range_iff_closure_range, exact stone_cech_unit_dense }, apply H.equalizer (hg.comp hh) hf, rw [comp.assoc, stone_cech_extend_extends ht, ← comp.assoc, hs, comp.left_id], end instance fintype.compact_space [fintype X] : compact_space X := { compact_univ := compact_of_finite set.finite_univ } lemma extremally_disconnected_of_projective [compact_space X] [t2_space X] (h : compact_t2.projective X) : extremally_disconnected X := begin constructor, intros U hU, let Z₁ : set (X × bool) := (-U).prod {tt}, let Z₂ : set (X × bool) := (closure U).prod {ff}, let Z : set (X × bool) := Z₁ ∪ Z₂, have hZ₁ : is_closed Z₁ := is_closed_prod (is_closed_compl_iff.mpr hU) trivial, have hZ₂ : is_closed Z₂ := is_closed_prod is_closed_closure trivial, have hZ : is_closed Z := is_closed_union hZ₁ hZ₂, have h_compl : -((subtype.val : Z → (X × bool)) ⁻¹' Z₂) = subtype.val ⁻¹' Z₁, { ext x, cases x with x hx, change x ∈ (_ ∪ _) at hx, simp only [set.mem_preimage, not_and, eq_tt_eq_not_eq_ff, set.mem_singleton_iff, set.mem_prod, set.mem_union_eq, set.mem_compl_eq] at hx ⊢, finish, }, let f : Z → X := prod.fst ∘ subtype.val, have f_cont : continuous f := continuous_fst.comp continuous_subtype_val, have f_sur : surjective f, { intro x, by_cases hx : x ∈ U, { refine ⟨⟨(x, ff), _⟩, rfl⟩, right, exact ⟨subset_closure hx, set.mem_singleton _⟩ }, { refine ⟨⟨(x, tt), _⟩, rfl⟩, left, refine ⟨hx, set.mem_singleton _⟩ } }, haveI : compact_space Z := compact_iff_compact_space.mp (compact_of_closed hZ), rcases h continuous_id f_cont f_sur with ⟨g, hg, g_sec⟩, let φ := subtype.val ∘ g, have hφ : continuous φ := continuous_subtype_val.comp hg, have hfstφ : prod.fst ∘ φ = id := by rwa comp.assoc at g_sec, suffices : closure U = φ ⁻¹' Z₂, { rw [this, set.preimage_comp], apply hg, rw [← is_closed_compl_iff, h_compl], exact continuous_iff_is_closed.mp continuous_subtype_val Z₁ hZ₁ }, have key : ∀ x ∈ U, φ x = (x, ff), { intros x hx, replace hfstφ := congr_fun hfstφ x, rw comp_apply at hfstφ, ext, { exact hfstφ }, { have : φ x ∈ (Z₁ ∪ Z₂) := (g x).property, simp [hx, hfstφ] at this, exact this.2 } }, apply set.subset.antisymm, { apply closure_minimal _ (continuous_iff_is_closed.mp hφ Z₂ hZ₂), intros x hx, simp [key, hx], exact subset_closure hx }, { intros x hx, rw [set.mem_preimage, set.mem_prod] at hx, replace hfstφ := congr_fun hfstφ x, rw comp_apply at hfstφ, rw hfstφ at hx, exact hx.1 } end
8fe70114d200ceadd3d58db856d2b733c9a5b9c6
82e44445c70db0f03e30d7be725775f122d72f3e
/src/measure_theory/l1_space.lean
84461638ffcc7bea387dfbe5a0e9ae2b7b3552f2
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
37,426
lean
/- Copyright (c) 2019 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou -/ import measure_theory.lp_space /-! # Integrable functions and `L¹` space In the first part of this file, the predicate `integrable` is defined and basic properties of integrable functions are proved. Such a predicate is already available under the name `mem_ℒp 1`. We give a direct definition which is easier to use, and show that it is equivalent to `mem_ℒp 1` In the second part, we establish an API between `integrable` and the space `L¹` of equivalence classes of integrable functions, already defined as a special case of `L^p` spaces for `p = 1`. ## Notation * `α →₁[μ] β` is the type of `L¹` space, where `α` is a `measure_space` and `β` is a `normed_group` with a `second_countable_topology`. `f : α →ₘ β` is a "function" in `L¹`. In comments, `[f]` is also used to denote an `L¹` function. `₁` can be typed as `\1`. ## Main definitions * Let `f : α → β` be a function, where `α` is a `measure_space` and `β` a `normed_group`. Then `has_finite_integral f` means `(∫⁻ a, nnnorm (f a)) < ∞`. * If `β` is moreover a `measurable_space` then `f` is called `integrable` if `f` is `measurable` and `has_finite_integral f` holds. ## Implementation notes To prove something for an arbitrary integrable function, a useful theorem is `integrable.induction` in the file `set_integral`. ## Tags integrable, function space, l1 -/ noncomputable theory open_locale classical topological_space big_operators ennreal measure_theory nnreal open set filter topological_space ennreal emetric measure_theory variables {α β γ δ : Type*} [measurable_space α] {μ ν : measure α} variables [normed_group β] variables [normed_group γ] namespace measure_theory /-! ### Some results about the Lebesgue integral involving a normed group -/ lemma lintegral_nnnorm_eq_lintegral_edist (f : α → β) : ∫⁻ a, nnnorm (f a) ∂μ = ∫⁻ a, edist (f a) 0 ∂μ := by simp only [edist_eq_coe_nnnorm] lemma lintegral_norm_eq_lintegral_edist (f : α → β) : ∫⁻ a, (ennreal.of_real ∥f a∥) ∂μ = ∫⁻ a, edist (f a) 0 ∂μ := by simp only [of_real_norm_eq_coe_nnnorm, edist_eq_coe_nnnorm] lemma lintegral_edist_triangle [second_countable_topology β] [measurable_space β] [opens_measurable_space β] {f g h : α → β} (hf : ae_measurable f μ) (hg : ae_measurable g μ) (hh : ae_measurable h μ) : ∫⁻ a, edist (f a) (g a) ∂μ ≤ ∫⁻ a, edist (f a) (h a) ∂μ + ∫⁻ a, edist (g a) (h a) ∂μ := begin rw ← lintegral_add' (hf.edist hh) (hg.edist hh), refine lintegral_mono (λ a, _), apply edist_triangle_right end lemma lintegral_nnnorm_zero : ∫⁻ a : α, nnnorm (0 : β) ∂μ = 0 := by simp lemma lintegral_nnnorm_add [measurable_space β] [opens_measurable_space β] [measurable_space γ] [opens_measurable_space γ] {f : α → β} {g : α → γ} (hf : ae_measurable f μ) (hg : ae_measurable g μ) : ∫⁻ a, nnnorm (f a) + nnnorm (g a) ∂μ = ∫⁻ a, nnnorm (f a) ∂μ + ∫⁻ a, nnnorm (g a) ∂μ := lintegral_add' hf.ennnorm hg.ennnorm lemma lintegral_nnnorm_neg {f : α → β} : ∫⁻ a, nnnorm ((-f) a) ∂μ = ∫⁻ a, nnnorm (f a) ∂μ := by simp only [pi.neg_apply, nnnorm_neg] /-! ### The predicate `has_finite_integral` -/ /-- `has_finite_integral f μ` means that the integral `∫⁻ a, ∥f a∥ ∂μ` is finite. `has_finite_integral f` means `has_finite_integral f volume`. -/ def has_finite_integral (f : α → β) (μ : measure α . volume_tac) : Prop := ∫⁻ a, nnnorm (f a) ∂μ < ∞ lemma has_finite_integral_iff_norm (f : α → β) : has_finite_integral f μ ↔ ∫⁻ a, (ennreal.of_real ∥f a∥) ∂μ < ∞ := by simp only [has_finite_integral, of_real_norm_eq_coe_nnnorm] lemma has_finite_integral_iff_edist (f : α → β) : has_finite_integral f μ ↔ ∫⁻ a, edist (f a) 0 ∂μ < ∞ := by simp only [has_finite_integral_iff_norm, edist_dist, dist_zero_right] lemma has_finite_integral_iff_of_real {f : α → ℝ} (h : 0 ≤ᵐ[μ] f) : has_finite_integral f μ ↔ ∫⁻ a, ennreal.of_real (f a) ∂μ < ∞ := have lintegral_eq : ∫⁻ a, (ennreal.of_real ∥f a∥) ∂μ = ∫⁻ a, ennreal.of_real (f a) ∂μ := begin refine lintegral_congr_ae (h.mono $ λ a h, _), rwa [real.norm_eq_abs, abs_of_nonneg] end, by rw [has_finite_integral_iff_norm, lintegral_eq] lemma has_finite_integral_iff_of_nnreal {f : α → ℝ≥0} : has_finite_integral (λ x, (f x : ℝ)) μ ↔ ∫⁻ a, f a ∂μ < ∞ := by simp [has_finite_integral_iff_norm] lemma has_finite_integral.mono {f : α → β} {g : α → γ} (hg : has_finite_integral g μ) (h : ∀ᵐ a ∂μ, ∥f a∥ ≤ ∥g a∥) : has_finite_integral f μ := begin simp only [has_finite_integral_iff_norm] at *, calc ∫⁻ a, (ennreal.of_real ∥f a∥) ∂μ ≤ ∫⁻ (a : α), (ennreal.of_real ∥g a∥) ∂μ : lintegral_mono_ae (h.mono $ assume a h, of_real_le_of_real h) ... < ∞ : hg end lemma has_finite_integral.mono' {f : α → β} {g : α → ℝ} (hg : has_finite_integral g μ) (h : ∀ᵐ a ∂μ, ∥f a∥ ≤ g a) : has_finite_integral f μ := hg.mono $ h.mono $ λ x hx, le_trans hx (le_abs_self _) lemma has_finite_integral.congr' {f : α → β} {g : α → γ} (hf : has_finite_integral f μ) (h : ∀ᵐ a ∂μ, ∥f a∥ = ∥g a∥) : has_finite_integral g μ := hf.mono $ eventually_eq.le $ eventually_eq.symm h lemma has_finite_integral_congr' {f : α → β} {g : α → γ} (h : ∀ᵐ a ∂μ, ∥f a∥ = ∥g a∥) : has_finite_integral f μ ↔ has_finite_integral g μ := ⟨λ hf, hf.congr' h, λ hg, hg.congr' $ eventually_eq.symm h⟩ lemma has_finite_integral.congr {f g : α → β} (hf : has_finite_integral f μ) (h : f =ᵐ[μ] g) : has_finite_integral g μ := hf.congr' $ h.fun_comp norm lemma has_finite_integral_congr {f g : α → β} (h : f =ᵐ[μ] g) : has_finite_integral f μ ↔ has_finite_integral g μ := has_finite_integral_congr' $ h.fun_comp norm lemma has_finite_integral_const_iff {c : β} : has_finite_integral (λ x : α, c) μ ↔ c = 0 ∨ μ univ < ∞ := begin simp only [has_finite_integral, lintegral_const], by_cases hc : c = 0, { simp [hc] }, { simp only [hc, false_or], refine ⟨λ h, _, λ h, mul_lt_top coe_lt_top h⟩, replace h := mul_lt_top (@coe_lt_top $ (nnnorm c)⁻¹) h, rwa [← mul_assoc, ← coe_mul, _root_.inv_mul_cancel, coe_one, one_mul] at h, rwa [ne.def, nnnorm_eq_zero] } end lemma has_finite_integral_const [finite_measure μ] (c : β) : has_finite_integral (λ x : α, c) μ := has_finite_integral_const_iff.2 (or.inr $ measure_lt_top _ _) lemma has_finite_integral_of_bounded [finite_measure μ] {f : α → β} {C : ℝ} (hC : ∀ᵐ a ∂μ, ∥f a∥ ≤ C) : has_finite_integral f μ := (has_finite_integral_const C).mono' hC lemma has_finite_integral.mono_measure {f : α → β} (h : has_finite_integral f ν) (hμ : μ ≤ ν) : has_finite_integral f μ := lt_of_le_of_lt (lintegral_mono' hμ (le_refl _)) h lemma has_finite_integral.add_measure {f : α → β} (hμ : has_finite_integral f μ) (hν : has_finite_integral f ν) : has_finite_integral f (μ + ν) := begin simp only [has_finite_integral, lintegral_add_measure] at *, exact add_lt_top.2 ⟨hμ, hν⟩ end lemma has_finite_integral.left_of_add_measure {f : α → β} (h : has_finite_integral f (μ + ν)) : has_finite_integral f μ := h.mono_measure $ measure.le_add_right $ le_refl _ lemma has_finite_integral.right_of_add_measure {f : α → β} (h : has_finite_integral f (μ + ν)) : has_finite_integral f ν := h.mono_measure $ measure.le_add_left $ le_refl _ @[simp] lemma has_finite_integral_add_measure {f : α → β} : has_finite_integral f (μ + ν) ↔ has_finite_integral f μ ∧ has_finite_integral f ν := ⟨λ h, ⟨h.left_of_add_measure, h.right_of_add_measure⟩, λ h, h.1.add_measure h.2⟩ lemma has_finite_integral.smul_measure {f : α → β} (h : has_finite_integral f μ) {c : ℝ≥0∞} (hc : c < ∞) : has_finite_integral f (c • μ) := begin simp only [has_finite_integral, lintegral_smul_measure] at *, exact mul_lt_top hc h end @[simp] lemma has_finite_integral_zero_measure (f : α → β) : has_finite_integral f 0 := by simp only [has_finite_integral, lintegral_zero_measure, with_top.zero_lt_top] variables (α β μ) @[simp] lemma has_finite_integral_zero : has_finite_integral (λa:α, (0:β)) μ := by simp [has_finite_integral] variables {α β μ} lemma has_finite_integral.neg {f : α → β} (hfi : has_finite_integral f μ) : has_finite_integral (-f) μ := by simpa [has_finite_integral] using hfi @[simp] lemma has_finite_integral_neg_iff {f : α → β} : has_finite_integral (-f) μ ↔ has_finite_integral f μ := ⟨λ h, neg_neg f ▸ h.neg, has_finite_integral.neg⟩ lemma has_finite_integral.norm {f : α → β} (hfi : has_finite_integral f μ) : has_finite_integral (λa, ∥f a∥) μ := have eq : (λa, (nnnorm ∥f a∥ : ℝ≥0∞)) = λa, (nnnorm (f a) : ℝ≥0∞), by { funext, rw nnnorm_norm }, by { rwa [has_finite_integral, eq] } lemma has_finite_integral_norm_iff (f : α → β) : has_finite_integral (λa, ∥f a∥) μ ↔ has_finite_integral f μ := has_finite_integral_congr' $ eventually_of_forall $ λ x, norm_norm (f x) section dominated_convergence variables {F : ℕ → α → β} {f : α → β} {bound : α → ℝ} lemma all_ae_of_real_F_le_bound (h : ∀ n, ∀ᵐ a ∂μ, ∥F n a∥ ≤ bound a) : ∀ n, ∀ᵐ a ∂μ, ennreal.of_real ∥F n a∥ ≤ ennreal.of_real (bound a) := λn, (h n).mono $ λ a h, ennreal.of_real_le_of_real h lemma all_ae_tendsto_of_real_norm (h : ∀ᵐ a ∂μ, tendsto (λ n, F n a) at_top $ 𝓝 $ f a) : ∀ᵐ a ∂μ, tendsto (λn, ennreal.of_real ∥F n a∥) at_top $ 𝓝 $ ennreal.of_real ∥f a∥ := h.mono $ λ a h, tendsto_of_real $ tendsto.comp (continuous.tendsto continuous_norm _) h lemma all_ae_of_real_f_le_bound (h_bound : ∀ n, ∀ᵐ a ∂μ, ∥F n a∥ ≤ bound a) (h_lim : ∀ᵐ a ∂μ, tendsto (λ n, F n a) at_top (𝓝 (f a))) : ∀ᵐ a ∂μ, ennreal.of_real ∥f a∥ ≤ ennreal.of_real (bound a) := begin have F_le_bound := all_ae_of_real_F_le_bound h_bound, rw ← ae_all_iff at F_le_bound, apply F_le_bound.mp ((all_ae_tendsto_of_real_norm h_lim).mono _), assume a tendsto_norm F_le_bound, exact le_of_tendsto' tendsto_norm (F_le_bound) end lemma has_finite_integral_of_dominated_convergence {F : ℕ → α → β} {f : α → β} {bound : α → ℝ} (bound_has_finite_integral : has_finite_integral bound μ) (h_bound : ∀ n, ∀ᵐ a ∂μ, ∥F n a∥ ≤ bound a) (h_lim : ∀ᵐ a ∂μ, tendsto (λ n, F n a) at_top (𝓝 (f a))) : has_finite_integral f μ := /- `∥F n a∥ ≤ bound a` and `∥F n a∥ --> ∥f a∥` implies `∥f a∥ ≤ bound a`, and so `∫ ∥f∥ ≤ ∫ bound < ∞` since `bound` is has_finite_integral -/ begin rw has_finite_integral_iff_norm, calc ∫⁻ a, (ennreal.of_real ∥f a∥) ∂μ ≤ ∫⁻ a, ennreal.of_real (bound a) ∂μ : lintegral_mono_ae $ all_ae_of_real_f_le_bound h_bound h_lim ... < ∞ : begin rw ← has_finite_integral_iff_of_real, { exact bound_has_finite_integral }, exact (h_bound 0).mono (λ a h, le_trans (norm_nonneg _) h) end end lemma tendsto_lintegral_norm_of_dominated_convergence [measurable_space β] [borel_space β] [second_countable_topology β] {F : ℕ → α → β} {f : α → β} {bound : α → ℝ} (F_measurable : ∀ n, ae_measurable (F n) μ) (f_measurable : ae_measurable f μ) (bound_has_finite_integral : has_finite_integral bound μ) (h_bound : ∀ n, ∀ᵐ a ∂μ, ∥F n a∥ ≤ bound a) (h_lim : ∀ᵐ a ∂μ, tendsto (λ n, F n a) at_top (𝓝 (f a))) : tendsto (λn, ∫⁻ a, (ennreal.of_real ∥F n a - f a∥) ∂μ) at_top (𝓝 0) := let b := λa, 2 * ennreal.of_real (bound a) in /- `∥F n a∥ ≤ bound a` and `F n a --> f a` implies `∥f a∥ ≤ bound a`, and thus by the triangle inequality, have `∥F n a - f a∥ ≤ 2 * (bound a). -/ have hb : ∀ n, ∀ᵐ a ∂μ, ennreal.of_real ∥F n a - f a∥ ≤ b a, begin assume n, filter_upwards [all_ae_of_real_F_le_bound h_bound n, all_ae_of_real_f_le_bound h_bound h_lim], assume a h₁ h₂, calc ennreal.of_real ∥F n a - f a∥ ≤ (ennreal.of_real ∥F n a∥) + (ennreal.of_real ∥f a∥) : begin rw [← ennreal.of_real_add], apply of_real_le_of_real, { apply norm_sub_le }, { exact norm_nonneg _ }, { exact norm_nonneg _ } end ... ≤ (ennreal.of_real (bound a)) + (ennreal.of_real (bound a)) : add_le_add h₁ h₂ ... = b a : by rw ← two_mul end, /- On the other hand, `F n a --> f a` implies that `∥F n a - f a∥ --> 0` -/ have h : ∀ᵐ a ∂μ, tendsto (λ n, ennreal.of_real ∥F n a - f a∥) at_top (𝓝 0), begin rw ← ennreal.of_real_zero, refine h_lim.mono (λ a h, (continuous_of_real.tendsto _).comp _), rwa ← tendsto_iff_norm_tendsto_zero end, /- Therefore, by the dominated convergence theorem for nonnegative integration, have ` ∫ ∥f a - F n a∥ --> 0 ` -/ begin suffices h : tendsto (λn, ∫⁻ a, (ennreal.of_real ∥F n a - f a∥) ∂μ) at_top (𝓝 (∫⁻ (a:α), 0 ∂μ)), { rwa lintegral_zero at h }, -- Using the dominated convergence theorem. refine tendsto_lintegral_of_dominated_convergence' _ _ hb _ _, -- Show `λa, ∥f a - F n a∥` is almost everywhere measurable for all `n` { exact λn, measurable_of_real.comp_ae_measurable ((F_measurable n).sub f_measurable).norm }, -- Show `2 * bound` is has_finite_integral { rw has_finite_integral_iff_of_real at bound_has_finite_integral, { calc ∫⁻ a, b a ∂μ = 2 * ∫⁻ a, ennreal.of_real (bound a) ∂μ : by { rw lintegral_const_mul', exact coe_ne_top } ... < ∞ : mul_lt_top (coe_lt_top) bound_has_finite_integral }, filter_upwards [h_bound 0] λ a h, le_trans (norm_nonneg _) h }, -- Show `∥f a - F n a∥ --> 0` { exact h } end end dominated_convergence section pos_part /-! Lemmas used for defining the positive part of a `L¹` function -/ lemma has_finite_integral.max_zero {f : α → ℝ} (hf : has_finite_integral f μ) : has_finite_integral (λa, max (f a) 0) μ := hf.mono $ eventually_of_forall $ λ x, by simp [real.norm_eq_abs, abs_le, abs_nonneg, le_abs_self] lemma has_finite_integral.min_zero {f : α → ℝ} (hf : has_finite_integral f μ) : has_finite_integral (λa, min (f a) 0) μ := hf.mono $ eventually_of_forall $ λ x, by simp [real.norm_eq_abs, abs_le, abs_nonneg, neg_le, neg_le_abs_self] end pos_part section normed_space variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β] lemma has_finite_integral.smul (c : 𝕜) {f : α → β} : has_finite_integral f μ → has_finite_integral (c • f) μ := begin simp only [has_finite_integral], assume hfi, calc ∫⁻ (a : α), nnnorm (c • f a) ∂μ = ∫⁻ (a : α), (nnnorm c) * nnnorm (f a) ∂μ : by simp only [nnnorm_smul, ennreal.coe_mul] ... < ∞ : begin rw lintegral_const_mul', exacts [mul_lt_top coe_lt_top hfi, coe_ne_top] end end lemma has_finite_integral_smul_iff {c : 𝕜} (hc : c ≠ 0) (f : α → β) : has_finite_integral (c • f) μ ↔ has_finite_integral f μ := begin split, { assume h, simpa only [smul_smul, inv_mul_cancel hc, one_smul] using h.smul c⁻¹ }, exact has_finite_integral.smul _ end lemma has_finite_integral.const_mul {f : α → ℝ} (h : has_finite_integral f μ) (c : ℝ) : has_finite_integral (λ x, c * f x) μ := (has_finite_integral.smul c h : _) lemma has_finite_integral.mul_const {f : α → ℝ} (h : has_finite_integral f μ) (c : ℝ) : has_finite_integral (λ x, f x * c) μ := by simp_rw [mul_comm, h.const_mul _] end normed_space /-! ### The predicate `integrable` -/ variables [measurable_space β] [measurable_space γ] [measurable_space δ] /-- `integrable f μ` means that `f` is measurable and that the integral `∫⁻ a, ∥f a∥ ∂μ` is finite. `integrable f` means `integrable f volume`. -/ def integrable (f : α → β) (μ : measure α . volume_tac) : Prop := ae_measurable f μ ∧ has_finite_integral f μ lemma integrable.ae_measurable {f : α → β} (hf : integrable f μ) : ae_measurable f μ := hf.1 lemma integrable.has_finite_integral {f : α → β} (hf : integrable f μ) : has_finite_integral f μ := hf.2 lemma integrable.mono {f : α → β} {g : α → γ} (hg : integrable g μ) (hf : ae_measurable f μ) (h : ∀ᵐ a ∂μ, ∥f a∥ ≤ ∥g a∥) : integrable f μ := ⟨hf, hg.has_finite_integral.mono h⟩ lemma integrable.mono' {f : α → β} {g : α → ℝ} (hg : integrable g μ) (hf : ae_measurable f μ) (h : ∀ᵐ a ∂μ, ∥f a∥ ≤ g a) : integrable f μ := ⟨hf, hg.has_finite_integral.mono' h⟩ lemma integrable.congr' {f : α → β} {g : α → γ} (hf : integrable f μ) (hg : ae_measurable g μ) (h : ∀ᵐ a ∂μ, ∥f a∥ = ∥g a∥) : integrable g μ := ⟨hg, hf.has_finite_integral.congr' h⟩ lemma integrable_congr' {f : α → β} {g : α → γ} (hf : ae_measurable f μ) (hg : ae_measurable g μ) (h : ∀ᵐ a ∂μ, ∥f a∥ = ∥g a∥) : integrable f μ ↔ integrable g μ := ⟨λ h2f, h2f.congr' hg h, λ h2g, h2g.congr' hf $ eventually_eq.symm h⟩ lemma integrable.congr {f g : α → β} (hf : integrable f μ) (h : f =ᵐ[μ] g) : integrable g μ := ⟨hf.1.congr h, hf.2.congr h⟩ lemma integrable_congr {f g : α → β} (h : f =ᵐ[μ] g) : integrable f μ ↔ integrable g μ := ⟨λ hf, hf.congr h, λ hg, hg.congr h.symm⟩ lemma integrable_const_iff {c : β} : integrable (λ x : α, c) μ ↔ c = 0 ∨ μ univ < ∞ := begin have : ae_measurable (λ (x : α), c) μ := measurable_const.ae_measurable, rw [integrable, and_iff_right this, has_finite_integral_const_iff] end lemma integrable_const [finite_measure μ] (c : β) : integrable (λ x : α, c) μ := integrable_const_iff.2 $ or.inr $ measure_lt_top _ _ lemma integrable.mono_measure {f : α → β} (h : integrable f ν) (hμ : μ ≤ ν) : integrable f μ := ⟨h.ae_measurable.mono_measure hμ, h.has_finite_integral.mono_measure hμ⟩ lemma integrable.add_measure {f : α → β} (hμ : integrable f μ) (hν : integrable f ν) : integrable f (μ + ν) := ⟨hμ.ae_measurable.add_measure hν.ae_measurable, hμ.has_finite_integral.add_measure hν.has_finite_integral⟩ lemma integrable.left_of_add_measure {f : α → β} (h : integrable f (μ + ν)) : integrable f μ := h.mono_measure $ measure.le_add_right $ le_refl _ lemma integrable.right_of_add_measure {f : α → β} (h : integrable f (μ + ν)) : integrable f ν := h.mono_measure $ measure.le_add_left $ le_refl _ @[simp] lemma integrable_add_measure {f : α → β} : integrable f (μ + ν) ↔ integrable f μ ∧ integrable f ν := ⟨λ h, ⟨h.left_of_add_measure, h.right_of_add_measure⟩, λ h, h.1.add_measure h.2⟩ lemma integrable.smul_measure {f : α → β} (h : integrable f μ) {c : ℝ≥0∞} (hc : c < ∞) : integrable f (c • μ) := ⟨h.ae_measurable.smul_measure c, h.has_finite_integral.smul_measure hc⟩ lemma integrable_map_measure [opens_measurable_space β] {f : α → δ} {g : δ → β} (hg : ae_measurable g (measure.map f μ)) (hf : measurable f) : integrable g (measure.map f μ) ↔ integrable (g ∘ f) μ := by simp [integrable, hg, hg.comp_measurable hf, has_finite_integral, lintegral_map' hg.ennnorm hf] lemma lintegral_edist_lt_top [second_countable_topology β] [opens_measurable_space β] {f g : α → β} (hf : integrable f μ) (hg : integrable g μ) : ∫⁻ a, edist (f a) (g a) ∂μ < ∞ := lt_of_le_of_lt (lintegral_edist_triangle hf.ae_measurable hg.ae_measurable (measurable_const.ae_measurable : ae_measurable (λa, (0 : β)) μ)) (ennreal.add_lt_top.2 $ by { simp_rw ← has_finite_integral_iff_edist, exact ⟨hf.has_finite_integral, hg.has_finite_integral⟩ }) variables (α β μ) @[simp] lemma integrable_zero : integrable (λ _, (0 : β)) μ := by simp [integrable, measurable_const.ae_measurable] variables {α β μ} lemma integrable.add' [opens_measurable_space β] {f g : α → β} (hf : integrable f μ) (hg : integrable g μ) : has_finite_integral (f + g) μ := calc ∫⁻ a, nnnorm (f a + g a) ∂μ ≤ ∫⁻ a, nnnorm (f a) + nnnorm (g a) ∂μ : lintegral_mono (λ a, by exact_mod_cast nnnorm_add_le _ _) ... = _ : lintegral_nnnorm_add hf.ae_measurable hg.ae_measurable ... < ∞ : add_lt_top.2 ⟨hf.has_finite_integral, hg.has_finite_integral⟩ lemma integrable.add [borel_space β] [second_countable_topology β] {f g : α → β} (hf : integrable f μ) (hg : integrable g μ) : integrable (f + g) μ := ⟨hf.ae_measurable.add hg.ae_measurable, hf.add' hg⟩ lemma integrable_finset_sum {ι} [borel_space β] [second_countable_topology β] (s : finset ι) {f : ι → α → β} (hf : ∀ i, integrable (f i) μ) : integrable (λ a, ∑ i in s, f i a) μ := begin refine finset.induction_on s _ _, { simp only [finset.sum_empty, integrable_zero] }, { assume i s his ih, simp only [his, finset.sum_insert, not_false_iff], exact (hf _).add ih } end lemma integrable.neg [borel_space β] {f : α → β} (hf : integrable f μ) : integrable (-f) μ := ⟨hf.ae_measurable.neg, hf.has_finite_integral.neg⟩ @[simp] lemma integrable_neg_iff [borel_space β] {f : α → β} : integrable (-f) μ ↔ integrable f μ := ⟨λ h, neg_neg f ▸ h.neg, integrable.neg⟩ lemma integrable.sub' [opens_measurable_space β] {f g : α → β} (hf : integrable f μ) (hg : integrable g μ) : has_finite_integral (f - g) μ := calc ∫⁻ a, nnnorm (f a - g a) ∂μ ≤ ∫⁻ a, nnnorm (f a) + nnnorm (-g a) ∂μ : lintegral_mono (assume a, by { simp only [sub_eq_add_neg], exact_mod_cast nnnorm_add_le _ _ } ) ... = _ : by { simp only [nnnorm_neg], exact lintegral_nnnorm_add hf.ae_measurable hg.ae_measurable } ... < ∞ : add_lt_top.2 ⟨hf.has_finite_integral, hg.has_finite_integral⟩ lemma integrable.sub [borel_space β] [second_countable_topology β] {f g : α → β} (hf : integrable f μ) (hg : integrable g μ) : integrable (f - g) μ := by simpa only [sub_eq_add_neg] using hf.add hg.neg lemma integrable.norm [opens_measurable_space β] {f : α → β} (hf : integrable f μ) : integrable (λa, ∥f a∥) μ := ⟨hf.ae_measurable.norm, hf.has_finite_integral.norm⟩ lemma integrable_norm_iff [opens_measurable_space β] {f : α → β} (hf : ae_measurable f μ) : integrable (λa, ∥f a∥) μ ↔ integrable f μ := by simp_rw [integrable, and_iff_right hf, and_iff_right hf.norm, has_finite_integral_norm_iff] lemma integrable_of_norm_sub_le [opens_measurable_space β] {f₀ f₁ : α → β} {g : α → ℝ} (hf₁_m : ae_measurable f₁ μ) (hf₀_i : integrable f₀ μ) (hg_i : integrable g μ) (h : ∀ᵐ a ∂μ, ∥f₀ a - f₁ a∥ ≤ g a) : integrable f₁ μ := begin have : ∀ᵐ a ∂μ, ∥f₁ a∥ ≤ ∥f₀ a∥ + g a, { apply h.mono, intros a ha, calc ∥f₁ a∥ ≤ ∥f₀ a∥ + ∥f₀ a - f₁ a∥ : norm_le_insert _ _ ... ≤ ∥f₀ a∥ + g a : add_le_add_left ha _ }, exact integrable.mono' (hf₀_i.norm.add hg_i) hf₁_m this end lemma integrable.prod_mk [opens_measurable_space β] [opens_measurable_space γ] {f : α → β} {g : α → γ} (hf : integrable f μ) (hg : integrable g μ) : integrable (λ x, (f x, g x)) μ := ⟨hf.ae_measurable.prod_mk hg.ae_measurable, (hf.norm.add' hg.norm).mono $ eventually_of_forall $ λ x, calc max ∥f x∥ ∥g x∥ ≤ ∥f x∥ + ∥g x∥ : max_le_add_of_nonneg (norm_nonneg _) (norm_nonneg _) ... ≤ ∥(∥f x∥ + ∥g x∥)∥ : le_abs_self _⟩ lemma mem_ℒp_one_iff_integrable {f : α → β} : mem_ℒp f 1 μ ↔ integrable f μ := by simp_rw [integrable, has_finite_integral, mem_ℒp, snorm_one_eq_lintegral_nnnorm] lemma mem_ℒp.integrable [borel_space β] {q : ℝ≥0∞} (hq1 : 1 ≤ q) {f : α → β} [finite_measure μ] (hfq : mem_ℒp f q μ) : integrable f μ := mem_ℒp_one_iff_integrable.mp (hfq.mem_ℒp_of_exponent_le hq1) lemma lipschitz_with.integrable_comp_iff_of_antilipschitz [complete_space β] [borel_space β] [borel_space γ] {K K'} {f : α → β} {g : β → γ} (hg : lipschitz_with K g) (hg' : antilipschitz_with K' g) (g0 : g 0 = 0) : integrable (g ∘ f) μ ↔ integrable f μ := by simp [← mem_ℒp_one_iff_integrable, hg.mem_ℒp_comp_iff_of_antilipschitz hg' g0] lemma integrable.real_to_nnreal {f : α → ℝ} (hf : integrable f μ) : integrable (λ x, ((f x).to_nnreal : ℝ)) μ := begin refine ⟨hf.ae_measurable.real_to_nnreal.coe_nnreal_real, _⟩, rw has_finite_integral_iff_norm, refine lt_of_le_of_lt _ ((has_finite_integral_iff_norm _).1 hf.has_finite_integral), apply lintegral_mono, assume x, simp [real.norm_eq_abs, ennreal.of_real_le_of_real, abs_le, abs_nonneg, le_abs_self], end section pos_part /-! ### Lemmas used for defining the positive part of a `L¹` function -/ lemma integrable.max_zero {f : α → ℝ} (hf : integrable f μ) : integrable (λa, max (f a) 0) μ := ⟨hf.ae_measurable.max measurable_const.ae_measurable, hf.has_finite_integral.max_zero⟩ lemma integrable.min_zero {f : α → ℝ} (hf : integrable f μ) : integrable (λa, min (f a) 0) μ := ⟨hf.ae_measurable.min measurable_const.ae_measurable, hf.has_finite_integral.min_zero⟩ end pos_part section normed_space variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β] [measurable_space 𝕜] [opens_measurable_space 𝕜] lemma integrable.smul [borel_space β] (c : 𝕜) {f : α → β} (hf : integrable f μ) : integrable (c • f) μ := ⟨hf.ae_measurable.const_smul c, hf.has_finite_integral.smul c⟩ lemma integrable_smul_iff [borel_space β] {c : 𝕜} (hc : c ≠ 0) (f : α → β) : integrable (c • f) μ ↔ integrable f μ := and_congr (ae_measurable_const_smul_iff' hc) (has_finite_integral_smul_iff hc f) lemma integrable.const_mul {f : α → ℝ} (h : integrable f μ) (c : ℝ) : integrable (λ x, c * f x) μ := integrable.smul c h lemma integrable.mul_const {f : α → ℝ} (h : integrable f μ) (c : ℝ) : integrable (λ x, f x * c) μ := by simp_rw [mul_comm, h.const_mul _] end normed_space section normed_space_over_complete_field variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] [complete_space 𝕜] [measurable_space 𝕜] variables [borel_space 𝕜] variables {E : Type*} [normed_group E] [normed_space 𝕜 E] [measurable_space E] [borel_space E] lemma integrable_smul_const {f : α → 𝕜} {c : E} (hc : c ≠ 0) : integrable (λ x, f x • c) μ ↔ integrable f μ := begin simp_rw [integrable, ae_measurable_smul_const hc, and.congr_right_iff, has_finite_integral, nnnorm_smul, ennreal.coe_mul], intro hf, rw [lintegral_mul_const' _ _ ennreal.coe_ne_top, ennreal.mul_lt_top_iff], have : ∀ x : ℝ≥0∞, x = 0 → x < ∞ := by simp, simp [hc, or_iff_left_of_imp (this _)] end end normed_space_over_complete_field section trim variables {H α' : Type*} [normed_group H] [measurable_space H] {m m0 : measurable_space α'} {μ' : measure α'} lemma integrable.trim (hm : m ≤ m0) [opens_measurable_space H] {f : α' → H} (hf_int : integrable f μ') (hf : @measurable _ _ m _ f) : @integrable _ _ m _ _ f (μ'.trim hm) := begin refine ⟨@measurable.ae_measurable α' _ m _ f (μ'.trim hm) hf, _⟩, rw [has_finite_integral, lintegral_trim hm _], { exact hf_int.2, }, { exact @measurable.coe_nnreal_ennreal α' m _ (@measurable.nnnorm _ α' _ _ _ m _ hf), }, end lemma integrable_of_integrable_trim (hm : m ≤ m0) [opens_measurable_space H] {f : α' → H} (hf_int : @integrable α' H m _ _ f (μ'.trim hm)) : integrable f μ' := begin obtain ⟨hf_meas_ae, hf⟩ := hf_int, refine ⟨ae_measurable_of_ae_measurable_trim hm hf_meas_ae, _⟩, rw has_finite_integral at hf ⊢, rwa lintegral_trim_ae hm _ at hf, exact @ae_measurable.coe_nnreal_ennreal α' m _ _ (@ae_measurable.nnnorm H α' _ _ _ m _ _ hf_meas_ae), end end trim section sigma_finite variables {α' E : Type*} {m m0 : measurable_space α'} [normed_group E] [measurable_space E] [opens_measurable_space E] lemma integrable_of_forall_fin_meas_le' {μ : measure α'} (hm : m ≤ m0) [@sigma_finite _ m (μ.trim hm)] (C : ℝ≥0∞) (hC : C < ∞) {f : α' → E} (hf_meas : ae_measurable f μ) (hf : ∀ s, measurable_set[m] s → μ s ≠ ∞ → ∫⁻ x in s, nnnorm (f x) ∂μ ≤ C) : integrable f μ := ⟨hf_meas, (lintegral_le_of_forall_fin_meas_le' hm C hf_meas.nnnorm.coe_nnreal_ennreal hf).trans_lt hC⟩ lemma integrable_of_forall_fin_meas_le [sigma_finite μ] (C : ℝ≥0∞) (hC : C < ∞) {f : α → E} (hf_meas : ae_measurable f μ) (hf : ∀ s : set α, measurable_set s → μ s ≠ ∞ → ∫⁻ x in s, nnnorm (f x) ∂μ ≤ C) : integrable f μ := @integrable_of_forall_fin_meas_le' _ _ _ _ _ _ _ _ le_rfl (by rwa trim_eq_self) C hC _ hf_meas hf end sigma_finite /-! ### The predicate `integrable` on measurable functions modulo a.e.-equality -/ namespace ae_eq_fun section /-- A class of almost everywhere equal functions is `integrable` if its function representative is integrable. -/ def integrable (f : α →ₘ[μ] β) : Prop := integrable f μ lemma integrable_mk {f : α → β} (hf : ae_measurable f μ ) : (integrable (mk f hf : α →ₘ[μ] β)) ↔ measure_theory.integrable f μ := begin simp [integrable], apply integrable_congr, exact coe_fn_mk f hf end lemma integrable_coe_fn {f : α →ₘ[μ] β} : (measure_theory.integrable f μ) ↔ integrable f := by rw [← integrable_mk, mk_coe_fn] lemma integrable_zero : integrable (0 : α →ₘ[μ] β) := (integrable_zero α β μ).congr (coe_fn_mk _ _).symm end section variables [borel_space β] lemma integrable.neg {f : α →ₘ[μ] β} : integrable f → integrable (-f) := induction_on f $ λ f hfm hfi, (integrable_mk _).2 ((integrable_mk hfm).1 hfi).neg section variable [second_countable_topology β] lemma integrable_iff_mem_L1 {f : α →ₘ[μ] β} : integrable f ↔ f ∈ (α →₁[μ] β) := by rw [← integrable_coe_fn, ← mem_ℒp_one_iff_integrable, Lp.mem_Lp_iff_mem_ℒp] lemma integrable.add {f g : α →ₘ[μ] β} : integrable f → integrable g → integrable (f + g) := begin refine induction_on₂ f g (λ f hf g hg hfi hgi, _), simp only [integrable_mk, mk_add_mk] at hfi hgi ⊢, exact hfi.add hgi end lemma integrable.sub {f g : α →ₘ[μ] β} (hf : integrable f) (hg : integrable g) : integrable (f - g) := (sub_eq_add_neg f g).symm ▸ hf.add hg.neg end section normed_space variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β] [measurable_space 𝕜] [opens_measurable_space 𝕜] lemma integrable.smul {c : 𝕜} {f : α →ₘ[μ] β} : integrable f → integrable (c • f) := induction_on f $ λ f hfm hfi, (integrable_mk _).2 $ ((integrable_mk hfm).1 hfi).smul _ end normed_space end end ae_eq_fun namespace L1 variables [second_countable_topology β] [borel_space β] lemma integrable_coe_fn (f : α →₁[μ] β) : integrable f μ := by { rw ← mem_ℒp_one_iff_integrable, exact Lp.mem_ℒp f } lemma has_finite_integral_coe_fn (f : α →₁[μ] β) : has_finite_integral f μ := (integrable_coe_fn f).has_finite_integral lemma measurable_coe_fn (f : α →₁[μ] β) : measurable f := Lp.measurable f lemma ae_measurable_coe_fn (f : α →₁[μ] β) : ae_measurable f μ := Lp.ae_measurable f lemma edist_def (f g : α →₁[μ] β) : edist f g = ∫⁻ a, edist (f a) (g a) ∂μ := by { simp [Lp.edist_def, snorm, snorm'], simp [edist_eq_coe_nnnorm_sub] } lemma dist_def (f g : α →₁[μ] β) : dist f g = (∫⁻ a, edist (f a) (g a) ∂μ).to_real := by { simp [Lp.dist_def, snorm, snorm'], simp [edist_eq_coe_nnnorm_sub] } lemma norm_def (f : α →₁[μ] β) : ∥f∥ = (∫⁻ a, nnnorm (f a) ∂μ).to_real := by { simp [Lp.norm_def, snorm, snorm'] } /-- Computing the norm of a difference between two L¹-functions. Note that this is not a special case of `norm_def` since `(f - g) x` and `f x - g x` are not equal (but only a.e.-equal). -/ lemma norm_sub_eq_lintegral (f g : α →₁[μ] β) : ∥f - g∥ = (∫⁻ x, (nnnorm (f x - g x) : ℝ≥0∞) ∂μ).to_real := begin rw [norm_def], congr' 1, rw lintegral_congr_ae, filter_upwards [Lp.coe_fn_sub f g], assume a ha, simp only [ha, pi.sub_apply], end lemma of_real_norm_eq_lintegral (f : α →₁[μ] β) : ennreal.of_real ∥f∥ = ∫⁻ x, (nnnorm (f x) : ℝ≥0∞) ∂μ := by { rw [norm_def, ennreal.of_real_to_real], rw [← ennreal.lt_top_iff_ne_top], exact has_finite_integral_coe_fn f } /-- Computing the norm of a difference between two L¹-functions. Note that this is not a special case of `of_real_norm_eq_lintegral` since `(f - g) x` and `f x - g x` are not equal (but only a.e.-equal). -/ lemma of_real_norm_sub_eq_lintegral (f g : α →₁[μ] β) : ennreal.of_real ∥f - g∥ = ∫⁻ x, (nnnorm (f x - g x) : ℝ≥0∞) ∂μ := begin simp_rw [of_real_norm_eq_lintegral, ← edist_eq_coe_nnnorm], apply lintegral_congr_ae, filter_upwards [Lp.coe_fn_sub f g], assume a ha, simp only [ha, pi.sub_apply], end end L1 namespace integrable variables [second_countable_topology β] [borel_space β] /-- Construct the equivalence class `[f]` of an integrable function `f`, as a member of the space `L1 β 1 μ`. -/ def to_L1 (f : α → β) (hf : integrable f μ) : α →₁[μ] β := (mem_ℒp_one_iff_integrable.2 hf).to_Lp f @[simp] lemma to_L1_coe_fn (f : α →₁[μ] β) (hf : integrable f μ) : hf.to_L1 f = f := by simp [integrable.to_L1] lemma coe_fn_to_L1 {f : α → β} (hf : integrable f μ) : hf.to_L1 f =ᵐ[μ] f := ae_eq_fun.coe_fn_mk _ _ @[simp] lemma to_L1_zero (h : integrable (0 : α → β) μ) : h.to_L1 0 = 0 := rfl @[simp] lemma to_L1_eq_mk (f : α → β) (hf : integrable f μ) : (hf.to_L1 f : α →ₘ[μ] β) = ae_eq_fun.mk f hf.ae_measurable := rfl @[simp] lemma to_L1_eq_to_L1_iff (f g : α → β) (hf : integrable f μ) (hg : integrable g μ) : to_L1 f hf = to_L1 g hg ↔ f =ᵐ[μ] g := mem_ℒp.to_Lp_eq_to_Lp_iff _ _ lemma to_L1_add (f g : α → β) (hf : integrable f μ) (hg : integrable g μ) : to_L1 (f + g) (hf.add hg) = to_L1 f hf + to_L1 g hg := rfl lemma to_L1_neg (f : α → β) (hf : integrable f μ) : to_L1 (- f) (integrable.neg hf) = - to_L1 f hf := rfl lemma to_L1_sub (f g : α → β) (hf : integrable f μ) (hg : integrable g μ) : to_L1 (f - g) (hf.sub hg) = to_L1 f hf - to_L1 g hg := rfl lemma norm_to_L1 (f : α → β) (hf : integrable f μ) : ∥hf.to_L1 f∥ = ennreal.to_real (∫⁻ a, edist (f a) 0 ∂μ) := by { simp [to_L1, snorm, snorm'], simp [edist_eq_coe_nnnorm] } lemma norm_to_L1_eq_lintegral_norm (f : α → β) (hf : integrable f μ) : ∥hf.to_L1 f∥ = ennreal.to_real (∫⁻ a, (ennreal.of_real ∥f a∥) ∂μ) := by { rw [norm_to_L1, lintegral_norm_eq_lintegral_edist] } @[simp] lemma edist_to_L1_to_L1 (f g : α → β) (hf : integrable f μ) (hg : integrable g μ) : edist (hf.to_L1 f) (hg.to_L1 g) = ∫⁻ a, edist (f a) (g a) ∂μ := by { simp [integrable.to_L1, snorm, snorm'], simp [edist_eq_coe_nnnorm_sub] } @[simp] lemma edist_to_L1_zero (f : α → β) (hf : integrable f μ) : edist (hf.to_L1 f) 0 = ∫⁻ a, edist (f a) 0 ∂μ := by { simp [integrable.to_L1, snorm, snorm'], simp [edist_eq_coe_nnnorm] } variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β] [measurable_space 𝕜] [opens_measurable_space 𝕜] lemma to_L1_smul (f : α → β) (hf : integrable f μ) (k : 𝕜) : to_L1 (λa, k • f a) (hf.smul k) = k • to_L1 f hf := rfl end integrable end measure_theory open measure_theory lemma integrable_zero_measure [measurable_space β] {f : α → β} : integrable f 0 := begin apply (integrable_zero _ _ _).congr, change (0 : measure α) {x | 0 ≠ f x} = 0, refl, end variables {E : Type*} [normed_group E] [measurable_space E] [borel_space E] [normed_space ℝ E] {H : Type*} [normed_group H] [normed_space ℝ H] lemma measure_theory.integrable.apply_continuous_linear_map {φ : α → H →L[ℝ] E} (φ_int : integrable φ μ) (v : H) : integrable (λ a, φ a v) μ := (φ_int.norm.mul_const ∥v∥).mono' (φ_int.ae_measurable.apply_continuous_linear_map v) (eventually_of_forall $ λ a, (φ a).le_op_norm v) variables {𝕜 : Type*} [is_R_or_C 𝕜] {G : Type*} [normed_group G] [normed_space 𝕜 G] [measurable_space G] [borel_space G] {F : Type*} [normed_group F] [normed_space 𝕜 F] [measurable_space F] [opens_measurable_space F] lemma continuous_linear_map.integrable_comp {φ : α → F} (L : F →L[𝕜] G) (φ_int : integrable φ μ) : integrable (λ (a : α), L (φ a)) μ := ((integrable.norm φ_int).const_mul ∥L∥).mono' (L.measurable.comp_ae_measurable φ_int.ae_measurable) (eventually_of_forall $ λ a, L.le_op_norm (φ a))
100fd940d27697c0bcf4fefb5e53905c56534fde
c777c32c8e484e195053731103c5e52af26a25d1
/src/analysis/matrix.lean
aef241badd38074b9569a7e146ada32485a858d5
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
20,653
lean
/- Copyright (c) 2021 Heather Macbeth. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Heather Macbeth, Eric Wieser -/ import analysis.normed_space.basic import analysis.normed_space.pi_Lp import analysis.inner_product_space.pi_L2 /-! # Matrices as a normed space In this file we provide the following non-instances for norms on matrices: * The elementwise norm: * `matrix.seminormed_add_comm_group` * `matrix.normed_add_comm_group` * `matrix.normed_space` * The Frobenius norm: * `matrix.frobenius_seminormed_add_comm_group` * `matrix.frobenius_normed_add_comm_group` * `matrix.frobenius_normed_space` * `matrix.frobenius_normed_ring` * `matrix.frobenius_normed_algebra` * The $L^\infty$ operator norm: * `matrix.linfty_op_seminormed_add_comm_group` * `matrix.linfty_op_normed_add_comm_group` * `matrix.linfty_op_normed_space` * `matrix.linfty_op_non_unital_semi_normed_ring` * `matrix.linfty_op_semi_normed_ring` * `matrix.linfty_op_non_unital_normed_ring` * `matrix.linfty_op_normed_ring` * `matrix.linfty_op_normed_algebra` These are not declared as instances because there are several natural choices for defining the norm of a matrix. -/ noncomputable theory open_locale big_operators nnreal matrix namespace matrix variables {R l m n α β : Type*} [fintype l] [fintype m] [fintype n] /-! ### The elementwise supremum norm -/ section linf_linf section seminormed_add_comm_group variables [seminormed_add_comm_group α] [seminormed_add_comm_group β] /-- Seminormed group instance (using sup norm of sup norm) for matrices over a seminormed group. Not declared as an instance because there are several natural choices for defining the norm of a matrix. -/ protected def seminormed_add_comm_group : seminormed_add_comm_group (matrix m n α) := pi.seminormed_add_comm_group local attribute [instance] matrix.seminormed_add_comm_group lemma norm_le_iff {r : ℝ} (hr : 0 ≤ r) {A : matrix m n α} : ‖A‖ ≤ r ↔ ∀ i j, ‖A i j‖ ≤ r := by simp [pi_norm_le_iff_of_nonneg hr] lemma nnnorm_le_iff {r : ℝ≥0} {A : matrix m n α} : ‖A‖₊ ≤ r ↔ ∀ i j, ‖A i j‖₊ ≤ r := by simp [pi_nnnorm_le_iff] lemma norm_lt_iff {r : ℝ} (hr : 0 < r) {A : matrix m n α} : ‖A‖ < r ↔ ∀ i j, ‖A i j‖ < r := by simp [pi_norm_lt_iff hr] lemma nnnorm_lt_iff {r : ℝ≥0} (hr : 0 < r) {A : matrix m n α} : ‖A‖₊ < r ↔ ∀ i j, ‖A i j‖₊ < r := by simp [pi_nnnorm_lt_iff hr] lemma norm_entry_le_entrywise_sup_norm (A : matrix m n α) {i : m} {j : n} : ‖A i j‖ ≤ ‖A‖ := (norm_le_pi_norm (A i) j).trans (norm_le_pi_norm A i) lemma nnnorm_entry_le_entrywise_sup_nnnorm (A : matrix m n α) {i : m} {j : n} : ‖A i j‖₊ ≤ ‖A‖₊ := (nnnorm_le_pi_nnnorm (A i) j).trans (nnnorm_le_pi_nnnorm A i) @[simp] lemma nnnorm_map_eq (A : matrix m n α) (f : α → β) (hf : ∀ a, ‖f a‖₊ = ‖a‖₊) : ‖A.map f‖₊ = ‖A‖₊ := by simp_rw [pi.nnnorm_def, matrix.map_apply, hf] @[simp] lemma norm_map_eq (A : matrix m n α) (f : α → β) (hf : ∀ a, ‖f a‖ = ‖a‖) : ‖A.map f‖ = ‖A‖ := (congr_arg (coe : ℝ≥0 → ℝ) $ nnnorm_map_eq A f $ λ a, subtype.ext $ hf a : _) @[simp] lemma nnnorm_transpose (A : matrix m n α) : ‖Aᵀ‖₊ = ‖A‖₊ := by { simp_rw [pi.nnnorm_def], exact finset.sup_comm _ _ _ } @[simp] lemma norm_transpose (A : matrix m n α) : ‖Aᵀ‖ = ‖A‖ := congr_arg coe $ nnnorm_transpose A @[simp] lemma nnnorm_conj_transpose [star_add_monoid α] [normed_star_group α] (A : matrix m n α) : ‖Aᴴ‖₊ = ‖A‖₊ := (nnnorm_map_eq _ _ nnnorm_star).trans A.nnnorm_transpose @[simp] lemma norm_conj_transpose [star_add_monoid α] [normed_star_group α] (A : matrix m n α) : ‖Aᴴ‖ = ‖A‖ := congr_arg coe $ nnnorm_conj_transpose A instance [star_add_monoid α] [normed_star_group α] : normed_star_group (matrix m m α) := ⟨norm_conj_transpose⟩ @[simp] lemma nnnorm_col (v : m → α) : ‖col v‖₊ = ‖v‖₊ := by simp [pi.nnnorm_def] @[simp] lemma norm_col (v : m → α) : ‖col v‖ = ‖v‖ := congr_arg coe $ nnnorm_col v @[simp] lemma nnnorm_row (v : n → α) : ‖row v‖₊ = ‖v‖₊ := by simp [pi.nnnorm_def] @[simp] lemma norm_row (v : n → α) : ‖row v‖ = ‖v‖ := congr_arg coe $ nnnorm_row v @[simp] lemma nnnorm_diagonal [decidable_eq n] (v : n → α) : ‖diagonal v‖₊ = ‖v‖₊ := begin simp_rw pi.nnnorm_def, congr' 1 with i : 1, refine le_antisymm (finset.sup_le $ λ j hj, _) _, { obtain rfl | hij := eq_or_ne i j, { rw diagonal_apply_eq }, { rw [diagonal_apply_ne _ hij, nnnorm_zero], exact zero_le _ }, }, { refine eq.trans_le _ (finset.le_sup (finset.mem_univ i)), rw diagonal_apply_eq } end @[simp] lemma norm_diagonal [decidable_eq n] (v : n → α) : ‖diagonal v‖ = ‖v‖ := congr_arg coe $ nnnorm_diagonal v /-- Note this is safe as an instance as it carries no data. -/ @[nolint fails_quickly] instance [nonempty n] [decidable_eq n] [has_one α] [norm_one_class α] : norm_one_class (matrix n n α) := ⟨(norm_diagonal _).trans $ norm_one⟩ end seminormed_add_comm_group /-- Normed group instance (using sup norm of sup norm) for matrices over a normed group. Not declared as an instance because there are several natural choices for defining the norm of a matrix. -/ protected def normed_add_comm_group [normed_add_comm_group α] : normed_add_comm_group (matrix m n α) := pi.normed_add_comm_group section normed_space local attribute [instance] matrix.seminormed_add_comm_group variables [normed_field R] [seminormed_add_comm_group α] [normed_space R α] /-- Normed space instance (using sup norm of sup norm) for matrices over a normed space. Not declared as an instance because there are several natural choices for defining the norm of a matrix. -/ protected def normed_space : normed_space R (matrix m n α) := pi.normed_space end normed_space end linf_linf /-! ### The $L_\infty$ operator norm This section defines the matrix norm $\|A\|_\infty = \operatorname{sup}_i (\sum_j \|A_{ij}\|)$. Note that this is equivalent to the operator norm, considering $A$ as a linear map between two $L^\infty$ spaces. -/ section linfty_op /-- Seminormed group instance (using sup norm of L1 norm) for matrices over a seminormed group. Not declared as an instance because there are several natural choices for defining the norm of a matrix. -/ local attribute [instance] protected def linfty_op_seminormed_add_comm_group [seminormed_add_comm_group α] : seminormed_add_comm_group (matrix m n α) := (by apply_instance : seminormed_add_comm_group (m → pi_Lp 1 (λ j : n, α))) /-- Normed group instance (using sup norm of L1 norm) for matrices over a normed ring. Not declared as an instance because there are several natural choices for defining the norm of a matrix. -/ local attribute [instance] protected def linfty_op_normed_add_comm_group [normed_add_comm_group α] : normed_add_comm_group (matrix m n α) := (by apply_instance : normed_add_comm_group (m → pi_Lp 1 (λ j : n, α))) /-- Normed space instance (using sup norm of L1 norm) for matrices over a normed space. Not declared as an instance because there are several natural choices for defining the norm of a matrix. -/ local attribute [instance] protected def linfty_op_normed_space [normed_field R] [seminormed_add_comm_group α] [normed_space R α] : normed_space R (matrix m n α) := (by apply_instance : normed_space R (m → pi_Lp 1 (λ j : n, α))) section seminormed_add_comm_group variables [seminormed_add_comm_group α] lemma linfty_op_norm_def (A : matrix m n α) : ‖A‖ = ((finset.univ : finset m).sup (λ i : m, ∑ j : n, ‖A i j‖₊) : ℝ≥0) := by simp [pi.norm_def, pi_Lp.nnnorm_eq_sum ennreal.one_ne_top] lemma linfty_op_nnnorm_def (A : matrix m n α) : ‖A‖₊ = (finset.univ : finset m).sup (λ i : m, ∑ j : n, ‖A i j‖₊) := subtype.ext $ linfty_op_norm_def A @[simp] lemma linfty_op_nnnorm_col (v : m → α) : ‖col v‖₊ = ‖v‖₊ := begin rw [linfty_op_nnnorm_def, pi.nnnorm_def], simp, end @[simp] lemma linfty_op_norm_col (v : m → α) : ‖col v‖ = ‖v‖ := congr_arg coe $ linfty_op_nnnorm_col v @[simp] lemma linfty_op_nnnorm_row (v : n → α) : ‖row v‖₊ = ∑ i, ‖v i‖₊ := by simp [linfty_op_nnnorm_def] @[simp] lemma linfty_op_norm_row (v : n → α) : ‖row v‖ = ∑ i, ‖v i‖ := (congr_arg coe $ linfty_op_nnnorm_row v).trans $ by simp [nnreal.coe_sum] @[simp] lemma linfty_op_nnnorm_diagonal [decidable_eq m] (v : m → α) : ‖diagonal v‖₊ = ‖v‖₊ := begin rw [linfty_op_nnnorm_def, pi.nnnorm_def], congr' 1 with i : 1, refine (finset.sum_eq_single_of_mem _ (finset.mem_univ i) $ λ j hj hij, _).trans _, { rw [diagonal_apply_ne' _ hij, nnnorm_zero] }, { rw [diagonal_apply_eq] }, end @[simp] lemma linfty_op_norm_diagonal [decidable_eq m] (v : m → α) : ‖diagonal v‖ = ‖v‖ := congr_arg coe $ linfty_op_nnnorm_diagonal v end seminormed_add_comm_group section non_unital_semi_normed_ring variables [non_unital_semi_normed_ring α] lemma linfty_op_nnnorm_mul (A : matrix l m α) (B : matrix m n α) : ‖A ⬝ B‖₊ ≤ ‖A‖₊ * ‖B‖₊ := begin simp_rw [linfty_op_nnnorm_def, matrix.mul_apply], calc finset.univ.sup (λ i, ∑ k, ‖∑ j, A i j * B j k‖₊) ≤ finset.univ.sup (λ i, ∑ k j, ‖A i j‖₊ * ‖B j k‖₊) : finset.sup_mono_fun $ λ i hi, finset.sum_le_sum $ λ k hk, nnnorm_sum_le_of_le _ $ λ j hj, nnnorm_mul_le _ _ ... = finset.univ.sup (λ i, ∑ j, (‖A i j‖₊ * ∑ k, ‖B j k‖₊)) : by simp_rw [@finset.sum_comm _ m n, finset.mul_sum] ... ≤ finset.univ.sup (λ i, ∑ j, ‖A i j‖₊ * finset.univ.sup (λ i, ∑ j, ‖B i j‖₊)) : finset.sup_mono_fun $ λ i hi, finset.sum_le_sum $ λ j hj, mul_le_mul_of_nonneg_left (finset.le_sup hj) (zero_le _) ... ≤ finset.univ.sup (λ i, ∑ j, ‖A i j‖₊) * finset.univ.sup (λ i, ∑ j, ‖B i j‖₊) : by simp_rw [←finset.sum_mul, ←nnreal.finset_sup_mul], end lemma linfty_op_norm_mul (A : matrix l m α) (B : matrix m n α) : ‖A ⬝ B‖ ≤ ‖A‖ * ‖B‖ := linfty_op_nnnorm_mul _ _ lemma linfty_op_nnnorm_mul_vec (A : matrix l m α) (v : m → α) : ‖A.mul_vec v‖₊ ≤ ‖A‖₊ * ‖v‖₊ := begin rw [←linfty_op_nnnorm_col (A.mul_vec v), ←linfty_op_nnnorm_col v], exact linfty_op_nnnorm_mul A (col v), end lemma linfty_op_norm_mul_vec (A : matrix l m α) (v : m → α) : ‖matrix.mul_vec A v‖ ≤ ‖A‖ * ‖v‖ := linfty_op_nnnorm_mul_vec _ _ end non_unital_semi_normed_ring /-- Seminormed non-unital ring instance (using sup norm of L1 norm) for matrices over a semi normed non-unital ring. Not declared as an instance because there are several natural choices for defining the norm of a matrix. -/ local attribute [instance] protected def linfty_op_non_unital_semi_normed_ring [non_unital_semi_normed_ring α] : non_unital_semi_normed_ring (matrix n n α) := { norm_mul := linfty_op_norm_mul, .. matrix.linfty_op_seminormed_add_comm_group, .. matrix.non_unital_ring } /-- The `L₁-L∞` norm preserves one on non-empty matrices. Note this is safe as an instance, as it carries no data. -/ instance linfty_op_norm_one_class [semi_normed_ring α] [norm_one_class α] [decidable_eq n] [nonempty n] : norm_one_class (matrix n n α) := { norm_one := (linfty_op_norm_diagonal _).trans norm_one } /-- Seminormed ring instance (using sup norm of L1 norm) for matrices over a semi normed ring. Not declared as an instance because there are several natural choices for defining the norm of a matrix. -/ local attribute [instance] protected def linfty_op_semi_normed_ring [semi_normed_ring α] [decidable_eq n] : semi_normed_ring (matrix n n α) := { .. matrix.linfty_op_non_unital_semi_normed_ring, .. matrix.ring } /-- Normed non-unital ring instance (using sup norm of L1 norm) for matrices over a normed non-unital ring. Not declared as an instance because there are several natural choices for defining the norm of a matrix. -/ local attribute [instance] protected def linfty_op_non_unital_normed_ring [non_unital_normed_ring α] : non_unital_normed_ring (matrix n n α) := { ..matrix.linfty_op_non_unital_semi_normed_ring } /-- Normed ring instance (using sup norm of L1 norm) for matrices over a normed ring. Not declared as an instance because there are several natural choices for defining the norm of a matrix. -/ local attribute [instance] protected def linfty_op_normed_ring [normed_ring α] [decidable_eq n] : normed_ring (matrix n n α) := { ..matrix.linfty_op_semi_normed_ring } /-- Normed algebra instance (using sup norm of L1 norm) for matrices over a normed algebra. Not declared as an instance because there are several natural choices for defining the norm of a matrix. -/ local attribute [instance] protected def linfty_op_normed_algebra [normed_field R] [semi_normed_ring α] [normed_algebra R α] [decidable_eq n] : normed_algebra R (matrix n n α) := { ..matrix.linfty_op_normed_space } end linfty_op /-! ### The Frobenius norm This is defined as $\|A\| = \sqrt{\sum_{i,j} \|A_{ij}\|^2}$. When the matrix is over the real or complex numbers, this norm is submultiplicative. -/ section frobenius open_locale matrix big_operators /-- Seminormed group instance (using frobenius norm) for matrices over a seminormed group. Not declared as an instance because there are several natural choices for defining the norm of a matrix. -/ local attribute [instance] def frobenius_seminormed_add_comm_group [seminormed_add_comm_group α] : seminormed_add_comm_group (matrix m n α) := (by apply_instance : seminormed_add_comm_group (pi_Lp 2 (λ i : m, pi_Lp 2 (λ j : n, α)))) /-- Normed group instance (using frobenius norm) for matrices over a normed group. Not declared as an instance because there are several natural choices for defining the norm of a matrix. -/ local attribute [instance] def frobenius_normed_add_comm_group [normed_add_comm_group α] : normed_add_comm_group (matrix m n α) := (by apply_instance : normed_add_comm_group (pi_Lp 2 (λ i : m, pi_Lp 2 (λ j : n, α)))) /-- Normed space instance (using frobenius norm) for matrices over a normed space. Not declared as an instance because there are several natural choices for defining the norm of a matrix. -/ local attribute [instance] def frobenius_normed_space [normed_field R] [seminormed_add_comm_group α] [normed_space R α] : normed_space R (matrix m n α) := (by apply_instance : normed_space R (pi_Lp 2 (λ i : m, pi_Lp 2 (λ j : n, α)))) section seminormed_add_comm_group variables [seminormed_add_comm_group α] [seminormed_add_comm_group β] lemma frobenius_nnnorm_def (A : matrix m n α) : ‖A‖₊ = (∑ i j, ‖A i j‖₊ ^ (2 : ℝ)) ^ (1/2 : ℝ) := by simp_rw [pi_Lp.nnnorm_eq_of_L2, nnreal.sq_sqrt, nnreal.sqrt_eq_rpow, nnreal.rpow_two] lemma frobenius_norm_def (A : matrix m n α) : ‖A‖ = (∑ i j, ‖A i j‖ ^ (2 : ℝ)) ^ (1/2 : ℝ) := (congr_arg coe (frobenius_nnnorm_def A)).trans $ by simp [nnreal.coe_sum] @[simp] lemma frobenius_nnnorm_map_eq (A : matrix m n α) (f : α → β) (hf : ∀ a, ‖f a‖₊ = ‖a‖₊) : ‖A.map f‖₊ = ‖A‖₊ := by simp_rw [frobenius_nnnorm_def, matrix.map_apply, hf] @[simp] lemma frobenius_norm_map_eq (A : matrix m n α) (f : α → β) (hf : ∀ a, ‖f a‖ = ‖a‖) : ‖A.map f‖ = ‖A‖ := (congr_arg (coe : ℝ≥0 → ℝ) $ frobenius_nnnorm_map_eq A f $ λ a, subtype.ext $ hf a : _) @[simp] lemma frobenius_nnnorm_transpose (A : matrix m n α) : ‖Aᵀ‖₊ = ‖A‖₊ := by { rw [frobenius_nnnorm_def, frobenius_nnnorm_def, finset.sum_comm], refl } @[simp] lemma frobenius_norm_transpose (A : matrix m n α) : ‖Aᵀ‖ = ‖A‖ := congr_arg coe $ frobenius_nnnorm_transpose A @[simp] lemma frobenius_nnnorm_conj_transpose [star_add_monoid α] [normed_star_group α] (A : matrix m n α) : ‖Aᴴ‖₊ = ‖A‖₊ := (frobenius_nnnorm_map_eq _ _ nnnorm_star).trans A.frobenius_nnnorm_transpose @[simp] lemma frobenius_norm_conj_transpose [star_add_monoid α] [normed_star_group α] (A : matrix m n α) : ‖Aᴴ‖ = ‖A‖ := congr_arg coe $ frobenius_nnnorm_conj_transpose A instance frobenius_normed_star_group [star_add_monoid α] [normed_star_group α] : normed_star_group (matrix m m α) := ⟨frobenius_norm_conj_transpose⟩ @[simp] lemma frobenius_norm_row (v : m → α) : ‖row v‖ = ‖(pi_Lp.equiv 2 _).symm v‖ := begin rw [frobenius_norm_def, fintype.sum_unique, pi_Lp.norm_eq_of_L2, real.sqrt_eq_rpow], simp only [row_apply, real.rpow_two, pi_Lp.equiv_symm_apply], end @[simp] lemma frobenius_nnnorm_row (v : m → α) : ‖row v‖₊ = ‖(pi_Lp.equiv 2 _).symm v‖₊ := subtype.ext $ frobenius_norm_row v @[simp] lemma frobenius_norm_col (v : n → α) : ‖col v‖ = ‖(pi_Lp.equiv 2 _).symm v‖ := begin simp_rw [frobenius_norm_def, fintype.sum_unique, pi_Lp.norm_eq_of_L2, real.sqrt_eq_rpow], simp only [col_apply, real.rpow_two, pi_Lp.equiv_symm_apply] end @[simp] lemma frobenius_nnnorm_col (v : n → α) : ‖col v‖₊ = ‖(pi_Lp.equiv 2 _).symm v‖₊ := subtype.ext $ frobenius_norm_col v @[simp] lemma frobenius_nnnorm_diagonal [decidable_eq n] (v : n → α) : ‖diagonal v‖₊ = ‖(pi_Lp.equiv 2 _).symm v‖₊ := begin simp_rw [frobenius_nnnorm_def, ←finset.sum_product', finset.univ_product_univ, pi_Lp.nnnorm_eq_of_L2], let s := (finset.univ : finset n).map ⟨λ i : n, (i, i), λ i j h, congr_arg prod.fst h⟩, rw ←finset.sum_subset (finset.subset_univ s) (λ i hi his, _), { rw [finset.sum_map, nnreal.sqrt_eq_rpow], dsimp, simp_rw [diagonal_apply_eq, nnreal.rpow_two] }, { suffices : i.1 ≠ i.2, { rw [diagonal_apply_ne _ this, nnnorm_zero, nnreal.zero_rpow two_ne_zero], }, intro h, exact finset.mem_map.not.mp his ⟨i.1, finset.mem_univ _, prod.ext rfl h⟩ } end @[simp] lemma frobenius_norm_diagonal [decidable_eq n] (v : n → α) : ‖diagonal v‖ = ‖(pi_Lp.equiv 2 _).symm v‖ := (congr_arg coe $ frobenius_nnnorm_diagonal v : _).trans rfl end seminormed_add_comm_group lemma frobenius_nnnorm_one [decidable_eq n] [seminormed_add_comm_group α] [has_one α] : ‖(1 : matrix n n α)‖₊ = nnreal.sqrt (fintype.card n) * ‖(1 : α)‖₊:= begin refine (frobenius_nnnorm_diagonal _).trans _, simp_rw [pi_Lp.nnnorm_equiv_symm_const ennreal.two_ne_top, nnreal.sqrt_eq_rpow], simp only [ennreal.to_real_div, ennreal.one_to_real, ennreal.to_real_bit0], end section is_R_or_C variables [is_R_or_C α] lemma frobenius_nnnorm_mul (A : matrix l m α) (B : matrix m n α) : ‖A ⬝ B‖₊ ≤ ‖A‖₊ * ‖B‖₊ := begin simp_rw [frobenius_nnnorm_def, matrix.mul_apply], rw [←nnreal.mul_rpow, @finset.sum_comm _ n m, finset.sum_mul_sum, finset.sum_product], refine nnreal.rpow_le_rpow _ one_half_pos.le, refine finset.sum_le_sum (λ i hi, finset.sum_le_sum $ λ j hj, _), rw [← nnreal.rpow_le_rpow_iff one_half_pos, ← nnreal.rpow_mul, mul_div_cancel' (1 : ℝ) two_ne_zero, nnreal.rpow_one, nnreal.mul_rpow], dsimp only, have := @nnnorm_inner_le_nnnorm α _ _ _ _ ((pi_Lp.equiv 2 (λ i, α)).symm (λ j, star (A i j))) ((pi_Lp.equiv 2 (λ i, α)).symm (λ k, B k j)), simpa only [pi_Lp.equiv_symm_apply, pi_Lp.inner_apply, is_R_or_C.inner_apply, star_ring_end_apply, pi.nnnorm_def, pi_Lp.nnnorm_eq_of_L2, star_star, nnnorm_star, nnreal.sqrt_eq_rpow, nnreal.rpow_two] using this, end lemma frobenius_norm_mul (A : matrix l m α) (B : matrix m n α) : ‖A ⬝ B‖ ≤ ‖A‖ * ‖B‖ := frobenius_nnnorm_mul A B /-- Normed ring instance (using frobenius norm) for matrices over `ℝ` or `ℂ`. Not declared as an instance because there are several natural choices for defining the norm of a matrix. -/ local attribute [instance] def frobenius_normed_ring [decidable_eq m] : normed_ring (matrix m m α) := { norm := has_norm.norm, norm_mul := frobenius_norm_mul, ..matrix.frobenius_seminormed_add_comm_group } /-- Normed algebra instance (using frobenius norm) for matrices over `ℝ` or `ℂ`. Not declared as an instance because there are several natural choices for defining the norm of a matrix. -/ local attribute [instance] def frobenius_normed_algebra [decidable_eq m] [normed_field R] [normed_algebra R α] : normed_algebra R (matrix m m α) := { ..matrix.frobenius_normed_space } end is_R_or_C end frobenius end matrix
8b550c0f6525c6049128360615b9ba88e669e2d7
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/compiler/phashmap.lean
79dd439b31334784a5ea3912b49e6b94afc9b559
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
2,063
lean
import Lean.Data.PersistentHashMap import Lean.Data.Format open Lean Std Lean.PersistentHashMap abbrev Map := PersistentHashMap Nat Nat partial def formatMap : Node Nat Nat → Format | Node.collision keys vals _ => Format.sbracket $ keys.size.fold (fun i fmt => let k := keys.get! i; let v := vals.get! i; let p := if i > 0 then fmt ++ format "," ++ Format.line else fmt; p ++ "c@" ++ Format.paren (format k ++ " => " ++ format v)) Format.nil | Node.entries entries => Format.sbracket $ entries.size.fold (fun i fmt => let entry := entries.get! i; let p := if i > 0 then fmt ++ format "," ++ Format.line else fmt; p ++ match entry with | Entry.null => "<null>" | Entry.ref node => formatMap node | Entry.entry k v => Format.paren (format k ++ " => " ++ format v)) Format.nil def mkMap (n : Nat) : Map := n.fold (fun i m => m.insert i (i*10)) PersistentHashMap.empty def check (n : Nat) (m : Map) : IO Unit := n.forM $ fun i => do match m.find? i with | none => IO.println s!"failed to find {i}" | some v => unless v == i*10 do IO.println s!"unexpected value {i} => {v}" def delOdd (n : Nat) (m : Map) : Map := n.fold (fun i m => if i % 2 == 0 then m else m.erase i) m def check2 (n : Nat) (bot : Nat) (m : Map) : IO Unit := n.forM $ fun i => do if i % 2 == 0 && i >= bot then match m.find? i with | none => IO.println s!"failed to find {i}" | some v => unless v == i*10 do IO.println s!"unexpected value {i} => {v}" else unless m.find? i == none do IO.println s!"mapping still contains {i}" def delLess (n : Nat) (m : Map) : Map := n.fold (fun i m => m.erase i) m def main (xs : List String) : IO Unit := do let n := 5000; let m := mkMap n; -- IO.println (formatMap m.root); IO.println m.stats; check n m; let m := delOdd n m; IO.println m.stats; check2 n 0 m; let m := delLess 4900 m; check2 n 4900 m; IO.println m.size; IO.println m.stats; let m := delLess 4990 m; check2 n 4990 m; IO.println m.size; IO.println m.stats
158341f80f121cf360001f986272db6472062a01
4a092885406df4e441e9bb9065d9405dacb94cd8
/src/for_mathlib/uniform_space/basic.lean
318257b0266eabd5b2ff8d3ecb383ed4250acba7
[ "Apache-2.0" ]
permissive
semorrison/lean-perfectoid-spaces
78c1572cedbfae9c3e460d8aaf91de38616904d8
bb4311dff45791170bcb1b6a983e2591bee88a19
refs/heads/master
1,588,841,765,494
1,554,805,620,000
1,554,805,620,000
180,353,546
0
1
null
1,554,809,880,000
1,554,809,880,000
null
UTF-8
Lean
false
false
943
lean
import topology.uniform_space.basic import for_mathlib.function section open uniform_space variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} variables [uniform_space α] [uniform_space β] [uniform_space γ] [uniform_space δ] def uniform_continuous₂ (f : α → β → γ) := uniform_continuous (function.uncurry f) lemma uniform_continuous₂_def (f : α → β → γ) : uniform_continuous₂ f ↔ uniform_continuous (function.uncurry f) := iff.rfl lemma uniform_continuous₂_curry (f : α × β → γ) : uniform_continuous₂ (function.curry f) ↔ uniform_continuous f := by rw [←function.uncurry_curry f] {occs := occurrences.pos [2]} ; refl lemma uniform_continuous₂.comp {f : α → β → γ} {g : γ → δ} (hf : uniform_continuous₂ f)(hg : uniform_continuous g) : uniform_continuous₂ (g ∘₂ f) := begin unfold uniform_continuous₂, rw function.uncurry_comp₂, exact hf.comp hg end end
650e2cf6923bc9a83a3f2e8c939234d4f04a9878
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/topology/sheaves/sheaf_condition/unique_gluing.lean
e9647e2a86406b9f6fa14c6e0e5aa750ae823817
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
11,618
lean
/- Copyright (c) 2021 Justus Springer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Justus Springer -/ import topology.sheaves.forget import category_theory.limits.shapes.types import topology.sheaves.sheaf import category_theory.types /-! # The sheaf condition in terms of unique gluings We provide an alternative formulation of the sheaf condition in terms of unique gluings. We work with sheaves valued in a concrete category `C` admitting all limits, whose forgetful functor `C ⥤ Type` preserves limits and reflects isomorphisms. The usual categories of algebraic structures, such as `Mon`, `AddCommGroup`, `Ring`, `CommRing` etc. are all examples of this kind of category. A presheaf `F : presheaf C X` satisfies the sheaf condition if and only if, for every compatible family of sections `sf : Π i : ι, F.obj (op (U i))`, there exists a unique gluing `s : F.obj (op (supr U))`. Here, the family `sf` is called compatible, if for all `i j : ι`, the restrictions of `sf i` and `sf j` to `U i ⊓ U j` agree. A section `s : F.obj (op (supr U))` is a gluing for the family `sf`, if `s` restricts to `sf i` on `U i` for all `i : ι` We show that the sheaf condition in terms of unique gluings is equivalent to the definition in terms of equalizers. Our approach is as follows: First, we show them to be equivalent for `Type`-valued presheaves. Then we use that composing a presheaf with a limit-preserving and isomorphism-reflecting functor leaves the sheaf condition invariant, as shown in `topology/sheaves/forget.lean`. -/ noncomputable theory open Top open Top.presheaf open Top.presheaf.sheaf_condition_equalizer_products open category_theory open category_theory.limits open topological_space open topological_space.opens open opposite universes u v variables {C : Type u} [category.{v} C] [concrete_category.{v} C] namespace Top namespace presheaf section local attribute [instance] concrete_category.has_coe_to_sort concrete_category.has_coe_to_fun variables {X : Top.{v}} (F : presheaf C X) {ι : Type v} (U : ι → opens X) /-- A family of sections `sf` is compatible, if the restrictions of `sf i` and `sf j` to `U i ⊓ U j` agree, for all `i` and `j` -/ def is_compatible (sf : Π i : ι, F.obj (op (U i))) : Prop := ∀ i j : ι, F.map (inf_le_left (U i) (U j)).op (sf i) = F.map (inf_le_right (U i) (U j)).op (sf j) /-- A section `s` is a gluing for a family of sections `sf` if it restricts to `sf i` on `U i`, for all `i` -/ def is_gluing (sf : Π i : ι, F.obj (op (U i))) (s : F.obj (op (supr U))) : Prop := ∀ i : ι, F.map (opens.le_supr U i).op s = sf i /-- The sheaf condition in terms of unique gluings. A presheaf `F : presheaf C X` satisfies this sheaf condition if and only if, for every compatible family of sections `sf : Π i : ι, F.obj (op (U i))`, there exists a unique gluing `s : F.obj (op (supr U))`. We prove this to be equivalent to the usual one below in `is_sheaf_iff_is_sheaf_unique_gluing` -/ def is_sheaf_unique_gluing : Prop := ∀ ⦃ι : Type v⦄ (U : ι → opens X) (sf : Π i : ι, F.obj (op (U i))), is_compatible F U sf → ∃! s : F.obj (op (supr U)), is_gluing F U sf s end section type_valued variables {X : Top.{v}} (F : presheaf (Type v) X) {ι : Type v} (U : ι → opens X) /-- For presheaves of types, terms of `pi_opens F U` are just families of sections. -/ def pi_opens_iso_sections_family : pi_opens F U ≅ Π i : ι, F.obj (op (U i)) := limits.is_limit.cone_point_unique_up_to_iso (limit.is_limit (discrete.functor (λ i : ι, F.obj (op (U i))))) ((types.product_limit_cone.{v v} (λ i : ι, F.obj (op (U i)))).is_limit) /-- Under the isomorphism `pi_opens_iso_sections_family`, compatibility of sections is the same as being equalized by the arrows `left_res` and `right_res` of the equalizer diagram. -/ lemma compatible_iff_left_res_eq_right_res (sf : pi_opens F U) : is_compatible F U ((pi_opens_iso_sections_family F U).hom sf) ↔ left_res F U sf = right_res F U sf := begin split ; intros h, { ext ⟨i, j⟩, rw [left_res, types.limit.lift_π_apply', fan.mk_π_app, right_res, types.limit.lift_π_apply', fan.mk_π_app], exact h i j, }, { intros i j, convert congr_arg (limits.pi.π (λ p : ι × ι, F.obj (op (U p.1 ⊓ U p.2))) (i,j)) h, { rw [left_res, types.pi_lift_π_apply], refl }, { rw [right_res, types.pi_lift_π_apply], refl } } end /-- Under the isomorphism `pi_opens_iso_sections_family`, being a gluing of a family of sections `sf` is the same as lying in the preimage of `res` (the leftmost arrow of the equalizer diagram). -/ @[simp] lemma is_gluing_iff_eq_res (sf : pi_opens F U) (s : F.obj (op (supr U))): is_gluing F U ((pi_opens_iso_sections_family F U).hom sf) s ↔ res F U s = sf := begin split ; intros h, { ext ⟨i⟩, rw [res, types.limit.lift_π_apply', fan.mk_π_app], exact h i, }, { intro i, convert congr_arg (limits.pi.π (λ i : ι, F.obj (op (U i))) i) h, rw [res, types.pi_lift_π_apply], refl }, end /-- The "equalizer" sheaf condition can be obtained from the sheaf condition in terms of unique gluings. -/ lemma is_sheaf_of_is_sheaf_unique_gluing_types (Fsh : F.is_sheaf_unique_gluing) : F.is_sheaf := begin rw is_sheaf_iff_is_sheaf_equalizer_products, intros ι U, refine ⟨fork.is_limit.mk' _ _⟩, intro s, have h_compatible : ∀ x : s.X, F.is_compatible U ((F.pi_opens_iso_sections_family U).hom (s.ι x)), { intro x, rw compatible_iff_left_res_eq_right_res, convert congr_fun s.condition x, }, choose m m_spec m_uniq using λ x : s.X, Fsh U ((pi_opens_iso_sections_family F U).hom (s.ι x)) (h_compatible x), refine ⟨m, _, _⟩, { ext ⟨i⟩ x, simp [res], exact m_spec x i, }, { intros l hl, ext x, apply m_uniq, rw is_gluing_iff_eq_res, exact congr_fun hl x }, end /-- The sheaf condition in terms of unique gluings can be obtained from the usual "equalizer" sheaf condition. -/ lemma is_sheaf_unique_gluing_of_is_sheaf_types (Fsh : F.is_sheaf) : F.is_sheaf_unique_gluing := begin rw is_sheaf_iff_is_sheaf_equalizer_products at Fsh, intros ι U sf hsf, let sf' := (pi_opens_iso_sections_family F U).inv sf, have hsf' : left_res F U sf' = right_res F U sf', { rwa [← compatible_iff_left_res_eq_right_res F U sf', inv_hom_id_apply] }, choose s s_spec s_uniq using types.unique_of_type_equalizer _ _ (Fsh U).some sf' hsf', use s, dsimp, split, { convert (is_gluing_iff_eq_res F U sf' _).mpr s_spec, rw inv_hom_id_apply }, { intros y hy, apply s_uniq, rw ← is_gluing_iff_eq_res F U, convert hy, rw inv_hom_id_apply, }, end /-- For type-valued presheaves, the sheaf condition in terms of unique gluings is equivalent to the usual sheaf condition in terms of equalizer diagrams. -/ lemma is_sheaf_iff_is_sheaf_unique_gluing_types : F.is_sheaf ↔ F.is_sheaf_unique_gluing := iff.intro (is_sheaf_unique_gluing_of_is_sheaf_types F) (is_sheaf_of_is_sheaf_unique_gluing_types F) end type_valued section local attribute [instance] concrete_category.has_coe_to_sort concrete_category.has_coe_to_fun variables [has_limits C] [reflects_isomorphisms (forget C)] [preserves_limits (forget C)] variables {X : Top.{v}} (F : presheaf C X) {ι : Type v} (U : ι → opens X) /-- For presheaves valued in a concrete category, whose forgetful functor reflects isomorphisms and preserves limits, the sheaf condition in terms of unique gluings is equivalent to the usual one in terms of equalizer diagrams. -/ lemma is_sheaf_iff_is_sheaf_unique_gluing : F.is_sheaf ↔ F.is_sheaf_unique_gluing := iff.trans (is_sheaf_iff_is_sheaf_comp (forget C) F) (is_sheaf_iff_is_sheaf_unique_gluing_types (F ⋙ forget C)) end end presheaf namespace sheaf open presheaf open category_theory section local attribute [instance] concrete_category.has_coe_to_sort concrete_category.has_coe_to_fun variables [has_limits C] [reflects_isomorphisms (concrete_category.forget C)] variables [preserves_limits (concrete_category.forget C)] variables {X : Top.{v}} (F : sheaf C X) {ι : Type v} (U : ι → opens X) /-- A more convenient way of obtaining a unique gluing of sections for a sheaf. -/ lemma exists_unique_gluing (sf : Π i : ι, F.1.obj (op (U i))) (h : is_compatible F.1 U sf ) : ∃! s : F.1.obj (op (supr U)), is_gluing F.1 U sf s := (is_sheaf_iff_is_sheaf_unique_gluing F.1).mp F.cond U sf h /-- In this version of the lemma, the inclusion homs `iUV` can be specified directly by the user, which can be more convenient in practice. -/ lemma exists_unique_gluing' (V : opens X) (iUV : Π i : ι, U i ⟶ V) (hcover : V ≤ supr U) (sf : Π i : ι, F.1.obj (op (U i))) (h : is_compatible F.1 U sf) : ∃! s : F.1.obj (op V), ∀ i : ι, F.1.map (iUV i).op s = sf i := begin have V_eq_supr_U : V = supr U := le_antisymm hcover (supr_le (λ i, (iUV i).le)), obtain ⟨gl, gl_spec, gl_uniq⟩ := F.exists_unique_gluing U sf h, refine ⟨F.1.map (eq_to_hom V_eq_supr_U).op gl, _, _⟩, { intro i, rw [← comp_apply, ← F.1.map_comp], exact gl_spec i }, { intros gl' gl'_spec, convert congr_arg _ (gl_uniq (F.1.map (eq_to_hom V_eq_supr_U.symm).op gl') (λ i,_)) ; rw [← comp_apply, ← F.1.map_comp], { rw [eq_to_hom_op, eq_to_hom_op, eq_to_hom_trans, eq_to_hom_refl, F.1.map_id, id_apply] }, { convert gl'_spec i } } end @[ext] lemma eq_of_locally_eq (s t : F.1.obj (op (supr U))) (h : ∀ i, F.1.map (opens.le_supr U i).op s = F.1.map (opens.le_supr U i).op t) : s = t := begin let sf : Π i : ι, F.1.obj (op (U i)) := λ i, F.1.map (opens.le_supr U i).op s, have sf_compatible : is_compatible _ U sf, { intros i j, simp_rw [← comp_apply, ← F.1.map_comp], refl }, obtain ⟨gl, -, gl_uniq⟩ := F.exists_unique_gluing U sf sf_compatible, transitivity gl, { apply gl_uniq, intro i, refl }, { symmetry, apply gl_uniq, intro i, rw ← h }, end /-- In this version of the lemma, the inclusion homs `iUV` can be specified directly by the user, which can be more convenient in practice. -/ lemma eq_of_locally_eq' (V : opens X) (iUV : Π i : ι, U i ⟶ V) (hcover : V ≤ supr U) (s t : F.1.obj (op V)) (h : ∀ i, F.1.map (iUV i).op s = F.1.map (iUV i).op t) : s = t := begin have V_eq_supr_U : V = supr U := le_antisymm hcover (supr_le (λ i, (iUV i).le)), suffices : F.1.map (eq_to_hom V_eq_supr_U.symm).op s = F.1.map (eq_to_hom V_eq_supr_U.symm).op t, { convert congr_arg (F.1.map (eq_to_hom V_eq_supr_U).op) this ; rw [← comp_apply, ← F.1.map_comp, eq_to_hom_op, eq_to_hom_op, eq_to_hom_trans, eq_to_hom_refl, F.1.map_id, id_apply] }, apply eq_of_locally_eq, intro i, rw [← comp_apply, ← comp_apply, ← F.1.map_comp], convert h i, end lemma eq_of_locally_eq₂ {U₁ U₂ V : opens X} (i₁ : U₁ ⟶ V) (i₂ : U₂ ⟶ V) (hcover : V ≤ U₁ ⊔ U₂) (s t : F.1.obj (op V)) (h₁ : F.1.map i₁.op s = F.1.map i₁.op t) (h₂ : F.1.map i₂.op s = F.1.map i₂.op t) : s = t := begin classical, fapply F.eq_of_locally_eq' (λ t : ulift bool, if t.1 then U₁ else U₂), { exact λ i, if h : i.1 then (eq_to_hom (if_pos h)) ≫ i₁ else (eq_to_hom (if_neg h)) ≫ i₂ }, { refine le_trans hcover _, rw sup_le_iff, split, { convert le_supr (λ t : ulift bool, if t.1 then U₁ else U₂) (ulift.up true) }, { convert le_supr (λ t : ulift bool, if t.1 then U₁ else U₂) (ulift.up false) } }, { rintro ⟨_|_⟩; simp [h₁, h₂] } end end end sheaf end Top
1ab727114a5fdccd2c037cafecca2f0c56ae1f6d
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/list/forall2.lean
9ae445e3262c22fb580278e3c0e988dbd444c155
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
8,641
lean
/- 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.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.list.basic import Mathlib.PostPort universes u v w z namespace Mathlib namespace list /- forall₂ -/ theorem forall₂_iff {α : Type u} {β : Type v} (R : α → β → Prop) : ∀ (ᾰ : List α) (ᾰ_1 : List β), forall₂ R ᾰ ᾰ_1 ↔ ᾰ = [] ∧ ᾰ_1 = [] ∨ Exists fun {a : α} => Exists fun {b : β} => Exists fun {l₁ : List α} => Exists fun {l₂ : List β} => R a b ∧ forall₂ R l₁ l₂ ∧ ᾰ = a :: l₁ ∧ ᾰ_1 = b :: l₂ := sorry @[simp] theorem forall₂_cons {α : Type u} {β : Type v} {R : α → β → Prop} {a : α} {b : β} {l₁ : List α} {l₂ : List β} : forall₂ R (a :: l₁) (b :: l₂) ↔ R a b ∧ forall₂ R l₁ l₂ := sorry theorem forall₂.imp {α : Type u} {β : Type v} {R : α → β → Prop} {S : α → β → Prop} (H : ∀ (a : α) (b : β), R a b → S a b) {l₁ : List α} {l₂ : List β} (h : forall₂ R l₁ l₂) : forall₂ S l₁ l₂ := sorry theorem forall₂.mp {α : Type u} {β : Type v} {r : α → β → Prop} {q : α → β → Prop} {s : α → β → Prop} (h : ∀ (a : α) (b : β), r a b → q a b → s a b) {l₁ : List α} {l₂ : List β} : forall₂ r l₁ l₂ → forall₂ q l₁ l₂ → forall₂ s l₁ l₂ := sorry theorem forall₂.flip {α : Type u} {β : Type v} {r : α → β → Prop} {a : List α} {b : List β} : forall₂ (flip r) b a → forall₂ r a b := sorry theorem forall₂_same {α : Type u} {r : α → α → Prop} {l : List α} : (∀ (x : α), x ∈ l → r x x) → forall₂ r l l := sorry theorem forall₂_refl {α : Type u} {r : α → α → Prop} [is_refl α r] (l : List α) : forall₂ r l l := forall₂_same fun (a : α) (h : a ∈ l) => is_refl.refl a theorem forall₂_eq_eq_eq {α : Type u} : forall₂ Eq = Eq := sorry @[simp] theorem forall₂_nil_left_iff {α : Type u} {β : Type v} {r : α → β → Prop} {l : List β} : forall₂ r [] l ↔ l = [] := sorry @[simp] theorem forall₂_nil_right_iff {α : Type u} {β : Type v} {r : α → β → Prop} {l : List α} : forall₂ r l [] ↔ l = [] := sorry theorem forall₂_cons_left_iff {α : Type u} {β : Type v} {r : α → β → Prop} {a : α} {l : List α} {u : List β} : forall₂ r (a :: l) u ↔ ∃ (b : β), ∃ (u' : List β), r a b ∧ forall₂ r l u' ∧ u = b :: u' := sorry theorem forall₂_cons_right_iff {α : Type u} {β : Type v} {r : α → β → Prop} {b : β} {l : List β} {u : List α} : forall₂ r u (b :: l) ↔ ∃ (a : α), ∃ (u' : List α), r a b ∧ forall₂ r u' l ∧ u = a :: u' := sorry theorem forall₂_and_left {α : Type u} {β : Type v} {r : α → β → Prop} {p : α → Prop} (l : List α) (u : List β) : forall₂ (fun (a : α) (b : β) => p a ∧ r a b) l u ↔ (∀ (a : α), a ∈ l → p a) ∧ forall₂ r l u := sorry @[simp] theorem forall₂_map_left_iff {α : Type u} {β : Type v} {γ : Type w} {r : α → β → Prop} {f : γ → α} {l : List γ} {u : List β} : forall₂ r (map f l) u ↔ forall₂ (fun (c : γ) (b : β) => r (f c) b) l u := sorry @[simp] theorem forall₂_map_right_iff {α : Type u} {β : Type v} {γ : Type w} {r : α → β → Prop} {f : γ → β} {l : List α} {u : List γ} : forall₂ r l (map f u) ↔ forall₂ (fun (a : α) (c : γ) => r a (f c)) l u := sorry theorem left_unique_forall₂ {α : Type u} {β : Type v} {r : α → β → Prop} (hr : relator.left_unique r) : relator.left_unique (forall₂ r) := sorry theorem right_unique_forall₂ {α : Type u} {β : Type v} {r : α → β → Prop} (hr : relator.right_unique r) : relator.right_unique (forall₂ r) := sorry theorem bi_unique_forall₂ {α : Type u} {β : Type v} {r : α → β → Prop} (hr : relator.bi_unique r) : relator.bi_unique (forall₂ r) := { left := fun (a : List α) (b : List β) (c : List α) => left_unique_forall₂ (and.left hr), right := fun (a : List α) (b c : List β) => right_unique_forall₂ (and.right hr) } theorem forall₂_length_eq {α : Type u} {β : Type v} {R : α → β → Prop} {l₁ : List α} {l₂ : List β} : forall₂ R l₁ l₂ → length l₁ = length l₂ := sorry theorem forall₂_zip {α : Type u} {β : Type v} {R : α → β → Prop} {l₁ : List α} {l₂ : List β} : forall₂ R l₁ l₂ → ∀ {a : α} {b : β}, (a, b) ∈ zip l₁ l₂ → R a b := sorry theorem forall₂_iff_zip {α : Type u} {β : Type v} {R : α → β → Prop} {l₁ : List α} {l₂ : List β} : forall₂ R l₁ l₂ ↔ length l₁ = length l₂ ∧ ∀ {a : α} {b : β}, (a, b) ∈ zip l₁ l₂ → R a b := sorry theorem forall₂_take {α : Type u} {β : Type v} {R : α → β → Prop} (n : ℕ) {l₁ : List α} {l₂ : List β} : forall₂ R l₁ l₂ → forall₂ R (take n l₁) (take n l₂) := sorry theorem forall₂_drop {α : Type u} {β : Type v} {R : α → β → Prop} (n : ℕ) {l₁ : List α} {l₂ : List β} : forall₂ R l₁ l₂ → forall₂ R (drop n l₁) (drop n l₂) := sorry theorem forall₂_take_append {α : Type u} {β : Type v} {R : α → β → Prop} (l : List α) (l₁ : List β) (l₂ : List β) (h : forall₂ R l (l₁ ++ l₂)) : forall₂ R (take (length l₁) l) l₁ := (fun (h' : forall₂ R (take (length l₁) l) (take (length l₁) (l₁ ++ l₂))) => eq.mp (Eq._oldrec (Eq.refl (forall₂ R (take (length l₁) l) (take (length l₁) (l₁ ++ l₂)))) (take_left l₁ l₂)) h') (forall₂_take (length l₁) h) theorem forall₂_drop_append {α : Type u} {β : Type v} {R : α → β → Prop} (l : List α) (l₁ : List β) (l₂ : List β) (h : forall₂ R l (l₁ ++ l₂)) : forall₂ R (drop (length l₁) l) l₂ := (fun (h' : forall₂ R (drop (length l₁) l) (drop (length l₁) (l₁ ++ l₂))) => eq.mp (Eq._oldrec (Eq.refl (forall₂ R (drop (length l₁) l) (drop (length l₁) (l₁ ++ l₂)))) (drop_left l₁ l₂)) h') (forall₂_drop (length l₁) h) theorem rel_mem {α : Type u} {β : Type v} {r : α → β → Prop} (hr : relator.bi_unique r) : relator.lift_fun r (forall₂ r ⇒ Iff) has_mem.mem has_mem.mem := sorry theorem rel_map {α : Type u} {β : Type v} {γ : Type w} {δ : Type z} {r : α → β → Prop} {p : γ → δ → Prop} : relator.lift_fun (r ⇒ p) (forall₂ r ⇒ forall₂ p) map map := sorry theorem rel_append {α : Type u} {β : Type v} {r : α → β → Prop} : relator.lift_fun (forall₂ r) (forall₂ r ⇒ forall₂ r) append append := sorry theorem rel_join {α : Type u} {β : Type v} {r : α → β → Prop} : relator.lift_fun (forall₂ (forall₂ r)) (forall₂ r) join join := sorry theorem rel_bind {α : Type u} {β : Type v} {γ : Type w} {δ : Type z} {r : α → β → Prop} {p : γ → δ → Prop} : relator.lift_fun (forall₂ r) ((r ⇒ forall₂ p) ⇒ forall₂ p) list.bind list.bind := fun (a : List α) (b : List β) (h₁ : forall₂ r a b) (f : α → List γ) (g : β → List δ) (h₂ : relator.lift_fun r (forall₂ p) f g) => rel_join (rel_map h₂ h₁) theorem rel_foldl {α : Type u} {β : Type v} {γ : Type w} {δ : Type z} {r : α → β → Prop} {p : γ → δ → Prop} : relator.lift_fun (p ⇒ r ⇒ p) (p ⇒ forall₂ r ⇒ p) foldl foldl := sorry theorem rel_foldr {α : Type u} {β : Type v} {γ : Type w} {δ : Type z} {r : α → β → Prop} {p : γ → δ → Prop} : relator.lift_fun (r ⇒ p ⇒ p) (p ⇒ forall₂ r ⇒ p) foldr foldr := sorry theorem rel_filter {α : Type u} {β : Type v} {r : α → β → Prop} {p : α → Prop} {q : β → Prop} [decidable_pred p] [decidable_pred q] (hpq : relator.lift_fun r Iff p q) : relator.lift_fun (forall₂ r) (forall₂ r) (filter p) (filter q) := sorry theorem filter_map_cons {α : Type u} {β : Type v} (f : α → Option β) (a : α) (l : List α) : filter_map f (a :: l) = option.cases_on (f a) (filter_map f l) fun (b : β) => b :: filter_map f l := sorry theorem rel_filter_map {α : Type u} {β : Type v} {γ : Type w} {δ : Type z} {r : α → β → Prop} {p : γ → δ → Prop} : relator.lift_fun (r ⇒ option.rel p) (forall₂ r ⇒ forall₂ p) filter_map filter_map := sorry theorem rel_sum {α : Type u} {β : Type v} {r : α → β → Prop} [add_monoid α] [add_monoid β] (h : r 0 0) (hf : relator.lift_fun r (r ⇒ r) Add.add Add.add) : relator.lift_fun (forall₂ r) r sum sum := rel_foldl hf h
43c9026a9f9c29327974316634636933617ac128
1a61aba1b67cddccce19532a9596efe44be4285f
/hott/init/types.hlean
c173c527195ed8f09466038647bd2834a878e1a4
[ "Apache-2.0" ]
permissive
eigengrau/lean
07986a0f2548688c13ba36231f6cdbee82abf4c6
f8a773be1112015e2d232661ce616d23f12874d0
refs/heads/master
1,610,939,198,566
1,441,352,386,000
1,441,352,494,000
41,903,576
0
0
null
1,441,352,210,000
1,441,352,210,000
null
UTF-8
Lean
false
false
9,077
hlean
/- Copyright (c) 2014-2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jeremy Avigad, Floris van Doorn, Jakob von Raumer -/ prelude import .num .wf -- Empty type -- ---------- namespace empty protected theorem elim {A : Type} (H : empty) : A := empty.rec (λe, A) H end empty protected definition empty.has_decidable_eq [instance] : decidable_eq empty := take (a b : empty), decidable.inl (!empty.elim a) -- Unit type -- --------- namespace unit notation `⋆` := star end unit -- Sigma type -- ---------- notation `Σ` binders `,` r:(scoped P, sigma P) := r namespace sigma notation `⟨`:max t:(foldr `,` (e r, mk e r)) `⟩`:0 := t --input ⟨ ⟩ as \< \> namespace ops postfix `.1`:(max+1) := pr1 postfix `.2`:(max+1) := pr2 abbreviation pr₁ := @pr1 abbreviation pr₂ := @pr2 end ops end sigma -- Sum type -- -------- namespace sum infixr ⊎ := sum infixr + := sum namespace low_precedence_plus reserve infixr `+`:25 -- conflicts with notation for addition infixr `+` := sum end low_precedence_plus variables {a b c d : Type} definition sum_of_sum_of_imp_of_imp (H₁ : a ⊎ b) (H₂ : a → c) (H₃ : b → d) : c ⊎ d := sum.rec_on H₁ (assume Ha : a, sum.inl (H₂ Ha)) (assume Hb : b, sum.inr (H₃ Hb)) definition sum_of_sum_of_imp_left (H₁ : a ⊎ c) (H : a → b) : b ⊎ c := sum.rec_on H₁ (assume H₂ : a, sum.inl (H H₂)) (assume H₂ : c, sum.inr H₂) definition sum_of_sum_of_imp_right (H₁ : c ⊎ a) (H : a → b) : c ⊎ b := sum.rec_on H₁ (assume H₂ : c, sum.inl H₂) (assume H₂ : a, sum.inr (H H₂)) end sum -- Product type -- ------------ abbreviation pair := @prod.mk namespace prod -- notation for n-ary tuples notation `(` h `,` t:(foldl `,` (e r, prod.mk r e) h) `)` := t infixr × := prod namespace ops infixr [parsing-only] * := prod postfix `.1`:(max+1) := pr1 postfix `.2`:(max+1) := pr2 abbreviation pr₁ := @pr1 abbreviation pr₂ := @pr2 end ops namespace low_precedence_times reserve infixr `*`:30 -- conflicts with notation for multiplication infixr `*` := prod end low_precedence_times open prod.ops definition flip {A B : Type} (a : A × B) : B × A := pair (pr2 a) (pr1 a) open well_founded section variables {A B : Type} variable (Ra : A → A → Type) variable (Rb : B → B → Type) -- Lexicographical order based on Ra and Rb inductive lex : A × B → A × B → Type := | left : ∀{a₁ b₁} a₂ b₂, Ra a₁ a₂ → lex (a₁, b₁) (a₂, b₂) | right : ∀a {b₁ b₂}, Rb b₁ b₂ → lex (a, b₁) (a, b₂) -- Relational product based on Ra and Rb inductive rprod : A × B → A × B → Type := intro : ∀{a₁ b₁ a₂ b₂}, Ra a₁ a₂ → Rb b₁ b₂ → rprod (a₁, b₁) (a₂, b₂) end section parameters {A B : Type} parameters {Ra : A → A → Type} {Rb : B → B → Type} local infix `≺`:50 := lex Ra Rb definition lex.accessible {a} (aca : acc Ra a) (acb : ∀b, acc Rb b): ∀b, acc (lex Ra Rb) (a, b) := acc.rec_on aca (λxa aca (iHa : ∀y, Ra y xa → ∀b, acc (lex Ra Rb) (y, b)), λb, acc.rec_on (acb b) (λxb acb (iHb : ∀y, Rb y xb → acc (lex Ra Rb) (xa, y)), acc.intro (xa, xb) (λp (lt : p ≺ (xa, xb)), have aux : xa = xa → xb = xb → acc (lex Ra Rb) p, from @prod.lex.rec_on A B Ra Rb (λp₁ p₂ h, pr₁ p₂ = xa → pr₂ p₂ = xb → acc (lex Ra Rb) p₁) p (xa, xb) lt (λa₁ b₁ a₂ b₂ (H : Ra a₁ a₂) (eq₂ : a₂ = xa) (eq₃ : b₂ = xb), show acc (lex Ra Rb) (a₁, b₁), from have Ra₁ : Ra a₁ xa, from eq.rec_on eq₂ H, iHa a₁ Ra₁ b₁) (λa b₁ b₂ (H : Rb b₁ b₂) (eq₂ : a = xa) (eq₃ : b₂ = xb), show acc (lex Ra Rb) (a, b₁), from have Rb₁ : Rb b₁ xb, from eq.rec_on eq₃ H, have eq₂' : xa = a, from eq.rec_on eq₂ rfl, eq.rec_on eq₂' (iHb b₁ Rb₁)), aux rfl rfl))) -- The lexicographical order of well founded relations is well-founded definition lex.wf (Ha : well_founded Ra) (Hb : well_founded Rb) : well_founded (lex Ra Rb) := well_founded.intro (λp, destruct p (λa b, lex.accessible (Ha a) (well_founded.apply Hb) b)) -- Relational product is a subrelation of the lex definition rprod.sub_lex : ∀ a b, rprod Ra Rb a b → lex Ra Rb a b := λa b H, prod.rprod.rec_on H (λ a₁ b₁ a₂ b₂ H₁ H₂, lex.left Rb a₂ b₂ H₁) -- The relational product of well founded relations is well-founded definition rprod.wf (Ha : well_founded Ra) (Hb : well_founded Rb) : well_founded (rprod Ra Rb) := subrelation.wf (rprod.sub_lex) (lex.wf Ha Hb) end end prod /- logic using prod and sum -/ variables {a b c d : Type} open prod sum unit /- prod -/ definition not_prod_of_not_left (b : Type) (Hna : ¬a) : ¬(a × b) := assume H : a × b, absurd (pr1 H) Hna definition not_prod_of_not_right (a : Type) {b : Type} (Hnb : ¬b) : ¬(a × b) := assume H : a × b, absurd (pr2 H) Hnb definition prod.swap (H : a × b) : b × a := pair (pr2 H) (pr1 H) definition prod_of_prod_of_imp_of_imp (H₁ : a × b) (H₂ : a → c) (H₃ : b → d) : c × d := by cases H₁ with aa bb; exact (H₂ aa, H₃ bb) definition prod_of_prod_of_imp_left (H₁ : a × c) (H : a → b) : b × c := by cases H₁ with aa cc; exact (H aa, cc) definition prod_of_prod_of_imp_right (H₁ : c × a) (H : a → b) : c × b := by cases H₁ with cc aa; exact (cc, H aa) definition prod.comm : a × b ↔ b × a := iff.intro (λH, prod.swap H) (λH, prod.swap H) definition prod.assoc : (a × b) × c ↔ a × (b × c) := iff.intro (assume H, pair (pr1 (pr1 H)) (pair (pr2 (pr1 H)) (pr2 H))) (assume H, pair (pair (pr1 H) (pr1 (pr2 H))) (pr2 (pr2 H))) definition prod_unit (a : Type) : a × unit ↔ a := iff.intro (assume H, pr1 H) (assume H, pair H star) definition unit_prod (a : Type) : unit × a ↔ a := iff.intro (assume H, pr2 H) (assume H, pair star H) definition prod_empty (a : Type) : a × empty ↔ empty := iff.intro (assume H, pr2 H) (assume H, !empty.elim H) definition empty_prod (a : Type) : empty × a ↔ empty := iff.intro (assume H, pr1 H) (assume H, !empty.elim H) definition prod_self (a : Type) : a × a ↔ a := iff.intro (assume H, pr1 H) (assume H, pair H H) /- sum -/ definition not_sum (Hna : ¬a) (Hnb : ¬b) : ¬(a ⊎ b) := assume H : a ⊎ b, sum.rec_on H (assume Ha, absurd Ha Hna) (assume Hb, absurd Hb Hnb) definition sum_of_sum_of_imp_of_imp (H₁ : a ⊎ b) (H₂ : a → c) (H₃ : b → d) : c ⊎ d := sum.rec_on H₁ (assume Ha : a, sum.inl (H₂ Ha)) (assume Hb : b, sum.inr (H₃ Hb)) definition sum_of_sum_of_imp_left (H₁ : a ⊎ c) (H : a → b) : b ⊎ c := sum.rec_on H₁ (assume H₂ : a, sum.inl (H H₂)) (assume H₂ : c, sum.inr H₂) definition sum_of_sum_of_imp_right (H₁ : c ⊎ a) (H : a → b) : c ⊎ b := sum.rec_on H₁ (assume H₂ : c, sum.inl H₂) (assume H₂ : a, sum.inr (H H₂)) definition sum.elim3 (H : a ⊎ b ⊎ c) (Ha : a → d) (Hb : b → d) (Hc : c → d) : d := sum.rec_on H Ha (assume H₂, sum.rec_on H₂ Hb Hc) definition sum_resolve_right (H₁ : a ⊎ b) (H₂ : ¬a) : b := sum.rec_on H₁ (assume Ha, absurd Ha H₂) (assume Hb, Hb) definition sum_resolve_left (H₁ : a ⊎ b) (H₂ : ¬b) : a := sum.rec_on H₁ (assume Ha, Ha) (assume Hb, absurd Hb H₂) definition sum.swap (H : a ⊎ b) : b ⊎ a := sum.rec_on H (assume Ha, sum.inr Ha) (assume Hb, sum.inl Hb) definition sum.comm : a ⊎ b ↔ b ⊎ a := iff.intro (λH, sum.swap H) (λH, sum.swap H) definition sum.assoc : (a ⊎ b) ⊎ c ↔ a ⊎ (b ⊎ c) := iff.intro (assume H, sum.rec_on H (assume H₁, sum.rec_on H₁ (assume Ha, sum.inl Ha) (assume Hb, sum.inr (sum.inl Hb))) (assume Hc, sum.inr (sum.inr Hc))) (assume H, sum.rec_on H (assume Ha, (sum.inl (sum.inl Ha))) (assume H₁, sum.rec_on H₁ (assume Hb, sum.inl (sum.inr Hb)) (assume Hc, sum.inr Hc))) definition sum_unit (a : Type) : a ⊎ unit ↔ unit := iff.intro (assume H, star) (assume H, sum.inr H) definition unit_sum (a : Type) : unit ⊎ a ↔ unit := iff.intro (assume H, star) (assume H, sum.inl H) definition sum_empty (a : Type) : a ⊎ empty ↔ a := iff.intro (assume H, sum.rec_on H (assume H1 : a, H1) (assume H1 : empty, !empty.elim H1)) (assume H, sum.inl H) definition empty_sum (a : Type) : empty ⊎ a ↔ a := iff.intro (assume H, sum.rec_on H (assume H1 : empty, !empty.elim H1) (assume H1 : a, H1)) (assume H, sum.inr H) definition sum_self (a : Type) : a ⊎ a ↔ a := iff.intro (assume H, sum.rec_on H (assume H1, H1) (assume H1, H1)) (assume H, sum.inl H)
a599cfc18d64ce4c7097cc1fb7538e0ad7d2cf2e
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/order/category/BoolAlg.lean
6aaaa3a2fab5ffb3d6ed4e46cfc980d1113f0777
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
2,815
lean
/- Copyright (c) 2022 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import order.category.HeytAlg /-! # The category of boolean algebras This defines `BoolAlg`, the category of boolean algebras. -/ open order_dual opposite set universes u open category_theory /-- The category of boolean algebras. -/ def BoolAlg := bundled boolean_algebra namespace BoolAlg instance : has_coe_to_sort BoolAlg Type* := bundled.has_coe_to_sort instance (X : BoolAlg) : boolean_algebra X := X.str /-- Construct a bundled `BoolAlg` from a `boolean_algebra`. -/ def of (α : Type*) [boolean_algebra α] : BoolAlg := bundled.of α @[simp] lemma coe_of (α : Type*) [boolean_algebra α] : ↥(of α) = α := rfl instance : inhabited BoolAlg := ⟨of punit⟩ /-- Turn a `BoolAlg` into a `BoundedDistribLattice` by forgetting its complement operation. -/ def to_BoundedDistribLattice (X : BoolAlg) : BoundedDistribLattice := BoundedDistribLattice.of X @[simp] lemma coe_to_BoundedDistribLattice (X : BoolAlg) : ↥X.to_BoundedDistribLattice = ↥X := rfl instance : large_category.{u} BoolAlg := induced_category.category to_BoundedDistribLattice instance : concrete_category BoolAlg := induced_category.concrete_category to_BoundedDistribLattice instance has_forget_to_BoundedDistribLattice : has_forget₂ BoolAlg BoundedDistribLattice := induced_category.has_forget₂ to_BoundedDistribLattice section local attribute [instance] bounded_lattice_hom_class.to_biheyting_hom_class @[simps] instance has_forget_to_HeytAlg : has_forget₂ BoolAlg HeytAlg := { forget₂ := { obj := λ X, ⟨X⟩, map := λ X Y f, show bounded_lattice_hom X Y, from f } } end /-- Constructs an equivalence between Boolean algebras from an order isomorphism between them. -/ @[simps] def iso.mk {α β : BoolAlg.{u}} (e : α ≃o β) : α ≅ β := { hom := (e : bounded_lattice_hom α β), inv := (e.symm : bounded_lattice_hom β α), hom_inv_id' := by { ext, exact e.symm_apply_apply _ }, inv_hom_id' := by { ext, exact e.apply_symm_apply _ } } /-- `order_dual` as a functor. -/ @[simps] def dual : BoolAlg ⥤ BoolAlg := { obj := λ X, of Xᵒᵈ, map := λ X Y, bounded_lattice_hom.dual } /-- The equivalence between `BoolAlg` and itself induced by `order_dual` both ways. -/ @[simps functor inverse] def dual_equiv : BoolAlg ≌ BoolAlg := equivalence.mk dual dual (nat_iso.of_components (λ X, iso.mk $ order_iso.dual_dual X) $ λ X Y f, rfl) (nat_iso.of_components (λ X, iso.mk $ order_iso.dual_dual X) $ λ X Y f, rfl) end BoolAlg lemma BoolAlg_dual_comp_forget_to_BoundedDistribLattice : BoolAlg.dual ⋙ forget₂ BoolAlg BoundedDistribLattice = forget₂ BoolAlg BoundedDistribLattice ⋙ BoundedDistribLattice.dual := rfl
0582cd413887c5b42a1a4a035440dc4a258dd140
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Init/Classical.lean
4d1a2772fda154fec1d3def1af54039b4eb2f29a
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
5,577
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Core import Init.NotationExtra universe u v /-! # Classical reasoning support -/ namespace Classical noncomputable def indefiniteDescription {α : Sort u} (p : α → Prop) (h : ∃ x, p x) : {x // p x} := choice <| let ⟨x, px⟩ := h; ⟨⟨x, px⟩⟩ noncomputable def choose {α : Sort u} {p : α → Prop} (h : ∃ x, p x) : α := (indefiniteDescription p h).val theorem choose_spec {α : Sort u} {p : α → Prop} (h : ∃ x, p x) : p (choose h) := (indefiniteDescription p h).property /-- Diaconescu's theorem: excluded middle from choice, Function extensionality and propositional extensionality. -/ theorem em (p : Prop) : p ∨ ¬p := let U (x : Prop) : Prop := x = True ∨ p let V (x : Prop) : Prop := x = False ∨ p have exU : ∃ x, U x := ⟨True, Or.inl rfl⟩ have exV : ∃ x, V x := ⟨False, Or.inl rfl⟩ let u : Prop := choose exU let v : Prop := choose exV have u_def : U u := choose_spec exU have v_def : V v := choose_spec exV have not_uv_or_p : u ≠ v ∨ p := match u_def, v_def with | Or.inr h, _ => Or.inr h | _, Or.inr h => Or.inr h | Or.inl hut, Or.inl hvf => have hne : u ≠ v := by simp [hvf, hut, true_ne_false] Or.inl hne have p_implies_uv : p → u = v := fun hp => have hpred : U = V := funext fun x => have hl : (x = True ∨ p) → (x = False ∨ p) := fun _ => Or.inr hp have hr : (x = False ∨ p) → (x = True ∨ p) := fun _ => Or.inr hp show (x = True ∨ p) = (x = False ∨ p) from propext (Iff.intro hl hr) have h₀ : ∀ exU exV, @choose _ U exU = @choose _ V exV := by rw [hpred]; intros; rfl show u = v from h₀ _ _ match not_uv_or_p with | Or.inl hne => Or.inr (mt p_implies_uv hne) | Or.inr h => Or.inl h theorem exists_true_of_nonempty {α : Sort u} : Nonempty α → ∃ _ : α, True | ⟨x⟩ => ⟨x, trivial⟩ noncomputable def inhabited_of_nonempty {α : Sort u} (h : Nonempty α) : Inhabited α := ⟨choice h⟩ noncomputable def inhabited_of_exists {α : Sort u} {p : α → Prop} (h : ∃ x, p x) : Inhabited α := inhabited_of_nonempty (Exists.elim h (fun w _ => ⟨w⟩)) /-- All propositions are `Decidable`. -/ noncomputable scoped instance (priority := low) propDecidable (a : Prop) : Decidable a := choice <| match em a with | Or.inl h => ⟨isTrue h⟩ | Or.inr h => ⟨isFalse h⟩ noncomputable def decidableInhabited (a : Prop) : Inhabited (Decidable a) where default := inferInstance noncomputable def typeDecidableEq (α : Sort u) : DecidableEq α := fun _ _ => inferInstance noncomputable def typeDecidable (α : Sort u) : PSum α (α → False) := match (propDecidable (Nonempty α)) with | (isTrue hp) => PSum.inl (@default _ (inhabited_of_nonempty hp)) | (isFalse hn) => PSum.inr (fun a => absurd (Nonempty.intro a) hn) noncomputable def strongIndefiniteDescription {α : Sort u} (p : α → Prop) (h : Nonempty α) : {x : α // (∃ y : α, p y) → p x} := @dite _ (∃ x : α, p x) (propDecidable _) (fun (hp : ∃ x : α, p x) => show {x : α // (∃ y : α, p y) → p x} from let xp := indefiniteDescription _ hp; ⟨xp.val, fun _ => xp.property⟩) (fun hp => ⟨choice h, fun h => absurd h hp⟩) /-- the Hilbert epsilon Function -/ noncomputable def epsilon {α : Sort u} [h : Nonempty α] (p : α → Prop) : α := (strongIndefiniteDescription p h).val theorem epsilon_spec_aux {α : Sort u} (h : Nonempty α) (p : α → Prop) : (∃ y, p y) → p (@epsilon α h p) := (strongIndefiniteDescription p h).property theorem epsilon_spec {α : Sort u} {p : α → Prop} (hex : ∃ y, p y) : p (@epsilon α (nonempty_of_exists hex) p) := epsilon_spec_aux (nonempty_of_exists hex) p hex theorem epsilon_singleton {α : Sort u} (x : α) : @epsilon α ⟨x⟩ (fun y => y = x) = x := @epsilon_spec α (fun y => y = x) ⟨x, rfl⟩ /-- the axiom of choice -/ theorem axiomOfChoice {α : Sort u} {β : α → Sort v} {r : ∀ x, β x → Prop} (h : ∀ x, ∃ y, r x y) : ∃ (f : ∀ x, β x), ∀ x, r x (f x) := ⟨_, fun x => choose_spec (h x)⟩ theorem skolem {α : Sort u} {b : α → Sort v} {p : ∀ x, b x → Prop} : (∀ x, ∃ y, p x y) ↔ ∃ (f : ∀ x, b x), ∀ x, p x (f x) := ⟨axiomOfChoice, fun ⟨f, hw⟩ (x) => ⟨f x, hw x⟩⟩ theorem propComplete (a : Prop) : a = True ∨ a = False := match em a with | Or.inl ha => Or.inl (propext (Iff.intro (fun _ => ⟨⟩) (fun _ => ha))) | Or.inr hn => Or.inr (propext (Iff.intro (fun h => hn h) (fun h => False.elim h))) -- this supercedes byCases in Decidable theorem byCases {p q : Prop} (hpq : p → q) (hnpq : ¬p → q) : q := Decidable.byCases (dec := propDecidable _) hpq hnpq -- this supercedes byContradiction in Decidable theorem byContradiction {p : Prop} (h : ¬p → False) : p := Decidable.byContradiction (dec := propDecidable _) h /-- `by_cases (h :)? p` splits the main goal into two cases, assuming `h : p` in the first branch, and `h : ¬ p` in the second branch. -/ syntax "by_cases " (atomic(ident " : "))? term : tactic macro_rules | `(tactic| by_cases $h : $e) => `(tactic| cases em $e with | inl $h => _ | inr $h => _) | `(tactic| by_cases $e) => `(tactic| cases em $e with | inl h => _ | inr h => _) end Classical
7246d7f57bf551c6cdb022f7d168b54a241e4438
9028d228ac200bbefe3a711342514dd4e4458bff
/src/ring_theory/unique_factorization_domain.lean
720ad682037cbb8643ad2709b89d162409582da3
[ "Apache-2.0" ]
permissive
mcncm/mathlib
8d25099344d9d2bee62822cb9ed43aa3e09fa05e
fde3d78cadeec5ef827b16ae55664ef115e66f57
refs/heads/master
1,672,743,316,277
1,602,618,514,000
1,602,618,514,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
46,952
lean
/- 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, Jens Wagemaker, Aaron Anderson -/ import algebra.gcd_monoid import ring_theory.integral_domain import ring_theory.noetherian /-- # Unique factorization ## Main Definitions * `wf_dvd_monoid` holds for `monoid`s for which a strict divisibility relation is well-founded. * `unique_factorization_monoid` holds for `wf_dvd_monoid`s where `irreducible` is equivalent to `prime` ## To do * set up the complete lattice structure on `factor_set`. -/ variables {α : Type*} local infix ` ~ᵤ ` : 50 := associated /-- Well-foundedness of the strict version of |, which is equivalent to the descending chain condition on divisibility and to the ascending chain condition on principal ideals in an integral domain. -/ class wf_dvd_monoid (α : Type*) [comm_monoid_with_zero α] : Prop := (well_founded_dvd_not_unit : well_founded (@dvd_not_unit α _)) export wf_dvd_monoid (well_founded_dvd_not_unit) @[priority 100] -- see Note [lower instance priority] instance is_noetherian_ring.wf_dvd_monoid [integral_domain α] [is_noetherian_ring α] : wf_dvd_monoid α := ⟨by { convert inv_image.wf (λ a, ideal.span ({a} : set α)) (well_founded_submodule_gt _ _), ext, exact ideal.span_singleton_lt_span_singleton.symm }⟩ instance polynomial.wf_dvd_monoid [integral_domain α] [wf_dvd_monoid α] : wf_dvd_monoid (polynomial α) := { well_founded_dvd_not_unit := begin classical, refine rel_hom.well_founded ⟨λ p, (if p = 0 then ⊤ else ↑p.degree, p.leading_coeff), _⟩ (prod.lex_wf (with_top.well_founded_lt $ with_bot.well_founded_lt nat.lt_wf) _inst_2.well_founded_dvd_not_unit), rintros a b ⟨ane0, ⟨c, ⟨not_unit_c, rfl⟩⟩⟩, rw [polynomial.degree_mul, if_neg ane0], split_ifs with hac, { rw [hac, polynomial.leading_coeff_zero], apply prod.lex.left, exact lt_of_le_of_ne le_top with_top.coe_ne_top }, have cne0 : c ≠ 0 := right_ne_zero_of_mul hac, simp only [cne0, ane0, polynomial.leading_coeff_mul], by_cases hdeg : c.degree = 0, { simp only [hdeg, add_zero], refine prod.lex.right _ ⟨_, ⟨c.leading_coeff, (λ unit_c, not_unit_c _), rfl⟩⟩, { rwa [ne, polynomial.leading_coeff_eq_zero] }, rw [polynomial.is_unit_iff, polynomial.eq_C_of_degree_eq_zero hdeg], use [c.leading_coeff, unit_c], rw [polynomial.leading_coeff, polynomial.nat_degree_eq_of_degree_eq_some hdeg] }, { apply prod.lex.left, rw polynomial.degree_eq_nat_degree cne0 at *, rw [with_top.coe_lt_coe, polynomial.degree_eq_nat_degree ane0, ← with_bot.coe_add, with_bot.coe_lt_coe], exact lt_add_of_pos_right _ (nat.pos_of_ne_zero (λ h, hdeg (h.symm ▸ with_bot.coe_zero))) }, end } namespace wf_dvd_monoid variables [comm_monoid_with_zero α] open associates nat theorem of_wf_dvd_monoid_associates (h : wf_dvd_monoid (associates α)): wf_dvd_monoid α := ⟨begin haveI := h, refine (surjective.well_founded_iff mk_surjective _).2 wf_dvd_monoid.well_founded_dvd_not_unit, intros, rw mk_dvd_not_unit_mk_iff end⟩ variables [wf_dvd_monoid α] instance wf_dvd_monoid_associates : wf_dvd_monoid (associates α) := ⟨begin refine (surjective.well_founded_iff mk_surjective _).1 wf_dvd_monoid.well_founded_dvd_not_unit, intros, rw mk_dvd_not_unit_mk_iff end⟩ theorem well_founded_associates : well_founded ((<) : associates α → associates α → Prop) := subrelation.wf (λ x y, dvd_not_unit_of_lt) wf_dvd_monoid.well_founded_dvd_not_unit local attribute [elab_as_eliminator] well_founded.fix lemma exists_irreducible_factor {a : α} (ha : ¬ is_unit a) (ha0 : a ≠ 0) : ∃ i, irreducible i ∧ i ∣ a := (irreducible_or_factor a ha).elim (λ hai, ⟨a, hai, dvd_refl _⟩) (well_founded.fix wf_dvd_monoid.well_founded_dvd_not_unit (λ a ih ha ha0 ⟨x, y, hx, hy, hxy⟩, have hx0 : x ≠ 0, from λ hx0, ha0 (by rw [← hxy, hx0, zero_mul]), (irreducible_or_factor x hx).elim (λ hxi, ⟨x, hxi, hxy ▸ by simp⟩) (λ hxf, let ⟨i, hi⟩ := ih x ⟨hx0, y, hy, hxy.symm⟩ hx hx0 hxf in ⟨i, hi.1, dvd.trans hi.2 (hxy ▸ by simp)⟩)) a ha ha0) @[elab_as_eliminator] lemma induction_on_irreducible {P : α → Prop} (a : α) (h0 : P 0) (hu : ∀ u : α, is_unit u → P u) (hi : ∀ a i : α, a ≠ 0 → irreducible i → P a → P (i * a)) : P a := by haveI := classical.dec; exact well_founded.fix wf_dvd_monoid.well_founded_dvd_not_unit (λ a ih, if ha0 : a = 0 then ha0.symm ▸ h0 else if hau : is_unit a then hu a hau else let ⟨i, hii, ⟨b, hb⟩⟩ := exists_irreducible_factor hau ha0 in have hb0 : b ≠ 0, from λ hb0, by simp * at *, hb.symm ▸ hi _ _ hb0 hii (ih _ ⟨hb0, i, hii.1, by rw [hb, mul_comm]⟩)) a lemma exists_factors (a : α) : a ≠ 0 → ∃f : multiset α, (∀b ∈ f, irreducible b) ∧ associated f.prod a := wf_dvd_monoid.induction_on_irreducible a (λ h, (h rfl).elim) (λ u hu _, ⟨0, ⟨by simp [hu], associated.symm (by simp [hu, associated_one_iff_is_unit])⟩⟩) (λ a i ha0 hii ih hia0, let ⟨s, hs⟩ := ih ha0 in ⟨i ::ₘ s, ⟨by clear _let_match; finish, by { rw multiset.prod_cons, exact associated_mul_mul (by refl) hs.2 }⟩⟩) end wf_dvd_monoid theorem wf_dvd_monoid.of_well_founded_associates [comm_cancel_monoid_with_zero α] (h : well_founded ((<) : associates α → associates α → Prop)) : wf_dvd_monoid α := wf_dvd_monoid.of_wf_dvd_monoid_associates ⟨by { convert h, ext, exact associates.dvd_not_unit_iff_lt }⟩ theorem wf_dvd_monoid.iff_well_founded_associates [comm_cancel_monoid_with_zero α] : wf_dvd_monoid α ↔ well_founded ((<) : associates α → associates α → Prop) := ⟨by apply wf_dvd_monoid.well_founded_associates, wf_dvd_monoid.of_well_founded_associates⟩ section prio set_option default_priority 100 -- see Note [default priority] /-- unique factorization monoids. These are defined as `comm_cancel_monoid_with_zero`s with well-founded strict divisibility relations, but this is equivalent to more familiar definitions: Each element (except zero) is uniquely represented as a multiset of irreducible factors. Uniqueness is only up to associated elements. Each element (except zero) is non-uniquely represented as a multiset of prime factors. To define a UFD using the definition in terms of multisets of irreducible factors, use the definition `of_unique_irreducible_factorization` To define a UFD using the definition in terms of multisets of prime factors, use the definition `of_exists_prime_factorization` -/ class unique_factorization_monoid (α : Type*) [comm_cancel_monoid_with_zero α] extends wf_dvd_monoid α : Prop := (irreducible_iff_prime : ∀ {a : α}, irreducible a ↔ prime a) instance ufm_of_gcd_of_wf_dvd_monoid [nontrivial α] [comm_cancel_monoid_with_zero α] [wf_dvd_monoid α] [gcd_monoid α] : unique_factorization_monoid α := { irreducible_iff_prime := λ _, gcd_monoid.irreducible_iff_prime .. ‹wf_dvd_monoid α› } instance associates.ufm [comm_cancel_monoid_with_zero α] [unique_factorization_monoid α] : unique_factorization_monoid (associates α) := { irreducible_iff_prime := by { rw ← associates.irreducible_iff_prime_iff, apply unique_factorization_monoid.irreducible_iff_prime, } .. (wf_dvd_monoid.wf_dvd_monoid_associates : wf_dvd_monoid (associates α)) } end prio namespace unique_factorization_monoid variables [comm_cancel_monoid_with_zero α] [unique_factorization_monoid α] theorem exists_prime_of_factor (a : α) : a ≠ 0 → ∃ f : multiset α, (∀b ∈ f, prime b) ∧ f.prod ~ᵤ a := by { simp_rw ← unique_factorization_monoid.irreducible_iff_prime, apply wf_dvd_monoid.exists_factors a } @[elab_as_eliminator] lemma induction_on_prime {P : α → Prop} (a : α) (h₁ : P 0) (h₂ : ∀ x : α, is_unit x → P x) (h₃ : ∀ a p : α, a ≠ 0 → prime p → P a → P (p * a)) : P a := begin simp_rw ← unique_factorization_monoid.irreducible_iff_prime at h₃, exact wf_dvd_monoid.induction_on_irreducible a h₁ h₂ h₃, end lemma factors_unique : ∀{f g : multiset α}, (∀x∈f, irreducible x) → (∀x∈g, irreducible x) → f.prod ~ᵤ g.prod → multiset.rel associated f g := by haveI := classical.dec_eq α; exact λ f, multiset.induction_on f (λ g _ hg h, multiset.rel_zero_left.2 $ multiset.eq_zero_of_forall_not_mem (λ x hx, have is_unit g.prod, by simpa [associated_one_iff_is_unit] using h.symm, (hg x hx).1 (is_unit_iff_dvd_one.2 (dvd.trans (multiset.dvd_prod hx) (is_unit_iff_dvd_one.1 this))))) (λ p f ih g hf hg hfg, let ⟨b, hbg, hb⟩ := exists_associated_mem_of_dvd_prod (irreducible_iff_prime.1 (hf p (by simp))) (λ q hq, irreducible_iff_prime.1 (hg _ hq)) $ (dvd_iff_dvd_of_rel_right hfg).1 (show p ∣ (p ::ₘ f).prod, by simp) in begin rw ← multiset.cons_erase hbg, exact multiset.rel.cons hb (ih (λ q hq, hf _ (by simp [hq])) (λ q (hq : q ∈ g.erase b), hg q (multiset.mem_of_mem_erase hq)) (associated_mul_left_cancel (by rwa [← multiset.prod_cons, ← multiset.prod_cons, multiset.cons_erase hbg]) hb (hf p (by simp)).ne_zero)) end) end unique_factorization_monoid lemma prime_factors_unique [comm_cancel_monoid_with_zero α] : ∀ {f g : multiset α}, (∀ x ∈ f, prime x) → (∀ x ∈ g, prime x) → f.prod ~ᵤ g.prod → multiset.rel associated f g := by haveI := classical.dec_eq α; exact λ f, multiset.induction_on f (λ g _ hg h, multiset.rel_zero_left.2 $ multiset.eq_zero_of_forall_not_mem (λ x hx, have is_unit g.prod, by simpa [associated_one_iff_is_unit] using h.symm, (irreducible_of_prime $ hg x hx).1 (is_unit_iff_dvd_one.2 (dvd.trans (multiset.dvd_prod hx) (is_unit_iff_dvd_one.1 this))))) (λ p f ih g hf hg hfg, let ⟨b, hbg, hb⟩ := exists_associated_mem_of_dvd_prod (hf p (by simp)) (λ q hq, hg _ hq) $ (dvd_iff_dvd_of_rel_right hfg).1 (show p ∣ (p ::ₘ f).prod, by simp) in begin rw ← multiset.cons_erase hbg, exact multiset.rel.cons hb (ih (λ q hq, hf _ (by simp [hq])) (λ q (hq : q ∈ g.erase b), hg q (multiset.mem_of_mem_erase hq)) (associated_mul_left_cancel (by rwa [← multiset.prod_cons, ← multiset.prod_cons, multiset.cons_erase hbg]) hb (hf p (by simp)).ne_zero)) end) /-- If an irreducible has a prime factorization, then it is an associate of one of its prime factors. -/ lemma prime_factors_irreducible [comm_cancel_monoid_with_zero α] {a : α} {f : multiset α} (ha : irreducible a) (pfa : (∀b ∈ f, prime b) ∧ f.prod ~ᵤ a) : ∃ p, a ~ᵤ p ∧ f = p ::ₘ 0 := begin haveI := classical.dec_eq α, refine multiset.induction_on f (λ h, (ha.1 (associated_one_iff_is_unit.1 (associated.symm h))).elim) _ pfa.2 pfa.1, rintros p s _ ⟨u, hu⟩ hs, use p, have hs0 : s = 0, { by_contra hs0, obtain ⟨q, hq⟩ := multiset.exists_mem_of_ne_zero hs0, apply (hs q (by simp [hq])).2.1, refine (ha.2 ((p * ↑u) * (s.erase q).prod) _ _).resolve_left _, { rw [mul_right_comm _ _ q, mul_assoc, ← multiset.prod_cons, multiset.cons_erase hq, ← hu, mul_comm, mul_comm p _, mul_assoc], simp, }, apply mt is_unit_of_mul_is_unit_left (mt is_unit_of_mul_is_unit_left _), apply (hs p (multiset.mem_cons_self _ _)).2.1 }, simp only [mul_one, multiset.prod_cons, multiset.prod_zero, hs0] at *, exact ⟨associated.symm ⟨u, hu⟩, rfl⟩, end section exists_prime_of_factor variables [comm_cancel_monoid_with_zero α] variables (pf : ∀ (a : α), a ≠ 0 → ∃ f : multiset α, (∀b ∈ f, prime b) ∧ f.prod ~ᵤ a) include pf lemma wf_dvd_monoid_of_exists_prime_of_factor : wf_dvd_monoid α := ⟨begin classical, apply rel_hom.well_founded (rel_hom.mk _ _) (with_top.well_founded_lt nat.lt_wf), { intro a, by_cases h : a = 0, { exact ⊤ }, exact (classical.some (pf a h)).card }, rintros a b ⟨ane0, ⟨c, hc, b_eq⟩⟩, rw dif_neg ane0, by_cases h : b = 0, { simp [h, lt_top_iff_ne_top] }, rw [dif_neg h, with_top.coe_lt_coe], have cne0 : c ≠ 0, { refine mt (λ con, _) h, rw [b_eq, con, mul_zero] }, calc multiset.card (classical.some (pf a ane0)) < _ + multiset.card (classical.some (pf c cne0)) : lt_add_of_pos_right _ (multiset.card_pos.mpr (λ con, hc (associated_one_iff_is_unit.mp _))) ... = multiset.card (classical.some (pf a ane0) + classical.some (pf c cne0)) : (multiset.card_add _ _).symm ... = multiset.card (classical.some (pf b h)) : multiset.card_eq_card_of_rel (prime_factors_unique _ (classical.some_spec (pf _ h)).1 _), { convert (classical.some_spec (pf c cne0)).2.symm, rw [con, multiset.prod_zero] }, { intros x hadd, rw multiset.mem_add at hadd, cases hadd; apply (classical.some_spec (pf _ _)).1 _ hadd }, { rw multiset.prod_add, transitivity a * c, { apply associated_mul_mul; apply (classical.some_spec (pf _ _)).2 }, { rw ← b_eq, apply (classical.some_spec (pf _ _)).2.symm, } } end⟩ lemma irreducible_iff_prime_of_exists_prime_of_factor {p : α} : irreducible p ↔ prime p := begin by_cases hp0 : p = 0, { simp [hp0] }, refine ⟨λ h, _, irreducible_of_prime⟩, obtain ⟨f, hf⟩ := pf p hp0, obtain ⟨q, hq, rfl⟩ := prime_factors_irreducible h hf, rw prime_iff_of_associated hq, exact hf.1 q (multiset.mem_cons_self _ _) end theorem unique_factorization_monoid_of_exists_prime_of_factor : unique_factorization_monoid α := { irreducible_iff_prime := λ _, irreducible_iff_prime_of_exists_prime_of_factor pf, .. wf_dvd_monoid_of_exists_prime_of_factor pf } end exists_prime_of_factor theorem unique_factorization_monoid_iff_exists_prime_of_factor [comm_cancel_monoid_with_zero α] : unique_factorization_monoid α ↔ (∀ (a : α), a ≠ 0 → ∃ f : multiset α, (∀b ∈ f, prime b) ∧ f.prod ~ᵤ a) := ⟨λ h, @unique_factorization_monoid.exists_prime_of_factor _ _ h, unique_factorization_monoid_of_exists_prime_of_factor⟩ theorem irreducible_iff_prime_of_exists_unique_irreducible_of_factor [comm_cancel_monoid_with_zero α] (eif : ∀ (a : α), a ≠ 0 → ∃ f : multiset α, (∀b ∈ f, irreducible b) ∧ f.prod ~ᵤ a) (uif : ∀ (f g : multiset α), (∀ x ∈ f, irreducible x) → (∀ x ∈ g, irreducible x) → f.prod ~ᵤ g.prod → multiset.rel associated f g) (p : α) : irreducible p ↔ prime p := ⟨by letI := classical.dec_eq α; exact λ hpi, ⟨hpi.ne_zero, hpi.1, λ a b ⟨x, hx⟩, if hab0 : a * b = 0 then (eq_zero_or_eq_zero_of_mul_eq_zero hab0).elim (λ ha0, by simp [ha0]) (λ hb0, by simp [hb0]) else have hx0 : x ≠ 0, from λ hx0, by simp * at *, have ha0 : a ≠ 0, from left_ne_zero_of_mul hab0, have hb0 : b ≠ 0, from right_ne_zero_of_mul hab0, begin cases eif x hx0 with fx hfx, cases eif a ha0 with fa hfa, cases eif b hb0 with fb hfb, have h : multiset.rel associated (p ::ₘ fx) (fa + fb), { apply uif, { exact λ i hi, (multiset.mem_cons.1 hi).elim (λ hip, hip.symm ▸ hpi) (hfx.1 _), }, { exact λ i hi, (multiset.mem_add.1 hi).elim (hfa.1 _) (hfb.1 _), }, calc multiset.prod (p ::ₘ fx) ~ᵤ a * b : by rw [hx, multiset.prod_cons]; exact associated_mul_mul (by refl) hfx.2 ... ~ᵤ (fa).prod * (fb).prod : associated_mul_mul hfa.2.symm hfb.2.symm ... = _ : by rw multiset.prod_add, }, exact let ⟨q, hqf, hq⟩ := multiset.exists_mem_of_rel_of_mem h (multiset.mem_cons_self p _) in (multiset.mem_add.1 hqf).elim (λ hqa, or.inl $ (dvd_iff_dvd_of_rel_left hq).2 $ (dvd_iff_dvd_of_rel_right hfa.2).1 (multiset.dvd_prod hqa)) (λ hqb, or.inr $ (dvd_iff_dvd_of_rel_left hq).2 $ (dvd_iff_dvd_of_rel_right hfb.2).1 (multiset.dvd_prod hqb)) end⟩, irreducible_of_prime⟩ theorem unique_factorization_monoid.of_exists_unique_irreducible_of_factor [comm_cancel_monoid_with_zero α] (eif : ∀ (a : α), a ≠ 0 → ∃ f : multiset α, (∀b ∈ f, irreducible b) ∧ f.prod ~ᵤ a) (uif : ∀ (f g : multiset α), (∀ x ∈ f, irreducible x) → (∀ x ∈ g, irreducible x) → f.prod ~ᵤ g.prod → multiset.rel associated f g) : unique_factorization_monoid α := unique_factorization_monoid_of_exists_prime_of_factor (by { convert eif, simp_rw irreducible_iff_prime_of_exists_unique_irreducible_of_factor eif uif }) namespace unique_factorization_monoid variables [comm_cancel_monoid_with_zero α] [decidable_eq α] [nontrivial α] [normalization_monoid α] variables [unique_factorization_monoid α] /-- Noncomputably determines the multiset of prime factors. -/ noncomputable def factors (a : α) : multiset α := if h : a = 0 then 0 else multiset.map normalize $ classical.some (unique_factorization_monoid.exists_prime_of_factor a h) theorem factors_prod {a : α} (ane0 : a ≠ 0) : associated (factors a).prod a := begin rw [factors, dif_neg ane0], refine associated.trans _ (classical.some_spec (exists_prime_of_factor a ane0)).2, rw [← associates.mk_eq_mk_iff_associated, ← associates.prod_mk, ← associates.prod_mk, multiset.map_map], congr' 2, ext, rw [function.comp_apply, associates.mk_normalize], end theorem prime_of_factor {a : α} : ∀ (x : α), x ∈ factors a → prime x := begin rw [factors], split_ifs with ane0, { simp }, intros x hx, rcases multiset.mem_map.1 hx with ⟨y, ⟨hy, rfl⟩⟩, rw prime_iff_of_associated (normalize_associated), exact (classical.some_spec (unique_factorization_monoid.exists_prime_of_factor a ane0)).1 y hy, end theorem irreducible_of_factor {a : α} : ∀ (x : α), x ∈ factors a → irreducible x := λ x h, irreducible_of_prime (prime_of_factor x h) theorem normalize_factor {a : α} : ∀ (x : α), x ∈ factors a → normalize x = x := begin rw factors, split_ifs with h, { simp }, intros x hx, obtain ⟨y, hy, rfl⟩ := multiset.mem_map.1 hx, apply normalize_idem end lemma factors_irreducible {a : α} (ha : irreducible a) : factors a = normalize a ::ₘ 0 := begin obtain ⟨p, a_assoc, hp⟩ := prime_factors_irreducible ha ⟨prime_of_factor, factors_prod ha.ne_zero⟩, have p_mem : p ∈ factors a, { rw hp, apply multiset.mem_cons_self }, convert hp, rwa [← normalize_factor p p_mem, normalize_eq_normalize_iff, dvd_dvd_iff_associated] end lemma exists_mem_factors_of_dvd {a p : α} (ha0 : a ≠ 0) (hp : irreducible p) : p ∣ a → ∃ q ∈ factors a, p ~ᵤ q := λ ⟨b, hb⟩, have hb0 : b ≠ 0, from λ hb0, by simp * at *, have multiset.rel associated (p ::ₘ factors b) (factors a), from factors_unique (λ x hx, (multiset.mem_cons.1 hx).elim (λ h, h.symm ▸ hp) (irreducible_of_factor _)) irreducible_of_factor (associated.symm $ calc multiset.prod (factors a) ~ᵤ a : factors_prod ha0 ... = p * b : hb ... ~ᵤ multiset.prod (p ::ₘ factors b) : by rw multiset.prod_cons; exact associated_mul_mul (associated.refl _) (associated.symm (factors_prod hb0))), multiset.exists_mem_of_rel_of_mem this (by simp) end unique_factorization_monoid namespace unique_factorization_monoid variables {R : Type*} [comm_cancel_monoid_with_zero R] [unique_factorization_monoid R] lemma no_factors_of_no_prime_of_factor {a b : R} (ha : a ≠ 0) (h : (∀ {d}, d ∣ a → d ∣ b → ¬ prime d)) : ∀ {d}, d ∣ a → d ∣ b → is_unit d := λ d, induction_on_prime d (by { simp only [zero_dvd_iff], intros, contradiction }) (λ x hx _ _, hx) (λ d q hp hq ih dvd_a dvd_b, absurd hq (h (dvd_of_mul_right_dvd dvd_a) (dvd_of_mul_right_dvd dvd_b))) /-- Euclid's lemma: if `a ∣ b * c` and `a` and `c` have no common prime factors, `a ∣ b`. Compare `is_coprime.dvd_of_dvd_mul_left`. -/ lemma dvd_of_dvd_mul_left_of_no_prime_of_factor {a b c : R} (ha : a ≠ 0) : (∀ {d}, d ∣ a → d ∣ c → ¬ prime d) → a ∣ b * c → a ∣ b := begin refine induction_on_prime c _ _ _, { intro no_factors, simp only [dvd_zero, mul_zero, forall_prop_of_true], haveI := classical.prop_decidable, exact is_unit_iff_forall_dvd.mp (no_factors_of_no_prime_of_factor ha @no_factors (dvd_refl a) (dvd_zero a)) _ }, { rintros _ ⟨x, rfl⟩ _ a_dvd_bx, apply units.dvd_mul_right.mp a_dvd_bx }, { intros c p hc hp ih no_factors a_dvd_bpc, apply ih (λ q dvd_a dvd_c hq, no_factors dvd_a (dvd_mul_of_dvd_right dvd_c _) hq), rw mul_left_comm at a_dvd_bpc, refine or.resolve_left (left_dvd_or_dvd_right_of_dvd_prime_mul hp a_dvd_bpc) (λ h, _), exact no_factors h (dvd_mul_right p c) hp } end /-- Euclid's lemma: if `a ∣ b * c` and `a` and `b` have no common prime factors, `a ∣ c`. Compare `is_coprime.dvd_of_dvd_mul_right`. -/ lemma dvd_of_dvd_mul_right_of_no_prime_of_factor {a b c : R} (ha : a ≠ 0) (no_factors : ∀ {d}, d ∣ a → d ∣ b → ¬ prime d) : a ∣ b * c → a ∣ c := by simpa [mul_comm b c] using dvd_of_dvd_mul_left_of_no_prime_of_factor ha @no_factors /-- If `a ≠ 0, b` are elements of a unique factorization domain, then dividing out their common factor `c'` gives `a'` and `b'` with no factors in common. -/ lemma exists_reduced_factors : ∀ (a ≠ (0 : R)) b, ∃ a' b' c', (∀ {d}, d ∣ a' → d ∣ b' → is_unit d) ∧ c' * a' = a ∧ c' * b' = b := begin haveI := classical.prop_decidable, intros a, refine induction_on_prime a _ _ _, { intros, contradiction }, { intros a a_unit a_ne_zero b, use [a, b, 1], split, { intros p p_dvd_a _, exact is_unit_of_dvd_unit p_dvd_a a_unit }, { simp } }, { intros a p a_ne_zero p_prime ih_a pa_ne_zero b, by_cases p ∣ b, { rcases h with ⟨b, rfl⟩, obtain ⟨a', b', c', no_factor, ha', hb'⟩ := ih_a a_ne_zero b, refine ⟨a', b', p * c', @no_factor, _, _⟩, { rw [mul_assoc, ha'] }, { rw [mul_assoc, hb'] } }, { obtain ⟨a', b', c', coprime, rfl, rfl⟩ := ih_a a_ne_zero b, refine ⟨p * a', b', c', _, mul_left_comm _ _ _, rfl⟩, intros q q_dvd_pa' q_dvd_b', cases left_dvd_or_dvd_right_of_dvd_prime_mul p_prime q_dvd_pa' with p_dvd_q q_dvd_a', { have : p ∣ c' * b' := dvd_mul_of_dvd_right (dvd_trans p_dvd_q q_dvd_b') _, contradiction }, exact coprime q_dvd_a' q_dvd_b' } } end lemma exists_reduced_factors' (a b : R) (hb : b ≠ 0) : ∃ a' b' c', (∀ {d}, d ∣ a' → d ∣ b' → is_unit d) ∧ c' * a' = a ∧ c' * b' = b := let ⟨b', a', c', no_factor, hb, ha⟩ := exists_reduced_factors b hb a in ⟨a', b', c', λ _ hpb hpa, no_factor hpa hpb, ha, hb⟩ end unique_factorization_monoid namespace associates open unique_factorization_monoid associated multiset variables [comm_cancel_monoid_with_zero α] /-- `factor_set α` representation elements of unique factorization domain as multisets. `multiset α` produced by `factors` are only unique up to associated elements, while the multisets in `factor_set α` are unqiue by equality and restricted to irreducible elements. This gives us a representation of each element as a unique multisets (or the added ⊤ for 0), which has a complete lattice struture. Infimum is the greatest common divisor and supremum is the least common multiple. -/ @[reducible] def {u} factor_set (α : Type u) [comm_cancel_monoid_with_zero α] : Type u := with_top (multiset { a : associates α // irreducible a }) local attribute [instance] associated.setoid theorem factor_set.coe_add {a b : multiset { a : associates α // irreducible a }} : (↑(a + b) : factor_set α) = a + b := by norm_cast lemma factor_set.sup_add_inf_eq_add [decidable_eq (associates α)] : ∀(a b : factor_set α), a ⊔ b + a ⊓ b = a + b | none b := show ⊤ ⊔ b + ⊤ ⊓ b = ⊤ + b, by simp | a none := show a ⊔ ⊤ + a ⊓ ⊤ = a + ⊤, by simp | (some a) (some b) := show (a : factor_set α) ⊔ b + a ⊓ b = a + b, from begin rw [← with_top.coe_sup, ← with_top.coe_inf, ← with_top.coe_add, ← with_top.coe_add, with_top.coe_eq_coe], exact multiset.union_add_inter _ _ end /-- Evaluates the product of a `factor_set` to be the product of the corresponding multiset, or `0` if there is none. -/ def factor_set.prod : factor_set α → associates α | none := 0 | (some s) := (s.map coe).prod @[simp] theorem prod_top : (⊤ : factor_set α).prod = 0 := rfl @[simp] theorem prod_coe {s : multiset { a : associates α // irreducible a }} : (s : factor_set α).prod = (s.map coe).prod := rfl @[simp] theorem prod_add : ∀(a b : factor_set α), (a + b).prod = a.prod * b.prod | none b := show (⊤ + b).prod = (⊤:factor_set α).prod * b.prod, by simp | a none := show (a + ⊤).prod = a.prod * (⊤:factor_set α).prod, by simp | (some a) (some b) := show (↑a + ↑b:factor_set α).prod = (↑a:factor_set α).prod * (↑b:factor_set α).prod, by rw [← factor_set.coe_add, prod_coe, prod_coe, prod_coe, multiset.map_add, multiset.prod_add] theorem prod_mono : ∀{a b : factor_set α}, a ≤ b → a.prod ≤ b.prod | none b h := have b = ⊤, from top_unique h, by rw [this, prod_top]; exact le_refl _ | a none h := show a.prod ≤ (⊤ : factor_set α).prod, by simp; exact le_top | (some a) (some b) h := prod_le_prod $ multiset.map_le_map $ with_top.coe_le_coe.1 $ h /-- `bcount p s` is the multiplicity of `p` in the factor_set `s` (with bundled `p`)-/ def bcount [decidable_eq (associates α)] (p : {a : associates α // irreducible a}) : factor_set α → ℕ | none := 0 | (some s) := s.count p variables [dec_irr : Π (p : associates α), decidable (irreducible p)] include dec_irr /-- `count p s` is the multiplicity of the irreducible `p` in the factor_set `s`. If `p` is not irreducible, `count p s` is defined to be `0`. -/ def count [decidable_eq (associates α)] (p : associates α) : factor_set α → ℕ := if hp : irreducible p then bcount ⟨p, hp⟩ else 0 @[simp] lemma count_some [decidable_eq (associates α)] {p : associates α} (hp : irreducible p) (s : multiset _) : count p (some s) = s.count ⟨p, hp⟩:= by { dunfold count, split_ifs, refl } @[simp] lemma count_zero [decidable_eq (associates α)] {p : associates α} (hp : irreducible p) : count p (0 : factor_set α) = 0 := by { dunfold count, split_ifs, refl } lemma count_reducible [decidable_eq (associates α)] {p : associates α} (hp : ¬ irreducible p) : count p = 0 := dif_neg hp omit dec_irr /-- membership in a factor_set (bundled version) -/ def bfactor_set_mem : {a : associates α // irreducible a} → (factor_set α) → Prop | _ ⊤ := true | p (some l) := p ∈ l include dec_irr /-- `factor_set_mem p s` is the predicate that the irreducible `p` is a member of `s : factor_set α`. If `p` is not irreducible, `p` is not a member of any `factor_set`. -/ def factor_set_mem (p : associates α) (s : factor_set α) : Prop := if hp : irreducible p then bfactor_set_mem ⟨p, hp⟩ s else false instance : has_mem (associates α) (factor_set α) := ⟨factor_set_mem⟩ @[simp] lemma factor_set_mem_eq_mem (p : associates α) (s : factor_set α) : factor_set_mem p s = (p ∈ s) := rfl lemma mem_factor_set_top {p : associates α} {hp : irreducible p} : p ∈ (⊤ : factor_set α) := begin dunfold has_mem.mem, dunfold factor_set_mem, split_ifs, exact trivial end lemma mem_factor_set_some {p : associates α} {hp : irreducible p} {l : multiset {a : associates α // irreducible a }} : p ∈ (l : factor_set α) ↔ subtype.mk p hp ∈ l := begin dunfold has_mem.mem, dunfold factor_set_mem, split_ifs, refl end lemma reducible_not_mem_factor_set {p : associates α} (hp : ¬ irreducible p) (s : factor_set α) : ¬ p ∈ s := λ (h : if hp : irreducible p then bfactor_set_mem ⟨p, hp⟩ s else false), by rwa [dif_neg hp] at h omit dec_irr variable [unique_factorization_monoid α] theorem unique' {p q : multiset (associates α)} : (∀a∈p, irreducible a) → (∀a∈q, irreducible a) → p.prod = q.prod → p = q := begin apply multiset.induction_on_multiset_quot p, apply multiset.induction_on_multiset_quot q, assume s t hs ht eq, refine multiset.map_mk_eq_map_mk_of_rel (unique_factorization_monoid.factors_unique _ _ _), { exact assume a ha, ((irreducible_mk _).1 $ hs _ $ multiset.mem_map_of_mem _ ha) }, { exact assume a ha, ((irreducible_mk _).1 $ ht _ $ multiset.mem_map_of_mem _ ha) }, simpa [quot_mk_eq_mk, prod_mk, mk_eq_mk_iff_associated] using eq end variables [nontrivial α] [normalization_monoid α] private theorem forall_map_mk_factors_irreducible [decidable_eq α] (x : α) (hx : x ≠ 0) : ∀(a : associates α), a ∈ multiset.map associates.mk (factors x) → irreducible a := begin assume a ha, rcases multiset.mem_map.1 ha with ⟨c, hc, rfl⟩, exact (irreducible_mk c).2 (irreducible_of_factor _ hc) end theorem prod_le_prod_iff_le {p q : multiset (associates α)} (hp : ∀a∈p, irreducible a) (hq : ∀a∈q, irreducible a) : p.prod ≤ q.prod ↔ p ≤ q := iff.intro begin classical, rintros ⟨⟨c⟩, eqc⟩, have : c ≠ 0, from (mt mk_eq_zero.2 $ assume (hc : quot.mk setoid.r c = 0), have (0 : associates α) ∈ q, from prod_eq_zero_iff.1 $ eqc.symm ▸ hc.symm ▸ mul_zero _, not_irreducible_zero ((irreducible_mk 0).1 $ hq _ this)), have : associates.mk (factors c).prod = quot.mk setoid.r c, from mk_eq_mk_iff_associated.2 (factors_prod this), refine multiset.le_iff_exists_add.2 ⟨(factors c).map associates.mk, unique' hq _ _⟩, { assume x hx, rcases multiset.mem_add.1 hx with h | h, exact hp x h, exact forall_map_mk_factors_irreducible c ‹c ≠ 0› _ h }, { simp [multiset.prod_add, prod_mk, *] at * } end prod_le_prod variables [dec : decidable_eq α] [dec' : decidable_eq (associates α)] include dec /-- This returns the multiset of irreducible factors as a `factor_set`, a multiset of irreducible associates `with_top`. -/ noncomputable def factors' (a : α) : multiset { a : associates α // irreducible a } := (factors a).pmap (λa ha, ⟨associates.mk a, (irreducible_mk _).2 ha⟩) (irreducible_of_factor) @[simp] theorem map_subtype_coe_factors' {a : α} : (factors' a).map coe = (factors a).map associates.mk := by simp [factors', multiset.map_pmap, multiset.pmap_eq_map] theorem factors'_cong {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) (h : a ~ᵤ b) : factors' a = factors' b := have multiset.rel associated (factors a) (factors b), from factors_unique irreducible_of_factor irreducible_of_factor ((factors_prod ha).trans $ h.trans $ (factors_prod hb).symm), by simpa [(multiset.map_eq_map subtype.coe_injective).symm, rel_associated_iff_map_eq_map.symm] include dec' /-- This returns the multiset of irreducible factors of an associate as a `factor_set`, a multiset of irreducible associates `with_top`. -/ noncomputable def factors (a : associates α) : factor_set α := begin refine (if h : a = 0 then ⊤ else quotient.hrec_on a (λx h, some $ factors' x) _ h), assume a b hab, apply function.hfunext, { have : a ~ᵤ 0 ↔ b ~ᵤ 0, from iff.intro (assume ha0, hab.symm.trans ha0) (assume hb0, hab.trans hb0), simp only [associated_zero_iff_eq_zero] at this, simp only [quotient_mk_eq_mk, this, mk_eq_zero] }, exact (assume ha hb eq, heq_of_eq $ congr_arg some $ factors'_cong (λ c, ha (mk_eq_zero.2 c)) (λ c, hb (mk_eq_zero.2 c)) hab) end @[simp] theorem factors_0 : (0 : associates α).factors = ⊤ := dif_pos rfl @[simp] theorem factors_mk (a : α) (h : a ≠ 0) : (associates.mk a).factors = factors' a := by { classical, apply dif_neg, apply (mt mk_eq_zero.1 h) } theorem prod_factors : ∀(s : factor_set α), s.prod.factors = s | none := by simp [factor_set.prod]; refl | (some s) := begin unfold factor_set.prod, generalize eq_a : (s.map coe).prod = a, rcases a with ⟨a⟩, rw quot_mk_eq_mk at *, have : (s.map (coe : _ → associates α)).prod ≠ 0, from assume ha, let ⟨⟨a, ha⟩, h, eq⟩ := multiset.mem_map.1 (prod_eq_zero_iff.1 ha) in have irreducible (0 : associates α), from eq ▸ ha, not_irreducible_zero ((irreducible_mk _).1 this), have ha : a ≠ 0, by simp [*] at *, suffices : (unique_factorization_monoid.factors a).map associates.mk = s.map coe, { rw [factors_mk a ha], apply congr_arg some _, simpa [(multiset.map_eq_map subtype.coe_injective).symm] }, refine unique' (forall_map_mk_factors_irreducible _ ha) (assume a ha, let ⟨⟨x, hx⟩, ha, eq⟩ := multiset.mem_map.1 ha in eq ▸ hx) _, rw [prod_mk, eq_a, mk_eq_mk_iff_associated], exact factors_prod ha end @[simp] theorem factors_prod (a : associates α) : a.factors.prod = a := quotient.induction_on a $ assume a, decidable.by_cases (assume : associates.mk a = 0, by simp [quotient_mk_eq_mk, this]) (assume : associates.mk a ≠ 0, have a ≠ 0, by simp * at *, by simp [this, quotient_mk_eq_mk, prod_mk, mk_eq_mk_iff_associated.2 (factors_prod this)]) theorem eq_of_factors_eq_factors {a b : associates α} (h : a.factors = b.factors) : a = b := have a.factors.prod = b.factors.prod, by rw h, by rwa [factors_prod, factors_prod] at this omit dec dec' theorem eq_of_prod_eq_prod {a b : factor_set α} (h : a.prod = b.prod) : a = b := begin classical, have : a.prod.factors = b.prod.factors, by rw h, rwa [prod_factors, prod_factors] at this end include dec dec' @[simp] theorem factors_mul (a b : associates α) : (a * b).factors = a.factors + b.factors := eq_of_prod_eq_prod $ eq_of_factors_eq_factors $ by rw [prod_add, factors_prod, factors_prod, factors_prod] theorem factors_mono : ∀{a b : associates α}, a ≤ b → a.factors ≤ b.factors | s t ⟨d, rfl⟩ := by rw [factors_mul] ; exact le_add_of_nonneg_right bot_le theorem factors_le {a b : associates α} : a.factors ≤ b.factors ↔ a ≤ b := iff.intro (assume h, have a.factors.prod ≤ b.factors.prod, from prod_mono h, by rwa [factors_prod, factors_prod] at this) factors_mono omit dec dec' theorem prod_le {a b : factor_set α} : a.prod ≤ b.prod ↔ a ≤ b := begin classical, exact iff.intro (assume h, have a.prod.factors ≤ b.prod.factors, from factors_mono h, by rwa [prod_factors, prod_factors] at this) prod_mono end include dec dec' noncomputable instance : has_sup (associates α) := ⟨λa b, (a.factors ⊔ b.factors).prod⟩ noncomputable instance : has_inf (associates α) := ⟨λa b, (a.factors ⊓ b.factors).prod⟩ noncomputable instance : bounded_lattice (associates α) := { sup := (⊔), inf := (⊓), sup_le := assume a b c hac hbc, factors_prod c ▸ prod_mono (sup_le (factors_mono hac) (factors_mono hbc)), le_sup_left := assume a b, le_trans (le_of_eq (factors_prod a).symm) $ prod_mono $ le_sup_left, le_sup_right := assume a b, le_trans (le_of_eq (factors_prod b).symm) $ prod_mono $ le_sup_right, le_inf := assume a b c hac hbc, factors_prod a ▸ prod_mono (le_inf (factors_mono hac) (factors_mono hbc)), inf_le_left := assume a b, le_trans (prod_mono inf_le_left) (le_of_eq (factors_prod a)), inf_le_right := assume a b, le_trans (prod_mono inf_le_right) (le_of_eq (factors_prod b)), .. associates.partial_order, .. associates.order_top, .. associates.order_bot } lemma sup_mul_inf (a b : associates α) : (a ⊔ b) * (a ⊓ b) = a * b := show (a.factors ⊔ b.factors).prod * (a.factors ⊓ b.factors).prod = a * b, begin refine eq_of_factors_eq_factors _, rw [← prod_add, prod_factors, factors_mul, factor_set.sup_add_inf_eq_add] end include dec_irr lemma dvd_of_mem_factors {a p : associates α} {hp : irreducible p} (hm : p ∈ factors a) : p ∣ a := begin by_cases ha0 : a = 0, { rw ha0, exact dvd_zero p }, obtain ⟨a0, nza, ha'⟩ := exists_non_zero_rep ha0, rw [← associates.factors_prod a], rw [← ha', factors_mk a0 nza] at hm ⊢, erw prod_coe, apply multiset.dvd_prod, apply multiset.mem_map.mpr, exact ⟨⟨p, hp⟩, mem_factor_set_some.mp hm, rfl⟩ end omit dec' lemma dvd_of_mem_factors' {a : α} {p : associates α} {hp : irreducible p} {hz : a ≠ 0} (h_mem : subtype.mk p hp ∈ factors' a) : p ∣ associates.mk a := by { haveI := classical.dec_eq (associates α), apply @dvd_of_mem_factors _ _ _ _ _ _ _ _ _ _ hp, rw factors_mk _ hz, apply mem_factor_set_some.2 h_mem } omit dec_irr lemma mem_factors'_of_dvd {a p : α} (ha0 : a ≠ 0) (hp : irreducible p) (hd : p ∣ a) : subtype.mk (associates.mk p) ((irreducible_mk _).2 hp) ∈ factors' a := begin obtain ⟨q, hq, hpq⟩ := exists_mem_factors_of_dvd ha0 hp hd, apply multiset.mem_pmap.mpr, use q, use hq, exact subtype.eq (eq.symm (mk_eq_mk_iff_associated.mpr hpq)) end include dec_irr lemma mem_factors'_iff_dvd {a p : α} (ha0 : a ≠ 0) (hp : irreducible p) : subtype.mk (associates.mk p) ((irreducible_mk _).2 hp) ∈ factors' a ↔ p ∣ a := begin split, { rw ← mk_dvd_mk, apply dvd_of_mem_factors', apply ha0 }, { apply mem_factors'_of_dvd ha0 } end include dec' lemma mem_factors_of_dvd {a p : α} (ha0 : a ≠ 0) (hp : irreducible p) (hd : p ∣ a) : (associates.mk p) ∈ factors (associates.mk a) := begin rw factors_mk _ ha0, exact mem_factor_set_some.mpr (mem_factors'_of_dvd ha0 hp hd) end lemma mem_factors_iff_dvd {a p : α} (ha0 : a ≠ 0) (hp : irreducible p) : (associates.mk p) ∈ factors (associates.mk a) ↔ p ∣ a := begin split, { rw ← mk_dvd_mk, apply dvd_of_mem_factors, exact (irreducible_mk p).mpr hp }, { apply mem_factors_of_dvd ha0 hp } end lemma exists_prime_dvd_of_not_inf_one {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) (h : (associates.mk a) ⊓ (associates.mk b) ≠ 1) : ∃ (p : α), prime p ∧ p ∣ a ∧ p ∣ b := begin have hz : (factors (associates.mk a)) ⊓ (factors (associates.mk b)) ≠ 0, { contrapose! h with hf, change ((factors (associates.mk a)) ⊓ (factors (associates.mk b))).prod = 1, rw hf, exact multiset.prod_zero }, rw [factors_mk a ha, factors_mk b hb, ← with_top.coe_inf] at hz, obtain ⟨⟨p0, p0_irr⟩, p0_mem⟩ := multiset.exists_mem_of_ne_zero ((mt with_top.coe_eq_coe.mpr) hz), rw multiset.inf_eq_inter at p0_mem, obtain ⟨p, rfl⟩ : ∃ p, associates.mk p = p0 := quot.exists_rep p0, refine ⟨p, _, _, _⟩, { rw [← irreducible_iff_prime, ← irreducible_mk], exact p0_irr }, { apply dvd_of_mk_le_mk, apply dvd_of_mem_factors' (multiset.mem_inter.mp p0_mem).left, apply ha, }, { apply dvd_of_mk_le_mk, apply dvd_of_mem_factors' (multiset.mem_inter.mp p0_mem).right, apply hb } end theorem coprime_iff_inf_one {a b : α} (ha0 : a ≠ 0) (hb0 : b ≠ 0) : (associates.mk a) ⊓ (associates.mk b) = 1 ↔ ∀ {d : α}, d ∣ a → d ∣ b → ¬ prime d := begin split, { intros hg p ha hb hp, refine ((associates.prime_mk _).mpr hp).not_unit (is_unit_of_dvd_one _ _), rw ← hg, exact le_inf (mk_le_mk_of_dvd ha) (mk_le_mk_of_dvd hb) }, { contrapose, intros hg hc, obtain ⟨p, hp, hpa, hpb⟩ := exists_prime_dvd_of_not_inf_one ha0 hb0 hg, exact hc hpa hpb hp } end omit dec_irr theorem factors_prime_pow {p : associates α} (hp : irreducible p) (k : ℕ) : factors (p ^ k) = some (multiset.repeat ⟨p, hp⟩ k) := eq_of_prod_eq_prod (by rw [associates.factors_prod, factor_set.prod, multiset.map_repeat, multiset.prod_repeat, subtype.coe_mk]) include dec_irr theorem prime_pow_dvd_iff_le {m p : associates α} (h₁ : m ≠ 0) (h₂ : irreducible p) {k : ℕ} : p ^ k ≤ m ↔ k ≤ count p m.factors := begin obtain ⟨a, nz, rfl⟩ := associates.exists_non_zero_rep h₁, rw [factors_mk _ nz, ← with_top.some_eq_coe, count_some, multiset.le_count_iff_repeat_le, ← factors_le, factors_prime_pow h₂, factors_mk _ nz], exact with_top.coe_le_coe end theorem le_of_count_ne_zero {m p : associates α} (h0 : m ≠ 0) (hp : irreducible p) : count p m.factors ≠ 0 → p ≤ m := begin rw [← nat.pos_iff_ne_zero], intro h, rw [← pow_one p], apply (prime_pow_dvd_iff_le h0 hp).2, simpa only end theorem count_mul {a : associates α} (ha : a ≠ 0) {b : associates α} (hb : b ≠ 0) {p : associates α} (hp : irreducible p) : count p (factors (a * b)) = count p a.factors + count p b.factors := begin obtain ⟨a0, nza, ha'⟩ := exists_non_zero_rep ha, obtain ⟨b0, nzb, hb'⟩ := exists_non_zero_rep hb, rw [factors_mul, ← ha', ← hb', factors_mk a0 nza, factors_mk b0 nzb, ← factor_set.coe_add, ← with_top.some_eq_coe, ← with_top.some_eq_coe, ← with_top.some_eq_coe, count_some hp, multiset.count_add, count_some hp, count_some hp] end theorem count_of_coprime {a : associates α} (ha : a ≠ 0) {b : associates α} (hb : b ≠ 0) (hab : ∀ d, d ∣ a → d ∣ b → ¬ prime d) {p : associates α} (hp : irreducible p) : count p a.factors = 0 ∨ count p b.factors = 0 := begin rw [or_iff_not_imp_left, ← ne.def], intro hca, contrapose! hab with hcb, exact ⟨p, le_of_count_ne_zero ha hp hca, le_of_count_ne_zero hb hp hcb, (irreducible_iff_prime.mp hp)⟩, end theorem count_mul_of_coprime {a : associates α} (ha : a ≠ 0) {b : associates α} (hb : b ≠ 0) {p : associates α} (hp : irreducible p) (hab : ∀ d, d ∣ a → d ∣ b → ¬ prime d) : count p a.factors = 0 ∨ count p a.factors = count p (a * b).factors := begin cases count_of_coprime ha hb hab hp with hz hb0, { tauto }, apply or.intro_right, rw [count_mul ha hb hp, hb0, add_zero] end theorem count_mul_of_coprime' {a : associates α} (ha : a ≠ 0) {b : associates α} (hb : b ≠ 0) {p : associates α} (hp : irreducible p) (hab : ∀ d, d ∣ a → d ∣ b → ¬ prime d) : count p (a * b).factors = count p a.factors ∨ count p (a * b).factors = count p b.factors := begin rw [count_mul ha hb hp], cases count_of_coprime ha hb hab hp with ha0 hb0, { apply or.intro_right, rw [ha0, zero_add] }, { apply or.intro_left, rw [hb0, add_zero] } end theorem dvd_count_of_dvd_count_mul {a b : associates α} (ha : a ≠ 0) (hb : b ≠ 0) {p : associates α} (hp : irreducible p) (hab : ∀ d, d ∣ a → d ∣ b → ¬ prime d) {k : ℕ} (habk : k ∣ count p (a * b).factors) : k ∣ count p a.factors := begin cases count_of_coprime ha hb hab hp with hz h, { rw hz, exact dvd_zero k }, { rw [count_mul ha hb hp, h] at habk, exact habk } end omit dec_irr @[simp] lemma factors_one : factors (1 : associates α) = 0 := begin apply eq_of_prod_eq_prod, rw associates.factors_prod, exact multiset.prod_zero, end @[simp] theorem pow_factors {a : associates α} {k : ℕ} : (a ^ k).factors = k •ℕ a.factors := begin induction k with n h, { rw [zero_nsmul, pow_zero], exact factors_one }, { rw [pow_succ, succ_nsmul, factors_mul, h] } end include dec_irr lemma count_pow {a : associates α} (ha : a ≠ 0) {p : associates α} (hp : irreducible p) (k : ℕ) : count p (a ^ k).factors = k * count p a.factors := begin induction k with n h, { rw [pow_zero, factors_one, zero_mul, count_zero hp] }, { rw [pow_succ, count_mul ha (pow_ne_zero' _ ha) hp, h, nat.succ_eq_add_one], ring } end theorem dvd_count_pow {a : associates α} (ha : a ≠ 0) {p : associates α} (hp : irreducible p) (k : ℕ) : k ∣ count p (a ^ k).factors := by { rw count_pow ha hp, apply dvd_mul_right } theorem is_pow_of_dvd_count {a : associates α} (ha : a ≠ 0) {k : ℕ} (hk : ∀ (p : associates α) (hp : irreducible p), k ∣ count p a.factors) : ∃ (b : associates α), a = b ^ k := begin obtain ⟨a0, hz, rfl⟩ := exists_non_zero_rep ha, rw [factors_mk a0 hz] at hk, have hk' : ∀ (p : {a : associates α // irreducible a}), k ∣ (factors' a0).count p, { intro p, have pp : p = ⟨p.val, p.2⟩, { simp only [subtype.coe_eta, subtype.val_eq_coe] }, rw [pp, ← count_some p.2], exact hk p.val p.2 }, obtain ⟨u, hu⟩ := multiset.exists_smul_of_dvd_count _ hk', use (u : factor_set α).prod, apply eq_of_factors_eq_factors, rw [pow_factors, prod_factors, factors_mk a0 hz, ← with_top.some_eq_coe, hu], exact with_bot.coe_nsmul u k end omit dec omit dec_irr omit dec' theorem eq_pow_of_mul_eq_pow {a b c : associates α} (ha : a ≠ 0) (hb : b ≠ 0) (hab : ∀ d, d ∣ a → d ∣ b → ¬ prime d) {k : ℕ} (h : a * b = c ^ k) : ∃ (d : associates α), a = d ^ k := begin classical, by_cases hk0 : k = 0, { use 1, rw [hk0, pow_zero] at h ⊢, apply (mul_eq_one_iff.1 h).1 }, { refine is_pow_of_dvd_count ha _, intros p hp, apply dvd_count_of_dvd_count_mul ha hb hp hab, rw h, apply dvd_count_pow _ hp, rintros rfl, rw zero_pow' _ hk0 at h, cases mul_eq_zero.mp h; contradiction } end end associates section open associates unique_factorization_monoid /-- `to_gcd_monoid` constructs a GCD monoid out of a normalization on a unique factorization domain. -/ noncomputable def unique_factorization_monoid.to_gcd_monoid (α : Type*) [integral_domain α] [unique_factorization_monoid α] [normalization_monoid α] [decidable_eq (associates α)] [decidable_eq α] : gcd_monoid α := { gcd := λa b, (associates.mk a ⊓ associates.mk b).out, lcm := λa b, (associates.mk a ⊔ associates.mk b).out, gcd_dvd_left := assume a b, (out_dvd_iff a (associates.mk a ⊓ associates.mk b)).2 $ inf_le_left, gcd_dvd_right := assume a b, (out_dvd_iff b (associates.mk a ⊓ associates.mk b)).2 $ inf_le_right, dvd_gcd := assume a b c hac hab, show a ∣ (associates.mk c ⊓ associates.mk b).out, by rw [dvd_out_iff, le_inf_iff, mk_le_mk_iff_dvd_iff, mk_le_mk_iff_dvd_iff]; exact ⟨hac, hab⟩, lcm_zero_left := assume a, show (⊤ ⊔ associates.mk a).out = 0, by simp, lcm_zero_right := assume a, show (associates.mk a ⊔ ⊤).out = 0, by simp, gcd_mul_lcm := assume a b, show (associates.mk a ⊓ associates.mk b).out * (associates.mk a ⊔ associates.mk b).out = normalize (a * b), by rw [← out_mk, ← out_mul, mul_comm, sup_mul_inf]; refl, normalize_gcd := assume a b, by convert normalize_out _, .. ‹normalization_monoid α› } end
b511288b08c6a6e6747ce5ff897bf22f9204b7d0
037dba89703a79cd4a4aec5e959818147f97635d
/src/2020/functions/surjective_comp.lean
63a28d68e0cc56780227c673ca98b6e214696861
[]
no_license
ImperialCollegeLondon/M40001_lean
3a6a09298da395ab51bc220a535035d45bbe919b
62a76fa92654c855af2b2fc2bef8e60acd16ccec
refs/heads/master
1,666,750,403,259
1,665,771,117,000
1,665,771,117,000
209,141,835
115
12
null
1,640,270,596,000
1,568,749,174,000
Lean
UTF-8
Lean
false
false
644
lean
import tactic open function variables (X Y Z : Type) (f : X → Y) (g : Y → Z) example : (surjective f) ∧ (surjective g) → surjective (g ∘ f) := begin -- Say f and g are surjective. rintros ⟨hf, hg⟩, -- Choose z in Z. intro z, -- Our job is to find x in X such that g(f(x))=z. -- Well g is assumed surjective so we can find y in Y -- such that g(y)=z rcases hg z with ⟨y, rfl⟩, -- And f is assumed surjective so we can find x in X -- such that f(x)=y rcases hf y with ⟨x, rfl⟩, -- let's use this x. use x, -- and now we see g(f(x))=g(y)=z so we're done end
3e20d6b7b218b42e5bfa4cac68055f9fab58a48f
a76f677b87d42a9470ba3a0a78cfddd3063118e6
/src/congruence/ang_lt.lean
b7b1e63ddb416df12a3668155ec23dddf5ad6521
[]
no_license
Ja1941/hilberts-axioms
50219c732ad5fa167408432e8c8baae259777a40
5b653a92e448b77da41c9893066b641bc4e6b316
refs/heads/master
1,693,238,884,856
1,635,702,120,000
1,635,702,120,000
385,546,384
9
1
null
null
null
null
UTF-8
Lean
false
false
9,464
lean
/- Copyright (c) 2021 Tianchen Zhao. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Tianchen Zhao -/ import congruence.basic /-! # Angle orderness This file defines how an angle is less than another and proves basic properties such as transitivity and trichotomy. ## References * See [Geometry: Euclid and Beyond] -/ open incidence_geometry incidence_order_geometry hilbert_plane variables [C : hilbert_plane] include C /--ang `α` is less than `β` if a part of it is congruent to `β`. That is, there exists a point inside `α` with one ray of `α` forms an ang congruent to `β`-/ def ang_lt (α β : ang) : Prop := ∃ a b p : C.pts, β = (∠ a β.vertex b) ∧ inside_ang p (∠ a β.vertex b) ∧ ((∠ a β.vertex p) ≅ₐ α) notation a`<ₐ`b := ang_lt a b lemma three_pt_ang_lt {a o b : C.pts} {α : ang} : (α <ₐ (∠ a o b)) ↔ ∃ p : C.pts, inside_ang p (∠ a o b) ∧ ((∠ a o p) ≅ₐ α):= begin split, { rintros ⟨a', b', p, haoba'ob', hp, ha'op⟩, rw three_pt_ang_vertex at haoba'ob' hp ha'op, have ha'ob' := ang_proper_iff_noncol.1 (inside_ang_proper hp), have haob : noncol a o b, rw [←ang_proper_iff_noncol, haoba'ob'], exact inside_ang_proper hp, have hoa := (noncol_neq haob).1.symm, cases ((three_pt_ang_eq_iff ha'ob').1 haoba'ob'.symm).2, { have haopa'op : (∠ a o p) = (∠ a' o p), rw [ang_symm, ang_symm a' _ _ ], refine ang_eq_same_side_pt _ _, exact same_side_pt_symm h.1, use p, rw [haoba'ob', haopa'op], exact ⟨hp, ha'op⟩ }, { rcases extend_congr_ang (inside_ang_proper' hp).1 hoa (noncol_in12 (noncol12 haob)) with ⟨q, ha'opqoa, hqb, -⟩, use q, split, refine (congr_ang_sub hp hqb _ _ _).1, exact (same_side_pt_neq h.2).2.symm, rw haoba'ob', exact ang_congr_refl _, rw [ang_symm, ang_symm a o q], exact ha'opqoa, rw ang_symm, rw ang_symm at ha'op, exact ang_congr_trans (ang_congr_symm ha'opqoa) ha'op } }, { rintros ⟨p, hp, haopα⟩, use [a, b, p], rw three_pt_ang_vertex, exact ⟨rfl, hp, haopα⟩ } end lemma ang_lt_congr {α β γ : ang} (hαβ : α ≅ₐ β) : ((α <ₐ γ) → (β <ₐ γ)) ∧ (ang_proper β → (γ <ₐ α) → (γ <ₐ β)) := begin rcases ang_three_pt α with ⟨a₁, b₁, hα⟩, rcases ang_three_pt β with ⟨a₂, b₂, hβ⟩, rcases ang_three_pt γ with ⟨a₃, b₃, hγ⟩, rw [hα, hβ, hγ], rw [hα, hβ] at hαβ, set o₁ := α.vertex, set o₂ := β.vertex, set o₃ := γ.vertex, split, { intro hαγ, rcases three_pt_ang_lt.1 hαγ with ⟨p, hpin, hp⟩, rw three_pt_ang_lt, use p, split, exact hpin, exact ang_congr_trans hp hαβ }, { intros h hγα, rcases three_pt_ang_lt.1 hγα with ⟨p, hpin, hp⟩, rw ang_proper_iff_noncol at h, rcases extend_congr_ang (inside_ang_proper' hpin).1 (noncol_neq h).1.symm (noncol_in12 (noncol12 h)) with ⟨q, hq, hqb₂, -⟩, rw three_pt_ang_lt, rw ang_symm q _ _ at hq, use q, split, apply (congr_ang_sub hpin hqb₂ _ _ _).1, exact (noncol_neq h).1.symm, exact hαβ, rw ang_symm, exact hq, rw ang_symm at hq, exact ang_congr_trans (ang_congr_symm hq) hp } end lemma ang_lt_trans {α β γ : ang} : ang_proper α → (α <ₐ β) → (β <ₐ γ) → (α <ₐ γ) := begin intros hα hαβ hβγ, rcases ang_three_pt β with ⟨a₂, b₂, hβ⟩, rcases ang_three_pt γ with ⟨a₃, b₃, hγ⟩, rw hγ, rw hβ at hαβ, rw [hβ, hγ] at hβγ, set o₂ := β.vertex, set o₃ := γ.vertex, rcases three_pt_ang_lt.1 hαβ with ⟨p, hpin, hp⟩, rcases three_pt_ang_lt.1 hβγ with ⟨q, hqin, hq⟩, have ha₃o₃b₃ := ang_proper_iff_noncol.1 (inside_ang_proper hqin), rcases extend_congr_ang hα (noncol_neq ha₃o₃b₃).1.symm (noncol_in23 (ang_proper_iff_noncol.1 (inside_ang_proper' hqin).1)) with ⟨x, hx, hxq, -⟩, rw three_pt_ang_lt, use x, split, apply inside_ang_trans hqin, apply (congr_ang_sub hpin hxq _ _ _).1, exact (noncol_neq (ang_proper_iff_noncol.1 (inside_ang_proper hqin))).1.symm, exact ang_congr_symm hq, rw ang_symm at hx, exact ang_congr_trans hp hx, rw ang_symm, exact ang_congr_symm hx end lemma ang_tri {α β : ang} (ha'o'b' : ang_proper α) (haob : ang_proper β) : ((α <ₐ β) ∨ (α ≅ₐ β) ∨ (β <ₐ α)) ∧ ¬((α <ₐ β) ∧ (α ≅ₐ β)) ∧ ¬((α <ₐ β) ∧ (β <ₐ α)) ∧ ¬(((α ≅ₐ β) ∧ (β <ₐ α))) := begin rcases ang_three_pt β with ⟨a, b, hβ⟩, rw [hβ, ang_proper_iff_noncol] at haob, set o := β.vertex, have hao := (noncol_neq haob).1, have hbo := (noncol_neq haob).2.2.symm, rcases extend_congr_ang ha'o'b' hao.symm (noncol_in12 (noncol12 haob)) with ⟨x, hx, hlxb, hu⟩, have hxo := (same_side_line_neq hlxb).1, have h₁ : same_side_line (o-ₗb) x a ↔ (α <ₐ β), rw hβ, split; rw three_pt_ang_lt, intro h₁, use x, split, rw inside_three_pt_ang, exact ⟨same_side_line_symm hlxb, same_side_line_symm h₁⟩, rw ang_symm, exact ang_congr_symm hx, rintros ⟨y, hyin, hy⟩, rw inside_three_pt_ang at hyin, rw ang_symm at hy, specialize hu y (same_side_line_trans (line_in_lines hao.symm) hlxb hyin.1) (ang_congr_symm hy), have hoxb := col_noncol (col_in13' ((ray_in_line o x) hu)) (noncol23 (same_side_line_noncol hyin.2 hbo.symm).2) hxo.symm, have hyo := (same_side_line_neq' hyin.1).1, apply same_side_line_trans (line_in_lines hbo.symm) _ (same_side_line_symm hyin.2), rw line_symm, exact t_shape_ray (noncol132 hoxb) (ray_in_neq hyo hu), have h₂ : x ∈ (o-ₗb) ↔ (α ≅ₐ β), rw hβ, split; intro h₂, have : (∠ x o a) = (∠ a o b), rw ang_symm, apply ang_eq_same_side_pt _ _, cases (line_separation ⟨(o-ₗb), line_in_lines hbo.symm, pt_left_in_line o b, h₂, pt_right_in_line o b⟩ hxo hbo).1, exact h, { have hx := (same_side_line_notin hlxb).1, have hb := (same_side_line_notin hlxb).2, rw ←not_diff_side_line at hlxb, exfalso, apply hlxb, apply diff_side_pt_line h (line_in_lines hao.symm) (pt_left_in_line o a) hx hb, exact hx, exact hb }, rw ←this, exact hx, { rw line_symm at hlxb, rw ang_symm at hx, exact col_in13 (ang_unique_same_side hao hlxb (ang_congr_trans (ang_congr_symm hx) h₂)).2 hbo.symm }, have h₃ : diff_side_line (o-ₗb) x a ↔ (β <ₐ α), split; intro h₃, apply (ang_lt_congr (ang_congr_symm hx)).2 ha'o'b', rw ang_symm, rw three_pt_ang_lt, use b, split, rw inside_three_pt_ang, split, exact hlxb, exact diff_same_side_line' (diff_side_line_symm h₃) (same_side_line_symm hlxb), rw hβ, exact ang_congr_refl _, have : ang_proper (∠ x o a), rw ang_proper_iff_noncol, intro hxoa, exact (same_side_line_notin hlxb).1 (col_in23 hxoa hao.symm), have := (ang_lt_congr hx).2 this h₃, rw [ang_symm, three_pt_ang_lt] at this, rcases this with ⟨p, hpin, hp⟩, rw hβ at hp, have hopb : same_side_pt o p b, rw inside_three_pt_ang at hpin, rw line_symm at hpin hlxb, exact ang_unique_same_side hao (same_side_line_trans (line_in_lines hao) (same_side_line_symm hpin.1) hlxb) hp, { have hbin := ray_inside_ang hpin hopb, cases crossbar hbin with y hy, rw seg_symm at hy, use y, exact ⟨(ray_in_line o b) hy.1, hy.2⟩, rw inside_three_pt_ang at hbin, exact ⟨noncol_in13 (same_side_line_noncol hbin.2 hxo.symm).2, noncol_in23 haob⟩ }, rw [←h₁, ←h₂, ←h₃], split, by_cases x ∈ (o-ₗb), right, left, exact h, cases (plane_separation h (noncol_in23 haob)).1 with h h, left, exact h, right, right, exact h, split, intro hf, exact (same_side_line_notin hf.1).1 hf.2, split, intro hf, rw ←not_diff_side_line at hf, exact hf.1 hf.2, exact hf.2.2.1, exact hf.2.2.2, intro hf, exact hf.2.2.1 hf.1 end lemma ang_lt_supplementary {α α' β β' : ang} (hαα' : α <ₐ α') (hαβ : supplementary α β) (hα'β' : supplementary α' β') : β' <ₐ β := begin have hαβ := hαβ, rcases hαβ with ⟨⟨a, b, c, d, hα, hβ, hcad⟩, hbac, hbad⟩, rw hβ at hbad, rcases hα'β' with ⟨⟨a', b', c', d', hα', hβ', hc'a'd'⟩, hb'a'c', hb'a'd'⟩, rw [hα', ang_proper_iff_noncol] at hb'a'c', rw [hβ', ang_proper_iff_noncol] at hb'a'd', rw [hβ, hβ'], rw [hα, hα'] at hαα', rw [hα, hβ] at hαβ, rw [ang_symm b' a' c'] at hαα', rcases three_pt_ang_lt.1 hαα' with ⟨e', he', hc'a'e'bac⟩, have ha'c' := (noncol_neq hb'a'c').2.2, have ha'd' := (noncol_neq hb'a'd').2.2, have ha'c'e' := (same_side_line_noncol (inside_three_pt_ang.1 he').1 ha'c').2, have ha'd'e' := col_noncol (col12 (between_col hc'a'd')) ha'c'e' ha'd', have : supplementary (∠ e' a' c') (∠ e' a' d'), rw three_pt_ang_supplementary, exact ⟨hc'a'd', noncol132 ha'c'e', noncol132 ha'd'e'⟩, rw ang_symm at hc'a'e'bac, have hbade'a'd' := supplementary_congr hαβ this (ang_congr_symm hc'a'e'bac), apply (ang_lt_congr (ang_congr_symm hbade'a'd')).2 hbad, rw ang_symm e' a' d', rw three_pt_ang_lt, use b', split, rw ang_symm, { apply inside_ang_trans' hc'a'd', rw ang_symm, exact he' }, { rw ang_symm, exact ang_congr_refl _ } end
9a5301d3d9afa46c11519b24fbee3d4f45b29ae5
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/simp_result.lean
7a96e627796e4587435b3b2a566e32fbd5c57766
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
3,375
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner, Scott Morrison -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.tactic.core import Mathlib.PostPort namespace Mathlib /-! # simp_result `dsimp_result` and `simp_result` are a pair of tactics for applying `dsimp` or `simp` to the result produced by other tactics. As examples, tactics which use `revert` and `intro` may insert additional `id` terms in the result they produce. If there is some reason these are undesirable (e.g. the result term needs to be human-readable, or satisfying syntactic rather than just definitional properties), wrapping those tactics in `dsimp_result` can remove the `id` terms "after the fact". Similarly, tactics using `subst` and `rw` will nearly always introduce `eq.rec` terms, but sometimes these will be easy to remove, for example by simplifying using `eq_rec_constant`. This is a non-definitional simplification lemma, and so wrapping these tactics in `simp_result` will result in a definitionally different result. There are several examples in the associated test file, demonstrating these interactions with `revert` and `subst`. These tactics should be used with some caution. You should consider whether there is any real need for the simplification of the result, and whether there is a more direct way of producing the result you wanted, before relying on these tactics. Both are implemented in terms of a generic `intercept_result` tactic, which allows you to run an arbitrary tactic and modify the returned results. -/ namespace tactic /-- `intercept_result m t` attempts to run a tactic `t`, intercepts any results `t` assigns to the goals, and runs `m : expr → tactic expr` on each of the expressions before assigning the returned values to the original goals. Because `intercept_result` uses `unsafe.type_context.assign` rather than `unify`, if the tactic `m` does something unreasonable you may produce terms that don't typecheck, possibly with mysterious error messages. Be careful! -/ -- Replace the goals with copies. -- Run the tactic on the copied goals. -- Run `m` on the produced terms, /-- `dsimp_result t` attempts to run a tactic `t`, intercepts any results it assigns to the goals, and runs `dsimp` on those results before assigning the simplified values to the original goals. -/ /-- `simp_result t` attempts to run a tactic `t`, intercepts any results `t` assigns to the goals, and runs `simp` on those results before assigning the simplified values to the original goals. -/ namespace interactive /-- `dsimp_result { tac }` attempts to run a tactic block `tac`, intercepts any results the tactic block would have assigned to the goals, and runs `dsimp` on those results before assigning the simplified values to the original goals. You can use the usual interactive syntax for `dsimp`, e.g. `dsimp_result only [a, b, c] with attr { tac }`. -/ /-- `simp_result { tac }` attempts to run a tactic block `tac`, intercepts any results the tactic block would have assigned to the goals, and runs `simp` on those results before assigning the simplified values to the original goals. You can use the usual interactive syntax for `simp`, e.g. `simp_result only [a, b, c] with attr { tac }`. -/ /-- `simp_result { tac }`
07a767d6f687f12b3f3bbdee429be00a9beca67a
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/finsupp/antidiagonal.lean
388c8dcdfb7870c435bb79654850e1b31129bd53
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
3,633
lean
/- 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, Yury Kudryashov -/ import data.finsupp.multiset import data.multiset.antidiagonal /-! # The `finsupp` counterpart of `multiset.antidiagonal`. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. The antidiagonal of `s : α →₀ ℕ` consists of all pairs `(t₁, t₂) : (α →₀ ℕ) × (α →₀ ℕ)` such that `t₁ + t₂ = s`. -/ noncomputable theory open_locale classical big_operators namespace finsupp open finset variables {α : Type*} /-- The `finsupp` counterpart of `multiset.antidiagonal`: the antidiagonal of `s : α →₀ ℕ` consists of all pairs `(t₁, t₂) : (α →₀ ℕ) × (α →₀ ℕ)` such that `t₁ + t₂ = s`. The finitely supported function `antidiagonal s` is equal to the multiplicities of these pairs. -/ def antidiagonal' (f : α →₀ ℕ) : ((α →₀ ℕ) × (α →₀ ℕ)) →₀ ℕ := (f.to_multiset.antidiagonal.map (prod.map multiset.to_finsupp multiset.to_finsupp)).to_finsupp /-- The antidiagonal of `s : α →₀ ℕ` is the finset of all pairs `(t₁, t₂) : (α →₀ ℕ) × (α →₀ ℕ)` such that `t₁ + t₂ = s`. -/ def antidiagonal (f : α →₀ ℕ) : finset ((α →₀ ℕ) × (α →₀ ℕ)) := f.antidiagonal'.support @[simp] lemma mem_antidiagonal {f : α →₀ ℕ} {p : (α →₀ ℕ) × (α →₀ ℕ)} : p ∈ antidiagonal f ↔ p.1 + p.2 = f := begin rcases p with ⟨p₁, p₂⟩, simp [antidiagonal, antidiagonal', ← and.assoc, ← finsupp.to_multiset.apply_eq_iff_eq] end lemma swap_mem_antidiagonal {n : α →₀ ℕ} {f : (α →₀ ℕ) × (α →₀ ℕ)} : f.swap ∈ antidiagonal n ↔ f ∈ antidiagonal n := by simp only [mem_antidiagonal, add_comm, prod.swap] lemma antidiagonal_filter_fst_eq (f g : α →₀ ℕ) [D : Π (p : (α →₀ ℕ) × (α →₀ ℕ)), decidable (p.1 = g)] : (antidiagonal f).filter (λ p, p.1 = g) = if g ≤ f then {(g, f - g)} else ∅ := begin ext ⟨a, b⟩, suffices : a = g → (a + b = f ↔ g ≤ f ∧ b = f - g), { simpa [apply_ite ((∈) (a, b)), ← and.assoc, @and.right_comm _ (a = _), and.congr_left_iff] }, unfreezingI {rintro rfl}, split, { rintro rfl, exact ⟨le_add_right le_rfl, (add_tsub_cancel_left _ _).symm⟩ }, { rintro ⟨h, rfl⟩, exact add_tsub_cancel_of_le h } end lemma antidiagonal_filter_snd_eq (f g : α →₀ ℕ) [D : Π (p : (α →₀ ℕ) × (α →₀ ℕ)), decidable (p.2 = g)] : (antidiagonal f).filter (λ p, p.2 = g) = if g ≤ f then {(f - g, g)} else ∅ := begin ext ⟨a, b⟩, suffices : b = g → (a + b = f ↔ g ≤ f ∧ a = f - g), { simpa [apply_ite ((∈) (a, b)), ← and.assoc, and.congr_left_iff] }, unfreezingI {rintro rfl}, split, { rintro rfl, exact ⟨le_add_left le_rfl, (add_tsub_cancel_right _ _).symm⟩ }, { rintro ⟨h, rfl⟩, exact tsub_add_cancel_of_le h } end @[simp] lemma antidiagonal_zero : antidiagonal (0 : α →₀ ℕ) = singleton (0,0) := by rw [antidiagonal, antidiagonal', multiset.to_finsupp_support]; refl @[to_additive] lemma prod_antidiagonal_swap {M : Type*} [comm_monoid M] (n : α →₀ ℕ) (f : (α →₀ ℕ) → (α →₀ ℕ) → M) : ∏ p in antidiagonal n, f p.1 p.2 = ∏ p in antidiagonal n, f p.2 p.1 := finset.prod_bij (λ p hp, p.swap) (λ p, swap_mem_antidiagonal.2) (λ p hp, rfl) (λ p₁ p₂ _ _ h, prod.swap_injective h) (λ p hp, ⟨p.swap, swap_mem_antidiagonal.2 hp, p.swap_swap.symm⟩) end finsupp
189a57d4e58456335b061b80609b890ef1b86357
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/probability/moments.lean
46efcf3c96c5f66e64ca09ed946d52ab54e64292
[ "Apache-2.0" ]
permissive
ramonfmir/mathlib
c5dc8b33155473fab97c38bd3aa6723dc289beaa
14c52e990c17f5a00c0cc9e09847af16fabbed25
refs/heads/master
1,661,979,343,526
1,660,830,384,000
1,660,830,384,000
182,072,989
0
0
null
1,555,585,876,000
1,555,585,876,000
null
UTF-8
Lean
false
false
13,957
lean
/- Copyright (c) 2022 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rémy Degenne -/ import probability.variance /-! # Moments and moment generating function ## Main definitions * `probability_theory.moment X p μ`: `p`th moment of a real random variable `X` with respect to measure `μ`, `μ[X^p]` * `probability_theory.central_moment X p μ`:`p`th central moment of `X` with respect to measure `μ`, `μ[(X - μ[X])^p]` * `probability_theory.mgf X μ t`: moment generating function of `X` with respect to measure `μ`, `μ[exp(t*X)]` * `probability_theory.cgf X μ t`: cumulant generating function, logarithm of the moment generating function ## Main results * `probability_theory.indep_fun.mgf_add`: if two real random variables `X` and `Y` are independent and their mgf are defined at `t`, then `mgf (X + Y) μ t = mgf X μ t * mgf Y μ t` * `probability_theory.indep_fun.cgf_add`: if two real random variables `X` and `Y` are independent and their mgf are defined at `t`, then `cgf (X + Y) μ t = cgf X μ t + cgf Y μ t` * `probability_theory.measure_ge_le_exp_cgf` and `probability_theory.measure_le_le_exp_cgf`: Chernoff bound on the upper (resp. lower) tail of a random variable. For `t` nonnegative such that the cgf exists, `ℙ(ε ≤ X) ≤ exp(- t*ε + cgf X ℙ t)`. See also `probability_theory.measure_ge_le_exp_mul_mgf` and `probability_theory.measure_le_le_exp_mul_mgf` for versions of these results using `mgf` instead of `cgf`. -/ open measure_theory filter finset real noncomputable theory open_locale big_operators measure_theory probability_theory ennreal nnreal namespace probability_theory variables {Ω ι : Type*} {m : measurable_space Ω} {X : Ω → ℝ} {p : ℕ} {μ : measure Ω} include m /-- Moment of a real random variable, `μ[X ^ p]`. -/ def moment (X : Ω → ℝ) (p : ℕ) (μ : measure Ω) : ℝ := μ[X ^ p] /-- Central moment of a real random variable, `μ[(X - μ[X]) ^ p]`. -/ def central_moment (X : Ω → ℝ) (p : ℕ) (μ : measure Ω) : ℝ := μ[(X - (λ x, μ[X])) ^ p] @[simp] lemma moment_zero (hp : p ≠ 0) : moment 0 p μ = 0 := by simp only [moment, hp, zero_pow', ne.def, not_false_iff, pi.zero_apply, integral_const, algebra.id.smul_eq_mul, mul_zero] @[simp] lemma central_moment_zero (hp : p ≠ 0) : central_moment 0 p μ = 0 := by simp only [central_moment, hp, pi.zero_apply, integral_const, algebra.id.smul_eq_mul, mul_zero, zero_sub, pi.pow_apply, pi.neg_apply, neg_zero', zero_pow', ne.def, not_false_iff] lemma central_moment_one' [is_finite_measure μ] (h_int : integrable X μ) : central_moment X 1 μ = (1 - (μ set.univ).to_real) * μ[X] := begin simp only [central_moment, pi.sub_apply, pow_one], rw integral_sub h_int (integrable_const _), simp only [sub_mul, integral_const, algebra.id.smul_eq_mul, one_mul], end @[simp] lemma central_moment_one [is_probability_measure μ] : central_moment X 1 μ = 0 := begin by_cases h_int : integrable X μ, { rw central_moment_one' h_int, simp only [measure_univ, ennreal.one_to_real, sub_self, zero_mul], }, { simp only [central_moment, pi.sub_apply, pow_one], have : ¬ integrable (λ x, X x - integral μ X) μ, { refine λ h_sub, h_int _, have h_add : X = (λ x, X x - integral μ X) + (λ x, integral μ X), { ext1 x, simp, }, rw h_add, exact h_sub.add (integrable_const _), }, rw integral_undef this, }, end @[simp] lemma central_moment_two_eq_variance : central_moment X 2 μ = variance X μ := rfl section moment_generating_function variables {t : ℝ} /-- Moment generating function of a real random variable `X`: `λ t, μ[exp(t*X)]`. -/ def mgf (X : Ω → ℝ) (μ : measure Ω) (t : ℝ) : ℝ := μ[λ ω, exp (t * X ω)] /-- Cumulant generating function of a real random variable `X`: `λ t, log μ[exp(t*X)]`. -/ def cgf (X : Ω → ℝ) (μ : measure Ω) (t : ℝ) : ℝ := log (mgf X μ t) @[simp] lemma mgf_zero_fun : mgf 0 μ t = (μ set.univ).to_real := by simp only [mgf, pi.zero_apply, mul_zero, exp_zero, integral_const, algebra.id.smul_eq_mul, mul_one] @[simp] lemma cgf_zero_fun : cgf 0 μ t = log (μ set.univ).to_real := by simp only [cgf, mgf_zero_fun] @[simp] lemma mgf_zero_measure : mgf X (0 : measure Ω) t = 0 := by simp only [mgf, integral_zero_measure] @[simp] lemma cgf_zero_measure : cgf X (0 : measure Ω) t = 0 := by simp only [cgf, log_zero, mgf_zero_measure] @[simp] lemma mgf_const' (c : ℝ) : mgf (λ _, c) μ t = (μ set.univ).to_real * exp (t * c) := by simp only [mgf, integral_const, algebra.id.smul_eq_mul] @[simp] lemma mgf_const (c : ℝ) [is_probability_measure μ] : mgf (λ _, c) μ t = exp (t * c) := by simp only [mgf_const', measure_univ, ennreal.one_to_real, one_mul] @[simp] lemma cgf_const' [is_finite_measure μ] (hμ : μ ≠ 0) (c : ℝ) : cgf (λ _, c) μ t = log (μ set.univ).to_real + t * c := begin simp only [cgf, mgf_const'], rw log_mul _ (exp_pos _).ne', { rw log_exp _, }, { rw [ne.def, ennreal.to_real_eq_zero_iff, measure.measure_univ_eq_zero], simp only [hμ, measure_ne_top μ set.univ, or_self, not_false_iff], }, end @[simp] lemma cgf_const [is_probability_measure μ] (c : ℝ) : cgf (λ _, c) μ t = t * c := by simp only [cgf, mgf_const, log_exp] @[simp] lemma mgf_zero' : mgf X μ 0 = (μ set.univ).to_real := by simp only [mgf, zero_mul, exp_zero, integral_const, algebra.id.smul_eq_mul, mul_one] @[simp] lemma mgf_zero [is_probability_measure μ] : mgf X μ 0 = 1 := by simp only [mgf_zero', measure_univ, ennreal.one_to_real] @[simp] lemma cgf_zero' : cgf X μ 0 = log (μ set.univ).to_real := by simp only [cgf, mgf_zero'] @[simp] lemma cgf_zero [is_probability_measure μ] : cgf X μ 0 = 0 := by simp only [cgf_zero', measure_univ, ennreal.one_to_real, log_one] lemma mgf_undef (hX : ¬ integrable (λ ω, exp (t * X ω)) μ) : mgf X μ t = 0 := by simp only [mgf, integral_undef hX] lemma cgf_undef (hX : ¬ integrable (λ ω, exp (t * X ω)) μ) : cgf X μ t = 0 := by simp only [cgf, mgf_undef hX, log_zero] lemma mgf_nonneg : 0 ≤ mgf X μ t := begin refine integral_nonneg _, intro ω, simp only [pi.zero_apply], exact (exp_pos _).le, end lemma mgf_pos' (hμ : μ ≠ 0) (h_int_X : integrable (λ ω, exp (t * X ω)) μ) : 0 < mgf X μ t := begin simp_rw mgf, have : ∫ (x : Ω), exp (t * X x) ∂μ = ∫ (x : Ω) in set.univ, exp (t * X x) ∂μ, { simp only [measure.restrict_univ], }, rw [this, set_integral_pos_iff_support_of_nonneg_ae _ _], { have h_eq_univ : function.support (λ (x : Ω), exp (t * X x)) = set.univ, { ext1 x, simp only [function.mem_support, set.mem_univ, iff_true], exact (exp_pos _).ne', }, rw [h_eq_univ, set.inter_univ _], refine ne.bot_lt _, simp only [hμ, ennreal.bot_eq_zero, ne.def, measure.measure_univ_eq_zero, not_false_iff], }, { refine eventually_of_forall (λ x, _), rw pi.zero_apply, exact (exp_pos _).le, }, { rwa integrable_on_univ, }, end lemma mgf_pos [is_probability_measure μ] (h_int_X : integrable (λ ω, exp (t * X ω)) μ) : 0 < mgf X μ t := mgf_pos' (is_probability_measure.ne_zero μ) h_int_X lemma mgf_neg : mgf (-X) μ t = mgf X μ (-t) := by simp_rw [mgf, pi.neg_apply, mul_neg, neg_mul] lemma cgf_neg : cgf (-X) μ t = cgf X μ (-t) := by simp_rw [cgf, mgf_neg] /-- This is a trivial application of `indep_fun.comp` but it will come up frequently. -/ lemma indep_fun.exp_mul {X Y : Ω → ℝ} (h_indep : indep_fun X Y μ) (s t : ℝ) : indep_fun (λ ω, exp (s * X ω)) (λ ω, exp (t * Y ω)) μ := begin have h_meas : ∀ t, measurable (λ x, exp (t * x)) := λ t, (measurable_id'.const_mul t).exp, change indep_fun ((λ x, exp (s * x)) ∘ X) ((λ x, exp (t * x)) ∘ Y) μ, exact indep_fun.comp h_indep (h_meas s) (h_meas t), end lemma indep_fun.mgf_add {X Y : Ω → ℝ} (h_indep : indep_fun X Y μ) (h_int_X : integrable (λ ω, exp (t * X ω)) μ) (h_int_Y : integrable (λ ω, exp (t * Y ω)) μ) : mgf (X + Y) μ t = mgf X μ t * mgf Y μ t := begin simp_rw [mgf, pi.add_apply, mul_add, exp_add], exact (h_indep.exp_mul t t).integral_mul_of_integrable' h_int_X h_int_Y, end lemma indep_fun.cgf_add {X Y : Ω → ℝ} (h_indep : indep_fun X Y μ) (h_int_X : integrable (λ ω, exp (t * X ω)) μ) (h_int_Y : integrable (λ ω, exp (t * Y ω)) μ) : cgf (X + Y) μ t = cgf X μ t + cgf Y μ t := begin by_cases hμ : μ = 0, { simp [hμ], }, simp only [cgf, h_indep.mgf_add h_int_X h_int_Y], exact log_mul (mgf_pos' hμ h_int_X).ne' (mgf_pos' hμ h_int_Y).ne', end lemma indep_fun.integrable_exp_mul_add {X Y : Ω → ℝ} (h_indep : indep_fun X Y μ) (h_int_X : integrable (λ ω, exp (t * X ω)) μ) (h_int_Y : integrable (λ ω, exp (t * Y ω)) μ) : integrable (λ ω, exp (t * (X + Y) ω)) μ := begin simp_rw [pi.add_apply, mul_add, exp_add], exact (h_indep.exp_mul t t).integrable_mul h_int_X h_int_Y, end lemma Indep_fun.integrable_exp_mul_sum [is_probability_measure μ] {X : ι → Ω → ℝ} (h_indep : Indep_fun (λ i, infer_instance) X μ) (h_meas : ∀ i, measurable (X i)) {s : finset ι} (h_int : ∀ i ∈ s, integrable (λ ω, exp (t * X i ω)) μ) : integrable (λ ω, exp (t * (∑ i in s, X i) ω)) μ := begin classical, induction s using finset.induction_on with i s hi_notin_s h_rec h_int, { simp only [pi.zero_apply, sum_apply, sum_empty, mul_zero, exp_zero], exact integrable_const _, }, { have : ∀ (i : ι), i ∈ s → integrable (λ (ω : Ω), exp (t * X i ω)) μ, from λ i hi, h_int i (mem_insert_of_mem hi), specialize h_rec this, rw sum_insert hi_notin_s, refine indep_fun.integrable_exp_mul_add _ (h_int i (mem_insert_self _ _)) h_rec, exact (h_indep.indep_fun_finset_sum_of_not_mem h_meas hi_notin_s).symm, }, end lemma Indep_fun.mgf_sum [is_probability_measure μ] {X : ι → Ω → ℝ} (h_indep : Indep_fun (λ i, infer_instance) X μ) (h_meas : ∀ i, measurable (X i)) {s : finset ι} (h_int : ∀ i ∈ s, integrable (λ ω, exp (t * X i ω)) μ) : mgf (∑ i in s, X i) μ t = ∏ i in s, mgf (X i) μ t := begin classical, induction s using finset.induction_on with i s hi_notin_s h_rec h_int, { simp only [sum_empty, mgf_zero_fun, measure_univ, ennreal.one_to_real, prod_empty], }, { have h_int' : ∀ (i : ι), i ∈ s → integrable (λ (ω : Ω), exp (t * X i ω)) μ, from λ i hi, h_int i (mem_insert_of_mem hi), rw [sum_insert hi_notin_s, indep_fun.mgf_add (h_indep.indep_fun_finset_sum_of_not_mem h_meas hi_notin_s).symm (h_int i (mem_insert_self _ _)) (h_indep.integrable_exp_mul_sum h_meas h_int'), h_rec h_int', prod_insert hi_notin_s], }, end lemma Indep_fun.cgf_sum [is_probability_measure μ] {X : ι → Ω → ℝ} (h_indep : Indep_fun (λ i, infer_instance) X μ) (h_meas : ∀ i, measurable (X i)) {s : finset ι} (h_int : ∀ i ∈ s, integrable (λ ω, exp (t * X i ω)) μ) : cgf (∑ i in s, X i) μ t = ∑ i in s, cgf (X i) μ t := begin simp_rw cgf, rw ← log_prod _ _ (λ j hj, _), { rw h_indep.mgf_sum h_meas h_int, }, { exact (mgf_pos (h_int j hj)).ne', }, end /-- **Chernoff bound** on the upper tail of a real random variable. -/ lemma measure_ge_le_exp_mul_mgf [is_finite_measure μ] (ε : ℝ) (ht : 0 ≤ t) (h_int : integrable (λ ω, exp (t * X ω)) μ) : (μ {ω | ε ≤ X ω}).to_real ≤ exp (- t * ε) * mgf X μ t := begin cases ht.eq_or_lt with ht_zero_eq ht_pos, { rw ht_zero_eq.symm, simp only [neg_zero', zero_mul, exp_zero, mgf_zero', one_mul], rw ennreal.to_real_le_to_real (measure_ne_top μ _) (measure_ne_top μ _), exact measure_mono (set.subset_univ _), }, calc (μ {ω | ε ≤ X ω}).to_real = (μ {ω | exp (t * ε) ≤ exp (t * X ω)}).to_real : begin congr' with ω, simp only [exp_le_exp, eq_iff_iff], exact ⟨λ h, mul_le_mul_of_nonneg_left h ht_pos.le, λ h, le_of_mul_le_mul_left h ht_pos⟩, end ... ≤ (exp (t * ε))⁻¹ * μ[λ ω, exp (t * X ω)] : begin have : exp (t * ε) * (μ {ω | exp (t * ε) ≤ exp (t * X ω)}).to_real ≤ μ[λ ω, exp (t * X ω)], from mul_meas_ge_le_integral_of_nonneg (λ x, (exp_pos _).le) h_int _, rwa [mul_comm (exp (t * ε))⁻¹, ← div_eq_mul_inv, le_div_iff' (exp_pos _)], end ... = exp (- t * ε) * mgf X μ t : by { rw [neg_mul, exp_neg], refl, }, end /-- **Chernoff bound** on the lower tail of a real random variable. -/ lemma measure_le_le_exp_mul_mgf [is_finite_measure μ] (ε : ℝ) (ht : t ≤ 0) (h_int : integrable (λ ω, exp (t * X ω)) μ) : (μ {ω | X ω ≤ ε}).to_real ≤ exp (- t * ε) * mgf X μ t := begin rw [← neg_neg t, ← mgf_neg, neg_neg, ← neg_mul_neg (-t)], refine eq.trans_le _ (measure_ge_le_exp_mul_mgf (-ε) (neg_nonneg.mpr ht) _), { congr' with ω, simp only [pi.neg_apply, neg_le_neg_iff], }, { simp_rw [pi.neg_apply, neg_mul_neg], exact h_int, }, end /-- **Chernoff bound** on the upper tail of a real random variable. -/ lemma measure_ge_le_exp_cgf [is_finite_measure μ] (ε : ℝ) (ht : 0 ≤ t) (h_int : integrable (λ ω, exp (t * X ω)) μ) : (μ {ω | ε ≤ X ω}).to_real ≤ exp (- t * ε + cgf X μ t) := begin refine (measure_ge_le_exp_mul_mgf ε ht h_int).trans _, rw exp_add, exact mul_le_mul le_rfl (le_exp_log _) mgf_nonneg (exp_pos _).le, end /-- **Chernoff bound** on the lower tail of a real random variable. -/ lemma measure_le_le_exp_cgf [is_finite_measure μ] (ε : ℝ) (ht : t ≤ 0) (h_int : integrable (λ ω, exp (t * X ω)) μ) : (μ {ω | X ω ≤ ε}).to_real ≤ exp (- t * ε + cgf X μ t) := begin refine (measure_le_le_exp_mul_mgf ε ht h_int).trans _, rw exp_add, exact mul_le_mul le_rfl (le_exp_log _) mgf_nonneg (exp_pos _).le, end end moment_generating_function end probability_theory
fbc5cbe9f3cb40028dd065f9b1196265497ec7aa
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/algebra/restrict_scalars.lean
5c3c9856ddb103f7def073568f2ccd9a63cb2e49
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
8,481
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Yury Kudryashov -/ import algebra.algebra.tower /-! # The `restrict_scalars` type alias See the documentation attached to the `restrict_scalars` definition for advice on how and when to use this type alias. As described there, it is often a better choice to use the `is_scalar_tower` typeclass instead. ## Main definitions * `restrict_scalars R S M`: the `S`-module `M` viewed as an `R` module when `S` is an `R`-algebra. Note that by default we do *not* have a `module S (restrict_scalars R S M)` instance for the original action. This is available as a def `restrict_scalars.module_orig` if really needed. * `restrict_scalars.add_equiv : restrict_scalars R S M ≃+ M`: the additive equivalence between the restricted and original space (in fact, they are definitionally equal, but sometimes it is helpful to avoid using this fact, to keep instances from leaking). * `restrict_scalars.ring_equiv : restrict_scalars R S A ≃+* A`: the ring equivalence between the restricted and original space when the module is an algebra. ## See also There are many similarly-named definitions elsewhere which do not refer to this type alias. These refer to restricting the scalar type in a bundled type, such as from `A →ₗ[R] B` to `A →ₗ[S] B`: * `linear_map.restrict_scalars` * `linear_equiv.restrict_scalars` * `alg_hom.restrict_scalars` * `alg_equiv.restrict_scalars` * `submodule.restrict_scalars` * `subalgebra.restrict_scalars` -/ variables (R S M A : Type*) /-- If we put an `R`-algebra structure on a semiring `S`, we get a natural equivalence from the category of `S`-modules to the category of representations of the algebra `S` (over `R`). The type synonym `restrict_scalars` is essentially this equivalence. Warning: use this type synonym judiciously! Consider an example where we want to construct an `R`-linear map from `M` to `S`, given: ```lean variables (R S M : Type*) variables [comm_semiring R] [semiring S] [algebra R S] [add_comm_monoid M] [module S M] ``` With the assumptions above we can't directly state our map as we have no `module R M` structure, but `restrict_scalars` permits it to be written as: ```lean -- an `R`-module structure on `M` is provided by `restrict_scalars` which is compatible example : restrict_scalars R S M →ₗ[R] S := sorry ``` However, it is usually better just to add this extra structure as an argument: ```lean -- an `R`-module structure on `M` and proof of its compatibility is provided by the user example [module R M] [is_scalar_tower R S M] : M →ₗ[R] S := sorry ``` The advantage of the second approach is that it defers the duty of providing the missing typeclasses `[module R M] [is_scalar_tower R S M]`. If some concrete `M` naturally carries these (as is often the case) then we have avoided `restrict_scalars` entirely. If not, we can pass `restrict_scalars R S M` later on instead of `M`. Note that this means we almost always want to state definitions and lemmas in the language of `is_scalar_tower` rather than `restrict_scalars`. An example of when one might want to use `restrict_scalars` would be if one has a vector space over a field of characteristic zero and wishes to make use of the `ℚ`-algebra structure. -/ @[nolint unused_arguments] def restrict_scalars (R S M : Type*) : Type* := M instance [I : inhabited M] : inhabited (restrict_scalars R S M) := I instance [I : add_comm_monoid M] : add_comm_monoid (restrict_scalars R S M) := I instance [I : add_comm_group M] : add_comm_group (restrict_scalars R S M) := I section module section variables [semiring S] [add_comm_monoid M] /-- We temporarily install an action of the original ring on `restrict_sclars R S M`. -/ def restrict_scalars.module_orig [I : module S M] : module S (restrict_scalars R S M) := I variables [comm_semiring R] [algebra R S] section local attribute [instance] restrict_scalars.module_orig /-- When `M` is a module over a ring `S`, and `S` is an algebra over `R`, then `M` inherits a module structure over `R`. The preferred way of setting this up is `[module R M] [module S M] [is_scalar_tower R S M]`. -/ instance [module S M] : module R (restrict_scalars R S M) := module.comp_hom M (algebra_map R S) /-- This instance is only relevant when `restrict_scalars.module_orig` is available as an instance. -/ instance [module S M] : is_scalar_tower R S (restrict_scalars R S M) := ⟨λ r S M, by { rw [algebra.smul_def, mul_smul], refl }⟩ end /-- When `M` is a right-module over a ring `S`, and `S` is an algebra over `R`, then `M` inherits a right-module structure over `R`. The preferred way of setting this up is `[module Rᵐᵒᵖ M] [module Sᵐᵒᵖ M] [is_scalar_tower Rᵐᵒᵖ Sᵐᵒᵖ M]`. -/ instance restrict_scalars.op_module [module Sᵐᵒᵖ M] : module Rᵐᵒᵖ (restrict_scalars R S M) := begin letI : module Sᵐᵒᵖ (restrict_scalars R S M) := ‹module Sᵐᵒᵖ M›, exact module.comp_hom M (algebra_map R S).op end instance restrict_scalars.is_central_scalar [module S M] [module Sᵐᵒᵖ M] [is_central_scalar S M] : is_central_scalar R (restrict_scalars R S M) := { op_smul_eq_smul := λ r x, (op_smul_eq_smul (algebra_map R S r) (_ : M) : _)} /-- The `R`-algebra homomorphism from the original coefficient algebra `S` to endomorphisms of `restrict_scalars R S M`. -/ def restrict_scalars.lsmul [module S M] : S →ₐ[R] module.End R (restrict_scalars R S M) := begin -- We use `restrict_scalars.module_orig` in the implementation, -- but not in the type. letI : module S (restrict_scalars R S M) := restrict_scalars.module_orig R S M, exact algebra.lsmul R (restrict_scalars R S M), end end variables [add_comm_monoid M] /-- `restrict_scalars.add_equiv` is the additive equivalence with the original module. -/ def restrict_scalars.add_equiv : restrict_scalars R S M ≃+ M := add_equiv.refl M variables [comm_semiring R] [semiring S] [algebra R S] [module S M] /-- Note that this lemma relies on the definitional equality `restrict_scalars R S M = M`, so usage may result in instance leakage. `restrict_scalars.add_equiv_map_smul` is the "hygienic" version. -/ lemma restrict_scalars_smul_def (c : R) (x : restrict_scalars R S M) : c • x = ((algebra_map R S c) • x : M) := rfl @[simp] lemma restrict_scalars.add_equiv_map_smul (c : R) (x : restrict_scalars R S M) : restrict_scalars.add_equiv R S M (c • x) = (algebra_map R S c) • restrict_scalars.add_equiv R S M x := rfl lemma restrict_scalars.add_equiv_symm_map_algebra_map_smul (r : R) (x : M) : (restrict_scalars.add_equiv R S M).symm (algebra_map R S r • x) = r • (restrict_scalars.add_equiv R S M).symm x := rfl lemma restrict_scalars.add_equiv_symm_map_smul_smul (r : R) (s : S) (x : M) : (restrict_scalars.add_equiv R S M).symm ((r • s) • x) = r • (restrict_scalars.add_equiv R S M ).symm (s • x) := by { rw [algebra.smul_def, mul_smul], refl, } lemma restrict_scalars.lsmul_apply_apply (s : S) (x : restrict_scalars R S M) : restrict_scalars.lsmul R S M s x = (restrict_scalars.add_equiv R S M).symm (s • (restrict_scalars.add_equiv R S M x)) := rfl end module section algebra instance [I : semiring A] : semiring (restrict_scalars R S A) := I instance [I : ring A] : ring (restrict_scalars R S A) := I instance [I : comm_semiring A] : comm_semiring (restrict_scalars R S A) := I instance [I : comm_ring A] : comm_ring (restrict_scalars R S A) := I variables [semiring A] /-- Tautological ring isomorphism `restrict_scalars R S A ≃+* A`. -/ def restrict_scalars.ring_equiv : restrict_scalars R S A ≃+* A := ring_equiv.refl _ variables [comm_semiring S] [algebra S A] [comm_semiring R] [algebra R S] @[simp] lemma restrict_scalars.ring_equiv_map_smul (r : R) (x : restrict_scalars R S A) : restrict_scalars.ring_equiv R S A (r • x) = (algebra_map R S r) • restrict_scalars.ring_equiv R S A x := rfl /-- `R ⟶ S` induces `S-Alg ⥤ R-Alg` -/ instance : algebra R (restrict_scalars R S A) := { smul := (•), commutes' := λ r x, algebra.commutes _ _, smul_def' := λ _ _, algebra.smul_def _ _, .. (algebra_map S A).comp (algebra_map R S) } @[simp] lemma restrict_scalars.ring_equiv_algebra_map (r : R) : restrict_scalars.ring_equiv R S A (algebra_map R (restrict_scalars R S A) r) = algebra_map S A (algebra_map R S r) := rfl end algebra
2f4b9cb2a708f275084d7a4d8808c1c0a57658dd
4727251e0cd73359b15b664c3170e5d754078599
/src/category_theory/limits/preserves/shapes/zero.lean
407b1444f4f9f8a38c7dca9fcd275e80c26fd216
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
5,045
lean
/- Copyright (c) 2022 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel -/ import category_theory.limits.preserves.shapes.terminal import category_theory.limits.shapes.zero_morphisms /-! # Preservation of zero objects and zero morphisms We define the class `preserves_zero_morphisms` and show basic properties. ## Main results We provide the following results: * Left adjoints and right adjoints preserve zero morphisms; * full functors preserve zero morphisms; * if both categories involved have a zero object, then a functor preserves zero morphisms if and only if it preserves the zero object; * functors which preserve initial or terminal objects preserve zero morphisms. -/ universes v₁ v₂ u₁ u₂ noncomputable theory open category_theory open category_theory.limits namespace category_theory.functor variables {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₂} D] section zero_morphisms variables [has_zero_morphisms C] [has_zero_morphisms D] /-- A functor preserves zero morphisms if it sends zero morphisms to zero morphisms. -/ class preserves_zero_morphisms (F : C ⥤ D) : Prop := (map_zero' : ∀ (X Y : C), F.map (0 : X ⟶ Y) = 0 . obviously) @[simp] protected lemma map_zero (F : C ⥤ D) [preserves_zero_morphisms F] (X Y : C) : F.map (0 : X ⟶ Y) = 0 := preserves_zero_morphisms.map_zero' _ _ lemma zero_of_map_zero (F : C ⥤ D) [preserves_zero_morphisms F] [faithful F] {X Y : C} (f : X ⟶ Y) (h : F.map f = 0) : f = 0 := F.map_injective $ h.trans $ eq.symm $ F.map_zero _ _ lemma map_eq_zero_iff (F : C ⥤ D) [preserves_zero_morphisms F] [faithful F] {X Y : C} {f : X ⟶ Y} : F.map f = 0 ↔ f = 0 := ⟨F.zero_of_map_zero _, by { rintro rfl, exact F.map_zero _ _ }⟩ @[priority 100] instance preserves_zero_morphisms_of_is_left_adjoint (F : C ⥤ D) [is_left_adjoint F] : preserves_zero_morphisms F := { map_zero' := λ X Y, let adj := adjunction.of_left_adjoint F in begin calc F.map (0 : X ⟶ Y) = F.map 0 ≫ F.map (adj.unit.app Y) ≫ adj.counit.app (F.obj Y) : _ ... = F.map 0 ≫ F.map ((right_adjoint F).map (0 : F.obj X ⟶ _)) ≫ adj.counit.app (F.obj Y) : _ ... = 0 : _, { rw adjunction.left_triangle_components, exact (category.comp_id _).symm }, { simp only [← category.assoc, ← F.map_comp, zero_comp] }, { simp only [adjunction.counit_naturality, comp_zero] } end } @[priority 100] instance preserves_zero_morphisms_of_is_right_adjoint (G : C ⥤ D) [is_right_adjoint G] : preserves_zero_morphisms G := { map_zero' := λ X Y, let adj := adjunction.of_right_adjoint G in begin calc G.map (0 : X ⟶ Y) = adj.unit.app (G.obj X) ≫ G.map (adj.counit.app X) ≫ G.map 0 : _ ... = adj.unit.app (G.obj X) ≫ G.map ((left_adjoint G).map (0 : _ ⟶ G.obj X)) ≫ G.map 0 : _ ... = 0 : _, { rw adjunction.right_triangle_components_assoc }, { simp only [← G.map_comp, comp_zero] }, { simp only [adjunction.unit_naturality_assoc, zero_comp] } end } @[priority 100] instance preserves_zero_morphisms_of_full (F : C ⥤ D) [full F] : preserves_zero_morphisms F := { map_zero' := λ X Y, calc F.map (0 : X ⟶ Y) = F.map (0 ≫ (F.preimage (0 : F.obj Y ⟶ F.obj Y))) : by rw zero_comp ... = 0 : by rw [F.map_comp, F.image_preimage, comp_zero] } end zero_morphisms section zero_object variables [has_zero_object C] [has_zero_object D] open_locale zero_object variables [has_zero_morphisms C] [has_zero_morphisms D] (F : C ⥤ D) /-- A functor that preserves zero morphisms also preserves the zero object. -/ @[simps] def map_zero_object [preserves_zero_morphisms F] : F.obj 0 ≅ 0 := { hom := 0, inv := 0, hom_inv_id' := by rw [← F.map_id, id_zero, F.map_zero, zero_comp], inv_hom_id' := by rw [id_zero, comp_zero] } variables {F} lemma preserves_zero_morphisms_of_map_zero_object (i : F.obj 0 ≅ 0) : preserves_zero_morphisms F := { map_zero' := λ X Y, calc F.map (0 : X ⟶ Y) = F.map (0 : X ⟶ 0) ≫ F.map 0 : by rw [← functor.map_comp, comp_zero] ... = F.map 0 ≫ (i.hom ≫ i.inv) ≫ F.map 0 : by rw [iso.hom_inv_id, category.id_comp] ... = 0 : by simp only [zero_of_to_zero i.hom, zero_comp, comp_zero] } @[priority 100] instance preserves_zero_morphisms_of_preserves_initial_object [preserves_colimit (functor.empty.{v₁} C) F] : preserves_zero_morphisms F := preserves_zero_morphisms_of_map_zero_object $ (F.map_iso has_zero_object.zero_iso_initial).trans $ (preserves_initial.iso F).trans has_zero_object.zero_iso_initial.symm @[priority 100] instance preserves_zero_morphisms_of_preserves_terminal_object [preserves_limit (functor.empty.{v₁} C) F] : preserves_zero_morphisms F := preserves_zero_morphisms_of_map_zero_object $ (F.map_iso has_zero_object.zero_iso_terminal).trans $ (preserves_terminal.iso F).trans has_zero_object.zero_iso_terminal.symm end zero_object end category_theory.functor
96e980de2e05148b26bdb017778a09df33b35748
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/category_theory/limits/shapes/constructions/equalizers.lean
92718a285c228c0703422a3eb694d1449e01d1fd
[ "Apache-2.0" ]
permissive
gebner/mathlib
eab0150cc4f79ec45d2016a8c21750244a2e7ff0
cc6a6edc397c55118df62831e23bfbd6e6c6b4ab
refs/heads/master
1,625,574,853,976
1,586,712,827,000
1,586,712,827,000
99,101,412
1
0
Apache-2.0
1,586,716,389,000
1,501,667,958,000
Lean
UTF-8
Lean
false
false
2,734
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import category_theory.limits.shapes.equalizers import category_theory.limits.shapes.binary_products import category_theory.limits.shapes.pullbacks /-! # Constructing equalizers from pullbacks and binary products. If a category has pullbacks and binary products, then it has equalizers. TODO: provide the dual result. -/ universes v u open category_theory category_theory.category namespace category_theory.limits variables {C : Type u} [𝒞 : category.{v} C] [has_binary_products.{v} C] [has_pullbacks.{v} C] include 𝒞 -- We hide the "implementation details" inside a namespace namespace has_equalizers_of_pullbacks_and_binary_products /-- Define the equalizing object -/ @[reducible] def construct_equalizer (F : walking_parallel_pair ⥤ C) : C := pullback (prod.lift (𝟙 _) (F.map walking_parallel_pair_hom.left)) (prod.lift (𝟙 _) (F.map walking_parallel_pair_hom.right)) /-- Define the equalizing morphism -/ abbreviation pullback_fst (F : walking_parallel_pair ⥤ C) : construct_equalizer F ⟶ F.obj walking_parallel_pair.zero := pullback.fst lemma pullback_fst_eq_pullback_snd (F : walking_parallel_pair ⥤ C) : pullback_fst F = pullback.snd := by convert pullback.condition =≫ limits.prod.fst; simp /-- Define the equalizing cone -/ @[reducible] def equalizer_cone (F : walking_parallel_pair ⥤ C) : cone F := cone.of_fork (fork.of_ι (pullback_fst F) (begin conv_rhs { rw pullback_fst_eq_pullback_snd, }, convert pullback.condition =≫ limits.prod.snd using 1; simp end)) /-- Show the equalizing cone is a limit -/ def equalizer_cone_is_limit (F : walking_parallel_pair ⥤ C) : is_limit (equalizer_cone F) := { lift := begin intro c, apply pullback.lift (c.π.app _) (c.π.app _), apply limit.hom_ext, rintro (_ | _); simp end, fac' := by rintros c (_ | _); simp, uniq' := begin intros c _ J, have J0 := J walking_parallel_pair.zero, simp at J0, apply pullback.hom_ext, { rwa limit.lift_π }, { erw [limit.lift_π, ← J0, pullback_fst_eq_pullback_snd] } end } end has_equalizers_of_pullbacks_and_binary_products open has_equalizers_of_pullbacks_and_binary_products /-- Any category with pullbacks and binary products, has equalizers. -/ -- This is not an instance, as it is not always how one wants to construct equalizers! def has_equalizers_of_pullbacks_and_binary_products : has_equalizers.{v} C := { has_limits_of_shape := { has_limit := λ F, { cone := equalizer_cone F, is_limit := equalizer_cone_is_limit F } } } end category_theory.limits
19599ed273ffe6ae281f389464945200019d2c94
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/model_theory/syntax.lean
288d455200966bac5d01c3a3f907ae7e31160c54
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
39,690
lean
/- 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 data.list.prod_sigma import data.set.prod import logic.equiv.fin import model_theory.language_map /-! # Basics on First-Order Syntax > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines first-order terms, formulas, sentences, and theories in a style inspired by the [Flypitch project](https://flypitch.github.io/). ## Main Definitions * A `first_order.language.term` is defined so that `L.term α` is the type of `L`-terms with free variables indexed by `α`. * A `first_order.language.formula` is defined so that `L.formula α` is the type of `L`-formulas with free variables indexed by `α`. * A `first_order.language.sentence` is a formula with no free variables. * A `first_order.language.Theory` is a set of sentences. * The variables of terms and formulas can be relabelled with `first_order.language.term.relabel`, `first_order.language.bounded_formula.relabel`, and `first_order.language.formula.relabel`. * Given an operation on terms and an operation on relations, `first_order.language.bounded_formula.map_term_rel` gives an operation on formulas. * `first_order.language.bounded_formula.cast_le` adds more `fin`-indexed variables. * `first_order.language.bounded_formula.lift_at` raises the indexes of the `fin`-indexed variables above a particular index. * `first_order.language.term.subst` and `first_order.language.bounded_formula.subst` substitute variables with given terms. * Language maps can act on syntactic objects with functions such as `first_order.language.Lhom.on_formula`. * `first_order.language.term.constants_vars_equiv` and `first_order.language.bounded_formula.constants_vars_equiv` switch terms and formulas between having constants in the language and having extra variables indexed by the same type. ## Implementation Notes * Formulas use a modified version of de Bruijn variables. Specifically, a `L.bounded_formula α 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.bounded_formula α (n + 1)`, we define the formula `∀' φ : L.bounded_formula α 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] -/ universes u v w u' v' namespace first_order namespace language variables (L : language.{u v}) {L' : language} variables {M : Type w} {N P : Type*} [L.Structure M] [L.Structure N] [L.Structure P] variables {α : Type u'} {β : Type v'} {γ : Type*} open_locale first_order open Structure fin /-- A term on `α` is either a variable indexed by an element of `α` or a function symbol applied to simpler terms. -/ inductive term (α : Type u') : Type (max u u') | var {} : ∀ (a : α), term | func {} : ∀ {l : ℕ} (f : L.functions l) (ts : fin l → term), term export term variable {L} namespace term open finset /-- The `finset` of variables used in a given term. -/ @[simp] def var_finset [decidable_eq α] : L.term α → finset α | (var i) := {i} | (func f ts) := univ.bUnion (λ i, (ts i).var_finset) /-- The `finset` of variables from the left side of a sum used in a given term. -/ @[simp] def var_finset_left [decidable_eq α] : L.term (α ⊕ β) → finset α | (var (sum.inl i)) := {i} | (var (sum.inr i)) := ∅ | (func f ts) := univ.bUnion (λ i, (ts i).var_finset_left) /-- Relabels a term's variables along a particular function. -/ @[simp] def relabel (g : α → β) : L.term α → L.term β | (var i) := var (g i) | (func f ts) := func f (λ i, (ts i).relabel) lemma relabel_id (t : L.term α) : t.relabel id = t := begin induction t with _ _ _ _ ih, { refl, }, { simp [ih] }, end @[simp] lemma relabel_id_eq_id : (term.relabel id : L.term α → L.term α) = id := funext relabel_id @[simp] lemma relabel_relabel (f : α → β) (g : β → γ) (t : L.term α) : (t.relabel f).relabel g = t.relabel (g ∘ f) := begin induction t with _ _ _ _ ih, { refl, }, { simp [ih] }, end @[simp] lemma relabel_comp_relabel (f : α → β) (g : β → γ) : (term.relabel g ∘ term.relabel f : L.term α → L.term γ) = term.relabel (g ∘ f) := funext (relabel_relabel f g) /-- Relabels a term's variables along a bijection. -/ @[simps] def relabel_equiv (g : α ≃ β) : L.term α ≃ L.term β := ⟨relabel g, relabel g.symm, λ t, by simp, λ t, by simp⟩ /-- Restricts a term to use only a set of the given variables. -/ def restrict_var [decidable_eq α] : Π (t : L.term α) (f : t.var_finset → β), L.term β | (var a) f := var (f ⟨a, mem_singleton_self a⟩) | (func F ts) f := func F (λ i, (ts i).restrict_var (f ∘ set.inclusion (subset_bUnion_of_mem _ (mem_univ i)))) /-- Restricts a term to use only a set of the given variables on the left side of a sum. -/ def restrict_var_left [decidable_eq α] {γ : Type*} : Π (t : L.term (α ⊕ γ)) (f : t.var_finset_left → β), L.term (β ⊕ γ) | (var (sum.inl a)) f := var (sum.inl (f ⟨a, mem_singleton_self a⟩)) | (var (sum.inr a)) f := var (sum.inr a) | (func F ts) f := func F (λ i, (ts i).restrict_var_left (f ∘ set.inclusion (subset_bUnion_of_mem _ (mem_univ i)))) end term /-- The representation of a constant symbol as a term. -/ def constants.term (c : L.constants) : (L.term α) := func c default /-- Applies a unary function to a term. -/ def functions.apply₁ (f : L.functions 1) (t : L.term α) : L.term α := func f ![t] /-- Applies a binary function to two terms. -/ def functions.apply₂ (f : L.functions 2) (t₁ t₂ : L.term α) : L.term α := func f ![t₁, t₂] namespace term /-- Sends a term with constants to a term with extra variables. -/ @[simp] def constants_to_vars : L[[γ]].term α → L.term (γ ⊕ α) | (var a) := var (sum.inr a) | (@func _ _ 0 f ts) := sum.cases_on f (λ f, func f (λ i, (ts i).constants_to_vars)) (λ c, var (sum.inl c)) | (@func _ _ (n + 1) f ts) := sum.cases_on f (λ f, func f (λ i, (ts i).constants_to_vars)) (λ c, is_empty_elim c) /-- Sends a term with extra variables to a term with constants. -/ @[simp] def vars_to_constants : L.term (γ ⊕ α) → L[[γ]].term α | (var (sum.inr a)) := var a | (var (sum.inl c)) := constants.term (sum.inr c) | (func f ts) := func (sum.inl f) (λ i, (ts i).vars_to_constants) /-- A bijection between terms with constants and terms with extra variables. -/ @[simps] def constants_vars_equiv : L[[γ]].term α ≃ L.term (γ ⊕ α) := ⟨constants_to_vars, vars_to_constants, begin intro t, induction t with _ n f _ ih, { refl }, { cases n, { cases f, { simp [constants_to_vars, vars_to_constants, ih] }, { simp [constants_to_vars, vars_to_constants, constants.term] } }, { cases f, { simp [constants_to_vars, vars_to_constants, ih] }, { exact is_empty_elim f } } } end, begin intro t, induction t with x n f _ ih, { cases x; refl }, { cases n; { simp [vars_to_constants, constants_to_vars, ih] } } end⟩ /-- A bijection between terms with constants and terms with extra variables. -/ def constants_vars_equiv_left : L[[γ]].term (α ⊕ β) ≃ L.term ((γ ⊕ α) ⊕ β) := constants_vars_equiv.trans (relabel_equiv (equiv.sum_assoc _ _ _)).symm @[simp] lemma constants_vars_equiv_left_apply (t : L[[γ]].term (α ⊕ β)) : constants_vars_equiv_left t = (constants_to_vars t).relabel (equiv.sum_assoc _ _ _).symm := rfl @[simp] lemma constants_vars_equiv_left_symm_apply (t : L.term ((γ ⊕ α) ⊕ β)) : constants_vars_equiv_left.symm t = vars_to_constants (t.relabel (equiv.sum_assoc _ _ _)) := rfl instance inhabited_of_var [inhabited α] : inhabited (L.term α) := ⟨var default⟩ instance inhabited_of_constant [inhabited L.constants] : inhabited (L.term α) := ⟨(default : L.constants).term⟩ /-- Raises all of the `fin`-indexed variables of a term greater than or equal to `m` by `n'`. -/ def lift_at {n : ℕ} (n' m : ℕ) : L.term (α ⊕ fin n) → L.term (α ⊕ fin (n + n')) := relabel (sum.map id (λ i, if ↑i < m then fin.cast_add n' i else fin.add_nat n' i)) /-- Substitutes the variables in a given term with terms. -/ @[simp] def subst : L.term α → (α → L.term β) → L.term β | (var a) tf := tf a | (func f ts) tf := (func f (λ i, (ts i).subst tf)) end term localized "prefix (name := language.term.var) `&`:max := first_order.language.term.var ∘ sum.inr" in first_order namespace Lhom /-- Maps a term's symbols along a language map. -/ @[simp] def on_term (φ : L →ᴸ L') : L.term α → L'.term α | (var i) := var i | (func f ts) := func (φ.on_function f) (λ i, on_term (ts i)) @[simp] lemma id_on_term : ((Lhom.id L).on_term : L.term α → L.term α) = id := begin ext t, induction t with _ _ _ _ ih, { refl }, { simp_rw [on_term, ih], refl, }, end @[simp] lemma comp_on_term {L'' : language} (φ : L' →ᴸ L'') (ψ : L →ᴸ L') : ((φ.comp ψ).on_term : L.term α → L''.term α) = φ.on_term ∘ ψ.on_term := begin ext t, induction t with _ _ _ _ ih, { refl }, { simp_rw [on_term, ih], refl, }, end end Lhom /-- Maps a term's symbols along a language equivalence. -/ @[simps] def Lequiv.on_term (φ : L ≃ᴸ L') : L.term α ≃ L'.term α := { to_fun := φ.to_Lhom.on_term, inv_fun := φ.inv_Lhom.on_term, left_inv := by rw [function.left_inverse_iff_comp, ← Lhom.comp_on_term, φ.left_inv, Lhom.id_on_term], right_inv := by rw [function.right_inverse_iff_comp, ← Lhom.comp_on_term, φ.right_inv, Lhom.id_on_term] } variables (L) (α) /-- `bounded_formula α n` is the type of formulas with free variables indexed by `α` and up to `n` additional free variables. -/ inductive bounded_formula : ℕ → Type (max u v u') | falsum {} {n} : bounded_formula n | equal {n} (t₁ t₂ : L.term (α ⊕ fin n)) : bounded_formula n | rel {n l : ℕ} (R : L.relations l) (ts : fin l → L.term (α ⊕ fin n)) : bounded_formula n | imp {n} (f₁ f₂ : bounded_formula n) : bounded_formula n | all {n} (f : bounded_formula (n+1)) : bounded_formula n /-- `formula α` is the type of formulas with all free variables indexed by `α`. -/ @[reducible] def formula := L.bounded_formula α 0 /-- A sentence is a formula with no free variables. -/ @[reducible] def sentence := L.formula empty /-- A theory is a set of sentences. -/ @[reducible] def Theory := set L.sentence variables {L} {α} {n : ℕ} /-- Applies a relation to terms as a bounded formula. -/ def relations.bounded_formula {l : ℕ} (R : L.relations n) (ts : fin n → L.term (α ⊕ fin l)) : L.bounded_formula α l := bounded_formula.rel R ts /-- Applies a unary relation to a term as a bounded formula. -/ def relations.bounded_formula₁ (r : L.relations 1) (t : L.term (α ⊕ fin n)) : L.bounded_formula α n := r.bounded_formula ![t] /-- Applies a binary relation to two terms as a bounded formula. -/ def relations.bounded_formula₂ (r : L.relations 2) (t₁ t₂ : L.term (α ⊕ fin n)) : L.bounded_formula α n := r.bounded_formula ![t₁, t₂] /-- The equality of two terms as a bounded formula. -/ def term.bd_equal (t₁ t₂ : L.term (α ⊕ fin n)) : (L.bounded_formula α n) := bounded_formula.equal t₁ t₂ /-- Applies a relation to terms as a bounded formula. -/ def relations.formula (R : L.relations n) (ts : fin n → L.term α) : L.formula α := R.bounded_formula (λ i, (ts i).relabel sum.inl) /-- Applies a unary relation to a term as a formula. -/ def relations.formula₁ (r : L.relations 1) (t : L.term α) : L.formula α := r.formula ![t] /-- Applies a binary relation to two terms as a formula. -/ def relations.formula₂ (r : L.relations 2) (t₁ t₂ : L.term α) : L.formula α := r.formula ![t₁, t₂] /-- The equality of two terms as a first-order formula. -/ def term.equal (t₁ t₂ : L.term α) : (L.formula α) := (t₁.relabel sum.inl).bd_equal (t₂.relabel sum.inl) namespace bounded_formula instance : inhabited (L.bounded_formula α n) := ⟨falsum⟩ instance : has_bot (L.bounded_formula α n) := ⟨falsum⟩ /-- The negation of a bounded formula is also a bounded formula. -/ @[pattern] protected def not (φ : L.bounded_formula α n) : L.bounded_formula α n := φ.imp ⊥ /-- Puts an `∃` quantifier on a bounded formula. -/ @[pattern] protected def ex (φ : L.bounded_formula α (n + 1)) : L.bounded_formula α n := φ.not.all.not instance : has_top (L.bounded_formula α n) := ⟨bounded_formula.not ⊥⟩ instance : has_inf (L.bounded_formula α n) := ⟨λ f g, (f.imp g.not).not⟩ instance : has_sup (L.bounded_formula α n) := ⟨λ f g, f.not.imp g⟩ /-- The biimplication between two bounded formulas. -/ protected def iff (φ ψ : L.bounded_formula α n) := φ.imp ψ ⊓ ψ.imp φ open finset /-- The `finset` of variables used in a given formula. -/ @[simp] def free_var_finset [decidable_eq α] : ∀ {n}, L.bounded_formula α n → finset α | n falsum := ∅ | n (equal t₁ t₂) := t₁.var_finset_left ∪ t₂.var_finset_left | n (rel R ts) := univ.bUnion (λ i, (ts i).var_finset_left) | n (imp f₁ f₂) := f₁.free_var_finset ∪ f₂.free_var_finset | n (all f) := f.free_var_finset /-- Casts `L.bounded_formula α m` as `L.bounded_formula α n`, where `m ≤ n`. -/ @[simp] def cast_le : ∀ {m n : ℕ} (h : m ≤ n), L.bounded_formula α m → L.bounded_formula α n | m n h falsum := falsum | m n h (equal t₁ t₂) := equal (t₁.relabel (sum.map id (fin.cast_le h))) (t₂.relabel (sum.map id (fin.cast_le h))) | m n h (rel R ts) := rel R (term.relabel (sum.map id (fin.cast_le h)) ∘ ts) | m n h (imp f₁ f₂) := (f₁.cast_le h).imp (f₂.cast_le h) | m n h (all f) := (f.cast_le (add_le_add_right h 1)).all @[simp] lemma cast_le_rfl {n} (h : n ≤ n) (φ : L.bounded_formula α n) : φ.cast_le h = φ := begin induction φ with _ _ _ _ _ _ _ _ _ _ _ ih1 ih2 _ _ ih3, { refl }, { simp [fin.cast_le_of_eq], }, { simp [fin.cast_le_of_eq], }, { simp [fin.cast_le_of_eq, ih1, ih2], }, { simp [fin.cast_le_of_eq, ih3], }, end @[simp] lemma cast_le_cast_le {k m n} (km : k ≤ m) (mn : m ≤ n) (φ : L.bounded_formula α k) : (φ.cast_le km).cast_le mn = φ.cast_le (km.trans mn) := begin revert m n, induction φ with _ _ _ _ _ _ _ _ _ _ _ ih1 ih2 _ _ ih3; intros m n km mn, { refl }, { simp }, { simp only [cast_le, eq_self_iff_true, heq_iff_eq, true_and], rw [← function.comp.assoc, relabel_comp_relabel], simp }, { simp [ih1, ih2] }, { simp only [cast_le, ih3] } end @[simp] lemma cast_le_comp_cast_le {k m n} (km : k ≤ m) (mn : m ≤ n) : (bounded_formula.cast_le mn ∘ bounded_formula.cast_le km : L.bounded_formula α k → L.bounded_formula α n) = bounded_formula.cast_le (km.trans mn) := funext (cast_le_cast_le km mn) /-- Restricts a bounded formula to only use a particular set of free variables. -/ def restrict_free_var [decidable_eq α] : Π {n : ℕ} (φ : L.bounded_formula α n) (f : φ.free_var_finset → β), L.bounded_formula β n | n falsum f := falsum | n (equal t₁ t₂) f := equal (t₁.restrict_var_left (f ∘ set.inclusion (subset_union_left _ _))) (t₂.restrict_var_left (f ∘ set.inclusion (subset_union_right _ _))) | n (rel R ts) f := rel R (λ i, (ts i).restrict_var_left (f ∘ set.inclusion (subset_bUnion_of_mem _ (mem_univ i)))) | n (imp φ₁ φ₂) f := (φ₁.restrict_free_var (f ∘ set.inclusion (subset_union_left _ _))).imp (φ₂.restrict_free_var (f ∘ set.inclusion (subset_union_right _ _))) | n (all φ) f := (φ.restrict_free_var f).all /-- Places universal quantifiers on all extra variables of a bounded formula. -/ def alls : ∀ {n}, L.bounded_formula α n → L.formula α | 0 φ := φ | (n + 1) φ := φ.all.alls /-- Places existential quantifiers on all extra variables of a bounded formula. -/ def exs : ∀ {n}, L.bounded_formula α n → L.formula α | 0 φ := φ | (n + 1) φ := φ.ex.exs /-- Maps bounded formulas along a map of terms and a map of relations. -/ def map_term_rel {g : ℕ → ℕ} (ft : ∀ n, L.term (α ⊕ fin n) → L'.term (β ⊕ fin (g n))) (fr : ∀ n, L.relations n → L'.relations n) (h : ∀ n, L'.bounded_formula β (g (n + 1)) → L'.bounded_formula β (g n + 1)) : ∀ {n}, L.bounded_formula α n → L'.bounded_formula β (g n) | n falsum := falsum | n (equal t₁ t₂) := equal (ft _ t₁) (ft _ t₂) | n (rel R ts) := rel (fr _ R) (λ i, ft _ (ts i)) | n (imp φ₁ φ₂) := φ₁.map_term_rel.imp φ₂.map_term_rel | n (all φ) := (h n φ.map_term_rel).all /-- Raises all of the `fin`-indexed variables of a formula greater than or equal to `m` by `n'`. -/ def lift_at : ∀ {n : ℕ} (n' m : ℕ), L.bounded_formula α n → L.bounded_formula α (n + n') := λ n n' m φ, φ.map_term_rel (λ k t, t.lift_at n' m) (λ _, id) (λ _, cast_le (by rw [add_assoc, add_comm 1, add_assoc])) @[simp] lemma map_term_rel_map_term_rel {L'' : language} (ft : ∀ n, L.term (α ⊕ fin n) → L'.term (β ⊕ fin n)) (fr : ∀ n, L.relations n → L'.relations n) (ft' : ∀ n, L'.term (β ⊕ fin n) → L''.term (γ ⊕ fin n)) (fr' : ∀ n, L'.relations n → L''.relations n) {n} (φ : L.bounded_formula α n) : (φ.map_term_rel ft fr (λ _, id)).map_term_rel ft' fr' (λ _, id) = φ.map_term_rel (λ _, (ft' _) ∘ (ft _)) (λ _, (fr' _) ∘ (fr _)) (λ _, id) := begin induction φ with _ _ _ _ _ _ _ _ _ _ _ ih1 ih2 _ _ ih3, { refl }, { simp [map_term_rel] }, { simp [map_term_rel] }, { simp [map_term_rel, ih1, ih2] }, { simp [map_term_rel, ih3], } end @[simp] lemma map_term_rel_id_id_id {n} (φ : L.bounded_formula α n) : φ.map_term_rel (λ _, id) (λ _, id) (λ _, id) = φ := begin induction φ with _ _ _ _ _ _ _ _ _ _ _ ih1 ih2 _ _ ih3, { refl }, { simp [map_term_rel] }, { simp [map_term_rel] }, { simp [map_term_rel, ih1, ih2] }, { simp [map_term_rel, ih3], } end /-- An equivalence of bounded formulas given by an equivalence of terms and an equivalence of relations. -/ @[simps] def map_term_rel_equiv (ft : ∀ n, L.term (α ⊕ fin n) ≃ L'.term (β ⊕ fin n)) (fr : ∀ n, L.relations n ≃ L'.relations n) {n} : L.bounded_formula α n ≃ L'.bounded_formula β n := ⟨map_term_rel (λ n, ft n) (λ n, fr n) (λ _, id), map_term_rel (λ n, (ft n).symm) (λ n, (fr n).symm) (λ _, id), λ φ, by simp, λ φ, by simp⟩ /-- A function to help relabel the variables in bounded formulas. -/ def relabel_aux (g : α → β ⊕ fin n) (k : ℕ) : α ⊕ fin k → β ⊕ fin (n + k) := sum.map id fin_sum_fin_equiv ∘ equiv.sum_assoc _ _ _ ∘ sum.map g id @[simp] lemma sum_elim_comp_relabel_aux {m : ℕ} {g : α → (β ⊕ fin n)} {v : β → M} {xs : fin (n + m) → M} : sum.elim v xs ∘ relabel_aux g m = sum.elim (sum.elim v (xs ∘ cast_add m) ∘ g) (xs ∘ nat_add n) := begin ext x, cases x, { simp only [bounded_formula.relabel_aux, function.comp_app, sum.map_inl, sum.elim_inl], cases g x with l r; simp }, { simp [bounded_formula.relabel_aux] } end @[simp] lemma relabel_aux_sum_inl (k : ℕ) : relabel_aux (sum.inl : α → α ⊕ fin n) k = sum.map id (nat_add n) := begin ext x, cases x; { simp [relabel_aux] }, end /-- Relabels a bounded formula's variables along a particular function. -/ def relabel (g : α → (β ⊕ fin n)) {k} (φ : L.bounded_formula α k) : L.bounded_formula β (n + k) := φ.map_term_rel (λ _ t, t.relabel (relabel_aux g _)) (λ _, id) (λ _, cast_le (ge_of_eq (add_assoc _ _ _))) /-- Relabels a bounded formula's free variables along a bijection. -/ def relabel_equiv (g : α ≃ β) {k} : L.bounded_formula α k ≃ L.bounded_formula β k := map_term_rel_equiv (λ n, term.relabel_equiv (g.sum_congr (_root_.equiv.refl _))) (λ n, _root_.equiv.refl _) @[simp] lemma relabel_falsum (g : α → (β ⊕ fin n)) {k} : (falsum : L.bounded_formula α k).relabel g = falsum := rfl @[simp] lemma relabel_bot (g : α → (β ⊕ fin n)) {k} : (⊥ : L.bounded_formula α k).relabel g = ⊥ := rfl @[simp] lemma relabel_imp (g : α → (β ⊕ fin n)) {k} (φ ψ : L.bounded_formula α k) : (φ.imp ψ).relabel g = (φ.relabel g).imp (ψ.relabel g) := rfl @[simp] lemma relabel_not (g : α → (β ⊕ fin n)) {k} (φ : L.bounded_formula α k) : φ.not.relabel g = (φ.relabel g).not := by simp [bounded_formula.not] @[simp] lemma relabel_all (g : α → (β ⊕ fin n)) {k} (φ : L.bounded_formula α (k + 1)) : φ.all.relabel g = (φ.relabel g).all := begin rw [relabel, map_term_rel, relabel], simp, end @[simp] lemma relabel_ex (g : α → (β ⊕ fin n)) {k} (φ : L.bounded_formula α (k + 1)) : φ.ex.relabel g = (φ.relabel g).ex := by simp [bounded_formula.ex] @[simp] lemma relabel_sum_inl (φ : L.bounded_formula α n) : (φ.relabel sum.inl : L.bounded_formula α (0 + n)) = φ.cast_le (ge_of_eq (zero_add n)) := begin simp only [relabel, relabel_aux_sum_inl], induction φ with _ _ _ _ _ _ _ _ _ _ _ ih1 ih2 _ _ ih3, { refl }, { simp [fin.nat_add_zero, cast_le_of_eq, map_term_rel] }, { simp [fin.nat_add_zero, cast_le_of_eq, map_term_rel] }, { simp [map_term_rel, ih1, ih2], }, { simp [map_term_rel, ih3, cast_le], }, end /-- Substitutes the variables in a given formula with terms. -/ @[simp] def subst {n : ℕ} (φ : L.bounded_formula α n) (f : α → L.term β) : L.bounded_formula β n := φ.map_term_rel (λ _ t, t.subst (sum.elim (term.relabel sum.inl ∘ f) (var ∘ sum.inr))) (λ _, id) (λ _, id) /-- A bijection sending formulas with constants to formulas with extra variables. -/ def constants_vars_equiv : L[[γ]].bounded_formula α n ≃ L.bounded_formula (γ ⊕ α) n := map_term_rel_equiv (λ _, term.constants_vars_equiv_left) (λ _, equiv.sum_empty _ _) /-- Turns the extra variables of a bounded formula into free variables. -/ @[simp] def to_formula : ∀ {n : ℕ}, L.bounded_formula α n → L.formula (α ⊕ fin n) | n falsum := falsum | n (equal t₁ t₂) := t₁.equal t₂ | n (rel R ts) := R.formula ts | n (imp φ₁ φ₂) := φ₁.to_formula.imp φ₂.to_formula | n (all φ) := (φ.to_formula.relabel (sum.elim (sum.inl ∘ sum.inl) (sum.map sum.inr id ∘ fin_sum_fin_equiv.symm))).all variables {l : ℕ} {φ ψ : L.bounded_formula α l} {θ : L.bounded_formula α l.succ} variables {v : α → M} {xs : fin l → M} /-- An atomic formula is either equality or a relation symbol applied to terms. Note that `⊥` and `⊤` are not considered atomic in this convention. -/ inductive is_atomic : L.bounded_formula α n → Prop | equal (t₁ t₂ : L.term (α ⊕ fin n)) : is_atomic (bd_equal t₁ t₂) | rel {l : ℕ} (R : L.relations l) (ts : fin l → L.term (α ⊕ fin n)) : is_atomic (R.bounded_formula ts) lemma not_all_is_atomic (φ : L.bounded_formula α (n + 1)) : ¬ φ.all.is_atomic := λ con, by cases con lemma not_ex_is_atomic (φ : L.bounded_formula α (n + 1)) : ¬ φ.ex.is_atomic := λ con, by cases con lemma is_atomic.relabel {m : ℕ} {φ : L.bounded_formula α m} (h : φ.is_atomic) (f : α → β ⊕ (fin n)) : (φ.relabel f).is_atomic := is_atomic.rec_on h (λ _ _, is_atomic.equal _ _) (λ _ _ _, is_atomic.rel _ _) lemma is_atomic.lift_at {k m : ℕ} (h : is_atomic φ) : (φ.lift_at k m).is_atomic := is_atomic.rec_on h (λ _ _, is_atomic.equal _ _) (λ _ _ _, is_atomic.rel _ _) lemma is_atomic.cast_le {h : l ≤ n} (hφ : is_atomic φ) : (φ.cast_le h).is_atomic := is_atomic.rec_on hφ (λ _ _, is_atomic.equal _ _) (λ _ _ _, is_atomic.rel _ _) /-- A quantifier-free formula is a formula defined without quantifiers. These are all equivalent to boolean combinations of atomic formulas. -/ inductive is_qf : L.bounded_formula α n → Prop | falsum : is_qf falsum | of_is_atomic {φ} (h : is_atomic φ) : is_qf φ | imp {φ₁ φ₂} (h₁ : is_qf φ₁) (h₂ : is_qf φ₂) : is_qf (φ₁.imp φ₂) lemma is_atomic.is_qf {φ : L.bounded_formula α n} : is_atomic φ → is_qf φ := is_qf.of_is_atomic lemma is_qf_bot : is_qf (⊥ : L.bounded_formula α n) := is_qf.falsum lemma is_qf.not {φ : L.bounded_formula α n} (h : is_qf φ) : is_qf φ.not := h.imp is_qf_bot lemma is_qf.relabel {m : ℕ} {φ : L.bounded_formula α m} (h : φ.is_qf) (f : α → β ⊕ (fin n)) : (φ.relabel f).is_qf := is_qf.rec_on h is_qf_bot (λ _ h, (h.relabel f).is_qf) (λ _ _ _ _ h1 h2, h1.imp h2) lemma is_qf.lift_at {k m : ℕ} (h : is_qf φ) : (φ.lift_at k m).is_qf := is_qf.rec_on h is_qf_bot (λ _ ih, ih.lift_at.is_qf) (λ _ _ _ _ ih1 ih2, ih1.imp ih2) lemma is_qf.cast_le {h : l ≤ n} (hφ : is_qf φ) : (φ.cast_le h).is_qf := is_qf.rec_on hφ is_qf_bot (λ _ ih, ih.cast_le.is_qf) (λ _ _ _ _ ih1 ih2, ih1.imp ih2) lemma not_all_is_qf (φ : L.bounded_formula α (n + 1)) : ¬ φ.all.is_qf := λ con, begin cases con with _ con, exact (φ.not_all_is_atomic con), end lemma not_ex_is_qf (φ : L.bounded_formula α (n + 1)) : ¬ φ.ex.is_qf := λ con, begin cases con with _ con _ _ con, { exact (φ.not_ex_is_atomic con) }, { exact not_all_is_qf _ con } end /-- Indicates that a bounded formula is in prenex normal form - that is, it consists of quantifiers applied to a quantifier-free formula. -/ inductive is_prenex : ∀ {n}, L.bounded_formula α n → Prop | of_is_qf {n} {φ : L.bounded_formula α n} (h : is_qf φ) : is_prenex φ | all {n} {φ : L.bounded_formula α (n + 1)} (h : is_prenex φ) : is_prenex φ.all | ex {n} {φ : L.bounded_formula α (n + 1)} (h : is_prenex φ) : is_prenex φ.ex lemma is_qf.is_prenex {φ : L.bounded_formula α n} : is_qf φ → is_prenex φ := is_prenex.of_is_qf lemma is_atomic.is_prenex {φ : L.bounded_formula α n} (h : is_atomic φ) : is_prenex φ := h.is_qf.is_prenex lemma is_prenex.induction_on_all_not {P : ∀ {n}, L.bounded_formula α n → Prop} {φ : L.bounded_formula α n} (h : is_prenex φ) (hq : ∀ {m} {ψ : L.bounded_formula α m}, ψ.is_qf → P ψ) (ha : ∀ {m} {ψ : L.bounded_formula α (m + 1)}, P ψ → P ψ.all) (hn : ∀ {m} {ψ : L.bounded_formula α m}, P ψ → P ψ.not) : P φ := is_prenex.rec_on h (λ _ _, hq) (λ _ _ _, ha) (λ _ _ _ ih, hn (ha (hn ih))) lemma is_prenex.relabel {m : ℕ} {φ : L.bounded_formula α m} (h : φ.is_prenex) (f : α → β ⊕ (fin n)) : (φ.relabel f).is_prenex := is_prenex.rec_on h (λ _ _ h, (h.relabel f).is_prenex) (λ _ _ _ h, by simp [h.all]) (λ _ _ _ h, by simp [h.ex]) lemma is_prenex.cast_le (hφ : is_prenex φ) : ∀ {n} {h : l ≤ n}, (φ.cast_le h).is_prenex := is_prenex.rec_on hφ (λ _ _ ih _ _, ih.cast_le.is_prenex) (λ _ _ _ ih _ _, ih.all) (λ _ _ _ ih _ _, ih.ex) lemma is_prenex.lift_at {k m : ℕ} (h : is_prenex φ) : (φ.lift_at k m).is_prenex := is_prenex.rec_on h (λ _ _ ih, ih.lift_at.is_prenex) (λ _ _ _ ih, ih.cast_le.all) (λ _ _ _ ih, ih.cast_le.ex) /-- An auxiliary operation to `first_order.language.bounded_formula.to_prenex`. If `φ` is quantifier-free and `ψ` is in prenex normal form, then `φ.to_prenex_imp_right ψ` is a prenex normal form for `φ.imp ψ`. -/ def to_prenex_imp_right : ∀ {n}, L.bounded_formula α n → L.bounded_formula α n → L.bounded_formula α n | n φ (bounded_formula.ex ψ) := ((φ.lift_at 1 n).to_prenex_imp_right ψ).ex | n φ (all ψ) := ((φ.lift_at 1 n).to_prenex_imp_right ψ).all | n φ ψ := φ.imp ψ lemma is_qf.to_prenex_imp_right {φ : L.bounded_formula α n} : Π {ψ : L.bounded_formula α n}, is_qf ψ → (φ.to_prenex_imp_right ψ = φ.imp ψ) | _ is_qf.falsum := rfl | _ (is_qf.of_is_atomic (is_atomic.equal _ _)) := rfl | _ (is_qf.of_is_atomic (is_atomic.rel _ _)) := rfl | _ (is_qf.imp is_qf.falsum _) := rfl | _ (is_qf.imp (is_qf.of_is_atomic (is_atomic.equal _ _)) _) := rfl | _ (is_qf.imp (is_qf.of_is_atomic (is_atomic.rel _ _)) _) := rfl | _ (is_qf.imp (is_qf.imp _ _) _) := rfl lemma is_prenex_to_prenex_imp_right {φ ψ : L.bounded_formula α n} (hφ : is_qf φ) (hψ : is_prenex ψ) : is_prenex (φ.to_prenex_imp_right ψ) := begin induction hψ with _ _ hψ _ _ _ ih1 _ _ _ ih2, { rw hψ.to_prenex_imp_right, exact (hφ.imp hψ).is_prenex }, { exact (ih1 hφ.lift_at).all }, { exact (ih2 hφ.lift_at).ex } end /-- An auxiliary operation to `first_order.language.bounded_formula.to_prenex`. If `φ` and `ψ` are in prenex normal form, then `φ.to_prenex_imp ψ` is a prenex normal form for `φ.imp ψ`. -/ def to_prenex_imp : ∀ {n}, L.bounded_formula α n → L.bounded_formula α n → L.bounded_formula α n | n (bounded_formula.ex φ) ψ := (φ.to_prenex_imp (ψ.lift_at 1 n)).all | n (all φ) ψ := (φ.to_prenex_imp (ψ.lift_at 1 n)).ex | _ φ ψ := φ.to_prenex_imp_right ψ lemma is_qf.to_prenex_imp : Π {φ ψ : L.bounded_formula α n}, φ.is_qf → φ.to_prenex_imp ψ = φ.to_prenex_imp_right ψ | _ _ is_qf.falsum := rfl | _ _ (is_qf.of_is_atomic (is_atomic.equal _ _)) := rfl | _ _ (is_qf.of_is_atomic (is_atomic.rel _ _)) := rfl | _ _ (is_qf.imp is_qf.falsum _) := rfl | _ _ (is_qf.imp (is_qf.of_is_atomic (is_atomic.equal _ _)) _) := rfl | _ _ (is_qf.imp (is_qf.of_is_atomic (is_atomic.rel _ _)) _) := rfl | _ _ (is_qf.imp (is_qf.imp _ _) _) := rfl lemma is_prenex_to_prenex_imp {φ ψ : L.bounded_formula α n} (hφ : is_prenex φ) (hψ : is_prenex ψ) : is_prenex (φ.to_prenex_imp ψ) := begin induction hφ with _ _ hφ _ _ _ ih1 _ _ _ ih2, { rw hφ.to_prenex_imp, exact is_prenex_to_prenex_imp_right hφ hψ }, { exact (ih1 hψ.lift_at).ex }, { exact (ih2 hψ.lift_at).all } end /-- For any bounded formula `φ`, `φ.to_prenex` is a semantically-equivalent formula in prenex normal form. -/ def to_prenex : ∀ {n}, L.bounded_formula α n → L.bounded_formula α n | _ falsum := ⊥ | _ (equal t₁ t₂) := t₁.bd_equal t₂ | _ (rel R ts) := rel R ts | _ (imp f₁ f₂) := f₁.to_prenex.to_prenex_imp f₂.to_prenex | _ (all f) := f.to_prenex.all lemma to_prenex_is_prenex (φ : L.bounded_formula α n) : φ.to_prenex.is_prenex := bounded_formula.rec_on φ (λ _, is_qf_bot.is_prenex) (λ _ _ _, (is_atomic.equal _ _).is_prenex) (λ _ _ _ _, (is_atomic.rel _ _).is_prenex) (λ _ _ _ h1 h2, is_prenex_to_prenex_imp h1 h2) (λ _ _, is_prenex.all) end bounded_formula namespace Lhom open bounded_formula /-- Maps a bounded formula's symbols along a language map. -/ @[simp] def on_bounded_formula (g : L →ᴸ L') : ∀ {k : ℕ}, L.bounded_formula α k → L'.bounded_formula α k | k falsum := falsum | k (equal t₁ t₂) := (g.on_term t₁).bd_equal (g.on_term t₂) | k (rel R ts) := (g.on_relation R).bounded_formula (g.on_term ∘ ts) | k (imp f₁ f₂) := (on_bounded_formula f₁).imp (on_bounded_formula f₂) | k (all f) := (on_bounded_formula f).all @[simp] lemma id_on_bounded_formula : ((Lhom.id L).on_bounded_formula : L.bounded_formula α n → L.bounded_formula α n) = id := begin ext f, induction f with _ _ _ _ _ _ _ _ _ _ _ ih1 ih2 _ _ ih3, { refl }, { rw [on_bounded_formula, Lhom.id_on_term, id.def, id.def, id.def, bd_equal] }, { rw [on_bounded_formula, Lhom.id_on_term], refl, }, { rw [on_bounded_formula, ih1, ih2, id.def, id.def, id.def] }, { rw [on_bounded_formula, ih3, id.def, id.def] } end @[simp] lemma comp_on_bounded_formula {L'' : language} (φ : L' →ᴸ L'') (ψ : L →ᴸ L') : ((φ.comp ψ).on_bounded_formula : L.bounded_formula α n → L''.bounded_formula α n) = φ.on_bounded_formula ∘ ψ.on_bounded_formula := begin ext f, induction f with _ _ _ _ _ _ _ _ _ _ _ ih1 ih2 _ _ ih3, { refl }, { simp only [on_bounded_formula, comp_on_term, function.comp_app], refl, }, { simp only [on_bounded_formula, comp_on_relation, comp_on_term, function.comp_app], refl }, { simp only [on_bounded_formula, function.comp_app, ih1, ih2, eq_self_iff_true, and_self], }, { simp only [ih3, on_bounded_formula, function.comp_app] } end /-- Maps a formula's symbols along a language map. -/ def on_formula (g : L →ᴸ L') : L.formula α → L'.formula α := g.on_bounded_formula /-- Maps a sentence's symbols along a language map. -/ def on_sentence (g : L →ᴸ L') : L.sentence → L'.sentence := g.on_formula /-- Maps a theory's symbols along a language map. -/ def on_Theory (g : L →ᴸ L') (T : L.Theory) : L'.Theory := g.on_sentence '' T @[simp] lemma mem_on_Theory {g : L →ᴸ L'} {T : L.Theory} {φ : L'.sentence} : φ ∈ g.on_Theory T ↔ ∃ φ₀, φ₀ ∈ T ∧ g.on_sentence φ₀ = φ := set.mem_image _ _ _ end Lhom namespace Lequiv /-- Maps a bounded formula's symbols along a language equivalence. -/ @[simps] def on_bounded_formula (φ : L ≃ᴸ L') : L.bounded_formula α n ≃ L'.bounded_formula α n := { to_fun := φ.to_Lhom.on_bounded_formula, inv_fun := φ.inv_Lhom.on_bounded_formula, left_inv := by rw [function.left_inverse_iff_comp, ← Lhom.comp_on_bounded_formula, φ.left_inv, Lhom.id_on_bounded_formula], right_inv := by rw [function.right_inverse_iff_comp, ← Lhom.comp_on_bounded_formula, φ.right_inv, Lhom.id_on_bounded_formula] } lemma on_bounded_formula_symm (φ : L ≃ᴸ L') : (φ.on_bounded_formula.symm : L'.bounded_formula α n ≃ L.bounded_formula α n) = φ.symm.on_bounded_formula := rfl /-- Maps a formula's symbols along a language equivalence. -/ def on_formula (φ : L ≃ᴸ L') : L.formula α ≃ L'.formula α := φ.on_bounded_formula @[simp] lemma on_formula_apply (φ : L ≃ᴸ L') : (φ.on_formula : L.formula α → L'.formula α) = φ.to_Lhom.on_formula := rfl @[simp] lemma on_formula_symm (φ : L ≃ᴸ L') : (φ.on_formula.symm : L'.formula α ≃ L.formula α) = φ.symm.on_formula := rfl /-- Maps a sentence's symbols along a language equivalence. -/ @[simps] def on_sentence (φ : L ≃ᴸ L') : L.sentence ≃ L'.sentence := φ.on_formula end Lequiv localized "infix (name := term.bd_equal) ` =' `:88 := first_order.language.term.bd_equal" in first_order -- input \~- or \simeq localized "infixr (name := bounded_formula.imp) ` ⟹ `:62 := first_order.language.bounded_formula.imp" in first_order -- input \==> localized "prefix (name := bounded_formula.all) `∀'`:110 := first_order.language.bounded_formula.all" in first_order localized "prefix (name := bounded_formula.not) `∼`:max := first_order.language.bounded_formula.not" in first_order -- input \~, the ASCII character ~ has too low precedence localized "infix (name := bounded_formula.iff) ` ⇔ `:61 := first_order.language.bounded_formula.iff" in first_order -- input \<=> localized "prefix (name := bounded_formula.ex) `∃'`:110 := first_order.language.bounded_formula.ex" in first_order -- input \ex namespace formula /-- Relabels a formula's variables along a particular function. -/ def relabel (g : α → β) : L.formula α → L.formula β := @bounded_formula.relabel _ _ _ 0 (sum.inl ∘ g) 0 /-- The graph of a function as a first-order formula. -/ def graph (f : L.functions n) : L.formula (fin (n + 1)) := equal (var 0) (func f (λ i, var i.succ)) /-- The negation of a formula. -/ protected def not (φ : L.formula α) : L.formula α := φ.not /-- The implication between formulas, as a formula. -/ protected def imp : L.formula α → L.formula α → L.formula α := bounded_formula.imp /-- The biimplication between formulas, as a formula. -/ protected def iff (φ ψ : L.formula α) : L.formula α := φ.iff ψ lemma is_atomic_graph (f : L.functions n) : (graph f).is_atomic := bounded_formula.is_atomic.equal _ _ /-- A bijection sending formulas to sentences with constants. -/ def equiv_sentence : L.formula α ≃ L[[α]].sentence := (bounded_formula.constants_vars_equiv.trans (bounded_formula.relabel_equiv (equiv.sum_empty _ _))).symm lemma equiv_sentence_not (φ : L.formula α) : equiv_sentence φ.not = (equiv_sentence φ).not := rfl lemma equiv_sentence_inf (φ ψ : L.formula α) : equiv_sentence (φ ⊓ ψ) = equiv_sentence φ ⊓ equiv_sentence ψ := rfl end formula namespace relations variable (r : L.relations 2) /-- The sentence indicating that a basic relation symbol is reflexive. -/ protected def reflexive : L.sentence := ∀' r.bounded_formula₂ &0 &0 /-- The sentence indicating that a basic relation symbol is irreflexive. -/ protected def irreflexive : L.sentence := ∀' ∼ (r.bounded_formula₂ &0 &0) /-- The sentence indicating that a basic relation symbol is symmetric. -/ protected def symmetric : L.sentence := ∀' ∀' (r.bounded_formula₂ &0 &1 ⟹ r.bounded_formula₂ &1 &0) /-- The sentence indicating that a basic relation symbol is antisymmetric. -/ protected def antisymmetric : L.sentence := ∀' ∀' (r.bounded_formula₂ &0 &1 ⟹ (r.bounded_formula₂ &1 &0 ⟹ term.bd_equal &0 &1)) /-- The sentence indicating that a basic relation symbol is transitive. -/ protected def transitive : L.sentence := ∀' ∀' ∀' (r.bounded_formula₂ &0 &1 ⟹ r.bounded_formula₂ &1 &2 ⟹ r.bounded_formula₂ &0 &2) /-- The sentence indicating that a basic relation symbol is total. -/ protected def total : L.sentence := ∀' ∀' (r.bounded_formula₂ &0 &1 ⊔ r.bounded_formula₂ &1 &0) end relations section cardinality variable (L) /-- A sentence indicating that a structure has `n` distinct elements. -/ protected def sentence.card_ge (n) : L.sentence := (((((list.fin_range n).product (list.fin_range n)).filter (λ ij : _ × _, ij.1 ≠ ij.2)).map (λ (ij : _ × _), ∼ ((& ij.1).bd_equal (& ij.2)))).foldr (⊓) ⊤).exs /-- A theory indicating that a structure is infinite. -/ def infinite_theory : L.Theory := set.range (sentence.card_ge L) /-- A theory that indicates a structure is nonempty. -/ def nonempty_theory : L.Theory := {sentence.card_ge L 1} /-- A theory indicating that each of a set of constants is distinct. -/ def distinct_constants_theory (s : set α) : L[[α]].Theory := (λ ab : α × α, (((L.con ab.1).term.equal (L.con ab.2).term).not)) '' (s ×ˢ s ∩ (set.diagonal α)ᶜ) variables {L} {α} open set lemma monotone_distinct_constants_theory : monotone (L.distinct_constants_theory : set α → L[[α]].Theory) := λ s t st, (image_subset _ (inter_subset_inter_left _ (prod_mono st st))) lemma directed_distinct_constants_theory : directed (⊆) (L.distinct_constants_theory : set α → L[[α]].Theory) := monotone.directed_le monotone_distinct_constants_theory lemma distinct_constants_theory_eq_Union (s : set α) : L.distinct_constants_theory s = ⋃ (t : finset s), L.distinct_constants_theory (t.map (function.embedding.subtype (λ x, x ∈ s))) := begin classical, simp only [distinct_constants_theory], rw [← image_Union, ← Union_inter], refine congr rfl (congr (congr rfl _) rfl), ext ⟨i, j⟩, simp only [prod_mk_mem_set_prod_eq, finset.coe_map, function.embedding.coe_subtype, mem_Union, mem_image, finset.mem_coe, subtype.exists, subtype.coe_mk, exists_and_distrib_right, exists_eq_right], refine ⟨λ h, ⟨{⟨i, h.1⟩, ⟨j, h.2⟩}, ⟨h.1, _⟩, ⟨h.2, _⟩⟩, _⟩, { simp }, { simp }, { rintros ⟨t, ⟨is, _⟩, ⟨js, _⟩⟩, exact ⟨is, js⟩ } end end cardinality end language end first_order
d16ce68154830ef557814d669d7216ffafcbd114
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/algebra/opposites.lean
c2e0735751a79b7e555d816df9e5ad2aa98489f7
[ "Apache-2.0" ]
permissive
abentkamp/mathlib
d9a75d291ec09f4637b0f30cc3880ffb07549ee5
5360e476391508e092b5a1e5210bd0ed22dc0755
refs/heads/master
1,682,382,954,948
1,622,106,077,000
1,622,106,077,000
149,285,665
0
0
null
null
null
null
UTF-8
Lean
false
false
13,933
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import data.opposite import algebra.field import algebra.group.commute import group_theory.group_action.defs import data.equiv.mul_add /-! # Algebraic operations on `αᵒᵖ` This file records several basic facts about the opposite of an algebraic structure, e.g. the opposite of a ring is a ring (with multiplication `x * y = yx`). Use is made of the identity functions `op : α → αᵒᵖ` and `unop : αᵒᵖ → α`. -/ namespace opposite universes u variables (α : Type u) instance [has_add α] : has_add (opposite α) := { add := λ x y, op (unop x + unop y) } instance [has_sub α] : has_sub (opposite α) := { sub := λ x y, op (unop x - unop y) } instance [add_semigroup α] : add_semigroup (opposite α) := { add_assoc := λ x y z, unop_injective $ add_assoc (unop x) (unop y) (unop z), .. opposite.has_add α } instance [add_left_cancel_semigroup α] : add_left_cancel_semigroup (opposite α) := { add_left_cancel := λ x y z H, unop_injective $ add_left_cancel $ op_injective H, .. opposite.add_semigroup α } instance [add_right_cancel_semigroup α] : add_right_cancel_semigroup (opposite α) := { add_right_cancel := λ x y z H, unop_injective $ add_right_cancel $ op_injective H, .. opposite.add_semigroup α } instance [add_comm_semigroup α] : add_comm_semigroup (opposite α) := { add_comm := λ x y, unop_injective $ add_comm (unop x) (unop y), .. opposite.add_semigroup α } instance [has_zero α] : has_zero (opposite α) := { zero := op 0 } instance [nontrivial α] : nontrivial (opposite α) := let ⟨x, y, h⟩ := exists_pair_ne α in nontrivial_of_ne (op x) (op y) (op_injective.ne h) section local attribute [semireducible] opposite @[simp] lemma unop_eq_zero_iff {α} [has_zero α] (a : αᵒᵖ) : a.unop = (0 : α) ↔ a = (0 : αᵒᵖ) := iff.refl _ @[simp] lemma op_eq_zero_iff {α} [has_zero α] (a : α) : op a = (0 : αᵒᵖ) ↔ a = (0 : α) := iff.refl _ end lemma unop_ne_zero_iff {α} [has_zero α] (a : αᵒᵖ) : a.unop ≠ (0 : α) ↔ a ≠ (0 : αᵒᵖ) := not_iff_not.mpr $ unop_eq_zero_iff a lemma op_ne_zero_iff {α} [has_zero α] (a : α) : op a ≠ (0 : αᵒᵖ) ↔ a ≠ (0 : α) := not_iff_not.mpr $ op_eq_zero_iff a instance [add_zero_class α] : add_zero_class (opposite α) := { zero_add := λ x, unop_injective $ zero_add $ unop x, add_zero := λ x, unop_injective $ add_zero $ unop x, .. opposite.has_add α, .. opposite.has_zero α } instance [add_monoid α] : add_monoid (opposite α) := { .. opposite.add_semigroup α, .. opposite.add_zero_class α } instance [add_comm_monoid α] : add_comm_monoid (opposite α) := { .. opposite.add_monoid α, .. opposite.add_comm_semigroup α } instance [has_neg α] : has_neg (opposite α) := { neg := λ x, op $ -(unop x) } instance [add_group α] : add_group (opposite α) := { add_left_neg := λ x, unop_injective $ add_left_neg $ unop x, sub_eq_add_neg := λ x y, unop_injective $ sub_eq_add_neg (unop x) (unop y), .. opposite.add_monoid α, .. opposite.has_neg α, .. opposite.has_sub α } instance [add_comm_group α] : add_comm_group (opposite α) := { .. opposite.add_group α, .. opposite.add_comm_monoid α } instance [has_mul α] : has_mul (opposite α) := { mul := λ x y, op (unop y * unop x) } instance [semigroup α] : semigroup (opposite α) := { mul_assoc := λ x y z, unop_injective $ eq.symm $ mul_assoc (unop z) (unop y) (unop x), .. opposite.has_mul α } instance [right_cancel_semigroup α] : left_cancel_semigroup (opposite α) := { mul_left_cancel := λ x y z H, unop_injective $ mul_right_cancel $ op_injective H, .. opposite.semigroup α } instance [left_cancel_semigroup α] : right_cancel_semigroup (opposite α) := { mul_right_cancel := λ x y z H, unop_injective $ mul_left_cancel $ op_injective H, .. opposite.semigroup α } instance [comm_semigroup α] : comm_semigroup (opposite α) := { mul_comm := λ x y, unop_injective $ mul_comm (unop y) (unop x), .. opposite.semigroup α } instance [has_one α] : has_one (opposite α) := { one := op 1 } section local attribute [semireducible] opposite @[simp] lemma unop_eq_one_iff {α} [has_one α] (a : αᵒᵖ) : a.unop = 1 ↔ a = 1 := iff.refl _ @[simp] lemma op_eq_one_iff {α} [has_one α] (a : α) : op a = 1 ↔ a = 1 := iff.refl _ end instance [mul_one_class α] : mul_one_class (opposite α) := { one_mul := λ x, unop_injective $ mul_one $ unop x, mul_one := λ x, unop_injective $ one_mul $ unop x, .. opposite.has_mul α, .. opposite.has_one α } instance [monoid α] : monoid (opposite α) := { .. opposite.semigroup α, .. opposite.mul_one_class α } instance [comm_monoid α] : comm_monoid (opposite α) := { .. opposite.monoid α, .. opposite.comm_semigroup α } instance [has_inv α] : has_inv (opposite α) := { inv := λ x, op $ (unop x)⁻¹ } instance [group α] : group (opposite α) := { mul_left_inv := λ x, unop_injective $ mul_inv_self $ unop x, .. opposite.monoid α, .. opposite.has_inv α } instance [comm_group α] : comm_group (opposite α) := { .. opposite.group α, .. opposite.comm_monoid α } instance [distrib α] : distrib (opposite α) := { left_distrib := λ x y z, unop_injective $ add_mul (unop y) (unop z) (unop x), right_distrib := λ x y z, unop_injective $ mul_add (unop z) (unop x) (unop y), .. opposite.has_add α, .. opposite.has_mul α } instance [mul_zero_class α] : mul_zero_class (opposite α) := { zero := 0, mul := (*), zero_mul := λ x, unop_injective $ mul_zero $ unop x, mul_zero := λ x, unop_injective $ zero_mul $ unop x } instance [mul_zero_one_class α] : mul_zero_one_class (opposite α) := { .. opposite.mul_zero_class α, .. opposite.mul_one_class α } instance [monoid_with_zero α] : monoid_with_zero (opposite α) := { .. opposite.monoid α, .. opposite.mul_zero_one_class α } instance [semiring α] : semiring (opposite α) := { .. opposite.add_comm_monoid α, .. opposite.monoid_with_zero α, .. opposite.distrib α } instance [ring α] : ring (opposite α) := { .. opposite.add_comm_group α, .. opposite.monoid α, .. opposite.semiring α } instance [comm_ring α] : comm_ring (opposite α) := { .. opposite.ring α, .. opposite.comm_semigroup α } instance [has_zero α] [has_mul α] [no_zero_divisors α] : no_zero_divisors (opposite α) := { eq_zero_or_eq_zero_of_mul_eq_zero := λ x y (H : op (_ * _) = op (0:α)), or.cases_on (eq_zero_or_eq_zero_of_mul_eq_zero $ op_injective H) (λ hy, or.inr $ unop_injective $ hy) (λ hx, or.inl $ unop_injective $ hx), } instance [integral_domain α] : integral_domain (opposite α) := { .. opposite.no_zero_divisors α, .. opposite.comm_ring α, .. opposite.nontrivial α } instance [group_with_zero α] : group_with_zero (opposite α) := { mul_inv_cancel := λ x hx, unop_injective $ inv_mul_cancel $ unop_injective.ne hx, inv_zero := unop_injective inv_zero, .. opposite.monoid_with_zero α, .. opposite.nontrivial α, .. opposite.has_inv α } instance [division_ring α] : division_ring (opposite α) := { .. opposite.group_with_zero α, .. opposite.ring α } instance [field α] : field (opposite α) := { .. opposite.division_ring α, .. opposite.comm_ring α } instance (R : Type*) [has_scalar R α] : has_scalar R (opposite α) := { smul := λ c x, op (c • unop x) } instance (R : Type*) [monoid R] [mul_action R α] : mul_action R (opposite α) := { one_smul := λ x, unop_injective $ one_smul R (unop x), mul_smul := λ r₁ r₂ x, unop_injective $ mul_smul r₁ r₂ (unop x), ..opposite.has_scalar α R } instance (R : Type*) [monoid R] [add_monoid α] [distrib_mul_action R α] : distrib_mul_action R (opposite α) := { smul_add := λ r x₁ x₂, unop_injective $ smul_add r (unop x₁) (unop x₂), smul_zero := λ r, unop_injective $ smul_zero r, ..opposite.mul_action α R } /-- Like `monoid.to_mul_action`, but multiplies on the right. -/ instance monoid.to_opposite_mul_action [monoid α] : mul_action (opposite α) α := { smul := λ c x, x * c.unop, one_smul := mul_one, mul_smul := λ x y r, (mul_assoc _ _ _).symm } -- The above instance does not create an unwanted diamond, the two paths to -- `mul_action (opposite α) (opposite α)` are defeq. example [monoid α] : monoid.to_mul_action (opposite α) = opposite.mul_action α (opposite α) := rfl lemma op_smul_eq_mul [monoid α] {a a' : α} : op a • a' = a' * a := rfl @[simp] lemma op_zero [has_zero α] : op (0 : α) = 0 := rfl @[simp] lemma unop_zero [has_zero α] : unop (0 : αᵒᵖ) = 0 := rfl @[simp] lemma op_one [has_one α] : op (1 : α) = 1 := rfl @[simp] lemma unop_one [has_one α] : unop (1 : αᵒᵖ) = 1 := rfl variable {α} @[simp] lemma op_add [has_add α] (x y : α) : op (x + y) = op x + op y := rfl @[simp] lemma unop_add [has_add α] (x y : αᵒᵖ) : unop (x + y) = unop x + unop y := rfl @[simp] lemma op_neg [has_neg α] (x : α) : op (-x) = -op x := rfl @[simp] lemma unop_neg [has_neg α] (x : αᵒᵖ) : unop (-x) = -unop x := rfl @[simp] lemma op_mul [has_mul α] (x y : α) : op (x * y) = op y * op x := rfl @[simp] lemma unop_mul [has_mul α] (x y : αᵒᵖ) : unop (x * y) = unop y * unop x := rfl @[simp] lemma op_inv [has_inv α] (x : α) : op (x⁻¹) = (op x)⁻¹ := rfl @[simp] lemma unop_inv [has_inv α] (x : αᵒᵖ) : unop (x⁻¹) = (unop x)⁻¹ := rfl @[simp] lemma op_sub [add_group α] (x y : α) : op (x - y) = op x - op y := rfl @[simp] lemma unop_sub [add_group α] (x y : αᵒᵖ) : unop (x - y) = unop x - unop y := rfl @[simp] lemma op_smul {R : Type*} [has_scalar R α] (c : R) (a : α) : op (c • a) = c • op a := rfl @[simp] lemma unop_smul {R : Type*} [has_scalar R α] (c : R) (a : αᵒᵖ) : unop (c • a) = c • unop a := rfl lemma semiconj_by.op [has_mul α] {a x y : α} (h : semiconj_by a x y) : semiconj_by (op a) (op y) (op x) := begin dunfold semiconj_by, rw [← op_mul, ← op_mul, h.eq] end lemma semiconj_by.unop [has_mul α] {a x y : αᵒᵖ} (h : semiconj_by a x y) : semiconj_by (unop a) (unop y) (unop x) := begin dunfold semiconj_by, rw [← unop_mul, ← unop_mul, h.eq] end @[simp] lemma semiconj_by_op [has_mul α] {a x y : α} : semiconj_by (op a) (op y) (op x) ↔ semiconj_by a x y := begin split, { intro h, rw [← unop_op a, ← unop_op x, ← unop_op y], exact semiconj_by.unop h }, { intro h, exact semiconj_by.op h } end @[simp] lemma semiconj_by_unop [has_mul α] {a x y : αᵒᵖ} : semiconj_by (unop a) (unop y) (unop x) ↔ semiconj_by a x y := by conv_rhs { rw [← op_unop a, ← op_unop x, ← op_unop y, semiconj_by_op] } lemma commute.op [has_mul α] {x y : α} (h : commute x y) : commute (op x) (op y) := begin dunfold commute at h ⊢, exact semiconj_by.op h end lemma commute.unop [has_mul α] {x y : αᵒᵖ} (h : commute x y) : commute (unop x) (unop y) := begin dunfold commute at h ⊢, exact semiconj_by.unop h end @[simp] lemma commute_op [has_mul α] {x y : α} : commute (op x) (op y) ↔ commute x y := begin dunfold commute, rw semiconj_by_op end @[simp] lemma commute_unop [has_mul α] {x y : αᵒᵖ} : commute (unop x) (unop y) ↔ commute x y := begin dunfold commute, rw semiconj_by_unop end /-- The function `op` is an additive equivalence. -/ def op_add_equiv [has_add α] : α ≃+ αᵒᵖ := { map_add' := λ a b, rfl, .. equiv_to_opposite } @[simp] lemma coe_op_add_equiv [has_add α] : (op_add_equiv : α → αᵒᵖ) = op := rfl @[simp] lemma coe_op_add_equiv_symm [has_add α] : (op_add_equiv.symm : αᵒᵖ → α) = unop := rfl @[simp] lemma op_add_equiv_to_equiv [has_add α] : (op_add_equiv : α ≃+ αᵒᵖ).to_equiv = equiv_to_opposite := rfl end opposite open opposite /-- Inversion on a group is a `mul_equiv` to the opposite group. When `G` is commutative, there is `mul_equiv.inv`. -/ @[simps {fully_applied := ff}] def mul_equiv.inv' (G : Type*) [group G] : G ≃* Gᵒᵖ := { to_fun := opposite.op ∘ has_inv.inv, inv_fun := has_inv.inv ∘ opposite.unop, map_mul' := λ x y, unop_injective $ mul_inv_rev x y, ..(equiv.inv G).trans equiv_to_opposite} /-- A monoid homomorphism `f : R →* S` such that `f x` commutes with `f y` for all `x, y` defines a monoid homomorphism to `Sᵒᵖ`. -/ @[simps {fully_applied := ff}] def monoid_hom.to_opposite {R S : Type*} [mul_one_class R] [mul_one_class S] (f : R →* S) (hf : ∀ x y, commute (f x) (f y)) : R →* Sᵒᵖ := { to_fun := opposite.op ∘ f, map_one' := congr_arg op f.map_one, map_mul' := λ x y, by simp [(hf x y).eq] } /-- A ring homomorphism `f : R →+* S` such that `f x` commutes with `f y` for all `x, y` defines a ring homomorphism to `Sᵒᵖ`. -/ @[simps {fully_applied := ff}] def ring_hom.to_opposite {R S : Type*} [semiring R] [semiring S] (f : R →+* S) (hf : ∀ x y, commute (f x) (f y)) : R →+* Sᵒᵖ := { to_fun := opposite.op ∘ f, .. ((opposite.op_add_equiv : S ≃+ Sᵒᵖ).to_add_monoid_hom.comp ↑f : R →+ Sᵒᵖ), .. f.to_monoid_hom.to_opposite hf } /-- The units of the opposites are equivalent to the opposites of the units. -/ def units.op_equiv {R} [monoid R] : units Rᵒᵖ ≃* (units R)ᵒᵖ := { to_fun := λ u, op ⟨unop u, unop ↑(u⁻¹), op_injective u.4, op_injective u.3⟩, inv_fun := op_induction $ λ u, ⟨op ↑(u), op ↑(u⁻¹), unop_injective $ u.4, unop_injective u.3⟩, map_mul' := λ x y, unop_injective $ units.ext $ rfl, left_inv := λ x, units.ext $ rfl, right_inv := λ x, unop_injective $ units.ext $ rfl } @[simp] lemma units.coe_unop_op_equiv {R} [monoid R] (u : units Rᵒᵖ) : ((units.op_equiv u).unop : R) = unop (u : Rᵒᵖ) := rfl @[simp] lemma units.coe_op_equiv_symm {R} [monoid R] (u : (units R)ᵒᵖ) : (units.op_equiv.symm u : Rᵒᵖ) = op (u.unop : R) := rfl
4cc7fc75af4b86d58c61f2423ea3c5a712108385
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/library/init/datatypes.lean
557a146ace124405cff0f0988f640d94658bc239
[ "Apache-2.0" ]
permissive
soonhokong/lean-osx
4a954262c780e404c1369d6c06516161d07fcb40
3670278342d2f4faa49d95b46d86642d7875b47c
refs/heads/master
1,611,410,334,552
1,474,425,686,000
1,474,425,686,000
12,043,103
5
1
null
null
null
null
UTF-8
Lean
false
false
14,651
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura Basic datatypes -/ prelude notation `Prop` := Type 0 notation `Type₂` := Type 2 notation `Type₃` := Type 3 universe variables u v inductive poly_unit : Type u | star : poly_unit inductive unit : Type | star : unit inductive true : Prop | intro : true inductive false : Prop inductive empty : Type inductive eq {A : Type u} (a : A) : A → Prop | refl : eq a inductive heq {A : Type u} (a : A) : Π {B : Type u}, B → Prop | refl : heq a structure prod (A : Type u) (B : Type v) := (pr1 : A) (pr2 : B) inductive and (a b : Prop) : Prop | intro : a → b → and definition and.elim_left {a b : Prop} (H : and a b) : a := and.rec (λ Ha Hb, Ha) H definition and.left := @and.elim_left definition and.elim_right {a b : Prop} (H : and a b) : b := and.rec (λ Ha Hb, Hb) H definition and.right := @and.elim_right inductive sum (A : Type u) (B : Type v) | inl {} : A → sum | inr {} : B → sum attribute [reducible] definition sum.intro_left {A : Type u} (B : Type v) (a : A) : sum A B := sum.inl a attribute [reducible] definition sum.intro_right (A : Type u) {B : Type v} (b : B) : sum A B := sum.inr b inductive or (a b : Prop) : Prop | inl {} : a → or | inr {} : b → or definition or.intro_left {a : Prop} (b : Prop) (Ha : a) : or a b := or.inl Ha definition or.intro_right (a : Prop) {b : Prop} (Hb : b) : or a b := or.inr Hb structure sigma {A : Type u} (B : A → Type v) := mk :: (pr1 : A) (pr2 : B pr1) -- pos_num and num are two auxiliary datatypes used when parsing numerals such as 13, 0, 26. -- The parser will generate the terms (pos (bit1 (bit1 (bit0 one)))), zero, and (pos (bit0 (bit1 (bit1 one)))). -- This representation can be coerced in whatever we want (e.g., naturals, integers, reals, etc). inductive pos_num : Type | one : pos_num | bit1 : pos_num → pos_num | bit0 : pos_num → pos_num namespace pos_num definition succ (a : pos_num) : pos_num := pos_num.rec_on a (bit0 one) (λn r, bit0 r) (λn r, bit1 n) end pos_num inductive num : Type | zero : num | pos : pos_num → num namespace num open pos_num definition succ (a : num) : num := num.rec_on a (pos one) (λp, pos (succ p)) end num inductive bool : Type | ff : bool | tt : bool inductive option (A : Type u) | none {} : option | some : A → option export option (none some) export bool (ff tt) inductive list (T : Type u) | nil {} : list | cons : T → list → list inductive nat | zero : nat | succ : nat → nat /- Declare builtin and reserved notation -/ notation `assume` binders `,` r:(scoped f, f) := r notation `take` binders `,` r:(scoped f, f) := r structure [class] has_zero (A : Type u) := (zero : A) structure [class] has_one (A : Type u) := (one : A) structure [class] has_add (A : Type u) := (add : A → A → A) structure [class] has_mul (A : Type u) := (mul : A → A → A) structure [class] has_inv (A : Type u) := (inv : A → A) structure [class] has_neg (A : Type u) := (neg : A → A) structure [class] has_sub (A : Type u) := (sub : A → A → A) structure [class] has_div (A : Type u) := (div : A → A → A) structure [class] has_dvd (A : Type u) := (dvd : A → A → Prop) structure [class] has_mod (A : Type u) := (mod : A → A → A) structure [class] has_le (A : Type u) := (le : A → A → Prop) structure [class] has_lt (A : Type u) := (lt : A → A → Prop) structure [class] has_append (A : Type u) := (append : A → A → A) structure [class] has_andthen(A : Type u) := (andthen : A → A → A) definition zero {A : Type u} [has_zero A] : A := has_zero.zero A definition one {A : Type u} [has_one A] : A := has_one.one A definition add {A : Type u} [has_add A] : A → A → A := has_add.add definition mul {A : Type u} [has_mul A] : A → A → A := has_mul.mul definition sub {A : Type u} [has_sub A] : A → A → A := has_sub.sub definition div {A : Type u} [has_div A] : A → A → A := has_div.div definition dvd {A : Type u} [has_dvd A] : A → A → Prop := has_dvd.dvd definition mod {A : Type u} [has_mod A] : A → A → A := has_mod.mod definition neg {A : Type u} [has_neg A] : A → A := has_neg.neg definition inv {A : Type u} [has_inv A] : A → A := has_inv.inv definition le {A : Type u} [has_le A] : A → A → Prop := has_le.le definition lt {A : Type u} [has_lt A] : A → A → Prop := has_lt.lt definition append {A : Type u} [has_append A] : A → A → A := has_append.append definition andthen {A : Type u} [has_andthen A] : A → A → A := has_andthen.andthen attribute [reducible] definition ge {A : Type u} [s : has_le A] (a b : A) : Prop := le b a attribute [reducible] definition gt {A : Type u} [s : has_lt A] (a b : A) : Prop := lt b a definition bit0 {A : Type u} [s : has_add A] (a : A) : A := add a a definition bit1 {A : Type u} [s₁ : has_one A] [s₂ : has_add A] (a : A) : A := add (bit0 a) one attribute [pattern] zero one bit0 bit1 add attribute [instance] definition num_has_zero : has_zero num := ⟨num.zero⟩ attribute [instance] definition num_has_one : has_one num := ⟨num.pos pos_num.one⟩ attribute [instance] definition pos_num_has_one : has_one pos_num := ⟨pos_num.one⟩ namespace pos_num definition is_one (a : pos_num) : bool := pos_num.rec_on a tt (λn r, ff) (λn r, ff) definition pred (a : pos_num) : pos_num := pos_num.rec_on a one (λn r, bit0 n) (λn r, bool.rec_on (is_one n) (bit1 r) one) definition size (a : pos_num) : pos_num := pos_num.rec_on a one (λn r, succ r) (λn r, succ r) definition add (a b : pos_num) : pos_num := pos_num.rec_on a succ (λn f b, pos_num.rec_on b (succ (bit1 n)) (λm r, succ (bit1 (f m))) (λm r, bit1 (f m))) (λn f b, pos_num.rec_on b (bit1 n) (λm r, bit1 (f m)) (λm r, bit0 (f m))) b end pos_num attribute [instance] definition pos_num_has_add : has_add pos_num := ⟨pos_num.add⟩ namespace num open pos_num definition add (a b : num) : num := num.rec_on a b (λpa, num.rec_on b (pos pa) (λpb, pos (pos_num.add pa pb))) end num attribute [instance] definition num_has_add : has_add num := ⟨num.add⟩ definition std.priority.default : num := 1000 definition std.priority.max : num := 4294967295 namespace nat protected definition prio := num.add std.priority.default 100 protected definition add (a b : nat) : nat := nat.rec a (λ b₁ r, nat.succ r) b definition of_pos_num (p : pos_num) : nat := pos_num.rec (succ zero) (λ n r, nat.add (nat.add r r) (succ zero)) (λ n r, nat.add r r) p definition of_num (n : num) : nat := num.rec zero (λ p, of_pos_num p) n end nat attribute pos_num_has_add pos_num_has_one num_has_zero num_has_one num_has_add [instance, priority nat.prio] attribute [instance, priority nat.prio] definition nat_has_zero : has_zero nat := ⟨nat.zero⟩ attribute [instance, priority nat.prio] definition nat_has_one : has_one nat := ⟨nat.succ (nat.zero)⟩ attribute [instance, priority nat.prio] definition nat_has_add : has_add nat := ⟨nat.add⟩ /- Global declarations of right binding strength If a module reassigns these, it will be incompatible with other modules that adhere to these conventions. When hovering over a symbol, use "C-c C-k" to see how to input it. -/ definition std.prec.max : num := 1024 -- the strength of application, identifiers, (, [, etc. definition std.prec.arrow : num := 25 /- The next definition is "max + 10". It can be used e.g. for postfix operations that should be stronger than application. -/ definition std.prec.max_plus := num.succ (num.succ (num.succ (num.succ (num.succ (num.succ (num.succ (num.succ (num.succ (num.succ std.prec.max))))))))) /- Logical operations and relations -/ reserve prefix `¬`:40 reserve prefix `~`:40 reserve infixr ` ∧ `:35 reserve infixr ` /\ `:35 reserve infixr ` \/ `:30 reserve infixr ` ∨ `:30 reserve infix ` <-> `:20 reserve infix ` ↔ `:20 reserve infix ` = `:50 reserve infix ` ≠ `:50 reserve infix ` ≈ `:50 reserve infix ` ~ `:50 reserve infix ` ≡ `:50 reserve infixl ` ⬝ `:75 reserve infixr ` ▸ `:75 reserve infixr ` ▹ `:75 /- types and type constructors -/ reserve infixr ` ⊕ `:30 reserve infixr ` × `:35 /- arithmetic operations -/ reserve infixl ` + `:65 reserve infixl ` - `:65 reserve infixl ` * `:70 reserve infixl ` / `:70 reserve infixl ` % `:70 reserve prefix `-`:100 reserve infix ` ^ `:80 reserve infixr ` ∘ `:90 -- input with \comp reserve postfix `⁻¹`:std.prec.max_plus -- input with \sy or \-1 or \inv reserve infix ` <= `:50 reserve infix ` ≤ `:50 reserve infix ` < `:50 reserve infix ` >= `:50 reserve infix ` ≥ `:50 reserve infix ` > `:50 /- boolean operations -/ reserve infixl ` && `:70 reserve infixl ` || `:65 /- set operations -/ reserve infix ` ∈ `:50 reserve infix ` ∉ `:50 reserve infixl ` ∩ `:70 reserve infixl ` ∪ `:65 reserve infix ` ⊆ `:50 reserve infix ` ⊇ `:50 reserve infix ` ' `:75 -- for the image of a set under a function reserve infix ` '- `:75 -- for the preimage of a set under a function /- other symbols -/ reserve infix ` ∣ `:50 reserve infixl ` ++ `:65 reserve infixr ` :: `:67 reserve infixl `; `:1 infix + := add infix * := mul infix - := sub infix / := div infix ∣ := dvd infix % := mod prefix - := neg postfix ⁻¹ := inv infix <= := le infix >= := ge infix ≤ := le infix ≥ := ge infix < := lt infix > := gt infix ++ := append infix ; := andthen /- eq basic support -/ notation a = b := eq a b attribute [pattern] definition rfl {A : Type u} {a : A} : a = a := eq.refl a namespace eq variables {A : Type u} variables {a b c a': A} attribute [elab_as_eliminator] theorem subst {P : A → Prop} (H₁ : a = b) (H₂ : P a) : P b := eq.rec H₂ H₁ theorem trans (H₁ : a = b) (H₂ : b = c) : a = c := subst H₂ H₁ theorem symm : a = b → b = a := λ h, eq.rec (refl a) h end eq notation H1 ▸ H2 := eq.subst H1 H2 attribute eq.subst [subst] attribute eq.refl [refl] attribute eq.trans [trans] attribute eq.symm [symm] /- sizeof -/ structure [class] has_sizeof (A : Type u) := (sizeof : A → nat) definition sizeof {A : Type u} [s : has_sizeof A] : A → nat := has_sizeof.sizeof /- Declare sizeof instances and lemmas for types declared before has_sizeof. From now on, the inductive compiler will automatically generate sizeof instances and lemmas. -/ /- Every type `A` has a default has_sizeof instance that just returns 0 for every element of `A` -/ attribute [instance] definition default_has_sizeof (A : Type u) : has_sizeof A := ⟨λ a, nat.zero⟩ attribute [simp, defeq, simp.sizeof] definition default_has_sizeof_eq (A : Type u) (a : A) : @sizeof A (default_has_sizeof A) a = 0 := rfl attribute [instance] definition nat_has_sizeof : has_sizeof nat := ⟨λ a, a⟩ attribute [simp, defeq, simp.sizeof] definition sizeof_nat_eq (a : nat) : sizeof a = a := rfl attribute [instance] definition prod_has_sizeof (A : Type u) (B : Type v) [has_sizeof A] [has_sizeof B] : has_sizeof (prod A B) := ⟨λ p, prod.cases_on p (λ a b, 1 + sizeof a + sizeof b)⟩ attribute [simp, defeq, simp.sizeof] definition sizeof_prod_eq {A : Type u} {B : Type v} [has_sizeof A] [has_sizeof B] (a : A) (b : B) : sizeof (prod.mk a b) = 1 + sizeof a + sizeof b := rfl attribute [instance] definition sum_has_sizeof (A : Type u) (B : Type v) [has_sizeof A] [has_sizeof B] : has_sizeof (sum A B) := ⟨λ s, sum.cases_on s (λ a, 1 + sizeof a) (λ b, 1 + sizeof b)⟩ attribute [simp, defeq, simp.sizeof] definition sizeof_sum_eq_left {A : Type u} {B : Type v} [has_sizeof A] [has_sizeof B] (a : A) : sizeof (@sum.inl A B a) = 1 + sizeof a := rfl attribute [simp, defeq, simp.sizeof] definition sizeof_sum_eq_right {A : Type u} {B : Type v} [has_sizeof A] [has_sizeof B] (b : B) : sizeof (@sum.inr A B b) = 1 + sizeof b := rfl attribute [instance] definition sigma_has_sizeof (A : Type u) (B : A → Type v) [has_sizeof A] [∀ a, has_sizeof (B a)] : has_sizeof (sigma B) := ⟨λ p, sigma.cases_on p (λ a b, 1 + sizeof a + sizeof b)⟩ attribute [simp, defeq, simp.sizeof] definition sizeof_sigma_eq {A : Type u} {B : A → Type v} [has_sizeof A] [∀ a, has_sizeof (B a)] (a : A) (b : B a) : sizeof (@sigma.mk A B a b) = 1 + sizeof a + sizeof b := rfl attribute [instance] definition unit_has_sizeof : has_sizeof unit := ⟨λ u, 1⟩ attribute [simp, defeq, simp.sizeof] definition sizeof_unit_eq (u : unit) : sizeof u = 1 := rfl attribute [instance] definition poly_unit_has_sizeof : has_sizeof poly_unit := ⟨λ u, 1⟩ attribute [simp, defeq, simp.sizeof] definition sizeof_poly_unit_eq (u : poly_unit) : sizeof u = 1 := rfl attribute [instance] definition bool_has_sizeof : has_sizeof bool := ⟨λ u, 1⟩ attribute [simp, defeq, simp.sizeof] definition sizeof_bool_eq (b : bool) : sizeof b = 1 := rfl attribute [instance] definition pos_num_has_sizeof : has_sizeof pos_num := ⟨λ p, nat.of_pos_num p⟩ attribute [simp, defeq, simp.sizeof] definition sizeof_pos_num_eq (p : pos_num) : sizeof p = nat.of_pos_num p := rfl attribute [instance] definition num_has_sizeof : has_sizeof num := ⟨λ p, nat.of_num p⟩ attribute [simp, defeq, simp.sizeof] definition sizeof_num_eq (n : num) : sizeof n = nat.of_num n := rfl attribute [instance] definition option_has_sizeof (A : Type u) [has_sizeof A] : has_sizeof (option A) := ⟨λ o, option.cases_on o 1 (λ a, 1 + sizeof a)⟩ attribute [simp, defeq, simp.sizeof] definition sizeof_option_none_eq (A : Type u) [has_sizeof A] : sizeof (@none A) = 1 := rfl attribute [simp, defeq, simp.sizeof] definition sizeof_option_some_eq {A : Type u} [has_sizeof A] (a : A) : sizeof (some a) = 1 + sizeof a := rfl attribute [instance] definition list_has_sizeof (A : Type u) [has_sizeof A] : has_sizeof (list A) := ⟨λ l, list.rec_on l 1 (λ a t ih, 1 + sizeof a + ih)⟩ attribute [simp, defeq, simp.sizeof] definition sizeof_list_nil_eq (A : Type u) [has_sizeof A] : sizeof (@list.nil A) = 1 := rfl attribute [simp, defeq, simp.sizeof] definition sizeof_list_cons_eq {A : Type u} [has_sizeof A] (a : A) (l : list A) : sizeof (list.cons a l) = 1 + sizeof a + sizeof l := rfl attribute [simp.sizeof] lemma nat_add_zero (n : nat) : n + 0 = n := rfl
7a8fa6d8892b77fd362d49140dd296e40ab9a9ed
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/by_exact.lean
7e111ec945974842ddbc0435aa87ca028c1559d9
[ "Apache-2.0" ]
permissive
soonhokong/lean
cb8aa01055ffe2af0fb99a16b4cda8463b882cd1
38607e3eb57f57f77c0ac114ad169e9e4262e24f
refs/heads/master
1,611,187,284,081
1,450,766,737,000
1,476,122,547,000
11,513,992
2
0
null
1,401,763,102,000
1,374,182,235,000
C++
UTF-8
Lean
false
false
144
lean
import data.nat open nat example (a b c : nat) (h₁ : a + 0 = b) (h₂ : b = c) : a = c := by esimp at h₁; rewrite h₂ at h₁; exact h₁
6f9252392d71bc12d5da9619235b0c8f066ef856
626e312b5c1cb2d88fca108f5933076012633192
/src/data/nat/enat.lean
eae8aaec54c092b5f16fa427382e154817f87469
[ "Apache-2.0" ]
permissive
Bioye97/mathlib
9db2f9ee54418d29dd06996279ba9dc874fd6beb
782a20a27ee83b523f801ff34efb1a9557085019
refs/heads/master
1,690,305,956,488
1,631,067,774,000
1,631,067,774,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
18,394
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import data.pfun import tactic.norm_num import data.equiv.mul_add /-! # Natural numbers with infinity The natural numbers and an extra `top` element `⊤`. ## Main definitions The following instances are defined: * `ordered_add_comm_monoid enat` * `canonically_ordered_add_monoid enat` There is no additive analogue of `monoid_with_zero`; if there were then `enat` could be an `add_monoid_with_top`. * `to_with_top` : the map from `enat` to `with_top ℕ`, with theorems that it plays well with `+` and `≤`. * `with_top_add_equiv : enat ≃+ with_top ℕ` * `with_top_order_iso : enat ≃o with_top ℕ` ## Implementation details `enat` is defined to be `part ℕ`. `+` and `≤` are defined on `enat`, 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 `enat`. Before the `open_locale classical` line, various proofs are made with decidability assumptions. This can cause issues -- see for example the non-simp lemma `to_with_top_zero` proved by `rfl`, followed by `@[simp] lemma to_with_top_zero'` whose proof uses `convert`. ## Tags enat, with_top ℕ -/ open part /-- Type of natural numbers with infinity (`⊤`) -/ def enat : Type := part ℕ namespace enat instance : has_zero enat := ⟨some 0⟩ instance : inhabited enat := ⟨0⟩ instance : has_one enat := ⟨some 1⟩ instance : has_add enat := ⟨λ x y, ⟨x.dom ∧ y.dom, λ h, get x h.1 + get y h.2⟩⟩ instance : has_coe ℕ enat := ⟨some⟩ instance (n : ℕ) : decidable (n : enat).dom := is_true trivial @[simp] lemma coe_inj {x y : ℕ} : (x : enat) = y ↔ x = y := part.some_inj @[simp] lemma dom_coe (x : ℕ) : (x : enat).dom := trivial instance : add_comm_monoid enat := { add := (+), zero := (0), add_comm := λ x y, part.ext' and.comm (λ _ _, add_comm _ _), zero_add := λ x, part.ext' (true_and _) (λ _ _, zero_add _), add_zero := λ x, part.ext' (and_true _) (λ _ _, add_zero _), add_assoc := λ x y z, part.ext' and.assoc (λ _ _, add_assoc _ _ _) } instance : has_le enat := ⟨λ x y, ∃ h : y.dom → x.dom, ∀ hy : y.dom, x.get (h hy) ≤ y.get hy⟩ instance : has_top enat := ⟨none⟩ instance : has_bot enat := ⟨0⟩ instance : has_sup enat := ⟨λ x y, ⟨x.dom ∧ y.dom, λ h, x.get h.1 ⊔ y.get h.2⟩⟩ lemma le_def (x y : enat) : x ≤ y ↔ ∃ h : y.dom → x.dom, ∀ hy : y.dom, x.get (h hy) ≤ y.get hy := iff.rfl @[elab_as_eliminator] protected lemma cases_on {P : enat → Prop} : ∀ a : enat, P ⊤ → (∀ n : ℕ, P n) → P a := part.induction_on @[simp] lemma top_add (x : enat) : ⊤ + x = ⊤ := part.ext' (false_and _) (λ h, h.left.elim) @[simp] lemma add_top (x : enat) : x + ⊤ = ⊤ := by rw [add_comm, top_add] @[simp, norm_cast] lemma coe_zero : ((0 : ℕ) : enat) = 0 := rfl @[simp, norm_cast] lemma coe_one : ((1 : ℕ) : enat) = 1 := rfl @[simp, norm_cast] lemma coe_add (x y : ℕ) : ((x + y : ℕ) : enat) = x + y := part.ext' (and_true _).symm (λ _ _, rfl) lemma get_coe {x : ℕ} : get (x : enat) true.intro = x := rfl @[simp, norm_cast] lemma get_coe' (x : ℕ) (h : (x : enat).dom) : get (x : enat) h = x := rfl lemma coe_add_get {x : ℕ} {y : enat} (h : ((x : enat) + y).dom) : get ((x : enat) + y) h = x + get y h.2 := rfl @[simp] lemma get_add {x y : enat} (h : (x + y).dom) : get (x + y) h = x.get h.1 + y.get h.2 := rfl @[simp] lemma coe_get {x : enat} (h : x.dom) : (x.get h : enat) = x := part.ext' (iff_of_true trivial h) (λ _ _, rfl) @[simp] lemma get_zero (h : (0 : enat).dom) : (0 : enat).get h = 0 := rfl @[simp] lemma get_one (h : (1 : enat).dom) : (1 : enat).get h = 1 := rfl lemma dom_of_le_of_dom {x y : enat} : x ≤ y → y.dom → x.dom := λ ⟨h, _⟩, h lemma dom_of_le_some {x : enat} {y : ℕ} (h : x ≤ y) : x.dom := dom_of_le_of_dom h trivial instance decidable_le (x y : enat) [decidable x.dom] [decidable y.dom] : decidable (x ≤ y) := if hx : x.dom then decidable_of_decidable_of_iff (show decidable (∀ (hy : (y : enat).dom), x.get hx ≤ (y : enat).get hy), from forall_prop_decidable _) $ by { dsimp [(≤)], simp only [hx, exists_prop_of_true, forall_true_iff] } else if hy : y.dom then is_false $ λ h, hx $ dom_of_le_of_dom h hy else is_true ⟨λ h, (hy h).elim, λ h, (hy h).elim⟩ /-- The coercion `ℕ → enat` preserves `0` and addition. -/ def coe_hom : ℕ →+ enat := ⟨coe, enat.coe_zero, enat.coe_add⟩ instance : partial_order enat := { le := (≤), le_refl := λ x, ⟨id, λ _, le_refl _⟩, le_trans := λ x y z ⟨hxy₁, hxy₂⟩ ⟨hyz₁, hyz₂⟩, ⟨hxy₁ ∘ hyz₁, λ _, le_trans (hxy₂ _) (hyz₂ _)⟩, le_antisymm := λ x y ⟨hxy₁, hxy₂⟩ ⟨hyx₁, hyx₂⟩, part.ext' ⟨hyx₁, hxy₁⟩ (λ _ _, le_antisymm (hxy₂ _) (hyx₂ _)) } lemma lt_def (x y : enat) : x < y ↔ ∃ (hx : x.dom), ∀ (hy : y.dom), x.get hx < y.get hy := begin rw [lt_iff_le_not_le, le_def, le_def, not_exists], split, { rintro ⟨⟨hyx, H⟩, h⟩, by_cases hx : x.dom, { use hx, intro hy, specialize H hy, specialize h (λ _, hy), rw not_forall at h, cases h with hx' h, rw not_le at h, exact h }, { specialize h (λ hx', (hx hx').elim), rw not_forall at h, cases h with hx' h, exact (hx hx').elim } }, { rintro ⟨hx, H⟩, exact ⟨⟨λ _, hx, λ hy, (H hy).le⟩, λ hxy h, not_lt_of_le (h _) (H _)⟩ } end @[simp, norm_cast] lemma coe_le_coe {x y : ℕ} : (x : enat) ≤ y ↔ x ≤ y := ⟨λ ⟨_, h⟩, h trivial, λ h, ⟨λ _, trivial, λ _, h⟩⟩ @[simp, norm_cast] lemma coe_lt_coe {x y : ℕ} : (x : enat) < y ↔ x < y := by rw [lt_iff_le_not_le, lt_iff_le_not_le, coe_le_coe, coe_le_coe] @[simp] lemma get_le_get {x y : enat} {hx : x.dom} {hy : y.dom} : x.get hx ≤ y.get hy ↔ x ≤ y := by conv { to_lhs, rw [← coe_le_coe, coe_get, coe_get]} lemma le_coe_iff (x : enat) (n : ℕ) : x ≤ n ↔ ∃ h : x.dom, x.get h ≤ n := begin show (∃ (h : true → x.dom), _) ↔ ∃ h : x.dom, x.get h ≤ n, simp only [forall_prop_of_true, dom_coe, get_coe'], split; rintro ⟨_, _⟩; refine ⟨_, _⟩; intros; try { assumption } end lemma lt_coe_iff (x : enat) (n : ℕ) : x < n ↔ ∃ h : x.dom, x.get h < n := by simp only [lt_def, forall_prop_of_true, get_coe', dom_coe] lemma coe_le_iff (n : ℕ) (x : enat) : (n : enat) ≤ x ↔ ∀ h : x.dom, n ≤ x.get h := by simpa only [le_def, exists_prop_of_true, dom_coe, forall_true_iff] using iff.rfl lemma coe_lt_iff (n : ℕ) (x : enat) : (n : enat) < x ↔ ∀ h : x.dom, n < x.get h := by simpa only [lt_def, exists_prop_of_true, dom_coe] using iff.rfl protected lemma zero_lt_one : (0 : enat) < 1 := by { norm_cast, norm_num } instance semilattice_sup_bot : semilattice_sup_bot enat := { sup := (⊔), bot := (⊥), bot_le := λ _, ⟨λ _, trivial, λ _, nat.zero_le _⟩, le_sup_left := λ _ _, ⟨and.left, λ _, le_sup_left⟩, le_sup_right := λ _ _, ⟨and.right, λ _, le_sup_right⟩, sup_le := λ x y z ⟨hx₁, hx₂⟩ ⟨hy₁, hy₂⟩, ⟨λ hz, ⟨hx₁ hz, hy₁ hz⟩, λ _, sup_le (hx₂ _) (hy₂ _)⟩, ..enat.partial_order } instance order_top : order_top enat := { top := (⊤), le_top := λ x, ⟨λ h, false.elim h, λ hy, false.elim hy⟩, ..enat.semilattice_sup_bot } lemma dom_of_lt {x y : enat} : x < y → x.dom := enat.cases_on x not_top_lt $ λ _ _, trivial lemma top_eq_none : (⊤ : enat) = none := rfl @[simp] lemma coe_lt_top (x : ℕ) : (x : enat) < ⊤ := lt_of_le_of_ne le_top (λ h, absurd (congr_arg dom h) true_ne_false) @[simp] lemma coe_ne_top (x : ℕ) : (x : enat) ≠ ⊤ := ne_of_lt (coe_lt_top x) lemma ne_top_iff {x : enat} : x ≠ ⊤ ↔ ∃(n : ℕ), x = n := part.ne_none_iff lemma ne_top_iff_dom {x : enat} : x ≠ ⊤ ↔ x.dom := by classical; exact not_iff_comm.1 part.eq_none_iff'.symm lemma ne_top_of_lt {x y : enat} (h : x < y) : x ≠ ⊤ := ne_of_lt $ lt_of_lt_of_le h le_top lemma eq_top_iff_forall_lt (x : enat) : x = ⊤ ↔ ∀ n : ℕ, (n : enat) < x := begin split, { rintro rfl n, exact coe_lt_top _ }, { contrapose!, rw ne_top_iff, rintro ⟨n, rfl⟩, exact ⟨n, irrefl _⟩ } end lemma eq_top_iff_forall_le (x : enat) : x = ⊤ ↔ ∀ n : ℕ, (n : enat) ≤ x := (eq_top_iff_forall_lt x).trans ⟨λ h n, (h n).le, λ h n, lt_of_lt_of_le (coe_lt_coe.mpr n.lt_succ_self) (h (n + 1))⟩ lemma pos_iff_one_le {x : enat} : 0 < x ↔ 1 ≤ x := enat.cases_on x ⟨λ _, le_top, λ _, coe_lt_top _⟩ (λ n, ⟨λ h, enat.coe_le_coe.2 (enat.coe_lt_coe.1 h), λ h, enat.coe_lt_coe.2 (enat.coe_le_coe.1 h)⟩) noncomputable instance : linear_order enat := { le_total := λ x y, enat.cases_on x (or.inr le_top) (enat.cases_on y (λ _, or.inl le_top) (λ x y, (le_total x y).elim (or.inr ∘ coe_le_coe.2) (or.inl ∘ coe_le_coe.2))), decidable_le := classical.dec_rel _, ..enat.partial_order } noncomputable instance : bounded_lattice enat := { inf := min, inf_le_left := min_le_left, inf_le_right := min_le_right, le_inf := λ _ _ _, le_min, ..enat.order_top, ..enat.semilattice_sup_bot } lemma sup_eq_max {a b : enat} : a ⊔ b = max a b := le_antisymm (sup_le (le_max_left _ _) (le_max_right _ _)) (max_le le_sup_left le_sup_right) lemma inf_eq_min {a b : enat} : a ⊓ b = min a b := rfl instance : ordered_add_comm_monoid enat := { add_le_add_left := λ a b ⟨h₁, h₂⟩ c, enat.cases_on c (by simp) (λ c, ⟨λ h, and.intro trivial (h₁ h.2), λ _, add_le_add_left (h₂ _) c⟩), ..enat.linear_order, ..enat.add_comm_monoid } instance : canonically_ordered_add_monoid enat := { le_iff_exists_add := λ a b, enat.cases_on b (iff_of_true le_top ⟨⊤, (add_top _).symm⟩) (λ b, enat.cases_on a (iff_of_false (not_le_of_gt (coe_lt_top _)) (not_exists.2 (λ x, ne_of_lt (by rw [top_add]; exact coe_lt_top _)))) (λ a, ⟨λ h, ⟨(b - a : ℕ), by rw [← coe_add, coe_inj, add_comm, nat.sub_add_cancel (coe_le_coe.1 h)]⟩, (λ ⟨c, hc⟩, enat.cases_on c (λ hc, hc.symm ▸ show (a : enat) ≤ a + ⊤, by rw [add_top]; exact le_top) (λ c (hc : (b : enat) = a + c), coe_le_coe.2 (by rw [← coe_add, coe_inj] at hc; rw hc; exact nat.le_add_right _ _)) hc)⟩)), ..enat.semilattice_sup_bot, ..enat.ordered_add_comm_monoid } protected lemma add_lt_add_right {x y z : enat} (h : x < y) (hz : z ≠ ⊤) : x + z < y + z := begin 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 enat.cases_on with n, { rw [top_add], apply_mod_cast coe_lt_top }, norm_cast at h, apply_mod_cast add_lt_add_right h end protected lemma add_lt_add_iff_right {x y z : enat} (hz : z ≠ ⊤) : x + z < y + z ↔ x < y := ⟨lt_of_add_lt_add_right, λ h, enat.add_lt_add_right h hz⟩ protected lemma add_lt_add_iff_left {x y z : enat} (hz : z ≠ ⊤) : z + x < z + y ↔ x < y := by rw [add_comm z, add_comm z, enat.add_lt_add_iff_right hz] protected lemma lt_add_iff_pos_right {x y : enat} (hx : x ≠ ⊤) : x < x + y ↔ 0 < y := by { conv_rhs { rw [← enat.add_lt_add_iff_left hx] }, rw [add_zero] } lemma lt_add_one {x : enat} (hx : x ≠ ⊤) : x < x + 1 := by { rw [enat.lt_add_iff_pos_right hx], norm_cast, norm_num } lemma le_of_lt_add_one {x y : enat} (h : x < y + 1) : x ≤ y := begin induction y using enat.cases_on with n, apply le_top, rcases ne_top_iff.mp (ne_top_of_lt h) with ⟨m, rfl⟩, apply_mod_cast nat.le_of_lt_succ, apply_mod_cast h end lemma add_one_le_of_lt {x y : enat} (h : x < y) : x + 1 ≤ y := begin induction y using enat.cases_on with n, apply le_top, rcases ne_top_iff.mp (ne_top_of_lt h) with ⟨m, rfl⟩, apply_mod_cast nat.succ_le_of_lt, apply_mod_cast h end lemma add_one_le_iff_lt {x y : enat} (hx : x ≠ ⊤) : x + 1 ≤ y ↔ x < y := begin split, swap, exact add_one_le_of_lt, intro h, rcases ne_top_iff.mp hx with ⟨m, rfl⟩, induction y using enat.cases_on with n, apply coe_lt_top, apply_mod_cast nat.lt_of_succ_le, apply_mod_cast h end lemma lt_add_one_iff_lt {x y : enat} (hx : x ≠ ⊤) : x < y + 1 ↔ x ≤ y := begin split, exact le_of_lt_add_one, intro h, rcases ne_top_iff.mp hx with ⟨m, rfl⟩, induction y using enat.cases_on with n, { rw [top_add], apply coe_lt_top }, apply_mod_cast nat.lt_succ_of_le, apply_mod_cast h end lemma add_eq_top_iff {a b : enat} : a + b = ⊤ ↔ a = ⊤ ∨ b = ⊤ := by apply enat.cases_on a; apply enat.cases_on b; simp; simp only [(enat.coe_add _ _).symm, enat.coe_ne_top]; simp protected lemma add_right_cancel_iff {a b c : enat} (hc : c ≠ ⊤) : a + c = b + c ↔ a = b := begin rcases ne_top_iff.1 hc with ⟨c, rfl⟩, apply enat.cases_on a; apply enat.cases_on b; simp [add_eq_top_iff, coe_ne_top, @eq_comm _ (⊤ : enat)]; simp only [(enat.coe_add _ _).symm, add_left_cancel_iff, enat.coe_inj, add_comm]; tauto end protected lemma add_left_cancel_iff {a b c : enat} (ha : a ≠ ⊤) : a + b = a + c ↔ b = c := by rw [add_comm a, add_comm a, enat.add_right_cancel_iff ha] section with_top /-- Computably converts an `enat` to a `with_top ℕ`. -/ def to_with_top (x : enat) [decidable x.dom] : with_top ℕ := x.to_option lemma to_with_top_top : to_with_top ⊤ = ⊤ := rfl @[simp] lemma to_with_top_top' {h : decidable (⊤ : enat).dom} : to_with_top ⊤ = ⊤ := by convert to_with_top_top lemma to_with_top_zero : to_with_top 0 = 0 := rfl @[simp] lemma to_with_top_zero' {h : decidable (0 : enat).dom} : to_with_top 0 = 0 := by convert to_with_top_zero lemma to_with_top_coe (n : ℕ) : to_with_top n = n := rfl @[simp] lemma to_with_top_coe' (n : ℕ) {h : decidable (n : enat).dom} : to_with_top (n : enat) = n := by convert to_with_top_coe n @[simp] lemma to_with_top_le {x y : enat} : Π [decidable x.dom] [decidable y.dom], by exactI to_with_top x ≤ to_with_top y ↔ x ≤ y := enat.cases_on y (by simp) (enat.cases_on x (by simp) (by intros; simp)) @[simp] lemma to_with_top_lt {x y : enat} [decidable x.dom] [decidable y.dom] : to_with_top x < to_with_top y ↔ x < y := lt_iff_lt_of_le_iff_le to_with_top_le end with_top section with_top_equiv open_locale classical @[simp] lemma to_with_top_add {x y : enat} : to_with_top (x + y) = to_with_top x + to_with_top y := begin apply enat.cases_on y; apply enat.cases_on x, { simp }, { simp }, { simp }, -- not sure why `simp` can't do this { intros, rw [to_with_top_coe', to_with_top_coe'], norm_cast, exact to_with_top_coe' _ } end /-- `equiv` between `enat` and `with_top ℕ` (for the order isomorphism see `with_top_order_iso`). -/ noncomputable def with_top_equiv : enat ≃ with_top ℕ := { to_fun := λ x, to_with_top x, inv_fun := λ x, match x with (some n) := coe n | none := ⊤ end, left_inv := λ x, by apply enat.cases_on x; intros; simp; refl, right_inv := λ x, by cases x; simp [with_top_equiv._match_1]; refl } @[simp] lemma with_top_equiv_top : with_top_equiv ⊤ = ⊤ := to_with_top_top' @[simp] lemma with_top_equiv_coe (n : nat) : with_top_equiv n = n := to_with_top_coe' _ @[simp] lemma with_top_equiv_zero : with_top_equiv 0 = 0 := with_top_equiv_coe _ @[simp] lemma with_top_equiv_le {x y : enat} : with_top_equiv x ≤ with_top_equiv y ↔ x ≤ y := to_with_top_le @[simp] lemma with_top_equiv_lt {x y : enat} : with_top_equiv x < with_top_equiv y ↔ x < y := to_with_top_lt /-- `to_with_top` induces an order isomorphism between `enat` and `with_top ℕ`. -/ noncomputable def with_top_order_iso : enat ≃o with_top ℕ := { map_rel_iff' := λ _ _, with_top_equiv_le, .. with_top_equiv} @[simp] lemma with_top_equiv_symm_top : with_top_equiv.symm ⊤ = ⊤ := rfl @[simp] lemma with_top_equiv_symm_coe (n : nat) : with_top_equiv.symm n = n := rfl @[simp] lemma with_top_equiv_symm_zero : with_top_equiv.symm 0 = 0 := rfl @[simp] lemma with_top_equiv_symm_le {x y : with_top ℕ} : with_top_equiv.symm x ≤ with_top_equiv.symm y ↔ x ≤ y := by rw ← with_top_equiv_le; simp @[simp] lemma with_top_equiv_symm_lt {x y : with_top ℕ} : with_top_equiv.symm x < with_top_equiv.symm y ↔ x < y := by rw ← with_top_equiv_lt; simp /-- `to_with_top` induces an additive monoid isomorphism between `enat` and `with_top ℕ`. -/ noncomputable def with_top_add_equiv : enat ≃+ with_top ℕ := { map_add' := λ x y, by simp only [with_top_equiv]; convert to_with_top_add, ..with_top_equiv} end with_top_equiv lemma lt_wf : well_founded ((<) : enat → enat → Prop) := show well_founded (λ a b : enat, a < b), by haveI := classical.dec; simp only [to_with_top_lt.symm] {eta := ff}; exact inv_image.wf _ (with_top.well_founded_lt nat.lt_wf) instance : has_well_founded enat := ⟨(<), lt_wf⟩ section find variables (P : ℕ → Prop) [decidable_pred P] /-- The smallest `enat` satisfying a (decidable) predicate `P : ℕ → Prop` -/ def find : enat := ⟨∃ n, P n, nat.find⟩ @[simp] lemma find_get (h : (find P).dom) : (find P).get h = nat.find h := rfl lemma find_dom (h : ∃ n, P n) : (find P).dom := h lemma lt_find (n : ℕ) (h : ∀ m ≤ n, ¬P m) : (n : enat) < find P := begin rw coe_lt_iff, intro h', rw find_get, have := @nat.find_spec P _ h', contrapose! this, exact h _ this end lemma lt_find_iff (n : ℕ) : (n : enat) < find P ↔ (∀ m ≤ n, ¬P m) := begin refine ⟨_, lt_find P n⟩, intros 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 } end lemma find_le (n : ℕ) (h : P n) : find P ≤ n := by { rw le_coe_iff, refine ⟨⟨_, h⟩, @nat.find_min' P _ _ _ h⟩ } lemma find_eq_top_iff : find P = ⊤ ↔ ∀ n, ¬P n := (eq_top_iff_forall_lt _).trans ⟨λ h n, (lt_find_iff P n).mp (h n) _ le_rfl, λ h n, lt_find P n $ λ _ _, h _⟩ end find noncomputable instance : linear_ordered_add_comm_monoid_with_top enat := { top_add' := top_add, .. enat.linear_order, .. enat.ordered_add_comm_monoid, .. enat.order_top } end enat
e7531e47af11c7c859cd7ff31ffdd442c6bd5c82
2a70b774d16dbdf5a533432ee0ebab6838df0948
/_target/deps/mathlib/src/algebra/algebra/operations.lean
9562a93fd44d97214c0d52d8cc1db09f1556be38
[ "Apache-2.0" ]
permissive
hjvromen/lewis
40b035973df7c77ebf927afab7878c76d05ff758
105b675f73630f028ad5d890897a51b3c1146fb0
refs/heads/master
1,677,944,636,343
1,676,555,301,000
1,676,555,301,000
327,553,599
0
0
null
null
null
null
UTF-8
Lean
false
false
12,177
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import algebra.algebra.basic /-! # Multiplication and division of submodules of an algebra. An interface for multiplication and division of sub-R-modules of an R-algebra A is developed. ## Main definitions Let `R` be a commutative ring (or semiring) and aet `A` be an `R`-algebra. * `1 : submodule R A` : the R-submodule R of the R-algebra A * `has_mul (submodule R A)` : multiplication of two sub-R-modules M and N of A is defined to be the smallest submodule containing all the products `m * n`. * `has_div (submodule R A)` : `I / J` is defined to be the submodule consisting of all `a : A` such that `a • J ⊆ I` It is proved that `submodule R A` is a semiring, and also an algebra over `set A`. ## Tags multiplication of submodules, division of subodules, submodule semiring -/ universes u v open algebra set namespace submodule variables {R : Type u} [comm_semiring R] section ring variables {A : Type v} [semiring A] [algebra R A] variables (S T : set A) {M N P Q : submodule R A} {m n : A} /-- `1 : submodule R A` is the submodule R of A. -/ instance : has_one (submodule R A) := ⟨submodule.map (of_id R A).to_linear_map (⊤ : submodule R R)⟩ theorem one_eq_map_top : (1 : submodule R A) = submodule.map (of_id R A).to_linear_map (⊤ : submodule R R) := rfl theorem one_eq_span : (1 : submodule R A) = R ∙ 1 := begin apply submodule.ext, intro a, erw [mem_map, mem_span_singleton], apply exists_congr, intro r, simpa [smul_def], end theorem one_le : (1 : submodule R A) ≤ P ↔ (1 : A) ∈ P := by simpa only [one_eq_span, span_le, set.singleton_subset_iff] /-- Multiplication of sub-R-modules of an R-algebra A. The submodule `M * N` is the smallest R-submodule of `A` containing the elements `m * n` for `m ∈ M` and `n ∈ N`. -/ instance : has_mul (submodule R A) := ⟨λ M N, ⨆ s : M, N.map $ algebra.lmul R A s.1⟩ theorem mul_mem_mul (hm : m ∈ M) (hn : n ∈ N) : m * n ∈ M * N := (le_supr _ ⟨m, hm⟩ : _ ≤ M * N) ⟨n, hn, rfl⟩ theorem mul_le : M * N ≤ P ↔ ∀ (m ∈ M) (n ∈ N), m * n ∈ P := ⟨λ H m hm n hn, H $ mul_mem_mul hm hn, λ H, supr_le $ λ ⟨m, hm⟩, map_le_iff_le_comap.2 $ λ n hn, H m hm n hn⟩ @[elab_as_eliminator] protected theorem mul_induction_on {C : A → Prop} {r : A} (hr : r ∈ M * N) (hm : ∀ (m ∈ M) (n ∈ N), C (m * n)) (h0 : C 0) (ha : ∀ x y, C x → C y → C (x + y)) (hs : ∀ (r : R) x, C x → C (r • x)) : C r := (@mul_le _ _ _ _ _ _ _ ⟨C, h0, ha, hs⟩).2 hm hr variables R theorem span_mul_span : span R S * span R T = span R (S * T) := begin apply le_antisymm, { rw mul_le, intros a ha b hb, apply span_induction ha, work_on_goal 0 { intros, apply span_induction hb, work_on_goal 0 { intros, exact subset_span ⟨_, _, ‹_›, ‹_›, rfl⟩ } }, all_goals { intros, simp only [mul_zero, zero_mul, zero_mem, left_distrib, right_distrib, mul_smul_comm, smul_mul_assoc], try {apply add_mem _ _ _}, try {apply smul_mem _ _ _} }, assumption' }, { rw span_le, rintros _ ⟨a, b, ha, hb, rfl⟩, exact mul_mem_mul (subset_span ha) (subset_span hb) } end variables {R} variables (M N P Q) protected theorem mul_assoc : (M * N) * P = M * (N * P) := le_antisymm (mul_le.2 $ λ mn hmn p hp, suffices M * N ≤ (M * (N * P)).comap (algebra.lmul_right R p), from this hmn, mul_le.2 $ λ m hm n hn, show m * n * p ∈ M * (N * P), from (mul_assoc m n p).symm ▸ mul_mem_mul hm (mul_mem_mul hn hp)) (mul_le.2 $ λ m hm np hnp, suffices N * P ≤ (M * N * P).comap (algebra.lmul_left R m), from this hnp, mul_le.2 $ λ n hn p hp, show m * (n * p) ∈ M * N * P, from mul_assoc m n p ▸ mul_mem_mul (mul_mem_mul hm hn) hp) @[simp] theorem mul_bot : M * ⊥ = ⊥ := eq_bot_iff.2 $ mul_le.2 $ λ m hm n hn, by rw [submodule.mem_bot] at hn ⊢; rw [hn, mul_zero] @[simp] theorem bot_mul : ⊥ * M = ⊥ := eq_bot_iff.2 $ mul_le.2 $ λ m hm n hn, by rw [submodule.mem_bot] at hm ⊢; rw [hm, zero_mul] @[simp] protected theorem one_mul : (1 : submodule R A) * M = M := by { conv_lhs { rw [one_eq_span, ← span_eq M] }, erw [span_mul_span, one_mul, span_eq] } @[simp] protected theorem mul_one : M * 1 = M := by { conv_lhs { rw [one_eq_span, ← span_eq M] }, erw [span_mul_span, mul_one, span_eq] } variables {M N P Q} @[mono] theorem mul_le_mul (hmp : M ≤ P) (hnq : N ≤ Q) : M * N ≤ P * Q := mul_le.2 $ λ m hm n hn, mul_mem_mul (hmp hm) (hnq hn) theorem mul_le_mul_left (h : M ≤ N) : M * P ≤ N * P := mul_le_mul h (le_refl P) theorem mul_le_mul_right (h : N ≤ P) : M * N ≤ M * P := mul_le_mul (le_refl M) h variables (M N P) theorem mul_sup : M * (N ⊔ P) = M * N ⊔ M * P := le_antisymm (mul_le.2 $ λ m hm np hnp, let ⟨n, hn, p, hp, hnp⟩ := mem_sup.1 hnp in mem_sup.2 ⟨_, mul_mem_mul hm hn, _, mul_mem_mul hm hp, hnp ▸ (mul_add m n p).symm⟩) (sup_le (mul_le_mul_right le_sup_left) (mul_le_mul_right le_sup_right)) theorem sup_mul : (M ⊔ N) * P = M * P ⊔ N * P := le_antisymm (mul_le.2 $ λ mn hmn p hp, let ⟨m, hm, n, hn, hmn⟩ := mem_sup.1 hmn in mem_sup.2 ⟨_, mul_mem_mul hm hp, _, mul_mem_mul hn hp, hmn ▸ (add_mul m n p).symm⟩) (sup_le (mul_le_mul_left le_sup_left) (mul_le_mul_left le_sup_right)) lemma mul_subset_mul : (↑M : set A) * (↑N : set A) ⊆ (↑(M * N) : set A) := by { rintros _ ⟨i, j, hi, hj, rfl⟩, exact mul_mem_mul hi hj } lemma map_mul {A'} [semiring A'] [algebra R A'] (f : A →ₐ[R] A') : map f.to_linear_map (M * N) = map f.to_linear_map M * map f.to_linear_map N := calc map f.to_linear_map (M * N) = ⨆ (i : M), (N.map (lmul R A i)).map f.to_linear_map : map_supr _ _ ... = map f.to_linear_map M * map f.to_linear_map N : begin apply congr_arg Sup, ext S, split; rintros ⟨y, hy⟩, { use [f y, mem_map.mpr ⟨y.1, y.2, rfl⟩], refine trans _ hy, ext, simp }, { obtain ⟨y', hy', fy_eq⟩ := mem_map.mp y.2, use [y', hy'], refine trans _ hy, rw f.to_linear_map_apply at fy_eq, ext, simp [fy_eq] } end variables {M N P} /-- Sub-R-modules of an R-algebra form a semiring. -/ instance : semiring (submodule R A) := { one_mul := submodule.one_mul, mul_one := submodule.mul_one, mul_assoc := submodule.mul_assoc, zero_mul := bot_mul, mul_zero := mul_bot, left_distrib := mul_sup, right_distrib := sup_mul, ..submodule.add_comm_monoid_submodule, ..submodule.has_one, ..submodule.has_mul } variables (M) lemma pow_subset_pow {n : ℕ} : (↑M : set A)^n ⊆ ↑(M^n : submodule R A) := begin induction n with n ih, { erw [pow_zero, pow_zero, set.singleton_subset_iff], rw [mem_coe, ← one_le], exact le_refl _ }, { rw [pow_succ, pow_succ], refine set.subset.trans (set.mul_subset_mul (subset.refl _) ih) _, apply mul_subset_mul } end /-- `span` is a semiring homomorphism (recall multiplication is pointwise multiplication of subsets on either side). -/ def span.ring_hom : set_semiring A →+* submodule R A := { to_fun := submodule.span R, map_zero' := span_empty, map_one' := le_antisymm (span_le.2 $ singleton_subset_iff.2 ⟨1, ⟨⟩, (algebra_map R A).map_one⟩) (map_le_iff_le_comap.2 $ λ r _, mem_span_singleton.2 ⟨r, (algebra_map_eq_smul_one r).symm⟩), map_add' := span_union, map_mul' := λ s t, by erw [span_mul_span, ← image_mul_prod] } end ring section comm_ring variables {A : Type v} [comm_semiring A] [algebra R A] variables {M N : submodule R A} {m n : A} theorem mul_mem_mul_rev (hm : m ∈ M) (hn : n ∈ N) : n * m ∈ M * N := mul_comm m n ▸ mul_mem_mul hm hn variables (M N) protected theorem mul_comm : M * N = N * M := le_antisymm (mul_le.2 $ λ r hrm s hsn, mul_mem_mul_rev hsn hrm) (mul_le.2 $ λ r hrn s hsm, mul_mem_mul_rev hsm hrn) /-- Sub-R-modules of an R-algebra A form a semiring. -/ instance : comm_semiring (submodule R A) := { mul_comm := submodule.mul_comm, .. submodule.semiring } variables (R A) /-- R-submodules of the R-algebra A are a module over `set A`. -/ instance semimodule_set : semimodule (set_semiring A) (submodule R A) := { smul := λ s P, span R s * P, smul_add := λ _ _ _, mul_add _ _ _, add_smul := λ s t P, show span R (s ⊔ t) * P = _, by { erw [span_union, right_distrib] }, mul_smul := λ s t P, show _ = _ * (_ * _), by { rw [← mul_assoc, span_mul_span, ← image_mul_prod] }, one_smul := λ P, show span R {(1 : A)} * P = _, by { conv_lhs {erw ← span_eq P}, erw [span_mul_span, one_mul, span_eq] }, zero_smul := λ P, show span R ∅ * P = ⊥, by erw [span_empty, bot_mul], smul_zero := λ _, mul_bot _ } variables {R A} lemma smul_def {s : set_semiring A} {P : submodule R A} : s • P = span R s * P := rfl lemma smul_le_smul {s t : set_semiring A} {M N : submodule R A} (h₁ : s.down ≤ t.down) (h₂ : M ≤ N) : s • M ≤ t • N := mul_le_mul (span_mono h₁) h₂ lemma smul_singleton (a : A) (M : submodule R A) : ({a} : set A).up • M = M.map (lmul_left _ a) := begin conv_lhs {rw ← span_eq M}, change span _ _ * span _ _ = _, rw [span_mul_span], apply le_antisymm, { rw span_le, rintros _ ⟨b, m, hb, hm, rfl⟩, rw [mem_coe, mem_map, set.mem_singleton_iff.mp hb], exact ⟨m, hm, rfl⟩ }, { rintros _ ⟨m, hm, rfl⟩, exact subset_span ⟨a, m, set.mem_singleton a, hm, rfl⟩ } end section quotient /-- The elements of `I / J` are the `x` such that `x • J ⊆ I`. In fact, we define `x ∈ I / J` to be `∀ y ∈ J, x * y ∈ I` (see `mem_div_iff_forall_mul_mem`), which is equivalent to `x • J ⊆ I` (see `mem_div_iff_smul_subset`), but nicer to use in proofs. This is the general form of the ideal quotient, traditionally written $I : J$. -/ instance : has_div (submodule R A) := ⟨ λ I J, { carrier := { x | ∀ y ∈ J, x * y ∈ I }, zero_mem' := λ y hy, by { rw zero_mul, apply submodule.zero_mem }, add_mem' := λ a b ha hb y hy, by { rw add_mul, exact submodule.add_mem _ (ha _ hy) (hb _ hy) }, smul_mem' := λ r x hx y hy, by { rw algebra.smul_mul_assoc, exact submodule.smul_mem _ _ (hx _ hy) } } ⟩ lemma mem_div_iff_forall_mul_mem {x : A} {I J : submodule R A} : x ∈ I / J ↔ ∀ y ∈ J, x * y ∈ I := iff.refl _ lemma mem_div_iff_smul_subset {x : A} {I J : submodule R A} : x ∈ I / J ↔ x • (J : set A) ⊆ I := ⟨ λ h y ⟨y', hy', xy'_eq_y⟩, by { rw ← xy'_eq_y, apply h, assumption }, λ h y hy, h (set.smul_mem_smul_set hy) ⟩ lemma le_div_iff {I J K : submodule R A} : I ≤ J / K ↔ ∀ (x ∈ I) (z ∈ K), x * z ∈ J := iff.refl _ lemma le_div_iff_mul_le {I J K : submodule R A} : I ≤ J / K ↔ I * K ≤ J := by rw [le_div_iff, mul_le] @[simp] lemma one_le_one_div {I : submodule R A} : 1 ≤ 1 / I ↔ I ≤ 1 := begin split, all_goals {intro hI}, {rwa [le_div_iff_mul_le, one_mul] at hI}, {rwa [le_div_iff_mul_le, one_mul]}, end lemma le_self_mul_one_div {I : submodule R A} (hI : I ≤ 1) : I ≤ I * (1 / I) := begin rw [← mul_one I] {occs := occurrences.pos [1]}, apply mul_le_mul_right (one_le_one_div.mpr hI), end lemma mul_one_div_le_one {I : submodule R A} : I * (1 / I) ≤ 1 := begin rw submodule.mul_le, intros m hm n hn, rw [submodule.mem_div_iff_forall_mul_mem] at hn, rw mul_comm, exact hn m hm, end @[simp] lemma map_div {B : Type*} [comm_ring B] [algebra R B] (I J : submodule R A) (h : A ≃ₐ[R] B) : (I / J).map h.to_linear_map = I.map h.to_linear_map / J.map h.to_linear_map := begin ext x, simp only [mem_map, mem_div_iff_forall_mul_mem], split, { rintro ⟨x, hx, rfl⟩ _ ⟨y, hy, rfl⟩, exact ⟨x * y, hx _ hy, h.map_mul x y⟩ }, { rintro hx, refine ⟨h.symm x, λ z hz, _, h.apply_symm_apply x⟩, obtain ⟨xz, xz_mem, hxz⟩ := hx (h z) ⟨z, hz, rfl⟩, convert xz_mem, apply h.injective, erw [h.map_mul, h.apply_symm_apply, hxz] } end end quotient end comm_ring end submodule
16c20f5b918ab88c773f066cea1186cf2f1c7797
d1a52c3f208fa42c41df8278c3d280f075eb020c
/stage0/src/Lean/Compiler/ExternAttr.lean
c61be64b25a74a0ba0f0e627e9ee2c78bf01361f
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
5,984
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Expr import Lean.Environment import Lean.Attributes import Lean.ProjFns import Lean.Meta.Basic namespace Lean inductive ExternEntry where | adhoc (backend : Name) | inline (backend : Name) (pattern : String) | standard (backend : Name) (fn : String) | foreign (backend : Name) (fn : String) /- - `@[extern]` encoding: ```.entries = [adhoc `all]``` - `@[extern "level_hash"]` encoding: ```.entries = [standard `all "levelHash"]``` - `@[extern cpp "lean::string_size" llvm "lean_str_size"]` encoding: ```.entries = [standard `cpp "lean::string_size", standard `llvm "leanStrSize"]``` - `@[extern cpp inline "#1 + #2"]` encoding: ```.entries = [inline `cpp "#1 + #2"]``` - `@[extern cpp "foo" llvm adhoc]` encoding: ```.entries = [standard `cpp "foo", adhoc `llvm]``` - `@[extern 2 cpp "io_prim_println"]` encoding: ```.arity? = 2, .entries = [standard `cpp "ioPrimPrintln"]``` -/ structure ExternAttrData where arity? : Option Nat := none entries : List ExternEntry deriving Inhabited -- def externEntry := leading_parser optional ident >> optional (nonReservedSymbol "inline ") >> strLit -- @[builtinAttrParser] def extern := leading_parser nonReservedSymbol "extern " >> optional numLit >> many externEntry private def syntaxToExternAttrData (stx : Syntax) : AttrM ExternAttrData := do let arity? := if stx[1].isNone then none else some <| stx[1][0].isNatLit?.getD 0 let entriesStx := stx[2].getArgs if entriesStx.size == 0 && arity? == none then return { entries := [ ExternEntry.adhoc `all ] } let mut entries := #[] for entryStx in entriesStx do let backend := if entryStx[0].isNone then `all else entryStx[0][0].getId let str ← match entryStx[2].isStrLit? with | none => throwErrorAt entryStx[2] "string literal expected" | some str => pure str if entryStx[1].isNone then entries := entries.push <| ExternEntry.standard backend str else entries := entries.push <| ExternEntry.inline backend str return { arity? := arity?, entries := entries.toList } @[extern "lean_add_extern"] constant addExtern (env : Environment) (n : Name) : ExceptT String Id Environment builtin_initialize externAttr : ParametricAttribute ExternAttrData ← registerParametricAttribute { name := `extern descr := "builtin and foreign functions" getParam := fun _ stx => syntaxToExternAttrData stx afterSet := fun declName _ => do let mut env ← getEnv if env.isProjectionFn declName || env.isConstructor declName then do env ← ofExcept $ addExtern env declName setEnv env else pure () } @[export lean_get_extern_attr_data] def getExternAttrData (env : Environment) (n : Name) : Option ExternAttrData := externAttr.getParam env n private def parseOptNum : Nat → String.Iterator → Nat → String.Iterator × Nat | 0, it, r => (it, r) | n+1, it, r => if !it.hasNext then (it, r) else let c := it.curr if '0' <= c && c <= '9' then parseOptNum n it.next (r*10 + (c.toNat - '0'.toNat)) else (it, r) def expandExternPatternAux (args : List String) : Nat → String.Iterator → String → String | 0, it, r => r | i+1, it, r => if ¬ it.hasNext then r else let c := it.curr if c ≠ '#' then expandExternPatternAux args i it.next (r.push c) else let it := it.next let (it, j) := parseOptNum it.remainingBytes it 0 let j := j-1 expandExternPatternAux args i it (r ++ args.getD j "") def expandExternPattern (pattern : String) (args : List String) : String := expandExternPatternAux args pattern.length pattern.mkIterator "" def mkSimpleFnCall (fn : String) (args : List String) : String := fn ++ "(" ++ ((args.intersperse ", ").foldl (·++·) "") ++ ")" def ExternEntry.backend : ExternEntry → Name | ExternEntry.adhoc n => n | ExternEntry.inline n _ => n | ExternEntry.standard n _ => n | ExternEntry.foreign n _ => n def getExternEntryForAux (backend : Name) : List ExternEntry → Option ExternEntry | [] => none | e::es => if e.backend == `all then some e else if e.backend == backend then some e else getExternEntryForAux backend es def getExternEntryFor (d : ExternAttrData) (backend : Name) : Option ExternEntry := getExternEntryForAux backend d.entries def isExtern (env : Environment) (fn : Name) : Bool := getExternAttrData env fn |>.isSome /- We say a Lean function marked as `[extern "<c_fn_nane>"]` is for all backends, and it is implemented using `extern "C"`. Thus, there is no name mangling. -/ def isExternC (env : Environment) (fn : Name) : Bool := match getExternAttrData env fn with | some { entries := [ ExternEntry.standard `all _ ], .. } => true | _ => false def getExternNameFor (env : Environment) (backend : Name) (fn : Name) : Option String := OptionM.run do let data ← getExternAttrData env fn let entry ← getExternEntryFor data backend match entry with | ExternEntry.standard _ n => pure n | ExternEntry.foreign _ n => pure n | _ => failure def getExternConstArity (declName : Name) : CoreM (Option Nat) := do let env ← getEnv match getExternAttrData env declName with | none => pure none | some data => match data.arity? with | some arity => pure arity | none => let cinfo ← getConstInfo declName let (arity, _) ← (Meta.forallTelescopeReducing cinfo.type fun xs _ => pure xs.size : MetaM Nat).run pure (some arity) @[export lean_get_extern_const_arity] def getExternConstArityExport (env : Environment) (declName : Name) : IO (Option Nat) := do try let (arity?, _) ← (getExternConstArity declName).toIO {} { env := env } pure arity? catch _ => pure none end Lean
2e03bb6a5994269f205e69a72e56dfe7cc2f28f7
e898bfefd5cb60a60220830c5eba68cab8d02c79
/uexp/src/uexp/rules/removeSemiJoinRightWithFilter.lean
fb482878ea85e88bf2c66f7fe9b28d51f1a7cf00
[ "BSD-2-Clause" ]
permissive
kkpapa/Cosette
9ed09e2dc4c1ecdef815c30b5501f64a7383a2ce
fda8fdbbf0de6c1be9b4104b87bbb06cede46329
refs/heads/master
1,584,573,128,049
1,526,370,422,000
1,526,370,422,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,777
lean
import ..sql import ..tactics import ..u_semiring import ..extra_constants import ..ucongr import ..TDP set_option profiler true open Expr open Proj open Pred open SQL open tree notation `int` := datatypes.int constant str_foo_: const int. theorem rule: forall ( Γ scm_dept scm_emp: Schema) (rel_dept: relation scm_dept) (rel_emp: relation scm_emp) (dept_deptno : Column int scm_dept) (dept_name : Column int scm_dept) (emp_empno : Column int scm_emp) (emp_ename : Column int scm_emp) (emp_job : Column int scm_emp) (emp_mgr : Column int scm_emp) (emp_hiredate : Column int scm_emp) (emp_comm : Column int scm_emp) (emp_sal : Column int scm_emp) (emp_deptno : Column int scm_emp) (emp_slacker : Column int scm_emp), denoteSQL ((SELECT1 (right⋅left⋅emp_ename) (FROM1 (product (table rel_emp) (product (table rel_dept) (table rel_emp))) WHERE (and (and (equal (uvariable (right⋅left⋅emp_deptno)) (uvariable (right⋅right⋅left⋅dept_deptno))) (equal (uvariable (right⋅right⋅left⋅dept_deptno)) (uvariable (right⋅right⋅right⋅emp_deptno)))) (equal (uvariable (right⋅right⋅left⋅dept_name)) (constantExpr str_foo_))))) : SQL Γ _ ) = denoteSQL ((SELECT1 (right⋅left⋅emp_ename) (FROM1 (product (table rel_emp) (product ((SELECT * FROM1 (table rel_dept) WHERE (equal (uvariable (right⋅dept_name)) (constantExpr str_foo_)))) (table rel_emp))) WHERE (and (equal (uvariable (right⋅left⋅emp_deptno)) (uvariable (right⋅right⋅left⋅dept_deptno))) (equal (uvariable (right⋅right⋅left⋅dept_deptno)) (uvariable (right⋅right⋅right⋅emp_deptno)))))) : SQL Γ _) := begin intros, unfold_all_denotations, funext, print_size, simp, print_size, TDP' ucongr, end
0d2cf4e633a7fd449128f460716fae89700b880b
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/category_theory/category/pairwise.lean
de489d6ba6601425e826433d4547cbcf85608b53
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
4,293
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import order.complete_lattice import category_theory.category.preorder import category_theory.limits.is_limit /-! # The category of "pairwise intersections". Given `ι : Type v`, we build the diagram category `pairwise ι` with objects `single i` and `pair i j`, for `i j : ι`, whose only non-identity morphisms are `left : pair i j ⟶ single i` and `right : pair i j ⟶ single j`. We use this later in describing (one formulation of) the sheaf condition. Given any function `U : ι → α`, where `α` is some complete lattice (e.g. `(opens X)ᵒᵖ`), we produce a functor `pairwise ι ⥤ α` in the obvious way, and show that `supr U` provides a colimit cocone over this functor. -/ noncomputable theory universes v u open category_theory open category_theory.limits namespace category_theory /-- An inductive type representing either a single term of a type `ι`, or a pair of terms. We use this as the objects of a category to describe the sheaf condition. -/ inductive pairwise (ι : Type v) | single : ι → pairwise | pair : ι → ι → pairwise variables {ι : Type v} namespace pairwise instance pairwise_inhabited [inhabited ι] : inhabited (pairwise ι) := ⟨single default⟩ /-- Morphisms in the category `pairwise ι`. The only non-identity morphisms are `left i j : single i ⟶ pair i j` and `right i j : single j ⟶ pair i j`. -/ inductive hom : pairwise ι → pairwise ι → Type v | id_single : Π i, hom (single i) (single i) | id_pair : Π i j, hom (pair i j) (pair i j) | left : Π i j, hom (pair i j) (single i) | right : Π i j, hom (pair i j) (single j) open hom instance hom_inhabited [inhabited ι] : inhabited (hom (single (default : ι)) (single default)) := ⟨id_single default⟩ /-- The identity morphism in `pairwise ι`. -/ def id : Π (o : pairwise ι), hom o o | (single i) := id_single i | (pair i j) := id_pair i j /-- Composition of morphisms in `pairwise ι`. -/ def comp : Π {o₁ o₂ o₃ : pairwise ι} (f : hom o₁ o₂) (g : hom o₂ o₃), hom o₁ o₃ | _ _ _ (id_single i) g := g | _ _ _ (id_pair i j) g := g | _ _ _ (left i j) (id_single _) := left i j | _ _ _ (right i j) (id_single _) := right i j section local attribute [tidy] tactic.case_bash instance : category (pairwise ι) := { hom := hom, id := id, comp := λ X Y Z f g, comp f g, } end variables {α : Type v} (U : ι → α) section variables [semilattice_inf α] /-- Auxiliary definition for `diagram`. -/ @[simp] def diagram_obj : pairwise ι → α | (single i) := U i | (pair i j) := U i ⊓ U j /-- Auxiliary definition for `diagram`. -/ @[simp] def diagram_map : Π {o₁ o₂ : pairwise ι} (f : o₁ ⟶ o₂), diagram_obj U o₁ ⟶ diagram_obj U o₂ | _ _ (id_single i) := 𝟙 _ | _ _ (id_pair i j) := 𝟙 _ | _ _ (left i j) := hom_of_le inf_le_left | _ _ (right i j) := hom_of_le inf_le_right /-- Given a function `U : ι → α` for `[semilattice_inf α]`, we obtain a functor `pairwise ι ⥤ α`, sending `single i` to `U i` and `pair i j` to `U i ⊓ U j`, and the morphisms to the obvious inequalities. -/ @[simps] def diagram : pairwise ι ⥤ α := { obj := diagram_obj U, map := λ X Y f, diagram_map U f, } end section -- `complete_lattice` is not really needed, as we only ever use `inf`, -- but the appropriate structure has not been defined. variables [complete_lattice α] /-- Auxiliary definition for `cocone`. -/ def cocone_ι_app : Π (o : pairwise ι), diagram_obj U o ⟶ supr U | (single i) := hom_of_le (le_supr U i) | (pair i j) := hom_of_le inf_le_left ≫ hom_of_le (le_supr U i) /-- Given a function `U : ι → α` for `[complete_lattice α]`, `supr U` provides a cocone over `diagram U`. -/ @[simps] def cocone : cocone (diagram U) := { X := supr U, ι := { app := cocone_ι_app U, } } /-- Given a function `U : ι → α` for `[complete_lattice α]`, `infi U` provides a limit cone over `diagram U`. -/ def cocone_is_colimit : is_colimit (cocone U) := { desc := λ s, hom_of_le begin apply complete_lattice.Sup_le, rintros _ ⟨j, rfl⟩, exact (s.ι.app (single j)).le end } end end pairwise end category_theory
2dec4c0c3a5ae8decae125753a8bd823a83aacf9
4727251e0cd73359b15b664c3170e5d754078599
/src/order/atoms.lean
67113c02b85483ddcf490306229a2dc6265405a5
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
26,597
lean
/- Copyright (c) 2020 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import order.complete_boolean_algebra import order.cover import order.modular_lattice import data.fintype.basic /-! # Atoms, Coatoms, and Simple Lattices This module defines atoms, which are minimal non-`⊥` elements in bounded lattices, simple lattices, which are lattices with only two elements, and related ideas. ## Main definitions ### Atoms and Coatoms * `is_atom a` indicates that the only element below `a` is `⊥`. * `is_coatom a` indicates that the only element above `a` is `⊤`. ### Atomic and Atomistic Lattices * `is_atomic` indicates that every element other than `⊥` is above an atom. * `is_coatomic` indicates that every element other than `⊤` is below a coatom. * `is_atomistic` indicates that every element is the `Sup` of a set of atoms. * `is_coatomistic` indicates that every element is the `Inf` of a set of coatoms. ### Simple Lattices * `is_simple_order` indicates that an order has only two unique elements, `⊥` and `⊤`. * `is_simple_order.bounded_order` * `is_simple_order.distrib_lattice` * Given an instance of `is_simple_order`, we provide the following definitions. These are not made global instances as they contain data : * `is_simple_order.boolean_algebra` * `is_simple_order.complete_lattice` * `is_simple_order.complete_boolean_algebra` ## Main results * `is_atom_dual_iff_is_coatom` and `is_coatom_dual_iff_is_atom` express the (definitional) duality of `is_atom` and `is_coatom`. * `is_simple_order_iff_is_atom_top` and `is_simple_order_iff_is_coatom_bot` express the connection between atoms, coatoms, and simple lattices * `is_compl.is_atom_iff_is_coatom` and `is_compl.is_coatom_if_is_atom`: In a modular bounded lattice, a complement of an atom is a coatom and vice versa. * `is_atomic_iff_is_coatomic`: A modular complemented lattice is atomic iff it is coatomic. * `fintype.to_is_atomic`, `fintype.to_is_coatomic`: Finite partial orders with bottom resp. top are atomic resp. coatomic. -/ variable {α : Type*} section atoms section is_atom /-- An atom of an `order_bot` is an element with no other element between it and `⊥`, which is not `⊥`. -/ def is_atom [preorder α] [order_bot α] (a : α) : Prop := a ≠ ⊥ ∧ (∀ b, b < a → b = ⊥) variables [partial_order α] [order_bot α] {a b x : α} lemma eq_bot_or_eq_of_le_atom (ha : is_atom a) (hab : b ≤ a) : b = ⊥ ∨ b = a := hab.lt_or_eq.imp_left (ha.2 b) lemma is_atom.Iic (ha : is_atom a) (hax : a ≤ x) : is_atom (⟨a, hax⟩ : set.Iic x) := ⟨λ con, ha.1 (subtype.mk_eq_mk.1 con), λ ⟨b, hb⟩ hba, subtype.mk_eq_mk.2 (ha.2 b hba)⟩ lemma is_atom.of_is_atom_coe_Iic {a : set.Iic x} (ha : is_atom a) : is_atom (a : α) := ⟨λ con, ha.1 (subtype.ext con), λ b hba, subtype.mk_eq_mk.1 (ha.2 ⟨b, hba.le.trans a.prop⟩ hba)⟩ @[simp] lemma bot_covby_iff : ⊥ ⋖ a ↔ is_atom a := ⟨λ h, ⟨h.lt.ne', λ b hba, not_not.1 $ λ hb, h.2 (ne.bot_lt hb) hba⟩, λ h, ⟨h.1.bot_lt, λ b hb hba, hb.ne' $ h.2 _ hba⟩⟩ alias bot_covby_iff ↔ covby.is_atom is_atom.bot_covby end is_atom section is_coatom /-- A coatom of an `order_top` is an element with no other element between it and `⊤`, which is not `⊤`. -/ def is_coatom [preorder α] [order_top α] (a : α) : Prop := a ≠ ⊤ ∧ (∀ b, a < b → b = ⊤) variables [partial_order α] [order_top α] {a b x : α} lemma eq_top_or_eq_of_coatom_le (ha : is_coatom a) (hab : a ≤ b) : b = ⊤ ∨ b = a := hab.lt_or_eq.imp (ha.2 b) eq_comm.2 lemma is_coatom.Ici (ha : is_coatom a) (hax : x ≤ a) : is_coatom (⟨a, hax⟩ : set.Ici x) := ⟨λ con, ha.1 (subtype.mk_eq_mk.1 con), λ ⟨b, hb⟩ hba, subtype.mk_eq_mk.2 (ha.2 b hba)⟩ lemma is_coatom.of_is_coatom_coe_Ici {a : set.Ici x} (ha : is_coatom a) : is_coatom (a : α) := ⟨λ con, ha.1 (subtype.ext con), λ b hba, subtype.mk_eq_mk.1 (ha.2 ⟨b, le_trans a.prop hba.le⟩ hba)⟩ @[simp] lemma covby_top_iff : a ⋖ ⊤ ↔ is_coatom a := ⟨λ h, ⟨h.ne, λ b hab, not_not.1 $ λ hb, h.2 hab $ ne.lt_top hb⟩, λ h, ⟨h.1.lt_top, λ b hab hb, hb.ne $ h.2 _ hab⟩⟩ alias covby_top_iff ↔ covby.is_coatom is_coatom.covby_top end is_coatom section pairwise lemma is_atom.inf_eq_bot_of_ne [semilattice_inf α] [order_bot α] {a b : α} (ha : is_atom a) (hb : is_atom b) (hab : a ≠ b) : a ⊓ b = ⊥ := or.elim (eq_bot_or_eq_of_le_atom ha inf_le_left) id (λ h1, or.elim (eq_bot_or_eq_of_le_atom hb inf_le_right) id (λ h2, false.rec _ (hab (le_antisymm (inf_eq_left.mp h1) (inf_eq_right.mp h2))))) lemma is_atom.disjoint_of_ne [semilattice_inf α] [order_bot α] {a b : α} (ha : is_atom a) (hb : is_atom b) (hab : a ≠ b) : disjoint a b := disjoint_iff.mpr (is_atom.inf_eq_bot_of_ne ha hb hab) lemma is_coatom.sup_eq_top_of_ne [semilattice_sup α] [order_top α] {a b : α} (ha : is_coatom a) (hb : is_coatom b) (hab : a ≠ b) : a ⊔ b = ⊤ := or.elim (eq_top_or_eq_of_coatom_le ha le_sup_left) id (λ h1, or.elim (eq_top_or_eq_of_coatom_le hb le_sup_right) id (λ h2, false.rec _ (hab (le_antisymm (sup_eq_right.mp h2) (sup_eq_left.mp h1))))) end pairwise variables [preorder α] {a : α} @[simp] lemma is_coatom_dual_iff_is_atom [order_bot α] : is_coatom (order_dual.to_dual a) ↔ is_atom a := iff.rfl @[simp] lemma is_atom_dual_iff_is_coatom [order_top α] : is_atom (order_dual.to_dual a) ↔ is_coatom a := iff.rfl end atoms section atomic variables [partial_order α] (α) /-- A lattice is atomic iff every element other than `⊥` has an atom below it. -/ class is_atomic [order_bot α] : Prop := (eq_bot_or_exists_atom_le : ∀ (b : α), b = ⊥ ∨ ∃ (a : α), is_atom a ∧ a ≤ b) /-- A lattice is coatomic iff every element other than `⊤` has a coatom above it. -/ class is_coatomic [order_top α] : Prop := (eq_top_or_exists_le_coatom : ∀ (b : α), b = ⊤ ∨ ∃ (a : α), is_coatom a ∧ b ≤ a) export is_atomic (eq_bot_or_exists_atom_le) is_coatomic (eq_top_or_exists_le_coatom) variable {α} @[simp] lemma is_coatomic_dual_iff_is_atomic [order_bot α] : is_coatomic αᵒᵈ ↔ is_atomic α := ⟨λ h, ⟨λ b, by apply h.eq_top_or_exists_le_coatom⟩, λ h, ⟨λ b, by apply h.eq_bot_or_exists_atom_le⟩⟩ @[simp] lemma is_atomic_dual_iff_is_coatomic [order_top α] : is_atomic αᵒᵈ ↔ is_coatomic α := ⟨λ h, ⟨λ b, by apply h.eq_bot_or_exists_atom_le⟩, λ h, ⟨λ b, by apply h.eq_top_or_exists_le_coatom⟩⟩ namespace is_atomic variables [order_bot α] [is_atomic α] instance is_coatomic_dual : is_coatomic αᵒᵈ := is_coatomic_dual_iff_is_atomic.2 ‹is_atomic α› instance {x : α} : is_atomic (set.Iic x) := ⟨λ ⟨y, hy⟩, (eq_bot_or_exists_atom_le y).imp subtype.mk_eq_mk.2 (λ ⟨a, ha, hay⟩, ⟨⟨a, hay.trans hy⟩, ha.Iic (hay.trans hy), hay⟩)⟩ end is_atomic namespace is_coatomic variables [order_top α] [is_coatomic α] instance is_coatomic : is_atomic αᵒᵈ := is_atomic_dual_iff_is_coatomic.2 ‹is_coatomic α› instance {x : α} : is_coatomic (set.Ici x) := ⟨λ ⟨y, hy⟩, (eq_top_or_exists_le_coatom y).imp subtype.mk_eq_mk.2 (λ ⟨a, ha, hay⟩, ⟨⟨a, le_trans hy hay⟩, ha.Ici (le_trans hy hay), hay⟩)⟩ end is_coatomic theorem is_atomic_iff_forall_is_atomic_Iic [order_bot α] : is_atomic α ↔ ∀ (x : α), is_atomic (set.Iic x) := ⟨@is_atomic.set.Iic.is_atomic _ _ _, λ h, ⟨λ x, ((@eq_bot_or_exists_atom_le _ _ _ (h x)) (⊤ : set.Iic x)).imp subtype.mk_eq_mk.1 (exists_imp_exists' coe (λ ⟨a, ha⟩, and.imp_left (is_atom.of_is_atom_coe_Iic)))⟩⟩ theorem is_coatomic_iff_forall_is_coatomic_Ici [order_top α] : is_coatomic α ↔ ∀ (x : α), is_coatomic (set.Ici x) := is_atomic_dual_iff_is_coatomic.symm.trans $ is_atomic_iff_forall_is_atomic_Iic.trans $ forall_congr (λ x, is_coatomic_dual_iff_is_atomic.symm.trans iff.rfl) section well_founded lemma is_atomic_of_order_bot_well_founded_lt [order_bot α] (h : well_founded ((<) : α → α → Prop)) : is_atomic α := ⟨λ a, or_iff_not_imp_left.2 $ λ ha, let ⟨b, hb, hm⟩ := h.has_min { b | b ≠ ⊥ ∧ b ≤ a } ⟨a, ha, le_rfl⟩ in ⟨b, ⟨hb.1, λ c, not_imp_not.1 $ λ hc hl, hm c ⟨hc, hl.le.trans hb.2⟩ hl⟩, hb.2⟩⟩ lemma is_coatomic_of_order_top_gt_well_founded [order_top α] (h : well_founded ((>) : α → α → Prop)) : is_coatomic α := is_atomic_dual_iff_is_coatomic.1 (@is_atomic_of_order_bot_well_founded_lt αᵒᵈ _ _ h) end well_founded end atomic section atomistic variables (α) [complete_lattice α] /-- A lattice is atomistic iff every element is a `Sup` of a set of atoms. -/ class is_atomistic : Prop := (eq_Sup_atoms : ∀ (b : α), ∃ (s : set α), b = Sup s ∧ ∀ a, a ∈ s → is_atom a) /-- A lattice is coatomistic iff every element is an `Inf` of a set of coatoms. -/ class is_coatomistic : Prop := (eq_Inf_coatoms : ∀ (b : α), ∃ (s : set α), b = Inf s ∧ ∀ a, a ∈ s → is_coatom a) export is_atomistic (eq_Sup_atoms) is_coatomistic (eq_Inf_coatoms) variable {α} @[simp] theorem is_coatomistic_dual_iff_is_atomistic : is_coatomistic αᵒᵈ ↔ is_atomistic α := ⟨λ h, ⟨λ b, by apply h.eq_Inf_coatoms⟩, λ h, ⟨λ b, by apply h.eq_Sup_atoms⟩⟩ @[simp] theorem is_atomistic_dual_iff_is_coatomistic : is_atomistic αᵒᵈ ↔ is_coatomistic α := ⟨λ h, ⟨λ b, by apply h.eq_Sup_atoms⟩, λ h, ⟨λ b, by apply h.eq_Inf_coatoms⟩⟩ namespace is_atomistic instance is_coatomistic_dual [h : is_atomistic α] : is_coatomistic αᵒᵈ := is_coatomistic_dual_iff_is_atomistic.2 h variable [is_atomistic α] @[priority 100] instance : is_atomic α := ⟨λ b, by { rcases eq_Sup_atoms b with ⟨s, rfl, hs⟩, cases s.eq_empty_or_nonempty with h h, { simp [h] }, { exact or.intro_right _ ⟨h.some, hs _ h.some_spec, le_Sup h.some_spec⟩ } } ⟩ end is_atomistic section is_atomistic variables [is_atomistic α] @[simp] theorem Sup_atoms_le_eq (b : α) : Sup {a : α | is_atom a ∧ a ≤ b} = b := begin rcases eq_Sup_atoms b with ⟨s, rfl, hs⟩, exact le_antisymm (Sup_le (λ _, and.right)) (Sup_le_Sup (λ a ha, ⟨hs a ha, le_Sup ha⟩)), end @[simp] theorem Sup_atoms_eq_top : Sup {a : α | is_atom a} = ⊤ := begin refine eq.trans (congr rfl (set.ext (λ x, _))) (Sup_atoms_le_eq ⊤), exact (and_iff_left le_top).symm, end theorem le_iff_atom_le_imp {a b : α} : a ≤ b ↔ ∀ c : α, is_atom c → c ≤ a → c ≤ b := ⟨λ ab c hc ca, le_trans ca ab, λ h, begin rw [← Sup_atoms_le_eq a, ← Sup_atoms_le_eq b], exact Sup_le_Sup (λ c hc, ⟨hc.1, h c hc.1 hc.2⟩), end⟩ end is_atomistic namespace is_coatomistic instance is_atomistic_dual [h : is_coatomistic α] : is_atomistic αᵒᵈ := is_atomistic_dual_iff_is_coatomistic.2 h variable [is_coatomistic α] @[priority 100] instance : is_coatomic α := ⟨λ b, by { rcases eq_Inf_coatoms b with ⟨s, rfl, hs⟩, cases s.eq_empty_or_nonempty with h h, { simp [h] }, { exact or.intro_right _ ⟨h.some, hs _ h.some_spec, Inf_le h.some_spec⟩ } } ⟩ end is_coatomistic end atomistic /-- An order is simple iff it has exactly two elements, `⊥` and `⊤`. -/ class is_simple_order (α : Type*) [has_le α] [bounded_order α] extends nontrivial α : Prop := (eq_bot_or_eq_top : ∀ (a : α), a = ⊥ ∨ a = ⊤) export is_simple_order (eq_bot_or_eq_top) theorem is_simple_order_iff_is_simple_order_order_dual [has_le α] [bounded_order α] : is_simple_order α ↔ is_simple_order αᵒᵈ := begin split; intro i; haveI := i, { exact { exists_pair_ne := @exists_pair_ne α _, eq_bot_or_eq_top := λ a, or.symm (eq_bot_or_eq_top ((order_dual.of_dual a)) : _ ∨ _) } }, { exact { exists_pair_ne := @exists_pair_ne αᵒᵈ _, eq_bot_or_eq_top := λ a, or.symm (eq_bot_or_eq_top (order_dual.to_dual a)) } } end lemma is_simple_order.bot_ne_top [has_le α] [bounded_order α] [is_simple_order α] : (⊥ : α) ≠ (⊤ : α) := begin obtain ⟨a, b, h⟩ := exists_pair_ne α, rcases eq_bot_or_eq_top a with rfl|rfl; rcases eq_bot_or_eq_top b with rfl|rfl; simpa <|> simpa using h.symm end section is_simple_order variables [partial_order α] [bounded_order α] [is_simple_order α] instance {α} [has_le α] [bounded_order α] [is_simple_order α] : is_simple_order αᵒᵈ := is_simple_order_iff_is_simple_order_order_dual.1 (by apply_instance) /-- A simple `bounded_order` induces a preorder. This is not an instance to prevent loops. -/ protected def is_simple_order.preorder {α} [has_le α] [bounded_order α] [is_simple_order α] : preorder α := { le := (≤), le_refl := λ a, by rcases eq_bot_or_eq_top a with rfl|rfl; simp, le_trans := λ a b c, begin rcases eq_bot_or_eq_top a with rfl|rfl, { simp }, { rcases eq_bot_or_eq_top b with rfl|rfl, { rcases eq_bot_or_eq_top c with rfl|rfl; simp }, { simp } } end } /-- A simple partial ordered `bounded_order` induces a linear order. This is not an instance to prevent loops. -/ protected def is_simple_order.linear_order [decidable_eq α] : linear_order α := { le_total := λ a b, by rcases eq_bot_or_eq_top a with rfl|rfl; simp, decidable_le := λ a b, if ha : a = ⊥ then is_true (ha.le.trans bot_le) else if hb : b = ⊤ then is_true (le_top.trans hb.ge) else is_false (λ H, hb (top_unique (le_trans (top_le_iff.mpr (or.resolve_left (eq_bot_or_eq_top a) ha)) H))), decidable_eq := by assumption, ..(infer_instance : partial_order α) } @[simp] lemma is_atom_top : is_atom (⊤ : α) := ⟨top_ne_bot, λ a ha, or.resolve_right (eq_bot_or_eq_top a) (ne_of_lt ha)⟩ @[simp] lemma is_coatom_bot : is_coatom (⊥ : α) := is_atom_dual_iff_is_coatom.1 is_atom_top lemma bot_covby_top : (⊥ : α) ⋖ ⊤ := is_atom_top.bot_covby end is_simple_order namespace is_simple_order section preorder variables [preorder α] [bounded_order α] [is_simple_order α] {a b : α} (h : a < b) lemma eq_bot_of_lt : a = ⊥ := (is_simple_order.eq_bot_or_eq_top _).resolve_right h.ne_top lemma eq_top_of_lt : b = ⊤ := (is_simple_order.eq_bot_or_eq_top _).resolve_left h.ne_bot alias eq_bot_of_lt ← has_lt.lt.eq_bot alias eq_top_of_lt ← has_lt.lt.eq_top end preorder section bounded_order variables [lattice α] [bounded_order α] [is_simple_order α] /-- A simple partial ordered `bounded_order` induces a lattice. This is not an instance to prevent loops -/ protected def lattice {α} [decidable_eq α] [partial_order α] [bounded_order α] [is_simple_order α] : lattice α := @linear_order.to_lattice α (is_simple_order.linear_order) /-- A lattice that is a `bounded_order` is a distributive lattice. This is not an instance to prevent loops -/ protected def distrib_lattice : distrib_lattice α := { le_sup_inf := λ x y z, by { rcases eq_bot_or_eq_top x with rfl | rfl; simp }, .. (infer_instance : lattice α) } @[priority 100] -- see Note [lower instance priority] instance : is_atomic α := ⟨λ b, (eq_bot_or_eq_top b).imp_right (λ h, ⟨⊤, ⟨is_atom_top, ge_of_eq h⟩⟩)⟩ @[priority 100] -- see Note [lower instance priority] instance : is_coatomic α := is_atomic_dual_iff_is_coatomic.1 is_simple_order.is_atomic end bounded_order /- It is important that in this section `is_simple_order` is the last type-class argument. -/ section decidable_eq variables [decidable_eq α] [partial_order α] [bounded_order α] [is_simple_order α] /-- Every simple lattice is isomorphic to `bool`, regardless of order. -/ @[simps] def equiv_bool {α} [decidable_eq α] [has_le α] [bounded_order α] [is_simple_order α] : α ≃ bool := { to_fun := λ x, x = ⊤, inv_fun := λ x, cond x ⊤ ⊥, left_inv := λ x, by { rcases (eq_bot_or_eq_top x) with rfl | rfl; simp [bot_ne_top] }, right_inv := λ x, by { cases x; simp [bot_ne_top] } } /-- Every simple lattice over a partial order is order-isomorphic to `bool`. -/ def order_iso_bool : α ≃o bool := { map_rel_iff' := λ a b, begin rcases (eq_bot_or_eq_top a) with rfl | rfl, { simp [bot_ne_top] }, { rcases (eq_bot_or_eq_top b) with rfl | rfl, { simp [bot_ne_top.symm, bot_ne_top, bool.ff_lt_tt] }, { simp [bot_ne_top] } } end, ..equiv_bool } /- It is important that `is_simple_order` is the last type-class argument of this instance, so that type-class inference fails quickly if it doesn't apply. -/ @[priority 200] instance {α} [decidable_eq α] [has_le α] [bounded_order α] [is_simple_order α] : fintype α := fintype.of_equiv bool equiv_bool.symm /-- A simple `bounded_order` is also a `boolean_algebra`. -/ protected def boolean_algebra {α} [decidable_eq α] [lattice α] [bounded_order α] [is_simple_order α] : boolean_algebra α := { compl := λ x, if x = ⊥ then ⊤ else ⊥, sdiff := λ x y, if x = ⊤ ∧ y = ⊥ then ⊤ else ⊥, sdiff_eq := λ x y, by rcases eq_bot_or_eq_top x with rfl | rfl; simp [bot_ne_top, has_sdiff.sdiff, compl], inf_compl_le_bot := λ x, begin rcases eq_bot_or_eq_top x with rfl | rfl, { simp }, { simp only [top_inf_eq], split_ifs with h h; simp [h] } end, top_le_sup_compl := λ x, by rcases eq_bot_or_eq_top x with rfl | rfl; simp, sup_inf_sdiff := λ x y, by rcases eq_bot_or_eq_top x with rfl | rfl; rcases eq_bot_or_eq_top y with rfl | rfl; simp [bot_ne_top], inf_inf_sdiff := λ x y, begin rcases eq_bot_or_eq_top x with rfl | rfl, { simpa }, rcases eq_bot_or_eq_top y with rfl | rfl, { simpa }, { simp only [true_and, top_inf_eq, eq_self_iff_true], split_ifs with h h; simpa [h] } end, .. (show bounded_order α, by apply_instance), .. is_simple_order.distrib_lattice } end decidable_eq variables [lattice α] [bounded_order α] [is_simple_order α] open_locale classical /-- A simple `bounded_order` is also complete. -/ protected noncomputable def complete_lattice : complete_lattice α := { Sup := λ s, if ⊤ ∈ s then ⊤ else ⊥, Inf := λ s, if ⊥ ∈ s then ⊥ else ⊤, le_Sup := λ s x h, by { rcases eq_bot_or_eq_top x with rfl | rfl, { exact bot_le }, { rw if_pos h } }, Sup_le := λ s x h, by { rcases eq_bot_or_eq_top x with rfl | rfl, { rw if_neg, intro con, exact bot_ne_top (eq_top_iff.2 (h ⊤ con)) }, { exact le_top } }, Inf_le := λ s x h, by { rcases eq_bot_or_eq_top x with rfl | rfl, { rw if_pos h }, { exact le_top } }, le_Inf := λ s x h, by { rcases eq_bot_or_eq_top x with rfl | rfl, { exact bot_le }, { rw if_neg, intro con, exact top_ne_bot (eq_bot_iff.2 (h ⊥ con)) } }, .. (infer_instance : lattice α), .. (infer_instance : bounded_order α) } /-- A simple `bounded_order` is also a `complete_boolean_algebra`. -/ protected noncomputable def complete_boolean_algebra : complete_boolean_algebra α := { infi_sup_le_sup_Inf := λ x s, by { rcases eq_bot_or_eq_top x with rfl | rfl, { simp only [bot_sup_eq, ← Inf_eq_infi], exact le_rfl }, { simp only [top_sup_eq, le_top] }, }, inf_Sup_le_supr_inf := λ x s, by { rcases eq_bot_or_eq_top x with rfl | rfl, { simp only [bot_inf_eq, bot_le] }, { simp only [top_inf_eq, ← Sup_eq_supr], exact le_rfl } }, .. is_simple_order.complete_lattice, .. is_simple_order.boolean_algebra } end is_simple_order namespace is_simple_order variables [complete_lattice α] [is_simple_order α] set_option default_priority 100 instance : is_atomistic α := ⟨λ b, (eq_bot_or_eq_top b).elim (λ h, ⟨∅, ⟨h.trans Sup_empty.symm, λ a ha, false.elim (set.not_mem_empty _ ha)⟩⟩) (λ h, ⟨{⊤}, h.trans Sup_singleton.symm, λ a ha, (set.mem_singleton_iff.1 ha).symm ▸ is_atom_top⟩)⟩ instance : is_coatomistic α := is_atomistic_dual_iff_is_coatomistic.1 is_simple_order.is_atomistic end is_simple_order namespace fintype namespace is_simple_order variables [partial_order α] [bounded_order α] [is_simple_order α] [decidable_eq α] lemma univ : (finset.univ : finset α) = {⊤, ⊥} := begin change finset.map _ (finset.univ : finset bool) = _, rw fintype.univ_bool, simp only [finset.map_insert, function.embedding.coe_fn_mk, finset.map_singleton], refl, end lemma card : fintype.card α = 2 := (fintype.of_equiv_card _).trans fintype.card_bool end is_simple_order end fintype namespace bool instance : is_simple_order bool := ⟨λ a, begin rw [← finset.mem_singleton, or.comm, ← finset.mem_insert, top_eq_tt, bot_eq_ff, ← fintype.univ_bool], apply finset.mem_univ, end⟩ end bool theorem is_simple_order_iff_is_atom_top [partial_order α] [bounded_order α] : is_simple_order α ↔ is_atom (⊤ : α) := ⟨λ h, @is_atom_top _ _ _ h, λ h, { exists_pair_ne := ⟨⊤, ⊥, h.1⟩, eq_bot_or_eq_top := λ a, ((eq_or_lt_of_le le_top).imp_right (h.2 a)).symm }⟩ theorem is_simple_order_iff_is_coatom_bot [partial_order α] [bounded_order α] : is_simple_order α ↔ is_coatom (⊥ : α) := is_simple_order_iff_is_simple_order_order_dual.trans is_simple_order_iff_is_atom_top namespace set theorem is_simple_order_Iic_iff_is_atom [partial_order α] [order_bot α] {a : α} : is_simple_order (Iic a) ↔ is_atom a := is_simple_order_iff_is_atom_top.trans $ and_congr (not_congr subtype.mk_eq_mk) ⟨λ h b ab, subtype.mk_eq_mk.1 (h ⟨b, le_of_lt ab⟩ ab), λ h ⟨b, hab⟩ hbotb, subtype.mk_eq_mk.2 (h b (subtype.mk_lt_mk.1 hbotb))⟩ theorem is_simple_order_Ici_iff_is_coatom [partial_order α] [order_top α] {a : α} : is_simple_order (Ici a) ↔ is_coatom a := is_simple_order_iff_is_coatom_bot.trans $ and_congr (not_congr subtype.mk_eq_mk) ⟨λ h b ab, subtype.mk_eq_mk.1 (h ⟨b, le_of_lt ab⟩ ab), λ h ⟨b, hab⟩ hbotb, subtype.mk_eq_mk.2 (h b (subtype.mk_lt_mk.1 hbotb))⟩ end set namespace order_iso variables {β : Type*} @[simp] lemma is_atom_iff [partial_order α] [order_bot α] [partial_order β] [order_bot β] (f : α ≃o β) (a : α) : is_atom (f a) ↔ is_atom a := and_congr (not_congr ⟨λ h, f.injective (f.map_bot.symm ▸ h), λ h, f.map_bot ▸ (congr rfl h)⟩) ⟨λ h b hb, f.injective ((h (f b) ((f : α ↪o β).lt_iff_lt.2 hb)).trans f.map_bot.symm), λ h b hb, f.symm.injective begin rw f.symm.map_bot, apply h, rw [← f.symm_apply_apply a], exact (f.symm : β ↪o α).lt_iff_lt.2 hb, end⟩ @[simp] lemma is_coatom_iff [partial_order α] [order_top α] [partial_order β] [order_top β] (f : α ≃o β) (a : α) : is_coatom (f a) ↔ is_coatom a := f.dual.is_atom_iff a lemma is_simple_order_iff [partial_order α] [bounded_order α] [partial_order β] [bounded_order β] (f : α ≃o β) : is_simple_order α ↔ is_simple_order β := by rw [is_simple_order_iff_is_atom_top, is_simple_order_iff_is_atom_top, ← f.is_atom_iff ⊤, f.map_top] lemma is_simple_order [partial_order α] [bounded_order α] [partial_order β] [bounded_order β] [h : is_simple_order β] (f : α ≃o β) : is_simple_order α := f.is_simple_order_iff.mpr h lemma is_atomic_iff [partial_order α] [order_bot α] [partial_order β] [order_bot β] (f : α ≃o β) : is_atomic α ↔ is_atomic β := begin suffices : (∀ b : α, b = ⊥ ∨ ∃ (a : α), is_atom a ∧ a ≤ b) ↔ (∀ b : β, b = ⊥ ∨ ∃ (a : β), is_atom a ∧ a ≤ b), from ⟨λ ⟨p⟩, ⟨this.mp p⟩, λ ⟨p⟩, ⟨this.mpr p⟩⟩, apply f.to_equiv.forall_congr, simp_rw [rel_iso.coe_fn_to_equiv], intro b, apply or_congr, { rw [f.apply_eq_iff_eq_symm_apply, map_bot], }, { split, { exact λ ⟨a, ha⟩, ⟨f a, ⟨(f.is_atom_iff a).mpr ha.1, f.le_iff_le.mpr ha.2⟩⟩, }, { rintros ⟨b, ⟨hb1, hb2⟩⟩, refine ⟨f.symm b, ⟨(f.symm.is_atom_iff b).mpr hb1, _⟩⟩, rwa [←f.le_iff_le, f.apply_symm_apply], }, }, end lemma is_coatomic_iff [partial_order α] [order_top α] [partial_order β] [order_top β] (f : α ≃o β) : is_coatomic α ↔ is_coatomic β := by { rw [←is_atomic_dual_iff_is_coatomic, ←is_atomic_dual_iff_is_coatomic], exact f.dual.is_atomic_iff } end order_iso section is_modular_lattice variables [lattice α] [bounded_order α] [is_modular_lattice α] namespace is_compl variables {a b : α} (hc : is_compl a b) include hc lemma is_atom_iff_is_coatom : is_atom a ↔ is_coatom b := set.is_simple_order_Iic_iff_is_atom.symm.trans $ hc.Iic_order_iso_Ici.is_simple_order_iff.trans set.is_simple_order_Ici_iff_is_coatom lemma is_coatom_iff_is_atom : is_coatom a ↔ is_atom b := hc.symm.is_atom_iff_is_coatom.symm end is_compl variables [is_complemented α] lemma is_coatomic_of_is_atomic_of_is_complemented_of_is_modular [is_atomic α] : is_coatomic α := ⟨λ x, begin rcases exists_is_compl x with ⟨y, xy⟩, apply (eq_bot_or_exists_atom_le y).imp _ _, { rintro rfl, exact eq_top_of_is_compl_bot xy }, { rintro ⟨a, ha, ay⟩, rcases exists_is_compl (xy.symm.Iic_order_iso_Ici ⟨a, ay⟩) with ⟨⟨b, xb⟩, hb⟩, refine ⟨↑(⟨b, xb⟩ : set.Ici x), is_coatom.of_is_coatom_coe_Ici _, xb⟩, rw [← hb.is_atom_iff_is_coatom, order_iso.is_atom_iff], apply ha.Iic } end⟩ lemma is_atomic_of_is_coatomic_of_is_complemented_of_is_modular [is_coatomic α] : is_atomic α := is_coatomic_dual_iff_is_atomic.1 is_coatomic_of_is_atomic_of_is_complemented_of_is_modular theorem is_atomic_iff_is_coatomic : is_atomic α ↔ is_coatomic α := ⟨λ h, @is_coatomic_of_is_atomic_of_is_complemented_of_is_modular _ _ _ _ _ h, λ h, @is_atomic_of_is_coatomic_of_is_complemented_of_is_modular _ _ _ _ _ h⟩ end is_modular_lattice section fintype open finset @[priority 100] -- see Note [lower instance priority] instance fintype.to_is_coatomic [partial_order α] [order_top α] [fintype α] : is_coatomic α := begin refine is_coatomic.mk (λ b, or_iff_not_imp_left.2 (λ ht, _)), obtain ⟨c, hc, hmax⟩ := set.finite.exists_maximal_wrt id { x : α | b ≤ x ∧ x ≠ ⊤ } (set.finite.of_fintype _) ⟨b, le_rfl, ht⟩, refine ⟨c, ⟨hc.2, λ y hcy, _⟩, hc.1⟩, by_contra hyt, obtain rfl : c = y := hmax y ⟨hc.1.trans hcy.le, hyt⟩ hcy.le, exact (lt_self_iff_false _).mp hcy end @[priority 100] -- see Note [lower instance priority] instance fintype.to_is_atomic [partial_order α] [order_bot α] [fintype α] : is_atomic α := is_coatomic_dual_iff_is_atomic.mp fintype.to_is_coatomic end fintype
f348f0741c00813225f34ccc37aa4c6bd6331c34
4bddde0d06fbd53be6f23d7f5899998e8f63410b
/src/tactic/iconfig/lib/default.lean
1044b8564d9d94d8ea055ed3170ab345cb5b6208
[]
no_license
khoek/libiconfig
4816290a5862af14b07683b3d2663e8e62832ef4
6f55c50bc5d852d26ee5ee4c5b52b2cda2a852e5
refs/heads/master
1,586,109,683,212
1,559,567,916,000
1,559,567,916,000
157,085,466
0
1
null
1,559,567,917,000
1,541,945,134,000
Lean
UTF-8
Lean
false
false
30
lean
import .tactic import .parser
f7949d97fedaf0feef38b99dd8e3c5253025118e
432d948a4d3d242fdfb44b81c9e1b1baacd58617
/src/data/set/lattice.lean
04ee427082a42710b6795dba6c6dbb663c0c0498
[ "Apache-2.0" ]
permissive
JLimperg/aesop3
306cc6570c556568897ed2e508c8869667252e8a
a4a116f650cc7403428e72bd2e2c4cda300fe03f
refs/heads/master
1,682,884,916,368
1,620,320,033,000
1,620,320,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
52,462
lean
/- 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, Johannes Hölzl, Mario Carneiro -- QUESTION: can make the first argument in ∀ x ∈ a, ... implicit? -/ import order.complete_boolean_algebra import data.sigma.basic import order.galois_connection import order.directed open function tactic set auto universes u v variables {α β γ : Type*} {ι ι' ι₂ : Sort*} namespace set instance lattice_set : complete_lattice (set α) := { Sup := λs, {a | ∃ t ∈ s, a ∈ t }, Inf := λs, {a | ∀ t ∈ s, a ∈ t }, le_Sup := assume s t t_in a a_in, ⟨t, ⟨t_in, a_in⟩⟩, Sup_le := assume s t h a ⟨t', ⟨t'_in, a_in⟩⟩, h t' t'_in a_in, le_Inf := assume s t h a a_in t' t'_in, h t' t'_in a_in, Inf_le := assume s t t_in a h, h _ t_in, .. set.boolean_algebra, .. (infer_instance : complete_lattice (α → Prop)) } /-- Image is monotone. See `set.image_image` for the statement in terms of `⊆`. -/ lemma monotone_image {f : α → β} : monotone (image f) := assume s t, assume h : s ⊆ t, image_subset _ h theorem monotone_inter [preorder β] {f g : β → set α} (hf : monotone f) (hg : monotone g) : monotone (λx, f x ∩ g x) := assume b₁ b₂ h, inter_subset_inter (hf h) (hg h) theorem monotone_union [preorder β] {f g : β → set α} (hf : monotone f) (hg : monotone g) : monotone (λx, f x ∪ g x) := assume b₁ b₂ h, union_subset_union (hf h) (hg h) theorem monotone_set_of [preorder α] {p : α → β → Prop} (hp : ∀b, monotone (λa, p a b)) : monotone (λa, {b | p a b}) := assume a a' h b, hp b h section galois_connection variables {f : α → β} protected lemma image_preimage : galois_connection (image f) (preimage f) := assume a b, image_subset_iff /-- `kern_image f s` is the set of `y` such that `f ⁻¹ y ⊆ s` -/ def kern_image (f : α → β) (s : set α) : set β := {y | ∀ ⦃x⦄, f x = y → x ∈ s} protected lemma preimage_kern_image : galois_connection (preimage f) (kern_image f) := assume a b, ⟨ assume h x hx y hy, have f y ∈ a, from hy.symm ▸ hx, h this, assume h x (hx : f x ∈ a), h hx rfl⟩ end galois_connection /- union and intersection over a family of sets indexed by a type -/ /-- Indexed union of a family of sets -/ @[reducible] def Union (s : ι → set β) : set β := supr s /-- Indexed intersection of a family of sets -/ @[reducible] def Inter (s : ι → set β) : set β := infi s notation `⋃` binders `, ` r:(scoped f, Union f) := r notation `⋂` binders `, ` r:(scoped f, Inter f) := r @[simp] theorem mem_Union {x : β} {s : ι → set β} : x ∈ Union s ↔ ∃ i, x ∈ s i := ⟨assume ⟨t, ⟨⟨a, (t_eq : s a = t)⟩, (h : x ∈ t)⟩⟩, ⟨a, t_eq.symm ▸ h⟩, assume ⟨a, h⟩, ⟨s a, ⟨⟨a, rfl⟩, h⟩⟩⟩ /- alternative proof: dsimp [Union, supr, Sup]; simp -/ -- TODO: more rewrite rules wrt forall / existentials and logical connectives -- TODO: also eliminate ∃i, ... ∧ i = t ∧ ... lemma exists_set_mem_of_union_eq_top {ι : Type*} (t : set ι) (s : ι → set β) (w : (⋃ i ∈ t, s i) = ⊤) (x : β) : ∃ (i ∈ t), x ∈ s i := begin have p : x ∈ ⊤ := set.mem_univ x, simpa only [←w, set.mem_Union] using p, end lemma nonempty_of_union_eq_top_of_nonempty {ι : Type*} (t : set ι) (s : ι → set α) (H : nonempty α) (w : (⋃ i ∈ t, s i) = ⊤) : t.nonempty := begin obtain ⟨x, m, -⟩ := exists_set_mem_of_union_eq_top t s w H.some, exact ⟨x, m⟩, end theorem set_of_exists (p : ι → β → Prop) : {x | ∃ i, p i x} = ⋃ i, {x | p i x} := ext $ λ i, mem_Union.symm @[simp] theorem mem_Inter {x : β} {s : ι → set β} : x ∈ Inter s ↔ ∀ i, x ∈ s i := ⟨assume (h : ∀a ∈ {a : set β | ∃i, s i = a}, x ∈ a) a, h (s a) ⟨a, rfl⟩, assume h t ⟨a, (eq : s a = t)⟩, eq ▸ h a⟩ theorem set_of_forall (p : ι → β → Prop) : {x | ∀ i, p i x} = ⋂ i, {x | p i x} := ext $ λ i, mem_Inter.symm theorem Union_subset {s : ι → set β} {t : set β} (h : ∀ i, s i ⊆ t) : (⋃ i, s i) ⊆ t := -- TODO: should be simpler when sets' order is based on lattices @supr_le (set β) _ set.lattice_set _ _ h theorem Union_subset_iff {s : ι → set β} {t : set β} : (⋃ i, s i) ⊆ t ↔ (∀ i, s i ⊆ t) := ⟨assume h i, subset.trans (le_supr s _) h, Union_subset⟩ theorem mem_Inter_of_mem {x : β} {s : ι → set β} : (∀ i, x ∈ s i) → (x ∈ ⋂ i, s i) := mem_Inter.2 theorem subset_Inter {t : set β} {s : ι → set β} (h : ∀ i, t ⊆ s i) : t ⊆ ⋂ i, s i := -- TODO: should be simpler when sets' order is based on lattices @le_infi (set β) _ set.lattice_set _ _ h theorem subset_Inter_iff {t : set β} {s : ι → set β} : t ⊆ (⋂ i, s i) ↔ ∀ i, t ⊆ s i := @le_infi_iff (set β) _ set.lattice_set _ _ theorem subset_Union : ∀ (s : ι → set β) (i : ι), s i ⊆ (⋃ i, s i) := le_supr -- This rather trivial consequence is convenient with `apply`, -- and has `i` explicit for this use case. theorem subset_subset_Union {A : set β} {s : ι → set β} (i : ι) (h : A ⊆ s i) : A ⊆ ⋃ (i : ι), s i := subset.trans h (subset_Union s i) theorem Inter_subset : ∀ (s : ι → set β) (i : ι), (⋂ i, s i) ⊆ s i := infi_le lemma Inter_subset_of_subset {s : ι → set α} {t : set α} (i : ι) (h : s i ⊆ t) : (⋂ i, s i) ⊆ t := set.subset.trans (set.Inter_subset s i) h lemma Inter_subset_Inter {s t : ι → set α} (h : ∀ i, s i ⊆ t i) : (⋂ i, s i) ⊆ (⋂ i, t i) := set.subset_Inter $ λ i, set.Inter_subset_of_subset i (h i) lemma Inter_subset_Inter2 {s : ι → set α} {t : ι' → set α} (h : ∀ j, ∃ i, s i ⊆ t j) : (⋂ i, s i) ⊆ (⋂ j, t j) := set.subset_Inter $ λ j, let ⟨i, hi⟩ := h j in Inter_subset_of_subset i hi lemma Inter_set_of (P : ι → α → Prop) : (⋂ i, {x : α | P i x }) = {x : α | ∀ i, P i x} := by { ext, simp } lemma Union_congr {f : ι → set α} {g : ι₂ → set α} (h : ι → ι₂) (h1 : surjective h) (h2 : ∀ x, g (h x) = f x) : (⋃ x, f x) = ⋃ y, g y := supr_congr h h1 h2 lemma Inter_congr {f : ι → set α} {g : ι₂ → set α} (h : ι → ι₂) (h1 : surjective h) (h2 : ∀ x, g (h x) = f x) : (⋂ x, f x) = ⋂ y, g y := infi_congr h h1 h2 theorem Union_const [nonempty ι] (s : set β) : (⋃ i:ι, s) = s := supr_const theorem Inter_const [nonempty ι] (s : set β) : (⋂ i:ι, s) = s := infi_const @[simp] -- complete_boolean_algebra theorem compl_Union (s : ι → set β) : (⋃ i, s i)ᶜ = (⋂ i, (s i)ᶜ) := ext (by simp) -- classical -- complete_boolean_algebra theorem compl_Inter (s : ι → set β) : (⋂ i, s i)ᶜ = (⋃ i, (s i)ᶜ) := ext (λ x, by simp [not_forall]) -- classical -- complete_boolean_algebra theorem Union_eq_comp_Inter_comp (s : ι → set β) : (⋃ i, s i) = (⋂ i, (s i)ᶜ)ᶜ := by simp [compl_Inter, compl_compl] -- classical -- complete_boolean_algebra theorem Inter_eq_comp_Union_comp (s : ι → set β) : (⋂ i, s i) = (⋃ i, (s i)ᶜ)ᶜ := by simp [compl_compl] theorem inter_Union (s : set β) (t : ι → set β) : s ∩ (⋃ i, t i) = ⋃ i, s ∩ t i := ext $ by simp theorem Union_inter (s : set β) (t : ι → set β) : (⋃ i, t i) ∩ s = ⋃ i, t i ∩ s := ext $ by simp theorem Union_union_distrib (s : ι → set β) (t : ι → set β) : (⋃ i, s i ∪ t i) = (⋃ i, s i) ∪ (⋃ i, t i) := ext $ by simp [exists_or_distrib] theorem Inter_inter_distrib (s : ι → set β) (t : ι → set β) : (⋂ i, s i ∩ t i) = (⋂ i, s i) ∩ (⋂ i, t i) := ext $ by simp [forall_and_distrib] theorem union_Union [nonempty ι] (s : set β) (t : ι → set β) : s ∪ (⋃ i, t i) = ⋃ i, s ∪ t i := by rw [Union_union_distrib, Union_const] theorem Union_union [nonempty ι] (s : set β) (t : ι → set β) : (⋃ i, t i) ∪ s = ⋃ i, t i ∪ s := by rw [Union_union_distrib, Union_const] theorem inter_Inter [nonempty ι] (s : set β) (t : ι → set β) : s ∩ (⋂ i, t i) = ⋂ i, s ∩ t i := by rw [Inter_inter_distrib, Inter_const] theorem Inter_inter [nonempty ι] (s : set β) (t : ι → set β) : (⋂ i, t i) ∩ s = ⋂ i, t i ∩ s := by rw [Inter_inter_distrib, Inter_const] -- classical theorem union_Inter (s : set β) (t : ι → set β) : s ∪ (⋂ i, t i) = ⋂ i, s ∪ t i := ext $ assume x, by simp [forall_or_distrib_left] theorem Union_diff (s : set β) (t : ι → set β) : (⋃ i, t i) \ s = ⋃ i, t i \ s := Union_inter _ _ theorem diff_Union [nonempty ι] (s : set β) (t : ι → set β) : s \ (⋃ i, t i) = ⋂ i, s \ t i := by rw [diff_eq, compl_Union, inter_Inter]; refl theorem diff_Inter (s : set β) (t : ι → set β) : s \ (⋂ i, t i) = ⋃ i, s \ t i := by rw [diff_eq, compl_Inter, inter_Union]; refl lemma directed_on_Union {r} {f : ι → set α} (hd : directed (⊆) f) (h : ∀x, directed_on r (f x)) : directed_on r (⋃x, f x) := by simp only [directed_on, exists_prop, mem_Union, exists_imp_distrib]; exact assume a₁ b₁ fb₁ a₂ b₂ fb₂, let ⟨z, zb₁, zb₂⟩ := hd b₁ b₂, ⟨x, xf, xa₁, xa₂⟩ := h z a₁ (zb₁ fb₁) a₂ (zb₂ fb₂) in ⟨x, ⟨z, xf⟩, xa₁, xa₂⟩ lemma Union_inter_subset {ι α} {s t : ι → set α} : (⋃ i, s i ∩ t i) ⊆ (⋃ i, s i) ∩ (⋃ i, t i) := by { rintro x ⟨_, ⟨i, rfl⟩, ⟨xs, xt⟩⟩, exact ⟨⟨_, ⟨i, rfl⟩, xs⟩, ⟨_, ⟨i, rfl⟩, xt⟩⟩ } lemma Union_inter_of_monotone {ι α} [semilattice_sup ι] {s t : ι → set α} (hs : monotone s) (ht : monotone t) : (⋃ i, s i ∩ t i) = (⋃ i, s i) ∩ (⋃ i, t i) := begin ext x, refine ⟨λ hx, Union_inter_subset hx, _⟩, rintro ⟨⟨_, ⟨i, rfl⟩, xs⟩, ⟨_, ⟨j, rfl⟩, xt⟩⟩, exact ⟨_, ⟨i ⊔ j, rfl⟩, ⟨hs le_sup_left xs, ht le_sup_right xt⟩⟩ end /-- An equality version of this lemma is `Union_Inter_of_monotone` in `data.set.finite`. -/ lemma Union_Inter_subset {ι ι' α} {s : ι → ι' → set α} : (⋃ j, ⋂ i, s i j) ⊆ ⋂ i, ⋃ j, s i j := by { rintro x ⟨_, ⟨i, rfl⟩, hx⟩ _ ⟨j, rfl⟩, exact ⟨_, ⟨i, rfl⟩, hx _ ⟨j, rfl⟩⟩ } lemma Union_option {ι} (s : option ι → set α) : (⋃ o, s o) = s none ∪ ⋃ i, s (some i) := supr_option s lemma Inter_option {ι} (s : option ι → set α) : (⋂ o, s o) = s none ∩ ⋂ i, s (some i) := infi_option s /-! ### Bounded unions and intersections -/ theorem mem_bUnion_iff {s : set α} {t : α → set β} {y : β} : y ∈ (⋃ x ∈ s, t x) ↔ ∃ x ∈ s, y ∈ t x := by simp theorem mem_bInter_iff {s : set α} {t : α → set β} {y : β} : y ∈ (⋂ x ∈ s, t x) ↔ ∀ x ∈ s, y ∈ t x := by simp theorem mem_bUnion {s : set α} {t : α → set β} {x : α} {y : β} (xs : x ∈ s) (ytx : y ∈ t x) : y ∈ ⋃ x ∈ s, t x := by simp; exact ⟨x, ⟨xs, ytx⟩⟩ theorem mem_bInter {s : set α} {t : α → set β} {y : β} (h : ∀ x ∈ s, y ∈ t x) : y ∈ ⋂ x ∈ s, t x := by simp; assumption theorem bUnion_subset {s : set α} {t : set β} {u : α → set β} (h : ∀ x ∈ s, u x ⊆ t) : (⋃ x ∈ s, u x) ⊆ t := show (⨆ x ∈ s, u x) ≤ t, -- TODO: should not be necessary when sets' order is based on lattices from supr_le $ assume x, supr_le (h x) theorem subset_bInter {s : set α} {t : set β} {u : α → set β} (h : ∀ x ∈ s, t ⊆ u x) : t ⊆ (⋂ x ∈ s, u x) := subset_Inter $ assume x, subset_Inter $ h x theorem subset_bUnion_of_mem {s : set α} {u : α → set β} {x : α} (xs : x ∈ s) : u x ⊆ (⋃ x ∈ s, u x) := show u x ≤ (⨆ x ∈ s, u x), from le_supr_of_le x $ le_supr _ xs theorem bInter_subset_of_mem {s : set α} {t : α → set β} {x : α} (xs : x ∈ s) : (⋂ x ∈ s, t x) ⊆ t x := show (⨅x ∈ s, t x) ≤ t x, from infi_le_of_le x $ infi_le _ xs theorem bUnion_subset_bUnion_left {s s' : set α} {t : α → set β} (h : s ⊆ s') : (⋃ x ∈ s, t x) ⊆ (⋃ x ∈ s', t x) := bUnion_subset (λ x xs, subset_bUnion_of_mem (h xs)) theorem bInter_subset_bInter_left {s s' : set α} {t : α → set β} (h : s' ⊆ s) : (⋂ x ∈ s, t x) ⊆ (⋂ x ∈ s', t x) := subset_bInter (λ x xs, bInter_subset_of_mem (h xs)) theorem bUnion_subset_bUnion_right {s : set α} {t1 t2 : α → set β} (h : ∀ x ∈ s, t1 x ⊆ t2 x) : (⋃ x ∈ s, t1 x) ⊆ (⋃ x ∈ s, t2 x) := bUnion_subset (λ x xs, subset.trans (h x xs) (subset_bUnion_of_mem xs)) theorem bInter_subset_bInter_right {s : set α} {t1 t2 : α → set β} (h : ∀ x ∈ s, t1 x ⊆ t2 x) : (⋂ x ∈ s, t1 x) ⊆ (⋂ x ∈ s, t2 x) := subset_bInter (λ x xs, subset.trans (bInter_subset_of_mem xs) (h x xs)) theorem bUnion_subset_bUnion {γ : Type*} {s : set α} {t : α → set β} {s' : set γ} {t' : γ → set β} (h : ∀ x ∈ s, ∃ y ∈ s', t x ⊆ t' y) : (⋃ x ∈ s, t x) ⊆ (⋃ y ∈ s', t' y) := begin intros x, simp only [mem_Union], rintros ⟨a, a_in, ha⟩, rcases h a a_in with ⟨c, c_in, hc⟩, exact ⟨c, c_in, hc ha⟩ end theorem bInter_mono' {s s' : set α} {t t' : α → set β} (hs : s ⊆ s') (h : ∀ x ∈ s, t x ⊆ t' x) : (⋂ x ∈ s', t x) ⊆ (⋂ x ∈ s, t' x) := begin intros x x_in, simp only [mem_Inter] at *, exact λ a a_in, h a a_in $ x_in _ (hs a_in) end theorem bInter_mono {s : set α} {t t' : α → set β} (h : ∀ x ∈ s, t x ⊆ t' x) : (⋂ x ∈ s, t x) ⊆ (⋂ x ∈ s, t' x) := bInter_mono' (subset.refl s) h theorem bUnion_mono {s : set α} {t t' : α → set β} (h : ∀ x ∈ s, t x ⊆ t' x) : (⋃ x ∈ s, t x) ⊆ (⋃ x ∈ s, t' x) := bUnion_subset_bUnion (λ x x_in, ⟨x, x_in, h x x_in⟩) theorem bUnion_eq_Union (s : set α) (t : Π x ∈ s, set β) : (⋃ x ∈ s, t x ‹_›) = (⋃ x : s, t x x.2) := supr_subtype' theorem bInter_eq_Inter (s : set α) (t : Π x ∈ s, set β) : (⋂ x ∈ s, t x ‹_›) = (⋂ x : s, t x x.2) := infi_subtype' theorem bInter_empty (u : α → set β) : (⋂ x ∈ (∅ : set α), u x) = univ := show (⨅x ∈ (∅ : set α), u x) = ⊤, -- simplifier should be able to rewrite x ∈ ∅ to false. from infi_emptyset theorem bInter_univ (u : α → set β) : (⋂ x ∈ @univ α, u x) = ⋂ x, u x := infi_univ -- TODO(Jeremy): here is an artifact of the the encoding of bounded intersection: -- without dsimp, the next theorem fails to type check, because there is a lambda -- in a type that needs to be contracted. Using simp [eq_of_mem_singleton xa] also works. @[simp] theorem bInter_singleton (a : α) (s : α → set β) : (⋂ x ∈ ({a} : set α), s x) = s a := show (⨅ x ∈ ({a} : set α), s x) = s a, by simp theorem bInter_union (s t : set α) (u : α → set β) : (⋂ x ∈ s ∪ t, u x) = (⋂ x ∈ s, u x) ∩ (⋂ x ∈ t, u x) := show (⨅ x ∈ s ∪ t, u x) = (⨅ x ∈ s, u x) ⊓ (⨅ x ∈ t, u x), from infi_union -- TODO(Jeremy): simp [insert_eq, bInter_union] doesn't work @[simp] theorem bInter_insert (a : α) (s : set α) (t : α → set β) : (⋂ x ∈ insert a s, t x) = t a ∩ (⋂ x ∈ s, t x) := begin rw insert_eq, simp [bInter_union] end -- TODO(Jeremy): another example of where an annotation is needed theorem bInter_pair (a b : α) (s : α → set β) : (⋂ x ∈ ({a, b} : set α), s x) = s a ∩ s b := by simp [inter_comm] theorem bUnion_empty (s : α → set β) : (⋃ x ∈ (∅ : set α), s x) = ∅ := supr_emptyset theorem bUnion_univ (s : α → set β) : (⋃ x ∈ @univ α, s x) = ⋃ x, s x := supr_univ @[simp] theorem bUnion_singleton (a : α) (s : α → set β) : (⋃ x ∈ ({a} : set α), s x) = s a := supr_singleton @[simp] theorem bUnion_of_singleton (s : set α) : (⋃ x ∈ s, {x}) = s := ext $ by simp theorem bUnion_union (s t : set α) (u : α → set β) : (⋃ x ∈ s ∪ t, u x) = (⋃ x ∈ s, u x) ∪ (⋃ x ∈ t, u x) := supr_union @[simp] lemma Union_subtype {α β : Type*} (s : set α) (f : α → set β) : (⋃ (i : s), f i) = ⋃ (i ∈ s), f i := (set.bUnion_eq_Union s $ λ x _, f x).symm -- TODO(Jeremy): once again, simp doesn't do it alone. @[simp] theorem bUnion_insert (a : α) (s : set α) (t : α → set β) : (⋃ x ∈ insert a s, t x) = t a ∪ (⋃ x ∈ s, t x) := begin rw [insert_eq], simp [bUnion_union] end theorem bUnion_pair (a b : α) (s : α → set β) : (⋃ x ∈ ({a, b} : set α), s x) = s a ∪ s b := by simp [union_comm] @[simp] -- complete_boolean_algebra theorem compl_bUnion (s : set α) (t : α → set β) : (⋃ i ∈ s, t i)ᶜ = (⋂ i ∈ s, (t i)ᶜ) := ext (λ x, by simp) -- classical -- complete_boolean_algebra theorem compl_bInter (s : set α) (t : α → set β) : (⋂ i ∈ s, t i)ᶜ = (⋃ i ∈ s, (t i)ᶜ) := ext (λ x, by simp [not_forall]) theorem inter_bUnion (s : set α) (t : α → set β) (u : set β) : u ∩ (⋃ i ∈ s, t i) = ⋃ i ∈ s, u ∩ t i := begin ext x, simp only [exists_prop, mem_Union, mem_inter_eq], exact ⟨λ ⟨hx, ⟨i, is, xi⟩⟩, ⟨i, is, hx, xi⟩, λ ⟨i, is, hx, xi⟩, ⟨hx, ⟨i, is, xi⟩⟩⟩ end theorem bUnion_inter (s : set α) (t : α → set β) (u : set β) : (⋃ i ∈ s, t i) ∩ u = (⋃ i ∈ s, t i ∩ u) := by simp [@inter_comm _ _ u, inter_bUnion] /-- Intersection of a set of sets. -/ @[reducible] def sInter (S : set (set α)) : set α := Inf S prefix `⋂₀`:110 := sInter theorem mem_sUnion_of_mem {x : α} {t : set α} {S : set (set α)} (hx : x ∈ t) (ht : t ∈ S) : x ∈ ⋃₀ S := ⟨t, ⟨ht, hx⟩⟩ theorem mem_sUnion {x : α} {S : set (set α)} : x ∈ ⋃₀ S ↔ ∃t ∈ S, x ∈ t := iff.rfl -- is this theorem really necessary? theorem not_mem_of_not_mem_sUnion {x : α} {t : set α} {S : set (set α)} (hx : x ∉ ⋃₀ S) (ht : t ∈ S) : x ∉ t := λ h, hx ⟨t, ht, h⟩ @[simp] theorem mem_sInter {x : α} {S : set (set α)} : x ∈ ⋂₀ S ↔ ∀ t ∈ S, x ∈ t := iff.rfl theorem sInter_subset_of_mem {S : set (set α)} {t : set α} (tS : t ∈ S) : ⋂₀ S ⊆ t := Inf_le tS theorem subset_sUnion_of_mem {S : set (set α)} {t : set α} (tS : t ∈ S) : t ⊆ ⋃₀ S := le_Sup tS lemma subset_sUnion_of_subset {s : set α} (t : set (set α)) (u : set α) (h₁ : s ⊆ u) (h₂ : u ∈ t) : s ⊆ ⋃₀ t := subset.trans h₁ (subset_sUnion_of_mem h₂) theorem sUnion_subset {S : set (set α)} {t : set α} (h : ∀t' ∈ S, t' ⊆ t) : (⋃₀ S) ⊆ t := Sup_le h theorem sUnion_subset_iff {s : set (set α)} {t : set α} : ⋃₀ s ⊆ t ↔ ∀t' ∈ s, t' ⊆ t := ⟨assume h t' ht', subset.trans (subset_sUnion_of_mem ht') h, sUnion_subset⟩ theorem subset_sInter {S : set (set α)} {t : set α} (h : ∀t' ∈ S, t ⊆ t') : t ⊆ (⋂₀ S) := le_Inf h theorem sUnion_subset_sUnion {S T : set (set α)} (h : S ⊆ T) : ⋃₀ S ⊆ ⋃₀ T := sUnion_subset $ λ s hs, subset_sUnion_of_mem (h hs) theorem sInter_subset_sInter {S T : set (set α)} (h : S ⊆ T) : ⋂₀ T ⊆ ⋂₀ S := subset_sInter $ λ s hs, sInter_subset_of_mem (h hs) @[simp] theorem sUnion_empty : ⋃₀ ∅ = (∅ : set α) := Sup_empty @[simp] theorem sInter_empty : ⋂₀ ∅ = (univ : set α) := Inf_empty @[simp] theorem sUnion_singleton (s : set α) : ⋃₀ {s} = s := Sup_singleton @[simp] theorem sInter_singleton (s : set α) : ⋂₀ {s} = s := Inf_singleton @[simp] theorem sUnion_eq_empty {S : set (set α)} : (⋃₀ S) = ∅ ↔ ∀ s ∈ S, s = ∅ := Sup_eq_bot @[simp] theorem sInter_eq_univ {S : set (set α)} : (⋂₀ S) = univ ↔ ∀ s ∈ S, s = univ := Inf_eq_top @[simp] theorem nonempty_sUnion {S : set (set α)} : (⋃₀ S).nonempty ↔ ∃ s ∈ S, set.nonempty s := by simp [← ne_empty_iff_nonempty] lemma nonempty.of_sUnion {s : set (set α)} (h : (⋃₀ s).nonempty) : s.nonempty := let ⟨s, hs, _⟩ := nonempty_sUnion.1 h in ⟨s, hs⟩ lemma nonempty.of_sUnion_eq_univ [nonempty α] {s : set (set α)} (h : ⋃₀ s = univ) : s.nonempty := nonempty.of_sUnion $ h.symm ▸ univ_nonempty theorem sUnion_union (S T : set (set α)) : ⋃₀ (S ∪ T) = ⋃₀ S ∪ ⋃₀ T := Sup_union theorem sInter_union (S T : set (set α)) : ⋂₀ (S ∪ T) = ⋂₀ S ∩ ⋂₀ T := Inf_union theorem sInter_Union (s : ι → set (set α)) : ⋂₀ (⋃ i, s i) = ⋂ i, ⋂₀ s i := begin ext x, simp only [mem_Union, mem_Inter, mem_sInter, exists_imp_distrib], split ; tauto end @[simp] theorem sUnion_insert (s : set α) (T : set (set α)) : ⋃₀ (insert s T) = s ∪ ⋃₀ T := Sup_insert @[simp] theorem sInter_insert (s : set α) (T : set (set α)) : ⋂₀ (insert s T) = s ∩ ⋂₀ T := Inf_insert theorem sUnion_pair (s t : set α) : ⋃₀ {s, t} = s ∪ t := Sup_pair theorem sInter_pair (s t : set α) : ⋂₀ {s, t} = s ∩ t := Inf_pair @[simp] theorem sUnion_image (f : α → set β) (s : set α) : ⋃₀ (f '' s) = ⋃ x ∈ s, f x := Sup_image @[simp] theorem sInter_image (f : α → set β) (s : set α) : ⋂₀ (f '' s) = ⋂ x ∈ s, f x := Inf_image @[simp] theorem sUnion_range (f : ι → set β) : ⋃₀ (range f) = ⋃ x, f x := rfl @[simp] theorem sInter_range (f : ι → set β) : ⋂₀ (range f) = ⋂ x, f x := rfl lemma Union_eq_univ_iff {f : ι → set α} : (⋃ i, f i) = univ ↔ ∀ x, ∃ i, x ∈ f i := by simp only [eq_univ_iff_forall, mem_Union] lemma bUnion_eq_univ_iff {f : α → set β} {s : set α} : (⋃ x ∈ s, f x) = univ ↔ ∀ y, ∃ x ∈ s, y ∈ f x := by simp only [Union_eq_univ_iff, mem_Union] lemma sUnion_eq_univ_iff {c : set (set α)} : ⋃₀ c = univ ↔ ∀ a, ∃ b ∈ c, a ∈ b := by simp only [eq_univ_iff_forall, mem_sUnion] theorem compl_sUnion (S : set (set α)) : (⋃₀ S)ᶜ = ⋂₀ (compl '' S) := ext $ λ x, by simp -- classical theorem sUnion_eq_compl_sInter_compl (S : set (set α)) : ⋃₀ S = (⋂₀ (compl '' S))ᶜ := by rw [←compl_compl (⋃₀ S), compl_sUnion] -- classical theorem compl_sInter (S : set (set α)) : (⋂₀ S)ᶜ = ⋃₀ (compl '' S) := by rw [sUnion_eq_compl_sInter_compl, compl_compl_image] -- classical theorem sInter_eq_comp_sUnion_compl (S : set (set α)) : ⋂₀ S = (⋃₀ (compl '' S))ᶜ := by rw [←compl_compl (⋂₀ S), compl_sInter] theorem inter_empty_of_inter_sUnion_empty {s t : set α} {S : set (set α)} (hs : t ∈ S) (h : s ∩ ⋃₀ S = ∅) : s ∩ t = ∅ := eq_empty_of_subset_empty $ by rw ← h; exact inter_subset_inter_right _ (subset_sUnion_of_mem hs) theorem range_sigma_eq_Union_range {γ : α → Type*} (f : sigma γ → β) : range f = ⋃ a, range (λ b, f ⟨a, b⟩) := set.ext $ by simp theorem Union_eq_range_sigma (s : α → set β) : (⋃ i, s i) = range (λ a : Σ i, s i, a.2) := by simp [set.ext_iff] theorem Union_image_preimage_sigma_mk_eq_self {ι : Type*} {σ : ι → Type*} (s : set (sigma σ)) : (⋃ i, sigma.mk i '' (sigma.mk i ⁻¹' s)) = s := begin ext x, simp only [mem_Union, mem_image, mem_preimage], split, { rintros ⟨i, a, h, rfl⟩, exact h }, { intro h, cases x with i a, exact ⟨i, a, h, rfl⟩ } end lemma sUnion_mono {s t : set (set α)} (h : s ⊆ t) : (⋃₀ s) ⊆ (⋃₀ t) := sUnion_subset $ assume t' ht', subset_sUnion_of_mem $ h ht' lemma Union_subset_Union {s t : ι → set α} (h : ∀i, s i ⊆ t i) : (⋃i, s i) ⊆ (⋃i, t i) := @supr_le_supr (set α) ι _ s t h lemma Union_subset_Union2 {s : ι → set α} {t : ι₂ → set α} (h : ∀i, ∃j, s i ⊆ t j) : (⋃i, s i) ⊆ (⋃i, t i) := @supr_le_supr2 (set α) ι ι₂ _ s t h lemma Union_subset_Union_const {s : set α} (h : ι → ι₂) : (⋃ i:ι, s) ⊆ (⋃ j:ι₂, s) := @supr_le_supr_const (set α) ι ι₂ _ s h @[simp] lemma Union_of_singleton (α : Type*) : (⋃(x : α), {x}) = @set.univ α := ext $ λ x, ⟨λ h, ⟨⟩, λ h, ⟨{x}, ⟨⟨x, rfl⟩, mem_singleton x⟩⟩⟩ @[simp] lemma Union_of_singleton_coe (s : set α) : (⋃ (i : s), {i} : set α) = s := ext $ by simp theorem bUnion_subset_Union (s : set α) (t : α → set β) : (⋃ x ∈ s, t x) ⊆ (⋃ x, t x) := Union_subset_Union $ λ i, Union_subset $ λ h, by refl lemma sUnion_eq_bUnion {s : set (set α)} : (⋃₀ s) = (⋃ (i : set α) (h : i ∈ s), i) := by rw [← sUnion_image, image_id'] lemma sInter_eq_bInter {s : set (set α)} : (⋂₀ s) = (⋂ (i : set α) (h : i ∈ s), i) := by rw [← sInter_image, image_id'] lemma sUnion_eq_Union {s : set (set α)} : (⋃₀ s) = (⋃ (i : s), i) := by simp only [←sUnion_range, subtype.range_coe] lemma sInter_eq_Inter {s : set (set α)} : (⋂₀ s) = (⋂ (i : s), i) := by simp only [←sInter_range, subtype.range_coe] lemma union_eq_Union {s₁ s₂ : set α} : s₁ ∪ s₂ = ⋃ b : bool, cond b s₁ s₂ := set.ext $ λ x, by simp [bool.exists_bool, or_comm] lemma inter_eq_Inter {s₁ s₂ : set α} : s₁ ∩ s₂ = ⋂ b : bool, cond b s₁ s₂ := set.ext $ λ x, by simp [bool.forall_bool, and_comm] instance : complete_boolean_algebra (set α) := { compl := compl, sdiff := (\), infi_sup_le_sup_Inf := assume s t x, show x ∈ (⋂ b ∈ t, s ∪ b) → x ∈ s ∪ (⋂₀ t), by simp; exact assume h, or.imp_right (assume hn : x ∉ s, assume i hi, or.resolve_left (h i hi) hn) (classical.em $ x ∈ s), inf_Sup_le_supr_inf := assume s t x, show x ∈ s ∩ (⋃₀ t) → x ∈ (⋃ b ∈ t, s ∩ b), by simp [-and_imp, and.left_comm], .. set.boolean_algebra, .. set.lattice_set } lemma sInter_union_sInter {S T : set (set α)} : (⋂₀S) ∪ (⋂₀T) = (⋂p ∈ S.prod T, (p : (set α) × (set α)).1 ∪ p.2) := Inf_sup_Inf lemma sUnion_inter_sUnion {s t : set (set α)} : (⋃₀s) ∩ (⋃₀t) = (⋃p ∈ s.prod t, (p : (set α) × (set α )).1 ∩ p.2) := Sup_inf_Sup /-- If `S` is a set of sets, and each `s ∈ S` can be represented as an intersection of sets `T s hs`, then `⋂₀ S` is the intersection of the union of all `T s hs`. -/ lemma sInter_bUnion {S : set (set α)} {T : Π s ∈ S, set (set α)} (hT : ∀s∈S, s = ⋂₀ T s ‹s ∈ S›) : ⋂₀ (⋃s∈S, T s ‹_›) = ⋂₀ S := begin ext, simp only [and_imp, exists_prop, set.mem_sInter, set.mem_Union, exists_imp_distrib], split, { assume H s sS, rw [hT s sS, mem_sInter], assume t tTs, exact H t s sS tTs }, { assume H t s sS tTs, suffices : s ⊆ t, exact this (H s sS), rw [hT s sS, sInter_eq_bInter], exact bInter_subset_of_mem tTs } end /-- If `S` is a set of sets, and each `s ∈ S` can be represented as an union of sets `T s hs`, then `⋃₀ S` is the union of the union of all `T s hs`. -/ lemma sUnion_bUnion {S : set (set α)} {T : Π s ∈ S, set (set α)} (hT : ∀s∈S, s = ⋃₀ T s ‹_›) : ⋃₀ (⋃s∈S, T s ‹_›) = ⋃₀ S := begin ext, simp only [exists_prop, set.mem_Union, set.mem_set_of_eq], split, { rintros ⟨t, ⟨⟨s, ⟨sS, tTs⟩⟩, xt⟩⟩, refine ⟨s, ⟨sS, _⟩⟩, rw hT s sS, exact subset_sUnion_of_mem tTs xt }, { rintros ⟨s, ⟨sS, xs⟩⟩, rw hT s sS at xs, rcases mem_sUnion.1 xs with ⟨t, tTs, xt⟩, exact ⟨t, ⟨⟨s, ⟨sS, tTs⟩⟩, xt⟩⟩ } end lemma Union_range_eq_sUnion {α β : Type*} (C : set (set α)) {f : ∀(s : C), β → s} (hf : ∀(s : C), surjective (f s)) : (⋃(y : β), range (λ(s : C), (f s y).val)) = ⋃₀ C := begin ext x, split, { rintro ⟨s, ⟨y, rfl⟩, ⟨⟨s, hs⟩, rfl⟩⟩, refine ⟨_, hs, _⟩, exact (f ⟨s, hs⟩ y).2 }, { rintro ⟨s, hs, hx⟩, cases hf ⟨s, hs⟩ ⟨x, hx⟩ with y hy, refine ⟨_, ⟨y, rfl⟩, ⟨⟨s, hs⟩, _⟩⟩, exact congr_arg subtype.val hy } end lemma Union_range_eq_Union {ι α β : Type*} (C : ι → set α) {f : ∀(x : ι), β → C x} (hf : ∀(x : ι), surjective (f x)) : (⋃(y : β), range (λ(x : ι), (f x y).val)) = ⋃x, C x := begin ext x, rw [mem_Union, mem_Union], split, { rintro ⟨y, ⟨i, rfl⟩⟩, exact ⟨i, (f i y).2⟩ }, { rintro ⟨i, hx⟩, cases hf i ⟨x, hx⟩ with y hy, refine ⟨y, ⟨i, congr_arg subtype.val hy⟩⟩ } end lemma union_distrib_Inter_right {ι : Type*} (s : ι → set α) (t : set α) : (⋂ i, s i) ∪ t = (⋂ i, s i ∪ t) := begin ext x, rw [mem_union_eq, mem_Inter], split ; finish end lemma union_distrib_Inter_left {ι : Type*} (s : ι → set α) (t : set α) : t ∪ (⋂ i, s i) = (⋂ i, t ∪ s i) := begin rw [union_comm, union_distrib_Inter_right], simp [union_comm] end section function /-! ### `maps_to` -/ lemma maps_to_sUnion {S : set (set α)} {t : set β} {f : α → β} (H : ∀ s ∈ S, maps_to f s t) : maps_to f (⋃₀ S) t := λ x ⟨s, hs, hx⟩, H s hs hx lemma maps_to_Union {s : ι → set α} {t : set β} {f : α → β} (H : ∀ i, maps_to f (s i) t) : maps_to f (⋃ i, s i) t := maps_to_sUnion $ forall_range_iff.2 H lemma maps_to_bUnion {p : ι → Prop} {s : Π (i : ι) (hi : p i), set α} {t : set β} {f : α → β} (H : ∀ i hi, maps_to f (s i hi) t) : maps_to f (⋃ i hi, s i hi) t := maps_to_Union $ λ i, maps_to_Union (H i) lemma maps_to_Union_Union {s : ι → set α} {t : ι → set β} {f : α → β} (H : ∀ i, maps_to f (s i) (t i)) : maps_to f (⋃ i, s i) (⋃ i, t i) := maps_to_Union $ λ i, (H i).mono (subset.refl _) (subset_Union t i) lemma maps_to_bUnion_bUnion {p : ι → Prop} {s : Π i (hi : p i), set α} {t : Π i (hi : p i), set β} {f : α → β} (H : ∀ i hi, maps_to f (s i hi) (t i hi)) : maps_to f (⋃ i hi, s i hi) (⋃ i hi, t i hi) := maps_to_Union_Union $ λ i, maps_to_Union_Union (H i) lemma maps_to_sInter {s : set α} {T : set (set β)} {f : α → β} (H : ∀ t ∈ T, maps_to f s t) : maps_to f s (⋂₀ T) := λ x hx t ht, H t ht hx lemma maps_to_Inter {s : set α} {t : ι → set β} {f : α → β} (H : ∀ i, maps_to f s (t i)) : maps_to f s (⋂ i, t i) := λ x hx, mem_Inter.2 $ λ i, H i hx lemma maps_to_bInter {p : ι → Prop} {s : set α} {t : Π i (hi : p i), set β} {f : α → β} (H : ∀ i hi, maps_to f s (t i hi)) : maps_to f s (⋂ i hi, t i hi) := maps_to_Inter $ λ i, maps_to_Inter (H i) lemma maps_to_Inter_Inter {s : ι → set α} {t : ι → set β} {f : α → β} (H : ∀ i, maps_to f (s i) (t i)) : maps_to f (⋂ i, s i) (⋂ i, t i) := maps_to_Inter $ λ i, (H i).mono (Inter_subset s i) (subset.refl _) lemma maps_to_bInter_bInter {p : ι → Prop} {s : Π i (hi : p i), set α} {t : Π i (hi : p i), set β} {f : α → β} (H : ∀ i hi, maps_to f (s i hi) (t i hi)) : maps_to f (⋂ i hi, s i hi) (⋂ i hi, t i hi) := maps_to_Inter_Inter $ λ i, maps_to_Inter_Inter (H i) lemma image_Inter_subset (s : ι → set α) (f : α → β) : f '' (⋂ i, s i) ⊆ ⋂ i, f '' (s i) := (maps_to_Inter_Inter $ λ i, maps_to_image f (s i)).image_subset lemma image_bInter_subset {p : ι → Prop} (s : Π i (hi : p i), set α) (f : α → β) : f '' (⋂ i hi, s i hi) ⊆ ⋂ i hi, f '' (s i hi) := (maps_to_bInter_bInter $ λ i hi, maps_to_image f (s i hi)).image_subset lemma image_sInter_subset (S : set (set α)) (f : α → β) : f '' (⋂₀ S) ⊆ ⋂ s ∈ S, f '' s := by { rw sInter_eq_bInter, apply image_bInter_subset } /-! ### `inj_on` -/ lemma inj_on.image_Inter_eq [nonempty ι] {s : ι → set α} {f : α → β} (h : inj_on f (⋃ i, s i)) : f '' (⋂ i, s i) = ⋂ i, f '' (s i) := begin inhabit ι, refine subset.antisymm (image_Inter_subset s f) (λ y hy, _), simp only [mem_Inter, mem_image_iff_bex] at hy, choose x hx hy using hy, refine ⟨x (default ι), mem_Inter.2 $ λ i, _, hy _⟩, suffices : x (default ι) = x i, { rw this, apply hx }, replace hx : ∀ i, x i ∈ ⋃ j, s j := λ i, (subset_Union _ _) (hx i), apply h (hx _) (hx _), simp only [hy] end lemma inj_on.image_bInter_eq {p : ι → Prop} {s : Π i (hi : p i), set α} (hp : ∃ i, p i) {f : α → β} (h : inj_on f (⋃ i hi, s i hi)) : f '' (⋂ i hi, s i hi) = ⋂ i hi, f '' (s i hi) := begin simp only [Inter, infi_subtype'], haveI : nonempty {i // p i} := nonempty_subtype.2 hp, apply inj_on.image_Inter_eq, simpa only [Union, supr_subtype'] using h end lemma inj_on_Union_of_directed {s : ι → set α} (hs : directed (⊆) s) {f : α → β} (hf : ∀ i, inj_on f (s i)) : inj_on f (⋃ i, s i) := begin intros x hx y hy hxy, rcases mem_Union.1 hx with ⟨i, hx⟩, rcases mem_Union.1 hy with ⟨j, hy⟩, rcases hs i j with ⟨k, hi, hj⟩, exact hf k (hi hx) (hj hy) hxy end /-! ### `surj_on` -/ lemma surj_on_sUnion {s : set α} {T : set (set β)} {f : α → β} (H : ∀ t ∈ T, surj_on f s t) : surj_on f s (⋃₀ T) := λ x ⟨t, ht, hx⟩, H t ht hx lemma surj_on_Union {s : set α} {t : ι → set β} {f : α → β} (H : ∀ i, surj_on f s (t i)) : surj_on f s (⋃ i, t i) := surj_on_sUnion $ forall_range_iff.2 H lemma surj_on_Union_Union {s : ι → set α} {t : ι → set β} {f : α → β} (H : ∀ i, surj_on f (s i) (t i)) : surj_on f (⋃ i, s i) (⋃ i, t i) := surj_on_Union $ λ i, (H i).mono (subset_Union _ _) (subset.refl _) lemma surj_on_bUnion {p : ι → Prop} {s : set α} {t : Π i (hi : p i), set β} {f : α → β} (H : ∀ i hi, surj_on f s (t i hi)) : surj_on f s (⋃ i hi, t i hi) := surj_on_Union $ λ i, surj_on_Union (H i) lemma surj_on_bUnion_bUnion {p : ι → Prop} {s : Π i (hi : p i), set α} {t : Π i (hi : p i), set β} {f : α → β} (H : ∀ i hi, surj_on f (s i hi) (t i hi)) : surj_on f (⋃ i hi, s i hi) (⋃ i hi, t i hi) := surj_on_Union_Union $ λ i, surj_on_Union_Union (H i) lemma surj_on_Inter [hi : nonempty ι] {s : ι → set α} {t : set β} {f : α → β} (H : ∀ i, surj_on f (s i) t) (Hinj : inj_on f (⋃ i, s i)) : surj_on f (⋂ i, s i) t := begin intros y hy, rw [Hinj.image_Inter_eq, mem_Inter], exact λ i, H i hy end lemma surj_on_Inter_Inter [hi : nonempty ι] {s : ι → set α} {t : ι → set β} {f : α → β} (H : ∀ i, surj_on f (s i) (t i)) (Hinj : inj_on f (⋃ i, s i)) : surj_on f (⋂ i, s i) (⋂ i, t i) := surj_on_Inter (λ i, (H i).mono (subset.refl _) (Inter_subset _ _)) Hinj /-! ### `bij_on` -/ lemma bij_on_Union {s : ι → set α} {t : ι → set β} {f : α → β} (H : ∀ i, bij_on f (s i) (t i)) (Hinj : inj_on f (⋃ i, s i)) : bij_on f (⋃ i, s i) (⋃ i, t i) := ⟨maps_to_Union_Union $ λ i, (H i).maps_to, Hinj, surj_on_Union_Union $ λ i, (H i).surj_on⟩ lemma bij_on_Inter [hi :nonempty ι] {s : ι → set α} {t : ι → set β} {f : α → β} (H : ∀ i, bij_on f (s i) (t i)) (Hinj : inj_on f (⋃ i, s i)) : bij_on f (⋂ i, s i) (⋂ i, t i) := ⟨maps_to_Inter_Inter $ λ i, (H i).maps_to, hi.elim $ λ i, (H i).inj_on.mono (Inter_subset _ _), surj_on_Inter_Inter (λ i, (H i).surj_on) Hinj⟩ lemma bij_on_Union_of_directed {s : ι → set α} (hs : directed (⊆) s) {t : ι → set β} {f : α → β} (H : ∀ i, bij_on f (s i) (t i)) : bij_on f (⋃ i, s i) (⋃ i, t i) := bij_on_Union H $ inj_on_Union_of_directed hs (λ i, (H i).inj_on) lemma bij_on_Inter_of_directed [nonempty ι] {s : ι → set α} (hs : directed (⊆) s) {t : ι → set β} {f : α → β} (H : ∀ i, bij_on f (s i) (t i)) : bij_on f (⋂ i, s i) (⋂ i, t i) := bij_on_Inter H $ inj_on_Union_of_directed hs (λ i, (H i).inj_on) end function section variables {p : Prop} {μ : p → set α} @[simp] lemma Inter_pos (hp : p) : (⋂h:p, μ h) = μ hp := infi_pos hp @[simp] lemma Inter_neg (hp : ¬ p) : (⋂h:p, μ h) = univ := infi_neg hp @[simp] lemma Union_pos (hp : p) : (⋃h:p, μ h) = μ hp := supr_pos hp @[simp] lemma Union_neg (hp : ¬ p) : (⋃h:p, μ h) = ∅ := supr_neg hp @[simp] lemma Union_empty : (⋃i:ι, ∅:set α) = ∅ := supr_bot @[simp] lemma Inter_univ : (⋂i:ι, univ:set α) = univ := infi_top variables {s : ι → set α} @[simp] lemma Union_eq_empty : (⋃ i, s i) = ∅ ↔ ∀ i, s i = ∅ := supr_eq_bot @[simp] lemma Inter_eq_univ : (⋂ i, s i) = univ ↔ ∀ i, s i = univ := infi_eq_top @[simp] lemma nonempty_Union : (⋃ i, s i).nonempty ↔ ∃ i, (s i).nonempty := by simp [← ne_empty_iff_nonempty] end section image lemma image_Union {f : α → β} {s : ι → set α} : f '' (⋃ i, s i) = (⋃i, f '' s i) := begin apply set.ext, intro x, simp [image, exists_and_distrib_right.symm, -exists_and_distrib_right], exact exists_swap end lemma univ_subtype {p : α → Prop} : (univ : set (subtype p)) = (⋃x (h : p x), {⟨x, h⟩}) := set.ext $ assume ⟨x, h⟩, by simp [h] lemma range_eq_Union {ι} (f : ι → α) : range f = (⋃i, {f i}) := set.ext $ assume a, by simp [@eq_comm α a] lemma image_eq_Union (f : α → β) (s : set α) : f '' s = (⋃i∈s, {f i}) := set.ext $ assume b, by simp [@eq_comm β b] @[simp] lemma bUnion_range {f : ι → α} {g : α → set β} : (⋃x ∈ range f, g x) = (⋃y, g (f y)) := supr_range @[simp] lemma bInter_range {f : ι → α} {g : α → set β} : (⋂x ∈ range f, g x) = (⋂y, g (f y)) := infi_range variables {s : set γ} {f : γ → α} {g : α → set β} @[simp] lemma bUnion_image : (⋃x∈ (f '' s), g x) = (⋃y ∈ s, g (f y)) := supr_image @[simp] lemma bInter_image : (⋂x∈ (f '' s), g x) = (⋂y ∈ s, g (f y)) := infi_image end image section preimage theorem monotone_preimage {f : α → β} : monotone (preimage f) := assume a b h, preimage_mono h @[simp] theorem preimage_Union {ι : Sort*} {f : α → β} {s : ι → set β} : preimage f (⋃i, s i) = (⋃i, preimage f (s i)) := set.ext $ by simp [preimage] theorem preimage_bUnion {ι} {f : α → β} {s : set ι} {t : ι → set β} : f ⁻¹' (⋃i ∈ s, t i) = (⋃i ∈ s, f ⁻¹' (t i)) := by simp @[simp] theorem preimage_sUnion {f : α → β} {s : set (set β)} : f ⁻¹' (⋃₀ s) = (⋃t ∈ s, f ⁻¹' t) := set.ext $ by simp [preimage] lemma preimage_Inter {ι : Sort*} {s : ι → set β} {f : α → β} : f ⁻¹' (⋂ i, s i) = (⋂ i, f ⁻¹' s i) := by ext; simp lemma preimage_bInter {s : γ → set β} {t : set γ} {f : α → β} : f ⁻¹' (⋂ i∈t, s i) = (⋂ i∈t, f ⁻¹' s i) := by ext; simp @[simp] lemma bUnion_preimage_singleton (f : α → β) (s : set β) : (⋃ y ∈ s, f ⁻¹' {y}) = f ⁻¹' s := by rw [← preimage_bUnion, bUnion_of_singleton] lemma bUnion_range_preimage_singleton (f : α → β) : (⋃ y ∈ range f, f ⁻¹' {y}) = univ := by simp end preimage section prod theorem monotone_prod [preorder α] {f : α → set β} {g : α → set γ} (hf : monotone f) (hg : monotone g) : monotone (λx, (f x).prod (g x)) := assume a b h, prod_mono (hf h) (hg h) alias monotone_prod ← monotone.set_prod lemma prod_Union {ι} {s : set α} {t : ι → set β} : s.prod (⋃ i, t i) = ⋃ i, s.prod (t i) := by { ext, simp } lemma prod_bUnion {ι} {u : set ι} {s : set α} {t : ι → set β} : s.prod (⋃ i ∈ u, t i) = ⋃ i ∈ u, s.prod (t i) := by simp_rw [prod_Union] lemma prod_sUnion {s : set α} {C : set (set β)} : s.prod (⋃₀ C) = ⋃₀ ((λ t, s.prod t) '' C) := by { simp only [sUnion_eq_bUnion, prod_bUnion, bUnion_image] } lemma Union_prod_const {ι} {s : ι → set α} {t : set β} : (⋃ i, s i).prod t = ⋃ i, (s i).prod t := by { ext, simp } lemma bUnion_prod_const {ι} {u : set ι} {s : ι → set α} {t : set β} : (⋃ i ∈ u, s i).prod t = ⋃ i ∈ u, (s i).prod t := by simp_rw [Union_prod_const] lemma sUnion_prod_const {C : set (set α)} {t : set β} : (⋃₀ C).prod t = ⋃₀ ((λ s : set α, s.prod t) '' C) := by { simp only [sUnion_eq_bUnion, bUnion_prod_const, bUnion_image] } lemma Union_prod {ι α β} (s : ι → set α) (t : ι → set β) : (⋃ (x : ι × ι), (s x.1).prod (t x.2)) = (⋃ (i : ι), s i).prod (⋃ (i : ι), t i) := by { ext, simp } lemma Union_prod_of_monotone [semilattice_sup α] {s : α → set β} {t : α → set γ} (hs : monotone s) (ht : monotone t) : (⋃ x, (s x).prod (t x)) = (⋃ x, (s x)).prod (⋃ x, (t x)) := begin ext ⟨z, w⟩, simp only [mem_prod, mem_Union, exists_imp_distrib, and_imp, iff_def], split, { intros x hz hw, exact ⟨⟨x, hz⟩, ⟨x, hw⟩⟩ }, { intros x hz x' hw, exact ⟨x ⊔ x', hs le_sup_left hz, ht le_sup_right hw⟩ } end end prod section image2 variables (f : α → β → γ) {s : set α} {t : set β} lemma Union_image_left : (⋃ a ∈ s, f a '' t) = image2 f s t := by { ext y, split; simp only [mem_Union]; rintros ⟨a, ha, x, hx, ax⟩; exact ⟨a, x, ha, hx, ax⟩ } lemma Union_image_right : (⋃ b ∈ t, (λ a, f a b) '' s) = image2 f s t := by { ext y, split; simp only [mem_Union]; rintros ⟨a, b, c, d, e⟩, exact ⟨c, a, d, b, e⟩, exact ⟨b, d, a, c, e⟩ } lemma image2_Union_left (s : ι → set α) (t : set β) : image2 f (⋃ i, s i) t = ⋃ i, image2 f (s i) t := by simp only [← image_prod, Union_prod_const, image_Union] lemma image2_Union_right (s : set α) (t : ι → set β) : image2 f s (⋃ i, t i) = ⋃ i, image2 f s (t i) := by simp only [← image_prod, prod_Union, image_Union] end image2 section seq /-- Given a set `s` of functions `α → β` and `t : set α`, `seq s t` is the union of `f '' t` over all `f ∈ s`. -/ def seq (s : set (α → β)) (t : set α) : set β := {b | ∃f∈s, ∃a∈t, (f : α → β) a = b} lemma seq_def {s : set (α → β)} {t : set α} : seq s t = ⋃f∈s, f '' t := set.ext $ by simp [seq] @[simp] lemma mem_seq_iff {s : set (α → β)} {t : set α} {b : β} : b ∈ seq s t ↔ ∃ (f ∈ s) (a ∈ t), (f : α → β) a = b := iff.rfl lemma seq_subset {s : set (α → β)} {t : set α} {u : set β} : seq s t ⊆ u ↔ (∀f∈s, ∀a∈t, (f : α → β) a ∈ u) := iff.intro (assume h f hf a ha, h ⟨f, hf, a, ha, rfl⟩) (assume h b ⟨f, hf, a, ha, eq⟩, eq ▸ h f hf a ha) lemma seq_mono {s₀ s₁ : set (α → β)} {t₀ t₁ : set α} (hs : s₀ ⊆ s₁) (ht : t₀ ⊆ t₁) : seq s₀ t₀ ⊆ seq s₁ t₁ := assume b ⟨f, hf, a, ha, eq⟩, ⟨f, hs hf, a, ht ha, eq⟩ lemma singleton_seq {f : α → β} {t : set α} : set.seq {f} t = f '' t := set.ext $ by simp lemma seq_singleton {s : set (α → β)} {a : α} : set.seq s {a} = (λf:α→β, f a) '' s := set.ext $ by simp lemma seq_seq {s : set (β → γ)} {t : set (α → β)} {u : set α} : seq s (seq t u) = seq (seq ((∘) '' s) t) u := begin refine set.ext (assume c, iff.intro _ _), { rintros ⟨f, hfs, b, ⟨g, hg, a, hau, rfl⟩, rfl⟩, exact ⟨f ∘ g, ⟨(∘) f, mem_image_of_mem _ hfs, g, hg, rfl⟩, a, hau, rfl⟩ }, { rintros ⟨fg, ⟨fc, ⟨f, hfs, rfl⟩, g, hgt, rfl⟩, a, ha, rfl⟩, exact ⟨f, hfs, g a, ⟨g, hgt, a, ha, rfl⟩, rfl⟩ } end lemma image_seq {f : β → γ} {s : set (α → β)} {t : set α} : f '' seq s t = seq ((∘) f '' s) t := by rw [← singleton_seq, ← singleton_seq, seq_seq, image_singleton] lemma prod_eq_seq {s : set α} {t : set β} : s.prod t = (prod.mk '' s).seq t := begin ext ⟨a, b⟩, split, { rintros ⟨ha, hb⟩, exact ⟨prod.mk a, ⟨a, ha, rfl⟩, b, hb, rfl⟩ }, { rintros ⟨f, ⟨x, hx, rfl⟩, y, hy, eq⟩, rw ← eq, exact ⟨hx, hy⟩ } end lemma prod_image_seq_comm (s : set α) (t : set β) : (prod.mk '' s).seq t = seq ((λb a, (a, b)) '' t) s := by rw [← prod_eq_seq, ← image_swap_prod, prod_eq_seq, image_seq, ← image_comp, prod.swap] lemma image2_eq_seq (f : α → β → γ) (s : set α) (t : set β) : image2 f s t = seq (f '' s) t := by { ext, simp } end seq instance : monad set := { pure := λ(α : Type u) a, {a}, bind := λ(α β : Type u) s f, ⋃i∈s, f i, seq := λ(α β : Type u), set.seq, map := λ(α β : Type u), set.image } section monad variables {α' β' : Type u} {s : set α'} {f : α' → set β'} {g : set (α' → β')} @[simp] lemma bind_def : s >>= f = ⋃i∈s, f i := rfl @[simp] lemma fmap_eq_image (f : α' → β') : f <$> s = f '' s := rfl @[simp] lemma seq_eq_set_seq {α β : Type*} (s : set (α → β)) (t : set α) : s <*> t = s.seq t := rfl @[simp] lemma pure_def (a : α) : (pure a : set α) = {a} := rfl end monad instance : is_lawful_monad set := { pure_bind := assume α β x f, by simp, bind_assoc := assume α β γ s f g, set.ext $ assume a, by simp [exists_and_distrib_right.symm, -exists_and_distrib_right, exists_and_distrib_left.symm, -exists_and_distrib_left, and_assoc]; exact exists_swap, id_map := assume α, id_map, bind_pure_comp_eq_map := assume α β f s, set.ext $ by simp [set.image, eq_comm], bind_map_eq_seq := assume α β s t, by simp [seq_def] } instance : is_comm_applicative (set : Type u → Type u) := ⟨ assume α β s t, prod_image_seq_comm s t ⟩ section pi variables {π : α → Type*} lemma pi_def (i : set α) (s : Πa, set (π a)) : pi i s = (⋂ a ∈ i, eval a ⁻¹' s a) := by { ext, simp } lemma univ_pi_eq_Inter (t : Π i, set (π i)) : pi univ t = ⋂ i, eval i ⁻¹' t i := by simp only [pi_def, Inter_pos, mem_univ] lemma pi_diff_pi_subset (i : set α) (s t : Πa, set (π a)) : pi i s \ pi i t ⊆ ⋃ a ∈ i, (eval a ⁻¹' (s a \ t a)) := begin refine diff_subset_comm.2 (λ x hx a ha, _), simp only [mem_diff, mem_pi, mem_Union, not_exists, mem_preimage, not_and, not_not, eval_apply] at hx, exact hx.2 _ ha (hx.1 _ ha) end lemma Union_univ_pi (t : Π i, ι → set (π i)) : (⋃ (x : α → ι), pi univ (λ i, t i (x i))) = pi univ (λ i, ⋃ (j : ι), t i j) := by { ext, simp [classical.skolem] } end pi end set namespace function namespace surjective lemma Union_comp {f : ι → ι₂} (hf : surjective f) (g : ι₂ → set α) : (⋃ x, g (f x)) = ⋃ y, g y := hf.supr_comp g lemma Inter_comp {f : ι → ι₂} (hf : surjective f) (g : ι₂ → set α) : (⋂ x, g (f x)) = ⋂ y, g y := hf.infi_comp g end surjective end function /-! ### Disjoint sets -/ section disjoint variables {s t u : set α} namespace disjoint /-! We define some lemmas in the `disjoint` namespace to be able to use projection notation. -/ theorem union_left (hs : disjoint s u) (ht : disjoint t u) : disjoint (s ∪ t) u := hs.sup_left ht theorem union_right (ht : disjoint s t) (hu : disjoint s u) : disjoint s (t ∪ u) := ht.sup_right hu lemma preimage {α β} (f : α → β) {s t : set β} (h : disjoint s t) : disjoint (f ⁻¹' s) (f ⁻¹' t) := λ x hx, h hx end disjoint namespace set protected theorem disjoint_iff : disjoint s t ↔ s ∩ t ⊆ ∅ := iff.rfl theorem disjoint_iff_inter_eq_empty : disjoint s t ↔ s ∩ t = ∅ := disjoint_iff lemma not_disjoint_iff : ¬disjoint s t ↔ ∃x, x ∈ s ∧ x ∈ t := not_forall.trans $ exists_congr $ λ x, not_not lemma disjoint_left : disjoint s t ↔ ∀ {a}, a ∈ s → a ∉ t := show (∀ x, ¬(x ∈ s ∩ t)) ↔ _, from ⟨λ h a, not_and.1 $ h a, λ h a, not_and.2 $ h a⟩ theorem disjoint_right : disjoint s t ↔ ∀ {a}, a ∈ t → a ∉ s := by rw [disjoint.comm, disjoint_left] theorem disjoint_of_subset_left (h : s ⊆ u) (d : disjoint u t) : disjoint s t := d.mono_left h theorem disjoint_of_subset_right (h : t ⊆ u) (d : disjoint s u) : disjoint s t := d.mono_right h theorem disjoint_of_subset {s t u v : set α} (h1 : s ⊆ u) (h2 : t ⊆ v) (d : disjoint u v) : disjoint s t := d.mono h1 h2 @[simp] theorem disjoint_union_left : disjoint (s ∪ t) u ↔ disjoint s u ∧ disjoint t u := disjoint_sup_left @[simp] theorem disjoint_union_right : disjoint s (t ∪ u) ↔ disjoint s t ∧ disjoint s u := disjoint_sup_right @[simp] theorem disjoint_Union_left {ι : Sort*} {s : ι → set α} : disjoint (⋃ i, s i) t ↔ ∀ i, disjoint (s i) t := supr_disjoint_iff @[simp] theorem disjoint_Union_right {ι : Sort*} {s : ι → set α} : disjoint t (⋃ i, s i) ↔ ∀ i, disjoint t (s i) := disjoint_supr_iff theorem disjoint_diff {a b : set α} : disjoint a (b \ a) := disjoint_iff.2 (inter_diff_self _ _) @[simp] theorem disjoint_empty (s : set α) : disjoint s ∅ := disjoint_bot_right @[simp] theorem empty_disjoint (s : set α) : disjoint ∅ s := disjoint_bot_left @[simp] lemma univ_disjoint {s : set α}: disjoint univ s ↔ s = ∅ := top_disjoint @[simp] lemma disjoint_univ {s : set α} : disjoint s univ ↔ s = ∅ := disjoint_top @[simp] theorem disjoint_singleton_left {a : α} {s : set α} : disjoint {a} s ↔ a ∉ s := by simp [set.disjoint_iff, subset_def]; exact iff.rfl @[simp] theorem disjoint_singleton_right {a : α} {s : set α} : disjoint s {a} ↔ a ∉ s := by rw [disjoint.comm]; exact disjoint_singleton_left theorem disjoint_image_image {f : β → α} {g : γ → α} {s : set β} {t : set γ} (h : ∀b∈s, ∀c∈t, f b ≠ g c) : disjoint (f '' s) (g '' t) := by rintros a ⟨⟨b, hb, eq⟩, ⟨c, hc, rfl⟩⟩; exact h b hb c hc eq theorem pairwise_on_disjoint_fiber (f : α → β) (s : set β) : pairwise_on s (disjoint on (λ y, f ⁻¹' {y})) := λ y₁ _ y₂ _ hy x ⟨hx₁, hx₂⟩, hy (eq.trans (eq.symm hx₁) hx₂) lemma preimage_eq_empty {f : α → β} {s : set β} (h : disjoint s (range f)) : f ⁻¹' s = ∅ := by simpa using h.preimage f lemma preimage_eq_empty_iff {f : α → β} {s : set β} : disjoint s (range f) ↔ f ⁻¹' s = ∅ := ⟨preimage_eq_empty, λ h, by { simp [eq_empty_iff_forall_not_mem, set.disjoint_iff_inter_eq_empty] at h ⊢, finish }⟩ end set end disjoint namespace set /-- A collection of sets is `pairwise_disjoint`, if any two different sets in this collection are disjoint. -/ def pairwise_disjoint (s : set (set α)) : Prop := pairwise_on s disjoint lemma pairwise_disjoint.subset {s t : set (set α)} (h : s ⊆ t) (ht : pairwise_disjoint t) : pairwise_disjoint s := pairwise_on.mono h ht lemma pairwise_disjoint.range {s : set (set α)} (f : s → set α) (hf : ∀(x : s), f x ⊆ x.1) (ht : pairwise_disjoint s) : pairwise_disjoint (range f) := begin rintro _ ⟨x, rfl⟩ _ ⟨y, rfl⟩ hxy, refine (ht _ x.2 _ y.2 _).mono (hf x) (hf y), intro h, apply hxy, apply congr_arg f, exact subtype.eq h end /- classical -/ lemma pairwise_disjoint.elim {s : set (set α)} (h : pairwise_disjoint s) {x y : set α} (hx : x ∈ s) (hy : y ∈ s) (z : α) (hzx : z ∈ x) (hzy : z ∈ y) : x = y := not_not.1 $ λ h', h x hx y hy h' ⟨hzx, hzy⟩ end set namespace set variables (t : α → set β) lemma subset_diff {s t u : set α} : s ⊆ t \ u ↔ s ⊆ t ∧ disjoint s u := ⟨λ h, ⟨λ x hxs, (h hxs).1, λ x ⟨hxs, hxu⟩, (h hxs).2 hxu⟩, λ ⟨h1, h2⟩ x hxs, ⟨h1 hxs, λ hxu, h2 ⟨hxs, hxu⟩⟩⟩ /-- If `t` is an indexed family of sets, then there is a natural map from `Σ i, t i` to `⋃ i, t i` sending `⟨i, x⟩` to `x`. -/ def sigma_to_Union (x : Σi, t i) : (⋃i, t i) := ⟨x.2, mem_Union.2 ⟨x.1, x.2.2⟩⟩ lemma sigma_to_Union_surjective : surjective (sigma_to_Union t) | ⟨b, hb⟩ := have ∃a, b ∈ t a, by simpa using hb, let ⟨a, hb⟩ := this in ⟨⟨a, ⟨b, hb⟩⟩, rfl⟩ lemma sigma_to_Union_injective (h : ∀i j, i ≠ j → disjoint (t i) (t j)) : injective (sigma_to_Union t) | ⟨a₁, ⟨b₁, h₁⟩⟩ ⟨a₂, ⟨b₂, h₂⟩⟩ eq := have b_eq : b₁ = b₂, from congr_arg subtype.val eq, have a_eq : a₁ = a₂, from classical.by_contradiction $ assume ne, have b₁ ∈ t a₁ ∩ t a₂, from ⟨h₁, b_eq.symm ▸ h₂⟩, h _ _ ne this, sigma.eq a_eq $ subtype.eq $ by subst b_eq; subst a_eq lemma sigma_to_Union_bijective (h : ∀i j, i ≠ j → disjoint (t i) (t j)) : bijective (sigma_to_Union t) := ⟨sigma_to_Union_injective t h, sigma_to_Union_surjective t⟩ /-- Equivalence between a disjoint union and a dependent sum. -/ noncomputable def Union_eq_sigma_of_disjoint {t : α → set β} (h : ∀i j, i ≠ j → disjoint (t i) (t j)) : (⋃i, t i) ≃ (Σi, t i) := (equiv.of_bijective _ $ sigma_to_Union_bijective t h).symm /-- Equivalence between a disjoint bounded union and a dependent sum. -/ noncomputable def bUnion_eq_sigma_of_disjoint {s : set α} {t : α → set β} (h : pairwise_on s (disjoint on t)) : (⋃i∈s, t i) ≃ (Σi:s, t i.val) := equiv.trans (equiv.set_congr (bUnion_eq_Union _ _)) $ Union_eq_sigma_of_disjoint $ assume ⟨i, hi⟩ ⟨j, hj⟩ ne, h _ hi _ hj $ assume eq, ne $ subtype.eq eq end set
3966674c09440af4c2b102d5ad2438c7c2658864
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/qexpr2.lean
2be8db4c9acca2909eb75a68995a95b4353bbe25
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
280
lean
open tactic set_option pp.all true example (a b c : nat) : true := by do x ← to_expr ```(_ + b) tt, trace x, infer_type x >>= trace, constructor, -- fill hole with 'c' get_local `c >>= exact, trace "------ after instantiate_mvars", instantiate_mvars x >>= trace
0dddc3d03ac35fa2a1c7dfbf4fe0059a31fb4b35
b24beef0a8b1a8e92be756a25aa78e24908b2b14
/src/for_mathlib/manifolds.lean
97cdfa8d50ff93abfa8590a071ed06edea72b5f9
[]
permissive
ChristopheMargerin/lftcm2020
14967e74cbe92a7b61d32d8130f32cfa09b5172b
589180047fa4fdfb3179636db58b0b0320549871
refs/heads/master
1,668,536,269,632
1,594,891,664,000
1,594,891,664,000
280,112,730
0
0
MIT
1,594,891,963,000
1,594,891,962,000
null
UTF-8
Lean
false
false
2,012
lean
import geometry.manifold.times_cont_mdiff import geometry.manifold.real_instances open set instance : has_zero (Icc (0 : ℝ) 1) := ⟨⟨(0 : ℝ), ⟨le_refl _, zero_le_one⟩⟩⟩ instance : has_one (Icc (0 : ℝ) 1) := ⟨⟨(1 : ℝ), ⟨zero_le_one, le_refl _⟩⟩⟩ namespace metric lemma is_closed_sphere {α : Type*} [metric_space α] {x : α} {r : ℝ} : is_closed (sphere x r) := is_closed_eq (continuous_id.dist continuous_const) continuous_const end metric section fderiv_id variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] variables {E : Type*} [normed_group E] [normed_space 𝕜 E] lemma fderiv_id' {x : E} : fderiv 𝕜 (λ (x : E), x) x = continuous_linear_map.id 𝕜 E := fderiv_id end fderiv_id lemma pi_Lp.norm_coord_le_norm {ι : Type*} [fintype ι] {p : ℝ} {hp : 1 ≤ p} {α : ι → Type*} [∀i, normed_group (α i)] (x : pi_Lp p hp α) (i : ι) : ∥x i∥ ≤ ∥x∥ := calc ∥x i∥ ≤ (∥x i∥ ^ p) ^ (1/p) : begin have : p ≠ 0 := ne_of_gt (lt_of_lt_of_le zero_lt_one hp), rw [← real.rpow_mul (norm_nonneg _), mul_one_div_cancel this, real.rpow_one], end ... ≤ _ : begin have A : ∀ j, 0 ≤ ∥x j∥ ^ p := λ j, real.rpow_nonneg_of_nonneg (norm_nonneg _) _, simp only [pi_Lp.norm_eq, one_mul, linear_map.coe_mk], apply real.rpow_le_rpow (A i), { exact finset.single_le_sum (λ j hj, A j) (finset.mem_univ _) }, { exact div_nonneg zero_le_one (lt_of_lt_of_le zero_lt_one hp) } end lemma pi_Lp.times_cont_diff_coord {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {ι : Type*} [fintype ι] {p : ℝ} {hp : 1 ≤ p} {α : ι → Type*} {n : with_top ℕ} (i : ι) [∀i, normed_group (α i)] [∀i, normed_space 𝕜 (α i)] : times_cont_diff 𝕜 n (λ x : pi_Lp p hp α, x i) := let F : pi_Lp p hp α →ₗ[𝕜] α i := { to_fun := λ x, x i, map_add' := λ x y, rfl, map_smul' := λ x c, rfl } in (F.mk_continuous 1 (λ x, by simpa using pi_Lp.norm_coord_le_norm x i)).times_cont_diff
b102cf29b05f397852721d8159b7ba40319404ea
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/order/succ_pred/basic.lean
c9f22fb29d788e26253c3bd64e6d0eb5b3070888
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
41,695
lean
/- Copyright (c) 2021 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import order.complete_lattice import order.cover import order.iterate /-! # Successor and predecessor This file defines successor and predecessor orders. `succ a`, the successor of an element `a : α` is the least element greater than `a`. `pred a` is the greatest element less than `a`. Typical examples include `ℕ`, `ℤ`, `ℕ+`, `fin n`, but also `enat`, the lexicographic order of a successor/predecessor order... ## Typeclasses * `succ_order`: Order equipped with a sensible successor function. * `pred_order`: Order equipped with a sensible predecessor function. * `is_succ_archimedean`: `succ_order` where `succ` iterated to an element gives all the greater ones. * `is_pred_archimedean`: `pred_order` where `pred` iterated to an element gives all the smaller ones. ## Implementation notes Maximal elements don't have a sensible successor. Thus the naïve typeclass ```lean class naive_succ_order (α : Type*) [preorder α] := (succ : α → α) (succ_le_iff : ∀ {a b}, succ a ≤ b ↔ a < b) (lt_succ_iff : ∀ {a b}, a < succ b ↔ a ≤ b) ``` can't apply to an `order_top` because plugging in `a = b = ⊤` into either of `succ_le_iff` and `lt_succ_iff` yields `⊤ < ⊤` (or more generally `m < m` for a maximal element `m`). The solution taken here is to remove the implications `≤ → <` and instead require that `a < succ a` for all non maximal elements (enforced by the combination of `le_succ` and the contrapositive of `max_of_succ_le`). The stricter condition of every element having a sensible successor can be obtained through the combination of `succ_order α` and `no_max_order α`. ## TODO Is `galois_connection pred succ` always true? If not, we should introduce ```lean class succ_pred_order (α : Type*) [preorder α] extends succ_order α, pred_order α := (pred_succ_gc : galois_connection (pred : α → α) succ) ``` `covby` should help here. -/ open function order_dual set variables {α : Type*} /-- Order equipped with a sensible successor function. -/ @[ext] class succ_order (α : Type*) [preorder α] := (succ : α → α) (le_succ : ∀ a, a ≤ succ a) (max_of_succ_le {a} : succ a ≤ a → is_max a) (succ_le_of_lt {a b} : a < b → succ a ≤ b) (le_of_lt_succ {a b} : a < succ b → a ≤ b) /-- Order equipped with a sensible predecessor function. -/ @[ext] class pred_order (α : Type*) [preorder α] := (pred : α → α) (pred_le : ∀ a, pred a ≤ a) (min_of_le_pred {a} : a ≤ pred a → is_min a) (le_pred_of_lt {a b} : a < b → a ≤ pred b) (le_of_pred_lt {a b} : pred a < b → a ≤ b) instance [preorder α] [succ_order α] : pred_order αᵒᵈ := { pred := to_dual ∘ succ_order.succ ∘ of_dual, pred_le := succ_order.le_succ, min_of_le_pred := λ _, succ_order.max_of_succ_le, le_pred_of_lt := λ a b h, succ_order.succ_le_of_lt h, le_of_pred_lt := λ a b, succ_order.le_of_lt_succ } instance [preorder α] [pred_order α] : succ_order αᵒᵈ := { succ := to_dual ∘ pred_order.pred ∘ of_dual, le_succ := pred_order.pred_le, max_of_succ_le := λ _, pred_order.min_of_le_pred, succ_le_of_lt := λ a b h, pred_order.le_pred_of_lt h, le_of_lt_succ := λ a b, pred_order.le_of_pred_lt } section preorder variables [preorder α] /-- A constructor for `succ_order α` usable when `α` has no maximal element. -/ def succ_order.of_succ_le_iff_of_le_lt_succ (succ : α → α) (hsucc_le_iff : ∀ {a b}, succ a ≤ b ↔ a < b) (hle_of_lt_succ : ∀ {a b}, a < succ b → a ≤ b) : succ_order α := { succ := succ, le_succ := λ a, (hsucc_le_iff.1 le_rfl).le, max_of_succ_le := λ a ha, (lt_irrefl a $ hsucc_le_iff.1 ha).elim, succ_le_of_lt := λ a b, hsucc_le_iff.2, le_of_lt_succ := λ a b, hle_of_lt_succ } /-- A constructor for `pred_order α` usable when `α` has no minimal element. -/ def pred_order.of_le_pred_iff_of_pred_le_pred (pred : α → α) (hle_pred_iff : ∀ {a b}, a ≤ pred b ↔ a < b) (hle_of_pred_lt : ∀ {a b}, pred a < b → a ≤ b) : pred_order α := { pred := pred, pred_le := λ a, (hle_pred_iff.1 le_rfl).le, min_of_le_pred := λ a ha, (lt_irrefl a $ hle_pred_iff.1 ha).elim, le_pred_of_lt := λ a b, hle_pred_iff.2, le_of_pred_lt := λ a b, hle_of_pred_lt } end preorder section linear_order variables [linear_order α] /-- A constructor for `succ_order α` for `α` a linear order. -/ @[simps] def succ_order.of_core (succ : α → α) (hn : ∀ {a}, ¬ is_max a → ∀ b, a < b ↔ succ a ≤ b) (hm : ∀ a, is_max a → succ a = a) : succ_order α := { succ := succ, succ_le_of_lt := λ a b, classical.by_cases (λ h hab, (hm a h).symm ▸ hab.le) (λ h, (hn h b).mp), le_succ := λ a, classical.by_cases (λ h, (hm a h).symm.le) (λ h, le_of_lt $ by simpa using (hn h a).not), le_of_lt_succ := λ a b hab, classical.by_cases (λ h, hm b h ▸ hab.le) (λ h, by simpa [hab] using (hn h a).not), max_of_succ_le := λ a, not_imp_not.mp $ λ h, by simpa using (hn h a).not } /-- A constructor for `pred_order α` for `α` a linear order. -/ @[simps] def pred_order.of_core {α} [linear_order α] (pred : α → α) (hn : ∀ {a}, ¬ is_min a → ∀ b, b ≤ pred a ↔ b < a) (hm : ∀ a, is_min a → pred a = a) : pred_order α := { pred := pred, le_pred_of_lt := λ a b, classical.by_cases (λ h hab, (hm b h).symm ▸ hab.le) (λ h, (hn h a).mpr), pred_le := λ a, classical.by_cases (λ h, (hm a h).le) (λ h, le_of_lt $ by simpa using (hn h a).not), le_of_pred_lt := λ a b hab, classical.by_cases (λ h, hm a h ▸ hab.le) (λ h, by simpa [hab] using (hn h b).not), min_of_le_pred := λ a, not_imp_not.mp $ λ h, by simpa using (hn h a).not } /-- A constructor for `succ_order α` usable when `α` is a linear order with no maximal element. -/ def succ_order.of_succ_le_iff (succ : α → α) (hsucc_le_iff : ∀ {a b}, succ a ≤ b ↔ a < b) : succ_order α := { succ := succ, le_succ := λ a, (hsucc_le_iff.1 le_rfl).le, max_of_succ_le := λ a ha, (lt_irrefl a $ hsucc_le_iff.1 ha).elim, succ_le_of_lt := λ a b, hsucc_le_iff.2, le_of_lt_succ := λ a b h, le_of_not_lt ((not_congr hsucc_le_iff).1 h.not_le) } /-- A constructor for `pred_order α` usable when `α` is a linear order with no minimal element. -/ def pred_order.of_le_pred_iff (pred : α → α) (hle_pred_iff : ∀ {a b}, a ≤ pred b ↔ a < b) : pred_order α := { pred := pred, pred_le := λ a, (hle_pred_iff.1 le_rfl).le, min_of_le_pred := λ a ha, (lt_irrefl a $ hle_pred_iff.1 ha).elim, le_pred_of_lt := λ a b, hle_pred_iff.2, le_of_pred_lt := λ a b h, le_of_not_lt ((not_congr hle_pred_iff).1 h.not_le) } end linear_order /-! ### Successor order -/ namespace order section preorder variables [preorder α] [succ_order α] {a b : α} /-- The successor of an element. If `a` is not maximal, then `succ a` is the least element greater than `a`. If `a` is maximal, then `succ a = a`. -/ def succ : α → α := succ_order.succ lemma le_succ : ∀ a : α, a ≤ succ a := succ_order.le_succ lemma max_of_succ_le {a : α} : succ a ≤ a → is_max a := succ_order.max_of_succ_le lemma succ_le_of_lt {a b : α} : a < b → succ a ≤ b := succ_order.succ_le_of_lt lemma le_of_lt_succ {a b : α} : a < succ b → a ≤ b := succ_order.le_of_lt_succ @[simp] lemma succ_le_iff_is_max : succ a ≤ a ↔ is_max a := ⟨max_of_succ_le, λ h, h $ le_succ _⟩ @[simp] lemma lt_succ_iff_not_is_max : a < succ a ↔ ¬ is_max a := ⟨not_is_max_of_lt, λ ha, (le_succ a).lt_of_not_le $ λ h, ha $ max_of_succ_le h⟩ alias lt_succ_iff_not_is_max ↔ _ lt_succ_of_not_is_max lemma wcovby_succ (a : α) : a ⩿ succ a := ⟨le_succ a, λ b hb, (succ_le_of_lt hb).not_lt⟩ lemma covby_succ_of_not_is_max (h : ¬ is_max a) : a ⋖ succ a := (wcovby_succ a).covby_of_lt $ lt_succ_of_not_is_max h lemma lt_succ_iff_of_not_is_max (ha : ¬ is_max a) : b < succ a ↔ b ≤ a := ⟨le_of_lt_succ, λ h, h.trans_lt $ lt_succ_of_not_is_max ha⟩ lemma succ_le_iff_of_not_is_max (ha : ¬ is_max a) : succ a ≤ b ↔ a < b := ⟨(lt_succ_of_not_is_max ha).trans_le, succ_le_of_lt⟩ lemma succ_lt_succ_iff_of_not_is_max (ha : ¬ is_max a) (hb : ¬ is_max b) : succ a < succ b ↔ a < b := by rw [lt_succ_iff_of_not_is_max hb, succ_le_iff_of_not_is_max ha] lemma succ_le_succ_iff_of_not_is_max (ha : ¬ is_max a) (hb : ¬ is_max b) : succ a ≤ succ b ↔ a ≤ b := by rw [succ_le_iff_of_not_is_max ha, lt_succ_iff_of_not_is_max hb] @[simp, mono] lemma succ_le_succ (h : a ≤ b) : succ a ≤ succ b := begin by_cases hb : is_max b, { by_cases hba : b ≤ a, { exact (hb $ hba.trans $ le_succ _).trans (le_succ _) }, { exact succ_le_of_lt ((h.lt_of_not_le hba).trans_le $ le_succ b) } }, { rwa [succ_le_iff_of_not_is_max (λ ha, hb $ ha.mono h), lt_succ_iff_of_not_is_max hb] } end lemma succ_mono : monotone (succ : α → α) := λ a b, succ_le_succ lemma le_succ_iterate (k : ℕ) (x : α) : x ≤ (succ^[k] x) := begin conv_lhs { rw (by simp only [function.iterate_id, id.def] : x = (id^[k] x)) }, exact monotone.le_iterate_of_le succ_mono le_succ k x, end lemma is_max_iterate_succ_of_eq_of_lt {n m : ℕ} (h_eq : (succ^[n] a) = (succ^[m] a)) (h_lt : n < m) : is_max (succ^[n] a) := begin refine max_of_succ_le (le_trans _ h_eq.symm.le), have : succ (succ^[n] a) = (succ^[n + 1] a), by rw function.iterate_succ', rw this, have h_le : n + 1 ≤ m := nat.succ_le_of_lt h_lt, exact monotone.monotone_iterate_of_le_map succ_mono (le_succ a) h_le, end lemma is_max_iterate_succ_of_eq_of_ne {n m : ℕ} (h_eq : (succ^[n] a) = (succ^[m] a)) (h_ne : n ≠ m) : is_max (succ^[n] a) := begin cases le_total n m, { exact is_max_iterate_succ_of_eq_of_lt h_eq (lt_of_le_of_ne h h_ne), }, { rw h_eq, exact is_max_iterate_succ_of_eq_of_lt h_eq.symm (lt_of_le_of_ne h h_ne.symm), }, end lemma Iio_succ_of_not_is_max (ha : ¬ is_max a) : Iio (succ a) = Iic a := set.ext $ λ x, lt_succ_iff_of_not_is_max ha lemma Ici_succ_of_not_is_max (ha : ¬ is_max a) : Ici (succ a) = Ioi a := set.ext $ λ x, succ_le_iff_of_not_is_max ha lemma Ico_succ_right_of_not_is_max (hb : ¬ is_max b) : Ico a (succ b) = Icc a b := by rw [←Ici_inter_Iio, Iio_succ_of_not_is_max hb, Ici_inter_Iic] lemma Ioo_succ_right_of_not_is_max (hb : ¬ is_max b) : Ioo a (succ b) = Ioc a b := by rw [←Ioi_inter_Iio, Iio_succ_of_not_is_max hb, Ioi_inter_Iic] lemma Icc_succ_left_of_not_is_max (ha : ¬ is_max a) : Icc (succ a) b = Ioc a b := by rw [←Ici_inter_Iic, Ici_succ_of_not_is_max ha, Ioi_inter_Iic] lemma Ico_succ_left_of_not_is_max (ha : ¬ is_max a) : Ico (succ a) b = Ioo a b := by rw [←Ici_inter_Iio, Ici_succ_of_not_is_max ha, Ioi_inter_Iio] section no_max_order variables [no_max_order α] lemma lt_succ (a : α) : a < succ a := lt_succ_of_not_is_max $ not_is_max a @[simp] lemma lt_succ_iff : a < succ b ↔ a ≤ b := lt_succ_iff_of_not_is_max $ not_is_max b @[simp] lemma succ_le_iff : succ a ≤ b ↔ a < b := succ_le_iff_of_not_is_max $ not_is_max a lemma succ_le_succ_iff : succ a ≤ succ b ↔ a ≤ b := by simp lemma succ_lt_succ_iff : succ a < succ b ↔ a < b := by simp alias succ_le_succ_iff ↔ le_of_succ_le_succ _ alias succ_lt_succ_iff ↔ lt_of_succ_lt_succ succ_lt_succ lemma succ_strict_mono : strict_mono (succ : α → α) := λ a b, succ_lt_succ lemma covby_succ (a : α) : a ⋖ succ a := covby_succ_of_not_is_max $ not_is_max a @[simp] lemma Iio_succ (a : α) : Iio (succ a) = Iic a := Iio_succ_of_not_is_max $ not_is_max _ @[simp] lemma Ici_succ (a : α) : Ici (succ a) = Ioi a := Ici_succ_of_not_is_max $ not_is_max _ @[simp] lemma Ico_succ_right (a b : α) : Ico a (succ b) = Icc a b := Ico_succ_right_of_not_is_max $ not_is_max _ @[simp] lemma Ioo_succ_right (a b : α) : Ioo a (succ b) = Ioc a b := Ioo_succ_right_of_not_is_max $ not_is_max _ @[simp] lemma Icc_succ_left (a b : α) : Icc (succ a) b = Ioc a b := Icc_succ_left_of_not_is_max $ not_is_max _ @[simp] lemma Ico_succ_left (a b : α) : Ico (succ a) b = Ioo a b := Ico_succ_left_of_not_is_max $ not_is_max _ end no_max_order end preorder section partial_order variables [partial_order α] [succ_order α] {a b : α} @[simp] lemma succ_eq_iff_is_max : succ a = a ↔ is_max a := ⟨λ h, max_of_succ_le h.le, λ h, h.eq_of_ge $ le_succ _⟩ alias succ_eq_iff_is_max ↔ _ _root_.is_max.succ_eq lemma succ_eq_succ_iff_of_not_is_max (ha : ¬ is_max a) (hb : ¬ is_max b) : succ a = succ b ↔ a = b := by rw [eq_iff_le_not_lt, eq_iff_le_not_lt, succ_le_succ_iff_of_not_is_max ha hb, succ_lt_succ_iff_of_not_is_max ha hb] lemma le_le_succ_iff : a ≤ b ∧ b ≤ succ a ↔ b = a ∨ b = succ a := begin refine ⟨λ h, or_iff_not_imp_left.2 $ λ hba : b ≠ a, h.2.antisymm (succ_le_of_lt $ h.1.lt_of_ne $ hba.symm), _⟩, rintro (rfl | rfl), { exact ⟨le_rfl, le_succ b⟩ }, { exact ⟨le_succ a, le_rfl⟩ } end lemma _root_.covby.succ_eq (h : a ⋖ b) : succ a = b := (succ_le_of_lt h.lt).eq_of_not_lt $ λ h', h.2 (lt_succ_of_not_is_max h.lt.not_is_max) h' lemma le_succ_iff_eq_or_le : a ≤ succ b ↔ a = succ b ∨ a ≤ b := begin by_cases hb : is_max b, { rw [hb.succ_eq, or_iff_right_of_imp le_of_eq] }, { rw [←lt_succ_iff_of_not_is_max hb, le_iff_eq_or_lt] } end lemma lt_succ_iff_eq_or_lt_of_not_is_max (hb : ¬ is_max b) : a < succ b ↔ a = b ∨ a < b := (lt_succ_iff_of_not_is_max hb).trans le_iff_eq_or_lt lemma Iic_succ (a : α) : Iic (succ a) = insert (succ a) (Iic a) := ext $ λ _, le_succ_iff_eq_or_le lemma Icc_succ_right (h : a ≤ succ b) : Icc a (succ b) = insert (succ b) (Icc a b) := by simp_rw [←Ici_inter_Iic, Iic_succ, inter_insert_of_mem (mem_Ici.2 h)] lemma Ioc_succ_right (h : a < succ b) : Ioc a (succ b) = insert (succ b) (Ioc a b) := by simp_rw [←Ioi_inter_Iic, Iic_succ, inter_insert_of_mem (mem_Ioi.2 h)] lemma Iio_succ_eq_insert_of_not_is_max (h : ¬is_max a) : Iio (succ a) = insert a (Iio a) := ext $ λ _, lt_succ_iff_eq_or_lt_of_not_is_max h lemma Ico_succ_right_eq_insert_of_not_is_max (h₁ : a ≤ b) (h₂ : ¬is_max b) : Ico a (succ b) = insert b (Ico a b) := by simp_rw [←Iio_inter_Ici, Iio_succ_eq_insert_of_not_is_max h₂, insert_inter_of_mem (mem_Ici.2 h₁)] lemma Ioo_succ_right_eq_insert_of_not_is_max (h₁ : a < b) (h₂ : ¬is_max b) : Ioo a (succ b) = insert b (Ioo a b) := by simp_rw [←Iio_inter_Ioi, Iio_succ_eq_insert_of_not_is_max h₂, insert_inter_of_mem (mem_Ioi.2 h₁)] section no_max_order variables [no_max_order α] @[simp] lemma succ_eq_succ_iff : succ a = succ b ↔ a = b := succ_eq_succ_iff_of_not_is_max (not_is_max a) (not_is_max b) lemma succ_injective : injective (succ : α → α) := λ a b, succ_eq_succ_iff.1 lemma succ_ne_succ_iff : succ a ≠ succ b ↔ a ≠ b := succ_injective.ne_iff alias succ_ne_succ_iff ↔ _ succ_ne_succ lemma lt_succ_iff_eq_or_lt : a < succ b ↔ a = b ∨ a < b := lt_succ_iff.trans le_iff_eq_or_lt lemma succ_eq_iff_covby : succ a = b ↔ a ⋖ b := ⟨by { rintro rfl, exact covby_succ _ }, covby.succ_eq⟩ lemma Iio_succ_eq_insert (a : α) : Iio (succ a) = insert a (Iio a) := Iio_succ_eq_insert_of_not_is_max $ not_is_max a lemma Ico_succ_right_eq_insert (h : a ≤ b) : Ico a (succ b) = insert b (Ico a b) := Ico_succ_right_eq_insert_of_not_is_max h $ not_is_max b lemma Ioo_succ_right_eq_insert (h : a < b) : Ioo a (succ b) = insert b (Ioo a b) := Ioo_succ_right_eq_insert_of_not_is_max h $ not_is_max b end no_max_order section order_top variables [order_top α] @[simp] lemma succ_top : succ (⊤ : α) = ⊤ := is_max_top.succ_eq @[simp] lemma succ_le_iff_eq_top : succ a ≤ a ↔ a = ⊤ := succ_le_iff_is_max.trans is_max_iff_eq_top @[simp] lemma lt_succ_iff_ne_top : a < succ a ↔ a ≠ ⊤ := lt_succ_iff_not_is_max.trans not_is_max_iff_ne_top end order_top section order_bot variable [order_bot α] @[simp] lemma lt_succ_bot_iff [no_max_order α] : a < succ ⊥ ↔ a = ⊥ := by rw [lt_succ_iff, le_bot_iff] lemma le_succ_bot_iff : a ≤ succ ⊥ ↔ a = ⊥ ∨ a = succ ⊥ := by rw [le_succ_iff_eq_or_le, le_bot_iff, or_comm] variable [nontrivial α] lemma bot_lt_succ (a : α) : ⊥ < succ a := (lt_succ_of_not_is_max not_is_max_bot).trans_le $ succ_mono bot_le lemma succ_ne_bot (a : α) : succ a ≠ ⊥ := (bot_lt_succ a).ne' end order_bot end partial_order /-- There is at most one way to define the successors in a `partial_order`. -/ instance [partial_order α] : subsingleton (succ_order α) := ⟨begin introsI h₀ h₁, ext a, by_cases ha : is_max a, { exact (@is_max.succ_eq _ _ h₀ _ ha).trans ha.succ_eq.symm }, { exact @covby.succ_eq _ _ h₀ _ _ (covby_succ_of_not_is_max ha) } end⟩ section complete_lattice variables [complete_lattice α] [succ_order α] lemma succ_eq_infi (a : α) : succ a = ⨅ b (h : a < b), b := begin refine le_antisymm (le_infi (λ b, le_infi succ_le_of_lt)) _, obtain rfl | ha := eq_or_ne a ⊤, { rw succ_top, exact le_top }, exact infi₂_le _ (lt_succ_iff_ne_top.2 ha), end end complete_lattice /-! ### Predecessor order -/ section preorder variables [preorder α] [pred_order α] {a b : α} /-- The predecessor of an element. If `a` is not minimal, then `pred a` is the greatest element less than `a`. If `a` is minimal, then `pred a = a`. -/ def pred : α → α := pred_order.pred lemma pred_le : ∀ a : α, pred a ≤ a := pred_order.pred_le lemma min_of_le_pred {a : α} : a ≤ pred a → is_min a := pred_order.min_of_le_pred lemma le_pred_of_lt {a b : α} : a < b → a ≤ pred b := pred_order.le_pred_of_lt lemma le_of_pred_lt {a b : α} : pred a < b → a ≤ b := pred_order.le_of_pred_lt @[simp] lemma le_pred_iff_is_min : a ≤ pred a ↔ is_min a := ⟨min_of_le_pred, λ h, h $ pred_le _⟩ @[simp] lemma pred_lt_iff_not_is_min : pred a < a ↔ ¬ is_min a := ⟨not_is_min_of_lt, λ ha, (pred_le a).lt_of_not_le $ λ h, ha $ min_of_le_pred h⟩ alias pred_lt_iff_not_is_min ↔ _ pred_lt_of_not_is_min lemma pred_wcovby (a : α) : pred a ⩿ a := ⟨pred_le a, λ b hb, (le_of_pred_lt hb).not_lt⟩ lemma pred_covby_of_not_is_min (h : ¬ is_min a) : pred a ⋖ a := (pred_wcovby a).covby_of_lt $ pred_lt_of_not_is_min h lemma pred_lt_iff_of_not_is_min (ha : ¬ is_min a) : pred a < b ↔ a ≤ b := ⟨le_of_pred_lt, (pred_lt_of_not_is_min ha).trans_le⟩ lemma le_pred_iff_of_not_is_min (ha : ¬ is_min a) : b ≤ pred a ↔ b < a := ⟨λ h, h.trans_lt $ pred_lt_of_not_is_min ha, le_pred_of_lt⟩ @[simp, mono] lemma pred_le_pred {a b : α} (h : a ≤ b) : pred a ≤ pred b := succ_le_succ h.dual lemma pred_mono : monotone (pred : α → α) := λ a b, pred_le_pred lemma pred_iterate_le (k : ℕ) (x : α) : (pred^[k] x) ≤ x := begin conv_rhs { rw (by simp only [function.iterate_id, id.def] : x = (id^[k] x)) }, exact monotone.iterate_le_of_le pred_mono pred_le k x, end lemma is_min_iterate_pred_of_eq_of_lt {n m : ℕ} (h_eq : (pred^[n] a) = (pred^[m] a)) (h_lt : n < m) : is_min (pred^[n] a) := @is_max_iterate_succ_of_eq_of_lt αᵒᵈ _ _ _ _ _ h_eq h_lt lemma is_min_iterate_pred_of_eq_of_ne {n m : ℕ} (h_eq : (pred^[n] a) = (pred^[m] a)) (h_ne : n ≠ m) : is_min (pred^[n] a) := @is_max_iterate_succ_of_eq_of_ne αᵒᵈ _ _ _ _ _ h_eq h_ne lemma Ioi_pred_of_not_is_min (ha : ¬ is_min a) : Ioi (pred a) = Ici a := set.ext $ λ x, pred_lt_iff_of_not_is_min ha lemma Iic_pred_of_not_is_min (ha : ¬ is_min a) : Iic (pred a) = Iio a := set.ext $ λ x, le_pred_iff_of_not_is_min ha lemma Ioc_pred_left_of_not_is_min (ha : ¬ is_min a) : Ioc (pred a) b = Icc a b := by rw [←Ioi_inter_Iic, Ioi_pred_of_not_is_min ha, Ici_inter_Iic] lemma Ioo_pred_left_of_not_is_min (ha : ¬ is_min a) : Ioo (pred a) b = Ico a b := by rw [←Ioi_inter_Iio, Ioi_pred_of_not_is_min ha, Ici_inter_Iio] lemma Icc_pred_right_of_not_is_min (ha : ¬ is_min b) : Icc a (pred b) = Ico a b := by rw [←Ici_inter_Iic, Iic_pred_of_not_is_min ha, Ici_inter_Iio] lemma Ioc_pred_right_of_not_is_min (ha : ¬ is_min b) : Ioc a (pred b) = Ioo a b := by rw [←Ioi_inter_Iic, Iic_pred_of_not_is_min ha, Ioi_inter_Iio] section no_min_order variables [no_min_order α] lemma pred_lt (a : α) : pred a < a := pred_lt_of_not_is_min $ not_is_min a @[simp] lemma pred_lt_iff : pred a < b ↔ a ≤ b := pred_lt_iff_of_not_is_min $ not_is_min a @[simp] lemma le_pred_iff : a ≤ pred b ↔ a < b := le_pred_iff_of_not_is_min $ not_is_min b lemma pred_le_pred_iff : pred a ≤ pred b ↔ a ≤ b := by simp lemma pred_lt_pred_iff : pred a < pred b ↔ a < b := by simp alias pred_le_pred_iff ↔ le_of_pred_le_pred _ alias pred_lt_pred_iff ↔ lt_of_pred_lt_pred pred_lt_pred lemma pred_strict_mono : strict_mono (pred : α → α) := λ a b, pred_lt_pred lemma pred_covby (a : α) : pred a ⋖ a := pred_covby_of_not_is_min $ not_is_min a @[simp] lemma Ioi_pred (a : α) : Ioi (pred a) = Ici a := Ioi_pred_of_not_is_min $ not_is_min a @[simp] lemma Iic_pred (a : α) : Iic (pred a) = Iio a := Iic_pred_of_not_is_min $ not_is_min a @[simp] lemma Ioc_pred_left (a b : α) : Ioc (pred a) b = Icc a b := Ioc_pred_left_of_not_is_min $ not_is_min _ @[simp] lemma Ioo_pred_left (a b : α) : Ioo (pred a) b = Ico a b := Ioo_pred_left_of_not_is_min $ not_is_min _ @[simp] lemma Icc_pred_right (a b : α) : Icc a (pred b) = Ico a b := Icc_pred_right_of_not_is_min $ not_is_min _ @[simp] lemma Ioc_pred_right (a b : α) : Ioc a (pred b) = Ioo a b := Ioc_pred_right_of_not_is_min $ not_is_min _ end no_min_order end preorder section partial_order variables [partial_order α] [pred_order α] {a b : α} @[simp] lemma pred_eq_iff_is_min : pred a = a ↔ is_min a := ⟨λ h, min_of_le_pred h.ge, λ h, h.eq_of_le $ pred_le _⟩ alias pred_eq_iff_is_min ↔ _ _root_.is_min.pred_eq lemma pred_le_le_iff {a b : α} : pred a ≤ b ∧ b ≤ a ↔ b = a ∨ b = pred a := begin refine ⟨λ h, or_iff_not_imp_left.2 $ λ hba : b ≠ a, (le_pred_of_lt $ h.2.lt_of_ne hba).antisymm h.1, _⟩, rintro (rfl | rfl), { exact ⟨pred_le b, le_rfl⟩ }, { exact ⟨le_rfl, pred_le a⟩ } end lemma _root_.covby.pred_eq {a b : α} (h : a ⋖ b) : pred b = a := (le_pred_of_lt h.lt).eq_of_not_gt $ λ h', h.2 h' $ pred_lt_of_not_is_min h.lt.not_is_min lemma pred_le_iff_eq_or_le : pred a ≤ b ↔ b = pred a ∨ a ≤ b := begin by_cases ha : is_min a, { rw [ha.pred_eq, or_iff_right_of_imp ge_of_eq] }, { rw [←pred_lt_iff_of_not_is_min ha, le_iff_eq_or_lt, eq_comm] } end lemma pred_lt_iff_eq_or_lt_of_not_is_min (ha : ¬ is_min a) : pred a < b ↔ a = b ∨ a < b := (pred_lt_iff_of_not_is_min ha).trans le_iff_eq_or_lt lemma Ici_pred (a : α) : Ici (pred a) = insert (pred a) (Ici a) := ext $ λ _, pred_le_iff_eq_or_le lemma Ioi_pred_eq_insert_of_not_is_min (ha : ¬ is_min a) : Ioi (pred a) = insert a (Ioi a) := begin ext x, simp only [insert, mem_set_of, @eq_comm _ x a], exact pred_lt_iff_eq_or_lt_of_not_is_min ha end lemma Icc_pred_left (h : pred a ≤ b) : Icc (pred a) b = insert (pred a) (Icc a b) := by simp_rw [←Ici_inter_Iic, Ici_pred, insert_inter_of_mem (mem_Iic.2 h)] lemma Ico_pred_left (h : pred a < b) : Ico (pred a) b = insert (pred a) (Ico a b) := by simp_rw [←Ici_inter_Iio, Ici_pred, insert_inter_of_mem (mem_Iio.2 h)] section no_min_order variables [no_min_order α] @[simp] lemma pred_eq_pred_iff : pred a = pred b ↔ a = b := by simp_rw [eq_iff_le_not_lt, pred_le_pred_iff, pred_lt_pred_iff] lemma pred_injective : injective (pred : α → α) := λ a b, pred_eq_pred_iff.1 lemma pred_ne_pred_iff : pred a ≠ pred b ↔ a ≠ b := pred_injective.ne_iff alias pred_ne_pred_iff ↔ _ pred_ne_pred lemma pred_lt_iff_eq_or_lt : pred a < b ↔ a = b ∨ a < b := pred_lt_iff.trans le_iff_eq_or_lt lemma pred_eq_iff_covby : pred b = a ↔ a ⋖ b := ⟨by { rintro rfl, exact pred_covby _ }, covby.pred_eq⟩ lemma Ioi_pred_eq_insert (a : α) : Ioi (pred a) = insert a (Ioi a) := ext $ λ _, pred_lt_iff_eq_or_lt.trans $ or_congr_left' eq_comm lemma Ico_pred_right_eq_insert (h : a ≤ b) : Ioc (pred a) b = insert a (Ioc a b) := by simp_rw [←Ioi_inter_Iic, Ioi_pred_eq_insert, insert_inter_of_mem (mem_Iic.2 h)] lemma Ioo_pred_right_eq_insert (h : a < b) : Ioo (pred a) b = insert a (Ioo a b) := by simp_rw [←Ioi_inter_Iio, Ioi_pred_eq_insert, insert_inter_of_mem (mem_Iio.2 h)] end no_min_order section order_bot variables [order_bot α] @[simp] lemma pred_bot : pred (⊥ : α) = ⊥ := is_min_bot.pred_eq @[simp] lemma le_pred_iff_eq_bot : a ≤ pred a ↔ a = ⊥ := @succ_le_iff_eq_top αᵒᵈ _ _ _ _ @[simp] lemma pred_lt_iff_ne_bot : pred a < a ↔ a ≠ ⊥ := @lt_succ_iff_ne_top αᵒᵈ _ _ _ _ end order_bot section order_top variable [order_top α] @[simp] lemma pred_top_lt_iff [no_min_order α] : pred ⊤ < a ↔ a = ⊤ := @lt_succ_bot_iff αᵒᵈ _ _ _ _ _ lemma pred_top_le_iff : pred ⊤ ≤ a ↔ a = ⊤ ∨ a = pred ⊤ := @le_succ_bot_iff αᵒᵈ _ _ _ _ variable [nontrivial α] lemma pred_lt_top (a : α) : pred a < ⊤ := (pred_mono le_top).trans_lt $ pred_lt_of_not_is_min not_is_min_top lemma pred_ne_top (a : α) : pred a ≠ ⊤ := (pred_lt_top a).ne end order_top end partial_order /-- There is at most one way to define the predecessors in a `partial_order`. -/ instance [partial_order α] : subsingleton (pred_order α) := ⟨begin introsI h₀ h₁, ext a, by_cases ha : is_min a, { exact (@is_min.pred_eq _ _ h₀ _ ha).trans ha.pred_eq.symm }, { exact @covby.pred_eq _ _ h₀ _ _ (pred_covby_of_not_is_min ha) } end⟩ section complete_lattice variables [complete_lattice α] [pred_order α] lemma pred_eq_supr (a : α) : pred a = ⨆ b (h : b < a), b := begin refine le_antisymm _ (supr_le (λ b, supr_le le_pred_of_lt)), obtain rfl | ha := eq_or_ne a ⊥, { rw pred_bot, exact bot_le }, { exact @le_supr₂ _ _ (λ b, b < a) _ (λ a _, a) (pred a) (pred_lt_iff_ne_bot.2 ha) } end end complete_lattice /-! ### Successor-predecessor orders -/ section succ_pred_order variables [partial_order α] [succ_order α] [pred_order α] {a b : α} @[simp] lemma succ_pred_of_not_is_min (h : ¬ is_min a) : succ (pred a) = a := (pred_covby_of_not_is_min h).succ_eq @[simp] lemma pred_succ_of_not_is_max (h : ¬ is_max a) : pred (succ a) = a := (covby_succ_of_not_is_max h).pred_eq @[simp] lemma succ_pred [no_min_order α] (a : α) : succ (pred a) = a := (pred_covby _).succ_eq @[simp] lemma pred_succ [no_max_order α] (a : α) : pred (succ a) = a := (covby_succ _).pred_eq lemma pred_succ_iterate_of_not_is_max (i : α) (n : ℕ) (hin : ¬ is_max (succ^[n-1] i)) : pred^[n] (succ^[n] i) = i := begin induction n with n hn, { simp only [function.iterate_zero, id.def], }, rw [nat.succ_sub_succ_eq_sub, nat.sub_zero] at hin, have h_not_max : ¬ is_max (succ^[n - 1] i), { cases n, { simpa using hin, }, rw [nat.succ_sub_succ_eq_sub, nat.sub_zero] at hn ⊢, have h_sub_le : (succ^[n] i) ≤ (succ^[n.succ] i), { rw function.iterate_succ', exact le_succ _, }, refine λ h_max, hin (λ j hj, _), have hj_le : j ≤ (succ^[n] i) := h_max (h_sub_le.trans hj), exact hj_le.trans h_sub_le, }, rw [function.iterate_succ, function.iterate_succ'], simp only [function.comp_app], rw pred_succ_of_not_is_max hin, exact hn h_not_max, end lemma succ_pred_iterate_of_not_is_min (i : α) (n : ℕ) (hin : ¬ is_min (pred^[n-1] i)) : succ^[n] (pred^[n] i) = i := @pred_succ_iterate_of_not_is_max αᵒᵈ _ _ _ i n hin end succ_pred_order end order open order /-! ### `with_bot`, `with_top` Adding a greatest/least element to a `succ_order` or to a `pred_order`. As far as successors and predecessors are concerned, there are four ways to add a bottom or top element to an order: * Adding a `⊤` to an `order_top`: Preserves `succ` and `pred`. * Adding a `⊤` to a `no_max_order`: Preserves `succ`. Never preserves `pred`. * Adding a `⊥` to an `order_bot`: Preserves `succ` and `pred`. * Adding a `⊥` to a `no_min_order`: Preserves `pred`. Never preserves `succ`. where "preserves `(succ/pred)`" means `(succ/pred)_order α → (succ/pred)_order ((with_top/with_bot) α)`. -/ namespace with_top /-! #### Adding a `⊤` to an `order_top` -/ section succ variables [decidable_eq α] [partial_order α] [order_top α] [succ_order α] instance : succ_order (with_top α) := { succ := λ a, match a with | ⊤ := ⊤ | (some a) := ite (a = ⊤) ⊤ (some (succ a)) end, le_succ := λ a, begin cases a, { exact le_top }, change _ ≤ ite _ _ _, split_ifs, { exact le_top }, { exact some_le_some.2 (le_succ a) } end, max_of_succ_le := λ a ha, begin cases a, { exact is_max_top }, change ite _ _ _ ≤ _ at ha, split_ifs at ha with ha', { exact (not_top_le_coe _ ha).elim }, { rw [some_le_some, succ_le_iff_eq_top] at ha, exact (ha' ha).elim } end, succ_le_of_lt := λ a b h, begin cases b, { exact le_top }, cases a, { exact (not_top_lt h).elim }, rw some_lt_some at h, change ite _ _ _ ≤ _, split_ifs with ha, { rw ha at h, exact (not_top_lt h).elim }, { exact some_le_some.2 (succ_le_of_lt h) } end, le_of_lt_succ := λ a b h, begin cases a, { exact (not_top_lt h).elim }, cases b, { exact le_top }, change _ < ite _ _ _ at h, rw some_le_some, split_ifs at h with hb, { rw hb, exact le_top }, { exact le_of_lt_succ (some_lt_some.1 h) } end } @[simp] lemma succ_coe_top : succ ↑(⊤ : α) = (⊤ : with_top α) := dif_pos rfl lemma succ_coe_of_ne_top {a : α} (h : a ≠ ⊤) : succ (↑a : with_top α) = ↑(succ a) := dif_neg h end succ section pred variables [preorder α] [order_top α] [pred_order α] instance : pred_order (with_top α) := { pred := λ a, match a with | ⊤ := some ⊤ | (some a) := some (pred a) end, pred_le := λ a, match a with | ⊤ := le_top | (some a) := some_le_some.2 (pred_le a) end, min_of_le_pred := λ a ha, begin cases a, { exact ((coe_lt_top (⊤ : α)).not_le ha).elim }, { exact (min_of_le_pred $ some_le_some.1 ha).with_top } end, le_pred_of_lt := λ a b h, begin cases a, { exact ((le_top).not_lt h).elim }, cases b, { exact some_le_some.2 le_top }, exact some_le_some.2 (le_pred_of_lt $ some_lt_some.1 h), end, le_of_pred_lt := λ a b h, begin cases b, { exact le_top }, cases a, { exact (not_top_lt $ some_lt_some.1 h).elim }, { exact some_le_some.2 (le_of_pred_lt $ some_lt_some.1 h) } end } @[simp] lemma pred_top : pred (⊤ : with_top α) = ↑(⊤ : α) := rfl @[simp] lemma pred_coe (a : α) : pred (↑a : with_top α) = ↑(pred a) := rfl end pred /-! #### Adding a `⊤` to a `no_max_order` -/ section succ variables [preorder α] [no_max_order α] [succ_order α] instance succ_order_of_no_max_order : succ_order (with_top α) := { succ := λ a, match a with | ⊤ := ⊤ | (some a) := some (succ a) end, le_succ := λ a, begin cases a, { exact le_top }, { exact some_le_some.2 (le_succ a) } end, max_of_succ_le := λ a ha, begin cases a, { exact is_max_top }, { exact (not_is_max _ $ max_of_succ_le $ some_le_some.1 ha).elim } end, succ_le_of_lt := λ a b h, begin cases a, { exact (not_top_lt h).elim }, cases b, { exact le_top}, { exact some_le_some.2 (succ_le_of_lt $ some_lt_some.1 h) } end, le_of_lt_succ := λ a b h, begin cases a, { exact (not_top_lt h).elim }, cases b, { exact le_top }, { exact some_le_some.2 (le_of_lt_succ $ some_lt_some.1 h) } end } @[simp] lemma succ_coe (a : α) : succ (↑a : with_top α) = ↑(succ a) := rfl end succ section pred variables [preorder α] [no_max_order α] instance [hα : nonempty α] : is_empty (pred_order (with_top α)) := ⟨begin introI, cases h : pred (⊤ : with_top α) with a ha, { exact hα.elim (λ a, (min_of_le_pred h.ge).not_lt $ coe_lt_top a) }, { obtain ⟨c, hc⟩ := exists_gt a, rw [←some_lt_some, ←h] at hc, exact (le_of_pred_lt hc).not_lt (some_lt_none _) } end⟩ end pred end with_top namespace with_bot /-! #### Adding a `⊥` to an `order_bot` -/ section succ variables [preorder α] [order_bot α] [succ_order α] instance : succ_order (with_bot α) := { succ := λ a, match a with | ⊥ := some ⊥ | (some a) := some (succ a) end, le_succ := λ a, match a with | ⊥ := bot_le | (some a) := some_le_some.2 (le_succ a) end, max_of_succ_le := λ a ha, begin cases a, { exact ((none_lt_some (⊥ : α)).not_le ha).elim }, { exact (max_of_succ_le $ some_le_some.1 ha).with_bot } end, succ_le_of_lt := λ a b h, begin cases b, { exact (not_lt_bot h).elim }, cases a, { exact some_le_some.2 bot_le }, { exact some_le_some.2 (succ_le_of_lt $ some_lt_some.1 h) } end, le_of_lt_succ := λ a b h, begin cases a, { exact bot_le }, cases b, { exact (not_lt_bot $ some_lt_some.1 h).elim }, { exact some_le_some.2 (le_of_lt_succ $ some_lt_some.1 h) } end } @[simp] lemma succ_bot : succ (⊥ : with_bot α) = ↑(⊥ : α) := rfl @[simp] lemma succ_coe (a : α) : succ (↑a : with_bot α) = ↑(succ a) := rfl end succ section pred variables [decidable_eq α] [partial_order α] [order_bot α] [pred_order α] instance : pred_order (with_bot α) := { pred := λ a, match a with | ⊥ := ⊥ | (some a) := ite (a = ⊥) ⊥ (some (pred a)) end, pred_le := λ a, begin cases a, { exact bot_le }, change ite _ _ _ ≤ _, split_ifs, { exact bot_le }, { exact some_le_some.2 (pred_le a) } end, min_of_le_pred := λ a ha, begin cases a, { exact is_min_bot }, change _ ≤ ite _ _ _ at ha, split_ifs at ha with ha', { exact (not_coe_le_bot _ ha).elim }, { rw [some_le_some, le_pred_iff_eq_bot] at ha, exact (ha' ha).elim } end, le_pred_of_lt := λ a b h, begin cases a, { exact bot_le }, cases b, { exact (not_lt_bot h).elim }, rw some_lt_some at h, change _ ≤ ite _ _ _, split_ifs with hb, { rw hb at h, exact (not_lt_bot h).elim }, { exact some_le_some.2 (le_pred_of_lt h) } end, le_of_pred_lt := λ a b h, begin cases b, { exact (not_lt_bot h).elim }, cases a, { exact bot_le }, change ite _ _ _ < _ at h, rw some_le_some, split_ifs at h with ha, { rw ha, exact bot_le }, { exact le_of_pred_lt (some_lt_some.1 h) } end } @[simp] lemma pred_coe_bot : pred ↑(⊥ : α) = (⊥ : with_bot α) := dif_pos rfl lemma pred_coe_of_ne_bot {a : α} (h : a ≠ ⊥) : pred (↑a : with_bot α) = ↑(pred a) := dif_neg h end pred /-! #### Adding a `⊥` to a `no_min_order` -/ section succ variables [preorder α] [no_min_order α] instance [hα : nonempty α] : is_empty (succ_order (with_bot α)) := ⟨begin introI, cases h : succ (⊥ : with_bot α) with a ha, { exact hα.elim (λ a, (max_of_succ_le h.le).not_lt $ bot_lt_coe a) }, { obtain ⟨c, hc⟩ := exists_lt a, rw [←some_lt_some, ←h] at hc, exact (le_of_lt_succ hc).not_lt (none_lt_some _) } end⟩ end succ section pred variables [preorder α] [no_min_order α] [pred_order α] instance pred_order_of_no_min_order : pred_order (with_bot α) := { pred := λ a, match a with | ⊥ := ⊥ | (some a) := some (pred a) end, pred_le := λ a, begin cases a, { exact bot_le }, { exact some_le_some.2 (pred_le a) } end, min_of_le_pred := λ a ha, begin cases a, { exact is_min_bot }, { exact (not_is_min _ $ min_of_le_pred $ some_le_some.1 ha).elim } end, le_pred_of_lt := λ a b h, begin cases b, { exact (not_lt_bot h).elim }, cases a, { exact bot_le }, { exact some_le_some.2 (le_pred_of_lt $ some_lt_some.1 h) } end, le_of_pred_lt := λ a b h, begin cases b, { exact (not_lt_bot h).elim }, cases a, { exact bot_le }, { exact some_le_some.2 (le_of_pred_lt $ some_lt_some.1 h) } end } @[simp] lemma pred_coe (a : α) : pred (↑a : with_bot α) = ↑(pred a) := rfl end pred end with_bot /-! ### Archimedeanness -/ /-- A `succ_order` is succ-archimedean if one can go from any two comparable elements by iterating `succ` -/ class is_succ_archimedean (α : Type*) [preorder α] [succ_order α] : Prop := (exists_succ_iterate_of_le {a b : α} (h : a ≤ b) : ∃ n, succ^[n] a = b) /-- A `pred_order` is pred-archimedean if one can go from any two comparable elements by iterating `pred` -/ class is_pred_archimedean (α : Type*) [preorder α] [pred_order α] : Prop := (exists_pred_iterate_of_le {a b : α} (h : a ≤ b) : ∃ n, pred^[n] b = a) export is_succ_archimedean (exists_succ_iterate_of_le) export is_pred_archimedean (exists_pred_iterate_of_le) section preorder variables [preorder α] section succ_order variables [succ_order α] [is_succ_archimedean α] {a b : α} instance : is_pred_archimedean αᵒᵈ := ⟨λ a b h, by convert exists_succ_iterate_of_le h.of_dual⟩ lemma has_le.le.exists_succ_iterate (h : a ≤ b) : ∃ n, succ^[n] a = b := exists_succ_iterate_of_le h lemma exists_succ_iterate_iff_le : (∃ n, succ^[n] a = b) ↔ a ≤ b := begin refine ⟨_, exists_succ_iterate_of_le⟩, rintro ⟨n, rfl⟩, exact id_le_iterate_of_id_le le_succ n a, end /-- Induction principle on a type with a `succ_order` for all elements above a given element `m`. -/ @[elab_as_eliminator] lemma succ.rec {P : α → Prop} {m : α} (h0 : P m) (h1 : ∀ n, m ≤ n → P n → P (succ n)) ⦃n : α⦄ (hmn : m ≤ n) : P n := begin obtain ⟨n, rfl⟩ := hmn.exists_succ_iterate, clear hmn, induction n with n ih, { exact h0 }, { rw [function.iterate_succ_apply'], exact h1 _ (id_le_iterate_of_id_le le_succ n m) ih } end lemma succ.rec_iff {p : α → Prop} (hsucc : ∀ a, p a ↔ p (succ a)) {a b : α} (h : a ≤ b) : p a ↔ p b := begin obtain ⟨n, rfl⟩ := h.exists_succ_iterate, exact iterate.rec (λ b, p a ↔ p b) (λ c hc, hc.trans (hsucc _)) iff.rfl n, end end succ_order section pred_order variables [pred_order α] [is_pred_archimedean α] {a b : α} instance : is_succ_archimedean αᵒᵈ := ⟨λ a b h, by convert exists_pred_iterate_of_le h.of_dual⟩ lemma has_le.le.exists_pred_iterate (h : a ≤ b) : ∃ n, pred^[n] b = a := exists_pred_iterate_of_le h lemma exists_pred_iterate_iff_le : (∃ n, pred^[n] b = a) ↔ a ≤ b := @exists_succ_iterate_iff_le αᵒᵈ _ _ _ _ _ /-- Induction principle on a type with a `pred_order` for all elements below a given element `m`. -/ @[elab_as_eliminator] lemma pred.rec {P : α → Prop} {m : α} (h0 : P m) (h1 : ∀ n, n ≤ m → P n → P (pred n)) ⦃n : α⦄ (hmn : n ≤ m) : P n := @succ.rec αᵒᵈ _ _ _ _ _ h0 h1 _ hmn lemma pred.rec_iff {p : α → Prop} (hsucc : ∀ a, p a ↔ p (pred a)) {a b : α} (h : a ≤ b) : p a ↔ p b := (@succ.rec_iff αᵒᵈ _ _ _ _ hsucc _ _ h).symm end pred_order end preorder section linear_order variables [linear_order α] section succ_order variables [succ_order α] [is_succ_archimedean α] {a b : α} lemma exists_succ_iterate_or : (∃ n, succ^[n] a = b) ∨ ∃ n, succ^[n] b = a := (le_total a b).imp exists_succ_iterate_of_le exists_succ_iterate_of_le lemma succ.rec_linear {p : α → Prop} (hsucc : ∀ a, p a ↔ p (succ a)) (a b : α) : p a ↔ p b := (le_total a b).elim (succ.rec_iff hsucc) (λ h, (succ.rec_iff hsucc h).symm) end succ_order section pred_order variables [pred_order α] [is_pred_archimedean α] {a b : α} lemma exists_pred_iterate_or : (∃ n, pred^[n] b = a) ∨ ∃ n, pred^[n] a = b := (le_total a b).imp exists_pred_iterate_of_le exists_pred_iterate_of_le lemma pred.rec_linear {p : α → Prop} (hsucc : ∀ a, p a ↔ p (pred a)) (a b : α) : p a ↔ p b := (le_total a b).elim (pred.rec_iff hsucc) (λ h, (pred.rec_iff hsucc h).symm) end pred_order end linear_order section is_well_order variables [linear_order α] @[priority 100] instance is_well_order.to_is_pred_archimedean [h : is_well_order α (<)] [pred_order α] : is_pred_archimedean α := ⟨λ a, begin refine well_founded.fix h.wf (λ b ih hab, _), replace hab := hab.eq_or_lt, rcases hab with rfl | hab, { exact ⟨0, rfl⟩ }, cases le_or_lt b (pred b) with hb hb, { cases (min_of_le_pred hb).not_lt hab }, obtain ⟨k, hk⟩ := ih (pred b) hb (le_pred_of_lt hab), refine ⟨k + 1, _⟩, rw [iterate_add_apply, iterate_one, hk], end⟩ @[priority 100] instance is_well_order.to_is_succ_archimedean [h : is_well_order α (>)] [succ_order α] : is_succ_archimedean α := by convert @order_dual.is_succ_archimedean αᵒᵈ _ _ _ end is_well_order section order_bot variables [preorder α] [order_bot α] [succ_order α] [is_succ_archimedean α] lemma succ.rec_bot (p : α → Prop) (hbot : p ⊥) (hsucc : ∀ a, p a → p (succ a)) (a : α) : p a := succ.rec hbot (λ x _ h, hsucc x h) (bot_le : ⊥ ≤ a) end order_bot section order_top variables [preorder α] [order_top α] [pred_order α] [is_pred_archimedean α] lemma pred.rec_top (p : α → Prop) (htop : p ⊤) (hpred : ∀ a, p a → p (pred a)) (a : α) : p a := pred.rec htop (λ x _ h, hpred x h) (le_top : a ≤ ⊤) end order_top
ce34ee16bc65397efd7854d97760a28d4f105bf7
ff5230333a701471f46c57e8c115a073ebaaa448
/library/init/meta/format.lean
82e1e45797c933e90cf7de1459915317668d2259
[ "Apache-2.0" ]
permissive
stanford-cs242/lean
f81721d2b5d00bc175f2e58c57b710d465e6c858
7bd861261f4a37326dcf8d7a17f1f1f330e4548c
refs/heads/master
1,600,957,431,849
1,576,465,093,000
1,576,465,093,000
225,779,423
0
3
Apache-2.0
1,575,433,936,000
1,575,433,935,000
null
UTF-8
Lean
false
false
5,903
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.meta.options init.function init.data.to_string universes u v inductive format.color | red | green | orange | blue | pink | cyan | grey /-- Format is a rich string with highlighting and information about how tabs should be put in if linebreaks are needed. A 'pretty string'. -/ meta constant format : Type /-- Indicate that it is ok to put a linebreak in here if the line is too long. -/ meta constant format.line : format /-- The whitespace character `" "`. -/ meta constant format.space : format /-- = `""` -/ meta constant format.nil : format /-- Concatenate the given formats. -/ meta constant format.compose : format → format → format /-- `format.nest n f` tells the formatter that `f` is nested inside something with length `n` so that it is pretty-printed with the correct tabs on a line break. For example, in `list.to_format` we have: ``` (nest 1 $ format.join $ list.intersperse ("," ++ line) $ xs.map to_fmt) ``` This will be written all on one line, but when the list is too large, it will put in linebreaks after the comma and indent later lines by 1. -/ meta constant format.nest : nat → format → format /-- Make the given format be displayed a particular color. [TODO] does this override nested colours etc? -/ meta constant format.highlight : format → color → format /-- [TODO] I think this might be obsolete, in the Lean source code it seems to be doing the same thing as `flatten`. -/ meta constant format.group : format → format meta constant format.of_string : string → format meta constant format.of_nat : nat → format /-- [TODO] -/ meta constant format.flatten : format → format meta constant format.to_string (f : format) (o : options := options.mk) : string meta constant format.of_options : options → format meta constant format.is_nil : format → bool /-- [TODO] -/ meta constant trace_fmt {α : Type u} : format → (unit → α) → α meta instance : inhabited format := ⟨format.space⟩ meta instance : has_append format := ⟨format.compose⟩ meta instance : has_to_string format := ⟨λ f, f.to_string options.mk⟩ /-- Use this instead of `has_to_string` to enable prettier formatting. See docstring for `format` for more on the differences between `format` and `string`. Note that `format` is `meta` while `string` is not. -/ meta class has_to_format (α : Type u) := (to_format : α → format) meta instance : has_to_format format := ⟨id⟩ meta def to_fmt {α : Type u} [has_to_format α] : α → format := has_to_format.to_format meta instance nat_to_format : has_coe nat format := ⟨format.of_nat⟩ meta instance string_to_format : has_coe string format := ⟨format.of_string⟩ open format list meta def format.indent (f : format) (n : nat) : format := nest n (line ++ f) meta def format.when {α : Type u} [has_to_format α] : bool → α → format | tt a := to_fmt a | ff a := nil meta def format.join (xs : list format) : format := foldl compose (of_string "") xs meta instance : has_to_format options := ⟨λ o, format.of_options o⟩ meta instance : has_to_format bool := ⟨λ b, if b then of_string "tt" else of_string "ff"⟩ meta instance {p : Prop} : has_to_format (decidable p) := ⟨λ b : decidable p, @ite p b _ (of_string "tt") (of_string "ff")⟩ meta instance : has_to_format string := ⟨λ s, format.of_string s⟩ meta instance : has_to_format nat := ⟨λ n, format.of_nat n⟩ meta instance : has_to_format unsigned := ⟨λ n, to_fmt n.to_nat⟩ meta instance : has_to_format char := ⟨λ c : char, format.of_string c.to_string⟩ meta def list.to_format {α : Type u} [has_to_format α] : list α → format | [] := to_fmt "[]" | xs := to_fmt "[" ++ group (nest 1 $ format.join $ list.intersperse ("," ++ line) $ xs.map to_fmt) ++ to_fmt "]" meta instance {α : Type u} [has_to_format α] : has_to_format (list α) := ⟨list.to_format⟩ attribute [instance] string.has_to_format meta instance : has_to_format name := ⟨λ n, to_fmt n.to_string⟩ meta instance : has_to_format unit := ⟨λ u, to_fmt "()"⟩ meta instance {α : Type u} [has_to_format α] : has_to_format (option α) := ⟨λ o, option.cases_on o (to_fmt "none") (λ a, to_fmt "(some " ++ nest 6 (to_fmt a) ++ to_fmt ")")⟩ meta instance sum_has_to_format {α : Type u} {β : Type v} [has_to_format α] [has_to_format β] : has_to_format (sum α β) := ⟨λ s, sum.cases_on s (λ a, to_fmt "(inl " ++ nest 5 (to_fmt a) ++ to_fmt ")") (λ b, to_fmt "(inr " ++ nest 5 (to_fmt b) ++ to_fmt ")")⟩ open prod meta instance {α : Type u} {β : Type v} [has_to_format α] [has_to_format β] : has_to_format (prod α β) := ⟨λ ⟨a, b⟩, group (nest 1 (to_fmt "(" ++ to_fmt a ++ to_fmt "," ++ line ++ to_fmt b ++ to_fmt ")"))⟩ open sigma meta instance {α : Type u} {β : α → Type v} [has_to_format α] [s : ∀ x, has_to_format (β x)] : has_to_format (sigma β) := ⟨λ ⟨a, b⟩, group (nest 1 (to_fmt "⟨" ++ to_fmt a ++ to_fmt "," ++ line ++ to_fmt b ++ to_fmt "⟩"))⟩ open subtype meta instance {α : Type u} {p : α → Prop} [has_to_format α] : has_to_format (subtype p) := ⟨λ s, to_fmt (val s)⟩ meta def format.bracket : string → string → format → format | o c f := to_fmt o ++ nest o.length f ++ to_fmt c meta def format.paren (f : format) : format := format.bracket "(" ")" f meta def format.cbrace (f : format) : format := format.bracket "{" "}" f meta def format.sbracket (f : format) : format := format.bracket "[" "]" f meta def format.dcbrace (f : format) : format := to_fmt "⦃" ++ nest 1 f ++ to_fmt "⦄"
8fd2103cd26349aecfbd8fded4956bbe56067ebd
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/ring_theory/ideal/quotient_operations.lean
106c861b9cc01367c5b5097e61a3aff8d6eaa80f
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
27,925
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import ring_theory.ideal.operations import ring_theory.ideal.quotient /-! # More operations on modules and ideals related to quotients > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. -/ universes u v w namespace ring_hom variables {R : Type u} {S : Type v} [comm_ring R] [comm_ring S] (f : R →+* S) /-- The induced map from the quotient by the kernel to the codomain. This is an isomorphism if `f` has a right inverse (`quotient_ker_equiv_of_right_inverse`) / is surjective (`quotient_ker_equiv_of_surjective`). -/ def ker_lift (f : R →+* S) : R ⧸ f.ker →+* S := ideal.quotient.lift _ f $ λ r, f.mem_ker.mp @[simp] lemma ker_lift_mk (f : R →+* S) (r : R) : ker_lift f (ideal.quotient.mk f.ker r) = f r := ideal.quotient.lift_mk _ _ _ /-- The induced map from the quotient by the kernel is injective. -/ lemma ker_lift_injective (f : R →+* S) : function.injective (ker_lift f) := assume a b, quotient.induction_on₂' a b $ assume a b (h : f a = f b), ideal.quotient.eq.2 $ show a - b ∈ ker f, by rw [mem_ker, map_sub, h, sub_self] lemma lift_injective_of_ker_le_ideal (I : ideal R) {f : R →+* S} (H : ∀ (a : R), a ∈ I → f a = 0) (hI : f.ker ≤ I) : function.injective (ideal.quotient.lift I f H) := begin rw [ring_hom.injective_iff_ker_eq_bot, ring_hom.ker_eq_bot_iff_eq_zero], intros u hu, obtain ⟨v, rfl⟩ := ideal.quotient.mk_surjective u, rw ideal.quotient.lift_mk at hu, rw [ideal.quotient.eq_zero_iff_mem], exact hI ((ring_hom.mem_ker f).mpr hu), end variable {f} /-- The **first isomorphism theorem** for commutative rings, computable version. -/ def quotient_ker_equiv_of_right_inverse {g : S → R} (hf : function.right_inverse g f) : R ⧸ f.ker ≃+* S := { to_fun := ker_lift f, inv_fun := (ideal.quotient.mk f.ker) ∘ g, left_inv := begin rintro ⟨x⟩, apply ker_lift_injective, simp [hf (f x)], end, right_inv := hf, ..ker_lift f} @[simp] lemma quotient_ker_equiv_of_right_inverse.apply {g : S → R} (hf : function.right_inverse g f) (x : R ⧸ f.ker) : quotient_ker_equiv_of_right_inverse hf x = ker_lift f x := rfl @[simp] lemma quotient_ker_equiv_of_right_inverse.symm.apply {g : S → R} (hf : function.right_inverse g f) (x : S) : (quotient_ker_equiv_of_right_inverse hf).symm x = ideal.quotient.mk f.ker (g x) := rfl /-- The **first isomorphism theorem** for commutative rings. -/ noncomputable def quotient_ker_equiv_of_surjective (hf : function.surjective f) : R ⧸ f.ker ≃+* S := quotient_ker_equiv_of_right_inverse (classical.some_spec hf.has_right_inverse) end ring_hom namespace ideal variables {R : Type u} {S : Type v} {F : Type w} [comm_ring R] [comm_ring S] @[simp] lemma map_quotient_self (I : ideal R) : map (quotient.mk I) I = ⊥ := eq_bot_iff.2 $ ideal.map_le_iff_le_comap.2 $ λ x hx, (submodule.mem_bot (R ⧸ I)).2 $ ideal.quotient.eq_zero_iff_mem.2 hx @[simp] lemma mk_ker {I : ideal R} : (quotient.mk I).ker = I := by ext; rw [ring_hom.ker, mem_comap, submodule.mem_bot, quotient.eq_zero_iff_mem] lemma map_mk_eq_bot_of_le {I J : ideal R} (h : I ≤ J) : I.map (J^.quotient.mk) = ⊥ := by { rw [map_eq_bot_iff_le_ker, mk_ker], exact h } lemma ker_quotient_lift {S : Type v} [comm_ring S] {I : ideal R} (f : R →+* S) (H : I ≤ f.ker) : (ideal.quotient.lift I f H).ker = (f.ker).map I^.quotient.mk := begin ext x, split, { intro hx, obtain ⟨y, hy⟩ := quotient.mk_surjective x, rw [ring_hom.mem_ker, ← hy, ideal.quotient.lift_mk, ← ring_hom.mem_ker] at hx, rw [← hy, mem_map_iff_of_surjective I^.quotient.mk quotient.mk_surjective], exact ⟨y, hx, rfl⟩ }, { intro hx, rw mem_map_iff_of_surjective I^.quotient.mk quotient.mk_surjective at hx, obtain ⟨y, hy⟩ := hx, rw [ring_hom.mem_ker, ← hy.right, ideal.quotient.lift_mk, ← (ring_hom.mem_ker f)], exact hy.left }, end @[simp] lemma bot_quotient_is_maximal_iff (I : ideal R) : (⊥ : ideal (R ⧸ I)).is_maximal ↔ I.is_maximal := ⟨λ hI, (@mk_ker _ _ I) ▸ @comap_is_maximal_of_surjective _ _ _ _ _ _ (quotient.mk I) quotient.mk_surjective ⊥ hI, λ hI, by { resetI, letI := quotient.field I, exact bot_is_maximal }⟩ /-- See also `ideal.mem_quotient_iff_mem` in case `I ≤ J`. -/ @[simp] lemma mem_quotient_iff_mem_sup {I J : ideal R} {x : R} : quotient.mk I x ∈ J.map (quotient.mk I) ↔ x ∈ J ⊔ I := by rw [← mem_comap, comap_map_of_surjective (quotient.mk I) quotient.mk_surjective, ← ring_hom.ker_eq_comap_bot, mk_ker] /-- See also `ideal.mem_quotient_iff_mem_sup` if the assumption `I ≤ J` is not available. -/ lemma mem_quotient_iff_mem {I J : ideal R} (hIJ : I ≤ J) {x : R} : quotient.mk I x ∈ J.map (quotient.mk I) ↔ x ∈ J := by rw [mem_quotient_iff_mem_sup, sup_eq_left.mpr hIJ] lemma comap_map_mk {I J : ideal R} (h : I ≤ J) : ideal.comap (ideal.quotient.mk I) (ideal.map (ideal.quotient.mk I) J) = J := by { ext, rw [← ideal.mem_quotient_iff_mem h, ideal.mem_comap], } section quotient_algebra variables (R₁ R₂ : Type*) {A B : Type*} variables [comm_semiring R₁] [comm_semiring R₂] [comm_ring A] [comm_ring B] variables [algebra R₁ A] [algebra R₂ A] [algebra R₁ B] /-- The `R₁`-algebra structure on `A/I` for an `R₁`-algebra `A` -/ instance quotient.algebra {I : ideal A} : algebra R₁ (A ⧸ I) := { to_fun := λ x, ideal.quotient.mk I (algebra_map R₁ A x), smul := (•), smul_def' := λ r x, quotient.induction_on' x $ λ x, ((quotient.mk I).congr_arg $ algebra.smul_def _ _).trans (ring_hom.map_mul _ _ _), commutes' := λ _ _, mul_comm _ _, .. ring_hom.comp (ideal.quotient.mk I) (algebra_map R₁ A) } -- Lean can struggle to find this instance later if we don't provide this shortcut instance quotient.is_scalar_tower [has_smul R₁ R₂] [is_scalar_tower R₁ R₂ A] (I : ideal A) : is_scalar_tower R₁ R₂ (A ⧸ I) := by apply_instance /-- The canonical morphism `A →ₐ[R₁] A ⧸ I` as morphism of `R₁`-algebras, for `I` an ideal of `A`, where `A` is an `R₁`-algebra. -/ def quotient.mkₐ (I : ideal A) : A →ₐ[R₁] A ⧸ I := ⟨λ a, submodule.quotient.mk a, rfl, λ _ _, rfl, rfl, λ _ _, rfl, λ _, rfl⟩ lemma quotient.alg_hom_ext {I : ideal A} {S} [semiring S] [algebra R₁ S] ⦃f g : A ⧸ I →ₐ[R₁] S⦄ (h : f.comp (quotient.mkₐ R₁ I) = g.comp (quotient.mkₐ R₁ I)) : f = g := alg_hom.ext $ λ x, quotient.induction_on' x $ alg_hom.congr_fun h lemma quotient.alg_map_eq (I : ideal A) : algebra_map R₁ (A ⧸ I) = (algebra_map A (A ⧸ I)).comp (algebra_map R₁ A) := rfl lemma quotient.mkₐ_to_ring_hom (I : ideal A) : (quotient.mkₐ R₁ I).to_ring_hom = ideal.quotient.mk I := rfl @[simp] lemma quotient.mkₐ_eq_mk (I : ideal A) : ⇑(quotient.mkₐ R₁ I) = ideal.quotient.mk I := rfl @[simp] lemma quotient.algebra_map_eq (I : ideal R) : algebra_map R (R ⧸ I) = I^.quotient.mk := rfl @[simp] lemma quotient.mk_comp_algebra_map (I : ideal A) : (quotient.mk I).comp (algebra_map R₁ A) = algebra_map R₁ (A ⧸ I) := rfl @[simp] lemma quotient.mk_algebra_map (I : ideal A) (x : R₁) : quotient.mk I (algebra_map R₁ A x) = algebra_map R₁ (A ⧸ I) x := rfl /-- The canonical morphism `A →ₐ[R₁] I.quotient` is surjective. -/ lemma quotient.mkₐ_surjective (I : ideal A) : function.surjective (quotient.mkₐ R₁ I) := surjective_quot_mk _ /-- The kernel of `A →ₐ[R₁] I.quotient` is `I`. -/ @[simp] lemma quotient.mkₐ_ker (I : ideal A) : (quotient.mkₐ R₁ I : A →+* A ⧸ I).ker = I := ideal.mk_ker variables {R₁} /-- `ideal.quotient.lift` as an `alg_hom`. -/ def quotient.liftₐ (I : ideal A) (f : A →ₐ[R₁] B) (hI : ∀ (a : A), a ∈ I → f a = 0) : A ⧸ I →ₐ[R₁] B := { commutes' := λ r, begin -- this is is_scalar_tower.algebra_map_apply R₁ A (A ⧸ I) but the file `algebra.algebra.tower` -- imports this file. have : algebra_map R₁ (A ⧸ I) r = algebra_map A (A ⧸ I) (algebra_map R₁ A r), { simp_rw [algebra.algebra_map_eq_smul_one, smul_assoc, one_smul] }, rw [this, ideal.quotient.algebra_map_eq, ring_hom.to_fun_eq_coe, ideal.quotient.lift_mk, alg_hom.coe_to_ring_hom, algebra.algebra_map_eq_smul_one, algebra.algebra_map_eq_smul_one, map_smul, map_one], end ..(ideal.quotient.lift I (f : A →+* B) hI) } @[simp] lemma quotient.liftₐ_apply (I : ideal A) (f : A →ₐ[R₁] B) (hI : ∀ (a : A), a ∈ I → f a = 0) (x) : ideal.quotient.liftₐ I f hI x = ideal.quotient.lift I (f : A →+* B) hI x := rfl lemma quotient.liftₐ_comp (I : ideal A) (f : A →ₐ[R₁] B) (hI : ∀ (a : A), a ∈ I → f a = 0) : (ideal.quotient.liftₐ I f hI).comp (ideal.quotient.mkₐ R₁ I) = f := alg_hom.ext (λ x, (ideal.quotient.lift_mk I (f : A →+* B) hI : _)) lemma ker_lift.map_smul (f : A →ₐ[R₁] B) (r : R₁) (x : A ⧸ f.to_ring_hom.ker) : f.to_ring_hom.ker_lift (r • x) = r • f.to_ring_hom.ker_lift x := begin obtain ⟨a, rfl⟩ := quotient.mkₐ_surjective R₁ _ x, rw [← alg_hom.map_smul, quotient.mkₐ_eq_mk, ring_hom.ker_lift_mk], exact f.map_smul _ _ end /-- The induced algebras morphism from the quotient by the kernel to the codomain. This is an isomorphism if `f` has a right inverse (`quotient_ker_alg_equiv_of_right_inverse`) / is surjective (`quotient_ker_alg_equiv_of_surjective`). -/ def ker_lift_alg (f : A →ₐ[R₁] B) : (A ⧸ f.to_ring_hom.ker) →ₐ[R₁] B := alg_hom.mk' f.to_ring_hom.ker_lift (λ _ _, ker_lift.map_smul f _ _) @[simp] lemma ker_lift_alg_mk (f : A →ₐ[R₁] B) (a : A) : ker_lift_alg f (quotient.mk f.to_ring_hom.ker a) = f a := rfl @[simp] lemma ker_lift_alg_to_ring_hom (f : A →ₐ[R₁] B) : (ker_lift_alg f).to_ring_hom = ring_hom.ker_lift f := rfl /-- The induced algebra morphism from the quotient by the kernel is injective. -/ lemma ker_lift_alg_injective (f : A →ₐ[R₁] B) : function.injective (ker_lift_alg f) := ring_hom.ker_lift_injective f /-- The **first isomorphism** theorem for algebras, computable version. -/ def quotient_ker_alg_equiv_of_right_inverse {f : A →ₐ[R₁] B} {g : B → A} (hf : function.right_inverse g f) : (A ⧸ f.to_ring_hom.ker) ≃ₐ[R₁] B := { ..ring_hom.quotient_ker_equiv_of_right_inverse (λ x, show f.to_ring_hom (g x) = x, from hf x), ..ker_lift_alg f} @[simp] lemma quotient_ker_alg_equiv_of_right_inverse.apply {f : A →ₐ[R₁] B} {g : B → A} (hf : function.right_inverse g f) (x : A ⧸ f.to_ring_hom.ker) : quotient_ker_alg_equiv_of_right_inverse hf x = ker_lift_alg f x := rfl @[simp] lemma quotient_ker_alg_equiv_of_right_inverse_symm.apply {f : A →ₐ[R₁] B} {g : B → A} (hf : function.right_inverse g f) (x : B) : (quotient_ker_alg_equiv_of_right_inverse hf).symm x = quotient.mkₐ R₁ f.to_ring_hom.ker (g x) := rfl /-- The **first isomorphism theorem** for algebras. -/ noncomputable def quotient_ker_alg_equiv_of_surjective {f : A →ₐ[R₁] B} (hf : function.surjective f) : (A ⧸ f.to_ring_hom.ker) ≃ₐ[R₁] B := quotient_ker_alg_equiv_of_right_inverse (classical.some_spec hf.has_right_inverse) /-- The ring hom `R/I →+* S/J` induced by a ring hom `f : R →+* S` with `I ≤ f⁻¹(J)` -/ def quotient_map {I : ideal R} (J : ideal S) (f : R →+* S) (hIJ : I ≤ J.comap f) : R ⧸ I →+* S ⧸ J := (quotient.lift I ((quotient.mk J).comp f) (λ _ ha, by simpa [function.comp_app, ring_hom.coe_comp, quotient.eq_zero_iff_mem] using hIJ ha)) @[simp] lemma quotient_map_mk {J : ideal R} {I : ideal S} {f : R →+* S} {H : J ≤ I.comap f} {x : R} : quotient_map I f H (quotient.mk J x) = quotient.mk I (f x) := quotient.lift_mk J _ _ @[simp] lemma quotient_map_algebra_map {J : ideal A} {I : ideal S} {f : A →+* S} {H : J ≤ I.comap f} {x : R₁} : quotient_map I f H (algebra_map R₁ (A ⧸ J) x) = quotient.mk I (f (algebra_map _ _ x)) := quotient.lift_mk J _ _ lemma quotient_map_comp_mk {J : ideal R} {I : ideal S} {f : R →+* S} (H : J ≤ I.comap f) : (quotient_map I f H).comp (quotient.mk J) = (quotient.mk I).comp f := ring_hom.ext (λ x, by simp only [function.comp_app, ring_hom.coe_comp, ideal.quotient_map_mk]) /-- The ring equiv `R/I ≃+* S/J` induced by a ring equiv `f : R ≃+** S`, where `J = f(I)`. -/ @[simps] def quotient_equiv (I : ideal R) (J : ideal S) (f : R ≃+* S) (hIJ : J = I.map (f : R →+* S)) : R ⧸ I ≃+* S ⧸ J := { inv_fun := quotient_map I ↑f.symm (by {rw hIJ, exact le_of_eq (map_comap_of_equiv I f)}), left_inv := by {rintro ⟨r⟩, simp }, right_inv := by {rintro ⟨s⟩, simp }, ..quotient_map J ↑f (by {rw hIJ, exact @le_comap_map _ S _ _ _ _ _ _}) } @[simp] lemma quotient_equiv_mk (I : ideal R) (J : ideal S) (f : R ≃+* S) (hIJ : J = I.map (f : R →+* S)) (x : R) : quotient_equiv I J f hIJ (ideal.quotient.mk I x) = ideal.quotient.mk J (f x) := rfl @[simp] lemma quotient_equiv_symm_mk (I : ideal R) (J : ideal S) (f : R ≃+* S) (hIJ : J = I.map (f : R →+* S)) (x : S) : (quotient_equiv I J f hIJ).symm (ideal.quotient.mk J x) = ideal.quotient.mk I (f.symm x) := rfl /-- `H` and `h` are kept as separate hypothesis since H is used in constructing the quotient map. -/ lemma quotient_map_injective' {J : ideal R} {I : ideal S} {f : R →+* S} {H : J ≤ I.comap f} (h : I.comap f ≤ J) : function.injective (quotient_map I f H) := begin refine (injective_iff_map_eq_zero (quotient_map I f H)).2 (λ a ha, _), obtain ⟨r, rfl⟩ := quotient.mk_surjective a, rw [quotient_map_mk, quotient.eq_zero_iff_mem] at ha, exact (quotient.eq_zero_iff_mem).mpr (h ha), end /-- If we take `J = I.comap f` then `quotient_map` is injective automatically. -/ lemma quotient_map_injective {I : ideal S} {f : R →+* S} : function.injective (quotient_map I f le_rfl) := quotient_map_injective' le_rfl lemma quotient_map_surjective {J : ideal R} {I : ideal S} {f : R →+* S} {H : J ≤ I.comap f} (hf : function.surjective f) : function.surjective (quotient_map I f H) := λ x, let ⟨x, hx⟩ := quotient.mk_surjective x in let ⟨y, hy⟩ := hf x in ⟨(quotient.mk J) y, by simp [hx, hy]⟩ /-- Commutativity of a square is preserved when taking quotients by an ideal. -/ lemma comp_quotient_map_eq_of_comp_eq {R' S' : Type*} [comm_ring R'] [comm_ring S'] {f : R →+* S} {f' : R' →+* S'} {g : R →+* R'} {g' : S →+* S'} (hfg : f'.comp g = g'.comp f) (I : ideal S') : (quotient_map I g' le_rfl).comp (quotient_map (I.comap g') f le_rfl) = (quotient_map I f' le_rfl).comp (quotient_map (I.comap f') g (le_of_eq (trans (comap_comap f g') (hfg ▸ (comap_comap g f'))))) := begin refine ring_hom.ext (λ a, _), obtain ⟨r, rfl⟩ := quotient.mk_surjective a, simp only [ring_hom.comp_apply, quotient_map_mk], exact congr_arg (quotient.mk I) (trans (g'.comp_apply f r).symm (hfg ▸ (f'.comp_apply g r))), end /-- The algebra hom `A/I →+* B/J` induced by an algebra hom `f : A →ₐ[R₁] B` with `I ≤ f⁻¹(J)`. -/ def quotient_mapₐ {I : ideal A} (J : ideal B) (f : A →ₐ[R₁] B) (hIJ : I ≤ J.comap f) : A ⧸ I →ₐ[R₁] B ⧸ J := { commutes' := λ r, by simp, ..quotient_map J (f : A →+* B) hIJ } @[simp] lemma quotient_map_mkₐ {I : ideal A} (J : ideal B) (f : A →ₐ[R₁] B) (H : I ≤ J.comap f) {x : A} : quotient_mapₐ J f H (quotient.mk I x) = quotient.mkₐ R₁ J (f x) := rfl lemma quotient_map_comp_mkₐ {I : ideal A} (J : ideal B) (f : A →ₐ[R₁] B) (H : I ≤ J.comap f) : (quotient_mapₐ J f H).comp (quotient.mkₐ R₁ I) = (quotient.mkₐ R₁ J).comp f := alg_hom.ext (λ x, by simp only [quotient_map_mkₐ, quotient.mkₐ_eq_mk, alg_hom.comp_apply]) /-- The algebra equiv `A/I ≃ₐ[R] B/J` induced by an algebra equiv `f : A ≃ₐ[R] B`, where`J = f(I)`. -/ def quotient_equiv_alg (I : ideal A) (J : ideal B) (f : A ≃ₐ[R₁] B) (hIJ : J = I.map (f : A →+* B)) : (A ⧸ I) ≃ₐ[R₁] B ⧸ J := { commutes' := λ r, by simp, ..quotient_equiv I J (f : A ≃+* B) hIJ } @[priority 100] instance quotient_algebra {I : ideal A} [algebra R A] : algebra (R ⧸ I.comap (algebra_map R A)) (A ⧸ I) := (quotient_map I (algebra_map R A) (le_of_eq rfl)).to_algebra lemma algebra_map_quotient_injective {I : ideal A} [algebra R A]: function.injective (algebra_map (R ⧸ I.comap (algebra_map R A)) (A ⧸ I)) := begin rintros ⟨a⟩ ⟨b⟩ hab, replace hab := quotient.eq.mp hab, rw ← ring_hom.map_sub at hab, exact quotient.eq.mpr hab end variable (R₁) /-- Quotienting by equal ideals gives equivalent algebras. -/ def quotient_equiv_alg_of_eq {I J : ideal A} (h : I = J) : (A ⧸ I) ≃ₐ[R₁] A ⧸ J := quotient_equiv_alg I J alg_equiv.refl $ h ▸ (map_id I).symm @[simp] lemma quotient_equiv_alg_of_eq_mk {I J : ideal A} (h : I = J) (x : A) : quotient_equiv_alg_of_eq R₁ h (ideal.quotient.mk I x) = ideal.quotient.mk J x := rfl @[simp] lemma quotient_equiv_alg_of_eq_symm {I J : ideal A} (h : I = J) : (quotient_equiv_alg_of_eq R₁ h).symm = quotient_equiv_alg_of_eq R₁ h.symm := by ext; refl end quotient_algebra end ideal namespace double_quot open ideal variable {R : Type u} section variables [comm_ring R] (I J : ideal R) /-- The obvious ring hom `R/I → R/(I ⊔ J)` -/ def quot_left_to_quot_sup : R ⧸ I →+* R ⧸ (I ⊔ J) := ideal.quotient.factor I (I ⊔ J) le_sup_left /-- The kernel of `quot_left_to_quot_sup` -/ lemma ker_quot_left_to_quot_sup : (quot_left_to_quot_sup I J).ker = J.map (ideal.quotient.mk I) := by simp only [mk_ker, sup_idem, sup_comm, quot_left_to_quot_sup, quotient.factor, ker_quotient_lift, map_eq_iff_sup_ker_eq_of_surjective I^.quotient.mk quotient.mk_surjective, ← sup_assoc] /-- The ring homomorphism `(R/I)/J' -> R/(I ⊔ J)` induced by `quot_left_to_quot_sup` where `J'` is the image of `J` in `R/I`-/ def quot_quot_to_quot_sup : (R ⧸ I) ⧸ J.map (ideal.quotient.mk I) →+* R ⧸ I ⊔ J := by exact ideal.quotient.lift (J.map (ideal.quotient.mk I)) (quot_left_to_quot_sup I J) (ker_quot_left_to_quot_sup I J).symm.le /-- The composite of the maps `R → (R/I)` and `(R/I) → (R/I)/J'` -/ def quot_quot_mk : R →+* ((R ⧸ I) ⧸ J.map I^.quotient.mk) := by exact ((J.map I^.quotient.mk)^.quotient.mk).comp I^.quotient.mk /-- The kernel of `quot_quot_mk` -/ lemma ker_quot_quot_mk : (quot_quot_mk I J).ker = I ⊔ J := by rw [ring_hom.ker_eq_comap_bot, quot_quot_mk, ← comap_comap, ← ring_hom.ker, mk_ker, comap_map_of_surjective (ideal.quotient.mk I) (quotient.mk_surjective), ← ring_hom.ker, mk_ker, sup_comm] /-- The ring homomorphism `R/(I ⊔ J) → (R/I)/J' `induced by `quot_quot_mk` -/ def lift_sup_quot_quot_mk (I J : ideal R) : R ⧸ (I ⊔ J) →+* (R ⧸ I) ⧸ J.map (ideal.quotient.mk I) := ideal.quotient.lift (I ⊔ J) (quot_quot_mk I J) (ker_quot_quot_mk I J).symm.le /-- `quot_quot_to_quot_add` and `lift_sup_double_qot_mk` are inverse isomorphisms. In the case where `I ≤ J`, this is the Third Isomorphism Theorem (see `quot_quot_equiv_quot_of_le`)-/ def quot_quot_equiv_quot_sup : (R ⧸ I) ⧸ J.map (ideal.quotient.mk I) ≃+* R ⧸ I ⊔ J := ring_equiv.of_hom_inv (quot_quot_to_quot_sup I J) (lift_sup_quot_quot_mk I J) (by { ext z, refl }) (by { ext z, refl }) @[simp] lemma quot_quot_equiv_quot_sup_quot_quot_mk (x : R) : quot_quot_equiv_quot_sup I J (quot_quot_mk I J x) = ideal.quotient.mk (I ⊔ J) x := rfl @[simp] lemma quot_quot_equiv_quot_sup_symm_quot_quot_mk (x : R) : (quot_quot_equiv_quot_sup I J).symm (ideal.quotient.mk (I ⊔ J) x) = quot_quot_mk I J x := rfl /-- The obvious isomorphism `(R/I)/J' → (R/J)/I' ` -/ def quot_quot_equiv_comm : (R ⧸ I) ⧸ J.map I^.quotient.mk ≃+* (R ⧸ J) ⧸ I.map J^.quotient.mk := ((quot_quot_equiv_quot_sup I J).trans (quot_equiv_of_eq sup_comm)).trans (quot_quot_equiv_quot_sup J I).symm @[simp] lemma quot_quot_equiv_comm_quot_quot_mk (x : R) : quot_quot_equiv_comm I J (quot_quot_mk I J x) = quot_quot_mk J I x := rfl @[simp] lemma quot_quot_equiv_comm_comp_quot_quot_mk : ring_hom.comp ↑(quot_quot_equiv_comm I J) (quot_quot_mk I J) = quot_quot_mk J I := ring_hom.ext $ quot_quot_equiv_comm_quot_quot_mk I J @[simp] lemma quot_quot_equiv_comm_symm : (quot_quot_equiv_comm I J).symm = quot_quot_equiv_comm J I := rfl variables {I J} /-- **The Third Isomorphism theorem** for rings. See `quot_quot_equiv_quot_sup` for a version that does not assume an inclusion of ideals. -/ def quot_quot_equiv_quot_of_le (h : I ≤ J) : (R ⧸ I) ⧸ (J.map I^.quotient.mk) ≃+* R ⧸ J := (quot_quot_equiv_quot_sup I J).trans (ideal.quot_equiv_of_eq $ sup_eq_right.mpr h) @[simp] lemma quot_quot_equiv_quot_of_le_quot_quot_mk (x : R) (h : I ≤ J) : quot_quot_equiv_quot_of_le h (quot_quot_mk I J x) = J^.quotient.mk x := rfl @[simp] lemma quot_quot_equiv_quot_of_le_symm_mk (x : R) (h : I ≤ J) : (quot_quot_equiv_quot_of_le h).symm (J^.quotient.mk x) = (quot_quot_mk I J x) := rfl lemma quot_quot_equiv_quot_of_le_comp_quot_quot_mk (h : I ≤ J) : ring_hom.comp ↑(quot_quot_equiv_quot_of_le h) (quot_quot_mk I J) = J^.quotient.mk := by ext ; refl lemma quot_quot_equiv_quot_of_le_symm_comp_mk (h : I ≤ J) : ring_hom.comp ↑(quot_quot_equiv_quot_of_le h).symm J^.quotient.mk = quot_quot_mk I J := by ext ; refl end section algebra @[simp] lemma quot_quot_equiv_comm_mk_mk [comm_ring R] (I J : ideal R) (x : R) : quot_quot_equiv_comm I J (ideal.quotient.mk _ (ideal.quotient.mk _ x)) = algebra_map R _ x := rfl variables [comm_semiring R] {A : Type v} [comm_ring A] [algebra R A] (I J : ideal A) @[simp] lemma quot_quot_equiv_quot_sup_quot_quot_algebra_map (x : R) : double_quot.quot_quot_equiv_quot_sup I J (algebra_map R _ x) = algebra_map _ _ x := rfl @[simp] lemma quot_quot_equiv_comm_algebra_map (x : R) : quot_quot_equiv_comm I J (algebra_map R _ x) = algebra_map _ _ x := rfl end algebra section algebra_quotient variables (R) {A : Type*} [comm_semiring R] [comm_ring A] [algebra R A] variables (I J : ideal A) /-- The natural algebra homomorphism `A / I → A / (I ⊔ J)`. -/ def quot_left_to_quot_supₐ : A ⧸ I →ₐ[R] A ⧸ (I ⊔ J) := alg_hom.mk (quot_left_to_quot_sup I J) rfl (map_mul _) rfl (map_add _) (λ _, rfl) @[simp] lemma quot_left_to_quot_supₐ_to_ring_hom : (quot_left_to_quot_supₐ R I J).to_ring_hom = quot_left_to_quot_sup I J := rfl @[simp] lemma coe_quot_left_to_quot_supₐ : ⇑(quot_left_to_quot_supₐ R I J) = quot_left_to_quot_sup I J := rfl /-- The algebra homomorphism `(A / I) / J' -> A / (I ⊔ J) induced by `quot_left_to_quot_sup`, where `J'` is the projection of `J` in `A / I`. -/ def quot_quot_to_quot_supₐ : (A ⧸ I) ⧸ J.map (I^.quotient.mkₐ R) →ₐ[R] A ⧸ I ⊔ J := alg_hom.mk (quot_quot_to_quot_sup I J) rfl (map_mul _) rfl (map_add _) (λ _, rfl) @[simp] lemma quot_quot_to_quot_supₐ_to_ring_hom : (quot_quot_to_quot_supₐ R I J).to_ring_hom = quot_quot_to_quot_sup I J := rfl @[simp] lemma coe_quot_quot_to_quot_supₐ : ⇑(quot_quot_to_quot_supₐ R I J) = quot_quot_to_quot_sup I J := rfl /-- The composition of the algebra homomorphisms `A → (A / I)` and `(A / I) → (A / I) / J'`, where `J'` is the projection `J` in `A / I`. -/ def quot_quot_mkₐ : A →ₐ[R] ((A ⧸ I) ⧸ J.map (I^.quotient.mkₐ R)) := alg_hom.mk (quot_quot_mk I J) rfl (map_mul _) rfl (map_add _) (λ _, rfl) @[simp] lemma quot_quot_mkₐ_to_ring_hom : (quot_quot_mkₐ R I J).to_ring_hom = quot_quot_mk I J := rfl @[simp] lemma coe_quot_quot_mkₐ : ⇑(quot_quot_mkₐ R I J) = quot_quot_mk I J := rfl /-- The injective algebra homomorphism `A / (I ⊔ J) → (A / I) / J'`induced by `quot_quot_mk`, where `J'` is the projection `J` in `A / I`. -/ def lift_sup_quot_quot_mkₐ (I J : ideal A) : A ⧸ (I ⊔ J) →ₐ[R] (A ⧸ I) ⧸ J.map (I^.quotient.mkₐ R) := alg_hom.mk (lift_sup_quot_quot_mk I J) rfl (map_mul _) rfl (map_add _) (λ _, rfl) @[simp] lemma lift_sup_quot_quot_mkₐ_to_ring_hom : (lift_sup_quot_quot_mkₐ R I J).to_ring_hom = lift_sup_quot_quot_mk I J := rfl @[simp] lemma coe_lift_sup_quot_quot_mkₐ : ⇑(lift_sup_quot_quot_mkₐ R I J) = lift_sup_quot_quot_mk I J := rfl /-- `quot_quot_to_quot_add` and `lift_sup_quot_quot_mk` are inverse isomorphisms. In the case where `I ≤ J`, this is the Third Isomorphism Theorem (see `quot_quot_equiv_quot_of_le`). -/ def quot_quot_equiv_quot_supₐ : ((A ⧸ I) ⧸ J.map (I^.quotient.mkₐ R)) ≃ₐ[R] A ⧸ I ⊔ J := @alg_equiv.of_ring_equiv R _ _ _ _ _ _ _ (quot_quot_equiv_quot_sup I J) (λ _, rfl) @[simp] lemma quot_quot_equiv_quot_supₐ_to_ring_equiv : (quot_quot_equiv_quot_supₐ R I J).to_ring_equiv = quot_quot_equiv_quot_sup I J := rfl @[simp] lemma coe_quot_quot_equiv_quot_supₐ : ⇑(quot_quot_equiv_quot_supₐ R I J) = quot_quot_equiv_quot_sup I J := rfl @[simp] lemma quot_quot_equiv_quot_supₐ_symm_to_ring_equiv: (quot_quot_equiv_quot_supₐ R I J).symm.to_ring_equiv = (quot_quot_equiv_quot_sup I J).symm := rfl @[simp] lemma coe_quot_quot_equiv_quot_supₐ_symm: ⇑(quot_quot_equiv_quot_supₐ R I J).symm = (quot_quot_equiv_quot_sup I J).symm := rfl /-- The natural algebra isomorphism `(A / I) / J' → (A / J) / I'`, where `J'` (resp. `I'`) is the projection of `J` in `A / I` (resp. `I` in `A / J`). -/ def quot_quot_equiv_commₐ : ((A ⧸ I) ⧸ J.map (I^.quotient.mkₐ R)) ≃ₐ[R] ((A ⧸ J) ⧸ I.map (J^.quotient.mkₐ R)) := @alg_equiv.of_ring_equiv R _ _ _ _ _ _ _ (quot_quot_equiv_comm I J) (λ _, rfl) @[simp] lemma quot_quot_equiv_commₐ_to_ring_equiv : (quot_quot_equiv_commₐ R I J).to_ring_equiv = quot_quot_equiv_comm I J := rfl @[simp] lemma coe_quot_quot_equiv_commₐ : ⇑(quot_quot_equiv_commₐ R I J) = quot_quot_equiv_comm I J := rfl @[simp] lemma quot_quot_equiv_comm_symmₐ : (quot_quot_equiv_commₐ R I J).symm = quot_quot_equiv_commₐ R J I := -- TODO: should be `rfl` but times out alg_equiv.ext $ λ x, (fun_like.congr_fun (quot_quot_equiv_comm_symm I J) x : _) @[simp] lemma quot_quot_equiv_comm_comp_quot_quot_mkₐ : alg_hom.comp ↑(quot_quot_equiv_commₐ R I J) (quot_quot_mkₐ R I J) = quot_quot_mkₐ R J I := alg_hom.ext $ quot_quot_equiv_comm_quot_quot_mk I J variables {I J} /-- The **third isomoprhism theorem** for rings. See `quot_quot_equiv_quot_sup` for version that does not assume an inclusion of ideals. -/ def quot_quot_equiv_quot_of_leₐ (h : I ≤ J) : ((A ⧸ I) ⧸ (J.map (I^.quotient.mkₐ R))) ≃ₐ[R] A ⧸ J := @alg_equiv.of_ring_equiv R _ _ _ _ _ _ _ (quot_quot_equiv_quot_of_le h) (λ _, rfl) @[simp] lemma quot_quot_equiv_quot_of_leₐ_to_ring_equiv (h : I ≤ J) : (quot_quot_equiv_quot_of_leₐ R h).to_ring_equiv = quot_quot_equiv_quot_of_le h := rfl @[simp] lemma coe_quot_quot_equiv_quot_of_leₐ (h : I ≤ J) : ⇑(quot_quot_equiv_quot_of_leₐ R h) = quot_quot_equiv_quot_of_le h := rfl @[simp] lemma quot_quot_equiv_quot_of_leₐ_symm_to_ring_equiv (h : I ≤ J) : (quot_quot_equiv_quot_of_leₐ R h).symm.to_ring_equiv = (quot_quot_equiv_quot_of_le h).symm := rfl @[simp] lemma coe_quot_quot_equiv_quot_of_leₐ_symm (h : I ≤ J) : ⇑(quot_quot_equiv_quot_of_leₐ R h).symm = (quot_quot_equiv_quot_of_le h).symm := rfl @[simp] lemma quot_quot_equiv_quot_of_le_comp_quot_quot_mkₐ (h : I ≤ J) : alg_hom.comp ↑(quot_quot_equiv_quot_of_leₐ R h) (quot_quot_mkₐ R I J) = J^.quotient.mkₐ R := rfl @[simp] lemma quot_quot_equiv_quot_of_le_symm_comp_mkₐ (h : I ≤ J) : alg_hom.comp ↑(quot_quot_equiv_quot_of_leₐ R h).symm (J^.quotient.mkₐ R) = quot_quot_mkₐ R I J := rfl end algebra_quotient end double_quot
2d760b159b08115d3092e64cb63092d3b5aa7050
dc06cc9775d64d571bf4778459ec6fde1f344116
/src/analysis/convex.lean
0cd3589e91b1741c2b87747d59ee365af6389e86
[ "Apache-2.0" ]
permissive
mgubi/mathlib
8c1ea39035776ad52cf189a7af8cc0eee7dea373
7c09ed5eec8434176fbc493e0115555ccc4c8f99
refs/heads/master
1,642,222,572,514
1,563,782,424,000
1,563,782,424,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
27,716
lean
/- Copyright (c) 2019 Alexander Bentkamp. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alexander Bentkamp Convex sets and functions on real vector spaces -/ import analysis.normed_space.basic import data.complex.basic import data.set.intervals import tactic.interactive import tactic.linarith import linear_algebra.basic import ring_theory.algebra local attribute [instance] classical.prop_decidable open set section vector_space variables {α : Type*} {β : Type*} {ι : Sort _} [add_comm_group α] [vector_space ℝ α] [add_comm_group β] [vector_space ℝ β] (A : set α) (B : set α) (x : α) /-- Convexity of sets -/ def convex (A : set α) := ∀ (x y : α) (a b : ℝ), x ∈ A → y ∈ A → 0 ≤ a → 0 ≤ b → a + b = 1 → a • x + b • y ∈ A /-- Alternative definition of set convexity -/ lemma convex_iff: convex A ↔ ∀ {x y : α} {θ : ℝ}, x ∈ A → y ∈ A → 0 ≤ θ → θ ≤ 1 → θ • x + (1 - θ) • y ∈ A := ⟨begin assume h x y θ hx hy hθ₁ hθ₂, have hθ₂ : 0 ≤ 1 - θ, by linarith, exact (h _ _ _ _ hx hy hθ₁ hθ₂ (by linarith)) end, begin assume h x y a b hx hy ha hb hab, have ha' : a ≤ 1, by linarith, have hb' : b = 1 - a, by linarith, rw hb', exact h hx hy ha ha' end⟩ /-- Another alternative definition of set convexity -/ lemma convex_iff_div: convex A ↔ ∀ {x y : α} {a : ℝ} {b : ℝ}, x ∈ A → y ∈ A → 0 ≤ a → 0 ≤ b → 0 < a + b → (a/(a+b)) • x + (b/(a+b)) • y ∈ A := ⟨begin assume h x y a b hx hy ha hb hab, apply h _ _ _ _ hx hy, have ha', from mul_le_mul_of_nonneg_left ha (le_of_lt (inv_pos hab)), rwa [mul_zero, ←div_eq_inv_mul] at ha', have hb', from mul_le_mul_of_nonneg_left hb (le_of_lt (inv_pos hab)), rwa [mul_zero, ←div_eq_inv_mul] at hb', rw [←add_div], exact div_self (ne_of_lt hab).symm end, begin assume h x y a b hx hy ha hb hab, have h', from h hx hy ha hb, rw [hab, div_one, div_one] at h', exact h' zero_lt_one end⟩ local notation `I` := (Icc 0 1 : set ℝ) /-- Segments in a vector space -/ def segment (x y : α) := {z : α | ∃ l : ℝ, l ∈ I ∧ z - x = l•(y-x)} local notation `[`x `, ` y `]` := segment x y lemma left_mem_segment (x y : α) : x ∈ [x, y] := ⟨0, ⟨⟨le_refl _, zero_le_one⟩, by simp⟩⟩ lemma right_mem_segment (x y : α) : y ∈ [x, y] := ⟨1, ⟨⟨zero_le_one, le_refl _⟩, by simp⟩⟩ lemma mem_segment_iff {x y z : α} : z ∈ [x, y] ↔ ∃ l ∈ I, z = x + l•(y - x) := by split; rintro ⟨l, l_in, H⟩; use [l, l_in]; try { rw sub_eq_iff_eq_add at H }; rw H; abel lemma mem_segment_iff' {x y z : α} : z ∈ [x, y] ↔ ∃ l ∈ I, z = ((1:ℝ)-l)•x + l•y := begin split; rintro ⟨l, l_in, H⟩; use [l, l_in]; try { rw sub_eq_iff_eq_add at H }; rw H; simp only [smul_sub, sub_smul, one_smul]; abel, end lemma segment_symm (x y : α) : [x, y] = [y, x] := begin ext z, rw [mem_segment_iff', mem_segment_iff'], split, all_goals { rintro ⟨l, ⟨hl₀, hl₁⟩, h⟩, use (1-l), split, split; linarith, rw [h]; simp }, end lemma segment_eq_Icc {a b : ℝ} (h : a ≤ b) : [a, b] = Icc a b := begin ext z, rw mem_segment_iff, split, { rintro ⟨l, ⟨hl₀, hl₁⟩, H⟩, rw smul_eq_mul at H, have hba : 0 ≤ b - a, by linarith, split ; rw H, { have := mul_le_mul (le_refl l) hba (le_refl _) hl₀, simpa using this, }, { have := mul_le_mul hl₁ (le_refl (b-a)) hba zero_le_one, rw one_mul at this, apply le_trans (add_le_add (le_refl a) this), convert le_refl _, show b = a + (b-a), by ring } }, { rintro ⟨hza, hzb⟩, by_cases hba : b-a = 0, { use [(0:ℝ), ⟨le_refl 0, zero_le_one⟩], rw zero_smul, linarith }, { have : (z-a)/(b-a) ∈ I, { change b -a ≠ 0 at hba, have : 0 < b - a, from lt_of_le_of_ne (by linarith) hba.symm, split, apply div_nonneg ; linarith, apply (div_le_iff this).2, simp, convert hzb, ring}, use [(z-a)/(b-a), this], rw [smul_eq_mul, div_mul_cancel], ring, exact hba } } end lemma segment_translate (a b c x : α) (hx : x ∈ [b, c]) : a + x ∈ [a + b, a + c] := begin refine exists.elim hx (λθ hθ, ⟨θ, ⟨hθ.1, _⟩⟩), simp only [smul_sub, smul_add] at *, simp [smul_add, (add_eq_of_eq_sub hθ.2.symm).symm] end lemma segment_translate_image (a b c: α) : (λx, a + x) '' [b, c] = [a + b, a + c] := begin apply subset.antisymm, { intros z hz, apply exists.elim hz, intros x hx, convert segment_translate a b c x _, { exact hx.2.symm }, { exact hx.1 } }, { intros z hz, apply exists.elim hz, intros θ hθ, use z - a, apply and.intro, { convert segment_translate (-a) (a + b) (a + c) z hz; simp }, { simp only [add_sub_cancel'_right] } } end lemma image_Icc_zero_one_eq_segment {x y : α} : (λ (t : ℝ), x + t • (y - x)) '' Icc 0 1 = segment x y := begin apply subset.antisymm, { intros z hz, apply exists.elim hz, intros x hx, use x, simp [hx.2.symm, hx.1] }, { intros z hz, apply exists.elim hz, intros a ha, exact ⟨a, ha.1, add_eq_of_eq_sub' (eq.symm ha.2)⟩ } end /-- Alternative defintion of set convexity using segments -/ lemma convex_segment_iff : convex A ↔ ∀ x y ∈ A, [x, y] ⊆ A := begin apply iff.intro, { intros hA x y hx hy z hseg, apply exists.elim hseg, intros l hl, have hz : z = l • y + (1-l) • x, { rw sub_eq_iff_eq_add.1 hl.2, rw [smul_sub, sub_smul, one_smul], simp }, rw hz, apply (convex_iff A).1 hA hy hx hl.1.1 hl.1.2 }, { intros hA, rw convex_iff, intros x y θ hx hy hθ₀ hθ₁, apply hA y x hy hx, use θ, apply and.intro, { exact and.intro hθ₀ hθ₁ }, { simp only [smul_sub, sub_smul, one_smul], simp } } end /- Examples of convex sets -/ lemma convex_empty : convex (∅ : set α) := by finish lemma convex_singleton (a : α) : convex ({a} : set α) := begin intros x y a b hx hy ha hb hab, rw [set.eq_of_mem_singleton hx, set.eq_of_mem_singleton hy, ←add_smul, hab], simp end lemma convex_univ : convex (set.univ : set α) := by finish lemma convex_inter (hA: convex A) (hB: convex B) : convex (A ∩ B) := λ x y a b (hx : x ∈ A ∩ B) (hy : y ∈ A ∩ B) (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1), ⟨hA _ _ _ _ hx.left hy.left ha hb hab, hB _ _ _ _ hx.right hy.right ha hb hab⟩ lemma convex_Inter {s: ι → set α} (h: ∀ i : ι, convex (s i)) : convex (Inter s) := begin intros x y a b hx hy ha hb hab, apply mem_Inter.2, exact λi, h i _ _ _ _ (mem_Inter.1 hx i) (mem_Inter.1 hy i) ha hb hab end lemma convex_prod {A : set α} {B : set β} (hA : convex A) (hB : convex B) : convex (set.prod A B) := begin intros x y a b hx hy ha hb hab, apply mem_prod.2, exact ⟨hA _ _ _ _ (mem_prod.1 hx).1 (mem_prod.1 hy).1 ha hb hab, hB _ _ _ _ (mem_prod.1 hx).2 (mem_prod.1 hy).2 ha hb hab⟩ end lemma convex_linear_image (f : α → β) (hf : is_linear_map ℝ f) (hA : convex A) : convex (image f A) := begin intros x y a b hx hy ha hb hab, apply exists.elim hx, intros x' hx', apply exists.elim hy, intros y' hy', use a • x' + b • y', split, { apply hA _ _ _ _ hx'.1 hy'.1 ha hb hab }, { simp [hx',hy',hf.add,hf.smul] } end lemma convex_linear_image' (f : α →ₗ[ℝ] β) (hA : convex A) : convex (image f A) := convex_linear_image A f.to_fun (linear_map.is_linear f) hA lemma convex_linear_preimage (A : set β) (f : α → β) (hf : is_linear_map ℝ f) (hA : convex A) : convex (preimage f A) := begin intros x y a b hx hy ha hb hab, simp [hf.add, hf.smul], exact hA (f x) (f y) a b hx hy ha hb hab end lemma convex_linear_preimage' (A : set β) (f : α →ₗ[ℝ] β) (hA : convex A) : convex (preimage f A) := convex_linear_preimage A f.to_fun (linear_map.is_linear f) hA lemma convex_neg : convex A → convex ((λ z, -z) '' A) := convex_linear_image _ _ is_linear_map.is_linear_map_neg lemma convex_neg_preimage : convex A → convex ((λ z, -z) ⁻¹' A) := convex_linear_preimage _ _ is_linear_map.is_linear_map_neg lemma convex_smul (c : ℝ) : convex A → convex ((λ z, c • z) '' A) := convex_linear_image _ _ (is_linear_map.is_linear_map_smul c) lemma convex_smul_preimage (c : ℝ) : convex A → convex ((λ z, c • z) ⁻¹' A) := convex_linear_preimage _ _ (is_linear_map.is_linear_map_smul _) lemma convex_add (hA : convex A) (hB : convex B) : convex ((λx : α × α, x.1 + x.2) '' (set.prod A B)) := begin apply convex_linear_image (set.prod A B) (λx : α × α, x.1 + x.2) is_linear_map.is_linear_map_add, exact convex_prod hA hB end lemma convex_sub (hA : convex A) (hB : convex B) : convex ((λx : α × α, x.1 - x.2) '' (set.prod A B)) := begin apply convex_linear_image (set.prod A B) (λx : α × α, x.1 - x.2) is_linear_map.is_linear_map_sub, exact convex_prod hA hB end lemma convex_translation (z : α) (hA : convex A) : convex ((λx, z + x) '' A) := begin have h : convex ((λ (x : α × α), x.fst + x.snd) '' set.prod (insert z ∅) A), from convex_add {z} A (convex_singleton z) hA, show convex ((λx, z + x) '' A), { rw [@insert_prod _ _ z ∅ A, set.empty_prod, set.union_empty, ←image_comp] at h, simp at h, exact h } end lemma convex_affinity (z : α) (c : ℝ) (hA : convex A) : convex ((λx, z + c • x) '' A) := begin have h : convex ((λ (x : α), z + x) '' ((λ (z : α), c • z) '' A)), from convex_translation _ z (convex_smul A c hA), show convex ((λx, z + c • x) '' A), { rw [←image_comp] at h, simp at h, exact h } end lemma convex_Iio (r : ℝ) : convex (Iio r) := begin intros x y a b hx hy ha hb hab, wlog h : x ≤ y using [x y a b, y x b a], exact le_total _ _, calc a * x + b * y ≤ a * y + b * y : add_le_add_right (mul_le_mul_of_nonneg_left h ha) _ ... = y : by rw [←add_mul a b y, hab, one_mul] ... < r : hy end lemma convex_Iic (r : ℝ) : convex (Iic r) := begin intros x y a b hx hy ha hb hab, wlog h : x ≤ y using [x y a b, y x b a], exact le_total _ _, calc a * x + b * y ≤ a * y + b * y : add_le_add_right (mul_le_mul_of_nonneg_left h ha) _ ... = y : by rw [←add_mul a b y, hab, one_mul] ... ≤ r : hy end lemma convex_Ioi (r : ℝ) : convex (Ioi r) := begin rw [← neg_neg r], rw (image_neg_Iio (-r)).symm, unfold convex, intros x y a b hx hy ha hb hab, exact convex_linear_image _ _ is_linear_map.is_linear_map_neg (convex_Iio (-r)) _ _ _ _ hx hy ha hb hab end lemma convex_Ici (r : ℝ) : convex (Ici r) := begin rw [← neg_neg r], rw (image_neg_Iic (-r)).symm, unfold convex, intros x y a b hx hy ha hb hab, exact convex_linear_image _ _ is_linear_map.is_linear_map_neg (convex_Iic (-r)) _ _ _ _ hx hy ha hb hab end lemma convex_Ioo (r : ℝ) (s : ℝ) : convex (Ioo r s) := convex_inter _ _ (convex_Ioi _) (convex_Iio _) lemma convex_Ico (r : ℝ) (s : ℝ) : convex (Ico r s) := convex_inter _ _ (convex_Ici _) (convex_Iio _) lemma convex_Ioc (r : ℝ) (s : ℝ) : convex (Ioc r s) := convex_inter _ _ (convex_Ioi _) (convex_Iic _) lemma convex_Icc (r : ℝ) (s : ℝ) : convex (Icc r s) := convex_inter _ _ (convex_Ici _) (convex_Iic _) lemma convex_segment (a b : α) : convex [a, b] := begin have : (λ (t : ℝ), a + t • (b - a)) = (λz : α, a + z) ∘ (λt:ℝ, t • (b - a)) := rfl, rw [← image_Icc_zero_one_eq_segment, this, image_comp], apply convex_translation _ _ (convex_linear_image _ _ _ (convex_Icc _ _)), exact is_linear_map.is_linear_map_smul' _ end lemma convex_halfspace_lt (f : α → ℝ) (h : is_linear_map ℝ f) (r : ℝ) : convex {w | f w < r} := begin assume x y a b hx hy ha hb hab, simp, rw [is_linear_map.add ℝ f, is_linear_map.smul f a, is_linear_map.smul f b], apply convex_Iio _ _ _ _ _ hx hy ha hb hab end lemma convex_halfspace_le (f : α → ℝ) (h : is_linear_map ℝ f) (r : ℝ) : convex {w | f w ≤ r} := begin assume x y a b hx hy ha hb hab, simp, rw [is_linear_map.add ℝ f, is_linear_map.smul f a, is_linear_map.smul f b], apply convex_Iic _ _ _ _ _ hx hy ha hb hab end lemma convex_halfspace_gt (f : α → ℝ) (h : is_linear_map ℝ f) (r : ℝ) : convex {w | r < f w} := begin assume x y a b hx hy ha hb hab, simp, rw [is_linear_map.add ℝ f, is_linear_map.smul f a, is_linear_map.smul f b], apply convex_Ioi _ _ _ _ _ hx hy ha hb hab end lemma convex_halfspace_ge (f : α → ℝ) (h : is_linear_map ℝ f) (r : ℝ) : convex {w | r ≤ f w} := begin assume x y a b hx hy ha hb hab, simp, rw [is_linear_map.add ℝ f, is_linear_map.smul f a, is_linear_map.smul f b], apply convex_Ici _ _ _ _ _ hx hy ha hb hab end lemma convex_halfplane (f : α → ℝ) (h : is_linear_map ℝ f) (r : ℝ) : convex {w | f w = r} := begin assume x y a b hx hy ha hb hab, simp at *, rw [is_linear_map.add ℝ f, is_linear_map.smul f a, is_linear_map.smul f b], rw [hx, hy, (add_smul a b r).symm, hab, one_smul] end lemma convex_halfspace_re_lt (r : ℝ) : convex {c : ℂ | c.re < r} := convex_halfspace_lt _ (is_linear_map.mk complex.add_re complex.smul_re) _ lemma convex_halfspace_re_le (r : ℝ) : convex {c : ℂ | c.re ≤ r} := convex_halfspace_le _ (is_linear_map.mk complex.add_re complex.smul_re) _ lemma convex_halfspace_re_gt (r : ℝ) : convex {c : ℂ | r < c.re } := convex_halfspace_gt _ (is_linear_map.mk complex.add_re complex.smul_re) _ lemma convex_halfspace_re_lge (r : ℝ) : convex {c : ℂ | r ≤ c.re} := convex_halfspace_ge _ (is_linear_map.mk complex.add_re complex.smul_re) _ lemma convex_halfspace_im_lt (r : ℝ) : convex {c : ℂ | c.im < r} := convex_halfspace_lt _ (is_linear_map.mk complex.add_im complex.smul_im) _ lemma convex_halfspace_im_le (r : ℝ) : convex {c : ℂ | c.im ≤ r} := convex_halfspace_le _ (is_linear_map.mk complex.add_im complex.smul_im) _ lemma convex_halfspace_im_gt (r : ℝ) : convex {c : ℂ | r < c.im } := convex_halfspace_gt _ (is_linear_map.mk complex.add_im complex.smul_im) _ lemma convex_halfspace_im_lge (r : ℝ) : convex {c : ℂ | r ≤ c.im} := convex_halfspace_ge _ (is_linear_map.mk complex.add_im complex.smul_im) _ lemma convex_sum {γ : Type*} (hA : convex A) (z : γ → α) (s : finset γ) : ∀ a : γ → ℝ, s.sum a = 1 → (∀ i ∈ s, 0 ≤ a i) → (∀ i ∈ s, z i ∈ A) → s.sum (λi, a i • z i) ∈ A := begin refine finset.induction _ _ s, { intros _ h_sum, simp at h_sum, exact false.elim h_sum }, { intros k s hks ih a h_sum ha hz, by_cases h_cases : s.sum a = 0, { have hak : a k = 1, by rwa [finset.sum_insert hks, h_cases, add_zero] at h_sum, have ha': ∀ i ∈ s, 0 ≤ a i, from λ i hi, ha i (finset.mem_insert_of_mem hi), have h_a0: ∀ i ∈ s, a i = 0, from (finset.sum_eq_zero_iff_of_nonneg ha').1 h_cases, have h_az0: ∀ i ∈ s, a i • z i = 0, { intros i hi, rw h_a0 i hi, exact zero_smul _ (z i) }, show finset.sum (insert k s) (λ (i : γ), a i • z i) ∈ A, { rw [finset.sum_insert hks, hak, finset.sum_eq_zero h_az0], simp, exact hz k (finset.mem_insert_self k s) } }, { have h_sum_nonneg : 0 ≤ s.sum a, { apply finset.zero_le_sum', intros i hi, apply ha _ (finset.mem_insert_of_mem hi) }, have h_div_in_A: s.sum (λ (i : γ), ((s.sum a)⁻¹ * a i) • z i) ∈ A, { apply ih, { rw finset.mul_sum.symm, exact division_ring.inv_mul_cancel h_cases }, { intros i hi, exact zero_le_mul (inv_nonneg.2 h_sum_nonneg) (ha i (finset.mem_insert_of_mem hi))}, { intros i hi, exact hz i (finset.mem_insert_of_mem hi) } }, have h_sum_in_A: a k • z k + finset.sum s a • finset.sum s (λ (i : γ), ((finset.sum s a)⁻¹ * a i) • z i) ∈ A, { apply hA, exact hz k (finset.mem_insert_self k s), exact h_div_in_A, exact ha k (finset.mem_insert_self k s), exact h_sum_nonneg, rw (finset.sum_insert hks).symm, exact h_sum }, show finset.sum (insert k s) (λ (i : γ), a i • z i) ∈ A, { rw finset.sum_insert hks, rw finset.smul_sum at h_sum_in_A, simp [smul_smul, (mul_assoc (s.sum a) _ _).symm] at h_sum_in_A, conv begin congr, congr, skip, congr, skip, funext, rw (one_mul (a _)).symm, rw (field.mul_inv_cancel h_cases).symm, end, exact h_sum_in_A } } } end lemma convex_sum_iff : convex A ↔ (∀ (s : finset α) (as : α → ℝ), s.sum as = 1 → (∀ i ∈ s, 0 ≤ as i) → (∀ x ∈ s, x ∈ A) → s.sum (λx, as x • x) ∈ A ) := begin apply iff.intro, { intros hA s as h_sum has hs, exact convex_sum A hA id s _ h_sum has hs }, { intros h, intros x y a b hx hy ha hb hab, by_cases h_cases: x = y, { rw [h_cases, ←add_smul, hab, one_smul], exact hy }, { let s := insert x (finset.singleton y), have h_sum_eq_add : finset.sum s (λ z, ite (x = z) a b • z) = a • x + b • y, { rw [finset.sum_insert (finset.not_mem_singleton.2 h_cases), finset.sum_singleton], simp [h_cases] }, rw h_sum_eq_add.symm, apply h s, { rw [finset.sum_insert (finset.not_mem_singleton.2 h_cases), finset.sum_singleton], simp [h_cases], exact hab }, { intros k hk, by_cases h_cases : x = k, { simp [h_cases], exact ha }, { simp [h_cases], exact hb } }, { intros z hz, apply or.elim (finset.mem_insert.1 hz), { intros h_eq, rw h_eq, exact hx }, { intros h_eq, rw finset.mem_singleton at h_eq, rw h_eq, exact hy } } } } end variables (D: set α) (D': set α) (f : α → ℝ) (g : α → ℝ) /-- Convexity of functions -/ def convex_on (f : α → ℝ) : Prop := convex D ∧ ∀ (x y : α) (a b : ℝ), x ∈ D → y ∈ D → 0 ≤ a → 0 ≤ b → a + b = 1 → f (a • x + b • y) ≤ a * f x + b * f y lemma convex_on_iff : convex_on D f ↔ convex D ∧ ∀ {x y : α} {θ : ℝ}, x ∈ D → y ∈ D → 0 ≤ θ → θ ≤ 1 → f (θ • x + (1 - θ) • y) ≤ θ * f x + (1 - θ) * f y := ⟨begin intro h, apply and.intro h.1, intros x y θ hx hy hθ₁ hθ₂, have hθ₂: 0 ≤ 1 - θ, by linarith, exact (h.2 _ _ _ _ hx hy hθ₁ hθ₂ (by linarith)) end, begin intro h, apply and.intro h.1, assume x y a b hx hy ha hb hab, have ha': a ≤ 1, by linarith, have hb': b = 1 - a, by linarith, rw hb', exact (h.2 hx hy ha ha') end⟩ lemma convex_on_iff_div: convex_on D f ↔ convex D ∧ ∀ {x y : α} {a : ℝ} {b : ℝ}, x ∈ D → y ∈ D → 0 ≤ a → 0 ≤ b → 0 < a + b → f ((a/(a+b)) • x + (b/(a+b)) • y) ≤ (a/(a+b)) * f x + (b/(a+b)) * f y := ⟨begin intro h, apply and.intro h.1, intros x y a b hx hy ha hb hab, apply h.2 _ _ _ _ hx hy, have ha', from mul_le_mul_of_nonneg_left ha (le_of_lt (inv_pos hab)), rwa [mul_zero, ←div_eq_inv_mul] at ha', have hb', from mul_le_mul_of_nonneg_left hb (le_of_lt (inv_pos hab)), rwa [mul_zero, ←div_eq_inv_mul] at hb', rw [←add_div], exact div_self (ne_of_lt hab).symm end, begin intro h, apply and.intro h.1, intros x y a b hx hy ha hb hab, have h', from h.2 hx hy ha hb, rw [hab, div_one, div_one] at h', exact h' zero_lt_one end⟩ lemma convex_on_sum {γ : Type} (s : finset γ) (z : γ → α) (hs : s ≠ ∅) : ∀ (a : γ → ℝ), convex_on D f → (∀ i ∈ s, 0 ≤ a i) → (∀ i ∈ s, z i ∈ D) → s.sum a = 1 → f (s.sum (λi, a i • z i)) ≤ s.sum (λi, a i • f (z i)) := begin refine finset.induction (by simp) _ s, intros k s hks ih a hf ha hz h_sum, by_cases h_cases : s.sum a = 0, { have hak : a k = 1, by rwa [finset.sum_insert hks, h_cases, add_zero] at h_sum, have ha': ∀ i ∈ s, 0 ≤ a i, from λ i hi, ha i (finset.mem_insert_of_mem hi), have h_a0: ∀ i ∈ s, a i = 0, from (finset.sum_eq_zero_iff_of_nonneg ha').1 h_cases, have h_az0: ∀ i ∈ s, a i • z i = 0, { intros i hi, rw h_a0 i hi, exact zero_smul _ _ }, have h_afz0: ∀ i ∈ s, a i • f (z i) = 0, { intros i hi, rw h_a0 i hi, exact zero_smul _ _ }, show f (finset.sum (insert k s) (λi, a i • z i)) ≤ finset.sum (insert k s) (λi, a i • f (z i)), { rw [finset.sum_insert hks, hak, finset.sum_eq_zero h_az0], rw [finset.sum_insert hks, hak, finset.sum_eq_zero h_afz0], simp } }, { have h_sum_nonneg : 0 ≤ s.sum a , { apply finset.zero_le_sum', intros i hi, apply ha _ (finset.mem_insert_of_mem hi) }, have ih_div: f (s.sum (λ (i : γ), ((s.sum a)⁻¹ * a i) • z i)) ≤ s.sum (λ (i : γ), ((s.sum a)⁻¹ * a i) • f (z i)), { apply ih _ hf, { intros i hi, exact zero_le_mul (inv_nonneg.2 h_sum_nonneg) (ha i (finset.mem_insert_of_mem hi))}, { intros i hi, exact hz i (finset.mem_insert_of_mem hi) }, { rw finset.mul_sum.symm, exact division_ring.inv_mul_cancel h_cases } }, have h_div_in_D: s.sum (λ (i : γ), ((s.sum a)⁻¹ * a i) • z i) ∈ D, { apply convex_sum _ hf.1, { rw finset.mul_sum.symm, exact division_ring.inv_mul_cancel h_cases }, { intros i hi, exact zero_le_mul (inv_nonneg.2 h_sum_nonneg) (ha i (finset.mem_insert_of_mem hi))}, { intros i hi, exact hz i (finset.mem_insert_of_mem hi) } }, have hf': f (a k • z k + s.sum a • s.sum (λ (i : γ), ((finset.sum s a)⁻¹ * a i) • z i)) ≤ a k • f (z k) + s.sum a • f (s.sum (λ (i : γ), ((finset.sum s a)⁻¹ * a i) • z i)), { apply hf.2, exact hz k (finset.mem_insert_self k s), exact h_div_in_D, exact ha k (finset.mem_insert_self k s), exact h_sum_nonneg, rw (finset.sum_insert hks).symm, exact h_sum }, have ih_div': f (a k • z k + s.sum a • s.sum (λ (i : γ), ((finset.sum s a)⁻¹ * a i) • z i)) ≤ a k • f (z k) + s.sum a • s.sum (λ (i : γ), ((finset.sum s a)⁻¹ * a i) • f (z i)), from trans hf' (add_le_add_left (mul_le_mul_of_nonneg_left ih_div h_sum_nonneg) _), show f (finset.sum (insert k s) (λ (i : γ), a i • z i)) ≤ finset.sum (insert k s) (λ (i : γ), a i • f (z i)), { simp [finset.sum_insert hks], simp [finset.smul_sum] at ih_div', simp [smul_smul, (mul_assoc (s.sum a) _ _).symm] at ih_div', convert ih_div', repeat { apply funext, intro i, rw [field.mul_inv_cancel, one_mul], exact h_cases } } } end lemma convex_on_linorder [hα : linear_order α] (f : α → ℝ) : convex_on D f ↔ convex D ∧ ∀ (x y : α) (a b : ℝ), x ∈ D → y ∈ D → x < y → a ≥ 0 → b ≥ 0 → a + b = 1 → f (a • x + b • y) ≤ a * f x + b * f y := begin apply iff.intro, { intro h, apply and.intro h.1, intros x y a b hx hy hxy ha hb hab, exact h.2 x y a b hx hy ha hb hab }, { intro h, apply and.intro h.1, intros x y a b hx hy ha hb hab, wlog hxy : x<=y using [x y a b, y x b a], exact le_total _ _, apply or.elim (lt_or_eq_of_le hxy), { intros hxy, exact h.2 x y a b hx hy hxy ha hb hab }, { intros hxy, rw [hxy,←add_smul, hab, one_smul,←add_mul,hab,one_mul] } } end lemma convex_on_subset (h_convex_on : convex_on D f) (h_subset : A ⊆ D) (h_convex : convex A) : convex_on A f := begin apply and.intro h_convex, intros x y a b hx hy, exact h_convex_on.2 x y a b (h_subset hx) (h_subset hy), end lemma convex_on_add (hf : convex_on D f) (hg : convex_on D g) : convex_on D (λx, f x + g x) := begin apply and.intro hf.1, intros x y a b hx hy ha hb hab, calc f (a • x + b • y) + g (a • x + b • y) ≤ (a * f x + b * f y) + (a * g x + b * g y) : add_le_add (hf.2 x y a b hx hy ha hb hab) (hg.2 x y a b hx hy ha hb hab) ... = a * f x + a * g x + b * f y + b * g y : by linarith ... = a * (f x + g x) + b * (f y + g y) : by simp [mul_add] end lemma convex_on_smul (c : ℝ) (hc : 0 ≤ c) (hf : convex_on D f) : convex_on D (λx, c * f x) := begin apply and.intro hf.1, intros x y a b hx hy ha hb hab, calc c * f (a • x + b • y) ≤ c * (a * f x + b * f y) : mul_le_mul_of_nonneg_left (hf.2 x y a b hx hy ha hb hab) hc ... = a * (c * f x) + b * (c * f y) : by rw mul_add; ac_refl end lemma convex_le_of_convex_on (hf : convex_on D f) (r : ℝ) : convex {x ∈ D | f x ≤ r} := begin intros x y a b hx hy ha hb hab, simp at *, apply and.intro, { exact hf.1 x y a b hx.1 hy.1 ha hb hab }, { apply le_trans (hf.2 x y a b hx.1 hy.1 ha hb hab), wlog h_wlog : f x ≤ f y using [x y a b, y x b a], apply le_total, calc a * f x + b * f y ≤ a * f y + b * f y : add_le_add (mul_le_mul_of_nonneg_left h_wlog ha) (le_refl _) ... = (a + b) * f y : (add_mul _ _ _).symm ... ≤ r : by rw [hab, one_mul]; exact hy.2 } end lemma convex_lt_of_convex_on (hf : convex_on D f) (r : ℝ) : convex {x ∈ D | f x < r} := begin intros x y a b hx hy ha hb hab, simp at *, apply and.intro, { exact hf.1 x y a b hx.1 hy.1 ha hb hab }, { apply lt_of_le_of_lt (hf.2 x y a b hx.1 hy.1 ha hb hab), wlog h_wlog : f x ≤ f y using [x y a b, y x b a], apply le_total, calc a * f x + b * f y ≤ a * f y + b * f y : add_le_add (mul_le_mul_of_nonneg_left h_wlog ha) (le_refl _) ... = (a + b) * f y : (add_mul _ _ _).symm ... < r : by rw [hab, one_mul]; exact hy.2 } end lemma le_on_interval_of_convex_on (x y : α) (a b : ℝ) (hf : convex_on D f) (hx : x ∈ D) (hy : y ∈ D) (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1) : f (a • x + b • y) ≤ max (f x) (f y) := calc f (a • x + b • y) ≤ a * f x + b * f y : hf.2 x y a b hx hy ha hb hab ... ≤ a * max (f x) (f y) + b * max (f x) (f y) : add_le_add (mul_le_mul_of_nonneg_left (le_max_left _ _) ha) (mul_le_mul_of_nonneg_left (le_max_right _ _) hb) ... ≤ max (f x) (f y) : by rw [←add_mul, hab, one_mul] end vector_space section normed_space variables {α : Type*} [normed_group α] [normed_space ℝ α] lemma convex_on_dist (z : α) (D : set α) (hD : convex D) : convex_on D (λz', dist z' z) := begin apply and.intro hD, intros x y a b hx hy ha hb hab, calc dist (a • x + b • y) z = ∥ (a • x + b • y) - (a + b) • z ∥ : by rw [hab, one_smul, normed_group.dist_eq] ... = ∥a • (x - z) + b • (y - z)∥ : by rw [add_smul, smul_sub, smul_sub]; simp ... ≤ ∥a • (x - z)∥ + ∥b • (y - z)∥ : norm_triangle (a • (x - z)) (b • (y - z)) ... = a * dist x z + b * dist y z : by simp [norm_smul, normed_group.dist_eq, real.norm_eq_abs, abs_of_nonneg ha, abs_of_nonneg hb] end lemma convex_ball (a : α) (r : ℝ) : convex (metric.ball a r) := by simpa using convex_lt_of_convex_on univ (λb, dist b a) (convex_on_dist _ _ convex_univ) r lemma convex_closed_ball (a : α) (r : ℝ) : convex (metric.closed_ball a r) := by simpa using convex_le_of_convex_on univ (λb, dist b a) (convex_on_dist _ _ convex_univ) r end normed_space
18ceccd6adba4557baf9cd5bb4e52fe34391b3b1
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/kronRWIssue.lean
dc74a3a5a08b4b7de60d68b32a3ca6d70f596912
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
441
lean
class Foo (α : Type) where decEq : DecidableEq α instance instDecidableEq {α} [Foo α] : DecidableEq α := Foo.decEq instance instFooNat : Foo Nat := ⟨by infer_instance⟩ def kron (i j : α) [DecidableEq α] : Nat := if (i=j) then 1 else 0 theorem kron_right_mul (α : Type) [foo : Foo α] (i j : α) (x : Nat) : x * kron i j = kron i j * x := sorry example {i j : Nat} : i * kron i j = kron i j * i := by rw [kron_right_mul]